Merge from vendor branch DIFFUTILS:
[dragonfly.git] / bin / ps / ps.c
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.
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 $
36  * $DragonFly: src/bin/ps/ps.c,v 1.6 2004/03/19 17:47:49 cpressey Exp $
37  */
38
39 #include <sys/param.h>
40 #include <sys/user.h>
41 #include <sys/time.h>
42 #include <sys/resource.h>
43 #include <sys/stat.h>
44 #include <sys/ioctl.h>
45 #include <sys/sysctl.h>
46
47 #include <ctype.h>
48 #include <err.h>
49 #include <errno.h>
50 #include <fcntl.h>
51 #include <kvm.h>
52 #include <limits.h>
53 #include <locale.h>
54 #include <nlist.h>
55 #include <paths.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <unistd.h>
60 #include <pwd.h>
61 #include <utmp.h>
62
63 #include "ps.h"
64
65 #define SEP ", \t"              /* username separators */
66
67 KINFO *kinfo;
68 struct varent *vhead, *vtail;
69
70 int     eval;                   /* exit value */
71 int     cflag;                  /* -c */
72 int     rawcpu;                 /* -C */
73 int     sumrusage;              /* -S */
74 int     termwidth;              /* width of screen (0 == infinity) */
75 int     totwidth;               /* calculated width of requested variables */
76
77 static int needuser, needcomm, needenv;
78 #if defined(LAZY_PS)
79 static int forceuread=0;
80 #define PS_ARGS "aCcefghjLlM:mN:O:o:p:rSTt:U:uvwx"
81 #else
82 static int forceuread=1;
83 #define PS_ARGS "aCceghjLlM:mN:O:o:p:rSTt:U:uvwx"
84 #endif
85
86 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
87
88 static const char *getfmt (char **(*)(kvm_t *, const struct kinfo_proc *, int),
89                     KINFO *, char *, int);
90 static char     *kludge_oldps_options (char *);
91 static int       pscomp (const void *, const void *);
92 static void      saveuser (KINFO *);
93 static void      scanvars (void);
94 static void      dynsizevars (KINFO *);
95 static void      sizevars (void);
96 static void      usage (void);
97 static uid_t    *getuids(const char *, int *);
98
99 static char dfmt[] = "pid tt state time command";
100 static char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
101 static char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
102 static char   o1[] = "pid";
103 static char   o2[] = "tt state time command";
104 static char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
105 static char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
106
107 kvm_t *kd;
108
109 int
110 main(int argc, char **argv)
111 {
112         struct kinfo_proc *kp;
113         struct varent *vent;
114         struct winsize ws;
115         dev_t ttydev;
116         pid_t pid;
117         uid_t *uids;
118         int all, ch, flag, i, fmt, lineno, nentries, nocludge, dropgid;
119         int prtheader, wflag, what, xflg, uid, nuids;
120         char errbuf[_POSIX2_LINE_MAX];
121         const char *cp, *nlistf, *memf;
122
123         (void) setlocale(LC_ALL, "");
124
125         if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
126              ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
127              ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
128              ws.ws_col == 0)
129                 termwidth = 79;
130         else
131                 termwidth = ws.ws_col - 1;
132
133         /*
134          * Don't apply a kludge if the first argument is an option taking an
135          * argument
136          */
137         if (argc > 1) {
138                 nocludge = 0;
139                 if (argv[1][0] == '-') {
140                         for (cp = PS_ARGS; *cp != '\0'; cp++) {
141                                 if (*cp != ':')
142                                         continue;
143                                 if (*(cp - 1) == argv[1][1]) {
144                                         nocludge = 1;
145                                         break;
146                                 }
147                         }
148                 }
149                 if (nocludge == 0)
150                         argv[1] = kludge_oldps_options(argv[1]);
151         }
152
153         all = fmt = prtheader = wflag = xflg = 0;
154         pid = -1;
155         nuids = 0;
156         uids = NULL;
157         ttydev = NODEV;
158         dropgid = 0;
159         memf = nlistf = _PATH_DEVNULL;
160         while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
161                 switch((char)ch) {
162                 case 'a':
163                         all = 1;
164                         break;
165                 case 'C':
166                         rawcpu = 1;
167                         break;
168                 case 'c':
169                         cflag = 1;
170                         break;
171                 case 'e':                       /* XXX set ufmt */
172                         needenv = 1;
173                         break;
174                 case 'g':
175                         break;                  /* no-op */
176                 case 'h':
177                         prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
178                         break;
179                 case 'j':
180                         parsefmt(jfmt);
181                         fmt = 1;
182                         jfmt[0] = '\0';
183                         break;
184                 case 'L':
185                         showkey();
186                         exit(0);
187                 case 'l':
188                         parsefmt(lfmt);
189                         fmt = 1;
190                         lfmt[0] = '\0';
191                         break;
192                 case 'M':
193                         memf = optarg;
194                         dropgid = 1;
195                         break;
196                 case 'm':
197                         sortby = SORTMEM;
198                         break;
199                 case 'N':
200                         nlistf = optarg;
201                         dropgid = 1;
202                         break;
203                 case 'O':
204                         parsefmt(o1);
205                         parsefmt(optarg);
206                         parsefmt(o2);
207                         o1[0] = o2[0] = '\0';
208                         fmt = 1;
209                         break;
210                 case 'o':
211                         parsefmt(optarg);
212                         fmt = 1;
213                         break;
214 #if defined(LAZY_PS)
215                 case 'f':
216                         if (getuid() == 0 || getgid() == 0)
217                             forceuread = 1;
218                         break;
219 #endif
220                 case 'p':
221                         pid = atol(optarg);
222                         xflg = 1;
223                         break;
224                 case 'r':
225                         sortby = SORTCPU;
226                         break;
227                 case 'S':
228                         sumrusage = 1;
229                         break;
230                 case 'T':
231                         if ((optarg = ttyname(STDIN_FILENO)) == NULL)
232                                 errx(1, "stdin: not a terminal");
233                         /* FALLTHROUGH */
234                 case 't': {
235                         struct stat sb;
236                         char pathbuf[PATH_MAX];
237                         const char *ttypath;
238
239                         if (strcmp(optarg, "co") == 0)
240                                 ttypath = _PATH_CONSOLE;
241                         else if (*optarg != '/') {
242                                 snprintf(pathbuf,
243                                     sizeof(pathbuf), "%s%s", _PATH_TTY, optarg);
244                                 ttypath = pathbuf;
245                         } else
246                                 ttypath = optarg;
247                         if (stat(ttypath, &sb) == -1)
248                                 err(1, "%s", ttypath);
249                         if (!S_ISCHR(sb.st_mode))
250                                 errx(1, "%s: not a terminal", ttypath);
251                         ttydev = sb.st_rdev;
252                         break;
253                 }
254                 case 'U':
255                         uids = getuids(optarg, &nuids);
256                         xflg++;         /* XXX: intuitive? */
257                         break;
258                 case 'u':
259                         parsefmt(ufmt);
260                         sortby = SORTCPU;
261                         fmt = 1;
262                         ufmt[0] = '\0';
263                         break;
264                 case 'v':
265                         parsefmt(vfmt);
266                         sortby = SORTMEM;
267                         fmt = 1;
268                         vfmt[0] = '\0';
269                         break;
270                 case 'w':
271                         if (wflag)
272                                 termwidth = UNLIMITED;
273                         else if (termwidth < 131)
274                                 termwidth = 131;
275                         wflag++;
276                         break;
277                 case 'x':
278                         xflg = 1;
279                         break;
280                 case '?':
281                 default:
282                         usage();
283                 }
284         argc -= optind;
285         argv += optind;
286
287 #define BACKWARD_COMPATIBILITY
288 #ifdef  BACKWARD_COMPATIBILITY
289         if (*argv) {
290                 nlistf = *argv;
291                 if (*++argv) {
292                         memf = *argv;
293                 }
294         }
295 #endif
296         /*
297          * Discard setgid privileges if not the running kernel so that bad
298          * guys can't print interesting stuff from kernel memory.
299          */
300         if (dropgid) {
301                 setgid(getgid());
302                 setuid(getuid());
303         }
304
305         kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
306         if (kd == 0)
307                 errx(1, "%s", errbuf);
308
309         if (!fmt)
310                 parsefmt(dfmt);
311
312         /* XXX - should be cleaner */
313         if (!all && ttydev == NODEV && pid == -1 && !nuids) {
314                 if ((uids = malloc(sizeof (*uids))) == NULL)
315                         errx(1, "malloc: %s", strerror(errno));
316                 nuids = 1;
317                 *uids = getuid();
318         }
319
320         /*
321          * scan requested variables, noting what structures are needed,
322          * and adjusting header widths as appropriate.
323          */
324         scanvars();
325         /*
326          * get proc list
327          */
328         if (nuids == 1) {
329                 what = KERN_PROC_UID;
330                 flag = *uids;
331         } else if (ttydev != NODEV) {
332                 what = KERN_PROC_TTY;
333                 flag = ttydev;
334         } else if (pid != -1) {
335                 what = KERN_PROC_PID;
336                 flag = pid;
337         } else {
338                 what = KERN_PROC_ALL;
339                 flag = 0;
340         }
341         /*
342          * select procs
343          */
344         if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == 0)
345                 errx(1, "%s", kvm_geterr(kd));
346         if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
347                 err(1, NULL);
348         for (i = nentries; --i >= 0; ++kp) {
349                 kinfo[i].ki_p = kp;
350                 if (needuser)
351                         saveuser(&kinfo[i]);
352                 dynsizevars(&kinfo[i]);
353         }
354
355         sizevars();
356
357         /*
358          * print header
359          */
360         printheader();
361         if (nentries == 0)
362                 exit(1);
363         /*
364          * sort proc list
365          */
366         qsort(kinfo, nentries, sizeof(KINFO), pscomp);
367         /*
368          * for each proc, call each variable output function.
369          */
370         for (i = lineno = 0; i < nentries; i++) {
371                 if (xflg == 0 && (KI_EPROC(&kinfo[i])->e_tdev == NODEV ||
372                     (KI_PROC(&kinfo[i])->p_flag & P_CONTROLT ) == 0))
373                         continue;
374                 if (nuids > 1) {
375                         for (uid = 0; uid < nuids; uid++)
376                                 if (KI_EPROC(&kinfo[i])->e_ucred.cr_uid ==
377                                     uids[uid])
378                                         break;
379                         if (uid == nuids)
380                                 continue;
381                 }
382                 for (vent = vhead; vent; vent = vent->next) {
383                         (vent->var->oproc)(&kinfo[i], vent);
384                         if (vent->next != NULL)
385                                 (void)putchar(' ');
386                 }
387                 (void)putchar('\n');
388                 if (prtheader && lineno++ == prtheader - 4) {
389                         (void)putchar('\n');
390                         printheader();
391                         lineno = 0;
392                 }
393         }
394         free(uids);
395
396         exit(eval);
397 }
398
399 uid_t *
400 getuids(const char *arg, int *nuids)
401 {
402         char name[UT_NAMESIZE + 1];
403         struct passwd *pwd;
404         uid_t *uids, *moreuids;
405         size_t l;
406         int alloc;
407
408
409         alloc = 0;
410         *nuids = 0;
411         uids = NULL;
412         for (; (l = strcspn(arg, SEP)) > 0; arg += l + strspn(arg + l, SEP)) {
413                 if (l >= sizeof name) {
414                         warnx("%.*s: name too long", l, arg);
415                         continue;
416                 }
417                 strncpy(name, arg, l);
418                 name[l] = '\0';
419                 if ((pwd = getpwnam(name)) == NULL) {
420                         warnx("%s: no such user", name);
421                         continue;
422                 }
423                 if (*nuids >= alloc) {
424                         alloc = (alloc + 1) << 1;
425                         moreuids = realloc(uids, alloc * sizeof (*uids));
426                         if (moreuids == NULL) {
427                                 free(uids);
428                                 errx(1, "realloc: %s", strerror(errno));
429                         }
430                         uids = moreuids;
431                 }
432                 uids[(*nuids)++] = pwd->pw_uid;
433         }
434         endpwent();
435
436         if (!*nuids)
437                 errx(1, "No users specified");
438
439         return uids;
440 }
441
442 static void
443 scanvars(void)
444 {
445         struct varent *vent;
446         VAR *v;
447
448         for (vent = vhead; vent; vent = vent->next) {
449                 v = vent->var;
450                 if (v->flag & DSIZ) {
451                         v->dwidth = v->width;
452                         v->width = 0;
453                 }
454                 if (v->flag & USER)
455                         needuser = 1;
456                 if (v->flag & COMM)
457                         needcomm = 1;
458         }
459 }
460
461 static void
462 dynsizevars(KINFO *ki)
463 {
464         struct varent *vent;
465         VAR *v;
466         int i;
467
468         for (vent = vhead; vent; vent = vent->next) {
469                 v = vent->var;
470                 if (!(v->flag & DSIZ))
471                         continue;
472                 i = (v->sproc)( ki);
473                 if (v->width < i)
474                         v->width = i;
475                 if (v->width > v->dwidth)
476                         v->width = v->dwidth;
477         }
478 }
479
480 static void
481 sizevars(void)
482 {
483         struct varent *vent;
484         VAR *v;
485         int i;
486
487         for (vent = vhead; vent; vent = vent->next) {
488                 v = vent->var;
489                 i = strlen(v->header);
490                 if (v->width < i)
491                         v->width = i;
492                 totwidth += v->width + 1;       /* +1 for space */
493         }
494         totwidth--;
495 }
496
497 static const char *
498 getfmt(char **(*fn) (kvm_t *, const struct kinfo_proc *, int), KINFO *ki, char
499     *comm, int maxlen)
500 {
501         const char *s;
502
503         if ((s =
504             fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen)) == NULL)
505                 err(1, NULL);
506         return (s);
507 }
508
509 #define UREADOK(ki)     (forceuread || (KI_PROC(ki)->p_flag & P_INMEM))
510
511 static void
512 saveuser(KINFO *ki)
513 {
514         struct usave *usp;
515
516         usp = &ki->ki_u;
517
518         if (KI_PROC(ki)->p_flag & P_INMEM) {
519                 /*
520                  * The u-area might be swapped out, and we can't get
521                  * at it because we have a crashdump and no swap.
522                  * If it's here fill in these fields, otherwise, just
523                  * leave them 0.
524                  */
525                 usp->u_start = KI_EPROC(ki)->e_stats.p_start;
526                 usp->u_ru = KI_EPROC(ki)->e_stats.p_ru;
527                 usp->u_cru = KI_EPROC(ki)->e_stats.p_cru;
528                 usp->u_valid = 1;
529         } else
530                 usp->u_valid = 0;
531         /*
532          * save arguments if needed
533          */
534         if (needcomm && (UREADOK(ki) || (KI_PROC(ki)->p_args != NULL))) {
535                 ki->ki_args = getfmt(kvm_getargv, ki, KI_THREAD(ki)->td_comm,
536                     MAXCOMLEN);
537         } else if (needcomm) {
538                 char *tmp;
539                 tmp = malloc(strlen(KI_THREAD(ki)->td_comm) + 3);
540                 sprintf(tmp, "(%s)", KI_THREAD(ki)->td_comm);
541                 ki->ki_args = tmp;
542         } else {
543                 ki->ki_args = NULL;
544         }
545         if (needenv && UREADOK(ki)) {
546                 ki->ki_env = getfmt(kvm_getenvv, ki, (char *)NULL, 0);
547         } else if (needenv) {
548                 ki->ki_env = "()";
549         } else {
550                 ki->ki_env = NULL;
551         }
552 }
553
554 static int
555 pscomp(const void *a, const void *b)
556 {
557         int i;
558 #define VSIZE(k) (KI_EPROC(k)->e_vm.vm_dsize + KI_EPROC(k)->e_vm.vm_ssize + \
559                   KI_EPROC(k)->e_vm.vm_tsize)
560
561         if (sortby == SORTCPU)
562                 return (getpcpu((const KINFO *)b) - getpcpu((const KINFO *)a));
563         if (sortby == SORTMEM)
564                 return (VSIZE((const KINFO *)b) - VSIZE((const KINFO *)a));
565         i =  KI_EPROC((const KINFO *)a)->e_tdev - KI_EPROC((const KINFO *)b)->e_tdev;
566         if (i == 0)
567                 i = KI_PROC((const KINFO *)a)->p_pid - KI_PROC((const KINFO *)b)->p_pid;
568         return (i);
569 }
570
571 /*
572  * ICK (all for getopt), would rather hide the ugliness
573  * here than taint the main code.
574  *
575  *  ps foo -> ps -foo
576  *  ps 34 -> ps -p34
577  *
578  * The old convention that 't' with no trailing tty arg means the users
579  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
580  * feature is available with the option 'T', which takes no argument.
581  */
582 static char *
583 kludge_oldps_options(char *s)
584 {
585         size_t len;
586         char *newopts, *ns, *cp;
587
588         len = strlen(s);
589         if ((newopts = ns = malloc(len + 2)) == NULL)
590                 err(1, NULL);
591         /*
592          * options begin with '-'
593          */
594         if (*s != '-')
595                 *ns++ = '-';    /* add option flag */
596         /*
597          * gaze to end of argv[1]
598          */
599         cp = s + len - 1;
600         /*
601          * if last letter is a 't' flag with no argument (in the context
602          * of the oldps options -- option string NOT starting with a '-' --
603          * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
604          *
605          * However, if a flag accepting a string argument is found in the
606          * option string, the remainder of the string is the argument to
607          * that flag; do not modify that argument.
608          */
609         if (strcspn(s, "MNOoU") == len && *cp == 't' && *s != '-')
610                 *cp = 'T';
611         else {
612                 /*
613                  * otherwise check for trailing number, which *may* be a
614                  * pid.
615                  */
616                 while (cp >= s && isdigit(*cp))
617                         --cp;
618         }
619         cp++;
620         memmove(ns, s, (size_t)(cp - s));       /* copy up to trailing number */
621         ns += cp - s;
622         /*
623          * if there's a trailing number, and not a preceding 'p' (pid) or
624          * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
625          */
626         if (isdigit(*cp) &&
627             (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
628             (cp - 1 == s || cp[-2] != 't'))
629                 *ns++ = 'p';
630         (void)strcpy(ns, cp);           /* and append the number */
631
632         return (newopts);
633 }
634
635 static void
636 usage(void)
637 {
638
639         (void)fprintf(stderr, "%s\n%s\n%s\n",
640             "usage: ps [-aChjlmrSTuvwx] [-O|o fmt] [-p pid] [-t tty] [-U user]",
641             "          [-M core] [-N system]",
642             "       ps [-L]");
643         exit(1);
644 }