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