xref: /freebsd/usr.bin/procstat/procstat.c (revision 5c4aa6257210502c93ad65882a8a4842d984bae2)
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;
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 		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 (aflag) {
469 			p = procstat_getprocs(prstat, KERN_PROC_PROC, 0, &cnt);
470 			if (p == NULL)
471 				xo_errx(1, "procstat_getprocs()");
472 			kinfo_proc_sort(p, cnt);
473 			for (i = 0; i < cnt; i++) {
474 				procstat(cmd, prstat, &p[i]);
475 
476 				/* Suppress header after first process. */
477 				procstat_opts |= PS_OPT_NOHEADER;
478 				xo_flush();
479 			}
480 			procstat_freeprocs(prstat, p);
481 		}
482 		for (i = 0; i < argc; i++) {
483 			l = strtol(argv[i], &dummy, 10);
484 			if (*dummy == '\0') {
485 				if (l < 0)
486 					usage(cmd);
487 				pid = l;
488 
489 				p = procstat_getprocs(prstat, KERN_PROC_PID,
490 				    pid, &cnt);
491 				if (p == NULL)
492 					xo_errx(1, "procstat_getprocs()");
493 				if (cnt != 0)
494 					procstat(cmd, prstat, p);
495 				procstat_freeprocs(prstat, p);
496 			} else {
497 				if ((cmd->cmp & PS_MODE_COMPAT) == 0) {
498 					cprstat = procstat_open_core(argv[i]);
499 					if (cprstat == NULL) {
500 						warnx("procstat_open()");
501 						continue;
502 					}
503 					p = procstat_getprocs(cprstat,
504 					    KERN_PROC_PID, -1, &cnt);
505 					if (p == NULL) {
506 						xo_errx(1,
507 						    "procstat_getprocs()");
508 					}
509 					if (cnt != 0)
510 						procstat(cmd, cprstat, p);
511 					procstat_freeprocs(cprstat, p);
512 					procstat_close(cprstat);
513 				} else {
514 					usage(cmd);
515 				}
516 			}
517 			if ((cmd->cmp & PS_MODE_COMPAT) == 0) {
518 				/* Suppress header after first process. */
519 				procstat_opts |= PS_OPT_NOHEADER;
520 			}
521 		}
522 
523 		xo_close_container(xocontainer);
524 		xo_close_container(progname);
525 		xo_finish();
526 		if (interval)
527 			sleep(interval);
528 	} while (interval);
529 
530 	procstat_close(prstat);
531 
532 	exit(0);
533 }
534 
535 void
536 cmdopt_none(int argc, char * const argv[])
537 {
538 	int ch;
539 
540 	while ((ch = getopt(argc, argv, "")) != -1) {
541 		switch (ch) {
542 		case '?':
543 		default:
544 			usage(NULL);
545 		}
546 	}
547 }
548 
549 void
550 cmdopt_verbose(int argc, char * const argv[])
551 {
552 	int ch;
553 
554 	while ((ch = getopt(argc, argv, "v")) != -1) {
555 		switch (ch) {
556 		case 'v':
557 			procstat_opts |= PS_OPT_VERBOSE;
558 			break;
559 		case '?':
560 		default:
561 			usage(NULL);
562 		}
563 	}
564 }
565 
566 void
567 cmdopt_signals(int argc, char * const argv[])
568 {
569 	int ch;
570 
571 	while ((ch = getopt(argc, argv, "n")) != -1) {
572 		switch (ch) {
573 		case 'n':
574 			procstat_opts |= PS_OPT_SIGNUM;
575 			break;
576 		case '?':
577 		default:
578 			usage(NULL);
579 		}
580 	}
581 }
582 
583 void
584 cmdopt_rusage(int argc, char * const argv[])
585 {
586 	int ch;
587 
588 	while ((ch = getopt(argc, argv, "Ht")) != -1) {
589 		switch (ch) {
590 		case 'H':
591 			/* FALLTHROUGH */
592 		case 't':
593 			procstat_opts |= PS_OPT_PERTHREAD;
594 			break;
595 		case '?':
596 		default:
597 			usage(NULL);
598 		}
599 	}
600 }
601 
602 void
603 cmdopt_files(int argc, char * const argv[])
604 {
605 	int ch;
606 
607 	while ((ch = getopt(argc, argv, "C")) != -1) {
608 		switch (ch) {
609 		case 'C':
610 			procstat_opts |= PS_OPT_CAPABILITIES;
611 			break;
612 		case '?':
613 		default:
614 			usage(NULL);
615 		}
616 	}
617 }
618 
619 void
620 cmdopt_cpuset(int argc, char * const argv[])
621 {
622 
623 	procstat_opts |= PS_OPT_PERTHREAD;
624 	cmdopt_none(argc, argv);
625 }
626