ps.c revision 97804
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#include <sys/cdefs.h>
35__FBSDID("$FreeBSD: head/bin/ps/ps.c 97804 2002-06-04 10:20:10Z tjr $");
36
37#ifndef lint
38static const char copyright[] =
39"@(#) Copyright (c) 1990, 1993, 1994\n\
40	The Regents of the University of California.  All rights reserved.\n";
41#endif /* not lint */
42
43#if 0
44#ifndef lint
45static char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
46#endif /* not lint */
47#endif
48
49#include <sys/param.h>
50#include <sys/user.h>
51#include <sys/stat.h>
52#include <sys/ioctl.h>
53#include <sys/sysctl.h>
54
55#include <ctype.h>
56#include <err.h>
57#include <fcntl.h>
58#include <kvm.h>
59#include <limits.h>
60#include <locale.h>
61#include <paths.h>
62#include <pwd.h>
63#include <stdio.h>
64#include <stdlib.h>
65#include <string.h>
66#include <unistd.h>
67#include <utmp.h>
68
69#include "lomac.h"
70#include "ps.h"
71
72#define SEP ", \t"		/* username separators */
73
74static KINFO *kinfo;
75struct varent *vhead;
76
77int	eval;			/* exit value */
78int	cflag;			/* -c */
79int	rawcpu;			/* -C */
80int	sumrusage;		/* -S */
81int	termwidth;		/* width of screen (0 == infinity) */
82int	totwidth;		/* calculated width of requested variables */
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
115int
116main(int argc, char *argv[])
117{
118	struct kinfo_proc *kp;
119	struct varent *vent;
120	struct winsize ws;
121	dev_t ttydev;
122	pid_t pid;
123	uid_t *uids;
124	int all, ch, flag, i, _fmt, lineno, nentries, dropgid;
125	int prtheader, wflag, what, xflg, uid, nuids;
126	char *cols;
127	char errbuf[_POSIX2_LINE_MAX];
128	const char *nlistf, *memf;
129
130	(void) setlocale(LC_ALL, "");
131
132	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
133		termwidth = atoi(cols);
134	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
135	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
136	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
137	     ws.ws_col == 0)
138		termwidth = 79;
139	else
140		termwidth = ws.ws_col - 1;
141
142	if (argc > 1)
143		argv[1] = kludge_oldps_options(argv[1]);
144
145	all = _fmt = prtheader = wflag = xflg = 0;
146	pid = -1;
147	nuids = 0;
148	uids = NULL;
149	ttydev = NODEV;
150	dropgid = 0;
151	memf = nlistf = _PATH_DEVNULL;
152	while ((ch = getopt(argc, argv,
153#if defined(LAZY_PS)
154	    "aCcefghjLlM:mN:O:o:p:rSTt:U:uvwxZ")) != -1)
155#else
156	    "aCceghjLlM:mN:O:o:p:rSTt:U:uvwxZ")) != -1)
157#endif
158		switch((char)ch) {
159		case 'a':
160			all = 1;
161			break;
162		case 'C':
163			rawcpu = 1;
164			break;
165		case 'c':
166			cflag = 1;
167			break;
168		case 'e':			/* XXX set ufmt */
169			needenv = 1;
170			break;
171		case 'g':
172			break;			/* no-op */
173		case 'h':
174			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
175			break;
176		case 'j':
177			parsefmt(jfmt);
178			_fmt = 1;
179			jfmt[0] = '\0';
180			break;
181		case 'L':
182			showkey();
183			exit(0);
184		case 'l':
185			parsefmt(lfmt);
186			_fmt = 1;
187			lfmt[0] = '\0';
188			break;
189		case 'M':
190			memf = optarg;
191			dropgid = 1;
192			break;
193		case 'm':
194			sortby = SORTMEM;
195			break;
196		case 'N':
197			nlistf = optarg;
198			dropgid = 1;
199			break;
200		case 'O':
201			parsefmt(o1);
202			parsefmt(optarg);
203			parsefmt(o2);
204			o1[0] = o2[0] = '\0';
205			_fmt = 1;
206			break;
207		case 'o':
208			parsefmt(optarg);
209			_fmt = 1;
210			break;
211#if defined(LAZY_PS)
212		case 'f':
213			if (getuid() == 0 || getgid() == 0)
214			    forceuread = 1;
215			break;
216#endif
217		case 'p':
218			pid = atol(optarg);
219			xflg = 1;
220			break;
221		case 'r':
222			sortby = SORTCPU;
223			break;
224		case 'S':
225			sumrusage = 1;
226			break;
227		case 'T':
228			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
229				errx(1, "stdin: not a terminal");
230			/* FALLTHROUGH */
231		case 't': {
232			struct stat sb;
233			char *ttypath, pathbuf[PATH_MAX];
234
235			if (strcmp(optarg, "co") == 0)
236				ttypath = strdup(_PATH_CONSOLE);
237			else if (*optarg != '/')
238				(void)snprintf(ttypath = pathbuf,
239				    sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
240			else
241				ttypath = optarg;
242			if (stat(ttypath, &sb) == -1)
243				err(1, "%s", ttypath);
244			if (!S_ISCHR(sb.st_mode))
245				errx(1, "%s: not a terminal", ttypath);
246			ttydev = sb.st_rdev;
247			break;
248		}
249		case 'U':
250			uids = getuids(optarg, &nuids);
251			xflg++;		/* XXX: intuitive? */
252			break;
253		case 'u':
254			parsefmt(ufmt);
255			sortby = SORTCPU;
256			_fmt = 1;
257			ufmt[0] = '\0';
258			break;
259		case 'v':
260			parsefmt(vfmt);
261			sortby = SORTMEM;
262			_fmt = 1;
263			vfmt[0] = '\0';
264			break;
265		case 'w':
266			if (wflag)
267				termwidth = UNLIMITED;
268			else if (termwidth < 131)
269				termwidth = 131;
270			wflag++;
271			break;
272		case 'x':
273			xflg = 1;
274			break;
275		case 'Z':
276			parsefmt(Zfmt);
277			Zfmt[0] = '\0';
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			err(1, "malloc");
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 || 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 && ((&kinfo[i])->ki_p->ki_tdev == NODEV ||
371		    ((&kinfo[i])->ki_p->ki_flag & P_CONTROLT ) == 0))
372			continue;
373		if (nuids > 1) {
374			for (uid = 0; uid < nuids; uid++)
375				if ((&kinfo[i])->ki_p->ki_uid == uids[uid])
376					break;
377			if (uid == nuids)
378				continue;
379		}
380		for (vent = vhead; vent; vent = vent->next) {
381			(vent->var->oproc)(&kinfo[i], vent);
382			if (vent->next != NULL)
383				(void)putchar(' ');
384		}
385		(void)putchar('\n');
386		if (prtheader && lineno++ == prtheader - 4) {
387			(void)putchar('\n');
388			printheader();
389			lineno = 0;
390		}
391	}
392	free(uids);
393	lomac_stop();
394
395	exit(eval);
396}
397
398uid_t *
399getuids(const char *arg, int *nuids)
400{
401	char name[UT_NAMESIZE + 1];
402	struct passwd *pwd;
403	uid_t *uids, *moreuids;
404	int alloc;
405	size_t l;
406
407
408	alloc = 0;
409	*nuids = 0;
410	uids = NULL;
411	for (; (l = strcspn(arg, SEP)) > 0; arg += l + strspn(arg + l, SEP)) {
412		if (l >= sizeof name) {
413			warnx("%.*s: name too long", (int)l, arg);
414			continue;
415		}
416		strncpy(name, arg, l);
417		name[l] = '\0';
418		if ((pwd = getpwnam(name)) == NULL) {
419			warnx("%s: no such user", name);
420			continue;
421		}
422		if (*nuids >= alloc) {
423			alloc = (alloc + 1) << 1;
424			moreuids = realloc(uids, alloc * sizeof (*uids));
425			if (moreuids == NULL) {
426				free(uids);
427				err(1, "realloc");
428			}
429			uids = moreuids;
430		}
431		uids[(*nuids)++] = pwd->pw_uid;
432	}
433	endpwent();
434
435	if (!*nuids)
436		errx(1, "No users specified");
437
438	return uids;
439}
440
441static void
442scanvars(void)
443{
444	struct varent *vent;
445	VAR *v;
446
447	for (vent = vhead; vent; vent = vent->next) {
448		v = vent->var;
449		if (v->flag & DSIZ) {
450			v->dwidth = v->width;
451			v->width = 0;
452		}
453		if (v->flag & USER)
454			needuser = 1;
455		if (v->flag & COMM)
456			needcomm = 1;
457	}
458}
459
460static void
461dynsizevars(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
479static void
480sizevars(void)
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
496static const char *
497fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
498  char *comm, int maxlen)
499{
500	const char *s;
501
502	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
503	if (s == NULL)
504		err(1, NULL);
505	return (s);
506}
507
508#define UREADOK(ki)	(forceuread || (ki->ki_p->ki_sflag & PS_INMEM))
509
510static void
511saveuser(KINFO *ki)
512{
513
514	if (ki->ki_p->ki_sflag & PS_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		ki->ki_valid = 1;
522	} else
523		ki->ki_valid = 0;
524	/*
525	 * save arguments if needed
526	 */
527	if (needcomm && (UREADOK(ki) || (ki->ki_p->ki_args != NULL))) {
528		ki->ki_args = strdup(fmt(kvm_getargv, ki, ki->ki_p->ki_comm,
529		    MAXCOMLEN));
530	} else if (needcomm) {
531		asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
532	} else {
533		ki->ki_args = NULL;
534	}
535	if (needenv && UREADOK(ki)) {
536		ki->ki_env = strdup(fmt(kvm_getenvv, ki, (char *)NULL, 0));
537	} else if (needenv) {
538		ki->ki_env = malloc(3);
539		strcpy(ki->ki_env, "()");
540	} else {
541		ki->ki_env = NULL;
542	}
543}
544
545static int
546pscomp(const void *a, const void *b)
547{
548	int i;
549#define VSIZE(k) ((k)->ki_p->ki_dsize + (k)->ki_p->ki_ssize + \
550		  (k)->ki_p->ki_tsize)
551
552	if (sortby == SORTCPU)
553		return (getpcpu((const KINFO *)b) - getpcpu((const KINFO *)a));
554	if (sortby == SORTMEM)
555		return (VSIZE((const KINFO *)b) - VSIZE((const KINFO *)a));
556	i =  (int)((const KINFO *)a)->ki_p->ki_tdev - (int)((const KINFO *)b)->ki_p->ki_tdev;
557	if (i == 0)
558		i = ((const KINFO *)a)->ki_p->ki_pid - ((const KINFO *)b)->ki_p->ki_pid;
559	return (i);
560}
561
562/*
563 * ICK (all for getopt), would rather hide the ugliness
564 * here than taint the main code.
565 *
566 *  ps foo -> ps -foo
567 *  ps 34 -> ps -p34
568 *
569 * The old convention that 't' with no trailing tty arg means the users
570 * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
571 * feature is available with the option 'T', which takes no argument.
572 */
573static char *
574kludge_oldps_options(char *s)
575{
576	size_t len;
577	char *newopts, *ns, *cp;
578
579	len = strlen(s);
580	if ((newopts = ns = malloc(len + 2)) == NULL)
581		err(1, NULL);
582	/*
583	 * options begin with '-'
584	 */
585	if (*s != '-')
586		*ns++ = '-';	/* add option flag */
587	/*
588	 * gaze to end of argv[1]
589	 */
590	cp = s + len - 1;
591	/*
592	 * if last letter is a 't' flag with no argument (in the context
593	 * of the oldps options -- option string NOT starting with a '-' --
594	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
595	 *
596	 * However, if a flag accepting a string argument is found in the
597	 * option string, the remainder of the string is the argument to
598	 * that flag; do not modify that argument.
599	 */
600	if (strcspn(s, "MNOoU") == len && *cp == 't' && *s != '-')
601		*cp = 'T';
602	else {
603		/*
604		 * otherwise check for trailing number, which *may* be a
605		 * pid.
606		 */
607		while (cp >= s && isdigit(*cp))
608			--cp;
609	}
610	cp++;
611	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
612	ns += cp - s;
613	/*
614	 * if there's a trailing number, and not a preceding 'p' (pid) or
615	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
616	 */
617	if (isdigit(*cp) &&
618	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
619	    (cp - 1 == s || cp[-2] != 't'))
620		*ns++ = 'p';
621	(void)strcpy(ns, cp);		/* and append the number */
622
623	return (newopts);
624}
625
626static void
627usage(void)
628{
629
630	(void)fprintf(stderr, "%s\n%s\n%s\n",
631	    "usage: ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty] [-U user]",
632	    "          [-M core] [-N system]",
633	    "       ps [-L]");
634	exit(1);
635}
636