xref: /illumos-gate/usr/src/cmd/dtrace/dtrace.c (revision 34e48580)
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:c: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 	va_start(ap, fmt);
250 	n = vfprintf(g_ofp, fmt, ap);
251 	va_end(ap);
252 
253 	if (n < 0) {
254 		if (errno != EINTR) {
255 			fatal("failed to write to %s",
256 			    g_ofile ? g_ofile : "<stdout>");
257 		}
258 		clearerr(g_ofp);
259 	}
260 }
261 
262 static char **
263 make_argv(char *s)
264 {
265 	const char *ws = "\f\n\r\t\v ";
266 	char **argv = malloc(sizeof (char *) * (strlen(s) / 2 + 1));
267 	int argc = 0;
268 	char *p = s;
269 
270 	if (argv == NULL)
271 		return (NULL);
272 
273 	for (p = strtok(s, ws); p != NULL; p = strtok(NULL, ws))
274 		argv[argc++] = p;
275 
276 	if (argc == 0)
277 		argv[argc++] = s;
278 
279 	argv[argc] = NULL;
280 	return (argv);
281 }
282 
283 static void
284 dof_prune(const char *fname)
285 {
286 	struct stat sbuf;
287 	size_t sz, i, j, mark, len;
288 	char *buf;
289 	int msg = 0, fd;
290 
291 	if ((fd = open(fname, O_RDONLY)) == -1) {
292 		/*
293 		 * This is okay only if the file doesn't exist at all.
294 		 */
295 		if (errno != ENOENT)
296 			fatal("failed to open %s", fname);
297 		return;
298 	}
299 
300 	if (fstat(fd, &sbuf) == -1)
301 		fatal("failed to fstat %s", fname);
302 
303 	if ((buf = malloc((sz = sbuf.st_size) + 1)) == NULL)
304 		fatal("failed to allocate memory for %s", fname);
305 
306 	if (read(fd, buf, sz) != sz)
307 		fatal("failed to read %s", fname);
308 
309 	buf[sz] = '\0';
310 	(void) close(fd);
311 
312 	if ((fd = open(fname, O_WRONLY | O_TRUNC)) == -1)
313 		fatal("failed to open %s for writing", fname);
314 
315 	len = strlen("dof-data-");
316 
317 	for (mark = 0, i = 0; i < sz; i++) {
318 		if (strncmp(&buf[i], "dof-data-", len) != 0)
319 			continue;
320 
321 		/*
322 		 * This is only a match if it's in the 0th column.
323 		 */
324 		if (i != 0 && buf[i - 1] != '\n')
325 			continue;
326 
327 		if (msg++ == 0) {
328 			error("cleaned up old anonymous "
329 			    "enabling in %s\n", fname);
330 		}
331 
332 		/*
333 		 * We have a match.  First write out our data up until now.
334 		 */
335 		if (i != mark) {
336 			if (write(fd, &buf[mark], i - mark) != i - mark)
337 				fatal("failed to write to %s", fname);
338 		}
339 
340 		/*
341 		 * Now scan forward until we scan past a newline.
342 		 */
343 		for (j = i; j < sz && buf[j] != '\n'; j++)
344 			continue;
345 
346 		/*
347 		 * Reset our mark.
348 		 */
349 		if ((mark = j + 1) >= sz)
350 			break;
351 
352 		i = j;
353 	}
354 
355 	if (mark < sz) {
356 		if (write(fd, &buf[mark], sz - mark) != sz - mark)
357 			fatal("failed to write to %s", fname);
358 	}
359 
360 	(void) close(fd);
361 	free(buf);
362 }
363 
364 static void
365 etcsystem_prune(void)
366 {
367 	struct stat sbuf;
368 	size_t sz;
369 	char *buf, *start, *end;
370 	int fd;
371 	char *fname = g_etcfile, *tmpname;
372 
373 	if ((fd = open(fname, O_RDONLY)) == -1)
374 		fatal("failed to open %s", fname);
375 
376 	if (fstat(fd, &sbuf) == -1)
377 		fatal("failed to fstat %s", fname);
378 
379 	if ((buf = malloc((sz = sbuf.st_size) + 1)) == NULL)
380 		fatal("failed to allocate memory for %s", fname);
381 
382 	if (read(fd, buf, sz) != sz)
383 		fatal("failed to read %s", fname);
384 
385 	buf[sz] = '\0';
386 	(void) close(fd);
387 
388 	if ((start = strstr(buf, g_etcbegin)) == NULL)
389 		goto out;
390 
391 	if (strlen(buf) != sz) {
392 		fatal("embedded nul byte in %s; manual repair of %s "
393 		    "required\n", fname, fname);
394 	}
395 
396 	if (strstr(start + 1, g_etcbegin) != NULL) {
397 		fatal("multiple start sentinels in %s; manual repair of %s "
398 		    "required\n", fname, fname);
399 	}
400 
401 	if ((end = strstr(buf, g_etcend)) == NULL) {
402 		fatal("missing end sentinel in %s; manual repair of %s "
403 		    "required\n", fname, fname);
404 	}
405 
406 	if (start > end) {
407 		fatal("end sentinel preceeds start sentinel in %s; manual "
408 		    "repair of %s required\n", fname, fname);
409 	}
410 
411 	end += strlen(g_etcend) + 1;
412 	bcopy(end, start, strlen(end) + 1);
413 
414 	tmpname = alloca(sz = strlen(fname) + 80);
415 	(void) snprintf(tmpname, sz, "%s.dtrace.%d", fname, getpid());
416 
417 	if ((fd = open(tmpname,
418 	    O_WRONLY | O_CREAT | O_EXCL, sbuf.st_mode)) == -1)
419 		fatal("failed to create %s", tmpname);
420 
421 	if (write(fd, buf, strlen(buf)) < strlen(buf)) {
422 		(void) unlink(tmpname);
423 		fatal("failed to write to %s", tmpname);
424 	}
425 
426 	(void) close(fd);
427 
428 	if (chown(tmpname, sbuf.st_uid, sbuf.st_gid) != 0) {
429 		(void) unlink(tmpname);
430 		fatal("failed to chown(2) %s to uid %d, gid %d", tmpname,
431 		    (int)sbuf.st_uid, (int)sbuf.st_gid);
432 	}
433 
434 	if (rename(tmpname, fname) == -1)
435 		fatal("rename of %s to %s failed", tmpname, fname);
436 
437 	error("cleaned up forceload directives in %s\n", fname);
438 out:
439 	free(buf);
440 }
441 
442 static void
443 etcsystem_add(void)
444 {
445 	const char *mods[20];
446 	int nmods, line;
447 
448 	if ((g_ofp = fopen(g_ofile = g_etcfile, "a")) == NULL)
449 		fatal("failed to open output file '%s'", g_ofile);
450 
451 	oprintf("%s\n", g_etcbegin);
452 
453 	for (line = 0; g_etc[line] != NULL; line++)
454 		oprintf("%s\n", g_etc[line]);
455 
456 	nmods = dtrace_provider_modules(g_dtp, mods,
457 	    sizeof (mods) / sizeof (char *) - 1);
458 
459 	if (nmods >= sizeof (mods) / sizeof (char *))
460 		fatal("unexpectedly large number of modules!");
461 
462 	mods[nmods++] = "dtrace";
463 
464 	for (line = 0; line < nmods; line++)
465 		oprintf("forceload: drv/%s\n", mods[line]);
466 
467 	oprintf("%s\n", g_etcend);
468 
469 	if (fclose(g_ofp) == EOF)
470 		fatal("failed to close output file '%s'", g_ofile);
471 
472 	error("added forceload directives to %s\n", g_ofile);
473 }
474 
475 static void
476 print_probe_info(const dtrace_probeinfo_t *p)
477 {
478 	char buf[BUFSIZ];
479 	int i;
480 
481 	oprintf("\n\tProbe Description Attributes\n");
482 
483 	oprintf("\t\tIdentifier Names: %s\n",
484 	    dtrace_stability_name(p->dtp_attr.dtat_name));
485 	oprintf("\t\tData Semantics:   %s\n",
486 	    dtrace_stability_name(p->dtp_attr.dtat_data));
487 	oprintf("\t\tDependency Class: %s\n",
488 	    dtrace_class_name(p->dtp_attr.dtat_class));
489 
490 	oprintf("\n\tArgument Attributes\n");
491 
492 	oprintf("\t\tIdentifier Names: %s\n",
493 	    dtrace_stability_name(p->dtp_arga.dtat_name));
494 	oprintf("\t\tData Semantics:   %s\n",
495 	    dtrace_stability_name(p->dtp_arga.dtat_data));
496 	oprintf("\t\tDependency Class: %s\n",
497 	    dtrace_class_name(p->dtp_arga.dtat_class));
498 
499 	oprintf("\n\tArgument Types\n");
500 
501 	for (i = 0; i < p->dtp_argc; i++) {
502 		if (ctf_type_name(p->dtp_argv[i].dtt_ctfp,
503 		    p->dtp_argv[i].dtt_type, buf, sizeof (buf)) == NULL)
504 			(void) strlcpy(buf, "(unknown)", sizeof (buf));
505 		oprintf("\t\targs[%d]: %s\n", i, buf);
506 	}
507 
508 	if (p->dtp_argc == 0)
509 		oprintf("\t\tNone\n");
510 
511 	oprintf("\n");
512 }
513 
514 /*ARGSUSED*/
515 static int
516 info_stmt(dtrace_hdl_t *dtp, dtrace_prog_t *pgp,
517     dtrace_stmtdesc_t *stp, dtrace_ecbdesc_t **last)
518 {
519 	dtrace_ecbdesc_t *edp = stp->dtsd_ecbdesc;
520 	dtrace_probedesc_t *pdp = &edp->dted_probe;
521 	dtrace_probeinfo_t p;
522 
523 	if (edp == *last)
524 		return (0);
525 
526 	oprintf("\n%s:%s:%s:%s\n",
527 	    pdp->dtpd_provider, pdp->dtpd_mod, pdp->dtpd_func, pdp->dtpd_name);
528 
529 	if (dtrace_probe_info(dtp, pdp, &p) == 0)
530 		print_probe_info(&p);
531 
532 	*last = edp;
533 	return (0);
534 }
535 
536 /*
537  * Execute the specified program by enabling the corresponding instrumentation.
538  * If -e has been specified, we get the program info but do not enable it.  If
539  * -v has been specified, we print a stability report for the program.
540  */
541 static void
542 exec_prog(const dtrace_cmd_t *dcp)
543 {
544 	dtrace_ecbdesc_t *last = NULL;
545 	dtrace_proginfo_t dpi;
546 
547 	if (!g_exec) {
548 		dtrace_program_info(g_dtp, dcp->dc_prog, &dpi);
549 	} else if (dtrace_program_exec(g_dtp, dcp->dc_prog, &dpi) == -1) {
550 		dfatal("failed to enable '%s'", dcp->dc_name);
551 	} else {
552 		notice("%s '%s' matched %u probe%s\n",
553 		    dcp->dc_desc, dcp->dc_name,
554 		    dpi.dpi_matches, dpi.dpi_matches == 1 ? "" : "s");
555 	}
556 
557 	if (g_verbose) {
558 		oprintf("\nStability attributes for %s %s:\n",
559 		    dcp->dc_desc, dcp->dc_name);
560 
561 		oprintf("\n\tMinimum Probe Description Attributes\n");
562 		oprintf("\t\tIdentifier Names: %s\n",
563 		    dtrace_stability_name(dpi.dpi_descattr.dtat_name));
564 		oprintf("\t\tData Semantics:   %s\n",
565 		    dtrace_stability_name(dpi.dpi_descattr.dtat_data));
566 		oprintf("\t\tDependency Class: %s\n",
567 		    dtrace_class_name(dpi.dpi_descattr.dtat_class));
568 
569 		oprintf("\n\tMinimum Statement Attributes\n");
570 
571 		oprintf("\t\tIdentifier Names: %s\n",
572 		    dtrace_stability_name(dpi.dpi_stmtattr.dtat_name));
573 		oprintf("\t\tData Semantics:   %s\n",
574 		    dtrace_stability_name(dpi.dpi_stmtattr.dtat_data));
575 		oprintf("\t\tDependency Class: %s\n",
576 		    dtrace_class_name(dpi.dpi_stmtattr.dtat_class));
577 
578 		if (!g_exec) {
579 			(void) dtrace_stmt_iter(g_dtp, dcp->dc_prog,
580 			    (dtrace_stmt_f *)info_stmt, &last);
581 		} else
582 			oprintf("\n");
583 	}
584 
585 	g_total += dpi.dpi_matches;
586 }
587 
588 /*
589  * Print out the specified DOF buffer as a set of ASCII bytes appropriate for
590  * storing in a driver.conf(4) file associated with the dtrace driver.
591  */
592 static void
593 anon_prog(const dtrace_cmd_t *dcp, dof_hdr_t *dof, int n)
594 {
595 	const uchar_t *p, *q;
596 
597 	if (dof == NULL)
598 		dfatal("failed to create DOF image for '%s'", dcp->dc_name);
599 
600 	p = (uchar_t *)dof;
601 	q = p + dof->dofh_loadsz;
602 
603 	oprintf("dof-data-%d=0x%x", n, *p++);
604 
605 	while (p < q)
606 		oprintf(",0x%x", *p++);
607 
608 	oprintf(";\n");
609 	dtrace_dof_destroy(g_dtp, dof);
610 }
611 
612 /*
613  * Link the specified D program in DOF form into an ELF file for use in either
614  * helpers, userland provider definitions, or both.  If -o was specified, that
615  * path is used as the output file name.  If -o wasn't specified and the input
616  * program is from a script whose name is %.d, use basename(%.o) as the output
617  * file name.  Otherwise we use "d.out" as the default output file name.
618  */
619 static void
620 link_prog(dtrace_cmd_t *dcp)
621 {
622 	char *p;
623 
624 	if (g_cmdc == 1 && g_ofile != NULL) {
625 		(void) strlcpy(dcp->dc_ofile, g_ofile, sizeof (dcp->dc_ofile));
626 	} else if ((p = strrchr(dcp->dc_arg, '.')) != NULL &&
627 	    strcmp(p, ".d") == 0) {
628 		p[0] = '\0'; /* strip .d suffix */
629 		(void) snprintf(dcp->dc_ofile, sizeof (dcp->dc_ofile),
630 		    "%s.o", basename(dcp->dc_arg));
631 	} else {
632 		(void) snprintf(dcp->dc_ofile, sizeof (dcp->dc_ofile),
633 		    g_cmdc > 1 ?  "%s.%d" : "%s", "d.out", (int)(dcp - g_cmdv));
634 	}
635 
636 	if (dtrace_program_link(g_dtp, dcp->dc_prog, DTRACE_D_PROBES,
637 	    dcp->dc_ofile, g_objc - 1, g_objv + 1) != 0)
638 		dfatal("failed to link %s %s", dcp->dc_desc, dcp->dc_name);
639 }
640 
641 /*ARGSUSED*/
642 static int
643 list_probe(dtrace_hdl_t *dtp, const dtrace_probedesc_t *pdp, void *arg)
644 {
645 	dtrace_probeinfo_t p;
646 
647 	oprintf("%5d %10s %17s %33s %s\n", pdp->dtpd_id,
648 	    pdp->dtpd_provider, pdp->dtpd_mod, pdp->dtpd_func, pdp->dtpd_name);
649 
650 	if (g_verbose && dtrace_probe_info(dtp, pdp, &p) == 0)
651 		print_probe_info(&p);
652 
653 	return (0);
654 }
655 
656 /*ARGSUSED*/
657 static int
658 list_stmt(dtrace_hdl_t *dtp, dtrace_prog_t *pgp,
659     dtrace_stmtdesc_t *stp, dtrace_ecbdesc_t **last)
660 {
661 	dtrace_ecbdesc_t *edp = stp->dtsd_ecbdesc;
662 
663 	if (edp == *last)
664 		return (0);
665 
666 	if (dtrace_probe_iter(g_dtp, &edp->dted_probe, list_probe, NULL) != 0) {
667 		error("failed to match %s:%s:%s:%s: %s\n",
668 		    edp->dted_probe.dtpd_provider, edp->dted_probe.dtpd_mod,
669 		    edp->dted_probe.dtpd_func, edp->dted_probe.dtpd_name,
670 		    dtrace_errmsg(dtp, dtrace_errno(dtp)));
671 	}
672 
673 	*last = edp;
674 	return (0);
675 }
676 
677 /*
678  * List the probes corresponding to the specified program by iterating over
679  * each statement and then matching probes to the statement probe descriptions.
680  */
681 static void
682 list_prog(const dtrace_cmd_t *dcp)
683 {
684 	dtrace_ecbdesc_t *last = NULL;
685 
686 	(void) dtrace_stmt_iter(g_dtp, dcp->dc_prog,
687 	    (dtrace_stmt_f *)list_stmt, &last);
688 }
689 
690 static void
691 compile_file(dtrace_cmd_t *dcp)
692 {
693 	char *arg0;
694 	FILE *fp;
695 
696 	if ((fp = fopen(dcp->dc_arg, "r")) == NULL)
697 		fatal("failed to open %s", dcp->dc_arg);
698 
699 	arg0 = g_argv[0];
700 	g_argv[0] = dcp->dc_arg;
701 
702 	if ((dcp->dc_prog = dtrace_program_fcompile(g_dtp, fp,
703 	    g_cflags, g_argc, g_argv)) == NULL)
704 		dfatal("failed to compile script %s", dcp->dc_arg);
705 
706 	g_argv[0] = arg0;
707 	(void) fclose(fp);
708 
709 	dcp->dc_desc = "script";
710 	dcp->dc_name = dcp->dc_arg;
711 }
712 
713 static void
714 compile_str(dtrace_cmd_t *dcp)
715 {
716 	char *p;
717 
718 	if ((dcp->dc_prog = dtrace_program_strcompile(g_dtp, dcp->dc_arg,
719 	    dcp->dc_spec, g_cflags | DTRACE_C_PSPEC, g_argc, g_argv)) == NULL)
720 		dfatal("invalid probe specifier %s", dcp->dc_arg);
721 
722 	if ((p = strpbrk(dcp->dc_arg, "{/;")) != NULL)
723 		*p = '\0'; /* crop name for reporting */
724 
725 	dcp->dc_desc = "description";
726 	dcp->dc_name = dcp->dc_arg;
727 }
728 
729 /*ARGSUSED*/
730 static void
731 prochandler(struct ps_prochandle *P, void *arg)
732 {
733 	const psinfo_t *prp = Ppsinfo(P);
734 	int pid = Pstatus(P)->pr_pid;
735 	char name[SIG2STR_MAX];
736 
737 	switch (Pstate(P)) {
738 	case PS_UNDEAD:
739 		/*
740 		 * Ideally we would like to always report pr_wstat here, but it
741 		 * isn't possible given current /proc semantics.  If we grabbed
742 		 * the process, Ppsinfo() will either fail or return a zeroed
743 		 * psinfo_t depending on how far the parent is in reaping it.
744 		 * When /proc provides a stable pr_wstat in the status file,
745 		 * this code can be improved by examining this new pr_wstat.
746 		 */
747 		if (prp != NULL && WIFSIGNALED(prp->pr_wstat)) {
748 			notice("pid %d terminated by %s\n", pid,
749 			    proc_signame(WTERMSIG(prp->pr_wstat),
750 			    name, sizeof (name)));
751 		} else if (prp != NULL && WEXITSTATUS(prp->pr_wstat) != 0) {
752 			notice("pid %d exited with status %d\n",
753 			    pid, WEXITSTATUS(prp->pr_wstat));
754 		} else {
755 			notice("pid %d has exited\n", pid);
756 		}
757 		g_pslive--;
758 		break;
759 
760 	case PS_LOST:
761 		notice("pid %d exec'd a set-id or unobservable program\n", pid);
762 		g_pslive--;
763 		break;
764 	}
765 }
766 
767 /*ARGSUSED*/
768 static int
769 errhandler(dtrace_errdata_t *data, void *arg)
770 {
771 	error(data->dteda_msg);
772 	return (DTRACE_HANDLE_OK);
773 }
774 
775 /*ARGSUSED*/
776 static int
777 drophandler(dtrace_dropdata_t *data, void *arg)
778 {
779 	error(data->dtdda_msg);
780 	return (DTRACE_HANDLE_OK);
781 }
782 
783 /*ARGSUSED*/
784 static int
785 chewrec(const dtrace_probedata_t *data, const dtrace_recdesc_t *rec, void *arg)
786 {
787 	dtrace_actkind_t act;
788 	uintptr_t addr;
789 
790 	if (rec == NULL) {
791 		/*
792 		 * We have processed the final record; output the newline if
793 		 * we're not in quiet mode.
794 		 */
795 		if (!g_quiet)
796 			oprintf("\n");
797 
798 		return (DTRACE_CONSUME_NEXT);
799 	}
800 
801 	act = rec->dtrd_action;
802 	addr = (uintptr_t)data->dtpda_data;
803 
804 	if (act == DTRACEACT_EXIT) {
805 		g_status = *((uint32_t *)addr);
806 		return (DTRACE_CONSUME_NEXT);
807 	}
808 
809 	return (DTRACE_CONSUME_THIS);
810 }
811 
812 /*ARGSUSED*/
813 static int
814 chew(const dtrace_probedata_t *data, void *arg)
815 {
816 	dtrace_probedesc_t *pd = data->dtpda_pdesc;
817 	processorid_t cpu = data->dtpda_cpu;
818 	static int heading;
819 
820 	if (g_impatient) {
821 		g_newline = 0;
822 		return (DTRACE_CONSUME_ABORT);
823 	}
824 
825 	if (heading == 0) {
826 		if (!g_flowindent) {
827 			if (!g_quiet) {
828 				oprintf("%3s %6s %32s\n",
829 				    "CPU", "ID", "FUNCTION:NAME");
830 			}
831 		} else {
832 			oprintf("%3s %-41s\n", "CPU", "FUNCTION");
833 		}
834 		heading = 1;
835 	}
836 
837 	if (!g_flowindent) {
838 		if (!g_quiet) {
839 			char name[DTRACE_FUNCNAMELEN + DTRACE_NAMELEN + 2];
840 
841 			(void) snprintf(name, sizeof (name), "%s:%s",
842 			    pd->dtpd_func, pd->dtpd_name);
843 
844 			oprintf("%3d %6d %32s ", cpu, pd->dtpd_id, name);
845 		}
846 	} else {
847 		int indent = data->dtpda_indent;
848 		char *name;
849 		size_t len;
850 
851 		if (data->dtpda_flow == DTRACEFLOW_NONE) {
852 			len = indent + DTRACE_FUNCNAMELEN + DTRACE_NAMELEN + 5;
853 			name = alloca(len);
854 			(void) snprintf(name, len, "%*s%s%s:%s", indent, "",
855 			    data->dtpda_prefix, pd->dtpd_func,
856 			    pd->dtpd_name);
857 		} else {
858 			len = indent + DTRACE_FUNCNAMELEN + 5;
859 			name = alloca(len);
860 			(void) snprintf(name, len, "%*s%s%s", indent, "",
861 			    data->dtpda_prefix, pd->dtpd_func);
862 		}
863 
864 		oprintf("%3d %-41s ", cpu, name);
865 	}
866 
867 	return (DTRACE_CONSUME_THIS);
868 }
869 
870 static void
871 go(void)
872 {
873 	int i;
874 
875 	struct {
876 		char *name;
877 		char *optname;
878 		dtrace_optval_t val;
879 	} bufs[] = {
880 		{ "buffer size", "bufsize" },
881 		{ "aggregation size", "aggsize" },
882 		{ "speculation size", "specsize" },
883 		{ "dynamic variable size", "dynvarsize" },
884 		{ NULL }
885 	}, rates[] = {
886 		{ "cleaning rate", "cleanrate" },
887 		{ "status rate", "statusrate" },
888 		{ NULL }
889 	};
890 
891 	for (i = 0; bufs[i].name != NULL; i++) {
892 		if (dtrace_getopt(g_dtp, bufs[i].optname, &bufs[i].val) == -1)
893 			fatal("couldn't get option %s", bufs[i].optname);
894 	}
895 
896 	for (i = 0; rates[i].name != NULL; i++) {
897 		if (dtrace_getopt(g_dtp, rates[i].optname, &rates[i].val) == -1)
898 			fatal("couldn't get option %s", rates[i].optname);
899 	}
900 
901 	if (dtrace_go(g_dtp) == -1)
902 		dfatal("could not enable tracing");
903 
904 	for (i = 0; bufs[i].name != NULL; i++) {
905 		dtrace_optval_t j = 0, mul = 10;
906 		dtrace_optval_t nsize;
907 
908 		if (bufs[i].val == DTRACEOPT_UNSET)
909 			continue;
910 
911 		(void) dtrace_getopt(g_dtp, bufs[i].optname, &nsize);
912 
913 		if (nsize == DTRACEOPT_UNSET || nsize == 0)
914 			continue;
915 
916 		if (nsize >= bufs[i].val - sizeof (uint64_t))
917 			continue;
918 
919 		for (; (INT64_C(1) << mul) <= nsize; j++, mul += 10)
920 			continue;
921 
922 		if (!(nsize & ((INT64_C(1) << (mul - 10)) - 1))) {
923 			error("%s lowered to %lld%c\n", bufs[i].name,
924 			    (long long)nsize >> (mul - 10), " kmgtpe"[j]);
925 		} else {
926 			error("%s lowered to %lld bytes\n", bufs[i].name,
927 			    (long long)nsize);
928 		}
929 	}
930 
931 	for (i = 0; rates[i].name != NULL; i++) {
932 		dtrace_optval_t nval;
933 		char *dir;
934 
935 		if (rates[i].val == DTRACEOPT_UNSET)
936 			continue;
937 
938 		(void) dtrace_getopt(g_dtp, rates[i].optname, &nval);
939 
940 		if (nval == DTRACEOPT_UNSET || nval == 0)
941 			continue;
942 
943 		if (rates[i].val == nval)
944 			continue;
945 
946 		dir = nval > rates[i].val ? "reduced" : "increased";
947 
948 		if (nval <= NANOSEC && (NANOSEC % nval) == 0) {
949 			error("%s %s to %lld hz\n", rates[i].name, dir,
950 			    (long long)NANOSEC / (long long)nval);
951 			continue;
952 		}
953 
954 		if ((nval % NANOSEC) == 0) {
955 			error("%s %s to once every %lld seconds\n",
956 			    rates[i].name, dir,
957 			    (long long)nval / (long long)NANOSEC);
958 			continue;
959 		}
960 
961 		error("%s %s to once every %lld nanoseconds\n",
962 		    rates[i].name, dir, (long long)nval);
963 	}
964 }
965 
966 /*ARGSUSED*/
967 static void
968 intr(int signo)
969 {
970 	if (!g_intr)
971 		g_newline = 1;
972 
973 	if (g_intr++)
974 		g_impatient = 1;
975 }
976 
977 int
978 main(int argc, char *argv[])
979 {
980 	dtrace_bufdesc_t buf;
981 	struct sigaction act;
982 	dtrace_status_t status[2];
983 	dtrace_optval_t opt;
984 	dtrace_cmd_t *dcp;
985 
986 	int done = 0, mode = 0;
987 	int err, i;
988 	char c, *p, **v;
989 	struct ps_prochandle *P;
990 	pid_t pid;
991 
992 	g_pname = basename(argv[0]);
993 
994 	if (argc == 1)
995 		return (usage(stderr));
996 
997 	if ((g_argv = malloc(sizeof (char *) * argc)) == NULL ||
998 	    (g_cmdv = malloc(sizeof (dtrace_cmd_t) * argc)) == NULL ||
999 	    (g_psv = malloc(sizeof (struct ps_prochandle *) * argc)) == NULL)
1000 		fatal("failed to allocate memory for arguments");
1001 
1002 	g_argv[g_argc++] = argv[0];	/* propagate argv[0] to D as $0/$$0 */
1003 	argv[0] = g_pname;		/* rewrite argv[0] for getopt errors */
1004 
1005 	bzero(status, sizeof (status));
1006 	bzero(&buf, sizeof (buf));
1007 
1008 	/*
1009 	 * Make an initial pass through argv[] processing any arguments that
1010 	 * affect our behavior mode (g_mode) and flags used for dtrace_open().
1011 	 * We also accumulate arguments that are not affiliated with getopt
1012 	 * options into g_argv[], and abort if any invalid options are found.
1013 	 */
1014 	for (optind = 1; optind < argc; optind++) {
1015 		while ((c = getopt(argc, argv, DTRACE_OPTSTR)) != EOF) {
1016 			switch (c) {
1017 			case '3':
1018 				if (strcmp(optarg, "2") != 0) {
1019 					(void) fprintf(stderr,
1020 					    "%s: illegal option -- 3%s\n",
1021 					    argv[0], optarg);
1022 					return (usage(stderr));
1023 				}
1024 				g_oflags &= ~DTRACE_O_LP64;
1025 				g_oflags |= DTRACE_O_ILP32;
1026 				break;
1027 
1028 			case '6':
1029 				if (strcmp(optarg, "4") != 0) {
1030 					(void) fprintf(stderr,
1031 					    "%s: illegal option -- 6%s\n",
1032 					    argv[0], optarg);
1033 					return (usage(stderr));
1034 				}
1035 				g_oflags &= ~DTRACE_O_ILP32;
1036 				g_oflags |= DTRACE_O_LP64;
1037 				break;
1038 
1039 			case 'a':
1040 				g_grabanon++; /* also checked in pass 2 below */
1041 				break;
1042 
1043 			case 'A':
1044 				g_mode = DMODE_ANON;
1045 				g_exec = 0;
1046 				mode++;
1047 				break;
1048 
1049 			case 'e':
1050 				g_exec = 0;
1051 				done = 1;
1052 				break;
1053 
1054 			case 'G':
1055 				g_mode = DMODE_LINK;
1056 				g_oflags |= DTRACE_O_NODEV;
1057 				g_cflags |= DTRACE_C_ZDEFS; /* -G implies -Z */
1058 				g_exec = 0;
1059 				mode++;
1060 				break;
1061 
1062 			case 'l':
1063 				g_mode = DMODE_LIST;
1064 				g_cflags |= DTRACE_C_ZDEFS; /* -l implies -Z */
1065 				mode++;
1066 				break;
1067 
1068 			case 'V':
1069 				g_mode = DMODE_VERS;
1070 				mode++;
1071 				break;
1072 
1073 			default:
1074 				if (strchr(DTRACE_OPTSTR, c) == NULL)
1075 					return (usage(stderr));
1076 			}
1077 		}
1078 
1079 		if (optind < argc)
1080 			g_argv[g_argc++] = argv[optind];
1081 	}
1082 
1083 	if (mode > 1) {
1084 		(void) fprintf(stderr, "%s: only one of the [-AGlV] options "
1085 		    "can be specified at a time\n", g_pname);
1086 		return (E_USAGE);
1087 	}
1088 
1089 	if (g_mode == DMODE_VERS)
1090 		return (printf("%s: %s\n", g_pname, _dtrace_version) <= 0);
1091 
1092 	/*
1093 	 * Open libdtrace.  If we are not actually going to be enabling any
1094 	 * instrumentation attempt to reopen libdtrace using DTRACE_O_NODEV.
1095 	 */
1096 	while ((g_dtp = dtrace_open(DTRACE_VERSION, g_oflags, &err)) == NULL) {
1097 		if (!(g_oflags & DTRACE_O_NODEV) && !g_exec && !g_grabanon) {
1098 			g_oflags |= DTRACE_O_NODEV;
1099 			continue;
1100 		}
1101 
1102 		fatal("failed to initialize dtrace: %s\n",
1103 		    dtrace_errmsg(NULL, err));
1104 	}
1105 
1106 	(void) dtrace_setopt(g_dtp, "bufsize", "4m");
1107 	(void) dtrace_setopt(g_dtp, "aggsize", "4m");
1108 
1109 	/*
1110 	 * If -G is specified, enable -xlink=dynamic and -xunodefs to permit
1111 	 * references to undefined symbols to remain as unresolved relocations.
1112 	 * If -A is specified, enable -xlink=primary to permit static linking
1113 	 * only to kernel symbols that are defined in a primary kernel module.
1114 	 */
1115 	if (g_mode == DMODE_LINK) {
1116 		(void) dtrace_setopt(g_dtp, "linkmode", "dynamic");
1117 		(void) dtrace_setopt(g_dtp, "unodefs", NULL);
1118 
1119 		g_objc = g_argc;
1120 		g_objv = g_argv;
1121 
1122 		/*
1123 		 * We still use g_argv[0], the name of the executable.
1124 		 */
1125 		g_argc = 1;
1126 	} else if (g_mode == DMODE_ANON)
1127 		(void) dtrace_setopt(g_dtp, "linkmode", "primary");
1128 
1129 	/*
1130 	 * Now that we have libdtrace open, make a second pass through argv[]
1131 	 * to perform any dtrace_setopt() calls and change any compiler flags.
1132 	 * We also accumulate any program specifications into our g_cmdv[] at
1133 	 * this time; these will compiled as part of the fourth processing pass.
1134 	 */
1135 	for (optind = 1; optind < argc; optind++) {
1136 		while ((c = getopt(argc, argv, DTRACE_OPTSTR)) != EOF) {
1137 			switch (c) {
1138 			case 'a':
1139 				if (dtrace_setopt(g_dtp, "grabanon", 0) != 0)
1140 					dfatal("failed to set -a");
1141 				break;
1142 
1143 			case 'b':
1144 				if (dtrace_setopt(g_dtp,
1145 				    "bufsize", optarg) != 0)
1146 					dfatal("failed to set -b %s", optarg);
1147 				break;
1148 
1149 			case 'C':
1150 				g_cflags |= DTRACE_C_CPP;
1151 				break;
1152 
1153 			case 'D':
1154 				if (dtrace_setopt(g_dtp, "define", optarg) != 0)
1155 					dfatal("failed to set -D %s", optarg);
1156 				break;
1157 
1158 			case 'f':
1159 				dcp = &g_cmdv[g_cmdc++];
1160 				dcp->dc_func = compile_str;
1161 				dcp->dc_spec = DTRACE_PROBESPEC_FUNC;
1162 				dcp->dc_arg = optarg;
1163 				break;
1164 
1165 			case 'F':
1166 				if (dtrace_setopt(g_dtp, "flowindent", 0) != 0)
1167 					dfatal("failed to set -F");
1168 				break;
1169 
1170 			case 'H':
1171 				if (dtrace_setopt(g_dtp, "cpphdrs", 0) != 0)
1172 					dfatal("failed to set -H");
1173 				break;
1174 
1175 			case 'i':
1176 				dcp = &g_cmdv[g_cmdc++];
1177 				dcp->dc_func = compile_str;
1178 				dcp->dc_spec = DTRACE_PROBESPEC_NAME;
1179 				dcp->dc_arg = optarg;
1180 				break;
1181 
1182 			case 'I':
1183 				if (dtrace_setopt(g_dtp, "incdir", optarg) != 0)
1184 					dfatal("failed to set -I %s", optarg);
1185 				break;
1186 
1187 			case 'L':
1188 				if (dtrace_setopt(g_dtp, "libdir", optarg) != 0)
1189 					dfatal("failed to set -L %s", optarg);
1190 				break;
1191 
1192 			case 'm':
1193 				dcp = &g_cmdv[g_cmdc++];
1194 				dcp->dc_func = compile_str;
1195 				dcp->dc_spec = DTRACE_PROBESPEC_MOD;
1196 				dcp->dc_arg = optarg;
1197 				break;
1198 
1199 			case 'n':
1200 				dcp = &g_cmdv[g_cmdc++];
1201 				dcp->dc_func = compile_str;
1202 				dcp->dc_spec = DTRACE_PROBESPEC_NAME;
1203 				dcp->dc_arg = optarg;
1204 				break;
1205 
1206 			case 'P':
1207 				dcp = &g_cmdv[g_cmdc++];
1208 				dcp->dc_func = compile_str;
1209 				dcp->dc_spec = DTRACE_PROBESPEC_PROVIDER;
1210 				dcp->dc_arg = optarg;
1211 				break;
1212 
1213 			case 'q':
1214 				if (dtrace_setopt(g_dtp, "quiet", 0) != 0)
1215 					dfatal("failed to set -q");
1216 				break;
1217 
1218 			case 'o':
1219 				g_ofile = optarg;
1220 				break;
1221 
1222 			case 's':
1223 				dcp = &g_cmdv[g_cmdc++];
1224 				dcp->dc_func = compile_file;
1225 				dcp->dc_spec = DTRACE_PROBESPEC_NONE;
1226 				dcp->dc_arg = optarg;
1227 				break;
1228 
1229 			case 'S':
1230 				g_cflags |= DTRACE_C_DIFV;
1231 				break;
1232 
1233 			case 'U':
1234 				if (dtrace_setopt(g_dtp, "undef", optarg) != 0)
1235 					dfatal("failed to set -U %s", optarg);
1236 				break;
1237 
1238 			case 'v':
1239 				g_verbose++;
1240 				break;
1241 
1242 			case 'w':
1243 				if (dtrace_setopt(g_dtp, "destructive", 0) != 0)
1244 					dfatal("failed to set -w");
1245 				break;
1246 
1247 			case 'x':
1248 				if ((p = strchr(optarg, '=')) != NULL)
1249 					*p++ = '\0';
1250 
1251 				if (dtrace_setopt(g_dtp, optarg, p) != 0)
1252 					dfatal("failed to set -x %s", optarg);
1253 				break;
1254 
1255 			case 'X':
1256 				if (dtrace_setopt(g_dtp, "stdc", optarg) != 0)
1257 					dfatal("failed to set -X %s", optarg);
1258 				break;
1259 
1260 			case 'Z':
1261 				g_cflags |= DTRACE_C_ZDEFS;
1262 				break;
1263 
1264 			default:
1265 				if (strchr(DTRACE_OPTSTR, c) == NULL)
1266 					return (usage(stderr));
1267 			}
1268 		}
1269 	}
1270 
1271 	/*
1272 	 * In our third pass we handle any command-line options related to
1273 	 * grabbing or creating victim processes.  The behavior of these calls
1274 	 * may been affected by any library options set by the second pass.
1275 	 */
1276 	for (optind = 1; optind < argc; optind++) {
1277 		while ((c = getopt(argc, argv, DTRACE_OPTSTR)) != EOF) {
1278 			switch (c) {
1279 			case 'c':
1280 				if ((v = make_argv(optarg)) == NULL)
1281 					fatal("failed to allocate memory");
1282 
1283 				P = dtrace_proc_create(g_dtp, v[0], v);
1284 				if (P == NULL)
1285 					dfatal(NULL); /* dtrace_errmsg() only */
1286 
1287 				g_psv[g_psc++] = P;
1288 				free(v);
1289 				break;
1290 
1291 			case 'p':
1292 				errno = 0;
1293 				pid = strtol(optarg, &p, 10);
1294 
1295 				if (errno != 0 || p == optarg || p[0] != '\0')
1296 					fatal("invalid pid: %s\n", optarg);
1297 
1298 				P = dtrace_proc_grab(g_dtp, pid, 0);
1299 				if (P == NULL)
1300 					dfatal(NULL); /* dtrace_errmsg() only */
1301 
1302 				g_psv[g_psc++] = P;
1303 				break;
1304 			}
1305 		}
1306 	}
1307 
1308 	/*
1309 	 * In our fourth pass we finish g_cmdv[] by calling dc_func to convert
1310 	 * each string or file specification into a compiled program structure.
1311 	 */
1312 	for (i = 0; i < g_cmdc; i++)
1313 		g_cmdv[i].dc_func(&g_cmdv[i]);
1314 
1315 	if (g_mode != DMODE_LIST) {
1316 		if (dtrace_handle_err(g_dtp, &errhandler, NULL) == -1)
1317 			dfatal("failed to establish error handler");
1318 
1319 		if (dtrace_handle_drop(g_dtp, &drophandler, NULL) == -1)
1320 			dfatal("failed to establish drop handler");
1321 
1322 		if (dtrace_handle_proc(g_dtp, &prochandler, NULL) == -1)
1323 			dfatal("failed to establish proc handler");
1324 	}
1325 
1326 	(void) dtrace_getopt(g_dtp, "flowindent", &opt);
1327 	g_flowindent = opt != DTRACEOPT_UNSET;
1328 
1329 	(void) dtrace_getopt(g_dtp, "grabanon", &opt);
1330 	g_grabanon = opt != DTRACEOPT_UNSET;
1331 
1332 	(void) dtrace_getopt(g_dtp, "quiet", &opt);
1333 	g_quiet = opt != DTRACEOPT_UNSET;
1334 
1335 	/*
1336 	 * Now make a fifth and final pass over the options that have been
1337 	 * turned into programs and saved in g_cmdv[], performing any mode-
1338 	 * specific processing.  If g_mode is DMODE_EXEC, we will break out
1339 	 * of the switch() and continue on to the data processing loop.  For
1340 	 * other modes, we will exit dtrace once mode-specific work is done.
1341 	 */
1342 	switch (g_mode) {
1343 	case DMODE_EXEC:
1344 		if (g_ofile != NULL && (g_ofp = fopen(g_ofile, "a")) == NULL)
1345 			fatal("failed to open output file '%s'", g_ofile);
1346 
1347 		for (i = 0; i < g_cmdc; i++)
1348 			exec_prog(&g_cmdv[i]);
1349 
1350 		if (done && !g_grabanon) {
1351 			dtrace_close(g_dtp);
1352 			return (g_status);
1353 		}
1354 		break;
1355 
1356 	case DMODE_ANON:
1357 		if (g_ofile == NULL)
1358 			g_ofile = "/kernel/drv/dtrace.conf";
1359 
1360 		dof_prune(g_ofile); /* strip out any old DOF directives */
1361 		etcsystem_prune(); /* string out any forceload directives */
1362 
1363 		if (g_cmdc == 0) {
1364 			dtrace_close(g_dtp);
1365 			return (g_status);
1366 		}
1367 
1368 		if ((g_ofp = fopen(g_ofile, "a")) == NULL)
1369 			fatal("failed to open output file '%s'", g_ofile);
1370 
1371 		for (i = 0; i < g_cmdc; i++) {
1372 			anon_prog(&g_cmdv[i],
1373 			    dtrace_dof_create(g_dtp, g_cmdv[i].dc_prog, 0), i);
1374 		}
1375 
1376 		/*
1377 		 * Dump out the DOF corresponding to the error handler and the
1378 		 * current options as the final DOF property in the .conf file.
1379 		 */
1380 		anon_prog(NULL, dtrace_geterr_dof(g_dtp), i++);
1381 		anon_prog(NULL, dtrace_getopt_dof(g_dtp), i++);
1382 
1383 		if (fclose(g_ofp) == EOF)
1384 			fatal("failed to close output file '%s'", g_ofile);
1385 
1386 		/*
1387 		 * These messages would use notice() rather than error(), but
1388 		 * we don't want them suppressed when -A is run on a D program
1389 		 * that itself contains a #pragma D option quiet.
1390 		 */
1391 		error("saved anonymous enabling in %s\n", g_ofile);
1392 		etcsystem_add();
1393 		error("run update_drv(1M) or reboot to enable changes\n");
1394 
1395 		dtrace_close(g_dtp);
1396 		return (g_status);
1397 
1398 	case DMODE_LINK:
1399 		for (i = 0; i < g_cmdc; i++)
1400 			link_prog(&g_cmdv[i]);
1401 
1402 		if (g_cmdc > 1 && g_ofile != NULL) {
1403 			char **objv = alloca(g_cmdc * sizeof (char *));
1404 
1405 			for (i = 0; i < g_cmdc; i++)
1406 				objv[i] = g_cmdv[i].dc_ofile;
1407 
1408 			if (dtrace_program_link(g_dtp, NULL, DTRACE_D_PROBES,
1409 			    g_ofile, g_cmdc, objv) != 0)
1410 				dfatal(NULL); /* dtrace_errmsg() only */
1411 		}
1412 
1413 		dtrace_close(g_dtp);
1414 		return (g_status);
1415 
1416 	case DMODE_LIST:
1417 		if (g_ofile != NULL && (g_ofp = fopen(g_ofile, "a")) == NULL)
1418 			fatal("failed to open output file '%s'", g_ofile);
1419 
1420 		oprintf("%5s %10s %17s %33s %s\n",
1421 		    "ID", "PROVIDER", "MODULE", "FUNCTION", "NAME");
1422 
1423 		for (i = 0; i < g_cmdc; i++)
1424 			list_prog(&g_cmdv[i]);
1425 
1426 		if (g_cmdc == 0)
1427 			(void) dtrace_probe_iter(g_dtp, NULL, list_probe, NULL);
1428 
1429 		dtrace_close(g_dtp);
1430 		return (g_status);
1431 	}
1432 
1433 	/*
1434 	 * If -a and -Z were not specified and no probes have been matched, no
1435 	 * probe criteria was specified on the command line and we abort.
1436 	 */
1437 	if (g_total == 0 && !g_grabanon && !(g_cflags & DTRACE_C_ZDEFS))
1438 		dfatal("no probes %s\n", g_cmdc ? "matched" : "specified");
1439 
1440 	/*
1441 	 * Start tracing.  Once we dtrace_go(), reload any options that affect
1442 	 * our globals in case consuming anonymous state has changed them.
1443 	 */
1444 	go();
1445 
1446 	(void) dtrace_getopt(g_dtp, "flowindent", &opt);
1447 	g_flowindent = opt != DTRACEOPT_UNSET;
1448 
1449 	(void) dtrace_getopt(g_dtp, "grabanon", &opt);
1450 	g_grabanon = opt != DTRACEOPT_UNSET;
1451 
1452 	(void) dtrace_getopt(g_dtp, "quiet", &opt);
1453 	g_quiet = opt != DTRACEOPT_UNSET;
1454 
1455 	(void) dtrace_getopt(g_dtp, "destructive", &opt);
1456 	if (opt != DTRACEOPT_UNSET)
1457 		notice("allowing destructive actions\n");
1458 
1459 	(void) sigemptyset(&act.sa_mask);
1460 	act.sa_flags = 0;
1461 	act.sa_handler = intr;
1462 	(void) sigaction(SIGINT, &act, NULL);
1463 	(void) sigaction(SIGTERM, &act, NULL);
1464 
1465 	/*
1466 	 * Now that tracing is active and we are ready to consume trace data,
1467 	 * continue any grabbed or created processes, setting them running
1468 	 * using the /proc control mechanism inside of libdtrace.
1469 	 */
1470 	for (i = 0; i < g_psc; i++)
1471 		dtrace_proc_continue(g_dtp, g_psv[i]);
1472 
1473 	g_pslive = g_psc; /* count for prochandler() */
1474 
1475 	do {
1476 		if (!g_intr && !done)
1477 			dtrace_sleep(g_dtp);
1478 
1479 		if (g_newline) {
1480 			/*
1481 			 * Output a newline just to make the output look
1482 			 * slightly cleaner.  Note that we do this even in
1483 			 * "quiet" mode...
1484 			 */
1485 			oprintf("\n");
1486 			g_newline = 0;
1487 		}
1488 
1489 		if (done || g_intr || (g_psc != 0 && g_pslive == 0)) {
1490 			done = 1;
1491 			if (dtrace_stop(g_dtp) == -1)
1492 				dfatal("couldn't stop tracing");
1493 		}
1494 
1495 		switch (dtrace_work(g_dtp, g_ofp, chew, chewrec, NULL)) {
1496 		case DTRACE_WORKSTATUS_DONE:
1497 			done = 1;
1498 			break;
1499 		case DTRACE_WORKSTATUS_OKAY:
1500 			break;
1501 		default:
1502 			if (!g_impatient && dtrace_errno(g_dtp) != EINTR)
1503 				dfatal("processing aborted");
1504 		}
1505 
1506 		if (fflush(g_ofp) == EOF)
1507 			clearerr(g_ofp);
1508 	} while (!done);
1509 
1510 	oprintf("\n");
1511 
1512 	if (!g_impatient) {
1513 		if (dtrace_aggregate_print(g_dtp, g_ofp, NULL) == -1 &&
1514 		    dtrace_errno(g_dtp) != EINTR)
1515 			dfatal("failed to print aggregations");
1516 	}
1517 
1518 	dtrace_close(g_dtp);
1519 	return (g_status);
1520 }
1521