xref: /titanic_44/usr/src/cmd/dtrace/dtrace.c (revision b7f45089ccbe01bab3d7c7377b49d80d2ae18a69)
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 } dtrace_cmd_t;
55 
56 #define	DMODE_VERS	0	/* display version information and exit (-V) */
57 #define	DMODE_EXEC	1	/* compile program for enabling (-a/e/E) */
58 #define	DMODE_ANON	2	/* compile program for anonymous tracing (-A) */
59 #define	DMODE_LINK	3	/* compile program for linking with ELF (-G) */
60 #define	DMODE_LIST	4	/* compile program and list probes (-l) */
61 
62 #define	E_SUCCESS	0
63 #define	E_ERROR		1
64 #define	E_USAGE		2
65 
66 static const char DTRACE_OPTSTR[] =
67 	"3:6:aAb:c:CD:ef:FGHi:I:lL:m:n:o:p:P:qs:SU:vVwx:X:Z";
68 
69 static char **g_argv;
70 static int g_argc;
71 static char **g_objv;
72 static int g_objc;
73 static dtrace_cmd_t *g_cmdv;
74 static int g_cmdc;
75 static struct ps_prochandle **g_psv;
76 static int g_psc;
77 static int g_pslive;
78 static char *g_pname;
79 static int g_quiet;
80 static int g_flowindent;
81 static int g_intr;
82 static int g_impatient;
83 static int g_newline;
84 static int g_total;
85 static int g_cflags;
86 static int g_oflags;
87 static int g_verbose;
88 static int g_exec = 1;
89 static int g_mode = DMODE_EXEC;
90 static int g_status = E_SUCCESS;
91 static int g_grabanon = 0;
92 static const char *g_ofile = NULL;
93 static FILE *g_ofp = stdout;
94 static dtrace_hdl_t *g_dtp;
95 static char *g_etcfile = "/etc/system";
96 static const char *g_etcbegin = "* vvvv Added by DTrace";
97 static const char *g_etcend = "* ^^^^ Added by DTrace";
98 
99 static const char *g_etc[] =  {
100 "*",
101 "* The following forceload directives were added by dtrace(1M) to allow for",
102 "* tracing during boot.  If these directives are removed, the system will",
103 "* continue to function, but tracing will not occur during boot as desired.",
104 "* To remove these directives (and this block comment) automatically, run",
105 "* \"dtrace -A\" without additional arguments.  See the \"Anonymous Tracing\"",
106 "* chapter of the Solaris Dynamic Tracing Guide for details.",
107 "*",
108 NULL };
109 
110 static int
111 usage(FILE *fp)
112 {
113 	static const char predact[] = "[[ predicate ] action ]";
114 
115 	(void) fprintf(fp, "Usage: %s [-32|-64] [-aACeFGHlqSvVwZ] "
116 	    "[-b bufsz] [-c cmd] [-D name[=def]]\n\t[-I path] [-L path] "
117 	    "[-o output] [-p pid] [-s script] [-U name]\n\t"
118 	    "[-x opt[=val]] [-X a|c|s|t]\n\n"
119 	    "\t[-P provider %s]\n"
120 	    "\t[-m [ provider: ] module %s]\n"
121 	    "\t[-f [[ provider: ] module: ] func %s]\n"
122 	    "\t[-n [[[ provider: ] module: ] func: ] name %s]\n"
123 	    "\t[-i probe-id %s] [ args ... ]\n\n", g_pname,
124 	    predact, predact, predact, predact, predact);
125 
126 	(void) fprintf(fp, "\tpredicate -> '/' D-expression '/'\n");
127 	(void) fprintf(fp, "\t   action -> '{' D-statements '}'\n");
128 
129 	(void) fprintf(fp, "\n"
130 	    "\t-32 generate 32-bit D programs and ELF files\n"
131 	    "\t-64 generate 64-bit D programs and ELF files\n\n"
132 	    "\t-a  claim anonymous tracing state\n"
133 	    "\t-A  generate driver.conf(4) directives for anonymous tracing\n"
134 	    "\t-b  set trace buffer size\n"
135 	    "\t-c  run specified command and exit upon its completion\n"
136 	    "\t-C  run cpp(1) preprocessor on script files\n"
137 	    "\t-D  define symbol when invoking preprocessor\n"
138 	    "\t-e  exit after compiling request but prior to enabling probes\n"
139 	    "\t-f  enable or list probes matching the specified function name\n"
140 	    "\t-F  coalesce trace output by function\n"
141 	    "\t-G  generate an ELF file containing embedded dtrace program\n"
142 	    "\t-H  print included files when invoking preprocessor\n"
143 	    "\t-i  enable or list probes matching the specified probe id\n"
144 	    "\t-I  add include directory to preprocessor search path\n"
145 	    "\t-l  list probes matching specified criteria\n"
146 	    "\t-L  add library directory to library search path\n"
147 	    "\t-m  enable or list probes matching the specified module name\n"
148 	    "\t-n  enable or list probes matching the specified probe name\n"
149 	    "\t-o  set output file\n"
150 	    "\t-p  grab specified process-ID and cache its symbol tables\n"
151 	    "\t-P  enable or list probes matching the specified provider name\n"
152 	    "\t-q  set quiet mode (only output explicitly traced data)\n"
153 	    "\t-s  enable or list probes according to the specified D script\n"
154 	    "\t-S  print D compiler intermediate code\n"
155 	    "\t-U  undefine symbol when invoking preprocessor\n"
156 	    "\t-v  set verbose mode (report stability attributes, arguments)\n"
157 	    "\t-V  report DTrace API version\n"
158 	    "\t-w  permit destructive actions\n"
159 	    "\t-x  enable or modify compiler and tracing options\n"
160 	    "\t-X  specify ISO C conformance settings for preprocessor\n"
161 	    "\t-Z  permit probe descriptions that match zero probes\n");
162 
163 	return (E_USAGE);
164 }
165 
166 static void
167 verror(const char *fmt, va_list ap)
168 {
169 	int error = errno;
170 
171 	(void) fprintf(stderr, "%s: ", g_pname);
172 	(void) vfprintf(stderr, fmt, ap);
173 
174 	if (fmt[strlen(fmt) - 1] != '\n')
175 		(void) fprintf(stderr, ": %s\n", strerror(error));
176 }
177 
178 /*PRINTFLIKE1*/
179 static void
180 fatal(const char *fmt, ...)
181 {
182 	va_list ap;
183 
184 	va_start(ap, fmt);
185 	verror(fmt, ap);
186 	va_end(ap);
187 
188 	exit(E_ERROR);
189 }
190 
191 /*PRINTFLIKE1*/
192 static void
193 dfatal(const char *fmt, ...)
194 {
195 	va_list ap;
196 
197 	va_start(ap, fmt);
198 
199 	(void) fprintf(stderr, "%s: ", g_pname);
200 	if (fmt != NULL)
201 		(void) vfprintf(stderr, fmt, ap);
202 
203 	va_end(ap);
204 
205 	if (fmt != NULL && fmt[strlen(fmt) - 1] != '\n') {
206 		(void) fprintf(stderr, ": %s\n",
207 		    dtrace_errmsg(g_dtp, dtrace_errno(g_dtp)));
208 	} else if (fmt == NULL) {
209 		(void) fprintf(stderr, "%s\n",
210 		    dtrace_errmsg(g_dtp, dtrace_errno(g_dtp)));
211 	}
212 
213 	exit(E_ERROR);
214 }
215 
216 /*PRINTFLIKE1*/
217 static void
218 error(const char *fmt, ...)
219 {
220 	va_list ap;
221 
222 	va_start(ap, fmt);
223 	verror(fmt, ap);
224 	va_end(ap);
225 }
226 
227 /*PRINTFLIKE1*/
228 static void
229 notice(const char *fmt, ...)
230 {
231 	va_list ap;
232 
233 	if (g_quiet)
234 		return; /* -q or quiet pragma suppresses notice()s */
235 
236 	va_start(ap, fmt);
237 	verror(fmt, ap);
238 	va_end(ap);
239 }
240 
241 /*PRINTFLIKE1*/
242 static void
243 oprintf(const char *fmt, ...)
244 {
245 	va_list ap;
246 	int n;
247 
248 	va_start(ap, fmt);
249 	n = vfprintf(g_ofp, fmt, ap);
250 	va_end(ap);
251 
252 	if (n < 0) {
253 		if (errno != EINTR) {
254 			fatal("failed to write to %s",
255 			    g_ofile ? g_ofile : "<stdout>");
256 		}
257 		clearerr(g_ofp);
258 	}
259 }
260 
261 static char **
262 make_argv(char *s)
263 {
264 	const char *ws = "\f\n\r\t\v ";
265 	char **argv = malloc(sizeof (char *) * (strlen(s) / 2 + 1));
266 	int argc = 0;
267 	char *p = s;
268 
269 	if (argv == NULL)
270 		return (NULL);
271 
272 	for (p = strtok(s, ws); p != NULL; p = strtok(NULL, ws))
273 		argv[argc++] = p;
274 
275 	if (argc == 0)
276 		argv[argc++] = s;
277 
278 	argv[argc] = NULL;
279 	return (argv);
280 }
281 
282 static void
283 dof_prune(const char *fname)
284 {
285 	struct stat sbuf;
286 	size_t sz, i, j, mark, len;
287 	char *buf;
288 	int msg = 0, fd;
289 
290 	if ((fd = open(fname, O_RDONLY)) == -1) {
291 		/*
292 		 * This is okay only if the file doesn't exist at all.
293 		 */
294 		if (errno != ENOENT)
295 			fatal("failed to open %s", fname);
296 		return;
297 	}
298 
299 	if (fstat(fd, &sbuf) == -1)
300 		fatal("failed to fstat %s", fname);
301 
302 	if ((buf = malloc((sz = sbuf.st_size) + 1)) == NULL)
303 		fatal("failed to allocate memory for %s", fname);
304 
305 	if (read(fd, buf, sz) != sz)
306 		fatal("failed to read %s", fname);
307 
308 	buf[sz] = '\0';
309 	(void) close(fd);
310 
311 	if ((fd = open(fname, O_WRONLY | O_TRUNC)) == -1)
312 		fatal("failed to open %s for writing", fname);
313 
314 	len = strlen("dof-data-");
315 
316 	for (mark = 0, i = 0; i < sz; i++) {
317 		if (strncmp(&buf[i], "dof-data-", len) != 0)
318 			continue;
319 
320 		/*
321 		 * This is only a match if it's in the 0th column.
322 		 */
323 		if (i != 0 && buf[i - 1] != '\n')
324 			continue;
325 
326 		if (msg++ == 0) {
327 			error("cleaned up old anonymous "
328 			    "enabling in %s\n", fname);
329 		}
330 
331 		/*
332 		 * We have a match.  First write out our data up until now.
333 		 */
334 		if (i != mark) {
335 			if (write(fd, &buf[mark], i - mark) != i - mark)
336 				fatal("failed to write to %s", fname);
337 		}
338 
339 		/*
340 		 * Now scan forward until we scan past a newline.
341 		 */
342 		for (j = i; j < sz && buf[j] != '\n'; j++)
343 			continue;
344 
345 		/*
346 		 * Reset our mark.
347 		 */
348 		if ((mark = j + 1) >= sz)
349 			break;
350 
351 		i = j;
352 	}
353 
354 	if (mark < sz) {
355 		if (write(fd, &buf[mark], sz - mark) != sz - mark)
356 			fatal("failed to write to %s", fname);
357 	}
358 
359 	(void) close(fd);
360 	free(buf);
361 }
362 
363 static void
364 etcsystem_prune(void)
365 {
366 	struct stat sbuf;
367 	size_t sz;
368 	char *buf, *start, *end;
369 	int fd;
370 	char *fname = g_etcfile, *tmpname;
371 
372 	if ((fd = open(fname, O_RDONLY)) == -1)
373 		fatal("failed to open %s", fname);
374 
375 	if (fstat(fd, &sbuf) == -1)
376 		fatal("failed to fstat %s", fname);
377 
378 	if ((buf = malloc((sz = sbuf.st_size) + 1)) == NULL)
379 		fatal("failed to allocate memory for %s", fname);
380 
381 	if (read(fd, buf, sz) != sz)
382 		fatal("failed to read %s", fname);
383 
384 	buf[sz] = '\0';
385 	(void) close(fd);
386 
387 	if ((start = strstr(buf, g_etcbegin)) == NULL)
388 		goto out;
389 
390 	if (strlen(buf) != sz) {
391 		fatal("embedded nul byte in %s; manual repair of %s "
392 		    "required\n", fname, fname);
393 	}
394 
395 	if (strstr(start + 1, g_etcbegin) != NULL) {
396 		fatal("multiple start sentinels in %s; manual repair of %s "
397 		    "required\n", fname, fname);
398 	}
399 
400 	if ((end = strstr(buf, g_etcend)) == NULL) {
401 		fatal("missing end sentinel in %s; manual repair of %s "
402 		    "required\n", fname, fname);
403 	}
404 
405 	if (start > end) {
406 		fatal("end sentinel preceeds start sentinel in %s; manual "
407 		    "repair of %s required\n", fname, fname);
408 	}
409 
410 	end += strlen(g_etcend) + 1;
411 	bcopy(end, start, strlen(end) + 1);
412 
413 	tmpname = alloca(sz = strlen(fname) + 80);
414 	(void) snprintf(tmpname, sz, "%s.dtrace.%d", fname, getpid());
415 
416 	if ((fd = open(tmpname,
417 	    O_WRONLY | O_CREAT | O_EXCL, sbuf.st_mode)) == -1)
418 		fatal("failed to create %s", tmpname);
419 
420 	if (write(fd, buf, strlen(buf)) < strlen(buf)) {
421 		(void) unlink(tmpname);
422 		fatal("failed to write to %s", tmpname);
423 	}
424 
425 	(void) close(fd);
426 
427 	if (chown(tmpname, sbuf.st_uid, sbuf.st_gid) != 0) {
428 		(void) unlink(tmpname);
429 		fatal("failed to chown(2) %s to uid %d, gid %d", tmpname,
430 		    (int)sbuf.st_uid, (int)sbuf.st_gid);
431 	}
432 
433 	if (rename(tmpname, fname) == -1)
434 		fatal("rename of %s to %s failed", tmpname, fname);
435 
436 	error("cleaned up forceload directives in %s\n", fname);
437 out:
438 	free(buf);
439 }
440 
441 static void
442 etcsystem_add(void)
443 {
444 	const char *mods[20];
445 	int nmods, line;
446 
447 	if ((g_ofp = fopen(g_ofile = g_etcfile, "a")) == NULL)
448 		fatal("failed to open output file '%s'", g_ofile);
449 
450 	oprintf("%s\n", g_etcbegin);
451 
452 	for (line = 0; g_etc[line] != NULL; line++)
453 		oprintf("%s\n", g_etc[line]);
454 
455 	nmods = dtrace_provider_modules(g_dtp, mods,
456 	    sizeof (mods) / sizeof (char *) - 1);
457 
458 	if (nmods >= sizeof (mods) / sizeof (char *))
459 		fatal("unexpectedly large number of modules!");
460 
461 	mods[nmods++] = "dtrace";
462 
463 	for (line = 0; line < nmods; line++)
464 		oprintf("forceload: drv/%s\n", mods[line]);
465 
466 	oprintf("%s\n", g_etcend);
467 
468 	if (fclose(g_ofp) == EOF)
469 		fatal("failed to close output file '%s'", g_ofile);
470 
471 	error("added forceload directives to %s\n", g_ofile);
472 }
473 
474 static void
475 print_probe_info(const dtrace_probeinfo_t *p)
476 {
477 	char buf[BUFSIZ];
478 	int i;
479 
480 	oprintf("\n\tProbe Description Attributes\n");
481 
482 	oprintf("\t\tIdentifier Names: %s\n",
483 	    dtrace_stability_name(p->dtp_attr.dtat_name));
484 	oprintf("\t\tData Semantics:   %s\n",
485 	    dtrace_stability_name(p->dtp_attr.dtat_data));
486 	oprintf("\t\tDependency Class: %s\n",
487 	    dtrace_class_name(p->dtp_attr.dtat_class));
488 
489 	oprintf("\n\tArgument Attributes\n");
490 
491 	oprintf("\t\tIdentifier Names: %s\n",
492 	    dtrace_stability_name(p->dtp_arga.dtat_name));
493 	oprintf("\t\tData Semantics:   %s\n",
494 	    dtrace_stability_name(p->dtp_arga.dtat_data));
495 	oprintf("\t\tDependency Class: %s\n",
496 	    dtrace_class_name(p->dtp_arga.dtat_class));
497 
498 	oprintf("\n\tArgument Types\n");
499 
500 	for (i = 0; i < p->dtp_argc; i++) {
501 		if (ctf_type_name(p->dtp_argv[i].dtt_ctfp,
502 		    p->dtp_argv[i].dtt_type, buf, sizeof (buf)) == NULL)
503 			(void) strlcpy(buf, "(unknown)", sizeof (buf));
504 		oprintf("\t\targs[%d]: %s\n", i, buf);
505 	}
506 
507 	if (p->dtp_argc == 0)
508 		oprintf("\t\tNone\n");
509 
510 	oprintf("\n");
511 }
512 
513 /*ARGSUSED*/
514 static int
515 info_stmt(dtrace_hdl_t *dtp, dtrace_prog_t *pgp,
516     dtrace_stmtdesc_t *stp, dtrace_ecbdesc_t **last)
517 {
518 	dtrace_ecbdesc_t *edp = stp->dtsd_ecbdesc;
519 	dtrace_probedesc_t *pdp = &edp->dted_probe;
520 	dtrace_probeinfo_t p;
521 
522 	if (edp == *last)
523 		return (0);
524 
525 	oprintf("\n%s:%s:%s:%s\n",
526 	    pdp->dtpd_provider, pdp->dtpd_mod, pdp->dtpd_func, pdp->dtpd_name);
527 
528 	if (dtrace_probe_info(dtp, pdp, &p) == 0)
529 		print_probe_info(&p);
530 
531 	*last = edp;
532 	return (0);
533 }
534 
535 /*
536  * Execute the specified program by enabling the corresponding instrumentation.
537  * If -e has been specified, we get the program info but do not enable it.  If
538  * -v has been specified, we print a stability report for the program.
539  */
540 static void
541 exec_prog(const dtrace_cmd_t *dcp)
542 {
543 	dtrace_ecbdesc_t *last = NULL;
544 	dtrace_proginfo_t dpi;
545 
546 	if (!g_exec) {
547 		dtrace_program_info(g_dtp, dcp->dc_prog, &dpi);
548 	} else if (dtrace_program_exec(g_dtp, dcp->dc_prog, &dpi) == -1) {
549 		dfatal("failed to enable '%s'", dcp->dc_name);
550 	} else {
551 		notice("%s '%s' matched %u probe%s\n",
552 		    dcp->dc_desc, dcp->dc_name,
553 		    dpi.dpi_matches, dpi.dpi_matches == 1 ? "" : "s");
554 	}
555 
556 	if (g_verbose) {
557 		oprintf("\nStability attributes for %s %s:\n",
558 		    dcp->dc_desc, dcp->dc_name);
559 
560 		oprintf("\n\tMinimum Probe Description Attributes\n");
561 		oprintf("\t\tIdentifier Names: %s\n",
562 		    dtrace_stability_name(dpi.dpi_descattr.dtat_name));
563 		oprintf("\t\tData Semantics:   %s\n",
564 		    dtrace_stability_name(dpi.dpi_descattr.dtat_data));
565 		oprintf("\t\tDependency Class: %s\n",
566 		    dtrace_class_name(dpi.dpi_descattr.dtat_class));
567 
568 		oprintf("\n\tMinimum Statement Attributes\n");
569 
570 		oprintf("\t\tIdentifier Names: %s\n",
571 		    dtrace_stability_name(dpi.dpi_stmtattr.dtat_name));
572 		oprintf("\t\tData Semantics:   %s\n",
573 		    dtrace_stability_name(dpi.dpi_stmtattr.dtat_data));
574 		oprintf("\t\tDependency Class: %s\n",
575 		    dtrace_class_name(dpi.dpi_stmtattr.dtat_class));
576 
577 		if (!g_exec) {
578 			(void) dtrace_stmt_iter(g_dtp, dcp->dc_prog,
579 			    (dtrace_stmt_f *)info_stmt, &last);
580 		} else
581 			oprintf("\n");
582 	}
583 
584 	g_total += dpi.dpi_matches;
585 }
586 
587 /*
588  * Print out the specified DOF buffer as a set of ASCII bytes appropriate for
589  * storing in a driver.conf(4) file associated with the dtrace driver.
590  */
591 static void
592 anon_prog(const dtrace_cmd_t *dcp, dof_hdr_t *dof, int n)
593 {
594 	const uchar_t *p, *q;
595 
596 	if (dof == NULL)
597 		dfatal("failed to create DOF image for '%s'", dcp->dc_name);
598 
599 	p = (uchar_t *)dof;
600 	q = p + dof->dofh_loadsz;
601 
602 	oprintf("dof-data-%d=0x%x", n, *p++);
603 
604 	while (p < q)
605 		oprintf(",0x%x", *p++);
606 
607 	oprintf(";\n");
608 	dtrace_dof_destroy(g_dtp, dof);
609 }
610 
611 /*
612  * Link the specified D program in DOF form into an ELF file for use in either
613  * helpers, userland provider definitions, or both.  If -o was specified, that
614  * path is used as the output file name.  If -o wasn't specified and the input
615  * program is from a script whose name is %.d, use basename(%.o) as the output
616  * file name.  Otherwise we use "d.out" as the default output file name.
617  */
618 static void
619 link_prog(const dtrace_cmd_t *dcp)
620 {
621 	char file[PATH_MAX], *p;
622 
623 	if (g_ofile != NULL) {
624 		(void) snprintf(file, sizeof (file), g_cmdc > 1 ?
625 		    "%s.%d" : "%s", g_ofile, (int)(dcp - g_cmdv));
626 	} else if ((p = strrchr(dcp->dc_arg, '.')) != NULL &&
627 	    strcmp(p, ".d") == 0) {
628 		p[0] = '\0'; /* strip .d suffix */
629 		(void) snprintf(file, sizeof (file),
630 		    "%s.o", basename(dcp->dc_arg));
631 	} else {
632 		(void) snprintf(file, sizeof (file), g_cmdc > 1 ?
633 		    "%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 	    file, 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 			return (g_status);
1352 		break;
1353 
1354 	case DMODE_ANON:
1355 		if (g_ofile == NULL)
1356 			g_ofile = "/kernel/drv/dtrace.conf";
1357 
1358 		dof_prune(g_ofile); /* strip out any old DOF directives */
1359 		etcsystem_prune(); /* string out any forceload directives */
1360 
1361 		if (g_cmdc == 0)
1362 			return (g_status);
1363 
1364 		if ((g_ofp = fopen(g_ofile, "a")) == NULL)
1365 			fatal("failed to open output file '%s'", g_ofile);
1366 
1367 		for (i = 0; i < g_cmdc; i++) {
1368 			anon_prog(&g_cmdv[i],
1369 			    dtrace_dof_create(g_dtp, g_cmdv[i].dc_prog, 0), i);
1370 		}
1371 
1372 		/*
1373 		 * Dump out the DOF corresponding to the error handler and the
1374 		 * current options as the final DOF property in the .conf file.
1375 		 */
1376 		anon_prog(NULL, dtrace_geterr_dof(g_dtp), i++);
1377 		anon_prog(NULL, dtrace_getopt_dof(g_dtp), i++);
1378 
1379 		if (fclose(g_ofp) == EOF)
1380 			fatal("failed to close output file '%s'", g_ofile);
1381 
1382 		/*
1383 		 * These messages would use notice() rather than error(), but
1384 		 * we don't want them suppressed when -A is run on a D program
1385 		 * that itself contains a #pragma D option quiet.
1386 		 */
1387 		error("saved anonymous enabling in %s\n", g_ofile);
1388 		etcsystem_add();
1389 		error("run update_drv(1M) or reboot to enable changes\n");
1390 
1391 		return (g_status);
1392 
1393 	case DMODE_LINK:
1394 		for (i = 0; i < g_cmdc; i++)
1395 			link_prog(&g_cmdv[i]);
1396 		return (g_status);
1397 
1398 	case DMODE_LIST:
1399 		if (g_ofile != NULL && (g_ofp = fopen(g_ofile, "a")) == NULL)
1400 			fatal("failed to open output file '%s'", g_ofile);
1401 
1402 		oprintf("%5s %10s %17s %33s %s\n",
1403 		    "ID", "PROVIDER", "MODULE", "FUNCTION", "NAME");
1404 
1405 		for (i = 0; i < g_cmdc; i++)
1406 			list_prog(&g_cmdv[i]);
1407 
1408 		if (g_cmdc == 0)
1409 			(void) dtrace_probe_iter(g_dtp, NULL, list_probe, NULL);
1410 
1411 		return (g_status);
1412 	}
1413 
1414 	/*
1415 	 * If -a and -Z were not specified and no probes have been matched, no
1416 	 * probe criteria was specified on the command line and we abort.
1417 	 */
1418 	if (g_total == 0 && !g_grabanon && !(g_cflags & DTRACE_C_ZDEFS))
1419 		dfatal("no probes %s\n", g_cmdc ? "matched" : "specified");
1420 
1421 	/*
1422 	 * Start tracing.  Once we dtrace_go(), reload any options that affect
1423 	 * our globals in case consuming anonymous state has changed them.
1424 	 */
1425 	go();
1426 
1427 	(void) dtrace_getopt(g_dtp, "flowindent", &opt);
1428 	g_flowindent = opt != DTRACEOPT_UNSET;
1429 
1430 	(void) dtrace_getopt(g_dtp, "grabanon", &opt);
1431 	g_grabanon = opt != DTRACEOPT_UNSET;
1432 
1433 	(void) dtrace_getopt(g_dtp, "quiet", &opt);
1434 	g_quiet = opt != DTRACEOPT_UNSET;
1435 
1436 	(void) dtrace_getopt(g_dtp, "destructive", &opt);
1437 	if (opt != DTRACEOPT_UNSET)
1438 		notice("allowing destructive actions\n");
1439 
1440 	(void) sigemptyset(&act.sa_mask);
1441 	act.sa_flags = 0;
1442 	act.sa_handler = intr;
1443 	(void) sigaction(SIGINT, &act, NULL);
1444 	(void) sigaction(SIGTERM, &act, NULL);
1445 
1446 	/*
1447 	 * Now that tracing is active and we are ready to consume trace data,
1448 	 * continue any grabbed or created processes, setting them running
1449 	 * using the /proc control mechanism inside of libdtrace.
1450 	 */
1451 	for (i = 0; i < g_psc; i++)
1452 		dtrace_proc_continue(g_dtp, g_psv[i]);
1453 
1454 	g_pslive = g_psc; /* count for prochandler() */
1455 
1456 	do {
1457 		if (!g_intr && !done)
1458 			dtrace_sleep(g_dtp);
1459 
1460 		if (g_newline) {
1461 			/*
1462 			 * Output a newline just to make the output look
1463 			 * slightly cleaner.  Note that we do this even in
1464 			 * "quiet" mode...
1465 			 */
1466 			oprintf("\n");
1467 			g_newline = 0;
1468 		}
1469 
1470 		if (done || g_intr || (g_psc != 0 && g_pslive == 0)) {
1471 			done = 1;
1472 			if (dtrace_stop(g_dtp) == -1)
1473 				dfatal("couldn't stop tracing");
1474 		}
1475 
1476 		switch (dtrace_work(g_dtp, g_ofp, chew, chewrec, NULL)) {
1477 		case DTRACE_WORKSTATUS_DONE:
1478 			done = 1;
1479 			break;
1480 		case DTRACE_WORKSTATUS_OKAY:
1481 			break;
1482 		default:
1483 			if (!g_impatient && dtrace_errno(g_dtp) != EINTR)
1484 				dfatal("processing aborted");
1485 		}
1486 
1487 		if (fflush(g_ofp) == EOF)
1488 			clearerr(g_ofp);
1489 	} while (!done);
1490 
1491 	oprintf("\n");
1492 
1493 	if (!g_impatient) {
1494 		if (dtrace_aggregate_print(g_dtp, g_ofp, NULL) == -1 &&
1495 		    dtrace_errno(g_dtp) != EINTR)
1496 			dfatal("failed to print aggregations");
1497 	}
1498 
1499 	dtrace_close(g_dtp);
1500 	return (g_status);
1501 }
1502