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>
56 #include <sys/ioctl.h>
57 #include <sys/sysctl.h>
58 #include <sys/mount.h>
77 #define _PATH_PTS "/dev/pts/"
79 #define W_SEP " \t" /* "Whitespace" list separators */
80 #define T_SEP "," /* "Terminate-element" list separators */
84 #define OPT_LAZY_f "f"
86 #define DEF_UREAD 1 /* Always do the more-expensive read. */
87 #define OPT_LAZY_f /* I.e., the `-f' option is not added. */
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.
94 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
97 int eval; /* Exit value */
98 time_t now; /* Current time(3) value */
100 int sumrusage; /* -S */
101 int termwidth; /* Width of the screen (0 == infinity). */
102 int showthreads; /* will threads be shown? */
104 struct velisthead varlist = STAILQ_HEAD_INITIALIZER(varlist);
106 static int forceuread = DEF_UREAD; /* Do extra work to get u-area. */
108 static int needcomm; /* -o "command" */
109 static int needenv; /* -e */
110 static int needuser; /* -o "user" */
111 static int optfatal; /* Fatal error parsing some list-option. */
113 static enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
116 typedef int addelem_rtn(struct listinfo *_inf, const char *_elem);
122 addelem_rtn *addelem;
133 static int addelem_gid(struct listinfo *, const char *);
134 static int addelem_pid(struct listinfo *, const char *);
135 static int addelem_tty(struct listinfo *, const char *);
136 static int addelem_uid(struct listinfo *, const char *);
137 static void add_list(struct listinfo *, const char *);
138 static void descendant_sort(KINFO *, int);
139 static void format_output(KINFO *);
140 static void *expand_list(struct listinfo *);
142 fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
143 KINFO *, char *, char *, int);
144 static void free_list(struct listinfo *);
145 static void init_list(struct listinfo *, addelem_rtn, int, const char *);
146 static char *kludge_oldps_options(const char *, char *, const char *);
147 static int pscomp(const void *, const void *);
148 static void saveuser(KINFO *);
149 static void scanvars(void);
150 static void sizevars(void);
151 static void usage(void);
153 static char dfmt[] = "pid,tt,state,time,command";
154 static char jfmt[] = "user,pid,ppid,pgid,sid,jobc,state,tt,time,command";
155 static char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
157 static char o1[] = "pid";
158 static char o2[] = "tt,state,time,command";
159 static char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
160 static char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
162 static char Zfmt[] = "label";
164 #define PS_ARGS "AaCcde" OPT_LAZY_f "G:gHhjLlM:mN:O:o:p:rSTt:U:uvwXxZ"
167 main(int argc, char *argv[])
169 struct listinfo gidlist, pgrplist, pidlist;
170 struct listinfo ruidlist, sesslist, ttylist, uidlist;
171 struct kinfo_proc *kp;
172 KINFO *kinfo = NULL, *next_KINFO;
176 const char *nlistf, *memf, *fmtstr, *str;
178 int all, ch, elem, flag, _fmt, i, lineno, linelen, left;
179 int descendancy, nentries, nkept, nselectors;
180 int prtheader, wflag, what, xkeep, xkeep_implied;
181 char errbuf[_POSIX2_LINE_MAX];
183 (void) setlocale(LC_ALL, "");
184 time(&now); /* Used by routines in print.c. */
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) ||
194 termwidth = ws.ws_col - 1;
197 * Hide a number of option-processing kludges in a separate routine,
198 * to support some historical BSD behaviors, such as `ps axu'.
201 argv[1] = kludge_oldps_options(PS_ARGS, argv[1], argv[2]);
203 all = descendancy = _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 = _PATH_DEVNULL;
215 while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
219 * Exactly the same as `-ax'. This has been
220 * added for compatibility with SUSv3, but for
221 * now it will not be described in the man page.
239 case 'e': /* XXX set ufmt */
244 if (getuid() == 0 || getgid() == 0)
249 add_list(&gidlist, optarg);
256 * XXX - This SUSv3 behavior is still under debate
257 * since it conflicts with the (undocumented)
258 * `-g' option. So we skip it for now.
260 add_list(&pgrplist, optarg);
265 /* The historical BSD-ish (from SunOS) behavior. */
269 showthreads = KERN_PROC_INC_THREAD;
272 prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
300 o1[0] = o2[0] = '\0';
308 add_list(&pidlist, optarg);
310 * Note: `-p' does not *set* xkeep, but any values
311 * from pidlist are checked before xkeep is. That
312 * way they are always matched, even if the user
320 * XXX - This un-standard option is still under
321 * debate. This is what SUSv3 defines as
322 * the `-U' option, and while it would be
323 * nice to have, it could cause even more
324 * confusion to implement it as `-R'.
326 add_list(&ruidlist, optarg);
340 * XXX - This non-standard option is still under
341 * debate. This *is* supported on Solaris,
342 * Linux, and IRIX, but conflicts with `-s'
343 * on NetBSD and maybe some older BSD's.
345 add_list(&sesslist, optarg);
351 if ((optarg = ttyname(STDIN_FILENO)) == NULL)
352 errx(1, "stdin: not a terminal");
355 add_list(&ttylist, optarg);
360 /* This is what SUSv3 defines as the `-u' option. */
361 add_list(&uidlist, optarg);
379 termwidth = UNLIMITED;
380 else if (termwidth < 131)
386 * Note that `-X' and `-x' are not standard "selector"
387 * options. For most selector-options, we check *all*
388 * processes to see if any are matched by the given
389 * value(s). After we have a set of all the matched
390 * processes, then `-X' and `-x' govern whether we
391 * modify that *matched* set for processes which do
392 * not have a controlling terminal. `-X' causes
393 * those processes to be deleted from the matched
394 * set, while `-x' causes them to be kept.
413 * If there arguments after processing all the options, attempt
414 * to treat them as a list of process ids.
417 if (!isdigitch(**argv))
419 add_list(&pidlist, *argv);
423 fprintf(stderr, "%s: illegal argument: %s\n",
424 getprogname(), *argv);
428 exit(1); /* Error messages already printed. */
429 if (xkeep < 0) /* Neither -X nor -x was specified. */
430 xkeep = xkeep_implied;
432 kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
434 errx(1, "%s", errbuf);
439 if (nselectors == 0) {
440 uidlist.l.ptr = malloc(sizeof(uid_t));
441 if (uidlist.l.ptr == NULL)
442 errx(1, "malloc failed");
444 uidlist.count = uidlist.maxcount = 1;
445 *uidlist.l.uids = getuid();
449 * scan requested variables, noting what structures are needed,
450 * and adjusting header widths as appropriate.
455 * Get process list. If the user requested just one selector-
456 * option, then kvm_getprocs can be asked to return just those
457 * processes. Otherwise, have it return all processes, and
458 * then this routine will search that full list and select the
459 * processes which match any of the user's selector-options.
461 what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
463 if (nselectors == 1) {
464 if (gidlist.count == 1) {
465 what = KERN_PROC_RGID | showthreads;
466 flag = *gidlist.l.gids;
468 } else if (pgrplist.count == 1) {
469 what = KERN_PROC_PGRP | showthreads;
470 flag = *pgrplist.l.pids;
472 } else if (pidlist.count == 1) {
473 what = KERN_PROC_PID | showthreads;
474 flag = *pidlist.l.pids;
476 } else if (ruidlist.count == 1) {
477 what = KERN_PROC_RUID | showthreads;
478 flag = *ruidlist.l.uids;
480 } else if (sesslist.count == 1) {
481 what = KERN_PROC_SESSION | showthreads;
482 flag = *sesslist.l.pids;
484 } else if (ttylist.count == 1) {
485 what = KERN_PROC_TTY | showthreads;
486 flag = *ttylist.l.ttys;
488 } else if (uidlist.count == 1) {
489 what = KERN_PROC_UID | showthreads;
490 flag = *uidlist.l.uids;
493 /* No need for this routine to select processes. */
502 kp = kvm_getprocs(kd, what, flag, &nentries);
503 if ((kp == NULL && nentries > 0) || (kp != NULL && nentries < 0))
504 errx(1, "%s", kvm_geterr(kd));
507 if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
508 errx(1, "malloc failed");
509 for (i = nentries; --i >= 0; ++kp) {
511 * If the user specified multiple selection-criteria,
512 * then keep any process matched by the inclusive OR
513 * of all the selection-criteria given.
515 if (pidlist.count > 0) {
516 for (elem = 0; elem < pidlist.count; elem++)
517 if (kp->ki_pid == pidlist.l.pids[elem])
521 * Note that we had to process pidlist before
522 * filtering out processes which do not have
523 * a controlling terminal.
526 if ((kp->ki_tdev == NODEV ||
527 (kp->ki_flag & P_CONTROLT) == 0))
532 if (gidlist.count > 0) {
533 for (elem = 0; elem < gidlist.count; elem++)
534 if (kp->ki_rgid == gidlist.l.gids[elem])
537 if (pgrplist.count > 0) {
538 for (elem = 0; elem < pgrplist.count; elem++)
540 pgrplist.l.pids[elem])
543 if (ruidlist.count > 0) {
544 for (elem = 0; elem < ruidlist.count; elem++)
546 ruidlist.l.uids[elem])
549 if (sesslist.count > 0) {
550 for (elem = 0; elem < sesslist.count; elem++)
551 if (kp->ki_sid == sesslist.l.pids[elem])
554 if (ttylist.count > 0) {
555 for (elem = 0; elem < ttylist.count; elem++)
556 if (kp->ki_tdev == ttylist.l.ttys[elem])
559 if (uidlist.count > 0) {
560 for (elem = 0; elem < uidlist.count; elem++)
561 if (kp->ki_uid == uidlist.l.uids[elem])
565 * This process did not match any of the user's
566 * selector-options, so skip the process.
571 next_KINFO = &kinfo[nkept];
572 next_KINFO->ki_p = kp;
573 next_KINFO->ki_d.level = 0;
574 next_KINFO->ki_d.prefix = NULL;
575 next_KINFO->ki_pcpu = getpcpu(next_KINFO);
576 if (sortby == SORTMEM)
577 next_KINFO->ki_memsize = kp->ki_tsize +
578 kp->ki_dsize + kp->ki_ssize;
580 saveuser(next_KINFO);
595 qsort(kinfo, nkept, sizeof(KINFO), pscomp);
598 * We want things in descendant order
601 descendant_sort(kinfo, nkept);
605 * Prepare formatted output.
607 for (i = 0; i < nkept; i++)
608 format_output(&kinfo[i]);
616 * Output formatted lines.
618 for (i = lineno = 0; i < nkept; i++) {
620 STAILQ_FOREACH(vent, &varlist, next_ve) {
621 if (vent->var->flag & LJUST)
626 ks = STAILQ_FIRST(&kinfo[i].ki_ks);
627 STAILQ_REMOVE_HEAD(&kinfo[i].ki_ks, ks_next);
628 /* Truncate rightmost column if neccessary. */
629 if (STAILQ_NEXT(vent, next_ve) == NULL &&
630 termwidth != UNLIMITED && ks->ks_str != NULL) {
631 left = termwidth - linelen;
632 if (left > 0 && left < (int)strlen(ks->ks_str))
633 ks->ks_str[left] = '\0';
638 /* No padding for the last column, if it's LJUST. */
639 if (STAILQ_NEXT(vent, next_ve) == NULL &&
640 vent->var->flag & LJUST)
641 linelen += printf(fmtstr, 0, str);
643 linelen += printf(fmtstr, vent->var->width, str);
645 if (ks->ks_str != NULL) {
652 if (STAILQ_NEXT(vent, next_ve) != NULL) {
658 if (prtheader && lineno++ == prtheader - 4) {
666 free_list(&pgrplist);
667 free_list(&ruidlist);
668 free_list(&sesslist);
671 for (i = 0; i < nkept; i++)
672 free(kinfo[i].ki_d.prefix);
679 addelem_gid(struct listinfo *inf, const char *elem)
682 const char *nameorID;
686 if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
688 warnx("Invalid (zero-length) %s name", inf->lname);
690 warnx("%s name too long: %s", inf->lname, elem);
692 return (0); /* Do not add this value. */
696 * SUSv3 states that `ps -G grouplist' should match "real-group
697 * ID numbers", and does not mention group-names. I do want to
698 * also support group-names, so this tries for a group-id first,
699 * and only tries for a name if that doesn't work. This is the
700 * opposite order of what is done in addelem_uid(), but in
701 * practice the order would only matter for group-names which
707 bigtemp = strtoul(elem, &endp, 10);
708 if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
709 nameorID = "name or ID matches";
710 grp = getgrgid((gid_t)bigtemp);
713 grp = getgrnam(elem);
715 warnx("No %s %s '%s'", inf->lname, nameorID, elem);
719 if (inf->count >= inf->maxcount)
721 inf->l.gids[(inf->count)++] = grp->gr_gid;
725 #define BSD_PID_MAX 99999 /* Copy of PID_MAX from sys/proc.h. */
727 addelem_pid(struct listinfo *inf, const char *elem)
733 warnx("Invalid (zero-length) process id");
735 return (0); /* Do not add this value. */
739 tempid = strtol(elem, &endp, 10);
740 if (*endp != '\0' || tempid < 0 || elem == endp) {
741 warnx("Invalid %s: %s", inf->lname, elem);
743 } else if (errno != 0 || tempid > BSD_PID_MAX) {
744 warnx("%s too large: %s", inf->lname, elem);
747 if (errno == ERANGE) {
751 if (inf->count >= inf->maxcount)
753 inf->l.pids[(inf->count)++] = tempid;
759 * The user can specify a device via one of three formats:
760 * 1) fully qualified, e.g.: /dev/ttyp0 /dev/console /dev/pts/0
761 * 2) missing "/dev", e.g.: ttyp0 console pts/0
762 * 3) two-letters, e.g.: p0 co 0
763 * (matching letters that would be seen in the "TT" column)
766 addelem_tty(struct listinfo *inf, const char *elem)
770 char pathbuf[PATH_MAX], pathbuf2[PATH_MAX], pathbuf3[PATH_MAX];
780 if (strcmp(elem, "co") == 0) {
781 ttypath = _PATH_CONSOLE;
786 strlcpy(pathbuf, _PATH_DEV, sizeof(pathbuf));
787 strlcat(pathbuf, elem, sizeof(pathbuf));
789 if (strncmp(pathbuf, _PATH_TTY, strlen(_PATH_TTY)) == 0)
791 if (strncmp(pathbuf, _PATH_PTS, strlen(_PATH_PTS)) == 0)
793 if (strcmp(pathbuf, _PATH_CONSOLE) == 0)
795 /* Check to see if /dev/tty${elem} exists */
796 strlcpy(pathbuf2, _PATH_TTY, sizeof(pathbuf2));
797 strlcat(pathbuf2, elem, sizeof(pathbuf2));
798 if (stat(pathbuf2, &sb) == 0 && S_ISCHR(sb.st_mode)) {
799 /* No need to repeat stat() && S_ISCHR() checks */
803 /* Check to see if /dev/pts/${elem} exists */
804 strlcpy(pathbuf3, _PATH_PTS, sizeof(pathbuf3));
805 strlcat(pathbuf3, elem, sizeof(pathbuf3));
806 if (stat(pathbuf3, &sb) == 0 && S_ISCHR(sb.st_mode)) {
807 /* No need to repeat stat() && S_ISCHR() checks */
814 if (stat(ttypath, &sb) == -1) {
815 if (pathbuf3[0] != '\0')
816 warn("%s, %s, and %s", pathbuf3, pathbuf2,
823 if (!S_ISCHR(sb.st_mode)) {
824 if (pathbuf3[0] != '\0')
825 warnx("%s, %s, and %s: Not a terminal",
826 pathbuf3, pathbuf2, ttypath);
828 warnx("%s: Not a terminal", ttypath);
833 if (inf->count >= inf->maxcount)
835 inf->l.ttys[(inf->count)++] = sb.st_rdev;
840 addelem_uid(struct listinfo *inf, const char *elem)
846 if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
848 warnx("Invalid (zero-length) %s name", inf->lname);
850 warnx("%s name too long: %s", inf->lname, elem);
852 return (0); /* Do not add this value. */
855 pwd = getpwnam(elem);
858 bigtemp = strtoul(elem, &endp, 10);
859 if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
860 warnx("No %s named '%s'", inf->lname, elem);
862 /* The string is all digits, so it might be a userID. */
863 pwd = getpwuid((uid_t)bigtemp);
865 warnx("No %s name or ID matches '%s'",
871 * These used to be treated as minor warnings (and the
872 * option was simply ignored), but now they are fatal
873 * errors (and the command will be aborted).
878 if (inf->count >= inf->maxcount)
880 inf->l.uids[(inf->count)++] = pwd->pw_uid;
885 add_list(struct listinfo *inf, const char *argp)
890 char elemcopy[PATH_MAX];
893 inf->addelem(inf, argp);
894 while (*argp != '\0') {
895 while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
900 if (strchr(T_SEP, *argp) == NULL) {
901 endp = elemcopy + sizeof(elemcopy) - 1;
902 while (*argp != '\0' && cp <= endp &&
903 strchr(W_SEP T_SEP, *argp) == NULL)
911 * Add this single element to the given list.
913 inf->addelem(inf, elemcopy);
916 * The string is too long to copy. Find the end
917 * of the string to print out the warning message.
919 while (*argp != '\0' && strchr(W_SEP T_SEP,
922 warnx("Value too long: %.*s", (int)(argp - savep),
927 * Skip over any number of trailing whitespace characters,
928 * but only one (at most) trailing element-terminating
931 while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
933 if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
935 /* Catch case where string ended with a comma. */
937 inf->addelem(inf, argp);
943 descendant_sort(KINFO *ki, int items)
945 int dst, lvl, maxlvl, n, ndst, nsrc, siblings, src;
950 * First, sort the entries by descendancy, tracking the descendancy
951 * depth in the ki_d.level field.
955 while (src < items) {
956 if (ki[src].ki_d.level) {
960 for (nsrc = 1; src + nsrc < items; nsrc++)
961 if (!ki[src + nsrc].ki_d.level)
964 for (dst = 0; dst < items; dst++) {
965 if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_pid)
967 if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_ppid)
976 for (ndst = 1; dst + ndst < items; ndst++)
977 if (ki[dst + ndst].ki_d.level <= ki[dst].ki_d.level)
980 for (n = src; n < src + nsrc; n++) {
981 ki[n].ki_d.level += ki[dst].ki_d.level + 1;
982 if (maxlvl < ki[n].ki_d.level)
983 maxlvl = ki[n].ki_d.level;
989 memmove(ki + src, ki + src + 1,
990 (dst - src + ndst - 1) * sizeof *ki);
991 ki[dst + ndst - 1] = kn;
995 } else if (src != dst + ndst) {
997 memmove(ki + dst + ndst + 1, ki + dst + ndst,
998 (src - dst - ndst) * sizeof *ki);
1012 * Now populate ki_d.prefix (instead of ki_d.level) with the command
1013 * prefix used to show descendancies.
1015 path = malloc((maxlvl + 7) / 8);
1016 memset(path, '\0', (maxlvl + 7) / 8);
1017 for (src = 0; src < items; src++) {
1018 if ((lvl = ki[src].ki_d.level) == 0) {
1019 ki[src].ki_d.prefix = NULL;
1022 if ((ki[src].ki_d.prefix = malloc(lvl * 2 + 1)) == NULL)
1023 errx(1, "malloc failed");
1024 for (n = 0; n < lvl - 2; n++) {
1025 ki[src].ki_d.prefix[n * 2] =
1026 path[n / 8] & 1 << (n % 8) ? '|' : ' ';
1027 ki[src].ki_d.prefix[n * 2 + 1] = ' ';
1030 /* Have I any more siblings? */
1031 for (siblings = 0, dst = src + 1; dst < items; dst++) {
1032 if (ki[dst].ki_d.level > lvl)
1034 if (ki[dst].ki_d.level == lvl)
1039 path[n / 8] |= 1 << (n % 8);
1041 path[n / 8] &= ~(1 << (n % 8));
1042 ki[src].ki_d.prefix[n * 2] = siblings ? '|' : '`';
1043 ki[src].ki_d.prefix[n * 2 + 1] = '-';
1046 strcpy(ki[src].ki_d.prefix + n * 2, "- ");
1052 expand_list(struct listinfo *inf)
1057 newmax = (inf->maxcount + 1) << 1;
1058 newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
1059 if (newlist == NULL) {
1061 errx(1, "realloc to %d %ss failed", newmax, inf->lname);
1063 inf->maxcount = newmax;
1064 inf->l.ptr = newlist;
1070 free_list(struct listinfo *inf)
1073 inf->count = inf->elemsize = inf->maxcount = 0;
1074 if (inf->l.ptr != NULL)
1076 inf->addelem = NULL;
1082 init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
1086 inf->count = inf->maxcount = 0;
1087 inf->elemsize = elemsize;
1088 inf->addelem = artn;
1094 find_varentry(VAR *v)
1096 struct varent *vent;
1098 STAILQ_FOREACH(vent, &varlist, next_ve) {
1099 if (strcmp(vent->var->name, v->name) == 0)
1108 struct varent *vent;
1111 STAILQ_FOREACH(vent, &varlist, next_ve) {
1121 format_output(KINFO *ki)
1123 struct varent *vent;
1129 STAILQ_INIT(&ki->ki_ks);
1130 STAILQ_FOREACH(vent, &varlist, next_ve) {
1132 str = (v->oproc)(ki, vent);
1133 ks = malloc(sizeof(*ks));
1135 errx(1, "malloc failed");
1137 STAILQ_INSERT_TAIL(&ki->ki_ks, ks, ks_next);
1150 struct varent *vent;
1154 STAILQ_FOREACH(vent, &varlist, next_ve) {
1156 i = strlen(vent->header);
1163 fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
1164 char *comm, char *thread, int maxlen)
1168 s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm,
1169 showthreads && ki->ki_p->ki_numthreads > 1 ? thread : NULL, maxlen);
1173 #define UREADOK(ki) (forceuread || (ki->ki_p->ki_flag & P_INMEM))
1179 if (ki->ki_p->ki_flag & P_INMEM) {
1181 * The u-area might be swapped out, and we can't get
1182 * at it because we have a crashdump and no swap.
1183 * If it's here fill in these fields, otherwise, just
1190 * save arguments if needed
1193 if (ki->ki_p->ki_stat == SZOMB)
1194 ki->ki_args = strdup("<defunct>");
1195 else if (UREADOK(ki) || (ki->ki_p->ki_args != NULL))
1196 ki->ki_args = strdup(fmt(kvm_getargv, ki,
1197 ki->ki_p->ki_comm, ki->ki_p->ki_tdname, MAXCOMLEN));
1199 asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
1200 if (ki->ki_args == NULL)
1201 errx(1, "malloc failed");
1207 ki->ki_env = strdup(fmt(kvm_getenvv, ki,
1208 (char *)NULL, (char *)NULL, 0));
1210 ki->ki_env = strdup("()");
1211 if (ki->ki_env == NULL)
1212 errx(1, "malloc failed");
1218 /* A macro used to improve the readability of pscomp(). */
1219 #define DIFF_RETURN(a, b, field) do { \
1220 if ((a)->field != (b)->field) \
1221 return (((a)->field < (b)->field) ? -1 : 1); \
1225 pscomp(const void *a, const void *b)
1227 const KINFO *ka, *kb;
1231 /* SORTCPU and SORTMEM are sorted in descending order. */
1232 if (sortby == SORTCPU)
1233 DIFF_RETURN(kb, ka, ki_pcpu);
1234 if (sortby == SORTMEM)
1235 DIFF_RETURN(kb, ka, ki_memsize);
1237 * TTY's are sorted in ascending order, except that all NODEV
1238 * processes come before all processes with a device.
1240 if (ka->ki_p->ki_tdev != kb->ki_p->ki_tdev) {
1241 if (ka->ki_p->ki_tdev == NODEV)
1243 if (kb->ki_p->ki_tdev == NODEV)
1245 DIFF_RETURN(ka, kb, ki_p->ki_tdev);
1248 /* PID's and TID's (threads) are sorted in ascending order. */
1249 DIFF_RETURN(ka, kb, ki_p->ki_pid);
1250 DIFF_RETURN(ka, kb, ki_p->ki_tid);
1256 * ICK (all for getopt), would rather hide the ugliness
1257 * here than taint the main code.
1262 * The old convention that 't' with no trailing tty arg means the users
1263 * tty, is only supported if argv[1] doesn't begin with a '-'. This same
1264 * feature is available with the option 'T', which takes no argument.
1267 kludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
1270 char *argp, *cp, *newopts, *ns, *optp, *pidp;
1273 * See if the original value includes any option which takes an
1274 * argument (and will thus use up the remainder of the string).
1277 if (optlist != NULL) {
1278 for (cp = origval; *cp != '\0'; cp++) {
1279 optp = strchr(optlist, *cp);
1280 if ((optp != NULL) && *(optp + 1) == ':') {
1286 if (argp != NULL && *origval == '-')
1290 * if last letter is a 't' flag with no argument (in the context
1291 * of the oldps options -- option string NOT starting with a '-' --
1292 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1294 * However, if a flag accepting a string argument is found earlier
1295 * in the option string (including a possible `t' flag), then the
1296 * remainder of the string must be the argument to that flag; so
1297 * do not modify that argument. Note that a trailing `t' would
1298 * cause argp to be set, if argp was not already set by some
1301 len = strlen(origval);
1302 cp = origval + len - 1;
1304 if (*cp == 't' && *origval != '-' && cp == argp) {
1305 if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
1307 } else if (argp == NULL) {
1309 * The original value did not include any option which takes
1310 * an argument (and that would include `p' and `t'), so check
1311 * the value for trailing number, or comma-separated list of
1312 * numbers, which we will treat as a pid request.
1314 if (isdigitch(*cp)) {
1315 while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1322 * If nothing needs to be added to the string, then return
1323 * the "original" (although possibly modified) value.
1325 if (*origval == '-' && pidp == NULL)
1329 * Create a copy of the string to add '-' and/or 'p' to the
1332 if ((newopts = ns = malloc(len + 3)) == NULL)
1333 errx(1, "malloc failed");
1335 if (*origval != '-')
1336 *ns++ = '-'; /* add option flag */
1339 strcpy(ns, origval);
1342 * Copy everything before the pid string, add the `p',
1343 * and then copy the pid string.
1345 len = pidp - origval;
1346 memcpy(ns, origval, len);
1358 #define SINGLE_OPTS "[-aCcde" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
1360 (void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
1361 "usage: ps " SINGLE_OPTS " [-O fmt | -o fmt] [-G gid[,gid...]]",
1362 " [-M core] [-N system]",
1363 " [-p pid[,pid...]] [-t tty[,tty...]] [-U user[,user...]]",