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