dt_subr.c revision 262067
197318Sphk/*
297318Sphk * CDDL HEADER START
397318Sphk *
497318Sphk * The contents of this file are subject to the terms of the
597318Sphk * Common Development and Distribution License (the "License").
697318Sphk * You may not use this file except in compliance with the License.
797318Sphk *
897318Sphk * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
997318Sphk * or http://www.opensolaris.org/os/licensing.
1097318Sphk * See the License for the specific language governing permissions
1197318Sphk * and limitations under the License.
1297318Sphk *
1397318Sphk * When distributing Covered Code, include this CDDL HEADER in each
1497318Sphk * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
1597318Sphk * If applicable, add the following below this CDDL HEADER, with the
1697318Sphk * fields enclosed by brackets "[]" replaced with your own identifying
1797318Sphk * information: Portions Copyright [yyyy] [name of copyright owner]
1897318Sphk *
1997318Sphk * CDDL HEADER END
2097318Sphk */
2197318Sphk
2297318Sphk/*
2397318Sphk * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
2497318Sphk * Copyright (c) 2012 by Delphix. All rights reserved.
2597318Sphk * Use is subject to license terms.
2697318Sphk */
2797318Sphk
2897318Sphk#if defined(sun)
2997318Sphk#include <sys/sysmacros.h>
3097318Sphk#endif
3197318Sphk#include <sys/isa_defs.h>
3297318Sphk
3397318Sphk#include <strings.h>
34139778Simp#include <unistd.h>
35139778Simp#include <stdarg.h>
36139778Simp#include <stddef.h>
3797318Sphk#include <stdlib.h>
3897318Sphk#include <stdio.h>
3997318Sphk#include <errno.h>
4097318Sphk#include <ctype.h>
4197318Sphk#if defined(sun)
4297318Sphk#include <alloca.h>
43116196Sobrien#else
44116196Sobrien#include <sys/sysctl.h>
45116196Sobrien#include <libproc_compat.h>
4697318Sphk#endif
4797318Sphk#include <assert.h>
4897318Sphk#include <libgen.h>
4997318Sphk#include <limits.h>
5097318Sphk#include <stdint.h>
5197318Sphk
5297318Sphk#include <dt_impl.h>
5397318Sphk
5498987Sphkstatic const struct {
55104087Sphk	size_t dtps_offset;
5698987Sphk	size_t dtps_len;
5797318Sphk} dtrace_probespecs[] = {
5897318Sphk	{ offsetof(dtrace_probedesc_t, dtpd_provider),	DTRACE_PROVNAMELEN },
5997318Sphk	{ offsetof(dtrace_probedesc_t, dtpd_mod),	DTRACE_MODNAMELEN },
60143418Sume	{ offsetof(dtrace_probedesc_t, dtpd_func),	DTRACE_FUNCNAMELEN },
6197318Sphk	{ offsetof(dtrace_probedesc_t, dtpd_name),	DTRACE_NAMELEN }
6297318Sphk};
6397318Sphk
6498987Sphkint
6598987Sphkdtrace_xstr2desc(dtrace_hdl_t *dtp, dtrace_probespec_t spec,
66107953Sphk    const char *s, int argc, char *const argv[], dtrace_probedesc_t *pdp)
67107953Sphk{
68107953Sphk	size_t off, len, vlen, wlen;
6997318Sphk	const char *p, *q, *v, *w;
7097318Sphk
7197318Sphk	char buf[32]; /* for id_t as %d (see below) */
7298987Sphk
7398987Sphk	if (spec < DTRACE_PROBESPEC_NONE || spec > DTRACE_PROBESPEC_NAME)
7498987Sphk		return (dt_set_errno(dtp, EINVAL));
7598987Sphk
7698987Sphk	bzero(pdp, sizeof (dtrace_probedesc_t));
7797318Sphk	p = s + strlen(s) - 1;
7897318Sphk
7997318Sphk	do {
8098987Sphk		for (len = 0; p >= s && *p != ':'; len++)
8197318Sphk			p--; /* move backward until we find a delimiter */
8297318Sphk
8398987Sphk		q = p + 1;
8498987Sphk		vlen = 0;
8598987Sphk		w = NULL;
8698987Sphk		wlen = 0;
8798987Sphk
8898987Sphk		if ((v = strchr(q, '$')) != NULL && v < q + len) {
8998987Sphk			/*
9098987Sphk			 * Set vlen to the length of the variable name and then
9198987Sphk			 * reset len to the length of the text prior to '$'. If
9298987Sphk			 * the name begins with a digit, interpret it using the
9398987Sphk			 * the argv[] array.  Otherwise we look in dt_macros.
9498987Sphk			 * For the moment, all dt_macros variables are of type
9598987Sphk			 * id_t (see dtrace_update() for more details on that).
9698987Sphk			 */
9797318Sphk			vlen = (size_t)(q + len - v);
9898987Sphk			len = (size_t)(v - q);
9998987Sphk
10098987Sphk			/*
10198987Sphk			 * If the variable string begins with $$, skip past the
10298987Sphk			 * leading dollar sign since $ and $$ are equivalent
10398987Sphk			 * macro reference operators in a probe description.
10498987Sphk			 */
10598987Sphk			if (vlen > 2 && v[1] == '$') {
10698987Sphk				vlen--;
10798987Sphk				v++;
10898987Sphk			}
10998987Sphk
11098987Sphk			if (isdigit(v[1])) {
11198987Sphk				long i;
11298987Sphk
11398987Sphk				errno = 0;
11498987Sphk				i = strtol(v + 1, (char **)&w, 10);
11598987Sphk
11698987Sphk				wlen = vlen - (w - v);
11798987Sphk
11898987Sphk				if (i < 0 || i >= argc || errno != 0)
11998987Sphk					return (dt_set_errno(dtp, EDT_BADSPCV));
12098987Sphk
12198987Sphk				v = argv[i];
12298987Sphk				vlen = strlen(v);
12398987Sphk
12498987Sphk				if (yypcb != NULL && yypcb->pcb_sargv == argv)
12598987Sphk					yypcb->pcb_sflagv[i] |= DT_IDFLG_REF;
12698987Sphk
12798987Sphk			} else if (vlen > 1) {
12898987Sphk				char *vstr = alloca(vlen);
12998987Sphk				dt_ident_t *idp;
13098987Sphk
13198987Sphk				(void) strncpy(vstr, v + 1, vlen - 1);
13298987Sphk				vstr[vlen - 1] = '\0';
13398987Sphk				idp = dt_idhash_lookup(dtp->dt_macros, vstr);
13497318Sphk
13597318Sphk				if (idp == NULL)
13697318Sphk					return (dt_set_errno(dtp, EDT_BADSPCV));
13797318Sphk
13897318Sphk				v = buf;
13998987Sphk				vlen = snprintf(buf, 32, "%d", idp->di_id);
14098987Sphk
14197318Sphk			} else
14297318Sphk				return (dt_set_errno(dtp, EDT_BADSPCV));
14397318Sphk		}
144111119Simp
14597318Sphk		if (spec == DTRACE_PROBESPEC_NONE)
14697318Sphk			return (dt_set_errno(dtp, EDT_BADSPEC));
14797318Sphk
14898987Sphk		if (len + vlen >= dtrace_probespecs[spec].dtps_len)
14997318Sphk			return (dt_set_errno(dtp, ENAMETOOLONG));
15098987Sphk
15198987Sphk		off = dtrace_probespecs[spec--].dtps_offset;
15297318Sphk		bcopy(q, (char *)pdp + off, len);
15398987Sphk		bcopy(v, (char *)pdp + off + len, vlen);
15497318Sphk		bcopy(w, (char *)pdp + off + len + vlen, wlen);
15598987Sphk	} while (--p >= s);
15698987Sphk
15798987Sphk	pdp->dtpd_id = DTRACE_IDNONE;
15897318Sphk	return (0);
15997318Sphk}
16097318Sphk
16197318Sphkint
16297318Sphkdtrace_str2desc(dtrace_hdl_t *dtp, dtrace_probespec_t spec,
16397318Sphk    const char *s, dtrace_probedesc_t *pdp)
16497318Sphk{
16598987Sphk	return (dtrace_xstr2desc(dtp, spec, s, 0, NULL, pdp));
16697318Sphk}
16797318Sphk
16897318Sphkint
16997318Sphkdtrace_id2desc(dtrace_hdl_t *dtp, dtrace_id_t id, dtrace_probedesc_t *pdp)
17097318Sphk{
17197318Sphk	bzero(pdp, sizeof (dtrace_probedesc_t));
17297318Sphk	pdp->dtpd_id = id;
17397318Sphk
17497318Sphk	if (dt_ioctl(dtp, DTRACEIOC_PROBES, pdp) == -1 ||
17597318Sphk	    pdp->dtpd_id != id)
17697318Sphk		return (dt_set_errno(dtp, EDT_BADID));
17797318Sphk
17898987Sphk	return (0);
17998987Sphk}
18097318Sphk
18197318Sphkchar *
18297318Sphkdtrace_desc2str(const dtrace_probedesc_t *pdp, char *buf, size_t len)
18397318Sphk{
18497318Sphk	if (pdp->dtpd_id == 0) {
18597318Sphk		(void) snprintf(buf, len, "%s:%s:%s:%s", pdp->dtpd_provider,
18697318Sphk		    pdp->dtpd_mod, pdp->dtpd_func, pdp->dtpd_name);
187104057Sphk	} else
188104195Sphk		(void) snprintf(buf, len, "%u", pdp->dtpd_id);
189104057Sphk
190104057Sphk	return (buf);
19197318Sphk}
19297318Sphk
19397318Sphkchar *
19497318Sphkdtrace_attr2str(dtrace_attribute_t attr, char *buf, size_t len)
19597318Sphk{
19697318Sphk	const char *name = dtrace_stability_name(attr.dtat_name);
197104057Sphk	const char *data = dtrace_stability_name(attr.dtat_data);
198104195Sphk	const char *class = dtrace_class_name(attr.dtat_class);
199104057Sphk
200104057Sphk	if (name == NULL || data == NULL || class == NULL)
20197318Sphk		return (NULL); /* one or more invalid attributes */
20297318Sphk
203111119Simp	(void) snprintf(buf, len, "%s/%s/%s", name, data, class);
20497318Sphk	return (buf);
20597318Sphk}
20697318Sphk
20797318Sphkstatic char *
20898987Sphkdt_getstrattr(char *p, char **qp)
20997318Sphk{
21098987Sphk	char *q;
21198987Sphk
21297318Sphk	if (*p == '\0')
21397318Sphk		return (NULL);
21498987Sphk
21597318Sphk	if ((q = strchr(p, '/')) == NULL)
21698987Sphk		q = p + strlen(p);
21797318Sphk	else
21897318Sphk		*q++ = '\0';
21997318Sphk
22097318Sphk	*qp = q;
221104057Sphk	return (p);
222104195Sphk}
223104057Sphk
224104057Sphkint
22597318Sphkdtrace_str2attr(const char *str, dtrace_attribute_t *attr)
22697318Sphk{
22797318Sphk	dtrace_stability_t s;
22897318Sphk	dtrace_class_t c;
22997318Sphk	char *p, *q;
230104195Sphk
23197318Sphk	if (str == NULL || attr == NULL)
23297318Sphk		return (-1); /* invalid function arguments */
23397318Sphk
23497318Sphk	*attr = _dtrace_maxattr;
23597318Sphk	p = alloca(strlen(str) + 1);
23697318Sphk	(void) strcpy(p, str);
23797318Sphk
23897318Sphk	if ((p = dt_getstrattr(p, &q)) == NULL)
23997318Sphk		return (0);
24098987Sphk
24197318Sphk	for (s = 0; s <= DTRACE_STABILITY_MAX; s++) {
24297318Sphk		if (strcasecmp(p, dtrace_stability_name(s)) == 0) {
24397318Sphk			attr->dtat_name = s;
24497318Sphk			break;
24597318Sphk		}
24698987Sphk	}
247249148Smav
24898987Sphk	if (s > DTRACE_STABILITY_MAX)
249114532Sphk		return (-1);
25097318Sphk
25197318Sphk	if ((p = dt_getstrattr(q, &q)) == NULL)
25297318Sphk		return (0);
25397318Sphk
25497318Sphk	for (s = 0; s <= DTRACE_STABILITY_MAX; s++) {
25597318Sphk		if (strcasecmp(p, dtrace_stability_name(s)) == 0) {
25697318Sphk			attr->dtat_data = s;
25797318Sphk			break;
25897318Sphk		}
25997318Sphk	}
26097318Sphk
26197318Sphk	if (s > DTRACE_STABILITY_MAX)
26297318Sphk		return (-1);
26397318Sphk
26497318Sphk	if ((p = dt_getstrattr(q, &q)) == NULL)
26597318Sphk		return (0);
26697318Sphk
267125755Sphk	for (c = 0; c <= DTRACE_CLASS_MAX; c++) {
26897318Sphk		if (strcasecmp(p, dtrace_class_name(c)) == 0) {
26997318Sphk			attr->dtat_class = c;
27097318Sphk			break;
27197318Sphk		}
27297318Sphk	}
27397318Sphk
27497318Sphk	if (c > DTRACE_CLASS_MAX || (p = dt_getstrattr(q, &q)) != NULL)
27597318Sphk		return (-1);
27697318Sphk
27797318Sphk	return (0);
27897318Sphk}
27997318Sphk
28097318Sphkconst char *
28197318Sphkdtrace_stability_name(dtrace_stability_t s)
28297318Sphk{
28397318Sphk	switch (s) {
28497318Sphk	case DTRACE_STABILITY_INTERNAL:	return ("Internal");
28597318Sphk	case DTRACE_STABILITY_PRIVATE:	return ("Private");
286125755Sphk	case DTRACE_STABILITY_OBSOLETE:	return ("Obsolete");
28797318Sphk	case DTRACE_STABILITY_EXTERNAL:	return ("External");
28898066Sphk	case DTRACE_STABILITY_UNSTABLE:	return ("Unstable");
28997318Sphk	case DTRACE_STABILITY_EVOLVING:	return ("Evolving");
29097318Sphk	case DTRACE_STABILITY_STABLE:	return ("Stable");
29197318Sphk	case DTRACE_STABILITY_STANDARD:	return ("Standard");
29297318Sphk	default:			return (NULL);
29397318Sphk	}
294104064Sphk}
295114491Sphk
29697318Sphkconst char *
29797318Sphkdtrace_class_name(dtrace_class_t c)
298105551Sphk{
299105551Sphk	switch (c) {
300152971Ssobomax	case DTRACE_CLASS_UNKNOWN:	return ("Unknown");
301152967Ssobomax	case DTRACE_CLASS_CPU:		return ("CPU");
30297318Sphk	case DTRACE_CLASS_PLATFORM:	return ("Platform");
30397318Sphk	case DTRACE_CLASS_GROUP:	return ("Group");
304111119Simp	case DTRACE_CLASS_ISA:		return ("ISA");
30598987Sphk	case DTRACE_CLASS_COMMON:	return ("Common");
30698987Sphk	default:			return (NULL);
30798987Sphk	}
30898987Sphk}
30998987Sphk
31098987Sphkdtrace_attribute_t
31198987Sphkdt_attr_min(dtrace_attribute_t a1, dtrace_attribute_t a2)
31298987Sphk{
31398987Sphk	dtrace_attribute_t am;
31498987Sphk
31597318Sphk	am.dtat_name = MIN(a1.dtat_name, a2.dtat_name);
31698987Sphk	am.dtat_data = MIN(a1.dtat_data, a2.dtat_data);
317114532Sphk	am.dtat_class = MIN(a1.dtat_class, a2.dtat_class);
31897318Sphk
31997318Sphk	return (am);
32097318Sphk}
32197318Sphk
32298987Sphkdtrace_attribute_t
32398987Sphkdt_attr_max(dtrace_attribute_t a1, dtrace_attribute_t a2)
32498987Sphk{
32598987Sphk	dtrace_attribute_t am;
32698987Sphk
327104087Sphk	am.dtat_name = MAX(a1.dtat_name, a2.dtat_name);
32898987Sphk	am.dtat_data = MAX(a1.dtat_data, a2.dtat_data);
32998987Sphk	am.dtat_class = MAX(a1.dtat_class, a2.dtat_class);
33098987Sphk
33198987Sphk	return (am);
33298987Sphk}
33398987Sphk
33498987Sphk/*
33598987Sphk * Compare two attributes and return an integer value in the following ranges:
336104087Sphk *
33798987Sphk * <0 if any of a1's attributes are less than a2's attributes
33898987Sphk * =0 if all of a1's attributes are equal to a2's attributes
33998987Sphk * >0 if all of a1's attributes are greater than or equal to a2's attributes
34098987Sphk *
34198987Sphk * To implement this function efficiently, we subtract a2's attributes from
34298987Sphk * a1's to obtain a negative result if an a1 attribute is less than its a2
34398987Sphk * counterpart.  We then OR the intermediate results together, relying on the
344104064Sphk * twos-complement property that if any result is negative, the bitwise union
345244547Sjh * will also be negative since the highest bit will be set in the result.
34697318Sphk */
347105551Sphkint
34897318Sphkdt_attr_cmp(dtrace_attribute_t a1, dtrace_attribute_t a2)
349104064Sphk{
350114491Sphk	return (((int)a1.dtat_name - a2.dtat_name) |
351104064Sphk	    ((int)a1.dtat_data - a2.dtat_data) |
35297318Sphk	    ((int)a1.dtat_class - a2.dtat_class));
35397318Sphk}
354125755Sphk
35597318Sphkchar *
35697318Sphkdt_attr_str(dtrace_attribute_t a, char *buf, size_t len)
35798066Sphk{
35897318Sphk	static const char stability[] = "ipoxuesS";
35997318Sphk	static const char class[] = "uCpgIc";
36097318Sphk
36197318Sphk	if (a.dtat_name < sizeof (stability) &&
36297318Sphk	    a.dtat_data < sizeof (stability) && a.dtat_class < sizeof (class)) {
36397318Sphk		(void) snprintf(buf, len, "[%c/%c/%c]", stability[a.dtat_name],
364112552Sphk		    stability[a.dtat_data], class[a.dtat_class]);
365133318Sphk	} else {
366112552Sphk		(void) snprintf(buf, len, "[%u/%u/%u]",
367133314Sphk		    a.dtat_name, a.dtat_data, a.dtat_class);
368133314Sphk	}
369133314Sphk
370133314Sphk	return (buf);
37197318Sphk}
37297318Sphk
37397318Sphkchar *
374dt_version_num2str(dt_version_t v, char *buf, size_t len)
375{
376	uint_t M = DT_VERSION_MAJOR(v);
377	uint_t m = DT_VERSION_MINOR(v);
378	uint_t u = DT_VERSION_MICRO(v);
379
380	if (u == 0)
381		(void) snprintf(buf, len, "%u.%u", M, m);
382	else
383		(void) snprintf(buf, len, "%u.%u.%u", M, m, u);
384
385	return (buf);
386}
387
388int
389dt_version_str2num(const char *s, dt_version_t *vp)
390{
391	int i = 0, n[3] = { 0, 0, 0 };
392	char c;
393
394	while ((c = *s++) != '\0') {
395		if (isdigit(c))
396			n[i] = n[i] * 10 + c - '0';
397		else if (c != '.' || i++ >= sizeof (n) / sizeof (n[0]) - 1)
398			return (-1);
399	}
400
401	if (n[0] > DT_VERSION_MAJMAX ||
402	    n[1] > DT_VERSION_MINMAX ||
403	    n[2] > DT_VERSION_MICMAX)
404		return (-1);
405
406	if (vp != NULL)
407		*vp = DT_VERSION_NUMBER(n[0], n[1], n[2]);
408
409	return (0);
410}
411
412int
413dt_version_defined(dt_version_t v)
414{
415	int i;
416
417	for (i = 0; _dtrace_versions[i] != 0; i++) {
418		if (_dtrace_versions[i] == v)
419			return (1);
420	}
421
422	return (0);
423}
424
425char *
426dt_cpp_add_arg(dtrace_hdl_t *dtp, const char *str)
427{
428	char *arg;
429
430	if (dtp->dt_cpp_argc == dtp->dt_cpp_args) {
431		int olds = dtp->dt_cpp_args;
432		int news = olds * 2;
433		char **argv = realloc(dtp->dt_cpp_argv, sizeof (char *) * news);
434
435		if (argv == NULL)
436			return (NULL);
437
438		bzero(&argv[olds], sizeof (char *) * olds);
439		dtp->dt_cpp_argv = argv;
440		dtp->dt_cpp_args = news;
441	}
442
443	if ((arg = strdup(str)) == NULL)
444		return (NULL);
445
446	assert(dtp->dt_cpp_argc < dtp->dt_cpp_args);
447	dtp->dt_cpp_argv[dtp->dt_cpp_argc++] = arg;
448	return (arg);
449}
450
451char *
452dt_cpp_pop_arg(dtrace_hdl_t *dtp)
453{
454	char *arg;
455
456	if (dtp->dt_cpp_argc <= 1)
457		return (NULL); /* dt_cpp_argv[0] cannot be popped */
458
459	arg = dtp->dt_cpp_argv[--dtp->dt_cpp_argc];
460	dtp->dt_cpp_argv[dtp->dt_cpp_argc] = NULL;
461
462	return (arg);
463}
464
465/*PRINTFLIKE1*/
466void
467dt_dprintf(const char *format, ...)
468{
469	if (_dtrace_debug) {
470		va_list alist;
471
472		va_start(alist, format);
473		(void) fputs("libdtrace DEBUG: ", stderr);
474		(void) vfprintf(stderr, format, alist);
475		va_end(alist);
476	}
477}
478
479int
480#if defined(sun)
481dt_ioctl(dtrace_hdl_t *dtp, int val, void *arg)
482#else
483dt_ioctl(dtrace_hdl_t *dtp, u_long val, void *arg)
484#endif
485{
486	const dtrace_vector_t *v = dtp->dt_vector;
487
488#if !defined(sun)
489	/* Avoid sign extension. */
490	val &= 0xffffffff;
491#endif
492
493	if (v != NULL)
494		return (v->dtv_ioctl(dtp->dt_varg, val, arg));
495
496	if (dtp->dt_fd >= 0)
497		return (ioctl(dtp->dt_fd, val, arg));
498
499	errno = EBADF;
500	return (-1);
501}
502
503int
504dt_status(dtrace_hdl_t *dtp, processorid_t cpu)
505{
506	const dtrace_vector_t *v = dtp->dt_vector;
507
508	if (v == NULL) {
509#if defined(sun)
510		return (p_online(cpu, P_STATUS));
511#else
512		int maxid = 0;
513		size_t len = sizeof(maxid);
514		if (sysctlbyname("kern.smp.maxid", &maxid, &len, NULL, 0) != 0)
515			return (cpu == 0 ? 1 : -1);
516		else
517			return (cpu <= maxid ? 1 : -1);
518#endif
519	}
520
521	return (v->dtv_status(dtp->dt_varg, cpu));
522}
523
524long
525dt_sysconf(dtrace_hdl_t *dtp, int name)
526{
527	const dtrace_vector_t *v = dtp->dt_vector;
528
529	if (v == NULL)
530		return (sysconf(name));
531
532	return (v->dtv_sysconf(dtp->dt_varg, name));
533}
534
535/*
536 * Wrapper around write(2) to handle partial writes.  For maximum safety of
537 * output files and proper error reporting, we continuing writing in the
538 * face of partial writes until write(2) fails or 'buf' is completely written.
539 * We also record any errno in the specified dtrace_hdl_t as well as 'errno'.
540 */
541ssize_t
542dt_write(dtrace_hdl_t *dtp, int fd, const void *buf, size_t n)
543{
544	ssize_t resid = n;
545	ssize_t len;
546
547	while (resid != 0) {
548		if ((len = write(fd, buf, resid)) <= 0)
549			break;
550
551		resid -= len;
552		buf = (char *)buf + len;
553	}
554
555	if (resid == n && n != 0)
556		return (dt_set_errno(dtp, errno));
557
558	return (n - resid);
559}
560
561/*
562 * This function handles all output from libdtrace, as well as the
563 * dtrace_sprintf() case.  If we're here due to dtrace_sprintf(), then
564 * dt_sprintf_buflen will be non-zero; in this case, we sprintf into the
565 * specified buffer and return.  Otherwise, if output is buffered (denoted by
566 * a NULL fp), we sprintf the desired output into the buffered buffer
567 * (expanding the buffer if required).  If we don't satisfy either of these
568 * conditions (that is, if we are to actually generate output), then we call
569 * fprintf with the specified fp.  In this case, we need to deal with one of
570 * the more annoying peculiarities of libc's printf routines:  any failed
571 * write persistently sets an error flag inside the FILE causing every
572 * subsequent write to fail, but only the caller that initiated the error gets
573 * the errno.  Since libdtrace clients often intercept SIGINT, this case is
574 * particularly frustrating since we don't want the EINTR on one attempt to
575 * write to the output file to preclude later attempts to write.  This
576 * function therefore does a clearerr() if any error occurred, and saves the
577 * errno for the caller inside the specified dtrace_hdl_t.
578 */
579/*PRINTFLIKE3*/
580int
581dt_printf(dtrace_hdl_t *dtp, FILE *fp, const char *format, ...)
582{
583	va_list ap;
584	int n;
585
586#if !defined(sun)
587	/*
588	 * On FreeBSD, check if output is currently being re-directed
589	 * to another file. If so, output to that file instead of the
590	 * one the caller has specified.
591	 */
592	if (dtp->dt_freopen_fp != NULL)
593		fp = dtp->dt_freopen_fp;
594#endif
595
596	va_start(ap, format);
597
598	if (dtp->dt_sprintf_buflen != 0) {
599		int len;
600		char *buf;
601
602		assert(dtp->dt_sprintf_buf != NULL);
603
604		buf = &dtp->dt_sprintf_buf[len = strlen(dtp->dt_sprintf_buf)];
605		len = dtp->dt_sprintf_buflen - len;
606		assert(len >= 0);
607
608		if ((n = vsnprintf(buf, len, format, ap)) < 0)
609			n = dt_set_errno(dtp, errno);
610
611		va_end(ap);
612
613		return (n);
614	}
615
616	if (fp == NULL) {
617		int needed, rval;
618		size_t avail;
619
620		/*
621		 * Using buffered output is not allowed if a handler has
622		 * not been installed.
623		 */
624		if (dtp->dt_bufhdlr == NULL) {
625			va_end(ap);
626			return (dt_set_errno(dtp, EDT_NOBUFFERED));
627		}
628
629		if (dtp->dt_buffered_buf == NULL) {
630			assert(dtp->dt_buffered_size == 0);
631			dtp->dt_buffered_size = 1;
632			dtp->dt_buffered_buf = malloc(dtp->dt_buffered_size);
633
634			if (dtp->dt_buffered_buf == NULL) {
635				va_end(ap);
636				return (dt_set_errno(dtp, EDT_NOMEM));
637			}
638
639			dtp->dt_buffered_offs = 0;
640			dtp->dt_buffered_buf[0] = '\0';
641		}
642
643		if ((needed = vsnprintf(NULL, 0, format, ap)) < 0) {
644			rval = dt_set_errno(dtp, errno);
645			va_end(ap);
646			return (rval);
647		}
648
649		if (needed == 0) {
650			va_end(ap);
651			return (0);
652		}
653
654		for (;;) {
655			char *newbuf;
656
657			assert(dtp->dt_buffered_offs < dtp->dt_buffered_size);
658			avail = dtp->dt_buffered_size - dtp->dt_buffered_offs;
659
660			if (needed + 1 < avail)
661				break;
662
663			if ((newbuf = realloc(dtp->dt_buffered_buf,
664			    dtp->dt_buffered_size << 1)) == NULL) {
665				va_end(ap);
666				return (dt_set_errno(dtp, EDT_NOMEM));
667			}
668
669			dtp->dt_buffered_buf = newbuf;
670			dtp->dt_buffered_size <<= 1;
671		}
672
673		if (vsnprintf(&dtp->dt_buffered_buf[dtp->dt_buffered_offs],
674		    avail, format, ap) < 0) {
675			rval = dt_set_errno(dtp, errno);
676			va_end(ap);
677			return (rval);
678		}
679
680		dtp->dt_buffered_offs += needed;
681		assert(dtp->dt_buffered_buf[dtp->dt_buffered_offs] == '\0');
682		va_end(ap);
683		return (0);
684	}
685
686	n = vfprintf(fp, format, ap);
687	fflush(fp);
688	va_end(ap);
689
690	if (n < 0) {
691		clearerr(fp);
692		return (dt_set_errno(dtp, errno));
693	}
694
695	return (n);
696}
697
698int
699dt_buffered_flush(dtrace_hdl_t *dtp, dtrace_probedata_t *pdata,
700    const dtrace_recdesc_t *rec, const dtrace_aggdata_t *agg, uint32_t flags)
701{
702	dtrace_bufdata_t data;
703
704	if (dtp->dt_buffered_offs == 0)
705		return (0);
706
707	data.dtbda_handle = dtp;
708	data.dtbda_buffered = dtp->dt_buffered_buf;
709	data.dtbda_probe = pdata;
710	data.dtbda_recdesc = rec;
711	data.dtbda_aggdata = agg;
712	data.dtbda_flags = flags;
713
714	if ((*dtp->dt_bufhdlr)(&data, dtp->dt_bufarg) == DTRACE_HANDLE_ABORT)
715		return (dt_set_errno(dtp, EDT_DIRABORT));
716
717	dtp->dt_buffered_offs = 0;
718	dtp->dt_buffered_buf[0] = '\0';
719
720	return (0);
721}
722
723void
724dt_buffered_destroy(dtrace_hdl_t *dtp)
725{
726	free(dtp->dt_buffered_buf);
727	dtp->dt_buffered_buf = NULL;
728	dtp->dt_buffered_offs = 0;
729	dtp->dt_buffered_size = 0;
730}
731
732void *
733dt_zalloc(dtrace_hdl_t *dtp, size_t size)
734{
735	void *data;
736
737	if ((data = malloc(size)) == NULL)
738		(void) dt_set_errno(dtp, EDT_NOMEM);
739	else
740		bzero(data, size);
741
742	return (data);
743}
744
745void *
746dt_alloc(dtrace_hdl_t *dtp, size_t size)
747{
748	void *data;
749
750	if ((data = malloc(size)) == NULL)
751		(void) dt_set_errno(dtp, EDT_NOMEM);
752
753	return (data);
754}
755
756void
757dt_free(dtrace_hdl_t *dtp, void *data)
758{
759	assert(dtp != NULL); /* ensure sane use of this interface */
760	free(data);
761}
762
763void
764dt_difo_free(dtrace_hdl_t *dtp, dtrace_difo_t *dp)
765{
766	if (dp == NULL)
767		return; /* simplify caller code */
768
769	dt_free(dtp, dp->dtdo_buf);
770	dt_free(dtp, dp->dtdo_inttab);
771	dt_free(dtp, dp->dtdo_strtab);
772	dt_free(dtp, dp->dtdo_vartab);
773	dt_free(dtp, dp->dtdo_kreltab);
774	dt_free(dtp, dp->dtdo_ureltab);
775	dt_free(dtp, dp->dtdo_xlmtab);
776
777	dt_free(dtp, dp);
778}
779
780/*
781 * dt_gmatch() is similar to gmatch(3GEN) and dtrace(7D) globbing, but also
782 * implements the behavior that an empty pattern matches any string.
783 */
784int
785dt_gmatch(const char *s, const char *p)
786{
787	return (p == NULL || *p == '\0' || gmatch(s, p));
788}
789
790char *
791dt_basename(char *str)
792{
793	char *last = strrchr(str, '/');
794
795	if (last == NULL)
796		return (str);
797
798	return (last + 1);
799}
800
801/*
802 * dt_popc() is a fast implementation of population count.  The algorithm is
803 * from "Hacker's Delight" by Henry Warren, Jr with a 64-bit equivalent added.
804 */
805ulong_t
806dt_popc(ulong_t x)
807{
808#if defined(_ILP32)
809	x = x - ((x >> 1) & 0x55555555UL);
810	x = (x & 0x33333333UL) + ((x >> 2) & 0x33333333UL);
811	x = (x + (x >> 4)) & 0x0F0F0F0FUL;
812	x = x + (x >> 8);
813	x = x + (x >> 16);
814	return (x & 0x3F);
815#elif defined(_LP64)
816	x = x - ((x >> 1) & 0x5555555555555555ULL);
817	x = (x & 0x3333333333333333ULL) + ((x >> 2) & 0x3333333333333333ULL);
818	x = (x + (x >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
819	x = x + (x >> 8);
820	x = x + (x >> 16);
821	x = x + (x >> 32);
822	return (x & 0x7F);
823#else
824/* This should be a #warning but for now ignore error. Err: "need td_popc() implementation" */
825#endif
826}
827
828/*
829 * dt_popcb() is a bitmap-based version of population count that returns the
830 * number of one bits in the specified bitmap 'bp' at bit positions below 'n'.
831 */
832ulong_t
833dt_popcb(const ulong_t *bp, ulong_t n)
834{
835	ulong_t maxb = n & BT_ULMASK;
836	ulong_t maxw = n >> BT_ULSHIFT;
837	ulong_t w, popc = 0;
838
839	if (n == 0)
840		return (0);
841
842	for (w = 0; w < maxw; w++)
843		popc += dt_popc(bp[w]);
844
845	return (popc + dt_popc(bp[maxw] & ((1UL << maxb) - 1)));
846}
847
848#if defined(sun)
849struct _rwlock;
850struct _lwp_mutex;
851
852int
853dt_rw_read_held(pthread_rwlock_t *lock)
854{
855	extern int _rw_read_held(struct _rwlock *);
856	return (_rw_read_held((struct _rwlock *)lock));
857}
858
859int
860dt_rw_write_held(pthread_rwlock_t *lock)
861{
862	extern int _rw_write_held(struct _rwlock *);
863	return (_rw_write_held((struct _rwlock *)lock));
864}
865#endif
866
867int
868dt_mutex_held(pthread_mutex_t *lock)
869{
870#if defined(sun)
871	extern int _mutex_held(struct _lwp_mutex *);
872	return (_mutex_held((struct _lwp_mutex *)lock));
873#else
874	return (1);
875#endif
876}
877
878static int
879dt_string2str(char *s, char *str, int nbytes)
880{
881	int len = strlen(s);
882
883	if (nbytes == 0) {
884		/*
885		 * Like snprintf(3C), we don't check the value of str if the
886		 * number of bytes is 0.
887		 */
888		return (len);
889	}
890
891	if (nbytes <= len) {
892		(void) strncpy(str, s, nbytes - 1);
893		/*
894		 * Like snprintf(3C) (and unlike strncpy(3C)), we guarantee
895		 * that the string is null-terminated.
896		 */
897		str[nbytes - 1] = '\0';
898	} else {
899		(void) strcpy(str, s);
900	}
901
902	return (len);
903}
904
905int
906dtrace_addr2str(dtrace_hdl_t *dtp, uint64_t addr, char *str, int nbytes)
907{
908	dtrace_syminfo_t dts;
909	GElf_Sym sym;
910
911	size_t n = 20; /* for 0x%llx\0 */
912	char *s;
913	int err;
914
915	if ((err = dtrace_lookup_by_addr(dtp, addr, &sym, &dts)) == 0)
916		n += strlen(dts.dts_object) + strlen(dts.dts_name) + 2; /* +` */
917
918	s = alloca(n);
919
920	if (err == 0 && addr != sym.st_value) {
921		(void) snprintf(s, n, "%s`%s+0x%llx", dts.dts_object,
922		    dts.dts_name, (u_longlong_t)addr - sym.st_value);
923	} else if (err == 0) {
924		(void) snprintf(s, n, "%s`%s",
925		    dts.dts_object, dts.dts_name);
926	} else {
927		/*
928		 * We'll repeat the lookup, but this time we'll specify a NULL
929		 * GElf_Sym -- indicating that we're only interested in the
930		 * containing module.
931		 */
932		if (dtrace_lookup_by_addr(dtp, addr, NULL, &dts) == 0) {
933			(void) snprintf(s, n, "%s`0x%llx", dts.dts_object,
934			    (u_longlong_t)addr);
935		} else {
936			(void) snprintf(s, n, "0x%llx", (u_longlong_t)addr);
937		}
938	}
939
940	return (dt_string2str(s, str, nbytes));
941}
942
943int
944dtrace_uaddr2str(dtrace_hdl_t *dtp, pid_t pid,
945    uint64_t addr, char *str, int nbytes)
946{
947	char name[PATH_MAX], objname[PATH_MAX], c[PATH_MAX * 2];
948	struct ps_prochandle *P = NULL;
949	GElf_Sym sym;
950	char *obj;
951
952	if (pid != 0)
953		P = dt_proc_grab(dtp, pid, PGRAB_RDONLY | PGRAB_FORCE, 0);
954
955	if (P == NULL) {
956	  (void) snprintf(c, sizeof (c), "0x%jx", (uintmax_t)addr);
957		return (dt_string2str(c, str, nbytes));
958	}
959
960	dt_proc_lock(dtp, P);
961
962	if (Plookup_by_addr(P, addr, name, sizeof (name), &sym) == 0) {
963		(void) Pobjname(P, addr, objname, sizeof (objname));
964
965		obj = dt_basename(objname);
966
967		if (addr > sym.st_value) {
968			(void) snprintf(c, sizeof (c), "%s`%s+0x%llx", obj,
969			    name, (u_longlong_t)(addr - sym.st_value));
970		} else {
971			(void) snprintf(c, sizeof (c), "%s`%s", obj, name);
972		}
973	} else if (Pobjname(P, addr, objname, sizeof (objname)) != 0) {
974		(void) snprintf(c, sizeof (c), "%s`0x%jx",
975				dt_basename(objname), (uintmax_t)addr);
976	} else {
977	  (void) snprintf(c, sizeof (c), "0x%jx", (uintmax_t)addr);
978	}
979
980	dt_proc_unlock(dtp, P);
981	dt_proc_release(dtp, P);
982
983	return (dt_string2str(c, str, nbytes));
984}
985