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