ps.c revision 127546
1243750Srwatson/*-
2156283Srwatson * Copyright (c) 1990, 1993, 1994
3156283Srwatson *	The Regents of the University of California.  All rights reserved.
4243750Srwatson *
5243750Srwatson * Redistribution and use in source and binary forms, with or without
6156283Srwatson * modification, are permitted provided that the following conditions
7156283Srwatson * are met:
8156283Srwatson * 1. Redistributions of source code must retain the above copyright
9156283Srwatson *    notice, this list of conditions and the following disclaimer.
10156283Srwatson * 2. Redistributions in binary form must reproduce the above copyright
11156283Srwatson *    notice, this list of conditions and the following disclaimer in the
12156283Srwatson *    documentation and/or other materials provided with the distribution.
13156283Srwatson * 3. All advertising materials mentioning features or use of this software
14156283Srwatson *    must display the following acknowledgement:
15156283Srwatson *	This product includes software developed by the University of
16156283Srwatson *	California, Berkeley and its contributors.
17243750Srwatson * 4. Neither the name of the University nor the names of its contributors
18243750Srwatson *    may be used to endorse or promote products derived from this software
19243750Srwatson *    without specific prior written permission.
20243750Srwatson *
21243750Srwatson * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22243750Srwatson * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23243750Srwatson * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24243750Srwatson * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25243750Srwatson * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26243750Srwatson * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27243750Srwatson * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28243750Srwatson * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29243750Srwatson * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30243750Srwatson * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31243750Srwatson * SUCH DAMAGE.
32243750Srwatson * ------+---------+---------+-------- + --------+---------+---------+---------*
33243750Srwatson * Copyright (c) 2004  - Garance Alistair Drosehn <gad@FreeBSD.org>.
34156283Srwatson * All rights reserved.
35243750Srwatson *
36156283Srwatson * Significant modifications made to bring `ps' options somewhat closer
37243750Srwatson * to the standard for `ps' as described in SingleUnixSpec-v3.
38156283Srwatson * ------+---------+---------+-------- + --------+---------+---------+---------*
39156283Srwatson */
40156283Srwatson
41156283Srwatson#ifndef lint
42156283Srwatsonstatic const char copyright[] =
43156283Srwatson"@(#) Copyright (c) 1990, 1993, 1994\n\
44156283Srwatson	The Regents of the University of California.  All rights reserved.\n";
45156283Srwatson#endif /* not lint */
46156283Srwatson
47156283Srwatson#if 0
48156283Srwatson#ifndef lint
49156283Srwatsonstatic char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
50156283Srwatson#endif /* not lint */
51156283Srwatson#endif
52186647Srwatson
53186647Srwatson#include <sys/cdefs.h>
54186647Srwatson__FBSDID("$FreeBSD: head/bin/ps/ps.c 127546 2004-03-29 01:27:13Z gad $");
55173143Srwatson
56156283Srwatson#include <sys/param.h>
57243750Srwatson#include <sys/proc.h>
58243750Srwatson#include <sys/user.h>
59243750Srwatson#include <sys/stat.h>
60243750Srwatson#include <sys/ioctl.h>
61243750Srwatson#include <sys/sysctl.h>
62293161Sbrueffer
63293161Sbrueffer#include <ctype.h>
64293161Sbrueffer#include <err.h>
65156283Srwatson#include <errno.h>
66156283Srwatson#include <fcntl.h>
67156283Srwatson#include <grp.h>
68156283Srwatson#include <kvm.h>
69156283Srwatson#include <limits.h>
70173143Srwatson#include <locale.h>
71156283Srwatson#include <paths.h>
72156283Srwatson#include <pwd.h>
73156283Srwatson#include <stdint.h>
74243750Srwatson#include <stdio.h>
75156283Srwatson#include <stdlib.h>
76156283Srwatson#include <string.h>
77156283Srwatson#include <unistd.h>
78156283Srwatson
79173143Srwatson#include "ps.h"
80173143Srwatson
81173143Srwatson#define	W_SEP	" \t"		/* "Whitespace" list separators */
82173143Srwatson#define	T_SEP	","		/* "Terminate-element" list separators */
83173143Srwatson
84243750Srwatson#ifdef LAZY_PS
85243750Srwatson#define	DEF_UREAD	0;
86243750Srwatson#define	OPT_LAZY_f	"f"
87243750Srwatson#else
88243750Srwatson#define	DEF_UREAD	1;	/* Always do the more-expensive read. */
89173143Srwatson#define	OPT_LAZY_f		/* I.e., the `-f' option is not added. */
90173143Srwatson#endif
91243750Srwatson
92243750Srwatsonint	 cflag;			/* -c */
93243750Srwatsonint	 eval;			/* Exit value */
94156283Srwatsontime_t	 now;			/* Current time(3) value */
95156283Srwatsonint	 rawcpu;		/* -C */
96243750Srwatsonint	 sumrusage;		/* -S */
97186647Srwatsonint	 termwidth;		/* Width of the screen (0 == infinity). */
98156283Srwatsonint	 totwidth;		/* Calculated-width of requested variables. */
99156283Srwatson
100156283Srwatsonstruct varent *vhead;
101156283Srwatson
102243750Srwatsonstatic int	 forceuread = DEF_UREAD; /* Do extra work to get u-area. */
103243750Srwatsonstatic kvm_t	*kd;
104243750Srwatsonstatic KINFO	*kinfo;
105243750Srwatsonstatic int	 needcomm;	/* -o "command" */
106243750Srwatsonstatic int	 needenv;	/* -e */
107243750Srwatsonstatic int	 needuser;	/* -o "user" */
108243750Srwatsonstatic int	 optfatal;	/* Fatal error parsing some list-option. */
109243750Srwatson
110243750Srwatsonstatic enum sort { DEFAULT, SORTMEM, SORTCPU } sortby = DEFAULT;
111243750Srwatson
112243750Srwatsonstruct listinfo;
113243750Srwatsontypedef	int	addelem_rtn(struct listinfo *_inf, const char *_elem);
114243750Srwatson
115243750Srwatsonstruct listinfo {
116243750Srwatson	int		 count;
117243750Srwatson	int		 maxcount;
118243750Srwatson	int		 elemsize;
119243750Srwatson	addelem_rtn	*addelem;
120243750Srwatson	const char	*lname;
121243750Srwatson	union {
122243750Srwatson		gid_t	*gids;
123243750Srwatson		pid_t	*pids;
124243750Srwatson		dev_t	*ttys;
125243750Srwatson		uid_t	*uids;
126243750Srwatson		void	*ptr;
127243750Srwatson	};
128243750Srwatson};
129243750Srwatson
130243750Srwatsonstatic int	 addelem_gid(struct listinfo *, const char *);
131243750Srwatsonstatic int	 addelem_pid(struct listinfo *, const char *);
132243750Srwatsonstatic int	 addelem_tty(struct listinfo *, const char *);
133156283Srwatsonstatic int	 addelem_uid(struct listinfo *, const char *);
134156283Srwatsonstatic void	 add_list(struct listinfo *, const char *);
135243750Srwatsonstatic void	 dynsizevars(KINFO *);
136156283Srwatsonstatic void	*expand_list(struct listinfo *);
137243750Srwatsonstatic const char *fmt(char **(*)(kvm_t *, const struct kinfo_proc *, int),
138243750Srwatson		    KINFO *, char *, int);
139156283Srwatsonstatic void	 free_list(struct listinfo *);
140156283Srwatsonstatic void	 init_list(struct listinfo *, addelem_rtn, int, const char *);
141156283Srwatsonstatic char	*kludge_oldps_options(char *);
142156283Srwatsonstatic int	 pscomp(const void *, const void *);
143156283Srwatsonstatic void	 saveuser(KINFO *);
144156283Srwatsonstatic void	 scanvars(void);
145156283Srwatsonstatic void	 sizevars(void);
146156283Srwatsonstatic void	 usage(void);
147156283Srwatson
148156283Srwatsonstatic char dfmt[] = "pid,tt,state,time,command";
149156283Srwatsonstatic char jfmt[] = "user,pid,ppid,pgid,jobc,state,tt,time,command";
150156283Srwatsonstatic char lfmt[] = "uid,pid,ppid,cpu,pri,nice,vsz,rss,mwchan,state,"
151156283Srwatson			"tt,time,command";
152156283Srwatsonstatic char   o1[] = "pid";
153156283Srwatsonstatic char   o2[] = "tt,state,time,command";
154156283Srwatsonstatic char ufmt[] = "user,pid,%cpu,%mem,vsz,rss,tt,state,start,time,command";
155243750Srwatsonstatic char vfmt[] = "pid,state,time,sl,re,pagein,vsz,rss,lim,tsiz,"
156191273Srwatson			"%cpu,%mem,command";
157243750Srwatsonstatic char Zfmt[] = "label";
158156283Srwatson
159156283Srwatson#define	PS_ARGS	"AaCc" OPT_LAZY_f "G:gHhjLlM:mN:O:o:p:rSTt:U:uvwXxZ"
160156283Srwatson
161156283Srwatsonint
162156283Srwatsonmain(int argc, char *argv[])
163243750Srwatson{
164173143Srwatson	struct listinfo gidlist, pgrplist, pidlist;
165173143Srwatson	struct listinfo ruidlist, sesslist, ttylist, uidlist;
166156283Srwatson	struct kinfo_proc *kp;
167156283Srwatson	struct varent *vent;
168156283Srwatson	struct winsize ws;
169156283Srwatson	const char *cp, *nlistf, *memf;
170243750Srwatson	char *cols;
171156283Srwatson	int all, ch, dropgid, elem, flag, _fmt, i, lineno;
172243750Srwatson	int nentries, nocludge, nkept, nselectors;
173243750Srwatson	int prtheader, showthreads, wflag, what, xkeep, xkeep_implied;
174243750Srwatson	char errbuf[_POSIX2_LINE_MAX];
175156283Srwatson
176156283Srwatson	(void) setlocale(LC_ALL, "");
177156283Srwatson	time(&now);			/* Used by routines in print.c. */
178243750Srwatson
179156283Srwatson	if ((cols = getenv("COLUMNS")) != NULL && *cols != '\0')
180156283Srwatson		termwidth = atoi(cols);
181156283Srwatson	else if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
182156283Srwatson	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
183243750Srwatson	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
184185573Srwatson	     ws.ws_col == 0)
185173143Srwatson		termwidth = 79;
186243750Srwatson	else
187191273Srwatson		termwidth = ws.ws_col - 1;
188243750Srwatson
189156283Srwatson	/*
190243750Srwatson	 * Don't apply a kludge if the first argument is an option taking an
191243750Srwatson	 * argument
192156283Srwatson	 */
193156283Srwatson	if (argc > 1) {
194156283Srwatson		nocludge = 0;
195156283Srwatson		if (argv[1][0] == '-') {
196156283Srwatson			for (cp = PS_ARGS; *cp != '\0'; cp++) {
197243750Srwatson				if (*cp != ':')
198156283Srwatson					continue;
199156283Srwatson				if (*(cp - 1) == argv[1][1]) {
200156283Srwatson					nocludge = 1;
201173143Srwatson					break;
202156283Srwatson				}
203156283Srwatson			}
204156283Srwatson		}
205156283Srwatson		if (nocludge == 0)
206243750Srwatson			argv[1] = kludge_oldps_options(argv[1]);
207243750Srwatson	}
208173143Srwatson
209173143Srwatson	all = dropgid = _fmt = nselectors = optfatal = 0;
210173143Srwatson	prtheader = showthreads = wflag = xkeep_implied = 0;
211173143Srwatson	xkeep = -1;			/* Neither -x nor -X. */
212243750Srwatson	init_list(&gidlist, addelem_gid, sizeof(gid_t), "group");
213156283Srwatson	init_list(&pgrplist, addelem_pid, sizeof(pid_t), "process group");
214243750Srwatson	init_list(&pidlist, addelem_pid, sizeof(pid_t), "process id");
215156283Srwatson	init_list(&ruidlist, addelem_uid, sizeof(uid_t), "ruser");
216156283Srwatson	init_list(&sesslist, addelem_pid, sizeof(pid_t), "session id");
217156283Srwatson	init_list(&ttylist, addelem_tty, sizeof(dev_t), "tty");
218156283Srwatson	init_list(&uidlist, addelem_uid, sizeof(uid_t), "user");
219156283Srwatson	memf = nlistf = _PATH_DEVNULL;
220156283Srwatson	while ((ch = getopt(argc, argv, PS_ARGS)) != -1)
221156283Srwatson		switch((char)ch) {
222156283Srwatson		case 'A':
223156283Srwatson			/*
224156283Srwatson			 * Exactly the same as `-ax'.   This has been
225156283Srwatson			 * added for compatability with SUSv3, but for
226173143Srwatson			 * now it will not be described in the man page.
227156283Srwatson			 */
228173143Srwatson			nselectors++;
229173143Srwatson			all = xkeep = 1;
230173143Srwatson			break;
231156283Srwatson		case 'a':
232156283Srwatson			nselectors++;
233156283Srwatson			all = 1;
234156283Srwatson			break;
235156283Srwatson		case 'C':
236156283Srwatson			rawcpu = 1;
237173143Srwatson			break;
238156283Srwatson		case 'c':
239156283Srwatson			cflag = 1;
240156283Srwatson			break;
241156283Srwatson		case 'e':			/* XXX set ufmt */
242156283Srwatson			needenv = 1;
243173143Srwatson			break;
244156283Srwatson#ifdef LAZY_PS
245156283Srwatson		case 'f':
246156283Srwatson			if (getuid() == 0 || getgid() == 0)
247156283Srwatson				forceuread = 1;
248173143Srwatson			break;
249156283Srwatson#endif
250156283Srwatson		case 'G':
251173143Srwatson			add_list(&gidlist, optarg);
252156283Srwatson			xkeep_implied = 1;
253156283Srwatson			nselectors++;
254173143Srwatson			break;
255156283Srwatson		case 'g':
256156283Srwatson#if 0
257191273Srwatson			/*
258173143Srwatson			 * XXX - This SUSv3 behavior is still under debate
259173143Srwatson			 *	since it conflicts with the (undocumented)
260186647Srwatson			 *	`-g' option.  So we skip it for now.
261243750Srwatson			 */
262156283Srwatson			add_list(&pgrplist, optarg);
263156283Srwatson			xkeep_implied = 1;
264156283Srwatson			nselectors++;
265156283Srwatson			break;
266156283Srwatson#else
267156283Srwatson			/* The historical BSD-ish (from SunOS) behavior. */
268156283Srwatson			break;			/* no-op */
269156283Srwatson#endif
270156283Srwatson		case 'H':
271156283Srwatson			showthreads = KERN_PROC_INC_THREAD;
272243750Srwatson			break;
273156283Srwatson		case 'h':
274156283Srwatson			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
275156283Srwatson			break;
276156283Srwatson		case 'j':
277156283Srwatson			parsefmt(jfmt, 0);
278243750Srwatson			_fmt = 1;
279243750Srwatson			jfmt[0] = '\0';
280156283Srwatson			break;
281156283Srwatson		case 'L':
282156283Srwatson			showkey();
283156283Srwatson			exit(0);
284243750Srwatson		case 'l':
285243750Srwatson			parsefmt(lfmt, 0);
286243750Srwatson			_fmt = 1;
287156283Srwatson			lfmt[0] = '\0';
288156283Srwatson			break;
289156283Srwatson		case 'M':
290156283Srwatson			memf = optarg;
291156283Srwatson			dropgid = 1;
292156283Srwatson			break;
293156283Srwatson		case 'm':
294156283Srwatson			sortby = SORTMEM;
295156283Srwatson			break;
296156283Srwatson		case 'N':
297156283Srwatson			nlistf = optarg;
298156283Srwatson			dropgid = 1;
299156283Srwatson			break;
300156283Srwatson		case 'O':
301156283Srwatson			parsefmt(o1, 1);
302243750Srwatson			parsefmt(optarg, 1);
303156283Srwatson			parsefmt(o2, 1);
304243750Srwatson			o1[0] = o2[0] = '\0';
305243750Srwatson			_fmt = 1;
306156283Srwatson			break;
307156283Srwatson		case 'o':
308243750Srwatson			parsefmt(optarg, 1);
309243750Srwatson			_fmt = 1;
310156283Srwatson			break;
311156283Srwatson		case 'p':
312156283Srwatson			add_list(&pidlist, optarg);
313156283Srwatson			/*
314156283Srwatson			 * Note: `-p' does not *set* xkeep, but any values
315243750Srwatson			 * from pidlist are checked before xkeep is.  That
316156283Srwatson			 * way they are always matched, even if the user
317156283Srwatson			 * specifies `-X'.
318156283Srwatson			 */
319156283Srwatson			nselectors++;
320156283Srwatson			break;
321156283Srwatson#if 0
322156283Srwatson		case 'R':
323156283Srwatson			/*
324156283Srwatson			 * XXX - This un-standard option is still under
325156283Srwatson			 *	debate.  This is what SUSv3 defines as
326156283Srwatson			 *	the `-U' option, and while it would be
327156283Srwatson			 *	nice to have, it could cause even more
328156283Srwatson			 *	confusion to implement it as `-R'.
329243750Srwatson			 */
330156283Srwatson			add_list(&ruidlist, optarg);
331156283Srwatson			xkeep_implied = 1;
332243750Srwatson			nselectors++;
333243750Srwatson			break;
334243750Srwatson#endif
335243750Srwatson		case 'r':
336243750Srwatson			sortby = SORTCPU;
337243750Srwatson			break;
338243750Srwatson		case 'S':
339156283Srwatson			sumrusage = 1;
340156283Srwatson			break;
341156283Srwatson#if 0
342156283Srwatson		case 's':
343156283Srwatson			/*
344156283Srwatson			 * XXX - This non-standard option is still under
345156283Srwatson			 *	debate.  This *is* supported on Solaris,
346156283Srwatson			 *	Linux, and IRIX, but conflicts with `-s'
347243750Srwatson			 *	on NetBSD and maybe some older BSD's.
348243750Srwatson			 */
349243750Srwatson			add_list(&sesslist, optarg);
350243750Srwatson			xkeep_implied = 1;
351243750Srwatson			nselectors++;
352156283Srwatson			break;
353156283Srwatson#endif
354156283Srwatson		case 'T':
355156283Srwatson			if ((optarg = ttyname(STDIN_FILENO)) == NULL)
356156283Srwatson				errx(1, "stdin: not a terminal");
357156283Srwatson			/* FALLTHROUGH */
358156283Srwatson		case 't':
359243750Srwatson			add_list(&ttylist, optarg);
360156283Srwatson			xkeep_implied = 1;
361156283Srwatson			nselectors++;
362156283Srwatson			break;
363156283Srwatson		case 'U':
364156283Srwatson			/* This is what SUSv3 defines as the `-u' option. */
365156283Srwatson			add_list(&uidlist, optarg);
366156283Srwatson			xkeep_implied = 1;
367243750Srwatson			nselectors++;
368156283Srwatson			break;
369156283Srwatson		case 'u':
370156283Srwatson			parsefmt(ufmt, 0);
371243750Srwatson			sortby = SORTCPU;
372156283Srwatson			_fmt = 1;
373243750Srwatson			ufmt[0] = '\0';
374243750Srwatson			break;
375243750Srwatson		case 'v':
376243750Srwatson			parsefmt(vfmt, 0);
377156283Srwatson			sortby = SORTMEM;
378156283Srwatson			_fmt = 1;
379156283Srwatson			vfmt[0] = '\0';
380156283Srwatson			break;
381156283Srwatson		case 'w':
382156283Srwatson			if (wflag)
383243750Srwatson				termwidth = UNLIMITED;
384191273Srwatson			else if (termwidth < 131)
385156283Srwatson				termwidth = 131;
386156283Srwatson			wflag++;
387156283Srwatson			break;
388156283Srwatson		case 'X':
389156283Srwatson			/*
390243750Srwatson			 * Note that `-X' and `-x' are not standard "selector"
391156283Srwatson			 * options. For most selector-options, we check *all*
392156283Srwatson			 * processes to see if any are matched by the given
393156283Srwatson			 * value(s).  After we have a set of all the matched
394156283Srwatson			 * processes, then `-X' and `-x' govern whether we
395156283Srwatson			 * modify that *matched* set for processes which do
396156283Srwatson			 * not have a controlling terminal.  `-X' causes
397156283Srwatson			 * those processes to be deleted from the matched
398156283Srwatson			 * set, while `-x' causes them to be kept.
399156283Srwatson			 */
400156283Srwatson			xkeep = 0;
401156283Srwatson			break;
402243750Srwatson		case 'x':
403156283Srwatson			xkeep = 1;
404156283Srwatson			break;
405156283Srwatson		case 'Z':
406156283Srwatson			parsefmt(Zfmt, 0);
407156283Srwatson			Zfmt[0] = '\0';
408156283Srwatson			break;
409191273Srwatson		case '?':
410191273Srwatson		default:
411243750Srwatson			usage();
412243750Srwatson		}
413156283Srwatson	argc -= optind;
414243750Srwatson	argv += optind;
415243750Srwatson	if (optfatal)
416243750Srwatson		exit(1);		/* Error messages already printed. */
417243750Srwatson	if (xkeep < 0)			/* Neither -X nor -x was specified. */
418243750Srwatson		xkeep = xkeep_implied;
419243750Srwatson
420243750Srwatson#define	BACKWARD_COMPATIBILITY
421156283Srwatson#ifdef	BACKWARD_COMPATIBILITY
422156283Srwatson	if (*argv) {
423156283Srwatson		nlistf = *argv;
424156283Srwatson		if (*++argv)
425156283Srwatson			memf = *argv;
426156283Srwatson	}
427156283Srwatson#endif
428156283Srwatson	/*
429191273Srwatson	 * Discard setgid privileges if not the running kernel so that bad
430191273Srwatson	 * guys can't print interesting stuff from kernel memory.
431243750Srwatson	 */
432156283Srwatson	if (dropgid) {
433243750Srwatson		setgid(getgid());
434156283Srwatson		setuid(getuid());
435156283Srwatson	}
436156283Srwatson
437243750Srwatson	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
438243750Srwatson	if (kd == 0)
439156283Srwatson		errx(1, "%s", errbuf);
440243750Srwatson
441243750Srwatson	if (!_fmt)
442243750Srwatson		parsefmt(dfmt, 0);
443243750Srwatson
444243750Srwatson	if (nselectors == 0) {
445243750Srwatson		uidlist.ptr = malloc(sizeof(uid_t));
446243750Srwatson		if (uidlist.ptr == NULL)
447243750Srwatson			errx(1, "malloc failed");
448243750Srwatson		nselectors = 1;
449243750Srwatson		uidlist.count = uidlist.maxcount = 1;
450243750Srwatson		*uidlist.uids = getuid();
451243750Srwatson	}
452243750Srwatson
453243750Srwatson	/*
454243750Srwatson	 * scan requested variables, noting what structures are needed,
455243750Srwatson	 * and adjusting header widths as appropriate.
456243750Srwatson	 */
457243750Srwatson	scanvars();
458243750Srwatson
459243750Srwatson	/*
460243750Srwatson	 * Get process list.  If the user requested just one selector-
461243750Srwatson	 * option, then kvm_getprocs can be asked to return just those
462243750Srwatson	 * processes.  Otherwise, have it return all processes, and
463156283Srwatson	 * then this routine will search that full list and select the
464156283Srwatson	 * processes which match any of the user's selector-options.
465243750Srwatson	 */
466156283Srwatson	what = showthreads != 0 ? KERN_PROC_ALL : KERN_PROC_PROC;
467156283Srwatson	flag = 0;
468156283Srwatson	if (nselectors == 1) {
469243750Srwatson		/* XXX - Apparently there's no KERN_PROC_GID flag. */
470173143Srwatson		if (pgrplist.count == 1) {
471173143Srwatson			what = KERN_PROC_PGRP | showthreads;
472173143Srwatson			flag = *pgrplist.pids;
473173143Srwatson			nselectors = 0;
474173143Srwatson		} else if (pidlist.count == 1) {
475173143Srwatson			what = KERN_PROC_PID | showthreads;
476173143Srwatson			flag = *pidlist.pids;
477173143Srwatson			nselectors = 0;
478173143Srwatson		} else if (ruidlist.count == 1) {
479173143Srwatson			what = KERN_PROC_RUID | showthreads;
480173143Srwatson			flag = *ruidlist.uids;
481173143Srwatson			nselectors = 0;
482156283Srwatson#if 0
483156283Srwatson		/*
484173143Srwatson		 * XXX - KERN_PROC_SESSION causes error in kvm_getprocs?
485243750Srwatson		 *	For now, always do sid-matching in this routine.
486243750Srwatson		 */
487243750Srwatson		} else if (sesslist.count == 1) {
488156283Srwatson			what = KERN_PROC_SESSION | showthreads;
489243750Srwatson			flag = *sesslist.pids;
490243750Srwatson			nselectors = 0;
491156283Srwatson#endif
492243750Srwatson		} else if (ttylist.count == 1) {
493156283Srwatson			what = KERN_PROC_TTY | showthreads;
494243750Srwatson			flag = *ttylist.ttys;
495243750Srwatson			nselectors = 0;
496156283Srwatson		} else if (uidlist.count == 1) {
497156283Srwatson			what = KERN_PROC_UID | showthreads;
498156283Srwatson			flag = *uidlist.uids;
499243750Srwatson			nselectors = 0;
500156283Srwatson		} else if (all) {
501243750Srwatson			/* No need for this routine to select processes. */
502243750Srwatson			nselectors = 0;
503243750Srwatson		}
504243750Srwatson	}
505243750Srwatson
506243750Srwatson	/*
507243750Srwatson	 * select procs
508243750Srwatson	 */
509243750Srwatson	nentries = -1;
510243750Srwatson	kp = kvm_getprocs(kd, what, flag, &nentries);
511243750Srwatson	if ((kp == NULL && nentries > 0) || (kp != NULL && nentries < 0))
512243750Srwatson		errx(1, "%s", kvm_geterr(kd));
513243750Srwatson	nkept = 0;
514156283Srwatson	if (nentries > 0) {
515243750Srwatson		if ((kinfo = malloc(nentries * sizeof(*kinfo))) == NULL)
516243750Srwatson			errx(1, "malloc failed");
517173143Srwatson		for (i = nentries; --i >= 0; ++kp) {
518173143Srwatson			/*
519243750Srwatson			 * If the user specified multiple selection-criteria,
520156283Srwatson			 * then keep any process matched by the inclusive OR
521156283Srwatson			 * of all the selection-criteria given.
522156283Srwatson			 */
523156283Srwatson			if (pidlist.count > 0) {
524243750Srwatson				for (elem = 0; elem < pidlist.count; elem++)
525243750Srwatson					if (kp->ki_pid == pidlist.pids[elem])
526243750Srwatson						goto keepit;
527156283Srwatson			}
528156283Srwatson			/*
529173143Srwatson			 * Note that we had to process pidlist before
530243750Srwatson			 * filtering out processes which do not have
531156283Srwatson			 * a controlling terminal.
532156283Srwatson			 */
533243750Srwatson			if (xkeep == 0) {
534156283Srwatson				if ((kp->ki_tdev == NODEV ||
535156283Srwatson				    (kp->ki_flag & P_CONTROLT) == 0))
536243750Srwatson					continue;
537243750Srwatson			}
538156283Srwatson			if (nselectors == 0)
539243750Srwatson				goto keepit;
540243750Srwatson			if (gidlist.count > 0) {
541243750Srwatson				for (elem = 0; elem < gidlist.count; elem++)
542191273Srwatson					if (kp->ki_rgid == gidlist.gids[elem])
543243750Srwatson						goto keepit;
544243750Srwatson			}
545243750Srwatson			if (pgrplist.count > 0) {
546243750Srwatson				for (elem = 0; elem < pgrplist.count; elem++)
547156283Srwatson					if (kp->ki_pgid == pgrplist.pids[elem])
548156283Srwatson						goto keepit;
549243750Srwatson			}
550156283Srwatson			if (ruidlist.count > 0) {
551156283Srwatson				for (elem = 0; elem < ruidlist.count; elem++)
552156283Srwatson					if (kp->ki_ruid == ruidlist.uids[elem])
553243750Srwatson						goto keepit;
554156283Srwatson			}
555156283Srwatson			if (sesslist.count > 0) {
556156283Srwatson				for (elem = 0; elem < sesslist.count; elem++)
557156283Srwatson					if (kp->ki_sid == sesslist.pids[elem])
558243750Srwatson						goto keepit;
559156283Srwatson			}
560243750Srwatson			if (ttylist.count > 0) {
561243750Srwatson				for (elem = 0; elem < ttylist.count; elem++)
562243750Srwatson					if (kp->ki_tdev == ttylist.ttys[elem])
563156283Srwatson						goto keepit;
564156283Srwatson			}
565156283Srwatson			if (uidlist.count > 0) {
566156283Srwatson				for (elem = 0; elem < uidlist.count; elem++)
567156283Srwatson					if (kp->ki_uid == uidlist.uids[elem])
568156283Srwatson						goto keepit;
569156283Srwatson			}
570243750Srwatson			/*
571156283Srwatson			 * This process did not match any of the user's
572243750Srwatson			 * selector-options, so skip the process.
573243750Srwatson			 */
574243750Srwatson			continue;
575243750Srwatson
576243750Srwatson		keepit:
577156283Srwatson			kinfo[nkept].ki_p = kp;
578156283Srwatson			if (needuser)
579156283Srwatson				saveuser(&kinfo[nkept]);
580243750Srwatson			dynsizevars(&kinfo[nkept]);
581156283Srwatson			nkept++;
582156283Srwatson		}
583156283Srwatson	}
584243750Srwatson
585156283Srwatson	sizevars();
586156283Srwatson
587156283Srwatson	/*
588243750Srwatson	 * print header
589156283Srwatson	 */
590156283Srwatson	printheader();
591243750Srwatson	if (nkept == 0)
592243750Srwatson		exit(1);
593156283Srwatson
594243750Srwatson	/*
595156283Srwatson	 * sort proc list
596156283Srwatson	 */
597156283Srwatson	qsort(kinfo, nkept, sizeof(KINFO), pscomp);
598156283Srwatson	/*
599156283Srwatson	 * For each process, call each variable output function.
600156283Srwatson	 */
601156283Srwatson	for (i = lineno = 0; i < nkept; i++) {
602156283Srwatson		for (vent = vhead; vent; vent = vent->next) {
603156283Srwatson			(vent->var->oproc)(&kinfo[i], vent);
604156283Srwatson			if (vent->next != NULL)
605156283Srwatson				(void)putchar(' ');
606156283Srwatson		}
607156283Srwatson		(void)putchar('\n');
608156283Srwatson		if (prtheader && lineno++ == prtheader - 4) {
609156283Srwatson			(void)putchar('\n');
610156283Srwatson			printheader();
611156283Srwatson			lineno = 0;
612156283Srwatson		}
613156283Srwatson	}
614156283Srwatson	free_list(&gidlist);
615243750Srwatson	free_list(&pidlist);
616243750Srwatson	free_list(&pgrplist);
617243750Srwatson	free_list(&ruidlist);
618243750Srwatson	free_list(&sesslist);
619156283Srwatson	free_list(&ttylist);
620156283Srwatson	free_list(&uidlist);
621173143Srwatson
622156283Srwatson	exit(eval);
623243750Srwatson}
624243750Srwatson
625243750Srwatsonstatic int
626243750Srwatsonaddelem_gid(struct listinfo *inf, const char *elem)
627243750Srwatson{
628243750Srwatson	struct group *grp;
629243750Srwatson	const char *nameorID;
630243750Srwatson	char *endp;
631243750Srwatson	intmax_t ltemp;
632243750Srwatson
633156283Srwatson	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
634156283Srwatson		if (*elem == '\0')
635156283Srwatson			warnx("Invalid (zero-length) %s name", inf->lname);
636156283Srwatson		else
637156283Srwatson			warnx("%s name too long: %s", inf->lname, elem);
638156283Srwatson		optfatal = 1;
639156283Srwatson		return (0);		/* Do not add this value. */
640156283Srwatson	}
641156283Srwatson
642156283Srwatson	/*
643156283Srwatson	 * SUSv3 states that `ps -G grouplist' should match "real-group
644156283Srwatson	 * ID numbers", and does not mention group-names.  I do want to
645156283Srwatson	 * also support group-names, so this tries for a group-id first,
646156283Srwatson	 * and only tries for a name if that doesn't work.  This is the
647156283Srwatson	 * opposite order of what is done in addelem_uid(), but in
648156283Srwatson	 * practice the order would only matter for group-names which
649156283Srwatson	 * are all-numeric.
650156283Srwatson	 */
651156283Srwatson	grp = NULL;
652156283Srwatson	nameorID = "named";
653156283Srwatson	errno = 0;
654156283Srwatson	ltemp = strtol(elem, &endp, 10);
655156283Srwatson	if (errno == 0 && *endp == '\0' && ltemp >= 0 && ltemp <= GID_MAX) {
656156283Srwatson		nameorID = "name or ID matches";
657156283Srwatson		grp = getgrgid((gid_t)ltemp);
658156283Srwatson	}
659156283Srwatson	if (grp == NULL)
660156283Srwatson		grp = getgrnam(elem);
661156283Srwatson	if (grp == NULL) {
662156283Srwatson		warnx("No %s %s '%s'", inf->lname, nameorID, elem);
663243750Srwatson		optfatal = 1;
664243750Srwatson		return (0);		/* Do not add this value. */
665243750Srwatson	}
666243750Srwatson
667243750Srwatson	if (inf->count >= inf->maxcount)
668243750Srwatson		expand_list(inf);
669243750Srwatson	inf->gids[(inf->count)++] = grp->gr_gid;
670243750Srwatson	return (1);
671243750Srwatson}
672156283Srwatson
673156283Srwatson#define	BSD_PID_MAX	99999	/* Copy of PID_MAX from sys/proc.h. */
674156283Srwatsonstatic int
675156283Srwatsonaddelem_pid(struct listinfo *inf, const char *elem)
676156283Srwatson{
677156283Srwatson	char *endp;
678243750Srwatson	long tempid;
679156283Srwatson
680156283Srwatson	if (*elem == '\0')
681156283Srwatson		tempid = 0L;
682156283Srwatson	else {
683156283Srwatson		errno = 0;
684156283Srwatson		tempid = strtol(elem, &endp, 10);
685156283Srwatson		if (*endp != '\0' || tempid < 0 || elem == endp) {
686156283Srwatson			warnx("Invalid %s: %s", inf->lname, elem);
687156283Srwatson			errno = ERANGE;
688156283Srwatson		} else if (errno != 0 || tempid > BSD_PID_MAX) {
689156283Srwatson			warnx("%s too large: %s", inf->lname, elem);
690156283Srwatson			errno = ERANGE;
691156283Srwatson		}
692156283Srwatson		if (errno == ERANGE) {
693156283Srwatson			optfatal = 1;
694156283Srwatson			return (0);	/* Do not add this value. */
695156283Srwatson		}
696156283Srwatson	}
697156283Srwatson
698156283Srwatson	if (inf->count >= inf->maxcount)
699243750Srwatson		expand_list(inf);
700243750Srwatson	inf->pids[(inf->count)++] = tempid;
701156283Srwatson	return (1);
702156283Srwatson}
703156283Srwatson#undef	BSD_PID_MAX
704156283Srwatson
705156283Srwatsonstatic int
706156283Srwatsonaddelem_tty(struct listinfo *inf, const char *elem)
707173143Srwatson{
708173143Srwatson	const char *ttypath;
709243750Srwatson	struct stat sb;
710243750Srwatson	char pathbuf[PATH_MAX];
711156283Srwatson
712156283Srwatson	if (strcmp(elem, "co") == 0)
713173143Srwatson		ttypath = strdup(_PATH_CONSOLE);
714173143Srwatson	else if (*elem == '/')
715243750Srwatson		ttypath = elem;
716243750Srwatson	else {
717156283Srwatson		strlcpy(pathbuf, _PATH_TTY, sizeof(pathbuf));
718156283Srwatson		strlcat(pathbuf, elem, sizeof(pathbuf));
719243750Srwatson		ttypath = pathbuf;
720243750Srwatson	}
721156283Srwatson
722156283Srwatson	if (stat(ttypath, &sb) == -1) {
723173143Srwatson		warn("%s", ttypath);
724173143Srwatson		optfatal = 1;
725243750Srwatson		return (0);		/* Do not add this value. */
726243750Srwatson	}
727173143Srwatson	if (!S_ISCHR(sb.st_mode)) {
728173143Srwatson		warn("%s: Not a terminal", ttypath);
729243750Srwatson		optfatal = 1;
730243750Srwatson		return (0);		/* Do not add this value. */
731156283Srwatson	}
732156283Srwatson
733156283Srwatson	if (inf->count >= inf->maxcount)
734156283Srwatson		expand_list(inf);
735156283Srwatson	inf->ttys[(inf->count)++] = sb.st_rdev;
736156283Srwatson	return (1);
737156283Srwatson}
738156283Srwatson
739156283Srwatsonstatic int
740156283Srwatsonaddelem_uid(struct listinfo *inf, const char *elem)
741156283Srwatson{
742156283Srwatson	struct passwd *pwd;
743156283Srwatson	char *endp;
744156283Srwatson	intmax_t ltemp;
745156283Srwatson
746156283Srwatson	if (*elem == '\0' || strlen(elem) >= MAXLOGNAME) {
747156283Srwatson		if (*elem == '\0')
748156283Srwatson			warnx("Invalid (zero-length) %s name", inf->lname);
749156283Srwatson		else
750156283Srwatson			warnx("%s name too long: %s", inf->lname, elem);
751173143Srwatson		optfatal = 1;
752156283Srwatson		return (0);		/* Do not add this value. */
753243750Srwatson	}
754243750Srwatson
755243750Srwatson	pwd = getpwnam(elem);
756156283Srwatson	if (pwd == NULL) {
757173143Srwatson		errno = 0;
758243750Srwatson		ltemp = strtol(elem, &endp, 10);
759243750Srwatson		if (errno != 0 || *endp != '\0' || ltemp < 0 ||
760243750Srwatson		    ltemp > UID_MAX)
761243750Srwatson			warnx("No %s named '%s'", inf->lname, elem);
762243750Srwatson		else {
763243750Srwatson			/* The string is all digits, so it might be a userID. */
764243750Srwatson			pwd = getpwuid((uid_t)ltemp);
765243750Srwatson			if (pwd == NULL)
766243750Srwatson				warnx("No %s name or ID matches '%s'",
767243750Srwatson				    inf->lname, elem);
768243750Srwatson		}
769243750Srwatson	}
770243750Srwatson	if (pwd == NULL) {
771243750Srwatson		/*
772243750Srwatson		 * These used to be treated as minor warnings (and the
773156283Srwatson		 * option was simply ignored), but now they are fatal
774243750Srwatson		 * errors (and the command will be aborted).
775156283Srwatson		 */
776156283Srwatson		optfatal = 1;
777156283Srwatson		return (0);		/* Do not add this value. */
778	}
779
780	if (inf->count >= inf->maxcount)
781		expand_list(inf);
782	inf->uids[(inf->count)++] = pwd->pw_uid;
783	return (1);
784}
785
786static void
787add_list(struct listinfo *inf, const char *argp)
788{
789	const char *savep;
790	char *cp, *endp;
791	int toolong;
792	char elemcopy[PATH_MAX];
793
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#ifndef ADD_PS_LISTRESET
811			/*
812			 * This is how the standard expects lists to
813			 * be handled.
814			 */
815			inf->addelem(inf, elemcopy);
816#else
817			/*
818			 * This would add a simple non-standard-but-convienent
819			 * feature.
820			 *
821			 * XXX - The first time I tried to add this check,
822			 *	it increased the total size of `ps' by 3940
823			 *	bytes on i386!  That's 12% of the entire
824			 *	program!  The `ps.o' file grew by only about
825			 *	40 bytes, but the final (stripped) executable
826			 *	in /bin/ps grew by 12%.  I have not had time
827			 *	to investigate, so skip the feature for now.
828			 */
829			/*
830			 * We now have a single element.  Add it to the
831			 * list, unless the element is ":".  In that case,
832			 * reset the list so previous entries are ignored.
833			 */
834			if (strcmp(elemcopy, ":") == 0)
835				inf->count = 0;
836			else
837				inf->addelem(inf, elemcopy);
838#endif
839		} else {
840			/*
841			 * The string is too long to copy.  Find the end
842			 * of the string to print out the warning message.
843			 */
844			while (*argp != '\0' && strchr(W_SEP T_SEP,
845			    *argp) == NULL)
846				argp++;
847			warnx("Value too long: %.*s", (int)(argp - savep),
848			    savep);
849			optfatal = 1;
850		}
851		/*
852		 * Skip over any number of trailing whitespace characters,
853		 * but only one (at most) trailing element-terminating
854		 * character.
855		 */
856		while (*argp != '\0' && strchr(W_SEP, *argp) != NULL)
857			argp++;
858		if (*argp != '\0' && strchr(T_SEP, *argp) != NULL) {
859			argp++;
860			/* Catch case where string ended with a comma. */
861			if (*argp == '\0')
862				inf->addelem(inf, argp);
863		}
864	}
865}
866
867static void *
868expand_list(struct listinfo *inf)
869{
870	void *newlist;
871	int newmax;
872
873	newmax = (inf->maxcount + 1) << 1;
874	newlist = realloc(inf->ptr, newmax * inf->elemsize);
875	if (newlist == NULL) {
876		free(inf->ptr);
877		errx(1, "realloc to %d %ss failed", newmax,
878		    inf->lname);
879	}
880	inf->maxcount = newmax;
881	inf->ptr = newlist;
882
883	return (newlist);
884}
885
886static void
887free_list(struct listinfo *inf)
888{
889
890	inf->count = inf->elemsize = inf->maxcount = 0;
891	if (inf->ptr != NULL)
892		free(inf->ptr);
893	inf->addelem = NULL;
894	inf->lname = NULL;
895	inf->ptr = NULL;
896}
897
898static void
899init_list(struct listinfo *inf, addelem_rtn artn, int elemsize,
900    const char *lname)
901{
902
903	inf->count = inf->maxcount = 0;
904	inf->elemsize = elemsize;
905	inf->addelem = artn;
906	inf->lname = lname;
907	inf->ptr = NULL;
908}
909
910VARENT *
911find_varentry(VAR *v)
912{
913	struct varent *vent;
914
915	for (vent = vhead; vent; vent = vent->next) {
916		if (strcmp(vent->var->name, v->name) == 0)
917			return vent;
918	}
919	return NULL;
920}
921
922static void
923scanvars(void)
924{
925	struct varent *vent;
926	VAR *v;
927
928	for (vent = vhead; vent; vent = vent->next) {
929		v = vent->var;
930		if (v->flag & DSIZ) {
931			v->dwidth = v->width;
932			v->width = 0;
933		}
934		if (v->flag & USER)
935			needuser = 1;
936		if (v->flag & COMM)
937			needcomm = 1;
938	}
939}
940
941static void
942dynsizevars(KINFO *ki)
943{
944	struct varent *vent;
945	VAR *v;
946	int i;
947
948	for (vent = vhead; vent; vent = vent->next) {
949		v = vent->var;
950		if (!(v->flag & DSIZ))
951			continue;
952		i = (v->sproc)( ki);
953		if (v->width < i)
954			v->width = i;
955		if (v->width > v->dwidth)
956			v->width = v->dwidth;
957	}
958}
959
960static void
961sizevars(void)
962{
963	struct varent *vent;
964	VAR *v;
965	int i;
966
967	for (vent = vhead; vent; vent = vent->next) {
968		v = vent->var;
969		i = strlen(vent->header);
970		if (v->width < i)
971			v->width = i;
972		totwidth += v->width + 1;	/* +1 for space */
973	}
974	totwidth--;
975}
976
977static const char *
978fmt(char **(*fn)(kvm_t *, const struct kinfo_proc *, int), KINFO *ki,
979    char *comm, int maxlen)
980{
981	const char *s;
982
983	s = fmt_argv((*fn)(kd, ki->ki_p, termwidth), comm, maxlen);
984	return (s);
985}
986
987#define UREADOK(ki)	(forceuread || (ki->ki_p->ki_sflag & PS_INMEM))
988
989static void
990saveuser(KINFO *ki)
991{
992
993	if (ki->ki_p->ki_sflag & PS_INMEM) {
994		/*
995		 * The u-area might be swapped out, and we can't get
996		 * at it because we have a crashdump and no swap.
997		 * If it's here fill in these fields, otherwise, just
998		 * leave them 0.
999		 */
1000		ki->ki_valid = 1;
1001	} else
1002		ki->ki_valid = 0;
1003	/*
1004	 * save arguments if needed
1005	 */
1006	if (needcomm && (UREADOK(ki) || (ki->ki_p->ki_args != NULL))) {
1007		ki->ki_args = strdup(fmt(kvm_getargv, ki, ki->ki_p->ki_comm,
1008		    MAXCOMLEN));
1009	} else if (needcomm) {
1010		asprintf(&ki->ki_args, "(%s)", ki->ki_p->ki_comm);
1011	} else {
1012		ki->ki_args = NULL;
1013	}
1014	if (needenv && UREADOK(ki)) {
1015		ki->ki_env = strdup(fmt(kvm_getenvv, ki, (char *)NULL, 0));
1016	} else if (needenv) {
1017		ki->ki_env = malloc(3);
1018		strcpy(ki->ki_env, "()");
1019	} else {
1020		ki->ki_env = NULL;
1021	}
1022}
1023
1024static int
1025pscomp(const void *a, const void *b)
1026{
1027	int i;
1028#define VSIZE(k) ((k)->ki_p->ki_dsize + (k)->ki_p->ki_ssize + \
1029		  (k)->ki_p->ki_tsize)
1030
1031	if (sortby == SORTCPU)
1032		return (getpcpu((const KINFO *)b) - getpcpu((const KINFO *)a));
1033	if (sortby == SORTMEM)
1034		return (VSIZE((const KINFO *)b) - VSIZE((const KINFO *)a));
1035	i =  (int)((const KINFO *)a)->ki_p->ki_tdev -
1036	    (int)((const KINFO *)b)->ki_p->ki_tdev;
1037	if (i == 0)
1038		i = ((const KINFO *)a)->ki_p->ki_pid -
1039		    ((const KINFO *)b)->ki_p->ki_pid;
1040	return (i);
1041}
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(char *s)
1056{
1057	int have_fmt;
1058	size_t len;
1059	char *newopts, *ns, *cp;
1060
1061	/*
1062	 * If we have an 'o' option, then note it, since we don't want to do
1063	 * some types of munging.
1064	 */
1065	have_fmt = index(s, 'o') != NULL;
1066
1067	len = strlen(s);
1068	if ((newopts = ns = malloc(len + 2)) == NULL)
1069		errx(1, "malloc failed");
1070	/*
1071	 * options begin with '-'
1072	 */
1073	if (*s != '-')
1074		*ns++ = '-';	/* add option flag */
1075	/*
1076	 * gaze to end of argv[1]
1077	 */
1078	cp = s + len - 1;
1079	/*
1080	 * if last letter is a 't' flag with no argument (in the context
1081	 * of the oldps options -- option string NOT starting with a '-' --
1082	 * then convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
1083	 *
1084	 * However, if a flag accepting a string argument is found in the
1085	 * option string, the remainder of the string is the argument to
1086	 * that flag; do not modify that argument.
1087	 */
1088	if (strcspn(s, "MNOoU") == len && *cp == 't' && *s != '-')
1089		*cp = 'T';
1090	else {
1091		/*
1092		 * otherwise check for trailing number, which *may* be a
1093		 * pid.
1094		 */
1095		while (cp >= s && isdigit(*cp))
1096			--cp;
1097	}
1098	cp++;
1099	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
1100	ns += cp - s;
1101	/*
1102	 * if there's a trailing number, and not a preceding 'p' (pid) or
1103	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
1104	 */
1105	if (isdigit(*cp) &&
1106	    (cp == s || (cp[-1] != 't' && cp[-1] != 'p')) &&
1107	    (cp - 1 == s || cp[-2] != 't') && !have_fmt)
1108		*ns++ = 'p';
1109	(void)strcpy(ns, cp);		/* and append the number */
1110
1111	return (newopts);
1112}
1113
1114static void
1115usage(void)
1116{
1117#define	SINGLE_OPTS	"[-aC" OPT_LAZY_f "HhjlmrSTuvwXxZ]"
1118
1119	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
1120	    "usage: ps " SINGLE_OPTS " [-G gid[,gid]] [-O|o fmt]",
1121	    "          [-p pid[,pid]] [-t tty[,tty]] [-U user[,user]]",
1122	    "          [-M core] [-N system]",
1123	    "       ps [-L]");
1124	exit(1);
1125}
1126