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