xref: /netbsd/bin/ps/ps.c (revision c4a72b64)
1 /*	$NetBSD: ps.c,v 1.47 2002/06/19 08:11:56 jdolecek Exp $	*/
2 
3 /*
4  * Copyright (c) 2000 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Simon Burge.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *        This product includes software developed by the NetBSD
21  *        Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 /*
40  * Copyright (c) 1990, 1993, 1994
41  *	The Regents of the University of California.  All rights reserved.
42  *
43  * Redistribution and use in source and binary forms, with or without
44  * modification, are permitted provided that the following conditions
45  * are met:
46  * 1. Redistributions of source code must retain the above copyright
47  *    notice, this list of conditions and the following disclaimer.
48  * 2. Redistributions in binary form must reproduce the above copyright
49  *    notice, this list of conditions and the following disclaimer in the
50  *    documentation and/or other materials provided with the distribution.
51  * 3. All advertising materials mentioning features or use of this software
52  *    must display the following acknowledgement:
53  *	This product includes software developed by the University of
54  *	California, Berkeley and its contributors.
55  * 4. Neither the name of the University nor the names of its contributors
56  *    may be used to endorse or promote products derived from this software
57  *    without specific prior written permission.
58  *
59  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69  * SUCH DAMAGE.
70  */
71 
72 #include <sys/cdefs.h>
73 #ifndef lint
74 __COPYRIGHT("@(#) Copyright (c) 1990, 1993, 1994\n\
75 	The Regents of the University of California.  All rights reserved.\n");
76 #endif /* not lint */
77 
78 #ifndef lint
79 #if 0
80 static char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
81 #else
82 __RCSID("$NetBSD: ps.c,v 1.47 2002/06/19 08:11:56 jdolecek Exp $");
83 #endif
84 #endif /* not lint */
85 
86 #include <sys/param.h>
87 #include <sys/user.h>
88 #include <sys/time.h>
89 #include <sys/resource.h>
90 #include <sys/proc.h>
91 #include <sys/stat.h>
92 #include <sys/ioctl.h>
93 #include <sys/sysctl.h>
94 
95 #include <ctype.h>
96 #include <err.h>
97 #include <errno.h>
98 #include <fcntl.h>
99 #include <kvm.h>
100 #include <limits.h>
101 #include <nlist.h>
102 #include <paths.h>
103 #include <pwd.h>
104 #include <stdio.h>
105 #include <stdlib.h>
106 #include <string.h>
107 #include <unistd.h>
108 
109 #include "ps.h"
110 
111 /*
112  * ARGOPTS must contain all option characters that take arguments
113  * (except for 't'!) - it is used in kludge_oldps_options()
114  */
115 #define	GETOPTSTR	"acCeghjKLlM:mN:O:o:p:rSTt:U:uvW:wx"
116 #define	ARGOPTS		"MNOopUW"
117 
118 struct kinfo_proc2 *kinfo;
119 struct varent *vhead, *vtail;
120 
121 int	eval;			/* exit value */
122 int	rawcpu;			/* -C */
123 int	sumrusage;		/* -S */
124 int	termwidth;		/* width of screen (0 == infinity) */
125 int	totwidth;		/* calculated width of requested variables */
126 
127 int	needcomm, needenv, commandonly, use_procfs;
128 uid_t	myuid;
129 
130 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
131 
132 static struct kinfo_proc2
133 		*getkinfo_kvm __P((kvm_t *, int, int, int *));
134 static char	*kludge_oldps_options __P((char *));
135 static int	 pscomp __P((const void *, const void *));
136 static void	 scanvars __P((void));
137 static void	 usage __P((void));
138 int		 main __P((int, char *[]));
139 
140 char dfmt[] = "pid tt state time command";
141 char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
142 char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
143 char   o1[] = "pid";
144 char   o2[] = "tt state time command";
145 char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
146 char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
147 
148 kvm_t *kd;
149 
150 int
151 main(argc, argv)
152 	int argc;
153 	char *argv[];
154 {
155 	struct varent *vent;
156 	struct winsize ws;
157 	int ch, flag, i, fmt, lineno, nentries;
158 	int prtheader, wflag, what, xflg, mode;
159 	char *nlistf, *memf, *swapf, errbuf[_POSIX2_LINE_MAX];
160 	char *ttname;
161 
162 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
163 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
164 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
165 	     ws.ws_col == 0)
166 		termwidth = 79;
167 	else
168 		termwidth = ws.ws_col - 1;
169 
170 	if (argc > 1)
171 		argv[1] = kludge_oldps_options(argv[1]);
172 
173 	fmt = prtheader = wflag = xflg = 0;
174 	what = KERN_PROC_UID;
175 	flag = myuid = getuid();
176 	memf = nlistf = swapf = NULL;
177 	mode = PRINTMODE;
178 	while ((ch = getopt(argc, argv, GETOPTSTR)) != -1)
179 		switch((char)ch) {
180 		case 'a':
181 			what = KERN_PROC_ALL;
182 			flag = 0;
183 			break;
184 		case 'c':
185 			commandonly = 1;
186 			break;
187 		case 'e':			/* XXX set ufmt */
188 			needenv = 1;
189 			break;
190 		case 'C':
191 			rawcpu = 1;
192 			break;
193 		case 'g':
194 			break;			/* no-op */
195 		case 'h':
196 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
197 			break;
198 		case 'j':
199 			parsefmt(jfmt);
200 			fmt = 1;
201 			jfmt[0] = '\0';
202 			break;
203 		case 'K':
204 			break;			/* no-op - was dontuseprocfs */
205 		case 'L':
206 			showkey();
207 			exit(0);
208 			/* NOTREACHED */
209 		case 'l':
210 			parsefmt(lfmt);
211 			fmt = 1;
212 			lfmt[0] = '\0';
213 			break;
214 		case 'M':
215 			memf = optarg;
216 			break;
217 		case 'm':
218 			sortby = SORTMEM;
219 			break;
220 		case 'N':
221 			nlistf = optarg;
222 			break;
223 		case 'O':
224 			parsefmt(o1);
225 			parsefmt(optarg);
226 			parsefmt(o2);
227 			o1[0] = o2[0] = '\0';
228 			fmt = 1;
229 			break;
230 		case 'o':
231 			parsefmt(optarg);
232 			fmt = 1;
233 			break;
234 		case 'p':
235 			what = KERN_PROC_PID;
236 			flag = atol(optarg);
237 			xflg = 1;
238 			break;
239 		case 'r':
240 			sortby = SORTCPU;
241 			break;
242 		case 'S':
243 			sumrusage = 1;
244 			break;
245 		case 'T':
246 			if ((ttname = ttyname(STDIN_FILENO)) == NULL)
247 				errx(1, "stdin: not a terminal");
248 			goto tty;
249 		case 't':
250 			ttname = optarg;
251 		tty: {
252 			struct stat sb;
253 			char *ttypath, pathbuf[MAXPATHLEN];
254 
255 			flag = 0;
256 			if (strcmp(ttname, "?") == 0)
257 				flag = KERN_PROC_TTY_NODEV;
258 			else if (strcmp(ttname, "-") == 0)
259 				flag = KERN_PROC_TTY_REVOKE;
260 			else if (strcmp(ttname, "co") == 0)
261 				ttypath = _PATH_CONSOLE;
262 			else if (*ttname != '/')
263 				(void)snprintf(ttypath = pathbuf,
264 				    sizeof(pathbuf), "%s%s", _PATH_TTY, ttname);
265 			else
266 				ttypath = ttname;
267 			what = KERN_PROC_TTY;
268 			if (flag == 0) {
269 				if (stat(ttypath, &sb) == -1)
270 					err(1, "%s", ttypath);
271 				if (!S_ISCHR(sb.st_mode))
272 					errx(1, "%s: not a terminal", ttypath);
273 				flag = sb.st_rdev;
274 			}
275 			break;
276 		}
277 		case 'U':
278 			if (*optarg != '\0') {
279 				struct passwd *pw;
280 				char *ep;
281 
282 				what = KERN_PROC_UID;
283 				pw = getpwnam(optarg);
284 				if (pw == NULL) {
285 					errno = 0;
286 					flag = strtoul(optarg, &ep, 10);
287 					if (errno)
288 						err(1, "%s", optarg);
289 					if (*ep != '\0')
290 						errx(1, "%s: illegal user name",
291 						    optarg);
292 				} else
293 					flag = pw->pw_uid;
294 			}
295 			break;
296 		case 'u':
297 			parsefmt(ufmt);
298 			sortby = SORTCPU;
299 			fmt = 1;
300 			ufmt[0] = '\0';
301 			break;
302 		case 'v':
303 			parsefmt(vfmt);
304 			sortby = SORTMEM;
305 			fmt = 1;
306 			vfmt[0] = '\0';
307 			break;
308 		case 'W':
309 			swapf = optarg;
310 			break;
311 		case 'w':
312 			if (wflag)
313 				termwidth = UNLIMITED;
314 			else if (termwidth < 131)
315 				termwidth = 131;
316 			wflag++;
317 			break;
318 		case 'x':
319 			xflg = 1;
320 			break;
321 		case '?':
322 		default:
323 			usage();
324 		}
325 	argc -= optind;
326 	argv += optind;
327 
328 #define	BACKWARD_COMPATIBILITY
329 #ifdef	BACKWARD_COMPATIBILITY
330 	if (*argv) {
331 		nlistf = *argv;
332 		if (*++argv) {
333 			memf = *argv;
334 			if (*++argv)
335 				swapf = *argv;
336 		}
337 	}
338 #endif
339 
340 	if (memf == NULL && swapf == NULL) {
341 		kd = kvm_openfiles(nlistf, memf, swapf, KVM_NO_FILES, errbuf);
342 		donlist_sysctl();
343 	} else
344 		kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
345 
346 	if (kd == 0)
347 		errx(1, "%s", errbuf);
348 
349 	if (!fmt)
350 		parsefmt(dfmt);
351 
352 	/*
353 	 * scan requested variables, noting what structures are needed.
354 	 */
355 	scanvars();
356 
357 	/*
358 	 * select procs
359 	 */
360 	if (!kd || !(kinfo = getkinfo_kvm(kd, what, flag, &nentries)))
361 	{
362 		if (kd)
363 			warnx("%s.", kvm_geterr(kd));
364 		exit(1);
365 	}
366 	if (nentries == 0) {
367 		printheader();
368 		exit(1);
369 	}
370 	/*
371 	 * sort proc list
372 	 */
373 	qsort(kinfo, nentries, sizeof(struct kinfo_proc2), pscomp);
374 	/*
375 	 * For each proc, call each variable output function in
376 	 * "setwidth" mode to determine the widest element of
377 	 * the column.
378 	 */
379 	if (mode == PRINTMODE)
380 		for (i = 0; i < nentries; i++) {
381 			struct kinfo_proc2 *ki = &kinfo[i];
382 
383 			if (xflg == 0 && (ki->p_tdev == NODEV ||
384 			    (ki->p_flag & P_CONTROLT) == 0))
385 				continue;
386 			for (vent = vhead; vent; vent = vent->next)
387 				(vent->var->oproc)(ki, vent, WIDTHMODE);
388 		}
389 	/*
390 	 * Print header - AFTER determining process field widths.
391 	 * printheader() also adds up the total width of all
392 	 * fields the first time it's called.
393 	 */
394 	printheader();
395 	/*
396 	 * For each proc, call each variable output function in
397 	 * print mode.
398 	 */
399 	for (i = lineno = 0; i < nentries; i++) {
400 		struct kinfo_proc2 *ki = &kinfo[i];
401 
402 		if (xflg == 0 && (ki->p_tdev == NODEV ||
403 		    (ki->p_flag & P_CONTROLT ) == 0))
404 			continue;
405 		for (vent = vhead; vent; vent = vent->next) {
406 			(vent->var->oproc)(ki, vent, mode);
407 			if (vent->next != NULL)
408 				(void)putchar(' ');
409 		}
410 		(void)putchar('\n');
411 		if (prtheader && lineno++ == prtheader - 4) {
412 			(void)putchar('\n');
413 			printheader();
414 			lineno = 0;
415 		}
416 	}
417 	exit(eval);
418 	/* NOTREACHED */
419 }
420 
421 static struct kinfo_proc2 *
422 getkinfo_kvm(kdp, what, flag, nentriesp)
423 	kvm_t *kdp;
424 	int what, flag, *nentriesp;
425 {
426 	return (kvm_getproc2(kdp, what, flag, sizeof(struct kinfo_proc2),
427 	    nentriesp));
428 }
429 
430 static void
431 scanvars()
432 {
433 	struct varent *vent;
434 	VAR *v;
435 
436 	for (vent = vhead; vent; vent = vent->next) {
437 		v = vent->var;
438 		if (v->flag & COMM) {
439 			needcomm = 1;
440 			break;
441 		}
442 	}
443 }
444 
445 static int
446 pscomp(a, b)
447 	const void *a, *b;
448 {
449 	struct kinfo_proc2 *ka = (struct kinfo_proc2 *)a;
450 	struct kinfo_proc2 *kb = (struct kinfo_proc2 *)b;
451 
452 	int i;
453 #define VSIZE(k) (k->p_vm_dsize + k->p_vm_ssize + k->p_vm_tsize)
454 
455 	if (sortby == SORTCPU)
456 		return (getpcpu(kb) - getpcpu(ka));
457 	if (sortby == SORTMEM)
458 		return (VSIZE(kb) - VSIZE(ka));
459 	i =  ka->p_tdev - kb->p_tdev;
460 
461 	if (i == 0)
462 		i = ka->p_pid - kb->p_pid;
463 	return (i);
464 }
465 
466 /*
467  * ICK (all for getopt), would rather hide the ugliness
468  * here than taint the main code.
469  *
470  *  ps foo -> ps -foo
471  *  ps 34 -> ps -p34
472  *
473  * The old convention that 't' with no trailing tty arg means the user's
474  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
475  * feature is available with the option 'T', which takes no argument.
476  */
477 static char *
478 kludge_oldps_options(s)
479 	char *s;
480 {
481 	size_t len;
482 	char *newopts, *ns, *cp;
483 
484 	len = strlen(s);
485 	if ((newopts = ns = malloc(len + 3)) == NULL)
486 		err(1, NULL);
487 	/*
488 	 * options begin with '-'
489 	 */
490 	if (*s != '-')
491 		*ns++ = '-';	/* add option flag */
492 	/*
493 	 * gaze to end of argv[1]
494 	 */
495 	cp = s + len - 1;
496 	/*
497 	 * if the last letter is a 't' flag and there are no other option
498 	 * characters that take arguments (eg U, p, o) in the option
499 	 * string and the option string doesn't start with a '-' then
500 	 * convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
501 	 */
502 	if (*cp == 't' && *s != '-' && strpbrk(s, ARGOPTS) == NULL)
503 		*cp = 'T';
504 	else {
505 		/*
506 		 * otherwise check for trailing number, which *may* be a
507 		 * pid.
508 		 */
509 		while (cp >= s && isdigit(*cp))
510 			--cp;
511 	}
512 	cp++;
513 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
514 	ns += cp - s;
515 	/*
516 	 * if there's a trailing number, and not a preceding 'p' (pid) or
517 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
518 	 */
519 	if (isdigit(*cp) &&
520 	    (cp == s || (cp[-1] != 'U' && cp[-1] != 't' && cp[-1] != 'p' &&
521 	     (cp - 1 == s || cp[-2] != 't'))))
522 		*ns++ = 'p';
523 	/* and append the number */
524 	(void)strcpy(ns, cp);		/* XXX strcpy is safe here */
525 
526 	return (newopts);
527 }
528 
529 static void
530 usage()
531 {
532 
533 	(void)fprintf(stderr,
534 	    "usage:\t%s\n\t   %s\n\t%s\n",
535 	    "ps [-acCehjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty]",
536 	    "[-M core] [-N system] [-W swap] [-U username]",
537 	    "ps [-L]");
538 	exit(1);
539 	/* NOTREACHED */
540 }
541