xref: /freebsd/bin/ps/ps.c (revision 7f3dea244c40159a41ab22da77a434d7c5b5e85a)
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 
34 #ifndef lint
35 static char const copyright[] =
36 "@(#) Copyright (c) 1990, 1993, 1994\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
43 #endif
44 static const char rcsid[] =
45   "$FreeBSD$";
46 #endif /* not lint */
47 
48 #include <sys/param.h>
49 #include <sys/user.h>
50 #include <sys/time.h>
51 #include <sys/resource.h>
52 #include <sys/stat.h>
53 #include <sys/ioctl.h>
54 #include <sys/sysctl.h>
55 
56 #include <ctype.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <kvm.h>
61 #include <limits.h>
62 #include <nlist.h>
63 #include <paths.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <unistd.h>
68 #include <locale.h>
69 #include <pwd.h>
70 
71 #include "ps.h"
72 
73 KINFO *kinfo;
74 struct varent *vhead, *vtail;
75 
76 int	eval;			/* exit value */
77 int	cflag;			/* -c */
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 #if defined(LAZY_PS)
85 static int forceuread=0;
86 #else
87 static int forceuread=1;
88 #endif
89 
90 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
91 
92 static char	*fmt __P((char **(*)(kvm_t *, const struct kinfo_proc *, int),
93 		    KINFO *, char *, int));
94 static char	*kludge_oldps_options __P((char *));
95 static int	 pscomp __P((const void *, const void *));
96 static void	 saveuser __P((KINFO *));
97 static void	 scanvars __P((void));
98 static void	 dynsizevars __P((KINFO *));
99 static void	 sizevars __P((void));
100 static void	 usage __P((void));
101 #ifdef __alpha__
102 static int	 get_uarea __P((struct proc *, struct pstats *));
103 #endif
104 
105 char dfmt[] = "pid tt state time command";
106 char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
107 char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
108 char   o1[] = "pid";
109 char   o2[] = "tt state time command";
110 char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
111 char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
112 
113 kvm_t *kd;
114 
115 int
116 main(argc, argv)
117 	int argc;
118 	char *argv[];
119 {
120 	struct kinfo_proc *kp;
121 	struct varent *vent;
122 	struct winsize ws;
123 	struct passwd *pwd;
124 	dev_t ttydev;
125 	pid_t pid;
126 	uid_t uid;
127 	int all, ch, flag, i, fmt, lineno, nentries, dropgid;
128 	int prtheader, wflag, what, xflg;
129 	char *nlistf, *memf, *swapf, errbuf[_POSIX2_LINE_MAX];
130 
131 	(void) setlocale(LC_ALL, "");
132 
133 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
134 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
135 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
136 	     ws.ws_col == 0)
137 		termwidth = 79;
138 	else
139 		termwidth = ws.ws_col - 1;
140 
141 	if (argc > 1)
142 		argv[1] = kludge_oldps_options(argv[1]);
143 
144 	all = fmt = prtheader = wflag = xflg = 0;
145 	pid = -1;
146 	uid = (uid_t) -1;
147 	ttydev = NODEV;
148 	dropgid = 0;
149 	memf = nlistf = swapf = _PATH_DEVNULL;
150 	while ((ch = getopt(argc, argv,
151 #if defined(LAZY_PS)
152 	    "aCcefghjLlM:mN:O:o:p:rSTt:U:uvW:wx")) != -1)
153 #else
154 	    "aCceghjLlM:mN:O:o:p:rSTt:U:uvW:wx")) != -1)
155 #endif
156 		switch((char)ch) {
157 		case 'a':
158 			all = 1;
159 			break;
160 		case 'C':
161 			rawcpu = 1;
162 			break;
163 		case 'c':
164 			cflag = 1;
165 			break;
166 		case 'e':			/* XXX set ufmt */
167 			needenv = 1;
168 			break;
169 		case 'g':
170 			break;			/* no-op */
171 		case 'h':
172 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
173 			break;
174 		case 'j':
175 			parsefmt(jfmt);
176 			fmt = 1;
177 			jfmt[0] = '\0';
178 			break;
179 		case 'L':
180 			showkey();
181 			exit(0);
182 		case 'l':
183 			parsefmt(lfmt);
184 			fmt = 1;
185 			lfmt[0] = '\0';
186 			break;
187 		case 'M':
188 			memf = optarg;
189 			dropgid = 1;
190 			break;
191 		case 'm':
192 			sortby = SORTMEM;
193 			break;
194 		case 'N':
195 			nlistf = optarg;
196 			dropgid = 1;
197 			break;
198 		case 'O':
199 			parsefmt(o1);
200 			parsefmt(optarg);
201 			parsefmt(o2);
202 			o1[0] = o2[0] = '\0';
203 			fmt = 1;
204 			break;
205 		case 'o':
206 			parsefmt(optarg);
207 			fmt = 1;
208 			break;
209 #if defined(LAZY_PS)
210 		case 'f':
211 			if (getuid() == 0 || getgid() == 0)
212 			    forceuread = 1;
213 			break;
214 #endif
215 		case 'p':
216 			pid = atol(optarg);
217 			xflg = 1;
218 			break;
219 		case 'r':
220 			sortby = SORTCPU;
221 			break;
222 		case 'S':
223 			sumrusage = 1;
224 			break;
225 		case 'T':
226 			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
227 				errx(1, "stdin: not a terminal");
228 			/* FALLTHROUGH */
229 		case 't': {
230 			struct stat sb;
231 			char *ttypath, pathbuf[MAXPATHLEN];
232 
233 			if (strcmp(optarg, "co") == 0)
234 				ttypath = _PATH_CONSOLE;
235 			else if (*optarg != '/')
236 				(void)snprintf(ttypath = pathbuf,
237 				    sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
238 			else
239 				ttypath = optarg;
240 			if (stat(ttypath, &sb) == -1)
241 				err(1, "%s", ttypath);
242 			if (!S_ISCHR(sb.st_mode))
243 				errx(1, "%s: not a terminal", ttypath);
244 			ttydev = sb.st_rdev;
245 			break;
246 		}
247 		case 'U':
248 			pwd = getpwnam(optarg);
249 			if (pwd == NULL)
250 				errx(1, "%s: no such user", optarg);
251 			uid = pwd->pw_uid;
252 			endpwent();
253 			xflg++;		/* XXX: intuitive? */
254 			break;
255 		case 'u':
256 			parsefmt(ufmt);
257 			sortby = SORTCPU;
258 			fmt = 1;
259 			ufmt[0] = '\0';
260 			break;
261 		case 'v':
262 			parsefmt(vfmt);
263 			sortby = SORTMEM;
264 			fmt = 1;
265 			vfmt[0] = '\0';
266 			break;
267 		case 'W':
268 			swapf = optarg;
269 			dropgid = 1;
270 			break;
271 		case 'w':
272 			if (wflag)
273 				termwidth = UNLIMITED;
274 			else if (termwidth < 131)
275 				termwidth = 131;
276 			wflag++;
277 			break;
278 		case 'x':
279 			xflg = 1;
280 			break;
281 		case '?':
282 		default:
283 			usage();
284 		}
285 	argc -= optind;
286 	argv += optind;
287 
288 #define	BACKWARD_COMPATIBILITY
289 #ifdef	BACKWARD_COMPATIBILITY
290 	if (*argv) {
291 		nlistf = *argv;
292 		if (*++argv) {
293 			memf = *argv;
294 			if (*++argv)
295 				swapf = *argv;
296 		}
297 	}
298 #endif
299 	/*
300 	 * Discard setgid privileges if not the running kernel so that bad
301 	 * guys can't print interesting stuff from kernel memory.
302 	 */
303 	if (dropgid) {
304 		setgid(getgid());
305 		setuid(getuid());
306 	}
307 
308 	kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
309 	if (kd == 0)
310 		errx(1, "%s", errbuf);
311 
312 	if (!fmt)
313 		parsefmt(dfmt);
314 
315 	/* XXX - should be cleaner */
316 	if (!all && ttydev == NODEV && pid == -1 && uid == (uid_t)-1)
317 		uid = getuid();
318 
319 	/*
320 	 * scan requested variables, noting what structures are needed,
321 	 * and adjusting header widths as appropiate.
322 	 */
323 	scanvars();
324 	/*
325 	 * get proc list
326 	 */
327 	if (uid != (uid_t) -1) {
328 		what = KERN_PROC_UID;
329 		flag = uid;
330 	} else if (ttydev != NODEV) {
331 		what = KERN_PROC_TTY;
332 		flag = ttydev;
333 	} else if (pid != -1) {
334 		what = KERN_PROC_PID;
335 		flag = pid;
336 	} else {
337 		what = KERN_PROC_ALL;
338 		flag = 0;
339 	}
340 	/*
341 	 * select procs
342 	 */
343 	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0)
344 		errx(1, "%s", kvm_geterr(kd));
345 	if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
346 		err(1, NULL);
347 	for (i = nentries; --i >= 0; ++kp) {
348 		kinfo[i].ki_p = kp;
349 		if (needuser)
350 			saveuser(&kinfo[i]);
351 		dynsizevars(&kinfo[i]);
352 	}
353 
354 	sizevars();
355 
356 	/*
357 	 * print header
358 	 */
359 	printheader();
360 	if (nentries == 0)
361 		exit(0);
362 	/*
363 	 * sort proc list
364 	 */
365 	qsort(kinfo, nentries, sizeof(KINFO), pscomp);
366 	/*
367 	 * for each proc, call each variable output function.
368 	 */
369 	for (i = lineno = 0; i < nentries; i++) {
370 		if (xflg == 0 && (KI_EPROC(&kinfo[i])->e_tdev == NODEV ||
371 		    (KI_PROC(&kinfo[i])->p_flag & P_CONTROLT ) == 0))
372 			continue;
373 		for (vent = vhead; vent; vent = vent->next) {
374 			(vent->var->oproc)(&kinfo[i], vent);
375 			if (vent->next != NULL)
376 				(void)putchar(' ');
377 		}
378 		(void)putchar('\n');
379 		if (prtheader && lineno++ == prtheader - 4) {
380 			(void)putchar('\n');
381 			printheader();
382 			lineno = 0;
383 		}
384 	}
385 	exit(eval);
386 }
387 
388 static void
389 scanvars()
390 {
391 	struct varent *vent;
392 	VAR *v;
393 
394 	for (vent = vhead; vent; vent = vent->next) {
395 		v = vent->var;
396 		if (v->flag & DSIZ) {
397 			v->dwidth = v->width;
398 			v->width = 0;
399 		}
400 		if (v->flag & USER)
401 			needuser = 1;
402 		if (v->flag & COMM)
403 			needcomm = 1;
404 	}
405 }
406 
407 static void
408 dynsizevars(ki)
409 	KINFO *ki;
410 {
411 	struct varent *vent;
412 	VAR *v;
413 	int i;
414 
415 	for (vent = vhead; vent; vent = vent->next) {
416 		v = vent->var;
417 		if (!(v->flag & DSIZ))
418 			continue;
419 		i = (v->sproc)( ki);
420 		if (v->width < i)
421 			v->width = i;
422 		if (v->width > v->dwidth)
423 			v->width = v->dwidth;
424 	}
425 }
426 
427 static void
428 sizevars()
429 {
430 	struct varent *vent;
431 	VAR *v;
432 	int i;
433 
434 	for (vent = vhead; vent; vent = vent->next) {
435 		v = vent->var;
436 		i = strlen(v->header);
437 		if (v->width < i)
438 			v->width = i;
439 		totwidth += v->width + 1;	/* +1 for space */
440 	}
441 	totwidth--;
442 }
443 
444 static char *
445 fmt(fn, ki, comm, maxlen)
446 	char **(*fn) __P((kvm_t *, const struct kinfo_proc *, int));
447 	KINFO *ki;
448 	char *comm;
449 	int maxlen;
450 {
451 	char *s;
452 
453 	if ((s =
454 	    fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen)) == NULL)
455 		err(1, NULL);
456 	return (s);
457 }
458 
459 #ifdef __alpha__
460 /*
461  * This is a kludge to work around the fact that on the alpha,
462  * the uarea is not mapped into the process address space.
463  */
464 static int get_uarea(p, pstats)
465 	struct proc		*p;
466 	struct pstats		*pstats;
467 {
468 	size_t			offset;
469 	static struct user	ubuf;
470 	kvm_t			*mkd;
471 	int			len;
472 
473 	offset = (size_t)p->p_addr;
474 	mkd = kvm_open(NULL, NULL, NULL, 0, NULL);
475 	if (mkd == NULL)
476 		return(0);
477 	len = kvm_read(mkd, offset, (char *)&ubuf, sizeof(struct user));
478 	kvm_close(mkd);
479 	if (len != sizeof(struct user))
480 		return(0);
481 
482 	bcopy((char *)&ubuf.u_stats, (char *)pstats, sizeof(struct pstats));
483 
484 	return(sizeof(struct pstats));
485 }
486 #endif
487 
488 #define UREADOK(ki)	(forceuread || (KI_PROC(ki)->p_flag & P_INMEM))
489 
490 static void
491 saveuser(ki)
492 	KINFO *ki;
493 {
494 	struct pstats pstats;
495 	struct usave *usp;
496 #ifndef __alpha__
497 	struct user *u_addr = (struct user *)USRSTACK;
498 #endif
499 
500 	usp = &ki->ki_u;
501 
502 #ifdef __alpha__
503 	if (UREADOK(ki) && get_uarea(KI_PROC(ki), &pstats) == sizeof(pstats)) {
504 #else
505 	if (UREADOK(ki) && kvm_uread(kd, KI_PROC(ki), (unsigned long)&u_addr->u_stats,
506 	    (char *)&pstats, sizeof(pstats)) == sizeof(pstats)) {
507 #endif
508 		/*
509 		 * The u-area might be swapped out, and we can't get
510 		 * at it because we have a crashdump and no swap.
511 		 * If it's here fill in these fields, otherwise, just
512 		 * leave them 0.
513 		 */
514 		usp->u_start = pstats.p_start;
515 		usp->u_ru = pstats.p_ru;
516 		usp->u_cru = pstats.p_cru;
517 		usp->u_valid = 1;
518 	} else
519 		usp->u_valid = 0;
520 	/*
521 	 * save arguments if needed
522 	 */
523 	if (needcomm && UREADOK(ki)) {
524 	    ki->ki_args = fmt(kvm_getargv, ki, KI_PROC(ki)->p_comm,
525 		MAXCOMLEN);
526 	} else if (needcomm) {
527 	    ki->ki_args = malloc(strlen(KI_PROC(ki)->p_comm) + 3);
528 	    sprintf(ki->ki_args, "(%s)", KI_PROC(ki)->p_comm);
529     } else {
530 	    ki->ki_args = NULL;
531     }
532     if (needenv && UREADOK(ki)) {
533 	    ki->ki_env = fmt(kvm_getenvv, ki, (char *)NULL, 0);
534     } else if (needenv) {
535 	    ki->ki_env = malloc(3);
536 	    strcpy(ki->ki_env, "()");
537     } else {
538 	    ki->ki_env = NULL;
539     }
540 }
541 
542 static int
543 pscomp(a, b)
544 	const void *a, *b;
545 {
546 	int i;
547 #define VSIZE(k) (KI_EPROC(k)->e_vm.vm_dsize + KI_EPROC(k)->e_vm.vm_ssize + \
548 		  KI_EPROC(k)->e_vm.vm_tsize)
549 
550 	if (sortby == SORTCPU)
551 		return (getpcpu((KINFO *)b) - getpcpu((KINFO *)a));
552 	if (sortby == SORTMEM)
553 		return (VSIZE((KINFO *)b) - VSIZE((KINFO *)a));
554 	i =  KI_EPROC((KINFO *)a)->e_tdev - KI_EPROC((KINFO *)b)->e_tdev;
555 	if (i == 0)
556 		i = KI_PROC((KINFO *)a)->p_pid - KI_PROC((KINFO *)b)->p_pid;
557 	return (i);
558 }
559 
560 /*
561  * ICK (all for getopt), would rather hide the ugliness
562  * here than taint the main code.
563  *
564  *  ps foo -> ps -foo
565  *  ps 34 -> ps -p34
566  *
567  * The old convention that 't' with no trailing tty arg means the users
568  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
569  * feature is available with the option 'T', which takes no argument.
570  */
571 static char *
572 kludge_oldps_options(s)
573 	char *s;
574 {
575 	size_t len;
576 	char *newopts, *ns, *cp;
577 
578 	len = strlen(s);
579 	if ((newopts = ns = malloc(len + 2)) == NULL)
580 		err(1, NULL);
581 	/*
582 	 * options begin with '-'
583 	 */
584 	if (*s != '-')
585 		*ns++ = '-';	/* add option flag */
586 	/*
587 	 * gaze to end of argv[1]
588 	 */
589 	cp = s + len - 1;
590 	/*
591 	 * if last letter is a 't' flag with no argument (in the context
592 	 * of the oldps options -- option string NOT starting with a '-' --
593 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
594 	 */
595 	if (*cp == 't' && *s != '-')
596 		*cp = 'T';
597 	else {
598 		/*
599 		 * otherwise check for trailing number, which *may* be a
600 		 * pid.
601 		 */
602 		while (cp >= s && isdigit(*cp))
603 			--cp;
604 	}
605 	cp++;
606 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
607 	ns += cp - s;
608 	/*
609 	 * if there's a trailing number, and not a preceding 'p' (pid) or
610 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
611 	 */
612 	if (isdigit(*cp) &&
613 	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
614 	    (cp - 1 == s || cp[-2] != 't'))
615 		*ns++ = 'p';
616 	(void)strcpy(ns, cp);		/* and append the number */
617 
618 	return (newopts);
619 }
620 
621 static void
622 usage()
623 {
624 
625 	(void)fprintf(stderr, "%s\n%s\n%s\n",
626 	    "usage: ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty] [-U user]",
627 	    "          [-M core] [-N system] [-W swap]",
628 	    "       ps [-L]");
629 	exit(1);
630 }
631