xref: /netbsd-src/bin/ps/ps.c (revision ce0bb6e8d2e560ecacbe865a848624f94498063b)
1 /*	$NetBSD: ps.c,v 1.13 1995/03/21 09:08:10 cgd 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.13 1995/03/21 09:08:10 cgd 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 static int needuser, needcomm, needenv, commandonly;
87 
88 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
89 
90 static char	*fmt __P((char **(*)(kvm_t *, const struct kinfo_proc *, int),
91 		    KINFO *, char *, int));
92 static char	*kludge_oldps_options __P((char *));
93 static int	 pscomp __P((const void *, const void *));
94 static void	 saveuser __P((KINFO *));
95 static void	 scanvars __P((void));
96 static void	 usage __P((void));
97 
98 char dfmt[] = "pid tt state time command";
99 char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
100 char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
101 char   o1[] = "pid";
102 char   o2[] = "tt state time command";
103 char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
104 char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
105 
106 kvm_t *kd;
107 
108 int
109 main(argc, argv)
110 	int argc;
111 	char *argv[];
112 {
113 	struct kinfo_proc *kp;
114 	struct varent *vent;
115 	struct winsize ws;
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[256];
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:uvW:wx")) != EOF)
141 		switch((char)ch) {
142 		case 'a':
143 			all = 1;
144 			break;
145 		case 'c':
146 			commandonly = 1;
147 			break;
148 		case 'e':			/* XXX set ufmt */
149 			needenv = 1;
150 			break;
151 		case 'C':
152 			rawcpu = 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 			parsefmt(ufmt);
226 			sortby = SORTCPU;
227 			fmt = 1;
228 			ufmt[0] = '\0';
229 			break;
230 		case 'v':
231 			parsefmt(vfmt);
232 			sortby = SORTMEM;
233 			fmt = 1;
234 			vfmt[0] = '\0';
235 			break;
236 		case 'W':
237 			swapf = optarg;
238 			break;
239 		case 'w':
240 			if (wflag)
241 				termwidth = UNLIMITED;
242 			else if (termwidth < 131)
243 				termwidth = 131;
244 			wflag++;
245 			break;
246 		case 'x':
247 			xflg = 1;
248 			break;
249 		case '?':
250 		default:
251 			usage();
252 		}
253 	argc -= optind;
254 	argv += optind;
255 
256 #define	BACKWARD_COMPATIBILITY
257 #ifdef	BACKWARD_COMPATIBILITY
258 	if (*argv) {
259 		nlistf = *argv;
260 		if (*++argv) {
261 			memf = *argv;
262 			if (*++argv)
263 				swapf = *argv;
264 		}
265 	}
266 #endif
267 	/*
268 	 * Discard setgid privileges if not the running kernel so that bad
269 	 * guys can't print interesting stuff from kernel memory.
270 	 */
271 	if (nlistf != NULL || memf != NULL || swapf != NULL)
272 		setgid(getgid());
273 
274 	kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
275 	if (kd == 0)
276 		errx(1, "%s", errbuf);
277 
278 	if (!fmt)
279 		parsefmt(dfmt);
280 
281 	if (!all && ttydev == NODEV && pid == -1)  /* XXX - should be cleaner */
282 		uid = getuid();
283 
284 	/*
285 	 * scan requested variables, noting what structures are needed,
286 	 * and adjusting header widths as appropiate.
287 	 */
288 	scanvars();
289 	/*
290 	 * get proc list
291 	 */
292 	if (uid != (uid_t) -1) {
293 		what = KERN_PROC_UID;
294 		flag = uid;
295 	} else if (ttydev != NODEV) {
296 		what = KERN_PROC_TTY;
297 		flag = ttydev;
298 	} else if (pid != -1) {
299 		what = KERN_PROC_PID;
300 		flag = pid;
301 	} else {
302 		what = KERN_PROC_ALL;
303 		flag = 0;
304 	}
305 	/*
306 	 * select procs
307 	 */
308 	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0)
309 		errx(1, "%s", kvm_geterr(kd));
310 	if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
311 		err(1, NULL);
312 	for (i = nentries; --i >= 0; ++kp) {
313 		kinfo[i].ki_p = kp;
314 		if (needuser)
315 			saveuser(&kinfo[i]);
316 	}
317 	/*
318 	 * print header
319 	 */
320 	printheader();
321 	if (nentries == 0)
322 		exit(0);
323 	/*
324 	 * sort proc list
325 	 */
326 	qsort(kinfo, nentries, sizeof(KINFO), pscomp);
327 	/*
328 	 * for each proc, call each variable output function.
329 	 */
330 	for (i = lineno = 0; i < nentries; i++) {
331 		if (xflg == 0 && (KI_EPROC(&kinfo[i])->e_tdev == NODEV ||
332 		    (KI_PROC(&kinfo[i])->p_flag & P_CONTROLT ) == 0))
333 			continue;
334 		for (vent = vhead; vent; vent = vent->next) {
335 			(vent->var->oproc)(&kinfo[i], 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 char *
371 fmt(fn, ki, comm, maxlen)
372 	char **(*fn) __P((kvm_t *, const struct kinfo_proc *, int));
373 	KINFO *ki;
374 	char *comm;
375 	int maxlen;
376 {
377 	char *s;
378 
379 	if ((s =
380 	    fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen)) == NULL)
381 		err(1, NULL);
382 	return (s);
383 }
384 
385 static void
386 saveuser(ki)
387 	KINFO *ki;
388 {
389 	struct pstats pstats;
390 	struct usave *usp;
391 
392 	usp = &ki->ki_u;
393 	if (kvm_read(kd, (u_long)&KI_PROC(ki)->p_addr->u_stats,
394 	    (char *)&pstats, sizeof(pstats)) == sizeof(pstats)) {
395 		/*
396 		 * The u-area might be swapped out, and we can't get
397 		 * at it because we have a crashdump and no swap.
398 		 * If it's here fill in these fields, otherwise, just
399 		 * leave them 0.
400 		 */
401 		usp->u_start = pstats.p_start;
402 		usp->u_ru = pstats.p_ru;
403 		usp->u_cru = pstats.p_cru;
404 		usp->u_valid = 1;
405 	} else
406 		usp->u_valid = 0;
407 	/*
408 	 * save arguments if needed
409 	 */
410 	if (needcomm) {
411 		if (commandonly)
412 			ki->ki_args = strdup(KI_PROC(ki)->p_comm);
413 		else
414 			ki->ki_args = fmt(kvm_getargv, ki, KI_PROC(ki)->p_comm,
415 			    MAXCOMLEN);
416 	} else
417 		ki->ki_args = NULL;
418 	if (needenv)
419 		ki->ki_env = fmt(kvm_getenvv, ki, (char *)NULL, 0);
420 	else
421 		ki->ki_env = NULL;
422 }
423 
424 static int
425 pscomp(a, b)
426 	const void *a, *b;
427 {
428 	int i;
429 #ifdef NEWVM
430 #define VSIZE(k) (KI_EPROC(k)->e_vm.vm_dsize + KI_EPROC(k)->e_vm.vm_ssize + \
431 		  KI_EPROC(k)->e_vm.vm_tsize)
432 #else
433 #define VSIZE(k) ((k)->ki_p->p_dsize + (k)->ki_p->p_ssize + (k)->ki_e->e_xsize)
434 #endif
435 
436 	if (sortby == SORTCPU)
437 		return (getpcpu((KINFO *)b) - getpcpu((KINFO *)a));
438 	if (sortby == SORTMEM)
439 		return (VSIZE((KINFO *)b) - VSIZE((KINFO *)a));
440 	i =  KI_EPROC((KINFO *)a)->e_tdev - KI_EPROC((KINFO *)b)->e_tdev;
441 	if (i == 0)
442 		i = KI_PROC((KINFO *)a)->p_pid - KI_PROC((KINFO *)b)->p_pid;
443 	return (i);
444 }
445 
446 /*
447  * ICK (all for getopt), would rather hide the ugliness
448  * here than taint the main code.
449  *
450  *  ps foo -> ps -foo
451  *  ps 34 -> ps -p34
452  *
453  * The old convention that 't' with no trailing tty arg means the users
454  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
455  * feature is available with the option 'T', which takes no argument.
456  */
457 static char *
458 kludge_oldps_options(s)
459 	char *s;
460 {
461 	size_t len;
462 	char *newopts, *ns, *cp;
463 
464 	len = strlen(s);
465 	if ((newopts = ns = malloc(len + 2)) == NULL)
466 		err(1, NULL);
467 	/*
468 	 * options begin with '-'
469 	 */
470 	if (*s != '-')
471 		*ns++ = '-';	/* add option flag */
472 	/*
473 	 * gaze to end of argv[1]
474 	 */
475 	cp = s + len - 1;
476 	/*
477 	 * if last letter is a 't' flag with no argument (in the context
478 	 * of the oldps options -- option string NOT starting with a '-' --
479 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
480 	 */
481 	if (*cp == 't' && *s != '-')
482 		*cp = 'T';
483 	else {
484 		/*
485 		 * otherwise check for trailing number, which *may* be a
486 		 * pid.
487 		 */
488 		while (cp >= s && isdigit(*cp))
489 			--cp;
490 	}
491 	cp++;
492 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
493 	ns += cp - s;
494 	/*
495 	 * if there's a trailing number, and not a preceding 'p' (pid) or
496 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
497 	 */
498 	if (isdigit(*cp) && (cp == s || cp[-1] != 't' && cp[-1] != 'p' &&
499 	    (cp - 1 == s || cp[-2] != 't')))
500 		*ns++ = 'p';
501 	(void)strcpy(ns, cp);		/* and append the number */
502 
503 	return (newopts);
504 }
505 
506 static void
507 usage()
508 {
509 
510 	(void)fprintf(stderr,
511 	    "usage:\t%s\n\t   %s\n\t%s\n",
512 	    "ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty]",
513 	    "[-M core] [-N system] [-W swap]",
514 	    "ps [-L]");
515 	exit(1);
516 }
517