xref: /dragonfly/bin/ps/ps.c (revision 2038fb68)
1 /*-
2  * Copyright (c) 1990, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * @(#) Copyright (c) 1990, 1993, 1994 The Regents of the University of California.  All rights reserved.
34  * @(#)ps.c	8.4 (Berkeley) 4/2/94
35  * $FreeBSD: src/bin/ps/ps.c,v 1.30.2.6 2002/07/04 08:30:37 sobomax Exp $
36  * $DragonFly: src/bin/ps/ps.c,v 1.25 2008/01/10 14:18:39 matthias Exp $
37  */
38 
39 #include <sys/param.h>
40 #include <sys/user.h>
41 #include <sys/time.h>
42 #include <sys/queue.h>
43 #include <sys/resource.h>
44 #include <sys/stat.h>
45 #include <sys/ioctl.h>
46 #include <sys/sysctl.h>
47 #include <sys/mount.h>
48 
49 #include <ctype.h>
50 #include <err.h>
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <kvm.h>
54 #include <limits.h>
55 #include <locale.h>
56 #include <nlist.h>
57 #include <paths.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62 #include <pwd.h>
63 #include <utmp.h>
64 
65 #include "ps.h"
66 
67 #define SEP ", \t"		/* username separators */
68 
69 KINFO *kinfo;
70 struct varent *vhead, *vtail;
71 
72 int	eval;			/* exit value */
73 int	cflag;			/* -c */
74 int	rawcpu;			/* -C */
75 int	sumrusage;		/* -S */
76 int	termwidth;		/* width of screen (0 == infinity) */
77 int	totwidth;		/* calculated width of requested variables */
78 int	numcpus;		/* hw.ncpu */
79 
80 static int needuser, needcomm, needenv;
81 #if defined(LAZY_PS)
82 static int forceuread=0;
83 #define PS_ARGS	"aCcefgHhjLlM:mN:O:o:p:rSTt:U:uvwx"
84 #else
85 static int forceuread=1;
86 #define PS_ARGS	"aCcegHhjLlM:mN:O:o:p:rSTt:U:uvwx"
87 #endif
88 
89 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
90 
91 static const char *getfmt (char **(*)(kvm_t *, const struct kinfo_proc *, int),
92 		    KINFO *, char *, int);
93 static char	*kludge_oldps_options (char *);
94 static int	 pscomp (const void *, const void *);
95 static void	 saveuser (KINFO *);
96 static void	 scanvars (void);
97 static void	 dynsizevars (KINFO *);
98 static void	 sizevars (void);
99 static int	 check_procfs(void);
100 static void	 usage (void);
101 static uid_t	*getuids(const char *, int *);
102 
103 struct timeval btime;
104 
105 static char dfmt[] = "pid tt state time command";
106 static char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
107 static char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
108 static char   o1[] = "pid";
109 static char   o2[] = "tt state time command";
110 static char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
111 static char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
112 
113 kvm_t *kd;
114 
115 int
116 main(int argc, char **argv)
117 {
118 	struct kinfo_proc *kp;
119 	struct varent *vent;
120 	struct winsize ws;
121 	dev_t ttydev;
122 	pid_t pid;
123 	uid_t *uids;
124 	int all, ch, flag, i, fmt, ofmt, lineno, nentries, nocludge, dropgid;
125 	int prtheader, wflag, what, xflg, uid, nuids, showtid;
126 	char errbuf[_POSIX2_LINE_MAX];
127 	const char *cp, *nlistf, *memf;
128 	size_t btime_size = sizeof(struct timeval);
129 	size_t numcpus_size = sizeof(numcpus);
130 
131 	setlocale(LC_ALL, "");
132 
133 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
134 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
135 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
136 	     ws.ws_col == 0)
137 		termwidth = 79;
138 	else
139 		termwidth = ws.ws_col - 1;
140 
141 	/*
142 	 * Don't apply a kludge if the first argument is an option taking an
143 	 * argument
144 	 */
145 	if (argc > 1) {
146 		nocludge = 0;
147 		if (argv[1][0] == '-') {
148 			for (cp = PS_ARGS; *cp != '\0'; cp++) {
149 				if (*cp != ':')
150 					continue;
151 				if (*(cp - 1) == argv[1][1]) {
152 					nocludge = 1;
153 					break;
154 				}
155 			}
156 		}
157 		if (nocludge == 0)
158 			argv[1] = kludge_oldps_options(argv[1]);
159 	}
160 
161 	all = fmt = ofmt = prtheader = wflag = xflg = showtid = 0;
162 	pid = -1;
163 	nuids = 0;
164 	uids = NULL;
165 	ttydev = NODEV;
166 	dropgid = 0;
167 	memf = nlistf = _PATH_DEVNULL;
168 	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
169 		switch((char)ch) {
170 		case 'a':
171 			all = 1;
172 			break;
173 		case 'C':
174 			rawcpu = 1;
175 			break;
176 		case 'c':
177 			cflag = 1;
178 			break;
179 		case 'e':			/* XXX set ufmt */
180 			needenv = 1;
181 			break;
182 		case 'g':
183 			break;			/* no-op */
184 		case 'H':
185 			showtid = KERN_PROC_FLAG_LWP;
186 			break;
187 		case 'h':
188 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
189 			break;
190 		case 'j':
191 			parsefmt(jfmt);
192 			fmt = 1;
193 			jfmt[0] = '\0';
194 			break;
195 		case 'L':
196 			showkey();
197 			exit(0);
198 		case 'l':
199 			parsefmt(lfmt);
200 			fmt = 1;
201 			lfmt[0] = '\0';
202 			break;
203 		case 'M':
204 			memf = optarg;
205 			dropgid = 1;
206 			break;
207 		case 'm':
208 			sortby = SORTMEM;
209 			break;
210 		case 'N':
211 			nlistf = optarg;
212 			dropgid = 1;
213 			break;
214 		case 'O':
215 			parsefmt(o1);
216 			parsefmt(optarg);
217 			parsefmt(o2);
218 			o1[0] = o2[0] = '\0';
219 			fmt = 1;
220 			break;
221 		case 'o':
222 			parsefmt(optarg);
223 			fmt = ofmt = 1;
224 			break;
225 #if defined(LAZY_PS)
226 		case 'f':
227 			if (getuid() == 0 || getgid() == 0)
228 			    forceuread = 1;
229 			break;
230 #endif
231 		case 'p':
232 			pid = atol(optarg);
233 			xflg = 1;
234 			break;
235 		case 'r':
236 			sortby = SORTCPU;
237 			break;
238 		case 'S':
239 			sumrusage = 1;
240 			break;
241 		case 'T':
242 			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
243 				errx(1, "stdin: not a terminal");
244 			/* FALLTHROUGH */
245 		case 't': {
246 			struct stat sb;
247 			char pathbuf[PATH_MAX];
248 			const char *ttypath;
249 
250 			if (strcmp(optarg, "co") == 0)
251 				ttypath = _PATH_CONSOLE;
252 			else if (*optarg != '/') {
253 				snprintf(pathbuf,
254 				    sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
255 				ttypath = pathbuf;
256 			} else
257 				ttypath = optarg;
258 			if (stat(ttypath, &sb) == -1)
259 				err(1, "%s", ttypath);
260 			if (!S_ISCHR(sb.st_mode))
261 				errx(1, "%s: not a terminal", ttypath);
262 			ttydev = sb.st_rdev;
263 			break;
264 		}
265 		case 'U':
266 			uids = getuids(optarg, &nuids);
267 			xflg++;		/* XXX: intuitive? */
268 			break;
269 		case 'u':
270 			parsefmt(ufmt);
271 			sortby = SORTCPU;
272 			fmt = 1;
273 			ufmt[0] = '\0';
274 			break;
275 		case 'v':
276 			parsefmt(vfmt);
277 			sortby = SORTMEM;
278 			fmt = 1;
279 			vfmt[0] = '\0';
280 			break;
281 		case 'w':
282 			if (wflag)
283 				termwidth = UNLIMITED;
284 			else if (termwidth < 131)
285 				termwidth = 131;
286 			wflag++;
287 			break;
288 		case 'x':
289 			xflg = 1;
290 			break;
291 		case '?':
292 		default:
293 			usage();
294 		}
295 	argc -= optind;
296 	argv += optind;
297 
298 	/*
299 	 * If the user specified ps -e then they want a copy of the process
300 	 * environment kvm_getenvv(3) attempts to open /proc/<pid>/mem.
301 	 * Check to make sure that procfs is mounted on /proc, otherwise
302 	 * print a warning informing the user that output will be incomplete.
303 	 */
304 	if (needenv == 1 && check_procfs() == 0)
305 		warnx("Process environment requires procfs(5)");
306 
307 #define	BACKWARD_COMPATIBILITY
308 #ifdef	BACKWARD_COMPATIBILITY
309 	if (*argv) {
310 		nlistf = *argv;
311 		if (*++argv) {
312 			memf = *argv;
313 		}
314 	}
315 #endif
316 	/*
317 	 * Discard setgid privileges if not the running kernel so that bad
318 	 * guys can't print interesting stuff from kernel memory.
319 	 */
320 	if (dropgid) {
321 		setgid(getgid());
322 		setuid(getuid());
323 	}
324 
325 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
326 	if (kd == 0)
327 		errx(1, "%s", errbuf);
328 
329 	if (!fmt)
330 		parsefmt(dfmt);
331 
332 	/*
333 	 * Add TID to output format if requested unless user-specific format
334 	 * selected.
335 	 */
336 	if (showtid && !ofmt)
337 		insert_tid_in_fmt();
338 
339 	/* XXX - should be cleaner */
340 	if (!all && ttydev == NODEV && pid == -1 && !nuids) {
341 		if ((uids = malloc(sizeof (*uids))) == NULL)
342 			errx(1, "malloc: %s", strerror(errno));
343 		nuids = 1;
344 		*uids = getuid();
345 	}
346 
347 	/*
348 	 * scan requested variables, noting what structures are needed,
349 	 * and adjusting header widths as appropriate.
350 	 */
351 	scanvars();
352 
353 	/*
354 	 * Get boot time
355 	 */
356 	if (sysctlbyname("kern.boottime", &btime, &btime_size, NULL, 0) < 0) {
357 		perror("sysctl: kern.boottime");
358 		exit(EXIT_FAILURE);
359 	}
360 
361 	/*
362 	 * Get number of cpus
363 	 */
364 	if (sysctlbyname("hw.ncpu", &numcpus, &numcpus_size, NULL, 0) < 0)
365 		numcpus = 1;
366 
367 	/*
368 	 * get proc list
369 	 */
370 	if (nuids == 1) {
371 		what = KERN_PROC_UID;
372 		flag = *uids;
373 	} else if (ttydev != NODEV) {
374 		what = KERN_PROC_TTY;
375 		flag = ttydev;
376 	} else if (pid != -1) {
377 		what = KERN_PROC_PID;
378 		flag = pid;
379 	} else {
380 		what = KERN_PROC_ALL;
381 		flag = 0;
382 	}
383 	what |= showtid;
384 
385 	/*
386 	 * select procs
387 	 */
388 	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == NULL)
389 		errx(1, "%s", kvm_geterr(kd));
390 	if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
391 		err(1, NULL);
392 	for (i = nentries; --i >= 0; ++kp) {
393 		kinfo[i].ki_proc = kp;
394 		if (needuser)
395 			saveuser(&kinfo[i]);
396 		dynsizevars(&kinfo[i]);
397 	}
398 
399 	sizevars();
400 
401 	/*
402 	 * print header
403 	 */
404 	printheader();
405 	if (nentries == 0)
406 		exit(1);
407 	/*
408 	 * sort proc list
409 	 */
410 	qsort(kinfo, nentries, sizeof(KINFO), pscomp);
411 	/*
412 	 * for each proc, call each variable output function.
413 	 */
414 	for (i = lineno = 0; i < nentries; i++) {
415 		if (xflg == 0 && (KI_PROC(&kinfo[i], tdev) == NODEV ||
416 		    (KI_PROC(&kinfo[i], flags) & P_CONTROLT ) == 0))
417 			continue;
418 		if (nuids > 1) {
419 			for (uid = 0; uid < nuids; uid++)
420 				if (KI_PROC(&kinfo[i], uid) ==
421 				    uids[uid])
422 					break;
423 			if (uid == nuids)
424 				continue;
425 		}
426 		STAILQ_FOREACH(vent, &var_head, link) {
427 			(vent->var->oproc)(&kinfo[i], vent);
428 			if (STAILQ_NEXT(vent, link) != NULL)
429 				putchar(' ');
430 		}
431 		putchar('\n');
432 		if (prtheader && lineno++ == prtheader - 4) {
433 			putchar('\n');
434 			printheader();
435 			lineno = 0;
436 		}
437 	}
438 	free(uids);
439 
440 	exit(eval);
441 }
442 
443 uid_t *
444 getuids(const char *arg, int *nuids)
445 {
446 	char name[UT_NAMESIZE + 1];
447 	struct passwd *pwd;
448 	uid_t *uids, *moreuids;
449 	size_t l;
450 	int alloc;
451 
452 
453 	alloc = 0;
454 	*nuids = 0;
455 	uids = NULL;
456 	for (; (l = strcspn(arg, SEP)) > 0; arg += l + strspn(arg + l, SEP)) {
457 		if (l >= sizeof name) {
458 			warnx("%.*s: name too long", (int)l, arg);
459 			continue;
460 		}
461 		strncpy(name, arg, l);
462 		name[l] = '\0';
463 		if ((pwd = getpwnam(name)) == NULL) {
464 			warnx("%s: no such user", name);
465 			continue;
466 		}
467 		if (*nuids >= alloc) {
468 			alloc = (alloc + 1) << 1;
469 			moreuids = realloc(uids, alloc * sizeof (*uids));
470 			if (moreuids == NULL) {
471 				free(uids);
472 				errx(1, "realloc: %s", strerror(errno));
473 			}
474 			uids = moreuids;
475 		}
476 		uids[(*nuids)++] = pwd->pw_uid;
477 	}
478 	endpwent();
479 
480 	if (!*nuids)
481 		errx(1, "No users specified");
482 
483 	return uids;
484 }
485 
486 static void
487 scanvars(void)
488 {
489 	struct varent *vent;
490 	const VAR *v;
491 
492 	STAILQ_FOREACH(vent, &var_head, link) {
493 		v = vent->var;
494 		if (v->flag & DSIZ) {
495 			vent->dwidth = vent->width;
496 			vent->width = 0;
497 		}
498 		if (v->flag & USER)
499 			needuser = 1;
500 		if (v->flag & COMM)
501 			needcomm = 1;
502 	}
503 }
504 
505 static void
506 dynsizevars(KINFO *ki)
507 {
508 	struct varent *vent;
509 	const VAR *v;
510 	int i;
511 
512 	STAILQ_FOREACH(vent, &var_head, link) {
513 		v = vent->var;
514 		if (!(v->flag & DSIZ))
515 			continue;
516 		i = (v->sproc)( ki);
517 		if (vent->width < i)
518 			vent->width = i;
519 		if (vent->width > vent->dwidth)
520 			vent->width = vent->dwidth;
521 	}
522 }
523 
524 static void
525 sizevars(void)
526 {
527 	struct varent *vent;
528 	const VAR *v;
529 	int i;
530 
531 	STAILQ_FOREACH(vent, &var_head, link) {
532 		v = vent->var;
533 		i = strlen(vent->header);
534 		if (vent->width < i)
535 			vent->width = i;
536 		totwidth += vent->width + 1;	/* +1 for space */
537 	}
538 	totwidth--;
539 }
540 
541 static const char *
542 getfmt(char **(*fn) (kvm_t *, const struct kinfo_proc *, int), KINFO *ki, char
543     *comm, int maxlen)
544 {
545 	const char *s;
546 
547 	if ((s =
548 	    fmt_argv((*fn)(kd, ki->ki_proc, termwidth), comm, maxlen)) == NULL)
549 		err(1, NULL);
550 	return (s);
551 }
552 
553 static void
554 saveuser(KINFO *ki)
555 {
556 	/*
557 	 * save arguments if needed
558 	 */
559 	if (needcomm) {
560 		ki->ki_args = getfmt(kvm_getargv, ki, KI_PROC(ki, comm),
561 		    MAXCOMLEN);
562 	} else {
563 		ki->ki_args = NULL;
564 	}
565 	if (needenv) {
566 		ki->ki_env = getfmt(kvm_getenvv, ki, NULL, 0);
567 	} else {
568 		ki->ki_env = NULL;
569 	}
570 }
571 
572 static int
573 pscomp(const void *a, const void *b)
574 {
575 	int i;
576 #define VSIZE(k) (KI_PROC(k, vm_dsize) + KI_PROC(k, vm_ssize) + \
577 		  KI_PROC(k, vm_tsize))
578 
579 #if 0
580 	if (sortby == SORTIAC)
581 		return (KI_PROC((const KINFO *)a)->p_usdata.bsd4.interactive - KI_PROC((const KINFO *)b)->p_usdata.bsd4.interactive);
582 #endif
583 	if (sortby == SORTCPU)
584 		return (getpcpu((const KINFO *)b) - getpcpu((const KINFO *)a));
585 	if (sortby == SORTMEM)
586 		return (VSIZE((const KINFO *)b) - VSIZE((const KINFO *)a));
587 	i =  KI_PROC((const KINFO *)a, tdev) - KI_PROC((const KINFO *)b, tdev);
588 	if (i == 0)
589 		i = KI_PROC((const KINFO *)a, pid) - KI_PROC((const KINFO *)b, pid);
590 	return (i);
591 }
592 
593 /*
594  * ICK (all for getopt), would rather hide the ugliness
595  * here than taint the main code.
596  *
597  *  ps foo -> ps -foo
598  *  ps 34 -> ps -p34
599  *
600  * The old convention that 't' with no trailing tty arg means the users
601  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
602  * feature is available with the option 'T', which takes no argument.
603  */
604 static char *
605 kludge_oldps_options(char *s)
606 {
607 	size_t len;
608 	char *newopts, *ns, *cp;
609 
610 	len = strlen(s);
611 	if ((newopts = ns = malloc(len + 2)) == NULL)
612 		err(1, NULL);
613 	/*
614 	 * options begin with '-'
615 	 */
616 	if (*s != '-')
617 		*ns++ = '-';	/* add option flag */
618 	/*
619 	 * gaze to end of argv[1]
620 	 */
621 	cp = s + len - 1;
622 	/*
623 	 * if last letter is a 't' flag with no argument (in the context
624 	 * of the oldps options -- option string NOT starting with a '-' --
625 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
626 	 *
627 	 * However, if a flag accepting a string argument is found in the
628 	 * option string, the remainder of the string is the argument to
629 	 * that flag; do not modify that argument.
630 	 */
631 	if (strcspn(s, "MNOoU") == len && *cp == 't' && *s != '-')
632 		*cp = 'T';
633 	else {
634 		/*
635 		 * otherwise check for trailing number, which *may* be a
636 		 * pid.
637 		 */
638 		while (cp >= s && isdigit(*cp))
639 			--cp;
640 	}
641 	cp++;
642 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
643 	ns += cp - s;
644 	/*
645 	 * if there's a trailing number, and not a preceding 'p' (pid) or
646 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
647 	 */
648 	if (isdigit(*cp) &&
649 	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
650 	    (cp - 1 == s || cp[-2] != 't'))
651 		*ns++ = 'p';
652 	strcpy(ns, cp);		/* and append the number */
653 
654 	return (newopts);
655 }
656 
657 static int
658 check_procfs(void)
659 {
660 	struct statfs mnt;
661 
662 	if (statfs("/proc", &mnt) < 0)
663 		return (0);
664 	if (strcmp(mnt.f_fstypename, "procfs") != 0)
665 		return (0);
666 	return (1);
667 }
668 
669 static void
670 usage(void)
671 {
672 
673 	fprintf(stderr, "%s\n%s\n%s\n",
674 	    "usage: ps [-aChHjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty] [-U user]",
675 	    "          [-M core] [-N system]",
676 	    "       ps [-L]");
677 	exit(1);
678 }
679