ps.c revision 69896
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 69896 2000-12-12 07:25:57Z mckusick $";
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 <nlist.h>
63#include <paths.h>
64#include <stdio.h>
65#include <stdlib.h>
66#include <string.h>
67#include <unistd.h>
68#include <locale.h>
69#include <pwd.h>
70#include <utmp.h>
71
72#include "ps.h"
73
74#define SEP ", \t"		/* username separators */
75
76KINFO *kinfo;
77struct varent *vhead, *vtail;
78
79int	eval;			/* exit value */
80int	cflag;			/* -c */
81int	rawcpu;			/* -C */
82int	sumrusage;		/* -S */
83int	termwidth;		/* width of screen (0 == infinity) */
84int	totwidth;		/* calculated width of requested variables */
85
86static int needuser, needcomm, needenv;
87#if defined(LAZY_PS)
88static int forceuread=0;
89#else
90static int forceuread=1;
91#endif
92
93enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
94
95static char	*fmt __P((char **(*)(kvm_t *, const struct kinfo_proc *, int),
96		    KINFO *, char *, int));
97static char	*kludge_oldps_options __P((char *));
98static int	 pscomp __P((const void *, const void *));
99static void	 saveuser __P((KINFO *));
100static void	 scanvars __P((void));
101static void	 dynsizevars __P((KINFO *));
102static void	 sizevars __P((void));
103static void	 usage __P((void));
104static uid_t	*getuids(const char *, int *);
105
106char dfmt[] = "pid tt state time command";
107char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
108char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
109char   o1[] = "pid";
110char   o2[] = "tt state time command";
111char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
112char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
113
114kvm_t *kd;
115
116int
117main(argc, argv)
118	int argc;
119	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, *swapf, 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 = swapf = _PATH_DEVNULL;
151	while ((ch = getopt(argc, argv,
152#if defined(LAZY_PS)
153	    "aCcefghjLlM:mN:O:o:p:rSTt:U:uvW:wx")) != -1)
154#else
155	    "aCceghjLlM:mN:O:o:p:rSTt:U:uvW:wx")) != -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[MAXPATHLEN];
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			swapf = optarg;
266			dropgid = 1;
267			break;
268		case 'w':
269			if (wflag)
270				termwidth = UNLIMITED;
271			else if (termwidth < 131)
272				termwidth = 131;
273			wflag++;
274			break;
275		case 'x':
276			xflg = 1;
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			if (*++argv)
292				swapf = *argv;
293		}
294	}
295#endif
296	/*
297	 * Discard setgid privileges if not the running kernel so that bad
298	 * guys can't print interesting stuff from kernel memory.
299	 */
300	if (dropgid) {
301		setgid(getgid());
302		setuid(getuid());
303	}
304
305	kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
306	if (kd == 0)
307		errx(1, "%s", errbuf);
308
309	if (!fmt)
310		parsefmt(dfmt);
311
312	/* XXX - should be cleaner */
313	if (!all && ttydev == NODEV && pid == -1 && !nuids) {
314		if ((uids = malloc(sizeof (*uids))) == NULL)
315			errx(1, "malloc: %s", strerror(errno));
316		nuids = 1;
317		*uids = getuid();
318	}
319
320	/*
321	 * scan requested variables, noting what structures are needed,
322	 * and adjusting header widths as appropriate.
323	 */
324	scanvars();
325	/*
326	 * get proc list
327	 */
328	if (nuids == 1) {
329		what = KERN_PROC_UID;
330		flag = *uids;
331	} else if (ttydev != NODEV) {
332		what = KERN_PROC_TTY;
333		flag = ttydev;
334	} else if (pid != -1) {
335		what = KERN_PROC_PID;
336		flag = pid;
337	} else {
338		what = KERN_PROC_ALL;
339		flag = 0;
340	}
341	/*
342	 * select procs
343	 */
344	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0)
345		errx(1, "%s", kvm_geterr(kd));
346	if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
347		err(1, NULL);
348	for (i = nentries; --i >= 0; ++kp) {
349		kinfo[i].ki_p = kp;
350		if (needuser)
351			saveuser(&kinfo[i]);
352		dynsizevars(&kinfo[i]);
353	}
354
355	sizevars();
356
357	/*
358	 * print header
359	 */
360	printheader();
361	if (nentries == 0)
362		exit(1);
363	/*
364	 * sort proc list
365	 */
366	qsort(kinfo, nentries, sizeof(KINFO), pscomp);
367	/*
368	 * for each proc, call each variable output function.
369	 */
370	for (i = lineno = 0; i < nentries; i++) {
371		if (xflg == 0 && ((&kinfo[i])->ki_p->ki_tdev == NODEV ||
372		    ((&kinfo[i])->ki_p->ki_flag & P_CONTROLT ) == 0))
373			continue;
374		if (nuids > 1) {
375			for (uid = 0; uid < nuids; uid++)
376				if ((&kinfo[i])->ki_p->ki_uid == uids[uid])
377					break;
378			if (uid == nuids)
379				continue;
380		}
381		for (vent = vhead; vent; vent = vent->next) {
382			(vent->var->oproc)(&kinfo[i], vent);
383			if (vent->next != NULL)
384				(void)putchar(' ');
385		}
386		(void)putchar('\n');
387		if (prtheader && lineno++ == prtheader - 4) {
388			(void)putchar('\n');
389			printheader();
390			lineno = 0;
391		}
392	}
393	free(uids);
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 l, alloc;
405
406
407	alloc = 0;
408	*nuids = 0;
409	uids = NULL;
410	for (; (l = strcspn(arg, SEP)) > 0; arg += l + strspn(arg + l, SEP)) {
411		if (l >= sizeof name) {
412			warnx("%.*s: name too long", l, arg);
413			continue;
414		}
415		strncpy(name, arg, l);
416		name[l] = '\0';
417		if ((pwd = getpwnam(name)) == NULL) {
418			warnx("%s: no such user", name);
419			continue;
420		}
421		if (*nuids >= alloc) {
422			alloc = (alloc + 1) << 1;
423			moreuids = realloc(uids, alloc * sizeof (*uids));
424			if (moreuids == NULL) {
425				free(uids);
426				errx(1, "realloc: %s", strerror(errno));
427			}
428			uids = moreuids;
429		}
430		uids[(*nuids)++] = pwd->pw_uid;
431	}
432	endpwent();
433
434	if (!*nuids)
435		errx(1, "No users specified");
436
437	return uids;
438}
439
440static void
441scanvars()
442{
443	struct varent *vent;
444	VAR *v;
445
446	for (vent = vhead; vent; vent = vent->next) {
447		v = vent->var;
448		if (v->flag & DSIZ) {
449			v->dwidth = v->width;
450			v->width = 0;
451		}
452		if (v->flag & USER)
453			needuser = 1;
454		if (v->flag & COMM)
455			needcomm = 1;
456	}
457}
458
459static void
460dynsizevars(ki)
461	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()
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 char *
497fmt(fn, ki, comm, maxlen)
498	char **(*fn) __P((kvm_t *, const struct kinfo_proc *, int));
499	KINFO *ki;
500	char *comm;
501	int maxlen;
502{
503	char *s;
504
505	if ((s =
506	    fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen)) == NULL)
507		err(1, NULL);
508	return (s);
509}
510
511#define UREADOK(ki)	(forceuread || (ki->ki_p->ki_flag & P_INMEM))
512
513static void
514saveuser(ki)
515	KINFO *ki;
516{
517
518	if (ki->ki_p->ki_flag & P_INMEM) {
519		/*
520		 * The u-area might be swapped out, and we can't get
521		 * at it because we have a crashdump and no swap.
522		 * If it's here fill in these fields, otherwise, just
523		 * leave them 0.
524		 */
525		ki->ki_valid = 1;
526	} else
527		ki->ki_valid = 0;
528	/*
529	 * save arguments if needed
530	 */
531	if (needcomm && (UREADOK(ki) || (ki->ki_p->ki_args != NULL))) {
532		ki->ki_args = fmt(kvm_getargv, ki, ki->ki_p->ki_comm,
533		    MAXCOMLEN);
534	} else if (needcomm) {
535		ki->ki_args = malloc(strlen(ki->ki_p->ki_comm) + 3);
536		sprintf(ki->ki_args, "(%s)", ki->ki_p->ki_comm);
537	} else {
538		ki->ki_args = NULL;
539	}
540	if (needenv && UREADOK(ki)) {
541		ki->ki_env = fmt(kvm_getenvv, ki, (char *)NULL, 0);
542	} else if (needenv) {
543		ki->ki_env = malloc(3);
544		strcpy(ki->ki_env, "()");
545	} else {
546		ki->ki_env = NULL;
547	}
548}
549
550static int
551pscomp(a, b)
552	const void *a, *b;
553{
554	int i;
555#define VSIZE(k) ((k)->ki_p->ki_dsize + (k)->ki_p->ki_ssize + \
556		  (k)->ki_p->ki_tsize)
557
558	if (sortby == SORTCPU)
559		return (getpcpu((KINFO *)b) - getpcpu((KINFO *)a));
560	if (sortby == SORTMEM)
561		return (VSIZE((KINFO *)b) - VSIZE((KINFO *)a));
562	i =  ((KINFO *)a)->ki_p->ki_tdev - ((KINFO *)b)->ki_p->ki_tdev;
563	if (i == 0)
564		i = ((KINFO *)a)->ki_p->ki_pid - ((KINFO *)b)->ki_p->ki_pid;
565	return (i);
566}
567
568/*
569 * ICK (all for getopt), would rather hide the ugliness
570 * here than taint the main code.
571 *
572 *  ps foo -> ps -foo
573 *  ps 34 -> ps -p34
574 *
575 * The old convention that 't' with no trailing tty arg means the users
576 * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
577 * feature is available with the option 'T', which takes no argument.
578 */
579static char *
580kludge_oldps_options(s)
581	char *s;
582{
583	size_t len;
584	char *newopts, *ns, *cp;
585
586	len = strlen(s);
587	if ((newopts = ns = malloc(len + 2)) == NULL)
588		err(1, NULL);
589	/*
590	 * options begin with '-'
591	 */
592	if (*s != '-')
593		*ns++ = '-';	/* add option flag */
594	/*
595	 * gaze to end of argv[1]
596	 */
597	cp = s + len - 1;
598	/*
599	 * if last letter is a 't' flag with no argument (in the context
600	 * of the oldps options -- option string NOT starting with a '-' --
601	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
602	 */
603	if (*cp == 't' && *s != '-')
604		*cp = 'T';
605	else {
606		/*
607		 * otherwise check for trailing number, which *may* be a
608		 * pid.
609		 */
610		while (cp >= s && isdigit(*cp))
611			--cp;
612	}
613	cp++;
614	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
615	ns += cp - s;
616	/*
617	 * if there's a trailing number, and not a preceding 'p' (pid) or
618	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
619	 */
620	if (isdigit(*cp) &&
621	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
622	    (cp - 1 == s || cp[-2] != 't'))
623		*ns++ = 'p';
624	(void)strcpy(ns, cp);		/* and append the number */
625
626	return (newopts);
627}
628
629static void
630usage()
631{
632
633	(void)fprintf(stderr, "%s\n%s\n%s\n",
634	    "usage: ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty] [-U user]",
635	    "          [-M core] [-N system] [-W swap]",
636	    "       ps [-L]");
637	exit(1);
638}
639