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