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