xref: /freebsd/usr.bin/procstat/procstat.c (revision c6989859ae9388eeb46a24fe88f9b8d07101c710)
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  * $FreeBSD$
31  */
32 
33 #include <sys/param.h>
34 #include <sys/sysctl.h>
35 #include <sys/user.h>
36 
37 #include <err.h>
38 #include <libprocstat.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <sysexits.h>
43 #include <unistd.h>
44 
45 #include "procstat.h"
46 
47 enum {
48 	PS_CMP_NORMAL = 0x00,
49 	PS_CMP_PLURAL = 0x01,
50 	PS_CMP_SUBSTR = 0x02
51 };
52 
53 struct procstat_cmd {
54 	const char *command;
55 	const char *xocontainer;
56 	const char *usage;
57 	void (*cmd)(struct procstat *, struct kinfo_proc *);
58 	void (*opt)(int, char * const *);
59 	int cmp;
60 };
61 
62 int procstat_opts = 0;
63 
64 static void cmdopt_none(int argc, char * const argv[]);
65 static void cmdopt_verbose(int argc, char * const argv[]);
66 static void cmdopt_signals(int argc, char * const argv[]);
67 static void cmdopt_rusage(int argc, char * const argv[]);
68 static void cmdopt_files(int argc, char * const argv[]);
69 static void cmdopt_cpuset(int argc, char * const argv[]);
70 
71 static const char *progname;
72 
73 /* aliased program parameters and arguments
74  * - usage field is abused to hold the pointer to the function
75  *   displaying program usage
76  */
77 static const struct procstat_cmd pacmd_table[] = {
78 	/* arguments are the same as for pwdx: pid or core file */
79 	{ "pargs", "args", NULL, &procstat_pargs, &cmdopt_none,
80 	    PS_CMP_NORMAL | PS_MODE_COMPAT },
81 	{ "penv", "env", NULL, &procstat_penv, &cmdopt_none,
82 	    PS_CMP_NORMAL | PS_MODE_COMPAT },
83 	{ "pwdx", "pwd", NULL, &procstat_pwdx, &cmdopt_none,
84 	    PS_CMP_NORMAL | PS_MODE_COMPAT }
85 };
86 
87 /* procstat parameters and arguments */
88 static const struct procstat_cmd cmd_table[] = {
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, len;
239 
240 	if (pprogname == NULL)
241 		return (NULL);
242 	len = strlen(pprogname);
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)
428 		cmd = getcmd(argv[0]);
429 	if (cmd != NULL) {
430 		if ((procstat_opts & PS_SUBCOMMAND_OPTS) != 0)
431 			usage(cmd);
432 		if (cmd->opt != NULL) {
433 			optreset = 1;
434 			optind = 1;
435 			cmd->opt(argc, argv);
436 			if ((cmd->cmp & PS_MODE_COMPAT) == 0) {
437 				argc -= optind;
438 				argv += optind;
439 			}
440 		} else {
441 			argc -= 1;
442 			argv += 1;
443 		}
444 	} else {
445 		cmd = getcmd("basic");
446 	}
447 	if (cmd->cmd != procstat_files &&
448 	    (procstat_opts & PS_OPT_CAPABILITIES) != 0 &&
449 	    (cmd->cmp & PS_MODE_COMPAT) == 0)
450 		usage(cmd);
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