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