xref: /freebsd/usr.bin/procstat/procstat.c (revision 7a7741af18d6c8a804cc643cb7ecda9d730c6aa6)
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 	{ "rlimitusage", "rlimitusage", NULL, &procstat_rlimitusage,
119 	    &cmdopt_none, PS_CMP_NORMAL },
120 	{ "rusage", "rusage", "[-Ht]", &procstat_rusage, &cmdopt_rusage,
121 	    PS_CMP_NORMAL },
122 	{ "sigfastblock", "sigfastblock", NULL, &procstat_sigfastblock,
123 	    &cmdopt_none, PS_CMP_NORMAL },
124 	{ "signal", "signals", "[-n]", &procstat_sigs, &cmdopt_signals,
125 	    PS_CMP_PLURAL | PS_CMP_SUBSTR },
126 	{ "thread", "threads", NULL, &procstat_threads, &cmdopt_none,
127 	    PS_CMP_PLURAL },
128 	{ "tsignal", "thread_signals", "[-n]", &procstat_threads_sigs,
129 	    &cmdopt_signals, PS_CMP_PLURAL | PS_CMP_SUBSTR },
130 	{ "vm", "vm", NULL, &procstat_vm, &cmdopt_none, PS_CMP_NORMAL }
131 };
132 
133 static void
134 usage(const struct procstat_cmd *cmd)
135 {
136 	size_t i, l;
137 	int multi;
138 
139 	if (cmd == NULL || (cmd->cmp & PS_MODE_COMPAT) == 0) {
140 		xo_error("usage: procstat [--libxo] [-h] [-M core] [-N system]"
141 		    " [-w interval] command\n"
142 		    "                [pid ... | core ...]\n"
143 		    "       procstat [--libxo] -a [-h] [-M core] [-N system] "
144 		    " [-w interval] command\n"
145 		    "       procstat [--libxo] [-h] [-M core] [-N system]"
146 		    " [-w interval]\n"
147 		    "                [-S | -b | -c | -e | -f [-C] | -i [-n] | "
148 		    "-j [-n] | -k [-k] |\n"
149 		    "                 -l | -r [-H] | -s | -t | -v | -x] "
150 		    "[pid ... | core ...]\n"
151 		    "       procstat [--libxo] -a [-h] [-M core] [-N system]"
152 		    " [-w interval]\n"
153 		    "                [-S | -b | -c | -e | -f [-C] | -i [-n] | "
154 		    "-j [-n] | -k [-k] |\n"
155 		    "                 -l | -r [-H] | -s | -t | -v | -x]\n"
156 		    "       procstat [--libxo] -L [-h] [-M core] [-N system] core ...\n"
157 		    "Available commands:\n");
158 		for (i = 0, l = nitems(cmd_table); i < l; i++) {
159 			multi = i + 1 < l && cmd_table[i].cmd ==
160 			    cmd_table[i + 1].cmd;
161 			xo_error("       %s%s%s", multi ? "[" : "",
162 			    cmd_table[i].command, (cmd_table[i].cmp &
163 			    PS_CMP_PLURAL) ? "(s)" : "");
164 			for (; i + 1 < l && cmd_table[i].cmd ==
165 			    cmd_table[i + 1].cmd; i++)
166 				xo_error(" | %s%s", cmd_table[i + 1].command,
167 				    (cmd_table[i].cmp & PS_CMP_PLURAL) ?
168 				    "(s)" : "");
169 			if (multi)
170 				xo_error("]");
171 			if (cmd_table[i].usage != NULL)
172 				xo_error(" %s", cmd_table[i].usage);
173 			xo_error("\n");
174 		}
175 	} else {
176 		xo_error("usage: %s [--libxo] pid ...\n", progname);
177 	}
178 	xo_finish();
179 	exit(EX_USAGE);
180 }
181 
182 static void
183 procstat(const struct procstat_cmd *cmd, struct procstat *prstat,
184     struct kinfo_proc *kipp)
185 {
186 	char *pidstr = NULL;
187 
188 	asprintf(&pidstr, "%d", kipp->ki_pid);
189 	if (pidstr == NULL)
190 		xo_errc(1, ENOMEM, "Failed to allocate memory in procstat()");
191 	xo_open_container(pidstr);
192 	cmd->cmd(prstat, kipp);
193 	xo_close_container(pidstr);
194 	free(pidstr);
195 }
196 
197 /*
198  * Sort processes first by pid and then tid.
199  */
200 static int
201 kinfo_proc_compare(const void *a, const void *b)
202 {
203 	int i;
204 
205 	i = ((const struct kinfo_proc *)a)->ki_pid -
206 	    ((const struct kinfo_proc *)b)->ki_pid;
207 	if (i != 0)
208 		return (i);
209 	i = ((const struct kinfo_proc *)a)->ki_tid -
210 	    ((const struct kinfo_proc *)b)->ki_tid;
211 	return (i);
212 }
213 
214 void
215 kinfo_proc_sort(struct kinfo_proc *kipp, int count)
216 {
217 
218 	qsort(kipp, count, sizeof(*kipp), kinfo_proc_compare);
219 }
220 
221 const char *
222 kinfo_proc_thread_name(const struct kinfo_proc *kipp)
223 {
224 	static char name[MAXCOMLEN+1];
225 
226 	strlcpy(name, kipp->ki_tdname, sizeof(name));
227 	strlcat(name, kipp->ki_moretdname, sizeof(name));
228 	if (name[0] == '\0' || strcmp(kipp->ki_comm, name) == 0) {
229 		name[0] = '-';
230 		name[1] = '\0';
231 	}
232 
233 	return (name);
234 }
235 
236 static const struct procstat_cmd *
237 getcmdbyprogname(const char *pprogname)
238 {
239 	const char *ca;
240 	size_t i;
241 
242 	if (pprogname == NULL)
243 		return (NULL);
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 	    (cmd->cmp & PS_MODE_NO_KINFO_PROC) == 0)
455 		usage(cmd);
456 
457 	if (memf != NULL)
458 		prstat = procstat_open_kvm(nlistf, memf);
459 	else
460 		prstat = procstat_open_sysctl();
461 	if (prstat == NULL)
462 		xo_errx(1, "procstat_open()");
463 	do {
464 		xocontainer = cmd->xocontainer != NULL ? cmd->xocontainer :
465 		    cmd->command;
466 		xo_set_version(PROCSTAT_XO_VERSION);
467 		xo_open_container(progname);
468 		xo_open_container(xocontainer);
469 
470 		if ((cmd->cmp & PS_MODE_NO_KINFO_PROC) != 0) {
471 			cmd->cmd(prstat, NULL);
472 			goto iter;
473 		}
474 
475 		if (aflag) {
476 			p = procstat_getprocs(prstat, KERN_PROC_PROC, 0, &cnt);
477 			if (p == NULL)
478 				xo_errx(1, "procstat_getprocs()");
479 			kinfo_proc_sort(p, cnt);
480 			for (i = 0; i < cnt; i++) {
481 				procstat(cmd, prstat, &p[i]);
482 
483 				/* Suppress header after first process. */
484 				procstat_opts |= PS_OPT_NOHEADER;
485 				xo_flush();
486 			}
487 			procstat_freeprocs(prstat, p);
488 		}
489 		for (i = 0; i < argc; i++) {
490 			l = strtol(argv[i], &dummy, 10);
491 			if (*dummy == '\0') {
492 				if (l < 0)
493 					usage(cmd);
494 				pid = l;
495 
496 				p = procstat_getprocs(prstat, KERN_PROC_PID,
497 				    pid, &cnt);
498 				if (p == NULL)
499 					xo_errx(1, "procstat_getprocs()");
500 				if (cnt != 0)
501 					procstat(cmd, prstat, p);
502 				procstat_freeprocs(prstat, p);
503 			} else {
504 				if ((cmd->cmp & PS_MODE_COMPAT) == 0) {
505 					cprstat = procstat_open_core(argv[i]);
506 					if (cprstat == NULL) {
507 						warnx("procstat_open()");
508 						continue;
509 					}
510 					p = procstat_getprocs(cprstat,
511 					    KERN_PROC_PID, -1, &cnt);
512 					if (p == NULL) {
513 						xo_errx(1,
514 						    "procstat_getprocs()");
515 					}
516 					if (cnt != 0)
517 						procstat(cmd, cprstat, p);
518 					procstat_freeprocs(cprstat, p);
519 					procstat_close(cprstat);
520 				} else {
521 					usage(cmd);
522 				}
523 			}
524 			if ((cmd->cmp & PS_MODE_COMPAT) == 0) {
525 				/* Suppress header after first process. */
526 				procstat_opts |= PS_OPT_NOHEADER;
527 			}
528 		}
529 
530 iter:
531 		xo_close_container(xocontainer);
532 		xo_close_container(progname);
533 		xo_finish();
534 		if (interval)
535 			sleep(interval);
536 	} while (interval);
537 
538 	procstat_close(prstat);
539 
540 	exit(0);
541 }
542 
543 void
544 cmdopt_none(int argc, char * const argv[])
545 {
546 	int ch;
547 
548 	while ((ch = getopt(argc, argv, "")) != -1) {
549 		switch (ch) {
550 		case '?':
551 		default:
552 			usage(NULL);
553 		}
554 	}
555 }
556 
557 void
558 cmdopt_verbose(int argc, char * const argv[])
559 {
560 	int ch;
561 
562 	while ((ch = getopt(argc, argv, "v")) != -1) {
563 		switch (ch) {
564 		case 'v':
565 			procstat_opts |= PS_OPT_VERBOSE;
566 			break;
567 		case '?':
568 		default:
569 			usage(NULL);
570 		}
571 	}
572 }
573 
574 void
575 cmdopt_signals(int argc, char * const argv[])
576 {
577 	int ch;
578 
579 	while ((ch = getopt(argc, argv, "n")) != -1) {
580 		switch (ch) {
581 		case 'n':
582 			procstat_opts |= PS_OPT_SIGNUM;
583 			break;
584 		case '?':
585 		default:
586 			usage(NULL);
587 		}
588 	}
589 }
590 
591 void
592 cmdopt_rusage(int argc, char * const argv[])
593 {
594 	int ch;
595 
596 	while ((ch = getopt(argc, argv, "Ht")) != -1) {
597 		switch (ch) {
598 		case 'H':
599 			/* FALLTHROUGH */
600 		case 't':
601 			procstat_opts |= PS_OPT_PERTHREAD;
602 			break;
603 		case '?':
604 		default:
605 			usage(NULL);
606 		}
607 	}
608 }
609 
610 void
611 cmdopt_files(int argc, char * const argv[])
612 {
613 	int ch;
614 
615 	while ((ch = getopt(argc, argv, "C")) != -1) {
616 		switch (ch) {
617 		case 'C':
618 			procstat_opts |= PS_OPT_CAPABILITIES;
619 			break;
620 		case '?':
621 		default:
622 			usage(NULL);
623 		}
624 	}
625 }
626 
627 void
628 cmdopt_cpuset(int argc, char * const argv[])
629 {
630 
631 	procstat_opts |= PS_OPT_PERTHREAD;
632 	cmdopt_none(argc, argv);
633 }
634