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>
79 #define _PATH_PTS "/dev/pts/"
81 #define W_SEP " \t" /* "Whitespace" list separators */
82 #define T_SEP "," /* "Terminate-element" list separators */
86 #define OPT_LAZY_f "f"
88 #define DEF_UREAD 1 /* Always do the more-expensive read. */
89 #define OPT_LAZY_f /* I.e., the `-f' option is not added. */
93 * isdigit takes an `int', but expects values in the range of unsigned char.
94 * This wrapper ensures that values from a 'char' end up in the correct range.
96 #define isdigitch(Anychar) isdigit((u_char)(Anychar))
99 int eval; /* Exit value */
100 time_t now; /* Current time(3) value */
102 int sumrusage; /* -S */
103 int termwidth; /* Width of the screen (0 == infinity). */
104 int showthreads; /* will threads be shown? */
106 struct velisthead varlist = STAILQ_HEAD_INITIALIZER(varlist);
108 static int forceuread = DEF_UREAD; /* Do extra work to get u-area. */
110 static int needcomm; /* -o "command" */
111 static int needenv; /* -e */
112 static int needuser; /* -o "user" */
113 static int optfatal; /* Fatal error parsing some list-option. */
114 static int pid_max; /* kern.max_pid */
116 static enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
119 typedef int addelem_rtn(struct listinfo *_inf, const char *_elem);
125 addelem_rtn *addelem;
137 static int addelem_gid(struct listinfo *, const char *);
138 static int addelem_jid(struct listinfo *, const char *);
139 static int addelem_pid(struct listinfo *, const char *);
140 static int addelem_tty(struct listinfo *, const char *);
141 static int addelem_uid(struct listinfo *, const char *);
142 static void add_list(struct listinfo *, const char *);
143 static void descendant_sort(KINFO *, int);
144 static void format_output(KINFO *);
145 static void *expand_list(struct listinfo *);
147 fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
148 KINFO *, char *, char *, int);
149 static void free_list(struct listinfo *);
150 static void init_list(struct listinfo *, addelem_rtn, int, const char *);
151 static char *kludge_oldps_options(const char *, char *, const char *);
152 static int pscomp(const void *, const void *);
153 static void saveuser(KINFO *);
154 static void scanvars(void);
155 static void sizevars(void);
156 static void pidmax_init(void);
157 static void usage(void);
159 static char dfmt[] = "pid,tt,state,time,command";
160 static char jfmt[] = "user,pid,ppid,pgid,sid,jobc,state,tt,time,command";
161 static char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
163 static char o1[] = "pid";
164 static char o2[] = "tt,state,time,command";
165 static char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
166 static char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
168 static char Zfmt[] = "label";
170 #define PS_ARGS "AaCcde" OPT_LAZY_f "G:gHhjJ:LlM:mN:O:o:p:rSTt:U:uvwXxZ"
173 main(int argc, char *argv[])
175 struct listinfo gidlist, jidlist, pgrplist, pidlist;
176 struct listinfo ruidlist, sesslist, ttylist, uidlist;
177 struct kinfo_proc *kp;
178 KINFO *kinfo = NULL, *next_KINFO;
182 const char *nlistf, *memf, *fmtstr, *str;
184 int all, ch, elem, flag, _fmt, i, lineno, linelen, left;
185 int descendancy, nentries, nkept, nselectors;
186 int prtheader, wflag, what, xkeep, xkeep_implied;
187 char errbuf[_POSIX2_LINE_MAX];
189 (void) setlocale(LC_ALL, "");
190 time(&now); /* Used by routines in print.c. */
192 if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
193 termwidth = atoi(cols);
194 else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
195 ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
196 ioctl(STDIN_FILENO, TIOCGWINSZ, (char *)&ws) == -1) ||
200 termwidth = ws.ws_col - 1;
203 * Hide a number of option-processing kludges in a separate routine,
204 * to support some historical BSD behaviors, such as `ps axu'.
207 argv[1] = kludge_oldps_options(PS_ARGS, argv[1], argv[2]);
211 all = descendancy = _fmt = nselectors = optfatal = 0;
212 prtheader = showthreads = wflag = xkeep_implied = 0;
213 xkeep = -1; /* Neither -x nor -X. */
214 init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
215 init_list(&jidlist, addelem_jid, sizeof(int), "jail id");
216 init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
217 init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
218 init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
219 init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
220 init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
221 init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
222 memf = _PATH_DEVNULL;
224 while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
228 * Exactly the same as `-ax'. This has been
229 * added for compatibility with SUSv3, but for
230 * now it will not be described in the man page.
248 case 'e': /* XXX set ufmt */
253 if (getuid() == 0 || getgid() == 0)
258 add_list(&gidlist, optarg);
265 * XXX - This SUSv3 behavior is still under debate
266 * since it conflicts with the (undocumented)
267 * `-g' option. So we skip it for now.
269 add_list(&pgrplist, optarg);
274 /* The historical BSD-ish (from SunOS) behavior. */
278 showthreads = KERN_PROC_INC_THREAD;
281 prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
284 add_list(&jidlist, optarg);
314 o1[0] = o2[0] = '\0';
322 add_list(&pidlist, optarg);
324 * Note: `-p' does not *set* xkeep, but any values
325 * from pidlist are checked before xkeep is. That
326 * way they are always matched, even if the user
334 * XXX - This un-standard option is still under
335 * debate. This is what SUSv3 defines as
336 * the `-U' option, and while it would be
337 * nice to have, it could cause even more
338 * confusion to implement it as `-R'.
340 add_list(&ruidlist, optarg);
354 * XXX - This non-standard option is still under
355 * debate. This *is* supported on Solaris,
356 * Linux, and IRIX, but conflicts with `-s'
357 * on NetBSD and maybe some older BSD's.
359 add_list(&sesslist, optarg);
365 if ((optarg = ttyname(STDIN_FILENO)) == NULL)
366 errx(1, "stdin: not a terminal");
369 add_list(&ttylist, optarg);
374 /* This is what SUSv3 defines as the `-u' option. */
375 add_list(&uidlist, optarg);
393 termwidth = UNLIMITED;
394 else if (termwidth < 131)
400 * Note that `-X' and `-x' are not standard "selector"
401 * options. For most selector-options, we check *all*
402 * processes to see if any are matched by the given
403 * value(s). After we have a set of all the matched
404 * processes, then `-X' and `-x' govern whether we
405 * modify that *matched* set for processes which do
406 * not have a controlling terminal. `-X' causes
407 * those processes to be deleted from the matched
408 * set, while `-x' causes them to be kept.
427 * If there arguments after processing all the options, attempt
428 * to treat them as a list of process ids.
431 if (!isdigitch(**argv))
433 add_list(&pidlist, *argv);
437 fprintf(stderr, "%s: illegal argument: %s\n",
438 getprogname(), *argv);
442 exit(1); /* Error messages already printed. */
443 if (xkeep < 0) /* Neither -X nor -x was specified. */
444 xkeep = xkeep_implied;
446 kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
448 errx(1, "%s", errbuf);
453 if (nselectors == 0) {
454 uidlist.l.ptr = malloc(sizeof(uid_t));
455 if (uidlist.l.ptr == NULL)
456 errx(1, "malloc failed");
458 uidlist.count = uidlist.maxcount = 1;
459 *uidlist.l.uids = getuid();
463 * scan requested variables, noting what structures are needed,
464 * and adjusting header widths as appropriate.
469 * Get process list. If the user requested just one selector-
470 * option, then kvm_getprocs can be asked to return just those
471 * processes. Otherwise, have it return all processes, and
472 * then this routine will search that full list and select the
473 * processes which match any of the user's selector-options.
475 what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
477 if (nselectors == 1) {
478 if (gidlist.count == 1) {
479 what = KERN_PROC_RGID | showthreads;
480 flag = *gidlist.l.gids;
482 } else if (pgrplist.count == 1) {
483 what = KERN_PROC_PGRP | showthreads;
484 flag = *pgrplist.l.pids;
486 } else if (pidlist.count == 1) {
487 what = KERN_PROC_PID | showthreads;
488 flag = *pidlist.l.pids;
490 } else if (ruidlist.count == 1) {
491 what = KERN_PROC_RUID | showthreads;
492 flag = *ruidlist.l.uids;
494 } else if (sesslist.count == 1) {
495 what = KERN_PROC_SESSION | showthreads;
496 flag = *sesslist.l.pids;
498 } else if (ttylist.count == 1) {
499 what = KERN_PROC_TTY | showthreads;
500 flag = *ttylist.l.ttys;
502 } else if (uidlist.count == 1) {
503 what = KERN_PROC_UID | showthreads;
504 flag = *uidlist.l.uids;
507 /* No need for this routine to select processes. */
516 kp = kvm_getprocs(kd, what, flag, &nentries);
517 if ((kp == NULL && nentries > 0) || (kp != NULL && nentries < 0))
518 errx(1, "%s", kvm_geterr(kd));
521 if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
522 errx(1, "malloc failed");
523 for (i = nentries; --i >= 0; ++kp) {
525 * If the user specified multiple selection-criteria,
526 * then keep any process matched by the inclusive OR
527 * of all the selection-criteria given.
529 if (pidlist.count > 0) {
530 for (elem = 0; elem < pidlist.count; elem++)
531 if (kp->ki_pid == pidlist.l.pids[elem])
535 * Note that we had to process pidlist before
536 * filtering out processes which do not have
537 * a controlling terminal.
540 if ((kp->ki_tdev == NODEV ||
541 (kp->ki_flag & P_CONTROLT) == 0))
546 if (gidlist.count > 0) {
547 for (elem = 0; elem < gidlist.count; elem++)
548 if (kp->ki_rgid == gidlist.l.gids[elem])
551 if (jidlist.count > 0) {
552 for (elem = 0; elem < jidlist.count; elem++)
553 if (kp->ki_jid == jidlist.l.jids[elem])
556 if (pgrplist.count > 0) {
557 for (elem = 0; elem < pgrplist.count; elem++)
559 pgrplist.l.pids[elem])
562 if (ruidlist.count > 0) {
563 for (elem = 0; elem < ruidlist.count; elem++)
565 ruidlist.l.uids[elem])
568 if (sesslist.count > 0) {
569 for (elem = 0; elem < sesslist.count; elem++)
570 if (kp->ki_sid == sesslist.l.pids[elem])
573 if (ttylist.count > 0) {
574 for (elem = 0; elem < ttylist.count; elem++)
575 if (kp->ki_tdev == ttylist.l.ttys[elem])
578 if (uidlist.count > 0) {
579 for (elem = 0; elem < uidlist.count; elem++)
580 if (kp->ki_uid == uidlist.l.uids[elem])
584 * This process did not match any of the user's
585 * selector-options, so skip the process.
590 next_KINFO = &kinfo[nkept];
591 next_KINFO->ki_p = kp;
592 next_KINFO->ki_d.level = 0;
593 next_KINFO->ki_d.prefix = NULL;
594 next_KINFO->ki_pcpu = getpcpu(next_KINFO);
595 if (sortby == SORTMEM)
596 next_KINFO->ki_memsize = kp->ki_tsize +
597 kp->ki_dsize + kp->ki_ssize;
599 saveuser(next_KINFO);
614 qsort(kinfo, nkept, sizeof(KINFO), pscomp);
617 * We want things in descendant order
620 descendant_sort(kinfo, nkept);
624 * Prepare formatted output.
626 for (i = 0; i < nkept; i++)
627 format_output(&kinfo[i]);
635 * Output formatted lines.
637 for (i = lineno = 0; i < nkept; i++) {
639 STAILQ_FOREACH(vent, &varlist, next_ve) {
640 if (vent->var->flag & LJUST)
645 ks = STAILQ_FIRST(&kinfo[i].ki_ks);
646 STAILQ_REMOVE_HEAD(&kinfo[i].ki_ks, ks_next);
647 /* Truncate rightmost column if necessary. */
648 if (STAILQ_NEXT(vent, next_ve) == NULL &&
649 termwidth != UNLIMITED && ks->ks_str != NULL) {
650 left = termwidth - linelen;
651 if (left > 0 && left < (int)strlen(ks->ks_str))
652 ks->ks_str[left] = '\0';
657 /* No padding for the last column, if it's LJUST. */
658 if (STAILQ_NEXT(vent, next_ve) == NULL &&
659 vent->var->flag & LJUST)
660 linelen += printf(fmtstr, 0, str);
662 linelen += printf(fmtstr, vent->var->width, str);
664 if (ks->ks_str != NULL) {
671 if (STAILQ_NEXT(vent, next_ve) != NULL) {
677 if (prtheader && lineno++ == prtheader - 4) {
686 free_list(&pgrplist);
687 free_list(&ruidlist);
688 free_list(&sesslist);
691 for (i = 0; i < nkept; i++)
692 free(kinfo[i].ki_d.prefix);
699 addelem_gid(struct listinfo *inf, const char *elem)
702 const char *nameorID;
706 if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
708 warnx("Invalid (zero-length) %s name", inf->lname);
710 warnx("%s name too long: %s", inf->lname, elem);
712 return (0); /* Do not add this value. */
716 * SUSv3 states that `ps -G grouplist' should match "real-group
717 * ID numbers", and does not mention group-names. I do want to
718 * also support group-names, so this tries for a group-id first,
719 * and only tries for a name if that doesn't work. This is the
720 * opposite order of what is done in addelem_uid(), but in
721 * practice the order would only matter for group-names which
727 bigtemp = strtoul(elem, &endp, 10);
728 if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
729 nameorID = "name or ID matches";
730 grp = getgrgid((gid_t)bigtemp);
733 grp = getgrnam(elem);
735 warnx("No %s %s '%s'", inf->lname, nameorID, elem);
739 if (inf->count >= inf->maxcount)
741 inf->l.gids[(inf->count)++] = grp->gr_gid;
746 addelem_jid(struct listinfo *inf, const char *elem)
751 warnx("Invalid (zero-length) jail id");
753 return (0); /* Do not add this value. */
756 tempid = jail_getid(elem);
758 warnx("Invalid %s: %s", inf->lname, elem);
763 if (inf->count >= inf->maxcount)
765 inf->l.jids[(inf->count)++] = tempid;
770 addelem_pid(struct listinfo *inf, const char *elem)
776 warnx("Invalid (zero-length) process id");
778 return (0); /* Do not add this value. */
782 tempid = strtol(elem, &endp, 10);
783 if (*endp != '\0' || tempid < 0 || elem == endp) {
784 warnx("Invalid %s: %s", inf->lname, elem);
786 } else if (errno != 0 || tempid > pid_max) {
787 warnx("%s too large: %s", inf->lname, elem);
790 if (errno == ERANGE) {
794 if (inf->count >= inf->maxcount)
796 inf->l.pids[(inf->count)++] = tempid;
801 * The user can specify a device via one of three formats:
802 * 1) fully qualified, e.g.: /dev/ttyp0 /dev/console /dev/pts/0
803 * 2) missing "/dev", e.g.: ttyp0 console pts/0
804 * 3) two-letters, e.g.: p0 co 0
805 * (matching letters that would be seen in the "TT" column)
808 addelem_tty(struct listinfo *inf, const char *elem)
812 char pathbuf[PATH_MAX], pathbuf2[PATH_MAX], pathbuf3[PATH_MAX];
822 if (strcmp(elem, "co") == 0) {
823 ttypath = _PATH_CONSOLE;
828 strlcpy(pathbuf, _PATH_DEV, sizeof(pathbuf));
829 strlcat(pathbuf, elem, sizeof(pathbuf));
831 if (strncmp(pathbuf, _PATH_TTY, strlen(_PATH_TTY)) == 0)
833 if (strncmp(pathbuf, _PATH_PTS, strlen(_PATH_PTS)) == 0)
835 if (strcmp(pathbuf, _PATH_CONSOLE) == 0)
837 /* Check to see if /dev/tty${elem} exists */
838 strlcpy(pathbuf2, _PATH_TTY, sizeof(pathbuf2));
839 strlcat(pathbuf2, elem, sizeof(pathbuf2));
840 if (stat(pathbuf2, &sb) == 0 && S_ISCHR(sb.st_mode)) {
841 /* No need to repeat stat() && S_ISCHR() checks */
845 /* Check to see if /dev/pts/${elem} exists */
846 strlcpy(pathbuf3, _PATH_PTS, sizeof(pathbuf3));
847 strlcat(pathbuf3, elem, sizeof(pathbuf3));
848 if (stat(pathbuf3, &sb) == 0 && S_ISCHR(sb.st_mode)) {
849 /* No need to repeat stat() && S_ISCHR() checks */
856 if (stat(ttypath, &sb) == -1) {
857 if (pathbuf3[0] != '\0')
858 warn("%s, %s, and %s", pathbuf3, pathbuf2,
865 if (!S_ISCHR(sb.st_mode)) {
866 if (pathbuf3[0] != '\0')
867 warnx("%s, %s, and %s: Not a terminal",
868 pathbuf3, pathbuf2, ttypath);
870 warnx("%s: Not a terminal", ttypath);
875 if (inf->count >= inf->maxcount)
877 inf->l.ttys[(inf->count)++] = sb.st_rdev;
882 addelem_uid(struct listinfo *inf, const char *elem)
888 if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
890 warnx("Invalid (zero-length) %s name", inf->lname);
892 warnx("%s name too long: %s", inf->lname, elem);
894 return (0); /* Do not add this value. */
897 pwd = getpwnam(elem);
900 bigtemp = strtoul(elem, &endp, 10);
901 if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
902 warnx("No %s named '%s'", inf->lname, elem);
904 /* The string is all digits, so it might be a userID. */
905 pwd = getpwuid((uid_t)bigtemp);
907 warnx("No %s name or ID matches '%s'",
913 * These used to be treated as minor warnings (and the
914 * option was simply ignored), but now they are fatal
915 * errors (and the command will be aborted).
920 if (inf->count >= inf->maxcount)
922 inf->l.uids[(inf->count)++] = pwd->pw_uid;
927 add_list(struct listinfo *inf, const char *argp)
932 char elemcopy[PATH_MAX];
935 inf->addelem(inf, argp);
936 while (*argp != '\0') {
937 while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
942 if (strchr(T_SEP, *argp) == NULL) {
943 endp = elemcopy + sizeof(elemcopy) - 1;
944 while (*argp != '\0' && cp <= endp &&
945 strchr(W_SEP T_SEP, *argp) == NULL)
953 * Add this single element to the given list.
955 inf->addelem(inf, elemcopy);
958 * The string is too long to copy. Find the end
959 * of the string to print out the warning message.
961 while (*argp != '\0' && strchr(W_SEP T_SEP,
964 warnx("Value too long: %.*s", (int)(argp - savep),
969 * Skip over any number of trailing whitespace characters,
970 * but only one (at most) trailing element-terminating
973 while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
975 if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
977 /* Catch case where string ended with a comma. */
979 inf->addelem(inf, argp);
985 descendant_sort(KINFO *ki, int items)
987 int dst, lvl, maxlvl, n, ndst, nsrc, siblings, src;
992 * First, sort the entries by descendancy, tracking the descendancy
993 * depth in the ki_d.level field.
997 while (src < items) {
998 if (ki[src].ki_d.level) {
1002 for (nsrc = 1; src + nsrc < items; nsrc++)
1003 if (!ki[src + nsrc].ki_d.level)
1006 for (dst = 0; dst < items; dst++) {
1007 if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_pid)
1009 if (ki[dst].ki_p->ki_pid == ki[src].ki_p->ki_ppid)
1018 for (ndst = 1; dst + ndst < items; ndst++)
1019 if (ki[dst + ndst].ki_d.level <= ki[dst].ki_d.level)
1022 for (n = src; n < src + nsrc; n++) {
1023 ki[n].ki_d.level += ki[dst].ki_d.level + 1;
1024 if (maxlvl < ki[n].ki_d.level)
1025 maxlvl = ki[n].ki_d.level;
1031 memmove(ki + src, ki + src + 1,
1032 (dst - src + ndst - 1) * sizeof *ki);
1033 ki[dst + ndst - 1] = kn;
1037 } else if (src != dst + ndst) {
1039 memmove(ki + dst + ndst + 1, ki + dst + ndst,
1040 (src - dst - ndst) * sizeof *ki);
1041 ki[dst + ndst] = kn;
1054 * Now populate ki_d.prefix (instead of ki_d.level) with the command
1055 * prefix used to show descendancies.
1057 path = malloc((maxlvl + 7) / 8);
1058 memset(path, '\0', (maxlvl + 7) / 8);
1059 for (src = 0; src < items; src++) {
1060 if ((lvl = ki[src].ki_d.level) == 0) {
1061 ki[src].ki_d.prefix = NULL;
1064 if ((ki[src].ki_d.prefix = malloc(lvl * 2 + 1)) == NULL)
1065 errx(1, "malloc failed");
1066 for (n = 0; n < lvl - 2; n++) {
1067 ki[src].ki_d.prefix[n * 2] =
1068 path[n / 8] & 1 << (n % 8) ? '|' : ' ';
1069 ki[src].ki_d.prefix[n * 2 + 1] = ' ';
1072 /* Have I any more siblings? */
1073 for (siblings = 0, dst = src + 1; dst < items; dst++) {
1074 if (ki[dst].ki_d.level > lvl)
1076 if (ki[dst].ki_d.level == lvl)
1081 path[n / 8] |= 1 << (n % 8);
1083 path[n / 8] &= ~(1 << (n % 8));
1084 ki[src].ki_d.prefix[n * 2] = siblings ? '|' : '`';
1085 ki[src].ki_d.prefix[n * 2 + 1] = '-';
1088 strcpy(ki[src].ki_d.prefix + n * 2, "- ");
1094 expand_list(struct listinfo *inf)
1099 newmax = (inf->maxcount + 1) << 1;
1100 newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
1101 if (newlist == NULL) {
1103 errx(1, "realloc to %d %ss failed", newmax, inf->lname);
1105 inf->maxcount = newmax;
1106 inf->l.ptr = newlist;
1112 free_list(struct listinfo *inf)
1115 inf->count = inf->elemsize = inf->maxcount = 0;
1116 if (inf->l.ptr != NULL)
1118 inf->addelem = NULL;
1124 init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
1128 inf->count = inf->maxcount = 0;
1129 inf->elemsize = elemsize;
1130 inf->addelem = artn;
1136 find_varentry(VAR *v)
1138 struct varent *vent;
1140 STAILQ_FOREACH(vent, &varlist, next_ve) {
1141 if (strcmp(vent->var->name, v->name) == 0)
1150 struct varent *vent;
1153 STAILQ_FOREACH(vent, &varlist, next_ve) {
1163 format_output(KINFO *ki)
1165 struct varent *vent;
1171 STAILQ_INIT(&ki->ki_ks);
1172 STAILQ_FOREACH(vent, &varlist, next_ve) {
1174 str = (v->oproc)(ki, vent);
1175 ks = malloc(sizeof(*ks));
1177 errx(1, "malloc failed");
1179 STAILQ_INSERT_TAIL(&ki->ki_ks, ks, ks_next);
1192 struct varent *vent;
1196 STAILQ_FOREACH(vent, &varlist, next_ve) {
1198 i = strlen(vent->header);
1205 fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
1206 char *comm, char *thread, int maxlen)
1210 s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm,
1211 showthreads && ki->ki_p->ki_numthreads > 1 ? thread : NULL, maxlen);
1215 #define UREADOK(ki) (forceuread || (ki->ki_p->ki_flag & P_INMEM))
1221 if (ki->ki_p->ki_flag & P_INMEM) {
1223 * The u-area might be swapped out, and we can't get
1224 * at it because we have a crashdump and no swap.
1225 * If it's here fill in these fields, otherwise, just
1232 * save arguments if needed
1235 if (ki->ki_p->ki_stat == SZOMB)
1236 ki->ki_args = strdup("<defunct>");
1237 else if (UREADOK(ki) || (ki->ki_p->ki_args != NULL))
1238 ki->ki_args = strdup(fmt(kvm_getargv, ki,
1239 ki->ki_p->ki_comm, ki->ki_p->ki_tdname, MAXCOMLEN));
1241 asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
1242 if (ki->ki_args == NULL)
1243 errx(1, "malloc failed");
1249 ki->ki_env = strdup(fmt(kvm_getenvv, ki,
1250 (char *)NULL, (char *)NULL, 0));
1252 ki->ki_env = strdup("()");
1253 if (ki->ki_env == NULL)
1254 errx(1, "malloc failed");
1260 /* A macro used to improve the readability of pscomp(). */
1261 #define DIFF_RETURN(a, b, field) do { \
1262 if ((a)->field != (b)->field) \
1263 return (((a)->field < (b)->field) ? -1 : 1); \
1267 pscomp(const void *a, const void *b)
1269 const KINFO *ka, *kb;
1273 /* SORTCPU and SORTMEM are sorted in descending order. */
1274 if (sortby == SORTCPU)
1275 DIFF_RETURN(kb, ka, ki_pcpu);
1276 if (sortby == SORTMEM)
1277 DIFF_RETURN(kb, ka, ki_memsize);
1279 * TTY's are sorted in ascending order, except that all NODEV
1280 * processes come before all processes with a device.
1282 if (ka->ki_p->ki_tdev != kb->ki_p->ki_tdev) {
1283 if (ka->ki_p->ki_tdev == NODEV)
1285 if (kb->ki_p->ki_tdev == NODEV)
1287 DIFF_RETURN(ka, kb, ki_p->ki_tdev);
1290 /* PID's and TID's (threads) are sorted in ascending order. */
1291 DIFF_RETURN(ka, kb, ki_p->ki_pid);
1292 DIFF_RETURN(ka, kb, ki_p->ki_tid);
1298 * ICK (all for getopt), would rather hide the ugliness
1299 * here than taint the main code.
1304 * The old convention that 't' with no trailing tty arg means the users
1305 * tty, is only supported if argv[1] doesn't begin with a '-'. This same
1306 * feature is available with the option 'T', which takes no argument.
1309 kludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
1312 char *argp, *cp, *newopts, *ns, *optp, *pidp;
1315 * See if the original value includes any option which takes an
1316 * argument (and will thus use up the remainder of the string).
1319 if (optlist != NULL) {
1320 for (cp = origval; *cp != '\0'; cp++) {
1321 optp = strchr(optlist, *cp);
1322 if ((optp != NULL) && *(optp + 1) == ':') {
1328 if (argp != NULL && *origval == '-')
1332 * if last letter is a 't' flag with no argument (in the context
1333 * of the oldps options -- option string NOT starting with a '-' --
1334 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1336 * However, if a flag accepting a string argument is found earlier
1337 * in the option string (including a possible `t' flag), then the
1338 * remainder of the string must be the argument to that flag; so
1339 * do not modify that argument. Note that a trailing `t' would
1340 * cause argp to be set, if argp was not already set by some
1343 len = strlen(origval);
1344 cp = origval + len - 1;
1346 if (*cp == 't' && *origval != '-' && cp == argp) {
1347 if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
1349 } else if (argp == NULL) {
1351 * The original value did not include any option which takes
1352 * an argument (and that would include `p' and `t'), so check
1353 * the value for trailing number, or comma-separated list of
1354 * numbers, which we will treat as a pid request.
1356 if (isdigitch(*cp)) {
1357 while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1364 * If nothing needs to be added to the string, then return
1365 * the "original" (although possibly modified) value.
1367 if (*origval == '-' && pidp == NULL)
1371 * Create a copy of the string to add '-' and/or 'p' to the
1374 if ((newopts = ns = malloc(len + 3)) == NULL)
1375 errx(1, "malloc failed");
1377 if (*origval != '-')
1378 *ns++ = '-'; /* add option flag */
1381 strcpy(ns, origval);
1384 * Copy everything before the pid string, add the `p',
1385 * and then copy the pid string.
1387 len = pidp - origval;
1388 memcpy(ns, origval, len);
1402 intsize = sizeof(pid_max);
1403 if (sysctlbyname("kern.pid_max", &pid_max, &intsize, NULL, 0) < 0) {
1404 warn("unable to read kern.pid_max");
1412 #define SINGLE_OPTS "[-aCcde" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
1414 (void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
1415 "usage: ps " SINGLE_OPTS " [-O fmt | -o fmt] [-G gid[,gid...]]",
1416 " [-J jid[,jid...]] [-M core] [-N system]",
1417 " [-p pid[,pid...]] [-t tty[,tty...]] [-U user[,user...]]",