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