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