Home | History | Annotate | Line # | Download | only in ps
ps.c revision 1.78
      1  1.78     joerg /*	$NetBSD: ps.c,v 1.78 2012/05/07 13:14:31 joerg Exp $	*/
      2  1.13       cgd 
      3  1.40    simonb /*
      4  1.70       apb  * Copyright (c) 2000-2008 The NetBSD Foundation, Inc.
      5  1.40    simonb  * All rights reserved.
      6  1.40    simonb  *
      7  1.40    simonb  * This code is derived from software contributed to The NetBSD Foundation
      8  1.40    simonb  * by Simon Burge.
      9  1.40    simonb  *
     10  1.40    simonb  * Redistribution and use in source and binary forms, with or without
     11  1.40    simonb  * modification, are permitted provided that the following conditions
     12  1.40    simonb  * are met:
     13  1.40    simonb  * 1. Redistributions of source code must retain the above copyright
     14  1.40    simonb  *    notice, this list of conditions and the following disclaimer.
     15  1.40    simonb  * 2. Redistributions in binary form must reproduce the above copyright
     16  1.40    simonb  *    notice, this list of conditions and the following disclaimer in the
     17  1.40    simonb  *    documentation and/or other materials provided with the distribution.
     18  1.40    simonb  *
     19  1.40    simonb  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  1.40    simonb  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  1.40    simonb  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  1.40    simonb  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  1.40    simonb  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  1.40    simonb  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  1.40    simonb  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  1.40    simonb  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  1.40    simonb  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  1.40    simonb  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  1.40    simonb  * POSSIBILITY OF SUCH DAMAGE.
     30  1.40    simonb  */
     31  1.40    simonb 
     32  1.40    simonb /*
     33  1.11       cgd  * Copyright (c) 1990, 1993, 1994
     34  1.11       cgd  *	The Regents of the University of California.  All rights reserved.
     35   1.1       cgd  *
     36   1.1       cgd  * Redistribution and use in source and binary forms, with or without
     37   1.1       cgd  * modification, are permitted provided that the following conditions
     38   1.1       cgd  * are met:
     39   1.1       cgd  * 1. Redistributions of source code must retain the above copyright
     40   1.1       cgd  *    notice, this list of conditions and the following disclaimer.
     41   1.1       cgd  * 2. Redistributions in binary form must reproduce the above copyright
     42   1.1       cgd  *    notice, this list of conditions and the following disclaimer in the
     43   1.1       cgd  *    documentation and/or other materials provided with the distribution.
     44  1.50       agc  * 3. Neither the name of the University nor the names of its contributors
     45   1.1       cgd  *    may be used to endorse or promote products derived from this software
     46   1.1       cgd  *    without specific prior written permission.
     47   1.1       cgd  *
     48   1.1       cgd  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     49   1.1       cgd  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     50   1.1       cgd  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     51   1.1       cgd  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     52   1.1       cgd  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     53   1.1       cgd  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     54   1.1       cgd  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     55   1.1       cgd  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     56   1.1       cgd  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     57   1.1       cgd  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     58   1.1       cgd  * SUCH DAMAGE.
     59   1.1       cgd  */
     60   1.1       cgd 
     61  1.19  christos #include <sys/cdefs.h>
     62   1.1       cgd #ifndef lint
     63  1.69     lukem __COPYRIGHT("@(#) Copyright (c) 1990, 1993, 1994\
     64  1.69     lukem  The Regents of the University of California.  All rights reserved.");
     65   1.1       cgd #endif /* not lint */
     66   1.1       cgd 
     67   1.1       cgd #ifndef lint
     68  1.13       cgd #if 0
     69  1.11       cgd static char sccsid[] = "@(#)ps.c	8.4 (Berkeley) 4/2/94";
     70  1.13       cgd #else
     71  1.78     joerg __RCSID("$NetBSD: ps.c,v 1.78 2012/05/07 13:14:31 joerg Exp $");
     72  1.13       cgd #endif
     73   1.1       cgd #endif /* not lint */
     74   1.1       cgd 
     75   1.1       cgd #include <sys/param.h>
     76   1.1       cgd #include <sys/user.h>
     77   1.1       cgd #include <sys/time.h>
     78   1.1       cgd #include <sys/resource.h>
     79  1.48   thorpej #include <sys/lwp.h>
     80   1.1       cgd #include <sys/proc.h>
     81   1.1       cgd #include <sys/stat.h>
     82   1.1       cgd #include <sys/ioctl.h>
     83  1.11       cgd #include <sys/sysctl.h>
     84  1.11       cgd 
     85  1.49       dsl #include <stddef.h>
     86  1.11       cgd #include <ctype.h>
     87  1.11       cgd #include <err.h>
     88  1.11       cgd #include <errno.h>
     89  1.11       cgd #include <fcntl.h>
     90  1.11       cgd #include <kvm.h>
     91  1.17        pk #include <limits.h>
     92  1.68  christos #include <locale.h>
     93   1.1       cgd #include <nlist.h>
     94  1.11       cgd #include <paths.h>
     95  1.25   mycroft #include <pwd.h>
     96   1.1       cgd #include <stdio.h>
     97   1.1       cgd #include <stdlib.h>
     98   1.1       cgd #include <string.h>
     99  1.11       cgd #include <unistd.h>
    100  1.11       cgd 
    101   1.1       cgd #include "ps.h"
    102   1.1       cgd 
    103  1.40    simonb /*
    104  1.40    simonb  * ARGOPTS must contain all option characters that take arguments
    105  1.40    simonb  * (except for 't'!) - it is used in kludge_oldps_options()
    106  1.40    simonb  */
    107  1.70       apb #define	GETOPTSTR	"aAcCeghjk:LlM:mN:O:o:p:rSsTt:U:uvW:wx"
    108  1.49       dsl #define	ARGOPTS		"kMNOopUW"
    109  1.40    simonb 
    110  1.38    simonb struct kinfo_proc2 *kinfo;
    111  1.61       apb struct varlist displaylist = SIMPLEQ_HEAD_INITIALIZER(displaylist);
    112  1.61       apb struct varlist sortlist = SIMPLEQ_HEAD_INITIALIZER(sortlist);
    113   1.1       cgd 
    114   1.1       cgd int	eval;			/* exit value */
    115   1.1       cgd int	rawcpu;			/* -C */
    116   1.1       cgd int	sumrusage;		/* -S */
    117   1.1       cgd int	termwidth;		/* width of screen (0 == infinity) */
    118   1.1       cgd int	totwidth;		/* calculated width of requested variables */
    119   1.1       cgd 
    120  1.48   thorpej int	needcomm, needenv, commandonly;
    121  1.33    simonb uid_t	myuid;
    122   1.1       cgd 
    123  1.48   thorpej static struct kinfo_lwp
    124  1.52    simonb 		*pick_representative_lwp(struct kinfo_proc2 *,
    125  1.52    simonb 		    struct kinfo_lwp *, int);
    126  1.38    simonb static struct kinfo_proc2
    127  1.52    simonb 		*getkinfo_kvm(kvm_t *, int, int, int *);
    128  1.52    simonb static char	*kludge_oldps_options(char *);
    129  1.52    simonb static int	 pscomp(const void *, const void *);
    130  1.52    simonb static void	 scanvars(void);
    131  1.76     joerg __dead static void	 usage(void);
    132  1.60  christos static int	 parsenum(const char *, const char *);
    133  1.52    simonb int		 main(int, char *[]);
    134   1.1       cgd 
    135   1.1       cgd char dfmt[] = "pid tt state time command";
    136   1.1       cgd char jfmt[] = "user pid ppid pgid sess jobc state tt time command";
    137   1.1       cgd char lfmt[] = "uid pid ppid cpu pri nice vsz rss wchan state tt time command";
    138  1.53    simonb char sfmt[] = "uid pid ppid cpu lid nlwp pri nice vsz rss wchan lstate tt "
    139  1.53    simonb 		"time command";
    140   1.1       cgd char ufmt[] = "user pid %cpu %mem vsz rss tt state start time command";
    141  1.11       cgd char vfmt[] = "pid state time sl re pagein vsz rss lim tsiz %cpu %mem command";
    142  1.11       cgd 
    143  1.64      yamt const char *default_fmt = dfmt;
    144  1.64      yamt 
    145  1.61       apb struct varent *Opos = NULL; /* -O flag inserts after this point */
    146  1.61       apb 
    147  1.11       cgd kvm_t *kd;
    148   1.1       cgd 
    149  1.78     joerg static long long
    150  1.78     joerg ttyname2dev(const char *ttname, int *xflg, int *what)
    151  1.78     joerg {
    152  1.78     joerg 	struct stat sb;
    153  1.78     joerg 	const char *ttypath;
    154  1.78     joerg 	char pathbuf[MAXPATHLEN];
    155  1.78     joerg 
    156  1.78     joerg 	ttypath = NULL;
    157  1.78     joerg 	if (strcmp(ttname, "?") == 0) {
    158  1.78     joerg 		*xflg = 1;
    159  1.78     joerg 		return KERN_PROC_TTY_NODEV;
    160  1.78     joerg 	}
    161  1.78     joerg 	if (strcmp(ttname, "-") == 0)
    162  1.78     joerg 		return KERN_PROC_TTY_REVOKE;
    163  1.78     joerg 
    164  1.78     joerg 	if (strcmp(ttname, "co") == 0)
    165  1.78     joerg 		ttypath = _PATH_CONSOLE;
    166  1.78     joerg 	else if (strncmp(ttname, "pts/", 4) == 0 ||
    167  1.78     joerg 		strncmp(ttname, "tty", 3) == 0) {
    168  1.78     joerg 		(void)snprintf(pathbuf,
    169  1.78     joerg 		    sizeof(pathbuf), "%s%s", _PATH_DEV, ttname);
    170  1.78     joerg 		ttypath = pathbuf;
    171  1.78     joerg 	} else if (*ttname != '/') {
    172  1.78     joerg 		(void)snprintf(pathbuf,
    173  1.78     joerg 		    sizeof(pathbuf), "%s%s", _PATH_TTY, ttname);
    174  1.78     joerg 		ttypath = pathbuf;
    175  1.78     joerg 	} else
    176  1.78     joerg 		ttypath = ttname;
    177  1.78     joerg 	*what = KERN_PROC_TTY;
    178  1.78     joerg 	if (stat(ttypath, &sb) == -1) {
    179  1.78     joerg 		devmajor_t pts = getdevmajor("pts", S_IFCHR);
    180  1.78     joerg 
    181  1.78     joerg 		if (pts != NODEVMAJOR && strncmp(ttname, "pts/", 4) == 0) {
    182  1.78     joerg 			int ptsminor = atoi(ttname + 4);
    183  1.78     joerg 
    184  1.78     joerg 			snprintf(pathbuf, sizeof(pathbuf), "pts/%d", ptsminor);
    185  1.78     joerg 			if (strcmp(pathbuf, ttname) == 0 && ptsminor >= 0)
    186  1.78     joerg 				return makedev(pts, ptsminor);
    187  1.78     joerg 		}
    188  1.78     joerg 		err(1, "%s", ttypath);
    189  1.78     joerg 	}
    190  1.78     joerg 	if (!S_ISCHR(sb.st_mode))
    191  1.78     joerg 		errx(1, "%s: not a terminal", ttypath);
    192  1.78     joerg 	return sb.st_rdev;
    193  1.78     joerg }
    194  1.78     joerg 
    195  1.11       cgd int
    196  1.52    simonb main(int argc, char *argv[])
    197   1.1       cgd {
    198  1.11       cgd 	struct varent *vent;
    199   1.1       cgd 	struct winsize ws;
    200  1.48   thorpej 	struct kinfo_lwp *kl, *l;
    201  1.72  christos 	int ch, i, j, fmt, lineno, nentries, nlwps;
    202  1.72  christos 	long long flag;
    203  1.48   thorpej 	int prtheader, wflag, what, xflg, mode, showlwps;
    204  1.17        pk 	char *nlistf, *memf, *swapf, errbuf[_POSIX2_LINE_MAX];
    205  1.26       kim 	char *ttname;
    206   1.1       cgd 
    207  1.68  christos 	setprogname(argv[0]);
    208  1.68  christos 	(void)setlocale(LC_ALL, "");
    209  1.68  christos 
    210  1.38    simonb 	if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
    211  1.38    simonb 	     ioctl(STDERR_FILENO, TIOCGWINSZ, (char *)&ws) == -1 &&
    212  1.38    simonb 	     ioctl(STDIN_FILENO,  TIOCGWINSZ, (char *)&ws) == -1) ||
    213   1.1       cgd 	     ws.ws_col == 0)
    214   1.1       cgd 		termwidth = 79;
    215   1.1       cgd 	else
    216   1.1       cgd 		termwidth = ws.ws_col - 1;
    217   1.1       cgd 
    218   1.1       cgd 	if (argc > 1)
    219   1.1       cgd 		argv[1] = kludge_oldps_options(argv[1]);
    220   1.1       cgd 
    221  1.48   thorpej 	fmt = prtheader = wflag = xflg = showlwps = 0;
    222  1.25   mycroft 	what = KERN_PROC_UID;
    223  1.33    simonb 	flag = myuid = getuid();
    224   1.1       cgd 	memf = nlistf = swapf = NULL;
    225  1.39    simonb 	mode = PRINTMODE;
    226  1.40    simonb 	while ((ch = getopt(argc, argv, GETOPTSTR)) != -1)
    227   1.1       cgd 		switch((char)ch) {
    228  1.70       apb 		case 'A':
    229  1.70       apb 			/* "-A" shows all processes, like "-ax" */
    230  1.70       apb 			xflg = 1;
    231  1.70       apb 			/*FALLTHROUGH*/
    232   1.1       cgd 		case 'a':
    233  1.25   mycroft 			what = KERN_PROC_ALL;
    234  1.25   mycroft 			flag = 0;
    235   1.1       cgd 			break;
    236  1.12   mycroft 		case 'c':
    237  1.12   mycroft 			commandonly = 1;
    238  1.12   mycroft 			break;
    239  1.11       cgd 		case 'e':			/* XXX set ufmt */
    240  1.11       cgd 			needenv = 1;
    241  1.11       cgd 			break;
    242   1.1       cgd 		case 'C':
    243   1.1       cgd 			rawcpu = 1;
    244   1.1       cgd 			break;
    245   1.1       cgd 		case 'g':
    246  1.11       cgd 			break;			/* no-op */
    247   1.1       cgd 		case 'h':
    248   1.1       cgd 			prtheader = ws.ws_row > 5 ? ws.ws_row : 22;
    249   1.1       cgd 			break;
    250   1.1       cgd 		case 'j':
    251   1.1       cgd 			parsefmt(jfmt);
    252  1.15   mycroft 			fmt = 1;
    253   1.1       cgd 			jfmt[0] = '\0';
    254   1.1       cgd 			break;
    255  1.49       dsl 		case 'k':
    256  1.49       dsl 			parsesort(optarg);
    257  1.49       dsl 			break;
    258  1.28  bgrayson 		case 'K':
    259  1.47  jdolecek 			break;			/* no-op - was dontuseprocfs */
    260  1.11       cgd 		case 'L':
    261   1.1       cgd 			showkey();
    262   1.1       cgd 			exit(0);
    263  1.23   mycroft 			/* NOTREACHED */
    264   1.1       cgd 		case 'l':
    265   1.1       cgd 			parsefmt(lfmt);
    266  1.15   mycroft 			fmt = 1;
    267   1.1       cgd 			lfmt[0] = '\0';
    268   1.1       cgd 			break;
    269   1.1       cgd 		case 'M':
    270   1.1       cgd 			memf = optarg;
    271   1.1       cgd 			break;
    272   1.1       cgd 		case 'm':
    273  1.49       dsl 			parsesort("vsz");
    274   1.1       cgd 			break;
    275   1.1       cgd 		case 'N':
    276   1.1       cgd 			nlistf = optarg;
    277   1.1       cgd 			break;
    278   1.1       cgd 		case 'O':
    279  1.61       apb 			/*
    280  1.61       apb 			 * If this is not the first -O option, insert
    281  1.61       apb 			 * just after the previous one.
    282  1.61       apb 			 *
    283  1.61       apb 			 * If there is no format yet, start with the default
    284  1.61       apb 			 * format, and insert after the pid column.
    285  1.61       apb 			 *
    286  1.61       apb 			 * If there is already a format, insert after
    287  1.61       apb 			 * the pid column, or at the end if there's no
    288  1.61       apb 			 * pid column.
    289  1.61       apb 			 */
    290  1.61       apb 			if (!Opos) {
    291  1.61       apb 				if (!fmt)
    292  1.64      yamt 					parsefmt(default_fmt);
    293  1.61       apb 				Opos = varlist_find(&displaylist, "pid");
    294  1.61       apb 			}
    295  1.61       apb 			parsefmt_insert(optarg, &Opos);
    296  1.15   mycroft 			fmt = 1;
    297   1.1       cgd 			break;
    298   1.1       cgd 		case 'o':
    299   1.1       cgd 			parsefmt(optarg);
    300  1.15   mycroft 			fmt = 1;
    301   1.1       cgd 			break;
    302   1.1       cgd 		case 'p':
    303  1.25   mycroft 			what = KERN_PROC_PID;
    304  1.60  christos 			flag = parsenum(optarg, "process id");
    305   1.1       cgd 			xflg = 1;
    306   1.1       cgd 			break;
    307   1.1       cgd 		case 'r':
    308  1.49       dsl 			parsesort("%cpu");
    309   1.1       cgd 			break;
    310   1.1       cgd 		case 'S':
    311   1.1       cgd 			sumrusage = 1;
    312   1.1       cgd 			break;
    313  1.48   thorpej 		case 's':
    314  1.48   thorpej 			/* -L was already taken... */
    315  1.48   thorpej 			showlwps = 1;
    316  1.64      yamt 			default_fmt = sfmt;
    317  1.48   thorpej 			break;
    318   1.1       cgd 		case 'T':
    319  1.22   mycroft 			if ((ttname = ttyname(STDIN_FILENO)) == NULL)
    320  1.11       cgd 				errx(1, "stdin: not a terminal");
    321  1.78     joerg 			flag = ttyname2dev(ttname, &xflg, &what);
    322  1.78     joerg 			break;
    323  1.22   mycroft 		case 't':
    324  1.78     joerg 			flag = ttyname2dev(optarg, &xflg, &what);
    325   1.1       cgd 			break;
    326  1.25   mycroft 		case 'U':
    327  1.25   mycroft 			if (*optarg != '\0') {
    328  1.25   mycroft 				struct passwd *pw;
    329  1.25   mycroft 
    330  1.25   mycroft 				what = KERN_PROC_UID;
    331  1.25   mycroft 				pw = getpwnam(optarg);
    332  1.25   mycroft 				if (pw == NULL) {
    333  1.60  christos 					flag = parsenum(optarg, "user name");
    334  1.25   mycroft 				} else
    335  1.25   mycroft 					flag = pw->pw_uid;
    336  1.25   mycroft 			}
    337  1.25   mycroft 			break;
    338   1.1       cgd 		case 'u':
    339   1.1       cgd 			parsefmt(ufmt);
    340  1.49       dsl 			parsesort("%cpu");
    341  1.15   mycroft 			fmt = 1;
    342   1.1       cgd 			ufmt[0] = '\0';
    343   1.1       cgd 			break;
    344   1.1       cgd 		case 'v':
    345   1.1       cgd 			parsefmt(vfmt);
    346  1.49       dsl 			parsesort("vsz");
    347  1.15   mycroft 			fmt = 1;
    348   1.1       cgd 			vfmt[0] = '\0';
    349   1.1       cgd 			break;
    350   1.1       cgd 		case 'W':
    351   1.1       cgd 			swapf = optarg;
    352   1.1       cgd 			break;
    353   1.1       cgd 		case 'w':
    354   1.6       cgd 			if (wflag)
    355   1.6       cgd 				termwidth = UNLIMITED;
    356   1.6       cgd 			else if (termwidth < 131)
    357   1.1       cgd 				termwidth = 131;
    358  1.11       cgd 			wflag++;
    359   1.1       cgd 			break;
    360   1.1       cgd 		case 'x':
    361   1.1       cgd 			xflg = 1;
    362   1.1       cgd 			break;
    363   1.1       cgd 		case '?':
    364   1.1       cgd 		default:
    365   1.1       cgd 			usage();
    366   1.1       cgd 		}
    367   1.1       cgd 	argc -= optind;
    368   1.1       cgd 	argv += optind;
    369   1.1       cgd 
    370   1.1       cgd #define	BACKWARD_COMPATIBILITY
    371   1.1       cgd #ifdef	BACKWARD_COMPATIBILITY
    372   1.1       cgd 	if (*argv) {
    373   1.1       cgd 		nlistf = *argv;
    374   1.1       cgd 		if (*++argv) {
    375   1.1       cgd 			memf = *argv;
    376   1.1       cgd 			if (*++argv)
    377   1.1       cgd 				swapf = *argv;
    378   1.1       cgd 		}
    379   1.1       cgd 	}
    380   1.1       cgd #endif
    381  1.11       cgd 
    382  1.49       dsl 	if (memf == NULL) {
    383  1.49       dsl 		kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
    384  1.38    simonb 		donlist_sysctl();
    385  1.38    simonb 	} else
    386  1.38    simonb 		kd = kvm_openfiles(nlistf, memf, swapf, O_RDONLY, errbuf);
    387  1.52    simonb 
    388  1.47  jdolecek 	if (kd == 0)
    389  1.47  jdolecek 		errx(1, "%s", errbuf);
    390  1.21       mrg 
    391  1.15   mycroft 	if (!fmt)
    392  1.64      yamt 		parsefmt(default_fmt);
    393   1.1       cgd 
    394  1.49       dsl 	/* Add default sort criteria */
    395  1.49       dsl 	parsesort("tdev,pid");
    396  1.61       apb 	SIMPLEQ_FOREACH(vent, &sortlist, next) {
    397  1.49       dsl 		if (vent->var->flag & LWP || vent->var->type == UNSPECIFIED)
    398  1.49       dsl 			warnx("Cannot sort on %s, sort key ignored\n",
    399  1.49       dsl 				vent->var->name);
    400  1.49       dsl 	}
    401  1.49       dsl 
    402   1.1       cgd 	/*
    403  1.39    simonb 	 * scan requested variables, noting what structures are needed.
    404   1.1       cgd 	 */
    405   1.1       cgd 	scanvars();
    406  1.29  jdolecek 
    407   1.1       cgd 	/*
    408   1.1       cgd 	 * select procs
    409   1.1       cgd 	 */
    410  1.48   thorpej 	if (!(kinfo = getkinfo_kvm(kd, what, flag, &nentries)))
    411  1.48   thorpej 		err(1, "%s", kvm_geterr(kd));
    412  1.39    simonb 	if (nentries == 0) {
    413  1.39    simonb 		printheader();
    414  1.42     cyber 		exit(1);
    415  1.39    simonb 	}
    416   1.1       cgd 	/*
    417   1.1       cgd 	 * sort proc list
    418   1.1       cgd 	 */
    419  1.38    simonb 	qsort(kinfo, nentries, sizeof(struct kinfo_proc2), pscomp);
    420   1.1       cgd 	/*
    421  1.39    simonb 	 * For each proc, call each variable output function in
    422  1.39    simonb 	 * "setwidth" mode to determine the widest element of
    423  1.39    simonb 	 * the column.
    424  1.39    simonb 	 */
    425  1.39    simonb 	if (mode == PRINTMODE)
    426  1.39    simonb 		for (i = 0; i < nentries; i++) {
    427  1.39    simonb 			struct kinfo_proc2 *ki = &kinfo[i];
    428  1.39    simonb 
    429  1.72  christos 			if (xflg == 0 && (ki->p_tdev == (uint32_t)NODEV ||
    430  1.63     pavel 			    (ki->p_flag & P_CONTROLT) == 0))
    431  1.39    simonb 				continue;
    432  1.48   thorpej 
    433  1.48   thorpej 			kl = kvm_getlwps(kd, ki->p_pid, ki->p_paddr,
    434  1.48   thorpej 			    sizeof(struct kinfo_lwp), &nlwps);
    435  1.48   thorpej 			if (kl == 0)
    436  1.48   thorpej 				nlwps = 0;
    437  1.48   thorpej 			if (showlwps == 0) {
    438  1.48   thorpej 				l = pick_representative_lwp(ki, kl, nlwps);
    439  1.61       apb 				SIMPLEQ_FOREACH(vent, &displaylist, next)
    440  1.48   thorpej 					OUTPUT(vent, ki, l, WIDTHMODE);
    441  1.48   thorpej 			} else {
    442  1.48   thorpej 				/* The printing is done with the loops
    443  1.48   thorpej 				 * reversed, but here we don't need that,
    444  1.48   thorpej 				 * and this improves the code locality a bit.
    445  1.48   thorpej 				 */
    446  1.61       apb 				SIMPLEQ_FOREACH(vent, &displaylist, next)
    447  1.48   thorpej 					for (j = 0; j < nlwps; j++)
    448  1.52    simonb 						OUTPUT(vent, ki, &kl[j],
    449  1.48   thorpej 						    WIDTHMODE);
    450  1.48   thorpej 			}
    451  1.39    simonb 		}
    452  1.39    simonb 	/*
    453  1.39    simonb 	 * Print header - AFTER determining process field widths.
    454  1.39    simonb 	 * printheader() also adds up the total width of all
    455  1.39    simonb 	 * fields the first time it's called.
    456  1.39    simonb 	 */
    457  1.39    simonb 	printheader();
    458  1.39    simonb 	/*
    459  1.39    simonb 	 * For each proc, call each variable output function in
    460  1.39    simonb 	 * print mode.
    461   1.1       cgd 	 */
    462   1.1       cgd 	for (i = lineno = 0; i < nentries; i++) {
    463  1.38    simonb 		struct kinfo_proc2 *ki = &kinfo[i];
    464  1.14   mycroft 
    465  1.72  christos 		if (xflg == 0 && (ki->p_tdev == (uint32_t)NODEV ||
    466  1.63     pavel 		    (ki->p_flag & P_CONTROLT ) == 0))
    467   1.1       cgd 			continue;
    468  1.48   thorpej 		kl = kvm_getlwps(kd, ki->p_pid, (u_long)ki->p_paddr,
    469  1.48   thorpej 		    sizeof(struct kinfo_lwp), &nlwps);
    470  1.48   thorpej 		if (kl == 0)
    471  1.48   thorpej 			nlwps = 0;
    472  1.48   thorpej 		if (showlwps == 0) {
    473  1.48   thorpej 			l = pick_representative_lwp(ki, kl, nlwps);
    474  1.61       apb 			SIMPLEQ_FOREACH(vent, &displaylist, next) {
    475  1.48   thorpej 				OUTPUT(vent, ki, l, mode);
    476  1.61       apb 				if (SIMPLEQ_NEXT(vent, next) != NULL)
    477  1.48   thorpej 					(void)putchar(' ');
    478  1.48   thorpej 			}
    479  1.11       cgd 			(void)putchar('\n');
    480  1.48   thorpej 			if (prtheader && lineno++ == prtheader - 4) {
    481  1.48   thorpej 				(void)putchar('\n');
    482  1.48   thorpej 				printheader();
    483  1.48   thorpej 				lineno = 0;
    484  1.48   thorpej 			}
    485  1.48   thorpej 		} else {
    486  1.48   thorpej 			for (j = 0; j < nlwps; j++) {
    487  1.61       apb 				SIMPLEQ_FOREACH(vent, &displaylist, next) {
    488  1.48   thorpej 					OUTPUT(vent, ki, &kl[j], mode);
    489  1.61       apb 					if (SIMPLEQ_NEXT(vent, next) != NULL)
    490  1.48   thorpej 						(void)putchar(' ');
    491  1.48   thorpej 				}
    492  1.48   thorpej 				(void)putchar('\n');
    493  1.48   thorpej 				if (prtheader && lineno++ == prtheader - 4) {
    494  1.48   thorpej 					(void)putchar('\n');
    495  1.48   thorpej 					printheader();
    496  1.48   thorpej 					lineno = 0;
    497  1.48   thorpej 				}
    498  1.48   thorpej 			}
    499   1.1       cgd 		}
    500   1.1       cgd 	}
    501   1.1       cgd 	exit(eval);
    502  1.23   mycroft 	/* NOTREACHED */
    503   1.1       cgd }
    504   1.1       cgd 
    505  1.48   thorpej static struct kinfo_lwp *
    506  1.52    simonb pick_representative_lwp(struct kinfo_proc2 *ki, struct kinfo_lwp *kl, int nlwps)
    507  1.48   thorpej {
    508  1.48   thorpej 	int i, onproc, running, sleeping, stopped, suspended;
    509  1.48   thorpej 	static struct kinfo_lwp zero_lwp;
    510  1.48   thorpej 
    511  1.48   thorpej 	if (kl == 0)
    512  1.48   thorpej 		return &zero_lwp;
    513  1.52    simonb 
    514  1.48   thorpej 	/* Trivial case: only one LWP */
    515  1.48   thorpej 	if (nlwps == 1)
    516  1.48   thorpej 		return kl;
    517  1.48   thorpej 
    518  1.48   thorpej 	switch (ki->p_realstat) {
    519  1.48   thorpej 	case SSTOP:
    520  1.48   thorpej 	case SACTIVE:
    521  1.48   thorpej 		/* Pick the most live LWP */
    522  1.48   thorpej 		onproc = running = sleeping = stopped = suspended = -1;
    523  1.48   thorpej 		for (i = 0; i < nlwps; i++) {
    524  1.48   thorpej 			switch (kl[i].l_stat) {
    525  1.48   thorpej 			case LSONPROC:
    526  1.48   thorpej 				onproc = i;
    527  1.48   thorpej 				break;
    528  1.48   thorpej 			case LSRUN:
    529  1.48   thorpej 				running = i;
    530  1.48   thorpej 				break;
    531  1.48   thorpej 			case LSSLEEP:
    532  1.48   thorpej 				sleeping = i;
    533  1.48   thorpej 				break;
    534  1.48   thorpej 			case LSSTOP:
    535  1.48   thorpej 				stopped = i;
    536  1.48   thorpej 				break;
    537  1.48   thorpej 			case LSSUSPENDED:
    538  1.48   thorpej 				suspended = i;
    539  1.48   thorpej 				break;
    540  1.48   thorpej 			}
    541  1.48   thorpej 		}
    542  1.48   thorpej 		if (onproc != -1)
    543  1.48   thorpej 			return &kl[onproc];
    544  1.48   thorpej 		if (running != -1)
    545  1.48   thorpej 			return &kl[running];
    546  1.48   thorpej 		if (sleeping != -1)
    547  1.48   thorpej 			return &kl[sleeping];
    548  1.48   thorpej 		if (stopped != -1)
    549  1.48   thorpej 			return &kl[stopped];
    550  1.48   thorpej 		if (suspended != -1)
    551  1.48   thorpej 			return &kl[suspended];
    552  1.48   thorpej 		break;
    553  1.48   thorpej 	case SZOMB:
    554  1.48   thorpej 		/* First will do */
    555  1.48   thorpej 		return kl;
    556  1.48   thorpej 		break;
    557  1.48   thorpej 	}
    558  1.48   thorpej 	/* Error condition! */
    559  1.48   thorpej 	warnx("Inconsistent LWP state for process %d\n", ki->p_pid);
    560  1.48   thorpej 	return kl;
    561  1.48   thorpej }
    562  1.52    simonb 
    563  1.48   thorpej 
    564  1.38    simonb static struct kinfo_proc2 *
    565  1.52    simonb getkinfo_kvm(kvm_t *kdp, int what, int flag, int *nentriesp)
    566  1.29  jdolecek {
    567  1.52    simonb 
    568  1.45     lukem 	return (kvm_getproc2(kdp, what, flag, sizeof(struct kinfo_proc2),
    569  1.38    simonb 	    nentriesp));
    570  1.29  jdolecek }
    571  1.29  jdolecek 
    572  1.11       cgd static void
    573  1.52    simonb scanvars(void)
    574   1.1       cgd {
    575  1.11       cgd 	struct varent *vent;
    576  1.11       cgd 	VAR *v;
    577   1.1       cgd 
    578  1.61       apb 	SIMPLEQ_FOREACH(vent, &displaylist, next) {
    579   1.1       cgd 		v = vent->var;
    580  1.43      matt 		if (v->flag & COMM) {
    581   1.1       cgd 			needcomm = 1;
    582  1.43      matt 			break;
    583  1.43      matt 		}
    584   1.1       cgd 	}
    585  1.11       cgd }
    586   1.1       cgd 
    587  1.11       cgd static int
    588  1.49       dsl pscomp(const void *a, const void *b)
    589   1.1       cgd {
    590  1.59  christos 	const struct kinfo_proc2 *ka = (const struct kinfo_proc2 *)a;
    591  1.59  christos 	const struct kinfo_proc2 *kb = (const struct kinfo_proc2 *)b;
    592  1.38    simonb 
    593   1.1       cgd 	int i;
    594  1.49       dsl 	int64_t i64;
    595  1.49       dsl 	VAR *v;
    596  1.49       dsl 	struct varent *ve;
    597  1.59  christos 	const sigset_t *sa, *sb;
    598  1.49       dsl 
    599  1.74       mrg #define	V_SIZE(k) ((k)->p_vm_msize)
    600  1.54    simonb #define	RDIFF_N(t, n) \
    601  1.59  christos 	if (((const t *)((const char *)ka + v->off))[n] > ((const t *)((const char *)kb + v->off))[n]) \
    602  1.49       dsl 		return 1; \
    603  1.59  christos 	if (((const t *)((const char *)ka + v->off))[n] < ((const t *)((const char *)kb + v->off))[n]) \
    604  1.49       dsl 		return -1;
    605  1.49       dsl 
    606  1.54    simonb #define	RDIFF(type) RDIFF_N(type, 0); continue
    607  1.49       dsl 
    608  1.61       apb 	SIMPLEQ_FOREACH(ve, &sortlist, next) {
    609  1.49       dsl 		v = ve->var;
    610  1.49       dsl 		if (v->flag & LWP)
    611  1.49       dsl 			/* LWP structure not available (yet) */
    612  1.49       dsl 			continue;
    613  1.49       dsl 		/* Sort on pvar() fields, + a few others */
    614  1.49       dsl 		switch (v->type) {
    615  1.49       dsl 		case CHAR:
    616  1.49       dsl 			RDIFF(char);
    617  1.49       dsl 		case UCHAR:
    618  1.49       dsl 			RDIFF(u_char);
    619  1.49       dsl 		case SHORT:
    620  1.49       dsl 			RDIFF(short);
    621  1.49       dsl 		case USHORT:
    622  1.49       dsl 			RDIFF(ushort);
    623  1.49       dsl 		case INT:
    624  1.49       dsl 			RDIFF(int);
    625  1.49       dsl 		case UINT:
    626  1.49       dsl 			RDIFF(uint);
    627  1.49       dsl 		case LONG:
    628  1.49       dsl 			RDIFF(long);
    629  1.49       dsl 		case ULONG:
    630  1.49       dsl 			RDIFF(ulong);
    631  1.49       dsl 		case INT32:
    632  1.49       dsl 			RDIFF(int32_t);
    633  1.49       dsl 		case UINT32:
    634  1.49       dsl 			RDIFF(uint32_t);
    635  1.49       dsl 		case SIGLIST:
    636  1.59  christos 			sa = (const void *)((const char *)a + v->off);
    637  1.59  christos 			sb = (const void *)((const char *)b + v->off);
    638  1.49       dsl 			i = 0;
    639  1.49       dsl 			do {
    640  1.49       dsl 				if (sa->__bits[i] > sb->__bits[i])
    641  1.49       dsl 					return 1;
    642  1.49       dsl 				if (sa->__bits[i] < sb->__bits[i])
    643  1.49       dsl 					return -1;
    644  1.49       dsl 				i++;
    645  1.73     lukem 			} while (i < (int)__arraycount(sa->__bits));
    646  1.49       dsl 			continue;
    647  1.49       dsl 		case INT64:
    648  1.49       dsl 			RDIFF(int64_t);
    649  1.49       dsl 		case KPTR:
    650  1.49       dsl 		case KPTR24:
    651  1.49       dsl 		case UINT64:
    652  1.49       dsl 			RDIFF(uint64_t);
    653  1.49       dsl 		case TIMEVAL:
    654  1.49       dsl 			/* compare xxx_sec then xxx_usec */
    655  1.49       dsl 			RDIFF_N(uint32_t, 0);
    656  1.49       dsl 			RDIFF_N(uint32_t, 1);
    657  1.49       dsl 			continue;
    658  1.49       dsl 		case CPUTIME:
    659  1.49       dsl 			i64 = ka->p_rtime_sec * 1000000 + ka->p_rtime_usec;
    660  1.49       dsl 			i64 -= kb->p_rtime_sec * 1000000 + kb->p_rtime_usec;
    661  1.49       dsl 			if (sumrusage) {
    662  1.49       dsl 				i64 += ka->p_uctime_sec * 1000000
    663  1.49       dsl 				    + ka->p_uctime_usec;
    664  1.49       dsl 				i64 -= kb->p_uctime_sec * 1000000
    665  1.49       dsl 				    + kb->p_uctime_usec;
    666  1.49       dsl 			}
    667  1.49       dsl 			if (i64 != 0)
    668  1.49       dsl 				return i64 > 0 ? 1 : -1;
    669  1.49       dsl 			continue;
    670  1.49       dsl 		case PCPU:
    671  1.49       dsl 			i = getpcpu(kb) - getpcpu(ka);
    672  1.49       dsl 			if (i != 0)
    673  1.49       dsl 				return i;
    674  1.49       dsl 			continue;
    675  1.49       dsl 		case VSIZE:
    676  1.49       dsl 			i = V_SIZE(kb) - V_SIZE(ka);
    677  1.49       dsl 			if (i != 0)
    678  1.49       dsl 				return i;
    679  1.49       dsl 			continue;
    680  1.49       dsl 
    681  1.49       dsl 		default:
    682  1.49       dsl 			/* Ignore everything else */
    683  1.49       dsl 			break;
    684  1.49       dsl 		}
    685  1.49       dsl 	}
    686  1.49       dsl 	return 0;
    687   1.1       cgd 
    688  1.49       dsl #undef VSIZE
    689   1.1       cgd }
    690   1.1       cgd 
    691   1.1       cgd /*
    692   1.1       cgd  * ICK (all for getopt), would rather hide the ugliness
    693   1.1       cgd  * here than taint the main code.
    694   1.1       cgd  *
    695   1.1       cgd  *  ps foo -> ps -foo
    696   1.1       cgd  *  ps 34 -> ps -p34
    697   1.1       cgd  *
    698  1.25   mycroft  * The old convention that 't' with no trailing tty arg means the user's
    699   1.1       cgd  * tty, is only supported if argv[1] doesn't begin with a '-'.  This same
    700   1.1       cgd  * feature is available with the option 'T', which takes no argument.
    701   1.1       cgd  */
    702  1.11       cgd static char *
    703  1.52    simonb kludge_oldps_options(char *s)
    704   1.1       cgd {
    705   1.1       cgd 	size_t len;
    706   1.1       cgd 	char *newopts, *ns, *cp;
    707   1.1       cgd 
    708   1.1       cgd 	len = strlen(s);
    709  1.16   thorpej 	if ((newopts = ns = malloc(len + 3)) == NULL)
    710  1.32  drochner 		err(1, NULL);
    711   1.1       cgd 	/*
    712   1.1       cgd 	 * options begin with '-'
    713   1.1       cgd 	 */
    714   1.1       cgd 	if (*s != '-')
    715   1.1       cgd 		*ns++ = '-';	/* add option flag */
    716   1.1       cgd 	/*
    717   1.1       cgd 	 * gaze to end of argv[1]
    718   1.1       cgd 	 */
    719   1.1       cgd 	cp = s + len - 1;
    720   1.1       cgd 	/*
    721  1.40    simonb 	 * if the last letter is a 't' flag and there are no other option
    722  1.40    simonb 	 * characters that take arguments (eg U, p, o) in the option
    723  1.40    simonb 	 * string and the option string doesn't start with a '-' then
    724  1.40    simonb 	 * convert to 'T' (meaning *this* terminal, i.e. ttyname(0)).
    725   1.1       cgd 	 */
    726  1.40    simonb 	if (*cp == 't' && *s != '-' && strpbrk(s, ARGOPTS) == NULL)
    727   1.1       cgd 		*cp = 'T';
    728   1.1       cgd 	else {
    729   1.1       cgd 		/*
    730   1.1       cgd 		 * otherwise check for trailing number, which *may* be a
    731   1.1       cgd 		 * pid.
    732   1.1       cgd 		 */
    733  1.55       dsl 		while (cp >= s && isdigit((unsigned char)*cp))
    734   1.1       cgd 			--cp;
    735   1.1       cgd 	}
    736   1.1       cgd 	cp++;
    737  1.11       cgd 	memmove(ns, s, (size_t)(cp - s));	/* copy up to trailing number */
    738   1.1       cgd 	ns += cp - s;
    739   1.1       cgd 	/*
    740   1.1       cgd 	 * if there's a trailing number, and not a preceding 'p' (pid) or
    741   1.1       cgd 	 * 't' (tty) flag, then assume it's a pid and insert a 'p' flag.
    742   1.1       cgd 	 */
    743  1.55       dsl 	if (isdigit((unsigned char)*cp) &&
    744  1.25   mycroft 	    (cp == s || (cp[-1] != 'U' && cp[-1] != 't' && cp[-1] != 'p' &&
    745  1.56    atatat 	    cp[-1] != '/' && (cp - 1 == s || cp[-2] != 't'))))
    746   1.1       cgd 		*ns++ = 'p';
    747  1.18       mrg 	/* and append the number */
    748  1.40    simonb 	(void)strcpy(ns, cp);		/* XXX strcpy is safe here */
    749   1.1       cgd 
    750   1.1       cgd 	return (newopts);
    751   1.1       cgd }
    752   1.1       cgd 
    753  1.60  christos static int
    754  1.60  christos parsenum(const char *str, const char *msg)
    755  1.60  christos {
    756  1.60  christos 	char *ep;
    757  1.60  christos 	unsigned long ul;
    758  1.60  christos 
    759  1.60  christos 	ul = strtoul(str, &ep, 0);
    760  1.60  christos 
    761  1.60  christos 	if (*str == '\0' || *ep != '\0')
    762  1.60  christos 		errx(1, "Invalid %s: `%s'", msg, str);
    763  1.60  christos 
    764  1.60  christos 	if (ul > INT_MAX)
    765  1.60  christos 		errx(1, "Out of range %s: `%s'", msg, str);
    766  1.60  christos 
    767  1.60  christos 	return (int)ul;
    768  1.60  christos }
    769  1.60  christos 
    770  1.11       cgd static void
    771  1.52    simonb usage(void)
    772   1.1       cgd {
    773   1.1       cgd 
    774  1.11       cgd 	(void)fprintf(stderr,
    775  1.11       cgd 	    "usage:\t%s\n\t   %s\n\t%s\n",
    776  1.71       wiz 	    "ps [-AaCcehjlmrSsTuvwx] [-k key] [-M core] [-N system] [-O fmt]",
    777  1.77       wiz 	    "[-o fmt] [-p pid] [-t tty] [-U user] [-W swap]",
    778  1.71       wiz 	    "ps -L");
    779   1.1       cgd 	exit(1);
    780  1.23   mycroft 	/* NOTREACHED */
    781   1.1       cgd }
    782