xref: /illumos-gate/usr/src/cmd/dtrace/dtrace.c (revision 35551380472894a564e057962b701af78f719377)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/wait.h>
32 
33 #include <dtrace.h>
34 #include <stdlib.h>
35 #include <stdarg.h>
36 #include <stdio.h>
37 #include <strings.h>
38 #include <unistd.h>
39 #include <limits.h>
40 #include <fcntl.h>
41 #include <errno.h>
42 #include <signal.h>
43 #include <alloca.h>
44 #include <libgen.h>
45 #include <libproc.h>
46 
47 typedef struct dtrace_cmd {
48 	void (*dc_func)(struct dtrace_cmd *);	/* function to compile arg */
49 	dtrace_probespec_t dc_spec;		/* probe specifier context */
50 	char *dc_arg;				/* argument from main argv */
51 	const char *dc_name;			/* name for error messages */
52 	const char *dc_desc;			/* desc for error messages */
53 	dtrace_prog_t *dc_prog;			/* program compiled from arg */
54 	char dc_ofile[PATH_MAX];		/* derived output file name */
55 } dtrace_cmd_t;
56 
57 #define	DMODE_VERS	0	/* display version information and exit (-V) */
58 #define	DMODE_EXEC	1	/* compile program for enabling (-a/e/E) */
59 #define	DMODE_ANON	2	/* compile program for anonymous tracing (-A) */
60 #define	DMODE_LINK	3	/* compile program for linking with ELF (-G) */
61 #define	DMODE_LIST	4	/* compile program and list probes (-l) */
62 
63 #define	E_SUCCESS	0
64 #define	E_ERROR		1
65 #define	E_USAGE		2
66 
67 static const char DTRACE_OPTSTR[] =
68 	"3:6:aAb:Bc:CD:ef:FGHi:I:lL:m:n:o:p:P:qs:SU:vVwx:X:Z";
69 
70 static char **g_argv;
71 static int g_argc;
72 static char **g_objv;
73 static int g_objc;
74 static dtrace_cmd_t *g_cmdv;
75 static int g_cmdc;
76 static struct ps_prochandle **g_psv;
77 static int g_psc;
78 static int g_pslive;
79 static char *g_pname;
80 static int g_quiet;
81 static int g_flowindent;
82 static int g_intr;
83 static int g_impatient;
84 static int g_newline;
85 static int g_total;
86 static int g_cflags;
87 static int g_oflags;
88 static int g_verbose;
89 static int g_exec = 1;
90 static int g_mode = DMODE_EXEC;
91 static int g_status = E_SUCCESS;
92 static int g_grabanon = 0;
93 static const char *g_ofile = NULL;
94 static FILE *g_ofp = stdout;
95 static dtrace_hdl_t *g_dtp;
96 static char *g_etcfile = "/etc/system";
97 static const char *g_etcbegin = "* vvvv Added by DTrace";
98 static const char *g_etcend = "* ^^^^ Added by DTrace";
99 
100 static const char *g_etc[] =  {
101 "*",
102 "* The following forceload directives were added by dtrace(1M) to allow for",
103 "* tracing during boot.  If these directives are removed, the system will",
104 "* continue to function, but tracing will not occur during boot as desired.",
105 "* To remove these directives (and this block comment) automatically, run",
106 "* \"dtrace -A\" without additional arguments.  See the \"Anonymous Tracing\"",
107 "* chapter of the Solaris Dynamic Tracing Guide for details.",
108 "*",
109 NULL };
110 
111 static int
112 usage(FILE *fp)
113 {
114 	static const char predact[] = "[[ predicate ] action ]";
115 
116 	(void) fprintf(fp, "Usage: %s [-32|-64] [-aACeFGHlqSvVwZ] "
117 	    "[-b bufsz] [-c cmd] [-D name[=def]]\n\t[-I path] [-L path] "
118 	    "[-o output] [-p pid] [-s script] [-U name]\n\t"
119 	    "[-x opt[=val]] [-X a|c|s|t]\n\n"
120 	    "\t[-P provider %s]\n"
121 	    "\t[-m [ provider: ] module %s]\n"
122 	    "\t[-f [[ provider: ] module: ] func %s]\n"
123 	    "\t[-n [[[ provider: ] module: ] func: ] name %s]\n"
124 	    "\t[-i probe-id %s] [ args ... ]\n\n", g_pname,
125 	    predact, predact, predact, predact, predact);
126 
127 	(void) fprintf(fp, "\tpredicate -> '/' D-expression '/'\n");
128 	(void) fprintf(fp, "\t   action -> '{' D-statements '}'\n");
129 
130 	(void) fprintf(fp, "\n"
131 	    "\t-32 generate 32-bit D programs and ELF files\n"
132 	    "\t-64 generate 64-bit D programs and ELF files\n\n"
133 	    "\t-a  claim anonymous tracing state\n"
134 	    "\t-A  generate driver.conf(4) directives for anonymous tracing\n"
135 	    "\t-b  set trace buffer size\n"
136 	    "\t-c  run specified command and exit upon its completion\n"
137 	    "\t-C  run cpp(1) preprocessor on script files\n"
138 	    "\t-D  define symbol when invoking preprocessor\n"
139 	    "\t-e  exit after compiling request but prior to enabling probes\n"
140 	    "\t-f  enable or list probes matching the specified function name\n"
141 	    "\t-F  coalesce trace output by function\n"
142 	    "\t-G  generate an ELF file containing embedded dtrace program\n"
143 	    "\t-H  print included files when invoking preprocessor\n"
144 	    "\t-i  enable or list probes matching the specified probe id\n"
145 	    "\t-I  add include directory to preprocessor search path\n"
146 	    "\t-l  list probes matching specified criteria\n"
147 	    "\t-L  add library directory to library search path\n"
148 	    "\t-m  enable or list probes matching the specified module name\n"
149 	    "\t-n  enable or list probes matching the specified probe name\n"
150 	    "\t-o  set output file\n"
151 	    "\t-p  grab specified process-ID and cache its symbol tables\n"
152 	    "\t-P  enable or list probes matching the specified provider name\n"
153 	    "\t-q  set quiet mode (only output explicitly traced data)\n"
154 	    "\t-s  enable or list probes according to the specified D script\n"
155 	    "\t-S  print D compiler intermediate code\n"
156 	    "\t-U  undefine symbol when invoking preprocessor\n"
157 	    "\t-v  set verbose mode (report stability attributes, arguments)\n"
158 	    "\t-V  report DTrace API version\n"
159 	    "\t-w  permit destructive actions\n"
160 	    "\t-x  enable or modify compiler and tracing options\n"
161 	    "\t-X  specify ISO C conformance settings for preprocessor\n"
162 	    "\t-Z  permit probe descriptions that match zero probes\n");
163 
164 	return (E_USAGE);
165 }
166 
167 static void
168 verror(const char *fmt, va_list ap)
169 {
170 	int error = errno;
171 
172 	(void) fprintf(stderr, "%s: ", g_pname);
173 	(void) vfprintf(stderr, fmt, ap);
174 
175 	if (fmt[strlen(fmt) - 1] != '\n')
176 		(void) fprintf(stderr, ": %s\n", strerror(error));
177 }
178 
179 /*PRINTFLIKE1*/
180 static void
181 fatal(const char *fmt, ...)
182 {
183 	va_list ap;
184 
185 	va_start(ap, fmt);
186 	verror(fmt, ap);
187 	va_end(ap);
188 
189 	exit(E_ERROR);
190 }
191 
192 /*PRINTFLIKE1*/
193 static void
194 dfatal(const char *fmt, ...)
195 {
196 	va_list ap;
197 
198 	va_start(ap, fmt);
199 
200 	(void) fprintf(stderr, "%s: ", g_pname);
201 	if (fmt != NULL)
202 		(void) vfprintf(stderr, fmt, ap);
203 
204 	va_end(ap);
205 
206 	if (fmt != NULL && fmt[strlen(fmt) - 1] != '\n') {
207 		(void) fprintf(stderr, ": %s\n",
208 		    dtrace_errmsg(g_dtp, dtrace_errno(g_dtp)));
209 	} else if (fmt == NULL) {
210 		(void) fprintf(stderr, "%s\n",
211 		    dtrace_errmsg(g_dtp, dtrace_errno(g_dtp)));
212 	}
213 
214 	exit(E_ERROR);
215 }
216 
217 /*PRINTFLIKE1*/
218 static void
219 error(const char *fmt, ...)
220 {
221 	va_list ap;
222 
223 	va_start(ap, fmt);
224 	verror(fmt, ap);
225 	va_end(ap);
226 }
227 
228 /*PRINTFLIKE1*/
229 static void
230 notice(const char *fmt, ...)
231 {
232 	va_list ap;
233 
234 	if (g_quiet)
235 		return; /* -q or quiet pragma suppresses notice()s */
236 
237 	va_start(ap, fmt);
238 	verror(fmt, ap);
239 	va_end(ap);
240 }
241 
242 /*PRINTFLIKE1*/
243 static void
244 oprintf(const char *fmt, ...)
245 {
246 	va_list ap;
247 	int n;
248 
249 	if (g_ofp == NULL)
250 		return;
251 
252 	va_start(ap, fmt);
253 	n = vfprintf(g_ofp, fmt, ap);
254 	va_end(ap);
255 
256 	if (n < 0) {
257 		if (errno != EINTR) {
258 			fatal("failed to write to %s",
259 			    g_ofile ? g_ofile : "<stdout>");
260 		}
261 		clearerr(g_ofp);
262 	}
263 }
264 
265 static char **
266 make_argv(char *s)
267 {
268 	const char *ws = "\f\n\r\t\v ";
269 	char **argv = malloc(sizeof (char *) * (strlen(s) / 2 + 1));
270 	int argc = 0;
271 	char *p = s;
272 
273 	if (argv == NULL)
274 		return (NULL);
275 
276 	for (p = strtok(s, ws); p != NULL; p = strtok(NULL, ws))
277 		argv[argc++] = p;
278 
279 	if (argc == 0)
280 		argv[argc++] = s;
281 
282 	argv[argc] = NULL;
283 	return (argv);
284 }
285 
286 static void
287 dof_prune(const char *fname)
288 {
289 	struct stat sbuf;
290 	size_t sz, i, j, mark, len;
291 	char *buf;
292 	int msg = 0, fd;
293 
294 	if ((fd = open(fname, O_RDONLY)) == -1) {
295 		/*
296 		 * This is okay only if the file doesn't exist at all.
297 		 */
298 		if (errno != ENOENT)
299 			fatal("failed to open %s", fname);
300 		return;
301 	}
302 
303 	if (fstat(fd, &sbuf) == -1)
304 		fatal("failed to fstat %s", fname);
305 
306 	if ((buf = malloc((sz = sbuf.st_size) + 1)) == NULL)
307 		fatal("failed to allocate memory for %s", fname);
308 
309 	if (read(fd, buf, sz) != sz)
310 		fatal("failed to read %s", fname);
311 
312 	buf[sz] = '\0';
313 	(void) close(fd);
314 
315 	if ((fd = open(fname, O_WRONLY | O_TRUNC)) == -1)
316 		fatal("failed to open %s for writing", fname);
317 
318 	len = strlen("dof-data-");
319 
320 	for (mark = 0, i = 0; i < sz; i++) {
321 		if (strncmp(&buf[i], "dof-data-", len) != 0)
322 			continue;
323 
324 		/*
325 		 * This is only a match if it's in the 0th column.
326 		 */
327 		if (i != 0 && buf[i - 1] != '\n')
328 			continue;
329 
330 		if (msg++ == 0) {
331 			error("cleaned up old anonymous "
332 			    "enabling in %s\n", fname);
333 		}
334 
335 		/*
336 		 * We have a match.  First write out our data up until now.
337 		 */
338 		if (i != mark) {
339 			if (write(fd, &buf[mark], i - mark) != i - mark)
340 				fatal("failed to write to %s", fname);
341 		}
342 
343 		/*
344 		 * Now scan forward until we scan past a newline.
345 		 */
346 		for (j = i; j < sz && buf[j] != '\n'; j++)
347 			continue;
348 
349 		/*
350 		 * Reset our mark.
351 		 */
352 		if ((mark = j + 1) >= sz)
353 			break;
354 
355 		i = j;
356 	}
357 
358 	if (mark < sz) {
359 		if (write(fd, &buf[mark], sz - mark) != sz - mark)
360 			fatal("failed to write to %s", fname);
361 	}
362 
363 	(void) close(fd);
364 	free(buf);
365 }
366 
367 static void
368 etcsystem_prune(void)
369 {
370 	struct stat sbuf;
371 	size_t sz;
372 	char *buf, *start, *end;
373 	int fd;
374 	char *fname = g_etcfile, *tmpname;
375 
376 	if ((fd = open(fname, O_RDONLY)) == -1)
377 		fatal("failed to open %s", fname);
378 
379 	if (fstat(fd, &sbuf) == -1)
380 		fatal("failed to fstat %s", fname);
381 
382 	if ((buf = malloc((sz = sbuf.st_size) + 1)) == NULL)
383 		fatal("failed to allocate memory for %s", fname);
384 
385 	if (read(fd, buf, sz) != sz)
386 		fatal("failed to read %s", fname);
387 
388 	buf[sz] = '\0';
389 	(void) close(fd);
390 
391 	if ((start = strstr(buf, g_etcbegin)) == NULL)
392 		goto out;
393 
394 	if (strlen(buf) != sz) {
395 		fatal("embedded nul byte in %s; manual repair of %s "
396 		    "required\n", fname, fname);
397 	}
398 
399 	if (strstr(start + 1, g_etcbegin) != NULL) {
400 		fatal("multiple start sentinels in %s; manual repair of %s "
401 		    "required\n", fname, fname);
402 	}
403 
404 	if ((end = strstr(buf, g_etcend)) == NULL) {
405 		fatal("missing end sentinel in %s; manual repair of %s "
406 		    "required\n", fname, fname);
407 	}
408 
409 	if (start > end) {
410 		fatal("end sentinel preceeds start sentinel in %s; manual "
411 		    "repair of %s required\n", fname, fname);
412 	}
413 
414 	end += strlen(g_etcend) + 1;
415 	bcopy(end, start, strlen(end) + 1);
416 
417 	tmpname = alloca(sz = strlen(fname) + 80);
418 	(void) snprintf(tmpname, sz, "%s.dtrace.%d", fname, getpid());
419 
420 	if ((fd = open(tmpname,
421 	    O_WRONLY | O_CREAT | O_EXCL, sbuf.st_mode)) == -1)
422 		fatal("failed to create %s", tmpname);
423 
424 	if (write(fd, buf, strlen(buf)) < strlen(buf)) {
425 		(void) unlink(tmpname);
426 		fatal("failed to write to %s", tmpname);
427 	}
428 
429 	(void) close(fd);
430 
431 	if (chown(tmpname, sbuf.st_uid, sbuf.st_gid) != 0) {
432 		(void) unlink(tmpname);
433 		fatal("failed to chown(2) %s to uid %d, gid %d", tmpname,
434 		    (int)sbuf.st_uid, (int)sbuf.st_gid);
435 	}
436 
437 	if (rename(tmpname, fname) == -1)
438 		fatal("rename of %s to %s failed", tmpname, fname);
439 
440 	error("cleaned up forceload directives in %s\n", fname);
441 out:
442 	free(buf);
443 }
444 
445 static void
446 etcsystem_add(void)
447 {
448 	const char *mods[20];
449 	int nmods, line;
450 
451 	if ((g_ofp = fopen(g_ofile = g_etcfile, "a")) == NULL)
452 		fatal("failed to open output file '%s'", g_ofile);
453 
454 	oprintf("%s\n", g_etcbegin);
455 
456 	for (line = 0; g_etc[line] != NULL; line++)
457 		oprintf("%s\n", g_etc[line]);
458 
459 	nmods = dtrace_provider_modules(g_dtp, mods,
460 	    sizeof (mods) / sizeof (char *) - 1);
461 
462 	if (nmods >= sizeof (mods) / sizeof (char *))
463 		fatal("unexpectedly large number of modules!");
464 
465 	mods[nmods++] = "dtrace";
466 
467 	for (line = 0; line < nmods; line++)
468 		oprintf("forceload: drv/%s\n", mods[line]);
469 
470 	oprintf("%s\n", g_etcend);
471 
472 	if (fclose(g_ofp) == EOF)
473 		fatal("failed to close output file '%s'", g_ofile);
474 
475 	error("added forceload directives to %s\n", g_ofile);
476 }
477 
478 static void
479 print_probe_info(const dtrace_probeinfo_t *p)
480 {
481 	char buf[BUFSIZ];
482 	int i;
483 
484 	oprintf("\n\tProbe Description Attributes\n");
485 
486 	oprintf("\t\tIdentifier Names: %s\n",
487 	    dtrace_stability_name(p->dtp_attr.dtat_name));
488 	oprintf("\t\tData Semantics:   %s\n",
489 	    dtrace_stability_name(p->dtp_attr.dtat_data));
490 	oprintf("\t\tDependency Class: %s\n",
491 	    dtrace_class_name(p->dtp_attr.dtat_class));
492 
493 	oprintf("\n\tArgument Attributes\n");
494 
495 	oprintf("\t\tIdentifier Names: %s\n",
496 	    dtrace_stability_name(p->dtp_arga.dtat_name));
497 	oprintf("\t\tData Semantics:   %s\n",
498 	    dtrace_stability_name(p->dtp_arga.dtat_data));
499 	oprintf("\t\tDependency Class: %s\n",
500 	    dtrace_class_name(p->dtp_arga.dtat_class));
501 
502 	oprintf("\n\tArgument Types\n");
503 
504 	for (i = 0; i < p->dtp_argc; i++) {
505 		if (ctf_type_name(p->dtp_argv[i].dtt_ctfp,
506 		    p->dtp_argv[i].dtt_type, buf, sizeof (buf)) == NULL)
507 			(void) strlcpy(buf, "(unknown)", sizeof (buf));
508 		oprintf("\t\targs[%d]: %s\n", i, buf);
509 	}
510 
511 	if (p->dtp_argc == 0)
512 		oprintf("\t\tNone\n");
513 
514 	oprintf("\n");
515 }
516 
517 /*ARGSUSED*/
518 static int
519 info_stmt(dtrace_hdl_t *dtp, dtrace_prog_t *pgp,
520     dtrace_stmtdesc_t *stp, dtrace_ecbdesc_t **last)
521 {
522 	dtrace_ecbdesc_t *edp = stp->dtsd_ecbdesc;
523 	dtrace_probedesc_t *pdp = &edp->dted_probe;
524 	dtrace_probeinfo_t p;
525 
526 	if (edp == *last)
527 		return (0);
528 
529 	oprintf("\n%s:%s:%s:%s\n",
530 	    pdp->dtpd_provider, pdp->dtpd_mod, pdp->dtpd_func, pdp->dtpd_name);
531 
532 	if (dtrace_probe_info(dtp, pdp, &p) == 0)
533 		print_probe_info(&p);
534 
535 	*last = edp;
536 	return (0);
537 }
538 
539 /*
540  * Execute the specified program by enabling the corresponding instrumentation.
541  * If -e has been specified, we get the program info but do not enable it.  If
542  * -v has been specified, we print a stability report for the program.
543  */
544 static void
545 exec_prog(const dtrace_cmd_t *dcp)
546 {
547 	dtrace_ecbdesc_t *last = NULL;
548 	dtrace_proginfo_t dpi;
549 
550 	if (!g_exec) {
551 		dtrace_program_info(g_dtp, dcp->dc_prog, &dpi);
552 	} else if (dtrace_program_exec(g_dtp, dcp->dc_prog, &dpi) == -1) {
553 		dfatal("failed to enable '%s'", dcp->dc_name);
554 	} else {
555 		notice("%s '%s' matched %u probe%s\n",
556 		    dcp->dc_desc, dcp->dc_name,
557 		    dpi.dpi_matches, dpi.dpi_matches == 1 ? "" : "s");
558 	}
559 
560 	if (g_verbose) {
561 		oprintf("\nStability attributes for %s %s:\n",
562 		    dcp->dc_desc, dcp->dc_name);
563 
564 		oprintf("\n\tMinimum Probe Description Attributes\n");
565 		oprintf("\t\tIdentifier Names: %s\n",
566 		    dtrace_stability_name(dpi.dpi_descattr.dtat_name));
567 		oprintf("\t\tData Semantics:   %s\n",
568 		    dtrace_stability_name(dpi.dpi_descattr.dtat_data));
569 		oprintf("\t\tDependency Class: %s\n",
570 		    dtrace_class_name(dpi.dpi_descattr.dtat_class));
571 
572 		oprintf("\n\tMinimum Statement Attributes\n");
573 
574 		oprintf("\t\tIdentifier Names: %s\n",
575 		    dtrace_stability_name(dpi.dpi_stmtattr.dtat_name));
576 		oprintf("\t\tData Semantics:   %s\n",
577 		    dtrace_stability_name(dpi.dpi_stmtattr.dtat_data));
578 		oprintf("\t\tDependency Class: %s\n",
579 		    dtrace_class_name(dpi.dpi_stmtattr.dtat_class));
580 
581 		if (!g_exec) {
582 			(void) dtrace_stmt_iter(g_dtp, dcp->dc_prog,
583 			    (dtrace_stmt_f *)info_stmt, &last);
584 		} else
585 			oprintf("\n");
586 	}
587 
588 	g_total += dpi.dpi_matches;
589 }
590 
591 /*
592  * Print out the specified DOF buffer as a set of ASCII bytes appropriate for
593  * storing in a driver.conf(4) file associated with the dtrace driver.
594  */
595 static void
596 anon_prog(const dtrace_cmd_t *dcp, dof_hdr_t *dof, int n)
597 {
598 	const uchar_t *p, *q;
599 
600 	if (dof == NULL)
601 		dfatal("failed to create DOF image for '%s'", dcp->dc_name);
602 
603 	p = (uchar_t *)dof;
604 	q = p + dof->dofh_loadsz;
605 
606 	oprintf("dof-data-%d=0x%x", n, *p++);
607 
608 	while (p < q)
609 		oprintf(",0x%x", *p++);
610 
611 	oprintf(";\n");
612 	dtrace_dof_destroy(g_dtp, dof);
613 }
614 
615 /*
616  * Link the specified D program in DOF form into an ELF file for use in either
617  * helpers, userland provider definitions, or both.  If -o was specified, that
618  * path is used as the output file name.  If -o wasn't specified and the input
619  * program is from a script whose name is %.d, use basename(%.o) as the output
620  * file name.  Otherwise we use "d.out" as the default output file name.
621  */
622 static void
623 link_prog(dtrace_cmd_t *dcp)
624 {
625 	char *p;
626 
627 	if (g_cmdc == 1 && g_ofile != NULL) {
628 		(void) strlcpy(dcp->dc_ofile, g_ofile, sizeof (dcp->dc_ofile));
629 	} else if ((p = strrchr(dcp->dc_arg, '.')) != NULL &&
630 	    strcmp(p, ".d") == 0) {
631 		p[0] = '\0'; /* strip .d suffix */
632 		(void) snprintf(dcp->dc_ofile, sizeof (dcp->dc_ofile),
633 		    "%s.o", basename(dcp->dc_arg));
634 	} else {
635 		(void) snprintf(dcp->dc_ofile, sizeof (dcp->dc_ofile),
636 		    g_cmdc > 1 ?  "%s.%d" : "%s", "d.out", (int)(dcp - g_cmdv));
637 	}
638 
639 	if (dtrace_program_link(g_dtp, dcp->dc_prog, DTRACE_D_PROBES,
640 	    dcp->dc_ofile, g_objc - 1, g_objv + 1) != 0)
641 		dfatal("failed to link %s %s", dcp->dc_desc, dcp->dc_name);
642 }
643 
644 /*ARGSUSED*/
645 static int
646 list_probe(dtrace_hdl_t *dtp, const dtrace_probedesc_t *pdp, void *arg)
647 {
648 	dtrace_probeinfo_t p;
649 
650 	oprintf("%5d %10s %17s %33s %s\n", pdp->dtpd_id,
651 	    pdp->dtpd_provider, pdp->dtpd_mod, pdp->dtpd_func, pdp->dtpd_name);
652 
653 	if (g_verbose && dtrace_probe_info(dtp, pdp, &p) == 0)
654 		print_probe_info(&p);
655 
656 	return (0);
657 }
658 
659 /*ARGSUSED*/
660 static int
661 list_stmt(dtrace_hdl_t *dtp, dtrace_prog_t *pgp,
662     dtrace_stmtdesc_t *stp, dtrace_ecbdesc_t **last)
663 {
664 	dtrace_ecbdesc_t *edp = stp->dtsd_ecbdesc;
665 
666 	if (edp == *last)
667 		return (0);
668 
669 	if (dtrace_probe_iter(g_dtp, &edp->dted_probe, list_probe, NULL) != 0) {
670 		error("failed to match %s:%s:%s:%s: %s\n",
671 		    edp->dted_probe.dtpd_provider, edp->dted_probe.dtpd_mod,
672 		    edp->dted_probe.dtpd_func, edp->dted_probe.dtpd_name,
673 		    dtrace_errmsg(dtp, dtrace_errno(dtp)));
674 	}
675 
676 	*last = edp;
677 	return (0);
678 }
679 
680 /*
681  * List the probes corresponding to the specified program by iterating over
682  * each statement and then matching probes to the statement probe descriptions.
683  */
684 static void
685 list_prog(const dtrace_cmd_t *dcp)
686 {
687 	dtrace_ecbdesc_t *last = NULL;
688 
689 	(void) dtrace_stmt_iter(g_dtp, dcp->dc_prog,
690 	    (dtrace_stmt_f *)list_stmt, &last);
691 }
692 
693 static void
694 compile_file(dtrace_cmd_t *dcp)
695 {
696 	char *arg0;
697 	FILE *fp;
698 
699 	if ((fp = fopen(dcp->dc_arg, "r")) == NULL)
700 		fatal("failed to open %s", dcp->dc_arg);
701 
702 	arg0 = g_argv[0];
703 	g_argv[0] = dcp->dc_arg;
704 
705 	if ((dcp->dc_prog = dtrace_program_fcompile(g_dtp, fp,
706 	    g_cflags, g_argc, g_argv)) == NULL)
707 		dfatal("failed to compile script %s", dcp->dc_arg);
708 
709 	g_argv[0] = arg0;
710 	(void) fclose(fp);
711 
712 	dcp->dc_desc = "script";
713 	dcp->dc_name = dcp->dc_arg;
714 }
715 
716 static void
717 compile_str(dtrace_cmd_t *dcp)
718 {
719 	char *p;
720 
721 	if ((dcp->dc_prog = dtrace_program_strcompile(g_dtp, dcp->dc_arg,
722 	    dcp->dc_spec, g_cflags | DTRACE_C_PSPEC, g_argc, g_argv)) == NULL)
723 		dfatal("invalid probe specifier %s", dcp->dc_arg);
724 
725 	if ((p = strpbrk(dcp->dc_arg, "{/;")) != NULL)
726 		*p = '\0'; /* crop name for reporting */
727 
728 	dcp->dc_desc = "description";
729 	dcp->dc_name = dcp->dc_arg;
730 }
731 
732 /*ARGSUSED*/
733 static void
734 prochandler(struct ps_prochandle *P, void *arg)
735 {
736 	const psinfo_t *prp = Ppsinfo(P);
737 	int pid = Pstatus(P)->pr_pid;
738 	char name[SIG2STR_MAX];
739 
740 	switch (Pstate(P)) {
741 	case PS_UNDEAD:
742 		/*
743 		 * Ideally we would like to always report pr_wstat here, but it
744 		 * isn't possible given current /proc semantics.  If we grabbed
745 		 * the process, Ppsinfo() will either fail or return a zeroed
746 		 * psinfo_t depending on how far the parent is in reaping it.
747 		 * When /proc provides a stable pr_wstat in the status file,
748 		 * this code can be improved by examining this new pr_wstat.
749 		 */
750 		if (prp != NULL && WIFSIGNALED(prp->pr_wstat)) {
751 			notice("pid %d terminated by %s\n", pid,
752 			    proc_signame(WTERMSIG(prp->pr_wstat),
753 			    name, sizeof (name)));
754 		} else if (prp != NULL && WEXITSTATUS(prp->pr_wstat) != 0) {
755 			notice("pid %d exited with status %d\n",
756 			    pid, WEXITSTATUS(prp->pr_wstat));
757 		} else {
758 			notice("pid %d has exited\n", pid);
759 		}
760 		g_pslive--;
761 		break;
762 
763 	case PS_LOST:
764 		notice("pid %d exec'd a set-id or unobservable program\n", pid);
765 		g_pslive--;
766 		break;
767 	}
768 }
769 
770 /*ARGSUSED*/
771 static int
772 errhandler(const dtrace_errdata_t *data, void *arg)
773 {
774 	error(data->dteda_msg);
775 	return (DTRACE_HANDLE_OK);
776 }
777 
778 /*ARGSUSED*/
779 static int
780 drophandler(const dtrace_dropdata_t *data, void *arg)
781 {
782 	error(data->dtdda_msg);
783 	return (DTRACE_HANDLE_OK);
784 }
785 
786 /*ARGSUSED*/
787 static int
788 setopthandler(const dtrace_setoptdata_t *data, void *arg)
789 {
790 	if (strcmp(data->dtsda_option, "quiet") == 0)
791 		g_quiet = data->dtsda_newval != DTRACEOPT_UNSET;
792 
793 	if (strcmp(data->dtsda_option, "flowindent") == 0)
794 		g_flowindent = data->dtsda_newval != DTRACEOPT_UNSET;
795 
796 	return (DTRACE_HANDLE_OK);
797 }
798 
799 #define	BUFDUMPHDR(hdr) \
800 	(void) printf("%s: %s%s\n", g_pname, hdr, strlen(hdr) > 0 ? ":" : "");
801 
802 #define	BUFDUMPSTR(ptr, field) \
803 	(void) printf("%s: %20s => ", g_pname, #field);	\
804 	if ((ptr)->field != NULL) {			\
805 		const char *c = (ptr)->field;		\
806 		(void) printf("\"");			\
807 		do {					\
808 			if (*c == '\n') {		\
809 				(void) printf("\\n");	\
810 				continue;		\
811 			}				\
812 							\
813 			(void) printf("%c", *c);	\
814 		} while (*c++ != '\0');			\
815 		(void) printf("\"\n");			\
816 	} else {					\
817 		(void) printf("<NULL>\n");		\
818 	}
819 
820 #define	BUFDUMPASSTR(ptr, field, str) \
821 	(void) printf("%s: %20s => %s\n", g_pname, #field, str);
822 
823 #define	BUFDUMP(ptr, field) \
824 	(void) printf("%s: %20s => %lld\n", g_pname, #field, \
825 	    (long long)(ptr)->field);
826 
827 #define	BUFDUMPPTR(ptr, field) \
828 	(void) printf("%s: %20s => %s\n", g_pname, #field, \
829 	    (ptr)->field != NULL ? "<non-NULL>" : "<NULL>");
830 
831 /*ARGSUSED*/
832 static int
833 bufhandler(const dtrace_bufdata_t *bufdata, void *arg)
834 {
835 	const dtrace_aggdata_t *agg = bufdata->dtbda_aggdata;
836 	const dtrace_recdesc_t *rec = bufdata->dtbda_recdesc;
837 	const dtrace_probedesc_t *pd;
838 	uint32_t flags = bufdata->dtbda_flags;
839 	char buf[512], *c = buf, *end = c + sizeof (buf);
840 	int i, printed;
841 
842 	struct {
843 		const char *name;
844 		uint32_t value;
845 	} flagnames[] = {
846 	    { "AGGVAL",		DTRACE_BUFDATA_AGGVAL },
847 	    { "AGGKEY",		DTRACE_BUFDATA_AGGKEY },
848 	    { "AGGFORMAT",	DTRACE_BUFDATA_AGGFORMAT },
849 	    { "AGGLAST",	DTRACE_BUFDATA_AGGLAST },
850 	    { "???",		UINT32_MAX },
851 	    { NULL }
852 	};
853 
854 	if (bufdata->dtbda_probe != NULL) {
855 		pd = bufdata->dtbda_probe->dtpda_pdesc;
856 	} else if (agg != NULL) {
857 		pd = agg->dtada_pdesc;
858 	} else {
859 		pd = NULL;
860 	}
861 
862 	BUFDUMPHDR(">>> Called buffer handler");
863 	BUFDUMPHDR("");
864 
865 	BUFDUMPHDR("  dtrace_bufdata");
866 	BUFDUMPSTR(bufdata, dtbda_buffered);
867 	BUFDUMPPTR(bufdata, dtbda_probe);
868 	BUFDUMPPTR(bufdata, dtbda_aggdata);
869 	BUFDUMPPTR(bufdata, dtbda_recdesc);
870 
871 	(void) snprintf(c, end - c, "0x%x ", bufdata->dtbda_flags);
872 	c += strlen(c);
873 
874 	for (i = 0, printed = 0; flagnames[i].name != NULL; i++) {
875 		if (!(flags & flagnames[i].value))
876 			continue;
877 
878 		(void) snprintf(c, end - c,
879 		    "%s%s", printed++ ? " | " : "(", flagnames[i].name);
880 		c += strlen(c);
881 		flags &= ~flagnames[i].value;
882 	}
883 
884 	if (printed)
885 		(void) snprintf(c, end - c, ")");
886 
887 	BUFDUMPASSTR(bufdata, dtbda_flags, buf);
888 	BUFDUMPHDR("");
889 
890 	if (pd != NULL) {
891 		BUFDUMPHDR("  dtrace_probedesc");
892 		BUFDUMPSTR(pd, dtpd_provider);
893 		BUFDUMPSTR(pd, dtpd_mod);
894 		BUFDUMPSTR(pd, dtpd_func);
895 		BUFDUMPSTR(pd, dtpd_name);
896 		BUFDUMPHDR("");
897 	}
898 
899 	if (rec != NULL) {
900 		BUFDUMPHDR("  dtrace_recdesc");
901 		BUFDUMP(rec, dtrd_action);
902 		BUFDUMP(rec, dtrd_size);
903 
904 		if (agg != NULL) {
905 			uint8_t *data;
906 			int lim = rec->dtrd_size;
907 
908 			(void) sprintf(buf, "%d (data: ", rec->dtrd_offset);
909 			c = buf + strlen(buf);
910 
911 			if (lim > sizeof (uint64_t))
912 				lim = sizeof (uint64_t);
913 
914 			data = (uint8_t *)agg->dtada_data + rec->dtrd_offset;
915 
916 			for (i = 0; i < lim; i++) {
917 				(void) snprintf(c, end - c, "%s%02x",
918 				    i == 0 ? "" : " ", *data++);
919 				c += strlen(c);
920 			}
921 
922 			(void) snprintf(c, end - c,
923 			    "%s)", lim < rec->dtrd_size ? " ..." : "");
924 			BUFDUMPASSTR(rec, dtrd_offset, buf);
925 		} else {
926 			BUFDUMP(rec, dtrd_offset);
927 		}
928 
929 		BUFDUMPHDR("");
930 	}
931 
932 	if (agg != NULL) {
933 		dtrace_aggdesc_t *desc = agg->dtada_desc;
934 
935 		BUFDUMPHDR("  dtrace_aggdesc");
936 		BUFDUMPSTR(desc, dtagd_name);
937 		BUFDUMP(desc, dtagd_varid);
938 		BUFDUMP(desc, dtagd_id);
939 		BUFDUMP(desc, dtagd_nrecs);
940 		BUFDUMPHDR("");
941 	}
942 
943 	return (DTRACE_HANDLE_OK);
944 }
945 
946 /*ARGSUSED*/
947 static int
948 chewrec(const dtrace_probedata_t *data, const dtrace_recdesc_t *rec, void *arg)
949 {
950 	dtrace_actkind_t act;
951 	uintptr_t addr;
952 
953 	if (rec == NULL) {
954 		/*
955 		 * We have processed the final record; output the newline if
956 		 * we're not in quiet mode.
957 		 */
958 		if (!g_quiet)
959 			oprintf("\n");
960 
961 		return (DTRACE_CONSUME_NEXT);
962 	}
963 
964 	act = rec->dtrd_action;
965 	addr = (uintptr_t)data->dtpda_data;
966 
967 	if (act == DTRACEACT_EXIT) {
968 		g_status = *((uint32_t *)addr);
969 		return (DTRACE_CONSUME_NEXT);
970 	}
971 
972 	return (DTRACE_CONSUME_THIS);
973 }
974 
975 /*ARGSUSED*/
976 static int
977 chew(const dtrace_probedata_t *data, void *arg)
978 {
979 	dtrace_probedesc_t *pd = data->dtpda_pdesc;
980 	processorid_t cpu = data->dtpda_cpu;
981 	static int heading;
982 
983 	if (g_impatient) {
984 		g_newline = 0;
985 		return (DTRACE_CONSUME_ABORT);
986 	}
987 
988 	if (heading == 0) {
989 		if (!g_flowindent) {
990 			if (!g_quiet) {
991 				oprintf("%3s %6s %32s\n",
992 				    "CPU", "ID", "FUNCTION:NAME");
993 			}
994 		} else {
995 			oprintf("%3s %-41s\n", "CPU", "FUNCTION");
996 		}
997 		heading = 1;
998 	}
999 
1000 	if (!g_flowindent) {
1001 		if (!g_quiet) {
1002 			char name[DTRACE_FUNCNAMELEN + DTRACE_NAMELEN + 2];
1003 
1004 			(void) snprintf(name, sizeof (name), "%s:%s",
1005 			    pd->dtpd_func, pd->dtpd_name);
1006 
1007 			oprintf("%3d %6d %32s ", cpu, pd->dtpd_id, name);
1008 		}
1009 	} else {
1010 		int indent = data->dtpda_indent;
1011 		char *name;
1012 		size_t len;
1013 
1014 		if (data->dtpda_flow == DTRACEFLOW_NONE) {
1015 			len = indent + DTRACE_FUNCNAMELEN + DTRACE_NAMELEN + 5;
1016 			name = alloca(len);
1017 			(void) snprintf(name, len, "%*s%s%s:%s", indent, "",
1018 			    data->dtpda_prefix, pd->dtpd_func,
1019 			    pd->dtpd_name);
1020 		} else {
1021 			len = indent + DTRACE_FUNCNAMELEN + 5;
1022 			name = alloca(len);
1023 			(void) snprintf(name, len, "%*s%s%s", indent, "",
1024 			    data->dtpda_prefix, pd->dtpd_func);
1025 		}
1026 
1027 		oprintf("%3d %-41s ", cpu, name);
1028 	}
1029 
1030 	return (DTRACE_CONSUME_THIS);
1031 }
1032 
1033 static void
1034 go(void)
1035 {
1036 	int i;
1037 
1038 	struct {
1039 		char *name;
1040 		char *optname;
1041 		dtrace_optval_t val;
1042 	} bufs[] = {
1043 		{ "buffer size", "bufsize" },
1044 		{ "aggregation size", "aggsize" },
1045 		{ "speculation size", "specsize" },
1046 		{ "dynamic variable size", "dynvarsize" },
1047 		{ NULL }
1048 	}, rates[] = {
1049 		{ "cleaning rate", "cleanrate" },
1050 		{ "status rate", "statusrate" },
1051 		{ NULL }
1052 	};
1053 
1054 	for (i = 0; bufs[i].name != NULL; i++) {
1055 		if (dtrace_getopt(g_dtp, bufs[i].optname, &bufs[i].val) == -1)
1056 			fatal("couldn't get option %s", bufs[i].optname);
1057 	}
1058 
1059 	for (i = 0; rates[i].name != NULL; i++) {
1060 		if (dtrace_getopt(g_dtp, rates[i].optname, &rates[i].val) == -1)
1061 			fatal("couldn't get option %s", rates[i].optname);
1062 	}
1063 
1064 	if (dtrace_go(g_dtp) == -1)
1065 		dfatal("could not enable tracing");
1066 
1067 	for (i = 0; bufs[i].name != NULL; i++) {
1068 		dtrace_optval_t j = 0, mul = 10;
1069 		dtrace_optval_t nsize;
1070 
1071 		if (bufs[i].val == DTRACEOPT_UNSET)
1072 			continue;
1073 
1074 		(void) dtrace_getopt(g_dtp, bufs[i].optname, &nsize);
1075 
1076 		if (nsize == DTRACEOPT_UNSET || nsize == 0)
1077 			continue;
1078 
1079 		if (nsize >= bufs[i].val - sizeof (uint64_t))
1080 			continue;
1081 
1082 		for (; (INT64_C(1) << mul) <= nsize; j++, mul += 10)
1083 			continue;
1084 
1085 		if (!(nsize & ((INT64_C(1) << (mul - 10)) - 1))) {
1086 			error("%s lowered to %lld%c\n", bufs[i].name,
1087 			    (long long)nsize >> (mul - 10), " kmgtpe"[j]);
1088 		} else {
1089 			error("%s lowered to %lld bytes\n", bufs[i].name,
1090 			    (long long)nsize);
1091 		}
1092 	}
1093 
1094 	for (i = 0; rates[i].name != NULL; i++) {
1095 		dtrace_optval_t nval;
1096 		char *dir;
1097 
1098 		if (rates[i].val == DTRACEOPT_UNSET)
1099 			continue;
1100 
1101 		(void) dtrace_getopt(g_dtp, rates[i].optname, &nval);
1102 
1103 		if (nval == DTRACEOPT_UNSET || nval == 0)
1104 			continue;
1105 
1106 		if (rates[i].val == nval)
1107 			continue;
1108 
1109 		dir = nval > rates[i].val ? "reduced" : "increased";
1110 
1111 		if (nval <= NANOSEC && (NANOSEC % nval) == 0) {
1112 			error("%s %s to %lld hz\n", rates[i].name, dir,
1113 			    (long long)NANOSEC / (long long)nval);
1114 			continue;
1115 		}
1116 
1117 		if ((nval % NANOSEC) == 0) {
1118 			error("%s %s to once every %lld seconds\n",
1119 			    rates[i].name, dir,
1120 			    (long long)nval / (long long)NANOSEC);
1121 			continue;
1122 		}
1123 
1124 		error("%s %s to once every %lld nanoseconds\n",
1125 		    rates[i].name, dir, (long long)nval);
1126 	}
1127 }
1128 
1129 /*ARGSUSED*/
1130 static void
1131 intr(int signo)
1132 {
1133 	if (!g_intr)
1134 		g_newline = 1;
1135 
1136 	if (g_intr++)
1137 		g_impatient = 1;
1138 }
1139 
1140 int
1141 main(int argc, char *argv[])
1142 {
1143 	dtrace_bufdesc_t buf;
1144 	struct sigaction act;
1145 	dtrace_status_t status[2];
1146 	dtrace_optval_t opt;
1147 	dtrace_cmd_t *dcp;
1148 
1149 	int done = 0, mode = 0;
1150 	int err, i;
1151 	char c, *p, **v;
1152 	struct ps_prochandle *P;
1153 	pid_t pid;
1154 
1155 	g_pname = basename(argv[0]);
1156 
1157 	if (argc == 1)
1158 		return (usage(stderr));
1159 
1160 	if ((g_argv = malloc(sizeof (char *) * argc)) == NULL ||
1161 	    (g_cmdv = malloc(sizeof (dtrace_cmd_t) * argc)) == NULL ||
1162 	    (g_psv = malloc(sizeof (struct ps_prochandle *) * argc)) == NULL)
1163 		fatal("failed to allocate memory for arguments");
1164 
1165 	g_argv[g_argc++] = argv[0];	/* propagate argv[0] to D as $0/$$0 */
1166 	argv[0] = g_pname;		/* rewrite argv[0] for getopt errors */
1167 
1168 	bzero(status, sizeof (status));
1169 	bzero(&buf, sizeof (buf));
1170 
1171 	/*
1172 	 * Make an initial pass through argv[] processing any arguments that
1173 	 * affect our behavior mode (g_mode) and flags used for dtrace_open().
1174 	 * We also accumulate arguments that are not affiliated with getopt
1175 	 * options into g_argv[], and abort if any invalid options are found.
1176 	 */
1177 	for (optind = 1; optind < argc; optind++) {
1178 		while ((c = getopt(argc, argv, DTRACE_OPTSTR)) != EOF) {
1179 			switch (c) {
1180 			case '3':
1181 				if (strcmp(optarg, "2") != 0) {
1182 					(void) fprintf(stderr,
1183 					    "%s: illegal option -- 3%s\n",
1184 					    argv[0], optarg);
1185 					return (usage(stderr));
1186 				}
1187 				g_oflags &= ~DTRACE_O_LP64;
1188 				g_oflags |= DTRACE_O_ILP32;
1189 				break;
1190 
1191 			case '6':
1192 				if (strcmp(optarg, "4") != 0) {
1193 					(void) fprintf(stderr,
1194 					    "%s: illegal option -- 6%s\n",
1195 					    argv[0], optarg);
1196 					return (usage(stderr));
1197 				}
1198 				g_oflags &= ~DTRACE_O_ILP32;
1199 				g_oflags |= DTRACE_O_LP64;
1200 				break;
1201 
1202 			case 'a':
1203 				g_grabanon++; /* also checked in pass 2 below */
1204 				break;
1205 
1206 			case 'A':
1207 				g_mode = DMODE_ANON;
1208 				g_exec = 0;
1209 				mode++;
1210 				break;
1211 
1212 			case 'e':
1213 				g_exec = 0;
1214 				done = 1;
1215 				break;
1216 
1217 			case 'G':
1218 				g_mode = DMODE_LINK;
1219 				g_oflags |= DTRACE_O_NODEV;
1220 				g_cflags |= DTRACE_C_ZDEFS; /* -G implies -Z */
1221 				g_exec = 0;
1222 				mode++;
1223 				break;
1224 
1225 			case 'l':
1226 				g_mode = DMODE_LIST;
1227 				g_cflags |= DTRACE_C_ZDEFS; /* -l implies -Z */
1228 				mode++;
1229 				break;
1230 
1231 			case 'V':
1232 				g_mode = DMODE_VERS;
1233 				mode++;
1234 				break;
1235 
1236 			default:
1237 				if (strchr(DTRACE_OPTSTR, c) == NULL)
1238 					return (usage(stderr));
1239 			}
1240 		}
1241 
1242 		if (optind < argc)
1243 			g_argv[g_argc++] = argv[optind];
1244 	}
1245 
1246 	if (mode > 1) {
1247 		(void) fprintf(stderr, "%s: only one of the [-AGlV] options "
1248 		    "can be specified at a time\n", g_pname);
1249 		return (E_USAGE);
1250 	}
1251 
1252 	if (g_mode == DMODE_VERS)
1253 		return (printf("%s: %s\n", g_pname, _dtrace_version) <= 0);
1254 
1255 	/*
1256 	 * Open libdtrace.  If we are not actually going to be enabling any
1257 	 * instrumentation attempt to reopen libdtrace using DTRACE_O_NODEV.
1258 	 */
1259 	while ((g_dtp = dtrace_open(DTRACE_VERSION, g_oflags, &err)) == NULL) {
1260 		if (!(g_oflags & DTRACE_O_NODEV) && !g_exec && !g_grabanon) {
1261 			g_oflags |= DTRACE_O_NODEV;
1262 			continue;
1263 		}
1264 
1265 		fatal("failed to initialize dtrace: %s\n",
1266 		    dtrace_errmsg(NULL, err));
1267 	}
1268 
1269 	(void) dtrace_setopt(g_dtp, "bufsize", "4m");
1270 	(void) dtrace_setopt(g_dtp, "aggsize", "4m");
1271 
1272 	/*
1273 	 * If -G is specified, enable -xlink=dynamic and -xunodefs to permit
1274 	 * references to undefined symbols to remain as unresolved relocations.
1275 	 * If -A is specified, enable -xlink=primary to permit static linking
1276 	 * only to kernel symbols that are defined in a primary kernel module.
1277 	 */
1278 	if (g_mode == DMODE_LINK) {
1279 		(void) dtrace_setopt(g_dtp, "linkmode", "dynamic");
1280 		(void) dtrace_setopt(g_dtp, "unodefs", NULL);
1281 
1282 		g_objc = g_argc;
1283 		g_objv = g_argv;
1284 
1285 		/*
1286 		 * We still use g_argv[0], the name of the executable.
1287 		 */
1288 		g_argc = 1;
1289 	} else if (g_mode == DMODE_ANON)
1290 		(void) dtrace_setopt(g_dtp, "linkmode", "primary");
1291 
1292 	/*
1293 	 * Now that we have libdtrace open, make a second pass through argv[]
1294 	 * to perform any dtrace_setopt() calls and change any compiler flags.
1295 	 * We also accumulate any program specifications into our g_cmdv[] at
1296 	 * this time; these will compiled as part of the fourth processing pass.
1297 	 */
1298 	for (optind = 1; optind < argc; optind++) {
1299 		while ((c = getopt(argc, argv, DTRACE_OPTSTR)) != EOF) {
1300 			switch (c) {
1301 			case 'a':
1302 				if (dtrace_setopt(g_dtp, "grabanon", 0) != 0)
1303 					dfatal("failed to set -a");
1304 				break;
1305 
1306 			case 'b':
1307 				if (dtrace_setopt(g_dtp,
1308 				    "bufsize", optarg) != 0)
1309 					dfatal("failed to set -b %s", optarg);
1310 				break;
1311 
1312 			case 'B':
1313 				g_ofp = NULL;
1314 				break;
1315 
1316 			case 'C':
1317 				g_cflags |= DTRACE_C_CPP;
1318 				break;
1319 
1320 			case 'D':
1321 				if (dtrace_setopt(g_dtp, "define", optarg) != 0)
1322 					dfatal("failed to set -D %s", optarg);
1323 				break;
1324 
1325 			case 'f':
1326 				dcp = &g_cmdv[g_cmdc++];
1327 				dcp->dc_func = compile_str;
1328 				dcp->dc_spec = DTRACE_PROBESPEC_FUNC;
1329 				dcp->dc_arg = optarg;
1330 				break;
1331 
1332 			case 'F':
1333 				if (dtrace_setopt(g_dtp, "flowindent", 0) != 0)
1334 					dfatal("failed to set -F");
1335 				break;
1336 
1337 			case 'H':
1338 				if (dtrace_setopt(g_dtp, "cpphdrs", 0) != 0)
1339 					dfatal("failed to set -H");
1340 				break;
1341 
1342 			case 'i':
1343 				dcp = &g_cmdv[g_cmdc++];
1344 				dcp->dc_func = compile_str;
1345 				dcp->dc_spec = DTRACE_PROBESPEC_NAME;
1346 				dcp->dc_arg = optarg;
1347 				break;
1348 
1349 			case 'I':
1350 				if (dtrace_setopt(g_dtp, "incdir", optarg) != 0)
1351 					dfatal("failed to set -I %s", optarg);
1352 				break;
1353 
1354 			case 'L':
1355 				if (dtrace_setopt(g_dtp, "libdir", optarg) != 0)
1356 					dfatal("failed to set -L %s", optarg);
1357 				break;
1358 
1359 			case 'm':
1360 				dcp = &g_cmdv[g_cmdc++];
1361 				dcp->dc_func = compile_str;
1362 				dcp->dc_spec = DTRACE_PROBESPEC_MOD;
1363 				dcp->dc_arg = optarg;
1364 				break;
1365 
1366 			case 'n':
1367 				dcp = &g_cmdv[g_cmdc++];
1368 				dcp->dc_func = compile_str;
1369 				dcp->dc_spec = DTRACE_PROBESPEC_NAME;
1370 				dcp->dc_arg = optarg;
1371 				break;
1372 
1373 			case 'P':
1374 				dcp = &g_cmdv[g_cmdc++];
1375 				dcp->dc_func = compile_str;
1376 				dcp->dc_spec = DTRACE_PROBESPEC_PROVIDER;
1377 				dcp->dc_arg = optarg;
1378 				break;
1379 
1380 			case 'q':
1381 				if (dtrace_setopt(g_dtp, "quiet", 0) != 0)
1382 					dfatal("failed to set -q");
1383 				break;
1384 
1385 			case 'o':
1386 				g_ofile = optarg;
1387 				break;
1388 
1389 			case 's':
1390 				dcp = &g_cmdv[g_cmdc++];
1391 				dcp->dc_func = compile_file;
1392 				dcp->dc_spec = DTRACE_PROBESPEC_NONE;
1393 				dcp->dc_arg = optarg;
1394 				break;
1395 
1396 			case 'S':
1397 				g_cflags |= DTRACE_C_DIFV;
1398 				break;
1399 
1400 			case 'U':
1401 				if (dtrace_setopt(g_dtp, "undef", optarg) != 0)
1402 					dfatal("failed to set -U %s", optarg);
1403 				break;
1404 
1405 			case 'v':
1406 				g_verbose++;
1407 				break;
1408 
1409 			case 'w':
1410 				if (dtrace_setopt(g_dtp, "destructive", 0) != 0)
1411 					dfatal("failed to set -w");
1412 				break;
1413 
1414 			case 'x':
1415 				if ((p = strchr(optarg, '=')) != NULL)
1416 					*p++ = '\0';
1417 
1418 				if (dtrace_setopt(g_dtp, optarg, p) != 0)
1419 					dfatal("failed to set -x %s", optarg);
1420 				break;
1421 
1422 			case 'X':
1423 				if (dtrace_setopt(g_dtp, "stdc", optarg) != 0)
1424 					dfatal("failed to set -X %s", optarg);
1425 				break;
1426 
1427 			case 'Z':
1428 				g_cflags |= DTRACE_C_ZDEFS;
1429 				break;
1430 
1431 			default:
1432 				if (strchr(DTRACE_OPTSTR, c) == NULL)
1433 					return (usage(stderr));
1434 			}
1435 		}
1436 	}
1437 
1438 	if (g_ofp == NULL && g_mode != DMODE_EXEC) {
1439 		(void) fprintf(stderr, "%s: -B not valid in combination"
1440 		    " with [-AGl] options\n", g_pname);
1441 		return (E_USAGE);
1442 	}
1443 
1444 	if (g_ofp == NULL && g_ofile != NULL) {
1445 		(void) fprintf(stderr, "%s: -B not valid in combination"
1446 		    " with -o option\n", g_pname);
1447 		return (E_USAGE);
1448 	}
1449 
1450 	/*
1451 	 * In our third pass we handle any command-line options related to
1452 	 * grabbing or creating victim processes.  The behavior of these calls
1453 	 * may been affected by any library options set by the second pass.
1454 	 */
1455 	for (optind = 1; optind < argc; optind++) {
1456 		while ((c = getopt(argc, argv, DTRACE_OPTSTR)) != EOF) {
1457 			switch (c) {
1458 			case 'c':
1459 				if ((v = make_argv(optarg)) == NULL)
1460 					fatal("failed to allocate memory");
1461 
1462 				P = dtrace_proc_create(g_dtp, v[0], v);
1463 				if (P == NULL)
1464 					dfatal(NULL); /* dtrace_errmsg() only */
1465 
1466 				g_psv[g_psc++] = P;
1467 				free(v);
1468 				break;
1469 
1470 			case 'p':
1471 				errno = 0;
1472 				pid = strtol(optarg, &p, 10);
1473 
1474 				if (errno != 0 || p == optarg || p[0] != '\0')
1475 					fatal("invalid pid: %s\n", optarg);
1476 
1477 				P = dtrace_proc_grab(g_dtp, pid, 0);
1478 				if (P == NULL)
1479 					dfatal(NULL); /* dtrace_errmsg() only */
1480 
1481 				g_psv[g_psc++] = P;
1482 				break;
1483 			}
1484 		}
1485 	}
1486 
1487 	/*
1488 	 * In our fourth pass we finish g_cmdv[] by calling dc_func to convert
1489 	 * each string or file specification into a compiled program structure.
1490 	 */
1491 	for (i = 0; i < g_cmdc; i++)
1492 		g_cmdv[i].dc_func(&g_cmdv[i]);
1493 
1494 	if (g_mode != DMODE_LIST) {
1495 		if (dtrace_handle_err(g_dtp, &errhandler, NULL) == -1)
1496 			dfatal("failed to establish error handler");
1497 
1498 		if (dtrace_handle_drop(g_dtp, &drophandler, NULL) == -1)
1499 			dfatal("failed to establish drop handler");
1500 
1501 		if (dtrace_handle_proc(g_dtp, &prochandler, NULL) == -1)
1502 			dfatal("failed to establish proc handler");
1503 
1504 		if (dtrace_handle_setopt(g_dtp, &setopthandler, NULL) == -1)
1505 			dfatal("failed to establish setopt handler");
1506 
1507 		if (g_ofp == NULL &&
1508 		    dtrace_handle_buffered(g_dtp, &bufhandler, NULL) == -1)
1509 			dfatal("failed to establish buffered handler");
1510 	}
1511 
1512 	(void) dtrace_getopt(g_dtp, "flowindent", &opt);
1513 	g_flowindent = opt != DTRACEOPT_UNSET;
1514 
1515 	(void) dtrace_getopt(g_dtp, "grabanon", &opt);
1516 	g_grabanon = opt != DTRACEOPT_UNSET;
1517 
1518 	(void) dtrace_getopt(g_dtp, "quiet", &opt);
1519 	g_quiet = opt != DTRACEOPT_UNSET;
1520 
1521 	/*
1522 	 * Now make a fifth and final pass over the options that have been
1523 	 * turned into programs and saved in g_cmdv[], performing any mode-
1524 	 * specific processing.  If g_mode is DMODE_EXEC, we will break out
1525 	 * of the switch() and continue on to the data processing loop.  For
1526 	 * other modes, we will exit dtrace once mode-specific work is done.
1527 	 */
1528 	switch (g_mode) {
1529 	case DMODE_EXEC:
1530 		if (g_ofile != NULL && (g_ofp = fopen(g_ofile, "a")) == NULL)
1531 			fatal("failed to open output file '%s'", g_ofile);
1532 
1533 		for (i = 0; i < g_cmdc; i++)
1534 			exec_prog(&g_cmdv[i]);
1535 
1536 		if (done && !g_grabanon) {
1537 			dtrace_close(g_dtp);
1538 			return (g_status);
1539 		}
1540 		break;
1541 
1542 	case DMODE_ANON:
1543 		if (g_ofile == NULL)
1544 			g_ofile = "/kernel/drv/dtrace.conf";
1545 
1546 		dof_prune(g_ofile); /* strip out any old DOF directives */
1547 		etcsystem_prune(); /* string out any forceload directives */
1548 
1549 		if (g_cmdc == 0) {
1550 			dtrace_close(g_dtp);
1551 			return (g_status);
1552 		}
1553 
1554 		if ((g_ofp = fopen(g_ofile, "a")) == NULL)
1555 			fatal("failed to open output file '%s'", g_ofile);
1556 
1557 		for (i = 0; i < g_cmdc; i++) {
1558 			anon_prog(&g_cmdv[i],
1559 			    dtrace_dof_create(g_dtp, g_cmdv[i].dc_prog, 0), i);
1560 		}
1561 
1562 		/*
1563 		 * Dump out the DOF corresponding to the error handler and the
1564 		 * current options as the final DOF property in the .conf file.
1565 		 */
1566 		anon_prog(NULL, dtrace_geterr_dof(g_dtp), i++);
1567 		anon_prog(NULL, dtrace_getopt_dof(g_dtp), i++);
1568 
1569 		if (fclose(g_ofp) == EOF)
1570 			fatal("failed to close output file '%s'", g_ofile);
1571 
1572 		/*
1573 		 * These messages would use notice() rather than error(), but
1574 		 * we don't want them suppressed when -A is run on a D program
1575 		 * that itself contains a #pragma D option quiet.
1576 		 */
1577 		error("saved anonymous enabling in %s\n", g_ofile);
1578 		etcsystem_add();
1579 		error("run update_drv(1M) or reboot to enable changes\n");
1580 
1581 		dtrace_close(g_dtp);
1582 		return (g_status);
1583 
1584 	case DMODE_LINK:
1585 		for (i = 0; i < g_cmdc; i++)
1586 			link_prog(&g_cmdv[i]);
1587 
1588 		if (g_cmdc > 1 && g_ofile != NULL) {
1589 			char **objv = alloca(g_cmdc * sizeof (char *));
1590 
1591 			for (i = 0; i < g_cmdc; i++)
1592 				objv[i] = g_cmdv[i].dc_ofile;
1593 
1594 			if (dtrace_program_link(g_dtp, NULL, DTRACE_D_PROBES,
1595 			    g_ofile, g_cmdc, objv) != 0)
1596 				dfatal(NULL); /* dtrace_errmsg() only */
1597 		}
1598 
1599 		dtrace_close(g_dtp);
1600 		return (g_status);
1601 
1602 	case DMODE_LIST:
1603 		if (g_ofile != NULL && (g_ofp = fopen(g_ofile, "a")) == NULL)
1604 			fatal("failed to open output file '%s'", g_ofile);
1605 
1606 		oprintf("%5s %10s %17s %33s %s\n",
1607 		    "ID", "PROVIDER", "MODULE", "FUNCTION", "NAME");
1608 
1609 		for (i = 0; i < g_cmdc; i++)
1610 			list_prog(&g_cmdv[i]);
1611 
1612 		if (g_cmdc == 0)
1613 			(void) dtrace_probe_iter(g_dtp, NULL, list_probe, NULL);
1614 
1615 		dtrace_close(g_dtp);
1616 		return (g_status);
1617 	}
1618 
1619 	/*
1620 	 * If -a and -Z were not specified and no probes have been matched, no
1621 	 * probe criteria was specified on the command line and we abort.
1622 	 */
1623 	if (g_total == 0 && !g_grabanon && !(g_cflags & DTRACE_C_ZDEFS))
1624 		dfatal("no probes %s\n", g_cmdc ? "matched" : "specified");
1625 
1626 	/*
1627 	 * Start tracing.  Once we dtrace_go(), reload any options that affect
1628 	 * our globals in case consuming anonymous state has changed them.
1629 	 */
1630 	go();
1631 
1632 	(void) dtrace_getopt(g_dtp, "flowindent", &opt);
1633 	g_flowindent = opt != DTRACEOPT_UNSET;
1634 
1635 	(void) dtrace_getopt(g_dtp, "grabanon", &opt);
1636 	g_grabanon = opt != DTRACEOPT_UNSET;
1637 
1638 	(void) dtrace_getopt(g_dtp, "quiet", &opt);
1639 	g_quiet = opt != DTRACEOPT_UNSET;
1640 
1641 	(void) dtrace_getopt(g_dtp, "destructive", &opt);
1642 	if (opt != DTRACEOPT_UNSET)
1643 		notice("allowing destructive actions\n");
1644 
1645 	(void) sigemptyset(&act.sa_mask);
1646 	act.sa_flags = 0;
1647 	act.sa_handler = intr;
1648 	(void) sigaction(SIGINT, &act, NULL);
1649 	(void) sigaction(SIGTERM, &act, NULL);
1650 
1651 	/*
1652 	 * Now that tracing is active and we are ready to consume trace data,
1653 	 * continue any grabbed or created processes, setting them running
1654 	 * using the /proc control mechanism inside of libdtrace.
1655 	 */
1656 	for (i = 0; i < g_psc; i++)
1657 		dtrace_proc_continue(g_dtp, g_psv[i]);
1658 
1659 	g_pslive = g_psc; /* count for prochandler() */
1660 
1661 	do {
1662 		if (!g_intr && !done)
1663 			dtrace_sleep(g_dtp);
1664 
1665 		if (g_newline) {
1666 			/*
1667 			 * Output a newline just to make the output look
1668 			 * slightly cleaner.  Note that we do this even in
1669 			 * "quiet" mode...
1670 			 */
1671 			oprintf("\n");
1672 			g_newline = 0;
1673 		}
1674 
1675 		if (done || g_intr || (g_psc != 0 && g_pslive == 0)) {
1676 			done = 1;
1677 			if (dtrace_stop(g_dtp) == -1)
1678 				dfatal("couldn't stop tracing");
1679 		}
1680 
1681 		switch (dtrace_work(g_dtp, g_ofp, chew, chewrec, NULL)) {
1682 		case DTRACE_WORKSTATUS_DONE:
1683 			done = 1;
1684 			break;
1685 		case DTRACE_WORKSTATUS_OKAY:
1686 			break;
1687 		default:
1688 			if (!g_impatient && dtrace_errno(g_dtp) != EINTR)
1689 				dfatal("processing aborted");
1690 		}
1691 
1692 		if (g_ofp != NULL && fflush(g_ofp) == EOF)
1693 			clearerr(g_ofp);
1694 	} while (!done);
1695 
1696 	oprintf("\n");
1697 
1698 	if (!g_impatient) {
1699 		if (dtrace_aggregate_print(g_dtp, g_ofp, NULL) == -1 &&
1700 		    dtrace_errno(g_dtp) != EINTR)
1701 			dfatal("failed to print aggregations");
1702 	}
1703 
1704 	dtrace_close(g_dtp);
1705 	return (g_status);
1706 }
1707