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