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