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