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