xref: /netbsd-src/external/cddl/osnet/dist/tools/ctf/cvt/ctf.c (revision 946379e7b37692fc43f68eb0d1c10daa0a7f3b6c)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  * Create and parse buffers containing CTF data.
28  */
29 
30 #if HAVE_NBTOOL_CONFIG_H
31 #include "nbtool_config.h"
32 #endif
33 
34 #include <sys/types.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <strings.h>
38 #include <ctype.h>
39 #include <zlib.h>
40 #include <elf.h>
41 
42 #include "ctf_headers.h"
43 #include "ctftools.h"
44 #include "strtab.h"
45 #include "memory.h"
46 
47 /*
48  * Name of the file currently being read, used to print error messages.  We
49  * assume that only one file will be read at a time, and thus make no attempt
50  * to allow curfile to be used simultaneously by multiple threads.
51  *
52  * The value is only valid during a call to ctf_load.
53  */
54 static char *curfile;
55 
56 #define	CTF_BUF_CHUNK_SIZE	(64 * 1024)
57 #define	RES_BUF_CHUNK_SIZE	(64 * 1024)
58 
59 static int ntypes = 0;		/* The number of types. */
60 
61 struct ctf_buf {
62 	strtab_t ctb_strtab;	/* string table */
63 	caddr_t ctb_base;	/* pointer to base of buffer */
64 	caddr_t ctb_end;	/* pointer to end of buffer */
65 	caddr_t ctb_ptr;	/* pointer to empty buffer space */
66 	size_t ctb_size;	/* size of buffer */
67 	int nptent;		/* number of processed types */
68 	int ntholes;		/* number of type holes */
69 };
70 
71 /*
72  * Macros to reverse byte order
73  */
74 #define	BSWAP_8(x)	((x) & 0xff)
75 #define	BSWAP_16(x)	((BSWAP_8(x) << 8) | BSWAP_8((x) >> 8))
76 #define	BSWAP_32(x)	((BSWAP_16(x) << 16) | BSWAP_16((x) >> 16))
77 
78 #define	SWAP_16(x)	(x) = BSWAP_16(x)
79 #define	SWAP_32(x)	(x) = BSWAP_32(x)
80 
81 static int target_requires_swap;
82 
83 /*PRINTFLIKE1*/
84 static void __printflike(1, 2)
85 parseterminate(const char *fmt, ...)
86 {
87 	static char msgbuf[1024]; /* sigh */
88 	va_list ap;
89 
90 	va_start(ap, fmt);
91 	vsnprintf(msgbuf, sizeof (msgbuf), fmt, ap);
92 	va_end(ap);
93 
94 	terminate("%s: %s\n", curfile, msgbuf);
95 }
96 
97 static void
98 ctf_buf_grow(ctf_buf_t *b)
99 {
100 	off_t ptroff = b->ctb_ptr - b->ctb_base;
101 
102 	b->ctb_size += CTF_BUF_CHUNK_SIZE;
103 	b->ctb_base = xrealloc(b->ctb_base, b->ctb_size);
104 	b->ctb_end = b->ctb_base + b->ctb_size;
105 	b->ctb_ptr = b->ctb_base + ptroff;
106 }
107 
108 static ctf_buf_t *
109 ctf_buf_new(void)
110 {
111 	ctf_buf_t *b = xcalloc(sizeof (ctf_buf_t));
112 
113 	strtab_create(&b->ctb_strtab);
114 	ctf_buf_grow(b);
115 
116 	return (b);
117 }
118 
119 static void
120 ctf_buf_free(ctf_buf_t *b)
121 {
122 	strtab_destroy(&b->ctb_strtab);
123 	free(b->ctb_base);
124 	free(b);
125 }
126 
127 static uint_t
128 ctf_buf_cur(ctf_buf_t *b)
129 {
130 	return (b->ctb_ptr - b->ctb_base);
131 }
132 
133 static void
134 ctf_buf_write(ctf_buf_t *b, void const *p, size_t n)
135 {
136 	size_t len;
137 
138 	while (n != 0) {
139 		if (b->ctb_ptr == b->ctb_end)
140 			ctf_buf_grow(b);
141 
142 		len = MIN((size_t)(b->ctb_end - b->ctb_ptr), n);
143 		bcopy(p, b->ctb_ptr, len);
144 		b->ctb_ptr += len;
145 
146 		p = (char const *)p + len;
147 		n -= len;
148 	}
149 }
150 
151 static int
152 write_label(void *arg1, void *arg2)
153 {
154 	labelent_t *le = arg1;
155 	ctf_buf_t *b = arg2;
156 	ctf_lblent_t ctl;
157 
158 	ctl.ctl_label = strtab_insert(&b->ctb_strtab, le->le_name);
159 	ctl.ctl_typeidx = le->le_idx;
160 
161 	if (target_requires_swap) {
162 		SWAP_32(ctl.ctl_label);
163 		SWAP_32(ctl.ctl_typeidx);
164 	}
165 
166 	ctf_buf_write(b, &ctl, sizeof (ctl));
167 
168 	return (1);
169 }
170 
171 static void
172 write_objects(iidesc_t *idp, ctf_buf_t *b)
173 {
174 	ushort_t id = (idp ? idp->ii_dtype->t_id : 0);
175 
176 	ctf_buf_write(b, &id, sizeof (id));
177 
178 	if (target_requires_swap) {
179 		SWAP_16(id);
180 	}
181 
182 	debug(3, "Wrote object %s (%d)\n", (idp ? idp->ii_name : "(null)"), id);
183 }
184 
185 static void
186 write_functions(iidesc_t *idp, ctf_buf_t *b)
187 {
188 	ushort_t fdata[2];
189 	ushort_t id;
190 	int nargs;
191 	int i;
192 
193 	if (!idp) {
194 		fdata[0] = 0;
195 		ctf_buf_write(b, &fdata[0], sizeof (fdata[0]));
196 
197 		debug(3, "Wrote function (null)\n");
198 		return;
199 	}
200 
201 	nargs = idp->ii_nargs + (idp->ii_vargs != 0);
202 
203 	if (nargs > CTF_MAX_VLEN) {
204 		terminate("function %s has too many args: %d > %d\n",
205 		    idp->ii_name, nargs, CTF_MAX_VLEN);
206 	}
207 
208 	fdata[0] = CTF_TYPE_INFO(CTF_K_FUNCTION, 1, nargs);
209 	fdata[1] = idp->ii_dtype->t_id;
210 
211 	if (target_requires_swap) {
212 		SWAP_16(fdata[0]);
213 		SWAP_16(fdata[1]);
214 	}
215 
216 	ctf_buf_write(b, fdata, sizeof (fdata));
217 
218 	for (i = 0; i < idp->ii_nargs; i++) {
219 		id = idp->ii_args[i]->t_id;
220 
221 		if (target_requires_swap) {
222 			SWAP_16(id);
223 		}
224 
225 		ctf_buf_write(b, &id, sizeof (id));
226 	}
227 
228 	if (idp->ii_vargs) {
229 		id = 0;
230 		ctf_buf_write(b, &id, sizeof (id));
231 	}
232 
233 	debug(3, "Wrote function %s (%d args)\n", idp->ii_name, nargs);
234 }
235 
236 /*
237  * Depending on the size of the type being described, either a ctf_stype_t (for
238  * types with size < CTF_LSTRUCT_THRESH) or a ctf_type_t (all others) will be
239  * written.  We isolate the determination here so the rest of the writer code
240  * doesn't need to care.
241  */
242 static void
243 write_sized_type_rec(ctf_buf_t *b, ctf_type_t *ctt, size_t size)
244 {
245 	if (size > CTF_MAX_SIZE) {
246 		ctt->ctt_size = CTF_LSIZE_SENT;
247 		ctt->ctt_lsizehi = CTF_SIZE_TO_LSIZE_HI(size);
248 		ctt->ctt_lsizelo = CTF_SIZE_TO_LSIZE_LO(size);
249 		if (target_requires_swap) {
250 			SWAP_32(ctt->ctt_name);
251 			SWAP_16(ctt->ctt_info);
252 			SWAP_16(ctt->ctt_size);
253 			SWAP_32(ctt->ctt_lsizehi);
254 			SWAP_32(ctt->ctt_lsizelo);
255 		}
256 		ctf_buf_write(b, ctt, sizeof (*ctt));
257 	} else {
258 		ctf_stype_t *cts = (ctf_stype_t *)ctt;
259 
260 		cts->ctt_size = (ushort_t)size;
261 
262 		if (target_requires_swap) {
263 			SWAP_32(cts->ctt_name);
264 			SWAP_16(cts->ctt_info);
265 			SWAP_16(cts->ctt_size);
266 		}
267 
268 		ctf_buf_write(b, cts, sizeof (*cts));
269 	}
270 }
271 
272 static void
273 write_unsized_type_rec(ctf_buf_t *b, ctf_type_t *ctt)
274 {
275 	ctf_stype_t *cts = (ctf_stype_t *)ctt;
276 
277 	if (target_requires_swap) {
278 		SWAP_32(cts->ctt_name);
279 		SWAP_16(cts->ctt_info);
280 		SWAP_16(cts->ctt_size);
281 	}
282 
283 	ctf_buf_write(b, cts, sizeof (*cts));
284 }
285 
286 static int
287 write_type(void *arg1, void *arg2)
288 {
289 	tdesc_t *tp = arg1;
290 	ctf_buf_t *b = arg2;
291 	elist_t *ep;
292 	mlist_t *mp;
293 	intr_t *ip;
294 
295 	size_t offset;
296 	uint_t encoding;
297 	uint_t data;
298 	int isroot = tp->t_flags & TDESC_F_ISROOT;
299 	int i;
300 
301 	ctf_type_t ctt;
302 	ctf_array_t cta;
303 	ctf_member_t ctm;
304 	ctf_lmember_t ctlm;
305 	ctf_enum_t cte;
306 	ushort_t id;
307 
308 	ctlm.ctlm_pad = 0;
309 
310 	/*
311 	 * There shouldn't be any holes in the type list (where a hole is
312 	 * defined as two consecutive tdescs without consecutive ids), but
313 	 * check for them just in case.  If we do find holes, we need to make
314 	 * fake entries to fill the holes, or we won't be able to reconstruct
315 	 * the tree from the written data.
316 	 */
317 	if (++b->nptent < CTF_TYPE_TO_INDEX(tp->t_id)) {
318 		debug(2, "genctf: type hole from %d < x < %d\n",
319 		    b->nptent - 1, CTF_TYPE_TO_INDEX(tp->t_id));
320 
321 		ctt.ctt_name = CTF_TYPE_NAME(CTF_STRTAB_0, 0);
322 		ctt.ctt_info = CTF_TYPE_INFO(0, 0, 0);
323 		while (b->nptent < CTF_TYPE_TO_INDEX(tp->t_id)) {
324 			write_sized_type_rec(b, &ctt, 0);
325 			b->nptent++;
326 		}
327 	}
328 
329 	offset = strtab_insert(&b->ctb_strtab, tp->t_name);
330 	ctt.ctt_name = CTF_TYPE_NAME(CTF_STRTAB_0, offset);
331 
332 	switch (tp->t_type) {
333 	case INTRINSIC:
334 		ip = tp->t_intr;
335 		if (ip->intr_type == INTR_INT)
336 			ctt.ctt_info = CTF_TYPE_INFO(CTF_K_INTEGER,
337 			    isroot, 1);
338 		else
339 			ctt.ctt_info = CTF_TYPE_INFO(CTF_K_FLOAT, isroot, 1);
340 		write_sized_type_rec(b, &ctt, tp->t_size);
341 
342 		encoding = 0;
343 
344 		if (ip->intr_type == INTR_INT) {
345 			if (ip->intr_signed)
346 				encoding |= CTF_INT_SIGNED;
347 			if (ip->intr_iformat == 'c')
348 				encoding |= CTF_INT_CHAR;
349 			else if (ip->intr_iformat == 'b')
350 				encoding |= CTF_INT_BOOL;
351 			else if (ip->intr_iformat == 'v')
352 				encoding |= CTF_INT_VARARGS;
353 		} else
354 			encoding = ip->intr_fformat;
355 
356 		data = CTF_INT_DATA(encoding, ip->intr_offset, ip->intr_nbits);
357 		if (target_requires_swap) {
358 			SWAP_32(data);
359 		}
360 		ctf_buf_write(b, &data, sizeof (data));
361 		break;
362 
363 	case POINTER:
364 		ctt.ctt_info = CTF_TYPE_INFO(CTF_K_POINTER, isroot, 0);
365 		ctt.ctt_type = tp->t_tdesc->t_id;
366 		write_unsized_type_rec(b, &ctt);
367 		break;
368 
369 	case ARRAY:
370 		ctt.ctt_info = CTF_TYPE_INFO(CTF_K_ARRAY, isroot, 1);
371 		write_sized_type_rec(b, &ctt, tp->t_size);
372 
373 		cta.cta_contents = tp->t_ardef->ad_contents->t_id;
374 		cta.cta_index = tp->t_ardef->ad_idxtype->t_id;
375 		cta.cta_nelems = tp->t_ardef->ad_nelems;
376 		if (target_requires_swap) {
377 			SWAP_16(cta.cta_contents);
378 			SWAP_16(cta.cta_index);
379 			SWAP_32(cta.cta_nelems);
380 		}
381 		ctf_buf_write(b, &cta, sizeof (cta));
382 		break;
383 
384 	case STRUCT:
385 	case UNION:
386 		for (i = 0, mp = tp->t_members; mp != NULL; mp = mp->ml_next)
387 			i++; /* count up struct or union members */
388 
389 		if (i > CTF_MAX_VLEN) {
390 			warning("sou %s has too many members: %d > %d\n",
391 			    tdesc_name(tp), i, CTF_MAX_VLEN);
392 			i = CTF_MAX_VLEN;
393 		}
394 
395 		if (tp->t_type == STRUCT)
396 			ctt.ctt_info = CTF_TYPE_INFO(CTF_K_STRUCT, isroot, i);
397 		else
398 			ctt.ctt_info = CTF_TYPE_INFO(CTF_K_UNION, isroot, i);
399 
400 		write_sized_type_rec(b, &ctt, tp->t_size);
401 
402 		if (tp->t_size < CTF_LSTRUCT_THRESH) {
403 			for (mp = tp->t_members; mp != NULL && i > 0;
404 			    mp = mp->ml_next) {
405 				offset = strtab_insert(&b->ctb_strtab,
406 				    mp->ml_name);
407 
408 				ctm.ctm_name = CTF_TYPE_NAME(CTF_STRTAB_0,
409 				    offset);
410 				ctm.ctm_type = mp->ml_type->t_id;
411 				ctm.ctm_offset = mp->ml_offset;
412 				if (target_requires_swap) {
413 					SWAP_32(ctm.ctm_name);
414 					SWAP_16(ctm.ctm_type);
415 					SWAP_16(ctm.ctm_offset);
416 				}
417 				ctf_buf_write(b, &ctm, sizeof (ctm));
418 				i--;
419 			}
420 		} else {
421 			for (mp = tp->t_members; mp != NULL && i > 0;
422 			    mp = mp->ml_next) {
423 				offset = strtab_insert(&b->ctb_strtab,
424 				    mp->ml_name);
425 
426 				ctlm.ctlm_name = CTF_TYPE_NAME(CTF_STRTAB_0,
427 				    offset);
428 				ctlm.ctlm_type = mp->ml_type->t_id;
429 				ctlm.ctlm_offsethi =
430 				    CTF_OFFSET_TO_LMEMHI(mp->ml_offset);
431 				ctlm.ctlm_offsetlo =
432 				    CTF_OFFSET_TO_LMEMLO(mp->ml_offset);
433 
434 				if (target_requires_swap) {
435 					SWAP_32(ctlm.ctlm_name);
436 					SWAP_16(ctlm.ctlm_type);
437 					SWAP_32(ctlm.ctlm_offsethi);
438 					SWAP_32(ctlm.ctlm_offsetlo);
439 				}
440 
441 				ctf_buf_write(b, &ctlm, sizeof (ctlm));
442 				i--;
443 			}
444 		}
445 		break;
446 
447 	case ENUM:
448 		for (i = 0, ep = tp->t_emem; ep != NULL; ep = ep->el_next)
449 			i++; /* count up enum members */
450 
451 		if (i > CTF_MAX_VLEN) {
452 			warning("enum %s has too many values: %d > %d\n",
453 			    tdesc_name(tp), i, CTF_MAX_VLEN);
454 			i = CTF_MAX_VLEN;
455 		}
456 
457 		ctt.ctt_info = CTF_TYPE_INFO(CTF_K_ENUM, isroot, i);
458 		write_sized_type_rec(b, &ctt, tp->t_size);
459 
460 		for (ep = tp->t_emem; ep != NULL && i > 0; ep = ep->el_next) {
461 			offset = strtab_insert(&b->ctb_strtab, ep->el_name);
462 			cte.cte_name = CTF_TYPE_NAME(CTF_STRTAB_0, offset);
463 			cte.cte_value = ep->el_number;
464 
465 			if (target_requires_swap) {
466 				SWAP_32(cte.cte_name);
467 				SWAP_32(cte.cte_value);
468 			}
469 
470 			ctf_buf_write(b, &cte, sizeof (cte));
471 			i--;
472 		}
473 		break;
474 
475 	case FORWARD:
476 		ctt.ctt_info = CTF_TYPE_INFO(CTF_K_FORWARD, isroot, 0);
477 		ctt.ctt_type = 0;
478 		write_unsized_type_rec(b, &ctt);
479 		break;
480 
481 	case TYPEDEF:
482 		ctt.ctt_info = CTF_TYPE_INFO(CTF_K_TYPEDEF, isroot, 0);
483 		ctt.ctt_type = tp->t_tdesc->t_id;
484 		write_unsized_type_rec(b, &ctt);
485 		break;
486 
487 	case VOLATILE:
488 		ctt.ctt_info = CTF_TYPE_INFO(CTF_K_VOLATILE, isroot, 0);
489 		ctt.ctt_type = tp->t_tdesc->t_id;
490 		write_unsized_type_rec(b, &ctt);
491 		break;
492 
493 	case CONST:
494 		ctt.ctt_info = CTF_TYPE_INFO(CTF_K_CONST, isroot, 0);
495 		ctt.ctt_type = tp->t_tdesc->t_id;
496 		write_unsized_type_rec(b, &ctt);
497 		break;
498 
499 	case FUNCTION:
500 		i = tp->t_fndef->fn_nargs + tp->t_fndef->fn_vargs;
501 
502 		if (i > CTF_MAX_VLEN) {
503 			terminate("function %s has too many args: %d > %d\n",
504 			    tdesc_name(tp), i, CTF_MAX_VLEN);
505 		}
506 
507 		ctt.ctt_info = CTF_TYPE_INFO(CTF_K_FUNCTION, isroot, i);
508 		ctt.ctt_type = tp->t_fndef->fn_ret->t_id;
509 		write_unsized_type_rec(b, &ctt);
510 
511 		for (i = 0; i < (int) tp->t_fndef->fn_nargs; i++) {
512 			id = tp->t_fndef->fn_args[i]->t_id;
513 
514 			if (target_requires_swap) {
515 				SWAP_16(id);
516 			}
517 
518 			ctf_buf_write(b, &id, sizeof (id));
519 		}
520 
521 		if (tp->t_fndef->fn_vargs) {
522 			id = 0;
523 			ctf_buf_write(b, &id, sizeof (id));
524 			i++;
525 		}
526 
527 		if (i & 1) {
528 			id = 0;
529 			ctf_buf_write(b, &id, sizeof (id));
530 		}
531 		break;
532 
533 	case RESTRICT:
534 		ctt.ctt_info = CTF_TYPE_INFO(CTF_K_RESTRICT, isroot, 0);
535 		ctt.ctt_type = tp->t_tdesc->t_id;
536 		write_unsized_type_rec(b, &ctt);
537 		break;
538 
539 	default:
540 		warning("Can't write unknown type %d\n", tp->t_type);
541 	}
542 
543 	debug(3, "Wrote type %d %s\n", tp->t_id, tdesc_name(tp));
544 
545 	return (1);
546 }
547 
548 typedef struct resbuf {
549 	caddr_t rb_base;
550 	caddr_t rb_ptr;
551 	size_t rb_size;
552 	z_stream rb_zstr;
553 } resbuf_t;
554 
555 static void
556 rbzs_grow(resbuf_t *rb)
557 {
558 	off_t ptroff = (caddr_t)rb->rb_zstr.next_out - rb->rb_base;
559 
560 	rb->rb_size += RES_BUF_CHUNK_SIZE;
561 	rb->rb_base = xrealloc(rb->rb_base, rb->rb_size);
562 	rb->rb_ptr = rb->rb_base + ptroff;
563 	rb->rb_zstr.next_out = (Bytef *)(rb->rb_ptr);
564 	rb->rb_zstr.avail_out += RES_BUF_CHUNK_SIZE;
565 }
566 
567 static void
568 compress_start(resbuf_t *rb)
569 {
570 	int rc;
571 
572 	rb->rb_zstr.zalloc = (alloc_func)0;
573 	rb->rb_zstr.zfree = (free_func)0;
574 	rb->rb_zstr.opaque = (voidpf)0;
575 
576 	if ((rc = deflateInit(&rb->rb_zstr, Z_BEST_COMPRESSION)) != Z_OK)
577 		parseterminate("zlib start failed: %s", zError(rc));
578 }
579 
580 static ssize_t
581 compress_buffer(void *buf, size_t n, void *data)
582 {
583 	resbuf_t *rb = (resbuf_t *)data;
584 	int rc;
585 
586 	rb->rb_zstr.next_out = (Bytef *)rb->rb_ptr;
587 	rb->rb_zstr.avail_out = rb->rb_size - (rb->rb_ptr - rb->rb_base);
588 	rb->rb_zstr.next_in = buf;
589 	rb->rb_zstr.avail_in = n;
590 
591 	while (rb->rb_zstr.avail_in) {
592 		if (rb->rb_zstr.avail_out == 0)
593 			rbzs_grow(rb);
594 
595 		if ((rc = deflate(&rb->rb_zstr, Z_NO_FLUSH)) != Z_OK)
596 			parseterminate("zlib deflate failed: %s", zError(rc));
597 	}
598 	rb->rb_ptr = (caddr_t)rb->rb_zstr.next_out;
599 
600 	return (n);
601 }
602 
603 static void
604 compress_flush(resbuf_t *rb, int type)
605 {
606 	int rc;
607 
608 	for (;;) {
609 		if (rb->rb_zstr.avail_out == 0)
610 			rbzs_grow(rb);
611 
612 		rc = deflate(&rb->rb_zstr, type);
613 		if ((type == Z_FULL_FLUSH && rc == Z_BUF_ERROR) ||
614 		    (type == Z_FINISH && rc == Z_STREAM_END))
615 			break;
616 		else if (rc != Z_OK)
617 			parseterminate("zlib finish failed: %s", zError(rc));
618 	}
619 	rb->rb_ptr = (caddr_t)rb->rb_zstr.next_out;
620 }
621 
622 static void
623 compress_end(resbuf_t *rb)
624 {
625 	int rc;
626 
627 	compress_flush(rb, Z_FINISH);
628 
629 	if ((rc = deflateEnd(&rb->rb_zstr)) != Z_OK)
630 		parseterminate("zlib end failed: %s", zError(rc));
631 }
632 
633 /*
634  * Pad the buffer to a power-of-2 boundary
635  */
636 static void
637 pad_buffer(ctf_buf_t *buf, int align)
638 {
639 	uint_t cur = ctf_buf_cur(buf);
640 	ssize_t topad = (align - (cur % align)) % align;
641 	static const char pad[8] = { 0 };
642 
643 	while (topad > 0) {
644 		ctf_buf_write(buf, pad, (topad > 8 ? 8 : topad));
645 		topad -= 8;
646 	}
647 }
648 
649 static ssize_t
650 bcopy_data(void *buf, size_t n, void *data)
651 {
652 	caddr_t *posp = (caddr_t *)data;
653 	bcopy(buf, *posp, n);
654 	*posp += n;
655 	return (n);
656 }
657 
658 static caddr_t
659 write_buffer(ctf_header_t *h, ctf_buf_t *buf, size_t *resszp)
660 {
661 	caddr_t outbuf;
662 	caddr_t bufpos;
663 
664 	outbuf = xmalloc(sizeof (ctf_header_t) + (buf->ctb_ptr - buf->ctb_base)
665 	    + buf->ctb_strtab.str_size);
666 
667 	bufpos = outbuf;
668 	(void) bcopy_data(h, sizeof (ctf_header_t), &bufpos);
669 	(void) bcopy_data(buf->ctb_base, buf->ctb_ptr - buf->ctb_base,
670 	    &bufpos);
671 	(void) strtab_write(&buf->ctb_strtab, bcopy_data, &bufpos);
672 	*resszp = bufpos - outbuf;
673 	return (outbuf);
674 }
675 
676 /*
677  * Create the compression buffer, and fill it with the CTF and string
678  * table data.  We flush the compression state between the two so the
679  * dictionary used for the string tables won't be polluted with values
680  * that made sense for the CTF data.
681  */
682 static caddr_t
683 write_compressed_buffer(ctf_header_t *h, ctf_buf_t *buf, size_t *resszp)
684 {
685 	resbuf_t resbuf;
686 	resbuf.rb_size = RES_BUF_CHUNK_SIZE;
687 	resbuf.rb_base = xmalloc(resbuf.rb_size);
688 	bcopy(h, resbuf.rb_base, sizeof (ctf_header_t));
689 	resbuf.rb_ptr = resbuf.rb_base + sizeof (ctf_header_t);
690 
691 	compress_start(&resbuf);
692 	(void) compress_buffer(buf->ctb_base, buf->ctb_ptr - buf->ctb_base,
693 	    &resbuf);
694 	compress_flush(&resbuf, Z_FULL_FLUSH);
695 	(void) strtab_write(&buf->ctb_strtab, compress_buffer, &resbuf);
696 	compress_end(&resbuf);
697 
698 	*resszp = (resbuf.rb_ptr - resbuf.rb_base);
699 	return (resbuf.rb_base);
700 }
701 
702 caddr_t
703 ctf_gen(iiburst_t *iiburst, size_t *resszp, int do_compress)
704 {
705 	ctf_buf_t *buf = ctf_buf_new();
706 	ctf_header_t h;
707 	caddr_t outbuf;
708 
709 	int i;
710 
711 	target_requires_swap = do_compress & CTF_SWAP_BYTES;
712 	do_compress &= ~CTF_SWAP_BYTES;
713 
714 	/*
715 	 * Prepare the header, and create the CTF output buffers.  The data
716 	 * object section and function section are both lists of 2-byte
717 	 * integers; we pad these out to the next 4-byte boundary if needed.
718 	 */
719 	h.cth_magic = CTF_MAGIC;
720 	h.cth_version = CTF_VERSION;
721 	h.cth_flags = do_compress ? CTF_F_COMPRESS : 0;
722 	h.cth_parlabel = strtab_insert(&buf->ctb_strtab,
723 	    iiburst->iib_td->td_parlabel);
724 	h.cth_parname = strtab_insert(&buf->ctb_strtab,
725 	    iiburst->iib_td->td_parname);
726 
727 	h.cth_lbloff = 0;
728 	(void) list_iter(iiburst->iib_td->td_labels, write_label,
729 	    buf);
730 
731 	pad_buffer(buf, 2);
732 	h.cth_objtoff = ctf_buf_cur(buf);
733 	for (i = 0; i < iiburst->iib_nobjts; i++)
734 		write_objects(iiburst->iib_objts[i], buf);
735 
736 	pad_buffer(buf, 2);
737 	h.cth_funcoff = ctf_buf_cur(buf);
738 	for (i = 0; i < iiburst->iib_nfuncs; i++)
739 		write_functions(iiburst->iib_funcs[i], buf);
740 
741 	pad_buffer(buf, 4);
742 	h.cth_typeoff = ctf_buf_cur(buf);
743 	(void) list_iter(iiburst->iib_types, write_type, buf);
744 
745 	debug(2, "CTF wrote %d types\n", list_count(iiburst->iib_types));
746 
747 	h.cth_stroff = ctf_buf_cur(buf);
748 	h.cth_strlen = strtab_size(&buf->ctb_strtab);
749 
750 	if (target_requires_swap) {
751 		SWAP_16(h.cth_preamble.ctp_magic);
752 		SWAP_32(h.cth_parlabel);
753 		SWAP_32(h.cth_parname);
754 		SWAP_32(h.cth_lbloff);
755 		SWAP_32(h.cth_objtoff);
756 		SWAP_32(h.cth_funcoff);
757 		SWAP_32(h.cth_typeoff);
758 		SWAP_32(h.cth_stroff);
759 		SWAP_32(h.cth_strlen);
760 	}
761 
762 	/*
763 	 * We only do compression for ctfmerge, as ctfconvert is only
764 	 * supposed to be used on intermediary build objects. This is
765 	 * significantly faster.
766 	 */
767 	if (do_compress)
768 		outbuf = write_compressed_buffer(&h, buf, resszp);
769 	else
770 		outbuf = write_buffer(&h, buf, resszp);
771 
772 	ctf_buf_free(buf);
773 	return (outbuf);
774 }
775 
776 static void
777 get_ctt_size(ctf_type_t *ctt, size_t *sizep, size_t *incrementp)
778 {
779 	if (ctt->ctt_size == CTF_LSIZE_SENT) {
780 		*sizep = (size_t)CTF_TYPE_LSIZE(ctt);
781 		*incrementp = sizeof (ctf_type_t);
782 	} else {
783 		*sizep = ctt->ctt_size;
784 		*incrementp = sizeof (ctf_stype_t);
785 	}
786 }
787 
788 static int
789 count_types(ctf_header_t *h, caddr_t data)
790 {
791 	caddr_t dptr = data + h->cth_typeoff;
792 	int count = 0;
793 
794 	dptr = data + h->cth_typeoff;
795 	while (dptr < data + h->cth_stroff) {
796 		void *v = (void *) dptr;
797 		ctf_type_t *ctt = v;
798 		size_t vlen = CTF_INFO_VLEN(ctt->ctt_info);
799 		size_t size, increment;
800 
801 		get_ctt_size(ctt, &size, &increment);
802 
803 		switch (CTF_INFO_KIND(ctt->ctt_info)) {
804 		case CTF_K_INTEGER:
805 		case CTF_K_FLOAT:
806 			dptr += 4;
807 			break;
808 		case CTF_K_POINTER:
809 		case CTF_K_FORWARD:
810 		case CTF_K_TYPEDEF:
811 		case CTF_K_VOLATILE:
812 		case CTF_K_CONST:
813 		case CTF_K_RESTRICT:
814 		case CTF_K_FUNCTION:
815 			dptr += sizeof (ushort_t) * (vlen + (vlen & 1));
816 			break;
817 		case CTF_K_ARRAY:
818 			dptr += sizeof (ctf_array_t);
819 			break;
820 		case CTF_K_STRUCT:
821 		case CTF_K_UNION:
822 			if (size < CTF_LSTRUCT_THRESH)
823 				dptr += sizeof (ctf_member_t) * vlen;
824 			else
825 				dptr += sizeof (ctf_lmember_t) * vlen;
826 			break;
827 		case CTF_K_ENUM:
828 			dptr += sizeof (ctf_enum_t) * vlen;
829 			break;
830 		case CTF_K_UNKNOWN:
831 			break;
832 		default:
833 			parseterminate("Unknown CTF type %d (#%d) at %#jx",
834 			    CTF_INFO_KIND(ctt->ctt_info), count,
835 			    (intmax_t)(dptr - data));
836 		}
837 
838 		dptr += increment;
839 		count++;
840 	}
841 
842 	debug(3, "CTF read %d types\n", count);
843 
844 	return (count);
845 }
846 
847 /*
848  * Resurrect the labels stored in the CTF data, returning the index associated
849  * with a label provided by the caller.  There are several cases, outlined
850  * below.  Note that, given two labels, the one associated with the lesser type
851  * index is considered to be older than the other.
852  *
853  *  1. matchlbl == NULL - return the index of the most recent label.
854  *  2. matchlbl == "BASE" - return the index of the oldest label.
855  *  3. matchlbl != NULL, but doesn't match any labels in the section - warn
856  *	the user, and proceed as if matchlbl == "BASE" (for safety).
857  *  4. matchlbl != NULL, and matches one of the labels in the section - return
858  *	the type index associated with the label.
859  */
860 static int
861 resurrect_labels(ctf_header_t *h, tdata_t *td, caddr_t ctfdata, char *matchlbl)
862 {
863 	caddr_t buf = ctfdata + h->cth_lbloff;
864 	caddr_t sbuf = ctfdata + h->cth_stroff;
865 	size_t bufsz = h->cth_objtoff - h->cth_lbloff;
866 	int lastidx = 0, baseidx = -1;
867 	char *baselabel = NULL;
868 	ctf_lblent_t *ctl;
869 	void *v = (void *) buf;
870 
871 	for (ctl = v; (caddr_t)ctl < buf + bufsz; ctl++) {
872 		char *label = sbuf + ctl->ctl_label;
873 
874 		lastidx = ctl->ctl_typeidx;
875 
876 		debug(3, "Resurrected label %s type idx %d\n", label, lastidx);
877 
878 		tdata_label_add(td, label, lastidx);
879 
880 		if (baseidx == -1) {
881 			baseidx = lastidx;
882 			baselabel = label;
883 			if (matchlbl != NULL && streq(matchlbl, "BASE"))
884 				return (lastidx);
885 		}
886 
887 		if (matchlbl != NULL && streq(label, matchlbl))
888 			return (lastidx);
889 	}
890 
891 	if (matchlbl != NULL) {
892 		/* User provided a label that didn't match */
893 		warning("%s: Cannot find label `%s' - using base (%s)\n",
894 		    curfile, matchlbl, (baselabel ? baselabel : "NONE"));
895 
896 		tdata_label_free(td);
897 		tdata_label_add(td, baselabel, baseidx);
898 
899 		return (baseidx);
900 	}
901 
902 	return (lastidx);
903 }
904 
905 static void
906 resurrect_objects(ctf_header_t *h, tdata_t *td, tdesc_t **tdarr, int tdsize,
907     caddr_t ctfdata, symit_data_t *si)
908 {
909 	caddr_t buf = ctfdata + h->cth_objtoff;
910 	size_t bufsz = h->cth_funcoff - h->cth_objtoff;
911 	caddr_t dptr;
912 
913 	symit_reset(si);
914 	for (dptr = buf; dptr < buf + bufsz; dptr += 2) {
915 		void *v = (void *) dptr;
916 		ushort_t id = *((ushort_t *)v);
917 		iidesc_t *ii;
918 		GElf_Sym *sym;
919 
920 		if (!(sym = symit_next(si, STT_OBJECT)) && id != 0) {
921 			parseterminate(
922 			    "Unexpected end of object symbols at %ju of %zu",
923 			    (intmax_t)(dptr - buf), bufsz);
924 		}
925 
926 		if (id == 0) {
927 			debug(3, "Skipping null object\n");
928 			continue;
929 		} else if (id >= tdsize) {
930 			parseterminate("Reference to invalid type %d", id);
931 		}
932 
933 		ii = iidesc_new(symit_name(si));
934 		ii->ii_dtype = tdarr[id];
935 		if (GELF_ST_BIND(sym->st_info) == STB_LOCAL) {
936 			ii->ii_type = II_SVAR;
937 			ii->ii_owner = xstrdup(symit_curfile(si));
938 		} else
939 			ii->ii_type = II_GVAR;
940 		hash_add(td->td_iihash, ii);
941 
942 		debug(3, "Resurrected %s object %s (%d) from %s\n",
943 		    (ii->ii_type == II_GVAR ? "global" : "static"),
944 		    ii->ii_name, id, (ii->ii_owner ? ii->ii_owner : "(none)"));
945 	}
946 }
947 
948 static void
949 resurrect_functions(ctf_header_t *h, tdata_t *td, tdesc_t **tdarr, int tdsize,
950     caddr_t ctfdata, symit_data_t *si)
951 {
952 	caddr_t buf = ctfdata + h->cth_funcoff;
953 	size_t bufsz = h->cth_typeoff - h->cth_funcoff;
954 	caddr_t dptr = buf;
955 	iidesc_t *ii;
956 	ushort_t info;
957 	ushort_t retid;
958 	GElf_Sym *sym;
959 	int i;
960 
961 	symit_reset(si);
962 	while (dptr < buf + bufsz) {
963 		void *v = (void *) dptr;
964 		info = *((ushort_t *)v);
965 		dptr += 2;
966 
967 		if (!(sym = symit_next(si, STT_FUNC)) && info != 0)
968 			parseterminate("Unexpected end of function symbols");
969 
970 		if (info == 0) {
971 			debug(3, "Skipping null function (%s)\n",
972 			    symit_name(si));
973 			continue;
974 		}
975 
976 		v = (void *) dptr;
977 		retid = *((ushort_t *)v);
978 		dptr += 2;
979 
980 		if (retid >= tdsize)
981 			parseterminate("Reference to invalid type %d", retid);
982 
983 		ii = iidesc_new(symit_name(si));
984 		ii->ii_dtype = tdarr[retid];
985 		if (GELF_ST_BIND(sym->st_info) == STB_LOCAL) {
986 			ii->ii_type = II_SFUN;
987 			ii->ii_owner = xstrdup(symit_curfile(si));
988 		} else
989 			ii->ii_type = II_GFUN;
990 		ii->ii_nargs = CTF_INFO_VLEN(info);
991 		if (ii->ii_nargs)
992 			ii->ii_args =
993 			    xmalloc(sizeof (tdesc_t *) * ii->ii_nargs);
994 
995 		for (i = 0; i < ii->ii_nargs; i++, dptr += 2) {
996 			v = (void *) dptr;
997 			ushort_t id = *((ushort_t *)v);
998 			if (id >= tdsize)
999 				parseterminate("Reference to invalid type %d",
1000 				    id);
1001 			ii->ii_args[i] = tdarr[id];
1002 		}
1003 
1004 		if (ii->ii_nargs && ii->ii_args[ii->ii_nargs - 1] == NULL) {
1005 			ii->ii_nargs--;
1006 			ii->ii_vargs = 1;
1007 		}
1008 
1009 		hash_add(td->td_iihash, ii);
1010 
1011 		debug(3, "Resurrected %s function %s (%d, %d args)\n",
1012 		    (ii->ii_type == II_GFUN ? "global" : "static"),
1013 		    ii->ii_name, retid, ii->ii_nargs);
1014 	}
1015 }
1016 
1017 static void
1018 resurrect_types(ctf_header_t *h, tdata_t *td, tdesc_t **tdarr, int tdsize,
1019     caddr_t ctfdata, int maxid)
1020 {
1021 	caddr_t buf = ctfdata + h->cth_typeoff;
1022 	size_t bufsz = h->cth_stroff - h->cth_typeoff;
1023 	caddr_t sbuf = ctfdata + h->cth_stroff;
1024 	caddr_t dptr = buf;
1025 	tdesc_t *tdp;
1026 	uint_t data;
1027 	uint_t encoding;
1028 	size_t size, increment;
1029 	int tcnt;
1030 	int iicnt = 0;
1031 	tid_t tid, argid;
1032 	int kind, vlen;
1033 	int i;
1034 
1035 	elist_t **epp;
1036 	mlist_t **mpp;
1037 	intr_t *ip;
1038 
1039 	ctf_type_t *ctt;
1040 	ctf_array_t *cta;
1041 	ctf_enum_t *cte;
1042 
1043 	/*
1044 	 * A maxid of zero indicates a request to resurrect all types, so reset
1045 	 * maxid to the maximum type id.
1046 	 */
1047 	if (maxid == 0)
1048 		maxid = CTF_MAX_TYPE;
1049 
1050 	for (dptr = buf, tcnt = 0, tid = 1; dptr < buf + bufsz; tcnt++, tid++) {
1051 		if (tid > maxid)
1052 			break;
1053 
1054 		if (tid >= tdsize)
1055 			parseterminate("Reference to invalid type %d", tid);
1056 
1057 		void *v = (void *) dptr;
1058 		ctt = v;
1059 
1060 		get_ctt_size(ctt, &size, &increment);
1061 		dptr += increment;
1062 
1063 		tdp = tdarr[tid];
1064 
1065 		if (CTF_NAME_STID(ctt->ctt_name) != CTF_STRTAB_0)
1066 			parseterminate(
1067 			    "Unable to cope with non-zero strtab id");
1068 		if (CTF_NAME_OFFSET(ctt->ctt_name) != 0) {
1069 			tdp->t_name =
1070 			    xstrdup(sbuf + CTF_NAME_OFFSET(ctt->ctt_name));
1071 		} else
1072 			tdp->t_name = NULL;
1073 
1074 		kind = CTF_INFO_KIND(ctt->ctt_info);
1075 		vlen = CTF_INFO_VLEN(ctt->ctt_info);
1076 
1077 		switch (kind) {
1078 		case CTF_K_INTEGER:
1079 			tdp->t_type = INTRINSIC;
1080 			tdp->t_size = size;
1081 
1082 			v = (void *) dptr;
1083 			data = *((uint_t *)v);
1084 			dptr += sizeof (uint_t);
1085 			encoding = CTF_INT_ENCODING(data);
1086 
1087 			ip = xmalloc(sizeof (intr_t));
1088 			ip->intr_type = INTR_INT;
1089 			ip->intr_signed = (encoding & CTF_INT_SIGNED) ? 1 : 0;
1090 
1091 			if (encoding & CTF_INT_CHAR)
1092 				ip->intr_iformat = 'c';
1093 			else if (encoding & CTF_INT_BOOL)
1094 				ip->intr_iformat = 'b';
1095 			else if (encoding & CTF_INT_VARARGS)
1096 				ip->intr_iformat = 'v';
1097 			else
1098 				ip->intr_iformat = '\0';
1099 
1100 			ip->intr_offset = CTF_INT_OFFSET(data);
1101 			ip->intr_nbits = CTF_INT_BITS(data);
1102 			tdp->t_intr = ip;
1103 			break;
1104 
1105 		case CTF_K_FLOAT:
1106 			tdp->t_type = INTRINSIC;
1107 			tdp->t_size = size;
1108 
1109 			v = (void *) dptr;
1110 			data = *((uint_t *)v);
1111 			dptr += sizeof (uint_t);
1112 
1113 			ip = xcalloc(sizeof (intr_t));
1114 			ip->intr_type = INTR_REAL;
1115 			ip->intr_fformat = CTF_FP_ENCODING(data);
1116 			ip->intr_offset = CTF_FP_OFFSET(data);
1117 			ip->intr_nbits = CTF_FP_BITS(data);
1118 			tdp->t_intr = ip;
1119 			break;
1120 
1121 		case CTF_K_POINTER:
1122 			tdp->t_type = POINTER;
1123 			tdp->t_tdesc = tdarr[ctt->ctt_type];
1124 			break;
1125 
1126 		case CTF_K_ARRAY:
1127 			tdp->t_type = ARRAY;
1128 			tdp->t_size = size;
1129 
1130 			v = (void *) dptr;
1131 			cta = v;
1132 			dptr += sizeof (ctf_array_t);
1133 
1134 			tdp->t_ardef = xmalloc(sizeof (ardef_t));
1135 			tdp->t_ardef->ad_contents = tdarr[cta->cta_contents];
1136 			tdp->t_ardef->ad_idxtype = tdarr[cta->cta_index];
1137 			tdp->t_ardef->ad_nelems = cta->cta_nelems;
1138 			break;
1139 
1140 		case CTF_K_STRUCT:
1141 		case CTF_K_UNION:
1142 			tdp->t_type = (kind == CTF_K_STRUCT ? STRUCT : UNION);
1143 			tdp->t_size = size;
1144 
1145 			if (size < CTF_LSTRUCT_THRESH) {
1146 				for (i = 0, mpp = &tdp->t_members; i < vlen;
1147 				    i++, mpp = &((*mpp)->ml_next)) {
1148 					v = (void *) dptr;
1149 					ctf_member_t *ctm = v;
1150 					dptr += sizeof (ctf_member_t);
1151 
1152 					*mpp = xmalloc(sizeof (mlist_t));
1153 					(*mpp)->ml_name = xstrdup(sbuf +
1154 					    ctm->ctm_name);
1155 					(*mpp)->ml_type = tdarr[ctm->ctm_type];
1156 					(*mpp)->ml_offset = ctm->ctm_offset;
1157 					(*mpp)->ml_size = 0;
1158 					if (ctm->ctm_type > ntypes) {
1159 						parseterminate("Invalid member type ctm_type=%d",
1160 						    ctm->ctm_type);
1161 					}
1162 				}
1163 			} else {
1164 				for (i = 0, mpp = &tdp->t_members; i < vlen;
1165 				    i++, mpp = &((*mpp)->ml_next)) {
1166 					v = (void *) dptr;
1167 					ctf_lmember_t *ctlm = v;
1168 					dptr += sizeof (ctf_lmember_t);
1169 
1170 					*mpp = xmalloc(sizeof (mlist_t));
1171 					(*mpp)->ml_name = xstrdup(sbuf +
1172 					    ctlm->ctlm_name);
1173 					(*mpp)->ml_type =
1174 					    tdarr[ctlm->ctlm_type];
1175 					(*mpp)->ml_offset =
1176 					    (int)CTF_LMEM_OFFSET(ctlm);
1177 					(*mpp)->ml_size = 0;
1178 					if (ctlm->ctlm_type > ntypes) {
1179 						parseterminate("Invalid lmember type ctlm_type=%d",
1180 						    ctlm->ctlm_type);
1181 					}
1182 				}
1183 			}
1184 
1185 			*mpp = NULL;
1186 			break;
1187 
1188 		case CTF_K_ENUM:
1189 			tdp->t_type = ENUM;
1190 			tdp->t_size = size;
1191 
1192 			for (i = 0, epp = &tdp->t_emem; i < vlen;
1193 			    i++, epp = &((*epp)->el_next)) {
1194 				v = (void *) dptr;
1195 				cte = v;
1196 				dptr += sizeof (ctf_enum_t);
1197 
1198 				*epp = xmalloc(sizeof (elist_t));
1199 				(*epp)->el_name = xstrdup(sbuf + cte->cte_name);
1200 				(*epp)->el_number = cte->cte_value;
1201 			}
1202 			*epp = NULL;
1203 			break;
1204 
1205 		case CTF_K_FORWARD:
1206 			tdp->t_type = FORWARD;
1207 			list_add(&td->td_fwdlist, tdp);
1208 			break;
1209 
1210 		case CTF_K_TYPEDEF:
1211 			tdp->t_type = TYPEDEF;
1212 			tdp->t_tdesc = tdarr[ctt->ctt_type];
1213 			break;
1214 
1215 		case CTF_K_VOLATILE:
1216 			tdp->t_type = VOLATILE;
1217 			tdp->t_tdesc = tdarr[ctt->ctt_type];
1218 			break;
1219 
1220 		case CTF_K_CONST:
1221 			tdp->t_type = CONST;
1222 			tdp->t_tdesc = tdarr[ctt->ctt_type];
1223 			break;
1224 
1225 		case CTF_K_FUNCTION:
1226 			tdp->t_type = FUNCTION;
1227 			tdp->t_fndef = xcalloc(sizeof (fndef_t));
1228 			tdp->t_fndef->fn_ret = tdarr[ctt->ctt_type];
1229 
1230 			v = (void *) (dptr + (sizeof (ushort_t) * (vlen - 1)));
1231 			if (vlen > 0 && *(ushort_t *)v == 0)
1232 				tdp->t_fndef->fn_vargs = 1;
1233 
1234 			tdp->t_fndef->fn_nargs = vlen - tdp->t_fndef->fn_vargs;
1235 			tdp->t_fndef->fn_args = xcalloc(sizeof (tdesc_t) *
1236 			    vlen - tdp->t_fndef->fn_vargs);
1237 
1238 			for (i = 0; i < vlen; i++) {
1239 				v = (void *) dptr;
1240 				argid = *(ushort_t *)v;
1241 				dptr += sizeof (ushort_t);
1242 
1243 				if (argid != 0)
1244 					tdp->t_fndef->fn_args[i] = tdarr[argid];
1245 			}
1246 
1247 			if (vlen & 1)
1248 				dptr += sizeof (ushort_t);
1249 			break;
1250 
1251 		case CTF_K_RESTRICT:
1252 			tdp->t_type = RESTRICT;
1253 			tdp->t_tdesc = tdarr[ctt->ctt_type];
1254 			break;
1255 
1256 		case CTF_K_UNKNOWN:
1257 			break;
1258 
1259 		default:
1260 			warning("Can't parse unknown CTF type %d\n", kind);
1261 		}
1262 
1263 		if (CTF_INFO_ISROOT(ctt->ctt_info)) {
1264 			iidesc_t *ii = iidesc_new(tdp->t_name);
1265 			if (tdp->t_type == STRUCT || tdp->t_type == UNION ||
1266 			    tdp->t_type == ENUM)
1267 				ii->ii_type = II_SOU;
1268 			else
1269 				ii->ii_type = II_TYPE;
1270 			ii->ii_dtype = tdp;
1271 			hash_add(td->td_iihash, ii);
1272 
1273 			iicnt++;
1274 		}
1275 
1276 		debug(3, "Resurrected %d %stype %s (%d)\n", tdp->t_type,
1277 		    (CTF_INFO_ISROOT(ctt->ctt_info) ? "root " : ""),
1278 		    tdesc_name(tdp), tdp->t_id);
1279 	}
1280 
1281 	debug(3, "Resurrected %d types (%d were roots)\n", tcnt, iicnt);
1282 }
1283 
1284 /*
1285  * For lack of other inspiration, we're going to take the boring route.  We
1286  * count the number of types.  This lets us malloc that many tdesc structs
1287  * before we start filling them in.  This has the advantage of allowing us to
1288  * avoid a merge-esque remap step.
1289  */
1290 static tdata_t *
1291 ctf_parse(ctf_header_t *h, caddr_t buf, symit_data_t *si, char *label)
1292 {
1293 	tdata_t *td = tdata_new();
1294 	tdesc_t **tdarr;
1295 	int idx, i;
1296 
1297 	ntypes = count_types(h, buf);
1298 
1299 	/* shudder */
1300 	tdarr = xcalloc(sizeof (tdesc_t *) * (ntypes + 1));
1301 	tdarr[0] = NULL;
1302 	for (i = 1; i <= ntypes; i++) {
1303 		tdarr[i] = xcalloc(sizeof (tdesc_t));
1304 		tdarr[i]->t_id = i;
1305 	}
1306 
1307 	td->td_parlabel = xstrdup(buf + h->cth_stroff + h->cth_parlabel);
1308 
1309 	/* we have the technology - we can rebuild them */
1310 	idx = resurrect_labels(h, td, buf, label);
1311 
1312 	resurrect_objects(h, td, tdarr, ntypes + 1, buf, si);
1313 	resurrect_functions(h, td, tdarr, ntypes + 1, buf, si);
1314 	resurrect_types(h, td, tdarr, ntypes + 1, buf, idx);
1315 
1316 	free(tdarr);
1317 
1318 	td->td_nextid = ntypes + 1;
1319 
1320 	return (td);
1321 }
1322 
1323 static size_t
1324 decompress_ctf(caddr_t cbuf, size_t cbufsz, caddr_t dbuf, size_t dbufsz)
1325 {
1326 	z_stream zstr;
1327 	int rc;
1328 
1329 	zstr.zalloc = (alloc_func)0;
1330 	zstr.zfree = (free_func)0;
1331 	zstr.opaque = (voidpf)0;
1332 
1333 	zstr.next_in = (Bytef *)cbuf;
1334 	zstr.avail_in = cbufsz;
1335 	zstr.next_out = (Bytef *)dbuf;
1336 	zstr.avail_out = dbufsz;
1337 
1338 	if ((rc = inflateInit(&zstr)) != Z_OK ||
1339 	    (rc = inflate(&zstr, Z_NO_FLUSH)) != Z_STREAM_END ||
1340 	    (rc = inflateEnd(&zstr)) != Z_OK) {
1341 		warning("CTF decompress zlib error %s\n", zError(rc));
1342 		return (0);
1343 	}
1344 
1345 	debug(3, "reflated %lu bytes to %lu, pointer at 0x%jx\n",
1346 	    zstr.total_in, zstr.total_out,
1347 	    (intmax_t)((caddr_t)zstr.next_in - cbuf));
1348 
1349 	return (zstr.total_out);
1350 }
1351 
1352 /*
1353  * Reconstruct the type tree from a given buffer of CTF data.  Only the types
1354  * up to the type associated with the provided label, inclusive, will be
1355  * reconstructed.  If a NULL label is provided, all types will be reconstructed.
1356  *
1357  * This function won't work on files that have been uniquified.
1358  */
1359 tdata_t *
1360 ctf_load(char *file, caddr_t buf, size_t bufsz, symit_data_t *si, char *label)
1361 {
1362 	ctf_header_t *h;
1363 	caddr_t ctfdata;
1364 	size_t ctfdatasz;
1365 	tdata_t *td;
1366 
1367 	curfile = file;
1368 
1369 	if (bufsz < sizeof (ctf_header_t))
1370 		parseterminate("Corrupt CTF - short header");
1371 
1372 	void *v = (void *) buf;
1373 	h = v;
1374 	buf += sizeof (ctf_header_t);
1375 	bufsz -= sizeof (ctf_header_t);
1376 
1377 	if (h->cth_magic != CTF_MAGIC)
1378 		parseterminate("Corrupt CTF - bad magic 0x%x", h->cth_magic);
1379 
1380 	if (h->cth_version != CTF_VERSION)
1381 		parseterminate("Unknown CTF version %d", h->cth_version);
1382 
1383 	ctfdatasz = h->cth_stroff + h->cth_strlen;
1384 	if (h->cth_flags & CTF_F_COMPRESS) {
1385 		size_t actual;
1386 
1387 		ctfdata = xmalloc(ctfdatasz);
1388 		if ((actual = decompress_ctf(buf, bufsz, ctfdata, ctfdatasz)) !=
1389 		    ctfdatasz) {
1390 			parseterminate("Corrupt CTF - short decompression "
1391 			    "(was %zu, expecting %zu)", actual, ctfdatasz);
1392 		}
1393 	} else {
1394 		ctfdata = buf;
1395 		ctfdatasz = bufsz;
1396 	}
1397 
1398 	td = ctf_parse(h, ctfdata, si, label);
1399 
1400 	if (h->cth_flags & CTF_F_COMPRESS)
1401 		free(ctfdata);
1402 
1403 	curfile = NULL;
1404 
1405 	return (td);
1406 }
1407