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