dt_printf.c revision 268578
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) 2013, Joyent, Inc. All rights reserved.
25 * Copyright (c) 2013 by Delphix. All rights reserved.
26 */
27
28#if defined(sun)
29#include <sys/sysmacros.h>
30#else
31#define	ABS(a)		((a) < 0 ? -(a) : (a))
32#endif
33#include <string.h>
34#include <strings.h>
35#include <stdlib.h>
36#if defined(sun)
37#include <alloca.h>
38#endif
39#include <assert.h>
40#include <ctype.h>
41#include <errno.h>
42#include <limits.h>
43#include <sys/socket.h>
44#include <netdb.h>
45#include <netinet/in.h>
46#include <arpa/inet.h>
47#include <arpa/nameser.h>
48
49#include <dt_printf.h>
50#include <dt_string.h>
51#include <dt_impl.h>
52
53/*ARGSUSED*/
54static int
55pfcheck_addr(dt_pfargv_t *pfv, dt_pfargd_t *pfd, dt_node_t *dnp)
56{
57	return (dt_node_is_pointer(dnp) || dt_node_is_integer(dnp));
58}
59
60/*ARGSUSED*/
61static int
62pfcheck_kaddr(dt_pfargv_t *pfv, dt_pfargd_t *pfd, dt_node_t *dnp)
63{
64	return (dt_node_is_pointer(dnp) || dt_node_is_integer(dnp) ||
65	    dt_node_is_symaddr(dnp));
66}
67
68/*ARGSUSED*/
69static int
70pfcheck_uaddr(dt_pfargv_t *pfv, dt_pfargd_t *pfd, dt_node_t *dnp)
71{
72	dtrace_hdl_t *dtp = pfv->pfv_dtp;
73	dt_ident_t *idp = dt_idhash_lookup(dtp->dt_macros, "target");
74
75	if (dt_node_is_usymaddr(dnp))
76		return (1);
77
78	if (idp == NULL || idp->di_id == 0)
79		return (0);
80
81	return (dt_node_is_pointer(dnp) || dt_node_is_integer(dnp));
82}
83
84/*ARGSUSED*/
85static int
86pfcheck_stack(dt_pfargv_t *pfv, dt_pfargd_t *pfd, dt_node_t *dnp)
87{
88	return (dt_node_is_stack(dnp));
89}
90
91/*ARGSUSED*/
92static int
93pfcheck_time(dt_pfargv_t *pfv, dt_pfargd_t *pfd, dt_node_t *dnp)
94{
95	return (dt_node_is_integer(dnp) &&
96	    dt_node_type_size(dnp) == sizeof (uint64_t));
97}
98
99/*ARGSUSED*/
100static int
101pfcheck_str(dt_pfargv_t *pfv, dt_pfargd_t *pfd, dt_node_t *dnp)
102{
103	ctf_file_t *ctfp;
104	ctf_encoding_t e;
105	ctf_arinfo_t r;
106	ctf_id_t base;
107	uint_t kind;
108
109	if (dt_node_is_string(dnp))
110		return (1);
111
112	ctfp = dnp->dn_ctfp;
113	base = ctf_type_resolve(ctfp, dnp->dn_type);
114	kind = ctf_type_kind(ctfp, base);
115
116	return (kind == CTF_K_ARRAY && ctf_array_info(ctfp, base, &r) == 0 &&
117	    (base = ctf_type_resolve(ctfp, r.ctr_contents)) != CTF_ERR &&
118	    ctf_type_encoding(ctfp, base, &e) == 0 && IS_CHAR(e));
119}
120
121/*ARGSUSED*/
122static int
123pfcheck_wstr(dt_pfargv_t *pfv, dt_pfargd_t *pfd, dt_node_t *dnp)
124{
125	ctf_file_t *ctfp = dnp->dn_ctfp;
126	ctf_id_t base = ctf_type_resolve(ctfp, dnp->dn_type);
127	uint_t kind = ctf_type_kind(ctfp, base);
128
129	ctf_encoding_t e;
130	ctf_arinfo_t r;
131
132	return (kind == CTF_K_ARRAY && ctf_array_info(ctfp, base, &r) == 0 &&
133	    (base = ctf_type_resolve(ctfp, r.ctr_contents)) != CTF_ERR &&
134	    ctf_type_kind(ctfp, base) == CTF_K_INTEGER &&
135	    ctf_type_encoding(ctfp, base, &e) == 0 && e.cte_bits == 32);
136}
137
138/*ARGSUSED*/
139static int
140pfcheck_csi(dt_pfargv_t *pfv, dt_pfargd_t *pfd, dt_node_t *dnp)
141{
142	return (dt_node_is_integer(dnp) &&
143	    dt_node_type_size(dnp) <= sizeof (int));
144}
145
146/*ARGSUSED*/
147static int
148pfcheck_fp(dt_pfargv_t *pfv, dt_pfargd_t *pfd, dt_node_t *dnp)
149{
150	return (dt_node_is_float(dnp));
151}
152
153/*ARGSUSED*/
154static int
155pfcheck_xint(dt_pfargv_t *pfv, dt_pfargd_t *pfd, dt_node_t *dnp)
156{
157	return (dt_node_is_integer(dnp));
158}
159
160/*ARGSUSED*/
161static int
162pfcheck_dint(dt_pfargv_t *pfv, dt_pfargd_t *pfd, dt_node_t *dnp)
163{
164	if (dnp->dn_flags & DT_NF_SIGNED)
165		pfd->pfd_fmt[strlen(pfd->pfd_fmt) - 1] = 'i';
166	else
167		pfd->pfd_fmt[strlen(pfd->pfd_fmt) - 1] = 'u';
168
169	return (dt_node_is_integer(dnp));
170}
171
172/*ARGSUSED*/
173static int
174pfcheck_xshort(dt_pfargv_t *pfv, dt_pfargd_t *pfd, dt_node_t *dnp)
175{
176	ctf_file_t *ctfp = dnp->dn_ctfp;
177	ctf_id_t type = ctf_type_resolve(ctfp, dnp->dn_type);
178	char n[DT_TYPE_NAMELEN];
179
180	return (ctf_type_name(ctfp, type, n, sizeof (n)) != NULL && (
181	    strcmp(n, "short") == 0 || strcmp(n, "signed short") == 0 ||
182	    strcmp(n, "unsigned short") == 0));
183}
184
185/*ARGSUSED*/
186static int
187pfcheck_xlong(dt_pfargv_t *pfv, dt_pfargd_t *pfd, dt_node_t *dnp)
188{
189	ctf_file_t *ctfp = dnp->dn_ctfp;
190	ctf_id_t type = ctf_type_resolve(ctfp, dnp->dn_type);
191	char n[DT_TYPE_NAMELEN];
192
193	return (ctf_type_name(ctfp, type, n, sizeof (n)) != NULL && (
194	    strcmp(n, "long") == 0 || strcmp(n, "signed long") == 0 ||
195	    strcmp(n, "unsigned long") == 0));
196}
197
198/*ARGSUSED*/
199static int
200pfcheck_xlonglong(dt_pfargv_t *pfv, dt_pfargd_t *pfd, dt_node_t *dnp)
201{
202	ctf_file_t *ctfp = dnp->dn_ctfp;
203	ctf_id_t type = dnp->dn_type;
204	char n[DT_TYPE_NAMELEN];
205
206	if (ctf_type_name(ctfp, ctf_type_resolve(ctfp, type), n,
207	    sizeof (n)) != NULL && (strcmp(n, "long long") == 0 ||
208	    strcmp(n, "signed long long") == 0 ||
209	    strcmp(n, "unsigned long long") == 0))
210		return (1);
211
212	/*
213	 * If the type used for %llx or %llX is not an [unsigned] long long, we
214	 * also permit it to be a [u]int64_t or any typedef thereof.  We know
215	 * that these typedefs are guaranteed to work with %ll[xX] in either
216	 * compilation environment even though they alias to "long" in LP64.
217	 */
218	while (ctf_type_kind(ctfp, type) == CTF_K_TYPEDEF) {
219		if (ctf_type_name(ctfp, type, n, sizeof (n)) != NULL &&
220		    (strcmp(n, "int64_t") == 0 || strcmp(n, "uint64_t") == 0))
221			return (1);
222
223		type = ctf_type_reference(ctfp, type);
224	}
225
226	return (0);
227}
228
229/*ARGSUSED*/
230static int
231pfcheck_type(dt_pfargv_t *pfv, dt_pfargd_t *pfd, dt_node_t *dnp)
232{
233	return (ctf_type_compat(dnp->dn_ctfp, ctf_type_resolve(dnp->dn_ctfp,
234	    dnp->dn_type), pfd->pfd_conv->pfc_dctfp, pfd->pfd_conv->pfc_dtype));
235}
236
237/*ARGSUSED*/
238static int
239pfprint_sint(dtrace_hdl_t *dtp, FILE *fp, const char *format,
240    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t unormal)
241{
242	int64_t normal = (int64_t)unormal;
243	int32_t n = (int32_t)normal;
244
245	switch (size) {
246	case sizeof (int8_t):
247		return (dt_printf(dtp, fp, format,
248		    (int32_t)*((int8_t *)addr) / n));
249	case sizeof (int16_t):
250		return (dt_printf(dtp, fp, format,
251		    (int32_t)*((int16_t *)addr) / n));
252	case sizeof (int32_t):
253		return (dt_printf(dtp, fp, format,
254		    *((int32_t *)addr) / n));
255	case sizeof (int64_t):
256		return (dt_printf(dtp, fp, format,
257		    *((int64_t *)addr) / normal));
258	default:
259		return (dt_set_errno(dtp, EDT_DMISMATCH));
260	}
261}
262
263/*ARGSUSED*/
264static int
265pfprint_uint(dtrace_hdl_t *dtp, FILE *fp, const char *format,
266    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
267{
268	uint32_t n = (uint32_t)normal;
269
270	switch (size) {
271	case sizeof (uint8_t):
272		return (dt_printf(dtp, fp, format,
273		    (uint32_t)*((uint8_t *)addr) / n));
274	case sizeof (uint16_t):
275		return (dt_printf(dtp, fp, format,
276		    (uint32_t)*((uint16_t *)addr) / n));
277	case sizeof (uint32_t):
278		return (dt_printf(dtp, fp, format,
279		    *((uint32_t *)addr) / n));
280	case sizeof (uint64_t):
281		return (dt_printf(dtp, fp, format,
282		    *((uint64_t *)addr) / normal));
283	default:
284		return (dt_set_errno(dtp, EDT_DMISMATCH));
285	}
286}
287
288static int
289pfprint_dint(dtrace_hdl_t *dtp, FILE *fp, const char *format,
290    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
291{
292	if (pfd->pfd_flags & DT_PFCONV_SIGNED)
293		return (pfprint_sint(dtp, fp, format, pfd, addr, size, normal));
294	else
295		return (pfprint_uint(dtp, fp, format, pfd, addr, size, normal));
296}
297
298/*ARGSUSED*/
299static int
300pfprint_fp(dtrace_hdl_t *dtp, FILE *fp, const char *format,
301    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
302{
303	double n = (double)normal;
304	long double ldn = (long double)normal;
305
306	switch (size) {
307	case sizeof (float):
308		return (dt_printf(dtp, fp, format,
309		    (double)*((float *)addr) / n));
310	case sizeof (double):
311		return (dt_printf(dtp, fp, format,
312		    *((double *)addr) / n));
313#if !defined(__arm__) && !defined(__powerpc__) && !defined(__mips__)
314	case sizeof (long double):
315		return (dt_printf(dtp, fp, format,
316		    *((long double *)addr) / ldn));
317#endif
318	default:
319		return (dt_set_errno(dtp, EDT_DMISMATCH));
320	}
321}
322
323/*ARGSUSED*/
324static int
325pfprint_addr(dtrace_hdl_t *dtp, FILE *fp, const char *format,
326    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
327{
328	char *s;
329	int n, len = 256;
330	uint64_t val;
331
332	switch (size) {
333	case sizeof (uint32_t):
334		val = *((uint32_t *)addr);
335		break;
336	case sizeof (uint64_t):
337		val = *((uint64_t *)addr);
338		break;
339	default:
340		return (dt_set_errno(dtp, EDT_DMISMATCH));
341	}
342
343	do {
344		n = len;
345		s = alloca(n);
346	} while ((len = dtrace_addr2str(dtp, val, s, n)) > n);
347
348	return (dt_printf(dtp, fp, format, s));
349}
350
351/*ARGSUSED*/
352static int
353pfprint_mod(dtrace_hdl_t *dtp, FILE *fp, const char *format,
354    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
355{
356	return (dt_print_mod(dtp, fp, format, (caddr_t)addr));
357}
358
359/*ARGSUSED*/
360static int
361pfprint_umod(dtrace_hdl_t *dtp, FILE *fp, const char *format,
362    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
363{
364	return (dt_print_umod(dtp, fp, format, (caddr_t)addr));
365}
366
367/*ARGSUSED*/
368static int
369pfprint_uaddr(dtrace_hdl_t *dtp, FILE *fp, const char *format,
370    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
371{
372	char *s;
373	int n, len = 256;
374	uint64_t val, pid = 0;
375
376	dt_ident_t *idp = dt_idhash_lookup(dtp->dt_macros, "target");
377
378	switch (size) {
379	case sizeof (uint32_t):
380		val = (u_longlong_t)*((uint32_t *)addr);
381		break;
382	case sizeof (uint64_t):
383		val = (u_longlong_t)*((uint64_t *)addr);
384		break;
385	case sizeof (uint64_t) * 2:
386		pid = ((uint64_t *)(uintptr_t)addr)[0];
387		val = ((uint64_t *)(uintptr_t)addr)[1];
388		break;
389	default:
390		return (dt_set_errno(dtp, EDT_DMISMATCH));
391	}
392
393	if (pid == 0 && dtp->dt_vector == NULL && idp != NULL)
394		pid = idp->di_id;
395
396	do {
397		n = len;
398		s = alloca(n);
399	} while ((len = dtrace_uaddr2str(dtp, pid, val, s, n)) > n);
400
401	return (dt_printf(dtp, fp, format, s));
402}
403
404/*ARGSUSED*/
405static int
406pfprint_stack(dtrace_hdl_t *dtp, FILE *fp, const char *format,
407    const dt_pfargd_t *pfd, const void *vaddr, size_t size, uint64_t normal)
408{
409	int width;
410	dtrace_optval_t saved = dtp->dt_options[DTRACEOPT_STACKINDENT];
411	const dtrace_recdesc_t *rec = pfd->pfd_rec;
412	caddr_t addr = (caddr_t)vaddr;
413	int err = 0;
414
415	/*
416	 * We have stashed the value of the STACKINDENT option, and we will
417	 * now override it for the purposes of formatting the stack.  If the
418	 * field has been specified as left-aligned (i.e. (%-#), we set the
419	 * indentation to be the width.  This is a slightly odd semantic, but
420	 * it's useful functionality -- and it's slightly odd to begin with to
421	 * be using a single format specifier to be formatting multiple lines
422	 * of text...
423	 */
424	if (pfd->pfd_dynwidth < 0) {
425		assert(pfd->pfd_flags & DT_PFCONV_DYNWIDTH);
426		width = -pfd->pfd_dynwidth;
427	} else if (pfd->pfd_flags & DT_PFCONV_LEFT) {
428		width = pfd->pfd_dynwidth ? pfd->pfd_dynwidth : pfd->pfd_width;
429	} else {
430		width = 0;
431	}
432
433	dtp->dt_options[DTRACEOPT_STACKINDENT] = width;
434
435	switch (rec->dtrd_action) {
436	case DTRACEACT_USTACK:
437	case DTRACEACT_JSTACK:
438		err = dt_print_ustack(dtp, fp, format, addr, rec->dtrd_arg);
439		break;
440
441	case DTRACEACT_STACK:
442		err = dt_print_stack(dtp, fp, format, addr, rec->dtrd_arg,
443		    rec->dtrd_size / rec->dtrd_arg);
444		break;
445
446	default:
447		assert(0);
448	}
449
450	dtp->dt_options[DTRACEOPT_STACKINDENT] = saved;
451
452	return (err);
453}
454
455/*ARGSUSED*/
456static int
457pfprint_time(dtrace_hdl_t *dtp, FILE *fp, const char *format,
458    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
459{
460	char src[32], buf[32], *dst = buf;
461	hrtime_t time = *((uint64_t *)addr);
462	time_t sec = (time_t)(time / NANOSEC);
463	int i;
464
465	/*
466	 * ctime(3C) returns a string of the form "Dec  3 17:20:00 1973\n\0".
467	 * Below, we turn this into the canonical adb/mdb /[yY] format,
468	 * "1973 Dec  3 17:20:00".
469	 */
470#if defined(sun)
471	(void) ctime_r(&sec, src, sizeof (src));
472#else
473	(void) ctime_r(&sec, src);
474#endif
475
476	/*
477	 * Place the 4-digit year at the head of the string...
478	 */
479	for (i = 20; i < 24; i++)
480		*dst++ = src[i];
481
482	/*
483	 * ...and follow it with the remainder (month, day, hh:mm:ss).
484	 */
485	for (i = 3; i < 19; i++)
486		*dst++ = src[i];
487
488	*dst = '\0';
489	return (dt_printf(dtp, fp, format, buf));
490}
491
492/*
493 * This prints the time in RFC 822 standard form.  This is useful for emitting
494 * notions of time that are consumed by standard tools (e.g., as part of an
495 * RSS feed).
496 */
497/*ARGSUSED*/
498static int
499pfprint_time822(dtrace_hdl_t *dtp, FILE *fp, const char *format,
500    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
501{
502	hrtime_t time = *((uint64_t *)addr);
503	time_t sec = (time_t)(time / NANOSEC);
504	struct tm tm;
505	char buf[64];
506
507	(void) localtime_r(&sec, &tm);
508	(void) strftime(buf, sizeof (buf), "%a, %d %b %G %T %Z", &tm);
509	return (dt_printf(dtp, fp, format, buf));
510}
511
512/*ARGSUSED*/
513static int
514pfprint_port(dtrace_hdl_t *dtp, FILE *fp, const char *format,
515    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
516{
517	uint16_t port = htons(*((uint16_t *)addr));
518	char buf[256];
519	struct servent *sv, res;
520
521#if defined(sun)
522	if ((sv = getservbyport_r(port, NULL, &res, buf, sizeof (buf))) != NULL)
523#else
524	if (getservbyport_r(port, NULL, &res, buf, sizeof (buf), &sv) > 0)
525#endif
526		return (dt_printf(dtp, fp, format, sv->s_name));
527
528	(void) snprintf(buf, sizeof (buf), "%d", *((uint16_t *)addr));
529	return (dt_printf(dtp, fp, format, buf));
530}
531
532/*ARGSUSED*/
533static int
534pfprint_inetaddr(dtrace_hdl_t *dtp, FILE *fp, const char *format,
535    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
536{
537	char *s = alloca(size + 1);
538	struct hostent *host, res;
539	char inetaddr[NS_IN6ADDRSZ];
540	char buf[1024];
541	int e;
542
543	bcopy(addr, s, size);
544	s[size] = '\0';
545
546	if (strchr(s, ':') == NULL && inet_pton(AF_INET, s, inetaddr) != -1) {
547#if defined(sun)
548		if ((host = gethostbyaddr_r(inetaddr, NS_INADDRSZ,
549		    AF_INET, &res, buf, sizeof (buf), &e)) != NULL)
550#else
551		if (gethostbyaddr_r(inetaddr, NS_INADDRSZ,
552		    AF_INET, &res, buf, sizeof (buf), &host, &e) > 0)
553#endif
554			return (dt_printf(dtp, fp, format, host->h_name));
555	} else if (inet_pton(AF_INET6, s, inetaddr) != -1) {
556		if ((host = getipnodebyaddr(inetaddr, NS_IN6ADDRSZ,
557		    AF_INET6, &e)) != NULL)
558			return (dt_printf(dtp, fp, format, host->h_name));
559	}
560
561	return (dt_printf(dtp, fp, format, s));
562}
563
564/*ARGSUSED*/
565static int
566pfprint_cstr(dtrace_hdl_t *dtp, FILE *fp, const char *format,
567    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
568{
569	char *s = alloca(size + 1);
570
571	bcopy(addr, s, size);
572	s[size] = '\0';
573	return (dt_printf(dtp, fp, format, s));
574}
575
576/*ARGSUSED*/
577static int
578pfprint_wstr(dtrace_hdl_t *dtp, FILE *fp, const char *format,
579    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
580{
581	wchar_t *ws = alloca(size + sizeof (wchar_t));
582
583	bcopy(addr, ws, size);
584	ws[size / sizeof (wchar_t)] = L'\0';
585	return (dt_printf(dtp, fp, format, ws));
586}
587
588/*ARGSUSED*/
589static int
590pfprint_estr(dtrace_hdl_t *dtp, FILE *fp, const char *format,
591    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
592{
593	char *s;
594	int n;
595
596	if ((s = strchr2esc(addr, size)) == NULL)
597		return (dt_set_errno(dtp, EDT_NOMEM));
598
599	n = dt_printf(dtp, fp, format, s);
600	free(s);
601	return (n);
602}
603
604static int
605pfprint_echr(dtrace_hdl_t *dtp, FILE *fp, const char *format,
606    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
607{
608	char c;
609
610	switch (size) {
611	case sizeof (int8_t):
612		c = *(int8_t *)addr;
613		break;
614	case sizeof (int16_t):
615		c = *(int16_t *)addr;
616		break;
617	case sizeof (int32_t):
618		c = *(int32_t *)addr;
619		break;
620	default:
621		return (dt_set_errno(dtp, EDT_DMISMATCH));
622	}
623
624	return (pfprint_estr(dtp, fp, format, pfd, &c, 1, normal));
625}
626
627/*ARGSUSED*/
628static int
629pfprint_pct(dtrace_hdl_t *dtp, FILE *fp, const char *format,
630    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
631{
632	return (dt_printf(dtp, fp, "%%"));
633}
634
635static const char pfproto_xint[] = "char, short, int, long, or long long";
636static const char pfproto_csi[] = "char, short, or int";
637static const char pfproto_fp[] = "float, double, or long double";
638static const char pfproto_addr[] = "pointer or integer";
639static const char pfproto_uaddr[] =
640	"pointer or integer (with -p/-c) or _usymaddr (without -p/-c)";
641static const char pfproto_cstr[] = "char [] or string (or use stringof)";
642static const char pfproto_wstr[] = "wchar_t []";
643
644/*
645 * Printf format conversion dictionary.  This table should match the set of
646 * conversions offered by printf(3C), as well as some additional extensions.
647 * The second parameter is an ASCII string which is either an actual type
648 * name we should look up (if pfcheck_type is specified), or just a descriptive
649 * string of the types expected for use in error messages.
650 */
651static const dt_pfconv_t _dtrace_conversions[] = {
652{ "a", "s", pfproto_addr, pfcheck_kaddr, pfprint_addr },
653{ "A", "s", pfproto_uaddr, pfcheck_uaddr, pfprint_uaddr },
654{ "c", "c", pfproto_csi, pfcheck_csi, pfprint_sint },
655{ "C", "s", pfproto_csi, pfcheck_csi, pfprint_echr },
656{ "d", "d", pfproto_xint, pfcheck_dint, pfprint_dint },
657{ "e", "e", pfproto_fp, pfcheck_fp, pfprint_fp },
658{ "E", "E", pfproto_fp, pfcheck_fp, pfprint_fp },
659{ "f", "f", pfproto_fp, pfcheck_fp, pfprint_fp },
660{ "g", "g", pfproto_fp, pfcheck_fp, pfprint_fp },
661{ "G", "G", pfproto_fp, pfcheck_fp, pfprint_fp },
662{ "hd", "d", "short", pfcheck_type, pfprint_sint },
663{ "hi", "i", "short", pfcheck_type, pfprint_sint },
664{ "ho", "o", "unsigned short", pfcheck_type, pfprint_uint },
665{ "hu", "u", "unsigned short", pfcheck_type, pfprint_uint },
666{ "hx", "x", "short", pfcheck_xshort, pfprint_uint },
667{ "hX", "X", "short", pfcheck_xshort, pfprint_uint },
668{ "i", "i", pfproto_xint, pfcheck_xint, pfprint_sint },
669{ "I", "s", pfproto_cstr, pfcheck_str, pfprint_inetaddr },
670{ "k", "s", "stack", pfcheck_stack, pfprint_stack },
671{ "lc", "lc", "int", pfcheck_type, pfprint_sint }, /* a.k.a. wint_t */
672{ "ld",	"d", "long", pfcheck_type, pfprint_sint },
673{ "li",	"i", "long", pfcheck_type, pfprint_sint },
674{ "lo",	"o", "unsigned long", pfcheck_type, pfprint_uint },
675{ "lu", "u", "unsigned long", pfcheck_type, pfprint_uint },
676{ "ls",	"ls", pfproto_wstr, pfcheck_wstr, pfprint_wstr },
677{ "lx",	"x", "long", pfcheck_xlong, pfprint_uint },
678{ "lX",	"X", "long", pfcheck_xlong, pfprint_uint },
679{ "lld", "d", "long long", pfcheck_type, pfprint_sint },
680{ "lli", "i", "long long", pfcheck_type, pfprint_sint },
681{ "llo", "o", "unsigned long long", pfcheck_type, pfprint_uint },
682{ "llu", "u", "unsigned long long", pfcheck_type, pfprint_uint },
683{ "llx", "x", "long long", pfcheck_xlonglong, pfprint_uint },
684{ "llX", "X", "long long", pfcheck_xlonglong, pfprint_uint },
685{ "Le",	"e", "long double", pfcheck_type, pfprint_fp },
686{ "LE",	"E", "long double", pfcheck_type, pfprint_fp },
687{ "Lf",	"f", "long double", pfcheck_type, pfprint_fp },
688{ "Lg",	"g", "long double", pfcheck_type, pfprint_fp },
689{ "LG",	"G", "long double", pfcheck_type, pfprint_fp },
690{ "o", "o", pfproto_xint, pfcheck_xint, pfprint_uint },
691{ "p", "x", pfproto_addr, pfcheck_addr, pfprint_uint },
692{ "P", "s", "uint16_t", pfcheck_type, pfprint_port },
693{ "s", "s", "char [] or string (or use stringof)", pfcheck_str, pfprint_cstr },
694{ "S", "s", pfproto_cstr, pfcheck_str, pfprint_estr },
695{ "T", "s", "int64_t", pfcheck_time, pfprint_time822 },
696{ "u", "u", pfproto_xint, pfcheck_xint, pfprint_uint },
697{ "wc",	"wc", "int", pfcheck_type, pfprint_sint }, /* a.k.a. wchar_t */
698{ "ws", "ws", pfproto_wstr, pfcheck_wstr, pfprint_wstr },
699{ "x", "x", pfproto_xint, pfcheck_xint, pfprint_uint },
700{ "X", "X", pfproto_xint, pfcheck_xint, pfprint_uint },
701{ "Y", "s", "int64_t", pfcheck_time, pfprint_time },
702{ "%", "%", "void", pfcheck_type, pfprint_pct },
703{ NULL, NULL, NULL, NULL, NULL }
704};
705
706int
707dt_pfdict_create(dtrace_hdl_t *dtp)
708{
709	uint_t n = _dtrace_strbuckets;
710	const dt_pfconv_t *pfd;
711	dt_pfdict_t *pdi;
712
713	if ((pdi = malloc(sizeof (dt_pfdict_t))) == NULL ||
714	    (pdi->pdi_buckets = malloc(sizeof (dt_pfconv_t *) * n)) == NULL) {
715		free(pdi);
716		return (dt_set_errno(dtp, EDT_NOMEM));
717	}
718
719	dtp->dt_pfdict = pdi;
720	bzero(pdi->pdi_buckets, sizeof (dt_pfconv_t *) * n);
721	pdi->pdi_nbuckets = n;
722
723	for (pfd = _dtrace_conversions; pfd->pfc_name != NULL; pfd++) {
724		dtrace_typeinfo_t dtt;
725		dt_pfconv_t *pfc;
726		uint_t h;
727
728		if ((pfc = malloc(sizeof (dt_pfconv_t))) == NULL) {
729			dt_pfdict_destroy(dtp);
730			return (dt_set_errno(dtp, EDT_NOMEM));
731		}
732
733		bcopy(pfd, pfc, sizeof (dt_pfconv_t));
734		h = dt_strtab_hash(pfc->pfc_name, NULL) % n;
735		pfc->pfc_next = pdi->pdi_buckets[h];
736		pdi->pdi_buckets[h] = pfc;
737
738		dtt.dtt_ctfp = NULL;
739		dtt.dtt_type = CTF_ERR;
740
741		/*
742		 * The "D" container or its parent must contain a definition of
743		 * any type referenced by a printf conversion.  If none can be
744		 * found, we fail to initialize the printf dictionary.
745		 */
746		if (pfc->pfc_check == &pfcheck_type && dtrace_lookup_by_type(
747		    dtp, DTRACE_OBJ_DDEFS, pfc->pfc_tstr, &dtt) != 0) {
748			dt_pfdict_destroy(dtp);
749			return (dt_set_errno(dtp, EDT_NOCONV));
750		}
751
752		pfc->pfc_dctfp = dtt.dtt_ctfp;
753		pfc->pfc_dtype = dtt.dtt_type;
754
755		/*
756		 * The "C" container may contain an alternate definition of an
757		 * explicit conversion type.  If it does, use it; otherwise
758		 * just set pfc_ctype to pfc_dtype so it is always valid.
759		 */
760		if (pfc->pfc_check == &pfcheck_type && dtrace_lookup_by_type(
761		    dtp, DTRACE_OBJ_CDEFS, pfc->pfc_tstr, &dtt) == 0) {
762			pfc->pfc_cctfp = dtt.dtt_ctfp;
763			pfc->pfc_ctype = dtt.dtt_type;
764		} else {
765			pfc->pfc_cctfp = pfc->pfc_dctfp;
766			pfc->pfc_ctype = pfc->pfc_dtype;
767		}
768
769		if (pfc->pfc_check == NULL || pfc->pfc_print == NULL ||
770		    pfc->pfc_ofmt == NULL || pfc->pfc_tstr == NULL) {
771			dt_pfdict_destroy(dtp);
772			return (dt_set_errno(dtp, EDT_BADCONV));
773		}
774
775		dt_dprintf("loaded printf conversion %%%s\n", pfc->pfc_name);
776	}
777
778	return (0);
779}
780
781void
782dt_pfdict_destroy(dtrace_hdl_t *dtp)
783{
784	dt_pfdict_t *pdi = dtp->dt_pfdict;
785	dt_pfconv_t *pfc, *nfc;
786	uint_t i;
787
788	if (pdi == NULL)
789		return;
790
791	for (i = 0; i < pdi->pdi_nbuckets; i++) {
792		for (pfc = pdi->pdi_buckets[i]; pfc != NULL; pfc = nfc) {
793			nfc = pfc->pfc_next;
794			free(pfc);
795		}
796	}
797
798	free(pdi->pdi_buckets);
799	free(pdi);
800	dtp->dt_pfdict = NULL;
801}
802
803static const dt_pfconv_t *
804dt_pfdict_lookup(dtrace_hdl_t *dtp, const char *name)
805{
806	dt_pfdict_t *pdi = dtp->dt_pfdict;
807	uint_t h = dt_strtab_hash(name, NULL) % pdi->pdi_nbuckets;
808	const dt_pfconv_t *pfc;
809
810	for (pfc = pdi->pdi_buckets[h]; pfc != NULL; pfc = pfc->pfc_next) {
811		if (strcmp(pfc->pfc_name, name) == 0)
812			break;
813	}
814
815	return (pfc);
816}
817
818static dt_pfargv_t *
819dt_printf_error(dtrace_hdl_t *dtp, int err)
820{
821	if (yypcb != NULL)
822		longjmp(yypcb->pcb_jmpbuf, err);
823
824	(void) dt_set_errno(dtp, err);
825	return (NULL);
826}
827
828dt_pfargv_t *
829dt_printf_create(dtrace_hdl_t *dtp, const char *s)
830{
831	dt_pfargd_t *pfd, *nfd = NULL;
832	dt_pfargv_t *pfv;
833	const char *p, *q;
834	char *format;
835
836	if ((pfv = malloc(sizeof (dt_pfargv_t))) == NULL ||
837	    (format = strdup(s)) == NULL) {
838		free(pfv);
839		return (dt_printf_error(dtp, EDT_NOMEM));
840	}
841
842	pfv->pfv_format = format;
843	pfv->pfv_argv = NULL;
844	pfv->pfv_argc = 0;
845	pfv->pfv_flags = 0;
846	pfv->pfv_dtp = dtp;
847
848	for (q = format; (p = strchr(q, '%')) != NULL; q = *p ? p + 1 : p) {
849		uint_t namelen = 0;
850		int digits = 0;
851		int dot = 0;
852
853		char name[8];
854		char c;
855		int n;
856
857		if ((pfd = malloc(sizeof (dt_pfargd_t))) == NULL) {
858			dt_printf_destroy(pfv);
859			return (dt_printf_error(dtp, EDT_NOMEM));
860		}
861
862		if (pfv->pfv_argv != NULL)
863			nfd->pfd_next = pfd;
864		else
865			pfv->pfv_argv = pfd;
866
867		bzero(pfd, sizeof (dt_pfargd_t));
868		pfv->pfv_argc++;
869		nfd = pfd;
870
871		if (p > q) {
872			pfd->pfd_preflen = (size_t)(p - q);
873			pfd->pfd_prefix = q;
874		}
875
876		fmt_switch:
877		switch (c = *++p) {
878		case '0': case '1': case '2': case '3': case '4':
879		case '5': case '6': case '7': case '8': case '9':
880			if (dot == 0 && digits == 0 && c == '0') {
881				pfd->pfd_flags |= DT_PFCONV_ZPAD;
882				pfd->pfd_flags &= ~DT_PFCONV_LEFT;
883				goto fmt_switch;
884			}
885
886			for (n = 0; isdigit(c); c = *++p)
887				n = n * 10 + c - '0';
888
889			if (dot)
890				pfd->pfd_prec = n;
891			else
892				pfd->pfd_width = n;
893
894			p--;
895			digits++;
896			goto fmt_switch;
897
898		case '#':
899			pfd->pfd_flags |= DT_PFCONV_ALT;
900			goto fmt_switch;
901
902		case '*':
903			n = dot ? DT_PFCONV_DYNPREC : DT_PFCONV_DYNWIDTH;
904
905			if (pfd->pfd_flags & n) {
906				yywarn("format conversion #%u has more than "
907				    "one '*' specified for the output %s\n",
908				    pfv->pfv_argc, n ? "precision" : "width");
909
910				dt_printf_destroy(pfv);
911				return (dt_printf_error(dtp, EDT_COMPILER));
912			}
913
914			pfd->pfd_flags |= n;
915			goto fmt_switch;
916
917		case '+':
918			pfd->pfd_flags |= DT_PFCONV_SPOS;
919			goto fmt_switch;
920
921		case '-':
922			pfd->pfd_flags |= DT_PFCONV_LEFT;
923			pfd->pfd_flags &= ~DT_PFCONV_ZPAD;
924			goto fmt_switch;
925
926		case '.':
927			if (dot++ != 0) {
928				yywarn("format conversion #%u has more than "
929				    "one '.' specified\n", pfv->pfv_argc);
930
931				dt_printf_destroy(pfv);
932				return (dt_printf_error(dtp, EDT_COMPILER));
933			}
934			digits = 0;
935			goto fmt_switch;
936
937		case '?':
938			if (dtp->dt_conf.dtc_ctfmodel == CTF_MODEL_LP64)
939				pfd->pfd_width = 16;
940			else
941				pfd->pfd_width = 8;
942			goto fmt_switch;
943
944		case '@':
945			pfd->pfd_flags |= DT_PFCONV_AGG;
946			goto fmt_switch;
947
948		case '\'':
949			pfd->pfd_flags |= DT_PFCONV_GROUP;
950			goto fmt_switch;
951
952		case ' ':
953			pfd->pfd_flags |= DT_PFCONV_SPACE;
954			goto fmt_switch;
955
956		case '$':
957			yywarn("format conversion #%u uses unsupported "
958			    "positional format (%%n$)\n", pfv->pfv_argc);
959
960			dt_printf_destroy(pfv);
961			return (dt_printf_error(dtp, EDT_COMPILER));
962
963		case '%':
964			if (p[-1] == '%')
965				goto default_lbl; /* if %% then use "%" conv */
966
967			yywarn("format conversion #%u cannot be combined "
968			    "with other format flags: %%%%\n", pfv->pfv_argc);
969
970			dt_printf_destroy(pfv);
971			return (dt_printf_error(dtp, EDT_COMPILER));
972
973		case '\0':
974			yywarn("format conversion #%u name expected before "
975			    "end of format string\n", pfv->pfv_argc);
976
977			dt_printf_destroy(pfv);
978			return (dt_printf_error(dtp, EDT_COMPILER));
979
980		case 'h':
981		case 'l':
982		case 'L':
983		case 'w':
984			if (namelen < sizeof (name) - 2)
985				name[namelen++] = c;
986			goto fmt_switch;
987
988		default_lbl:
989		default:
990			name[namelen++] = c;
991			name[namelen] = '\0';
992		}
993
994		pfd->pfd_conv = dt_pfdict_lookup(dtp, name);
995
996		if (pfd->pfd_conv == NULL) {
997			yywarn("format conversion #%u is undefined: %%%s\n",
998			    pfv->pfv_argc, name);
999			dt_printf_destroy(pfv);
1000			return (dt_printf_error(dtp, EDT_COMPILER));
1001		}
1002	}
1003
1004	if (*q != '\0' || *format == '\0') {
1005		if ((pfd = malloc(sizeof (dt_pfargd_t))) == NULL) {
1006			dt_printf_destroy(pfv);
1007			return (dt_printf_error(dtp, EDT_NOMEM));
1008		}
1009
1010		if (pfv->pfv_argv != NULL)
1011			nfd->pfd_next = pfd;
1012		else
1013			pfv->pfv_argv = pfd;
1014
1015		bzero(pfd, sizeof (dt_pfargd_t));
1016		pfv->pfv_argc++;
1017
1018		pfd->pfd_prefix = q;
1019		pfd->pfd_preflen = strlen(q);
1020	}
1021
1022	return (pfv);
1023}
1024
1025void
1026dt_printf_destroy(dt_pfargv_t *pfv)
1027{
1028	dt_pfargd_t *pfd, *nfd;
1029
1030	for (pfd = pfv->pfv_argv; pfd != NULL; pfd = nfd) {
1031		nfd = pfd->pfd_next;
1032		free(pfd);
1033	}
1034
1035	free(pfv->pfv_format);
1036	free(pfv);
1037}
1038
1039void
1040dt_printf_validate(dt_pfargv_t *pfv, uint_t flags,
1041    dt_ident_t *idp, int foff, dtrace_actkind_t kind, dt_node_t *dnp)
1042{
1043	dt_pfargd_t *pfd = pfv->pfv_argv;
1044	const char *func = idp->di_name;
1045
1046	char n[DT_TYPE_NAMELEN];
1047	dtrace_typeinfo_t dtt;
1048	const char *aggtype;
1049	dt_node_t aggnode;
1050	int i, j;
1051
1052	if (pfv->pfv_format[0] == '\0') {
1053		xyerror(D_PRINTF_FMT_EMPTY,
1054		    "%s( ) format string is empty\n", func);
1055	}
1056
1057	pfv->pfv_flags = flags;
1058
1059	/*
1060	 * We fake up a parse node representing the type that can be used with
1061	 * an aggregation result conversion, which -- for all but count() --
1062	 * is a signed quantity.
1063	 */
1064	if (kind != DTRACEAGG_COUNT)
1065		aggtype = "int64_t";
1066	else
1067		aggtype = "uint64_t";
1068
1069	if (dt_type_lookup(aggtype, &dtt) != 0)
1070		xyerror(D_TYPE_ERR, "failed to lookup agg type %s\n", aggtype);
1071
1072	bzero(&aggnode, sizeof (aggnode));
1073	dt_node_type_assign(&aggnode, dtt.dtt_ctfp, dtt.dtt_type, B_FALSE);
1074
1075	for (i = 0, j = 0; i < pfv->pfv_argc; i++, pfd = pfd->pfd_next) {
1076		const dt_pfconv_t *pfc = pfd->pfd_conv;
1077		const char *dyns[2];
1078		int dync = 0;
1079
1080		char vname[64];
1081		dt_node_t *vnp;
1082
1083		if (pfc == NULL)
1084			continue; /* no checking if argd is just a prefix */
1085
1086		if (pfc->pfc_print == &pfprint_pct) {
1087			(void) strcat(pfd->pfd_fmt, pfc->pfc_ofmt);
1088			continue;
1089		}
1090
1091		if (pfd->pfd_flags & DT_PFCONV_DYNPREC)
1092			dyns[dync++] = ".*";
1093		if (pfd->pfd_flags & DT_PFCONV_DYNWIDTH)
1094			dyns[dync++] = "*";
1095
1096		for (; dync != 0; dync--) {
1097			if (dnp == NULL) {
1098				xyerror(D_PRINTF_DYN_PROTO,
1099				    "%s( ) prototype mismatch: conversion "
1100				    "#%d (%%%s) is missing a corresponding "
1101				    "\"%s\" argument\n", func, i + 1,
1102				    pfc->pfc_name, dyns[dync - 1]);
1103			}
1104
1105			if (dt_node_is_integer(dnp) == 0) {
1106				xyerror(D_PRINTF_DYN_TYPE,
1107				    "%s( ) argument #%d is incompatible "
1108				    "with conversion #%d prototype:\n"
1109				    "\tconversion: %% %s %s\n"
1110				    "\t prototype: int\n\t  argument: %s\n",
1111				    func, j + foff + 1, i + 1,
1112				    dyns[dync - 1], pfc->pfc_name,
1113				    dt_node_type_name(dnp, n, sizeof (n)));
1114			}
1115
1116			dnp = dnp->dn_list;
1117			j++;
1118		}
1119
1120		/*
1121		 * If this conversion is consuming the aggregation data, set
1122		 * the value node pointer (vnp) to a fake node based on the
1123		 * aggregating function result type.  Otherwise assign vnp to
1124		 * the next parse node in the argument list, if there is one.
1125		 */
1126		if (pfd->pfd_flags & DT_PFCONV_AGG) {
1127			if (!(flags & DT_PRINTF_AGGREGATION)) {
1128				xyerror(D_PRINTF_AGG_CONV,
1129				    "%%@ conversion requires an aggregation"
1130				    " and is not for use with %s( )\n", func);
1131			}
1132			(void) strlcpy(vname, "aggregating action",
1133			    sizeof (vname));
1134			vnp = &aggnode;
1135		} else if (dnp == NULL) {
1136			xyerror(D_PRINTF_ARG_PROTO,
1137			    "%s( ) prototype mismatch: conversion #%d (%%"
1138			    "%s) is missing a corresponding value argument\n",
1139			    func, i + 1, pfc->pfc_name);
1140		} else {
1141			(void) snprintf(vname, sizeof (vname),
1142			    "argument #%d", j + foff + 1);
1143			vnp = dnp;
1144			dnp = dnp->dn_list;
1145			j++;
1146		}
1147
1148		/*
1149		 * Fill in the proposed final format string by prepending any
1150		 * size-related prefixes to the pfconv's format string.  The
1151		 * pfc_check() function below may optionally modify the format
1152		 * as part of validating the type of the input argument.
1153		 */
1154		if (pfc->pfc_print == &pfprint_sint ||
1155		    pfc->pfc_print == &pfprint_uint ||
1156		    pfc->pfc_print == &pfprint_dint) {
1157			if (dt_node_type_size(vnp) == sizeof (uint64_t))
1158				(void) strcpy(pfd->pfd_fmt, "ll");
1159		} else if (pfc->pfc_print == &pfprint_fp) {
1160			if (dt_node_type_size(vnp) == sizeof (long double))
1161				(void) strcpy(pfd->pfd_fmt, "L");
1162		}
1163
1164		(void) strcat(pfd->pfd_fmt, pfc->pfc_ofmt);
1165
1166		/*
1167		 * Validate the format conversion against the value node type.
1168		 * If the conversion is good, create the descriptor format
1169		 * string by concatenating together any required printf(3C)
1170		 * size prefixes with the conversion's native format string.
1171		 */
1172		if (pfc->pfc_check(pfv, pfd, vnp) == 0) {
1173			xyerror(D_PRINTF_ARG_TYPE,
1174			    "%s( ) %s is incompatible with "
1175			    "conversion #%d prototype:\n\tconversion: %%%s\n"
1176			    "\t prototype: %s\n\t  argument: %s\n", func,
1177			    vname, i + 1, pfc->pfc_name, pfc->pfc_tstr,
1178			    dt_node_type_name(vnp, n, sizeof (n)));
1179		}
1180	}
1181
1182	if ((flags & DT_PRINTF_EXACTLEN) && dnp != NULL) {
1183		xyerror(D_PRINTF_ARG_EXTRA,
1184		    "%s( ) prototype mismatch: only %d arguments "
1185		    "required by this format string\n", func, j);
1186	}
1187}
1188
1189void
1190dt_printa_validate(dt_node_t *lhs, dt_node_t *rhs)
1191{
1192	dt_ident_t *lid, *rid;
1193	dt_node_t *lproto, *rproto;
1194	int largc, rargc, argn;
1195	char n1[DT_TYPE_NAMELEN];
1196	char n2[DT_TYPE_NAMELEN];
1197
1198	assert(lhs->dn_kind == DT_NODE_AGG);
1199	assert(rhs->dn_kind == DT_NODE_AGG);
1200
1201	lid = lhs->dn_ident;
1202	rid = rhs->dn_ident;
1203
1204	lproto = ((dt_idsig_t *)lid->di_data)->dis_args;
1205	rproto = ((dt_idsig_t *)rid->di_data)->dis_args;
1206
1207	/*
1208	 * First, get an argument count on each side.  These must match.
1209	 */
1210	for (largc = 0; lproto != NULL; lproto = lproto->dn_list)
1211		largc++;
1212
1213	for (rargc = 0; rproto != NULL; rproto = rproto->dn_list)
1214		rargc++;
1215
1216	if (largc != rargc) {
1217		xyerror(D_PRINTA_AGGKEY, "printa( ): @%s and @%s do not have "
1218		    "matching key signatures: @%s has %d key%s, @%s has %d "
1219		    "key%s", lid->di_name, rid->di_name,
1220		    lid->di_name, largc, largc == 1 ? "" : "s",
1221		    rid->di_name, rargc, rargc == 1 ? "" : "s");
1222	}
1223
1224	/*
1225	 * Now iterate over the keys to verify that each type matches.
1226	 */
1227	lproto = ((dt_idsig_t *)lid->di_data)->dis_args;
1228	rproto = ((dt_idsig_t *)rid->di_data)->dis_args;
1229
1230	for (argn = 1; lproto != NULL; argn++, lproto = lproto->dn_list,
1231	    rproto = rproto->dn_list) {
1232		assert(rproto != NULL);
1233
1234		if (dt_node_is_argcompat(lproto, rproto))
1235			continue;
1236
1237		xyerror(D_PRINTA_AGGPROTO, "printa( ): @%s[ ] key #%d is "
1238		    "incompatible with @%s:\n%9s key #%d: %s\n"
1239		    "%9s key #%d: %s\n",
1240		    rid->di_name, argn, lid->di_name, lid->di_name, argn,
1241		    dt_node_type_name(lproto, n1, sizeof (n1)), rid->di_name,
1242		    argn, dt_node_type_name(rproto, n2, sizeof (n2)));
1243	}
1244}
1245
1246static int
1247dt_printf_getint(dtrace_hdl_t *dtp, const dtrace_recdesc_t *recp,
1248    uint_t nrecs, const void *buf, size_t len, int *ip)
1249{
1250	uintptr_t addr;
1251
1252	if (nrecs == 0)
1253		return (dt_set_errno(dtp, EDT_DMISMATCH));
1254
1255	addr = (uintptr_t)buf + recp->dtrd_offset;
1256
1257	if (addr + sizeof (int) > (uintptr_t)buf + len)
1258		return (dt_set_errno(dtp, EDT_DOFFSET));
1259
1260	if (addr & (recp->dtrd_alignment - 1))
1261		return (dt_set_errno(dtp, EDT_DALIGN));
1262
1263	switch (recp->dtrd_size) {
1264	case sizeof (int8_t):
1265		*ip = (int)*((int8_t *)addr);
1266		break;
1267	case sizeof (int16_t):
1268		*ip = (int)*((int16_t *)addr);
1269		break;
1270	case sizeof (int32_t):
1271		*ip = (int)*((int32_t *)addr);
1272		break;
1273	case sizeof (int64_t):
1274		*ip = (int)*((int64_t *)addr);
1275		break;
1276	default:
1277		return (dt_set_errno(dtp, EDT_DMISMATCH));
1278	}
1279
1280	return (0);
1281}
1282
1283/*ARGSUSED*/
1284static int
1285pfprint_average(dtrace_hdl_t *dtp, FILE *fp, const char *format,
1286    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
1287{
1288	const uint64_t *data = addr;
1289
1290	if (size != sizeof (uint64_t) * 2)
1291		return (dt_set_errno(dtp, EDT_DMISMATCH));
1292
1293	return (dt_printf(dtp, fp, format,
1294	    data[0] ? data[1] / normal / data[0] : 0));
1295}
1296
1297/*ARGSUSED*/
1298static int
1299pfprint_stddev(dtrace_hdl_t *dtp, FILE *fp, const char *format,
1300    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
1301{
1302	const uint64_t *data = addr;
1303
1304	if (size != sizeof (uint64_t) * 4)
1305		return (dt_set_errno(dtp, EDT_DMISMATCH));
1306
1307	return (dt_printf(dtp, fp, format,
1308	    dt_stddev((uint64_t *)data, normal)));
1309}
1310
1311/*ARGSUSED*/
1312static int
1313pfprint_quantize(dtrace_hdl_t *dtp, FILE *fp, const char *format,
1314    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
1315{
1316	return (dt_print_quantize(dtp, fp, addr, size, normal));
1317}
1318
1319/*ARGSUSED*/
1320static int
1321pfprint_lquantize(dtrace_hdl_t *dtp, FILE *fp, const char *format,
1322    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
1323{
1324	return (dt_print_lquantize(dtp, fp, addr, size, normal));
1325}
1326
1327/*ARGSUSED*/
1328static int
1329pfprint_llquantize(dtrace_hdl_t *dtp, FILE *fp, const char *format,
1330    const dt_pfargd_t *pfd, const void *addr, size_t size, uint64_t normal)
1331{
1332	return (dt_print_llquantize(dtp, fp, addr, size, normal));
1333}
1334
1335static int
1336dt_printf_format(dtrace_hdl_t *dtp, FILE *fp, const dt_pfargv_t *pfv,
1337    const dtrace_recdesc_t *recs, uint_t nrecs, const void *buf,
1338    size_t len, const dtrace_aggdata_t **aggsdata, int naggvars)
1339{
1340	dt_pfargd_t *pfd = pfv->pfv_argv;
1341	const dtrace_recdesc_t *recp = recs;
1342	const dtrace_aggdata_t *aggdata;
1343	dtrace_aggdesc_t *agg;
1344	caddr_t lim = (caddr_t)buf + len, limit;
1345	char format[64] = "%";
1346	int i, aggrec, curagg = -1;
1347	uint64_t normal;
1348
1349	/*
1350	 * If we are formatting an aggregation, set 'aggrec' to the index of
1351	 * the final record description (the aggregation result) so we can use
1352	 * this record index with any conversion where DT_PFCONV_AGG is set.
1353	 * (The actual aggregation used will vary as we increment through the
1354	 * aggregation variables that we have been passed.)  Finally, we
1355	 * decrement nrecs to prevent this record from being used with any
1356	 * other conversion.
1357	 */
1358	if (pfv->pfv_flags & DT_PRINTF_AGGREGATION) {
1359		assert(aggsdata != NULL);
1360		assert(naggvars > 0);
1361
1362		if (nrecs == 0)
1363			return (dt_set_errno(dtp, EDT_DMISMATCH));
1364
1365		curagg = naggvars > 1 ? 1 : 0;
1366		aggdata = aggsdata[0];
1367		aggrec = aggdata->dtada_desc->dtagd_nrecs - 1;
1368		nrecs--;
1369	}
1370
1371	for (i = 0; i < pfv->pfv_argc; i++, pfd = pfd->pfd_next) {
1372		const dt_pfconv_t *pfc = pfd->pfd_conv;
1373		int width = pfd->pfd_width;
1374		int prec = pfd->pfd_prec;
1375		int rval;
1376
1377		char *f = format + 1; /* skip initial '%' */
1378		const dtrace_recdesc_t *rec;
1379		dt_pfprint_f *func;
1380		caddr_t addr;
1381		size_t size;
1382		uint32_t flags;
1383
1384		if (pfd->pfd_preflen != 0) {
1385			char *tmp = alloca(pfd->pfd_preflen + 1);
1386
1387			bcopy(pfd->pfd_prefix, tmp, pfd->pfd_preflen);
1388			tmp[pfd->pfd_preflen] = '\0';
1389
1390			if ((rval = dt_printf(dtp, fp, tmp)) < 0)
1391				return (rval);
1392
1393			if (pfv->pfv_flags & DT_PRINTF_AGGREGATION) {
1394				/*
1395				 * For printa(), we flush the buffer after each
1396				 * prefix, setting the flags to indicate that
1397				 * this is part of the printa() format string.
1398				 */
1399				flags = DTRACE_BUFDATA_AGGFORMAT;
1400
1401				if (pfc == NULL && i == pfv->pfv_argc - 1)
1402					flags |= DTRACE_BUFDATA_AGGLAST;
1403
1404				if (dt_buffered_flush(dtp, NULL, NULL,
1405				    aggdata, flags) < 0)
1406					return (-1);
1407			}
1408		}
1409
1410		if (pfc == NULL) {
1411			if (pfv->pfv_argc == 1)
1412				return (nrecs != 0);
1413			continue;
1414		}
1415
1416		/*
1417		 * If the conversion is %%, just invoke the print callback
1418		 * with no data record and continue; it consumes no record.
1419		 */
1420		if (pfc->pfc_print == &pfprint_pct) {
1421			if (pfc->pfc_print(dtp, fp, NULL, pfd, NULL, 0, 1) >= 0)
1422				continue;
1423			return (-1); /* errno is set for us */
1424		}
1425
1426		if (pfd->pfd_flags & DT_PFCONV_DYNWIDTH) {
1427			if (dt_printf_getint(dtp, recp++, nrecs--, buf,
1428			    len, &width) == -1)
1429				return (-1); /* errno is set for us */
1430			pfd->pfd_dynwidth = width;
1431		} else {
1432			pfd->pfd_dynwidth = 0;
1433		}
1434
1435		if ((pfd->pfd_flags & DT_PFCONV_DYNPREC) && dt_printf_getint(
1436		    dtp, recp++, nrecs--, buf, len, &prec) == -1)
1437			return (-1); /* errno is set for us */
1438
1439		if (pfd->pfd_flags & DT_PFCONV_AGG) {
1440			/*
1441			 * This should be impossible -- the compiler shouldn't
1442			 * create a DT_PFCONV_AGG conversion without an
1443			 * aggregation present.  Still, we'd rather fail
1444			 * gracefully than blow up...
1445			 */
1446			if (aggsdata == NULL)
1447				return (dt_set_errno(dtp, EDT_DMISMATCH));
1448
1449			aggdata = aggsdata[curagg];
1450			agg = aggdata->dtada_desc;
1451
1452			/*
1453			 * We increment the current aggregation variable, but
1454			 * not beyond the number of aggregation variables that
1455			 * we're printing. This has the (desired) effect that
1456			 * DT_PFCONV_AGG conversions beyond the number of
1457			 * aggregation variables (re-)convert the aggregation
1458			 * value of the last aggregation variable.
1459			 */
1460			if (curagg < naggvars - 1)
1461				curagg++;
1462
1463			rec = &agg->dtagd_rec[aggrec];
1464			addr = aggdata->dtada_data + rec->dtrd_offset;
1465			limit = addr + aggdata->dtada_size;
1466			normal = aggdata->dtada_normal;
1467			flags = DTRACE_BUFDATA_AGGVAL;
1468		} else {
1469			if (nrecs == 0)
1470				return (dt_set_errno(dtp, EDT_DMISMATCH));
1471
1472			if (pfv->pfv_flags & DT_PRINTF_AGGREGATION) {
1473				/*
1474				 * When printing aggregation keys, we always
1475				 * set the aggdata to be the representative
1476				 * (zeroth) aggregation.  The aggdata isn't
1477				 * actually used here in this case, but it is
1478				 * passed to the buffer handler and must
1479				 * therefore still be correct.
1480				 */
1481				aggdata = aggsdata[0];
1482				flags = DTRACE_BUFDATA_AGGKEY;
1483			}
1484
1485			rec = recp++;
1486			nrecs--;
1487			addr = (caddr_t)buf + rec->dtrd_offset;
1488			limit = lim;
1489			normal = 1;
1490		}
1491
1492		size = rec->dtrd_size;
1493
1494		if (addr + size > limit) {
1495			dt_dprintf("bad size: addr=%p size=0x%x lim=%p\n",
1496			    (void *)addr, rec->dtrd_size, (void *)lim);
1497			return (dt_set_errno(dtp, EDT_DOFFSET));
1498		}
1499
1500		if (rec->dtrd_alignment != 0 &&
1501		    ((uintptr_t)addr & (rec->dtrd_alignment - 1)) != 0) {
1502			dt_dprintf("bad align: addr=%p size=0x%x align=0x%x\n",
1503			    (void *)addr, rec->dtrd_size, rec->dtrd_alignment);
1504			return (dt_set_errno(dtp, EDT_DALIGN));
1505		}
1506
1507		switch (rec->dtrd_action) {
1508		case DTRACEAGG_AVG:
1509			func = pfprint_average;
1510			break;
1511		case DTRACEAGG_STDDEV:
1512			func = pfprint_stddev;
1513			break;
1514		case DTRACEAGG_QUANTIZE:
1515			func = pfprint_quantize;
1516			break;
1517		case DTRACEAGG_LQUANTIZE:
1518			func = pfprint_lquantize;
1519			break;
1520		case DTRACEAGG_LLQUANTIZE:
1521			func = pfprint_llquantize;
1522			break;
1523		case DTRACEACT_MOD:
1524			func = pfprint_mod;
1525			break;
1526		case DTRACEACT_UMOD:
1527			func = pfprint_umod;
1528			break;
1529		default:
1530			func = pfc->pfc_print;
1531			break;
1532		}
1533
1534		if (pfd->pfd_flags & DT_PFCONV_ALT)
1535			*f++ = '#';
1536		if (pfd->pfd_flags & DT_PFCONV_ZPAD)
1537			*f++ = '0';
1538		if (width < 0 || (pfd->pfd_flags & DT_PFCONV_LEFT))
1539			*f++ = '-';
1540		if (pfd->pfd_flags & DT_PFCONV_SPOS)
1541			*f++ = '+';
1542		if (pfd->pfd_flags & DT_PFCONV_GROUP)
1543			*f++ = '\'';
1544		if (pfd->pfd_flags & DT_PFCONV_SPACE)
1545			*f++ = ' ';
1546
1547		/*
1548		 * If we're printing a stack and DT_PFCONV_LEFT is set, we
1549		 * don't add the width to the format string.  See the block
1550		 * comment in pfprint_stack() for a description of the
1551		 * behavior in this case.
1552		 */
1553		if (func == pfprint_stack && (pfd->pfd_flags & DT_PFCONV_LEFT))
1554			width = 0;
1555
1556		if (width != 0)
1557			f += snprintf(f, sizeof (format), "%d", ABS(width));
1558
1559		if (prec > 0)
1560			f += snprintf(f, sizeof (format), ".%d", prec);
1561
1562		(void) strcpy(f, pfd->pfd_fmt);
1563		pfd->pfd_rec = rec;
1564
1565		if (func(dtp, fp, format, pfd, addr, size, normal) < 0)
1566			return (-1); /* errno is set for us */
1567
1568		if (pfv->pfv_flags & DT_PRINTF_AGGREGATION) {
1569			/*
1570			 * For printa(), we flush the buffer after each tuple
1571			 * element, inidicating that this is the last record
1572			 * as appropriate.
1573			 */
1574			if (i == pfv->pfv_argc - 1)
1575				flags |= DTRACE_BUFDATA_AGGLAST;
1576
1577			if (dt_buffered_flush(dtp, NULL,
1578			    rec, aggdata, flags) < 0)
1579				return (-1);
1580		}
1581	}
1582
1583	return ((int)(recp - recs));
1584}
1585
1586int
1587dtrace_sprintf(dtrace_hdl_t *dtp, FILE *fp, void *fmtdata,
1588    const dtrace_recdesc_t *recp, uint_t nrecs, const void *buf, size_t len)
1589{
1590	dtrace_optval_t size;
1591	int rval;
1592
1593	rval = dtrace_getopt(dtp, "strsize", &size);
1594	assert(rval == 0);
1595	assert(dtp->dt_sprintf_buflen == 0);
1596
1597	if (dtp->dt_sprintf_buf != NULL)
1598		free(dtp->dt_sprintf_buf);
1599
1600	if ((dtp->dt_sprintf_buf = malloc(size)) == NULL)
1601		return (dt_set_errno(dtp, EDT_NOMEM));
1602
1603	bzero(dtp->dt_sprintf_buf, size);
1604	dtp->dt_sprintf_buflen = size;
1605	rval = dt_printf_format(dtp, fp, fmtdata, recp, nrecs, buf, len,
1606	    NULL, 0);
1607	dtp->dt_sprintf_buflen = 0;
1608
1609	if (rval == -1)
1610		free(dtp->dt_sprintf_buf);
1611
1612	return (rval);
1613}
1614
1615/*ARGSUSED*/
1616int
1617dtrace_system(dtrace_hdl_t *dtp, FILE *fp, void *fmtdata,
1618    const dtrace_probedata_t *data, const dtrace_recdesc_t *recp,
1619    uint_t nrecs, const void *buf, size_t len)
1620{
1621	int rval = dtrace_sprintf(dtp, fp, fmtdata, recp, nrecs, buf, len);
1622
1623	if (rval == -1)
1624		return (rval);
1625
1626	/*
1627	 * Before we execute the specified command, flush fp to assure that
1628	 * any prior dt_printf()'s appear before the output of the command
1629	 * not after it.
1630	 */
1631	(void) fflush(fp);
1632
1633	if (system(dtp->dt_sprintf_buf) == -1)
1634		return (dt_set_errno(dtp, errno));
1635
1636	return (rval);
1637}
1638
1639int
1640dtrace_freopen(dtrace_hdl_t *dtp, FILE *fp, void *fmtdata,
1641    const dtrace_probedata_t *data, const dtrace_recdesc_t *recp,
1642    uint_t nrecs, const void *buf, size_t len)
1643{
1644	char selfbuf[40], restorebuf[40], *filename;
1645	FILE *nfp;
1646	int rval, errval;
1647	dt_pfargv_t *pfv = fmtdata;
1648	dt_pfargd_t *pfd = pfv->pfv_argv;
1649
1650	rval = dtrace_sprintf(dtp, fp, fmtdata, recp, nrecs, buf, len);
1651
1652	if (rval == -1 || fp == NULL)
1653		return (rval);
1654
1655#if defined(sun)
1656	if (pfd->pfd_preflen != 0 &&
1657	    strcmp(pfd->pfd_prefix, DT_FREOPEN_RESTORE) == 0) {
1658		/*
1659		 * The only way to have the format string set to the value
1660		 * DT_FREOPEN_RESTORE is via the empty freopen() string --
1661		 * denoting that we should restore the old stdout.
1662		 */
1663		assert(strcmp(dtp->dt_sprintf_buf, DT_FREOPEN_RESTORE) == 0);
1664
1665		if (dtp->dt_stdout_fd == -1) {
1666			/*
1667			 * We could complain here by generating an error,
1668			 * but it seems like overkill:  it seems that calling
1669			 * freopen() to restore stdout when freopen() has
1670			 * never before been called should just be a no-op,
1671			 * so we just return in this case.
1672			 */
1673			return (rval);
1674		}
1675
1676		(void) snprintf(restorebuf, sizeof (restorebuf),
1677		    "/dev/fd/%d", dtp->dt_stdout_fd);
1678		filename = restorebuf;
1679	} else {
1680		filename = dtp->dt_sprintf_buf;
1681	}
1682
1683	/*
1684	 * freopen(3C) will always close the specified stream and underlying
1685	 * file descriptor -- even if the specified file can't be opened.
1686	 * Even for the semantic cesspool that is standard I/O, this is
1687	 * surprisingly brain-dead behavior:  it means that any failure to
1688	 * open the specified file destroys the specified stream in the
1689	 * process -- which is particularly relevant when the specified stream
1690	 * happens (or rather, happened) to be stdout.  This could be resolved
1691	 * were there an "fdreopen()" equivalent of freopen() that allowed one
1692	 * to pass a file descriptor instead of the name of a file, but there
1693	 * is no such thing.  However, we can effect this ourselves by first
1694	 * fopen()'ing the desired file, and then (assuming that that works),
1695	 * freopen()'ing "/dev/fd/[fileno]", where [fileno] is the underlying
1696	 * file descriptor for the fopen()'d file.  This way, if the fopen()
1697	 * fails, we can fail the operation without destroying stdout.
1698	 */
1699	if ((nfp = fopen(filename, "aF")) == NULL) {
1700		char *msg = strerror(errno);
1701		char *faultstr;
1702		int len = 80;
1703
1704		len += strlen(msg) + strlen(filename);
1705		faultstr = alloca(len);
1706
1707		(void) snprintf(faultstr, len, "couldn't freopen() \"%s\": %s",
1708		    filename, strerror(errno));
1709
1710		if ((errval = dt_handle_liberr(dtp, data, faultstr)) == 0)
1711			return (rval);
1712
1713		return (errval);
1714	}
1715
1716	(void) snprintf(selfbuf, sizeof (selfbuf), "/dev/fd/%d", fileno(nfp));
1717
1718	if (dtp->dt_stdout_fd == -1) {
1719		/*
1720		 * If this is the first time that we're calling freopen(),
1721		 * we're going to stash away the file descriptor for stdout.
1722		 * We don't expect the dup(2) to fail, so if it does we must
1723		 * return failure.
1724		 */
1725		if ((dtp->dt_stdout_fd = dup(fileno(fp))) == -1) {
1726			(void) fclose(nfp);
1727			return (dt_set_errno(dtp, errno));
1728		}
1729	}
1730
1731	if (freopen(selfbuf, "aF", fp) == NULL) {
1732		(void) fclose(nfp);
1733		return (dt_set_errno(dtp, errno));
1734	}
1735
1736	(void) fclose(nfp);
1737#else
1738	/*
1739	 * The 'standard output' (which is not necessarily stdout)
1740	 * treatment on FreeBSD is implemented differently than on
1741	 * Solaris because FreeBSD's freopen() will attempt to re-use
1742	 * the current file descriptor, causing the previous file to
1743	 * be closed and thereby preventing it from be re-activated
1744	 * later.
1745	 *
1746	 * For FreeBSD we use the concept of setting an output file
1747	 * pointer in the DTrace handle if a dtrace_freopen() has
1748	 * enabled another output file and we leave the caller's
1749	 * file pointer untouched. If it was actually stdout, then
1750	 * stdout remains open. If it was another file, then that
1751	 * file remains open. While a dtrace_freopen() has activated
1752	 * another file, we keep a pointer to that which we use in
1753	 * the output functions by preference and only use the caller's
1754	 * file pointer if no dtrace_freopen() call has been made.
1755	 *
1756	 * The check to see if we're re-activating the caller's
1757	 * output file is much the same as on Solaris.
1758	 */
1759	if (pfd->pfd_preflen != 0 &&
1760	    strcmp(pfd->pfd_prefix, DT_FREOPEN_RESTORE) == 0) {
1761		/*
1762		 * The only way to have the format string set to the value
1763		 * DT_FREOPEN_RESTORE is via the empty freopen() string --
1764		 * denoting that we should restore the old stdout.
1765		 */
1766		assert(strcmp(dtp->dt_sprintf_buf, DT_FREOPEN_RESTORE) == 0);
1767
1768		if (dtp->dt_freopen_fp == NULL) {
1769			/*
1770			 * We could complain here by generating an error,
1771			 * but it seems like overkill:  it seems that calling
1772			 * freopen() to restore stdout when freopen() has
1773			 * never before been called should just be a no-op,
1774			 * so we just return in this case.
1775			 */
1776			return (rval);
1777		}
1778
1779		/*
1780		 * At this point, to re-active the original output file,
1781		 * on FreeBSD we only code the current file that this
1782		 * function opened previously.
1783		 */
1784		(void) fclose(dtp->dt_freopen_fp);
1785		dtp->dt_freopen_fp = NULL;
1786
1787		return (rval);
1788	}
1789
1790	if ((nfp = fopen(dtp->dt_sprintf_buf, "a")) == NULL) {
1791		char *msg = strerror(errno);
1792		char *faultstr;
1793		int len = 80;
1794
1795		len += strlen(msg) + strlen(dtp->dt_sprintf_buf);
1796		faultstr = alloca(len);
1797
1798		(void) snprintf(faultstr, len, "couldn't freopen() \"%s\": %s",
1799		    dtp->dt_sprintf_buf, strerror(errno));
1800
1801		if ((errval = dt_handle_liberr(dtp, data, faultstr)) == 0)
1802			return (rval);
1803
1804		return (errval);
1805	}
1806
1807	if (dtp->dt_freopen_fp != NULL)
1808		(void) fclose(dtp->dt_freopen_fp);
1809
1810	/* Remember that the output has been redirected to the new file. */
1811	dtp->dt_freopen_fp = nfp;
1812#endif
1813
1814	return (rval);
1815}
1816
1817/*ARGSUSED*/
1818int
1819dtrace_fprintf(dtrace_hdl_t *dtp, FILE *fp, void *fmtdata,
1820    const dtrace_probedata_t *data, const dtrace_recdesc_t *recp,
1821    uint_t nrecs, const void *buf, size_t len)
1822{
1823	return (dt_printf_format(dtp, fp, fmtdata,
1824	    recp, nrecs, buf, len, NULL, 0));
1825}
1826
1827void *
1828dtrace_printf_create(dtrace_hdl_t *dtp, const char *s)
1829{
1830	dt_pfargv_t *pfv = dt_printf_create(dtp, s);
1831	dt_pfargd_t *pfd;
1832	int i;
1833
1834	if (pfv == NULL)
1835		return (NULL);		/* errno has been set for us */
1836
1837	pfd = pfv->pfv_argv;
1838
1839	for (i = 0; i < pfv->pfv_argc; i++, pfd = pfd->pfd_next) {
1840		const dt_pfconv_t *pfc = pfd->pfd_conv;
1841
1842		if (pfc == NULL)
1843			continue;
1844
1845		/*
1846		 * If the output format is not %s then we assume that we have
1847		 * been given a correctly-sized format string, so we copy the
1848		 * true format name including the size modifier.  If the output
1849		 * format is %s, then either the input format is %s as well or
1850		 * it is one of our custom formats (e.g. pfprint_addr), so we
1851		 * must set pfd_fmt to be the output format conversion "s".
1852		 */
1853		if (strcmp(pfc->pfc_ofmt, "s") != 0)
1854			(void) strcat(pfd->pfd_fmt, pfc->pfc_name);
1855		else
1856			(void) strcat(pfd->pfd_fmt, pfc->pfc_ofmt);
1857	}
1858
1859	return (pfv);
1860}
1861
1862void *
1863dtrace_printa_create(dtrace_hdl_t *dtp, const char *s)
1864{
1865	dt_pfargv_t *pfv = dtrace_printf_create(dtp, s);
1866
1867	if (pfv == NULL)
1868		return (NULL);		/* errno has been set for us */
1869
1870	pfv->pfv_flags |= DT_PRINTF_AGGREGATION;
1871
1872	return (pfv);
1873}
1874
1875/*ARGSUSED*/
1876size_t
1877dtrace_printf_format(dtrace_hdl_t *dtp, void *fmtdata, char *s, size_t len)
1878{
1879	dt_pfargv_t *pfv = fmtdata;
1880	dt_pfargd_t *pfd = pfv->pfv_argv;
1881
1882	/*
1883	 * An upper bound on the string length is the length of the original
1884	 * format string, plus three times the number of conversions (each
1885	 * conversion could add up an additional "ll" and/or pfd_width digit
1886	 * in the case of converting %? to %16) plus one for a terminating \0.
1887	 */
1888	size_t formatlen = strlen(pfv->pfv_format) + 3 * pfv->pfv_argc + 1;
1889	char *format = alloca(formatlen);
1890	char *f = format;
1891	int i, j;
1892
1893	for (i = 0; i < pfv->pfv_argc; i++, pfd = pfd->pfd_next) {
1894		const dt_pfconv_t *pfc = pfd->pfd_conv;
1895		const char *str;
1896		int width = pfd->pfd_width;
1897		int prec = pfd->pfd_prec;
1898
1899		if (pfd->pfd_preflen != 0) {
1900			for (j = 0; j < pfd->pfd_preflen; j++)
1901				*f++ = pfd->pfd_prefix[j];
1902		}
1903
1904		if (pfc == NULL)
1905			continue;
1906
1907		*f++ = '%';
1908
1909		if (pfd->pfd_flags & DT_PFCONV_ALT)
1910			*f++ = '#';
1911		if (pfd->pfd_flags & DT_PFCONV_ZPAD)
1912			*f++ = '0';
1913		if (pfd->pfd_flags & DT_PFCONV_LEFT)
1914			*f++ = '-';
1915		if (pfd->pfd_flags & DT_PFCONV_SPOS)
1916			*f++ = '+';
1917		if (pfd->pfd_flags & DT_PFCONV_DYNWIDTH)
1918			*f++ = '*';
1919		if (pfd->pfd_flags & DT_PFCONV_DYNPREC) {
1920			*f++ = '.';
1921			*f++ = '*';
1922		}
1923		if (pfd->pfd_flags & DT_PFCONV_GROUP)
1924			*f++ = '\'';
1925		if (pfd->pfd_flags & DT_PFCONV_SPACE)
1926			*f++ = ' ';
1927		if (pfd->pfd_flags & DT_PFCONV_AGG)
1928			*f++ = '@';
1929
1930		if (width != 0)
1931			f += snprintf(f, sizeof (format), "%d", width);
1932
1933		if (prec != 0)
1934			f += snprintf(f, sizeof (format), ".%d", prec);
1935
1936		/*
1937		 * If the output format is %s, then either %s is the underlying
1938		 * conversion or the conversion is one of our customized ones,
1939		 * e.g. pfprint_addr.  In these cases, put the original string
1940		 * name of the conversion (pfc_name) into the pickled format
1941		 * string rather than the derived conversion (pfd_fmt).
1942		 */
1943		if (strcmp(pfc->pfc_ofmt, "s") == 0)
1944			str = pfc->pfc_name;
1945		else
1946			str = pfd->pfd_fmt;
1947
1948		for (j = 0; str[j] != '\0'; j++)
1949			*f++ = str[j];
1950	}
1951
1952	*f = '\0'; /* insert nul byte; do not count in return value */
1953
1954	assert(f < format + formatlen);
1955	(void) strncpy(s, format, len);
1956
1957	return ((size_t)(f - format));
1958}
1959
1960static int
1961dt_fprinta(const dtrace_aggdata_t *adp, void *arg)
1962{
1963	const dtrace_aggdesc_t *agg = adp->dtada_desc;
1964	const dtrace_recdesc_t *recp = &agg->dtagd_rec[0];
1965	uint_t nrecs = agg->dtagd_nrecs;
1966	dt_pfwalk_t *pfw = arg;
1967	dtrace_hdl_t *dtp = pfw->pfw_argv->pfv_dtp;
1968	int id;
1969
1970	if (dt_printf_getint(dtp, recp++, nrecs--,
1971	    adp->dtada_data, adp->dtada_size, &id) != 0 || pfw->pfw_aid != id)
1972		return (0); /* no aggregation id or id does not match */
1973
1974	if (dt_printf_format(dtp, pfw->pfw_fp, pfw->pfw_argv,
1975	    recp, nrecs, adp->dtada_data, adp->dtada_size, &adp, 1) == -1)
1976		return (pfw->pfw_err = dtp->dt_errno);
1977
1978	/*
1979	 * Cast away the const to set the bit indicating that this aggregation
1980	 * has been printed.
1981	 */
1982	((dtrace_aggdesc_t *)agg)->dtagd_flags |= DTRACE_AGD_PRINTED;
1983
1984	return (0);
1985}
1986
1987static int
1988dt_fprintas(const dtrace_aggdata_t **aggsdata, int naggvars, void *arg)
1989{
1990	const dtrace_aggdata_t *aggdata = aggsdata[0];
1991	const dtrace_aggdesc_t *agg = aggdata->dtada_desc;
1992	const dtrace_recdesc_t *rec = &agg->dtagd_rec[1];
1993	uint_t nrecs = agg->dtagd_nrecs - 1;
1994	dt_pfwalk_t *pfw = arg;
1995	dtrace_hdl_t *dtp = pfw->pfw_argv->pfv_dtp;
1996	int i;
1997
1998	if (dt_printf_format(dtp, pfw->pfw_fp, pfw->pfw_argv,
1999	    rec, nrecs, aggdata->dtada_data, aggdata->dtada_size,
2000	    aggsdata, naggvars) == -1)
2001		return (pfw->pfw_err = dtp->dt_errno);
2002
2003	/*
2004	 * For each aggregation, indicate that it has been printed, casting
2005	 * away the const as necessary.
2006	 */
2007	for (i = 1; i < naggvars; i++) {
2008		agg = aggsdata[i]->dtada_desc;
2009		((dtrace_aggdesc_t *)agg)->dtagd_flags |= DTRACE_AGD_PRINTED;
2010	}
2011
2012	return (0);
2013}
2014/*ARGSUSED*/
2015int
2016dtrace_fprinta(dtrace_hdl_t *dtp, FILE *fp, void *fmtdata,
2017    const dtrace_probedata_t *data, const dtrace_recdesc_t *recs,
2018    uint_t nrecs, const void *buf, size_t len)
2019{
2020	dt_pfwalk_t pfw;
2021	int i, naggvars = 0;
2022	dtrace_aggvarid_t *aggvars;
2023
2024	aggvars = alloca(nrecs * sizeof (dtrace_aggvarid_t));
2025
2026	/*
2027	 * This might be a printa() with multiple aggregation variables.  We
2028	 * need to scan forward through the records until we find a record from
2029	 * a different statement.
2030	 */
2031	for (i = 0; i < nrecs; i++) {
2032		const dtrace_recdesc_t *nrec = &recs[i];
2033
2034		if (nrec->dtrd_uarg != recs->dtrd_uarg)
2035			break;
2036
2037		if (nrec->dtrd_action != recs->dtrd_action)
2038			return (dt_set_errno(dtp, EDT_BADAGG));
2039
2040		aggvars[naggvars++] =
2041		    /* LINTED - alignment */
2042		    *((dtrace_aggvarid_t *)((caddr_t)buf + nrec->dtrd_offset));
2043	}
2044
2045	if (naggvars == 0)
2046		return (dt_set_errno(dtp, EDT_BADAGG));
2047
2048	pfw.pfw_argv = fmtdata;
2049	pfw.pfw_fp = fp;
2050	pfw.pfw_err = 0;
2051
2052	if (naggvars == 1) {
2053		pfw.pfw_aid = aggvars[0];
2054
2055		if (dtrace_aggregate_walk_sorted(dtp,
2056		    dt_fprinta, &pfw) == -1 || pfw.pfw_err != 0)
2057			return (-1); /* errno is set for us */
2058	} else {
2059		if (dtrace_aggregate_walk_joined(dtp, aggvars, naggvars,
2060		    dt_fprintas, &pfw) == -1 || pfw.pfw_err != 0)
2061			return (-1); /* errno is set for us */
2062	}
2063
2064	return (i);
2065}
2066