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