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