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