xref: /freebsd/usr.bin/procstat/procstat.c (revision 833a452e9f082a7982a31c21f0da437dbbe0a39d)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2007, 2011 Robert N. M. Watson
5  * Copyright (c) 2015 Allan Jude <allanjude@freebsd.org>
6  * Copyright (c) 2017 Dell EMC
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/param.h>
35 #include <sys/sysctl.h>
36 #include <sys/user.h>
37 
38 #include <err.h>
39 #include <libprocstat.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <sysexits.h>
44 #include <unistd.h>
45 
46 #include "procstat.h"
47 
48 enum {
49 	PS_CMP_NORMAL = 0x00,
50 	PS_CMP_PLURAL = 0x01,
51 	PS_CMP_SUBSTR = 0x02
52 };
53 
54 struct procstat_cmd {
55 	const char *command;
56 	const char *xocontainer;
57 	const char *usage;
58 	void (*cmd)(struct procstat *, struct kinfo_proc *);
59 	void (*opt)(int, char * const *);
60 	int cmp;
61 };
62 
63 int procstat_opts = 0;
64 
65 static void cmdopt_none(int argc, char * const argv[]);
66 static void cmdopt_verbose(int argc, char * const argv[]);
67 static void cmdopt_signals(int argc, char * const argv[]);
68 static void cmdopt_rusage(int argc, char * const argv[]);
69 static void cmdopt_files(int argc, char * const argv[]);
70 static void cmdopt_cpuset(int argc, char * const argv[]);
71 
72 static const char *progname;
73 
74 /* aliased program parameters and arguments
75  * - usage field is abused to hold the pointer to the function
76  *   displaying program usage
77  */
78 static const struct procstat_cmd pacmd_table[] = {
79 	/* arguments are the same as for pwdx: pid or core file */
80 	{ "pargs", "args", NULL, &procstat_pargs, &cmdopt_none,
81 	    PS_CMP_NORMAL | PS_MODE_COMPAT },
82 	{ "penv", "env", NULL, &procstat_penv, &cmdopt_none,
83 	    PS_CMP_NORMAL | PS_MODE_COMPAT },
84 	{ "pwdx", "pwd", NULL, &procstat_pwdx, &cmdopt_none,
85 	    PS_CMP_NORMAL | PS_MODE_COMPAT }
86 };
87 
88 /* procstat parameters and arguments */
89 static const struct procstat_cmd cmd_table[] = {
90 	{ "argument", "arguments", NULL, &procstat_args, &cmdopt_none,
91 	    PS_CMP_PLURAL | PS_CMP_SUBSTR },
92 	{ "auxv", "auxv", NULL, &procstat_auxv, &cmdopt_none, PS_CMP_NORMAL },
93 	{ "basic", "basic", NULL, &procstat_basic, &cmdopt_none,
94 	    PS_CMP_NORMAL },
95 	{ "binary", "binary", NULL, &procstat_bin, &cmdopt_none,
96 	    PS_CMP_SUBSTR },
97 	{ "cpuset", "cs", NULL, &procstat_cs, &cmdopt_cpuset, PS_CMP_NORMAL },
98 	{ "cs", "cs", NULL, &procstat_cs, &cmdopt_cpuset, PS_CMP_NORMAL },
99 	{ "credential", "credentials", NULL, &procstat_cred, &cmdopt_none,
100 	    PS_CMP_PLURAL | PS_CMP_SUBSTR },
101 	{ "environment", "environment", NULL, &procstat_env, &cmdopt_none,
102 	    PS_CMP_SUBSTR },
103 	{ "fd", "files", "[-C]", &procstat_files, &cmdopt_files,
104 	    PS_CMP_PLURAL },
105 	{ "file", "files", "[-C]", &procstat_files, &cmdopt_files,
106 	    PS_CMP_PLURAL },
107 	{ "kstack", "kstack", "[-v]", &procstat_kstack, &cmdopt_verbose,
108 	    PS_CMP_NORMAL },
109 	{ "pargs", "args", NULL, &procstat_pargs, &cmdopt_none,
110 	    PS_CMP_NORMAL },
111 	{ "penv", "env", NULL, &procstat_penv, &cmdopt_none,
112 	    PS_CMP_NORMAL },
113 	{ "ptlwpinfo", "ptlwpinfo", NULL, &procstat_ptlwpinfo, &cmdopt_none,
114 	    PS_CMP_NORMAL },
115 	{ "pwdx", "pwd", NULL, &procstat_pwdx, &cmdopt_none,
116 	    PS_CMP_NORMAL },
117 	{ "rlimit", "rlimit", NULL, &procstat_rlimit, &cmdopt_none,
118 	    PS_CMP_NORMAL },
119 	{ "rusage", "rusage", "[-Ht]", &procstat_rusage, &cmdopt_rusage,
120 	    PS_CMP_NORMAL },
121 	{ "sigfastblock", "sigfastblock", NULL, &procstat_sigfastblock,
122 	    &cmdopt_none, PS_CMP_NORMAL },
123 	{ "signal", "signals", "[-n]", &procstat_sigs, &cmdopt_signals,
124 	    PS_CMP_PLURAL | PS_CMP_SUBSTR },
125 	{ "thread", "threads", NULL, &procstat_threads, &cmdopt_none,
126 	    PS_CMP_PLURAL },
127 	{ "tsignal", "thread_signals", "[-n]", &procstat_threads_sigs,
128 	    &cmdopt_signals, PS_CMP_PLURAL | PS_CMP_SUBSTR },
129 	{ "vm", "vm", NULL, &procstat_vm, &cmdopt_none, PS_CMP_NORMAL }
130 };
131 
132 static void
133 usage(const struct procstat_cmd *cmd)
134 {
135 	size_t i, l;
136 	int multi;
137 
138 	if (cmd == NULL || (cmd->cmp & PS_MODE_COMPAT) == 0) {
139 		xo_error("usage: procstat [--libxo] [-h] [-M core] [-N system]"
140 		    " [-w interval] command\n"
141 		    "                [pid ... | core ...]\n"
142 		    "       procstat [--libxo] -a [-h] [-M core] [-N system] "
143 		    " [-w interval] command\n"
144 		    "       procstat [--libxo] [-h] [-M core] [-N system]"
145 		    " [-w interval]\n"
146 		    "                [-S | -b | -c | -e | -f [-C] | -i [-n] | "
147 		    "-j [-n] | -k [-k] |\n"
148 		    "                 -l | -r [-H] | -s | -t | -v | -x] "
149 		    "[pid ... | core ...]\n"
150 		    "       procstat [--libxo] -a [-h] [-M core] [-N system]"
151 		    " [-w interval]\n"
152 		    "                [-S | -b | -c | -e | -f [-C] | -i [-n] | "
153 		    "-j [-n] | -k [-k] |\n"
154 		    "                 -l | -r [-H] | -s | -t | -v | -x]\n"
155 		    "       procstat [--libxo] -L [-h] [-M core] [-N system] core ...\n"
156 		    "Available commands:\n");
157 		for (i = 0, l = nitems(cmd_table); i < l; i++) {
158 			multi = i + 1 < l && cmd_table[i].cmd ==
159 			    cmd_table[i + 1].cmd;
160 			xo_error("       %s%s%s", multi ? "[" : "",
161 			    cmd_table[i].command, (cmd_table[i].cmp &
162 			    PS_CMP_PLURAL) ? "(s)" : "");
163 			for (; i + 1 < l && cmd_table[i].cmd ==
164 			    cmd_table[i + 1].cmd; i++)
165 				xo_error(" | %s%s", cmd_table[i + 1].command,
166 				    (cmd_table[i].cmp & PS_CMP_PLURAL) ?
167 				    "(s)" : "");
168 			if (multi)
169 				xo_error("]");
170 			if (cmd_table[i].usage != NULL)
171 				xo_error(" %s", cmd_table[i].usage);
172 			xo_error("\n");
173 		}
174 	} else {
175 		xo_error("usage: %s [--libxo] pid ...\n", progname);
176 	}
177 	xo_finish();
178 	exit(EX_USAGE);
179 }
180 
181 static void
182 procstat(const struct procstat_cmd *cmd, struct procstat *prstat,
183     struct kinfo_proc *kipp)
184 {
185 	char *pidstr = NULL;
186 
187 	asprintf(&pidstr, "%d", kipp->ki_pid);
188 	if (pidstr == NULL)
189 		xo_errc(1, ENOMEM, "Failed to allocate memory in procstat()");
190 	xo_open_container(pidstr);
191 	cmd->cmd(prstat, kipp);
192 	xo_close_container(pidstr);
193 	free(pidstr);
194 }
195 
196 /*
197  * Sort processes first by pid and then tid.
198  */
199 static int
200 kinfo_proc_compare(const void *a, const void *b)
201 {
202 	int i;
203 
204 	i = ((const struct kinfo_proc *)a)->ki_pid -
205 	    ((const struct kinfo_proc *)b)->ki_pid;
206 	if (i != 0)
207 		return (i);
208 	i = ((const struct kinfo_proc *)a)->ki_tid -
209 	    ((const struct kinfo_proc *)b)->ki_tid;
210 	return (i);
211 }
212 
213 void
214 kinfo_proc_sort(struct kinfo_proc *kipp, int count)
215 {
216 
217 	qsort(kipp, count, sizeof(*kipp), kinfo_proc_compare);
218 }
219 
220 const char *
221 kinfo_proc_thread_name(const struct kinfo_proc *kipp)
222 {
223 	static char name[MAXCOMLEN+1];
224 
225 	strlcpy(name, kipp->ki_tdname, sizeof(name));
226 	strlcat(name, kipp->ki_moretdname, sizeof(name));
227 	if (name[0] == '\0' || strcmp(kipp->ki_comm, name) == 0) {
228 		name[0] = '-';
229 		name[1] = '\0';
230 	}
231 
232 	return (name);
233 }
234 
235 static const struct procstat_cmd *
236 getcmdbyprogname(const char *pprogname)
237 {
238 	const char *ca;
239 	size_t i, len;
240 
241 	if (pprogname == NULL)
242 		return (NULL);
243 	len = strlen(pprogname);
244 
245 	for (i = 0; i < nitems(pacmd_table); i++) {
246 		ca = pacmd_table[i].command;
247 		if (ca != NULL && strcmp(ca, pprogname) == 0)
248 			return (&pacmd_table[i]);
249 	}
250 
251 	return (NULL);
252 }
253 
254 static const struct procstat_cmd *
255 getcmd(const char *str)
256 {
257 	const struct procstat_cmd *cmd;
258 	size_t i, l;
259 	int cmp, s;
260 
261 	if (str == NULL)
262 		return (NULL);
263 	cmd = NULL;
264 	if ((l = strlen(str)) == 0)
265 		return (getcmd("basic"));
266 	s = l > 1 && strcasecmp(str + l - 1, "s") == 0;
267 	for (i = 0; i < nitems(cmd_table); i++) {
268 		/*
269 		 * After the first match substring matches are disabled,
270 		 * allowing subsequent full matches to take precedence.
271 		 */
272 		if (cmd == NULL && (cmd_table[i].cmp & PS_CMP_SUBSTR))
273 			cmp = strncasecmp(str, cmd_table[i].command, l -
274 			    ((cmd_table[i].cmp & PS_CMP_PLURAL) && s ? 1 : 0));
275 		else if ((cmd_table[i].cmp & PS_CMP_PLURAL) && s &&
276 		    l == strlen(cmd_table[i].command) + 1)
277 			cmp = strncasecmp(str, cmd_table[i].command, l - 1);
278 		else
279 			cmp = strcasecmp(str, cmd_table[i].command);
280 		if (cmp == 0)
281 			cmd = &cmd_table[i];
282 	}
283 	return (cmd);
284 }
285 
286 int
287 main(int argc, char *argv[])
288 {
289 	struct kinfo_proc *p;
290 	const struct procstat_cmd *cmd;
291 	struct procstat *prstat, *cprstat;
292 	char *dummy, *nlistf, *memf;
293 	const char *xocontainer;
294 	long l;
295 	pid_t pid;
296 	int aflag, ch, cnt, i, interval;
297 
298 	interval = 0;
299 	cmd = NULL;
300 	memf = nlistf = NULL;
301 	aflag = 0;
302 	argc = xo_parse_args(argc, argv);
303 
304 	progname = getprogname();
305 	cmd = getcmdbyprogname(progname);
306 
307 	while ((ch = getopt(argc, argv, "abCcefHhijkLlM:N:nrSstvw:x")) != -1) {
308 		switch (ch) {
309 		case 'a':
310 			aflag++;
311 			break;
312 		case 'b':
313 			if (cmd != NULL)
314 				usage(cmd);
315 			cmd = getcmd("binary");
316 			break;
317 		case 'C':
318 			procstat_opts |= PS_OPT_CAPABILITIES;
319 			break;
320 		case 'c':
321 			if (cmd != NULL)
322 				usage(cmd);
323 			cmd = getcmd("arguments");
324 			break;
325 		case 'e':
326 			if (cmd != NULL)
327 				usage(cmd);
328 			cmd = getcmd("environment");
329 			break;
330 		case 'f':
331 			if (cmd != NULL)
332 				usage(cmd);
333 			cmd = getcmd("files");
334 			break;
335 		case 'H':
336 			procstat_opts |= PS_OPT_PERTHREAD;
337 			break;
338 		case 'h':
339 			procstat_opts |= PS_OPT_NOHEADER;
340 			break;
341 		case 'i':
342 			if (cmd != NULL)
343 				usage(cmd);
344 			cmd = getcmd("signals");
345 			break;
346 		case 'j':
347 			if (cmd != NULL)
348 				usage(cmd);
349 			cmd = getcmd("tsignals");
350 			break;
351 		case 'k':
352 			if (cmd != NULL && cmd->cmd == procstat_kstack) {
353 				if ((procstat_opts & PS_OPT_VERBOSE) != 0)
354 					usage(cmd);
355 				procstat_opts |= PS_OPT_VERBOSE;
356 			} else {
357 				if (cmd != NULL)
358 					usage(cmd);
359 				cmd = getcmd("kstack");
360 			}
361 			break;
362 		case 'L':
363 			if (cmd != NULL)
364 				usage(cmd);
365 			cmd = getcmd("ptlwpinfo");
366 			break;
367 		case 'l':
368 			if (cmd != NULL)
369 				usage(cmd);
370 			cmd = getcmd("rlimit");
371 			break;
372 		case 'M':
373 			memf = optarg;
374 			break;
375 		case 'N':
376 			nlistf = optarg;
377 			break;
378 		case 'n':
379 			procstat_opts |= PS_OPT_SIGNUM;
380 			break;
381 		case 'r':
382 			if (cmd != NULL)
383 				usage(cmd);
384 			cmd = getcmd("rusage");
385 			break;
386 		case 'S':
387 			if (cmd != NULL)
388 				usage(cmd);
389 			cmd = getcmd("cpuset");
390 			break;
391 		case 's':
392 			if (cmd != NULL)
393 				usage(cmd);
394 			cmd = getcmd("credentials");
395 			break;
396 		case 't':
397 			if (cmd != NULL)
398 				usage(cmd);
399 			cmd = getcmd("threads");
400 			break;
401 		case 'v':
402 			if (cmd != NULL)
403 				usage(cmd);
404 			cmd = getcmd("vm");
405 			break;
406 		case 'w':
407 			l = strtol(optarg, &dummy, 10);
408 			if (*dummy != '\0')
409 				usage(cmd);
410 			if (l < 1 || l > INT_MAX)
411 				usage(cmd);
412 			interval = l;
413 			break;
414 		case 'x':
415 			if (cmd != NULL)
416 				usage(cmd);
417 			cmd = getcmd("auxv");
418 			break;
419 		case '?':
420 		default:
421 			usage(cmd);
422 		}
423 
424 	}
425 	argc -= optind;
426 	argv += optind;
427 
428 	if (cmd == NULL && argv[0] != NULL && (cmd = getcmd(argv[0])) != NULL) {
429 		if ((procstat_opts & PS_SUBCOMMAND_OPTS) != 0)
430 			usage(cmd);
431 		if (cmd->opt != NULL) {
432 			optreset = 1;
433 			optind = 1;
434 			cmd->opt(argc, argv);
435 			if ((cmd->cmp & PS_MODE_COMPAT) == 0) {
436 				argc -= optind;
437 				argv += optind;
438 			}
439 		} else {
440 			argc -= 1;
441 			argv += 1;
442 		}
443 	} else {
444 		if (cmd == NULL)
445 			cmd = getcmd("basic");
446 		if (cmd->cmd != procstat_files &&
447 		    (procstat_opts & PS_OPT_CAPABILITIES) != 0 &&
448 		    (cmd->cmp & PS_MODE_COMPAT) == 0)
449 			usage(cmd);
450 	}
451 
452 	/* Must specify either the -a flag or a list of pids. */
453 	if (!(aflag == 1 && argc == 0) && !(aflag == 0 && argc > 0))
454 		usage(cmd);
455 
456 	if (memf != NULL)
457 		prstat = procstat_open_kvm(nlistf, memf);
458 	else
459 		prstat = procstat_open_sysctl();
460 	if (prstat == NULL)
461 		xo_errx(1, "procstat_open()");
462 	do {
463 		xocontainer = cmd->xocontainer != NULL ? cmd->xocontainer :
464 		    cmd->command;
465 		xo_set_version(PROCSTAT_XO_VERSION);
466 		xo_open_container(progname);
467 		xo_open_container(xocontainer);
468 
469 		if (aflag) {
470 			p = procstat_getprocs(prstat, KERN_PROC_PROC, 0, &cnt);
471 			if (p == NULL)
472 				xo_errx(1, "procstat_getprocs()");
473 			kinfo_proc_sort(p, cnt);
474 			for (i = 0; i < cnt; i++) {
475 				procstat(cmd, prstat, &p[i]);
476 
477 				/* Suppress header after first process. */
478 				procstat_opts |= PS_OPT_NOHEADER;
479 				xo_flush();
480 			}
481 			procstat_freeprocs(prstat, p);
482 		}
483 		for (i = 0; i < argc; i++) {
484 			l = strtol(argv[i], &dummy, 10);
485 			if (*dummy == '\0') {
486 				if (l < 0)
487 					usage(cmd);
488 				pid = l;
489 
490 				p = procstat_getprocs(prstat, KERN_PROC_PID,
491 				    pid, &cnt);
492 				if (p == NULL)
493 					xo_errx(1, "procstat_getprocs()");
494 				if (cnt != 0)
495 					procstat(cmd, prstat, p);
496 				procstat_freeprocs(prstat, p);
497 			} else {
498 				if ((cmd->cmp & PS_MODE_COMPAT) == 0) {
499 					cprstat = procstat_open_core(argv[i]);
500 					if (cprstat == NULL) {
501 						warnx("procstat_open()");
502 						continue;
503 					}
504 					p = procstat_getprocs(cprstat,
505 					    KERN_PROC_PID, -1, &cnt);
506 					if (p == NULL) {
507 						xo_errx(1,
508 						    "procstat_getprocs()");
509 					}
510 					if (cnt != 0)
511 						procstat(cmd, cprstat, p);
512 					procstat_freeprocs(cprstat, p);
513 					procstat_close(cprstat);
514 				} else {
515 					usage(cmd);
516 				}
517 			}
518 			if ((cmd->cmp & PS_MODE_COMPAT) == 0) {
519 				/* Suppress header after first process. */
520 				procstat_opts |= PS_OPT_NOHEADER;
521 			}
522 		}
523 
524 		xo_close_container(xocontainer);
525 		xo_close_container(progname);
526 		xo_finish();
527 		if (interval)
528 			sleep(interval);
529 	} while (interval);
530 
531 	procstat_close(prstat);
532 
533 	exit(0);
534 }
535 
536 void
537 cmdopt_none(int argc, char * const argv[])
538 {
539 	int ch;
540 
541 	while ((ch = getopt(argc, argv, "")) != -1) {
542 		switch (ch) {
543 		case '?':
544 		default:
545 			usage(NULL);
546 		}
547 	}
548 }
549 
550 void
551 cmdopt_verbose(int argc, char * const argv[])
552 {
553 	int ch;
554 
555 	while ((ch = getopt(argc, argv, "v")) != -1) {
556 		switch (ch) {
557 		case 'v':
558 			procstat_opts |= PS_OPT_VERBOSE;
559 			break;
560 		case '?':
561 		default:
562 			usage(NULL);
563 		}
564 	}
565 }
566 
567 void
568 cmdopt_signals(int argc, char * const argv[])
569 {
570 	int ch;
571 
572 	while ((ch = getopt(argc, argv, "n")) != -1) {
573 		switch (ch) {
574 		case 'n':
575 			procstat_opts |= PS_OPT_SIGNUM;
576 			break;
577 		case '?':
578 		default:
579 			usage(NULL);
580 		}
581 	}
582 }
583 
584 void
585 cmdopt_rusage(int argc, char * const argv[])
586 {
587 	int ch;
588 
589 	while ((ch = getopt(argc, argv, "Ht")) != -1) {
590 		switch (ch) {
591 		case 'H':
592 			/* FALLTHROUGH */
593 		case 't':
594 			procstat_opts |= PS_OPT_PERTHREAD;
595 			break;
596 		case '?':
597 		default:
598 			usage(NULL);
599 		}
600 	}
601 }
602 
603 void
604 cmdopt_files(int argc, char * const argv[])
605 {
606 	int ch;
607 
608 	while ((ch = getopt(argc, argv, "C")) != -1) {
609 		switch (ch) {
610 		case 'C':
611 			procstat_opts |= PS_OPT_CAPABILITIES;
612 			break;
613 		case '?':
614 		default:
615 			usage(NULL);
616 		}
617 	}
618 }
619 
620 void
621 cmdopt_cpuset(int argc, char * const argv[])
622 {
623 
624 	procstat_opts |= PS_OPT_PERTHREAD;
625 	cmdopt_none(argc, argv);
626 }
627