ps.c revision 130999
138928Sjdp/*-
238928Sjdp * Copyright (c) 1990, 1993, 1994
338928Sjdp *	The Regents of the University of California.  All rights reserved.
438928Sjdp *
538928Sjdp * Redistribution and use in source and binary forms, with or without
638928Sjdp * modification, are permitted provided that the following conditions
738928Sjdp * are met:
838928Sjdp * 1. Redistributions of source code must retain the above copyright
938928Sjdp *    notice, this list of conditions and the following disclaimer.
1038928Sjdp * 2. Redistributions in binary form must reproduce the above copyright
1138928Sjdp *    notice, this list of conditions and the following disclaimer in the
1238928Sjdp *    documentation and/or other materials provided with the distribution.
1338928Sjdp * 4. Neither the name of the University nor the names of its contributors
1438928Sjdp *    may be used to endorse or promote products derived from this software
1538928Sjdp *    without specific prior written permission.
1638928Sjdp *
1738928Sjdp * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
1838928Sjdp * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1938928Sjdp * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2038928Sjdp * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2138928Sjdp * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2238928Sjdp * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2338928Sjdp * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2438928Sjdp * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2538928Sjdp * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2638928Sjdp * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2738928Sjdp * SUCH DAMAGE.
2838928Sjdp * ------+---------+---------+-------- + --------+---------+---------+---------*
2938928Sjdp * Copyright (c) 2004  - Garance Alistair Drosehn <gad@FreeBSD.org>.
3038928Sjdp * All rights reserved.
3138928Sjdp *
3238928Sjdp * Significant modifications made to bring `ps' options somewhat closer
3338928Sjdp * to the standard for `ps' as described in SingleUnixSpec-v3.
3438928Sjdp * ------+---------+---------+-------- + --------+---------+---------+---------*
3538928Sjdp */
3638928Sjdp
3738928Sjdp#ifndef lint
3838928Sjdpstatic const char copyright[] =
3938928Sjdp"@(#) Copyright (c) 1990, 1993, 1994\n\
4038928Sjdp	The Regents of the University of California.  All rights reserved.\n";
4138928Sjdp#endif /* not lint */
4238928Sjdp
4338928Sjdp#if 0
4438928Sjdp#ifndef lint
4538928Sjdpstatic char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
4638928Sjdp#endif /* not lint */
4738928Sjdp#endif
4838928Sjdp
4938928Sjdp#include <sys/cdefs.h>
5038928Sjdp__FBSDID("$FreeBSD: head/bin/ps/ps.c 130999 2004-06-23 23:48:09Z gad $");
5138928Sjdp
5238928Sjdp#include <sys/param.h>
5338928Sjdp#include <sys/proc.h>
5438928Sjdp#include <sys/user.h>
5538928Sjdp#include <sys/stat.h>
5638928Sjdp#include <sys/ioctl.h>
5738928Sjdp#include <sys/sysctl.h>
5838928Sjdp
5938928Sjdp#include <ctype.h>
6038928Sjdp#include <err.h>
6138928Sjdp#include <errno.h>
6238928Sjdp#include <fcntl.h>
6338928Sjdp#include <grp.h>
6438928Sjdp#include <kvm.h>
6538928Sjdp#include <limits.h>
6638928Sjdp#include <locale.h>
6738928Sjdp#include <paths.h>
6838928Sjdp#include <pwd.h>
6938928Sjdp#include <stdio.h>
7038928Sjdp#include <stdlib.h>
7138928Sjdp#include <string.h>
7238928Sjdp#include <unistd.h>
7338928Sjdp
7438928Sjdp#include "ps.h"
7538928Sjdp
7638928Sjdp#define	W_SEP	" \t"		/* "Whitespace" list separators */
7738928Sjdp#define	T_SEP	","		/* "Terminate-element" list separators */
7838928Sjdp
7938928Sjdp#ifdef LAZY_PS
8038928Sjdp#define	DEF_UREAD	0
8138928Sjdp#define	OPT_LAZY_f	"f"
8238928Sjdp#else
8338928Sjdp#define	DEF_UREAD	1	/* Always do the more-expensive read. */
8438928Sjdp#define	OPT_LAZY_f		/* I.e., the `-f' option is not added. */
8538928Sjdp#endif
8638928Sjdp
8738928Sjdp/*
8838928Sjdp * isdigit takes an `int', but expects values in the range of unsigned char.
8938928Sjdp * This wrapper ensures that values from a 'char' end up in the correct range.
9038928Sjdp */
9138928Sjdp#define	isdigitch(Anychar) isdigit((u_char)(Anychar))
9238928Sjdp
9338928Sjdpint	 cflag;			/* -c */
9438928Sjdpint	 eval;			/* Exit value */
9538928Sjdptime_t	 now;			/* Current time(3) value */
9638928Sjdpint	 rawcpu;		/* -C */
9738928Sjdpint	 sumrusage;		/* -S */
9838928Sjdpint	 termwidth;		/* Width of the screen (0 == infinity). */
9938928Sjdpint	 totwidth;		/* Calculated-width of requested variables. */
10038928Sjdp
10138928Sjdpstruct velisthead varlist = STAILQ_HEAD_INITIALIZER(varlist);
10238928Sjdp
10338928Sjdpstatic int	 forceuread = DEF_UREAD; /* Do extra work to get u-area. */
10438928Sjdpstatic kvm_t	*kd;
10538928Sjdpstatic KINFO	*kinfo;
10638928Sjdpstatic int	 needcomm;	/* -o "command" */
107static int	 needenv;	/* -e */
108static int	 needuser;	/* -o "user" */
109static int	 optfatal;	/* Fatal error parsing some list-option. */
110
111static enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
112
113struct listinfo;
114typedef	int	addelem_rtn(struct listinfo *_inf, const char *_elem);
115
116struct listinfo {
117	int		 count;
118	int		 maxcount;
119	int		 elemsize;
120	addelem_rtn	*addelem;
121	const char	*lname;
122	union {
123		gid_t	*gids;
124		pid_t	*pids;
125		dev_t	*ttys;
126		uid_t	*uids;
127		void	*ptr;
128	} l;
129};
130
131static int	 addelem_gid(struct listinfo *, const char *);
132static int	 addelem_pid(struct listinfo *, const char *);
133static int	 addelem_tty(struct listinfo *, const char *);
134static int	 addelem_uid(struct listinfo *, const char *);
135static void	 add_list(struct listinfo *, const char *);
136static void	 dynsizevars(KINFO *);
137static void	*expand_list(struct listinfo *);
138static const char *
139		 fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
140		    KINFO *, char *, int);
141static void	 free_list(struct listinfo *);
142static void	 init_list(struct listinfo *, addelem_rtn, int, const char *);
143static char	*kludge_oldps_options(const char *, char *, const char *);
144static int	 pscomp(const void *, const void *);
145static void	 saveuser(KINFO *);
146static void	 scanvars(void);
147static void	 sizevars(void);
148static void	 usage(void);
149
150static char dfmt[] = "pid,tt,state,time,command";
151static char jfmt[] = "user,pid,ppid,pgid,sid,jobc,state,tt,time,command";
152static char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
153			"tt,time,command";
154static char   o1[] = "pid";
155static char   o2[] = "tt,state,time,command";
156static char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
157static char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
158			"%cpu,%mem,command";
159static char Zfmt[] = "label";
160
161#define	PS_ARGS	"AaCce" OPT_LAZY_f "G:gHhjLlM:mN:O:o:p:rSTt:U:uvwXxZ"
162
163int
164main(int argc, char *argv[])
165{
166	struct listinfo gidlist, pgrplist, pidlist;
167	struct listinfo ruidlist, sesslist, ttylist, uidlist;
168	struct kinfo_proc *kp;
169	KINFO *next_KINFO;
170	struct varent *vent;
171	struct winsize ws;
172	const char *nlistf, *memf;
173	char *cols;
174	int all, ch, dropgid, elem, flag, _fmt, i, lineno;
175	int nentries, nkept, nselectors;
176	int prtheader, showthreads, wflag, what, xkeep, xkeep_implied;
177	char errbuf[_POSIX2_LINE_MAX];
178
179	(void) setlocale(LC_ALL, "");
180	time(&now);			/* Used by routines in print.c. */
181
182	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
183		termwidth = atoi(cols);
184	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
185	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
186	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
187	     ws.ws_col == 0)
188		termwidth = 79;
189	else
190		termwidth = ws.ws_col - 1;
191
192	/*
193	 * Hide a number of option-processing kludges in a separate routine,
194	 * to support some historical BSD behaviors, such as `ps axu'.
195	 */
196	if (argc > 1)
197		argv[1] = kludge_oldps_options(PS_ARGS, argv[1], argv[2]);
198
199	all = dropgid = _fmt = nselectors = optfatal = 0;
200	prtheader = showthreads = wflag = xkeep_implied = 0;
201	xkeep = -1;			/* Neither -x nor -X. */
202	init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
203	init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
204	init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
205	init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
206	init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
207	init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
208	init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
209	memf = nlistf = _PATH_DEVNULL;
210	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
211		switch ((char)ch) {
212		case 'A':
213			/*
214			 * Exactly the same as `-ax'.   This has been
215			 * added for compatability with SUSv3, but for
216			 * now it will not be described in the man page.
217			 */
218			nselectors++;
219			all = xkeep = 1;
220			break;
221		case 'a':
222			nselectors++;
223			all = 1;
224			break;
225		case 'C':
226			rawcpu = 1;
227			break;
228		case 'c':
229			cflag = 1;
230			break;
231		case 'e':			/* XXX set ufmt */
232			needenv = 1;
233			break;
234#ifdef LAZY_PS
235		case 'f':
236			if (getuid() == 0 || getgid() == 0)
237				forceuread = 1;
238			break;
239#endif
240		case 'G':
241			add_list(&gidlist, optarg);
242			xkeep_implied = 1;
243			nselectors++;
244			break;
245		case 'g':
246#if 0
247			/*-
248			 * XXX - This SUSv3 behavior is still under debate
249			 *	since it conflicts with the (undocumented)
250			 *	`-g' option.  So we skip it for now.
251			 */
252			add_list(&pgrplist, optarg);
253			xkeep_implied = 1;
254			nselectors++;
255			break;
256#else
257			/* The historical BSD-ish (from SunOS) behavior. */
258			break;			/* no-op */
259#endif
260		case 'H':
261			showthreads = KERN_PROC_INC_THREAD;
262			break;
263		case 'h':
264			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
265			break;
266		case 'j':
267			parsefmt(jfmt, 0);
268			_fmt = 1;
269			jfmt[0] = '\0';
270			break;
271		case 'L':
272			showkey();
273			exit(0);
274		case 'l':
275			parsefmt(lfmt, 0);
276			_fmt = 1;
277			lfmt[0] = '\0';
278			break;
279		case 'M':
280			memf = optarg;
281			dropgid = 1;
282			break;
283		case 'm':
284			sortby = SORTMEM;
285			break;
286		case 'N':
287			nlistf = optarg;
288			dropgid = 1;
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 there arguments after processing all the options, attempt
408	 * to treat them as a list of process ids.
409	 */
410	while (*argv) {
411		if (!isdigitch(**argv))
412			break;
413		add_list(&pidlist, *argv);
414		argv++;
415	}
416	if (*argv) {
417		fprintf(stderr, "%s: illegal argument: %s\n",
418		    getprogname(), *argv);
419		usage();
420	}
421	if (optfatal)
422		exit(1);		/* Error messages already printed. */
423	if (xkeep < 0)			/* Neither -X nor -x was specified. */
424		xkeep = xkeep_implied;
425
426
427	/*
428	 * Discard setgid privileges if not the running kernel so that bad
429	 * guys can't print interesting stuff from kernel memory.
430	 */
431	if (dropgid)
432		setgid(getgid());
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
706static int
707addelem_tty(struct listinfo *inf, const char *elem)
708{
709	const char *ttypath;
710	struct stat sb;
711	char pathbuf[PATH_MAX];
712
713	if (strcmp(elem, "co") == 0)
714		ttypath = strdup(_PATH_CONSOLE);
715	else if (*elem == '/')
716		ttypath = elem;
717	else {
718		strlcpy(pathbuf, _PATH_TTY, sizeof(pathbuf));
719		strlcat(pathbuf, elem, sizeof(pathbuf));
720		ttypath = pathbuf;
721	}
722
723	if (stat(ttypath, &sb) == -1) {
724		warn("%s", ttypath);
725		optfatal = 1;
726		return (0);
727	}
728	if (!S_ISCHR(sb.st_mode)) {
729		warn("%s: Not a terminal", ttypath);
730		optfatal = 1;
731		return (0);
732	}
733	if (inf->count >= inf->maxcount)
734		expand_list(inf);
735	inf->l.ttys[(inf->count)++] = sb.st_rdev;
736	return (1);
737}
738
739static int
740addelem_uid(struct listinfo *inf, const char *elem)
741{
742	struct passwd *pwd;
743	char *endp;
744	u_long bigtemp;
745
746	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
747		if (*elem == '\0')
748			warnx("Invalid (zero-length) %s name", inf->lname);
749		else
750			warnx("%s name too long: %s", inf->lname, elem);
751		optfatal = 1;
752		return (0);		/* Do not add this value. */
753	}
754
755	pwd = getpwnam(elem);
756	if (pwd == NULL) {
757		errno = 0;
758		bigtemp = strtoul(elem, &endp, 10);
759		if (errno != 0 || *endp != '\0' || bigtemp > UID_MAX)
760			warnx("No %s named '%s'", inf->lname, elem);
761		else {
762			/* The string is all digits, so it might be a userID. */
763			pwd = getpwuid((uid_t)bigtemp);
764			if (pwd == NULL)
765				warnx("No %s name or ID matches '%s'",
766				    inf->lname, elem);
767		}
768	}
769	if (pwd == NULL) {
770		/*
771		 * These used to be treated as minor warnings (and the
772		 * option was simply ignored), but now they are fatal
773		 * errors (and the command will be aborted).
774		 */
775		optfatal = 1;
776		return (0);
777	}
778	if (inf->count >= inf->maxcount)
779		expand_list(inf);
780	inf->l.uids[(inf->count)++] = pwd->pw_uid;
781	return (1);
782}
783
784static void
785add_list(struct listinfo *inf, const char *argp)
786{
787	const char *savep;
788	char *cp, *endp;
789	int toolong;
790	char elemcopy[PATH_MAX];
791
792	if (*argp == 0)
793		inf->addelem(inf, elemcopy);
794	while (*argp != '\0') {
795		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
796			argp++;
797		savep = argp;
798		toolong = 0;
799		cp = elemcopy;
800		if (strchr(T_SEP, *argp) == NULL) {
801			endp = elemcopy + sizeof(elemcopy) - 1;
802			while (*argp != '\0' && cp <= endp &&
803			    strchr(W_SEP T_SEP, *argp) == NULL)
804				*cp++ = *argp++;
805			if (cp > endp)
806				toolong = 1;
807		}
808		if (!toolong) {
809			*cp = '\0';
810			/*
811			 * Add this single element to the given list.
812			 */
813			inf->addelem(inf, elemcopy);
814		} else {
815			/*
816			 * The string is too long to copy.  Find the end
817			 * of the string to print out the warning message.
818			 */
819			while (*argp != '\0' && strchr(W_SEP T_SEP,
820			    *argp) == NULL)
821				argp++;
822			warnx("Value too long: %.*s", (int)(argp - savep),
823			    savep);
824			optfatal = 1;
825		}
826		/*
827		 * Skip over any number of trailing whitespace characters,
828		 * but only one (at most) trailing element-terminating
829		 * character.
830		 */
831		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
832			argp++;
833		if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
834			argp++;
835			/* Catch case where string ended with a comma. */
836			if (*argp == '\0')
837				inf->addelem(inf, argp);
838		}
839	}
840}
841
842static void *
843expand_list(struct listinfo *inf)
844{
845	void *newlist;
846	int newmax;
847
848	newmax = (inf->maxcount + 1) << 1;
849	newlist = realloc(inf->l.ptr, newmax * inf->elemsize);
850	if (newlist == NULL) {
851		free(inf->l.ptr);
852		errx(1, "realloc to %d %ss failed", newmax, inf->lname);
853	}
854	inf->maxcount = newmax;
855	inf->l.ptr = newlist;
856
857	return (newlist);
858}
859
860static void
861free_list(struct listinfo *inf)
862{
863
864	inf->count = inf->elemsize = inf->maxcount = 0;
865	if (inf->l.ptr != NULL)
866		free(inf->l.ptr);
867	inf->addelem = NULL;
868	inf->lname = NULL;
869	inf->l.ptr = NULL;
870}
871
872static void
873init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
874    const char *lname)
875{
876
877	inf->count = inf->maxcount = 0;
878	inf->elemsize = elemsize;
879	inf->addelem = artn;
880	inf->lname = lname;
881	inf->l.ptr = NULL;
882}
883
884VARENT *
885find_varentry(VAR *v)
886{
887	struct varent *vent;
888
889	STAILQ_FOREACH(vent, &varlist, next_ve) {
890		if (strcmp(vent->var->name, v->name) == 0)
891			return vent;
892	}
893	return NULL;
894}
895
896static void
897scanvars(void)
898{
899	struct varent *vent;
900	VAR *v;
901
902	STAILQ_FOREACH(vent, &varlist, next_ve) {
903		v = vent->var;
904		if (v->flag & DSIZ) {
905			v->dwidth = v->width;
906			v->width = 0;
907		}
908		if (v->flag & USER)
909			needuser = 1;
910		if (v->flag & COMM)
911			needcomm = 1;
912	}
913}
914
915static void
916dynsizevars(KINFO *ki)
917{
918	struct varent *vent;
919	VAR *v;
920	int i;
921
922	STAILQ_FOREACH(vent, &varlist, next_ve) {
923		v = vent->var;
924		if (!(v->flag & DSIZ))
925			continue;
926		i = (v->sproc)( ki);
927		if (v->width < i)
928			v->width = i;
929		if (v->width > v->dwidth)
930			v->width = v->dwidth;
931	}
932}
933
934static void
935sizevars(void)
936{
937	struct varent *vent;
938	VAR *v;
939	int i;
940
941	STAILQ_FOREACH(vent, &varlist, next_ve) {
942		v = vent->var;
943		i = strlen(vent->header);
944		if (v->width < i)
945			v->width = i;
946		totwidth += v->width + 1;	/* +1 for space */
947	}
948	totwidth--;
949}
950
951static const char *
952fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
953    char *comm, int maxlen)
954{
955	const char *s;
956
957	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
958	return (s);
959}
960
961#define UREADOK(ki)	(forceuread || (ki->ki_p->ki_sflag & PS_INMEM))
962
963static void
964saveuser(KINFO *ki)
965{
966
967	if (ki->ki_p->ki_sflag & PS_INMEM) {
968		/*
969		 * The u-area might be swapped out, and we can't get
970		 * at it because we have a crashdump and no swap.
971		 * If it's here fill in these fields, otherwise, just
972		 * leave them 0.
973		 */
974		ki->ki_valid = 1;
975	} else
976		ki->ki_valid = 0;
977	/*
978	 * save arguments if needed
979	 */
980	if (needcomm) {
981		if (ki->ki_p->ki_stat == SZOMB)
982			ki->ki_args = strdup("<defunct>");
983		else if (UREADOK(ki) || (ki->ki_p->ki_args != NULL))
984			ki->ki_args = strdup(fmt(kvm_getargv, ki,
985			    ki->ki_p->ki_comm, MAXCOMLEN));
986		else
987			asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
988		if (ki->ki_env == NULL)
989			errx(1, "malloc failed");
990	} else {
991		ki->ki_args = NULL;
992	}
993	if (needenv) {
994		if (UREADOK(ki))
995			ki->ki_env = strdup(fmt(kvm_getenvv, ki,
996			    (char *)NULL, 0));
997		else
998			ki->ki_env = strdup("()");
999		if (ki->ki_env == NULL)
1000			errx(1, "malloc failed");
1001	} else {
1002		ki->ki_env = NULL;
1003	}
1004}
1005
1006/* A macro used to improve the readability of pscomp(). */
1007#define	DIFF_RETURN(a, b, field) do {	\
1008	if ((a)->field != (b)->field)	\
1009		return (((a)->field < (b)->field) ? -1 : 1); 	\
1010} while (0)
1011
1012static int
1013pscomp(const void *a, const void *b)
1014{
1015	const KINFO *ka, *kb;
1016
1017	ka = a;
1018	kb = b;
1019	/* SORTCPU and SORTMEM are sorted in descending order. */
1020	if (sortby == SORTCPU)
1021		DIFF_RETURN(kb, ka, ki_pcpu);
1022	if (sortby == SORTMEM)
1023		DIFF_RETURN(kb, ka, ki_memsize);
1024	/*
1025	 * TTY's are sorted in ascending order, except that all NODEV
1026	 * processes come before all processes with a device.
1027	 */
1028	if (ka->ki_p->ki_tdev != kb->ki_p->ki_tdev) {
1029		if (ka->ki_p->ki_tdev == NODEV)
1030			return (-1);
1031		if (kb->ki_p->ki_tdev == NODEV)
1032			return (1);
1033		DIFF_RETURN(ka, kb, ki_p->ki_tdev);
1034	}
1035
1036	/* PID's and TID's (threads) are sorted in ascending order. */
1037	DIFF_RETURN(ka, kb, ki_p->ki_pid);
1038	DIFF_RETURN(ka, kb, ki_p->ki_tid);
1039	return (0);
1040}
1041#undef DIFF_RETURN
1042
1043/*
1044 * ICK (all for getopt), would rather hide the ugliness
1045 * here than taint the main code.
1046 *
1047 *  ps foo -> ps -foo
1048 *  ps 34 -> ps -p34
1049 *
1050 * The old convention that 't' with no trailing tty arg means the users
1051 * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
1052 * feature is available with the option 'T', which takes no argument.
1053 */
1054static char *
1055kludge_oldps_options(const char *optlist, char *origval, const char *nextarg)
1056{
1057	size_t len;
1058	char *argp, *cp, *newopts, *ns, *optp, *pidp;
1059
1060	/*
1061	 * See if the original value includes any option which takes an
1062	 * argument (and will thus use up the remainder of the string).
1063	 */
1064	argp = NULL;
1065	if (optlist != NULL) {
1066		for (cp = origval; *cp != '\0'; cp++) {
1067			optp = strchr(optlist, *cp);
1068			if ((optp != NULL) && *(optp + 1) == ':') {
1069				argp = cp;
1070				break;
1071			}
1072		}
1073	}
1074	if (argp != NULL && *origval == '-')
1075		return (origval);
1076
1077	/*
1078	 * if last letter is a 't' flag with no argument (in the context
1079	 * of the oldps options -- option string NOT starting with a '-' --
1080	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1081	 *
1082	 * However, if a flag accepting a string argument is found earlier
1083	 * in the option string (including a possible `t' flag), then the
1084	 * remainder of the string must be the argument to that flag; so
1085	 * do not modify that argument.  Note that a trailing `t' would
1086	 * cause argp to be set, if argp was not already set by some
1087	 * earlier option.
1088	 */
1089	len = strlen(origval);
1090	cp = origval + len - 1;
1091	pidp = NULL;
1092	if (*cp == 't' && *origval != '-' && cp == argp) {
1093		if (nextarg == NULL || *nextarg == '-' || isdigitch(*nextarg))
1094			*cp = 'T';
1095	} else if (argp == NULL) {
1096		/*
1097		 * The original value did not include any option which takes
1098		 * an argument (and that would include `p' and `t'), so check
1099		 * the value for trailing number, or comma-separated list of
1100		 * numbers, which we will treat as a pid request.
1101		 */
1102		if (isdigitch(*cp)) {
1103			while (cp >= origval && (*cp == ',' || isdigitch(*cp)))
1104				--cp;
1105			pidp = cp + 1;
1106		}
1107	}
1108
1109	/*
1110	 * If nothing needs to be added to the string, then return
1111	 * the "original" (although possibly modified) value.
1112	 */
1113	if (*origval == '-' && pidp == NULL)
1114		return (origval);
1115
1116	/*
1117	 * Create a copy of the string to add '-' and/or 'p' to the
1118	 * original value.
1119	 */
1120	if ((newopts = ns = malloc(len + 3)) == NULL)
1121		errx(1, "malloc failed");
1122
1123	if (*origval != '-')
1124		*ns++ = '-';	/* add option flag */
1125
1126	if (pidp == NULL)
1127		strcpy(ns, origval);
1128	else {
1129		/*
1130		 * Copy everything before the pid string, add the `p',
1131		 * and then copy the pid string.
1132		 */
1133		len = pidp - origval;
1134		memcpy(ns, origval, len);
1135		ns += len;
1136		*ns++ = 'p';
1137		strcpy(ns, pidp);
1138	}
1139
1140	return (newopts);
1141}
1142
1143static void
1144usage(void)
1145{
1146#define	SINGLE_OPTS	"[-aCc" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
1147
1148	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
1149	    "usage: ps " SINGLE_OPTS " [-G gid[,gid]] [-O|o fmt]",
1150	    "          [-p pid[,pid]] [-t tty[,tty]] [-U user[,user]]",
1151	    "          [-M core] [-N system]",
1152	    "       ps [-L]");
1153	exit(1);
1154}
1155