xref: /titanic_44/usr/src/cmd/dtrace/dtrace.c (revision 6dfee4834394825da35b977ca71cdc965bc7b6a4)
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(const 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(const 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 setopthandler(const dtrace_setoptdata_t *data, void *arg)
786 {
787 	if (strcmp(data->dtsda_option, "quiet") == 0)
788 		g_quiet = data->dtsda_newval != DTRACEOPT_UNSET;
789 
790 	if (strcmp(data->dtsda_option, "flowindent") == 0)
791 		g_flowindent = data->dtsda_newval != DTRACEOPT_UNSET;
792 
793 	return (DTRACE_HANDLE_OK);
794 }
795 
796 /*ARGSUSED*/
797 static int
798 chewrec(const dtrace_probedata_t *data, const dtrace_recdesc_t *rec, void *arg)
799 {
800 	dtrace_actkind_t act;
801 	uintptr_t addr;
802 
803 	if (rec == NULL) {
804 		/*
805 		 * We have processed the final record; output the newline if
806 		 * we're not in quiet mode.
807 		 */
808 		if (!g_quiet)
809 			oprintf("\n");
810 
811 		return (DTRACE_CONSUME_NEXT);
812 	}
813 
814 	act = rec->dtrd_action;
815 	addr = (uintptr_t)data->dtpda_data;
816 
817 	if (act == DTRACEACT_EXIT) {
818 		g_status = *((uint32_t *)addr);
819 		return (DTRACE_CONSUME_NEXT);
820 	}
821 
822 	return (DTRACE_CONSUME_THIS);
823 }
824 
825 /*ARGSUSED*/
826 static int
827 chew(const dtrace_probedata_t *data, void *arg)
828 {
829 	dtrace_probedesc_t *pd = data->dtpda_pdesc;
830 	processorid_t cpu = data->dtpda_cpu;
831 	static int heading;
832 
833 	if (g_impatient) {
834 		g_newline = 0;
835 		return (DTRACE_CONSUME_ABORT);
836 	}
837 
838 	if (heading == 0) {
839 		if (!g_flowindent) {
840 			if (!g_quiet) {
841 				oprintf("%3s %6s %32s\n",
842 				    "CPU", "ID", "FUNCTION:NAME");
843 			}
844 		} else {
845 			oprintf("%3s %-41s\n", "CPU", "FUNCTION");
846 		}
847 		heading = 1;
848 	}
849 
850 	if (!g_flowindent) {
851 		if (!g_quiet) {
852 			char name[DTRACE_FUNCNAMELEN + DTRACE_NAMELEN + 2];
853 
854 			(void) snprintf(name, sizeof (name), "%s:%s",
855 			    pd->dtpd_func, pd->dtpd_name);
856 
857 			oprintf("%3d %6d %32s ", cpu, pd->dtpd_id, name);
858 		}
859 	} else {
860 		int indent = data->dtpda_indent;
861 		char *name;
862 		size_t len;
863 
864 		if (data->dtpda_flow == DTRACEFLOW_NONE) {
865 			len = indent + DTRACE_FUNCNAMELEN + DTRACE_NAMELEN + 5;
866 			name = alloca(len);
867 			(void) snprintf(name, len, "%*s%s%s:%s", indent, "",
868 			    data->dtpda_prefix, pd->dtpd_func,
869 			    pd->dtpd_name);
870 		} else {
871 			len = indent + DTRACE_FUNCNAMELEN + 5;
872 			name = alloca(len);
873 			(void) snprintf(name, len, "%*s%s%s", indent, "",
874 			    data->dtpda_prefix, pd->dtpd_func);
875 		}
876 
877 		oprintf("%3d %-41s ", cpu, name);
878 	}
879 
880 	return (DTRACE_CONSUME_THIS);
881 }
882 
883 static void
884 go(void)
885 {
886 	int i;
887 
888 	struct {
889 		char *name;
890 		char *optname;
891 		dtrace_optval_t val;
892 	} bufs[] = {
893 		{ "buffer size", "bufsize" },
894 		{ "aggregation size", "aggsize" },
895 		{ "speculation size", "specsize" },
896 		{ "dynamic variable size", "dynvarsize" },
897 		{ NULL }
898 	}, rates[] = {
899 		{ "cleaning rate", "cleanrate" },
900 		{ "status rate", "statusrate" },
901 		{ NULL }
902 	};
903 
904 	for (i = 0; bufs[i].name != NULL; i++) {
905 		if (dtrace_getopt(g_dtp, bufs[i].optname, &bufs[i].val) == -1)
906 			fatal("couldn't get option %s", bufs[i].optname);
907 	}
908 
909 	for (i = 0; rates[i].name != NULL; i++) {
910 		if (dtrace_getopt(g_dtp, rates[i].optname, &rates[i].val) == -1)
911 			fatal("couldn't get option %s", rates[i].optname);
912 	}
913 
914 	if (dtrace_go(g_dtp) == -1)
915 		dfatal("could not enable tracing");
916 
917 	for (i = 0; bufs[i].name != NULL; i++) {
918 		dtrace_optval_t j = 0, mul = 10;
919 		dtrace_optval_t nsize;
920 
921 		if (bufs[i].val == DTRACEOPT_UNSET)
922 			continue;
923 
924 		(void) dtrace_getopt(g_dtp, bufs[i].optname, &nsize);
925 
926 		if (nsize == DTRACEOPT_UNSET || nsize == 0)
927 			continue;
928 
929 		if (nsize >= bufs[i].val - sizeof (uint64_t))
930 			continue;
931 
932 		for (; (INT64_C(1) << mul) <= nsize; j++, mul += 10)
933 			continue;
934 
935 		if (!(nsize & ((INT64_C(1) << (mul - 10)) - 1))) {
936 			error("%s lowered to %lld%c\n", bufs[i].name,
937 			    (long long)nsize >> (mul - 10), " kmgtpe"[j]);
938 		} else {
939 			error("%s lowered to %lld bytes\n", bufs[i].name,
940 			    (long long)nsize);
941 		}
942 	}
943 
944 	for (i = 0; rates[i].name != NULL; i++) {
945 		dtrace_optval_t nval;
946 		char *dir;
947 
948 		if (rates[i].val == DTRACEOPT_UNSET)
949 			continue;
950 
951 		(void) dtrace_getopt(g_dtp, rates[i].optname, &nval);
952 
953 		if (nval == DTRACEOPT_UNSET || nval == 0)
954 			continue;
955 
956 		if (rates[i].val == nval)
957 			continue;
958 
959 		dir = nval > rates[i].val ? "reduced" : "increased";
960 
961 		if (nval <= NANOSEC && (NANOSEC % nval) == 0) {
962 			error("%s %s to %lld hz\n", rates[i].name, dir,
963 			    (long long)NANOSEC / (long long)nval);
964 			continue;
965 		}
966 
967 		if ((nval % NANOSEC) == 0) {
968 			error("%s %s to once every %lld seconds\n",
969 			    rates[i].name, dir,
970 			    (long long)nval / (long long)NANOSEC);
971 			continue;
972 		}
973 
974 		error("%s %s to once every %lld nanoseconds\n",
975 		    rates[i].name, dir, (long long)nval);
976 	}
977 }
978 
979 /*ARGSUSED*/
980 static void
981 intr(int signo)
982 {
983 	if (!g_intr)
984 		g_newline = 1;
985 
986 	if (g_intr++)
987 		g_impatient = 1;
988 }
989 
990 int
991 main(int argc, char *argv[])
992 {
993 	dtrace_bufdesc_t buf;
994 	struct sigaction act;
995 	dtrace_status_t status[2];
996 	dtrace_optval_t opt;
997 	dtrace_cmd_t *dcp;
998 
999 	int done = 0, mode = 0;
1000 	int err, i;
1001 	char c, *p, **v;
1002 	struct ps_prochandle *P;
1003 	pid_t pid;
1004 
1005 	g_pname = basename(argv[0]);
1006 
1007 	if (argc == 1)
1008 		return (usage(stderr));
1009 
1010 	if ((g_argv = malloc(sizeof (char *) * argc)) == NULL ||
1011 	    (g_cmdv = malloc(sizeof (dtrace_cmd_t) * argc)) == NULL ||
1012 	    (g_psv = malloc(sizeof (struct ps_prochandle *) * argc)) == NULL)
1013 		fatal("failed to allocate memory for arguments");
1014 
1015 	g_argv[g_argc++] = argv[0];	/* propagate argv[0] to D as $0/$$0 */
1016 	argv[0] = g_pname;		/* rewrite argv[0] for getopt errors */
1017 
1018 	bzero(status, sizeof (status));
1019 	bzero(&buf, sizeof (buf));
1020 
1021 	/*
1022 	 * Make an initial pass through argv[] processing any arguments that
1023 	 * affect our behavior mode (g_mode) and flags used for dtrace_open().
1024 	 * We also accumulate arguments that are not affiliated with getopt
1025 	 * options into g_argv[], and abort if any invalid options are found.
1026 	 */
1027 	for (optind = 1; optind < argc; optind++) {
1028 		while ((c = getopt(argc, argv, DTRACE_OPTSTR)) != EOF) {
1029 			switch (c) {
1030 			case '3':
1031 				if (strcmp(optarg, "2") != 0) {
1032 					(void) fprintf(stderr,
1033 					    "%s: illegal option -- 3%s\n",
1034 					    argv[0], optarg);
1035 					return (usage(stderr));
1036 				}
1037 				g_oflags &= ~DTRACE_O_LP64;
1038 				g_oflags |= DTRACE_O_ILP32;
1039 				break;
1040 
1041 			case '6':
1042 				if (strcmp(optarg, "4") != 0) {
1043 					(void) fprintf(stderr,
1044 					    "%s: illegal option -- 6%s\n",
1045 					    argv[0], optarg);
1046 					return (usage(stderr));
1047 				}
1048 				g_oflags &= ~DTRACE_O_ILP32;
1049 				g_oflags |= DTRACE_O_LP64;
1050 				break;
1051 
1052 			case 'a':
1053 				g_grabanon++; /* also checked in pass 2 below */
1054 				break;
1055 
1056 			case 'A':
1057 				g_mode = DMODE_ANON;
1058 				g_exec = 0;
1059 				mode++;
1060 				break;
1061 
1062 			case 'e':
1063 				g_exec = 0;
1064 				done = 1;
1065 				break;
1066 
1067 			case 'G':
1068 				g_mode = DMODE_LINK;
1069 				g_oflags |= DTRACE_O_NODEV;
1070 				g_cflags |= DTRACE_C_ZDEFS; /* -G implies -Z */
1071 				g_exec = 0;
1072 				mode++;
1073 				break;
1074 
1075 			case 'l':
1076 				g_mode = DMODE_LIST;
1077 				g_cflags |= DTRACE_C_ZDEFS; /* -l implies -Z */
1078 				mode++;
1079 				break;
1080 
1081 			case 'V':
1082 				g_mode = DMODE_VERS;
1083 				mode++;
1084 				break;
1085 
1086 			default:
1087 				if (strchr(DTRACE_OPTSTR, c) == NULL)
1088 					return (usage(stderr));
1089 			}
1090 		}
1091 
1092 		if (optind < argc)
1093 			g_argv[g_argc++] = argv[optind];
1094 	}
1095 
1096 	if (mode > 1) {
1097 		(void) fprintf(stderr, "%s: only one of the [-AGlV] options "
1098 		    "can be specified at a time\n", g_pname);
1099 		return (E_USAGE);
1100 	}
1101 
1102 	if (g_mode == DMODE_VERS)
1103 		return (printf("%s: %s\n", g_pname, _dtrace_version) <= 0);
1104 
1105 	/*
1106 	 * Open libdtrace.  If we are not actually going to be enabling any
1107 	 * instrumentation attempt to reopen libdtrace using DTRACE_O_NODEV.
1108 	 */
1109 	while ((g_dtp = dtrace_open(DTRACE_VERSION, g_oflags, &err)) == NULL) {
1110 		if (!(g_oflags & DTRACE_O_NODEV) && !g_exec && !g_grabanon) {
1111 			g_oflags |= DTRACE_O_NODEV;
1112 			continue;
1113 		}
1114 
1115 		fatal("failed to initialize dtrace: %s\n",
1116 		    dtrace_errmsg(NULL, err));
1117 	}
1118 
1119 	(void) dtrace_setopt(g_dtp, "bufsize", "4m");
1120 	(void) dtrace_setopt(g_dtp, "aggsize", "4m");
1121 
1122 	/*
1123 	 * If -G is specified, enable -xlink=dynamic and -xunodefs to permit
1124 	 * references to undefined symbols to remain as unresolved relocations.
1125 	 * If -A is specified, enable -xlink=primary to permit static linking
1126 	 * only to kernel symbols that are defined in a primary kernel module.
1127 	 */
1128 	if (g_mode == DMODE_LINK) {
1129 		(void) dtrace_setopt(g_dtp, "linkmode", "dynamic");
1130 		(void) dtrace_setopt(g_dtp, "unodefs", NULL);
1131 
1132 		g_objc = g_argc;
1133 		g_objv = g_argv;
1134 
1135 		/*
1136 		 * We still use g_argv[0], the name of the executable.
1137 		 */
1138 		g_argc = 1;
1139 	} else if (g_mode == DMODE_ANON)
1140 		(void) dtrace_setopt(g_dtp, "linkmode", "primary");
1141 
1142 	/*
1143 	 * Now that we have libdtrace open, make a second pass through argv[]
1144 	 * to perform any dtrace_setopt() calls and change any compiler flags.
1145 	 * We also accumulate any program specifications into our g_cmdv[] at
1146 	 * this time; these will compiled as part of the fourth processing pass.
1147 	 */
1148 	for (optind = 1; optind < argc; optind++) {
1149 		while ((c = getopt(argc, argv, DTRACE_OPTSTR)) != EOF) {
1150 			switch (c) {
1151 			case 'a':
1152 				if (dtrace_setopt(g_dtp, "grabanon", 0) != 0)
1153 					dfatal("failed to set -a");
1154 				break;
1155 
1156 			case 'b':
1157 				if (dtrace_setopt(g_dtp,
1158 				    "bufsize", optarg) != 0)
1159 					dfatal("failed to set -b %s", optarg);
1160 				break;
1161 
1162 			case 'C':
1163 				g_cflags |= DTRACE_C_CPP;
1164 				break;
1165 
1166 			case 'D':
1167 				if (dtrace_setopt(g_dtp, "define", optarg) != 0)
1168 					dfatal("failed to set -D %s", optarg);
1169 				break;
1170 
1171 			case 'f':
1172 				dcp = &g_cmdv[g_cmdc++];
1173 				dcp->dc_func = compile_str;
1174 				dcp->dc_spec = DTRACE_PROBESPEC_FUNC;
1175 				dcp->dc_arg = optarg;
1176 				break;
1177 
1178 			case 'F':
1179 				if (dtrace_setopt(g_dtp, "flowindent", 0) != 0)
1180 					dfatal("failed to set -F");
1181 				break;
1182 
1183 			case 'H':
1184 				if (dtrace_setopt(g_dtp, "cpphdrs", 0) != 0)
1185 					dfatal("failed to set -H");
1186 				break;
1187 
1188 			case 'i':
1189 				dcp = &g_cmdv[g_cmdc++];
1190 				dcp->dc_func = compile_str;
1191 				dcp->dc_spec = DTRACE_PROBESPEC_NAME;
1192 				dcp->dc_arg = optarg;
1193 				break;
1194 
1195 			case 'I':
1196 				if (dtrace_setopt(g_dtp, "incdir", optarg) != 0)
1197 					dfatal("failed to set -I %s", optarg);
1198 				break;
1199 
1200 			case 'L':
1201 				if (dtrace_setopt(g_dtp, "libdir", optarg) != 0)
1202 					dfatal("failed to set -L %s", optarg);
1203 				break;
1204 
1205 			case 'm':
1206 				dcp = &g_cmdv[g_cmdc++];
1207 				dcp->dc_func = compile_str;
1208 				dcp->dc_spec = DTRACE_PROBESPEC_MOD;
1209 				dcp->dc_arg = optarg;
1210 				break;
1211 
1212 			case 'n':
1213 				dcp = &g_cmdv[g_cmdc++];
1214 				dcp->dc_func = compile_str;
1215 				dcp->dc_spec = DTRACE_PROBESPEC_NAME;
1216 				dcp->dc_arg = optarg;
1217 				break;
1218 
1219 			case 'P':
1220 				dcp = &g_cmdv[g_cmdc++];
1221 				dcp->dc_func = compile_str;
1222 				dcp->dc_spec = DTRACE_PROBESPEC_PROVIDER;
1223 				dcp->dc_arg = optarg;
1224 				break;
1225 
1226 			case 'q':
1227 				if (dtrace_setopt(g_dtp, "quiet", 0) != 0)
1228 					dfatal("failed to set -q");
1229 				break;
1230 
1231 			case 'o':
1232 				g_ofile = optarg;
1233 				break;
1234 
1235 			case 's':
1236 				dcp = &g_cmdv[g_cmdc++];
1237 				dcp->dc_func = compile_file;
1238 				dcp->dc_spec = DTRACE_PROBESPEC_NONE;
1239 				dcp->dc_arg = optarg;
1240 				break;
1241 
1242 			case 'S':
1243 				g_cflags |= DTRACE_C_DIFV;
1244 				break;
1245 
1246 			case 'U':
1247 				if (dtrace_setopt(g_dtp, "undef", optarg) != 0)
1248 					dfatal("failed to set -U %s", optarg);
1249 				break;
1250 
1251 			case 'v':
1252 				g_verbose++;
1253 				break;
1254 
1255 			case 'w':
1256 				if (dtrace_setopt(g_dtp, "destructive", 0) != 0)
1257 					dfatal("failed to set -w");
1258 				break;
1259 
1260 			case 'x':
1261 				if ((p = strchr(optarg, '=')) != NULL)
1262 					*p++ = '\0';
1263 
1264 				if (dtrace_setopt(g_dtp, optarg, p) != 0)
1265 					dfatal("failed to set -x %s", optarg);
1266 				break;
1267 
1268 			case 'X':
1269 				if (dtrace_setopt(g_dtp, "stdc", optarg) != 0)
1270 					dfatal("failed to set -X %s", optarg);
1271 				break;
1272 
1273 			case 'Z':
1274 				g_cflags |= DTRACE_C_ZDEFS;
1275 				break;
1276 
1277 			default:
1278 				if (strchr(DTRACE_OPTSTR, c) == NULL)
1279 					return (usage(stderr));
1280 			}
1281 		}
1282 	}
1283 
1284 	/*
1285 	 * In our third pass we handle any command-line options related to
1286 	 * grabbing or creating victim processes.  The behavior of these calls
1287 	 * may been affected by any library options set by the second pass.
1288 	 */
1289 	for (optind = 1; optind < argc; optind++) {
1290 		while ((c = getopt(argc, argv, DTRACE_OPTSTR)) != EOF) {
1291 			switch (c) {
1292 			case 'c':
1293 				if ((v = make_argv(optarg)) == NULL)
1294 					fatal("failed to allocate memory");
1295 
1296 				P = dtrace_proc_create(g_dtp, v[0], v);
1297 				if (P == NULL)
1298 					dfatal(NULL); /* dtrace_errmsg() only */
1299 
1300 				g_psv[g_psc++] = P;
1301 				free(v);
1302 				break;
1303 
1304 			case 'p':
1305 				errno = 0;
1306 				pid = strtol(optarg, &p, 10);
1307 
1308 				if (errno != 0 || p == optarg || p[0] != '\0')
1309 					fatal("invalid pid: %s\n", optarg);
1310 
1311 				P = dtrace_proc_grab(g_dtp, pid, 0);
1312 				if (P == NULL)
1313 					dfatal(NULL); /* dtrace_errmsg() only */
1314 
1315 				g_psv[g_psc++] = P;
1316 				break;
1317 			}
1318 		}
1319 	}
1320 
1321 	/*
1322 	 * In our fourth pass we finish g_cmdv[] by calling dc_func to convert
1323 	 * each string or file specification into a compiled program structure.
1324 	 */
1325 	for (i = 0; i < g_cmdc; i++)
1326 		g_cmdv[i].dc_func(&g_cmdv[i]);
1327 
1328 	if (g_mode != DMODE_LIST) {
1329 		if (dtrace_handle_err(g_dtp, &errhandler, NULL) == -1)
1330 			dfatal("failed to establish error handler");
1331 
1332 		if (dtrace_handle_drop(g_dtp, &drophandler, NULL) == -1)
1333 			dfatal("failed to establish drop handler");
1334 
1335 		if (dtrace_handle_proc(g_dtp, &prochandler, NULL) == -1)
1336 			dfatal("failed to establish proc handler");
1337 
1338 		if (dtrace_handle_setopt(g_dtp, &setopthandler, NULL) == -1)
1339 			dfatal("failed to establish setopt handler");
1340 	}
1341 
1342 	(void) dtrace_getopt(g_dtp, "flowindent", &opt);
1343 	g_flowindent = opt != DTRACEOPT_UNSET;
1344 
1345 	(void) dtrace_getopt(g_dtp, "grabanon", &opt);
1346 	g_grabanon = opt != DTRACEOPT_UNSET;
1347 
1348 	(void) dtrace_getopt(g_dtp, "quiet", &opt);
1349 	g_quiet = opt != DTRACEOPT_UNSET;
1350 
1351 	/*
1352 	 * Now make a fifth and final pass over the options that have been
1353 	 * turned into programs and saved in g_cmdv[], performing any mode-
1354 	 * specific processing.  If g_mode is DMODE_EXEC, we will break out
1355 	 * of the switch() and continue on to the data processing loop.  For
1356 	 * other modes, we will exit dtrace once mode-specific work is done.
1357 	 */
1358 	switch (g_mode) {
1359 	case DMODE_EXEC:
1360 		if (g_ofile != NULL && (g_ofp = fopen(g_ofile, "a")) == NULL)
1361 			fatal("failed to open output file '%s'", g_ofile);
1362 
1363 		for (i = 0; i < g_cmdc; i++)
1364 			exec_prog(&g_cmdv[i]);
1365 
1366 		if (done && !g_grabanon) {
1367 			dtrace_close(g_dtp);
1368 			return (g_status);
1369 		}
1370 		break;
1371 
1372 	case DMODE_ANON:
1373 		if (g_ofile == NULL)
1374 			g_ofile = "/kernel/drv/dtrace.conf";
1375 
1376 		dof_prune(g_ofile); /* strip out any old DOF directives */
1377 		etcsystem_prune(); /* string out any forceload directives */
1378 
1379 		if (g_cmdc == 0) {
1380 			dtrace_close(g_dtp);
1381 			return (g_status);
1382 		}
1383 
1384 		if ((g_ofp = fopen(g_ofile, "a")) == NULL)
1385 			fatal("failed to open output file '%s'", g_ofile);
1386 
1387 		for (i = 0; i < g_cmdc; i++) {
1388 			anon_prog(&g_cmdv[i],
1389 			    dtrace_dof_create(g_dtp, g_cmdv[i].dc_prog, 0), i);
1390 		}
1391 
1392 		/*
1393 		 * Dump out the DOF corresponding to the error handler and the
1394 		 * current options as the final DOF property in the .conf file.
1395 		 */
1396 		anon_prog(NULL, dtrace_geterr_dof(g_dtp), i++);
1397 		anon_prog(NULL, dtrace_getopt_dof(g_dtp), i++);
1398 
1399 		if (fclose(g_ofp) == EOF)
1400 			fatal("failed to close output file '%s'", g_ofile);
1401 
1402 		/*
1403 		 * These messages would use notice() rather than error(), but
1404 		 * we don't want them suppressed when -A is run on a D program
1405 		 * that itself contains a #pragma D option quiet.
1406 		 */
1407 		error("saved anonymous enabling in %s\n", g_ofile);
1408 		etcsystem_add();
1409 		error("run update_drv(1M) or reboot to enable changes\n");
1410 
1411 		dtrace_close(g_dtp);
1412 		return (g_status);
1413 
1414 	case DMODE_LINK:
1415 		for (i = 0; i < g_cmdc; i++)
1416 			link_prog(&g_cmdv[i]);
1417 
1418 		if (g_cmdc > 1 && g_ofile != NULL) {
1419 			char **objv = alloca(g_cmdc * sizeof (char *));
1420 
1421 			for (i = 0; i < g_cmdc; i++)
1422 				objv[i] = g_cmdv[i].dc_ofile;
1423 
1424 			if (dtrace_program_link(g_dtp, NULL, DTRACE_D_PROBES,
1425 			    g_ofile, g_cmdc, objv) != 0)
1426 				dfatal(NULL); /* dtrace_errmsg() only */
1427 		}
1428 
1429 		dtrace_close(g_dtp);
1430 		return (g_status);
1431 
1432 	case DMODE_LIST:
1433 		if (g_ofile != NULL && (g_ofp = fopen(g_ofile, "a")) == NULL)
1434 			fatal("failed to open output file '%s'", g_ofile);
1435 
1436 		oprintf("%5s %10s %17s %33s %s\n",
1437 		    "ID", "PROVIDER", "MODULE", "FUNCTION", "NAME");
1438 
1439 		for (i = 0; i < g_cmdc; i++)
1440 			list_prog(&g_cmdv[i]);
1441 
1442 		if (g_cmdc == 0)
1443 			(void) dtrace_probe_iter(g_dtp, NULL, list_probe, NULL);
1444 
1445 		dtrace_close(g_dtp);
1446 		return (g_status);
1447 	}
1448 
1449 	/*
1450 	 * If -a and -Z were not specified and no probes have been matched, no
1451 	 * probe criteria was specified on the command line and we abort.
1452 	 */
1453 	if (g_total == 0 && !g_grabanon && !(g_cflags & DTRACE_C_ZDEFS))
1454 		dfatal("no probes %s\n", g_cmdc ? "matched" : "specified");
1455 
1456 	/*
1457 	 * Start tracing.  Once we dtrace_go(), reload any options that affect
1458 	 * our globals in case consuming anonymous state has changed them.
1459 	 */
1460 	go();
1461 
1462 	(void) dtrace_getopt(g_dtp, "flowindent", &opt);
1463 	g_flowindent = opt != DTRACEOPT_UNSET;
1464 
1465 	(void) dtrace_getopt(g_dtp, "grabanon", &opt);
1466 	g_grabanon = opt != DTRACEOPT_UNSET;
1467 
1468 	(void) dtrace_getopt(g_dtp, "quiet", &opt);
1469 	g_quiet = opt != DTRACEOPT_UNSET;
1470 
1471 	(void) dtrace_getopt(g_dtp, "destructive", &opt);
1472 	if (opt != DTRACEOPT_UNSET)
1473 		notice("allowing destructive actions\n");
1474 
1475 	(void) sigemptyset(&act.sa_mask);
1476 	act.sa_flags = 0;
1477 	act.sa_handler = intr;
1478 	(void) sigaction(SIGINT, &act, NULL);
1479 	(void) sigaction(SIGTERM, &act, NULL);
1480 
1481 	/*
1482 	 * Now that tracing is active and we are ready to consume trace data,
1483 	 * continue any grabbed or created processes, setting them running
1484 	 * using the /proc control mechanism inside of libdtrace.
1485 	 */
1486 	for (i = 0; i < g_psc; i++)
1487 		dtrace_proc_continue(g_dtp, g_psv[i]);
1488 
1489 	g_pslive = g_psc; /* count for prochandler() */
1490 
1491 	do {
1492 		if (!g_intr && !done)
1493 			dtrace_sleep(g_dtp);
1494 
1495 		if (g_newline) {
1496 			/*
1497 			 * Output a newline just to make the output look
1498 			 * slightly cleaner.  Note that we do this even in
1499 			 * "quiet" mode...
1500 			 */
1501 			oprintf("\n");
1502 			g_newline = 0;
1503 		}
1504 
1505 		if (done || g_intr || (g_psc != 0 && g_pslive == 0)) {
1506 			done = 1;
1507 			if (dtrace_stop(g_dtp) == -1)
1508 				dfatal("couldn't stop tracing");
1509 		}
1510 
1511 		switch (dtrace_work(g_dtp, g_ofp, chew, chewrec, NULL)) {
1512 		case DTRACE_WORKSTATUS_DONE:
1513 			done = 1;
1514 			break;
1515 		case DTRACE_WORKSTATUS_OKAY:
1516 			break;
1517 		default:
1518 			if (!g_impatient && dtrace_errno(g_dtp) != EINTR)
1519 				dfatal("processing aborted");
1520 		}
1521 
1522 		if (fflush(g_ofp) == EOF)
1523 			clearerr(g_ofp);
1524 	} while (!done);
1525 
1526 	oprintf("\n");
1527 
1528 	if (!g_impatient) {
1529 		if (dtrace_aggregate_print(g_dtp, g_ofp, NULL) == -1 &&
1530 		    dtrace_errno(g_dtp) != EINTR)
1531 			dfatal("failed to print aggregations");
1532 	}
1533 
1534 	dtrace_close(g_dtp);
1535 	return (g_status);
1536 }
1537