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