ps.c revision 137890
12140Speterz/*-
22362Sohair * Copyright (c) 1990, 1993, 1994
32140Speterz *	The Regents of the University of California.  All rights reserved.
42140Speterz *
52140Speterz * Redistribution and use in source and binary forms, with or without
62140Speterz * modification, are permitted provided that the following conditions
72140Speterz * are met:
82140Speterz * 1. Redistributions of source code must retain the above copyright
92140Speterz *    notice, this list of conditions and the following disclaimer.
102140Speterz * 2. Redistributions in binary form must reproduce the above copyright
112140Speterz *    notice, this list of conditions and the following disclaimer in the
122140Speterz *    documentation and/or other materials provided with the distribution.
132140Speterz * 4. Neither the name of the University nor the names of its contributors
142140Speterz *    may be used to endorse or promote products derived from this software
152140Speterz *    without specific prior written permission.
162140Speterz *
172140Speterz * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
182140Speterz * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
192362Sohair * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
202362Sohair * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
212362Sohair * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
222140Speterz * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
232140Speterz * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
242140Speterz * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
252140Speterz * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
262140Speterz * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
272140Speterz * SUCH DAMAGE.
282140Speterz * ------+---------+---------+-------- + --------+---------+---------+---------*
292140Speterz * Copyright (c) 2004  - Garance Alistair Drosehn <gad@FreeBSD.org>.
302140Speterz * All rights reserved.
312140Speterz *
322140Speterz * Significant modifications made to bring `ps' options somewhat closer
332140Speterz * to the standard for `ps' as described in SingleUnixSpec-v3.
342140Speterz * ------+---------+---------+-------- + --------+---------+---------+---------*
352140Speterz */
362140Speterz
372140Speterz#ifndef lint
382140Speterzstatic const char copyright[] =
392140Speterz"@(#) Copyright (c) 1990, 1993, 1994\n\
402140Speterz	The Regents of the University of California.  All rights reserved.\n";
412140Speterz#endif /* not lint */
422140Speterz
432140Speterz#if 0
442140Speterz#ifndef lint
452140Speterzstatic char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
462140Speterz#endif /* not lint */
472140Speterz#endif
482140Speterz
492140Speterz#include <sys/cdefs.h>
502140Speterz__FBSDID("$FreeBSD: head/bin/ps/ps.c 137890 2004-11-19 16:11:54Z csjp $");
512140Speterz
522140Speterz#include <sys/param.h>
532140Speterz#include <sys/proc.h>
542140Speterz#include <sys/user.h>
552140Speterz#include <sys/stat.h>
562140Speterz#include <sys/ioctl.h>
572140Speterz#include <sys/sysctl.h>
582140Speterz#include <sys/mount.h>
592140Speterz
602140Speterz#include <ctype.h>
612140Speterz#include <err.h>
622140Speterz#include <errno.h>
632140Speterz#include <fcntl.h>
642140Speterz#include <grp.h>
652140Speterz#include <kvm.h>
662140Speterz#include <limits.h>
672140Speterz#include <locale.h>
682140Speterz#include <paths.h>
692140Speterz#include <pwd.h>
702140Speterz#include <stdio.h>
712140Speterz#include <stdlib.h>
722140Speterz#include <string.h>
732140Speterz#include <unistd.h>
742140Speterz
752140Speterz#include "ps.h"
762140Speterz
772140Speterz#define	W_SEP	" \t"		/* "Whitespace" list separators */
782140Speterz#define	T_SEP	","		/* "Terminate-element" list separators */
792140Speterz
802140Speterz#ifdef LAZY_PS
812140Speterz#define	DEF_UREAD	0
822140Speterz#define	OPT_LAZY_f	"f"
832140Speterz#else
842140Speterz#define	DEF_UREAD	1	/* Always do the more-expensive read. */
852140Speterz#define	OPT_LAZY_f		/* I.e., the `-f' option is not added. */
862140Speterz#endif
872140Speterz
882140Speterz/*
892140Speterz * isdigit takes an `int', but expects values in the range of unsigned char.
902140Speterz * This wrapper ensures that values from a 'char' end up in the correct range.
912140Speterz */
922140Speterz#define	isdigitch(Anychar) isdigit((u_char)(Anychar))
932140Speterz
942140Speterzint	 cflag;			/* -c */
952140Speterzint	 eval;			/* Exit value */
962140Speterztime_t	 now;			/* Current time(3) value */
972140Speterzint	 rawcpu;		/* -C */
982140Speterzint	 sumrusage;		/* -S */
99int	 termwidth;		/* Width of the screen (0 == infinity). */
100int	 totwidth;		/* Calculated-width of requested variables. */
101
102struct velisthead varlist = STAILQ_HEAD_INITIALIZER(varlist);
103
104static int	 forceuread = DEF_UREAD; /* Do extra work to get u-area. */
105static kvm_t	*kd;
106static KINFO	*kinfo;
107static int	 needcomm;	/* -o "command" */
108static int	 needenv;	/* -e */
109static int	 needuser;	/* -o "user" */
110static int	 optfatal;	/* Fatal error parsing some list-option. */
111
112static enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
113
114struct listinfo;
115typedef	int	addelem_rtn(struct listinfo *_inf, const char *_elem);
116
117struct listinfo {
118	int		 count;
119	int		 maxcount;
120	int		 elemsize;
121	addelem_rtn	*addelem;
122	const char	*lname;
123	union {
124		gid_t	*gids;
125		pid_t	*pids;
126		dev_t	*ttys;
127		uid_t	*uids;
128		void	*ptr;
129	} l;
130};
131
132static int	 check_procfs(void);
133static int	 addelem_gid(struct listinfo *, const char *);
134static int	 addelem_pid(struct listinfo *, const char *);
135static int	 addelem_tty(struct listinfo *, const char *);
136static int	 addelem_uid(struct listinfo *, const char *);
137static void	 add_list(struct listinfo *, const char *);
138static void	 dynsizevars(KINFO *);
139static void	*expand_list(struct listinfo *);
140static const char *
141		 fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
142		    KINFO *, char *, int);
143static void	 free_list(struct listinfo *);
144static void	 init_list(struct listinfo *, addelem_rtn, int, const char *);
145static char	*kludge_oldps_options(const char *, char *, const char *);
146static int	 pscomp(const void *, const void *);
147static void	 saveuser(KINFO *);
148static void	 scanvars(void);
149static void	 sizevars(void);
150static void	 usage(void);
151
152static char dfmt[] = "pid,tt,state,time,command";
153static char jfmt[] = "user,pid,ppid,pgid,sid,jobc,state,tt,time,command";
154static char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
155			"tt,time,command";
156static char   o1[] = "pid";
157static char   o2[] = "tt,state,time,command";
158static char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
159static char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
160			"%cpu,%mem,command";
161static char Zfmt[] = "label";
162
163#define	PS_ARGS	"AaCce" OPT_LAZY_f "G:gHhjLlM:mN:O:o:p:rSTt:U:uvwXxZ"
164
165int
166main(int argc, char *argv[])
167{
168	struct listinfo gidlist, pgrplist, pidlist;
169	struct listinfo ruidlist, sesslist, ttylist, uidlist;
170	struct kinfo_proc *kp;
171	KINFO *next_KINFO;
172	struct varent *vent;
173	struct winsize ws;
174	const char *nlistf, *memf;
175	char *cols;
176	int all, ch, elem, flag, _fmt, i, lineno;
177	int nentries, nkept, nselectors;
178	int prtheader, showthreads, wflag, what, xkeep, xkeep_implied;
179	char errbuf[_POSIX2_LINE_MAX];
180
181	(void) setlocale(LC_ALL, "");
182	time(&now);			/* Used by routines in print.c. */
183
184	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
185		termwidth = atoi(cols);
186	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
187	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
188	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
189	     ws.ws_col == 0)
190		termwidth = 79;
191	else
192		termwidth = ws.ws_col - 1;
193
194	/*
195	 * Hide a number of option-processing kludges in a separate routine,
196	 * to support some historical BSD behaviors, such as `ps axu'.
197	 */
198	if (argc > 1)
199		argv[1] = kludge_oldps_options(PS_ARGS, argv[1], argv[2]);
200
201	all = _fmt = nselectors = optfatal = 0;
202	prtheader = showthreads = wflag = xkeep_implied = 0;
203	xkeep = -1;			/* Neither -x nor -X. */
204	init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
205	init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
206	init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
207	init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
208	init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
209	init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
210	init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
211	memf = nlistf = _PATH_DEVNULL;
212	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
213		switch ((char)ch) {
214		case 'A':
215			/*
216			 * Exactly the same as `-ax'.   This has been
217			 * added for compatability with SUSv3, but for
218			 * now it will not be described in the man page.
219			 */
220			nselectors++;
221			all = xkeep = 1;
222			break;
223		case 'a':
224			nselectors++;
225			all = 1;
226			break;
227		case 'C':
228			rawcpu = 1;
229			break;
230		case 'c':
231			cflag = 1;
232			break;
233		case 'e':			/* XXX set ufmt */
234			needenv = 1;
235			break;
236#ifdef LAZY_PS
237		case 'f':
238			if (getuid() == 0 || getgid() == 0)
239				forceuread = 1;
240			break;
241#endif
242		case 'G':
243			add_list(&gidlist, optarg);
244			xkeep_implied = 1;
245			nselectors++;
246			break;
247		case 'g':
248#if 0
249			/*-
250			 * XXX - This SUSv3 behavior is still under debate
251			 *	since it conflicts with the (undocumented)
252			 *	`-g' option.  So we skip it for now.
253			 */
254			add_list(&pgrplist, optarg);
255			xkeep_implied = 1;
256			nselectors++;
257			break;
258#else
259			/* The historical BSD-ish (from SunOS) behavior. */
260			break;			/* no-op */
261#endif
262		case 'H':
263			showthreads = KERN_PROC_INC_THREAD;
264			break;
265		case 'h':
266			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
267			break;
268		case 'j':
269			parsefmt(jfmt, 0);
270			_fmt = 1;
271			jfmt[0] = '\0';
272			break;
273		case 'L':
274			showkey();
275			exit(0);
276		case 'l':
277			parsefmt(lfmt, 0);
278			_fmt = 1;
279			lfmt[0] = '\0';
280			break;
281		case 'M':
282			memf = optarg;
283			break;
284		case 'm':
285			sortby = SORTMEM;
286			break;
287		case 'N':
288			nlistf = optarg;
289			break;
290		case 'O':
291			parsefmt(o1, 1);
292			parsefmt(optarg, 1);
293			parsefmt(o2, 1);
294			o1[0] = o2[0] = '\0';
295			_fmt = 1;
296			break;
297		case 'o':
298			parsefmt(optarg, 1);
299			_fmt = 1;
300			break;
301		case 'p':
302			add_list(&pidlist, optarg);
303			/*
304			 * Note: `-p' does not *set* xkeep, but any values
305			 * from pidlist are checked before xkeep is.  That
306			 * way they are always matched, even if the user
307			 * specifies `-X'.
308			 */
309			nselectors++;
310			break;
311#if 0
312		case 'R':
313			/*-
314			 * XXX - This un-standard option is still under
315			 *	debate.  This is what SUSv3 defines as
316			 *	the `-U' option, and while it would be
317			 *	nice to have, it could cause even more
318			 *	confusion to implement it as `-R'.
319			 */
320			add_list(&ruidlist, optarg);
321			xkeep_implied = 1;
322			nselectors++;
323			break;
324#endif
325		case 'r':
326			sortby = SORTCPU;
327			break;
328		case 'S':
329			sumrusage = 1;
330			break;
331#if 0
332		case 's':
333			/*-
334			 * XXX - This non-standard option is still under
335			 *	debate.  This *is* supported on Solaris,
336			 *	Linux, and IRIX, but conflicts with `-s'
337			 *	on NetBSD and maybe some older BSD's.
338			 */
339			add_list(&sesslist, optarg);
340			xkeep_implied = 1;
341			nselectors++;
342			break;
343#endif
344		case 'T':
345			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
346				errx(1, "stdin: not a terminal");
347			/* FALLTHROUGH */
348		case 't':
349			add_list(&ttylist, optarg);
350			xkeep_implied = 1;
351			nselectors++;
352			break;
353		case 'U':
354			/* This is what SUSv3 defines as the `-u' option. */
355			add_list(&uidlist, optarg);
356			xkeep_implied = 1;
357			nselectors++;
358			break;
359		case 'u':
360			parsefmt(ufmt, 0);
361			sortby = SORTCPU;
362			_fmt = 1;
363			ufmt[0] = '\0';
364			break;
365		case 'v':
366			parsefmt(vfmt, 0);
367			sortby = SORTMEM;
368			_fmt = 1;
369			vfmt[0] = '\0';
370			break;
371		case 'w':
372			if (wflag)
373				termwidth = UNLIMITED;
374			else if (termwidth < 131)
375				termwidth = 131;
376			wflag++;
377			break;
378		case 'X':
379			/*
380			 * Note that `-X' and `-x' are not standard "selector"
381			 * options. For most selector-options, we check *all*
382			 * processes to see if any are matched by the given
383			 * value(s).  After we have a set of all the matched
384			 * processes, then `-X' and `-x' govern whether we
385			 * modify that *matched* set for processes which do
386			 * not have a controlling terminal.  `-X' causes
387			 * those processes to be deleted from the matched
388			 * set, while `-x' causes them to be kept.
389			 */
390			xkeep = 0;
391			break;
392		case 'x':
393			xkeep = 1;
394			break;
395		case 'Z':
396			parsefmt(Zfmt, 0);
397			Zfmt[0] = '\0';
398			break;
399		case '?':
400		default:
401			usage();
402		}
403	argc -= optind;
404	argv += optind;
405
406	/*
407	 * If the user specified ps -e then they want a copy of the process
408	 * environment kvm_getenvv(3) attempts to open /proc/<pid>/mem.
409	 * Check to make sure that procfs is mounted on /proc, otherwise
410	 * print a warning informing the user that output will be incomplete.
411	 */
412	if (needenv == 1 && check_procfs() == 0)
413		warnx("Process environment requires procfs(5)");
414	/*
415	 * If there arguments after processing all the options, attempt
416	 * to treat them as a list of process ids.
417	 */
418	while (*argv) {
419		if (!isdigitch(**argv))
420			break;
421		add_list(&pidlist, *argv);
422		argv++;
423	}
424	if (*argv) {
425		fprintf(stderr, "%s: illegal argument: %s\n",
426		    getprogname(), *argv);
427		usage();
428	}
429	if (optfatal)
430		exit(1);		/* Error messages already printed. */
431	if (xkeep < 0)			/* Neither -X nor -x was specified. */
432		xkeep = xkeep_implied;
433
434	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
435	if (kd == 0)
436		errx(1, "%s", errbuf);
437
438	if (!_fmt)
439		parsefmt(dfmt, 0);
440
441	if (nselectors == 0) {
442		uidlist.l.ptr = malloc(sizeof(uid_t));
443		if (uidlist.l.ptr == NULL)
444			errx(1, "malloc failed");
445		nselectors = 1;
446		uidlist.count = uidlist.maxcount = 1;
447		*uidlist.l.uids = getuid();
448	}
449
450	/*
451	 * scan requested variables, noting what structures are needed,
452	 * and adjusting header widths as appropriate.
453	 */
454	scanvars();
455
456	/*
457	 * Get process list.  If the user requested just one selector-
458	 * option, then kvm_getprocs can be asked to return just those
459	 * processes.  Otherwise, have it return all processes, and
460	 * then this routine will search that full list and select the
461	 * processes which match any of the user's selector-options.
462	 */
463	what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
464	flag = 0;
465	if (nselectors == 1) {
466		if (gidlist.count == 1) {
467			what = KERN_PROC_RGID | showthreads;
468			flag = *gidlist.l.gids;
469			nselectors = 0;
470		} else if (pgrplist.count == 1) {
471			what = KERN_PROC_PGRP | showthreads;
472			flag = *pgrplist.l.pids;
473			nselectors = 0;
474		} else if (pidlist.count == 1) {
475			what = KERN_PROC_PID | showthreads;
476			flag = *pidlist.l.pids;
477			nselectors = 0;
478		} else if (ruidlist.count == 1) {
479			what = KERN_PROC_RUID | showthreads;
480			flag = *ruidlist.l.uids;
481			nselectors = 0;
482		} else if (sesslist.count == 1) {
483			what = KERN_PROC_SESSION | showthreads;
484			flag = *sesslist.l.pids;
485			nselectors = 0;
486		} else if (ttylist.count == 1) {
487			what = KERN_PROC_TTY | showthreads;
488			flag = *ttylist.l.ttys;
489			nselectors = 0;
490		} else if (uidlist.count == 1) {
491			what = KERN_PROC_UID | showthreads;
492			flag = *uidlist.l.uids;
493			nselectors = 0;
494		} else if (all) {
495			/* No need for this routine to select processes. */
496			nselectors = 0;
497		}
498	}
499
500	/*
501	 * select procs
502	 */
503	nentries = -1;
504	kp = kvm_getprocs(kd, what, flag, &nentries);
505	if ((kp == NULL && nentries > 0) || (kp != NULL && nentries < 0))
506		errx(1, "%s", kvm_geterr(kd));
507	nkept = 0;
508	if (nentries > 0) {
509		if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
510			errx(1, "malloc failed");
511		for (i = nentries; --i >= 0; ++kp) {
512			/*
513			 * If the user specified multiple selection-criteria,
514			 * then keep any process matched by the inclusive OR
515			 * of all the selection-criteria given.
516			 */
517			if (pidlist.count > 0) {
518				for (elem = 0; elem < pidlist.count; elem++)
519					if (kp->ki_pid == pidlist.l.pids[elem])
520						goto keepit;
521			}
522			/*
523			 * Note that we had to process pidlist before
524			 * filtering out processes which do not have
525			 * a controlling terminal.
526			 */
527			if (xkeep == 0) {
528				if ((kp->ki_tdev == NODEV ||
529				    (kp->ki_flag & P_CONTROLT) == 0))
530					continue;
531			}
532			if (nselectors == 0)
533				goto keepit;
534			if (gidlist.count > 0) {
535				for (elem = 0; elem < gidlist.count; elem++)
536					if (kp->ki_rgid == gidlist.l.gids[elem])
537						goto keepit;
538			}
539			if (pgrplist.count > 0) {
540				for (elem = 0; elem < pgrplist.count; elem++)
541					if (kp->ki_pgid ==
542					    pgrplist.l.pids[elem])
543						goto keepit;
544			}
545			if (ruidlist.count > 0) {
546				for (elem = 0; elem < ruidlist.count; elem++)
547					if (kp->ki_ruid ==
548					    ruidlist.l.uids[elem])
549						goto keepit;
550			}
551			if (sesslist.count > 0) {
552				for (elem = 0; elem < sesslist.count; elem++)
553					if (kp->ki_sid == sesslist.l.pids[elem])
554						goto keepit;
555			}
556			if (ttylist.count > 0) {
557				for (elem = 0; elem < ttylist.count; elem++)
558					if (kp->ki_tdev == ttylist.l.ttys[elem])
559						goto keepit;
560			}
561			if (uidlist.count > 0) {
562				for (elem = 0; elem < uidlist.count; elem++)
563					if (kp->ki_uid == uidlist.l.uids[elem])
564						goto keepit;
565			}
566			/*
567			 * This process did not match any of the user's
568			 * selector-options, so skip the process.
569			 */
570			continue;
571
572		keepit:
573			next_KINFO = &kinfo[nkept];
574			next_KINFO->ki_p = kp;
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;
579			if (needuser)
580				saveuser(next_KINFO);
581			dynsizevars(next_KINFO);
582			nkept++;
583		}
584	}
585
586	sizevars();
587
588	/*
589	 * print header
590	 */
591	printheader();
592	if (nkept == 0)
593		exit(1);
594
595	/*
596	 * sort proc list
597	 */
598	qsort(kinfo, nkept, sizeof(KINFO), pscomp);
599	/*
600	 * For each process, call each variable output function.
601	 */
602	for (i = lineno = 0; i < nkept; i++) {
603		STAILQ_FOREACH(vent, &varlist, next_ve) {
604			(vent->var->oproc)(&kinfo[i], vent);
605			if (STAILQ_NEXT(vent, next_ve) != NULL)
606				(void)putchar(' ');
607		}
608		(void)putchar('\n');
609		if (prtheader && lineno++ == prtheader - 4) {
610			(void)putchar('\n');
611			printheader();
612			lineno = 0;
613		}
614	}
615	free_list(&gidlist);
616	free_list(&pidlist);
617	free_list(&pgrplist);
618	free_list(&ruidlist);
619	free_list(&sesslist);
620	free_list(&ttylist);
621	free_list(&uidlist);
622
623	exit(eval);
624}
625
626static int
627addelem_gid(struct listinfo *inf, const char *elem)
628{
629	struct group *grp;
630	const char *nameorID;
631	char *endp;
632	u_long bigtemp;
633
634	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
635		if (*elem == '\0')
636			warnx("Invalid (zero-length) %s name", inf->lname);
637		else
638			warnx("%s name too long: %s", inf->lname, elem);
639		optfatal = 1;
640		return (0);		/* Do not add this value. */
641	}
642
643	/*
644	 * SUSv3 states that `ps -G grouplist' should match "real-group
645	 * ID numbers", and does not mention group-names.  I do want to
646	 * also support group-names, so this tries for a group-id first,
647	 * and only tries for a name if that doesn't work.  This is the
648	 * opposite order of what is done in addelem_uid(), but in
649	 * practice the order would only matter for group-names which
650	 * are all-numeric.
651	 */
652	grp = NULL;
653	nameorID = "named";
654	errno = 0;
655	bigtemp = strtoul(elem, &endp, 10);
656	if (errno == 0 && *endp == '\0' && bigtemp <= GID_MAX) {
657		nameorID = "name or ID matches";
658		grp = getgrgid((gid_t)bigtemp);
659	}
660	if (grp == NULL)
661		grp = getgrnam(elem);
662	if (grp == NULL) {
663		warnx("No %s %s '%s'", inf->lname, nameorID, elem);
664		optfatal = 1;
665		return (0);
666	}
667	if (inf->count >= inf->maxcount)
668		expand_list(inf);
669	inf->l.gids[(inf->count)++] = grp->gr_gid;
670	return (1);
671}
672
673#define	BSD_PID_MAX	99999		/* Copy of PID_MAX from sys/proc.h. */
674static int
675addelem_pid(struct listinfo *inf, const char *elem)
676{
677	char *endp;
678	long tempid;
679
680	if (*elem == '\0') {
681		warnx("Invalid (zero-length) process id");
682		optfatal = 1;
683		return (0);		/* Do not add this value. */
684	}
685
686	errno = 0;
687	tempid = strtol(elem, &endp, 10);
688	if (*endp != '\0' || tempid < 0 || elem == endp) {
689		warnx("Invalid %s: %s", inf->lname, elem);
690		errno = ERANGE;
691	} else if (errno != 0 || tempid > BSD_PID_MAX) {
692		warnx("%s too large: %s", inf->lname, elem);
693		errno = ERANGE;
694	}
695	if (errno == ERANGE) {
696		optfatal = 1;
697		return (0);
698	}
699	if (inf->count >= inf->maxcount)
700		expand_list(inf);
701	inf->l.pids[(inf->count)++] = tempid;
702	return (1);
703}
704#undef	BSD_PID_MAX
705
706/*-
707 * The user can specify a device via one of three formats:
708 *     1) fully qualified, e.g.:     /dev/ttyp0 /dev/console
709 *     2) missing "/dev", e.g.:      ttyp0      console
710 *     3) two-letters, e.g.:         p0         co
711 *        (matching letters that would be seen in the "TT" column)
712 */
713static int
714addelem_tty(struct listinfo *inf, const char *elem)
715{
716	const char *ttypath;
717	struct stat sb;
718	char pathbuf[PATH_MAX], pathbuf2[PATH_MAX];
719
720	ttypath = NULL;
721	pathbuf2[0] = '\0';
722	switch (*elem) {
723	case '/':
724		ttypath = elem;
725		break;
726	case 'c':
727		if (strcmp(elem, "co") == 0) {
728			ttypath = _PATH_CONSOLE;
729			break;
730		}
731		/* FALLTHROUGH */
732	default:
733		strlcpy(pathbuf, _PATH_DEV, sizeof(pathbuf));
734		strlcat(pathbuf, elem, sizeof(pathbuf));
735		ttypath = pathbuf;
736		if (strncmp(pathbuf, _PATH_TTY, strlen(_PATH_TTY)) == 0)
737			break;
738		if (strcmp(pathbuf, _PATH_CONSOLE) == 0)
739			break;
740		/* Check to see if /dev/tty${elem} exists */
741		strlcpy(pathbuf2, _PATH_TTY, sizeof(pathbuf2));
742		strlcat(pathbuf2, elem, sizeof(pathbuf2));
743		if (stat(pathbuf2, &sb) == 0 && S_ISCHR(sb.st_mode)) {
744			/* No need to repeat stat() && S_ISCHR() checks */
745			ttypath = NULL;
746			break;
747		}
748		break;
749	}
750	if (ttypath) {
751		if (stat(ttypath, &sb) == -1) {
752			if (pathbuf2[0] != '\0')
753				warn("%s and %s", pathbuf2, ttypath);
754			else
755				warn("%s", ttypath);
756			optfatal = 1;
757			return (0);
758		}
759		if (!S_ISCHR(sb.st_mode)) {
760			if (pathbuf2[0] != '\0')
761				warnx("%s and %s: Not a terminal", pathbuf2,
762				    ttypath);
763			else
764				warnx("%s: Not a terminal", ttypath);
765			optfatal = 1;
766			return (0);
767		}
768	}
769	if (inf->count >= inf->maxcount)
770		expand_list(inf);
771	inf->l.ttys[(inf->count)++] = sb.st_rdev;
772	return (1);
773}
774
775static int
776addelem_uid(struct listinfo *inf, const char *elem)
777{
778	struct passwd *pwd;
779	char *endp;
780	u_long bigtemp;
781
782	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
783		if (*elem == '\0')
784			warnx("Invalid (zero-length) %s name", inf->lname);
785		else
786			warnx("%s name too long: %s", inf->lname, elem);
787		optfatal = 1;
788		return (0);		/* Do not add this value. */
789	}
790
791	pwd = getpwnam(elem);
792	if (pwd == NULL) {
793		errno = 0;
794		bigtemp = strtoul(elem, &endp, 10);
795		if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
796			warnx("No %s named '%s'", inf->lname, elem);
797		else {
798			/* The string is all digits, so it might be a userID. */
799			pwd = getpwuid((uid_t)bigtemp);
800			if (pwd == NULL)
801				warnx("No %s name or ID matches '%s'",
802				    inf->lname, elem);
803		}
804	}
805	if (pwd == NULL) {
806		/*
807		 * These used to be treated as minor warnings (and the
808		 * option was simply ignored), but now they are fatal
809		 * errors (and the command will be aborted).
810		 */
811		optfatal = 1;
812		return (0);
813	}
814	if (inf->count >= inf->maxcount)
815		expand_list(inf);
816	inf->l.uids[(inf->count)++] = pwd->pw_uid;
817	return (1);
818}
819
820static void
821add_list(struct listinfo *inf, const char *argp)
822{
823	const char *savep;
824	char *cp, *endp;
825	int toolong;
826	char elemcopy[PATH_MAX];
827
828	if (*argp == 0)
829		inf->addelem(inf, elemcopy);
830	while (*argp != '\0') {
831		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
832			argp++;
833		savep = argp;
834		toolong = 0;
835		cp = elemcopy;
836		if (strchr(T_SEP, *argp) == NULL) {
837			endp = elemcopy + sizeof(elemcopy) - 1;
838			while (*argp != '\0' && cp <= endp &&
839			    strchr(W_SEP T_SEP, *argp) == NULL)
840				*cp++ = *argp++;
841			if (cp > endp)
842				toolong = 1;
843		}
844		if (!toolong) {
845			*cp = '\0';
846			/*
847			 * Add this single element to the given list.
848			 */
849			inf->addelem(inf, elemcopy);
850		} else {
851			/*
852			 * The string is too long to copy.  Find the end
853			 * of the string to print out the warning message.
854			 */
855			while (*argp != '\0' && strchr(W_SEP T_SEP,
856			    *argp) == NULL)
857				argp++;
858			warnx("Value too long: %.*s", (int)(argp - savep),
859			    savep);
860			optfatal = 1;
861		}
862		/*
863		 * Skip over any number of trailing whitespace characters,
864		 * but only one (at most) trailing element-terminating
865		 * character.
866		 */
867		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
868			argp++;
869		if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
870			argp++;
871			/* Catch case where string ended with a comma. */
872			if (*argp == '\0')
873				inf->addelem(inf, argp);
874		}
875	}
876}
877
878static void *
879expand_list(struct listinfo *inf)
880{
881	void *newlist;
882	int newmax;
883
884	newmax = (inf->maxcount + 1) << 1;
885	newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
886	if (newlist == NULL) {
887		free(inf->l.ptr);
888		errx(1, "realloc to %d %ss failed", newmax, inf->lname);
889	}
890	inf->maxcount = newmax;
891	inf->l.ptr = newlist;
892
893	return (newlist);
894}
895
896static void
897free_list(struct listinfo *inf)
898{
899
900	inf->count = inf->elemsize = inf->maxcount = 0;
901	if (inf->l.ptr != NULL)
902		free(inf->l.ptr);
903	inf->addelem = NULL;
904	inf->lname = NULL;
905	inf->l.ptr = NULL;
906}
907
908static void
909init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
910    const char *lname)
911{
912
913	inf->count = inf->maxcount = 0;
914	inf->elemsize = elemsize;
915	inf->addelem = artn;
916	inf->lname = lname;
917	inf->l.ptr = NULL;
918}
919
920VARENT *
921find_varentry(VAR *v)
922{
923	struct varent *vent;
924
925	STAILQ_FOREACH(vent, &varlist, next_ve) {
926		if (strcmp(vent->var->name, v->name) == 0)
927			return vent;
928	}
929	return NULL;
930}
931
932static void
933scanvars(void)
934{
935	struct varent *vent;
936	VAR *v;
937
938	STAILQ_FOREACH(vent, &varlist, next_ve) {
939		v = vent->var;
940		if (v->flag & DSIZ) {
941			v->dwidth = v->width;
942			v->width = 0;
943		}
944		if (v->flag & USER)
945			needuser = 1;
946		if (v->flag & COMM)
947			needcomm = 1;
948	}
949}
950
951static void
952dynsizevars(KINFO *ki)
953{
954	struct varent *vent;
955	VAR *v;
956	int i;
957
958	STAILQ_FOREACH(vent, &varlist, next_ve) {
959		v = vent->var;
960		if (!(v->flag & DSIZ))
961			continue;
962		i = (v->sproc)( ki);
963		if (v->width < i)
964			v->width = i;
965		if (v->width > v->dwidth)
966			v->width = v->dwidth;
967	}
968}
969
970static void
971sizevars(void)
972{
973	struct varent *vent;
974	VAR *v;
975	int i;
976
977	STAILQ_FOREACH(vent, &varlist, next_ve) {
978		v = vent->var;
979		i = strlen(vent->header);
980		if (v->width < i)
981			v->width = i;
982		totwidth += v->width + 1;	/* +1 for space */
983	}
984	totwidth--;
985}
986
987static const char *
988fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
989    char *comm, int maxlen)
990{
991	const char *s;
992
993	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
994	return (s);
995}
996
997#define UREADOK(ki)	(forceuread || (ki->ki_p->ki_sflag & PS_INMEM))
998
999static void
1000saveuser(KINFO *ki)
1001{
1002
1003	if (ki->ki_p->ki_sflag & PS_INMEM) {
1004		/*
1005		 * The u-area might be swapped out, and we can't get
1006		 * at it because we have a crashdump and no swap.
1007		 * If it's here fill in these fields, otherwise, just
1008		 * leave them 0.
1009		 */
1010		ki->ki_valid = 1;
1011	} else
1012		ki->ki_valid = 0;
1013	/*
1014	 * save arguments if needed
1015	 */
1016	if (needcomm) {
1017		if (ki->ki_p->ki_stat == SZOMB)
1018			ki->ki_args = strdup("<defunct>");
1019		else if (UREADOK(ki) || (ki->ki_p->ki_args != NULL))
1020			ki->ki_args = strdup(fmt(kvm_getargv, ki,
1021			    ki->ki_p->ki_comm, MAXCOMLEN));
1022		else
1023			asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
1024		if (ki->ki_args == NULL)
1025			errx(1, "malloc failed");
1026	} else {
1027		ki->ki_args = NULL;
1028	}
1029	if (needenv) {
1030		if (UREADOK(ki))
1031			ki->ki_env = strdup(fmt(kvm_getenvv, ki,
1032			    (char *)NULL, 0));
1033		else
1034			ki->ki_env = strdup("()");
1035		if (ki->ki_env == NULL)
1036			errx(1, "malloc failed");
1037	} else {
1038		ki->ki_env = NULL;
1039	}
1040}
1041
1042/* A macro used to improve the readability of pscomp(). */
1043#define	DIFF_RETURN(a, b, field) do {	\
1044	if ((a)->field != (b)->field)	\
1045		return (((a)->field < (b)->field) ? -1 : 1); 	\
1046} while (0)
1047
1048static int
1049pscomp(const void *a, const void *b)
1050{
1051	const KINFO *ka, *kb;
1052
1053	ka = a;
1054	kb = b;
1055	/* SORTCPU and SORTMEM are sorted in descending order. */
1056	if (sortby == SORTCPU)
1057		DIFF_RETURN(kb, ka, ki_pcpu);
1058	if (sortby == SORTMEM)
1059		DIFF_RETURN(kb, ka, ki_memsize);
1060	/*
1061	 * TTY's are sorted in ascending order, except that all NODEV
1062	 * processes come before all processes with a device.
1063	 */
1064	if (ka->ki_p->ki_tdev != kb->ki_p->ki_tdev) {
1065		if (ka->ki_p->ki_tdev == NODEV)
1066			return (-1);
1067		if (kb->ki_p->ki_tdev == NODEV)
1068			return (1);
1069		DIFF_RETURN(ka, kb, ki_p->ki_tdev);
1070	}
1071
1072	/* PID's and TID's (threads) are sorted in ascending order. */
1073	DIFF_RETURN(ka, kb, ki_p->ki_pid);
1074	DIFF_RETURN(ka, kb, ki_p->ki_tid);
1075	return (0);
1076}
1077#undef DIFF_RETURN
1078
1079/*
1080 * ICK (all for getopt), would rather hide the ugliness
1081 * here than taint the main code.
1082 *
1083 *  ps foo -> ps -foo
1084 *  ps 34 -> ps -p34
1085 *
1086 * The old convention that 't' with no trailing tty arg means the users
1087 * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
1088 * feature is available with the option 'T', which takes no argument.
1089 */
1090static char *
1091kludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
1092{
1093	size_t len;
1094	char *argp, *cp, *newopts, *ns, *optp, *pidp;
1095
1096	/*
1097	 * See if the original value includes any option which takes an
1098	 * argument (and will thus use up the remainder of the string).
1099	 */
1100	argp = NULL;
1101	if (optlist != NULL) {
1102		for (cp = origval; *cp != '\0'; cp++) {
1103			optp = strchr(optlist, *cp);
1104			if ((optp != NULL) && *(optp + 1) == ':') {
1105				argp = cp;
1106				break;
1107			}
1108		}
1109	}
1110	if (argp != NULL && *origval == '-')
1111		return (origval);
1112
1113	/*
1114	 * if last letter is a 't' flag with no argument (in the context
1115	 * of the oldps options -- option string NOT starting with a '-' --
1116	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1117	 *
1118	 * However, if a flag accepting a string argument is found earlier
1119	 * in the option string (including a possible `t' flag), then the
1120	 * remainder of the string must be the argument to that flag; so
1121	 * do not modify that argument.  Note that a trailing `t' would
1122	 * cause argp to be set, if argp was not already set by some
1123	 * earlier option.
1124	 */
1125	len = strlen(origval);
1126	cp = origval + len - 1;
1127	pidp = NULL;
1128	if (*cp == 't' && *origval != '-' && cp == argp) {
1129		if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
1130			*cp = 'T';
1131	} else if (argp == NULL) {
1132		/*
1133		 * The original value did not include any option which takes
1134		 * an argument (and that would include `p' and `t'), so check
1135		 * the value for trailing number, or comma-separated list of
1136		 * numbers, which we will treat as a pid request.
1137		 */
1138		if (isdigitch(*cp)) {
1139			while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1140				--cp;
1141			pidp = cp + 1;
1142		}
1143	}
1144
1145	/*
1146	 * If nothing needs to be added to the string, then return
1147	 * the "original" (although possibly modified) value.
1148	 */
1149	if (*origval == '-' && pidp == NULL)
1150		return (origval);
1151
1152	/*
1153	 * Create a copy of the string to add '-' and/or 'p' to the
1154	 * original value.
1155	 */
1156	if ((newopts = ns = malloc(len + 3)) == NULL)
1157		errx(1, "malloc failed");
1158
1159	if (*origval != '-')
1160		*ns++ = '-';	/* add option flag */
1161
1162	if (pidp == NULL)
1163		strcpy(ns, origval);
1164	else {
1165		/*
1166		 * Copy everything before the pid string, add the `p',
1167		 * and then copy the pid string.
1168		 */
1169		len = pidp - origval;
1170		memcpy(ns, origval, len);
1171		ns += len;
1172		*ns++ = 'p';
1173		strcpy(ns, pidp);
1174	}
1175
1176	return (newopts);
1177}
1178
1179static int
1180check_procfs(void)
1181{
1182	struct statfs mnt;
1183
1184	if (statfs("/proc", &mnt) < 0)
1185		return (0);
1186	if (strcmp(mnt.f_fstypename, "procfs") != 0)
1187		return (0);
1188	return (1);
1189}
1190
1191static void
1192usage(void)
1193{
1194#define	SINGLE_OPTS	"[-aCc" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
1195
1196	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
1197	    "usage: ps " SINGLE_OPTS " [-G gid[,gid]] [-O|o fmt]",
1198	    "          [-p pid[,pid]] [-t tty[,tty]] [-U user[,user]]",
1199	    "          [-M core] [-N system]",
1200	    "       ps [-L]");
1201	exit(1);
1202}
1203