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