ps: Sync usage() to SYNOPSIS
[dragonfly.git] / bin / ps / ps.c
CommitLineData
984263bc
MD
1/*-
2 * Copyright (c) 1990, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
1de703da
MD
32 *
33 * @(#) Copyright (c) 1990, 1993, 1994 The Regents of the University of California. All rights reserved.
34 * @(#)ps.c 8.4 (Berkeley) 4/2/94
35 * $FreeBSD: src/bin/ps/ps.c,v 1.30.2.6 2002/07/04 08:30:37 sobomax Exp $
9915ae30 36 * $DragonFly: src/bin/ps/ps.c,v 1.25 2008/01/10 14:18:39 matthias Exp $
984263bc
MD
37 */
38
984263bc
MD
39#include <sys/param.h>
40#include <sys/user.h>
41#include <sys/time.h>
023c70f2 42#include <sys/queue.h>
984263bc
MD
43#include <sys/resource.h>
44#include <sys/stat.h>
45#include <sys/ioctl.h>
46#include <sys/sysctl.h>
9915ae30 47#include <sys/mount.h>
984263bc
MD
48
49#include <ctype.h>
50#include <err.h>
51#include <errno.h>
52#include <fcntl.h>
53#include <kvm.h>
54#include <limits.h>
55#include <locale.h>
56#include <nlist.h>
57#include <paths.h>
58#include <stdio.h>
59#include <stdlib.h>
60#include <string.h>
61#include <unistd.h>
62#include <pwd.h>
63#include <utmp.h>
64
65#include "ps.h"
66
67#define SEP ", \t" /* username separators */
68
69KINFO *kinfo;
70struct varent *vhead, *vtail;
71
72int eval; /* exit value */
73int cflag; /* -c */
74int rawcpu; /* -C */
75int sumrusage; /* -S */
76int termwidth; /* width of screen (0 == infinity) */
77int totwidth; /* calculated width of requested variables */
18988e7a 78int numcpus; /* hw.ncpu */
984263bc
MD
79
80static int needuser, needcomm, needenv;
81#if defined(LAZY_PS)
82static int forceuread=0;
2b0645c3 83#define PS_ARGS "aCcefgHhjLlM:mN:O:o:p:rSTt:U:uvwx"
984263bc
MD
84#else
85static int forceuread=1;
2b0645c3 86#define PS_ARGS "aCcegHhjLlM:mN:O:o:p:rSTt:U:uvwx"
984263bc
MD
87#endif
88
7bbde2b7 89enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
984263bc 90
c443019b 91static const char *getfmt (char **(*)(kvm_t *, const struct kinfo_proc *, int),
9dbf638f
DR
92 KINFO *, char *, int);
93static char *kludge_oldps_options (char *);
94static int pscomp (const void *, const void *);
95static void saveuser (KINFO *);
96static void scanvars (void);
97static void dynsizevars (KINFO *);
98static void sizevars (void);
9915ae30 99static int check_procfs(void);
9dbf638f 100static void usage (void);
984263bc
MD
101static uid_t *getuids(const char *, int *);
102
0d4b6715 103struct timeval btime;
0d4b6715 104
c443019b
CP
105static char dfmt[] = "pid tt state time command";
106static char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
107static char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
108static char o1[] = "pid";
109static char o2[] = "tt state time command";
110static char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
111static char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
984263bc
MD
112
113kvm_t *kd;
114
115int
b5744197 116main(int argc, char **argv)
984263bc
MD
117{
118 struct kinfo_proc *kp;
119 struct varent *vent;
120 struct winsize ws;
121 dev_t ttydev;
122 pid_t pid;
123 uid_t *uids;
2b0645c3
MD
124 int all, ch, flag, i, fmt, ofmt, lineno, nentries, nocludge, dropgid;
125 int prtheader, wflag, what, xflg, uid, nuids, showtid;
c443019b
CP
126 char errbuf[_POSIX2_LINE_MAX];
127 const char *cp, *nlistf, *memf;
18988e7a
MD
128 size_t btime_size = sizeof(struct timeval);
129 size_t numcpus_size = sizeof(numcpus);
984263bc 130
f9af826d 131 setlocale(LC_ALL, "");
984263bc
MD
132
133 if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
134 ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
135 ioctl(STDIN_FILENO, TIOCGWINSZ, (char *)&ws) == -1) ||
136 ws.ws_col == 0)
137 termwidth = 79;
138 else
139 termwidth = ws.ws_col - 1;
140
141 /*
142 * Don't apply a kludge if the first argument is an option taking an
143 * argument
144 */
145 if (argc > 1) {
146 nocludge = 0;
147 if (argv[1][0] == '-') {
148 for (cp = PS_ARGS; *cp != '\0'; cp++) {
149 if (*cp != ':')
150 continue;
151 if (*(cp - 1) == argv[1][1]) {
152 nocludge = 1;
153 break;
154 }
155 }
156 }
157 if (nocludge == 0)
158 argv[1] = kludge_oldps_options(argv[1]);
159 }
160
2b0645c3 161 all = fmt = ofmt = prtheader = wflag = xflg = showtid = 0;
984263bc
MD
162 pid = -1;
163 nuids = 0;
164 uids = NULL;
165 ttydev = NODEV;
166 dropgid = 0;
167 memf = nlistf = _PATH_DEVNULL;
168 while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
169 switch((char)ch) {
170 case 'a':
171 all = 1;
172 break;
173 case 'C':
174 rawcpu = 1;
175 break;
176 case 'c':
177 cflag = 1;
178 break;
179 case 'e': /* XXX set ufmt */
180 needenv = 1;
181 break;
182 case 'g':
183 break; /* no-op */
2b0645c3
MD
184 case 'H':
185 showtid = KERN_PROC_FLAG_LWP;
186 break;
984263bc
MD
187 case 'h':
188 prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
189 break;
190 case 'j':
191 parsefmt(jfmt);
192 fmt = 1;
193 jfmt[0] = '\0';
194 break;
195 case 'L':
196 showkey();
197 exit(0);
198 case 'l':
199 parsefmt(lfmt);
200 fmt = 1;
201 lfmt[0] = '\0';
202 break;
203 case 'M':
204 memf = optarg;
205 dropgid = 1;
206 break;
207 case 'm':
208 sortby = SORTMEM;
209 break;
210 case 'N':
211 nlistf = optarg;
212 dropgid = 1;
213 break;
214 case 'O':
215 parsefmt(o1);
216 parsefmt(optarg);
217 parsefmt(o2);
218 o1[0] = o2[0] = '\0';
219 fmt = 1;
220 break;
221 case 'o':
222 parsefmt(optarg);
2b0645c3 223 fmt = ofmt = 1;
984263bc
MD
224 break;
225#if defined(LAZY_PS)
226 case 'f':
227 if (getuid() == 0 || getgid() == 0)
228 forceuread = 1;
229 break;
230#endif
231 case 'p':
232 pid = atol(optarg);
233 xflg = 1;
234 break;
235 case 'r':
236 sortby = SORTCPU;
237 break;
238 case 'S':
239 sumrusage = 1;
240 break;
241 case 'T':
242 if ((optarg = ttyname(STDIN_FILENO)) == NULL)
243 errx(1, "stdin: not a terminal");
244 /* FALLTHROUGH */
245 case 't': {
246 struct stat sb;
c443019b
CP
247 char pathbuf[PATH_MAX];
248 const char *ttypath;
984263bc
MD
249
250 if (strcmp(optarg, "co") == 0)
251 ttypath = _PATH_CONSOLE;
c443019b
CP
252 else if (*optarg != '/') {
253 snprintf(pathbuf,
984263bc 254 sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
c443019b
CP
255 ttypath = pathbuf;
256 } else
984263bc
MD
257 ttypath = optarg;
258 if (stat(ttypath, &sb) == -1)
259 err(1, "%s", ttypath);
260 if (!S_ISCHR(sb.st_mode))
261 errx(1, "%s: not a terminal", ttypath);
262 ttydev = sb.st_rdev;
263 break;
264 }
265 case 'U':
266 uids = getuids(optarg, &nuids);
267 xflg++; /* XXX: intuitive? */
268 break;
269 case 'u':
270 parsefmt(ufmt);
271 sortby = SORTCPU;
272 fmt = 1;
273 ufmt[0] = '\0';
274 break;
275 case 'v':
276 parsefmt(vfmt);
277 sortby = SORTMEM;
278 fmt = 1;
279 vfmt[0] = '\0';
280 break;
281 case 'w':
282 if (wflag)
283 termwidth = UNLIMITED;
284 else if (termwidth < 131)
285 termwidth = 131;
286 wflag++;
287 break;
288 case 'x':
289 xflg = 1;
290 break;
291 case '?':
292 default:
293 usage();
294 }
295 argc -= optind;
296 argv += optind;
297
9915ae30
MS
298 /*
299 * If the user specified ps -e then they want a copy of the process
300 * environment kvm_getenvv(3) attempts to open /proc/<pid>/mem.
301 * Check to make sure that procfs is mounted on /proc, otherwise
302 * print a warning informing the user that output will be incomplete.
303 */
304 if (needenv == 1 && check_procfs() == 0)
305 warnx("Process environment requires procfs(5)");
306
984263bc
MD
307#define BACKWARD_COMPATIBILITY
308#ifdef BACKWARD_COMPATIBILITY
309 if (*argv) {
310 nlistf = *argv;
311 if (*++argv) {
312 memf = *argv;
313 }
314 }
315#endif
316 /*
317 * Discard setgid privileges if not the running kernel so that bad
318 * guys can't print interesting stuff from kernel memory.
319 */
320 if (dropgid) {
321 setgid(getgid());
322 setuid(getuid());
323 }
324
325 kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
326 if (kd == 0)
327 errx(1, "%s", errbuf);
328
329 if (!fmt)
330 parsefmt(dfmt);
331
2b0645c3
MD
332 /*
333 * Add TID to output format if requested unless user-specific format
334 * selected.
335 */
336 if (showtid && !ofmt)
337 insert_tid_in_fmt();
338
984263bc
MD
339 /* XXX - should be cleaner */
340 if (!all && ttydev == NODEV && pid == -1 && !nuids) {
341 if ((uids = malloc(sizeof (*uids))) == NULL)
342 errx(1, "malloc: %s", strerror(errno));
343 nuids = 1;
344 *uids = getuid();
345 }
346
347 /*
348 * scan requested variables, noting what structures are needed,
349 * and adjusting header widths as appropriate.
350 */
351 scanvars();
0d4b6715
HP
352
353 /*
354 * Get boot time
355 */
356 if (sysctlbyname("kern.boottime", &btime, &btime_size, NULL, 0) < 0) {
357 perror("sysctl: kern.boottime");
358 exit(EXIT_FAILURE);
359 }
360
18988e7a
MD
361 /*
362 * Get number of cpus
363 */
601f7af5 364 if (sysctlbyname("hw.ncpu", &numcpus, &numcpus_size, NULL, 0) < 0)
18988e7a
MD
365 numcpus = 1;
366
984263bc
MD
367 /*
368 * get proc list
369 */
370 if (nuids == 1) {
371 what = KERN_PROC_UID;
372 flag = *uids;
373 } else if (ttydev != NODEV) {
374 what = KERN_PROC_TTY;
375 flag = ttydev;
376 } else if (pid != -1) {
377 what = KERN_PROC_PID;
378 flag = pid;
379 } else {
380 what = KERN_PROC_ALL;
381 flag = 0;
382 }
2b0645c3
MD
383 what |= showtid;
384
984263bc
MD
385 /*
386 * select procs
387 */
78d47ffa 388 if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == NULL)
984263bc
MD
389 errx(1, "%s", kvm_geterr(kd));
390 if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
391 err(1, NULL);
392 for (i = nentries; --i >= 0; ++kp) {
5dfd06ac 393 kinfo[i].ki_proc = kp;
984263bc
MD
394 if (needuser)
395 saveuser(&kinfo[i]);
396 dynsizevars(&kinfo[i]);
397 }
398
399 sizevars();
400
401 /*
402 * print header
403 */
404 printheader();
405 if (nentries == 0)
406 exit(1);
407 /*
408 * sort proc list
409 */
410 qsort(kinfo, nentries, sizeof(KINFO), pscomp);
411 /*
412 * for each proc, call each variable output function.
413 */
414 for (i = lineno = 0; i < nentries; i++) {
5dfd06ac
SS
415 if (xflg == 0 && (KI_PROC(&kinfo[i], tdev) == NODEV ||
416 (KI_PROC(&kinfo[i], flags) & P_CONTROLT ) == 0))
984263bc
MD
417 continue;
418 if (nuids > 1) {
419 for (uid = 0; uid < nuids; uid++)
5dfd06ac 420 if (KI_PROC(&kinfo[i], uid) ==
984263bc
MD
421 uids[uid])
422 break;
423 if (uid == nuids)
424 continue;
425 }
023c70f2 426 STAILQ_FOREACH(vent, &var_head, link) {
984263bc 427 (vent->var->oproc)(&kinfo[i], vent);
023c70f2 428 if (STAILQ_NEXT(vent, link) != NULL)
f9af826d 429 putchar(' ');
984263bc 430 }
f9af826d 431 putchar('\n');
984263bc 432 if (prtheader && lineno++ == prtheader - 4) {
f9af826d 433 putchar('\n');
984263bc
MD
434 printheader();
435 lineno = 0;
436 }
437 }
438 free(uids);
439
440 exit(eval);
441}
442
443uid_t *
444getuids(const char *arg, int *nuids)
445{
446 char name[UT_NAMESIZE + 1];
447 struct passwd *pwd;
448 uid_t *uids, *moreuids;
c443019b
CP
449 size_t l;
450 int alloc;
984263bc
MD
451
452
453 alloc = 0;
454 *nuids = 0;
455 uids = NULL;
456 for (; (l = strcspn(arg, SEP)) > 0; arg += l + strspn(arg + l, SEP)) {
457 if (l >= sizeof name) {
d40c67b6 458 warnx("%.*s: name too long", (int)l, arg);
984263bc
MD
459 continue;
460 }
461 strncpy(name, arg, l);
462 name[l] = '\0';
463 if ((pwd = getpwnam(name)) == NULL) {
464 warnx("%s: no such user", name);
465 continue;
466 }
467 if (*nuids >= alloc) {
468 alloc = (alloc + 1) << 1;
469 moreuids = realloc(uids, alloc * sizeof (*uids));
470 if (moreuids == NULL) {
471 free(uids);
472 errx(1, "realloc: %s", strerror(errno));
473 }
474 uids = moreuids;
475 }
476 uids[(*nuids)++] = pwd->pw_uid;
477 }
478 endpwent();
479
480 if (!*nuids)
481 errx(1, "No users specified");
482
483 return uids;
484}
485
486static void
b5744197 487scanvars(void)
984263bc
MD
488{
489 struct varent *vent;
023c70f2 490 const VAR *v;
984263bc 491
023c70f2 492 STAILQ_FOREACH(vent, &var_head, link) {
984263bc
MD
493 v = vent->var;
494 if (v->flag & DSIZ) {
f5df644b 495 vent->dwidth = vent->width;
023c70f2 496 vent->width = 0;
984263bc
MD
497 }
498 if (v->flag & USER)
499 needuser = 1;
500 if (v->flag & COMM)
501 needcomm = 1;
502 }
503}
504
505static void
b5744197 506dynsizevars(KINFO *ki)
984263bc
MD
507{
508 struct varent *vent;
023c70f2 509 const VAR *v;
984263bc
MD
510 int i;
511
023c70f2 512 STAILQ_FOREACH(vent, &var_head, link) {
984263bc
MD
513 v = vent->var;
514 if (!(v->flag & DSIZ))
515 continue;
516 i = (v->sproc)( ki);
f5df644b 517 if (vent->width < i)
023c70f2 518 vent->width = i;
f5df644b 519 if (vent->width > vent->dwidth)
023c70f2 520 vent->width = vent->dwidth;
984263bc
MD
521 }
522}
523
524static void
b5744197 525sizevars(void)
984263bc
MD
526{
527 struct varent *vent;
984263bc
MD
528 int i;
529
023c70f2 530 STAILQ_FOREACH(vent, &var_head, link) {
023c70f2
JS
531 i = strlen(vent->header);
532 if (vent->width < i)
533 vent->width = i;
534 totwidth += vent->width + 1; /* +1 for space */
984263bc
MD
535 }
536 totwidth--;
537}
538
c443019b
CP
539static const char *
540getfmt(char **(*fn) (kvm_t *, const struct kinfo_proc *, int), KINFO *ki, char
b5744197 541 *comm, int maxlen)
984263bc 542{
c443019b 543 const char *s;
984263bc
MD
544
545 if ((s =
5dfd06ac 546 fmt_argv((*fn)(kd, ki->ki_proc, termwidth), comm, maxlen)) == NULL)
984263bc
MD
547 err(1, NULL);
548 return (s);
549}
550
984263bc 551static void
b5744197 552saveuser(KINFO *ki)
984263bc 553{
984263bc
MD
554 /*
555 * save arguments if needed
556 */
5dfd06ac
SS
557 if (needcomm) {
558 ki->ki_args = getfmt(kvm_getargv, ki, KI_PROC(ki, comm),
984263bc 559 MAXCOMLEN);
984263bc
MD
560 } else {
561 ki->ki_args = NULL;
562 }
5dfd06ac 563 if (needenv) {
2038fb68 564 ki->ki_env = getfmt(kvm_getenvv, ki, NULL, 0);
984263bc
MD
565 } else {
566 ki->ki_env = NULL;
567 }
568}
569
570static int
b5744197 571pscomp(const void *a, const void *b)
984263bc
MD
572{
573 int i;
5dfd06ac
SS
574#define VSIZE(k) (KI_PROC(k, vm_dsize) + KI_PROC(k, vm_ssize) + \
575 KI_PROC(k, vm_tsize))
984263bc 576
7bbde2b7 577#if 0
d40c67b6 578 if (sortby == SORTIAC)
352f5709 579 return (KI_PROC((const KINFO *)a)->p_usdata.bsd4.interactive - KI_PROC((const KINFO *)b)->p_usdata.bsd4.interactive);
7bbde2b7 580#endif
984263bc 581 if (sortby == SORTCPU)
c443019b 582 return (getpcpu((const KINFO *)b) - getpcpu((const KINFO *)a));
984263bc 583 if (sortby == SORTMEM)
c443019b 584 return (VSIZE((const KINFO *)b) - VSIZE((const KINFO *)a));
5dfd06ac 585 i = KI_PROC((const KINFO *)a, tdev) - KI_PROC((const KINFO *)b, tdev);
984263bc 586 if (i == 0)
5dfd06ac 587 i = KI_PROC((const KINFO *)a, pid) - KI_PROC((const KINFO *)b, pid);
984263bc
MD
588 return (i);
589}
590
591/*
592 * ICK (all for getopt), would rather hide the ugliness
593 * here than taint the main code.
594 *
595 * ps foo -> ps -foo
596 * ps 34 -> ps -p34
597 *
598 * The old convention that 't' with no trailing tty arg means the users
599 * tty, is only supported if argv[1] doesn't begin with a '-'. This same
600 * feature is available with the option 'T', which takes no argument.
601 */
602static char *
b5744197 603kludge_oldps_options(char *s)
984263bc
MD
604{
605 size_t len;
606 char *newopts, *ns, *cp;
607
608 len = strlen(s);
609 if ((newopts = ns = malloc(len + 2)) == NULL)
610 err(1, NULL);
611 /*
612 * options begin with '-'
613 */
614 if (*s != '-')
615 *ns++ = '-'; /* add option flag */
616 /*
617 * gaze to end of argv[1]
618 */
619 cp = s + len - 1;
620 /*
621 * if last letter is a 't' flag with no argument (in the context
622 * of the oldps options -- option string NOT starting with a '-' --
623 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
624 *
625 * However, if a flag accepting a string argument is found in the
626 * option string, the remainder of the string is the argument to
627 * that flag; do not modify that argument.
628 */
629 if (strcspn(s, "MNOoU") == len && *cp == 't' && *s != '-')
630 *cp = 'T';
631 else {
632 /*
633 * otherwise check for trailing number, which *may* be a
634 * pid.
635 */
636 while (cp >= s && isdigit(*cp))
637 --cp;
638 }
639 cp++;
640 memmove(ns, s, (size_t)(cp - s)); /* copy up to trailing number */
641 ns += cp - s;
642 /*
643 * if there's a trailing number, and not a preceding 'p' (pid) or
644 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
645 */
646 if (isdigit(*cp) &&
647 (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
648 (cp - 1 == s || cp[-2] != 't'))
649 *ns++ = 'p';
f9af826d 650 strcpy(ns, cp); /* and append the number */
984263bc
MD
651
652 return (newopts);
653}
654
9915ae30
MS
655static int
656check_procfs(void)
657{
658 struct statfs mnt;
659
660 if (statfs("/proc", &mnt) < 0)
661 return (0);
662 if (strcmp(mnt.f_fstypename, "procfs") != 0)
663 return (0);
664 return (1);
665}
666
984263bc 667static void
b5744197 668usage(void)
984263bc
MD
669{
670
f9af826d 671 fprintf(stderr, "%s\n%s\n%s\n",
d7385f75
TN
672 "usage: ps [-aCcefhHjlmrSTuvwx] [-M core] [-N system] [-O fmt] [-o fmt] [-p pid]",
673 " [-t tty] [-U username]",
984263bc
MD
674 " ps [-L]");
675 exit(1);
676}