]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - bin/ps/ps.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.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  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  * ------+---------+---------+-------- + --------+---------+---------+---------*
29  * Copyright (c) 2004  - Garance Alistair Drosehn <gad@FreeBSD.org>.
30  * All rights reserved.
31  *
32  * Significant modifications made to bring `ps' options somewhat closer
33  * to the standard for `ps' as described in SingleUnixSpec-v3.
34  * ------+---------+---------+-------- + --------+---------+---------+---------*
35  */
36
37 #ifndef lint
38 static const char copyright[] =
39 "@(#) Copyright (c) 1990, 1993, 1994\n\
40         The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42
43 #if 0
44 #ifndef lint
45 static char sccsid[] = "@(#)ps.c        8.4 (Berkeley) 4/2/94";
46 #endif /* not lint */
47 #endif
48
49 #include <sys/cdefs.h>
50 __FBSDID("$FreeBSD$");
51
52 #include <sys/param.h>
53 #include <sys/proc.h>
54 #include <sys/user.h>
55 #include <sys/stat.h>
56 #include <sys/ioctl.h>
57 #include <sys/sysctl.h>
58 #include <sys/mount.h>
59
60 #include <ctype.h>
61 #include <err.h>
62 #include <errno.h>
63 #include <fcntl.h>
64 #include <grp.h>
65 #include <kvm.h>
66 #include <limits.h>
67 #include <locale.h>
68 #include <paths.h>
69 #include <pwd.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <unistd.h>
74
75 #include "ps.h"
76
77 #define _PATH_PTS       "/dev/pts/"
78
79 #define W_SEP   " \t"           /* "Whitespace" list separators */
80 #define T_SEP   ","             /* "Terminate-element" list separators */
81
82 #ifdef LAZY_PS
83 #define DEF_UREAD       0
84 #define OPT_LAZY_f      "f"
85 #else
86 #define DEF_UREAD       1       /* Always do the more-expensive read. */
87 #define OPT_LAZY_f              /* I.e., the `-f' option is not added. */
88 #endif
89
90 /*
91  * isdigit takes an `int', but expects values in the range of unsigned char.
92  * This wrapper ensures that values from a 'char' end up in the correct range.
93  */
94 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
95
96 int      cflag;                 /* -c */
97 int      eval;                  /* Exit value */
98 time_t   now;                   /* Current time(3) value */
99 int      rawcpu;                /* -C */
100 int      sumrusage;             /* -S */
101 int      termwidth;             /* Width of the screen (0 == infinity). */
102 int      totwidth;              /* Calculated-width of requested variables. */
103 int      showthreads;           /* will threads be shown? */
104
105 struct velisthead varlist = STAILQ_HEAD_INITIALIZER(varlist);
106
107 static int       forceuread = DEF_UREAD; /* Do extra work to get u-area. */
108 static kvm_t    *kd;
109 static KINFO    *kinfo;
110 static int       needcomm;      /* -o "command" */
111 static int       needenv;       /* -e */
112 static int       needuser;      /* -o "user" */
113 static int       optfatal;      /* Fatal error parsing some list-option. */
114
115 static enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
116
117 struct listinfo;
118 typedef int     addelem_rtn(struct listinfo *_inf, const char *_elem);
119
120 struct listinfo {
121         int              count;
122         int              maxcount;
123         int              elemsize;
124         addelem_rtn     *addelem;
125         const char      *lname;
126         union {
127                 gid_t   *gids;
128                 pid_t   *pids;
129                 dev_t   *ttys;
130                 uid_t   *uids;
131                 void    *ptr;
132         } l;
133 };
134
135 static int       check_procfs(void);
136 static int       addelem_gid(struct listinfo *, const char *);
137 static int       addelem_pid(struct listinfo *, const char *);
138 static int       addelem_tty(struct listinfo *, const char *);
139 static int       addelem_uid(struct listinfo *, const char *);
140 static void      add_list(struct listinfo *, const char *);
141 static void      descendant_sort(KINFO *, int);
142 static void      dynsizevars(KINFO *);
143 static void     *expand_list(struct listinfo *);
144 static const char *
145                  fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
146                     KINFO *, char *, int);
147 static void      free_list(struct listinfo *);
148 static void      init_list(struct listinfo *, addelem_rtn, int, const char *);
149 static char     *kludge_oldps_options(const char *, char *, const char *);
150 static int       pscomp(const void *, const void *);
151 static void      saveuser(KINFO *);
152 static void      scanvars(void);
153 static void      sizevars(void);
154 static void      usage(void);
155
156 static char dfmt[] = "pid,tt,state,time,command";
157 static char jfmt[] = "user,pid,ppid,pgid,sid,jobc,state,tt,time,command";
158 static char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
159                         "tt,time,command";
160 static char   o1[] = "pid";
161 static char   o2[] = "tt,state,time,command";
162 static char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
163 static char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
164                         "%cpu,%mem,command";
165 static char Zfmt[] = "label";
166
167 #define PS_ARGS "AaCcde" OPT_LAZY_f "G:gHhjLlM:mN:O:o:p:rSTt:U:uvwXxZ"
168
169 int
170 main(int argc, char *argv[])
171 {
172         struct listinfo gidlist, pgrplist, pidlist;
173         struct listinfo ruidlist, sesslist, ttylist, uidlist;
174         struct kinfo_proc *kp;
175         KINFO *next_KINFO;
176         struct varent *vent;
177         struct winsize ws;
178         const char *nlistf, *memf;
179         char *cols;
180         int all, ch, elem, flag, _fmt, i, lineno;
181         int descendancy, nentries, nkept, nselectors;
182         int prtheader, wflag, what, xkeep, xkeep_implied;
183         char errbuf[_POSIX2_LINE_MAX];
184
185         (void) setlocale(LC_ALL, "");
186         time(&now);                     /* Used by routines in print.c. */
187
188         if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
189                 termwidth = atoi(cols);
190         else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
191              ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
192              ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
193              ws.ws_col == 0)
194                 termwidth = 79;
195         else
196                 termwidth = ws.ws_col - 1;
197
198         /*
199          * Hide a number of option-processing kludges in a separate routine,
200          * to support some historical BSD behaviors, such as `ps axu'.
201          */
202         if (argc > 1)
203                 argv[1] = kludge_oldps_options(PS_ARGS, argv[1], argv[2]);
204
205         all = descendancy = _fmt = nselectors = optfatal = 0;
206         prtheader = showthreads = wflag = xkeep_implied = 0;
207         xkeep = -1;                     /* Neither -x nor -X. */
208         init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
209         init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
210         init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
211         init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
212         init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
213         init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
214         init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
215         memf = _PATH_DEVNULL;
216         nlistf = NULL;
217         while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
218                 switch (ch) {
219                 case 'A':
220                         /*
221                          * Exactly the same as `-ax'.   This has been
222                          * added for compatability with SUSv3, but for
223                          * now it will not be described in the man page.
224                          */
225                         nselectors++;
226                         all = xkeep = 1;
227                         break;
228                 case 'a':
229                         nselectors++;
230                         all = 1;
231                         break;
232                 case 'C':
233                         rawcpu = 1;
234                         break;
235                 case 'c':
236                         cflag = 1;
237                         break;
238                 case 'd':
239                         descendancy = 1;
240                         break;
241                 case 'e':                       /* XXX set ufmt */
242                         needenv = 1;
243                         break;
244 #ifdef LAZY_PS
245                 case 'f':
246                         if (getuid() == 0 || getgid() == 0)
247                                 forceuread = 1;
248                         break;
249 #endif
250                 case 'G':
251                         add_list(&gidlist, optarg);
252                         xkeep_implied = 1;
253                         nselectors++;
254                         break;
255                 case 'g':
256 #if 0
257                         /*-
258                          * XXX - This SUSv3 behavior is still under debate
259                          *      since it conflicts with the (undocumented)
260                          *      `-g' option.  So we skip it for now.
261                          */
262                         add_list(&pgrplist, optarg);
263                         xkeep_implied = 1;
264                         nselectors++;
265                         break;
266 #else
267                         /* The historical BSD-ish (from SunOS) behavior. */
268                         break;                  /* no-op */
269 #endif
270                 case 'H':
271                         showthreads = KERN_PROC_INC_THREAD;
272                         break;
273                 case 'h':
274                         prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
275                         break;
276                 case 'j':
277                         parsefmt(jfmt, 0);
278                         _fmt = 1;
279                         jfmt[0] = '\0';
280                         break;
281                 case 'L':
282                         showkey();
283                         exit(0);
284                 case 'l':
285                         parsefmt(lfmt, 0);
286                         _fmt = 1;
287                         lfmt[0] = '\0';
288                         break;
289                 case 'M':
290                         memf = optarg;
291                         break;
292                 case 'm':
293                         sortby = SORTMEM;
294                         break;
295                 case 'N':
296                         nlistf = optarg;
297                         break;
298                 case 'O':
299                         parsefmt(o1, 1);
300                         parsefmt(optarg, 1);
301                         parsefmt(o2, 1);
302                         o1[0] = o2[0] = '\0';
303                         _fmt = 1;
304                         break;
305                 case 'o':
306                         parsefmt(optarg, 1);
307                         _fmt = 1;
308                         break;
309                 case 'p':
310                         add_list(&pidlist, optarg);
311                         /*
312                          * Note: `-p' does not *set* xkeep, but any values
313                          * from pidlist are checked before xkeep is.  That
314                          * way they are always matched, even if the user
315                          * specifies `-X'.
316                          */
317                         nselectors++;
318                         break;
319 #if 0
320                 case 'R':
321                         /*-
322                          * XXX - This un-standard option is still under
323                          *      debate.  This is what SUSv3 defines as
324                          *      the `-U' option, and while it would be
325                          *      nice to have, it could cause even more
326                          *      confusion to implement it as `-R'.
327                          */
328                         add_list(&ruidlist, optarg);
329                         xkeep_implied = 1;
330                         nselectors++;
331                         break;
332 #endif
333                 case 'r':
334                         sortby = SORTCPU;
335                         break;
336                 case 'S':
337                         sumrusage = 1;
338                         break;
339 #if 0
340                 case 's':
341                         /*-
342                          * XXX - This non-standard option is still under
343                          *      debate.  This *is* supported on Solaris,
344                          *      Linux, and IRIX, but conflicts with `-s'
345                          *      on NetBSD and maybe some older BSD's.
346                          */
347                         add_list(&sesslist, optarg);
348                         xkeep_implied = 1;
349                         nselectors++;
350                         break;
351 #endif
352                 case 'T':
353                         if ((optarg = ttyname(STDIN_FILENO)) == NULL)
354                                 errx(1, "stdin: not a terminal");
355                         /* FALLTHROUGH */
356                 case 't':
357                         add_list(&ttylist, optarg);
358                         xkeep_implied = 1;
359                         nselectors++;
360                         break;
361                 case 'U':
362                         /* This is what SUSv3 defines as the `-u' option. */
363                         add_list(&uidlist, optarg);
364                         xkeep_implied = 1;
365                         nselectors++;
366                         break;
367                 case 'u':
368                         parsefmt(ufmt, 0);
369                         sortby = SORTCPU;
370                         _fmt = 1;
371                         ufmt[0] = '\0';
372                         break;
373                 case 'v':
374                         parsefmt(vfmt, 0);
375                         sortby = SORTMEM;
376                         _fmt = 1;
377                         vfmt[0] = '\0';
378                         break;
379                 case 'w':
380                         if (wflag)
381                                 termwidth = UNLIMITED;
382                         else if (termwidth < 131)
383                                 termwidth = 131;
384                         wflag++;
385                         break;
386                 case 'X':
387                         /*
388                          * Note that `-X' and `-x' are not standard "selector"
389                          * options. For most selector-options, we check *all*
390                          * processes to see if any are matched by the given
391                          * value(s).  After we have a set of all the matched
392                          * processes, then `-X' and `-x' govern whether we
393                          * modify that *matched* set for processes which do
394                          * not have a controlling terminal.  `-X' causes
395                          * those processes to be deleted from the matched
396                          * set, while `-x' causes them to be kept.
397                          */
398                         xkeep = 0;
399                         break;
400                 case 'x':
401                         xkeep = 1;
402                         break;
403                 case 'Z':
404                         parsefmt(Zfmt, 0);
405                         Zfmt[0] = '\0';
406                         break;
407                 case '?':
408                 default:
409                         usage();
410                 }
411         argc -= optind;
412         argv += optind;
413
414         /*
415          * If the user specified ps -e then they want a copy of the process
416          * environment kvm_getenvv(3) attempts to open /proc/<pid>/mem.
417          * Check to make sure that procfs is mounted on /proc, otherwise
418          * print a warning informing the user that output will be incomplete.
419          */
420         if (needenv == 1 && check_procfs() == 0)
421                 warnx("Process environment requires procfs(5)");
422         /*
423          * If there arguments after processing all the options, attempt
424          * to treat them as a list of process ids.
425          */
426         while (*argv) {
427                 if (!isdigitch(**argv))
428                         break;
429                 add_list(&pidlist, *argv);
430                 argv++;
431         }
432         if (*argv) {
433                 fprintf(stderr, "%s: illegal argument: %s\n",
434                     getprogname(), *argv);
435                 usage();
436         }
437         if (optfatal)
438                 exit(1);                /* Error messages already printed. */
439         if (xkeep < 0)                  /* Neither -X nor -x was specified. */
440                 xkeep = xkeep_implied;
441
442         kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
443         if (kd == 0)
444                 errx(1, "%s", errbuf);
445
446         if (!_fmt)
447                 parsefmt(dfmt, 0);
448
449         if (nselectors == 0) {
450                 uidlist.l.ptr = malloc(sizeof(uid_t));
451                 if (uidlist.l.ptr == NULL)
452                         errx(1, "malloc failed");
453                 nselectors = 1;
454                 uidlist.count = uidlist.maxcount = 1;
455                 *uidlist.l.uids = getuid();
456         }
457
458         /*
459          * scan requested variables, noting what structures are needed,
460          * and adjusting header widths as appropriate.
461          */
462         scanvars();
463
464         /*
465          * Get process list.  If the user requested just one selector-
466          * option, then kvm_getprocs can be asked to return just those
467          * processes.  Otherwise, have it return all processes, and
468          * then this routine will search that full list and select the
469          * processes which match any of the user's selector-options.
470          */
471         what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
472         flag = 0;
473         if (nselectors == 1) {
474                 if (gidlist.count == 1) {
475                         what = KERN_PROC_RGID | showthreads;
476                         flag = *gidlist.l.gids;
477                         nselectors = 0;
478                 } else if (pgrplist.count == 1) {
479                         what = KERN_PROC_PGRP | showthreads;
480                         flag = *pgrplist.l.pids;
481                         nselectors = 0;
482                 } else if (pidlist.count == 1) {
483                         what = KERN_PROC_PID | showthreads;
484                         flag = *pidlist.l.pids;
485                         nselectors = 0;
486                 } else if (ruidlist.count == 1) {
487                         what = KERN_PROC_RUID | showthreads;
488                         flag = *ruidlist.l.uids;
489                         nselectors = 0;
490                 } else if (sesslist.count == 1) {
491                         what = KERN_PROC_SESSION | showthreads;
492                         flag = *sesslist.l.pids;
493                         nselectors = 0;
494                 } else if (ttylist.count == 1) {
495                         what = KERN_PROC_TTY | showthreads;
496                         flag = *ttylist.l.ttys;
497                         nselectors = 0;
498                 } else if (uidlist.count == 1) {
499                         what = KERN_PROC_UID | showthreads;
500                         flag = *uidlist.l.uids;
501                         nselectors = 0;
502                 } else if (all) {
503                         /* No need for this routine to select processes. */
504                         nselectors = 0;
505                 }
506         }
507
508         /*
509          * select procs
510          */
511         nentries = -1;
512         kp = kvm_getprocs(kd, what, flag, &nentries);
513         if ((kp == NULL && nentries > 0) || (kp != NULL && nentries < 0))
514                 errx(1, "%s", kvm_geterr(kd));
515         nkept = 0;
516         if (nentries > 0) {
517                 if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
518                         errx(1, "malloc failed");
519                 for (i = nentries; --i >= 0; ++kp) {
520                         /*
521                          * If the user specified multiple selection-criteria,
522                          * then keep any process matched by the inclusive OR
523                          * of all the selection-criteria given.
524                          */
525                         if (pidlist.count > 0) {
526                                 for (elem = 0; elem < pidlist.count; elem++)
527                                         if (kp->ki_pid == pidlist.l.pids[elem])
528                                                 goto keepit;
529                         }
530                         /*
531                          * Note that we had to process pidlist before
532                          * filtering out processes which do not have
533                          * a controlling terminal.
534                          */
535                         if (xkeep == 0) {
536                                 if ((kp->ki_tdev == NODEV ||
537                                     (kp->ki_flag & P_CONTROLT) == 0))
538                                         continue;
539                         }
540                         if (nselectors == 0)
541                                 goto keepit;
542                         if (gidlist.count > 0) {
543                                 for (elem = 0; elem < gidlist.count; elem++)
544                                         if (kp->ki_rgid == gidlist.l.gids[elem])
545                                                 goto keepit;
546                         }
547                         if (pgrplist.count > 0) {
548                                 for (elem = 0; elem < pgrplist.count; elem++)
549                                         if (kp->ki_pgid ==
550                                             pgrplist.l.pids[elem])
551                                                 goto keepit;
552                         }
553                         if (ruidlist.count > 0) {
554                                 for (elem = 0; elem < ruidlist.count; elem++)
555                                         if (kp->ki_ruid ==
556                                             ruidlist.l.uids[elem])
557                                                 goto keepit;
558                         }
559                         if (sesslist.count > 0) {
560                                 for (elem = 0; elem < sesslist.count; elem++)
561                                         if (kp->ki_sid == sesslist.l.pids[elem])
562                                                 goto keepit;
563                         }
564                         if (ttylist.count > 0) {
565                                 for (elem = 0; elem < ttylist.count; elem++)
566                                         if (kp->ki_tdev == ttylist.l.ttys[elem])
567                                                 goto keepit;
568                         }
569                         if (uidlist.count > 0) {
570                                 for (elem = 0; elem < uidlist.count; elem++)
571                                         if (kp->ki_uid == uidlist.l.uids[elem])
572                                                 goto keepit;
573                         }
574                         /*
575                          * This process did not match any of the user's
576                          * selector-options, so skip the process.
577                          */
578                         continue;
579
580                 keepit:
581                         next_KINFO = &kinfo[nkept];
582                         next_KINFO->ki_p = kp;
583                         next_KINFO->ki_d.level = 0;
584                         next_KINFO->ki_d.prefix = NULL;
585                         next_KINFO->ki_pcpu = getpcpu(next_KINFO);
586                         if (sortby == SORTMEM)
587                                 next_KINFO->ki_memsize = kp->ki_tsize +
588                                     kp->ki_dsize + kp->ki_ssize;
589                         if (needuser)
590                                 saveuser(next_KINFO);
591                         dynsizevars(next_KINFO);
592                         nkept++;
593                 }
594         }
595
596         sizevars();
597
598         /*
599          * print header
600          */
601         printheader();
602         if (nkept == 0)
603                 exit(1);
604
605         /*
606          * sort proc list
607          */
608         qsort(kinfo, nkept, sizeof(KINFO), pscomp);
609
610         /*
611          * We want things in descendant order
612          */
613         if (descendancy)
614                 descendant_sort(kinfo, nkept);
615
616         /*
617          * For each process, call each variable output function.
618          */
619         for (i = lineno = 0; i < nkept; i++) {
620                 STAILQ_FOREACH(vent, &varlist, next_ve) {
621                         (vent->var->oproc)(&kinfo[i], vent);
622                         if (STAILQ_NEXT(vent, next_ve) != NULL)
623                                 (void)putchar(' ');
624                 }
625                 (void)putchar('\n');
626                 if (prtheader && lineno++ == prtheader - 4) {
627                         (void)putchar('\n');
628                         printheader();
629                         lineno = 0;
630                 }
631         }
632         free_list(&gidlist);
633         free_list(&pidlist);
634         free_list(&pgrplist);
635         free_list(&ruidlist);
636         free_list(&sesslist);
637         free_list(&ttylist);
638         free_list(&uidlist);
639         for (i = 0; i < nkept; i++)
640                 free(kinfo[i].ki_d.prefix);
641         free(kinfo);
642
643         exit(eval);
644 }
645
646 static int
647 addelem_gid(struct listinfo *inf, const char *elem)
648 {
649         struct group *grp;
650         const char *nameorID;
651         char *endp;
652         u_long bigtemp;
653
654         if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
655                 if (*elem == '\0')
656                         warnx("Invalid (zero-length) %s name", inf->lname);
657                 else
658                         warnx("%s name too long: %s", inf->lname, elem);
659                 optfatal = 1;
660                 return (0);             /* Do not add this value. */
661         }
662
663         /*
664          * SUSv3 states that `ps -G grouplist' should match "real-group
665          * ID numbers", and does not mention group-names.  I do want to
666          * also support group-names, so this tries for a group-id first,
667          * and only tries for a name if that doesn't work.  This is the
668          * opposite order of what is done in addelem_uid(), but in
669          * practice the order would only matter for group-names which
670          * are all-numeric.
671          */
672         grp = NULL;
673         nameorID = "named";
674         errno = 0;
675         bigtemp = strtoul(elem, &endp, 10);
676         if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
677                 nameorID = "name or ID matches";
678                 grp = getgrgid((gid_t)bigtemp);
679         }
680         if (grp == NULL)
681                 grp = getgrnam(elem);
682         if (grp == NULL) {
683                 warnx("No %s %s '%s'", inf->lname, nameorID, elem);
684                 optfatal = 1;
685                 return (0);
686         }
687         if (inf->count >= inf->maxcount)
688                 expand_list(inf);
689         inf->l.gids[(inf->count)++] = grp->gr_gid;
690         return (1);
691 }
692
693 #define BSD_PID_MAX     99999           /* Copy of PID_MAX from sys/proc.h. */
694 static int
695 addelem_pid(struct listinfo *inf, const char *elem)
696 {
697         char *endp;
698         long tempid;
699
700         if (*elem == '\0') {
701                 warnx("Invalid (zero-length) process id");
702                 optfatal = 1;
703                 return (0);             /* Do not add this value. */
704         }
705
706         errno = 0;
707         tempid = strtol(elem, &endp, 10);
708         if (*endp != '\0' || tempid < 0 || elem == endp) {
709                 warnx("Invalid %s: %s", inf->lname, elem);
710                 errno = ERANGE;
711         } else if (errno != 0 || tempid > BSD_PID_MAX) {
712                 warnx("%s too large: %s", inf->lname, elem);
713                 errno = ERANGE;
714         }
715         if (errno == ERANGE) {
716                 optfatal = 1;
717                 return (0);
718         }
719         if (inf->count >= inf->maxcount)
720                 expand_list(inf);
721         inf->l.pids[(inf->count)++] = tempid;
722         return (1);
723 }
724 #undef  BSD_PID_MAX
725
726 /*-
727  * The user can specify a device via one of three formats:
728  *     1) fully qualified, e.g.:     /dev/ttyp0 /dev/console    /dev/pts/0
729  *     2) missing "/dev", e.g.:      ttyp0      console         pts/0
730  *     3) two-letters, e.g.:         p0         co              0
731  *        (matching letters that would be seen in the "TT" column)
732  */
733 static int
734 addelem_tty(struct listinfo *inf, const char *elem)
735 {
736         const char *ttypath;
737         struct stat sb;
738         char pathbuf[PATH_MAX], pathbuf2[PATH_MAX], pathbuf3[PATH_MAX];
739
740         ttypath = NULL;
741         pathbuf2[0] = '\0';
742         pathbuf3[0] = '\0';
743         switch (*elem) {
744         case '/':
745                 ttypath = elem;
746                 break;
747         case 'c':
748                 if (strcmp(elem, "co") == 0) {
749                         ttypath = _PATH_CONSOLE;
750                         break;
751                 }
752                 /* FALLTHROUGH */
753         default:
754                 strlcpy(pathbuf, _PATH_DEV, sizeof(pathbuf));
755                 strlcat(pathbuf, elem, sizeof(pathbuf));
756                 ttypath = pathbuf;
757                 if (strncmp(pathbuf, _PATH_TTY, strlen(_PATH_TTY)) == 0)
758                         break;
759                 if (strncmp(pathbuf, _PATH_PTS, strlen(_PATH_PTS)) == 0)
760                         break;
761                 if (strcmp(pathbuf, _PATH_CONSOLE) == 0)
762                         break;
763                 /* Check to see if /dev/tty${elem} exists */
764                 strlcpy(pathbuf2, _PATH_TTY, sizeof(pathbuf2));
765                 strlcat(pathbuf2, elem, sizeof(pathbuf2));
766                 if (stat(pathbuf2, &sb) == 0 && S_ISCHR(sb.st_mode)) {
767                         /* No need to repeat stat() && S_ISCHR() checks */
768                         ttypath = NULL;
769                         break;
770                 }
771                 /* Check to see if /dev/pts/${elem} exists */
772                 strlcpy(pathbuf3, _PATH_PTS, sizeof(pathbuf3));
773                 strlcat(pathbuf3, elem, sizeof(pathbuf3));
774                 if (stat(pathbuf3, &sb) == 0 && S_ISCHR(sb.st_mode)) {
775                         /* No need to repeat stat() && S_ISCHR() checks */
776                         ttypath = NULL;
777                         break;
778                 }
779                 break;
780         }
781         if (ttypath) {
782                 if (stat(ttypath, &sb) == -1) {
783                         if (pathbuf3[0] != '\0')
784                                 warn("%s, %s, and %s", pathbuf3, pathbuf2,
785                                     ttypath);
786                         else
787                                 warn("%s", ttypath);
788                         optfatal = 1;
789                         return (0);
790                 }
791                 if (!S_ISCHR(sb.st_mode)) {
792                         if (pathbuf3[0] != '\0')
793                                 warnx("%s, %s, and %s: Not a terminal",
794                                     pathbuf3, pathbuf2, ttypath);
795                         else
796                                 warnx("%s: Not a terminal", ttypath);
797                         optfatal = 1;
798                         return (0);
799                 }
800         }
801         if (inf->count >= inf->maxcount)
802                 expand_list(inf);
803         inf->l.ttys[(inf->count)++] = sb.st_rdev;
804         return (1);
805 }
806
807 static int
808 addelem_uid(struct listinfo *inf, const char *elem)
809 {
810         struct passwd *pwd;
811         char *endp;
812         u_long bigtemp;
813
814         if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
815                 if (*elem == '\0')
816                         warnx("Invalid (zero-length) %s name", inf->lname);
817                 else
818                         warnx("%s name too long: %s", inf->lname, elem);
819                 optfatal = 1;
820                 return (0);             /* Do not add this value. */
821         }
822
823         pwd = getpwnam(elem);
824         if (pwd == NULL) {
825                 errno = 0;
826                 bigtemp = strtoul(elem, &endp, 10);
827                 if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
828                         warnx("No %s named '%s'", inf->lname, elem);
829                 else {
830                         /* The string is all digits, so it might be a userID. */
831                         pwd = getpwuid((uid_t)bigtemp);
832                         if (pwd == NULL)
833                                 warnx("No %s name or ID matches '%s'",
834                                     inf->lname, elem);
835                 }
836         }
837         if (pwd == NULL) {
838                 /*
839                  * These used to be treated as minor warnings (and the
840                  * option was simply ignored), but now they are fatal
841                  * errors (and the command will be aborted).
842                  */
843                 optfatal = 1;
844                 return (0);
845         }
846         if (inf->count >= inf->maxcount)
847                 expand_list(inf);
848         inf->l.uids[(inf->count)++] = pwd->pw_uid;
849         return (1);
850 }
851
852 static void
853 add_list(struct listinfo *inf, const char *argp)
854 {
855         const char *savep;
856         char *cp, *endp;
857         int toolong;
858         char elemcopy[PATH_MAX];
859
860         if (*argp == 0)
861                 inf->addelem(inf, elemcopy);
862         while (*argp != '\0') {
863                 while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
864                         argp++;
865                 savep = argp;
866                 toolong = 0;
867                 cp = elemcopy;
868                 if (strchr(T_SEP, *argp) == NULL) {
869                         endp = elemcopy + sizeof(elemcopy) - 1;
870                         while (*argp != '\0' && cp <= endp &&
871                             strchr(W_SEP T_SEP, *argp) == NULL)
872                                 *cp++ = *argp++;
873                         if (cp > endp)
874                                 toolong = 1;
875                 }
876                 if (!toolong) {
877                         *cp = '\0';
878                         /*
879                          * Add this single element to the given list.
880                          */
881                         inf->addelem(inf, elemcopy);
882                 } else {
883                         /*
884                          * The string is too long to copy.  Find the end
885                          * of the string to print out the warning message.
886                          */
887                         while (*argp != '\0' && strchr(W_SEP T_SEP,
888                             *argp) == NULL)
889                                 argp++;
890                         warnx("Value too long: %.*s", (int)(argp - savep),
891                             savep);
892                         optfatal = 1;
893                 }
894                 /*
895                  * Skip over any number of trailing whitespace characters,
896                  * but only one (at most) trailing element-terminating
897                  * character.
898                  */
899                 while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
900                         argp++;
901                 if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
902                         argp++;
903                         /* Catch case where string ended with a comma. */
904                         if (*argp == '\0')
905                                 inf->addelem(inf, argp);
906                 }
907         }
908 }
909
910 static void
911 descendant_sort(KINFO *ki, int items)
912 {
913         int dst, lvl, maxlvl, n, ndst, nsrc, siblings, src;
914         unsigned char *path;
915         KINFO kn;
916
917         /*
918          * First, sort the entries by descendancy, tracking the descendancy
919          * depth in the ki_d.level field.
920          */
921         src = 0;
922         maxlvl = 0;
923         while (src < items) {
924                 if (ki[src].ki_d.level) {
925                         src++;
926                         continue;
927                 }
928                 for (nsrc = 1; src + nsrc < items; nsrc++)
929                         if (!ki[src + nsrc].ki_d.level)
930                                 break;
931
932                 for (dst = 0; dst < items; dst++) {
933                         if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_pid)
934                                 continue;
935                         if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_ppid)
936                                 break;
937                 }
938
939                 if (dst == items) {
940                         src += nsrc;
941                         continue;
942                 }
943
944                 for (ndst = 1; dst + ndst < items; ndst++)
945                         if (ki[dst + ndst].ki_d.level <= ki[dst].ki_d.level)
946                                 break;
947
948                 for (n = src; n < src + nsrc; n++) {
949                         ki[n].ki_d.level += ki[dst].ki_d.level + 1;
950                         if (maxlvl < ki[n].ki_d.level)
951                                 maxlvl = ki[n].ki_d.level;
952                 }
953
954                 while (nsrc) {
955                         if (src < dst) {
956                                 kn = ki[src];
957                                 memmove(ki + src, ki + src + 1,
958                                     (dst - src + ndst - 1) * sizeof *ki);
959                                 ki[dst + ndst - 1] = kn;
960                                 nsrc--;
961                                 dst--;
962                                 ndst++;
963                         } else if (src != dst + ndst) {
964                                 kn = ki[src];
965                                 memmove(ki + dst + ndst + 1, ki + dst + ndst,
966                                     (src - dst - ndst) * sizeof *ki);
967                                 ki[dst + ndst] = kn;
968                                 ndst++;
969                                 nsrc--;
970                                 src++;
971                         } else {
972                                 ndst += nsrc;
973                                 src += nsrc;
974                                 nsrc = 0;
975                         }
976                 }
977         }
978
979         /*
980          * Now populate ki_d.prefix (instead of ki_d.level) with the command
981          * prefix used to show descendancies.
982          */
983         path = malloc((maxlvl + 7) / 8);
984         memset(path, '\0', (maxlvl + 7) / 8);
985         for (src = 0; src < items; src++) {
986                 if ((lvl = ki[src].ki_d.level) == 0) {
987                         ki[src].ki_d.prefix = NULL;
988                         continue;
989                 }
990                 if ((ki[src].ki_d.prefix = malloc(lvl * 2 + 1)) == NULL)
991                         errx(1, "malloc failed");
992                 for (n = 0; n < lvl - 2; n++) {
993                         ki[src].ki_d.prefix[n * 2] =
994                             path[n / 8] & 1 << (n % 8) ? '|' : ' ';
995                         ki[src].ki_d.prefix[n * 2 + 1] = ' ';
996                 }
997                 if (n == lvl - 2) {
998                         /* Have I any more siblings? */
999                         for (siblings = 0, dst = src + 1; dst < items; dst++) {
1000                                 if (ki[dst].ki_d.level > lvl)
1001                                         continue;
1002                                 if (ki[dst].ki_d.level == lvl)
1003                                         siblings = 1;
1004                                 break;
1005                         }
1006                         if (siblings)
1007                                 path[n / 8] |= 1 << (n % 8);
1008                         else
1009                                 path[n / 8] &= ~(1 << (n % 8));
1010                         ki[src].ki_d.prefix[n * 2] = siblings ? '|' : '`';
1011                         ki[src].ki_d.prefix[n * 2 + 1] = '-';
1012                         n++;
1013                 }
1014                 strcpy(ki[src].ki_d.prefix + n * 2, "- ");
1015         }
1016         free(path);
1017 }
1018
1019 static void *
1020 expand_list(struct listinfo *inf)
1021 {
1022         void *newlist;
1023         int newmax;
1024
1025         newmax = (inf->maxcount + 1) << 1;
1026         newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
1027         if (newlist == NULL) {
1028                 free(inf->l.ptr);
1029                 errx(1, "realloc to %d %ss failed", newmax, inf->lname);
1030         }
1031         inf->maxcount = newmax;
1032         inf->l.ptr = newlist;
1033
1034         return (newlist);
1035 }
1036
1037 static void
1038 free_list(struct listinfo *inf)
1039 {
1040
1041         inf->count = inf->elemsize = inf->maxcount = 0;
1042         if (inf->l.ptr != NULL)
1043                 free(inf->l.ptr);
1044         inf->addelem = NULL;
1045         inf->lname = NULL;
1046         inf->l.ptr = NULL;
1047 }
1048
1049 static void
1050 init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
1051     const char *lname)
1052 {
1053
1054         inf->count = inf->maxcount = 0;
1055         inf->elemsize = elemsize;
1056         inf->addelem = artn;
1057         inf->lname = lname;
1058         inf->l.ptr = NULL;
1059 }
1060
1061 VARENT *
1062 find_varentry(VAR *v)
1063 {
1064         struct varent *vent;
1065
1066         STAILQ_FOREACH(vent, &varlist, next_ve) {
1067                 if (strcmp(vent->var->name, v->name) == 0)
1068                         return vent;
1069         }
1070         return NULL;
1071 }
1072
1073 static void
1074 scanvars(void)
1075 {
1076         struct varent *vent;
1077         VAR *v;
1078
1079         STAILQ_FOREACH(vent, &varlist, next_ve) {
1080                 v = vent->var;
1081                 if (v->flag & DSIZ) {
1082                         v->dwidth = v->width;
1083                         v->width = 0;
1084                 }
1085                 if (v->flag & USER)
1086                         needuser = 1;
1087                 if (v->flag & COMM)
1088                         needcomm = 1;
1089         }
1090 }
1091
1092 static void
1093 dynsizevars(KINFO *ki)
1094 {
1095         struct varent *vent;
1096         VAR *v;
1097         int i;
1098
1099         STAILQ_FOREACH(vent, &varlist, next_ve) {
1100                 v = vent->var;
1101                 if (!(v->flag & DSIZ))
1102                         continue;
1103                 i = (v->sproc)( ki);
1104                 if (v->width < i)
1105                         v->width = i;
1106                 if (v->width > v->dwidth)
1107                         v->width = v->dwidth;
1108         }
1109 }
1110
1111 static void
1112 sizevars(void)
1113 {
1114         struct varent *vent;
1115         VAR *v;
1116         int i;
1117
1118         STAILQ_FOREACH(vent, &varlist, next_ve) {
1119                 v = vent->var;
1120                 i = strlen(vent->header);
1121                 if (v->width < i)
1122                         v->width = i;
1123                 totwidth += v->width + 1;       /* +1 for space */
1124         }
1125         totwidth--;
1126 }
1127
1128 static const char *
1129 fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
1130     char *comm, int maxlen)
1131 {
1132         const char *s;
1133
1134         s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
1135         return (s);
1136 }
1137
1138 #define UREADOK(ki)     (forceuread || (ki->ki_p->ki_flag & P_INMEM))
1139
1140 static void
1141 saveuser(KINFO *ki)
1142 {
1143
1144         if (ki->ki_p->ki_flag & P_INMEM) {
1145                 /*
1146                  * The u-area might be swapped out, and we can't get
1147                  * at it because we have a crashdump and no swap.
1148                  * If it's here fill in these fields, otherwise, just
1149                  * leave them 0.
1150                  */
1151                 ki->ki_valid = 1;
1152         } else
1153                 ki->ki_valid = 0;
1154         /*
1155          * save arguments if needed
1156          */
1157         if (needcomm) {
1158                 if (ki->ki_p->ki_stat == SZOMB)
1159                         ki->ki_args = strdup("<defunct>");
1160                 else if (UREADOK(ki) || (ki->ki_p->ki_args != NULL))
1161                         ki->ki_args = strdup(fmt(kvm_getargv, ki,
1162                             ki->ki_p->ki_comm, MAXCOMLEN));
1163                 else
1164                         asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
1165                 if (ki->ki_args == NULL)
1166                         errx(1, "malloc failed");
1167         } else {
1168                 ki->ki_args = NULL;
1169         }
1170         if (needenv) {
1171                 if (UREADOK(ki))
1172                         ki->ki_env = strdup(fmt(kvm_getenvv, ki,
1173                             (char *)NULL, 0));
1174                 else
1175                         ki->ki_env = strdup("()");
1176                 if (ki->ki_env == NULL)
1177                         errx(1, "malloc failed");
1178         } else {
1179                 ki->ki_env = NULL;
1180         }
1181 }
1182
1183 /* A macro used to improve the readability of pscomp(). */
1184 #define DIFF_RETURN(a, b, field) do {   \
1185         if ((a)->field != (b)->field)   \
1186                 return (((a)->field < (b)->field) ? -1 : 1);    \
1187 } while (0)
1188
1189 static int
1190 pscomp(const void *a, const void *b)
1191 {
1192         const KINFO *ka, *kb;
1193
1194         ka = a;
1195         kb = b;
1196         /* SORTCPU and SORTMEM are sorted in descending order. */
1197         if (sortby == SORTCPU)
1198                 DIFF_RETURN(kb, ka, ki_pcpu);
1199         if (sortby == SORTMEM)
1200                 DIFF_RETURN(kb, ka, ki_memsize);
1201         /*
1202          * TTY's are sorted in ascending order, except that all NODEV
1203          * processes come before all processes with a device.
1204          */
1205         if (ka->ki_p->ki_tdev != kb->ki_p->ki_tdev) {
1206                 if (ka->ki_p->ki_tdev == NODEV)
1207                         return (-1);
1208                 if (kb->ki_p->ki_tdev == NODEV)
1209                         return (1);
1210                 DIFF_RETURN(ka, kb, ki_p->ki_tdev);
1211         }
1212
1213         /* PID's and TID's (threads) are sorted in ascending order. */
1214         DIFF_RETURN(ka, kb, ki_p->ki_pid);
1215         DIFF_RETURN(ka, kb, ki_p->ki_tid);
1216         return (0);
1217 }
1218 #undef DIFF_RETURN
1219
1220 /*
1221  * ICK (all for getopt), would rather hide the ugliness
1222  * here than taint the main code.
1223  *
1224  *  ps foo -> ps -foo
1225  *  ps 34 -> ps -p34
1226  *
1227  * The old convention that 't' with no trailing tty arg means the users
1228  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
1229  * feature is available with the option 'T', which takes no argument.
1230  */
1231 static char *
1232 kludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
1233 {
1234         size_t len;
1235         char *argp, *cp, *newopts, *ns, *optp, *pidp;
1236
1237         /*
1238          * See if the original value includes any option which takes an
1239          * argument (and will thus use up the remainder of the string).
1240          */
1241         argp = NULL;
1242         if (optlist != NULL) {
1243                 for (cp = origval; *cp != '\0'; cp++) {
1244                         optp = strchr(optlist, *cp);
1245                         if ((optp != NULL) && *(optp + 1) == ':') {
1246                                 argp = cp;
1247                                 break;
1248                         }
1249                 }
1250         }
1251         if (argp != NULL && *origval == '-')
1252                 return (origval);
1253
1254         /*
1255          * if last letter is a 't' flag with no argument (in the context
1256          * of the oldps options -- option string NOT starting with a '-' --
1257          * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1258          *
1259          * However, if a flag accepting a string argument is found earlier
1260          * in the option string (including a possible `t' flag), then the
1261          * remainder of the string must be the argument to that flag; so
1262          * do not modify that argument.  Note that a trailing `t' would
1263          * cause argp to be set, if argp was not already set by some
1264          * earlier option.
1265          */
1266         len = strlen(origval);
1267         cp = origval + len - 1;
1268         pidp = NULL;
1269         if (*cp == 't' && *origval != '-' && cp == argp) {
1270                 if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
1271                         *cp = 'T';
1272         } else if (argp == NULL) {
1273                 /*
1274                  * The original value did not include any option which takes
1275                  * an argument (and that would include `p' and `t'), so check
1276                  * the value for trailing number, or comma-separated list of
1277                  * numbers, which we will treat as a pid request.
1278                  */
1279                 if (isdigitch(*cp)) {
1280                         while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1281                                 --cp;
1282                         pidp = cp + 1;
1283                 }
1284         }
1285
1286         /*
1287          * If nothing needs to be added to the string, then return
1288          * the "original" (although possibly modified) value.
1289          */
1290         if (*origval == '-' && pidp == NULL)
1291                 return (origval);
1292
1293         /*
1294          * Create a copy of the string to add '-' and/or 'p' to the
1295          * original value.
1296          */
1297         if ((newopts = ns = malloc(len + 3)) == NULL)
1298                 errx(1, "malloc failed");
1299
1300         if (*origval != '-')
1301                 *ns++ = '-';    /* add option flag */
1302
1303         if (pidp == NULL)
1304                 strcpy(ns, origval);
1305         else {
1306                 /*
1307                  * Copy everything before the pid string, add the `p',
1308                  * and then copy the pid string.
1309                  */
1310                 len = pidp - origval;
1311                 memcpy(ns, origval, len);
1312                 ns += len;
1313                 *ns++ = 'p';
1314                 strcpy(ns, pidp);
1315         }
1316
1317         return (newopts);
1318 }
1319
1320 static int
1321 check_procfs(void)
1322 {
1323         struct statfs mnt;
1324
1325         if (statfs("/proc", &mnt) < 0)
1326                 return (0);
1327         if (strcmp(mnt.f_fstypename, "procfs") != 0)
1328                 return (0);
1329         return (1);
1330 }
1331
1332 static void
1333 usage(void)
1334 {
1335 #define SINGLE_OPTS     "[-aCcde" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
1336
1337         (void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
1338             "usage: ps " SINGLE_OPTS " [-O fmt | -o fmt] [-G gid[,gid...]]",
1339             "          [-M core] [-N system]",
1340             "          [-p pid[,pid...]] [-t tty[,tty...]] [-U user[,user...]]",
1341             "       ps [-L]");
1342         exit(1);
1343 }