]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libdtrace/common/dt_cc.c
Move the OpenSolaris vendor sources from vendor-cddl into vendor/opensolaris
[FreeBSD/FreeBSD.git] / lib / libdtrace / common / dt_cc.c
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 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26
27 #pragma ident   "%Z%%M% %I%     %E% SMI"
28
29 /*
30  * DTrace D Language Compiler
31  *
32  * The code in this source file implements the main engine for the D language
33  * compiler.  The driver routine for the compiler is dt_compile(), below.  The
34  * compiler operates on either stdio FILEs or in-memory strings as its input
35  * and can produce either dtrace_prog_t structures from a D program or a single
36  * dtrace_difo_t structure from a D expression.  Multiple entry points are
37  * provided as wrappers around dt_compile() for the various input/output pairs.
38  * The compiler itself is implemented across the following source files:
39  *
40  * dt_lex.l - lex scanner
41  * dt_grammar.y - yacc grammar
42  * dt_parser.c - parse tree creation and semantic checking
43  * dt_decl.c - declaration stack processing
44  * dt_xlator.c - D translator lookup and creation
45  * dt_ident.c - identifier and symbol table routines
46  * dt_pragma.c - #pragma processing and D pragmas
47  * dt_printf.c - D printf() and printa() argument checking and processing
48  * dt_cc.c - compiler driver and dtrace_prog_t construction
49  * dt_cg.c - DIF code generator
50  * dt_as.c - DIF assembler
51  * dt_dof.c - dtrace_prog_t -> DOF conversion
52  *
53  * Several other source files provide collections of utility routines used by
54  * these major files.  The compiler itself is implemented in multiple passes:
55  *
56  * (1) The input program is scanned and parsed by dt_lex.l and dt_grammar.y
57  *     and parse tree nodes are constructed using the routines in dt_parser.c.
58  *     This node construction pass is described further in dt_parser.c.
59  *
60  * (2) The parse tree is "cooked" by assigning each clause a context (see the
61  *     routine dt_setcontext(), below) based on its probe description and then
62  *     recursively descending the tree performing semantic checking.  The cook
63  *     routines are also implemented in dt_parser.c and described there.
64  *
65  * (3) For actions that are DIF expression statements, the DIF code generator
66  *     and assembler are invoked to create a finished DIFO for the statement.
67  *
68  * (4) The dtrace_prog_t data structures for the program clauses and actions
69  *     are built, containing pointers to any DIFOs created in step (3).
70  *
71  * (5) The caller invokes a routine in dt_dof.c to convert the finished program
72  *     into DOF format for use in anonymous tracing or enabling in the kernel.
73  *
74  * In the implementation, steps 2-4 are intertwined in that they are performed
75  * in order for each clause as part of a loop that executes over the clauses.
76  *
77  * The D compiler currently implements nearly no optimization.  The compiler
78  * implements integer constant folding as part of pass (1), and a set of very
79  * simple peephole optimizations as part of pass (3).  As with any C compiler,
80  * a large number of optimizations are possible on both the intermediate data
81  * structures and the generated DIF code.  These possibilities should be
82  * investigated in the context of whether they will have any substantive effect
83  * on the overall DTrace probe effect before they are undertaken.
84  */
85
86 #include <sys/types.h>
87 #include <sys/wait.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
667         if (dt_node_is_void(dnp->dn_args)) {
668                 dnerror(dnp->dn_args, D_TRACE_VOID,
669                     "trace( ) may not be applied to a void expression\n");
670         }
671
672         if (dt_node_is_dynamic(dnp->dn_args)) {
673                 dnerror(dnp->dn_args, D_TRACE_DYN,
674                     "trace( ) may not be applied to a dynamic expression\n");
675         }
676
677         dt_cg(yypcb, dnp->dn_args);
678         ap->dtad_difo = dt_as(yypcb);
679         ap->dtad_kind = DTRACEACT_DIFEXPR;
680 }
681
682 static void
683 dt_action_tracemem(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
684 {
685         dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
686
687         dt_node_t *addr = dnp->dn_args;
688         dt_node_t *size = dnp->dn_args->dn_list;
689
690         char n[DT_TYPE_NAMELEN];
691
692         if (dt_node_is_integer(addr) == 0 && dt_node_is_pointer(addr) == 0) {
693                 dnerror(addr, D_TRACEMEM_ADDR,
694                     "tracemem( ) argument #1 is incompatible with "
695                     "prototype:\n\tprototype: pointer or integer\n"
696                     "\t argument: %s\n",
697                     dt_node_type_name(addr, n, sizeof (n)));
698         }
699
700         if (dt_node_is_posconst(size) == 0) {
701                 dnerror(size, D_TRACEMEM_SIZE, "tracemem( ) argument #2 must "
702                     "be a non-zero positive integral constant expression\n");
703         }
704
705         dt_cg(yypcb, addr);
706         ap->dtad_difo = dt_as(yypcb);
707         ap->dtad_kind = DTRACEACT_DIFEXPR;
708
709         ap->dtad_difo->dtdo_rtype.dtdt_flags |= DIF_TF_BYREF;
710         ap->dtad_difo->dtdo_rtype.dtdt_size = size->dn_value;
711 }
712
713 static void
714 dt_action_stack_args(dtrace_hdl_t *dtp, dtrace_actdesc_t *ap, dt_node_t *arg0)
715 {
716         ap->dtad_kind = DTRACEACT_STACK;
717
718         if (dtp->dt_options[DTRACEOPT_STACKFRAMES] != DTRACEOPT_UNSET) {
719                 ap->dtad_arg = dtp->dt_options[DTRACEOPT_STACKFRAMES];
720         } else {
721                 ap->dtad_arg = 0;
722         }
723
724         if (arg0 != NULL) {
725                 if (arg0->dn_list != NULL) {
726                         dnerror(arg0, D_STACK_PROTO, "stack( ) prototype "
727                             "mismatch: too many arguments\n");
728                 }
729
730                 if (dt_node_is_posconst(arg0) == 0) {
731                         dnerror(arg0, D_STACK_SIZE, "stack( ) size must be a "
732                             "non-zero positive integral constant expression\n");
733                 }
734
735                 ap->dtad_arg = arg0->dn_value;
736         }
737 }
738
739 static void
740 dt_action_stack(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
741 {
742         dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
743         dt_action_stack_args(dtp, ap, dnp->dn_args);
744 }
745
746 static void
747 dt_action_ustack_args(dtrace_hdl_t *dtp, dtrace_actdesc_t *ap, dt_node_t *dnp)
748 {
749         uint32_t nframes = 0;
750         uint32_t strsize = 0;   /* default string table size */
751         dt_node_t *arg0 = dnp->dn_args;
752         dt_node_t *arg1 = arg0 != NULL ? arg0->dn_list : NULL;
753
754         assert(dnp->dn_ident->di_id == DT_ACT_JSTACK ||
755             dnp->dn_ident->di_id == DT_ACT_USTACK);
756
757         if (dnp->dn_ident->di_id == DT_ACT_JSTACK) {
758                 if (dtp->dt_options[DTRACEOPT_JSTACKFRAMES] != DTRACEOPT_UNSET)
759                         nframes = dtp->dt_options[DTRACEOPT_JSTACKFRAMES];
760
761                 if (dtp->dt_options[DTRACEOPT_JSTACKSTRSIZE] != DTRACEOPT_UNSET)
762                         strsize = dtp->dt_options[DTRACEOPT_JSTACKSTRSIZE];
763
764                 ap->dtad_kind = DTRACEACT_JSTACK;
765         } else {
766                 assert(dnp->dn_ident->di_id == DT_ACT_USTACK);
767
768                 if (dtp->dt_options[DTRACEOPT_USTACKFRAMES] != DTRACEOPT_UNSET)
769                         nframes = dtp->dt_options[DTRACEOPT_USTACKFRAMES];
770
771                 ap->dtad_kind = DTRACEACT_USTACK;
772         }
773
774         if (arg0 != NULL) {
775                 if (!dt_node_is_posconst(arg0)) {
776                         dnerror(arg0, D_USTACK_FRAMES, "ustack( ) argument #1 "
777                             "must be a non-zero positive integer constant\n");
778                 }
779                 nframes = (uint32_t)arg0->dn_value;
780         }
781
782         if (arg1 != NULL) {
783                 if (arg1->dn_kind != DT_NODE_INT ||
784                     ((arg1->dn_flags & DT_NF_SIGNED) &&
785                     (int64_t)arg1->dn_value < 0)) {
786                         dnerror(arg1, D_USTACK_STRSIZE, "ustack( ) argument #2 "
787                             "must be a positive integer constant\n");
788                 }
789
790                 if (arg1->dn_list != NULL) {
791                         dnerror(arg1, D_USTACK_PROTO, "ustack( ) prototype "
792                             "mismatch: too many arguments\n");
793                 }
794
795                 strsize = (uint32_t)arg1->dn_value;
796         }
797
798         ap->dtad_arg = DTRACE_USTACK_ARG(nframes, strsize);
799 }
800
801 static void
802 dt_action_ustack(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
803 {
804         dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
805         dt_action_ustack_args(dtp, ap, dnp);
806 }
807
808 static void
809 dt_action_setopt(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
810 {
811         dtrace_actdesc_t *ap;
812         dt_node_t *arg0, *arg1;
813
814         /*
815          * The prototype guarantees that we are called with either one or
816          * two arguments, and that any arguments that are present are strings.
817          */
818         arg0 = dnp->dn_args;
819         arg1 = arg0->dn_list;
820
821         ap = dt_stmt_action(dtp, sdp);
822         dt_cg(yypcb, arg0);
823         ap->dtad_difo = dt_as(yypcb);
824         ap->dtad_kind = DTRACEACT_LIBACT;
825         ap->dtad_arg = DT_ACT_SETOPT;
826
827         ap = dt_stmt_action(dtp, sdp);
828
829         if (arg1 == NULL) {
830                 dt_action_difconst(ap, 0, DTRACEACT_LIBACT);
831         } else {
832                 dt_cg(yypcb, arg1);
833                 ap->dtad_difo = dt_as(yypcb);
834                 ap->dtad_kind = DTRACEACT_LIBACT;
835         }
836
837         ap->dtad_arg = DT_ACT_SETOPT;
838 }
839
840 /*ARGSUSED*/
841 static void
842 dt_action_symmod_args(dtrace_hdl_t *dtp, dtrace_actdesc_t *ap,
843     dt_node_t *dnp, dtrace_actkind_t kind)
844 {
845         assert(kind == DTRACEACT_SYM || kind == DTRACEACT_MOD ||
846             kind == DTRACEACT_USYM || kind == DTRACEACT_UMOD ||
847             kind == DTRACEACT_UADDR);
848
849         dt_cg(yypcb, dnp);
850         ap->dtad_difo = dt_as(yypcb);
851         ap->dtad_kind = kind;
852         ap->dtad_difo->dtdo_rtype.dtdt_size = sizeof (uint64_t);
853 }
854
855 static void
856 dt_action_symmod(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp,
857     dtrace_actkind_t kind)
858 {
859         dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
860         dt_action_symmod_args(dtp, ap, dnp->dn_args, kind);
861 }
862
863 /*ARGSUSED*/
864 static void
865 dt_action_ftruncate(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
866 {
867         dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
868
869         /*
870          * Library actions need a DIFO that serves as an argument.  As
871          * ftruncate() doesn't take an argument, we generate the constant 0
872          * in a DIFO; this constant will be ignored when the ftruncate() is
873          * processed.
874          */
875         dt_action_difconst(ap, 0, DTRACEACT_LIBACT);
876         ap->dtad_arg = DT_ACT_FTRUNCATE;
877 }
878
879 /*ARGSUSED*/
880 static void
881 dt_action_stop(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
882 {
883         dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
884
885         ap->dtad_kind = DTRACEACT_STOP;
886         ap->dtad_arg = 0;
887 }
888
889 /*ARGSUSED*/
890 static void
891 dt_action_breakpoint(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
892 {
893         dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
894
895         ap->dtad_kind = DTRACEACT_BREAKPOINT;
896         ap->dtad_arg = 0;
897 }
898
899 /*ARGSUSED*/
900 static void
901 dt_action_panic(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
902 {
903         dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
904
905         ap->dtad_kind = DTRACEACT_PANIC;
906         ap->dtad_arg = 0;
907 }
908
909 static void
910 dt_action_chill(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
911 {
912         dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
913
914         dt_cg(yypcb, dnp->dn_args);
915         ap->dtad_difo = dt_as(yypcb);
916         ap->dtad_kind = DTRACEACT_CHILL;
917 }
918
919 static void
920 dt_action_raise(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
921 {
922         dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
923
924         dt_cg(yypcb, dnp->dn_args);
925         ap->dtad_difo = dt_as(yypcb);
926         ap->dtad_kind = DTRACEACT_RAISE;
927 }
928
929 static void
930 dt_action_exit(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
931 {
932         dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
933
934         dt_cg(yypcb, dnp->dn_args);
935         ap->dtad_difo = dt_as(yypcb);
936         ap->dtad_kind = DTRACEACT_EXIT;
937         ap->dtad_difo->dtdo_rtype.dtdt_size = sizeof (int);
938 }
939
940 static void
941 dt_action_speculate(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
942 {
943         dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
944
945         dt_cg(yypcb, dnp->dn_args);
946         ap->dtad_difo = dt_as(yypcb);
947         ap->dtad_kind = DTRACEACT_SPECULATE;
948 }
949
950 static void
951 dt_action_commit(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
952 {
953         dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
954
955         dt_cg(yypcb, dnp->dn_args);
956         ap->dtad_difo = dt_as(yypcb);
957         ap->dtad_kind = DTRACEACT_COMMIT;
958 }
959
960 static void
961 dt_action_discard(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
962 {
963         dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
964
965         dt_cg(yypcb, dnp->dn_args);
966         ap->dtad_difo = dt_as(yypcb);
967         ap->dtad_kind = DTRACEACT_DISCARD;
968 }
969
970 static void
971 dt_compile_fun(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
972 {
973         switch (dnp->dn_expr->dn_ident->di_id) {
974         case DT_ACT_BREAKPOINT:
975                 dt_action_breakpoint(dtp, dnp->dn_expr, sdp);
976                 break;
977         case DT_ACT_CHILL:
978                 dt_action_chill(dtp, dnp->dn_expr, sdp);
979                 break;
980         case DT_ACT_CLEAR:
981                 dt_action_clear(dtp, dnp->dn_expr, sdp);
982                 break;
983         case DT_ACT_COMMIT:
984                 dt_action_commit(dtp, dnp->dn_expr, sdp);
985                 break;
986         case DT_ACT_DENORMALIZE:
987                 dt_action_normalize(dtp, dnp->dn_expr, sdp);
988                 break;
989         case DT_ACT_DISCARD:
990                 dt_action_discard(dtp, dnp->dn_expr, sdp);
991                 break;
992         case DT_ACT_EXIT:
993                 dt_action_exit(dtp, dnp->dn_expr, sdp);
994                 break;
995         case DT_ACT_FREOPEN:
996                 dt_action_printflike(dtp, dnp->dn_expr, sdp, DTRACEACT_FREOPEN);
997                 break;
998         case DT_ACT_FTRUNCATE:
999                 dt_action_ftruncate(dtp, dnp->dn_expr, sdp);
1000                 break;
1001         case DT_ACT_MOD:
1002                 dt_action_symmod(dtp, dnp->dn_expr, sdp, DTRACEACT_MOD);
1003                 break;
1004         case DT_ACT_NORMALIZE:
1005                 dt_action_normalize(dtp, dnp->dn_expr, sdp);
1006                 break;
1007         case DT_ACT_PANIC:
1008                 dt_action_panic(dtp, dnp->dn_expr, sdp);
1009                 break;
1010         case DT_ACT_PRINTA:
1011                 dt_action_printa(dtp, dnp->dn_expr, sdp);
1012                 break;
1013         case DT_ACT_PRINTF:
1014                 dt_action_printflike(dtp, dnp->dn_expr, sdp, DTRACEACT_PRINTF);
1015                 break;
1016         case DT_ACT_RAISE:
1017                 dt_action_raise(dtp, dnp->dn_expr, sdp);
1018                 break;
1019         case DT_ACT_SETOPT:
1020                 dt_action_setopt(dtp, dnp->dn_expr, sdp);
1021                 break;
1022         case DT_ACT_SPECULATE:
1023                 dt_action_speculate(dtp, dnp->dn_expr, sdp);
1024                 break;
1025         case DT_ACT_STACK:
1026                 dt_action_stack(dtp, dnp->dn_expr, sdp);
1027                 break;
1028         case DT_ACT_STOP:
1029                 dt_action_stop(dtp, dnp->dn_expr, sdp);
1030                 break;
1031         case DT_ACT_SYM:
1032                 dt_action_symmod(dtp, dnp->dn_expr, sdp, DTRACEACT_SYM);
1033                 break;
1034         case DT_ACT_SYSTEM:
1035                 dt_action_printflike(dtp, dnp->dn_expr, sdp, DTRACEACT_SYSTEM);
1036                 break;
1037         case DT_ACT_TRACE:
1038                 dt_action_trace(dtp, dnp->dn_expr, sdp);
1039                 break;
1040         case DT_ACT_TRACEMEM:
1041                 dt_action_tracemem(dtp, dnp->dn_expr, sdp);
1042                 break;
1043         case DT_ACT_TRUNC:
1044                 dt_action_trunc(dtp, dnp->dn_expr, sdp);
1045                 break;
1046         case DT_ACT_UADDR:
1047                 dt_action_symmod(dtp, dnp->dn_expr, sdp, DTRACEACT_UADDR);
1048                 break;
1049         case DT_ACT_UMOD:
1050                 dt_action_symmod(dtp, dnp->dn_expr, sdp, DTRACEACT_UMOD);
1051                 break;
1052         case DT_ACT_USYM:
1053                 dt_action_symmod(dtp, dnp->dn_expr, sdp, DTRACEACT_USYM);
1054                 break;
1055         case DT_ACT_USTACK:
1056         case DT_ACT_JSTACK:
1057                 dt_action_ustack(dtp, dnp->dn_expr, sdp);
1058                 break;
1059         default:
1060                 dnerror(dnp->dn_expr, D_UNKNOWN, "tracing function %s( ) is "
1061                     "not yet supported\n", dnp->dn_expr->dn_ident->di_name);
1062         }
1063 }
1064
1065 static void
1066 dt_compile_exp(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
1067 {
1068         dtrace_actdesc_t *ap = dt_stmt_action(dtp, sdp);
1069
1070         dt_cg(yypcb, dnp->dn_expr);
1071         ap->dtad_difo = dt_as(yypcb);
1072         ap->dtad_difo->dtdo_rtype = dt_void_rtype;
1073         ap->dtad_kind = DTRACEACT_DIFEXPR;
1074 }
1075
1076 static void
1077 dt_compile_agg(dtrace_hdl_t *dtp, dt_node_t *dnp, dtrace_stmtdesc_t *sdp)
1078 {
1079         dt_ident_t *aid, *fid;
1080         dt_node_t *anp, *incr = NULL;
1081         dtrace_actdesc_t *ap;
1082         uint_t n = 1, argmax;
1083         uint64_t arg = 0;
1084
1085         /*
1086          * If the aggregation has no aggregating function applied to it, then
1087          * this statement has no effect.  Flag this as a programming error.
1088          */
1089         if (dnp->dn_aggfun == NULL) {
1090                 dnerror(dnp, D_AGG_NULL, "expression has null effect: @%s\n",
1091                     dnp->dn_ident->di_name);
1092         }
1093
1094         aid = dnp->dn_ident;
1095         fid = dnp->dn_aggfun->dn_ident;
1096
1097         if (dnp->dn_aggfun->dn_args != NULL &&
1098             dt_node_is_scalar(dnp->dn_aggfun->dn_args) == 0) {
1099                 dnerror(dnp->dn_aggfun, D_AGG_SCALAR, "%s( ) argument #1 must "
1100                     "be of scalar type\n", fid->di_name);
1101         }
1102
1103         /*
1104          * The ID of the aggregation itself is implicitly recorded as the first
1105          * member of each aggregation tuple so we can distinguish them later.
1106          */
1107         ap = dt_stmt_action(dtp, sdp);
1108         dt_action_difconst(ap, aid->di_id, DTRACEACT_DIFEXPR);
1109
1110         for (anp = dnp->dn_aggtup; anp != NULL; anp = anp->dn_list) {
1111                 ap = dt_stmt_action(dtp, sdp);
1112                 n++;
1113
1114                 if (anp->dn_kind == DT_NODE_FUNC) {
1115                         if (anp->dn_ident->di_id == DT_ACT_STACK) {
1116                                 dt_action_stack_args(dtp, ap, anp->dn_args);
1117                                 continue;
1118                         }
1119
1120                         if (anp->dn_ident->di_id == DT_ACT_USTACK ||
1121                             anp->dn_ident->di_id == DT_ACT_JSTACK) {
1122                                 dt_action_ustack_args(dtp, ap, anp);
1123                                 continue;
1124                         }
1125
1126                         switch (anp->dn_ident->di_id) {
1127                         case DT_ACT_UADDR:
1128                                 dt_action_symmod_args(dtp, ap,
1129                                     anp->dn_args, DTRACEACT_UADDR);
1130                                 continue;
1131
1132                         case DT_ACT_USYM:
1133                                 dt_action_symmod_args(dtp, ap,
1134                                     anp->dn_args, DTRACEACT_USYM);
1135                                 continue;
1136
1137                         case DT_ACT_UMOD:
1138                                 dt_action_symmod_args(dtp, ap,
1139                                     anp->dn_args, DTRACEACT_UMOD);
1140                                 continue;
1141
1142                         case DT_ACT_SYM:
1143                                 dt_action_symmod_args(dtp, ap,
1144                                     anp->dn_args, DTRACEACT_SYM);
1145                                 continue;
1146
1147                         case DT_ACT_MOD:
1148                                 dt_action_symmod_args(dtp, ap,
1149                                     anp->dn_args, DTRACEACT_MOD);
1150                                 continue;
1151
1152                         default:
1153                                 break;
1154                         }
1155                 }
1156
1157                 dt_cg(yypcb, anp);
1158                 ap->dtad_difo = dt_as(yypcb);
1159                 ap->dtad_kind = DTRACEACT_DIFEXPR;
1160         }
1161
1162         if (fid->di_id == DTRACEAGG_LQUANTIZE) {
1163                 /*
1164                  * For linear quantization, we have between two and four
1165                  * arguments in addition to the expression:
1166                  *
1167                  *    arg1 => Base value
1168                  *    arg2 => Limit value
1169                  *    arg3 => Quantization level step size (defaults to 1)
1170                  *    arg4 => Quantization increment value (defaults to 1)
1171                  */
1172                 dt_node_t *arg1 = dnp->dn_aggfun->dn_args->dn_list;
1173                 dt_node_t *arg2 = arg1->dn_list;
1174                 dt_node_t *arg3 = arg2->dn_list;
1175                 dt_idsig_t *isp;
1176                 uint64_t nlevels, step = 1, oarg;
1177                 int64_t baseval, limitval;
1178
1179                 if (arg1->dn_kind != DT_NODE_INT) {
1180                         dnerror(arg1, D_LQUANT_BASETYPE, "lquantize( ) "
1181                             "argument #1 must be an integer constant\n");
1182                 }
1183
1184                 baseval = (int64_t)arg1->dn_value;
1185
1186                 if (baseval < INT32_MIN || baseval > INT32_MAX) {
1187                         dnerror(arg1, D_LQUANT_BASEVAL, "lquantize( ) "
1188                             "argument #1 must be a 32-bit quantity\n");
1189                 }
1190
1191                 if (arg2->dn_kind != DT_NODE_INT) {
1192                         dnerror(arg2, D_LQUANT_LIMTYPE, "lquantize( ) "
1193                             "argument #2 must be an integer constant\n");
1194                 }
1195
1196                 limitval = (int64_t)arg2->dn_value;
1197
1198                 if (limitval < INT32_MIN || limitval > INT32_MAX) {
1199                         dnerror(arg2, D_LQUANT_LIMVAL, "lquantize( ) "
1200                             "argument #2 must be a 32-bit quantity\n");
1201                 }
1202
1203                 if (limitval < baseval) {
1204                         dnerror(dnp, D_LQUANT_MISMATCH,
1205                             "lquantize( ) base (argument #1) must be less "
1206                             "than limit (argument #2)\n");
1207                 }
1208
1209                 if (arg3 != NULL) {
1210                         if (!dt_node_is_posconst(arg3)) {
1211                                 dnerror(arg3, D_LQUANT_STEPTYPE, "lquantize( ) "
1212                                     "argument #3 must be a non-zero positive "
1213                                     "integer constant\n");
1214                         }
1215
1216                         if ((step = arg3->dn_value) > UINT16_MAX) {
1217                                 dnerror(arg3, D_LQUANT_STEPVAL, "lquantize( ) "
1218                                     "argument #3 must be a 16-bit quantity\n");
1219                         }
1220                 }
1221
1222                 nlevels = (limitval - baseval) / step;
1223
1224                 if (nlevels == 0) {
1225                         dnerror(dnp, D_LQUANT_STEPLARGE,
1226                             "lquantize( ) step (argument #3) too large: must "
1227                             "have at least one quantization level\n");
1228                 }
1229
1230                 if (nlevels > UINT16_MAX) {
1231                         dnerror(dnp, D_LQUANT_STEPSMALL, "lquantize( ) step "
1232                             "(argument #3) too small: number of quantization "
1233                             "levels must be a 16-bit quantity\n");
1234                 }
1235
1236                 arg = (step << DTRACE_LQUANTIZE_STEPSHIFT) |
1237                     (nlevels << DTRACE_LQUANTIZE_LEVELSHIFT) |
1238                     ((baseval << DTRACE_LQUANTIZE_BASESHIFT) &
1239                     DTRACE_LQUANTIZE_BASEMASK);
1240
1241                 assert(arg != 0);
1242
1243                 isp = (dt_idsig_t *)aid->di_data;
1244
1245                 if (isp->dis_auxinfo == 0) {
1246                         /*
1247                          * This is the first time we've seen an lquantize()
1248                          * for this aggregation; we'll store our argument
1249                          * as the auxiliary signature information.
1250                          */
1251                         isp->dis_auxinfo = arg;
1252                 } else if ((oarg = isp->dis_auxinfo) != arg) {
1253                         /*
1254                          * If we have seen this lquantize() before and the
1255                          * argument doesn't match the original argument, pick
1256                          * the original argument apart to concisely report the
1257                          * mismatch.
1258                          */
1259                         int obaseval = DTRACE_LQUANTIZE_BASE(oarg);
1260                         int onlevels = DTRACE_LQUANTIZE_LEVELS(oarg);
1261                         int ostep = DTRACE_LQUANTIZE_STEP(oarg);
1262
1263                         if (obaseval != baseval) {
1264                                 dnerror(dnp, D_LQUANT_MATCHBASE, "lquantize( ) "
1265                                     "base (argument #1) doesn't match previous "
1266                                     "declaration: expected %d, found %d\n",
1267                                     obaseval, (int)baseval);
1268                         }
1269
1270                         if (onlevels * ostep != nlevels * step) {
1271                                 dnerror(dnp, D_LQUANT_MATCHLIM, "lquantize( ) "
1272                                     "limit (argument #2) doesn't match previous"
1273                                     " declaration: expected %d, found %d\n",
1274                                     obaseval + onlevels * ostep,
1275                                     (int)baseval + (int)nlevels * (int)step);
1276                         }
1277
1278                         if (ostep != step) {
1279                                 dnerror(dnp, D_LQUANT_MATCHSTEP, "lquantize( ) "
1280                                     "step (argument #3) doesn't match previous "
1281                                     "declaration: expected %d, found %d\n",
1282                                     ostep, (int)step);
1283                         }
1284
1285                         /*
1286                          * We shouldn't be able to get here -- one of the
1287                          * parameters must be mismatched if the arguments
1288                          * didn't match.
1289                          */
1290                         assert(0);
1291                 }
1292
1293                 incr = arg3 != NULL ? arg3->dn_list : NULL;
1294                 argmax = 5;
1295         }
1296
1297         if (fid->di_id == DTRACEAGG_QUANTIZE) {
1298                 incr = dnp->dn_aggfun->dn_args->dn_list;
1299                 argmax = 2;
1300         }
1301
1302         if (incr != NULL) {
1303                 if (!dt_node_is_scalar(incr)) {
1304                         dnerror(dnp, D_PROTO_ARG, "%s( ) increment value "
1305                             "(argument #%d) must be of scalar type\n",
1306                             fid->di_name, argmax);
1307                 }
1308
1309                 if ((anp = incr->dn_list) != NULL) {
1310                         int argc = argmax;
1311
1312                         for (; anp != NULL; anp = anp->dn_list)
1313                                 argc++;
1314
1315                         dnerror(incr, D_PROTO_LEN, "%s( ) prototype "
1316                             "mismatch: %d args passed, at most %d expected",
1317                             fid->di_name, argc, argmax);
1318                 }
1319
1320                 ap = dt_stmt_action(dtp, sdp);
1321                 n++;
1322
1323                 dt_cg(yypcb, incr);
1324                 ap->dtad_difo = dt_as(yypcb);
1325                 ap->dtad_difo->dtdo_rtype = dt_void_rtype;
1326                 ap->dtad_kind = DTRACEACT_DIFEXPR;
1327         }
1328
1329         assert(sdp->dtsd_aggdata == NULL);
1330         sdp->dtsd_aggdata = aid;
1331
1332         ap = dt_stmt_action(dtp, sdp);
1333         assert(fid->di_kind == DT_IDENT_AGGFUNC);
1334         assert(DTRACEACT_ISAGG(fid->di_id));
1335         ap->dtad_kind = fid->di_id;
1336         ap->dtad_ntuple = n;
1337         ap->dtad_arg = arg;
1338
1339         if (dnp->dn_aggfun->dn_args != NULL) {
1340                 dt_cg(yypcb, dnp->dn_aggfun->dn_args);
1341                 ap->dtad_difo = dt_as(yypcb);
1342         }
1343 }
1344
1345 static void
1346 dt_compile_one_clause(dtrace_hdl_t *dtp, dt_node_t *cnp, dt_node_t *pnp)
1347 {
1348         dtrace_ecbdesc_t *edp;
1349         dtrace_stmtdesc_t *sdp;
1350         dt_node_t *dnp;
1351
1352         yylineno = pnp->dn_line;
1353         dt_setcontext(dtp, pnp->dn_desc);
1354         (void) dt_node_cook(cnp, DT_IDFLG_REF);
1355
1356         if (DT_TREEDUMP_PASS(dtp, 2))
1357                 dt_node_printr(cnp, stderr, 0);
1358
1359         if ((edp = dt_ecbdesc_create(dtp, pnp->dn_desc)) == NULL)
1360                 longjmp(yypcb->pcb_jmpbuf, EDT_NOMEM);
1361
1362         assert(yypcb->pcb_ecbdesc == NULL);
1363         yypcb->pcb_ecbdesc = edp;
1364
1365         if (cnp->dn_pred != NULL) {
1366                 dt_cg(yypcb, cnp->dn_pred);
1367                 edp->dted_pred.dtpdd_difo = dt_as(yypcb);
1368         }
1369
1370         if (cnp->dn_acts == NULL) {
1371                 dt_stmt_append(dt_stmt_create(dtp, edp,
1372                     cnp->dn_ctxattr, _dtrace_defattr), cnp);
1373         }
1374
1375         for (dnp = cnp->dn_acts; dnp != NULL; dnp = dnp->dn_list) {
1376                 assert(yypcb->pcb_stmt == NULL);
1377                 sdp = dt_stmt_create(dtp, edp, cnp->dn_ctxattr, cnp->dn_attr);
1378
1379                 switch (dnp->dn_kind) {
1380                 case DT_NODE_DEXPR:
1381                         if (dnp->dn_expr->dn_kind == DT_NODE_AGG)
1382                                 dt_compile_agg(dtp, dnp->dn_expr, sdp);
1383                         else
1384                                 dt_compile_exp(dtp, dnp, sdp);
1385                         break;
1386                 case DT_NODE_DFUNC:
1387                         dt_compile_fun(dtp, dnp, sdp);
1388                         break;
1389                 case DT_NODE_AGG:
1390                         dt_compile_agg(dtp, dnp, sdp);
1391                         break;
1392                 default:
1393                         dnerror(dnp, D_UNKNOWN, "internal error -- node kind "
1394                             "%u is not a valid statement\n", dnp->dn_kind);
1395                 }
1396
1397                 assert(yypcb->pcb_stmt == sdp);
1398                 dt_stmt_append(sdp, dnp);
1399         }
1400
1401         assert(yypcb->pcb_ecbdesc == edp);
1402         dt_ecbdesc_release(dtp, edp);
1403         dt_endcontext(dtp);
1404         yypcb->pcb_ecbdesc = NULL;
1405 }
1406
1407 static void
1408 dt_compile_clause(dtrace_hdl_t *dtp, dt_node_t *cnp)
1409 {
1410         dt_node_t *pnp;
1411
1412         for (pnp = cnp->dn_pdescs; pnp != NULL; pnp = pnp->dn_list)
1413                 dt_compile_one_clause(dtp, cnp, pnp);
1414 }
1415
1416 static void
1417 dt_compile_xlator(dt_node_t *dnp)
1418 {
1419         dt_xlator_t *dxp = dnp->dn_xlator;
1420         dt_node_t *mnp;
1421
1422         for (mnp = dnp->dn_members; mnp != NULL; mnp = mnp->dn_list) {
1423                 assert(dxp->dx_membdif[mnp->dn_membid] == NULL);
1424                 dt_cg(yypcb, mnp);
1425                 dxp->dx_membdif[mnp->dn_membid] = dt_as(yypcb);
1426         }
1427 }
1428
1429 void
1430 dt_setcontext(dtrace_hdl_t *dtp, dtrace_probedesc_t *pdp)
1431 {
1432         const dtrace_pattr_t *pap;
1433         dt_probe_t *prp;
1434         dt_provider_t *pvp;
1435         dt_ident_t *idp;
1436         char attrstr[8];
1437         int err;
1438
1439         /*
1440          * Both kernel and pid based providers are allowed to have names
1441          * ending with what could be interpreted as a number. We assume it's
1442          * a pid and that we may need to dynamically create probes for
1443          * that process if:
1444          *
1445          * (1) The provider doesn't exist, or,
1446          * (2) The provider exists and has DTRACE_PRIV_PROC privilege.
1447          *
1448          * On an error, dt_pid_create_probes() will set the error message
1449          * and tag -- we just have to longjmp() out of here.
1450          */
1451         if (isdigit(pdp->dtpd_provider[strlen(pdp->dtpd_provider) - 1]) &&
1452             ((pvp = dt_provider_lookup(dtp, pdp->dtpd_provider)) == NULL ||
1453             pvp->pv_desc.dtvd_priv.dtpp_flags & DTRACE_PRIV_PROC) &&
1454             dt_pid_create_probes(pdp, dtp, yypcb) != 0) {
1455                 longjmp(yypcb->pcb_jmpbuf, EDT_COMPILER);
1456         }
1457
1458         /*
1459          * Call dt_probe_info() to get the probe arguments and attributes.  If
1460          * a representative probe is found, set 'pap' to the probe provider's
1461          * attributes.  Otherwise set 'pap' to default Unstable attributes.
1462          */
1463         if ((prp = dt_probe_info(dtp, pdp, &yypcb->pcb_pinfo)) == NULL) {
1464                 pap = &_dtrace_prvdesc;
1465                 err = dtrace_errno(dtp);
1466                 bzero(&yypcb->pcb_pinfo, sizeof (dtrace_probeinfo_t));
1467                 yypcb->pcb_pinfo.dtp_attr = pap->dtpa_provider;
1468                 yypcb->pcb_pinfo.dtp_arga = pap->dtpa_args;
1469         } else {
1470                 pap = &prp->pr_pvp->pv_desc.dtvd_attr;
1471                 err = 0;
1472         }
1473
1474         if (err == EDT_NOPROBE && !(yypcb->pcb_cflags & DTRACE_C_ZDEFS)) {
1475                 xyerror(D_PDESC_ZERO, "probe description %s:%s:%s:%s does not "
1476                     "match any probes\n", pdp->dtpd_provider, pdp->dtpd_mod,
1477                     pdp->dtpd_func, pdp->dtpd_name);
1478         }
1479
1480         if (err != EDT_NOPROBE && err != EDT_UNSTABLE && err != 0)
1481                 xyerror(D_PDESC_INVAL, "%s\n", dtrace_errmsg(dtp, err));
1482
1483         dt_dprintf("set context to %s:%s:%s:%s [%u] prp=%p attr=%s argc=%d\n",
1484             pdp->dtpd_provider, pdp->dtpd_mod, pdp->dtpd_func, pdp->dtpd_name,
1485             pdp->dtpd_id, (void *)prp, dt_attr_str(yypcb->pcb_pinfo.dtp_attr,
1486             attrstr, sizeof (attrstr)), yypcb->pcb_pinfo.dtp_argc);
1487
1488         /*
1489          * Reset the stability attributes of D global variables that vary
1490          * based on the attributes of the provider and context itself.
1491          */
1492         if ((idp = dt_idhash_lookup(dtp->dt_globals, "probeprov")) != NULL)
1493                 idp->di_attr = pap->dtpa_provider;
1494         if ((idp = dt_idhash_lookup(dtp->dt_globals, "probemod")) != NULL)
1495                 idp->di_attr = pap->dtpa_mod;
1496         if ((idp = dt_idhash_lookup(dtp->dt_globals, "probefunc")) != NULL)
1497                 idp->di_attr = pap->dtpa_func;
1498         if ((idp = dt_idhash_lookup(dtp->dt_globals, "probename")) != NULL)
1499                 idp->di_attr = pap->dtpa_name;
1500         if ((idp = dt_idhash_lookup(dtp->dt_globals, "args")) != NULL)
1501                 idp->di_attr = pap->dtpa_args;
1502
1503         yypcb->pcb_pdesc = pdp;
1504         yypcb->pcb_probe = prp;
1505 }
1506
1507 /*
1508  * Reset context-dependent variables and state at the end of cooking a D probe
1509  * definition clause.  This ensures that external declarations between clauses
1510  * do not reference any stale context-dependent data from the previous clause.
1511  */
1512 void
1513 dt_endcontext(dtrace_hdl_t *dtp)
1514 {
1515         static const char *const cvars[] = {
1516                 "probeprov", "probemod", "probefunc", "probename", "args", NULL
1517         };
1518
1519         dt_ident_t *idp;
1520         int i;
1521
1522         for (i = 0; cvars[i] != NULL; i++) {
1523                 if ((idp = dt_idhash_lookup(dtp->dt_globals, cvars[i])) != NULL)
1524                         idp->di_attr = _dtrace_defattr;
1525         }
1526
1527         yypcb->pcb_pdesc = NULL;
1528         yypcb->pcb_probe = NULL;
1529 }
1530
1531 static int
1532 dt_reduceid(dt_idhash_t *dhp, dt_ident_t *idp, dtrace_hdl_t *dtp)
1533 {
1534         if (idp->di_vers != 0 && idp->di_vers > dtp->dt_vmax)
1535                 dt_idhash_delete(dhp, idp);
1536
1537         return (0);
1538 }
1539
1540 /*
1541  * When dtrace_setopt() is called for "version", it calls dt_reduce() to remove
1542  * any identifiers or translators that have been previously defined as bound to
1543  * a version greater than the specified version.  Therefore, in our current
1544  * version implementation, establishing a binding is a one-way transformation.
1545  * In addition, no versioning is currently provided for types as our .d library
1546  * files do not define any types and we reserve prefixes DTRACE_ and dtrace_
1547  * for our exclusive use.  If required, type versioning will require more work.
1548  */
1549 int
1550 dt_reduce(dtrace_hdl_t *dtp, dt_version_t v)
1551 {
1552         char s[DT_VERSION_STRMAX];
1553         dt_xlator_t *dxp, *nxp;
1554
1555         if (v > dtp->dt_vmax)
1556                 return (dt_set_errno(dtp, EDT_VERSREDUCED));
1557         else if (v == dtp->dt_vmax)
1558                 return (0); /* no reduction necessary */
1559
1560         dt_dprintf("reducing api version to %s\n",
1561             dt_version_num2str(v, s, sizeof (s)));
1562
1563         dtp->dt_vmax = v;
1564
1565         for (dxp = dt_list_next(&dtp->dt_xlators); dxp != NULL; dxp = nxp) {
1566                 nxp = dt_list_next(dxp);
1567                 if ((dxp->dx_souid.di_vers != 0 && dxp->dx_souid.di_vers > v) ||
1568                     (dxp->dx_ptrid.di_vers != 0 && dxp->dx_ptrid.di_vers > v))
1569                         dt_list_delete(&dtp->dt_xlators, dxp);
1570         }
1571
1572         (void) dt_idhash_iter(dtp->dt_macros, (dt_idhash_f *)dt_reduceid, dtp);
1573         (void) dt_idhash_iter(dtp->dt_aggs, (dt_idhash_f *)dt_reduceid, dtp);
1574         (void) dt_idhash_iter(dtp->dt_globals, (dt_idhash_f *)dt_reduceid, dtp);
1575         (void) dt_idhash_iter(dtp->dt_tls, (dt_idhash_f *)dt_reduceid, dtp);
1576
1577         return (0);
1578 }
1579
1580 /*
1581  * Fork and exec the cpp(1) preprocessor to run over the specified input file,
1582  * and return a FILE handle for the cpp output.  We use the /dev/fd filesystem
1583  * here to simplify the code by leveraging file descriptor inheritance.
1584  */
1585 static FILE *
1586 dt_preproc(dtrace_hdl_t *dtp, FILE *ifp)
1587 {
1588         int argc = dtp->dt_cpp_argc;
1589         char **argv = malloc(sizeof (char *) * (argc + 5));
1590         FILE *ofp = tmpfile();
1591
1592         char ipath[20], opath[20]; /* big enough for /dev/fd/ + INT_MAX + \0 */
1593         char verdef[32]; /* big enough for -D__SUNW_D_VERSION=0x%08x + \0 */
1594
1595         struct sigaction act, oact;
1596         sigset_t mask, omask;
1597
1598         int wstat, estat;
1599         pid_t pid;
1600         off64_t off;
1601         int c;
1602
1603         if (argv == NULL || ofp == NULL) {
1604                 (void) dt_set_errno(dtp, errno);
1605                 goto err;
1606         }
1607
1608         /*
1609          * If the input is a seekable file, see if it is an interpreter file.
1610          * If we see #!, seek past the first line because cpp will choke on it.
1611          * We start cpp just prior to the \n at the end of this line so that
1612          * it still sees the newline, ensuring that #line values are correct.
1613          */
1614         if (isatty(fileno(ifp)) == 0 && (off = ftello64(ifp)) != -1) {
1615                 if ((c = fgetc(ifp)) == '#' && (c = fgetc(ifp)) == '!') {
1616                         for (off += 2; c != '\n'; off++) {
1617                                 if ((c = fgetc(ifp)) == EOF)
1618                                         break;
1619                         }
1620                         if (c == '\n')
1621                                 off--; /* start cpp just prior to \n */
1622                 }
1623                 (void) fflush(ifp);
1624                 (void) fseeko64(ifp, off, SEEK_SET);
1625         }
1626
1627         (void) snprintf(ipath, sizeof (ipath), "/dev/fd/%d", fileno(ifp));
1628         (void) snprintf(opath, sizeof (opath), "/dev/fd/%d", fileno(ofp));
1629
1630         bcopy(dtp->dt_cpp_argv, argv, sizeof (char *) * argc);
1631
1632         (void) snprintf(verdef, sizeof (verdef),
1633             "-D__SUNW_D_VERSION=0x%08x", dtp->dt_vmax);
1634         argv[argc++] = verdef;
1635
1636         switch (dtp->dt_stdcmode) {
1637         case DT_STDC_XA:
1638         case DT_STDC_XT:
1639                 argv[argc++] = "-D__STDC__=0";
1640                 break;
1641         case DT_STDC_XC:
1642                 argv[argc++] = "-D__STDC__=1";
1643                 break;
1644         }
1645
1646         argv[argc++] = ipath;
1647         argv[argc++] = opath;
1648         argv[argc] = NULL;
1649
1650         /*
1651          * libdtrace must be able to be embedded in other programs that may
1652          * include application-specific signal handlers.  Therefore, if we
1653          * need to fork to run cpp(1), we must avoid generating a SIGCHLD
1654          * that could confuse the containing application.  To do this,
1655          * we block SIGCHLD and reset its disposition to SIG_DFL.
1656          * We restore our signal state once we are done.
1657          */
1658         (void) sigemptyset(&mask);
1659         (void) sigaddset(&mask, SIGCHLD);
1660         (void) sigprocmask(SIG_BLOCK, &mask, &omask);
1661
1662         bzero(&act, sizeof (act));
1663         act.sa_handler = SIG_DFL;
1664         (void) sigaction(SIGCHLD, &act, &oact);
1665
1666         if ((pid = fork1()) == -1) {
1667                 (void) sigaction(SIGCHLD, &oact, NULL);
1668                 (void) sigprocmask(SIG_SETMASK, &omask, NULL);
1669                 (void) dt_set_errno(dtp, EDT_CPPFORK);
1670                 goto err;
1671         }
1672
1673         if (pid == 0) {
1674                 (void) execvp(dtp->dt_cpp_path, argv);
1675                 _exit(errno == ENOENT ? 127 : 126);
1676         }
1677
1678         do {
1679                 dt_dprintf("waiting for %s (PID %d)\n", dtp->dt_cpp_path,
1680                     (int)pid);
1681         } while (waitpid(pid, &wstat, 0) == -1 && errno == EINTR);
1682
1683         (void) sigaction(SIGCHLD, &oact, NULL);
1684         (void) sigprocmask(SIG_SETMASK, &omask, NULL);
1685
1686         dt_dprintf("%s returned exit status 0x%x\n", dtp->dt_cpp_path, wstat);
1687         estat = WIFEXITED(wstat) ? WEXITSTATUS(wstat) : -1;
1688
1689         if (estat != 0) {
1690                 switch (estat) {
1691                 case 126:
1692                         (void) dt_set_errno(dtp, EDT_CPPEXEC);
1693                         break;
1694                 case 127:
1695                         (void) dt_set_errno(dtp, EDT_CPPENT);
1696                         break;
1697                 default:
1698                         (void) dt_set_errno(dtp, EDT_CPPERR);
1699                 }
1700                 goto err;
1701         }
1702
1703         free(argv);
1704         (void) fflush(ofp);
1705         (void) fseek(ofp, 0, SEEK_SET);
1706         return (ofp);
1707
1708 err:
1709         free(argv);
1710         (void) fclose(ofp);
1711         return (NULL);
1712 }
1713
1714 static void
1715 dt_lib_depend_error(dtrace_hdl_t *dtp, const char *format, ...)
1716 {
1717         va_list ap;
1718
1719         va_start(ap, format);
1720         dt_set_errmsg(dtp, NULL, NULL, NULL, 0, format, ap);
1721         va_end(ap);
1722 }
1723
1724 int
1725 dt_lib_depend_add(dtrace_hdl_t *dtp, dt_list_t *dlp, const char *arg)
1726 {
1727         dt_lib_depend_t *dld;
1728         const char *end;
1729
1730         assert(arg != NULL);
1731
1732         if ((end = strrchr(arg, '/')) == NULL)
1733                 return (dt_set_errno(dtp, EINVAL));
1734
1735         if ((dld = dt_zalloc(dtp, sizeof (dt_lib_depend_t))) == NULL)
1736                 return (-1);
1737
1738         if ((dld->dtld_libpath = dt_alloc(dtp, MAXPATHLEN)) == NULL) {
1739                 dt_free(dtp, dld);
1740                 return (-1);
1741         }
1742
1743         (void) strlcpy(dld->dtld_libpath, arg, end - arg + 2);
1744         if ((dld->dtld_library = strdup(arg)) == NULL) {
1745                 dt_free(dtp, dld->dtld_libpath);
1746                 dt_free(dtp, dld);
1747                 return (dt_set_errno(dtp, EDT_NOMEM));
1748         }
1749
1750         dt_list_append(dlp, dld);
1751         return (0);
1752 }
1753
1754 dt_lib_depend_t *
1755 dt_lib_depend_lookup(dt_list_t *dld, const char *arg)
1756 {
1757         dt_lib_depend_t *dldn;
1758
1759         for (dldn = dt_list_next(dld); dldn != NULL;
1760             dldn = dt_list_next(dldn)) {
1761                 if (strcmp(dldn->dtld_library, arg) == 0)
1762                         return (dldn);
1763         }
1764
1765         return (NULL);
1766 }
1767
1768 /*
1769  * Go through all the library files, and, if any library dependencies exist for
1770  * that file, add it to that node's list of dependents. The result of this
1771  * will be a graph which can then be topologically sorted to produce a
1772  * compilation order.
1773  */
1774 static int
1775 dt_lib_build_graph(dtrace_hdl_t *dtp)
1776 {
1777         dt_lib_depend_t *dld, *dpld;
1778
1779         for (dld = dt_list_next(&dtp->dt_lib_dep); dld != NULL;
1780             dld = dt_list_next(dld)) {
1781                 char *library = dld->dtld_library;
1782
1783                 for (dpld = dt_list_next(&dld->dtld_dependencies); dpld != NULL;
1784                     dpld = dt_list_next(dpld)) {
1785                         dt_lib_depend_t *dlda;
1786
1787                         if ((dlda = dt_lib_depend_lookup(&dtp->dt_lib_dep,
1788                             dpld->dtld_library)) == NULL) {
1789                                 dt_lib_depend_error(dtp,
1790                                     "Invalid library dependency in %s: %s\n",
1791                                     dld->dtld_library, dpld->dtld_library);
1792
1793                                 return (dt_set_errno(dtp, EDT_COMPILER));
1794                         }
1795
1796                         if ((dt_lib_depend_add(dtp, &dlda->dtld_dependents,
1797                             library)) != 0) {
1798                                 return (-1); /* preserve dt_errno */
1799                         }
1800                 }
1801         }
1802         return (0);
1803 }
1804
1805 static int
1806 dt_topo_sort(dtrace_hdl_t *dtp, dt_lib_depend_t *dld, int *count)
1807 {
1808         dt_lib_depend_t *dpld, *dlda, *new;
1809
1810         dld->dtld_start = ++(*count);
1811
1812         for (dpld = dt_list_next(&dld->dtld_dependents); dpld != NULL;
1813             dpld = dt_list_next(dpld)) {
1814                 dlda = dt_lib_depend_lookup(&dtp->dt_lib_dep,
1815                     dpld->dtld_library);
1816                 assert(dlda != NULL);
1817
1818                 if (dlda->dtld_start == 0 &&
1819                     dt_topo_sort(dtp, dlda, count) == -1)
1820                         return (-1);
1821         }
1822
1823         if ((new = dt_zalloc(dtp, sizeof (dt_lib_depend_t))) == NULL)
1824                 return (-1);
1825
1826         if ((new->dtld_library = strdup(dld->dtld_library)) == NULL) {
1827                 dt_free(dtp, new);
1828                 return (dt_set_errno(dtp, EDT_NOMEM));
1829         }
1830
1831         new->dtld_start = dld->dtld_start;
1832         new->dtld_finish = dld->dtld_finish = ++(*count);
1833         dt_list_prepend(&dtp->dt_lib_dep_sorted, new);
1834
1835         dt_dprintf("library %s sorted (%d/%d)\n", new->dtld_library,
1836             new->dtld_start, new->dtld_finish);
1837
1838         return (0);
1839 }
1840
1841 static int
1842 dt_lib_depend_sort(dtrace_hdl_t *dtp)
1843 {
1844         dt_lib_depend_t *dld, *dpld, *dlda;
1845         int count = 0;
1846
1847         if (dt_lib_build_graph(dtp) == -1)
1848                 return (-1); /* preserve dt_errno */
1849
1850         /*
1851          * Perform a topological sort of the graph that hangs off
1852          * dtp->dt_lib_dep. The result of this process will be a
1853          * dependency ordered list located at dtp->dt_lib_dep_sorted.
1854          */
1855         for (dld = dt_list_next(&dtp->dt_lib_dep); dld != NULL;
1856             dld = dt_list_next(dld)) {
1857                 if (dld->dtld_start == 0 &&
1858                     dt_topo_sort(dtp, dld, &count) == -1)
1859                         return (-1); /* preserve dt_errno */;
1860         }
1861
1862         /*
1863          * Check the graph for cycles. If an ancestor's finishing time is
1864          * less than any of its dependent's finishing times then a back edge
1865          * exists in the graph and this is a cycle.
1866          */
1867         for (dld = dt_list_next(&dtp->dt_lib_dep); dld != NULL;
1868             dld = dt_list_next(dld)) {
1869                 for (dpld = dt_list_next(&dld->dtld_dependents); dpld != NULL;
1870                     dpld = dt_list_next(dpld)) {
1871                         dlda = dt_lib_depend_lookup(&dtp->dt_lib_dep_sorted,
1872                             dpld->dtld_library);
1873                         assert(dlda != NULL);
1874
1875                         if (dlda->dtld_finish > dld->dtld_finish) {
1876                                 dt_lib_depend_error(dtp,
1877                                     "Cyclic dependency detected: %s => %s\n",
1878                                     dld->dtld_library, dpld->dtld_library);
1879
1880                                 return (dt_set_errno(dtp, EDT_COMPILER));
1881                         }
1882                 }
1883         }
1884
1885         return (0);
1886 }
1887
1888 static void
1889 dt_lib_depend_free(dtrace_hdl_t *dtp)
1890 {
1891         dt_lib_depend_t *dld, *dlda;
1892
1893         while ((dld = dt_list_next(&dtp->dt_lib_dep)) != NULL) {
1894                 while ((dlda = dt_list_next(&dld->dtld_dependencies)) != NULL) {
1895                         dt_list_delete(&dld->dtld_dependencies, dlda);
1896                         dt_free(dtp, dlda->dtld_library);
1897                         dt_free(dtp, dlda->dtld_libpath);
1898                         dt_free(dtp, dlda);
1899                 }
1900                 while ((dlda = dt_list_next(&dld->dtld_dependents)) != NULL) {
1901                         dt_list_delete(&dld->dtld_dependents, dlda);
1902                         dt_free(dtp, dlda->dtld_library);
1903                         dt_free(dtp, dlda->dtld_libpath);
1904                         dt_free(dtp, dlda);
1905                 }
1906                 dt_list_delete(&dtp->dt_lib_dep, dld);
1907                 dt_free(dtp, dld->dtld_library);
1908                 dt_free(dtp, dld->dtld_libpath);
1909                 dt_free(dtp, dld);
1910         }
1911
1912         while ((dld = dt_list_next(&dtp->dt_lib_dep_sorted)) != NULL) {
1913                 dt_list_delete(&dtp->dt_lib_dep_sorted, dld);
1914                 dt_free(dtp, dld->dtld_library);
1915                 dt_free(dtp, dld);
1916         }
1917 }
1918
1919
1920 /*
1921  * Open all of the .d library files found in the specified directory and
1922  * compile each one in topological order to cache its inlines and translators,
1923  * etc.  We silently ignore any missing directories and other files found
1924  * therein. We only fail (and thereby fail dt_load_libs()) if we fail to
1925  * compile a library and the error is something other than #pragma D depends_on.
1926  * Dependency errors are silently ignored to permit a library directory to
1927  * contain libraries which may not be accessible depending on our privileges.
1928  */
1929 static int
1930 dt_load_libs_dir(dtrace_hdl_t *dtp, const char *path)
1931 {
1932         struct dirent *dp;
1933         const char *p;
1934         DIR *dirp;
1935
1936         char fname[PATH_MAX];
1937         dtrace_prog_t *pgp;
1938         FILE *fp;
1939         void *rv;
1940         dt_lib_depend_t *dld;
1941
1942         if ((dirp = opendir(path)) == NULL) {
1943                 dt_dprintf("skipping lib dir %s: %s\n", path, strerror(errno));
1944                 return (0);
1945         }
1946
1947         /* First, parse each file for library dependencies. */
1948         while ((dp = readdir(dirp)) != NULL) {
1949                 if ((p = strrchr(dp->d_name, '.')) == NULL || strcmp(p, ".d"))
1950                         continue; /* skip any filename not ending in .d */
1951
1952                 (void) snprintf(fname, sizeof (fname),
1953                     "%s/%s", path, dp->d_name);
1954
1955                 if ((fp = fopen(fname, "r")) == NULL) {
1956                         dt_dprintf("skipping library %s: %s\n",
1957                             fname, strerror(errno));
1958                         continue;
1959                 }
1960
1961                 dtp->dt_filetag = fname;
1962                 if (dt_lib_depend_add(dtp, &dtp->dt_lib_dep, fname) != 0)
1963                         goto err;
1964
1965                 rv = dt_compile(dtp, DT_CTX_DPROG,
1966                     DTRACE_PROBESPEC_NAME, NULL,
1967                     DTRACE_C_EMPTY | DTRACE_C_CTL, 0, NULL, fp, NULL);
1968
1969                 if (rv != NULL && dtp->dt_errno &&
1970                     (dtp->dt_errno != EDT_COMPILER ||
1971                     dtp->dt_errtag != dt_errtag(D_PRAGMA_DEPEND)))
1972                         goto err;
1973
1974                 if (dtp->dt_errno)
1975                         dt_dprintf("error parsing library %s: %s\n",
1976                             fname, dtrace_errmsg(dtp, dtrace_errno(dtp)));
1977
1978                 (void) fclose(fp);
1979                 dtp->dt_filetag = NULL;
1980         }
1981
1982         (void) closedir(dirp);
1983         /*
1984          * Finish building the graph containing the library dependencies
1985          * and perform a topological sort to generate an ordered list
1986          * for compilation.
1987          */
1988         if (dt_lib_depend_sort(dtp) == -1)
1989                 goto err;
1990
1991         for (dld = dt_list_next(&dtp->dt_lib_dep_sorted); dld != NULL;
1992             dld = dt_list_next(dld)) {
1993
1994                 if ((fp = fopen(dld->dtld_library, "r")) == NULL) {
1995                         dt_dprintf("skipping library %s: %s\n",
1996                             dld->dtld_library, strerror(errno));
1997                         continue;
1998                 }
1999
2000                 dtp->dt_filetag = dld->dtld_library;
2001                 pgp = dtrace_program_fcompile(dtp, fp, DTRACE_C_EMPTY, 0, NULL);
2002                 (void) fclose(fp);
2003                 dtp->dt_filetag = NULL;
2004
2005                 if (pgp == NULL && (dtp->dt_errno != EDT_COMPILER ||
2006                     dtp->dt_errtag != dt_errtag(D_PRAGMA_DEPEND)))
2007                         goto err;
2008
2009                 if (pgp == NULL) {
2010                         dt_dprintf("skipping library %s: %s\n",
2011                             dld->dtld_library,
2012                             dtrace_errmsg(dtp, dtrace_errno(dtp)));
2013                 } else
2014                         dt_program_destroy(dtp, pgp);
2015         }
2016
2017         dt_lib_depend_free(dtp);
2018         return (0);
2019
2020 err:
2021         dt_lib_depend_free(dtp);
2022         return (-1); /* preserve dt_errno */
2023 }
2024
2025 /*
2026  * Load the contents of any appropriate DTrace .d library files.  These files
2027  * contain inlines and translators that will be cached by the compiler.  We
2028  * defer this activity until the first compile to permit libdtrace clients to
2029  * add their own library directories and so that we can properly report errors.
2030  */
2031 static int
2032 dt_load_libs(dtrace_hdl_t *dtp)
2033 {
2034         dt_dirpath_t *dirp;
2035
2036         if (dtp->dt_cflags & DTRACE_C_NOLIBS)
2037                 return (0); /* libraries already processed */
2038
2039         dtp->dt_cflags |= DTRACE_C_NOLIBS;
2040
2041         for (dirp = dt_list_next(&dtp->dt_lib_path);
2042             dirp != NULL; dirp = dt_list_next(dirp)) {
2043                 if (dt_load_libs_dir(dtp, dirp->dir_path) != 0) {
2044                         dtp->dt_cflags &= ~DTRACE_C_NOLIBS;
2045                         return (-1); /* errno is set for us */
2046                 }
2047         }
2048
2049         return (0);
2050 }
2051
2052 static void *
2053 dt_compile(dtrace_hdl_t *dtp, int context, dtrace_probespec_t pspec, void *arg,
2054     uint_t cflags, int argc, char *const argv[], FILE *fp, const char *s)
2055 {
2056         dt_node_t *dnp;
2057         dt_decl_t *ddp;
2058         dt_pcb_t pcb;
2059         void *rv;
2060         int err;
2061
2062         if ((fp == NULL && s == NULL) || (cflags & ~DTRACE_C_MASK) != 0) {
2063                 (void) dt_set_errno(dtp, EINVAL);
2064                 return (NULL);
2065         }
2066
2067         if (dt_list_next(&dtp->dt_lib_path) != NULL && dt_load_libs(dtp) != 0)
2068                 return (NULL); /* errno is set for us */
2069
2070         (void) ctf_discard(dtp->dt_cdefs->dm_ctfp);
2071         (void) ctf_discard(dtp->dt_ddefs->dm_ctfp);
2072
2073         (void) dt_idhash_iter(dtp->dt_globals, dt_idreset, NULL);
2074         (void) dt_idhash_iter(dtp->dt_tls, dt_idreset, NULL);
2075
2076         if (fp && (cflags & DTRACE_C_CPP) && (fp = dt_preproc(dtp, fp)) == NULL)
2077                 return (NULL); /* errno is set for us */
2078
2079         dt_pcb_push(dtp, &pcb);
2080
2081         pcb.pcb_fileptr = fp;
2082         pcb.pcb_string = s;
2083         pcb.pcb_strptr = s;
2084         pcb.pcb_strlen = s ? strlen(s) : 0;
2085         pcb.pcb_sargc = argc;
2086         pcb.pcb_sargv = argv;
2087         pcb.pcb_sflagv = argc ? calloc(argc, sizeof (ushort_t)) : NULL;
2088         pcb.pcb_pspec = pspec;
2089         pcb.pcb_cflags = dtp->dt_cflags | cflags;
2090         pcb.pcb_amin = dtp->dt_amin;
2091         pcb.pcb_yystate = -1;
2092         pcb.pcb_context = context;
2093         pcb.pcb_token = context;
2094
2095         if (context != DT_CTX_DPROG)
2096                 yybegin(YYS_EXPR);
2097         else if (cflags & DTRACE_C_CTL)
2098                 yybegin(YYS_CONTROL);
2099         else
2100                 yybegin(YYS_CLAUSE);
2101
2102         if ((err = setjmp(yypcb->pcb_jmpbuf)) != 0)
2103                 goto out;
2104
2105         if (yypcb->pcb_sargc != 0 && yypcb->pcb_sflagv == NULL)
2106                 longjmp(yypcb->pcb_jmpbuf, EDT_NOMEM);
2107
2108         yypcb->pcb_idents = dt_idhash_create("ambiguous", NULL, 0, 0);
2109         yypcb->pcb_locals = dt_idhash_create("clause local", NULL,
2110             DIF_VAR_OTHER_UBASE, DIF_VAR_OTHER_MAX);
2111
2112         if (yypcb->pcb_idents == NULL || yypcb->pcb_locals == NULL)
2113                 longjmp(yypcb->pcb_jmpbuf, EDT_NOMEM);
2114
2115         /*
2116          * Invoke the parser to evaluate the D source code.  If any errors
2117          * occur during parsing, an error function will be called and we
2118          * will longjmp back to pcb_jmpbuf to abort.  If parsing succeeds,
2119          * we optionally display the parse tree if debugging is enabled.
2120          */
2121         if (yyparse() != 0 || yypcb->pcb_root == NULL)
2122                 xyerror(D_EMPTY, "empty D program translation unit\n");
2123
2124         yybegin(YYS_DONE);
2125
2126         if (cflags & DTRACE_C_CTL)
2127                 goto out;
2128
2129         if (context != DT_CTX_DTYPE && DT_TREEDUMP_PASS(dtp, 1))
2130                 dt_node_printr(yypcb->pcb_root, stderr, 0);
2131
2132         if (yypcb->pcb_pragmas != NULL)
2133                 (void) dt_idhash_iter(yypcb->pcb_pragmas, dt_idpragma, NULL);
2134
2135         if (argc > 1 && !(yypcb->pcb_cflags & DTRACE_C_ARGREF) &&
2136             !(yypcb->pcb_sflagv[argc - 1] & DT_IDFLG_REF)) {
2137                 xyerror(D_MACRO_UNUSED, "extraneous argument '%s' ($%d is "
2138                     "not referenced)\n", yypcb->pcb_sargv[argc - 1], argc - 1);
2139         }
2140
2141         /*
2142          * If we have successfully created a parse tree for a D program, loop
2143          * over the clauses and actions and instantiate the corresponding
2144          * libdtrace program.  If we are parsing a D expression, then we
2145          * simply run the code generator and assembler on the resulting tree.
2146          */
2147         switch (context) {
2148         case DT_CTX_DPROG:
2149                 assert(yypcb->pcb_root->dn_kind == DT_NODE_PROG);
2150
2151                 if ((dnp = yypcb->pcb_root->dn_list) == NULL &&
2152                     !(yypcb->pcb_cflags & DTRACE_C_EMPTY))
2153                         xyerror(D_EMPTY, "empty D program translation unit\n");
2154
2155                 if ((yypcb->pcb_prog = dt_program_create(dtp)) == NULL)
2156                         longjmp(yypcb->pcb_jmpbuf, dtrace_errno(dtp));
2157
2158                 for (; dnp != NULL; dnp = dnp->dn_list) {
2159                         switch (dnp->dn_kind) {
2160                         case DT_NODE_CLAUSE:
2161                                 dt_compile_clause(dtp, dnp);
2162                                 break;
2163                         case DT_NODE_XLATOR:
2164                                 if (dtp->dt_xlatemode == DT_XL_DYNAMIC)
2165                                         dt_compile_xlator(dnp);
2166                                 break;
2167                         case DT_NODE_PROVIDER:
2168                                 (void) dt_node_cook(dnp, DT_IDFLG_REF);
2169                                 break;
2170                         }
2171                 }
2172
2173                 yypcb->pcb_prog->dp_xrefs = yypcb->pcb_asxrefs;
2174                 yypcb->pcb_prog->dp_xrefslen = yypcb->pcb_asxreflen;
2175                 yypcb->pcb_asxrefs = NULL;
2176                 yypcb->pcb_asxreflen = 0;
2177
2178                 rv = yypcb->pcb_prog;
2179                 break;
2180
2181         case DT_CTX_DEXPR:
2182                 (void) dt_node_cook(yypcb->pcb_root, DT_IDFLG_REF);
2183                 dt_cg(yypcb, yypcb->pcb_root);
2184                 rv = dt_as(yypcb);
2185                 break;
2186
2187         case DT_CTX_DTYPE:
2188                 ddp = (dt_decl_t *)yypcb->pcb_root; /* root is really a decl */
2189                 err = dt_decl_type(ddp, arg);
2190                 dt_decl_free(ddp);
2191
2192                 if (err != 0)
2193                         longjmp(yypcb->pcb_jmpbuf, EDT_COMPILER);
2194
2195                 rv = NULL;
2196                 break;
2197         }
2198
2199 out:
2200         if (context != DT_CTX_DTYPE && DT_TREEDUMP_PASS(dtp, 3))
2201                 dt_node_printr(yypcb->pcb_root, stderr, 0);
2202
2203         if (dtp->dt_cdefs_fd != -1 && (ftruncate64(dtp->dt_cdefs_fd, 0) == -1 ||
2204             lseek64(dtp->dt_cdefs_fd, 0, SEEK_SET) == -1 ||
2205             ctf_write(dtp->dt_cdefs->dm_ctfp, dtp->dt_cdefs_fd) == CTF_ERR))
2206                 dt_dprintf("failed to update CTF cache: %s\n", strerror(errno));
2207
2208         if (dtp->dt_ddefs_fd != -1 && (ftruncate64(dtp->dt_ddefs_fd, 0) == -1 ||
2209             lseek64(dtp->dt_ddefs_fd, 0, SEEK_SET) == -1 ||
2210             ctf_write(dtp->dt_ddefs->dm_ctfp, dtp->dt_ddefs_fd) == CTF_ERR))
2211                 dt_dprintf("failed to update CTF cache: %s\n", strerror(errno));
2212
2213         if (yypcb->pcb_fileptr && (cflags & DTRACE_C_CPP))
2214                 (void) fclose(yypcb->pcb_fileptr); /* close dt_preproc() file */
2215
2216         dt_pcb_pop(dtp, err);
2217         (void) dt_set_errno(dtp, err);
2218         return (err ? NULL : rv);
2219 }
2220
2221 dtrace_prog_t *
2222 dtrace_program_strcompile(dtrace_hdl_t *dtp, const char *s,
2223     dtrace_probespec_t spec, uint_t cflags, int argc, char *const argv[])
2224 {
2225         return (dt_compile(dtp, DT_CTX_DPROG,
2226             spec, NULL, cflags, argc, argv, NULL, s));
2227 }
2228
2229 dtrace_prog_t *
2230 dtrace_program_fcompile(dtrace_hdl_t *dtp, FILE *fp,
2231     uint_t cflags, int argc, char *const argv[])
2232 {
2233         return (dt_compile(dtp, DT_CTX_DPROG,
2234             DTRACE_PROBESPEC_NAME, NULL, cflags, argc, argv, fp, NULL));
2235 }
2236
2237 int
2238 dtrace_type_strcompile(dtrace_hdl_t *dtp, const char *s, dtrace_typeinfo_t *dtt)
2239 {
2240         (void) dt_compile(dtp, DT_CTX_DTYPE,
2241             DTRACE_PROBESPEC_NONE, dtt, 0, 0, NULL, NULL, s);
2242         return (dtp->dt_errno ? -1 : 0);
2243 }
2244
2245 int
2246 dtrace_type_fcompile(dtrace_hdl_t *dtp, FILE *fp, dtrace_typeinfo_t *dtt)
2247 {
2248         (void) dt_compile(dtp, DT_CTX_DTYPE,
2249             DTRACE_PROBESPEC_NONE, dtt, 0, 0, NULL, fp, NULL);
2250         return (dtp->dt_errno ? -1 : 0);
2251 }