ps.c revision 1.36 1 /* $NetBSD: ps.c,v 1.36 2000/04/15 04:40:46 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.36 2000/04/15 04:40:46 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 dontuseprocfs = 1;
182 break;
183 case 'm':
184 sortby = SORTMEM;
185 break;
186 case 'N':
187 nlistf = optarg;
188 break;
189 case 'O':
190 parsefmt(o1);
191 parsefmt(optarg);
192 parsefmt(o2);
193 o1[0] = o2[0] = '\0';
194 fmt = 1;
195 break;
196 case 'o':
197 parsefmt(optarg);
198 fmt = 1;
199 break;
200 case 'p':
201 what = KERN_PROC_PID;
202 flag = atol(optarg);
203 xflg = 1;
204 break;
205 case 'r':
206 sortby = SORTCPU;
207 break;
208 case 'S':
209 sumrusage = 1;
210 break;
211 case 'T':
212 if ((ttname = ttyname(STDIN_FILENO)) == NULL)
213 errx(1, "stdin: not a terminal");
214 goto tty;
215 case 't':
216 ttname = optarg;
217 tty: {
218 struct stat sb;
219 char *ttypath, pathbuf[MAXPATHLEN];
220
221 flag = 0;
222 if (strcmp(ttname, "?") == 0)
223 flag = KERN_PROC_TTY_NODEV;
224 else if (strcmp(ttname, "-") == 0)
225 flag = KERN_PROC_TTY_REVOKE;
226 else if (strcmp(ttname, "co") == 0)
227 ttypath = _PATH_CONSOLE;
228 else if (*ttname != '/')
229 (void)snprintf(ttypath = pathbuf,
230 sizeof(pathbuf), "%s%s", _PATH_TTY, ttname);
231 else
232 ttypath = ttname;
233 what = KERN_PROC_TTY;
234 if (flag == 0) {
235 if (stat(ttypath, &sb) == -1)
236 err(1, "%s", ttypath);
237 if (!S_ISCHR(sb.st_mode))
238 errx(1, "%s: not a terminal", ttypath);
239 flag = sb.st_rdev;
240 }
241 break;
242 }
243 case 'U':
244 if (*optarg != '\0') {
245 struct passwd *pw;
246 char *ep;
247
248 what = KERN_PROC_UID;
249 pw = getpwnam(optarg);
250 if (pw == NULL) {
251 errno = 0;
252 flag = strtoul(optarg, &ep, 10);
253 if (errno)
254 err(1, "%s", optarg);
255 if (*ep != '\0')
256 errx(1, "%s: illegal user name",
257 optarg);
258 } else
259 flag = pw->pw_uid;
260 }
261 break;
262 case 'u':
263 parsefmt(ufmt);
264 sortby = SORTCPU;
265 fmt = 1;
266 ufmt[0] = '\0';
267 break;
268 case 'v':
269 parsefmt(vfmt);
270 sortby = SORTMEM;
271 fmt = 1;
272 vfmt[0] = '\0';
273 break;
274 case 'W':
275 swapf = optarg;
276 break;
277 case 'w':
278 if (wflag)
279 termwidth = UNLIMITED;
280 else if (termwidth < 131)
281 termwidth = 131;
282 wflag++;
283 break;
284 case 'x':
285 xflg = 1;
286 break;
287 case '?':
288 default:
289 usage();
290 }
291 argc -= optind;
292 argv += optind;
293
294 #define BACKWARD_COMPATIBILITY
295 #ifdef BACKWARD_COMPATIBILITY
296 if (*argv) {
297 nlistf = *argv;
298 if (*++argv) {
299 memf = *argv;
300 if (*++argv)
301 swapf = *argv;
302 }
303 }
304 #endif
305 /*
306 * Discard setgid privileges. If not the running kernel, we toss
307 * them away totally so that bad guys can't print interesting stuff
308 * from kernel memory, otherwise switch back to kmem for the
309 * duration of the kvm_openfiles() call.
310 */
311 if (nlistf != NULL || memf != NULL || swapf != NULL)
312 (void)setgid(getgid());
313 else
314 (void)setegid(egid);
315
316 kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
317 if (kd == 0) {
318 if (dontuseprocfs)
319 errx(1, "%s", errbuf);
320 else {
321 warnx("kvm_openfiles: %s", errbuf);
322 fprintf(stderr, "ps: falling back to /proc-based lookup\n");
323 }
324 }
325
326 if (nlistf == NULL && memf == NULL && swapf == NULL)
327 (void)setgid(getgid());
328
329 if (!fmt)
330 parsefmt(dfmt);
331
332 /*
333 * scan requested variables, noting what structures are needed,
334 * and adjusting header widths as appropiate.
335 */
336 scanvars();
337
338 /*
339 * select procs
340 */
341 if (!kd || !(kinfo = getkinfo_kvm(kd, what, flag, &nentries, needuser)))
342 {
343 /* If/when the /proc-based code is ripped out
344 * again, make sure all references to the -K
345 * option are also pulled (getopt(), usage(),
346 * man page). See the man page comments about
347 * this for more details. */
348 /* sysctl() ought to provide some sort of
349 * always-working-but-minimal-functionality
350 * method of providing at least some of the
351 * process information. Unfortunately, such a
352 * change will require too much work to be put
353 * into 1.4. For now, enable this experimental
354 * /proc-based support instead (if /proc is
355 * mounted) to grab as much information as we can.
356 * The guts of emulating kvm_getprocs() is in
357 * the file procfs_ops.c. */
358 if (kd)
359 warnx("%s.", kvm_geterr(kd));
360 if (dontuseprocfs) {
361 exit(1);
362 }
363 /* procfs_getprocs supports all but the
364 * KERN_PROC_RUID flag. */
365 kinfo = getkinfo_procfs(what, flag, &nentries);
366 if (kinfo == 0) {
367 errx(1, "fallback /proc-based lookup also failed. %s",
368 "Giving up...");
369 }
370 fprintf(stderr, "%s%s",
371 "Warning: /proc does not provide ",
372 "valid data for all fields.\n");
373 use_procfs = 1;
374 }
375
376 /*
377 * print header
378 */
379 printheader();
380 if (nentries == 0)
381 exit(0);
382 /*
383 * sort proc list
384 */
385 qsort(kinfo, nentries, sizeof(KINFO), pscomp);
386 /*
387 * for each proc, call each variable output function.
388 */
389 for (i = lineno = 0; i < nentries; i++) {
390 KINFO *ki = &kinfo[i];
391
392 if (xflg == 0 && (KI_EPROC(ki)->e_tdev == NODEV ||
393 (KI_PROC(ki)->p_flag & P_CONTROLT ) == 0))
394 continue;
395 for (vent = vhead; vent; vent = vent->next) {
396 (vent->var->oproc)(ki, vent);
397 if (vent->next != NULL)
398 (void)putchar(' ');
399 }
400 (void)putchar('\n');
401 if (prtheader && lineno++ == prtheader - 4) {
402 (void)putchar('\n');
403 printheader();
404 lineno = 0;
405 }
406 }
407 exit(eval);
408 /* NOTREACHED */
409 }
410
411 static KINFO *
412 getkinfo_kvm(kd, what, flag, nentriesp, needuser)
413 kvm_t *kd;
414 int what, flag, *nentriesp, needuser;
415 {
416 struct kinfo_proc *kp;
417 KINFO *kinfo=NULL;
418 size_t i;
419
420 if ((kp = kvm_getprocs(kd, what, flag, nentriesp)) != 0)
421 {
422 if ((kinfo = malloc((*nentriesp) * sizeof(*kinfo))) == NULL)
423 err(1, NULL);
424 for (i = (*nentriesp); i-- > 0; kp++) {
425 kinfo[i].ki_p = kp;
426 if (needuser)
427 saveuser(&kinfo[i]);
428 }
429 }
430
431 return (kinfo);
432 }
433
434 static void
435 scanvars()
436 {
437 struct varent *vent;
438 VAR *v;
439 int i;
440
441 for (vent = vhead; vent; vent = vent->next) {
442 v = vent->var;
443 i = strlen(v->header);
444 if (v->width < i)
445 v->width = i;
446 totwidth += v->width + 1; /* +1 for space */
447 if (v->flag & USER)
448 needuser = 1;
449 if (v->flag & COMM)
450 needcomm = 1;
451 }
452 totwidth--;
453 }
454
455 static void
456 saveuser(ki)
457 KINFO *ki;
458 {
459 struct pstats pstats;
460 struct usave *usp;
461
462 usp = &ki->ki_u;
463 if (kvm_read(kd, (u_long)&KI_PROC(ki)->p_addr->u_stats,
464 (char *)&pstats, sizeof(pstats)) == sizeof(pstats)) {
465 /*
466 * The u-area might be swapped out, and we can't get
467 * at it because we have a crashdump and no swap.
468 * If it's here fill in these fields, otherwise, just
469 * leave them 0.
470 */
471 usp->u_start = pstats.p_start;
472 usp->u_ru = pstats.p_ru;
473 usp->u_cru = pstats.p_cru;
474 usp->u_valid = 1;
475 } else
476 usp->u_valid = 0;
477 }
478
479 static int
480 pscomp(a, b)
481 const void *a, *b;
482 {
483 int i;
484 #ifdef NEWVM
485 #define VSIZE(k) (KI_EPROC(k)->e_vm.vm_dsize + KI_EPROC(k)->e_vm.vm_ssize + \
486 KI_EPROC(k)->e_vm.vm_tsize)
487 #else
488 #define VSIZE(k) ((k)->ki_p->p_dsize + (k)->ki_p->p_ssize + (k)->ki_e->e_xsize)
489 #endif
490
491 if (sortby == SORTCPU)
492 return (getpcpu((KINFO *)b) - getpcpu((KINFO *)a));
493 if (sortby == SORTMEM)
494 return (VSIZE((KINFO *)b) - VSIZE((KINFO *)a));
495 i = KI_EPROC((KINFO *)a)->e_tdev - KI_EPROC((KINFO *)b)->e_tdev;
496 if (i == 0)
497 i = KI_PROC((KINFO *)a)->p_pid - KI_PROC((KINFO *)b)->p_pid;
498 return (i);
499 }
500
501 /*
502 * ICK (all for getopt), would rather hide the ugliness
503 * here than taint the main code.
504 *
505 * ps foo -> ps -foo
506 * ps 34 -> ps -p34
507 *
508 * The old convention that 't' with no trailing tty arg means the user's
509 * tty, is only supported if argv[1] doesn't begin with a '-'. This same
510 * feature is available with the option 'T', which takes no argument.
511 */
512 static char *
513 kludge_oldps_options(s)
514 char *s;
515 {
516 size_t len;
517 char *newopts, *ns, *cp;
518
519 len = strlen(s);
520 if ((newopts = ns = malloc(len + 3)) == NULL)
521 err(1, NULL);
522 /*
523 * options begin with '-'
524 */
525 if (*s != '-')
526 *ns++ = '-'; /* add option flag */
527 /*
528 * gaze to end of argv[1]
529 */
530 cp = s + len - 1;
531 /*
532 * if last letter is a 't' flag with no argument (in the context
533 * of the oldps options -- option string NOT starting with a '-' --
534 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
535 */
536 if (*cp == 't' && *s != '-')
537 *cp = 'T';
538 else {
539 /*
540 * otherwise check for trailing number, which *may* be a
541 * pid.
542 */
543 while (cp >= s && isdigit(*cp))
544 --cp;
545 }
546 cp++;
547 memmove(ns, s, (size_t)(cp - s)); /* copy up to trailing number */
548 ns += cp - s;
549 /*
550 * if there's a trailing number, and not a preceding 'p' (pid) or
551 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
552 */
553 if (isdigit(*cp) &&
554 (cp == s || (cp[-1] != 'U' && cp[-1] != 't' && cp[-1] != 'p' &&
555 (cp - 1 == s || cp[-2] != 't'))))
556 *ns++ = 'p';
557 /* and append the number */
558 (void)strcpy(ns, cp); /* XXX strcpy is safe */
559
560 return (newopts);
561 }
562
563 static void
564 usage()
565 {
566
567 (void)fprintf(stderr,
568 "usage:\t%s\n\t %s\n\t%s\n",
569 "ps [-aChjKlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty]",
570 "[-M core] [-N system] [-W swap] [-U username]",
571 "ps [-L]");
572 exit(1);
573 /* NOTREACHED */
574 }
575