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