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