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