xref: /freebsd/bin/ps/ps.c (revision d82e286489da73321a47e329d98a98817b0438b6)
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.8 1995/10/23 21:06:31 ache Exp $
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 static char 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/proc.h>
51 #include <sys/stat.h>
52 #include <sys/ioctl.h>
53 #include <sys/sysctl.h>
54 
55 #include <ctype.h>
56 #include <err.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <kvm.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 
68 #include "ps.h"
69 
70 #ifdef P_PPWAIT
71 #define NEWVM
72 #endif
73 
74 KINFO *kinfo;
75 struct varent *vhead, *vtail;
76 
77 int	eval;			/* exit value */
78 int	rawcpu;			/* -C */
79 int	sumrusage;		/* -S */
80 int	termwidth;		/* width of screen (0 == infinity) */
81 int	totwidth;		/* calculated width of requested variables */
82 
83 static int needuser, needcomm, needenv;
84 
85 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
86 
87 static char	*fmt __P((char **(*)(kvm_t *, const struct kinfo_proc *, int),
88 		    KINFO *, char *, int));
89 static char	*kludge_oldps_options __P((char *));
90 static int	 pscomp __P((const void *, const void *));
91 static void	 saveuser __P((KINFO *));
92 static void	 scanvars __P((void));
93 static void	 usage __P((void));
94 
95 char dfmt[] = "pid tt state time command";
96 char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
97 char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
98 char   o1[] = "pid";
99 char   o2[] = "tt state time command";
100 char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
101 char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
102 
103 kvm_t *kd;
104 
105 int
106 main(argc, argv)
107 	int argc;
108 	char *argv[];
109 {
110 	struct kinfo_proc *kp;
111 	struct varent *vent;
112 	struct winsize ws;
113 	dev_t ttydev;
114 	pid_t pid;
115 	uid_t uid;
116 	int all, ch, flag, i, fmt, lineno, nentries;
117 	int prtheader, wflag, what, xflg;
118 	char *nlistf, *memf, *swapf, errbuf[256];
119 
120 	(void) setlocale(LC_ALL, "");
121 
122 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
123 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
124 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
125 	     ws.ws_col == 0)
126 		termwidth = 79;
127 	else
128 		termwidth = ws.ws_col - 1;
129 
130 	if (argc > 1)
131 		argv[1] = kludge_oldps_options(argv[1]);
132 
133 	all = fmt = prtheader = wflag = xflg = 0;
134 	pid = -1;
135 	uid = (uid_t) -1;
136 	ttydev = NODEV;
137 	memf = nlistf = swapf = NULL;
138 	while ((ch = getopt(argc, argv,
139 	    "aCeghjLlM:mN:O:o:p:rSTt:uvW:wx")) != EOF)
140 		switch((char)ch) {
141 		case 'a':
142 			all = 1;
143 			break;
144 		case 'e':			/* XXX set ufmt */
145 			needenv = 1;
146 			break;
147 		case 'C':
148 			rawcpu = 1;
149 			break;
150 		case 'g':
151 			break;			/* no-op */
152 		case 'h':
153 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
154 			break;
155 		case 'j':
156 			parsefmt(jfmt);
157 			fmt = 1;
158 			jfmt[0] = '\0';
159 			break;
160 		case 'L':
161 			showkey();
162 			exit(0);
163 		case 'l':
164 			parsefmt(lfmt);
165 			fmt = 1;
166 			lfmt[0] = '\0';
167 			break;
168 		case 'M':
169 			memf = optarg;
170 			break;
171 		case 'm':
172 			sortby = SORTMEM;
173 			break;
174 		case 'N':
175 			nlistf = optarg;
176 			break;
177 		case 'O':
178 			parsefmt(o1);
179 			parsefmt(optarg);
180 			parsefmt(o2);
181 			o1[0] = o2[0] = '\0';
182 			fmt = 1;
183 			break;
184 		case 'o':
185 			parsefmt(optarg);
186 			fmt = 1;
187 			break;
188 		case 'p':
189 			pid = atol(optarg);
190 			xflg = 1;
191 			break;
192 		case 'r':
193 			sortby = SORTCPU;
194 			break;
195 		case 'S':
196 			sumrusage = 1;
197 			break;
198 		case 'T':
199 			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
200 				errx(1, "stdin: not a terminal");
201 			/* FALLTHROUGH */
202 		case 't': {
203 			struct stat sb;
204 			char *ttypath, pathbuf[MAXPATHLEN];
205 
206 			if (strcmp(optarg, "co") == 0)
207 				ttypath = _PATH_CONSOLE;
208 			else if (*optarg != '/')
209 				(void)snprintf(ttypath = pathbuf,
210 				    sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
211 			else
212 				ttypath = optarg;
213 			if (stat(ttypath, &sb) == -1)
214 				err(1, "%s", ttypath);
215 			if (!S_ISCHR(sb.st_mode))
216 				errx(1, "%s: not a terminal", ttypath);
217 			ttydev = sb.st_rdev;
218 			break;
219 		}
220 		case 'u':
221 			parsefmt(ufmt);
222 			sortby = SORTCPU;
223 			fmt = 1;
224 			ufmt[0] = '\0';
225 			break;
226 		case 'v':
227 			parsefmt(vfmt);
228 			sortby = SORTMEM;
229 			fmt = 1;
230 			vfmt[0] = '\0';
231 			break;
232 		case 'W':
233 			swapf = optarg;
234 			break;
235 		case 'w':
236 			if (wflag)
237 				termwidth = UNLIMITED;
238 			else if (termwidth < 131)
239 				termwidth = 131;
240 			wflag++;
241 			break;
242 		case 'x':
243 			xflg = 1;
244 			break;
245 		case '?':
246 		default:
247 			usage();
248 		}
249 	argc -= optind;
250 	argv += optind;
251 
252 #define	BACKWARD_COMPATIBILITY
253 #ifdef	BACKWARD_COMPATIBILITY
254 	if (*argv) {
255 		nlistf = *argv;
256 		if (*++argv) {
257 			memf = *argv;
258 			if (*++argv)
259 				swapf = *argv;
260 		}
261 	}
262 #endif
263 	/*
264 	 * Discard setgid privileges if not the running kernel so that bad
265 	 * guys can't print interesting stuff from kernel memory.
266 	 */
267 	if (nlistf != NULL || memf != NULL || swapf != NULL)
268 		setgid(getgid());
269 
270 	kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
271 	if (kd == 0)
272 		errx(1, "%s", errbuf);
273 
274 	if (!fmt)
275 		parsefmt(dfmt);
276 
277 	if (!all && ttydev == NODEV && pid == -1)  /* XXX - should be cleaner */
278 		uid = getuid();
279 
280 	/*
281 	 * scan requested variables, noting what structures are needed,
282 	 * and adjusting header widths as appropiate.
283 	 */
284 	scanvars();
285 	/*
286 	 * get proc list
287 	 */
288 	if (uid != (uid_t) -1) {
289 		what = KERN_PROC_UID;
290 		flag = uid;
291 	} else if (ttydev != NODEV) {
292 		what = KERN_PROC_TTY;
293 		flag = ttydev;
294 	} else if (pid != -1) {
295 		what = KERN_PROC_PID;
296 		flag = pid;
297 	} else {
298 		what = KERN_PROC_ALL;
299 		flag = 0;
300 	}
301 	/*
302 	 * select procs
303 	 */
304 	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0)
305 		errx(1, "%s", kvm_geterr(kd));
306 	if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
307 		err(1, NULL);
308 	for (i = nentries; --i >= 0; ++kp) {
309 		kinfo[i].ki_p = kp;
310 		if (needuser)
311 			saveuser(&kinfo[i]);
312 	}
313 	/*
314 	 * print header
315 	 */
316 	printheader();
317 	if (nentries == 0)
318 		exit(0);
319 	/*
320 	 * sort proc list
321 	 */
322 	qsort(kinfo, nentries, sizeof(KINFO), pscomp);
323 	/*
324 	 * for each proc, call each variable output function.
325 	 */
326 	for (i = lineno = 0; i < nentries; i++) {
327 		if (xflg == 0 && (KI_EPROC(&kinfo[i])->e_tdev == NODEV ||
328 		    (KI_PROC(&kinfo[i])->p_flag & P_CONTROLT ) == 0))
329 			continue;
330 		for (vent = vhead; vent; vent = vent->next) {
331 			(vent->var->oproc)(&kinfo[i], vent);
332 			if (vent->next != NULL)
333 				(void)putchar(' ');
334 		}
335 		(void)putchar('\n');
336 		if (prtheader && lineno++ == prtheader - 4) {
337 			(void)putchar('\n');
338 			printheader();
339 			lineno = 0;
340 		}
341 	}
342 	exit(eval);
343 }
344 
345 static void
346 scanvars()
347 {
348 	struct varent *vent;
349 	VAR *v;
350 	int i;
351 
352 	for (vent = vhead; vent; vent = vent->next) {
353 		v = vent->var;
354 		i = strlen(v->header);
355 		if (v->width < i)
356 			v->width = i;
357 		totwidth += v->width + 1;	/* +1 for space */
358 		if (v->flag & USER)
359 			needuser = 1;
360 		if (v->flag & COMM)
361 			needcomm = 1;
362 	}
363 	totwidth--;
364 }
365 
366 static char *
367 fmt(fn, ki, comm, maxlen)
368 	char **(*fn) __P((kvm_t *, const struct kinfo_proc *, int));
369 	KINFO *ki;
370 	char *comm;
371 	int maxlen;
372 {
373 	char *s;
374 
375 	if ((s =
376 	    fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen)) == NULL)
377 		err(1, NULL);
378 	return (s);
379 }
380 
381 static void
382 saveuser(ki)
383 	KINFO *ki;
384 {
385 	struct pstats pstats;
386 	struct usave *usp;
387 	struct user *u_addr = (struct user *)USRSTACK;
388 
389 	usp = &ki->ki_u;
390 	if (kvm_uread(kd, KI_PROC(ki), (unsigned long)&u_addr->u_stats,
391 	    (char *)&pstats, sizeof(pstats)) == sizeof(pstats)) {
392 		/*
393 		 * The u-area might be swapped out, and we can't get
394 		 * at it because we have a crashdump and no swap.
395 		 * If it's here fill in these fields, otherwise, just
396 		 * leave them 0.
397 		 */
398 		usp->u_start = pstats.p_start;
399 		usp->u_ru = pstats.p_ru;
400 		usp->u_cru = pstats.p_cru;
401 		usp->u_valid = 1;
402 	} else
403 		usp->u_valid = 0;
404 	/*
405 	 * save arguments if needed
406 	 */
407 	if (needcomm)
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) &&
493 	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
494 	    (cp - 1 == s || cp[-2] != 't'))
495 		*ns++ = 'p';
496 	(void)strcpy(ns, cp);		/* and append the number */
497 
498 	return (newopts);
499 }
500 
501 static void
502 usage()
503 {
504 
505 	(void)fprintf(stderr,
506 	    "usage:\t%s\n\t   %s\n\t%s\n",
507 	    "ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty]",
508 	    "[-M core] [-N system] [-W swap]",
509 	    "ps [-L]");
510 	exit(1);
511 }
512