xref: /netbsd-src/external/cddl/osnet/dist/lib/libdtrace/common/dt_subr.c (revision d909946ca08dceb44d7d0f22ec9488679695d976)
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 2010 Sun Microsystems, Inc.  All rights reserved.
24  * Copyright (c) 2012 by Delphix. All rights reserved.
25  * Use is subject to license terms.
26  */
27 
28 #ifdef illumos
29 #include <sys/sysmacros.h>
30 #endif
31 #include <sys/isa_defs.h>
32 
33 #include <strings.h>
34 #include <unistd.h>
35 #include <stdarg.h>
36 #include <stddef.h>
37 #include <stdlib.h>
38 #include <stdio.h>
39 #include <errno.h>
40 #include <ctype.h>
41 #ifdef illumos
42 #include <alloca.h>
43 #else
44 #include <sys/sysctl.h>
45 #include <sys/ioctl.h>
46 #include <libproc_compat.h>
47 #endif
48 #include <assert.h>
49 #include <libgen.h>
50 #include <limits.h>
51 #include <stdint.h>
52 
53 #include <dt_impl.h>
54 
55 static const struct {
56 	size_t dtps_offset;
57 	size_t dtps_len;
58 } dtrace_probespecs[] = {
59 	{ offsetof(dtrace_probedesc_t, dtpd_provider),	DTRACE_PROVNAMELEN },
60 	{ offsetof(dtrace_probedesc_t, dtpd_mod),	DTRACE_MODNAMELEN },
61 	{ offsetof(dtrace_probedesc_t, dtpd_func),	DTRACE_FUNCNAMELEN },
62 	{ offsetof(dtrace_probedesc_t, dtpd_name),	DTRACE_NAMELEN }
63 };
64 
65 int
66 dtrace_xstr2desc(dtrace_hdl_t *dtp, dtrace_probespec_t spec,
67     const char *s, int argc, char *const argv[], dtrace_probedesc_t *pdp)
68 {
69 	size_t off, len, vlen, wlen;
70 	const char *p, *q, *v, *w;
71 
72 	char buf[32]; /* for id_t as %d (see below) */
73 
74 	if (spec < DTRACE_PROBESPEC_NONE || spec > DTRACE_PROBESPEC_NAME)
75 		return (dt_set_errno(dtp, EINVAL));
76 
77 	bzero(pdp, sizeof (dtrace_probedesc_t));
78 	p = s + strlen(s) - 1;
79 
80 	do {
81 		for (len = 0; p >= s && *p != ':'; len++)
82 			p--; /* move backward until we find a delimiter */
83 
84 		q = p + 1;
85 		vlen = 0;
86 		w = NULL;
87 		wlen = 0;
88 
89 		if ((v = strchr(q, '$')) != NULL && v < q + len) {
90 			/*
91 			 * Set vlen to the length of the variable name and then
92 			 * reset len to the length of the text prior to '$'. If
93 			 * the name begins with a digit, interpret it using the
94 			 * the argv[] array.  Otherwise we look in dt_macros.
95 			 * For the moment, all dt_macros variables are of type
96 			 * id_t (see dtrace_update() for more details on that).
97 			 */
98 			vlen = (size_t)(q + len - v);
99 			len = (size_t)(v - q);
100 
101 			/*
102 			 * If the variable string begins with $$, skip past the
103 			 * leading dollar sign since $ and $$ are equivalent
104 			 * macro reference operators in a probe description.
105 			 */
106 			if (vlen > 2 && v[1] == '$') {
107 				vlen--;
108 				v++;
109 			}
110 
111 			if (isdigit((unsigned char)v[1])) {
112 				long i;
113 
114 				errno = 0;
115 				i = strtol(v + 1, (char **)&w, 10);
116 
117 				wlen = vlen - (w - v);
118 
119 				if (i < 0 || i >= argc || errno != 0)
120 					return (dt_set_errno(dtp, EDT_BADSPCV));
121 
122 				v = argv[i];
123 				vlen = strlen(v);
124 
125 				if (yypcb != NULL && yypcb->pcb_sargv == argv)
126 					yypcb->pcb_sflagv[i] |= DT_IDFLG_REF;
127 
128 			} else if (vlen > 1) {
129 				char *vstr = alloca(vlen);
130 				dt_ident_t *idp;
131 
132 				(void) strncpy(vstr, v + 1, vlen - 1);
133 				vstr[vlen - 1] = '\0';
134 				idp = dt_idhash_lookup(dtp->dt_macros, vstr);
135 
136 				if (idp == NULL)
137 					return (dt_set_errno(dtp, EDT_BADSPCV));
138 
139 				v = buf;
140 				vlen = snprintf(buf, 32, "%d", idp->di_id);
141 
142 			} else
143 				return (dt_set_errno(dtp, EDT_BADSPCV));
144 		}
145 
146 		if (spec == DTRACE_PROBESPEC_NONE)
147 			return (dt_set_errno(dtp, EDT_BADSPEC));
148 
149 		if (len + vlen >= dtrace_probespecs[spec].dtps_len)
150 			return (dt_set_errno(dtp, ENAMETOOLONG));
151 
152 		off = dtrace_probespecs[spec--].dtps_offset;
153 		bcopy(q, (char *)pdp + off, len);
154 		bcopy(v, (char *)pdp + off + len, vlen);
155 		bcopy(w, (char *)pdp + off + len + vlen, wlen);
156 	} while (--p >= s);
157 
158 	pdp->dtpd_id = DTRACE_IDNONE;
159 	return (0);
160 }
161 
162 int
163 dtrace_str2desc(dtrace_hdl_t *dtp, dtrace_probespec_t spec,
164     const char *s, dtrace_probedesc_t *pdp)
165 {
166 	return (dtrace_xstr2desc(dtp, spec, s, 0, NULL, pdp));
167 }
168 
169 int
170 dtrace_id2desc(dtrace_hdl_t *dtp, dtrace_id_t id, dtrace_probedesc_t *pdp)
171 {
172 	bzero(pdp, sizeof (dtrace_probedesc_t));
173 	pdp->dtpd_id = id;
174 
175 	if (dt_ioctl(dtp, DTRACEIOC_PROBES, pdp) == -1 ||
176 	    pdp->dtpd_id != id)
177 		return (dt_set_errno(dtp, EDT_BADID));
178 
179 	return (0);
180 }
181 
182 char *
183 dtrace_desc2str(const dtrace_probedesc_t *pdp, char *buf, size_t len)
184 {
185 	if (pdp->dtpd_id == 0) {
186 		(void) snprintf(buf, len, "%s:%s:%s:%s", pdp->dtpd_provider,
187 		    pdp->dtpd_mod, pdp->dtpd_func, pdp->dtpd_name);
188 	} else
189 		(void) snprintf(buf, len, "%u", pdp->dtpd_id);
190 
191 	return (buf);
192 }
193 
194 char *
195 dtrace_attr2str(dtrace_attribute_t attr, char *buf, size_t len)
196 {
197 	const char *name = dtrace_stability_name(attr.dtat_name);
198 	const char *data = dtrace_stability_name(attr.dtat_data);
199 	const char *class = dtrace_class_name(attr.dtat_class);
200 
201 	if (name == NULL || data == NULL || class == NULL)
202 		return (NULL); /* one or more invalid attributes */
203 
204 	(void) snprintf(buf, len, "%s/%s/%s", name, data, class);
205 	return (buf);
206 }
207 
208 static char *
209 dt_getstrattr(char *p, char **qp)
210 {
211 	char *q;
212 
213 	if (*p == '\0')
214 		return (NULL);
215 
216 	if ((q = strchr(p, '/')) == NULL)
217 		q = p + strlen(p);
218 	else
219 		*q++ = '\0';
220 
221 	*qp = q;
222 	return (p);
223 }
224 
225 int
226 dtrace_str2attr(const char *str, dtrace_attribute_t *attr)
227 {
228 	dtrace_stability_t s;
229 	dtrace_class_t c;
230 	char *p, *q;
231 
232 	if (str == NULL || attr == NULL)
233 		return (-1); /* invalid function arguments */
234 
235 	*attr = _dtrace_maxattr;
236 	p = alloca(strlen(str) + 1);
237 	(void) strcpy(p, str);
238 
239 	if ((p = dt_getstrattr(p, &q)) == NULL)
240 		return (0);
241 
242 	for (s = 0; s <= DTRACE_STABILITY_MAX; s++) {
243 		if (strcasecmp(p, dtrace_stability_name(s)) == 0) {
244 			attr->dtat_name = s;
245 			break;
246 		}
247 	}
248 
249 	if (s > DTRACE_STABILITY_MAX)
250 		return (-1);
251 
252 	if ((p = dt_getstrattr(q, &q)) == NULL)
253 		return (0);
254 
255 	for (s = 0; s <= DTRACE_STABILITY_MAX; s++) {
256 		if (strcasecmp(p, dtrace_stability_name(s)) == 0) {
257 			attr->dtat_data = s;
258 			break;
259 		}
260 	}
261 
262 	if (s > DTRACE_STABILITY_MAX)
263 		return (-1);
264 
265 	if ((p = dt_getstrattr(q, &q)) == NULL)
266 		return (0);
267 
268 	for (c = 0; c <= DTRACE_CLASS_MAX; c++) {
269 		if (strcasecmp(p, dtrace_class_name(c)) == 0) {
270 			attr->dtat_class = c;
271 			break;
272 		}
273 	}
274 
275 	if (c > DTRACE_CLASS_MAX || (p = dt_getstrattr(q, &q)) != NULL)
276 		return (-1);
277 
278 	return (0);
279 }
280 
281 const char *
282 dtrace_stability_name(dtrace_stability_t s)
283 {
284 	switch (s) {
285 	case DTRACE_STABILITY_INTERNAL:	return ("Internal");
286 	case DTRACE_STABILITY_PRIVATE:	return ("Private");
287 	case DTRACE_STABILITY_OBSOLETE:	return ("Obsolete");
288 	case DTRACE_STABILITY_EXTERNAL:	return ("External");
289 	case DTRACE_STABILITY_UNSTABLE:	return ("Unstable");
290 	case DTRACE_STABILITY_EVOLVING:	return ("Evolving");
291 	case DTRACE_STABILITY_STABLE:	return ("Stable");
292 	case DTRACE_STABILITY_STANDARD:	return ("Standard");
293 	default:			return (NULL);
294 	}
295 }
296 
297 const char *
298 dtrace_class_name(dtrace_class_t c)
299 {
300 	switch (c) {
301 	case DTRACE_CLASS_UNKNOWN:	return ("Unknown");
302 	case DTRACE_CLASS_CPU:		return ("CPU");
303 	case DTRACE_CLASS_PLATFORM:	return ("Platform");
304 	case DTRACE_CLASS_GROUP:	return ("Group");
305 	case DTRACE_CLASS_ISA:		return ("ISA");
306 	case DTRACE_CLASS_COMMON:	return ("Common");
307 	default:			return (NULL);
308 	}
309 }
310 
311 dtrace_attribute_t
312 dt_attr_min(dtrace_attribute_t a1, dtrace_attribute_t a2)
313 {
314 	dtrace_attribute_t am;
315 
316 	am.dtat_name = MIN(a1.dtat_name, a2.dtat_name);
317 	am.dtat_data = MIN(a1.dtat_data, a2.dtat_data);
318 	am.dtat_class = MIN(a1.dtat_class, a2.dtat_class);
319 
320 	return (am);
321 }
322 
323 dtrace_attribute_t
324 dt_attr_max(dtrace_attribute_t a1, dtrace_attribute_t a2)
325 {
326 	dtrace_attribute_t am;
327 
328 	am.dtat_name = MAX(a1.dtat_name, a2.dtat_name);
329 	am.dtat_data = MAX(a1.dtat_data, a2.dtat_data);
330 	am.dtat_class = MAX(a1.dtat_class, a2.dtat_class);
331 
332 	return (am);
333 }
334 
335 /*
336  * Compare two attributes and return an integer value in the following ranges:
337  *
338  * <0 if any of a1's attributes are less than a2's attributes
339  * =0 if all of a1's attributes are equal to a2's attributes
340  * >0 if all of a1's attributes are greater than or equal to a2's attributes
341  *
342  * To implement this function efficiently, we subtract a2's attributes from
343  * a1's to obtain a negative result if an a1 attribute is less than its a2
344  * counterpart.  We then OR the intermediate results together, relying on the
345  * twos-complement property that if any result is negative, the bitwise union
346  * will also be negative since the highest bit will be set in the result.
347  */
348 int
349 dt_attr_cmp(dtrace_attribute_t a1, dtrace_attribute_t a2)
350 {
351 	return (((int)a1.dtat_name - a2.dtat_name) |
352 	    ((int)a1.dtat_data - a2.dtat_data) |
353 	    ((int)a1.dtat_class - a2.dtat_class));
354 }
355 
356 char *
357 dt_attr_str(dtrace_attribute_t a, char *buf, size_t len)
358 {
359 	static const char stability[] = "ipoxuesS";
360 	static const char class[] = "uCpgIc";
361 
362 	if (a.dtat_name < sizeof (stability) &&
363 	    a.dtat_data < sizeof (stability) && a.dtat_class < sizeof (class)) {
364 		(void) snprintf(buf, len, "[%c/%c/%c]", stability[a.dtat_name],
365 		    stability[a.dtat_data], class[a.dtat_class]);
366 	} else {
367 		(void) snprintf(buf, len, "[%u/%u/%u]",
368 		    a.dtat_name, a.dtat_data, a.dtat_class);
369 	}
370 
371 	return (buf);
372 }
373 
374 char *
375 dt_version_num2str(dt_version_t v, char *buf, size_t len)
376 {
377 	uint_t M = DT_VERSION_MAJOR(v);
378 	uint_t m = DT_VERSION_MINOR(v);
379 	uint_t u = DT_VERSION_MICRO(v);
380 
381 	if (u == 0)
382 		(void) snprintf(buf, len, "%u.%u", M, m);
383 	else
384 		(void) snprintf(buf, len, "%u.%u.%u", M, m, u);
385 
386 	return (buf);
387 }
388 
389 int
390 dt_version_str2num(const char *s, dt_version_t *vp)
391 {
392 	int i = 0, n[3] = { 0, 0, 0 };
393 	char c;
394 
395 	while ((c = *s++) != '\0') {
396 		if (isdigit((unsigned char)c))
397 			n[i] = n[i] * 10 + c - '0';
398 		else if (c != '.' || i++ >= sizeof (n) / sizeof (n[0]) - 1)
399 			return (-1);
400 	}
401 
402 	if (n[0] > DT_VERSION_MAJMAX ||
403 	    n[1] > DT_VERSION_MINMAX ||
404 	    n[2] > DT_VERSION_MICMAX)
405 		return (-1);
406 
407 	if (vp != NULL)
408 		*vp = DT_VERSION_NUMBER(n[0], n[1], n[2]);
409 
410 	return (0);
411 }
412 
413 int
414 dt_version_defined(dt_version_t v)
415 {
416 	int i;
417 
418 	for (i = 0; _dtrace_versions[i] != 0; i++) {
419 		if (_dtrace_versions[i] == v)
420 			return (1);
421 	}
422 
423 	return (0);
424 }
425 
426 char *
427 dt_cpp_add_arg(dtrace_hdl_t *dtp, const char *str)
428 {
429 	char *arg;
430 
431 	if (dtp->dt_cpp_argc == dtp->dt_cpp_args) {
432 		int olds = dtp->dt_cpp_args;
433 		int news = olds * 2;
434 		char **argv = realloc(dtp->dt_cpp_argv, sizeof (char *) * news);
435 
436 		if (argv == NULL)
437 			return (NULL);
438 
439 		bzero(&argv[olds], sizeof (char *) * olds);
440 		dtp->dt_cpp_argv = argv;
441 		dtp->dt_cpp_args = news;
442 	}
443 
444 	if ((arg = strdup(str)) == NULL)
445 		return (NULL);
446 
447 	assert(dtp->dt_cpp_argc < dtp->dt_cpp_args);
448 	dtp->dt_cpp_argv[dtp->dt_cpp_argc++] = arg;
449 	return (arg);
450 }
451 
452 char *
453 dt_cpp_pop_arg(dtrace_hdl_t *dtp)
454 {
455 	char *arg;
456 
457 	if (dtp->dt_cpp_argc <= 1)
458 		return (NULL); /* dt_cpp_argv[0] cannot be popped */
459 
460 	arg = dtp->dt_cpp_argv[--dtp->dt_cpp_argc];
461 	dtp->dt_cpp_argv[dtp->dt_cpp_argc] = NULL;
462 
463 	return (arg);
464 }
465 
466 /*PRINTFLIKE1*/
467 void
468 dt_dprintf(const char *format, ...)
469 {
470 	if (_dtrace_debug) {
471 		va_list alist;
472 
473 		va_start(alist, format);
474 		(void) fputs("libdtrace DEBUG: ", stderr);
475 		(void) vfprintf(stderr, format, alist);
476 		va_end(alist);
477 	}
478 }
479 
480 int
481 #ifdef illumos
482 dt_ioctl(dtrace_hdl_t *dtp, int val, void *arg)
483 #else
484 dt_ioctl(dtrace_hdl_t *dtp, u_long val, void *arg)
485 #endif
486 {
487 	const dtrace_vector_t *v = dtp->dt_vector;
488 
489 #ifndef illumos
490 	/* Avoid sign extension. */
491 	val &= 0xffffffff;
492 #endif
493 
494 	if (v != NULL)
495 		return (v->dtv_ioctl(dtp->dt_varg, val, arg));
496 
497 	if (dtp->dt_fd >= 0)
498 		return (ioctl(dtp->dt_fd, val, arg));
499 
500 	errno = EBADF;
501 	return (-1);
502 }
503 
504 int
505 dt_status(dtrace_hdl_t *dtp, processorid_t cpu)
506 {
507 	const dtrace_vector_t *v = dtp->dt_vector;
508 
509 	if (v == NULL) {
510 #ifdef illumos
511 		return (p_online(cpu, P_STATUS));
512 #else
513 		int maxid = 0;
514 		size_t len = sizeof(maxid);
515 		if (sysctlbyname("kern.smp.maxid", &maxid, &len, NULL, 0) != 0)
516 			return (cpu == 0 ? 1 : -1);
517 		else
518 			return (cpu <= maxid ? 1 : -1);
519 #endif
520 	}
521 
522 	return (v->dtv_status(dtp->dt_varg, cpu));
523 }
524 
525 long
526 dt_sysconf(dtrace_hdl_t *dtp, int name)
527 {
528 	const dtrace_vector_t *v = dtp->dt_vector;
529 
530 	if (v == NULL)
531 		return (sysconf(name));
532 
533 	return (v->dtv_sysconf(dtp->dt_varg, name));
534 }
535 
536 /*
537  * Wrapper around write(2) to handle partial writes.  For maximum safety of
538  * output files and proper error reporting, we continuing writing in the
539  * face of partial writes until write(2) fails or 'buf' is completely written.
540  * We also record any errno in the specified dtrace_hdl_t as well as 'errno'.
541  */
542 ssize_t
543 dt_write(dtrace_hdl_t *dtp, int fd, const void *buf, size_t n)
544 {
545 	ssize_t resid = n;
546 	ssize_t len;
547 
548 	while (resid != 0) {
549 		if ((len = write(fd, buf, resid)) <= 0)
550 			break;
551 
552 		resid -= len;
553 		buf = (char *)buf + len;
554 	}
555 
556 	if (resid == n && n != 0)
557 		return (dt_set_errno(dtp, errno));
558 
559 	return (n - resid);
560 }
561 
562 /*
563  * This function handles all output from libdtrace, as well as the
564  * dtrace_sprintf() case.  If we're here due to dtrace_sprintf(), then
565  * dt_sprintf_buflen will be non-zero; in this case, we sprintf into the
566  * specified buffer and return.  Otherwise, if output is buffered (denoted by
567  * a NULL fp), we sprintf the desired output into the buffered buffer
568  * (expanding the buffer if required).  If we don't satisfy either of these
569  * conditions (that is, if we are to actually generate output), then we call
570  * fprintf with the specified fp.  In this case, we need to deal with one of
571  * the more annoying peculiarities of libc's printf routines:  any failed
572  * write persistently sets an error flag inside the FILE causing every
573  * subsequent write to fail, but only the caller that initiated the error gets
574  * the errno.  Since libdtrace clients often intercept SIGINT, this case is
575  * particularly frustrating since we don't want the EINTR on one attempt to
576  * write to the output file to preclude later attempts to write.  This
577  * function therefore does a clearerr() if any error occurred, and saves the
578  * errno for the caller inside the specified dtrace_hdl_t.
579  */
580 /*PRINTFLIKE3*/
581 int
582 dt_printf(dtrace_hdl_t *dtp, FILE *fp, const char *format, ...)
583 {
584 	va_list ap;
585 	int n;
586 
587 #ifndef illumos
588 	/*
589 	 * On FreeBSD, check if output is currently being re-directed
590 	 * to another file. If so, output to that file instead of the
591 	 * one the caller has specified.
592 	 */
593 	if (dtp->dt_freopen_fp != NULL)
594 		fp = dtp->dt_freopen_fp;
595 #endif
596 
597 	va_start(ap, format);
598 
599 	if (dtp->dt_sprintf_buflen != 0) {
600 		int len;
601 		char *buf;
602 
603 		assert(dtp->dt_sprintf_buf != NULL);
604 
605 		buf = &dtp->dt_sprintf_buf[len = strlen(dtp->dt_sprintf_buf)];
606 		len = dtp->dt_sprintf_buflen - len;
607 		assert(len >= 0);
608 
609 		if ((n = vsnprintf(buf, len, format, ap)) < 0)
610 			n = dt_set_errno(dtp, errno);
611 
612 		va_end(ap);
613 
614 		return (n);
615 	}
616 
617 	if (fp == NULL) {
618 		int needed, rval;
619 		size_t avail;
620 
621 		/*
622 		 * Using buffered output is not allowed if a handler has
623 		 * not been installed.
624 		 */
625 		if (dtp->dt_bufhdlr == NULL) {
626 			va_end(ap);
627 			return (dt_set_errno(dtp, EDT_NOBUFFERED));
628 		}
629 
630 		if (dtp->dt_buffered_buf == NULL) {
631 			assert(dtp->dt_buffered_size == 0);
632 			dtp->dt_buffered_size = 1;
633 			dtp->dt_buffered_buf = malloc(dtp->dt_buffered_size);
634 
635 			if (dtp->dt_buffered_buf == NULL) {
636 				va_end(ap);
637 				return (dt_set_errno(dtp, EDT_NOMEM));
638 			}
639 
640 			dtp->dt_buffered_offs = 0;
641 			dtp->dt_buffered_buf[0] = '\0';
642 		}
643 
644 		if ((needed = vsnprintf(NULL, 0, format, ap)) < 0) {
645 			rval = dt_set_errno(dtp, errno);
646 			va_end(ap);
647 			return (rval);
648 		}
649 
650 		if (needed == 0) {
651 			va_end(ap);
652 			return (0);
653 		}
654 
655 		for (;;) {
656 			char *newbuf;
657 
658 			assert(dtp->dt_buffered_offs < dtp->dt_buffered_size);
659 			avail = dtp->dt_buffered_size - dtp->dt_buffered_offs;
660 
661 			if (needed + 1 < avail)
662 				break;
663 
664 			if ((newbuf = realloc(dtp->dt_buffered_buf,
665 			    dtp->dt_buffered_size << 1)) == NULL) {
666 				va_end(ap);
667 				return (dt_set_errno(dtp, EDT_NOMEM));
668 			}
669 
670 			dtp->dt_buffered_buf = newbuf;
671 			dtp->dt_buffered_size <<= 1;
672 		}
673 
674 		if (vsnprintf(&dtp->dt_buffered_buf[dtp->dt_buffered_offs],
675 		    avail, format, ap) < 0) {
676 			rval = dt_set_errno(dtp, errno);
677 			va_end(ap);
678 			return (rval);
679 		}
680 
681 		dtp->dt_buffered_offs += needed;
682 		assert(dtp->dt_buffered_buf[dtp->dt_buffered_offs] == '\0');
683 		va_end(ap);
684 		return (0);
685 	}
686 
687 	n = vfprintf(fp, format, ap);
688 	fflush(fp);
689 	va_end(ap);
690 
691 	if (n < 0) {
692 		clearerr(fp);
693 		return (dt_set_errno(dtp, errno));
694 	}
695 
696 	return (n);
697 }
698 
699 int
700 dt_buffered_flush(dtrace_hdl_t *dtp, dtrace_probedata_t *pdata,
701     const dtrace_recdesc_t *rec, const dtrace_aggdata_t *agg, uint32_t flags)
702 {
703 	dtrace_bufdata_t data;
704 
705 	if (dtp->dt_buffered_offs == 0)
706 		return (0);
707 
708 	data.dtbda_handle = dtp;
709 	data.dtbda_buffered = dtp->dt_buffered_buf;
710 	data.dtbda_probe = pdata;
711 	data.dtbda_recdesc = rec;
712 	data.dtbda_aggdata = agg;
713 	data.dtbda_flags = flags;
714 
715 	if ((*dtp->dt_bufhdlr)(&data, dtp->dt_bufarg) == DTRACE_HANDLE_ABORT)
716 		return (dt_set_errno(dtp, EDT_DIRABORT));
717 
718 	dtp->dt_buffered_offs = 0;
719 	dtp->dt_buffered_buf[0] = '\0';
720 
721 	return (0);
722 }
723 
724 void
725 dt_buffered_destroy(dtrace_hdl_t *dtp)
726 {
727 	free(dtp->dt_buffered_buf);
728 	dtp->dt_buffered_buf = NULL;
729 	dtp->dt_buffered_offs = 0;
730 	dtp->dt_buffered_size = 0;
731 }
732 
733 void *
734 dt_zalloc(dtrace_hdl_t *dtp, size_t size)
735 {
736 	void *data;
737 
738 	if ((data = malloc(size)) == NULL)
739 		(void) dt_set_errno(dtp, EDT_NOMEM);
740 	else
741 		bzero(data, size);
742 
743 	return (data);
744 }
745 
746 void *
747 dt_alloc(dtrace_hdl_t *dtp, size_t size)
748 {
749 	void *data;
750 
751 	if ((data = malloc(size)) == NULL)
752 		(void) dt_set_errno(dtp, EDT_NOMEM);
753 
754 	return (data);
755 }
756 
757 void
758 dt_free(dtrace_hdl_t *dtp, void *data)
759 {
760 	assert(dtp != NULL); /* ensure sane use of this interface */
761 	free(data);
762 }
763 
764 void
765 dt_difo_free(dtrace_hdl_t *dtp, dtrace_difo_t *dp)
766 {
767 	if (dp == NULL)
768 		return; /* simplify caller code */
769 
770 	dt_free(dtp, dp->dtdo_buf);
771 	dt_free(dtp, dp->dtdo_inttab);
772 	dt_free(dtp, dp->dtdo_strtab);
773 	dt_free(dtp, dp->dtdo_vartab);
774 	dt_free(dtp, dp->dtdo_kreltab);
775 	dt_free(dtp, dp->dtdo_ureltab);
776 	dt_free(dtp, dp->dtdo_xlmtab);
777 
778 	dt_free(dtp, dp);
779 }
780 
781 /*
782  * dt_gmatch() is similar to gmatch(3GEN) and dtrace(7D) globbing, but also
783  * implements the behavior that an empty pattern matches any string.
784  */
785 int
786 dt_gmatch(const char *s, const char *p)
787 {
788 	return (p == NULL || *p == '\0' || gmatch(s, p));
789 }
790 
791 char *
792 dt_basename(char *str)
793 {
794 	char *last = strrchr(str, '/');
795 
796 	if (last == NULL)
797 		return (str);
798 
799 	return (last + 1);
800 }
801 
802 /*
803  * dt_popc() is a fast implementation of population count.  The algorithm is
804  * from "Hacker's Delight" by Henry Warren, Jr with a 64-bit equivalent added.
805  */
806 ulong_t
807 dt_popc(ulong_t x)
808 {
809 #if defined(_ILP32)
810 	x = x - ((x >> 1) & 0x55555555UL);
811 	x = (x & 0x33333333UL) + ((x >> 2) & 0x33333333UL);
812 	x = (x + (x >> 4)) & 0x0F0F0F0FUL;
813 	x = x + (x >> 8);
814 	x = x + (x >> 16);
815 	return (x & 0x3F);
816 #elif defined(_LP64)
817 	x = x - ((x >> 1) & 0x5555555555555555ULL);
818 	x = (x & 0x3333333333333333ULL) + ((x >> 2) & 0x3333333333333333ULL);
819 	x = (x + (x >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
820 	x = x + (x >> 8);
821 	x = x + (x >> 16);
822 	x = x + (x >> 32);
823 	return (x & 0x7F);
824 #else
825 /* This should be a #warning but for now ignore error. Err: "need td_popc() implementation" */
826 #endif
827 }
828 
829 /*
830  * dt_popcb() is a bitmap-based version of population count that returns the
831  * number of one bits in the specified bitmap 'bp' at bit positions below 'n'.
832  */
833 ulong_t
834 dt_popcb(const ulong_t *bp, ulong_t n)
835 {
836 	ulong_t maxb = n & BT_ULMASK;
837 	ulong_t maxw = n >> BT_ULSHIFT;
838 	ulong_t w, popc = 0;
839 
840 	if (n == 0)
841 		return (0);
842 
843 	for (w = 0; w < maxw; w++)
844 		popc += dt_popc(bp[w]);
845 
846 	return (popc + dt_popc(bp[maxw] & ((1UL << maxb) - 1)));
847 }
848 
849 #ifdef illumos
850 struct _rwlock;
851 struct _lwp_mutex;
852 
853 int
854 dt_rw_read_held(pthread_rwlock_t *lock)
855 {
856 	extern int _rw_read_held(struct _rwlock *);
857 	return (_rw_read_held((struct _rwlock *)lock));
858 }
859 
860 int
861 dt_rw_write_held(pthread_rwlock_t *lock)
862 {
863 	extern int _rw_write_held(struct _rwlock *);
864 	return (_rw_write_held((struct _rwlock *)lock));
865 }
866 #endif
867 
868 int
869 dt_mutex_held(pthread_mutex_t *lock)
870 {
871 #ifdef illumos
872 	extern int _mutex_held(struct _lwp_mutex *);
873 	return (_mutex_held((struct _lwp_mutex *)lock));
874 #else
875 	return (1);
876 #endif
877 }
878 
879 static int
880 dt_string2str(char *s, char *str, int nbytes)
881 {
882 	int len = strlen(s);
883 
884 	if (nbytes == 0) {
885 		/*
886 		 * Like snprintf(3C), we don't check the value of str if the
887 		 * number of bytes is 0.
888 		 */
889 		return (len);
890 	}
891 
892 	if (nbytes <= len) {
893 		(void) strncpy(str, s, nbytes - 1);
894 		/*
895 		 * Like snprintf(3C) (and unlike strncpy(3C)), we guarantee
896 		 * that the string is null-terminated.
897 		 */
898 		str[nbytes - 1] = '\0';
899 	} else {
900 		(void) strcpy(str, s);
901 	}
902 
903 	return (len);
904 }
905 
906 int
907 dtrace_addr2str(dtrace_hdl_t *dtp, uint64_t addr, char *str, int nbytes)
908 {
909 	dtrace_syminfo_t dts;
910 	GElf_Sym sym;
911 
912 	size_t n = 20; /* for 0x%llx\0 */
913 	char *s;
914 	int err;
915 
916 	if ((err = dtrace_lookup_by_addr(dtp, addr, &sym, &dts)) == 0)
917 		n += strlen(dts.dts_object) + strlen(dts.dts_name) + 2; /* +` */
918 
919 	s = alloca(n);
920 
921 	if (err == 0 && addr != sym.st_value) {
922 		(void) snprintf(s, n, "%s`%s+0x%llx", dts.dts_object,
923 		    dts.dts_name, (unsigned long long)addr - sym.st_value);
924 	} else if (err == 0) {
925 		(void) snprintf(s, n, "%s`%s",
926 		    dts.dts_object, dts.dts_name);
927 	} else {
928 		/*
929 		 * We'll repeat the lookup, but this time we'll specify a NULL
930 		 * GElf_Sym -- indicating that we're only interested in the
931 		 * containing module.
932 		 */
933 		if (dtrace_lookup_by_addr(dtp, addr, NULL, &dts) == 0) {
934 			(void) snprintf(s, n, "%s`0x%llx", dts.dts_object,
935 			    (unsigned long long)addr);
936 		} else {
937 			(void) snprintf(s, n, "0x%llx", (unsigned long long)addr);
938 		}
939 	}
940 
941 	return (dt_string2str(s, str, nbytes));
942 }
943 
944 int
945 dtrace_uaddr2str(dtrace_hdl_t *dtp, pid_t pid,
946     uint64_t addr, char *str, int nbytes)
947 {
948 	char name[PATH_MAX], objname[PATH_MAX], c[PATH_MAX * 2];
949 	struct ps_prochandle *P = NULL;
950 	GElf_Sym sym;
951 	char *obj;
952 
953 	if (pid != 0)
954 		P = dt_proc_grab(dtp, pid, PGRAB_RDONLY | PGRAB_FORCE, 0);
955 
956 	if (P == NULL) {
957 	  (void) snprintf(c, sizeof (c), "0x%jx", (uintmax_t)addr);
958 		return (dt_string2str(c, str, nbytes));
959 	}
960 
961 	dt_proc_lock(dtp, P);
962 
963 	if (Plookup_by_addr(P, addr, name, sizeof (name), &sym) == 0) {
964 		(void) Pobjname(P, addr, objname, sizeof (objname));
965 
966 		obj = dt_basename(objname);
967 
968 		if (addr > sym.st_value) {
969 			(void) snprintf(c, sizeof (c), "%s`%s+0x%llx", obj,
970 			    name, (unsigned long long)(addr - sym.st_value));
971 		} else {
972 			(void) snprintf(c, sizeof (c), "%s`%s", obj, name);
973 		}
974 	} else if (Pobjname(P, addr, objname, sizeof (objname)) != 0) {
975 		(void) snprintf(c, sizeof (c), "%s`0x%jx",
976 				dt_basename(objname), (uintmax_t)addr);
977 	} else {
978 	  (void) snprintf(c, sizeof (c), "0x%jx", (uintmax_t)addr);
979 	}
980 
981 	dt_proc_unlock(dtp, P);
982 	dt_proc_release(dtp, P);
983 
984 	return (dt_string2str(c, str, nbytes));
985 }
986