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