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