xref: /freebsd/bin/ps/ps.c (revision b601c69bdbe8755d26570261d7fd4c02ee4eff74)
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 <nlist.h>
63 #include <paths.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <unistd.h>
68 #include <locale.h>
69 #include <pwd.h>
70 
71 #include "ps.h"
72 
73 KINFO *kinfo;
74 struct varent *vhead, *vtail;
75 
76 int	eval;			/* exit value */
77 int	cflag;			/* -c */
78 int	rawcpu;			/* -C */
79 int	sumrusage;		/* -S */
80 int	termwidth;		/* width of screen (0 == infinity) */
81 int	totwidth;		/* calculated width of requested variables */
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 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
91 
92 static char	*fmt __P((char **(*)(kvm_t *, const struct kinfo_proc *, int),
93 		    KINFO *, char *, int));
94 static char	*kludge_oldps_options __P((char *));
95 static int	 pscomp __P((const void *, const void *));
96 static void	 saveuser __P((KINFO *));
97 static void	 scanvars __P((void));
98 static void	 dynsizevars __P((KINFO *));
99 static void	 sizevars __P((void));
100 static void	 usage __P((void));
101 
102 char dfmt[] = "pid tt state time command";
103 char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
104 char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
105 char   o1[] = "pid";
106 char   o2[] = "tt state time command";
107 char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
108 char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
109 
110 kvm_t *kd;
111 
112 int
113 main(argc, argv)
114 	int argc;
115 	char *argv[];
116 {
117 	struct kinfo_proc *kp;
118 	struct varent *vent;
119 	struct winsize ws;
120 	struct passwd *pwd;
121 	dev_t ttydev;
122 	pid_t pid;
123 	uid_t uid;
124 	int all, ch, flag, i, fmt, lineno, nentries, dropgid;
125 	int prtheader, wflag, what, xflg;
126 	char *nlistf, *memf, *swapf, errbuf[_POSIX2_LINE_MAX];
127 
128 	(void) setlocale(LC_ALL, "");
129 
130 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
131 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
132 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
133 	     ws.ws_col == 0)
134 		termwidth = 79;
135 	else
136 		termwidth = ws.ws_col - 1;
137 
138 	if (argc > 1)
139 		argv[1] = kludge_oldps_options(argv[1]);
140 
141 	all = fmt = prtheader = wflag = xflg = 0;
142 	pid = -1;
143 	uid = (uid_t) -1;
144 	ttydev = NODEV;
145 	dropgid = 0;
146 	memf = nlistf = swapf = _PATH_DEVNULL;
147 	while ((ch = getopt(argc, argv,
148 #if defined(LAZY_PS)
149 	    "aCcefghjLlM:mN:O:o:p:rSTt:U:uvW:wx")) != -1)
150 #else
151 	    "aCceghjLlM:mN:O:o:p:rSTt:U:uvW:wx")) != -1)
152 #endif
153 		switch((char)ch) {
154 		case 'a':
155 			all = 1;
156 			break;
157 		case 'C':
158 			rawcpu = 1;
159 			break;
160 		case 'c':
161 			cflag = 1;
162 			break;
163 		case 'e':			/* XXX set ufmt */
164 			needenv = 1;
165 			break;
166 		case 'g':
167 			break;			/* no-op */
168 		case 'h':
169 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
170 			break;
171 		case 'j':
172 			parsefmt(jfmt);
173 			fmt = 1;
174 			jfmt[0] = '\0';
175 			break;
176 		case 'L':
177 			showkey();
178 			exit(0);
179 		case 'l':
180 			parsefmt(lfmt);
181 			fmt = 1;
182 			lfmt[0] = '\0';
183 			break;
184 		case 'M':
185 			memf = optarg;
186 			dropgid = 1;
187 			break;
188 		case 'm':
189 			sortby = SORTMEM;
190 			break;
191 		case 'N':
192 			nlistf = optarg;
193 			dropgid = 1;
194 			break;
195 		case 'O':
196 			parsefmt(o1);
197 			parsefmt(optarg);
198 			parsefmt(o2);
199 			o1[0] = o2[0] = '\0';
200 			fmt = 1;
201 			break;
202 		case 'o':
203 			parsefmt(optarg);
204 			fmt = 1;
205 			break;
206 #if defined(LAZY_PS)
207 		case 'f':
208 			if (getuid() == 0 || getgid() == 0)
209 			    forceuread = 1;
210 			break;
211 #endif
212 		case 'p':
213 			pid = atol(optarg);
214 			xflg = 1;
215 			break;
216 		case 'r':
217 			sortby = SORTCPU;
218 			break;
219 		case 'S':
220 			sumrusage = 1;
221 			break;
222 		case 'T':
223 			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
224 				errx(1, "stdin: not a terminal");
225 			/* FALLTHROUGH */
226 		case 't': {
227 			struct stat sb;
228 			char *ttypath, pathbuf[MAXPATHLEN];
229 
230 			if (strcmp(optarg, "co") == 0)
231 				ttypath = _PATH_CONSOLE;
232 			else if (*optarg != '/')
233 				(void)snprintf(ttypath = pathbuf,
234 				    sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
235 			else
236 				ttypath = optarg;
237 			if (stat(ttypath, &sb) == -1)
238 				err(1, "%s", ttypath);
239 			if (!S_ISCHR(sb.st_mode))
240 				errx(1, "%s: not a terminal", ttypath);
241 			ttydev = sb.st_rdev;
242 			break;
243 		}
244 		case 'U':
245 			pwd = getpwnam(optarg);
246 			if (pwd == NULL)
247 				errx(1, "%s: no such user", optarg);
248 			uid = pwd->pw_uid;
249 			endpwent();
250 			xflg++;		/* XXX: intuitive? */
251 			break;
252 		case 'u':
253 			parsefmt(ufmt);
254 			sortby = SORTCPU;
255 			fmt = 1;
256 			ufmt[0] = '\0';
257 			break;
258 		case 'v':
259 			parsefmt(vfmt);
260 			sortby = SORTMEM;
261 			fmt = 1;
262 			vfmt[0] = '\0';
263 			break;
264 		case 'W':
265 			swapf = optarg;
266 			dropgid = 1;
267 			break;
268 		case 'w':
269 			if (wflag)
270 				termwidth = UNLIMITED;
271 			else if (termwidth < 131)
272 				termwidth = 131;
273 			wflag++;
274 			break;
275 		case 'x':
276 			xflg = 1;
277 			break;
278 		case '?':
279 		default:
280 			usage();
281 		}
282 	argc -= optind;
283 	argv += optind;
284 
285 #define	BACKWARD_COMPATIBILITY
286 #ifdef	BACKWARD_COMPATIBILITY
287 	if (*argv) {
288 		nlistf = *argv;
289 		if (*++argv) {
290 			memf = *argv;
291 			if (*++argv)
292 				swapf = *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, swapf, 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 && uid == (uid_t)-1)
314 		uid = getuid();
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 (uid != (uid_t) -1) {
325 		what = KERN_PROC_UID;
326 		flag = uid;
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)
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 && (KI_EPROC(&kinfo[i])->e_tdev == NODEV ||
368 		    (KI_PROC(&kinfo[i])->p_flag & P_CONTROLT ) == 0))
369 			continue;
370 		for (vent = vhead; vent; vent = vent->next) {
371 			(vent->var->oproc)(&kinfo[i], vent);
372 			if (vent->next != NULL)
373 				(void)putchar(' ');
374 		}
375 		(void)putchar('\n');
376 		if (prtheader && lineno++ == prtheader - 4) {
377 			(void)putchar('\n');
378 			printheader();
379 			lineno = 0;
380 		}
381 	}
382 	exit(eval);
383 }
384 
385 static void
386 scanvars()
387 {
388 	struct varent *vent;
389 	VAR *v;
390 
391 	for (vent = vhead; vent; vent = vent->next) {
392 		v = vent->var;
393 		if (v->flag & DSIZ) {
394 			v->dwidth = v->width;
395 			v->width = 0;
396 		}
397 		if (v->flag & USER)
398 			needuser = 1;
399 		if (v->flag & COMM)
400 			needcomm = 1;
401 	}
402 }
403 
404 static void
405 dynsizevars(ki)
406 	KINFO *ki;
407 {
408 	struct varent *vent;
409 	VAR *v;
410 	int i;
411 
412 	for (vent = vhead; vent; vent = vent->next) {
413 		v = vent->var;
414 		if (!(v->flag & DSIZ))
415 			continue;
416 		i = (v->sproc)( ki);
417 		if (v->width < i)
418 			v->width = i;
419 		if (v->width > v->dwidth)
420 			v->width = v->dwidth;
421 	}
422 }
423 
424 static void
425 sizevars()
426 {
427 	struct varent *vent;
428 	VAR *v;
429 	int i;
430 
431 	for (vent = vhead; vent; vent = vent->next) {
432 		v = vent->var;
433 		i = strlen(v->header);
434 		if (v->width < i)
435 			v->width = i;
436 		totwidth += v->width + 1;	/* +1 for space */
437 	}
438 	totwidth--;
439 }
440 
441 static char *
442 fmt(fn, ki, comm, maxlen)
443 	char **(*fn) __P((kvm_t *, const struct kinfo_proc *, int));
444 	KINFO *ki;
445 	char *comm;
446 	int maxlen;
447 {
448 	char *s;
449 
450 	if ((s =
451 	    fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen)) == NULL)
452 		err(1, NULL);
453 	return (s);
454 }
455 
456 #define UREADOK(ki)	(forceuread || (KI_PROC(ki)->p_flag & P_INMEM))
457 
458 static void
459 saveuser(ki)
460 	KINFO *ki;
461 {
462 	struct usave *usp;
463 
464 	usp = &ki->ki_u;
465 
466 	if (KI_PROC(ki)->p_flag & P_INMEM) {
467 		/*
468 		 * The u-area might be swapped out, and we can't get
469 		 * at it because we have a crashdump and no swap.
470 		 * If it's here fill in these fields, otherwise, just
471 		 * leave them 0.
472 		 */
473 		usp->u_start = KI_EPROC(ki)->e_stats.p_start;
474 		usp->u_ru = KI_EPROC(ki)->e_stats.p_ru;
475 		usp->u_cru = KI_EPROC(ki)->e_stats.p_cru;
476 		usp->u_valid = 1;
477 	} else
478 		usp->u_valid = 0;
479 	/*
480 	 * save arguments if needed
481 	 */
482 	if (needcomm && (UREADOK(ki) || (KI_PROC(ki)->p_args != NULL))) {
483 		ki->ki_args = fmt(kvm_getargv, ki, KI_PROC(ki)->p_comm,
484 		    MAXCOMLEN);
485 	} else if (needcomm) {
486 		ki->ki_args = malloc(strlen(KI_PROC(ki)->p_comm) + 3);
487 		sprintf(ki->ki_args, "(%s)", KI_PROC(ki)->p_comm);
488 	} else {
489 		ki->ki_args = NULL;
490 	}
491 	if (needenv && UREADOK(ki)) {
492 		ki->ki_env = fmt(kvm_getenvv, ki, (char *)NULL, 0);
493 	} else if (needenv) {
494 		ki->ki_env = malloc(3);
495 		strcpy(ki->ki_env, "()");
496 	} else {
497 		ki->ki_env = NULL;
498 	}
499 }
500 
501 static int
502 pscomp(a, b)
503 	const void *a, *b;
504 {
505 	int i;
506 #define VSIZE(k) (KI_EPROC(k)->e_vm.vm_dsize + KI_EPROC(k)->e_vm.vm_ssize + \
507 		  KI_EPROC(k)->e_vm.vm_tsize)
508 
509 	if (sortby == SORTCPU)
510 		return (getpcpu((KINFO *)b) - getpcpu((KINFO *)a));
511 	if (sortby == SORTMEM)
512 		return (VSIZE((KINFO *)b) - VSIZE((KINFO *)a));
513 	i =  KI_EPROC((KINFO *)a)->e_tdev - KI_EPROC((KINFO *)b)->e_tdev;
514 	if (i == 0)
515 		i = KI_PROC((KINFO *)a)->p_pid - KI_PROC((KINFO *)b)->p_pid;
516 	return (i);
517 }
518 
519 /*
520  * ICK (all for getopt), would rather hide the ugliness
521  * here than taint the main code.
522  *
523  *  ps foo -> ps -foo
524  *  ps 34 -> ps -p34
525  *
526  * The old convention that 't' with no trailing tty arg means the users
527  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
528  * feature is available with the option 'T', which takes no argument.
529  */
530 static char *
531 kludge_oldps_options(s)
532 	char *s;
533 {
534 	size_t len;
535 	char *newopts, *ns, *cp;
536 
537 	len = strlen(s);
538 	if ((newopts = ns = malloc(len + 2)) == NULL)
539 		err(1, NULL);
540 	/*
541 	 * options begin with '-'
542 	 */
543 	if (*s != '-')
544 		*ns++ = '-';	/* add option flag */
545 	/*
546 	 * gaze to end of argv[1]
547 	 */
548 	cp = s + len - 1;
549 	/*
550 	 * if last letter is a 't' flag with no argument (in the context
551 	 * of the oldps options -- option string NOT starting with a '-' --
552 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
553 	 */
554 	if (*cp == 't' && *s != '-')
555 		*cp = 'T';
556 	else {
557 		/*
558 		 * otherwise check for trailing number, which *may* be a
559 		 * pid.
560 		 */
561 		while (cp >= s && isdigit(*cp))
562 			--cp;
563 	}
564 	cp++;
565 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
566 	ns += cp - s;
567 	/*
568 	 * if there's a trailing number, and not a preceding 'p' (pid) or
569 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
570 	 */
571 	if (isdigit(*cp) &&
572 	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
573 	    (cp - 1 == s || cp[-2] != 't'))
574 		*ns++ = 'p';
575 	(void)strcpy(ns, cp);		/* and append the number */
576 
577 	return (newopts);
578 }
579 
580 static void
581 usage()
582 {
583 
584 	(void)fprintf(stderr, "%s\n%s\n%s\n",
585 	    "usage: ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty] [-U user]",
586 	    "          [-M core] [-N system] [-W swap]",
587 	    "       ps [-L]");
588 	exit(1);
589 }
590