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