xref: /titanic_50/usr/src/lib/libdtrace/common/dt_cc.c (revision c2589d1319a6171334739fb4b10ddc8317ec486b)
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 (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011, Joyent Inc. All rights reserved.
25  * Copyright (c) 2012 by Delphix. All rights reserved.
26  */
27 
28 /*
29  * DTrace D Language Compiler
30  *
31  * The code in this source file implements the main engine for the D language
32  * compiler.  The driver routine for the compiler is dt_compile(), below.  The
33  * compiler operates on either stdio FILEs or in-memory strings as its input
34  * and can produce either dtrace_prog_t structures from a D program or a single
35  * dtrace_difo_t structure from a D expression.  Multiple entry points are
36  * provided as wrappers around dt_compile() for the various input/output pairs.
37  * The compiler itself is implemented across the following source files:
38  *
39  * dt_lex.l - lex scanner
40  * dt_grammar.y - yacc grammar
41  * dt_parser.c - parse tree creation and semantic checking
42  * dt_decl.c - declaration stack processing
43  * dt_xlator.c - D translator lookup and creation
44  * dt_ident.c - identifier and symbol table routines
45  * dt_pragma.c - #pragma processing and D pragmas
46  * dt_printf.c - D printf() and printa() argument checking and processing
47  * dt_cc.c - compiler driver and dtrace_prog_t construction
48  * dt_cg.c - DIF code generator
49  * dt_as.c - DIF assembler
50  * dt_dof.c - dtrace_prog_t -> DOF conversion
51  *
52  * Several other source files provide collections of utility routines used by
53  * these major files.  The compiler itself is implemented in multiple passes:
54  *
55  * (1) The input program is scanned and parsed by dt_lex.l and dt_grammar.y
56  *     and parse tree nodes are constructed using the routines in dt_parser.c.
57  *     This node construction pass is described further in dt_parser.c.
58  *
59  * (2) The parse tree is "cooked" by assigning each clause a context (see the
60  *     routine dt_setcontext(), below) based on its probe description and then
61  *     recursively descending the tree performing semantic checking.  The cook
62  *     routines are also implemented in dt_parser.c and described there.
63  *
64  * (3) For actions that are DIF expression statements, the DIF code generator
65  *     and assembler are invoked to create a finished DIFO for the statement.
66  *
67  * (4) The dtrace_prog_t data structures for the program clauses and actions
68  *     are built, containing pointers to any DIFOs created in step (3).
69  *
70  * (5) The caller invokes a routine in dt_dof.c to convert the finished program
71  *     into DOF format for use in anonymous tracing or enabling in the kernel.
72  *
73  * In the implementation, steps 2-4 are intertwined in that they are performed
74  * in order for each clause as part of a loop that executes over the clauses.
75  *
76  * The D compiler currently implements nearly no optimization.  The compiler
77  * implements integer constant folding as part of pass (1), and a set of very
78  * simple peephole optimizations as part of pass (3).  As with any C compiler,
79  * a large number of optimizations are possible on both the intermediate data
80  * structures and the generated DIF code.  These possibilities should be
81  * investigated in the context of whether they will have any substantive effect
82  * on the overall DTrace probe effect before they are undertaken.
83  */
84 
85 #include <sys/types.h>
86 #include <sys/wait.h>
87 #include <sys/sysmacros.h>
88 
89 #include <assert.h>
90 #include <strings.h>
91 #include <signal.h>
92 #include <unistd.h>
93 #include <stdlib.h>
94 #include <stdio.h>
95 #include <errno.h>
96 #include <ucontext.h>
97 #include <limits.h>
98 #include <ctype.h>
99 #include <dirent.h>
100 #include <dt_module.h>
101 #include <dt_program.h>
102 #include <dt_provider.h>
103 #include <dt_printf.h>
104 #include <dt_pid.h>
105 #include <dt_grammar.h>
106 #include <dt_ident.h>
107 #include <dt_string.h>
108 #include <dt_impl.h>
109 
110 static const dtrace_diftype_t dt_void_rtype = {
111 	DIF_TYPE_CTF, CTF_K_INTEGER, 0, 0, 0
112 };
113 
114 static const dtrace_diftype_t dt_int_rtype = {
115 	DIF_TYPE_CTF, CTF_K_INTEGER, 0, 0, sizeof (uint64_t)
116 };
117 
118 static void *dt_compile(dtrace_hdl_t *, int, dtrace_probespec_t, void *,
119     uint_t, int, char *const[], FILE *, const char *);
120 
121 
122 /*ARGSUSED*/
123 static int
124 dt_idreset(dt_idhash_t *dhp, dt_ident_t *idp, void *ignored)
125 {
126 	idp->di_flags &= ~(DT_IDFLG_REF | DT_IDFLG_MOD |
127 	    DT_IDFLG_DIFR | DT_IDFLG_DIFW);
128 	return (0);
129 }
130 
131 /*ARGSUSED*/
132 static int
133 dt_idpragma(dt_idhash_t *dhp, dt_ident_t *idp, void *ignored)
134 {
135 	yylineno = idp->di_lineno;
136 	xyerror(D_PRAGMA_UNUSED, "unused #pragma %s\n", (char *)idp->di_iarg);
137 	return (0);
138 }
139 
140 static dtrace_stmtdesc_t *
141 dt_stmt_create(dtrace_hdl_t *dtp, dtrace_ecbdesc_t *edp,
142     dtrace_attribute_t descattr, dtrace_attribute_t stmtattr)
143 {
144 	dtrace_stmtdesc_t *sdp = dtrace_stmt_create(dtp, edp);
145 
146 	if (sdp == NULL)
147 		longjmp(yypcb->pcb_jmpbuf, EDT_NOMEM);
148 
149 	assert(yypcb->pcb_stmt == NULL);
150 	yypcb->pcb_stmt = sdp;
151 
152 	sdp->dtsd_descattr = descattr;
153 	sdp->dtsd_stmtattr = stmtattr;
154 
155 	return (sdp);
156 }
157 
158 static dtrace_actdesc_t *
159 dt_stmt_action(dtrace_hdl_t *dtp, dtrace_stmtdesc_t *sdp)
160 {
161 	dtrace_actdesc_t *new;
162 
163 	if ((new = dtrace_stmt_action(dtp, sdp)) == NULL)
164 		longjmp(yypcb->pcb_jmpbuf, EDT_NOMEM);
165 
166 	return (new);
167 }
168 
169 /*
170  * Utility function to determine if a given action description is destructive.
171  * The dtdo_destructive bit is set for us by the DIF assembler (see dt_as.c).
172  */
173 static int
174 dt_action_destructive(const dtrace_actdesc_t *ap)
175 {
176 	return (DTRACEACT_ISDESTRUCTIVE(ap->dtad_kind) || (ap->dtad_kind ==
177 	    DTRACEACT_DIFEXPR && ap->dtad_difo->dtdo_destructive));
178 }
179 
180 static void
181 dt_stmt_append(dtrace_stmtdesc_t *sdp, const dt_node_t *dnp)
182 {
183 	dtrace_ecbdesc_t *edp = sdp->dtsd_ecbdesc;
184 	dtrace_actdesc_t *ap, *tap;
185 	int commit = 0;
186 	int speculate = 0;
187 	int datarec = 0;
188 
189 	/*
190 	 * Make sure that the new statement jibes with the rest of the ECB.
191 	 */
192 	for (ap = edp->dted_action; ap != NULL; ap = ap->dtad_next) {
193 		if (ap->dtad_kind == DTRACEACT_COMMIT) {
194 			if (commit) {
195 				dnerror(dnp, D_COMM_COMM, "commit( ) may "
196 				    "not follow commit( )\n");
197 			}
198 
199 			if (datarec) {
200 				dnerror(dnp, D_COMM_DREC, "commit( ) may "
201 				    "not follow data-recording action(s)\n");
202 			}
203 
204 			for (tap = ap; tap != NULL; tap = tap->dtad_next) {
205 				if (!DTRACEACT_ISAGG(tap->dtad_kind))
206 					continue;
207 
208 				dnerror(dnp, D_AGG_COMM, "aggregating actions "
209 				    "may not follow commit( )\n");
210 			}
211 
212 			commit = 1;
213 			continue;
214 		}
215 
216 		if (ap->dtad_kind == DTRACEACT_SPECULATE) {
217 			if (speculate) {
218 				dnerror(dnp, D_SPEC_SPEC, "speculate( ) may "
219 				    "not follow speculate( )\n");
220 			}
221 
222 			if (commit) {
223 				dnerror(dnp, D_SPEC_COMM, "speculate( ) may "
224 				    "not follow commit( )\n");
225 			}
226 
227 			if (datarec) {
228 				dnerror(dnp, D_SPEC_DREC, "speculate( ) may "
229 				    "not follow data-recording action(s)\n");
230 			}
231 
232 			speculate = 1;
233 			continue;
234 		}
235 
236 		if (DTRACEACT_ISAGG(ap->dtad_kind)) {
237 			if (speculate) {
238 				dnerror(dnp, D_AGG_SPEC, "aggregating actions "
239 				    "may not follow speculate( )\n");
240 			}
241 
242 			datarec = 1;
243 			continue;
244 		}
245 
246 		if (speculate) {
247 			if (dt_action_destructive(ap)) {
248 				dnerror(dnp, D_ACT_SPEC, "destructive actions "
249 				    "may not follow speculate( )\n");
250 			}
251 
252 			if (ap->dtad_kind == DTRACEACT_EXIT) {
253 				dnerror(dnp, D_EXIT_SPEC, "exit( ) may not "
254 				    "follow speculate( )\n");
255 			}
256 		}
257 
258 		/*
259 		 * Exclude all non data-recording actions.
260 		 */
261 		if (dt_action_destructive(ap) ||
262 		    ap->dtad_kind == DTRACEACT_DISCARD)
263 			continue;
264 
265 		if (ap->dtad_kind == DTRACEACT_DIFEXPR &&
266 		    ap->dtad_difo->dtdo_rtype.dtdt_kind == DIF_TYPE_CTF &&
267 		    ap->dtad_difo->dtdo_rtype.dtdt_size == 0)
268 			continue;
269 
270 		if (commit) {
271 			dnerror(dnp, D_DREC_COMM, "data-recording actions "
272 			    "may not follow commit( )\n");
273 		}
274 
275 		if (!speculate)
276 			datarec = 1;
277 	}
278 
279 	if (dtrace_stmt_add(yypcb->pcb_hdl, yypcb->pcb_prog, sdp) != 0)
280 		longjmp(yypcb->pcb_jmpbuf, dtrace_errno(yypcb->pcb_hdl));
281 
282 	if (yypcb->pcb_stmt == sdp)
283 		yypcb->pcb_stmt = NULL;
284 }
285 
286 /*
287  * For the first element of an aggregation tuple or for printa(), we create a
288  * simple DIF program that simply returns the immediate value that is the ID
289  * of the aggregation itself.  This could be optimized in the future by
290  * creating a new in-kernel dtad_kind that just returns an integer.
291  */
292 static void
293 dt_action_difconst(dtrace_actdesc_t *ap, uint_t id, dtrace_actkind_t kind)
294 {
295 	dtrace_hdl_t *dtp = yypcb->pcb_hdl;
296 	dtrace_difo_t *dp = dt_zalloc(dtp, sizeof (dtrace_difo_t));
297 
298 	if (dp == NULL)
299 		longjmp(yypcb->pcb_jmpbuf, EDT_NOMEM);
300 
301 	dp->dtdo_buf = dt_alloc(dtp, sizeof (dif_instr_t) * 2);
302 	dp->dtdo_inttab = dt_alloc(dtp, sizeof (uint64_t));
303 
304 	if (dp->dtdo_buf == NULL || dp->dtdo_inttab == NULL) {
305 		dt_difo_free(dtp, dp);
306 		longjmp(yypcb->pcb_jmpbuf, EDT_NOMEM);
307 	}
308 
309 	dp->dtdo_buf[0] = DIF_INSTR_SETX(0, 1); /* setx	DIF_INTEGER[0], %r1 */
310 	dp->dtdo_buf[1] = DIF_INSTR_RET(1);	/* ret	%r1 */
311 	dp->dtdo_len = 2;
312 	dp->dtdo_inttab[0] = id;
313 	dp->dtdo_intlen = 1;
314 	dp->dtdo_rtype = dt_int_rtype;
315 
316 	ap->dtad_difo = dp;
317 	ap->dtad_kind = kind;
318 }
319 
320 static void
321 dt_action_clear(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
322 {
323 	dt_ident_t *aid;
324 	dtrace_actdesc_t *ap;
325 	dt_node_t *anp;
326 
327 	char n[DT_TYPE_NAMELEN];
328 	int argc = 0;
329 
330 	for (anp = dnp->dn_args; anp != NULL; anp = anp->dn_list)
331 		argc++; /* count up arguments for error messages below */
332 
333 	if (argc != 1) {
334 		dnerror(dnp, D_CLEAR_PROTO,
335 		    "%s( ) prototype mismatch: %d args passed, 1 expected\n",
336 		    dnp->dn_ident->di_name, argc);
337 	}
338 
339 	anp = dnp->dn_args;
340 	assert(anp != NULL);
341 
342 	if (anp->dn_kind != DT_NODE_AGG) {
343 		dnerror(dnp, D_CLEAR_AGGARG,
344 		    "%s( ) argument #1 is incompatible with prototype:\n"
345 		    "\tprototype: aggregation\n\t argument: %s\n",
346 		    dnp->dn_ident->di_name,
347 		    dt_node_type_name(anp, n, sizeof (n)));
348 	}
349 
350 	aid = anp->dn_ident;
351 
352 	if (aid->di_gen == dtp->dt_gen && !(aid->di_flags & DT_IDFLG_MOD)) {
353 		dnerror(dnp, D_CLEAR_AGGBAD,
354 		    "undefined aggregation: @%s\n", aid->di_name);
355 	}
356 
357 	ap = dt_stmt_action(dtp, sdp);
358 	dt_action_difconst(ap, anp->dn_ident->di_id, DTRACEACT_LIBACT);
359 	ap->dtad_arg = DT_ACT_CLEAR;
360 }
361 
362 static void
363 dt_action_normalize(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
364 {
365 	dt_ident_t *aid;
366 	dtrace_actdesc_t *ap;
367 	dt_node_t *anp, *normal;
368 	int denormal = (strcmp(dnp->dn_ident->di_name, "denormalize") == 0);
369 
370 	char n[DT_TYPE_NAMELEN];
371 	int argc = 0;
372 
373 	for (anp = dnp->dn_args; anp != NULL; anp = anp->dn_list)
374 		argc++; /* count up arguments for error messages below */
375 
376 	if ((denormal && argc != 1) || (!denormal && argc != 2)) {
377 		dnerror(dnp, D_NORMALIZE_PROTO,
378 		    "%s( ) prototype mismatch: %d args passed, %d expected\n",
379 		    dnp->dn_ident->di_name, argc, denormal ? 1 : 2);
380 	}
381 
382 	anp = dnp->dn_args;
383 	assert(anp != NULL);
384 
385 	if (anp->dn_kind != DT_NODE_AGG) {
386 		dnerror(dnp, D_NORMALIZE_AGGARG,
387 		    "%s( ) argument #1 is incompatible with prototype:\n"
388 		    "\tprototype: aggregation\n\t argument: %s\n",
389 		    dnp->dn_ident->di_name,
390 		    dt_node_type_name(anp, n, sizeof (n)));
391 	}
392 
393 	if ((normal = anp->dn_list) != NULL && !dt_node_is_scalar(normal)) {
394 		dnerror(dnp, D_NORMALIZE_SCALAR,
395 		    "%s( ) argument #2 must be of scalar type\n",
396 		    dnp->dn_ident->di_name);
397 	}
398 
399 	aid = anp->dn_ident;
400 
401 	if (aid->di_gen == dtp->dt_gen && !(aid->di_flags & DT_IDFLG_MOD)) {
402 		dnerror(dnp, D_NORMALIZE_AGGBAD,
403 		    "undefined aggregation: @%s\n", aid->di_name);
404 	}
405 
406 	ap = dt_stmt_action(dtp, sdp);
407 	dt_action_difconst(ap, anp->dn_ident->di_id, DTRACEACT_LIBACT);
408 
409 	if (denormal) {
410 		ap->dtad_arg = DT_ACT_DENORMALIZE;
411 		return;
412 	}
413 
414 	ap->dtad_arg = DT_ACT_NORMALIZE;
415 
416 	assert(normal != NULL);
417 	ap = dt_stmt_action(dtp, sdp);
418 	dt_cg(yypcb, normal);
419 
420 	ap->dtad_difo = dt_as(yypcb);
421 	ap->dtad_kind = DTRACEACT_LIBACT;
422 	ap->dtad_arg = DT_ACT_NORMALIZE;
423 }
424 
425 static void
426 dt_action_trunc(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
427 {
428 	dt_ident_t *aid;
429 	dtrace_actdesc_t *ap;
430 	dt_node_t *anp, *trunc;
431 
432 	char n[DT_TYPE_NAMELEN];
433 	int argc = 0;
434 
435 	for (anp = dnp->dn_args; anp != NULL; anp = anp->dn_list)
436 		argc++; /* count up arguments for error messages below */
437 
438 	if (argc > 2 || argc < 1) {
439 		dnerror(dnp, D_TRUNC_PROTO,
440 		    "%s( ) prototype mismatch: %d args passed, %s expected\n",
441 		    dnp->dn_ident->di_name, argc,
442 		    argc < 1 ? "at least 1" : "no more than 2");
443 	}
444 
445 	anp = dnp->dn_args;
446 	assert(anp != NULL);
447 	trunc = anp->dn_list;
448 
449 	if (anp->dn_kind != DT_NODE_AGG) {
450 		dnerror(dnp, D_TRUNC_AGGARG,
451 		    "%s( ) argument #1 is incompatible with prototype:\n"
452 		    "\tprototype: aggregation\n\t argument: %s\n",
453 		    dnp->dn_ident->di_name,
454 		    dt_node_type_name(anp, n, sizeof (n)));
455 	}
456 
457 	if (argc == 2) {
458 		assert(trunc != NULL);
459 		if (!dt_node_is_scalar(trunc)) {
460 			dnerror(dnp, D_TRUNC_SCALAR,
461 			    "%s( ) argument #2 must be of scalar type\n",
462 			    dnp->dn_ident->di_name);
463 		}
464 	}
465 
466 	aid = anp->dn_ident;
467 
468 	if (aid->di_gen == dtp->dt_gen && !(aid->di_flags & DT_IDFLG_MOD)) {
469 		dnerror(dnp, D_TRUNC_AGGBAD,
470 		    "undefined aggregation: @%s\n", aid->di_name);
471 	}
472 
473 	ap = dt_stmt_action(dtp, sdp);
474 	dt_action_difconst(ap, anp->dn_ident->di_id, DTRACEACT_LIBACT);
475 	ap->dtad_arg = DT_ACT_TRUNC;
476 
477 	ap = dt_stmt_action(dtp, sdp);
478 
479 	if (argc == 1) {
480 		dt_action_difconst(ap, 0, DTRACEACT_LIBACT);
481 	} else {
482 		assert(trunc != NULL);
483 		dt_cg(yypcb, trunc);
484 		ap->dtad_difo = dt_as(yypcb);
485 		ap->dtad_kind = DTRACEACT_LIBACT;
486 	}
487 
488 	ap->dtad_arg = DT_ACT_TRUNC;
489 }
490 
491 static void
492 dt_action_printa(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
493 {
494 	dt_ident_t *aid, *fid;
495 	dtrace_actdesc_t *ap;
496 	const char *format;
497 	dt_node_t *anp, *proto = NULL;
498 
499 	char n[DT_TYPE_NAMELEN];
500 	int argc = 0, argr = 0;
501 
502 	for (anp = dnp->dn_args; anp != NULL; anp = anp->dn_list)
503 		argc++; /* count up arguments for error messages below */
504 
505 	switch (dnp->dn_args->dn_kind) {
506 	case DT_NODE_STRING:
507 		format = dnp->dn_args->dn_string;
508 		anp = dnp->dn_args->dn_list;
509 		argr = 2;
510 		break;
511 	case DT_NODE_AGG:
512 		format = NULL;
513 		anp = dnp->dn_args;
514 		argr = 1;
515 		break;
516 	default:
517 		format = NULL;
518 		anp = dnp->dn_args;
519 		argr = 1;
520 	}
521 
522 	if (argc < argr) {
523 		dnerror(dnp, D_PRINTA_PROTO,
524 		    "%s( ) prototype mismatch: %d args passed, %d expected\n",
525 		    dnp->dn_ident->di_name, argc, argr);
526 	}
527 
528 	assert(anp != NULL);
529 
530 	while (anp != NULL) {
531 		if (anp->dn_kind != DT_NODE_AGG) {
532 			dnerror(dnp, D_PRINTA_AGGARG,
533 			    "%s( ) argument #%d is incompatible with "
534 			    "prototype:\n\tprototype: aggregation\n"
535 			    "\t argument: %s\n", dnp->dn_ident->di_name, argr,
536 			    dt_node_type_name(anp, n, sizeof (n)));
537 		}
538 
539 		aid = anp->dn_ident;
540 		fid = aid->di_iarg;
541 
542 		if (aid->di_gen == dtp->dt_gen &&
543 		    !(aid->di_flags & DT_IDFLG_MOD)) {
544 			dnerror(dnp, D_PRINTA_AGGBAD,
545 			    "undefined aggregation: @%s\n", aid->di_name);
546 		}
547 
548 		/*
549 		 * If we have multiple aggregations, we must be sure that
550 		 * their key signatures match.
551 		 */
552 		if (proto != NULL) {
553 			dt_printa_validate(proto, anp);
554 		} else {
555 			proto = anp;
556 		}
557 
558 		if (format != NULL) {
559 			yylineno = dnp->dn_line;
560 
561 			sdp->dtsd_fmtdata =
562 			    dt_printf_create(yypcb->pcb_hdl, format);
563 			dt_printf_validate(sdp->dtsd_fmtdata,
564 			    DT_PRINTF_AGGREGATION, dnp->dn_ident, 1,
565 			    fid->di_id, ((dt_idsig_t *)aid->di_data)->dis_args);
566 			format = NULL;
567 		}
568 
569 		ap = dt_stmt_action(dtp, sdp);
570 		dt_action_difconst(ap, anp->dn_ident->di_id, DTRACEACT_PRINTA);
571 
572 		anp = anp->dn_list;
573 		argr++;
574 	}
575 }
576 
577 static void
578 dt_action_printflike(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp,
579     dtrace_actkind_t kind)
580 {
581 	dt_node_t *anp, *arg1;
582 	dtrace_actdesc_t *ap = NULL;
583 	char n[DT_TYPE_NAMELEN], *str;
584 
585 	assert(DTRACEACT_ISPRINTFLIKE(kind));
586 
587 	if (dnp->dn_args->dn_kind != DT_NODE_STRING) {
588 		dnerror(dnp, D_PRINTF_ARG_FMT,
589 		    "%s( ) argument #1 is incompatible with prototype:\n"
590 		    "\tprototype: string constant\n\t argument: %s\n",
591 		    dnp->dn_ident->di_name,
592 		    dt_node_type_name(dnp->dn_args, n, sizeof (n)));
593 	}
594 
595 	arg1 = dnp->dn_args->dn_list;
596 	yylineno = dnp->dn_line;
597 	str = dnp->dn_args->dn_string;
598 
599 
600 	/*
601 	 * If this is an freopen(), we use an empty string to denote that
602 	 * stdout should be restored.  For other printf()-like actions, an
603 	 * empty format string is illegal:  an empty format string would
604 	 * result in malformed DOF, and the compiler thus flags an empty
605 	 * format string as a compile-time error.  To avoid propagating the
606 	 * freopen() special case throughout the system, we simply transpose
607 	 * an empty string into a sentinel string (DT_FREOPEN_RESTORE) that
608 	 * denotes that stdout should be restored.
609 	 */
610 	if (kind == DTRACEACT_FREOPEN) {
611 		if (strcmp(str, DT_FREOPEN_RESTORE) == 0) {
612 			/*
613 			 * Our sentinel is always an invalid argument to
614 			 * freopen(), but if it's been manually specified, we
615 			 * must fail now instead of when the freopen() is
616 			 * actually evaluated.
617 			 */
618 			dnerror(dnp, D_FREOPEN_INVALID,
619 			    "%s( ) argument #1 cannot be \"%s\"\n",
620 			    dnp->dn_ident->di_name, DT_FREOPEN_RESTORE);
621 		}
622 
623 		if (str[0] == '\0')
624 			str = DT_FREOPEN_RESTORE;
625 	}
626 
627 	sdp->dtsd_fmtdata = dt_printf_create(dtp, str);
628 
629 	dt_printf_validate(sdp->dtsd_fmtdata, DT_PRINTF_EXACTLEN,
630 	    dnp->dn_ident, 1, DTRACEACT_AGGREGATION, arg1);
631 
632 	if (arg1 == NULL) {
633 		dif_instr_t *dbuf;
634 		dtrace_difo_t *dp;
635 
636 		if ((dbuf = dt_alloc(dtp, sizeof (dif_instr_t))) == NULL ||
637 		    (dp = dt_zalloc(dtp, sizeof (dtrace_difo_t))) == NULL) {
638 			dt_free(dtp, dbuf);
639 			longjmp(yypcb->pcb_jmpbuf, EDT_NOMEM);
640 		}
641 
642 		dbuf[0] = DIF_INSTR_RET(DIF_REG_R0); /* ret %r0 */
643 
644 		dp->dtdo_buf = dbuf;
645 		dp->dtdo_len = 1;
646 		dp->dtdo_rtype = dt_int_rtype;
647 
648 		ap = dt_stmt_action(dtp, sdp);
649 		ap->dtad_difo = dp;
650 		ap->dtad_kind = kind;
651 		return;
652 	}
653 
654 	for (anp = arg1; anp != NULL; anp = anp->dn_list) {
655 		ap = dt_stmt_action(dtp, sdp);
656 		dt_cg(yypcb, anp);
657 		ap->dtad_difo = dt_as(yypcb);
658 		ap->dtad_kind = kind;
659 	}
660 }
661 
662 static void
663 dt_action_trace(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
664 {
665 	dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
666 	boolean_t istrace = (dnp->dn_ident->di_id == DT_ACT_TRACE);
667 	const char *act = istrace ?  "trace" : "print";
668 
669 	if (dt_node_is_void(dnp->dn_args)) {
670 		dnerror(dnp->dn_args, istrace ? D_TRACE_VOID : D_PRINT_VOID,
671 		    "%s( ) may not be applied to a void expression\n", act);
672 	}
673 
674 	if (dt_node_resolve(dnp->dn_args, DT_IDENT_XLPTR) != NULL) {
675 		dnerror(dnp->dn_args, istrace ? D_TRACE_DYN : D_PRINT_DYN,
676 		    "%s( ) may not be applied to a translated pointer\n", act);
677 	}
678 
679 	if (dnp->dn_args->dn_kind == DT_NODE_AGG) {
680 		dnerror(dnp->dn_args, istrace ? D_TRACE_AGG : D_PRINT_AGG,
681 		    "%s( ) may not be applied to an aggregation%s\n", act,
682 		    istrace ? "" : " -- did you mean printa()?");
683 	}
684 
685 	dt_cg(yypcb, dnp->dn_args);
686 
687 	/*
688 	 * The print() action behaves identically to trace(), except that it
689 	 * stores the CTF type of the argument (if present) within the DOF for
690 	 * the DIFEXPR action.  To do this, we set the 'dtsd_strdata' to point
691 	 * to the fully-qualified CTF type ID for the result of the DIF
692 	 * action.  We use the ID instead of the name to handles complex types
693 	 * like arrays and function pointers that can't be resolved by
694 	 * ctf_type_lookup().  This is later processed by dtrace_dof_create()
695 	 * and turned into a reference into the string table so that we can
696 	 * get the type information when we process the data after the fact.
697 	 */
698 	if (dnp->dn_ident->di_id == DT_ACT_PRINT) {
699 		dt_node_t *dret;
700 		size_t n;
701 		dt_module_t *dmp;
702 
703 		dret = yypcb->pcb_dret;
704 		dmp = dt_module_lookup_by_ctf(dtp, dret->dn_ctfp);
705 
706 		n = snprintf(NULL, 0, "%s`%d", dmp->dm_name, dret->dn_type) + 1;
707 		sdp->dtsd_strdata = dt_alloc(dtp, n);
708 		if (sdp->dtsd_strdata == NULL)
709 			longjmp(yypcb->pcb_jmpbuf, EDT_NOMEM);
710 		(void) snprintf(sdp->dtsd_strdata, n, "%s`%d", dmp->dm_name,
711 		    dret->dn_type);
712 	}
713 
714 	ap->dtad_difo = dt_as(yypcb);
715 	ap->dtad_kind = DTRACEACT_DIFEXPR;
716 }
717 
718 static void
719 dt_action_tracemem(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
720 {
721 	dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
722 
723 	dt_node_t *addr = dnp->dn_args;
724 	dt_node_t *max = dnp->dn_args->dn_list;
725 	dt_node_t *size;
726 
727 	char n[DT_TYPE_NAMELEN];
728 
729 	if (dt_node_is_integer(addr) == 0 && dt_node_is_pointer(addr) == 0) {
730 		dnerror(addr, D_TRACEMEM_ADDR,
731 		    "tracemem( ) argument #1 is incompatible with "
732 		    "prototype:\n\tprototype: pointer or integer\n"
733 		    "\t argument: %s\n",
734 		    dt_node_type_name(addr, n, sizeof (n)));
735 	}
736 
737 	if (dt_node_is_posconst(max) == 0) {
738 		dnerror(max, D_TRACEMEM_SIZE, "tracemem( ) argument #2 must "
739 		    "be a non-zero positive integral constant expression\n");
740 	}
741 
742 	if ((size = max->dn_list) != NULL) {
743 		if (size->dn_list != NULL) {
744 			dnerror(size, D_TRACEMEM_ARGS, "tracemem ( ) prototype "
745 			    "mismatch: expected at most 3 args\n");
746 		}
747 
748 		if (!dt_node_is_scalar(size)) {
749 			dnerror(size, D_TRACEMEM_DYNSIZE, "tracemem ( ) "
750 			    "dynamic size (argument #3) must be of "
751 			    "scalar type\n");
752 		}
753 
754 		dt_cg(yypcb, size);
755 		ap->dtad_difo = dt_as(yypcb);
756 		ap->dtad_difo->dtdo_rtype = dt_int_rtype;
757 		ap->dtad_kind = DTRACEACT_TRACEMEM_DYNSIZE;
758 
759 		ap = dt_stmt_action(dtp, sdp);
760 	}
761 
762 	dt_cg(yypcb, addr);
763 	ap->dtad_difo = dt_as(yypcb);
764 	ap->dtad_kind = DTRACEACT_TRACEMEM;
765 
766 	ap->dtad_difo->dtdo_rtype.dtdt_flags |= DIF_TF_BYREF;
767 	ap->dtad_difo->dtdo_rtype.dtdt_size = max->dn_value;
768 }
769 
770 static void
771 dt_action_stack_args(dtrace_hdl_t *dtp, dtrace_actdesc_t *ap, dt_node_t *arg0)
772 {
773 	ap->dtad_kind = DTRACEACT_STACK;
774 
775 	if (dtp->dt_options[DTRACEOPT_STACKFRAMES] != DTRACEOPT_UNSET) {
776 		ap->dtad_arg = dtp->dt_options[DTRACEOPT_STACKFRAMES];
777 	} else {
778 		ap->dtad_arg = 0;
779 	}
780 
781 	if (arg0 != NULL) {
782 		if (arg0->dn_list != NULL) {
783 			dnerror(arg0, D_STACK_PROTO, "stack( ) prototype "
784 			    "mismatch: too many arguments\n");
785 		}
786 
787 		if (dt_node_is_posconst(arg0) == 0) {
788 			dnerror(arg0, D_STACK_SIZE, "stack( ) size must be a "
789 			    "non-zero positive integral constant expression\n");
790 		}
791 
792 		ap->dtad_arg = arg0->dn_value;
793 	}
794 }
795 
796 static void
797 dt_action_stack(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
798 {
799 	dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
800 	dt_action_stack_args(dtp, ap, dnp->dn_args);
801 }
802 
803 static void
804 dt_action_ustack_args(dtrace_hdl_t *dtp, dtrace_actdesc_t *ap, dt_node_t *dnp)
805 {
806 	uint32_t nframes = 0;
807 	uint32_t strsize = 0;	/* default string table size */
808 	dt_node_t *arg0 = dnp->dn_args;
809 	dt_node_t *arg1 = arg0 != NULL ? arg0->dn_list : NULL;
810 
811 	assert(dnp->dn_ident->di_id == DT_ACT_JSTACK ||
812 	    dnp->dn_ident->di_id == DT_ACT_USTACK);
813 
814 	if (dnp->dn_ident->di_id == DT_ACT_JSTACK) {
815 		if (dtp->dt_options[DTRACEOPT_JSTACKFRAMES] != DTRACEOPT_UNSET)
816 			nframes = dtp->dt_options[DTRACEOPT_JSTACKFRAMES];
817 
818 		if (dtp->dt_options[DTRACEOPT_JSTACKSTRSIZE] != DTRACEOPT_UNSET)
819 			strsize = dtp->dt_options[DTRACEOPT_JSTACKSTRSIZE];
820 
821 		ap->dtad_kind = DTRACEACT_JSTACK;
822 	} else {
823 		assert(dnp->dn_ident->di_id == DT_ACT_USTACK);
824 
825 		if (dtp->dt_options[DTRACEOPT_USTACKFRAMES] != DTRACEOPT_UNSET)
826 			nframes = dtp->dt_options[DTRACEOPT_USTACKFRAMES];
827 
828 		ap->dtad_kind = DTRACEACT_USTACK;
829 	}
830 
831 	if (arg0 != NULL) {
832 		if (!dt_node_is_posconst(arg0)) {
833 			dnerror(arg0, D_USTACK_FRAMES, "ustack( ) argument #1 "
834 			    "must be a non-zero positive integer constant\n");
835 		}
836 		nframes = (uint32_t)arg0->dn_value;
837 	}
838 
839 	if (arg1 != NULL) {
840 		if (arg1->dn_kind != DT_NODE_INT ||
841 		    ((arg1->dn_flags & DT_NF_SIGNED) &&
842 		    (int64_t)arg1->dn_value < 0)) {
843 			dnerror(arg1, D_USTACK_STRSIZE, "ustack( ) argument #2 "
844 			    "must be a positive integer constant\n");
845 		}
846 
847 		if (arg1->dn_list != NULL) {
848 			dnerror(arg1, D_USTACK_PROTO, "ustack( ) prototype "
849 			    "mismatch: too many arguments\n");
850 		}
851 
852 		strsize = (uint32_t)arg1->dn_value;
853 	}
854 
855 	ap->dtad_arg = DTRACE_USTACK_ARG(nframes, strsize);
856 }
857 
858 static void
859 dt_action_ustack(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
860 {
861 	dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
862 	dt_action_ustack_args(dtp, ap, dnp);
863 }
864 
865 static void
866 dt_action_setopt(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
867 {
868 	dtrace_actdesc_t *ap;
869 	dt_node_t *arg0, *arg1;
870 
871 	/*
872 	 * The prototype guarantees that we are called with either one or
873 	 * two arguments, and that any arguments that are present are strings.
874 	 */
875 	arg0 = dnp->dn_args;
876 	arg1 = arg0->dn_list;
877 
878 	ap = dt_stmt_action(dtp, sdp);
879 	dt_cg(yypcb, arg0);
880 	ap->dtad_difo = dt_as(yypcb);
881 	ap->dtad_kind = DTRACEACT_LIBACT;
882 	ap->dtad_arg = DT_ACT_SETOPT;
883 
884 	ap = dt_stmt_action(dtp, sdp);
885 
886 	if (arg1 == NULL) {
887 		dt_action_difconst(ap, 0, DTRACEACT_LIBACT);
888 	} else {
889 		dt_cg(yypcb, arg1);
890 		ap->dtad_difo = dt_as(yypcb);
891 		ap->dtad_kind = DTRACEACT_LIBACT;
892 	}
893 
894 	ap->dtad_arg = DT_ACT_SETOPT;
895 }
896 
897 /*ARGSUSED*/
898 static void
899 dt_action_symmod_args(dtrace_hdl_t *dtp, dtrace_actdesc_t *ap,
900     dt_node_t *dnp, dtrace_actkind_t kind)
901 {
902 	assert(kind == DTRACEACT_SYM || kind == DTRACEACT_MOD ||
903 	    kind == DTRACEACT_USYM || kind == DTRACEACT_UMOD ||
904 	    kind == DTRACEACT_UADDR);
905 
906 	dt_cg(yypcb, dnp);
907 	ap->dtad_difo = dt_as(yypcb);
908 	ap->dtad_kind = kind;
909 	ap->dtad_difo->dtdo_rtype.dtdt_size = sizeof (uint64_t);
910 }
911 
912 static void
913 dt_action_symmod(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp,
914     dtrace_actkind_t kind)
915 {
916 	dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
917 	dt_action_symmod_args(dtp, ap, dnp->dn_args, kind);
918 }
919 
920 /*ARGSUSED*/
921 static void
922 dt_action_ftruncate(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
923 {
924 	dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
925 
926 	/*
927 	 * Library actions need a DIFO that serves as an argument.  As
928 	 * ftruncate() doesn't take an argument, we generate the constant 0
929 	 * in a DIFO; this constant will be ignored when the ftruncate() is
930 	 * processed.
931 	 */
932 	dt_action_difconst(ap, 0, DTRACEACT_LIBACT);
933 	ap->dtad_arg = DT_ACT_FTRUNCATE;
934 }
935 
936 /*ARGSUSED*/
937 static void
938 dt_action_stop(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
939 {
940 	dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
941 
942 	ap->dtad_kind = DTRACEACT_STOP;
943 	ap->dtad_arg = 0;
944 }
945 
946 /*ARGSUSED*/
947 static void
948 dt_action_breakpoint(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
949 {
950 	dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
951 
952 	ap->dtad_kind = DTRACEACT_BREAKPOINT;
953 	ap->dtad_arg = 0;
954 }
955 
956 /*ARGSUSED*/
957 static void
958 dt_action_panic(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
959 {
960 	dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
961 
962 	ap->dtad_kind = DTRACEACT_PANIC;
963 	ap->dtad_arg = 0;
964 }
965 
966 static void
967 dt_action_chill(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
968 {
969 	dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
970 
971 	dt_cg(yypcb, dnp->dn_args);
972 	ap->dtad_difo = dt_as(yypcb);
973 	ap->dtad_kind = DTRACEACT_CHILL;
974 }
975 
976 static void
977 dt_action_raise(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
978 {
979 	dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
980 
981 	dt_cg(yypcb, dnp->dn_args);
982 	ap->dtad_difo = dt_as(yypcb);
983 	ap->dtad_kind = DTRACEACT_RAISE;
984 }
985 
986 static void
987 dt_action_exit(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
988 {
989 	dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
990 
991 	dt_cg(yypcb, dnp->dn_args);
992 	ap->dtad_difo = dt_as(yypcb);
993 	ap->dtad_kind = DTRACEACT_EXIT;
994 	ap->dtad_difo->dtdo_rtype.dtdt_size = sizeof (int);
995 }
996 
997 static void
998 dt_action_speculate(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
999 {
1000 	dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
1001 
1002 	dt_cg(yypcb, dnp->dn_args);
1003 	ap->dtad_difo = dt_as(yypcb);
1004 	ap->dtad_kind = DTRACEACT_SPECULATE;
1005 }
1006 
1007 static void
1008 dt_action_commit(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
1009 {
1010 	dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
1011 
1012 	dt_cg(yypcb, dnp->dn_args);
1013 	ap->dtad_difo = dt_as(yypcb);
1014 	ap->dtad_kind = DTRACEACT_COMMIT;
1015 }
1016 
1017 static void
1018 dt_action_discard(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
1019 {
1020 	dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
1021 
1022 	dt_cg(yypcb, dnp->dn_args);
1023 	ap->dtad_difo = dt_as(yypcb);
1024 	ap->dtad_kind = DTRACEACT_DISCARD;
1025 }
1026 
1027 static void
1028 dt_compile_fun(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
1029 {
1030 	switch (dnp->dn_expr->dn_ident->di_id) {
1031 	case DT_ACT_BREAKPOINT:
1032 		dt_action_breakpoint(dtp, dnp->dn_expr, sdp);
1033 		break;
1034 	case DT_ACT_CHILL:
1035 		dt_action_chill(dtp, dnp->dn_expr, sdp);
1036 		break;
1037 	case DT_ACT_CLEAR:
1038 		dt_action_clear(dtp, dnp->dn_expr, sdp);
1039 		break;
1040 	case DT_ACT_COMMIT:
1041 		dt_action_commit(dtp, dnp->dn_expr, sdp);
1042 		break;
1043 	case DT_ACT_DENORMALIZE:
1044 		dt_action_normalize(dtp, dnp->dn_expr, sdp);
1045 		break;
1046 	case DT_ACT_DISCARD:
1047 		dt_action_discard(dtp, dnp->dn_expr, sdp);
1048 		break;
1049 	case DT_ACT_EXIT:
1050 		dt_action_exit(dtp, dnp->dn_expr, sdp);
1051 		break;
1052 	case DT_ACT_FREOPEN:
1053 		dt_action_printflike(dtp, dnp->dn_expr, sdp, DTRACEACT_FREOPEN);
1054 		break;
1055 	case DT_ACT_FTRUNCATE:
1056 		dt_action_ftruncate(dtp, dnp->dn_expr, sdp);
1057 		break;
1058 	case DT_ACT_MOD:
1059 		dt_action_symmod(dtp, dnp->dn_expr, sdp, DTRACEACT_MOD);
1060 		break;
1061 	case DT_ACT_NORMALIZE:
1062 		dt_action_normalize(dtp, dnp->dn_expr, sdp);
1063 		break;
1064 	case DT_ACT_PANIC:
1065 		dt_action_panic(dtp, dnp->dn_expr, sdp);
1066 		break;
1067 	case DT_ACT_PRINT:
1068 		dt_action_trace(dtp, dnp->dn_expr, sdp);
1069 		break;
1070 	case DT_ACT_PRINTA:
1071 		dt_action_printa(dtp, dnp->dn_expr, sdp);
1072 		break;
1073 	case DT_ACT_PRINTF:
1074 		dt_action_printflike(dtp, dnp->dn_expr, sdp, DTRACEACT_PRINTF);
1075 		break;
1076 	case DT_ACT_RAISE:
1077 		dt_action_raise(dtp, dnp->dn_expr, sdp);
1078 		break;
1079 	case DT_ACT_SETOPT:
1080 		dt_action_setopt(dtp, dnp->dn_expr, sdp);
1081 		break;
1082 	case DT_ACT_SPECULATE:
1083 		dt_action_speculate(dtp, dnp->dn_expr, sdp);
1084 		break;
1085 	case DT_ACT_STACK:
1086 		dt_action_stack(dtp, dnp->dn_expr, sdp);
1087 		break;
1088 	case DT_ACT_STOP:
1089 		dt_action_stop(dtp, dnp->dn_expr, sdp);
1090 		break;
1091 	case DT_ACT_SYM:
1092 		dt_action_symmod(dtp, dnp->dn_expr, sdp, DTRACEACT_SYM);
1093 		break;
1094 	case DT_ACT_SYSTEM:
1095 		dt_action_printflike(dtp, dnp->dn_expr, sdp, DTRACEACT_SYSTEM);
1096 		break;
1097 	case DT_ACT_TRACE:
1098 		dt_action_trace(dtp, dnp->dn_expr, sdp);
1099 		break;
1100 	case DT_ACT_TRACEMEM:
1101 		dt_action_tracemem(dtp, dnp->dn_expr, sdp);
1102 		break;
1103 	case DT_ACT_TRUNC:
1104 		dt_action_trunc(dtp, dnp->dn_expr, sdp);
1105 		break;
1106 	case DT_ACT_UADDR:
1107 		dt_action_symmod(dtp, dnp->dn_expr, sdp, DTRACEACT_UADDR);
1108 		break;
1109 	case DT_ACT_UMOD:
1110 		dt_action_symmod(dtp, dnp->dn_expr, sdp, DTRACEACT_UMOD);
1111 		break;
1112 	case DT_ACT_USYM:
1113 		dt_action_symmod(dtp, dnp->dn_expr, sdp, DTRACEACT_USYM);
1114 		break;
1115 	case DT_ACT_USTACK:
1116 	case DT_ACT_JSTACK:
1117 		dt_action_ustack(dtp, dnp->dn_expr, sdp);
1118 		break;
1119 	default:
1120 		dnerror(dnp->dn_expr, D_UNKNOWN, "tracing function %s( ) is "
1121 		    "not yet supported\n", dnp->dn_expr->dn_ident->di_name);
1122 	}
1123 }
1124 
1125 static void
1126 dt_compile_exp(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
1127 {
1128 	dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
1129 
1130 	dt_cg(yypcb, dnp->dn_expr);
1131 	ap->dtad_difo = dt_as(yypcb);
1132 	ap->dtad_difo->dtdo_rtype = dt_void_rtype;
1133 	ap->dtad_kind = DTRACEACT_DIFEXPR;
1134 }
1135 
1136 static void
1137 dt_compile_agg(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
1138 {
1139 	dt_ident_t *aid, *fid;
1140 	dt_node_t *anp, *incr = NULL;
1141 	dtrace_actdesc_t *ap;
1142 	uint_t n = 1, argmax;
1143 	uint64_t arg = 0;
1144 
1145 	/*
1146 	 * If the aggregation has no aggregating function applied to it, then
1147 	 * this statement has no effect.  Flag this as a programming error.
1148 	 */
1149 	if (dnp->dn_aggfun == NULL) {
1150 		dnerror(dnp, D_AGG_NULL, "expression has null effect: @%s\n",
1151 		    dnp->dn_ident->di_name);
1152 	}
1153 
1154 	aid = dnp->dn_ident;
1155 	fid = dnp->dn_aggfun->dn_ident;
1156 
1157 	if (dnp->dn_aggfun->dn_args != NULL &&
1158 	    dt_node_is_scalar(dnp->dn_aggfun->dn_args) == 0) {
1159 		dnerror(dnp->dn_aggfun, D_AGG_SCALAR, "%s( ) argument #1 must "
1160 		    "be of scalar type\n", fid->di_name);
1161 	}
1162 
1163 	/*
1164 	 * The ID of the aggregation itself is implicitly recorded as the first
1165 	 * member of each aggregation tuple so we can distinguish them later.
1166 	 */
1167 	ap = dt_stmt_action(dtp, sdp);
1168 	dt_action_difconst(ap, aid->di_id, DTRACEACT_DIFEXPR);
1169 
1170 	for (anp = dnp->dn_aggtup; anp != NULL; anp = anp->dn_list) {
1171 		ap = dt_stmt_action(dtp, sdp);
1172 		n++;
1173 
1174 		if (anp->dn_kind == DT_NODE_FUNC) {
1175 			if (anp->dn_ident->di_id == DT_ACT_STACK) {
1176 				dt_action_stack_args(dtp, ap, anp->dn_args);
1177 				continue;
1178 			}
1179 
1180 			if (anp->dn_ident->di_id == DT_ACT_USTACK ||
1181 			    anp->dn_ident->di_id == DT_ACT_JSTACK) {
1182 				dt_action_ustack_args(dtp, ap, anp);
1183 				continue;
1184 			}
1185 
1186 			switch (anp->dn_ident->di_id) {
1187 			case DT_ACT_UADDR:
1188 				dt_action_symmod_args(dtp, ap,
1189 				    anp->dn_args, DTRACEACT_UADDR);
1190 				continue;
1191 
1192 			case DT_ACT_USYM:
1193 				dt_action_symmod_args(dtp, ap,
1194 				    anp->dn_args, DTRACEACT_USYM);
1195 				continue;
1196 
1197 			case DT_ACT_UMOD:
1198 				dt_action_symmod_args(dtp, ap,
1199 				    anp->dn_args, DTRACEACT_UMOD);
1200 				continue;
1201 
1202 			case DT_ACT_SYM:
1203 				dt_action_symmod_args(dtp, ap,
1204 				    anp->dn_args, DTRACEACT_SYM);
1205 				continue;
1206 
1207 			case DT_ACT_MOD:
1208 				dt_action_symmod_args(dtp, ap,
1209 				    anp->dn_args, DTRACEACT_MOD);
1210 				continue;
1211 
1212 			default:
1213 				break;
1214 			}
1215 		}
1216 
1217 		dt_cg(yypcb, anp);
1218 		ap->dtad_difo = dt_as(yypcb);
1219 		ap->dtad_kind = DTRACEACT_DIFEXPR;
1220 	}
1221 
1222 	if (fid->di_id == DTRACEAGG_LQUANTIZE) {
1223 		/*
1224 		 * For linear quantization, we have between two and four
1225 		 * arguments in addition to the expression:
1226 		 *
1227 		 *    arg1 => Base value
1228 		 *    arg2 => Limit value
1229 		 *    arg3 => Quantization level step size (defaults to 1)
1230 		 *    arg4 => Quantization increment value (defaults to 1)
1231 		 */
1232 		dt_node_t *arg1 = dnp->dn_aggfun->dn_args->dn_list;
1233 		dt_node_t *arg2 = arg1->dn_list;
1234 		dt_node_t *arg3 = arg2->dn_list;
1235 		dt_idsig_t *isp;
1236 		uint64_t nlevels, step = 1, oarg;
1237 		int64_t baseval, limitval;
1238 
1239 		if (arg1->dn_kind != DT_NODE_INT) {
1240 			dnerror(arg1, D_LQUANT_BASETYPE, "lquantize( ) "
1241 			    "argument #1 must be an integer constant\n");
1242 		}
1243 
1244 		baseval = (int64_t)arg1->dn_value;
1245 
1246 		if (baseval < INT32_MIN || baseval > INT32_MAX) {
1247 			dnerror(arg1, D_LQUANT_BASEVAL, "lquantize( ) "
1248 			    "argument #1 must be a 32-bit quantity\n");
1249 		}
1250 
1251 		if (arg2->dn_kind != DT_NODE_INT) {
1252 			dnerror(arg2, D_LQUANT_LIMTYPE, "lquantize( ) "
1253 			    "argument #2 must be an integer constant\n");
1254 		}
1255 
1256 		limitval = (int64_t)arg2->dn_value;
1257 
1258 		if (limitval < INT32_MIN || limitval > INT32_MAX) {
1259 			dnerror(arg2, D_LQUANT_LIMVAL, "lquantize( ) "
1260 			    "argument #2 must be a 32-bit quantity\n");
1261 		}
1262 
1263 		if (limitval < baseval) {
1264 			dnerror(dnp, D_LQUANT_MISMATCH,
1265 			    "lquantize( ) base (argument #1) must be less "
1266 			    "than limit (argument #2)\n");
1267 		}
1268 
1269 		if (arg3 != NULL) {
1270 			if (!dt_node_is_posconst(arg3)) {
1271 				dnerror(arg3, D_LQUANT_STEPTYPE, "lquantize( ) "
1272 				    "argument #3 must be a non-zero positive "
1273 				    "integer constant\n");
1274 			}
1275 
1276 			if ((step = arg3->dn_value) > UINT16_MAX) {
1277 				dnerror(arg3, D_LQUANT_STEPVAL, "lquantize( ) "
1278 				    "argument #3 must be a 16-bit quantity\n");
1279 			}
1280 		}
1281 
1282 		nlevels = (limitval - baseval) / step;
1283 
1284 		if (nlevels == 0) {
1285 			dnerror(dnp, D_LQUANT_STEPLARGE,
1286 			    "lquantize( ) step (argument #3) too large: must "
1287 			    "have at least one quantization level\n");
1288 		}
1289 
1290 		if (nlevels > UINT16_MAX) {
1291 			dnerror(dnp, D_LQUANT_STEPSMALL, "lquantize( ) step "
1292 			    "(argument #3) too small: number of quantization "
1293 			    "levels must be a 16-bit quantity\n");
1294 		}
1295 
1296 		arg = (step << DTRACE_LQUANTIZE_STEPSHIFT) |
1297 		    (nlevels << DTRACE_LQUANTIZE_LEVELSHIFT) |
1298 		    ((baseval << DTRACE_LQUANTIZE_BASESHIFT) &
1299 		    DTRACE_LQUANTIZE_BASEMASK);
1300 
1301 		assert(arg != 0);
1302 
1303 		isp = (dt_idsig_t *)aid->di_data;
1304 
1305 		if (isp->dis_auxinfo == 0) {
1306 			/*
1307 			 * This is the first time we've seen an lquantize()
1308 			 * for this aggregation; we'll store our argument
1309 			 * as the auxiliary signature information.
1310 			 */
1311 			isp->dis_auxinfo = arg;
1312 		} else if ((oarg = isp->dis_auxinfo) != arg) {
1313 			/*
1314 			 * If we have seen this lquantize() before and the
1315 			 * argument doesn't match the original argument, pick
1316 			 * the original argument apart to concisely report the
1317 			 * mismatch.
1318 			 */
1319 			int obaseval = DTRACE_LQUANTIZE_BASE(oarg);
1320 			int onlevels = DTRACE_LQUANTIZE_LEVELS(oarg);
1321 			int ostep = DTRACE_LQUANTIZE_STEP(oarg);
1322 
1323 			if (obaseval != baseval) {
1324 				dnerror(dnp, D_LQUANT_MATCHBASE, "lquantize( ) "
1325 				    "base (argument #1) doesn't match previous "
1326 				    "declaration: expected %d, found %d\n",
1327 				    obaseval, (int)baseval);
1328 			}
1329 
1330 			if (onlevels * ostep != nlevels * step) {
1331 				dnerror(dnp, D_LQUANT_MATCHLIM, "lquantize( ) "
1332 				    "limit (argument #2) doesn't match previous"
1333 				    " declaration: expected %d, found %d\n",
1334 				    obaseval + onlevels * ostep,
1335 				    (int)baseval + (int)nlevels * (int)step);
1336 			}
1337 
1338 			if (ostep != step) {
1339 				dnerror(dnp, D_LQUANT_MATCHSTEP, "lquantize( ) "
1340 				    "step (argument #3) doesn't match previous "
1341 				    "declaration: expected %d, found %d\n",
1342 				    ostep, (int)step);
1343 			}
1344 
1345 			/*
1346 			 * We shouldn't be able to get here -- one of the
1347 			 * parameters must be mismatched if the arguments
1348 			 * didn't match.
1349 			 */
1350 			assert(0);
1351 		}
1352 
1353 		incr = arg3 != NULL ? arg3->dn_list : NULL;
1354 		argmax = 5;
1355 	}
1356 
1357 	if (fid->di_id == DTRACEAGG_LLQUANTIZE) {
1358 		/*
1359 		 * For log/linear quantizations, we have between one and five
1360 		 * arguments in addition to the expression:
1361 		 *
1362 		 *    arg1 => Factor
1363 		 *    arg2 => Low magnitude
1364 		 *    arg3 => High magnitude
1365 		 *    arg4 => Number of steps per magnitude
1366 		 *    arg5 => Quantization increment value (defaults to 1)
1367 		 */
1368 		dt_node_t *llarg = dnp->dn_aggfun->dn_args->dn_list;
1369 		uint64_t oarg, order, v;
1370 		dt_idsig_t *isp;
1371 		int i;
1372 
1373 		struct {
1374 			char *str;		/* string identifier */
1375 			int badtype;		/* error on bad type */
1376 			int badval;		/* error on bad value */
1377 			int mismatch;		/* error on bad match */
1378 			int shift;		/* shift value */
1379 			uint16_t value;		/* value itself */
1380 		} args[] = {
1381 			{ "factor", D_LLQUANT_FACTORTYPE,
1382 			    D_LLQUANT_FACTORVAL, D_LLQUANT_FACTORMATCH,
1383 			    DTRACE_LLQUANTIZE_FACTORSHIFT },
1384 			{ "low magnitude", D_LLQUANT_LOWTYPE,
1385 			    D_LLQUANT_LOWVAL, D_LLQUANT_LOWMATCH,
1386 			    DTRACE_LLQUANTIZE_LOWSHIFT },
1387 			{ "high magnitude", D_LLQUANT_HIGHTYPE,
1388 			    D_LLQUANT_HIGHVAL, D_LLQUANT_HIGHMATCH,
1389 			    DTRACE_LLQUANTIZE_HIGHSHIFT },
1390 			{ "linear steps per magnitude", D_LLQUANT_NSTEPTYPE,
1391 			    D_LLQUANT_NSTEPVAL, D_LLQUANT_NSTEPMATCH,
1392 			    DTRACE_LLQUANTIZE_NSTEPSHIFT },
1393 			{ NULL }
1394 		};
1395 
1396 		assert(arg == 0);
1397 
1398 		for (i = 0; args[i].str != NULL; i++) {
1399 			if (llarg->dn_kind != DT_NODE_INT) {
1400 				dnerror(llarg, args[i].badtype, "llquantize( ) "
1401 				    "argument #%d (%s) must be an "
1402 				    "integer constant\n", i + 1, args[i].str);
1403 			}
1404 
1405 			if ((uint64_t)llarg->dn_value > UINT16_MAX) {
1406 				dnerror(llarg, args[i].badval, "llquantize( ) "
1407 				    "argument #%d (%s) must be an unsigned "
1408 				    "16-bit quantity\n", i + 1, args[i].str);
1409 			}
1410 
1411 			args[i].value = (uint16_t)llarg->dn_value;
1412 
1413 			assert(!(arg & (UINT16_MAX << args[i].shift)));
1414 			arg |= ((uint64_t)args[i].value << args[i].shift);
1415 			llarg = llarg->dn_list;
1416 		}
1417 
1418 		assert(arg != 0);
1419 
1420 		if (args[0].value < 2) {
1421 			dnerror(dnp, D_LLQUANT_FACTORSMALL, "llquantize( ) "
1422 			    "factor (argument #1) must be two or more\n");
1423 		}
1424 
1425 		if (args[1].value >= args[2].value) {
1426 			dnerror(dnp, D_LLQUANT_MAGRANGE, "llquantize( ) "
1427 			    "high magnitude (argument #3) must be greater "
1428 			    "than low magnitude (argument #2)\n");
1429 		}
1430 
1431 		if (args[3].value < args[0].value) {
1432 			dnerror(dnp, D_LLQUANT_FACTORNSTEPS, "llquantize( ) "
1433 			    "factor (argument #1) must be less than or "
1434 			    "equal to the number of linear steps per "
1435 			    "magnitude (argument #4)\n");
1436 		}
1437 
1438 		for (v = args[0].value; v < args[3].value; v *= args[0].value)
1439 			continue;
1440 
1441 		if ((args[3].value % args[0].value) || (v % args[3].value)) {
1442 			dnerror(dnp, D_LLQUANT_FACTOREVEN, "llquantize( ) "
1443 			    "factor (argument #1) must evenly divide the "
1444 			    "number of steps per magnitude (argument #4), "
1445 			    "and the number of steps per magnitude must evenly "
1446 			    "divide a power of the factor\n");
1447 		}
1448 
1449 		for (i = 0, order = 1; i < args[2].value; i++) {
1450 			if (order * args[0].value > order) {
1451 				order *= args[0].value;
1452 				continue;
1453 			}
1454 
1455 			dnerror(dnp, D_LLQUANT_MAGTOOBIG, "llquantize( ) "
1456 			    "factor (%d) raised to power of high magnitude "
1457 			    "(%d) overflows 64-bits\n", args[0].value,
1458 			    args[2].value);
1459 		}
1460 
1461 		isp = (dt_idsig_t *)aid->di_data;
1462 
1463 		if (isp->dis_auxinfo == 0) {
1464 			/*
1465 			 * This is the first time we've seen an llquantize()
1466 			 * for this aggregation; we'll store our argument
1467 			 * as the auxiliary signature information.
1468 			 */
1469 			isp->dis_auxinfo = arg;
1470 		} else if ((oarg = isp->dis_auxinfo) != arg) {
1471 			/*
1472 			 * If we have seen this llquantize() before and the
1473 			 * argument doesn't match the original argument, pick
1474 			 * the original argument apart to concisely report the
1475 			 * mismatch.
1476 			 */
1477 			int expected = 0, found = 0;
1478 
1479 			for (i = 0; expected == found; i++) {
1480 				assert(args[i].str != NULL);
1481 
1482 				expected = (oarg >> args[i].shift) & UINT16_MAX;
1483 				found = (arg >> args[i].shift) & UINT16_MAX;
1484 			}
1485 
1486 			dnerror(dnp, args[i - 1].mismatch, "llquantize( ) "
1487 			    "%s (argument #%d) doesn't match previous "
1488 			    "declaration: expected %d, found %d\n",
1489 			    args[i - 1].str, i, expected, found);
1490 		}
1491 
1492 		incr = llarg;
1493 		argmax = 6;
1494 	}
1495 
1496 	if (fid->di_id == DTRACEAGG_QUANTIZE) {
1497 		incr = dnp->dn_aggfun->dn_args->dn_list;
1498 		argmax = 2;
1499 	}
1500 
1501 	if (incr != NULL) {
1502 		if (!dt_node_is_scalar(incr)) {
1503 			dnerror(dnp, D_PROTO_ARG, "%s( ) increment value "
1504 			    "(argument #%d) must be of scalar type\n",
1505 			    fid->di_name, argmax);
1506 		}
1507 
1508 		if ((anp = incr->dn_list) != NULL) {
1509 			int argc = argmax;
1510 
1511 			for (; anp != NULL; anp = anp->dn_list)
1512 				argc++;
1513 
1514 			dnerror(incr, D_PROTO_LEN, "%s( ) prototype "
1515 			    "mismatch: %d args passed, at most %d expected",
1516 			    fid->di_name, argc, argmax);
1517 		}
1518 
1519 		ap = dt_stmt_action(dtp, sdp);
1520 		n++;
1521 
1522 		dt_cg(yypcb, incr);
1523 		ap->dtad_difo = dt_as(yypcb);
1524 		ap->dtad_difo->dtdo_rtype = dt_void_rtype;
1525 		ap->dtad_kind = DTRACEACT_DIFEXPR;
1526 	}
1527 
1528 	assert(sdp->dtsd_aggdata == NULL);
1529 	sdp->dtsd_aggdata = aid;
1530 
1531 	ap = dt_stmt_action(dtp, sdp);
1532 	assert(fid->di_kind == DT_IDENT_AGGFUNC);
1533 	assert(DTRACEACT_ISAGG(fid->di_id));
1534 	ap->dtad_kind = fid->di_id;
1535 	ap->dtad_ntuple = n;
1536 	ap->dtad_arg = arg;
1537 
1538 	if (dnp->dn_aggfun->dn_args != NULL) {
1539 		dt_cg(yypcb, dnp->dn_aggfun->dn_args);
1540 		ap->dtad_difo = dt_as(yypcb);
1541 	}
1542 }
1543 
1544 static void
1545 dt_compile_one_clause(dtrace_hdl_t *dtp, dt_node_t *cnp, dt_node_t *pnp)
1546 {
1547 	dtrace_ecbdesc_t *edp;
1548 	dtrace_stmtdesc_t *sdp;
1549 	dt_node_t *dnp;
1550 
1551 	yylineno = pnp->dn_line;
1552 	dt_setcontext(dtp, pnp->dn_desc);
1553 	(void) dt_node_cook(cnp, DT_IDFLG_REF);
1554 
1555 	if (DT_TREEDUMP_PASS(dtp, 2))
1556 		dt_node_printr(cnp, stderr, 0);
1557 
1558 	if ((edp = dt_ecbdesc_create(dtp, pnp->dn_desc)) == NULL)
1559 		longjmp(yypcb->pcb_jmpbuf, EDT_NOMEM);
1560 
1561 	assert(yypcb->pcb_ecbdesc == NULL);
1562 	yypcb->pcb_ecbdesc = edp;
1563 
1564 	if (cnp->dn_pred != NULL) {
1565 		dt_cg(yypcb, cnp->dn_pred);
1566 		edp->dted_pred.dtpdd_difo = dt_as(yypcb);
1567 	}
1568 
1569 	if (cnp->dn_acts == NULL) {
1570 		dt_stmt_append(dt_stmt_create(dtp, edp,
1571 		    cnp->dn_ctxattr, _dtrace_defattr), cnp);
1572 	}
1573 
1574 	for (dnp = cnp->dn_acts; dnp != NULL; dnp = dnp->dn_list) {
1575 		assert(yypcb->pcb_stmt == NULL);
1576 		sdp = dt_stmt_create(dtp, edp, cnp->dn_ctxattr, cnp->dn_attr);
1577 
1578 		switch (dnp->dn_kind) {
1579 		case DT_NODE_DEXPR:
1580 			if (dnp->dn_expr->dn_kind == DT_NODE_AGG)
1581 				dt_compile_agg(dtp, dnp->dn_expr, sdp);
1582 			else
1583 				dt_compile_exp(dtp, dnp, sdp);
1584 			break;
1585 		case DT_NODE_DFUNC:
1586 			dt_compile_fun(dtp, dnp, sdp);
1587 			break;
1588 		case DT_NODE_AGG:
1589 			dt_compile_agg(dtp, dnp, sdp);
1590 			break;
1591 		default:
1592 			dnerror(dnp, D_UNKNOWN, "internal error -- node kind "
1593 			    "%u is not a valid statement\n", dnp->dn_kind);
1594 		}
1595 
1596 		assert(yypcb->pcb_stmt == sdp);
1597 		dt_stmt_append(sdp, dnp);
1598 	}
1599 
1600 	assert(yypcb->pcb_ecbdesc == edp);
1601 	dt_ecbdesc_release(dtp, edp);
1602 	dt_endcontext(dtp);
1603 	yypcb->pcb_ecbdesc = NULL;
1604 }
1605 
1606 static void
1607 dt_compile_clause(dtrace_hdl_t *dtp, dt_node_t *cnp)
1608 {
1609 	dt_node_t *pnp;
1610 
1611 	for (pnp = cnp->dn_pdescs; pnp != NULL; pnp = pnp->dn_list)
1612 		dt_compile_one_clause(dtp, cnp, pnp);
1613 }
1614 
1615 static void
1616 dt_compile_xlator(dt_node_t *dnp)
1617 {
1618 	dt_xlator_t *dxp = dnp->dn_xlator;
1619 	dt_node_t *mnp;
1620 
1621 	for (mnp = dnp->dn_members; mnp != NULL; mnp = mnp->dn_list) {
1622 		assert(dxp->dx_membdif[mnp->dn_membid] == NULL);
1623 		dt_cg(yypcb, mnp);
1624 		dxp->dx_membdif[mnp->dn_membid] = dt_as(yypcb);
1625 	}
1626 }
1627 
1628 void
1629 dt_setcontext(dtrace_hdl_t *dtp, dtrace_probedesc_t *pdp)
1630 {
1631 	const dtrace_pattr_t *pap;
1632 	dt_probe_t *prp;
1633 	dt_provider_t *pvp;
1634 	dt_ident_t *idp;
1635 	char attrstr[8];
1636 	int err;
1637 
1638 	/*
1639 	 * Both kernel and pid based providers are allowed to have names
1640 	 * ending with what could be interpreted as a number. We assume it's
1641 	 * a pid and that we may need to dynamically create probes for
1642 	 * that process if:
1643 	 *
1644 	 * (1) The provider doesn't exist, or,
1645 	 * (2) The provider exists and has DTRACE_PRIV_PROC privilege.
1646 	 *
1647 	 * On an error, dt_pid_create_probes() will set the error message
1648 	 * and tag -- we just have to longjmp() out of here.
1649 	 */
1650 	if (isdigit(pdp->dtpd_provider[strlen(pdp->dtpd_provider) - 1]) &&
1651 	    ((pvp = dt_provider_lookup(dtp, pdp->dtpd_provider)) == NULL ||
1652 	    pvp->pv_desc.dtvd_priv.dtpp_flags & DTRACE_PRIV_PROC) &&
1653 	    dt_pid_create_probes(pdp, dtp, yypcb) != 0) {
1654 		longjmp(yypcb->pcb_jmpbuf, EDT_COMPILER);
1655 	}
1656 
1657 	/*
1658 	 * Call dt_probe_info() to get the probe arguments and attributes.  If
1659 	 * a representative probe is found, set 'pap' to the probe provider's
1660 	 * attributes.  Otherwise set 'pap' to default Unstable attributes.
1661 	 */
1662 	if ((prp = dt_probe_info(dtp, pdp, &yypcb->pcb_pinfo)) == NULL) {
1663 		pap = &_dtrace_prvdesc;
1664 		err = dtrace_errno(dtp);
1665 		bzero(&yypcb->pcb_pinfo, sizeof (dtrace_probeinfo_t));
1666 		yypcb->pcb_pinfo.dtp_attr = pap->dtpa_provider;
1667 		yypcb->pcb_pinfo.dtp_arga = pap->dtpa_args;
1668 	} else {
1669 		pap = &prp->pr_pvp->pv_desc.dtvd_attr;
1670 		err = 0;
1671 	}
1672 
1673 	if (err == EDT_NOPROBE && !(yypcb->pcb_cflags & DTRACE_C_ZDEFS)) {
1674 		xyerror(D_PDESC_ZERO, "probe description %s:%s:%s:%s does not "
1675 		    "match any probes\n", pdp->dtpd_provider, pdp->dtpd_mod,
1676 		    pdp->dtpd_func, pdp->dtpd_name);
1677 	}
1678 
1679 	if (err != EDT_NOPROBE && err != EDT_UNSTABLE && err != 0)
1680 		xyerror(D_PDESC_INVAL, "%s\n", dtrace_errmsg(dtp, err));
1681 
1682 	dt_dprintf("set context to %s:%s:%s:%s [%u] prp=%p attr=%s argc=%d\n",
1683 	    pdp->dtpd_provider, pdp->dtpd_mod, pdp->dtpd_func, pdp->dtpd_name,
1684 	    pdp->dtpd_id, (void *)prp, dt_attr_str(yypcb->pcb_pinfo.dtp_attr,
1685 	    attrstr, sizeof (attrstr)), yypcb->pcb_pinfo.dtp_argc);
1686 
1687 	/*
1688 	 * Reset the stability attributes of D global variables that vary
1689 	 * based on the attributes of the provider and context itself.
1690 	 */
1691 	if ((idp = dt_idhash_lookup(dtp->dt_globals, "probeprov")) != NULL)
1692 		idp->di_attr = pap->dtpa_provider;
1693 	if ((idp = dt_idhash_lookup(dtp->dt_globals, "probemod")) != NULL)
1694 		idp->di_attr = pap->dtpa_mod;
1695 	if ((idp = dt_idhash_lookup(dtp->dt_globals, "probefunc")) != NULL)
1696 		idp->di_attr = pap->dtpa_func;
1697 	if ((idp = dt_idhash_lookup(dtp->dt_globals, "probename")) != NULL)
1698 		idp->di_attr = pap->dtpa_name;
1699 	if ((idp = dt_idhash_lookup(dtp->dt_globals, "args")) != NULL)
1700 		idp->di_attr = pap->dtpa_args;
1701 
1702 	yypcb->pcb_pdesc = pdp;
1703 	yypcb->pcb_probe = prp;
1704 }
1705 
1706 /*
1707  * Reset context-dependent variables and state at the end of cooking a D probe
1708  * definition clause.  This ensures that external declarations between clauses
1709  * do not reference any stale context-dependent data from the previous clause.
1710  */
1711 void
1712 dt_endcontext(dtrace_hdl_t *dtp)
1713 {
1714 	static const char *const cvars[] = {
1715 		"probeprov", "probemod", "probefunc", "probename", "args", NULL
1716 	};
1717 
1718 	dt_ident_t *idp;
1719 	int i;
1720 
1721 	for (i = 0; cvars[i] != NULL; i++) {
1722 		if ((idp = dt_idhash_lookup(dtp->dt_globals, cvars[i])) != NULL)
1723 			idp->di_attr = _dtrace_defattr;
1724 	}
1725 
1726 	yypcb->pcb_pdesc = NULL;
1727 	yypcb->pcb_probe = NULL;
1728 }
1729 
1730 static int
1731 dt_reduceid(dt_idhash_t *dhp, dt_ident_t *idp, dtrace_hdl_t *dtp)
1732 {
1733 	if (idp->di_vers != 0 && idp->di_vers > dtp->dt_vmax)
1734 		dt_idhash_delete(dhp, idp);
1735 
1736 	return (0);
1737 }
1738 
1739 /*
1740  * When dtrace_setopt() is called for "version", it calls dt_reduce() to remove
1741  * any identifiers or translators that have been previously defined as bound to
1742  * a version greater than the specified version.  Therefore, in our current
1743  * version implementation, establishing a binding is a one-way transformation.
1744  * In addition, no versioning is currently provided for types as our .d library
1745  * files do not define any types and we reserve prefixes DTRACE_ and dtrace_
1746  * for our exclusive use.  If required, type versioning will require more work.
1747  */
1748 int
1749 dt_reduce(dtrace_hdl_t *dtp, dt_version_t v)
1750 {
1751 	char s[DT_VERSION_STRMAX];
1752 	dt_xlator_t *dxp, *nxp;
1753 
1754 	if (v > dtp->dt_vmax)
1755 		return (dt_set_errno(dtp, EDT_VERSREDUCED));
1756 	else if (v == dtp->dt_vmax)
1757 		return (0); /* no reduction necessary */
1758 
1759 	dt_dprintf("reducing api version to %s\n",
1760 	    dt_version_num2str(v, s, sizeof (s)));
1761 
1762 	dtp->dt_vmax = v;
1763 
1764 	for (dxp = dt_list_next(&dtp->dt_xlators); dxp != NULL; dxp = nxp) {
1765 		nxp = dt_list_next(dxp);
1766 		if ((dxp->dx_souid.di_vers != 0 && dxp->dx_souid.di_vers > v) ||
1767 		    (dxp->dx_ptrid.di_vers != 0 && dxp->dx_ptrid.di_vers > v))
1768 			dt_list_delete(&dtp->dt_xlators, dxp);
1769 	}
1770 
1771 	(void) dt_idhash_iter(dtp->dt_macros, (dt_idhash_f *)dt_reduceid, dtp);
1772 	(void) dt_idhash_iter(dtp->dt_aggs, (dt_idhash_f *)dt_reduceid, dtp);
1773 	(void) dt_idhash_iter(dtp->dt_globals, (dt_idhash_f *)dt_reduceid, dtp);
1774 	(void) dt_idhash_iter(dtp->dt_tls, (dt_idhash_f *)dt_reduceid, dtp);
1775 
1776 	return (0);
1777 }
1778 
1779 /*
1780  * Fork and exec the cpp(1) preprocessor to run over the specified input file,
1781  * and return a FILE handle for the cpp output.  We use the /dev/fd filesystem
1782  * here to simplify the code by leveraging file descriptor inheritance.
1783  */
1784 static FILE *
1785 dt_preproc(dtrace_hdl_t *dtp, FILE *ifp)
1786 {
1787 	int argc = dtp->dt_cpp_argc;
1788 	char **argv = malloc(sizeof (char *) * (argc + 5));
1789 	FILE *ofp = tmpfile();
1790 
1791 	char ipath[20], opath[20]; /* big enough for /dev/fd/ + INT_MAX + \0 */
1792 	char verdef[32]; /* big enough for -D__SUNW_D_VERSION=0x%08x + \0 */
1793 
1794 	struct sigaction act, oact;
1795 	sigset_t mask, omask;
1796 
1797 	int wstat, estat;
1798 	pid_t pid;
1799 	off64_t off;
1800 	int c;
1801 
1802 	if (argv == NULL || ofp == NULL) {
1803 		(void) dt_set_errno(dtp, errno);
1804 		goto err;
1805 	}
1806 
1807 	/*
1808 	 * If the input is a seekable file, see if it is an interpreter file.
1809 	 * If we see #!, seek past the first line because cpp will choke on it.
1810 	 * We start cpp just prior to the \n at the end of this line so that
1811 	 * it still sees the newline, ensuring that #line values are correct.
1812 	 */
1813 	if (isatty(fileno(ifp)) == 0 && (off = ftello64(ifp)) != -1) {
1814 		if ((c = fgetc(ifp)) == '#' && (c = fgetc(ifp)) == '!') {
1815 			for (off += 2; c != '\n'; off++) {
1816 				if ((c = fgetc(ifp)) == EOF)
1817 					break;
1818 			}
1819 			if (c == '\n')
1820 				off--; /* start cpp just prior to \n */
1821 		}
1822 		(void) fflush(ifp);
1823 		(void) fseeko64(ifp, off, SEEK_SET);
1824 	}
1825 
1826 	(void) snprintf(ipath, sizeof (ipath), "/dev/fd/%d", fileno(ifp));
1827 	(void) snprintf(opath, sizeof (opath), "/dev/fd/%d", fileno(ofp));
1828 
1829 	bcopy(dtp->dt_cpp_argv, argv, sizeof (char *) * argc);
1830 
1831 	(void) snprintf(verdef, sizeof (verdef),
1832 	    "-D__SUNW_D_VERSION=0x%08x", dtp->dt_vmax);
1833 	argv[argc++] = verdef;
1834 
1835 	switch (dtp->dt_stdcmode) {
1836 	case DT_STDC_XA:
1837 	case DT_STDC_XT:
1838 		argv[argc++] = "-D__STDC__=0";
1839 		break;
1840 	case DT_STDC_XC:
1841 		argv[argc++] = "-D__STDC__=1";
1842 		break;
1843 	}
1844 
1845 	argv[argc++] = ipath;
1846 	argv[argc++] = opath;
1847 	argv[argc] = NULL;
1848 
1849 	/*
1850 	 * libdtrace must be able to be embedded in other programs that may
1851 	 * include application-specific signal handlers.  Therefore, if we
1852 	 * need to fork to run cpp(1), we must avoid generating a SIGCHLD
1853 	 * that could confuse the containing application.  To do this,
1854 	 * we block SIGCHLD and reset its disposition to SIG_DFL.
1855 	 * We restore our signal state once we are done.
1856 	 */
1857 	(void) sigemptyset(&mask);
1858 	(void) sigaddset(&mask, SIGCHLD);
1859 	(void) sigprocmask(SIG_BLOCK, &mask, &omask);
1860 
1861 	bzero(&act, sizeof (act));
1862 	act.sa_handler = SIG_DFL;
1863 	(void) sigaction(SIGCHLD, &act, &oact);
1864 
1865 	if ((pid = fork1()) == -1) {
1866 		(void) sigaction(SIGCHLD, &oact, NULL);
1867 		(void) sigprocmask(SIG_SETMASK, &omask, NULL);
1868 		(void) dt_set_errno(dtp, EDT_CPPFORK);
1869 		goto err;
1870 	}
1871 
1872 	if (pid == 0) {
1873 		(void) execvp(dtp->dt_cpp_path, argv);
1874 		_exit(errno == ENOENT ? 127 : 126);
1875 	}
1876 
1877 	do {
1878 		dt_dprintf("waiting for %s (PID %d)\n", dtp->dt_cpp_path,
1879 		    (int)pid);
1880 	} while (waitpid(pid, &wstat, 0) == -1 && errno == EINTR);
1881 
1882 	(void) sigaction(SIGCHLD, &oact, NULL);
1883 	(void) sigprocmask(SIG_SETMASK, &omask, NULL);
1884 
1885 	dt_dprintf("%s returned exit status 0x%x\n", dtp->dt_cpp_path, wstat);
1886 	estat = WIFEXITED(wstat) ? WEXITSTATUS(wstat) : -1;
1887 
1888 	if (estat != 0) {
1889 		switch (estat) {
1890 		case 126:
1891 			(void) dt_set_errno(dtp, EDT_CPPEXEC);
1892 			break;
1893 		case 127:
1894 			(void) dt_set_errno(dtp, EDT_CPPENT);
1895 			break;
1896 		default:
1897 			(void) dt_set_errno(dtp, EDT_CPPERR);
1898 		}
1899 		goto err;
1900 	}
1901 
1902 	free(argv);
1903 	(void) fflush(ofp);
1904 	(void) fseek(ofp, 0, SEEK_SET);
1905 	return (ofp);
1906 
1907 err:
1908 	free(argv);
1909 	(void) fclose(ofp);
1910 	return (NULL);
1911 }
1912 
1913 static void
1914 dt_lib_depend_error(dtrace_hdl_t *dtp, const char *format, ...)
1915 {
1916 	va_list ap;
1917 
1918 	va_start(ap, format);
1919 	dt_set_errmsg(dtp, NULL, NULL, NULL, 0, format, ap);
1920 	va_end(ap);
1921 }
1922 
1923 int
1924 dt_lib_depend_add(dtrace_hdl_t *dtp, dt_list_t *dlp, const char *arg)
1925 {
1926 	dt_lib_depend_t *dld;
1927 	const char *end;
1928 
1929 	assert(arg != NULL);
1930 
1931 	if ((end = strrchr(arg, '/')) == NULL)
1932 		return (dt_set_errno(dtp, EINVAL));
1933 
1934 	if ((dld = dt_zalloc(dtp, sizeof (dt_lib_depend_t))) == NULL)
1935 		return (-1);
1936 
1937 	if ((dld->dtld_libpath = dt_alloc(dtp, MAXPATHLEN)) == NULL) {
1938 		dt_free(dtp, dld);
1939 		return (-1);
1940 	}
1941 
1942 	(void) strlcpy(dld->dtld_libpath, arg, end - arg + 2);
1943 	if ((dld->dtld_library = strdup(arg)) == NULL) {
1944 		dt_free(dtp, dld->dtld_libpath);
1945 		dt_free(dtp, dld);
1946 		return (dt_set_errno(dtp, EDT_NOMEM));
1947 	}
1948 
1949 	dt_list_append(dlp, dld);
1950 	return (0);
1951 }
1952 
1953 dt_lib_depend_t *
1954 dt_lib_depend_lookup(dt_list_t *dld, const char *arg)
1955 {
1956 	dt_lib_depend_t *dldn;
1957 
1958 	for (dldn = dt_list_next(dld); dldn != NULL;
1959 	    dldn = dt_list_next(dldn)) {
1960 		if (strcmp(dldn->dtld_library, arg) == 0)
1961 			return (dldn);
1962 	}
1963 
1964 	return (NULL);
1965 }
1966 
1967 /*
1968  * Go through all the library files, and, if any library dependencies exist for
1969  * that file, add it to that node's list of dependents. The result of this
1970  * will be a graph which can then be topologically sorted to produce a
1971  * compilation order.
1972  */
1973 static int
1974 dt_lib_build_graph(dtrace_hdl_t *dtp)
1975 {
1976 	dt_lib_depend_t *dld, *dpld;
1977 
1978 	for (dld = dt_list_next(&dtp->dt_lib_dep); dld != NULL;
1979 	    dld = dt_list_next(dld)) {
1980 		char *library = dld->dtld_library;
1981 
1982 		for (dpld = dt_list_next(&dld->dtld_dependencies); dpld != NULL;
1983 		    dpld = dt_list_next(dpld)) {
1984 			dt_lib_depend_t *dlda;
1985 
1986 			if ((dlda = dt_lib_depend_lookup(&dtp->dt_lib_dep,
1987 			    dpld->dtld_library)) == NULL) {
1988 				dt_lib_depend_error(dtp,
1989 				    "Invalid library dependency in %s: %s\n",
1990 				    dld->dtld_library, dpld->dtld_library);
1991 
1992 				return (dt_set_errno(dtp, EDT_COMPILER));
1993 			}
1994 
1995 			if ((dt_lib_depend_add(dtp, &dlda->dtld_dependents,
1996 			    library)) != 0) {
1997 				return (-1); /* preserve dt_errno */
1998 			}
1999 		}
2000 	}
2001 	return (0);
2002 }
2003 
2004 static int
2005 dt_topo_sort(dtrace_hdl_t *dtp, dt_lib_depend_t *dld, int *count)
2006 {
2007 	dt_lib_depend_t *dpld, *dlda, *new;
2008 
2009 	dld->dtld_start = ++(*count);
2010 
2011 	for (dpld = dt_list_next(&dld->dtld_dependents); dpld != NULL;
2012 	    dpld = dt_list_next(dpld)) {
2013 		dlda = dt_lib_depend_lookup(&dtp->dt_lib_dep,
2014 		    dpld->dtld_library);
2015 		assert(dlda != NULL);
2016 
2017 		if (dlda->dtld_start == 0 &&
2018 		    dt_topo_sort(dtp, dlda, count) == -1)
2019 			return (-1);
2020 	}
2021 
2022 	if ((new = dt_zalloc(dtp, sizeof (dt_lib_depend_t))) == NULL)
2023 		return (-1);
2024 
2025 	if ((new->dtld_library = strdup(dld->dtld_library)) == NULL) {
2026 		dt_free(dtp, new);
2027 		return (dt_set_errno(dtp, EDT_NOMEM));
2028 	}
2029 
2030 	new->dtld_start = dld->dtld_start;
2031 	new->dtld_finish = dld->dtld_finish = ++(*count);
2032 	dt_list_prepend(&dtp->dt_lib_dep_sorted, new);
2033 
2034 	dt_dprintf("library %s sorted (%d/%d)\n", new->dtld_library,
2035 	    new->dtld_start, new->dtld_finish);
2036 
2037 	return (0);
2038 }
2039 
2040 static int
2041 dt_lib_depend_sort(dtrace_hdl_t *dtp)
2042 {
2043 	dt_lib_depend_t *dld, *dpld, *dlda;
2044 	int count = 0;
2045 
2046 	if (dt_lib_build_graph(dtp) == -1)
2047 		return (-1); /* preserve dt_errno */
2048 
2049 	/*
2050 	 * Perform a topological sort of the graph that hangs off
2051 	 * dtp->dt_lib_dep. The result of this process will be a
2052 	 * dependency ordered list located at dtp->dt_lib_dep_sorted.
2053 	 */
2054 	for (dld = dt_list_next(&dtp->dt_lib_dep); dld != NULL;
2055 	    dld = dt_list_next(dld)) {
2056 		if (dld->dtld_start == 0 &&
2057 		    dt_topo_sort(dtp, dld, &count) == -1)
2058 			return (-1); /* preserve dt_errno */;
2059 	}
2060 
2061 	/*
2062 	 * Check the graph for cycles. If an ancestor's finishing time is
2063 	 * less than any of its dependent's finishing times then a back edge
2064 	 * exists in the graph and this is a cycle.
2065 	 */
2066 	for (dld = dt_list_next(&dtp->dt_lib_dep); dld != NULL;
2067 	    dld = dt_list_next(dld)) {
2068 		for (dpld = dt_list_next(&dld->dtld_dependents); dpld != NULL;
2069 		    dpld = dt_list_next(dpld)) {
2070 			dlda = dt_lib_depend_lookup(&dtp->dt_lib_dep_sorted,
2071 			    dpld->dtld_library);
2072 			assert(dlda != NULL);
2073 
2074 			if (dlda->dtld_finish > dld->dtld_finish) {
2075 				dt_lib_depend_error(dtp,
2076 				    "Cyclic dependency detected: %s => %s\n",
2077 				    dld->dtld_library, dpld->dtld_library);
2078 
2079 				return (dt_set_errno(dtp, EDT_COMPILER));
2080 			}
2081 		}
2082 	}
2083 
2084 	return (0);
2085 }
2086 
2087 static void
2088 dt_lib_depend_free(dtrace_hdl_t *dtp)
2089 {
2090 	dt_lib_depend_t *dld, *dlda;
2091 
2092 	while ((dld = dt_list_next(&dtp->dt_lib_dep)) != NULL) {
2093 		while ((dlda = dt_list_next(&dld->dtld_dependencies)) != NULL) {
2094 			dt_list_delete(&dld->dtld_dependencies, dlda);
2095 			dt_free(dtp, dlda->dtld_library);
2096 			dt_free(dtp, dlda->dtld_libpath);
2097 			dt_free(dtp, dlda);
2098 		}
2099 		while ((dlda = dt_list_next(&dld->dtld_dependents)) != NULL) {
2100 			dt_list_delete(&dld->dtld_dependents, dlda);
2101 			dt_free(dtp, dlda->dtld_library);
2102 			dt_free(dtp, dlda->dtld_libpath);
2103 			dt_free(dtp, dlda);
2104 		}
2105 		dt_list_delete(&dtp->dt_lib_dep, dld);
2106 		dt_free(dtp, dld->dtld_library);
2107 		dt_free(dtp, dld->dtld_libpath);
2108 		dt_free(dtp, dld);
2109 	}
2110 
2111 	while ((dld = dt_list_next(&dtp->dt_lib_dep_sorted)) != NULL) {
2112 		dt_list_delete(&dtp->dt_lib_dep_sorted, dld);
2113 		dt_free(dtp, dld->dtld_library);
2114 		dt_free(dtp, dld);
2115 	}
2116 }
2117 
2118 /*
2119  * Open all the .d library files found in the specified directory and
2120  * compile each one of them.  We silently ignore any missing directories and
2121  * other files found therein.  We only fail (and thereby fail dt_load_libs()) if
2122  * we fail to compile a library and the error is something other than #pragma D
2123  * depends_on.  Dependency errors are silently ignored to permit a library
2124  * directory to contain libraries which may not be accessible depending on our
2125  * privileges.
2126  */
2127 static int
2128 dt_load_libs_dir(dtrace_hdl_t *dtp, const char *path)
2129 {
2130 	struct dirent *dp;
2131 	const char *p, *end;
2132 	DIR *dirp;
2133 
2134 	char fname[PATH_MAX];
2135 	FILE *fp;
2136 	void *rv;
2137 	dt_lib_depend_t *dld;
2138 
2139 	if ((dirp = opendir(path)) == NULL) {
2140 		dt_dprintf("skipping lib dir %s: %s\n", path, strerror(errno));
2141 		return (0);
2142 	}
2143 
2144 	/* First, parse each file for library dependencies. */
2145 	while ((dp = readdir(dirp)) != NULL) {
2146 		if ((p = strrchr(dp->d_name, '.')) == NULL || strcmp(p, ".d"))
2147 			continue; /* skip any filename not ending in .d */
2148 
2149 		(void) snprintf(fname, sizeof (fname),
2150 		    "%s/%s", path, dp->d_name);
2151 
2152 		if ((fp = fopen(fname, "r")) == NULL) {
2153 			dt_dprintf("skipping library %s: %s\n",
2154 			    fname, strerror(errno));
2155 			continue;
2156 		}
2157 
2158 		/*
2159 		 * Skip files whose name match an already processed library
2160 		 */
2161 		for (dld = dt_list_next(&dtp->dt_lib_dep); dld != NULL;
2162 		    dld = dt_list_next(dld)) {
2163 			end = strrchr(dld->dtld_library, '/');
2164 			/* dt_lib_depend_add ensures this */
2165 			assert(end != NULL);
2166 			if (strcmp(end + 1, dp->d_name) == 0)
2167 				break;
2168 		}
2169 
2170 		if (dld != NULL) {
2171 			dt_dprintf("skipping library %s, already processed "
2172 			    "library with the same name: %s", dp->d_name,
2173 			    dld->dtld_library);
2174 			continue;
2175 		}
2176 
2177 		dtp->dt_filetag = fname;
2178 		if (dt_lib_depend_add(dtp, &dtp->dt_lib_dep, fname) != 0)
2179 			return (-1); /* preserve dt_errno */
2180 
2181 		rv = dt_compile(dtp, DT_CTX_DPROG,
2182 		    DTRACE_PROBESPEC_NAME, NULL,
2183 		    DTRACE_C_EMPTY | DTRACE_C_CTL, 0, NULL, fp, NULL);
2184 
2185 		if (rv != NULL && dtp->dt_errno &&
2186 		    (dtp->dt_errno != EDT_COMPILER ||
2187 		    dtp->dt_errtag != dt_errtag(D_PRAGMA_DEPEND)))
2188 			return (-1); /* preserve dt_errno */
2189 
2190 		if (dtp->dt_errno)
2191 			dt_dprintf("error parsing library %s: %s\n",
2192 			    fname, dtrace_errmsg(dtp, dtrace_errno(dtp)));
2193 
2194 		(void) fclose(fp);
2195 		dtp->dt_filetag = NULL;
2196 	}
2197 
2198 	(void) closedir(dirp);
2199 
2200 	return (0);
2201 }
2202 
2203 /*
2204  * Perform a topological sorting of all the libraries found across the entire
2205  * dt_lib_path.  Once sorted, compile each one in topological order to cache its
2206  * inlines and translators, etc.  We silently ignore any missing directories and
2207  * other files found therein. We only fail (and thereby fail dt_load_libs()) if
2208  * we fail to compile a library and the error is something other than #pragma D
2209  * depends_on.  Dependency errors are silently ignored to permit a library
2210  * directory to contain libraries which may not be accessible depending on our
2211  * privileges.
2212  */
2213 static int
2214 dt_load_libs_sort(dtrace_hdl_t *dtp)
2215 {
2216 	dtrace_prog_t *pgp;
2217 	FILE *fp;
2218 	dt_lib_depend_t *dld;
2219 
2220 	/*
2221 	 * Finish building the graph containing the library dependencies
2222 	 * and perform a topological sort to generate an ordered list
2223 	 * for compilation.
2224 	 */
2225 	if (dt_lib_depend_sort(dtp) == -1)
2226 		goto err;
2227 
2228 	for (dld = dt_list_next(&dtp->dt_lib_dep_sorted); dld != NULL;
2229 	    dld = dt_list_next(dld)) {
2230 
2231 		if ((fp = fopen(dld->dtld_library, "r")) == NULL) {
2232 			dt_dprintf("skipping library %s: %s\n",
2233 			    dld->dtld_library, strerror(errno));
2234 			continue;
2235 		}
2236 
2237 		dtp->dt_filetag = dld->dtld_library;
2238 		pgp = dtrace_program_fcompile(dtp, fp, DTRACE_C_EMPTY, 0, NULL);
2239 		(void) fclose(fp);
2240 		dtp->dt_filetag = NULL;
2241 
2242 		if (pgp == NULL && (dtp->dt_errno != EDT_COMPILER ||
2243 		    dtp->dt_errtag != dt_errtag(D_PRAGMA_DEPEND)))
2244 			goto err;
2245 
2246 		if (pgp == NULL) {
2247 			dt_dprintf("skipping library %s: %s\n",
2248 			    dld->dtld_library,
2249 			    dtrace_errmsg(dtp, dtrace_errno(dtp)));
2250 		} else {
2251 			dld->dtld_loaded = B_TRUE;
2252 			dt_program_destroy(dtp, pgp);
2253 		}
2254 	}
2255 
2256 	dt_lib_depend_free(dtp);
2257 	return (0);
2258 
2259 err:
2260 	dt_lib_depend_free(dtp);
2261 	return (-1); /* preserve dt_errno */
2262 }
2263 
2264 /*
2265  * Load the contents of any appropriate DTrace .d library files.  These files
2266  * contain inlines and translators that will be cached by the compiler.  We
2267  * defer this activity until the first compile to permit libdtrace clients to
2268  * add their own library directories and so that we can properly report errors.
2269  */
2270 static int
2271 dt_load_libs(dtrace_hdl_t *dtp)
2272 {
2273 	dt_dirpath_t *dirp;
2274 
2275 	if (dtp->dt_cflags & DTRACE_C_NOLIBS)
2276 		return (0); /* libraries already processed */
2277 
2278 	dtp->dt_cflags |= DTRACE_C_NOLIBS;
2279 
2280 	/*
2281 	 * /usr/lib/dtrace is always at the head of the list. The rest of the
2282 	 * list is specified in the precedence order the user requested. Process
2283 	 * everything other than the head first. DTRACE_C_NOLIBS has already
2284 	 * been spcified so dt_vopen will ensure that there is always one entry
2285 	 * in dt_lib_path.
2286 	 */
2287 	for (dirp = dt_list_next(dt_list_next(&dtp->dt_lib_path));
2288 	    dirp != NULL; dirp = dt_list_next(dirp)) {
2289 		if (dt_load_libs_dir(dtp, dirp->dir_path) != 0) {
2290 			dtp->dt_cflags &= ~DTRACE_C_NOLIBS;
2291 			return (-1); /* errno is set for us */
2292 		}
2293 	}
2294 
2295 	/* Handle /usr/lib/dtrace */
2296 	dirp = dt_list_next(&dtp->dt_lib_path);
2297 	if (dt_load_libs_dir(dtp, dirp->dir_path) != 0) {
2298 		dtp->dt_cflags &= ~DTRACE_C_NOLIBS;
2299 		return (-1); /* errno is set for us */
2300 	}
2301 
2302 	if (dt_load_libs_sort(dtp) < 0)
2303 		return (-1); /* errno is set for us */
2304 
2305 	return (0);
2306 }
2307 
2308 static void *
2309 dt_compile(dtrace_hdl_t *dtp, int context, dtrace_probespec_t pspec, void *arg,
2310     uint_t cflags, int argc, char *const argv[], FILE *fp, const char *s)
2311 {
2312 	dt_node_t *dnp;
2313 	dt_decl_t *ddp;
2314 	dt_pcb_t pcb;
2315 	void *rv;
2316 	int err;
2317 
2318 	if ((fp == NULL && s == NULL) || (cflags & ~DTRACE_C_MASK) != 0) {
2319 		(void) dt_set_errno(dtp, EINVAL);
2320 		return (NULL);
2321 	}
2322 
2323 	if (dt_list_next(&dtp->dt_lib_path) != NULL && dt_load_libs(dtp) != 0)
2324 		return (NULL); /* errno is set for us */
2325 
2326 	if (dtp->dt_globals->dh_nelems != 0)
2327 		(void) dt_idhash_iter(dtp->dt_globals, dt_idreset, NULL);
2328 
2329 	if (dtp->dt_tls->dh_nelems != 0)
2330 		(void) dt_idhash_iter(dtp->dt_tls, dt_idreset, NULL);
2331 
2332 	if (fp && (cflags & DTRACE_C_CPP) && (fp = dt_preproc(dtp, fp)) == NULL)
2333 		return (NULL); /* errno is set for us */
2334 
2335 	dt_pcb_push(dtp, &pcb);
2336 
2337 	pcb.pcb_fileptr = fp;
2338 	pcb.pcb_string = s;
2339 	pcb.pcb_strptr = s;
2340 	pcb.pcb_strlen = s ? strlen(s) : 0;
2341 	pcb.pcb_sargc = argc;
2342 	pcb.pcb_sargv = argv;
2343 	pcb.pcb_sflagv = argc ? calloc(argc, sizeof (ushort_t)) : NULL;
2344 	pcb.pcb_pspec = pspec;
2345 	pcb.pcb_cflags = dtp->dt_cflags | cflags;
2346 	pcb.pcb_amin = dtp->dt_amin;
2347 	pcb.pcb_yystate = -1;
2348 	pcb.pcb_context = context;
2349 	pcb.pcb_token = context;
2350 
2351 	if (context != DT_CTX_DPROG)
2352 		yybegin(YYS_EXPR);
2353 	else if (cflags & DTRACE_C_CTL)
2354 		yybegin(YYS_CONTROL);
2355 	else
2356 		yybegin(YYS_CLAUSE);
2357 
2358 	if ((err = setjmp(yypcb->pcb_jmpbuf)) != 0)
2359 		goto out;
2360 
2361 	if (yypcb->pcb_sargc != 0 && yypcb->pcb_sflagv == NULL)
2362 		longjmp(yypcb->pcb_jmpbuf, EDT_NOMEM);
2363 
2364 	yypcb->pcb_idents = dt_idhash_create("ambiguous", NULL, 0, 0);
2365 	yypcb->pcb_locals = dt_idhash_create("clause local", NULL,
2366 	    DIF_VAR_OTHER_UBASE, DIF_VAR_OTHER_MAX);
2367 
2368 	if (yypcb->pcb_idents == NULL || yypcb->pcb_locals == NULL)
2369 		longjmp(yypcb->pcb_jmpbuf, EDT_NOMEM);
2370 
2371 	/*
2372 	 * Invoke the parser to evaluate the D source code.  If any errors
2373 	 * occur during parsing, an error function will be called and we
2374 	 * will longjmp back to pcb_jmpbuf to abort.  If parsing succeeds,
2375 	 * we optionally display the parse tree if debugging is enabled.
2376 	 */
2377 	if (yyparse() != 0 || yypcb->pcb_root == NULL)
2378 		xyerror(D_EMPTY, "empty D program translation unit\n");
2379 
2380 	yybegin(YYS_DONE);
2381 
2382 	if (cflags & DTRACE_C_CTL)
2383 		goto out;
2384 
2385 	if (context != DT_CTX_DTYPE && DT_TREEDUMP_PASS(dtp, 1))
2386 		dt_node_printr(yypcb->pcb_root, stderr, 0);
2387 
2388 	if (yypcb->pcb_pragmas != NULL)
2389 		(void) dt_idhash_iter(yypcb->pcb_pragmas, dt_idpragma, NULL);
2390 
2391 	if (argc > 1 && !(yypcb->pcb_cflags & DTRACE_C_ARGREF) &&
2392 	    !(yypcb->pcb_sflagv[argc - 1] & DT_IDFLG_REF)) {
2393 		xyerror(D_MACRO_UNUSED, "extraneous argument '%s' ($%d is "
2394 		    "not referenced)\n", yypcb->pcb_sargv[argc - 1], argc - 1);
2395 	}
2396 
2397 	/*
2398 	 * If we have successfully created a parse tree for a D program, loop
2399 	 * over the clauses and actions and instantiate the corresponding
2400 	 * libdtrace program.  If we are parsing a D expression, then we
2401 	 * simply run the code generator and assembler on the resulting tree.
2402 	 */
2403 	switch (context) {
2404 	case DT_CTX_DPROG:
2405 		assert(yypcb->pcb_root->dn_kind == DT_NODE_PROG);
2406 
2407 		if ((dnp = yypcb->pcb_root->dn_list) == NULL &&
2408 		    !(yypcb->pcb_cflags & DTRACE_C_EMPTY))
2409 			xyerror(D_EMPTY, "empty D program translation unit\n");
2410 
2411 		if ((yypcb->pcb_prog = dt_program_create(dtp)) == NULL)
2412 			longjmp(yypcb->pcb_jmpbuf, dtrace_errno(dtp));
2413 
2414 		for (; dnp != NULL; dnp = dnp->dn_list) {
2415 			switch (dnp->dn_kind) {
2416 			case DT_NODE_CLAUSE:
2417 				dt_compile_clause(dtp, dnp);
2418 				break;
2419 			case DT_NODE_XLATOR:
2420 				if (dtp->dt_xlatemode == DT_XL_DYNAMIC)
2421 					dt_compile_xlator(dnp);
2422 				break;
2423 			case DT_NODE_PROVIDER:
2424 				(void) dt_node_cook(dnp, DT_IDFLG_REF);
2425 				break;
2426 			}
2427 		}
2428 
2429 		yypcb->pcb_prog->dp_xrefs = yypcb->pcb_asxrefs;
2430 		yypcb->pcb_prog->dp_xrefslen = yypcb->pcb_asxreflen;
2431 		yypcb->pcb_asxrefs = NULL;
2432 		yypcb->pcb_asxreflen = 0;
2433 
2434 		rv = yypcb->pcb_prog;
2435 		break;
2436 
2437 	case DT_CTX_DEXPR:
2438 		(void) dt_node_cook(yypcb->pcb_root, DT_IDFLG_REF);
2439 		dt_cg(yypcb, yypcb->pcb_root);
2440 		rv = dt_as(yypcb);
2441 		break;
2442 
2443 	case DT_CTX_DTYPE:
2444 		ddp = (dt_decl_t *)yypcb->pcb_root; /* root is really a decl */
2445 		err = dt_decl_type(ddp, arg);
2446 		dt_decl_free(ddp);
2447 
2448 		if (err != 0)
2449 			longjmp(yypcb->pcb_jmpbuf, EDT_COMPILER);
2450 
2451 		rv = NULL;
2452 		break;
2453 	}
2454 
2455 out:
2456 	if (context != DT_CTX_DTYPE && yypcb->pcb_root != NULL &&
2457 	    DT_TREEDUMP_PASS(dtp, 3))
2458 		dt_node_printr(yypcb->pcb_root, stderr, 0);
2459 
2460 	if (dtp->dt_cdefs_fd != -1 && (ftruncate64(dtp->dt_cdefs_fd, 0) == -1 ||
2461 	    lseek64(dtp->dt_cdefs_fd, 0, SEEK_SET) == -1 ||
2462 	    ctf_write(dtp->dt_cdefs->dm_ctfp, dtp->dt_cdefs_fd) == CTF_ERR))
2463 		dt_dprintf("failed to update CTF cache: %s\n", strerror(errno));
2464 
2465 	if (dtp->dt_ddefs_fd != -1 && (ftruncate64(dtp->dt_ddefs_fd, 0) == -1 ||
2466 	    lseek64(dtp->dt_ddefs_fd, 0, SEEK_SET) == -1 ||
2467 	    ctf_write(dtp->dt_ddefs->dm_ctfp, dtp->dt_ddefs_fd) == CTF_ERR))
2468 		dt_dprintf("failed to update CTF cache: %s\n", strerror(errno));
2469 
2470 	if (yypcb->pcb_fileptr && (cflags & DTRACE_C_CPP))
2471 		(void) fclose(yypcb->pcb_fileptr); /* close dt_preproc() file */
2472 
2473 	dt_pcb_pop(dtp, err);
2474 	(void) dt_set_errno(dtp, err);
2475 	return (err ? NULL : rv);
2476 }
2477 
2478 dtrace_prog_t *
2479 dtrace_program_strcompile(dtrace_hdl_t *dtp, const char *s,
2480     dtrace_probespec_t spec, uint_t cflags, int argc, char *const argv[])
2481 {
2482 	return (dt_compile(dtp, DT_CTX_DPROG,
2483 	    spec, NULL, cflags, argc, argv, NULL, s));
2484 }
2485 
2486 dtrace_prog_t *
2487 dtrace_program_fcompile(dtrace_hdl_t *dtp, FILE *fp,
2488     uint_t cflags, int argc, char *const argv[])
2489 {
2490 	return (dt_compile(dtp, DT_CTX_DPROG,
2491 	    DTRACE_PROBESPEC_NAME, NULL, cflags, argc, argv, fp, NULL));
2492 }
2493 
2494 int
2495 dtrace_type_strcompile(dtrace_hdl_t *dtp, const char *s, dtrace_typeinfo_t *dtt)
2496 {
2497 	(void) dt_compile(dtp, DT_CTX_DTYPE,
2498 	    DTRACE_PROBESPEC_NONE, dtt, 0, 0, NULL, NULL, s);
2499 	return (dtp->dt_errno ? -1 : 0);
2500 }
2501 
2502 int
2503 dtrace_type_fcompile(dtrace_hdl_t *dtp, FILE *fp, dtrace_typeinfo_t *dtt)
2504 {
2505 	(void) dt_compile(dtp, DT_CTX_DTYPE,
2506 	    DTRACE_PROBESPEC_NONE, dtt, 0, 0, NULL, fp, NULL);
2507 	return (dtp->dt_errno ? -1 : 0);
2508 }
2509