xref: /freebsd/usr.bin/procstat/procstat.c (revision 734e82fe33aa764367791a7d603b383996c6b40b)
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/cdefs.h>
32 #include <sys/param.h>
33 #include <sys/sysctl.h>
34 #include <sys/user.h>
35 
36 #include <err.h>
37 #include <libprocstat.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <sysexits.h>
42 #include <unistd.h>
43 
44 #include "procstat.h"
45 
46 enum {
47 	PS_CMP_NORMAL = 0x00,
48 	PS_CMP_PLURAL = 0x01,
49 	PS_CMP_SUBSTR = 0x02
50 };
51 
52 struct procstat_cmd {
53 	const char *command;
54 	const char *xocontainer;
55 	const char *usage;
56 	void (*cmd)(struct procstat *, struct kinfo_proc *);
57 	void (*opt)(int, char * const *);
58 	int cmp;
59 };
60 
61 int procstat_opts = 0;
62 
63 static void cmdopt_none(int argc, char * const argv[]);
64 static void cmdopt_verbose(int argc, char * const argv[]);
65 static void cmdopt_signals(int argc, char * const argv[]);
66 static void cmdopt_rusage(int argc, char * const argv[]);
67 static void cmdopt_files(int argc, char * const argv[]);
68 static void cmdopt_cpuset(int argc, char * const argv[]);
69 
70 static const char *progname;
71 
72 /* aliased program parameters and arguments
73  * - usage field is abused to hold the pointer to the function
74  *   displaying program usage
75  */
76 static const struct procstat_cmd pacmd_table[] = {
77 	/* arguments are the same as for pwdx: pid or core file */
78 	{ "pargs", "args", NULL, &procstat_pargs, &cmdopt_none,
79 	    PS_CMP_NORMAL | PS_MODE_COMPAT },
80 	{ "penv", "env", NULL, &procstat_penv, &cmdopt_none,
81 	    PS_CMP_NORMAL | PS_MODE_COMPAT },
82 	{ "pwdx", "pwd", NULL, &procstat_pwdx, &cmdopt_none,
83 	    PS_CMP_NORMAL | PS_MODE_COMPAT }
84 };
85 
86 /* procstat parameters and arguments */
87 static const struct procstat_cmd cmd_table[] = {
88 	{ "advlock", "advisory_locks", NULL, &procstat_advlocks, &cmdopt_none,
89 	    PS_CMP_PLURAL | PS_CMP_SUBSTR | PS_MODE_NO_KINFO_PROC },
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;
240 
241 	if (pprogname == NULL)
242 		return (NULL);
243 
244 	for (i = 0; i < nitems(pacmd_table); i++) {
245 		ca = pacmd_table[i].command;
246 		if (ca != NULL && strcmp(ca, pprogname) == 0)
247 			return (&pacmd_table[i]);
248 	}
249 
250 	return (NULL);
251 }
252 
253 static const struct procstat_cmd *
254 getcmd(const char *str)
255 {
256 	const struct procstat_cmd *cmd;
257 	size_t i, l;
258 	int cmp, s;
259 
260 	if (str == NULL)
261 		return (NULL);
262 	cmd = NULL;
263 	if ((l = strlen(str)) == 0)
264 		return (getcmd("basic"));
265 	s = l > 1 && strcasecmp(str + l - 1, "s") == 0;
266 	for (i = 0; i < nitems(cmd_table); i++) {
267 		/*
268 		 * After the first match substring matches are disabled,
269 		 * allowing subsequent full matches to take precedence.
270 		 */
271 		if (cmd == NULL && (cmd_table[i].cmp & PS_CMP_SUBSTR))
272 			cmp = strncasecmp(str, cmd_table[i].command, l -
273 			    ((cmd_table[i].cmp & PS_CMP_PLURAL) && s ? 1 : 0));
274 		else if ((cmd_table[i].cmp & PS_CMP_PLURAL) && s &&
275 		    l == strlen(cmd_table[i].command) + 1)
276 			cmp = strncasecmp(str, cmd_table[i].command, l - 1);
277 		else
278 			cmp = strcasecmp(str, cmd_table[i].command);
279 		if (cmp == 0)
280 			cmd = &cmd_table[i];
281 	}
282 	return (cmd);
283 }
284 
285 int
286 main(int argc, char *argv[])
287 {
288 	struct kinfo_proc *p;
289 	const struct procstat_cmd *cmd;
290 	struct procstat *prstat, *cprstat;
291 	char *dummy, *nlistf, *memf;
292 	const char *xocontainer;
293 	long l;
294 	pid_t pid;
295 	int aflag, ch, cnt, i, interval;
296 
297 	interval = 0;
298 	cmd = NULL;
299 	memf = nlistf = NULL;
300 	aflag = 0;
301 	argc = xo_parse_args(argc, argv);
302 
303 	progname = getprogname();
304 	cmd = getcmdbyprogname(progname);
305 
306 	while ((ch = getopt(argc, argv, "abCcefHhijkLlM:N:nrSstvw:x")) != -1) {
307 		switch (ch) {
308 		case 'a':
309 			aflag++;
310 			break;
311 		case 'b':
312 			if (cmd != NULL)
313 				usage(cmd);
314 			cmd = getcmd("binary");
315 			break;
316 		case 'C':
317 			procstat_opts |= PS_OPT_CAPABILITIES;
318 			break;
319 		case 'c':
320 			if (cmd != NULL)
321 				usage(cmd);
322 			cmd = getcmd("arguments");
323 			break;
324 		case 'e':
325 			if (cmd != NULL)
326 				usage(cmd);
327 			cmd = getcmd("environment");
328 			break;
329 		case 'f':
330 			if (cmd != NULL)
331 				usage(cmd);
332 			cmd = getcmd("files");
333 			break;
334 		case 'H':
335 			procstat_opts |= PS_OPT_PERTHREAD;
336 			break;
337 		case 'h':
338 			procstat_opts |= PS_OPT_NOHEADER;
339 			break;
340 		case 'i':
341 			if (cmd != NULL)
342 				usage(cmd);
343 			cmd = getcmd("signals");
344 			break;
345 		case 'j':
346 			if (cmd != NULL)
347 				usage(cmd);
348 			cmd = getcmd("tsignals");
349 			break;
350 		case 'k':
351 			if (cmd != NULL && cmd->cmd == procstat_kstack) {
352 				if ((procstat_opts & PS_OPT_VERBOSE) != 0)
353 					usage(cmd);
354 				procstat_opts |= PS_OPT_VERBOSE;
355 			} else {
356 				if (cmd != NULL)
357 					usage(cmd);
358 				cmd = getcmd("kstack");
359 			}
360 			break;
361 		case 'L':
362 			if (cmd != NULL)
363 				usage(cmd);
364 			cmd = getcmd("ptlwpinfo");
365 			break;
366 		case 'l':
367 			if (cmd != NULL)
368 				usage(cmd);
369 			cmd = getcmd("rlimit");
370 			break;
371 		case 'M':
372 			memf = optarg;
373 			break;
374 		case 'N':
375 			nlistf = optarg;
376 			break;
377 		case 'n':
378 			procstat_opts |= PS_OPT_SIGNUM;
379 			break;
380 		case 'r':
381 			if (cmd != NULL)
382 				usage(cmd);
383 			cmd = getcmd("rusage");
384 			break;
385 		case 'S':
386 			if (cmd != NULL)
387 				usage(cmd);
388 			cmd = getcmd("cpuset");
389 			break;
390 		case 's':
391 			if (cmd != NULL)
392 				usage(cmd);
393 			cmd = getcmd("credentials");
394 			break;
395 		case 't':
396 			if (cmd != NULL)
397 				usage(cmd);
398 			cmd = getcmd("threads");
399 			break;
400 		case 'v':
401 			if (cmd != NULL)
402 				usage(cmd);
403 			cmd = getcmd("vm");
404 			break;
405 		case 'w':
406 			l = strtol(optarg, &dummy, 10);
407 			if (*dummy != '\0')
408 				usage(cmd);
409 			if (l < 1 || l > INT_MAX)
410 				usage(cmd);
411 			interval = l;
412 			break;
413 		case 'x':
414 			if (cmd != NULL)
415 				usage(cmd);
416 			cmd = getcmd("auxv");
417 			break;
418 		case '?':
419 		default:
420 			usage(cmd);
421 		}
422 
423 	}
424 	argc -= optind;
425 	argv += optind;
426 
427 	if (cmd == NULL && argv[0] != NULL && (cmd = getcmd(argv[0])) != NULL) {
428 		if ((procstat_opts & PS_SUBCOMMAND_OPTS) != 0)
429 			usage(cmd);
430 		if (cmd->opt != NULL) {
431 			optreset = 1;
432 			optind = 1;
433 			cmd->opt(argc, argv);
434 			if ((cmd->cmp & PS_MODE_COMPAT) == 0) {
435 				argc -= optind;
436 				argv += optind;
437 			}
438 		} else {
439 			argc -= 1;
440 			argv += 1;
441 		}
442 	} else {
443 		if (cmd == NULL)
444 			cmd = getcmd("basic");
445 		if (cmd->cmd != procstat_files &&
446 		    (procstat_opts & PS_OPT_CAPABILITIES) != 0 &&
447 		    (cmd->cmp & PS_MODE_COMPAT) == 0)
448 			usage(cmd);
449 	}
450 
451 	/* Must specify either the -a flag or a list of pids. */
452 	if (!(aflag == 1 && argc == 0) && !(aflag == 0 && argc > 0) &&
453 	    (cmd->cmp & PS_MODE_NO_KINFO_PROC) == 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 ((cmd->cmp & PS_MODE_NO_KINFO_PROC) != 0) {
470 			cmd->cmd(prstat, NULL);
471 			goto iter;
472 		}
473 
474 		if (aflag) {
475 			p = procstat_getprocs(prstat, KERN_PROC_PROC, 0, &cnt);
476 			if (p == NULL)
477 				xo_errx(1, "procstat_getprocs()");
478 			kinfo_proc_sort(p, cnt);
479 			for (i = 0; i < cnt; i++) {
480 				procstat(cmd, prstat, &p[i]);
481 
482 				/* Suppress header after first process. */
483 				procstat_opts |= PS_OPT_NOHEADER;
484 				xo_flush();
485 			}
486 			procstat_freeprocs(prstat, p);
487 		}
488 		for (i = 0; i < argc; i++) {
489 			l = strtol(argv[i], &dummy, 10);
490 			if (*dummy == '\0') {
491 				if (l < 0)
492 					usage(cmd);
493 				pid = l;
494 
495 				p = procstat_getprocs(prstat, KERN_PROC_PID,
496 				    pid, &cnt);
497 				if (p == NULL)
498 					xo_errx(1, "procstat_getprocs()");
499 				if (cnt != 0)
500 					procstat(cmd, prstat, p);
501 				procstat_freeprocs(prstat, p);
502 			} else {
503 				if ((cmd->cmp & PS_MODE_COMPAT) == 0) {
504 					cprstat = procstat_open_core(argv[i]);
505 					if (cprstat == NULL) {
506 						warnx("procstat_open()");
507 						continue;
508 					}
509 					p = procstat_getprocs(cprstat,
510 					    KERN_PROC_PID, -1, &cnt);
511 					if (p == NULL) {
512 						xo_errx(1,
513 						    "procstat_getprocs()");
514 					}
515 					if (cnt != 0)
516 						procstat(cmd, cprstat, p);
517 					procstat_freeprocs(cprstat, p);
518 					procstat_close(cprstat);
519 				} else {
520 					usage(cmd);
521 				}
522 			}
523 			if ((cmd->cmp & PS_MODE_COMPAT) == 0) {
524 				/* Suppress header after first process. */
525 				procstat_opts |= PS_OPT_NOHEADER;
526 			}
527 		}
528 
529 iter:
530 		xo_close_container(xocontainer);
531 		xo_close_container(progname);
532 		xo_finish();
533 		if (interval)
534 			sleep(interval);
535 	} while (interval);
536 
537 	procstat_close(prstat);
538 
539 	exit(0);
540 }
541 
542 void
543 cmdopt_none(int argc, char * const argv[])
544 {
545 	int ch;
546 
547 	while ((ch = getopt(argc, argv, "")) != -1) {
548 		switch (ch) {
549 		case '?':
550 		default:
551 			usage(NULL);
552 		}
553 	}
554 }
555 
556 void
557 cmdopt_verbose(int argc, char * const argv[])
558 {
559 	int ch;
560 
561 	while ((ch = getopt(argc, argv, "v")) != -1) {
562 		switch (ch) {
563 		case 'v':
564 			procstat_opts |= PS_OPT_VERBOSE;
565 			break;
566 		case '?':
567 		default:
568 			usage(NULL);
569 		}
570 	}
571 }
572 
573 void
574 cmdopt_signals(int argc, char * const argv[])
575 {
576 	int ch;
577 
578 	while ((ch = getopt(argc, argv, "n")) != -1) {
579 		switch (ch) {
580 		case 'n':
581 			procstat_opts |= PS_OPT_SIGNUM;
582 			break;
583 		case '?':
584 		default:
585 			usage(NULL);
586 		}
587 	}
588 }
589 
590 void
591 cmdopt_rusage(int argc, char * const argv[])
592 {
593 	int ch;
594 
595 	while ((ch = getopt(argc, argv, "Ht")) != -1) {
596 		switch (ch) {
597 		case 'H':
598 			/* FALLTHROUGH */
599 		case 't':
600 			procstat_opts |= PS_OPT_PERTHREAD;
601 			break;
602 		case '?':
603 		default:
604 			usage(NULL);
605 		}
606 	}
607 }
608 
609 void
610 cmdopt_files(int argc, char * const argv[])
611 {
612 	int ch;
613 
614 	while ((ch = getopt(argc, argv, "C")) != -1) {
615 		switch (ch) {
616 		case 'C':
617 			procstat_opts |= PS_OPT_CAPABILITIES;
618 			break;
619 		case '?':
620 		default:
621 			usage(NULL);
622 		}
623 	}
624 }
625 
626 void
627 cmdopt_cpuset(int argc, char * const argv[])
628 {
629 
630 	procstat_opts |= PS_OPT_PERTHREAD;
631 	cmdopt_none(argc, argv);
632 }
633