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