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