ps.c revision 1.22 1 /* $NetBSD: ps.c,v 1.22 1998/07/27 17:06:48 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 #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.22 1998/07/27 17:06:48 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 <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 int main __P((int, char *[]));
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 gid_t egid = getegid();
120 int all, ch, flag, i, fmt, lineno, nentries;
121 int prtheader, wflag, what, xflg;
122 char *nlistf, *memf, *swapf, errbuf[_POSIX2_LINE_MAX];
123 const 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 all = fmt = prtheader = wflag = xflg = 0;
138 pid = -1;
139 uid = (uid_t) -1;
140 ttydev = NODEV;
141 memf = nlistf = swapf = NULL;
142 while ((ch = getopt(argc, argv,
143 "acCeghjLlM:mN:O:o:p:rSTt:uvW:wx")) != -1)
144 switch((char)ch) {
145 case 'a':
146 all = 1;
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 'L':
168 showkey();
169 exit(0);
170 case 'l':
171 parsefmt(lfmt);
172 fmt = 1;
173 lfmt[0] = '\0';
174 break;
175 case 'M':
176 memf = optarg;
177 break;
178 case 'm':
179 sortby = SORTMEM;
180 break;
181 case 'N':
182 nlistf = optarg;
183 break;
184 case 'O':
185 parsefmt(o1);
186 parsefmt(optarg);
187 parsefmt(o2);
188 o1[0] = o2[0] = '\0';
189 fmt = 1;
190 break;
191 case 'o':
192 parsefmt(optarg);
193 fmt = 1;
194 break;
195 case 'p':
196 pid = atol(optarg);
197 xflg = 1;
198 break;
199 case 'r':
200 sortby = SORTCPU;
201 break;
202 case 'S':
203 sumrusage = 1;
204 break;
205 case 'T':
206 if ((ttname = ttyname(STDIN_FILENO)) == NULL)
207 errx(1, "stdin: not a terminal");
208 goto tty;
209 case 't':
210 ttname = optarg;
211 tty: {
212 struct stat sb;
213 char *ttypath, pathbuf[MAXPATHLEN];
214
215 if (strcmp(optarg, "co") == 0)
216 ttypath = _PATH_CONSOLE;
217 else if (*optarg != '/')
218 (void)snprintf(ttypath = pathbuf,
219 sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
220 else
221 ttypath = optarg;
222 if (stat(ttypath, &sb) == -1)
223 err(1, "%s", ttypath);
224 if (!S_ISCHR(sb.st_mode))
225 errx(1, "%s: not a terminal", ttypath);
226 ttydev = sb.st_rdev;
227 break;
228 }
229 case 'u':
230 parsefmt(ufmt);
231 sortby = SORTCPU;
232 fmt = 1;
233 ufmt[0] = '\0';
234 break;
235 case 'v':
236 parsefmt(vfmt);
237 sortby = SORTMEM;
238 fmt = 1;
239 vfmt[0] = '\0';
240 break;
241 case 'W':
242 swapf = optarg;
243 break;
244 case 'w':
245 if (wflag)
246 termwidth = UNLIMITED;
247 else if (termwidth < 131)
248 termwidth = 131;
249 wflag++;
250 break;
251 case 'x':
252 xflg = 1;
253 break;
254 case '?':
255 default:
256 usage();
257 }
258 argc -= optind;
259 argv += optind;
260
261 #define BACKWARD_COMPATIBILITY
262 #ifdef BACKWARD_COMPATIBILITY
263 if (*argv) {
264 nlistf = *argv;
265 if (*++argv) {
266 memf = *argv;
267 if (*++argv)
268 swapf = *argv;
269 }
270 }
271 #endif
272 /*
273 * Discard setgid privileges. If not the running kernel, we toss
274 * them away totally so that bad guys can't print interesting stuff
275 * from kernel memory, otherwise switch back to kmem for the
276 * duration of the kvm_openfiles() call.
277 */
278 if (nlistf != NULL || memf != NULL || swapf != NULL)
279 (void)setgid(getgid());
280 else
281 (void)setegid(egid);
282
283 kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
284 if (kd == 0)
285 errx(1, "%s", errbuf);
286
287 if (nlistf == NULL && memf == NULL && swapf == NULL)
288 (void)setgid(getgid());
289
290 if (!fmt)
291 parsefmt(dfmt);
292
293 if (!all && ttydev == NODEV && pid == -1) /* XXX - should be cleaner */
294 uid = getuid();
295
296 /*
297 * scan requested variables, noting what structures are needed,
298 * and adjusting header widths as appropiate.
299 */
300 scanvars();
301 /*
302 * get proc list
303 */
304 if (uid != (uid_t) -1) {
305 what = KERN_PROC_UID;
306 flag = uid;
307 } else if (ttydev != NODEV) {
308 what = KERN_PROC_TTY;
309 flag = ttydev;
310 } else if (pid != -1) {
311 what = KERN_PROC_PID;
312 flag = pid;
313 } else {
314 what = KERN_PROC_ALL;
315 flag = 0;
316 }
317 /*
318 * select procs
319 */
320 if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0)
321 errx(1, "%s", kvm_geterr(kd));
322 if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
323 err(1, "%s", "");
324 for (i = nentries; --i >= 0; ++kp) {
325 kinfo[i].ki_p = kp;
326 if (needuser)
327 saveuser(&kinfo[i]);
328 }
329 /*
330 * print header
331 */
332 printheader();
333 if (nentries == 0)
334 exit(0);
335 /*
336 * sort proc list
337 */
338 qsort(kinfo, nentries, sizeof(KINFO), pscomp);
339 /*
340 * for each proc, call each variable output function.
341 */
342 for (i = lineno = 0; i < nentries; i++) {
343 KINFO *ki = &kinfo[i];
344
345 if (xflg == 0 && (KI_EPROC(ki)->e_tdev == NODEV ||
346 (KI_PROC(ki)->p_flag & P_CONTROLT ) == 0))
347 continue;
348 for (vent = vhead; vent; vent = vent->next) {
349 (vent->var->oproc)(ki, vent);
350 if (vent->next != NULL)
351 (void)putchar(' ');
352 }
353 (void)putchar('\n');
354 if (prtheader && lineno++ == prtheader - 4) {
355 (void)putchar('\n');
356 printheader();
357 lineno = 0;
358 }
359 }
360 exit(eval);
361 }
362
363 static void
364 scanvars()
365 {
366 struct varent *vent;
367 VAR *v;
368 int i;
369
370 for (vent = vhead; vent; vent = vent->next) {
371 v = vent->var;
372 i = strlen(v->header);
373 if (v->width < i)
374 v->width = i;
375 totwidth += v->width + 1; /* +1 for space */
376 if (v->flag & USER)
377 needuser = 1;
378 if (v->flag & COMM)
379 needcomm = 1;
380 }
381 totwidth--;
382 }
383
384 static void
385 saveuser(ki)
386 KINFO *ki;
387 {
388 struct pstats pstats;
389 struct usave *usp;
390
391 usp = &ki->ki_u;
392 if (kvm_read(kd, (u_long)&KI_PROC(ki)->p_addr->u_stats,
393 (char *)&pstats, sizeof(pstats)) == sizeof(pstats)) {
394 /*
395 * The u-area might be swapped out, and we can't get
396 * at it because we have a crashdump and no swap.
397 * If it's here fill in these fields, otherwise, just
398 * leave them 0.
399 */
400 usp->u_start = pstats.p_start;
401 usp->u_ru = pstats.p_ru;
402 usp->u_cru = pstats.p_cru;
403 usp->u_valid = 1;
404 } else
405 usp->u_valid = 0;
406 }
407
408 static int
409 pscomp(a, b)
410 const void *a, *b;
411 {
412 int i;
413 #ifdef NEWVM
414 #define VSIZE(k) (KI_EPROC(k)->e_vm.vm_dsize + KI_EPROC(k)->e_vm.vm_ssize + \
415 KI_EPROC(k)->e_vm.vm_tsize)
416 #else
417 #define VSIZE(k) ((k)->ki_p->p_dsize + (k)->ki_p->p_ssize + (k)->ki_e->e_xsize)
418 #endif
419
420 if (sortby == SORTCPU)
421 return (getpcpu((KINFO *)b) - getpcpu((KINFO *)a));
422 if (sortby == SORTMEM)
423 return (VSIZE((KINFO *)b) - VSIZE((KINFO *)a));
424 i = KI_EPROC((KINFO *)a)->e_tdev - KI_EPROC((KINFO *)b)->e_tdev;
425 if (i == 0)
426 i = KI_PROC((KINFO *)a)->p_pid - KI_PROC((KINFO *)b)->p_pid;
427 return (i);
428 }
429
430 /*
431 * ICK (all for getopt), would rather hide the ugliness
432 * here than taint the main code.
433 *
434 * ps foo -> ps -foo
435 * ps 34 -> ps -p34
436 *
437 * The old convention that 't' with no trailing tty arg means the users
438 * tty, is only supported if argv[1] doesn't begin with a '-'. This same
439 * feature is available with the option 'T', which takes no argument.
440 */
441 static char *
442 kludge_oldps_options(s)
443 char *s;
444 {
445 size_t len;
446 char *newopts, *ns, *cp;
447
448 len = strlen(s);
449 if ((newopts = ns = malloc(len + 3)) == NULL)
450 err(1, "%s", "");
451 /*
452 * options begin with '-'
453 */
454 if (*s != '-')
455 *ns++ = '-'; /* add option flag */
456 /*
457 * gaze to end of argv[1]
458 */
459 cp = s + len - 1;
460 /*
461 * if last letter is a 't' flag with no argument (in the context
462 * of the oldps options -- option string NOT starting with a '-' --
463 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
464 */
465 if (*cp == 't' && *s != '-')
466 *cp = 'T';
467 else {
468 /*
469 * otherwise check for trailing number, which *may* be a
470 * pid.
471 */
472 while (cp >= s && isdigit(*cp))
473 --cp;
474 }
475 cp++;
476 memmove(ns, s, (size_t)(cp - s)); /* copy up to trailing number */
477 ns += cp - s;
478 /*
479 * if there's a trailing number, and not a preceding 'p' (pid) or
480 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
481 */
482 if (isdigit(*cp) && (cp == s || (cp[-1] != 't' && cp[-1] != 'p' &&
483 (cp - 1 == s || cp[-2] != 't'))))
484 *ns++ = 'p';
485 /* and append the number */
486 (void)strcpy(ns, cp); /* XXX strcpy is safe */
487
488 return (newopts);
489 }
490
491 static void
492 usage()
493 {
494
495 (void)fprintf(stderr,
496 "usage:\t%s\n\t %s\n\t%s\n",
497 "ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty]",
498 "[-M core] [-N system] [-W swap]",
499 "ps [-L]");
500 exit(1);
501 }
502