xref: /freebsd/bin/ps/ps.c (revision 6a66acb565dde6d5b0ee52eef2a631fbb09df153)
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	"aCcefghjLlM:mN:O:o:p:rSTt:U:uvwxZ"
117 #else
118 #define PS_ARGS	"aCceghjLlM: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;
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 	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
178 		switch((char)ch) {
179 		case 'a':
180 			all = 1;
181 			break;
182 		case 'C':
183 			rawcpu = 1;
184 			break;
185 		case 'c':
186 			cflag = 1;
187 			break;
188 		case 'e':			/* XXX set ufmt */
189 			needenv = 1;
190 			break;
191 		case 'g':
192 			break;			/* no-op */
193 		case 'h':
194 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
195 			break;
196 		case 'j':
197 			parsefmt(jfmt, 0);
198 			_fmt = 1;
199 			jfmt[0] = '\0';
200 			break;
201 		case 'L':
202 			showkey();
203 			exit(0);
204 		case 'l':
205 			parsefmt(lfmt, 0);
206 			_fmt = 1;
207 			lfmt[0] = '\0';
208 			break;
209 		case 'M':
210 			memf = optarg;
211 			dropgid = 1;
212 			break;
213 		case 'm':
214 			sortby = SORTMEM;
215 			break;
216 		case 'N':
217 			nlistf = optarg;
218 			dropgid = 1;
219 			break;
220 		case 'O':
221 			parsefmt(o1, 1);
222 			parsefmt(optarg, 1);
223 			parsefmt(o2, 1);
224 			o1[0] = o2[0] = '\0';
225 			_fmt = 1;
226 			break;
227 		case 'o':
228 			parsefmt(optarg, 1);
229 			_fmt = 1;
230 			break;
231 #if defined(LAZY_PS)
232 		case 'f':
233 			if (getuid() == 0 || getgid() == 0)
234 			    forceuread = 1;
235 			break;
236 #endif
237 		case 'p':
238 			pid = atol(optarg);
239 			xflg = 1;
240 			break;
241 		case 'r':
242 			sortby = SORTCPU;
243 			break;
244 		case 'S':
245 			sumrusage = 1;
246 			break;
247 		case 'T':
248 			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
249 				errx(1, "stdin: not a terminal");
250 			/* FALLTHROUGH */
251 		case 't': {
252 			struct stat sb;
253 			char *ttypath, pathbuf[PATH_MAX];
254 
255 			if (strcmp(optarg, "co") == 0)
256 				ttypath = strdup(_PATH_CONSOLE);
257 			else if (*optarg != '/')
258 				(void)snprintf(ttypath = pathbuf,
259 				    sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
260 			else
261 				ttypath = optarg;
262 			if (stat(ttypath, &sb) == -1)
263 				err(1, "%s", ttypath);
264 			if (!S_ISCHR(sb.st_mode))
265 				errx(1, "%s: not a terminal", ttypath);
266 			ttydev = sb.st_rdev;
267 			break;
268 		}
269 		case 'U':
270 			uids = getuids(optarg, &nuids);
271 			xflg++;		/* XXX: intuitive? */
272 			break;
273 		case 'u':
274 			parsefmt(ufmt, 0);
275 			sortby = SORTCPU;
276 			_fmt = 1;
277 			ufmt[0] = '\0';
278 			break;
279 		case 'v':
280 			parsefmt(vfmt, 0);
281 			sortby = SORTMEM;
282 			_fmt = 1;
283 			vfmt[0] = '\0';
284 			break;
285 		case 'w':
286 			if (wflag)
287 				termwidth = UNLIMITED;
288 			else if (termwidth < 131)
289 				termwidth = 131;
290 			wflag++;
291 			break;
292 		case 'x':
293 			xflg = 1;
294 			break;
295 		case 'Z':
296 			parsefmt(Zfmt, 0);
297 			Zfmt[0] = '\0';
298 			break;
299 		case '?':
300 		default:
301 			usage();
302 		}
303 	argc -= optind;
304 	argv += optind;
305 
306 #define	BACKWARD_COMPATIBILITY
307 #ifdef	BACKWARD_COMPATIBILITY
308 	if (*argv) {
309 		nlistf = *argv;
310 		if (*++argv) {
311 			memf = *argv;
312 		}
313 	}
314 #endif
315 	/*
316 	 * Discard setgid privileges if not the running kernel so that bad
317 	 * guys can't print interesting stuff from kernel memory.
318 	 */
319 	if (dropgid) {
320 		setgid(getgid());
321 		setuid(getuid());
322 	}
323 
324 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
325 	if (kd == 0)
326 		errx(1, "%s", errbuf);
327 
328 	if (!_fmt)
329 		parsefmt(dfmt, 0);
330 
331 	/* XXX - should be cleaner */
332 	if (!all && ttydev == NODEV && pid == -1 && !nuids) {
333 		if ((uids = malloc(sizeof (*uids))) == NULL)
334 			errx(1, "malloc failed");
335 		nuids = 1;
336 		*uids = getuid();
337 	}
338 
339 	/*
340 	 * scan requested variables, noting what structures are needed,
341 	 * and adjusting header widths as appropriate.
342 	 */
343 	scanvars();
344 	/*
345 	 * get proc list
346 	 */
347 	if (nuids == 1) {
348 		what = KERN_PROC_UID;
349 		flag = *uids;
350 	} else if (ttydev != NODEV) {
351 		what = KERN_PROC_TTY;
352 		flag = ttydev;
353 	} else if (pid != -1) {
354 		what = KERN_PROC_PID;
355 		flag = pid;
356 	} else {
357 		what = KERN_PROC_ALL;
358 		flag = 0;
359 	}
360 	/*
361 	 * select procs
362 	 */
363 	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0 || nentries < 0)
364 		errx(1, "%s", kvm_geterr(kd));
365 	if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
366 		errx(1, "malloc failed");
367 	for (i = nentries; --i >= 0; ++kp) {
368 		kinfo[i].ki_p = kp;
369 		if (needuser)
370 			saveuser(&kinfo[i]);
371 		dynsizevars(&kinfo[i]);
372 	}
373 
374 	sizevars();
375 
376 	/*
377 	 * print header
378 	 */
379 	printheader();
380 	if (nentries == 0)
381 		exit(1);
382 	/*
383 	 * sort proc list
384 	 */
385 	qsort(kinfo, nentries, sizeof(KINFO), pscomp);
386 	/*
387 	 * for each proc, call each variable output function.
388 	 */
389 	for (i = lineno = 0; i < nentries; i++) {
390 		if (xflg == 0 && ((&kinfo[i])->ki_p->ki_tdev == NODEV ||
391 		    ((&kinfo[i])->ki_p->ki_flag & P_CONTROLT ) == 0))
392 			continue;
393 		if (nuids > 1) {
394 			for (uid = 0; uid < nuids; uid++)
395 				if ((&kinfo[i])->ki_p->ki_uid == uids[uid])
396 					break;
397 			if (uid == nuids)
398 				continue;
399 		}
400 		for (vent = vhead; vent; vent = vent->next) {
401 			(vent->var->oproc)(&kinfo[i], vent);
402 			if (vent->next != NULL)
403 				(void)putchar(' ');
404 		}
405 		(void)putchar('\n');
406 		if (prtheader && lineno++ == prtheader - 4) {
407 			(void)putchar('\n');
408 			printheader();
409 			lineno = 0;
410 		}
411 	}
412 	free(uids);
413 
414 	exit(eval);
415 }
416 
417 uid_t *
418 getuids(const char *arg, int *nuids)
419 {
420 	char name[MAXLOGNAME];
421 	struct passwd *pwd;
422 	uid_t *uids, *moreuids;
423 	int alloc;
424 	size_t l;
425 
426 
427 	alloc = 0;
428 	*nuids = 0;
429 	uids = NULL;
430 	for (; (l = strcspn(arg, SEP)) > 0; arg += l + strspn(arg + l, SEP)) {
431 		if (l >= sizeof name) {
432 			warnx("%.*s: name too long", (int)l, arg);
433 			continue;
434 		}
435 		strncpy(name, arg, l);
436 		name[l] = '\0';
437 		if ((pwd = getpwnam(name)) == NULL) {
438 			warnx("%s: no such user", name);
439 			continue;
440 		}
441 		if (*nuids >= alloc) {
442 			alloc = (alloc + 1) << 1;
443 			moreuids = realloc(uids, alloc * sizeof (*uids));
444 			if (moreuids == NULL) {
445 				free(uids);
446 				errx(1, "realloc failed");
447 			}
448 			uids = moreuids;
449 		}
450 		uids[(*nuids)++] = pwd->pw_uid;
451 	}
452 	endpwent();
453 
454 	if (!*nuids)
455 		errx(1, "No users specified");
456 
457 	return uids;
458 }
459 
460 VARENT *
461 find_varentry(VAR *v)
462 {
463 	struct varent *vent;
464 
465 	for (vent = vhead; vent; vent = vent->next) {
466 		if (strcmp(vent->var->name, v->name) == 0)
467 			return vent;
468 	}
469 	return NULL;
470 }
471 
472 static void
473 scanvars(void)
474 {
475 	struct varent *vent;
476 	VAR *v;
477 
478 	for (vent = vhead; vent; vent = vent->next) {
479 		v = vent->var;
480 		if (v->flag & DSIZ) {
481 			v->dwidth = v->width;
482 			v->width = 0;
483 		}
484 		if (v->flag & USER)
485 			needuser = 1;
486 		if (v->flag & COMM)
487 			needcomm = 1;
488 	}
489 }
490 
491 static void
492 dynsizevars(KINFO *ki)
493 {
494 	struct varent *vent;
495 	VAR *v;
496 	int i;
497 
498 	for (vent = vhead; vent; vent = vent->next) {
499 		v = vent->var;
500 		if (!(v->flag & DSIZ))
501 			continue;
502 		i = (v->sproc)( ki);
503 		if (v->width < i)
504 			v->width = i;
505 		if (v->width > v->dwidth)
506 			v->width = v->dwidth;
507 	}
508 }
509 
510 static void
511 sizevars(void)
512 {
513 	struct varent *vent;
514 	VAR *v;
515 	int i;
516 
517 	for (vent = vhead; vent; vent = vent->next) {
518 		v = vent->var;
519 		i = strlen(vent->header);
520 		if (v->width < i)
521 			v->width = i;
522 		totwidth += v->width + 1;	/* +1 for space */
523 	}
524 	totwidth--;
525 }
526 
527 static const char *
528 fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
529   char *comm, int maxlen)
530 {
531 	const char *s;
532 
533 	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
534 	return (s);
535 }
536 
537 #define UREADOK(ki)	(forceuread || (ki->ki_p->ki_sflag & PS_INMEM))
538 
539 static void
540 saveuser(KINFO *ki)
541 {
542 
543 	if (ki->ki_p->ki_sflag & PS_INMEM) {
544 		/*
545 		 * The u-area might be swapped out, and we can't get
546 		 * at it because we have a crashdump and no swap.
547 		 * If it's here fill in these fields, otherwise, just
548 		 * leave them 0.
549 		 */
550 		ki->ki_valid = 1;
551 	} else
552 		ki->ki_valid = 0;
553 	/*
554 	 * save arguments if needed
555 	 */
556 	if (needcomm && (UREADOK(ki) || (ki->ki_p->ki_args != NULL))) {
557 		ki->ki_args = strdup(fmt(kvm_getargv, ki, ki->ki_p->ki_comm,
558 		    MAXCOMLEN));
559 	} else if (needcomm) {
560 		asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
561 	} else {
562 		ki->ki_args = NULL;
563 	}
564 	if (needenv && UREADOK(ki)) {
565 		ki->ki_env = strdup(fmt(kvm_getenvv, ki, (char *)NULL, 0));
566 	} else if (needenv) {
567 		ki->ki_env = malloc(3);
568 		strcpy(ki->ki_env, "()");
569 	} else {
570 		ki->ki_env = NULL;
571 	}
572 }
573 
574 static int
575 pscomp(const void *a, const void *b)
576 {
577 	int i;
578 #define VSIZE(k) ((k)->ki_p->ki_dsize + (k)->ki_p->ki_ssize + \
579 		  (k)->ki_p->ki_tsize)
580 
581 	if (sortby == SORTCPU)
582 		return (getpcpu((const KINFO *)b) - getpcpu((const KINFO *)a));
583 	if (sortby == SORTMEM)
584 		return (VSIZE((const KINFO *)b) - VSIZE((const KINFO *)a));
585 	i =  (int)((const KINFO *)a)->ki_p->ki_tdev - (int)((const KINFO *)b)->ki_p->ki_tdev;
586 	if (i == 0)
587 		i = ((const KINFO *)a)->ki_p->ki_pid - ((const KINFO *)b)->ki_p->ki_pid;
588 	return (i);
589 }
590 
591 /*
592  * ICK (all for getopt), would rather hide the ugliness
593  * here than taint the main code.
594  *
595  *  ps foo -> ps -foo
596  *  ps 34 -> ps -p34
597  *
598  * The old convention that 't' with no trailing tty arg means the users
599  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
600  * feature is available with the option 'T', which takes no argument.
601  */
602 static char *
603 kludge_oldps_options(char *s)
604 {
605 	int have_fmt;
606 	size_t len;
607 	char *newopts, *ns, *cp;
608 
609 	/*
610 	 * If we have an 'o' option, then note it, since we don't want to do
611 	 * some types of munging.
612 	 */
613 	have_fmt = index(s, 'o') != NULL;
614 
615 	len = strlen(s);
616 	if ((newopts = ns = malloc(len + 2)) == NULL)
617 		errx(1, "malloc failed");
618 	/*
619 	 * options begin with '-'
620 	 */
621 	if (*s != '-')
622 		*ns++ = '-';	/* add option flag */
623 	/*
624 	 * gaze to end of argv[1]
625 	 */
626 	cp = s + len - 1;
627 	/*
628 	 * if last letter is a 't' flag with no argument (in the context
629 	 * of the oldps options -- option string NOT starting with a '-' --
630 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
631 	 *
632 	 * However, if a flag accepting a string argument is found in the
633 	 * option string, the remainder of the string is the argument to
634 	 * that flag; do not modify that argument.
635 	 */
636 	if (strcspn(s, "MNOoU") == len && *cp == 't' && *s != '-')
637 		*cp = 'T';
638 	else {
639 		/*
640 		 * otherwise check for trailing number, which *may* be a
641 		 * pid.
642 		 */
643 		while (cp >= s && isdigit(*cp))
644 			--cp;
645 	}
646 	cp++;
647 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
648 	ns += cp - s;
649 	/*
650 	 * if there's a trailing number, and not a preceding 'p' (pid) or
651 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
652 	 */
653 	if (isdigit(*cp) &&
654 	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
655 	    (cp - 1 == s || cp[-2] != 't') && !have_fmt)
656 		*ns++ = 'p';
657 	(void)strcpy(ns, cp);		/* and append the number */
658 
659 	return (newopts);
660 }
661 
662 static void
663 usage(void)
664 {
665 
666 	(void)fprintf(stderr, "%s\n%s\n%s\n",
667 	    "usage: ps [-aChjlmrSTuvwxZ] [-O|o fmt] [-p pid] [-t tty] [-U user]",
668 	    "          [-M core] [-N system]",
669 	    "       ps [-L]");
670 	exit(1);
671 }
672