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