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