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