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