ps.c revision 19068
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 *	$Id: ps.c,v 1.12 1996/01/20 10:43:54 mpp Exp $
34 */
35
36#ifndef lint
37static char copyright[] =
38"@(#) Copyright (c) 1990, 1993, 1994\n\
39	The Regents of the University of California.  All rights reserved.\n";
40#endif /* not lint */
41
42#ifndef lint
43static char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
44#endif /* not lint */
45
46#include <sys/param.h>
47#include <sys/user.h>
48#include <sys/time.h>
49#include <sys/resource.h>
50#include <sys/proc.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 <errno.h>
58#include <fcntl.h>
59#include <kvm.h>
60#include <limits.h>
61#include <nlist.h>
62#include <paths.h>
63#include <stdio.h>
64#include <stdlib.h>
65#include <string.h>
66#include <unistd.h>
67#include <locale.h>
68#include <pwd.h>
69
70#include "ps.h"
71
72#ifdef P_PPWAIT
73#define NEWVM
74#endif
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
88enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
89
90static char	*fmt __P((char **(*)(kvm_t *, const struct kinfo_proc *, int),
91		    KINFO *, char *, int));
92static char	*kludge_oldps_options __P((char *));
93static int	 pscomp __P((const void *, const void *));
94static void	 saveuser __P((KINFO *));
95static void	 scanvars __P((void));
96static void	 usage __P((void));
97
98char dfmt[] = "pid tt state time command";
99char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
100char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
101char   o1[] = "pid";
102char   o2[] = "tt state time command";
103char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
104char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
105
106kvm_t *kd;
107
108int
109main(argc, argv)
110	int argc;
111	char *argv[];
112{
113	struct kinfo_proc *kp;
114	struct varent *vent;
115	struct winsize ws;
116	struct passwd *pwd;
117	dev_t ttydev;
118	pid_t pid;
119	uid_t uid;
120	int all, ch, flag, i, fmt, lineno, nentries;
121	int prtheader, wflag, what, xflg;
122	char *nlistf, *memf, *swapf, errbuf[_POSIX2_LINE_MAX];
123
124	(void) setlocale(LC_ALL, "");
125
126	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
127	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
128	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
129	     ws.ws_col == 0)
130		termwidth = 79;
131	else
132		termwidth = ws.ws_col - 1;
133
134	if (argc > 1)
135		argv[1] = kludge_oldps_options(argv[1]);
136
137	all = fmt = prtheader = wflag = xflg = 0;
138	pid = -1;
139	uid = (uid_t) -1;
140	ttydev = NODEV;
141	memf = nlistf = swapf = NULL;
142	while ((ch = getopt(argc, argv,
143	    "aCceghjLlM:mN:O:o:p:rSTt:U:uvW:wx")) != EOF)
144		switch((char)ch) {
145		case 'a':
146			all = 1;
147			break;
148		case 'C':
149			rawcpu = 1;
150			break;
151		case 'c':
152			cflag = 1;
153			break;
154		case 'e':			/* XXX set ufmt */
155			needenv = 1;
156			break;
157		case 'g':
158			break;			/* no-op */
159		case 'h':
160			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
161			break;
162		case 'j':
163			parsefmt(jfmt);
164			fmt = 1;
165			jfmt[0] = '\0';
166			break;
167		case 'L':
168			showkey();
169			exit(0);
170		case 'l':
171			parsefmt(lfmt);
172			fmt = 1;
173			lfmt[0] = '\0';
174			break;
175		case 'M':
176			memf = optarg;
177			break;
178		case 'm':
179			sortby = SORTMEM;
180			break;
181		case 'N':
182			nlistf = optarg;
183			break;
184		case 'O':
185			parsefmt(o1);
186			parsefmt(optarg);
187			parsefmt(o2);
188			o1[0] = o2[0] = '\0';
189			fmt = 1;
190			break;
191		case 'o':
192			parsefmt(optarg);
193			fmt = 1;
194			break;
195		case 'p':
196			pid = atol(optarg);
197			xflg = 1;
198			break;
199		case 'r':
200			sortby = SORTCPU;
201			break;
202		case 'S':
203			sumrusage = 1;
204			break;
205		case 'T':
206			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
207				errx(1, "stdin: not a terminal");
208			/* FALLTHROUGH */
209		case 't': {
210			struct stat sb;
211			char *ttypath, pathbuf[MAXPATHLEN];
212
213			if (strcmp(optarg, "co") == 0)
214				ttypath = _PATH_CONSOLE;
215			else if (*optarg != '/')
216				(void)snprintf(ttypath = pathbuf,
217				    sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
218			else
219				ttypath = optarg;
220			if (stat(ttypath, &sb) == -1)
221				err(1, "%s", ttypath);
222			if (!S_ISCHR(sb.st_mode))
223				errx(1, "%s: not a terminal", ttypath);
224			ttydev = sb.st_rdev;
225			break;
226		}
227		case 'U':
228			pwd = getpwnam(optarg);
229			if (pwd == NULL)
230				errx(1, "%s: no such user", optarg);
231			uid = pwd->pw_uid;
232			endpwent();
233			xflg++;		/* XXX: intuitive? */
234			break;
235		case 'u':
236			parsefmt(ufmt);
237			sortby = SORTCPU;
238			fmt = 1;
239			ufmt[0] = '\0';
240			break;
241		case 'v':
242			parsefmt(vfmt);
243			sortby = SORTMEM;
244			fmt = 1;
245			vfmt[0] = '\0';
246			break;
247		case 'W':
248			swapf = optarg;
249			break;
250		case 'w':
251			if (wflag)
252				termwidth = UNLIMITED;
253			else if (termwidth < 131)
254				termwidth = 131;
255			wflag++;
256			break;
257		case 'x':
258			xflg = 1;
259			break;
260		case '?':
261		default:
262			usage();
263		}
264	argc -= optind;
265	argv += optind;
266
267#define	BACKWARD_COMPATIBILITY
268#ifdef	BACKWARD_COMPATIBILITY
269	if (*argv) {
270		nlistf = *argv;
271		if (*++argv) {
272			memf = *argv;
273			if (*++argv)
274				swapf = *argv;
275		}
276	}
277#endif
278	/*
279	 * Discard setgid privileges if not the running kernel so that bad
280	 * guys can't print interesting stuff from kernel memory.
281	 */
282	if (nlistf != NULL || memf != NULL || swapf != NULL)
283		setgid(getgid());
284
285	kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
286	if (kd == 0)
287		errx(1, "%s", errbuf);
288
289	if (!fmt)
290		parsefmt(dfmt);
291
292	/* XXX - should be cleaner */
293	if (!all && ttydev == NODEV && pid == -1 && uid == (uid_t)-1)
294		uid = getuid();
295
296	/*
297	 * scan requested variables, noting what structures are needed,
298	 * and adjusting header widths as appropiate.
299	 */
300	scanvars();
301	/*
302	 * get proc list
303	 */
304	if (uid != (uid_t) -1) {
305		what = KERN_PROC_UID;
306		flag = uid;
307	} else if (ttydev != NODEV) {
308		what = KERN_PROC_TTY;
309		flag = ttydev;
310	} else if (pid != -1) {
311		what = KERN_PROC_PID;
312		flag = pid;
313	} else {
314		what = KERN_PROC_ALL;
315		flag = 0;
316	}
317	/*
318	 * select procs
319	 */
320	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0)
321		errx(1, "%s", kvm_geterr(kd));
322	if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
323		err(1, NULL);
324	for (i = nentries; --i >= 0; ++kp) {
325		kinfo[i].ki_p = kp;
326		if (needuser)
327			saveuser(&kinfo[i]);
328	}
329	/*
330	 * print header
331	 */
332	printheader();
333	if (nentries == 0)
334		exit(0);
335	/*
336	 * sort proc list
337	 */
338	qsort(kinfo, nentries, sizeof(KINFO), pscomp);
339	/*
340	 * for each proc, call each variable output function.
341	 */
342	for (i = lineno = 0; i < nentries; i++) {
343		if (xflg == 0 && (KI_EPROC(&kinfo[i])->e_tdev == NODEV ||
344		    (KI_PROC(&kinfo[i])->p_flag & P_CONTROLT ) == 0))
345			continue;
346		for (vent = vhead; vent; vent = vent->next) {
347			(vent->var->oproc)(&kinfo[i], vent);
348			if (vent->next != NULL)
349				(void)putchar(' ');
350		}
351		(void)putchar('\n');
352		if (prtheader && lineno++ == prtheader - 4) {
353			(void)putchar('\n');
354			printheader();
355			lineno = 0;
356		}
357	}
358	exit(eval);
359}
360
361static void
362scanvars()
363{
364	struct varent *vent;
365	VAR *v;
366	int i;
367
368	for (vent = vhead; vent; vent = vent->next) {
369		v = vent->var;
370		i = strlen(v->header);
371		if (v->width < i)
372			v->width = i;
373		totwidth += v->width + 1;	/* +1 for space */
374		if (v->flag & USER)
375			needuser = 1;
376		if (v->flag & COMM)
377			needcomm = 1;
378	}
379	totwidth--;
380}
381
382static char *
383fmt(fn, ki, comm, maxlen)
384	char **(*fn) __P((kvm_t *, const struct kinfo_proc *, int));
385	KINFO *ki;
386	char *comm;
387	int maxlen;
388{
389	char *s;
390
391	if ((s =
392	    fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen)) == NULL)
393		err(1, NULL);
394	return (s);
395}
396
397static void
398saveuser(ki)
399	KINFO *ki;
400{
401	struct pstats pstats;
402	struct usave *usp;
403	struct user *u_addr = (struct user *)USRSTACK;
404
405	usp = &ki->ki_u;
406	if (kvm_uread(kd, KI_PROC(ki), (unsigned long)&u_addr->u_stats,
407	    (char *)&pstats, sizeof(pstats)) == sizeof(pstats)) {
408		/*
409		 * The u-area might be swapped out, and we can't get
410		 * at it because we have a crashdump and no swap.
411		 * If it's here fill in these fields, otherwise, just
412		 * leave them 0.
413		 */
414		usp->u_start = pstats.p_start;
415		usp->u_ru = pstats.p_ru;
416		usp->u_cru = pstats.p_cru;
417		usp->u_valid = 1;
418	} else
419		usp->u_valid = 0;
420	/*
421	 * save arguments if needed
422	 */
423	if (needcomm)
424		ki->ki_args = fmt(kvm_getargv, ki, KI_PROC(ki)->p_comm,
425		    MAXCOMLEN);
426	else
427		ki->ki_args = NULL;
428	if (needenv)
429		ki->ki_env = fmt(kvm_getenvv, ki, (char *)NULL, 0);
430	else
431		ki->ki_env = NULL;
432}
433
434static int
435pscomp(a, b)
436	const void *a, *b;
437{
438	int i;
439#ifdef NEWVM
440#define VSIZE(k) (KI_EPROC(k)->e_vm.vm_dsize + KI_EPROC(k)->e_vm.vm_ssize + \
441		  KI_EPROC(k)->e_vm.vm_tsize)
442#else
443#define VSIZE(k) ((k)->ki_p->p_dsize + (k)->ki_p->p_ssize + (k)->ki_e->e_xsize)
444#endif
445
446	if (sortby == SORTCPU)
447		return (getpcpu((KINFO *)b) - getpcpu((KINFO *)a));
448	if (sortby == SORTMEM)
449		return (VSIZE((KINFO *)b) - VSIZE((KINFO *)a));
450	i =  KI_EPROC((KINFO *)a)->e_tdev - KI_EPROC((KINFO *)b)->e_tdev;
451	if (i == 0)
452		i = KI_PROC((KINFO *)a)->p_pid - KI_PROC((KINFO *)b)->p_pid;
453	return (i);
454}
455
456/*
457 * ICK (all for getopt), would rather hide the ugliness
458 * here than taint the main code.
459 *
460 *  ps foo -> ps -foo
461 *  ps 34 -> ps -p34
462 *
463 * The old convention that 't' with no trailing tty arg means the users
464 * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
465 * feature is available with the option 'T', which takes no argument.
466 */
467static char *
468kludge_oldps_options(s)
469	char *s;
470{
471	size_t len;
472	char *newopts, *ns, *cp;
473
474	len = strlen(s);
475	if ((newopts = ns = malloc(len + 2)) == NULL)
476		err(1, NULL);
477	/*
478	 * options begin with '-'
479	 */
480	if (*s != '-')
481		*ns++ = '-';	/* add option flag */
482	/*
483	 * gaze to end of argv[1]
484	 */
485	cp = s + len - 1;
486	/*
487	 * if last letter is a 't' flag with no argument (in the context
488	 * of the oldps options -- option string NOT starting with a '-' --
489	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
490	 */
491	if (*cp == 't' && *s != '-')
492		*cp = 'T';
493	else {
494		/*
495		 * otherwise check for trailing number, which *may* be a
496		 * pid.
497		 */
498		while (cp >= s && isdigit(*cp))
499			--cp;
500	}
501	cp++;
502	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
503	ns += cp - s;
504	/*
505	 * if there's a trailing number, and not a preceding 'p' (pid) or
506	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
507	 */
508	if (isdigit(*cp) &&
509	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
510	    (cp - 1 == s || cp[-2] != 't'))
511		*ns++ = 'p';
512	(void)strcpy(ns, cp);		/* and append the number */
513
514	return (newopts);
515}
516
517static void
518usage()
519{
520
521	(void)fprintf(stderr,
522	    "usage:\t%s\n\t   %s\n\t%s\n",
523	    "ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty] [-U user]",
524	    "[-M core] [-N system] [-W swap]",
525	    "ps [-L]");
526	exit(1);
527}
528