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