xref: /freebsd/bin/ps/ps.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
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 
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1990, 1993, 1994\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #if 0
41 #ifndef lint
42 static char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
43 #endif /* not lint */
44 #endif
45 
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48 
49 #include <sys/param.h>
50 #include <sys/user.h>
51 #include <sys/stat.h>
52 #include <sys/ioctl.h>
53 #include <sys/sysctl.h>
54 
55 #include <ctype.h>
56 #include <err.h>
57 #include <fcntl.h>
58 #include <kvm.h>
59 #include <limits.h>
60 #include <locale.h>
61 #include <paths.h>
62 #include <pwd.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <unistd.h>
67 
68 #include "ps.h"
69 
70 #define SEP ", \t"		/* username separators */
71 
72 static KINFO *kinfo;
73 struct varent *vhead;
74 
75 int	eval;			/* exit value */
76 int	cflag;			/* -c */
77 int	rawcpu;			/* -C */
78 int	sumrusage;		/* -S */
79 int	termwidth;		/* width of screen (0 == infinity) */
80 int	totwidth;		/* calculated width of requested variables */
81 
82 time_t	now;			/* current time(3) value */
83 
84 static int needuser, needcomm, needenv;
85 #if defined(LAZY_PS)
86 static int forceuread=0;
87 #else
88 static int forceuread=1;
89 #endif
90 
91 static enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
92 
93 static const	 char *fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
94 		    KINFO *, char *, int);
95 static char	*kludge_oldps_options(char *);
96 static int	 pscomp(const void *, const void *);
97 static void	 saveuser(KINFO *);
98 static void	 scanvars(void);
99 static void	 dynsizevars(KINFO *);
100 static void	 sizevars(void);
101 static void	 usage(void);
102 static uid_t	*getuids(const char *, int *);
103 
104 static char dfmt[] = "pid,tt,state,time,command";
105 static char jfmt[] = "user,pid,ppid,pgid,jobc,state,tt,time,command";
106 static char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,tt,time,command";
107 static char   o1[] = "pid";
108 static char   o2[] = "tt,state,time,command";
109 static char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
110 static char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,%cpu,%mem,command";
111 static char Zfmt[] = "label";
112 
113 static kvm_t *kd;
114 
115 #if defined(LAZY_PS)
116 #define PS_ARGS	"aCcefgHhjLlM:mN:O:o:p:rSTt:U:uvwxZ"
117 #else
118 #define PS_ARGS	"aCcegHhjLlM:mN:O:o:p:rSTt:U:uvwxZ"
119 #endif
120 
121 int
122 main(int argc, char *argv[])
123 {
124 	struct kinfo_proc *kp;
125 	struct varent *vent;
126 	struct winsize ws;
127 	dev_t ttydev;
128 	pid_t pid;
129 	uid_t *uids;
130 	int all, ch, flag, i, _fmt, lineno, nentries, nocludge, dropgid;
131 	int prtheader, wflag, what, xflg, uid, nuids, showthreads;
132 	char *cols;
133 	char errbuf[_POSIX2_LINE_MAX];
134 	const char *cp, *nlistf, *memf;
135 
136 	(void) setlocale(LC_ALL, "");
137 	/* Set the time to what it is right now. */
138 	time(&now);
139 
140 	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
141 		termwidth = atoi(cols);
142 	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
143 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
144 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
145 	     ws.ws_col == 0)
146 		termwidth = 79;
147 	else
148 		termwidth = ws.ws_col - 1;
149 
150 	/*
151 	 * Don't apply a kludge if the first argument is an option taking an
152 	 * argument
153 	 */
154 	if (argc > 1) {
155 		nocludge = 0;
156 		if (argv[1][0] == '-') {
157 			for (cp = PS_ARGS; *cp != '\0'; cp++) {
158 				if (*cp != ':')
159 					continue;
160 				if (*(cp - 1) == argv[1][1]) {
161 					nocludge = 1;
162 					break;
163 				}
164 			}
165 		}
166 		if (nocludge == 0)
167 			argv[1] = kludge_oldps_options(argv[1]);
168 	}
169 
170 	all = _fmt = prtheader = wflag = xflg = 0;
171 	pid = -1;
172 	nuids = 0;
173 	uids = NULL;
174 	ttydev = NODEV;
175 	dropgid = 0;
176 	memf = nlistf = _PATH_DEVNULL;
177 	showthreads = 0;
178 	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
179 		switch((char)ch) {
180 		case 'a':
181 			all = 1;
182 			break;
183 		case 'C':
184 			rawcpu = 1;
185 			break;
186 		case 'c':
187 			cflag = 1;
188 			break;
189 		case 'e':			/* XXX set ufmt */
190 			needenv = 1;
191 			break;
192 		case 'g':
193 			break;			/* no-op */
194 		case 'H':
195 			showthreads = 1;
196 			break;
197 		case 'h':
198 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
199 			break;
200 		case 'j':
201 			parsefmt(jfmt, 0);
202 			_fmt = 1;
203 			jfmt[0] = '\0';
204 			break;
205 		case 'L':
206 			showkey();
207 			exit(0);
208 		case 'l':
209 			parsefmt(lfmt, 0);
210 			_fmt = 1;
211 			lfmt[0] = '\0';
212 			break;
213 		case 'M':
214 			memf = optarg;
215 			dropgid = 1;
216 			break;
217 		case 'm':
218 			sortby = SORTMEM;
219 			break;
220 		case 'N':
221 			nlistf = optarg;
222 			dropgid = 1;
223 			break;
224 		case 'O':
225 			parsefmt(o1, 1);
226 			parsefmt(optarg, 1);
227 			parsefmt(o2, 1);
228 			o1[0] = o2[0] = '\0';
229 			_fmt = 1;
230 			break;
231 		case 'o':
232 			parsefmt(optarg, 1);
233 			_fmt = 1;
234 			break;
235 #if defined(LAZY_PS)
236 		case 'f':
237 			if (getuid() == 0 || getgid() == 0)
238 			    forceuread = 1;
239 			break;
240 #endif
241 		case 'p':
242 			pid = atol(optarg);
243 			xflg = 1;
244 			break;
245 		case 'r':
246 			sortby = SORTCPU;
247 			break;
248 		case 'S':
249 			sumrusage = 1;
250 			break;
251 		case 'T':
252 			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
253 				errx(1, "stdin: not a terminal");
254 			/* FALLTHROUGH */
255 		case 't': {
256 			struct stat sb;
257 			char *ttypath, pathbuf[PATH_MAX];
258 
259 			if (strcmp(optarg, "co") == 0)
260 				ttypath = strdup(_PATH_CONSOLE);
261 			else if (*optarg != '/')
262 				(void)snprintf(ttypath = pathbuf,
263 				    sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
264 			else
265 				ttypath = optarg;
266 			if (stat(ttypath, &sb) == -1)
267 				err(1, "%s", ttypath);
268 			if (!S_ISCHR(sb.st_mode))
269 				errx(1, "%s: not a terminal", ttypath);
270 			ttydev = sb.st_rdev;
271 			break;
272 		}
273 		case 'U':
274 			uids = getuids(optarg, &nuids);
275 			xflg++;		/* XXX: intuitive? */
276 			break;
277 		case 'u':
278 			parsefmt(ufmt, 0);
279 			sortby = SORTCPU;
280 			_fmt = 1;
281 			ufmt[0] = '\0';
282 			break;
283 		case 'v':
284 			parsefmt(vfmt, 0);
285 			sortby = SORTMEM;
286 			_fmt = 1;
287 			vfmt[0] = '\0';
288 			break;
289 		case 'w':
290 			if (wflag)
291 				termwidth = UNLIMITED;
292 			else if (termwidth < 131)
293 				termwidth = 131;
294 			wflag++;
295 			break;
296 		case 'x':
297 			xflg = 1;
298 			break;
299 		case 'Z':
300 			parsefmt(Zfmt, 0);
301 			Zfmt[0] = '\0';
302 			break;
303 		case '?':
304 		default:
305 			usage();
306 		}
307 	argc -= optind;
308 	argv += optind;
309 
310 #define	BACKWARD_COMPATIBILITY
311 #ifdef	BACKWARD_COMPATIBILITY
312 	if (*argv) {
313 		nlistf = *argv;
314 		if (*++argv) {
315 			memf = *argv;
316 		}
317 	}
318 #endif
319 	/*
320 	 * Discard setgid privileges if not the running kernel so that bad
321 	 * guys can't print interesting stuff from kernel memory.
322 	 */
323 	if (dropgid) {
324 		setgid(getgid());
325 		setuid(getuid());
326 	}
327 
328 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
329 	if (kd == 0)
330 		errx(1, "%s", errbuf);
331 
332 	if (!_fmt)
333 		parsefmt(dfmt, 0);
334 
335 	/* XXX - should be cleaner */
336 	if (!all && ttydev == NODEV && pid == -1 && !nuids) {
337 		if ((uids = malloc(sizeof (*uids))) == NULL)
338 			errx(1, "malloc failed");
339 		nuids = 1;
340 		*uids = getuid();
341 	}
342 
343 	/*
344 	 * scan requested variables, noting what structures are needed,
345 	 * and adjusting header widths as appropriate.
346 	 */
347 	scanvars();
348 	/*
349 	 * get proc list
350 	 */
351 	if (nuids == 1) {
352 		what = KERN_PROC_UID;
353 		flag = *uids;
354 	} else if (ttydev != NODEV) {
355 		what = KERN_PROC_TTY;
356 		flag = ttydev;
357 	} else if (pid != -1) {
358 		what = KERN_PROC_PID;
359 		flag = pid;
360 	} else if (showthreads == 1) {
361 		what = KERN_PROC_ALL;
362 		flag = 0;
363 	} else {
364 		what = KERN_PROC_PROC;
365 		flag = 0;
366 	}
367 	/*
368 	 * select procs
369 	 */
370 	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0 || nentries < 0)
371 		errx(1, "%s", kvm_geterr(kd));
372 	if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
373 		errx(1, "malloc failed");
374 	for (i = nentries; --i >= 0; ++kp) {
375 		kinfo[i].ki_p = kp;
376 		if (needuser)
377 			saveuser(&kinfo[i]);
378 		dynsizevars(&kinfo[i]);
379 	}
380 
381 	sizevars();
382 
383 	/*
384 	 * print header
385 	 */
386 	printheader();
387 	if (nentries == 0)
388 		exit(1);
389 	/*
390 	 * sort proc list
391 	 */
392 	qsort(kinfo, nentries, sizeof(KINFO), pscomp);
393 	/*
394 	 * for each proc, call each variable output function.
395 	 */
396 	for (i = lineno = 0; i < nentries; i++) {
397 		if (xflg == 0 && ((&kinfo[i])->ki_p->ki_tdev == NODEV ||
398 		    ((&kinfo[i])->ki_p->ki_flag & P_CONTROLT ) == 0))
399 			continue;
400 		if (nuids > 1) {
401 			for (uid = 0; uid < nuids; uid++)
402 				if ((&kinfo[i])->ki_p->ki_uid == uids[uid])
403 					break;
404 			if (uid == nuids)
405 				continue;
406 		}
407 		for (vent = vhead; vent; vent = vent->next) {
408 			(vent->var->oproc)(&kinfo[i], vent);
409 			if (vent->next != NULL)
410 				(void)putchar(' ');
411 		}
412 		(void)putchar('\n');
413 		if (prtheader && lineno++ == prtheader - 4) {
414 			(void)putchar('\n');
415 			printheader();
416 			lineno = 0;
417 		}
418 	}
419 	free(uids);
420 
421 	exit(eval);
422 }
423 
424 uid_t *
425 getuids(const char *arg, int *nuids)
426 {
427 	char name[MAXLOGNAME];
428 	struct passwd *pwd;
429 	uid_t *uids, *moreuids;
430 	int alloc;
431 	size_t l;
432 
433 
434 	alloc = 0;
435 	*nuids = 0;
436 	uids = NULL;
437 	for (; (l = strcspn(arg, SEP)) > 0; arg += l + strspn(arg + l, SEP)) {
438 		if (l >= sizeof name) {
439 			warnx("%.*s: name too long", (int)l, arg);
440 			continue;
441 		}
442 		strncpy(name, arg, l);
443 		name[l] = '\0';
444 		if ((pwd = getpwnam(name)) == NULL) {
445 			warnx("%s: no such user", name);
446 			continue;
447 		}
448 		if (*nuids >= alloc) {
449 			alloc = (alloc + 1) << 1;
450 			moreuids = realloc(uids, alloc * sizeof (*uids));
451 			if (moreuids == NULL) {
452 				free(uids);
453 				errx(1, "realloc failed");
454 			}
455 			uids = moreuids;
456 		}
457 		uids[(*nuids)++] = pwd->pw_uid;
458 	}
459 	endpwent();
460 
461 	if (!*nuids)
462 		errx(1, "No users specified");
463 
464 	return uids;
465 }
466 
467 VARENT *
468 find_varentry(VAR *v)
469 {
470 	struct varent *vent;
471 
472 	for (vent = vhead; vent; vent = vent->next) {
473 		if (strcmp(vent->var->name, v->name) == 0)
474 			return vent;
475 	}
476 	return NULL;
477 }
478 
479 static void
480 scanvars(void)
481 {
482 	struct varent *vent;
483 	VAR *v;
484 
485 	for (vent = vhead; vent; vent = vent->next) {
486 		v = vent->var;
487 		if (v->flag & DSIZ) {
488 			v->dwidth = v->width;
489 			v->width = 0;
490 		}
491 		if (v->flag & USER)
492 			needuser = 1;
493 		if (v->flag & COMM)
494 			needcomm = 1;
495 	}
496 }
497 
498 static void
499 dynsizevars(KINFO *ki)
500 {
501 	struct varent *vent;
502 	VAR *v;
503 	int i;
504 
505 	for (vent = vhead; vent; vent = vent->next) {
506 		v = vent->var;
507 		if (!(v->flag & DSIZ))
508 			continue;
509 		i = (v->sproc)( ki);
510 		if (v->width < i)
511 			v->width = i;
512 		if (v->width > v->dwidth)
513 			v->width = v->dwidth;
514 	}
515 }
516 
517 static void
518 sizevars(void)
519 {
520 	struct varent *vent;
521 	VAR *v;
522 	int i;
523 
524 	for (vent = vhead; vent; vent = vent->next) {
525 		v = vent->var;
526 		i = strlen(vent->header);
527 		if (v->width < i)
528 			v->width = i;
529 		totwidth += v->width + 1;	/* +1 for space */
530 	}
531 	totwidth--;
532 }
533 
534 static const char *
535 fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
536   char *comm, int maxlen)
537 {
538 	const char *s;
539 
540 	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
541 	return (s);
542 }
543 
544 #define UREADOK(ki)	(forceuread || (ki->ki_p->ki_sflag & PS_INMEM))
545 
546 static void
547 saveuser(KINFO *ki)
548 {
549 
550 	if (ki->ki_p->ki_sflag & PS_INMEM) {
551 		/*
552 		 * The u-area might be swapped out, and we can't get
553 		 * at it because we have a crashdump and no swap.
554 		 * If it's here fill in these fields, otherwise, just
555 		 * leave them 0.
556 		 */
557 		ki->ki_valid = 1;
558 	} else
559 		ki->ki_valid = 0;
560 	/*
561 	 * save arguments if needed
562 	 */
563 	if (needcomm && (UREADOK(ki) || (ki->ki_p->ki_args != NULL))) {
564 		ki->ki_args = strdup(fmt(kvm_getargv, ki, ki->ki_p->ki_comm,
565 		    MAXCOMLEN));
566 	} else if (needcomm) {
567 		asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
568 	} else {
569 		ki->ki_args = NULL;
570 	}
571 	if (needenv && UREADOK(ki)) {
572 		ki->ki_env = strdup(fmt(kvm_getenvv, ki, (char *)NULL, 0));
573 	} else if (needenv) {
574 		ki->ki_env = malloc(3);
575 		strcpy(ki->ki_env, "()");
576 	} else {
577 		ki->ki_env = NULL;
578 	}
579 }
580 
581 static int
582 pscomp(const void *a, const void *b)
583 {
584 	int i;
585 #define VSIZE(k) ((k)->ki_p->ki_dsize + (k)->ki_p->ki_ssize + \
586 		  (k)->ki_p->ki_tsize)
587 
588 	if (sortby == SORTCPU)
589 		return (getpcpu((const KINFO *)b) - getpcpu((const KINFO *)a));
590 	if (sortby == SORTMEM)
591 		return (VSIZE((const KINFO *)b) - VSIZE((const KINFO *)a));
592 	i =  (int)((const KINFO *)a)->ki_p->ki_tdev - (int)((const KINFO *)b)->ki_p->ki_tdev;
593 	if (i == 0)
594 		i = ((const KINFO *)a)->ki_p->ki_pid - ((const KINFO *)b)->ki_p->ki_pid;
595 	return (i);
596 }
597 
598 /*
599  * ICK (all for getopt), would rather hide the ugliness
600  * here than taint the main code.
601  *
602  *  ps foo -> ps -foo
603  *  ps 34 -> ps -p34
604  *
605  * The old convention that 't' with no trailing tty arg means the users
606  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
607  * feature is available with the option 'T', which takes no argument.
608  */
609 static char *
610 kludge_oldps_options(char *s)
611 {
612 	int have_fmt;
613 	size_t len;
614 	char *newopts, *ns, *cp;
615 
616 	/*
617 	 * If we have an 'o' option, then note it, since we don't want to do
618 	 * some types of munging.
619 	 */
620 	have_fmt = index(s, 'o') != NULL;
621 
622 	len = strlen(s);
623 	if ((newopts = ns = malloc(len + 2)) == NULL)
624 		errx(1, "malloc failed");
625 	/*
626 	 * options begin with '-'
627 	 */
628 	if (*s != '-')
629 		*ns++ = '-';	/* add option flag */
630 	/*
631 	 * gaze to end of argv[1]
632 	 */
633 	cp = s + len - 1;
634 	/*
635 	 * if last letter is a 't' flag with no argument (in the context
636 	 * of the oldps options -- option string NOT starting with a '-' --
637 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
638 	 *
639 	 * However, if a flag accepting a string argument is found in the
640 	 * option string, the remainder of the string is the argument to
641 	 * that flag; do not modify that argument.
642 	 */
643 	if (strcspn(s, "MNOoU") == len && *cp == 't' && *s != '-')
644 		*cp = 'T';
645 	else {
646 		/*
647 		 * otherwise check for trailing number, which *may* be a
648 		 * pid.
649 		 */
650 		while (cp >= s && isdigit(*cp))
651 			--cp;
652 	}
653 	cp++;
654 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
655 	ns += cp - s;
656 	/*
657 	 * if there's a trailing number, and not a preceding 'p' (pid) or
658 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
659 	 */
660 	if (isdigit(*cp) &&
661 	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
662 	    (cp - 1 == s || cp[-2] != 't') && !have_fmt)
663 		*ns++ = 'p';
664 	(void)strcpy(ns, cp);		/* and append the number */
665 
666 	return (newopts);
667 }
668 
669 static void
670 usage(void)
671 {
672 
673 	(void)fprintf(stderr, "%s\n%s\n%s\n",
674 	    "usage: ps [-aCHhjlmrSTuvwxZ] [-O|o fmt] [-p pid] [-t tty] [-U user]",
675 	    "          [-M core] [-N system]",
676 	    "       ps [-L]");
677 	exit(1);
678 }
679