xref: /dragonfly/bin/ps/ps.c (revision 820c5b08)
1 /*-
2  * Copyright (c) 1990, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * @(#) Copyright (c) 1990, 1993, 1994 The Regents of the University of California.  All rights reserved.
30  * @(#)ps.c	8.4 (Berkeley) 4/2/94
31  * $FreeBSD: src/bin/ps/ps.c,v 1.30.2.6 2002/07/04 08:30:37 sobomax Exp $
32  */
33 
34 #include <sys/user.h>
35 #include <sys/param.h>
36 #include <sys/time.h>
37 #include <sys/queue.h>
38 #include <sys/resource.h>
39 #include <sys/stat.h>
40 #include <sys/ioctl.h>
41 #include <sys/sysctl.h>
42 #include <sys/mount.h>
43 
44 #include <ctype.h>
45 #include <err.h>
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <kvm.h>
49 #include <limits.h>
50 #include <locale.h>
51 #include <nlist.h>
52 #include <paths.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
57 #include <pwd.h>
58 
59 #include "ps.h"
60 
61 #define SEP ", \t"		/* username separators */
62 
63 #define KHSIZE	2048
64 #define KHMASK	(KHSIZE - 1)
65 
66 KINFO *KInfo;
67 KINFO **KSort;
68 struct varent *vhead, *vtail;
69 
70 int	eval;			/* exit value */
71 int	cflag;			/* -c */
72 int	rawcpu;			/* -C */
73 int	sumrusage;		/* -S */
74 int	termwidth;		/* width of screen (0 == infinity) */
75 int	totwidth;		/* calculated width of requested variables */
76 int	numcpus;		/* hw.ncpu */
77 int	showtid;		/* -H */
78 
79 static int needuser, needcomm, needenv;
80 #if defined(LAZY_PS)
81 static int forceuread=0;
82 #define PS_ARGS	"aCcefgHhjLlM:mN:O:o:p:rRSTt:U:uvwx"
83 #else
84 static int forceuread=1;
85 #define PS_ARGS	"aCcegHhjLlM:mN:O:o:p:rRSTt:U:uvwx"
86 #endif
87 
88 enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
89 
90 static const char *getfmt (char **(*)(kvm_t *, const struct kinfo_proc *, int),
91 		    KINFO *, char *, int);
92 static char	*kludge_oldps_options (char *);
93 static int	 pscomp (const void *, const void *);
94 static void	 dochain (KINFO **ksort, int *nentriesp, pid_t pid);
95 static void	 saveuser (KINFO *);
96 static void	 scanvars (void);
97 static void	 dynsizevars (KINFO *);
98 static void	 sizevars (void);
99 static int	 check_procfs(void);
100 static void	 usage (void);
101 static uid_t	*getuids(const char *, int *);
102 
103 struct timeval btime;
104 
105 static char dfmt[] = "pid tt state time command";
106 static char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
107 static char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
108 static char   o1[] = "pid";
109 static char   o2[] = "tt state time command";
110 static char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
111 static char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
112 
113 kvm_t *kd;
114 
115 int
116 main(int argc, char **argv)
117 {
118 	struct kinfo_proc *kp;
119 	struct varent *vent;
120 	struct winsize ws;
121 	dev_t ttydev;
122 	pid_t pid;
123 	uid_t *uids;
124 	int all, ch, flag, i, fmt, ofmt, lineno, nentries, nocludge, dropgid;
125 	int prtheader, wflag, what, xflg, uid, nuids;
126 	int chainflg;
127 	char errbuf[_POSIX2_LINE_MAX];
128 	const char *cp, *nlistf, *memf;
129 	size_t btime_size = sizeof(struct timeval);
130 	size_t numcpus_size = sizeof(numcpus);
131 
132 	setlocale(LC_ALL, "");
133 
134 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
135 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
136 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
137 	     ws.ws_col == 0)
138 		termwidth = 79;
139 	else
140 		termwidth = ws.ws_col - 1;
141 
142 	/*
143 	 * Don't apply a kludge if the first argument is an option taking an
144 	 * argument
145 	 */
146 	if (argc > 1) {
147 		nocludge = 0;
148 		if (argv[1][0] == '-') {
149 			for (cp = PS_ARGS; *cp != '\0'; cp++) {
150 				if (*cp != ':')
151 					continue;
152 				if (*(cp - 1) == argv[1][1]) {
153 					nocludge = 1;
154 					break;
155 				}
156 			}
157 		}
158 		if (nocludge == 0)
159 			argv[1] = kludge_oldps_options(argv[1]);
160 	}
161 
162 	all = fmt = ofmt = prtheader = wflag = xflg = showtid = 0;
163 	chainflg = 0;
164 	pid = -1;
165 	nuids = 0;
166 	uids = NULL;
167 	ttydev = NODEV;
168 	dropgid = 0;
169 	memf = nlistf = _PATH_DEVNULL;
170 
171 	while ((ch = getopt(argc, argv, PS_ARGS)) != -1) {
172 		switch((char)ch) {
173 		case 'a':
174 			all = 1;
175 			break;
176 		case 'C':
177 			rawcpu = 1;
178 			break;
179 		case 'c':
180 			cflag = 1;
181 			break;
182 		case 'e':			/* XXX set ufmt */
183 			needenv = 1;
184 			break;
185 		case 'g':
186 			break;			/* no-op */
187 		case 'H':
188 			showtid = KERN_PROC_FLAG_LWP;
189 			break;
190 		case 'h':
191 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
192 			break;
193 		case 'j':
194 			parsefmt(jfmt);
195 			fmt = 1;
196 			jfmt[0] = '\0';
197 			break;
198 		case 'L':
199 			showkey();
200 			exit(0);
201 		case 'l':
202 			parsefmt(lfmt);
203 			fmt = 1;
204 			lfmt[0] = '\0';
205 			break;
206 		case 'M':
207 			memf = optarg;
208 			dropgid = 1;
209 			break;
210 		case 'm':
211 			sortby = SORTMEM;
212 			break;
213 		case 'N':
214 			nlistf = optarg;
215 			dropgid = 1;
216 			break;
217 		case 'O':
218 			parsefmt(o1);
219 			parsefmt(optarg);
220 			parsefmt(o2);
221 			o1[0] = o2[0] = '\0';
222 			fmt = 1;
223 			break;
224 		case 'o':
225 			parsefmt(optarg);
226 			fmt = ofmt = 1;
227 			break;
228 #if defined(LAZY_PS)
229 		case 'f':
230 			if (getuid() == 0 || getgid() == 0)
231 			    forceuread = 1;
232 			break;
233 #endif
234 		case 'p':
235 			pid = atol(optarg);
236 			xflg = 1;
237 			break;
238 		case 'r':
239 			sortby = SORTCPU;
240 			break;
241 		case 'R':
242 			chainflg = 1;
243 			break;
244 		case 'S':
245 			sumrusage = 1;
246 			break;
247 		case 'T':
248 			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
249 				errx(1, "stdin: not a terminal");
250 			/* FALLTHROUGH */
251 		case 't': {
252 			struct stat sb;
253 			char pathbuf[PATH_MAX];
254 			const char *ttypath;
255 
256 			if (strcmp(optarg, "co") == 0) {
257 				ttypath = _PATH_CONSOLE;
258 			} else if (*optarg >= '0' && *optarg <= '9') {
259 				snprintf(pathbuf, sizeof(pathbuf),
260 					 "%spts/%s", _PATH_DEV, optarg);
261 				ttypath = pathbuf;
262 			} else if (*optarg != '/') {
263 				snprintf(pathbuf, sizeof(pathbuf),
264 					 "%s%s", _PATH_TTY, optarg);
265 				ttypath = pathbuf;
266 			} else {
267 				ttypath = optarg;
268 			}
269 			if (stat(ttypath, &sb) == -1)
270 				err(1, "%s", ttypath);
271 			if (!S_ISCHR(sb.st_mode))
272 				errx(1, "%s: not a terminal", ttypath);
273 			ttydev = sb.st_rdev;
274 			break;
275 		}
276 		case 'U':
277 			uids = getuids(optarg, &nuids);
278 			xflg++;		/* XXX: intuitive? */
279 			break;
280 		case 'u':
281 			parsefmt(ufmt);
282 			sortby = SORTCPU;
283 			fmt = 1;
284 			ufmt[0] = '\0';
285 			break;
286 		case 'v':
287 			parsefmt(vfmt);
288 			sortby = SORTMEM;
289 			fmt = 1;
290 			vfmt[0] = '\0';
291 			break;
292 		case 'w':
293 			if (wflag)
294 				termwidth = UNLIMITED;
295 			else if (termwidth < 131)
296 				termwidth = 131;
297 			wflag++;
298 			break;
299 		case 'x':
300 			xflg = 1;
301 			break;
302 		case '?':
303 		default:
304 			usage();
305 		}
306 	}
307 	argc -= optind;
308 	argv += optind;
309 
310 	/*
311 	 * If the user specified ps -e then they want a copy of the process
312 	 * environment kvm_getenvv(3) attempts to open /proc/<pid>/mem.
313 	 * Check to make sure that procfs is mounted on /proc, otherwise
314 	 * print a warning informing the user that output will be incomplete.
315 	 */
316 	if (needenv == 1 && check_procfs() == 0)
317 		warnx("Process environment requires procfs(5)");
318 
319 #define	BACKWARD_COMPATIBILITY
320 #ifdef	BACKWARD_COMPATIBILITY
321 	if (*argv) {
322 		nlistf = *argv;
323 		if (*++argv) {
324 			memf = *argv;
325 		}
326 	}
327 #endif
328 	/*
329 	 * Discard setgid privileges if not the running kernel so that bad
330 	 * guys can't print interesting stuff from kernel memory.
331 	 */
332 	if (dropgid) {
333 		setgid(getgid());
334 		setuid(getuid());
335 	}
336 
337 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
338 	if (kd == NULL)
339 		errx(1, "%s", errbuf);
340 
341 	if (!fmt)
342 		parsefmt(dfmt);
343 
344 	/*
345 	 * Add TID to output format if requested unless user-specific format
346 	 * selected.
347 	 */
348 	if (showtid && !ofmt)
349 		insert_tid_in_fmt();
350 
351 	/* XXX - should be cleaner */
352 	if (!all && ttydev == NODEV && pid == -1 && !nuids) {
353 		if ((uids = malloc(sizeof (*uids))) == NULL)
354 			errx(1, "malloc: %s", strerror(errno));
355 		nuids = 1;
356 		*uids = getuid();
357 	}
358 
359 	/*
360 	 * scan requested variables, noting what structures are needed,
361 	 * and adjusting header widths as appropriate.
362 	 */
363 	scanvars();
364 
365 	/*
366 	 * Get boot time
367 	 */
368 	if (sysctlbyname("kern.boottime", &btime, &btime_size, NULL, 0) < 0) {
369 		perror("sysctl: kern.boottime");
370 		exit(EXIT_FAILURE);
371 	}
372 
373 	/*
374 	 * Get number of cpus
375 	 */
376 	if (sysctlbyname("hw.ncpu", &numcpus, &numcpus_size, NULL, 0) < 0)
377 		numcpus = 1;
378 
379 	/*
380 	 * get proc list
381 	 */
382 	if (nuids == 1) {
383 		what = KERN_PROC_UID;
384 		flag = *uids;
385 	} else if (ttydev != NODEV) {
386 		what = KERN_PROC_TTY;
387 		flag = ttydev;
388 	} else if (pid != -1 && chainflg == 0) {
389 		what = KERN_PROC_PID;
390 		flag = pid;
391 	} else {
392 		what = KERN_PROC_ALL;
393 		flag = 0;
394 	}
395 	what |= showtid;
396 
397 	/*
398 	 * select procs
399 	 */
400 	if ((kp = kvm_getprocs(kd, what, flag, &nentries)) == NULL)
401 		errx(1, "%s", kvm_geterr(kd));
402 	if ((KInfo = calloc(nentries, sizeof(KINFO))) == NULL)
403 		err(1, NULL);
404 	if ((KSort = malloc(nentries * sizeof(KINFO *))) == NULL)
405 		err(1, NULL);
406 
407 	for (i = 0; i < nentries; ++i) {
408 		KInfo[i].ki_proc = &kp[i];
409 		KInfo[i].ki_indent = -1;
410 		KInfo[i].ki_ctailp = &KInfo[i].ki_cbase;
411 		if (needuser)
412 			saveuser(&KInfo[i]);
413 		dynsizevars(&KInfo[i]);
414 		KSort[i] = &KInfo[i];
415 	}
416 
417 	sizevars();
418 
419 	/*
420 	 * print header
421 	 */
422 	printheader();
423 	if (nentries == 0)
424 		exit(1);
425 	/*
426 	 * sort proc list
427 	 */
428 	qsort(KSort, nentries, sizeof(KINFO *), pscomp);
429 
430 	/*
431 	 * rejigger and indent children, parent(s) and children
432 	 * at each level retain the above sort characteristics.
433 	 */
434 	if (chainflg)
435 		dochain(KSort, &nentries, pid);
436 
437 	/*
438 	 * for each proc, call each variable output function.
439 	 */
440 	for (i = lineno = 0; i < nentries; i++) {
441 		if (xflg == 0 && (KI_PROC(KSort[i], tdev) == NODEV ||
442 		    (KI_PROC(KSort[i], flags) & P_CONTROLT ) == 0))
443 			continue;
444 		if (nuids > 1) {
445 			for (uid = 0; uid < nuids; uid++)
446 				if (KI_PROC(KSort[i], uid) ==
447 				    uids[uid])
448 					break;
449 			if (uid == nuids)
450 				continue;
451 		}
452 		STAILQ_FOREACH(vent, &var_head, link) {
453 			(vent->var->oproc)(KSort[i], vent);
454 			if (STAILQ_NEXT(vent, link) != NULL)
455 				putchar(' ');
456 		}
457 		putchar('\n');
458 		if (prtheader && lineno++ == prtheader - 4) {
459 			putchar('\n');
460 			printheader();
461 			lineno = 0;
462 		}
463 	}
464 	free(uids);
465 
466 	exit(eval);
467 }
468 
469 uid_t *
470 getuids(const char *arg, int *nuids)
471 {
472 	char name[MAXLOGNAME];
473 	struct passwd *pwd;
474 	uid_t *uids, *moreuids;
475 	size_t l;
476 	int alloc;
477 
478 
479 	alloc = 0;
480 	*nuids = 0;
481 	uids = NULL;
482 	for (; (l = strcspn(arg, SEP)) > 0; arg += l + strspn(arg + l, SEP)) {
483 		if (l >= sizeof name) {
484 			warnx("%.*s: name too long", (int)l, arg);
485 			continue;
486 		}
487 		strncpy(name, arg, l);
488 		name[l] = '\0';
489 		if ((pwd = getpwnam(name)) == NULL) {
490 			warnx("%s: no such user", name);
491 			continue;
492 		}
493 		if (*nuids >= alloc) {
494 			alloc = (alloc + 1) << 1;
495 			moreuids = realloc(uids, alloc * sizeof (*uids));
496 			if (moreuids == NULL) {
497 				free(uids);
498 				errx(1, "realloc: %s", strerror(errno));
499 			}
500 			uids = moreuids;
501 		}
502 		uids[(*nuids)++] = pwd->pw_uid;
503 	}
504 	endpwent();
505 
506 	if (!*nuids)
507 		errx(1, "No users specified");
508 
509 	return uids;
510 }
511 
512 static void
513 scanvars(void)
514 {
515 	struct varent *vent;
516 	const VAR *v;
517 
518 	STAILQ_FOREACH(vent, &var_head, link) {
519 		v = vent->var;
520 		if (v->flag & DSIZ) {
521 			vent->dwidth = vent->width;
522 			vent->width = 0;
523 		}
524 		if (v->flag & USER)
525 			needuser = 1;
526 		if (v->flag & COMM)
527 			needcomm = 1;
528 	}
529 }
530 
531 static void
532 dynsizevars(KINFO *ki)
533 {
534 	struct varent *vent;
535 	const VAR *v;
536 	int i;
537 
538 	STAILQ_FOREACH(vent, &var_head, link) {
539 		v = vent->var;
540 		if (!(v->flag & DSIZ))
541 			continue;
542 		i = (v->sproc)( ki);
543 		if (vent->width < i)
544 			vent->width = i;
545 		if (vent->width > vent->dwidth)
546 			vent->width = vent->dwidth;
547 	}
548 }
549 
550 static void
551 sizevars(void)
552 {
553 	struct varent *vent;
554 	int i;
555 
556 	STAILQ_FOREACH(vent, &var_head, link) {
557 		i = strlen(vent->header);
558 		if (vent->width < i)
559 			vent->width = i;
560 		totwidth += vent->width + 1;	/* +1 for space */
561 	}
562 	totwidth--;
563 }
564 
565 static const char *
566 getfmt(char **(*fn) (kvm_t *, const struct kinfo_proc *, int), KINFO *ki, char
567     *comm, int maxlen)
568 {
569 	const char *s;
570 
571 	if ((s =
572 	    fmt_argv((*fn)(kd, ki->ki_proc, termwidth), comm, maxlen)) == NULL)
573 		err(1, NULL);
574 	return (s);
575 }
576 
577 static void
578 saveuser(KINFO *ki)
579 {
580 	/*
581 	 * save arguments if needed
582 	 */
583 	if (needcomm) {
584 		ki->ki_args = getfmt(kvm_getargv, ki, KI_PROC(ki, comm),
585 		    MAXCOMLEN);
586 	} else {
587 		ki->ki_args = NULL;
588 	}
589 	if (needenv) {
590 		ki->ki_env = getfmt(kvm_getenvv, ki, NULL, 0);
591 	} else {
592 		ki->ki_env = NULL;
593 	}
594 }
595 
596 static int
597 pscomp(const void *arg_a, const void *arg_b)
598 {
599 	const KINFO *a = *(KINFO * const *)arg_a;
600 	const KINFO *b = *(KINFO * const *)arg_b;
601 	double di;
602 	segsz_t si;
603 	int i;
604 
605 #define VSIZE(k) (KI_PROC(k, vm_dsize) + KI_PROC(k, vm_ssize) + \
606 		  KI_PROC(k, vm_tsize))
607 
608 #if 0
609 	if (sortby == SORTIAC)
610 		return (KI_PROC(a)->p_usdata.bsd4.interactive - KI_PROC(b)->p_usdata.bsd4.interactive);
611 #endif
612 	if (sortby == SORTCPU) {
613 		di = getpcpu(b) - getpcpu(a);
614 		if (di < 0.0)
615 			return(-1);
616 		if (di > 0.0)
617 			return(+1);
618 		/* fall through */
619 	}
620 	if (sortby == SORTMEM) {
621 		si = VSIZE(b) - VSIZE(a);
622 		if (si < 0)
623 			return(-1);
624 		if (si > 0)
625 			return(+1);
626 		/* fall through */
627 	}
628 	i = KI_PROC(a, tdev) - KI_PROC(b, tdev);
629 	if (i == 0)
630 		i = KI_PROC(a, pid) - KI_PROC(b, pid);
631 	return (i);
632 }
633 
634 /*
635  * Chain (-R) option.  Sub-sorts by parent/child association.
636  */
637 static int dochain_final(KINFO **kfinal, KINFO *base, int j);
638 
639 static void
640 dochain (KINFO **ksort, int *nentriesp, pid_t pid)
641 {
642 	int nentries = *nentriesp;
643 	int i;
644 	int j;
645 	int hi;
646 	pid_t ppid;
647 	KINFO *scan;
648 	KINFO **khash;
649 	KINFO **kfinal;
650 
651 	/*
652 	 * First hash all the pids so we can quickly locate the
653 	 * parent pids.
654 	 */
655 	khash = calloc(KHSIZE, sizeof(KINFO *));
656 	kfinal = calloc(nentries, sizeof(KINFO *));
657 
658 	for (i = 0; i < nentries; ++i) {
659 		hi = KI_PROC(ksort[i], pid) & KHMASK;
660 
661 		ksort[i]->ki_hnext = khash[hi];
662 		khash[hi] = ksort[i];
663 	}
664 
665 	/*
666 	 * Now run through the list and create the parent associations.
667 	 */
668 	for (i = 0; i < nentries; ++i) {
669 		ppid = KI_PROC(ksort[i], ppid);
670 
671 		if (ppid <= 0 || KI_PROC(ksort[i], pid) <= 0) {
672 			scan = NULL;
673 		} else {
674 			for (scan = khash[ppid & KHMASK];
675 			     scan;
676 			     scan = scan->ki_hnext) {
677 				if (ppid == KI_PROC(scan, pid))
678 					break;
679 			}
680 		}
681 		if (scan) {
682 			ksort[i]->ki_parent = scan;
683 			*scan->ki_ctailp = ksort[i];
684 			scan->ki_ctailp = &ksort[i]->ki_cnext;
685 		}
686 	}
687 
688 	/*
689 	 * Now regenerate the list starting at root entries, then copyback.
690 	 */
691 	for (i = j = 0; i < nentries; ++i) {
692 		if (pid != (pid_t)-1) {
693 			if (KI_PROC(ksort[i], pid) == pid) {
694 				ksort[i]->ki_indent = 0;
695 				j = dochain_final(kfinal, ksort[i], j);
696 			}
697 		} else if (ksort[i]->ki_parent == NULL) {
698 			ksort[i]->ki_indent = 0;
699 			j = dochain_final(kfinal, ksort[i], j);
700 		}
701 	}
702 
703 	/*
704 	 * There might be fewer entries if we restricted the chain to a
705 	 * pid.
706 	 */
707 	nentries = j;
708 	*nentriesp = nentries;
709 
710 	if (nentries)
711 		bcopy(kfinal, ksort, nentries * sizeof(kfinal[0]));
712 	free(kfinal);
713 	free(khash);
714 }
715 
716 static int
717 dochain_final(KINFO **kfinal, KINFO *base, int j)
718 {
719 	KINFO *scan;
720 
721 	kfinal[j++] = base;
722 	for (scan = base->ki_cbase; scan; scan = scan->ki_cnext) {
723 		/*
724 		 * Don't let us loop
725 		 */
726 		if (scan->ki_indent >= 0)
727 			continue;
728 		scan->ki_indent = base->ki_indent + 1;
729 		j = dochain_final(kfinal, scan, j);
730 	}
731 	return (j);
732 }
733 
734 /*
735  * ICK (all for getopt), would rather hide the ugliness
736  * here than taint the main code.
737  *
738  *  ps foo -> ps -foo
739  *  ps 34 -> ps -p34
740  *
741  * The old convention that 't' with no trailing tty arg means the users
742  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
743  * feature is available with the option 'T', which takes no argument.
744  */
745 static char *
746 kludge_oldps_options(char *s)
747 {
748 	size_t len;
749 	char *newopts, *ns, *cp;
750 
751 	len = strlen(s);
752 	if ((newopts = ns = malloc(len + 2)) == NULL)
753 		err(1, NULL);
754 	/*
755 	 * options begin with '-'
756 	 */
757 	if (*s != '-')
758 		*ns++ = '-';	/* add option flag */
759 
760 	/*
761 	 * gaze to end of argv[1]
762 	 */
763 	cp = s + len - 1;
764 
765 	/*
766 	 * if last letter is a 't' flag with no argument (in the context
767 	 * of the oldps options -- option string NOT starting with a '-' --
768 	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
769 	 *
770 	 * However, if a flag accepting a string argument is found in the
771 	 * option string, the remainder of the string is the argument to
772 	 * that flag; do not modify that argument.
773 	 */
774 	if (strcspn(s, "MNOoU") == len && *cp == 't' && *s != '-') {
775 		*cp = 'T';
776 	} else {
777 		/*
778 		 * otherwise check for trailing number, which *may* be a
779 		 * pid.
780 		 */
781 		while (cp >= s && isdigit(*cp))
782 			--cp;
783 	}
784 	cp++;
785 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
786 	ns += cp - s;
787 	/*
788 	 * if there's a trailing number, and not a preceding 'p' (pid) or
789 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
790 	 */
791 	if (isdigit(*cp) &&
792 	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
793 	    (cp - 1 == s || cp[-2] != 't')) {
794 		*ns++ = 'p';
795 	}
796 	strcpy(ns, cp);		/* and append the number */
797 
798 	return (newopts);
799 }
800 
801 static int
802 check_procfs(void)
803 {
804 	struct statfs mnt;
805 
806 	if (statfs("/proc", &mnt) < 0)
807 		return (0);
808 	if (strcmp(mnt.f_fstypename, "procfs") != 0)
809 		return (0);
810 	return (1);
811 }
812 
813 static void
814 usage(void)
815 {
816 
817 	fprintf(stderr, "%s\n%s\n%s\n",
818 	    "usage: ps [-aCcefhHjlmrSTuvwx] [-M core] [-N system] [-O fmt] [-o fmt] [-p pid]",
819 	    "          [-t tty] [-U username]",
820 	    "       ps [-L]");
821 	exit(1);
822 }
823