2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1990, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
30 * ------+---------+---------+-------- + --------+---------+---------+---------*
31 * Copyright (c) 2004 - Garance Alistair Drosehn <gad@FreeBSD.org>.
32 * All rights reserved.
34 * Significant modifications made to bring `ps' options somewhat closer
35 * to the standard for `ps' as described in SingleUnixSpec-v3.
36 * ------+---------+---------+-------- + --------+---------+---------+---------*
40 static const char copyright[] =
41 "@(#) Copyright (c) 1990, 1993, 1994\n\
42 The Regents of the University of California. All rights reserved.\n";
47 static char sccsid[] = "@(#)ps.c 8.4 (Berkeley) 4/2/94";
51 #include <sys/cdefs.h>
52 __FBSDID("$FreeBSD$");
54 #include <sys/param.h>
59 #include <sys/ioctl.h>
60 #include <sys/sysctl.h>
61 #include <sys/mount.h>
82 #define _PATH_PTS "/dev/pts/"
84 #define W_SEP " \t" /* "Whitespace" list separators */
85 #define T_SEP "," /* "Terminate-element" list separators */
89 #define OPT_LAZY_f "f"
91 #define DEF_UREAD 1 /* Always do the more-expensive read. */
92 #define OPT_LAZY_f /* I.e., the `-f' option is not added. */
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.
99 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
102 int eval; /* Exit value */
103 time_t now; /* Current time(3) value */
105 int sumrusage; /* -S */
106 int termwidth; /* Width of the screen (0 == infinity). */
107 int showthreads; /* will threads be shown? */
109 struct velisthead varlist = STAILQ_HEAD_INITIALIZER(varlist);
111 static int forceuread = DEF_UREAD; /* Do extra work to get u-area. */
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 */
119 static enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
122 typedef int addelem_rtn(struct listinfo *_inf, const char *_elem);
128 addelem_rtn *addelem;
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 *);
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);
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,"
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,"
171 static char Zfmt[] = "label";
173 #define PS_ARGS "AaCcde" OPT_LAZY_f "G:gHhjJ:LlM:mN:O:o:p:rSTt:U:uvwXxZ"
176 main(int argc, char *argv[])
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;
184 struct winsize ws = { .ws_row = 0 };
185 const char *nlistf, *memf, *str;
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];
194 (void) setlocale(LC_ALL, "");
195 time(&now); /* Used by routines in print.c. */
198 * Compute default output line length before processing options.
199 * If COLUMNS is set, use it. Otherwise, if this is part of an
200 * interactive job (i.e. one associated with a terminal), use
201 * the terminal width. "Interactive" is determined by whether
202 * any of stdout, stderr, or stdin is a terminal. The intent
203 * is that "ps", "ps | more", and "ps | grep" all use the same
204 * default line length unless -w is specified.
206 * If not interactive, the default length was traditionally 79.
207 * It has been changed to unlimited. This is mostly for the
208 * benefit of non-interactive scripts, which arguably should
209 * use -ww, but is compatible with Linux.
211 if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
212 termwidth = atoi(cols);
213 else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
214 ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
215 ioctl(STDIN_FILENO, TIOCGWINSZ, (char *)&ws) == -1) ||
217 termwidth = UNLIMITED;
219 termwidth = ws.ws_col - 1;
222 * Hide a number of option-processing kludges in a separate routine,
223 * to support some historical BSD behaviors, such as `ps axu'.
226 argv[1] = kludge_oldps_options(PS_ARGS, argv[1], argv[2]);
230 all = descendancy = _fmt = nselectors = optfatal = 0;
231 prtheader = showthreads = wflag = xkeep_implied = 0;
232 xkeep = -1; /* Neither -x nor -X. */
233 init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
234 init_list(&jidlist, addelem_jid, sizeof(int), "jail id");
235 init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
236 init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
237 init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
238 init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
239 init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
240 init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
241 memf = _PATH_DEVNULL;
244 argc = xo_parse_args(argc, argv);
248 while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
252 * Exactly the same as `-ax'. This has been
253 * added for compatibility with SUSv3, but for
254 * now it will not be described in the man page.
272 case 'e': /* XXX set ufmt */
277 if (getuid() == 0 || getgid() == 0)
282 add_list(&gidlist, optarg);
289 * XXX - This SUSv3 behavior is still under debate
290 * since it conflicts with the (undocumented)
291 * `-g' option. So we skip it for now.
293 add_list(&pgrplist, optarg);
298 /* The historical BSD-ish (from SunOS) behavior. */
302 showthreads = KERN_PROC_INC_THREAD;
305 prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
308 add_list(&jidlist, optarg);
338 o1[0] = o2[0] = '\0';
346 add_list(&pidlist, optarg);
348 * Note: `-p' does not *set* xkeep, but any values
349 * from pidlist are checked before xkeep is. That
350 * way they are always matched, even if the user
358 * XXX - This un-standard option is still under
359 * debate. This is what SUSv3 defines as
360 * the `-U' option, and while it would be
361 * nice to have, it could cause even more
362 * confusion to implement it as `-R'.
364 add_list(&ruidlist, optarg);
378 * XXX - This non-standard option is still under
379 * debate. This *is* supported on Solaris,
380 * Linux, and IRIX, but conflicts with `-s'
381 * on NetBSD and maybe some older BSD's.
383 add_list(&sesslist, optarg);
389 if ((optarg = ttyname(STDIN_FILENO)) == NULL)
390 xo_errx(1, "stdin: not a terminal");
393 add_list(&ttylist, optarg);
398 /* This is what SUSv3 defines as the `-u' option. */
399 add_list(&uidlist, optarg);
417 termwidth = UNLIMITED;
418 else if (termwidth < 131 && termwidth != UNLIMITED)
424 * Note that `-X' and `-x' are not standard "selector"
425 * options. For most selector-options, we check *all*
426 * processes to see if any are matched by the given
427 * value(s). After we have a set of all the matched
428 * processes, then `-X' and `-x' govern whether we
429 * modify that *matched* set for processes which do
430 * not have a controlling terminal. `-X' causes
431 * those processes to be deleted from the matched
432 * set, while `-x' causes them to be kept.
451 * If there arguments after processing all the options, attempt
452 * to treat them as a list of process ids.
455 if (!isdigitch(**argv))
457 add_list(&pidlist, *argv);
461 xo_warnx("illegal argument: %s\n", *argv);
465 exit(1); /* Error messages already printed. */
466 if (xkeep < 0) /* Neither -X nor -x was specified. */
467 xkeep = xkeep_implied;
469 kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
471 xo_errx(1, "%s", errbuf);
476 if (nselectors == 0) {
477 uidlist.l.ptr = malloc(sizeof(uid_t));
478 if (uidlist.l.ptr == NULL)
479 xo_errx(1, "malloc failed");
481 uidlist.count = uidlist.maxcount = 1;
482 *uidlist.l.uids = getuid();
486 * scan requested variables, noting what structures are needed,
487 * and adjusting header widths as appropriate.
492 * Get process list. If the user requested just one selector-
493 * option, then kvm_getprocs can be asked to return just those
494 * processes. Otherwise, have it return all processes, and
495 * then this routine will search that full list and select the
496 * processes which match any of the user's selector-options.
498 what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
500 if (nselectors == 1) {
501 if (gidlist.count == 1) {
502 what = KERN_PROC_RGID | showthreads;
503 flag = *gidlist.l.gids;
505 } else if (pgrplist.count == 1) {
506 what = KERN_PROC_PGRP | showthreads;
507 flag = *pgrplist.l.pids;
509 } else if (pidlist.count == 1) {
510 what = KERN_PROC_PID | showthreads;
511 flag = *pidlist.l.pids;
513 } else if (ruidlist.count == 1) {
514 what = KERN_PROC_RUID | showthreads;
515 flag = *ruidlist.l.uids;
517 } else if (sesslist.count == 1) {
518 what = KERN_PROC_SESSION | showthreads;
519 flag = *sesslist.l.pids;
521 } else if (ttylist.count == 1) {
522 what = KERN_PROC_TTY | showthreads;
523 flag = *ttylist.l.ttys;
525 } else if (uidlist.count == 1) {
526 what = KERN_PROC_UID | showthreads;
527 flag = *uidlist.l.uids;
530 /* No need for this routine to select processes. */
539 kp = kvm_getprocs(kd, what, flag, &nentries);
541 * Ignore ESRCH to preserve behaviour of "ps -p nonexistent-pid"
542 * not reporting an error.
544 if ((kp == NULL && errno != ESRCH) || (kp != NULL && nentries < 0))
545 xo_errx(1, "%s", kvm_geterr(kd));
548 if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
549 xo_errx(1, "malloc failed");
550 for (i = nentries; --i >= 0; ++kp) {
552 * If the user specified multiple selection-criteria,
553 * then keep any process matched by the inclusive OR
554 * of all the selection-criteria given.
556 if (pidlist.count > 0) {
557 for (elem = 0; elem < pidlist.count; elem++)
558 if (kp->ki_pid == pidlist.l.pids[elem])
562 * Note that we had to process pidlist before
563 * filtering out processes which do not have
564 * a controlling terminal.
567 if ((kp->ki_tdev == NODEV ||
568 (kp->ki_flag & P_CONTROLT) == 0))
573 if (gidlist.count > 0) {
574 for (elem = 0; elem < gidlist.count; elem++)
575 if (kp->ki_rgid == gidlist.l.gids[elem])
578 if (jidlist.count > 0) {
579 for (elem = 0; elem < jidlist.count; elem++)
580 if (kp->ki_jid == jidlist.l.jids[elem])
583 if (pgrplist.count > 0) {
584 for (elem = 0; elem < pgrplist.count; elem++)
586 pgrplist.l.pids[elem])
589 if (ruidlist.count > 0) {
590 for (elem = 0; elem < ruidlist.count; elem++)
592 ruidlist.l.uids[elem])
595 if (sesslist.count > 0) {
596 for (elem = 0; elem < sesslist.count; elem++)
597 if (kp->ki_sid == sesslist.l.pids[elem])
600 if (ttylist.count > 0) {
601 for (elem = 0; elem < ttylist.count; elem++)
602 if (kp->ki_tdev == ttylist.l.ttys[elem])
605 if (uidlist.count > 0) {
606 for (elem = 0; elem < uidlist.count; elem++)
607 if (kp->ki_uid == uidlist.l.uids[elem])
611 * This process did not match any of the user's
612 * selector-options, so skip the process.
617 next_KINFO = &kinfo[nkept];
618 next_KINFO->ki_p = kp;
619 next_KINFO->ki_d.level = 0;
620 next_KINFO->ki_d.prefix = NULL;
621 next_KINFO->ki_pcpu = getpcpu(next_KINFO);
622 if (sortby == SORTMEM)
623 next_KINFO->ki_memsize = kp->ki_tsize +
624 kp->ki_dsize + kp->ki_ssize;
626 saveuser(next_KINFO);
642 qsort(kinfo, nkept, sizeof(KINFO), pscomp);
645 * We want things in descendant order
648 descendant_sort(kinfo, nkept);
652 * Prepare formatted output.
654 for (i = 0; i < nkept; i++)
655 format_output(&kinfo[i]);
660 xo_open_container("process-information");
662 if (xo_get_style(NULL) != XO_STYLE_TEXT)
663 termwidth = UNLIMITED;
666 * Output formatted lines.
668 xo_open_list("process");
669 for (i = lineno = 0; i < nkept; i++) {
671 xo_open_instance("process");
672 STAILQ_FOREACH(vent, &varlist, next_ve) {
673 ks = STAILQ_FIRST(&kinfo[i].ki_ks);
674 STAILQ_REMOVE_HEAD(&kinfo[i].ki_ks, ks_next);
675 /* Truncate rightmost column if necessary. */
676 fwidthmax = _POSIX2_LINE_MAX;
677 if (STAILQ_NEXT(vent, next_ve) == NULL &&
678 termwidth != UNLIMITED && ks->ks_str != NULL) {
679 left = termwidth - linelen;
680 if (left > 0 && left < (int)strlen(ks->ks_str))
687 /* No padding for the last column, if it's LJUST. */
688 fwidthmin = (xo_get_style(NULL) != XO_STYLE_TEXT ||
689 (STAILQ_NEXT(vent, next_ve) == NULL &&
690 (vent->var->flag & LJUST))) ? 0 : vent->var->width;
691 snprintf(fmtbuf, sizeof(fmtbuf), "{:%s/%%%s%d..%ds}",
692 vent->var->field ? vent->var->field : vent->var->name,
693 (vent->var->flag & LJUST) ? "-" : "",
694 fwidthmin, fwidthmax);
695 xo_emit(fmtbuf, str);
696 linelen += fwidthmin;
698 if (ks->ks_str != NULL) {
705 if (STAILQ_NEXT(vent, next_ve) != NULL) {
711 xo_close_instance("process");
712 if (prtheader && lineno++ == prtheader - 4) {
718 xo_close_list("process");
719 xo_close_container("process-information");
725 free_list(&pgrplist);
726 free_list(&ruidlist);
727 free_list(&sesslist);
730 for (i = 0; i < nkept; i++)
731 free(kinfo[i].ki_d.prefix);
738 addelem_gid(struct listinfo *inf, const char *elem)
741 const char *nameorID;
745 if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
747 xo_warnx("Invalid (zero-length) %s name", inf->lname);
749 xo_warnx("%s name too long: %s", inf->lname, elem);
751 return (0); /* Do not add this value. */
755 * SUSv3 states that `ps -G grouplist' should match "real-group
756 * ID numbers", and does not mention group-names. I do want to
757 * also support group-names, so this tries for a group-id first,
758 * and only tries for a name if that doesn't work. This is the
759 * opposite order of what is done in addelem_uid(), but in
760 * practice the order would only matter for group-names which
766 bigtemp = strtoul(elem, &endp, 10);
767 if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
768 nameorID = "name or ID matches";
769 grp = getgrgid((gid_t)bigtemp);
772 grp = getgrnam(elem);
774 xo_warnx("No %s %s '%s'", inf->lname, nameorID, elem);
778 if (inf->count >= inf->maxcount)
780 inf->l.gids[(inf->count)++] = grp->gr_gid;
785 addelem_jid(struct listinfo *inf, const char *elem)
790 warnx("Invalid (zero-length) jail id");
792 return (0); /* Do not add this value. */
795 tempid = jail_getid(elem);
797 warnx("Invalid %s: %s", inf->lname, elem);
802 if (inf->count >= inf->maxcount)
804 inf->l.jids[(inf->count)++] = tempid;
809 addelem_pid(struct listinfo *inf, const char *elem)
815 xo_warnx("Invalid (zero-length) process id");
817 return (0); /* Do not add this value. */
821 tempid = strtol(elem, &endp, 10);
822 if (*endp != '\0' || tempid < 0 || elem == endp) {
823 xo_warnx("Invalid %s: %s", inf->lname, elem);
825 } else if (errno != 0 || tempid > pid_max) {
826 xo_warnx("%s too large: %s", inf->lname, elem);
829 if (errno == ERANGE) {
833 if (inf->count >= inf->maxcount)
835 inf->l.pids[(inf->count)++] = tempid;
840 * The user can specify a device via one of three formats:
841 * 1) fully qualified, e.g.: /dev/ttyp0 /dev/console /dev/pts/0
842 * 2) missing "/dev", e.g.: ttyp0 console pts/0
843 * 3) two-letters, e.g.: p0 co 0
844 * (matching letters that would be seen in the "TT" column)
847 addelem_tty(struct listinfo *inf, const char *elem)
851 char pathbuf[PATH_MAX], pathbuf2[PATH_MAX], pathbuf3[PATH_MAX];
861 if (strcmp(elem, "co") == 0) {
862 ttypath = _PATH_CONSOLE;
867 strlcpy(pathbuf, _PATH_DEV, sizeof(pathbuf));
868 strlcat(pathbuf, elem, sizeof(pathbuf));
870 if (strncmp(pathbuf, _PATH_TTY, strlen(_PATH_TTY)) == 0)
872 if (strncmp(pathbuf, _PATH_PTS, strlen(_PATH_PTS)) == 0)
874 if (strcmp(pathbuf, _PATH_CONSOLE) == 0)
876 /* Check to see if /dev/tty${elem} exists */
877 strlcpy(pathbuf2, _PATH_TTY, sizeof(pathbuf2));
878 strlcat(pathbuf2, elem, sizeof(pathbuf2));
879 if (stat(pathbuf2, &sb) == 0 && S_ISCHR(sb.st_mode)) {
880 /* No need to repeat stat() && S_ISCHR() checks */
884 /* Check to see if /dev/pts/${elem} exists */
885 strlcpy(pathbuf3, _PATH_PTS, sizeof(pathbuf3));
886 strlcat(pathbuf3, elem, sizeof(pathbuf3));
887 if (stat(pathbuf3, &sb) == 0 && S_ISCHR(sb.st_mode)) {
888 /* No need to repeat stat() && S_ISCHR() checks */
895 if (stat(ttypath, &sb) == -1) {
896 if (pathbuf3[0] != '\0')
897 xo_warn("%s, %s, and %s", pathbuf3, pathbuf2,
900 xo_warn("%s", ttypath);
904 if (!S_ISCHR(sb.st_mode)) {
905 if (pathbuf3[0] != '\0')
906 xo_warnx("%s, %s, and %s: Not a terminal",
907 pathbuf3, pathbuf2, ttypath);
909 xo_warnx("%s: Not a terminal", ttypath);
914 if (inf->count >= inf->maxcount)
916 inf->l.ttys[(inf->count)++] = sb.st_rdev;
921 addelem_uid(struct listinfo *inf, const char *elem)
927 if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
929 xo_warnx("Invalid (zero-length) %s name", inf->lname);
931 xo_warnx("%s name too long: %s", inf->lname, elem);
933 return (0); /* Do not add this value. */
936 pwd = getpwnam(elem);
939 bigtemp = strtoul(elem, &endp, 10);
940 if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
941 xo_warnx("No %s named '%s'", inf->lname, elem);
943 /* The string is all digits, so it might be a userID. */
944 pwd = getpwuid((uid_t)bigtemp);
946 xo_warnx("No %s name or ID matches '%s'",
952 * These used to be treated as minor warnings (and the
953 * option was simply ignored), but now they are fatal
954 * errors (and the command will be aborted).
959 if (inf->count >= inf->maxcount)
961 inf->l.uids[(inf->count)++] = pwd->pw_uid;
966 add_list(struct listinfo *inf, const char *argp)
971 char elemcopy[PATH_MAX];
974 inf->addelem(inf, argp);
975 while (*argp != '\0') {
976 while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
981 if (strchr(T_SEP, *argp) == NULL) {
982 endp = elemcopy + sizeof(elemcopy) - 1;
983 while (*argp != '\0' && cp <= endp &&
984 strchr(W_SEP T_SEP, *argp) == NULL)
992 * Add this single element to the given list.
994 inf->addelem(inf, elemcopy);
997 * The string is too long to copy. Find the end
998 * of the string to print out the warning message.
1000 while (*argp != '\0' && strchr(W_SEP T_SEP,
1003 xo_warnx("Value too long: %.*s", (int)(argp - savep),
1008 * Skip over any number of trailing whitespace characters,
1009 * but only one (at most) trailing element-terminating
1012 while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
1014 if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
1016 /* Catch case where string ended with a comma. */
1018 inf->addelem(inf, argp);
1024 descendant_sort(KINFO *ki, int items)
1026 int dst, lvl, maxlvl, n, ndst, nsrc, siblings, src;
1027 unsigned char *path;
1031 * First, sort the entries by descendancy, tracking the descendancy
1032 * depth in the ki_d.level field.
1036 while (src < items) {
1037 if (ki[src].ki_d.level) {
1041 for (nsrc = 1; src + nsrc < items; nsrc++)
1042 if (!ki[src + nsrc].ki_d.level)
1045 for (dst = 0; dst < items; dst++) {
1046 if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_pid)
1048 if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_ppid)
1057 for (ndst = 1; dst + ndst < items; ndst++)
1058 if (ki[dst + ndst].ki_d.level <= ki[dst].ki_d.level)
1061 for (n = src; n < src + nsrc; n++) {
1062 ki[n].ki_d.level += ki[dst].ki_d.level + 1;
1063 if (maxlvl < ki[n].ki_d.level)
1064 maxlvl = ki[n].ki_d.level;
1070 memmove(ki + src, ki + src + 1,
1071 (dst - src + ndst - 1) * sizeof *ki);
1072 ki[dst + ndst - 1] = kn;
1076 } else if (src != dst + ndst) {
1078 memmove(ki + dst + ndst + 1, ki + dst + ndst,
1079 (src - dst - ndst) * sizeof *ki);
1080 ki[dst + ndst] = kn;
1093 * Now populate ki_d.prefix (instead of ki_d.level) with the command
1094 * prefix used to show descendancies.
1096 path = malloc((maxlvl + 7) / 8);
1097 memset(path, '\0', (maxlvl + 7) / 8);
1098 for (src = 0; src < items; src++) {
1099 if ((lvl = ki[src].ki_d.level) == 0) {
1100 ki[src].ki_d.prefix = NULL;
1103 if ((ki[src].ki_d.prefix = malloc(lvl * 2 + 1)) == NULL)
1104 xo_errx(1, "malloc failed");
1105 for (n = 0; n < lvl - 2; n++) {
1106 ki[src].ki_d.prefix[n * 2] =
1107 path[n / 8] & 1 << (n % 8) ? '|' : ' ';
1108 ki[src].ki_d.prefix[n * 2 + 1] = ' ';
1111 /* Have I any more siblings? */
1112 for (siblings = 0, dst = src + 1; dst < items; dst++) {
1113 if (ki[dst].ki_d.level > lvl)
1115 if (ki[dst].ki_d.level == lvl)
1120 path[n / 8] |= 1 << (n % 8);
1122 path[n / 8] &= ~(1 << (n % 8));
1123 ki[src].ki_d.prefix[n * 2] = siblings ? '|' : '`';
1124 ki[src].ki_d.prefix[n * 2 + 1] = '-';
1127 strcpy(ki[src].ki_d.prefix + n * 2, "- ");
1133 expand_list(struct listinfo *inf)
1138 newmax = (inf->maxcount + 1) << 1;
1139 newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
1140 if (newlist == NULL) {
1142 xo_errx(1, "realloc to %d %ss failed", newmax, inf->lname);
1144 inf->maxcount = newmax;
1145 inf->l.ptr = newlist;
1151 free_list(struct listinfo *inf)
1154 inf->count = inf->elemsize = inf->maxcount = 0;
1155 if (inf->l.ptr != NULL)
1157 inf->addelem = NULL;
1163 init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
1167 inf->count = inf->maxcount = 0;
1168 inf->elemsize = elemsize;
1169 inf->addelem = artn;
1175 find_varentry(VAR *v)
1177 struct varent *vent;
1179 STAILQ_FOREACH(vent, &varlist, next_ve) {
1180 if (strcmp(vent->var->name, v->name) == 0)
1189 struct varent *vent;
1192 STAILQ_FOREACH(vent, &varlist, next_ve) {
1202 format_output(KINFO *ki)
1204 struct varent *vent;
1210 STAILQ_INIT(&ki->ki_ks);
1211 STAILQ_FOREACH(vent, &varlist, next_ve) {
1213 str = (v->oproc)(ki, vent);
1214 ks = malloc(sizeof(*ks));
1216 xo_errx(1, "malloc failed");
1218 STAILQ_INSERT_TAIL(&ki->ki_ks, ks, ks_next);
1231 struct varent *vent;
1235 STAILQ_FOREACH(vent, &varlist, next_ve) {
1237 i = strlen(vent->header);
1244 fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
1245 char *comm, char *thread, int maxlen)
1249 s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm,
1250 showthreads && ki->ki_p->ki_numthreads > 1 ? thread : NULL, maxlen);
1254 #define UREADOK(ki) (forceuread || (ki->ki_p->ki_flag & P_INMEM))
1261 if (ki->ki_p->ki_flag & P_INMEM) {
1263 * The u-area might be swapped out, and we can't get
1264 * at it because we have a crashdump and no swap.
1265 * If it's here fill in these fields, otherwise, just
1272 * save arguments if needed
1275 if (ki->ki_p->ki_stat == SZOMB)
1276 ki->ki_args = strdup("<defunct>");
1277 else if (UREADOK(ki) || (ki->ki_p->ki_args != NULL))
1278 ki->ki_args = fmt(kvm_getargv, ki,
1279 ki->ki_p->ki_comm, ki->ki_p->ki_tdname, MAXCOMLEN);
1281 asprintf(&argsp, "(%s)", ki->ki_p->ki_comm);
1282 ki->ki_args = argsp;
1284 if (ki->ki_args == NULL)
1285 xo_errx(1, "malloc failed");
1291 ki->ki_env = fmt(kvm_getenvv, ki,
1292 (char *)NULL, (char *)NULL, 0);
1294 ki->ki_env = strdup("()");
1295 if (ki->ki_env == NULL)
1296 xo_errx(1, "malloc failed");
1302 /* A macro used to improve the readability of pscomp(). */
1303 #define DIFF_RETURN(a, b, field) do { \
1304 if ((a)->field != (b)->field) \
1305 return (((a)->field < (b)->field) ? -1 : 1); \
1309 pscomp(const void *a, const void *b)
1311 const KINFO *ka, *kb;
1315 /* SORTCPU and SORTMEM are sorted in descending order. */
1316 if (sortby == SORTCPU)
1317 DIFF_RETURN(kb, ka, ki_pcpu);
1318 if (sortby == SORTMEM)
1319 DIFF_RETURN(kb, ka, ki_memsize);
1321 * TTY's are sorted in ascending order, except that all NODEV
1322 * processes come before all processes with a device.
1324 if (ka->ki_p->ki_tdev != kb->ki_p->ki_tdev) {
1325 if (ka->ki_p->ki_tdev == NODEV)
1327 if (kb->ki_p->ki_tdev == NODEV)
1329 DIFF_RETURN(ka, kb, ki_p->ki_tdev);
1332 /* PID's and TID's (threads) are sorted in ascending order. */
1333 DIFF_RETURN(ka, kb, ki_p->ki_pid);
1334 DIFF_RETURN(ka, kb, ki_p->ki_tid);
1340 * ICK (all for getopt), would rather hide the ugliness
1341 * here than taint the main code.
1346 * The old convention that 't' with no trailing tty arg means the users
1347 * tty, is only supported if argv[1] doesn't begin with a '-'. This same
1348 * feature is available with the option 'T', which takes no argument.
1351 kludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
1354 char *argp, *cp, *newopts, *ns, *optp, *pidp;
1357 * See if the original value includes any option which takes an
1358 * argument (and will thus use up the remainder of the string).
1361 if (optlist != NULL) {
1362 for (cp = origval; *cp != '\0'; cp++) {
1363 optp = strchr(optlist, *cp);
1364 if ((optp != NULL) && *(optp + 1) == ':') {
1370 if (argp != NULL && *origval == '-')
1374 * if last letter is a 't' flag with no argument (in the context
1375 * of the oldps options -- option string NOT starting with a '-' --
1376 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1378 * However, if a flag accepting a string argument is found earlier
1379 * in the option string (including a possible `t' flag), then the
1380 * remainder of the string must be the argument to that flag; so
1381 * do not modify that argument. Note that a trailing `t' would
1382 * cause argp to be set, if argp was not already set by some
1385 len = strlen(origval);
1386 cp = origval + len - 1;
1388 if (*cp == 't' && *origval != '-' && cp == argp) {
1389 if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
1391 } else if (argp == NULL) {
1393 * The original value did not include any option which takes
1394 * an argument (and that would include `p' and `t'), so check
1395 * the value for trailing number, or comma-separated list of
1396 * numbers, which we will treat as a pid request.
1398 if (isdigitch(*cp)) {
1399 while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1406 * If nothing needs to be added to the string, then return
1407 * the "original" (although possibly modified) value.
1409 if (*origval == '-' && pidp == NULL)
1413 * Create a copy of the string to add '-' and/or 'p' to the
1416 if ((newopts = ns = malloc(len + 3)) == NULL)
1417 xo_errx(1, "malloc failed");
1419 if (*origval != '-')
1420 *ns++ = '-'; /* add option flag */
1423 strcpy(ns, origval);
1426 * Copy everything before the pid string, add the `p',
1427 * and then copy the pid string.
1429 len = pidp - origval;
1430 memcpy(ns, origval, len);
1444 intsize = sizeof(pid_max);
1445 if (sysctlbyname("kern.pid_max", &pid_max, &intsize, NULL, 0) < 0) {
1446 xo_warn("unable to read kern.pid_max");
1454 #define SINGLE_OPTS "[-aCcde" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
1456 (void)xo_error("%s\n%s\n%s\n%s\n",
1457 "usage: ps " SINGLE_OPTS " [-O fmt | -o fmt] [-G gid[,gid...]]",
1458 " [-J jid[,jid...]] [-M core] [-N system]",
1459 " [-p pid[,pid...]] [-t tty[,tty...]] [-U user[,user...]]",