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