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