xref: /original-bsd/bin/ps/ps.c (revision 9360d17c)
1 /*-
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 char copyright[] =
10 "@(#) Copyright (c) 1990 The Regents of the University of California.\n\
11  All rights reserved.\n";
12 #endif /* not lint */
13 
14 #ifndef lint
15 static char sccsid[] = "@(#)ps.c	5.47 (Berkeley) 06/05/92";
16 #endif /* not lint */
17 
18 #include <sys/param.h>
19 #include <sys/file.h>
20 #include <sys/user.h>
21 #include <sys/time.h>
22 #include <sys/resource.h>
23 #include <sys/proc.h>
24 #include <sys/stat.h>
25 #include <sys/ioctl.h>
26 #include <sys/kinfo.h>
27 #include <nlist.h>
28 #include <kvm.h>
29 #include <errno.h>
30 #include <unistd.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <paths.h>
35 #include <ctype.h>
36 #include "ps.h"
37 
38 #ifdef SPPWAIT
39 #define NEWVM
40 #endif
41 
42 KINFO *kinfo;
43 struct varent *vhead, *vtail;
44 
45 int	eval;			/* exit value */
46 int	rawcpu;			/* -C */
47 int	sumrusage;		/* -S */
48 int	termwidth;		/* width of screen (0 == infinity) */
49 int	totwidth;		/* calculated width of requested variables */
50 
51 static int needuser, needcomm, needenv;
52 
53 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
54 
55 static void	 err __P((const char *, ...));
56 static char	*fmt __P((char **(*)(kvm_t *, const struct kinfo_proc *, int),
57 		    KINFO *, char *, int));
58 static char	*kludge_oldps_options __P((char *));
59 static int	 pscomp __P((const void *, const void *));
60 static void	 saveuser __P((KINFO *));
61 static void	 scanvars __P((void));
62 static void	 usage __P((void));
63 
64 char dfmt[] = "pid tt state time command";
65 char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
66 char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
67 char   o1[] = "pid";
68 char   o2[] = "tt state time command";
69 char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
70 char vfmt[] =
71 	"pid state time sl re pagein vsz rss lim tsiz trs %cpu %mem command";
72 
73 kvm_t *kd;
74 
75 int
76 main(argc, argv)
77 	int argc;
78 	char *argv[];
79 {
80 	register struct kinfo_proc *kp;
81 	register struct varent *vent;
82 	int nentries;
83 	register int i;
84 	struct winsize ws;
85 	dev_t ttydev;
86 	int all, ch, flag, fmt, lineno, pid, prtheader, uid, wflag, what, xflg;
87 	char *nlistf, *memf, *swapf, errbuf[256];
88 
89 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
90 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
91 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
92 	     ws.ws_col == 0)
93 		termwidth = 79;
94 	else
95 		termwidth = ws.ws_col - 1;
96 
97 	if (argc > 1)
98 		argv[1] = kludge_oldps_options(argv[1]);
99 
100 	all = fmt = wflag = xflg = 0;
101 	pid = uid = -1;
102 	ttydev = NODEV;
103 	memf = nlistf = swapf = NULL;
104 	while ((ch = getopt(argc, argv,
105 	    "aCeghjLlM:mN:O:o:p:rSTt:uvW:wx")) != EOF)
106 		switch((char)ch) {
107 		case 'a':
108 			all = 1;
109 			break;
110 		case 'e':
111 			/* 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 				err("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("%s: %s", ttypath, strerror(errno));
182 			if (!S_ISCHR(sb.st_mode))
183 				err("%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 
223 		nlistf = *argv;
224 		if (*++argv) {
225 			memf = *argv;
226 			if (*++argv)
227 				swapf = *argv;
228 		}
229 	}
230 #endif
231 	/*
232 	 * Discard setgid privileges if not the running kernel so that bad
233 	 * guys can't print interesting stuff from kernel memory.
234 	 */
235 	if (nlistf != NULL || memf != NULL || swapf != NULL)
236 		setgid(getgid());
237 
238 	kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
239 	if (kd == 0)
240 		err("%s", errbuf);
241 
242 	if (!fmt)
243 		parsefmt(dfmt);
244 
245 	if (!all && ttydev == NODEV && pid == -1)  /* XXX - should be cleaner */
246 		uid = getuid();
247 
248 	/*
249 	 * scan requested variables, noting what structures are needed,
250 	 * and adjusting header widths as appropiate.
251 	 */
252 	scanvars();
253 	/*
254 	 * get proc list
255 	 */
256 	if (uid != -1) {
257 		what = KINFO_PROC_UID;
258 		flag = uid;
259 	} else if (ttydev != NODEV) {
260 		what = KINFO_PROC_TTY;
261 		flag = ttydev;
262 	} else if (pid != -1) {
263 		what = KINFO_PROC_PID;
264 		flag = pid;
265 	} else
266 		what = KINFO_PROC_ALL;
267 	/*
268 	 * select procs
269 	 */
270 	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0)
271 		err("%s", kvm_geterr(kd));
272 	kinfo = malloc(nentries * sizeof(*kinfo));
273 	if (kinfo == NULL)
274 		err("%s", strerror(errno));
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 & SCTTY ) == 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 	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
343 	if (s == NULL)
344 		err("%s", strerror(errno));
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("%s", strerror(errno));
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 	bcopy(s, ns, (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 #if __STDC__
467 #include <stdarg.h>
468 #else
469 #include <varargs.h>
470 #endif
471 
472 void
473 #if __STDC__
474 err(const char *fmt, ...)
475 #else
476 err(fmt, va_alist)
477 	char *fmt;
478         va_dcl
479 #endif
480 {
481 	va_list ap;
482 #if __STDC__
483 	va_start(ap, fmt);
484 #else
485 	va_start(ap);
486 #endif
487 	(void)fprintf(stderr, "ps: ");
488 	(void)vfprintf(stderr, fmt, ap);
489 	va_end(ap);
490 	(void)fprintf(stderr, "\n");
491 	exit(1);
492 	/* NOTREACHED */
493 }
494 
495 static void
496 usage()
497 {
498 	(void)fprintf(stderr,
499 "usage: ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty]\n\t  [-M core] [-N system] [-W swap]\n       ps [-L]\n");
500 	exit(1);
501 }
502