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