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