xref: /netbsd-src/bin/ps/ps.c (revision 76dfffe33547c37f8bdd446e3e4ab0f3c16cea4b)
1 /*	$NetBSD: ps.c,v 1.16 1996/09/27 02:59:53 thorpej Exp $	*/
2 
3 /*-
4  * Copyright (c) 1990, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the University of
18  *	California, Berkeley and its contributors.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #ifndef lint
37 static char 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 #if 0
44 static char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
45 #else
46 static char rcsid[] = "$NetBSD: ps.c,v 1.16 1996/09/27 02:59:53 thorpej Exp $";
47 #endif
48 #endif /* not lint */
49 
50 #include <sys/param.h>
51 #include <sys/user.h>
52 #include <sys/time.h>
53 #include <sys/resource.h>
54 #include <sys/proc.h>
55 #include <sys/stat.h>
56 #include <sys/ioctl.h>
57 #include <sys/sysctl.h>
58 
59 #include <ctype.h>
60 #include <err.h>
61 #include <errno.h>
62 #include <fcntl.h>
63 #include <kvm.h>
64 #include <nlist.h>
65 #include <paths.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <unistd.h>
70 
71 #include "ps.h"
72 
73 #ifdef P_PPWAIT
74 #define NEWVM
75 #endif
76 
77 KINFO *kinfo;
78 struct varent *vhead, *vtail;
79 
80 int	eval;			/* exit value */
81 int	rawcpu;			/* -C */
82 int	sumrusage;		/* -S */
83 int	termwidth;		/* width of screen (0 == infinity) */
84 int	totwidth;		/* calculated width of requested variables */
85 
86 int	needuser, needcomm, needenv, commandonly;
87 
88 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
89 
90 static char	*kludge_oldps_options __P((char *));
91 static int	 pscomp __P((const void *, const void *));
92 static void	 saveuser __P((KINFO *));
93 static void	 scanvars __P((void));
94 static void	 usage __P((void));
95 
96 char dfmt[] = "pid tt state time command";
97 char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
98 char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
99 char   o1[] = "pid";
100 char   o2[] = "tt state time command";
101 char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
102 char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
103 
104 kvm_t *kd;
105 
106 int
107 main(argc, argv)
108 	int argc;
109 	char *argv[];
110 {
111 	struct kinfo_proc *kp;
112 	struct varent *vent;
113 	struct winsize ws;
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[256];
120 
121 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
122 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
123 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
124 	     ws.ws_col == 0)
125 		termwidth = 79;
126 	else
127 		termwidth = ws.ws_col - 1;
128 
129 	if (argc > 1)
130 		argv[1] = kludge_oldps_options(argv[1]);
131 
132 	all = fmt = prtheader = wflag = xflg = 0;
133 	pid = -1;
134 	uid = (uid_t) -1;
135 	ttydev = NODEV;
136 	memf = nlistf = swapf = NULL;
137 	while ((ch = getopt(argc, argv,
138 	    "acCeghjLlM:mN:O:o:p:rSTt:uvW:wx")) != EOF)
139 		switch((char)ch) {
140 		case 'a':
141 			all = 1;
142 			break;
143 		case 'c':
144 			commandonly = 1;
145 			break;
146 		case 'e':			/* XXX set ufmt */
147 			needenv = 1;
148 			break;
149 		case 'C':
150 			rawcpu = 1;
151 			break;
152 		case 'g':
153 			break;			/* no-op */
154 		case 'h':
155 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
156 			break;
157 		case 'j':
158 			parsefmt(jfmt);
159 			fmt = 1;
160 			jfmt[0] = '\0';
161 			break;
162 		case 'L':
163 			showkey();
164 			exit(0);
165 		case 'l':
166 			parsefmt(lfmt);
167 			fmt = 1;
168 			lfmt[0] = '\0';
169 			break;
170 		case 'M':
171 			memf = optarg;
172 			break;
173 		case 'm':
174 			sortby = SORTMEM;
175 			break;
176 		case 'N':
177 			nlistf = optarg;
178 			break;
179 		case 'O':
180 			parsefmt(o1);
181 			parsefmt(optarg);
182 			parsefmt(o2);
183 			o1[0] = o2[0] = '\0';
184 			fmt = 1;
185 			break;
186 		case 'o':
187 			parsefmt(optarg);
188 			fmt = 1;
189 			break;
190 		case 'p':
191 			pid = atol(optarg);
192 			xflg = 1;
193 			break;
194 		case 'r':
195 			sortby = SORTCPU;
196 			break;
197 		case 'S':
198 			sumrusage = 1;
199 			break;
200 		case 'T':
201 			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
202 				errx(1, "stdin: not a terminal");
203 			/* FALLTHROUGH */
204 		case 't': {
205 			struct stat sb;
206 			char *ttypath, pathbuf[MAXPATHLEN];
207 
208 			if (strcmp(optarg, "co") == 0)
209 				ttypath = _PATH_CONSOLE;
210 			else if (*optarg != '/')
211 				(void)snprintf(ttypath = pathbuf,
212 				    sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
213 			else
214 				ttypath = optarg;
215 			if (stat(ttypath, &sb) == -1)
216 				err(1, "%s", ttypath);
217 			if (!S_ISCHR(sb.st_mode))
218 				errx(1, "%s: not a terminal", ttypath);
219 			ttydev = sb.st_rdev;
220 			break;
221 		}
222 		case 'u':
223 			parsefmt(ufmt);
224 			sortby = SORTCPU;
225 			fmt = 1;
226 			ufmt[0] = '\0';
227 			break;
228 		case 'v':
229 			parsefmt(vfmt);
230 			sortby = SORTMEM;
231 			fmt = 1;
232 			vfmt[0] = '\0';
233 			break;
234 		case 'W':
235 			swapf = optarg;
236 			break;
237 		case 'w':
238 			if (wflag)
239 				termwidth = UNLIMITED;
240 			else if (termwidth < 131)
241 				termwidth = 131;
242 			wflag++;
243 			break;
244 		case 'x':
245 			xflg = 1;
246 			break;
247 		case '?':
248 		default:
249 			usage();
250 		}
251 	argc -= optind;
252 	argv += optind;
253 
254 #define	BACKWARD_COMPATIBILITY
255 #ifdef	BACKWARD_COMPATIBILITY
256 	if (*argv) {
257 		nlistf = *argv;
258 		if (*++argv) {
259 			memf = *argv;
260 			if (*++argv)
261 				swapf = *argv;
262 		}
263 	}
264 #endif
265 	/*
266 	 * Discard setgid privileges if not the running kernel so that bad
267 	 * guys can't print interesting stuff from kernel memory.
268 	 */
269 	if (nlistf != NULL || memf != NULL || swapf != NULL)
270 		setgid(getgid());
271 
272 	kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
273 	if (kd == 0)
274 		errx(1, "%s", errbuf);
275 
276 	if (!fmt)
277 		parsefmt(dfmt);
278 
279 	if (!all && ttydev == NODEV && pid == -1)  /* XXX - should be cleaner */
280 		uid = getuid();
281 
282 	/*
283 	 * scan requested variables, noting what structures are needed,
284 	 * and adjusting header widths as appropiate.
285 	 */
286 	scanvars();
287 	/*
288 	 * get proc list
289 	 */
290 	if (uid != (uid_t) -1) {
291 		what = KERN_PROC_UID;
292 		flag = uid;
293 	} else if (ttydev != NODEV) {
294 		what = KERN_PROC_TTY;
295 		flag = ttydev;
296 	} else if (pid != -1) {
297 		what = KERN_PROC_PID;
298 		flag = pid;
299 	} else {
300 		what = KERN_PROC_ALL;
301 		flag = 0;
302 	}
303 	/*
304 	 * select procs
305 	 */
306 	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0)
307 		errx(1, "%s", kvm_geterr(kd));
308 	if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
309 		err(1, NULL);
310 	for (i = nentries; --i >= 0; ++kp) {
311 		kinfo[i].ki_p = kp;
312 		if (needuser)
313 			saveuser(&kinfo[i]);
314 	}
315 	/*
316 	 * print header
317 	 */
318 	printheader();
319 	if (nentries == 0)
320 		exit(0);
321 	/*
322 	 * sort proc list
323 	 */
324 	qsort(kinfo, nentries, sizeof(KINFO), pscomp);
325 	/*
326 	 * for each proc, call each variable output function.
327 	 */
328 	for (i = lineno = 0; i < nentries; i++) {
329 		KINFO *ki = &kinfo[i];
330 
331 		if (xflg == 0 && (KI_EPROC(ki)->e_tdev == NODEV ||
332 		    (KI_PROC(ki)->p_flag & P_CONTROLT ) == 0))
333 			continue;
334 		for (vent = vhead; vent; vent = vent->next) {
335 			(vent->var->oproc)(ki, vent);
336 			if (vent->next != NULL)
337 				(void)putchar(' ');
338 		}
339 		(void)putchar('\n');
340 		if (prtheader && lineno++ == prtheader - 4) {
341 			(void)putchar('\n');
342 			printheader();
343 			lineno = 0;
344 		}
345 	}
346 	exit(eval);
347 }
348 
349 static void
350 scanvars()
351 {
352 	struct varent *vent;
353 	VAR *v;
354 	int i;
355 
356 	for (vent = vhead; vent; vent = vent->next) {
357 		v = vent->var;
358 		i = strlen(v->header);
359 		if (v->width < i)
360 			v->width = i;
361 		totwidth += v->width + 1;	/* +1 for space */
362 		if (v->flag & USER)
363 			needuser = 1;
364 		if (v->flag & COMM)
365 			needcomm = 1;
366 	}
367 	totwidth--;
368 }
369 
370 static void
371 saveuser(ki)
372 	KINFO *ki;
373 {
374 	struct pstats pstats;
375 	struct usave *usp;
376 
377 	usp = &ki->ki_u;
378 	if (kvm_read(kd, (u_long)&KI_PROC(ki)->p_addr->u_stats,
379 	    (char *)&pstats, sizeof(pstats)) == sizeof(pstats)) {
380 		/*
381 		 * The u-area might be swapped out, and we can't get
382 		 * at it because we have a crashdump and no swap.
383 		 * If it's here fill in these fields, otherwise, just
384 		 * leave them 0.
385 		 */
386 		usp->u_start = pstats.p_start;
387 		usp->u_ru = pstats.p_ru;
388 		usp->u_cru = pstats.p_cru;
389 		usp->u_valid = 1;
390 	} else
391 		usp->u_valid = 0;
392 }
393 
394 static int
395 pscomp(a, b)
396 	const void *a, *b;
397 {
398 	int i;
399 #ifdef NEWVM
400 #define VSIZE(k) (KI_EPROC(k)->e_vm.vm_dsize + KI_EPROC(k)->e_vm.vm_ssize + \
401 		  KI_EPROC(k)->e_vm.vm_tsize)
402 #else
403 #define VSIZE(k) ((k)->ki_p->p_dsize + (k)->ki_p->p_ssize + (k)->ki_e->e_xsize)
404 #endif
405 
406 	if (sortby == SORTCPU)
407 		return (getpcpu((KINFO *)b) - getpcpu((KINFO *)a));
408 	if (sortby == SORTMEM)
409 		return (VSIZE((KINFO *)b) - VSIZE((KINFO *)a));
410 	i =  KI_EPROC((KINFO *)a)->e_tdev - KI_EPROC((KINFO *)b)->e_tdev;
411 	if (i == 0)
412 		i = KI_PROC((KINFO *)a)->p_pid - KI_PROC((KINFO *)b)->p_pid;
413 	return (i);
414 }
415 
416 /*
417  * ICK (all for getopt), would rather hide the ugliness
418  * here than taint the main code.
419  *
420  *  ps foo -> ps -foo
421  *  ps 34 -> ps -p34
422  *
423  * The old convention that 't' with no trailing tty arg means the users
424  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
425  * feature is available with the option 'T', which takes no argument.
426  */
427 static char *
428 kludge_oldps_options(s)
429 	char *s;
430 {
431 	size_t len;
432 	char *newopts, *ns, *cp;
433 
434 	len = strlen(s);
435 	if ((newopts = ns = malloc(len + 3)) == NULL)
436 		err(1, NULL);
437 	/*
438 	 * options begin with '-'
439 	 */
440 	if (*s != '-')
441 		*ns++ = '-';	/* add option flag */
442 	/*
443 	 * gaze to end of argv[1]
444 	 */
445 	cp = s + len - 1;
446 	/*
447 	 * if last letter is a 't' flag with no argument (in the context
448 	 * of the oldps options -- option string NOT starting with a '-' --
449 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
450 	 */
451 	if (*cp == 't' && *s != '-')
452 		*cp = 'T';
453 	else {
454 		/*
455 		 * otherwise check for trailing number, which *may* be a
456 		 * pid.
457 		 */
458 		while (cp >= s && isdigit(*cp))
459 			--cp;
460 	}
461 	cp++;
462 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
463 	ns += cp - s;
464 	/*
465 	 * if there's a trailing number, and not a preceding 'p' (pid) or
466 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
467 	 */
468 	if (isdigit(*cp) && (cp == s || cp[-1] != 't' && cp[-1] != 'p' &&
469 	    (cp - 1 == s || cp[-2] != 't')))
470 		*ns++ = 'p';
471 	(void)strcpy(ns, cp);		/* and append the number */
472 
473 	return (newopts);
474 }
475 
476 static void
477 usage()
478 {
479 
480 	(void)fprintf(stderr,
481 	    "usage:\t%s\n\t   %s\n\t%s\n",
482 	    "ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty]",
483 	    "[-M core] [-N system] [-W swap]",
484 	    "ps [-L]");
485 	exit(1);
486 }
487