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