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