2 * Copyright (c) 1990, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
28 * ------+---------+---------+-------- + --------+---------+---------+---------*
29 * Copyright (c) 2004 - Garance Alistair Drosehn <gad@FreeBSD.org>.
30 * All rights reserved.
32 * Significant modifications made to bring `ps' options somewhat closer
33 * to the standard for `ps' as described in SingleUnixSpec-v3.
34 * ------+---------+---------+-------- + --------+---------+---------+---------*
38 static const char copyright[] =
39 "@(#) Copyright (c) 1990, 1993, 1994\n\
40 The Regents of the University of California. All rights reserved.\n";
45 static char sccsid[] = "@(#)ps.c 8.4 (Berkeley) 4/2/94";
49 #include <sys/cdefs.h>
50 __FBSDID("$FreeBSD$");
52 #include <sys/param.h>
57 #include <sys/ioctl.h>
58 #include <sys/sysctl.h>
59 #include <sys/mount.h>
80 #define _PATH_PTS "/dev/pts/"
82 #define W_SEP " \t" /* "Whitespace" list separators */
83 #define T_SEP "," /* "Terminate-element" list separators */
87 #define OPT_LAZY_f "f"
89 #define DEF_UREAD 1 /* Always do the more-expensive read. */
90 #define OPT_LAZY_f /* I.e., the `-f' option is not added. */
94 * isdigit takes an `int', but expects values in the range of unsigned char.
95 * This wrapper ensures that values from a 'char' end up in the correct range.
97 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
100 int eval; /* Exit value */
101 time_t now; /* Current time(3) value */
103 int sumrusage; /* -S */
104 int termwidth; /* Width of the screen (0 == infinity). */
105 int showthreads; /* will threads be shown? */
107 struct velisthead varlist = STAILQ_HEAD_INITIALIZER(varlist);
109 static int forceuread = DEF_UREAD; /* Do extra work to get u-area. */
111 static int needcomm; /* -o "command" */
112 static int needenv; /* -e */
113 static int needuser; /* -o "user" */
114 static int optfatal; /* Fatal error parsing some list-option. */
115 static int pid_max; /* kern.max_pid */
117 static enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
120 typedef int addelem_rtn(struct listinfo *_inf, const char *_elem);
126 addelem_rtn *addelem;
138 static int addelem_gid(struct listinfo *, const char *);
139 static int addelem_jid(struct listinfo *, const char *);
140 static int addelem_pid(struct listinfo *, const char *);
141 static int addelem_tty(struct listinfo *, const char *);
142 static int addelem_uid(struct listinfo *, const char *);
143 static void add_list(struct listinfo *, const char *);
144 static void descendant_sort(KINFO *, int);
145 static void format_output(KINFO *);
146 static void *expand_list(struct listinfo *);
148 fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
149 KINFO *, char *, char *, int);
150 static void free_list(struct listinfo *);
151 static void init_list(struct listinfo *, addelem_rtn, int, const char *);
152 static char *kludge_oldps_options(const char *, char *, const char *);
153 static int pscomp(const void *, const void *);
154 static void saveuser(KINFO *);
155 static void scanvars(void);
156 static void sizevars(void);
157 static void pidmax_init(void);
158 static void usage(void);
160 static char dfmt[] = "pid,tt,state,time,command";
161 static char jfmt[] = "user,pid,ppid,pgid,sid,jobc,state,tt,time,command";
162 static char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
164 static char o1[] = "pid";
165 static char o2[] = "tt,state,time,command";
166 static char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
167 static char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
169 static char Zfmt[] = "label";
171 #define PS_ARGS "AaCcde" OPT_LAZY_f "G:gHhjJ:LlM:mN:O:o:p:rSTt:U:uvwXxZ"
174 main(int argc, char *argv[])
176 struct listinfo gidlist, jidlist, pgrplist, pidlist;
177 struct listinfo ruidlist, sesslist, ttylist, uidlist;
178 struct kinfo_proc *kp;
179 KINFO *kinfo = NULL, *next_KINFO;
182 struct winsize ws = { .ws_row = 0 };
183 const char *nlistf, *memf, *str;
185 int all, ch, elem, flag, _fmt, i, lineno, linelen, left;
186 int descendancy, nentries, nkept, nselectors;
187 int prtheader, wflag, what, xkeep, xkeep_implied;
188 int fwidthmin, fwidthmax;
189 char errbuf[_POSIX2_LINE_MAX];
190 char fmtbuf[_POSIX2_LINE_MAX];
192 (void) setlocale(LC_ALL, "");
193 time(&now); /* Used by routines in print.c. */
195 if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
196 termwidth = atoi(cols);
197 else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
198 ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
199 ioctl(STDIN_FILENO, TIOCGWINSZ, (char *)&ws) == -1) ||
203 termwidth = ws.ws_col - 1;
206 * Hide a number of option-processing kludges in a separate routine,
207 * to support some historical BSD behaviors, such as `ps axu'.
210 argv[1] = kludge_oldps_options(PS_ARGS, argv[1], argv[2]);
214 all = descendancy = _fmt = nselectors = optfatal = 0;
215 prtheader = showthreads = wflag = xkeep_implied = 0;
216 xkeep = -1; /* Neither -x nor -X. */
217 init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
218 init_list(&jidlist, addelem_jid, sizeof(int), "jail id");
219 init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
220 init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
221 init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
222 init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
223 init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
224 init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
225 memf = _PATH_DEVNULL;
228 argc = xo_parse_args(argc, argv);
232 while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
236 * Exactly the same as `-ax'. This has been
237 * added for compatibility with SUSv3, but for
238 * now it will not be described in the man page.
256 case 'e': /* XXX set ufmt */
261 if (getuid() == 0 || getgid() == 0)
266 add_list(&gidlist, optarg);
273 * XXX - This SUSv3 behavior is still under debate
274 * since it conflicts with the (undocumented)
275 * `-g' option. So we skip it for now.
277 add_list(&pgrplist, optarg);
282 /* The historical BSD-ish (from SunOS) behavior. */
286 showthreads = KERN_PROC_INC_THREAD;
289 prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
292 add_list(&jidlist, optarg);
322 o1[0] = o2[0] = '\0';
330 add_list(&pidlist, optarg);
332 * Note: `-p' does not *set* xkeep, but any values
333 * from pidlist are checked before xkeep is. That
334 * way they are always matched, even if the user
342 * XXX - This un-standard option is still under
343 * debate. This is what SUSv3 defines as
344 * the `-U' option, and while it would be
345 * nice to have, it could cause even more
346 * confusion to implement it as `-R'.
348 add_list(&ruidlist, optarg);
362 * XXX - This non-standard option is still under
363 * debate. This *is* supported on Solaris,
364 * Linux, and IRIX, but conflicts with `-s'
365 * on NetBSD and maybe some older BSD's.
367 add_list(&sesslist, optarg);
373 if ((optarg = ttyname(STDIN_FILENO)) == NULL)
374 xo_errx(1, "stdin: not a terminal");
377 add_list(&ttylist, optarg);
382 /* This is what SUSv3 defines as the `-u' option. */
383 add_list(&uidlist, optarg);
401 termwidth = UNLIMITED;
402 else if (termwidth < 131)
408 * Note that `-X' and `-x' are not standard "selector"
409 * options. For most selector-options, we check *all*
410 * processes to see if any are matched by the given
411 * value(s). After we have a set of all the matched
412 * processes, then `-X' and `-x' govern whether we
413 * modify that *matched* set for processes which do
414 * not have a controlling terminal. `-X' causes
415 * those processes to be deleted from the matched
416 * set, while `-x' causes them to be kept.
435 * If there arguments after processing all the options, attempt
436 * to treat them as a list of process ids.
439 if (!isdigitch(**argv))
441 add_list(&pidlist, *argv);
445 xo_warnx("illegal argument: %s\n", *argv);
449 exit(1); /* Error messages already printed. */
450 if (xkeep < 0) /* Neither -X nor -x was specified. */
451 xkeep = xkeep_implied;
453 kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
455 xo_errx(1, "%s", errbuf);
460 if (nselectors == 0) {
461 uidlist.l.ptr = malloc(sizeof(uid_t));
462 if (uidlist.l.ptr == NULL)
463 xo_errx(1, "malloc failed");
465 uidlist.count = uidlist.maxcount = 1;
466 *uidlist.l.uids = getuid();
470 * scan requested variables, noting what structures are needed,
471 * and adjusting header widths as appropriate.
476 * Get process list. If the user requested just one selector-
477 * option, then kvm_getprocs can be asked to return just those
478 * processes. Otherwise, have it return all processes, and
479 * then this routine will search that full list and select the
480 * processes which match any of the user's selector-options.
482 what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
484 if (nselectors == 1) {
485 if (gidlist.count == 1) {
486 what = KERN_PROC_RGID | showthreads;
487 flag = *gidlist.l.gids;
489 } else if (pgrplist.count == 1) {
490 what = KERN_PROC_PGRP | showthreads;
491 flag = *pgrplist.l.pids;
493 } else if (pidlist.count == 1) {
494 what = KERN_PROC_PID | showthreads;
495 flag = *pidlist.l.pids;
497 } else if (ruidlist.count == 1) {
498 what = KERN_PROC_RUID | showthreads;
499 flag = *ruidlist.l.uids;
501 } else if (sesslist.count == 1) {
502 what = KERN_PROC_SESSION | showthreads;
503 flag = *sesslist.l.pids;
505 } else if (ttylist.count == 1) {
506 what = KERN_PROC_TTY | showthreads;
507 flag = *ttylist.l.ttys;
509 } else if (uidlist.count == 1) {
510 what = KERN_PROC_UID | showthreads;
511 flag = *uidlist.l.uids;
514 /* No need for this routine to select processes. */
523 kp = kvm_getprocs(kd, what, flag, &nentries);
524 if ((kp == NULL && nentries > 0) || (kp != NULL && nentries < 0))
525 xo_errx(1, "%s", kvm_geterr(kd));
528 if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
529 xo_errx(1, "malloc failed");
530 for (i = nentries; --i >= 0; ++kp) {
532 * If the user specified multiple selection-criteria,
533 * then keep any process matched by the inclusive OR
534 * of all the selection-criteria given.
536 if (pidlist.count > 0) {
537 for (elem = 0; elem < pidlist.count; elem++)
538 if (kp->ki_pid == pidlist.l.pids[elem])
542 * Note that we had to process pidlist before
543 * filtering out processes which do not have
544 * a controlling terminal.
547 if ((kp->ki_tdev == NODEV ||
548 (kp->ki_flag & P_CONTROLT) == 0))
553 if (gidlist.count > 0) {
554 for (elem = 0; elem < gidlist.count; elem++)
555 if (kp->ki_rgid == gidlist.l.gids[elem])
558 if (jidlist.count > 0) {
559 for (elem = 0; elem < jidlist.count; elem++)
560 if (kp->ki_jid == jidlist.l.jids[elem])
563 if (pgrplist.count > 0) {
564 for (elem = 0; elem < pgrplist.count; elem++)
566 pgrplist.l.pids[elem])
569 if (ruidlist.count > 0) {
570 for (elem = 0; elem < ruidlist.count; elem++)
572 ruidlist.l.uids[elem])
575 if (sesslist.count > 0) {
576 for (elem = 0; elem < sesslist.count; elem++)
577 if (kp->ki_sid == sesslist.l.pids[elem])
580 if (ttylist.count > 0) {
581 for (elem = 0; elem < ttylist.count; elem++)
582 if (kp->ki_tdev == ttylist.l.ttys[elem])
585 if (uidlist.count > 0) {
586 for (elem = 0; elem < uidlist.count; elem++)
587 if (kp->ki_uid == uidlist.l.uids[elem])
591 * This process did not match any of the user's
592 * selector-options, so skip the process.
597 next_KINFO = &kinfo[nkept];
598 next_KINFO->ki_p = kp;
599 next_KINFO->ki_d.level = 0;
600 next_KINFO->ki_d.prefix = NULL;
601 next_KINFO->ki_pcpu = getpcpu(next_KINFO);
602 if (sortby == SORTMEM)
603 next_KINFO->ki_memsize = kp->ki_tsize +
604 kp->ki_dsize + kp->ki_ssize;
606 saveuser(next_KINFO);
622 qsort(kinfo, nkept, sizeof(KINFO), pscomp);
625 * We want things in descendant order
628 descendant_sort(kinfo, nkept);
632 * Prepare formatted output.
634 for (i = 0; i < nkept; i++)
635 format_output(&kinfo[i]);
640 xo_open_container("process-information");
642 if (xo_get_style(NULL) != XO_STYLE_TEXT)
643 termwidth = UNLIMITED;
646 * Output formatted lines.
648 xo_open_list("process");
649 for (i = lineno = 0; i < nkept; i++) {
651 xo_open_instance("process");
652 STAILQ_FOREACH(vent, &varlist, next_ve) {
653 ks = STAILQ_FIRST(&kinfo[i].ki_ks);
654 STAILQ_REMOVE_HEAD(&kinfo[i].ki_ks, ks_next);
655 /* Truncate rightmost column if necessary. */
656 fwidthmax = _POSIX2_LINE_MAX;
657 if (STAILQ_NEXT(vent, next_ve) == NULL &&
658 termwidth != UNLIMITED && ks->ks_str != NULL) {
659 left = termwidth - linelen;
660 if (left > 0 && left < (int)strlen(ks->ks_str))
667 /* No padding for the last column, if it's LJUST. */
668 fwidthmin = (xo_get_style(NULL) != XO_STYLE_TEXT ||
669 (STAILQ_NEXT(vent, next_ve) == NULL &&
670 (vent->var->flag & LJUST))) ? 0 : vent->var->width;
671 snprintf(fmtbuf, sizeof(fmtbuf), "{:%s/%%%s%d..%ds}",
672 vent->var->field ?: vent->var->name,
673 (vent->var->flag & LJUST) ? "-" : "",
674 fwidthmin, fwidthmax);
675 xo_emit(fmtbuf, str);
676 linelen += fwidthmin;
678 if (ks->ks_str != NULL) {
685 if (STAILQ_NEXT(vent, next_ve) != NULL) {
691 xo_close_instance("process");
692 if (prtheader && lineno++ == prtheader - 4) {
698 xo_close_list("process");
699 xo_close_container("process-information");
705 free_list(&pgrplist);
706 free_list(&ruidlist);
707 free_list(&sesslist);
710 for (i = 0; i < nkept; i++)
711 free(kinfo[i].ki_d.prefix);
718 addelem_gid(struct listinfo *inf, const char *elem)
721 const char *nameorID;
725 if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
727 xo_warnx("Invalid (zero-length) %s name", inf->lname);
729 xo_warnx("%s name too long: %s", inf->lname, elem);
731 return (0); /* Do not add this value. */
735 * SUSv3 states that `ps -G grouplist' should match "real-group
736 * ID numbers", and does not mention group-names. I do want to
737 * also support group-names, so this tries for a group-id first,
738 * and only tries for a name if that doesn't work. This is the
739 * opposite order of what is done in addelem_uid(), but in
740 * practice the order would only matter for group-names which
746 bigtemp = strtoul(elem, &endp, 10);
747 if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
748 nameorID = "name or ID matches";
749 grp = getgrgid((gid_t)bigtemp);
752 grp = getgrnam(elem);
754 xo_warnx("No %s %s '%s'", inf->lname, nameorID, elem);
758 if (inf->count >= inf->maxcount)
760 inf->l.gids[(inf->count)++] = grp->gr_gid;
765 addelem_jid(struct listinfo *inf, const char *elem)
770 warnx("Invalid (zero-length) jail id");
772 return (0); /* Do not add this value. */
775 tempid = jail_getid(elem);
777 warnx("Invalid %s: %s", inf->lname, elem);
782 if (inf->count >= inf->maxcount)
784 inf->l.jids[(inf->count)++] = tempid;
789 addelem_pid(struct listinfo *inf, const char *elem)
795 xo_warnx("Invalid (zero-length) process id");
797 return (0); /* Do not add this value. */
801 tempid = strtol(elem, &endp, 10);
802 if (*endp != '\0' || tempid < 0 || elem == endp) {
803 xo_warnx("Invalid %s: %s", inf->lname, elem);
805 } else if (errno != 0 || tempid > pid_max) {
806 xo_warnx("%s too large: %s", inf->lname, elem);
809 if (errno == ERANGE) {
813 if (inf->count >= inf->maxcount)
815 inf->l.pids[(inf->count)++] = tempid;
820 * The user can specify a device via one of three formats:
821 * 1) fully qualified, e.g.: /dev/ttyp0 /dev/console /dev/pts/0
822 * 2) missing "/dev", e.g.: ttyp0 console pts/0
823 * 3) two-letters, e.g.: p0 co 0
824 * (matching letters that would be seen in the "TT" column)
827 addelem_tty(struct listinfo *inf, const char *elem)
831 char pathbuf[PATH_MAX], pathbuf2[PATH_MAX], pathbuf3[PATH_MAX];
841 if (strcmp(elem, "co") == 0) {
842 ttypath = _PATH_CONSOLE;
847 strlcpy(pathbuf, _PATH_DEV, sizeof(pathbuf));
848 strlcat(pathbuf, elem, sizeof(pathbuf));
850 if (strncmp(pathbuf, _PATH_TTY, strlen(_PATH_TTY)) == 0)
852 if (strncmp(pathbuf, _PATH_PTS, strlen(_PATH_PTS)) == 0)
854 if (strcmp(pathbuf, _PATH_CONSOLE) == 0)
856 /* Check to see if /dev/tty${elem} exists */
857 strlcpy(pathbuf2, _PATH_TTY, sizeof(pathbuf2));
858 strlcat(pathbuf2, elem, sizeof(pathbuf2));
859 if (stat(pathbuf2, &sb) == 0 && S_ISCHR(sb.st_mode)) {
860 /* No need to repeat stat() && S_ISCHR() checks */
864 /* Check to see if /dev/pts/${elem} exists */
865 strlcpy(pathbuf3, _PATH_PTS, sizeof(pathbuf3));
866 strlcat(pathbuf3, elem, sizeof(pathbuf3));
867 if (stat(pathbuf3, &sb) == 0 && S_ISCHR(sb.st_mode)) {
868 /* No need to repeat stat() && S_ISCHR() checks */
875 if (stat(ttypath, &sb) == -1) {
876 if (pathbuf3[0] != '\0')
877 xo_warn("%s, %s, and %s", pathbuf3, pathbuf2,
880 xo_warn("%s", ttypath);
884 if (!S_ISCHR(sb.st_mode)) {
885 if (pathbuf3[0] != '\0')
886 xo_warnx("%s, %s, and %s: Not a terminal",
887 pathbuf3, pathbuf2, ttypath);
889 xo_warnx("%s: Not a terminal", ttypath);
894 if (inf->count >= inf->maxcount)
896 inf->l.ttys[(inf->count)++] = sb.st_rdev;
901 addelem_uid(struct listinfo *inf, const char *elem)
907 if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
909 xo_warnx("Invalid (zero-length) %s name", inf->lname);
911 xo_warnx("%s name too long: %s", inf->lname, elem);
913 return (0); /* Do not add this value. */
916 pwd = getpwnam(elem);
919 bigtemp = strtoul(elem, &endp, 10);
920 if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
921 xo_warnx("No %s named '%s'", inf->lname, elem);
923 /* The string is all digits, so it might be a userID. */
924 pwd = getpwuid((uid_t)bigtemp);
926 xo_warnx("No %s name or ID matches '%s'",
932 * These used to be treated as minor warnings (and the
933 * option was simply ignored), but now they are fatal
934 * errors (and the command will be aborted).
939 if (inf->count >= inf->maxcount)
941 inf->l.uids[(inf->count)++] = pwd->pw_uid;
946 add_list(struct listinfo *inf, const char *argp)
951 char elemcopy[PATH_MAX];
954 inf->addelem(inf, argp);
955 while (*argp != '\0') {
956 while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
961 if (strchr(T_SEP, *argp) == NULL) {
962 endp = elemcopy + sizeof(elemcopy) - 1;
963 while (*argp != '\0' && cp <= endp &&
964 strchr(W_SEP T_SEP, *argp) == NULL)
972 * Add this single element to the given list.
974 inf->addelem(inf, elemcopy);
977 * The string is too long to copy. Find the end
978 * of the string to print out the warning message.
980 while (*argp != '\0' && strchr(W_SEP T_SEP,
983 xo_warnx("Value too long: %.*s", (int)(argp - savep),
988 * Skip over any number of trailing whitespace characters,
989 * but only one (at most) trailing element-terminating
992 while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
994 if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
996 /* Catch case where string ended with a comma. */
998 inf->addelem(inf, argp);
1004 descendant_sort(KINFO *ki, int items)
1006 int dst, lvl, maxlvl, n, ndst, nsrc, siblings, src;
1007 unsigned char *path;
1011 * First, sort the entries by descendancy, tracking the descendancy
1012 * depth in the ki_d.level field.
1016 while (src < items) {
1017 if (ki[src].ki_d.level) {
1021 for (nsrc = 1; src + nsrc < items; nsrc++)
1022 if (!ki[src + nsrc].ki_d.level)
1025 for (dst = 0; dst < items; dst++) {
1026 if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_pid)
1028 if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_ppid)
1037 for (ndst = 1; dst + ndst < items; ndst++)
1038 if (ki[dst + ndst].ki_d.level <= ki[dst].ki_d.level)
1041 for (n = src; n < src + nsrc; n++) {
1042 ki[n].ki_d.level += ki[dst].ki_d.level + 1;
1043 if (maxlvl < ki[n].ki_d.level)
1044 maxlvl = ki[n].ki_d.level;
1050 memmove(ki + src, ki + src + 1,
1051 (dst - src + ndst - 1) * sizeof *ki);
1052 ki[dst + ndst - 1] = kn;
1056 } else if (src != dst + ndst) {
1058 memmove(ki + dst + ndst + 1, ki + dst + ndst,
1059 (src - dst - ndst) * sizeof *ki);
1060 ki[dst + ndst] = kn;
1073 * Now populate ki_d.prefix (instead of ki_d.level) with the command
1074 * prefix used to show descendancies.
1076 path = malloc((maxlvl + 7) / 8);
1077 memset(path, '\0', (maxlvl + 7) / 8);
1078 for (src = 0; src < items; src++) {
1079 if ((lvl = ki[src].ki_d.level) == 0) {
1080 ki[src].ki_d.prefix = NULL;
1083 if ((ki[src].ki_d.prefix = malloc(lvl * 2 + 1)) == NULL)
1084 xo_errx(1, "malloc failed");
1085 for (n = 0; n < lvl - 2; n++) {
1086 ki[src].ki_d.prefix[n * 2] =
1087 path[n / 8] & 1 << (n % 8) ? '|' : ' ';
1088 ki[src].ki_d.prefix[n * 2 + 1] = ' ';
1091 /* Have I any more siblings? */
1092 for (siblings = 0, dst = src + 1; dst < items; dst++) {
1093 if (ki[dst].ki_d.level > lvl)
1095 if (ki[dst].ki_d.level == lvl)
1100 path[n / 8] |= 1 << (n % 8);
1102 path[n / 8] &= ~(1 << (n % 8));
1103 ki[src].ki_d.prefix[n * 2] = siblings ? '|' : '`';
1104 ki[src].ki_d.prefix[n * 2 + 1] = '-';
1107 strcpy(ki[src].ki_d.prefix + n * 2, "- ");
1113 expand_list(struct listinfo *inf)
1118 newmax = (inf->maxcount + 1) << 1;
1119 newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
1120 if (newlist == NULL) {
1122 xo_errx(1, "realloc to %d %ss failed", newmax, inf->lname);
1124 inf->maxcount = newmax;
1125 inf->l.ptr = newlist;
1131 free_list(struct listinfo *inf)
1134 inf->count = inf->elemsize = inf->maxcount = 0;
1135 if (inf->l.ptr != NULL)
1137 inf->addelem = NULL;
1143 init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
1147 inf->count = inf->maxcount = 0;
1148 inf->elemsize = elemsize;
1149 inf->addelem = artn;
1155 find_varentry(VAR *v)
1157 struct varent *vent;
1159 STAILQ_FOREACH(vent, &varlist, next_ve) {
1160 if (strcmp(vent->var->name, v->name) == 0)
1169 struct varent *vent;
1172 STAILQ_FOREACH(vent, &varlist, next_ve) {
1182 format_output(KINFO *ki)
1184 struct varent *vent;
1190 STAILQ_INIT(&ki->ki_ks);
1191 STAILQ_FOREACH(vent, &varlist, next_ve) {
1193 str = (v->oproc)(ki, vent);
1194 ks = malloc(sizeof(*ks));
1196 xo_errx(1, "malloc failed");
1198 STAILQ_INSERT_TAIL(&ki->ki_ks, ks, ks_next);
1211 struct varent *vent;
1215 STAILQ_FOREACH(vent, &varlist, next_ve) {
1217 i = strlen(vent->header);
1224 fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
1225 char *comm, char *thread, int maxlen)
1229 s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm,
1230 showthreads && ki->ki_p->ki_numthreads > 1 ? thread : NULL, maxlen);
1234 #define UREADOK(ki) (forceuread || (ki->ki_p->ki_flag & P_INMEM))
1241 if (ki->ki_p->ki_flag & P_INMEM) {
1243 * The u-area might be swapped out, and we can't get
1244 * at it because we have a crashdump and no swap.
1245 * If it's here fill in these fields, otherwise, just
1252 * save arguments if needed
1255 if (ki->ki_p->ki_stat == SZOMB)
1256 ki->ki_args = strdup("<defunct>");
1257 else if (UREADOK(ki) || (ki->ki_p->ki_args != NULL))
1258 ki->ki_args = fmt(kvm_getargv, ki,
1259 ki->ki_p->ki_comm, ki->ki_p->ki_tdname, MAXCOMLEN);
1261 asprintf(&argsp, "(%s)", ki->ki_p->ki_comm);
1262 ki->ki_args = argsp;
1264 if (ki->ki_args == NULL)
1265 xo_errx(1, "malloc failed");
1271 ki->ki_env = fmt(kvm_getenvv, ki,
1272 (char *)NULL, (char *)NULL, 0);
1274 ki->ki_env = strdup("()");
1275 if (ki->ki_env == NULL)
1276 xo_errx(1, "malloc failed");
1282 /* A macro used to improve the readability of pscomp(). */
1283 #define DIFF_RETURN(a, b, field) do { \
1284 if ((a)->field != (b)->field) \
1285 return (((a)->field < (b)->field) ? -1 : 1); \
1289 pscomp(const void *a, const void *b)
1291 const KINFO *ka, *kb;
1295 /* SORTCPU and SORTMEM are sorted in descending order. */
1296 if (sortby == SORTCPU)
1297 DIFF_RETURN(kb, ka, ki_pcpu);
1298 if (sortby == SORTMEM)
1299 DIFF_RETURN(kb, ka, ki_memsize);
1301 * TTY's are sorted in ascending order, except that all NODEV
1302 * processes come before all processes with a device.
1304 if (ka->ki_p->ki_tdev != kb->ki_p->ki_tdev) {
1305 if (ka->ki_p->ki_tdev == NODEV)
1307 if (kb->ki_p->ki_tdev == NODEV)
1309 DIFF_RETURN(ka, kb, ki_p->ki_tdev);
1312 /* PID's and TID's (threads) are sorted in ascending order. */
1313 DIFF_RETURN(ka, kb, ki_p->ki_pid);
1314 DIFF_RETURN(ka, kb, ki_p->ki_tid);
1320 * ICK (all for getopt), would rather hide the ugliness
1321 * here than taint the main code.
1326 * The old convention that 't' with no trailing tty arg means the users
1327 * tty, is only supported if argv[1] doesn't begin with a '-'. This same
1328 * feature is available with the option 'T', which takes no argument.
1331 kludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
1334 char *argp, *cp, *newopts, *ns, *optp, *pidp;
1337 * See if the original value includes any option which takes an
1338 * argument (and will thus use up the remainder of the string).
1341 if (optlist != NULL) {
1342 for (cp = origval; *cp != '\0'; cp++) {
1343 optp = strchr(optlist, *cp);
1344 if ((optp != NULL) && *(optp + 1) == ':') {
1350 if (argp != NULL && *origval == '-')
1354 * if last letter is a 't' flag with no argument (in the context
1355 * of the oldps options -- option string NOT starting with a '-' --
1356 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1358 * However, if a flag accepting a string argument is found earlier
1359 * in the option string (including a possible `t' flag), then the
1360 * remainder of the string must be the argument to that flag; so
1361 * do not modify that argument. Note that a trailing `t' would
1362 * cause argp to be set, if argp was not already set by some
1365 len = strlen(origval);
1366 cp = origval + len - 1;
1368 if (*cp == 't' && *origval != '-' && cp == argp) {
1369 if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
1371 } else if (argp == NULL) {
1373 * The original value did not include any option which takes
1374 * an argument (and that would include `p' and `t'), so check
1375 * the value for trailing number, or comma-separated list of
1376 * numbers, which we will treat as a pid request.
1378 if (isdigitch(*cp)) {
1379 while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1386 * If nothing needs to be added to the string, then return
1387 * the "original" (although possibly modified) value.
1389 if (*origval == '-' && pidp == NULL)
1393 * Create a copy of the string to add '-' and/or 'p' to the
1396 if ((newopts = ns = malloc(len + 3)) == NULL)
1397 xo_errx(1, "malloc failed");
1399 if (*origval != '-')
1400 *ns++ = '-'; /* add option flag */
1403 strcpy(ns, origval);
1406 * Copy everything before the pid string, add the `p',
1407 * and then copy the pid string.
1409 len = pidp - origval;
1410 memcpy(ns, origval, len);
1424 intsize = sizeof(pid_max);
1425 if (sysctlbyname("kern.pid_max", &pid_max, &intsize, NULL, 0) < 0) {
1426 xo_warn("unable to read kern.pid_max");
1434 #define SINGLE_OPTS "[-aCcde" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
1436 (void)xo_error("%s\n%s\n%s\n%s\n",
1437 "usage: ps " SINGLE_OPTS " [-O fmt | -o fmt] [-G gid[,gid...]]",
1438 " [-J jid[,jid...]] [-M core] [-N system]",
1439 " [-p pid[,pid...]] [-t tty[,tty...]] [-U user[,user...]]",