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