xref: /freebsd/cddl/contrib/opensolaris/common/ctf/ctf_open.c (revision 2d5d2a986ce1a93b8567dbdf3f80bc2b545d6998)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
25  * Use is subject to license terms.
26  */
27 /*
28  * Copyright (c) 2013, Joyent, Inc.  All rights reserved.
29  */
30 
31 #include <ctf_impl.h>
32 #include <sys/mman.h>
33 #include <sys/zmod.h>
34 
35 static const ctf_dmodel_t _libctf_models[] = {
36 	{ "ILP32", CTF_MODEL_ILP32, 4, 1, 2, 4, 4 },
37 	{ "LP64", CTF_MODEL_LP64, 8, 1, 2, 4, 8 },
38 	{ NULL, 0, 0, 0, 0, 0, 0 }
39 };
40 
41 const char _CTF_SECTION[] = ".SUNW_ctf";
42 const char _CTF_NULLSTR[] = "";
43 
44 int _libctf_version = CTF_VERSION;	/* library client version */
45 int _libctf_debug = 0;			/* debugging messages enabled */
46 
47 static ushort_t
48 get_kind_v2(ushort_t info)
49 {
50 	return (CTF_INFO_KIND(info));
51 }
52 
53 static ushort_t
54 get_root_v2(ushort_t info)
55 {
56 	return (CTF_INFO_ISROOT(info));
57 }
58 
59 static ushort_t
60 get_vlen_v2(ushort_t info)
61 {
62 	return (CTF_INFO_VLEN(info));
63 }
64 
65 static const ctf_fileops_t ctf_fileops[] = {
66 	{ NULL, NULL },
67 	{ NULL, NULL },
68 	{ get_kind_v2, get_root_v2, get_vlen_v2 },
69 };
70 
71 /*
72  * Convert a 32-bit ELF symbol into GElf (Elf64) and return a pointer to it.
73  */
74 static Elf64_Sym *
75 sym_to_gelf(const Elf32_Sym *src, Elf64_Sym *dst)
76 {
77 	dst->st_name = src->st_name;
78 	dst->st_value = src->st_value;
79 	dst->st_size = src->st_size;
80 	dst->st_info = src->st_info;
81 	dst->st_other = src->st_other;
82 	dst->st_shndx = src->st_shndx;
83 
84 	return (dst);
85 }
86 
87 /*
88  * Initialize the symtab translation table by filling each entry with the
89  * offset of the CTF type or function data corresponding to each STT_FUNC or
90  * STT_OBJECT entry in the symbol table.
91  */
92 static int
93 init_symtab(ctf_file_t *fp, const ctf_header_t *hp,
94     const ctf_sect_t *sp, const ctf_sect_t *strp)
95 {
96 	const uchar_t *symp = sp->cts_data;
97 	uint_t *xp = fp->ctf_sxlate;
98 	uint_t *xend = xp + fp->ctf_nsyms;
99 
100 	uint_t objtoff = hp->cth_objtoff;
101 	uint_t funcoff = hp->cth_funcoff;
102 
103 	ushort_t info, vlen;
104 	Elf64_Sym sym, *gsp;
105 	const char *name;
106 
107 	/*
108 	 * The CTF data object and function type sections are ordered to match
109 	 * the relative order of the respective symbol types in the symtab.
110 	 * If no type information is available for a symbol table entry, a
111 	 * pad is inserted in the CTF section.  As a further optimization,
112 	 * anonymous or undefined symbols are omitted from the CTF data.
113 	 */
114 	for (; xp < xend; xp++, symp += sp->cts_entsize) {
115 		if (sp->cts_entsize == sizeof (Elf32_Sym))
116 			gsp = sym_to_gelf((Elf32_Sym *)(uintptr_t)symp, &sym);
117 		else
118 			gsp = (Elf64_Sym *)(uintptr_t)symp;
119 
120 		if (gsp->st_name < strp->cts_size)
121 			name = (const char *)strp->cts_data + gsp->st_name;
122 		else
123 			name = _CTF_NULLSTR;
124 
125 		if (gsp->st_name == 0 || gsp->st_shndx == SHN_UNDEF ||
126 		    strcmp(name, "_START_") == 0 ||
127 		    strcmp(name, "_END_") == 0) {
128 			*xp = -1u;
129 			continue;
130 		}
131 
132 		switch (ELF64_ST_TYPE(gsp->st_info)) {
133 		case STT_OBJECT:
134 			if (objtoff >= hp->cth_funcoff ||
135 			    (gsp->st_shndx == SHN_ABS && gsp->st_value == 0)) {
136 				*xp = -1u;
137 				break;
138 			}
139 
140 			*xp = objtoff;
141 			objtoff += sizeof (ushort_t);
142 			break;
143 
144 		case STT_FUNC:
145 			if (funcoff >= hp->cth_typeoff) {
146 				*xp = -1u;
147 				break;
148 			}
149 
150 			*xp = funcoff;
151 
152 			info = *(ushort_t *)((uintptr_t)fp->ctf_buf + funcoff);
153 			vlen = LCTF_INFO_VLEN(fp, info);
154 
155 			/*
156 			 * If we encounter a zero pad at the end, just skip it.
157 			 * Otherwise skip over the function and its return type
158 			 * (+2) and the argument list (vlen).
159 			 */
160 			if (LCTF_INFO_KIND(fp, info) == CTF_K_UNKNOWN &&
161 			    vlen == 0)
162 				funcoff += sizeof (ushort_t); /* skip pad */
163 			else
164 				funcoff += sizeof (ushort_t) * (vlen + 2);
165 			break;
166 
167 		default:
168 			*xp = -1u;
169 			break;
170 		}
171 	}
172 
173 	ctf_dprintf("loaded %lu symtab entries\n", fp->ctf_nsyms);
174 	return (0);
175 }
176 
177 /*
178  * Initialize the type ID translation table with the byte offset of each type,
179  * and initialize the hash tables of each named type.
180  */
181 static int
182 init_types(ctf_file_t *fp, const ctf_header_t *cth)
183 {
184 	/* LINTED - pointer alignment */
185 	const ctf_type_t *tbuf = (ctf_type_t *)(fp->ctf_buf + cth->cth_typeoff);
186 	/* LINTED - pointer alignment */
187 	const ctf_type_t *tend = (ctf_type_t *)(fp->ctf_buf + cth->cth_stroff);
188 
189 	ulong_t pop[CTF_K_MAX + 1] = { 0 };
190 	const ctf_type_t *tp;
191 	ctf_hash_t *hp;
192 	ushort_t id, dst;
193 	uint_t *xp;
194 
195 	/*
196 	 * We initially determine whether the container is a child or a parent
197 	 * based on the value of cth_parname.  To support containers that pre-
198 	 * date cth_parname, we also scan the types themselves for references
199 	 * to values in the range reserved for child types in our first pass.
200 	 */
201 	int child = cth->cth_parname != 0;
202 	int nlstructs = 0, nlunions = 0;
203 	int err;
204 
205 	/*
206 	 * We make two passes through the entire type section.  In this first
207 	 * pass, we count the number of each type and the total number of types.
208 	 */
209 	for (tp = tbuf; tp < tend; fp->ctf_typemax++) {
210 		ushort_t kind = LCTF_INFO_KIND(fp, tp->ctt_info);
211 		ulong_t vlen = LCTF_INFO_VLEN(fp, tp->ctt_info);
212 		ssize_t size, increment;
213 
214 		size_t vbytes;
215 		uint_t n;
216 
217 		(void) ctf_get_ctt_size(fp, tp, &size, &increment);
218 
219 		switch (kind) {
220 		case CTF_K_INTEGER:
221 		case CTF_K_FLOAT:
222 			vbytes = sizeof (uint_t);
223 			break;
224 		case CTF_K_ARRAY:
225 			vbytes = sizeof (ctf_array_t);
226 			break;
227 		case CTF_K_FUNCTION:
228 			vbytes = sizeof (ushort_t) * (vlen + (vlen & 1));
229 			break;
230 		case CTF_K_STRUCT:
231 		case CTF_K_UNION:
232 			if (size < CTF_LSTRUCT_THRESH) {
233 				ctf_member_t *mp = (ctf_member_t *)
234 				    ((uintptr_t)tp + increment);
235 
236 				vbytes = sizeof (ctf_member_t) * vlen;
237 				for (n = vlen; n != 0; n--, mp++)
238 					child |= CTF_TYPE_ISCHILD(mp->ctm_type);
239 			} else {
240 				ctf_lmember_t *lmp = (ctf_lmember_t *)
241 				    ((uintptr_t)tp + increment);
242 
243 				vbytes = sizeof (ctf_lmember_t) * vlen;
244 				for (n = vlen; n != 0; n--, lmp++)
245 					child |=
246 					    CTF_TYPE_ISCHILD(lmp->ctlm_type);
247 			}
248 			break;
249 		case CTF_K_ENUM:
250 			vbytes = sizeof (ctf_enum_t) * vlen;
251 			break;
252 		case CTF_K_FORWARD:
253 			/*
254 			 * For forward declarations, ctt_type is the CTF_K_*
255 			 * kind for the tag, so bump that population count too.
256 			 * If ctt_type is unknown, treat the tag as a struct.
257 			 */
258 			if (tp->ctt_type == CTF_K_UNKNOWN ||
259 			    tp->ctt_type >= CTF_K_MAX)
260 				pop[CTF_K_STRUCT]++;
261 			else
262 				pop[tp->ctt_type]++;
263 			/*FALLTHRU*/
264 		case CTF_K_UNKNOWN:
265 			vbytes = 0;
266 			break;
267 		case CTF_K_POINTER:
268 		case CTF_K_TYPEDEF:
269 		case CTF_K_VOLATILE:
270 		case CTF_K_CONST:
271 		case CTF_K_RESTRICT:
272 			child |= CTF_TYPE_ISCHILD(tp->ctt_type);
273 			vbytes = 0;
274 			break;
275 		default:
276 			ctf_dprintf("detected invalid CTF kind -- %u\n", kind);
277 			return (ECTF_CORRUPT);
278 		}
279 		tp = (ctf_type_t *)((uintptr_t)tp + increment + vbytes);
280 		pop[kind]++;
281 	}
282 
283 	/*
284 	 * If we detected a reference to a child type ID, then we know this
285 	 * container is a child and may have a parent's types imported later.
286 	 */
287 	if (child) {
288 		ctf_dprintf("CTF container %p is a child\n", (void *)fp);
289 		fp->ctf_flags |= LCTF_CHILD;
290 	} else
291 		ctf_dprintf("CTF container %p is a parent\n", (void *)fp);
292 
293 	/*
294 	 * Now that we've counted up the number of each type, we can allocate
295 	 * the hash tables, type translation table, and pointer table.
296 	 */
297 	if ((err = ctf_hash_create(&fp->ctf_structs, pop[CTF_K_STRUCT])) != 0)
298 		return (err);
299 
300 	if ((err = ctf_hash_create(&fp->ctf_unions, pop[CTF_K_UNION])) != 0)
301 		return (err);
302 
303 	if ((err = ctf_hash_create(&fp->ctf_enums, pop[CTF_K_ENUM])) != 0)
304 		return (err);
305 
306 	if ((err = ctf_hash_create(&fp->ctf_names,
307 	    pop[CTF_K_INTEGER] + pop[CTF_K_FLOAT] + pop[CTF_K_FUNCTION] +
308 	    pop[CTF_K_TYPEDEF] + pop[CTF_K_POINTER] + pop[CTF_K_VOLATILE] +
309 	    pop[CTF_K_CONST] + pop[CTF_K_RESTRICT])) != 0)
310 		return (err);
311 
312 	fp->ctf_txlate = ctf_alloc(sizeof (uint_t) * (fp->ctf_typemax + 1));
313 	fp->ctf_ptrtab = ctf_alloc(sizeof (ushort_t) * (fp->ctf_typemax + 1));
314 
315 	if (fp->ctf_txlate == NULL || fp->ctf_ptrtab == NULL)
316 		return (EAGAIN); /* memory allocation failed */
317 
318 	xp = fp->ctf_txlate;
319 	*xp++ = 0; /* type id 0 is used as a sentinel value */
320 
321 	bzero(fp->ctf_txlate, sizeof (uint_t) * (fp->ctf_typemax + 1));
322 	bzero(fp->ctf_ptrtab, sizeof (ushort_t) * (fp->ctf_typemax + 1));
323 
324 	/*
325 	 * In the second pass through the types, we fill in each entry of the
326 	 * type and pointer tables and add names to the appropriate hashes.
327 	 */
328 	for (id = 1, tp = tbuf; tp < tend; xp++, id++) {
329 		ushort_t kind = LCTF_INFO_KIND(fp, tp->ctt_info);
330 		ulong_t vlen = LCTF_INFO_VLEN(fp, tp->ctt_info);
331 		ssize_t size, increment;
332 
333 		const char *name;
334 		size_t vbytes;
335 		ctf_helem_t *hep;
336 		ctf_encoding_t cte;
337 
338 		(void) ctf_get_ctt_size(fp, tp, &size, &increment);
339 		name = ctf_strptr(fp, tp->ctt_name);
340 
341 		switch (kind) {
342 		case CTF_K_INTEGER:
343 		case CTF_K_FLOAT:
344 			/*
345 			 * Only insert a new integer base type definition if
346 			 * this type name has not been defined yet.  We re-use
347 			 * the names with different encodings for bit-fields.
348 			 */
349 			if ((hep = ctf_hash_lookup(&fp->ctf_names, fp,
350 			    name, strlen(name))) == NULL) {
351 				err = ctf_hash_insert(&fp->ctf_names, fp,
352 				    CTF_INDEX_TO_TYPE(id, child), tp->ctt_name);
353 				if (err != 0 && err != ECTF_STRTAB)
354 					return (err);
355 			} else if (ctf_type_encoding(fp, hep->h_type,
356 			    &cte) == 0 && cte.cte_bits == 0) {
357 				/*
358 				 * Work-around SOS8 stabs bug: replace existing
359 				 * intrinsic w/ same name if it was zero bits.
360 				 */
361 				hep->h_type = CTF_INDEX_TO_TYPE(id, child);
362 			}
363 			vbytes = sizeof (uint_t);
364 			break;
365 
366 		case CTF_K_ARRAY:
367 			vbytes = sizeof (ctf_array_t);
368 			break;
369 
370 		case CTF_K_FUNCTION:
371 			err = ctf_hash_insert(&fp->ctf_names, fp,
372 			    CTF_INDEX_TO_TYPE(id, child), tp->ctt_name);
373 			if (err != 0 && err != ECTF_STRTAB)
374 				return (err);
375 			vbytes = sizeof (ushort_t) * (vlen + (vlen & 1));
376 			break;
377 
378 		case CTF_K_STRUCT:
379 			err = ctf_hash_define(&fp->ctf_structs, fp,
380 			    CTF_INDEX_TO_TYPE(id, child), tp->ctt_name);
381 
382 			if (err != 0 && err != ECTF_STRTAB)
383 				return (err);
384 
385 			if (size < CTF_LSTRUCT_THRESH)
386 				vbytes = sizeof (ctf_member_t) * vlen;
387 			else {
388 				vbytes = sizeof (ctf_lmember_t) * vlen;
389 				nlstructs++;
390 			}
391 			break;
392 
393 		case CTF_K_UNION:
394 			err = ctf_hash_define(&fp->ctf_unions, fp,
395 			    CTF_INDEX_TO_TYPE(id, child), tp->ctt_name);
396 
397 			if (err != 0 && err != ECTF_STRTAB)
398 				return (err);
399 
400 			if (size < CTF_LSTRUCT_THRESH)
401 				vbytes = sizeof (ctf_member_t) * vlen;
402 			else {
403 				vbytes = sizeof (ctf_lmember_t) * vlen;
404 				nlunions++;
405 			}
406 			break;
407 
408 		case CTF_K_ENUM:
409 			err = ctf_hash_define(&fp->ctf_enums, fp,
410 			    CTF_INDEX_TO_TYPE(id, child), tp->ctt_name);
411 
412 			if (err != 0 && err != ECTF_STRTAB)
413 				return (err);
414 
415 			vbytes = sizeof (ctf_enum_t) * vlen;
416 			break;
417 
418 		case CTF_K_TYPEDEF:
419 			err = ctf_hash_insert(&fp->ctf_names, fp,
420 			    CTF_INDEX_TO_TYPE(id, child), tp->ctt_name);
421 			if (err != 0 && err != ECTF_STRTAB)
422 				return (err);
423 			vbytes = 0;
424 			break;
425 
426 		case CTF_K_FORWARD:
427 			/*
428 			 * Only insert forward tags into the given hash if the
429 			 * type or tag name is not already present.
430 			 */
431 			switch (tp->ctt_type) {
432 			case CTF_K_STRUCT:
433 				hp = &fp->ctf_structs;
434 				break;
435 			case CTF_K_UNION:
436 				hp = &fp->ctf_unions;
437 				break;
438 			case CTF_K_ENUM:
439 				hp = &fp->ctf_enums;
440 				break;
441 			default:
442 				hp = &fp->ctf_structs;
443 			}
444 
445 			if (ctf_hash_lookup(hp, fp,
446 			    name, strlen(name)) == NULL) {
447 				err = ctf_hash_insert(hp, fp,
448 				    CTF_INDEX_TO_TYPE(id, child), tp->ctt_name);
449 				if (err != 0 && err != ECTF_STRTAB)
450 					return (err);
451 			}
452 			vbytes = 0;
453 			break;
454 
455 		case CTF_K_POINTER:
456 			/*
457 			 * If the type referenced by the pointer is in this CTF
458 			 * container, then store the index of the pointer type
459 			 * in fp->ctf_ptrtab[ index of referenced type ].
460 			 */
461 			if (CTF_TYPE_ISCHILD(tp->ctt_type) == child &&
462 			    CTF_TYPE_TO_INDEX(tp->ctt_type) <= fp->ctf_typemax)
463 				fp->ctf_ptrtab[
464 				    CTF_TYPE_TO_INDEX(tp->ctt_type)] = id;
465 			/*FALLTHRU*/
466 
467 		case CTF_K_VOLATILE:
468 		case CTF_K_CONST:
469 		case CTF_K_RESTRICT:
470 			err = ctf_hash_insert(&fp->ctf_names, fp,
471 			    CTF_INDEX_TO_TYPE(id, child), tp->ctt_name);
472 			if (err != 0 && err != ECTF_STRTAB)
473 				return (err);
474 			/*FALLTHRU*/
475 
476 		default:
477 			vbytes = 0;
478 			break;
479 		}
480 
481 		*xp = (uint_t)((uintptr_t)tp - (uintptr_t)fp->ctf_buf);
482 		tp = (ctf_type_t *)((uintptr_t)tp + increment + vbytes);
483 	}
484 
485 	ctf_dprintf("%lu total types processed\n", fp->ctf_typemax);
486 	ctf_dprintf("%u enum names hashed\n", ctf_hash_size(&fp->ctf_enums));
487 	ctf_dprintf("%u struct names hashed (%d long)\n",
488 	    ctf_hash_size(&fp->ctf_structs), nlstructs);
489 	ctf_dprintf("%u union names hashed (%d long)\n",
490 	    ctf_hash_size(&fp->ctf_unions), nlunions);
491 	ctf_dprintf("%u base type names hashed\n",
492 	    ctf_hash_size(&fp->ctf_names));
493 
494 	/*
495 	 * Make an additional pass through the pointer table to find pointers
496 	 * that point to anonymous typedef nodes.  If we find one, modify the
497 	 * pointer table so that the pointer is also known to point to the
498 	 * node that is referenced by the anonymous typedef node.
499 	 */
500 	for (id = 1; id <= fp->ctf_typemax; id++) {
501 		if ((dst = fp->ctf_ptrtab[id]) != 0) {
502 			tp = LCTF_INDEX_TO_TYPEPTR(fp, id);
503 
504 			if (LCTF_INFO_KIND(fp, tp->ctt_info) == CTF_K_TYPEDEF &&
505 			    strcmp(ctf_strptr(fp, tp->ctt_name), "") == 0 &&
506 			    CTF_TYPE_ISCHILD(tp->ctt_type) == child &&
507 			    CTF_TYPE_TO_INDEX(tp->ctt_type) <= fp->ctf_typemax)
508 				fp->ctf_ptrtab[
509 				    CTF_TYPE_TO_INDEX(tp->ctt_type)] = dst;
510 		}
511 	}
512 
513 	return (0);
514 }
515 
516 /*
517  * Decode the specified CTF buffer and optional symbol table and create a new
518  * CTF container representing the symbolic debugging information.  This code
519  * can be used directly by the debugger, or it can be used as the engine for
520  * ctf_fdopen() or ctf_open(), below.
521  */
522 ctf_file_t *
523 ctf_bufopen(const ctf_sect_t *ctfsect, const ctf_sect_t *symsect,
524     const ctf_sect_t *strsect, int *errp)
525 {
526 	const ctf_preamble_t *pp;
527 	ctf_header_t hp;
528 	ctf_file_t *fp;
529 	void *buf, *base;
530 	size_t size, hdrsz;
531 	int err;
532 
533 	if (ctfsect == NULL || ((symsect == NULL) != (strsect == NULL)))
534 		return (ctf_set_open_errno(errp, EINVAL));
535 
536 	if (symsect != NULL && symsect->cts_entsize != sizeof (Elf32_Sym) &&
537 	    symsect->cts_entsize != sizeof (Elf64_Sym))
538 		return (ctf_set_open_errno(errp, ECTF_SYMTAB));
539 
540 	if (symsect != NULL && symsect->cts_data == NULL)
541 		return (ctf_set_open_errno(errp, ECTF_SYMBAD));
542 
543 	if (strsect != NULL && strsect->cts_data == NULL)
544 		return (ctf_set_open_errno(errp, ECTF_STRBAD));
545 
546 	if (ctfsect->cts_size < sizeof (ctf_preamble_t))
547 		return (ctf_set_open_errno(errp, ECTF_NOCTFBUF));
548 
549 	pp = (const ctf_preamble_t *)ctfsect->cts_data;
550 
551 	ctf_dprintf("ctf_bufopen: magic=0x%x version=%u\n",
552 	    pp->ctp_magic, pp->ctp_version);
553 
554 	/*
555 	 * Validate each part of the CTF header (either V1 or V2).
556 	 * First, we validate the preamble (common to all versions).  At that
557 	 * point, we know specific header version, and can validate the
558 	 * version-specific parts including section offsets and alignments.
559 	 */
560 	if (pp->ctp_magic != CTF_MAGIC)
561 		return (ctf_set_open_errno(errp, ECTF_NOCTFBUF));
562 
563 	if (pp->ctp_version == CTF_VERSION_2) {
564 		if (ctfsect->cts_size < sizeof (ctf_header_t))
565 			return (ctf_set_open_errno(errp, ECTF_NOCTFBUF));
566 
567 		bcopy(ctfsect->cts_data, &hp, sizeof (hp));
568 		hdrsz = sizeof (ctf_header_t);
569 
570 	} else
571 		return (ctf_set_open_errno(errp, ECTF_CTFVERS));
572 
573 	size = hp.cth_stroff + hp.cth_strlen;
574 
575 	ctf_dprintf("ctf_bufopen: uncompressed size=%lu\n", (ulong_t)size);
576 
577 	if (hp.cth_lbloff > size || hp.cth_objtoff > size ||
578 	    hp.cth_funcoff > size || hp.cth_typeoff > size ||
579 	    hp.cth_stroff > size)
580 		return (ctf_set_open_errno(errp, ECTF_CORRUPT));
581 
582 	if (hp.cth_lbloff > hp.cth_objtoff ||
583 	    hp.cth_objtoff > hp.cth_funcoff ||
584 	    hp.cth_funcoff > hp.cth_typeoff ||
585 	    hp.cth_typeoff > hp.cth_stroff)
586 		return (ctf_set_open_errno(errp, ECTF_CORRUPT));
587 
588 	if ((hp.cth_lbloff & 3) || (hp.cth_objtoff & 1) ||
589 	    (hp.cth_funcoff & 1) || (hp.cth_typeoff & 3))
590 		return (ctf_set_open_errno(errp, ECTF_CORRUPT));
591 
592 	/*
593 	 * Once everything is determined to be valid, attempt to decompress
594 	 * the CTF data buffer if it is compressed.  Otherwise we just put
595 	 * the data section's buffer pointer into ctf_buf, below.
596 	 */
597 	if (hp.cth_flags & CTF_F_COMPRESS) {
598 		size_t srclen, dstlen;
599 		const void *src;
600 		int rc = Z_OK;
601 
602 		if (ctf_zopen(errp) == NULL)
603 			return (NULL); /* errp is set for us */
604 
605 		if ((base = ctf_data_alloc(size + hdrsz)) == MAP_FAILED)
606 			return (ctf_set_open_errno(errp, ECTF_ZALLOC));
607 
608 		bcopy(ctfsect->cts_data, base, hdrsz);
609 		((ctf_preamble_t *)base)->ctp_flags &= ~CTF_F_COMPRESS;
610 		buf = (uchar_t *)base + hdrsz;
611 
612 		src = (uchar_t *)ctfsect->cts_data + hdrsz;
613 		srclen = ctfsect->cts_size - hdrsz;
614 		dstlen = size;
615 
616 		if ((rc = z_uncompress(buf, &dstlen, src, srclen)) != Z_OK) {
617 			ctf_dprintf("zlib inflate err: %s\n", z_strerror(rc));
618 			ctf_data_free(base, size + hdrsz);
619 			return (ctf_set_open_errno(errp, ECTF_DECOMPRESS));
620 		}
621 
622 		if (dstlen != size) {
623 			ctf_dprintf("zlib inflate short -- got %lu of %lu "
624 			    "bytes\n", (ulong_t)dstlen, (ulong_t)size);
625 			ctf_data_free(base, size + hdrsz);
626 			return (ctf_set_open_errno(errp, ECTF_CORRUPT));
627 		}
628 
629 		ctf_data_protect(base, size + hdrsz);
630 
631 	} else {
632 		base = (void *)ctfsect->cts_data;
633 		buf = (uchar_t *)base + hdrsz;
634 	}
635 
636 	/*
637 	 * Once we have uncompressed and validated the CTF data buffer, we can
638 	 * proceed with allocating a ctf_file_t and initializing it.
639 	 */
640 	if ((fp = ctf_alloc(sizeof (ctf_file_t))) == NULL)
641 		return (ctf_set_open_errno(errp, EAGAIN));
642 
643 	bzero(fp, sizeof (ctf_file_t));
644 	fp->ctf_version = hp.cth_version;
645 	fp->ctf_fileops = &ctf_fileops[hp.cth_version];
646 	bcopy(ctfsect, &fp->ctf_data, sizeof (ctf_sect_t));
647 
648 	if (symsect != NULL) {
649 		bcopy(symsect, &fp->ctf_symtab, sizeof (ctf_sect_t));
650 		bcopy(strsect, &fp->ctf_strtab, sizeof (ctf_sect_t));
651 	}
652 
653 	if (fp->ctf_data.cts_name != NULL)
654 		fp->ctf_data.cts_name = ctf_strdup(fp->ctf_data.cts_name);
655 	if (fp->ctf_symtab.cts_name != NULL)
656 		fp->ctf_symtab.cts_name = ctf_strdup(fp->ctf_symtab.cts_name);
657 	if (fp->ctf_strtab.cts_name != NULL)
658 		fp->ctf_strtab.cts_name = ctf_strdup(fp->ctf_strtab.cts_name);
659 
660 	if (fp->ctf_data.cts_name == NULL)
661 		fp->ctf_data.cts_name = _CTF_NULLSTR;
662 	if (fp->ctf_symtab.cts_name == NULL)
663 		fp->ctf_symtab.cts_name = _CTF_NULLSTR;
664 	if (fp->ctf_strtab.cts_name == NULL)
665 		fp->ctf_strtab.cts_name = _CTF_NULLSTR;
666 
667 	fp->ctf_str[CTF_STRTAB_0].cts_strs = (const char *)buf + hp.cth_stroff;
668 	fp->ctf_str[CTF_STRTAB_0].cts_len = hp.cth_strlen;
669 
670 	if (strsect != NULL) {
671 		fp->ctf_str[CTF_STRTAB_1].cts_strs = strsect->cts_data;
672 		fp->ctf_str[CTF_STRTAB_1].cts_len = strsect->cts_size;
673 	}
674 
675 	fp->ctf_base = base;
676 	fp->ctf_buf = buf;
677 	fp->ctf_size = size + hdrsz;
678 
679 	/*
680 	 * If we have a parent container name and label, store the relocated
681 	 * string pointers in the CTF container for easy access later.
682 	 */
683 	if (hp.cth_parlabel != 0)
684 		fp->ctf_parlabel = ctf_strptr(fp, hp.cth_parlabel);
685 	if (hp.cth_parname != 0)
686 		fp->ctf_parname = ctf_strptr(fp, hp.cth_parname);
687 
688 	ctf_dprintf("ctf_bufopen: parent name %s (label %s)\n",
689 	    fp->ctf_parname ? fp->ctf_parname : "<NULL>",
690 	    fp->ctf_parlabel ? fp->ctf_parlabel : "<NULL>");
691 
692 	/*
693 	 * If we have a symbol table section, allocate and initialize
694 	 * the symtab translation table, pointed to by ctf_sxlate.
695 	 */
696 	if (symsect != NULL) {
697 		fp->ctf_nsyms = symsect->cts_size / symsect->cts_entsize;
698 		fp->ctf_sxlate = ctf_alloc(fp->ctf_nsyms * sizeof (uint_t));
699 
700 		if (fp->ctf_sxlate == NULL) {
701 			(void) ctf_set_open_errno(errp, EAGAIN);
702 			goto bad;
703 		}
704 
705 		if ((err = init_symtab(fp, &hp, symsect, strsect)) != 0) {
706 			(void) ctf_set_open_errno(errp, err);
707 			goto bad;
708 		}
709 	}
710 
711 	if ((err = init_types(fp, &hp)) != 0) {
712 		(void) ctf_set_open_errno(errp, err);
713 		goto bad;
714 	}
715 
716 	/*
717 	 * Initialize the ctf_lookup_by_name top-level dictionary.  We keep an
718 	 * array of type name prefixes and the corresponding ctf_hash to use.
719 	 * NOTE: This code must be kept in sync with the code in ctf_update().
720 	 */
721 	fp->ctf_lookups[0].ctl_prefix = "struct";
722 	fp->ctf_lookups[0].ctl_len = strlen(fp->ctf_lookups[0].ctl_prefix);
723 	fp->ctf_lookups[0].ctl_hash = &fp->ctf_structs;
724 	fp->ctf_lookups[1].ctl_prefix = "union";
725 	fp->ctf_lookups[1].ctl_len = strlen(fp->ctf_lookups[1].ctl_prefix);
726 	fp->ctf_lookups[1].ctl_hash = &fp->ctf_unions;
727 	fp->ctf_lookups[2].ctl_prefix = "enum";
728 	fp->ctf_lookups[2].ctl_len = strlen(fp->ctf_lookups[2].ctl_prefix);
729 	fp->ctf_lookups[2].ctl_hash = &fp->ctf_enums;
730 	fp->ctf_lookups[3].ctl_prefix = _CTF_NULLSTR;
731 	fp->ctf_lookups[3].ctl_len = strlen(fp->ctf_lookups[3].ctl_prefix);
732 	fp->ctf_lookups[3].ctl_hash = &fp->ctf_names;
733 	fp->ctf_lookups[4].ctl_prefix = NULL;
734 	fp->ctf_lookups[4].ctl_len = 0;
735 	fp->ctf_lookups[4].ctl_hash = NULL;
736 
737 	if (symsect != NULL) {
738 		if (symsect->cts_entsize == sizeof (Elf64_Sym))
739 			(void) ctf_setmodel(fp, CTF_MODEL_LP64);
740 		else
741 			(void) ctf_setmodel(fp, CTF_MODEL_ILP32);
742 	} else
743 		(void) ctf_setmodel(fp, CTF_MODEL_NATIVE);
744 
745 	fp->ctf_refcnt = 1;
746 	return (fp);
747 
748 bad:
749 	ctf_close(fp);
750 	return (NULL);
751 }
752 
753 /*
754  * Dupliate a ctf_file_t and its underlying section information into a new
755  * container. This works by copying the three ctf_sect_t's of the original
756  * container if they exist and passing those into ctf_bufopen. To copy those, we
757  * mmap anonymous memory with ctf_data_alloc and bcopy the data across. It's not
758  * the cheapest thing, but it's what we've got.
759  */
760 ctf_file_t *
761 ctf_dup(ctf_file_t *ofp)
762 {
763 	ctf_file_t *fp;
764 	ctf_sect_t ctfsect, symsect, strsect;
765 	ctf_sect_t *ctp, *symp, *strp;
766 	void *cbuf, *symbuf, *strbuf;
767 	int err;
768 
769 	cbuf = symbuf = strbuf = NULL;
770 	/*
771 	 * The ctfsect isn't allowed to not exist, but the symbol and string
772 	 * section might not. We only need to copy the data of the section, not
773 	 * the name, as ctf_bufopen will take care of that.
774 	 */
775 	bcopy(&ofp->ctf_data, &ctfsect, sizeof (ctf_sect_t));
776 	cbuf = ctf_data_alloc(ctfsect.cts_size);
777 	if (cbuf == NULL) {
778 		(void) ctf_set_errno(ofp, ECTF_MMAP);
779 		return (NULL);
780 	}
781 
782 	bcopy(ctfsect.cts_data, cbuf, ctfsect.cts_size);
783 	ctf_data_protect(cbuf, ctfsect.cts_size);
784 	ctfsect.cts_data = cbuf;
785 	ctfsect.cts_offset = 0;
786 	ctp = &ctfsect;
787 
788 	if (ofp->ctf_symtab.cts_data != NULL) {
789 		bcopy(&ofp->ctf_symtab, &symsect, sizeof (ctf_sect_t));
790 		symbuf = ctf_data_alloc(symsect.cts_size);
791 		if (symbuf == NULL) {
792 			(void) ctf_set_errno(ofp, ECTF_MMAP);
793 			goto err;
794 		}
795 		bcopy(symsect.cts_data, symbuf, symsect.cts_size);
796 		ctf_data_protect(symbuf, symsect.cts_size);
797 		symsect.cts_data = symbuf;
798 		symsect.cts_offset = 0;
799 		symp = &symsect;
800 	} else {
801 		symp = NULL;
802 	}
803 
804 	if (ofp->ctf_strtab.cts_data != NULL) {
805 		bcopy(&ofp->ctf_strtab, &strsect, sizeof (ctf_sect_t));
806 		strbuf = ctf_data_alloc(strsect.cts_size);
807 		if (strbuf == NULL) {
808 			(void) ctf_set_errno(ofp, ECTF_MMAP);
809 			goto err;
810 		}
811 		bcopy(strsect.cts_data, strbuf, strsect.cts_size);
812 		ctf_data_protect(strbuf, strsect.cts_size);
813 		strsect.cts_data = strbuf;
814 		strsect.cts_offset = 0;
815 		strp = &strsect;
816 	} else {
817 		strp = NULL;
818 	}
819 
820 	fp = ctf_bufopen(ctp, symp, strp, &err);
821 	if (fp == NULL) {
822 		(void) ctf_set_errno(ofp, err);
823 		goto err;
824 	}
825 
826 	fp->ctf_flags |= LCTF_MMAP;
827 
828 	return (fp);
829 
830 err:
831 	ctf_data_free(cbuf, ctfsect.cts_size);
832 	if (symbuf != NULL)
833 		ctf_data_free(symbuf, symsect.cts_size);
834 	if (strbuf != NULL)
835 		ctf_data_free(strbuf, strsect.cts_size);
836 	return (NULL);
837 }
838 
839 /*
840  * Close the specified CTF container and free associated data structures.  Note
841  * that ctf_close() is a reference counted operation: if the specified file is
842  * the parent of other active containers, its reference count will be greater
843  * than one and it will be freed later when no active children exist.
844  */
845 void
846 ctf_close(ctf_file_t *fp)
847 {
848 	ctf_dtdef_t *dtd, *ntd;
849 
850 	if (fp == NULL)
851 		return; /* allow ctf_close(NULL) to simplify caller code */
852 
853 	ctf_dprintf("ctf_close(%p) refcnt=%u\n", (void *)fp, fp->ctf_refcnt);
854 
855 	if (fp->ctf_refcnt > 1) {
856 		fp->ctf_refcnt--;
857 		return;
858 	}
859 
860 	if (fp->ctf_parent != NULL)
861 		ctf_close(fp->ctf_parent);
862 
863 	/*
864 	 * Note, to work properly with reference counting on the dynamic
865 	 * section, we must delete the list in reverse.
866 	 */
867 	for (dtd = ctf_list_prev(&fp->ctf_dtdefs); dtd != NULL; dtd = ntd) {
868 		ntd = ctf_list_prev(dtd);
869 		ctf_dtd_delete(fp, dtd);
870 	}
871 
872 	ctf_free(fp->ctf_dthash, fp->ctf_dthashlen * sizeof (ctf_dtdef_t *));
873 
874 	if (fp->ctf_flags & LCTF_MMAP) {
875 		if (fp->ctf_data.cts_data != NULL)
876 			ctf_sect_munmap(&fp->ctf_data);
877 		if (fp->ctf_symtab.cts_data != NULL)
878 			ctf_sect_munmap(&fp->ctf_symtab);
879 		if (fp->ctf_strtab.cts_data != NULL)
880 			ctf_sect_munmap(&fp->ctf_strtab);
881 	}
882 
883 	if (fp->ctf_data.cts_name != _CTF_NULLSTR &&
884 	    fp->ctf_data.cts_name != NULL) {
885 		ctf_free((char *)fp->ctf_data.cts_name,
886 		    strlen(fp->ctf_data.cts_name) + 1);
887 	}
888 
889 	if (fp->ctf_symtab.cts_name != _CTF_NULLSTR &&
890 	    fp->ctf_symtab.cts_name != NULL) {
891 		ctf_free((char *)fp->ctf_symtab.cts_name,
892 		    strlen(fp->ctf_symtab.cts_name) + 1);
893 	}
894 
895 	if (fp->ctf_strtab.cts_name != _CTF_NULLSTR &&
896 	    fp->ctf_strtab.cts_name != NULL) {
897 		ctf_free((char *)fp->ctf_strtab.cts_name,
898 		    strlen(fp->ctf_strtab.cts_name) + 1);
899 	}
900 
901 	if (fp->ctf_base != fp->ctf_data.cts_data && fp->ctf_base != NULL)
902 		ctf_data_free((void *)fp->ctf_base, fp->ctf_size);
903 
904 	if (fp->ctf_sxlate != NULL)
905 		ctf_free(fp->ctf_sxlate, sizeof (uint_t) * fp->ctf_nsyms);
906 
907 	if (fp->ctf_txlate != NULL) {
908 		ctf_free(fp->ctf_txlate,
909 		    sizeof (uint_t) * (fp->ctf_typemax + 1));
910 	}
911 
912 	if (fp->ctf_ptrtab != NULL) {
913 		ctf_free(fp->ctf_ptrtab,
914 		    sizeof (ushort_t) * (fp->ctf_typemax + 1));
915 	}
916 
917 	ctf_hash_destroy(&fp->ctf_structs);
918 	ctf_hash_destroy(&fp->ctf_unions);
919 	ctf_hash_destroy(&fp->ctf_enums);
920 	ctf_hash_destroy(&fp->ctf_names);
921 
922 	ctf_free(fp, sizeof (ctf_file_t));
923 }
924 
925 /*
926  * Return the CTF handle for the parent CTF container, if one exists.
927  * Otherwise return NULL to indicate this container has no imported parent.
928  */
929 ctf_file_t *
930 ctf_parent_file(ctf_file_t *fp)
931 {
932 	return (fp->ctf_parent);
933 }
934 
935 /*
936  * Return the name of the parent CTF container, if one exists.  Otherwise
937  * return NULL to indicate this container is a root container.
938  */
939 const char *
940 ctf_parent_name(ctf_file_t *fp)
941 {
942 	return (fp->ctf_parname);
943 }
944 
945 /*
946  * Import the types from the specified parent container by storing a pointer
947  * to it in ctf_parent and incrementing its reference count.  Only one parent
948  * is allowed: if a parent already exists, it is replaced by the new parent.
949  */
950 int
951 ctf_import(ctf_file_t *fp, ctf_file_t *pfp)
952 {
953 	if (fp == NULL || fp == pfp || (pfp != NULL && pfp->ctf_refcnt == 0))
954 		return (ctf_set_errno(fp, EINVAL));
955 
956 	if (pfp != NULL && pfp->ctf_dmodel != fp->ctf_dmodel)
957 		return (ctf_set_errno(fp, ECTF_DMODEL));
958 
959 	if (fp->ctf_parent != NULL)
960 		ctf_close(fp->ctf_parent);
961 
962 	if (pfp != NULL) {
963 		fp->ctf_flags |= LCTF_CHILD;
964 		pfp->ctf_refcnt++;
965 	}
966 
967 	fp->ctf_parent = pfp;
968 	return (0);
969 }
970 
971 /*
972  * Set the data model constant for the CTF container.
973  */
974 int
975 ctf_setmodel(ctf_file_t *fp, int model)
976 {
977 	const ctf_dmodel_t *dp;
978 
979 	for (dp = _libctf_models; dp->ctd_name != NULL; dp++) {
980 		if (dp->ctd_code == model) {
981 			fp->ctf_dmodel = dp;
982 			return (0);
983 		}
984 	}
985 
986 	return (ctf_set_errno(fp, EINVAL));
987 }
988 
989 /*
990  * Return the data model constant for the CTF container.
991  */
992 int
993 ctf_getmodel(ctf_file_t *fp)
994 {
995 	return (fp->ctf_dmodel->ctd_code);
996 }
997 
998 void
999 ctf_setspecific(ctf_file_t *fp, void *data)
1000 {
1001 	fp->ctf_specific = data;
1002 }
1003 
1004 void *
1005 ctf_getspecific(ctf_file_t *fp)
1006 {
1007 	return (fp->ctf_specific);
1008 }
1009