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