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