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 * Copyright 2003 Sun Microsystems, Inc.  All rights reserved.
24 * Use is subject to license terms.
25 */
26
27#pragma ident	"@(#)ctf_lib.c	1.3	05/06/08 SMI"
28
29#include <sys/types.h>
30#include <sys/stat.h>
31#include <sys/mman.h>
32#include <ctf_impl.h>
33#include <unistd.h>
34#include <fcntl.h>
35#include <errno.h>
36#include <dlfcn.h>
37#include <gelf.h>
38
39#if !defined(__APPLE__)
40#ifdef _LP64
41static const char *_libctf_zlib = "/usr/lib/64/libz.so";
42#else
43static const char *_libctf_zlib = "/usr/lib/libz.so";
44#endif
45#else
46static const char *_libctf_zlib = "/usr/lib/libz.dylib";
47#endif /* __APPLE__ */
48
49static struct {
50	int (*z_uncompress)(uchar_t *, ulong_t *, const uchar_t *, ulong_t);
51	const char *(*z_error)(int);
52	void *z_dlp;
53} zlib;
54
55#if !defined(__APPLE__)
56static size_t _PAGESIZE;
57static size_t _PAGEMASK;
58
59#pragma init(_libctf_init)
60void
61_libctf_init(void)
62{
63	const char *p = getenv("LIBCTF_DECOMPRESSOR");
64
65	if (p != NULL)
66		_libctf_zlib = p; /* use alternate decompression library */
67
68	_libctf_debug = getenv("LIBCTF_DEBUG") != NULL;
69
70	_PAGESIZE = getpagesize();
71	_PAGEMASK = ~(_PAGESIZE - 1);
72}
73#else
74#define _PAGEMASK (~(getpagesize() - 1)) /* Infrequently used, let's burn the cost of the library call. */
75#endif /* __APPLE__ */
76
77/*
78 * Attempt to dlopen the decompression library and locate the symbols of
79 * interest that we will need to call.  This information in cached so
80 * that multiple calls to ctf_bufopen() do not need to reopen the library.
81 */
82void *
83ctf_zopen(int *errp)
84{
85	ctf_dprintf("decompressing CTF data using %s\n", _libctf_zlib);
86
87	if (zlib.z_dlp != NULL)
88		return (zlib.z_dlp); /* library is already loaded */
89
90	if (access(_libctf_zlib, R_OK) == -1)
91		return (ctf_set_open_errno(errp, ECTF_ZMISSING));
92
93	if ((zlib.z_dlp = dlopen(_libctf_zlib, RTLD_LAZY | RTLD_LOCAL)) == NULL)
94		return (ctf_set_open_errno(errp, ECTF_ZINIT));
95
96	zlib.z_uncompress = (int (*)()) dlsym(zlib.z_dlp, "uncompress");
97	zlib.z_error = (const char *(*)()) dlsym(zlib.z_dlp, "zError");
98
99	if (zlib.z_uncompress == NULL || zlib.z_error == NULL) {
100		(void) dlclose(zlib.z_dlp);
101		bzero(&zlib, sizeof (zlib));
102		return (ctf_set_open_errno(errp, ECTF_ZINIT));
103	}
104
105	return (zlib.z_dlp);
106}
107
108/*
109 * The ctf_bufopen() routine calls these subroutines, defined by <sys/zmod.h>,
110 * which we then patch through to the functions in the decompression library.
111 */
112int
113z_uncompress(void *dst, size_t *dstlen, const void *src, size_t srclen)
114{
115	return (zlib.z_uncompress(dst, (ulong_t *)dstlen, src, srclen));
116}
117
118const char *
119z_strerror(int err)
120{
121	return (zlib.z_error(err));
122}
123
124/*
125 * Convert a 32-bit ELF file header into GElf.
126 */
127static void
128ehdr_to_gelf(const Elf32_Ehdr *src, GElf_Ehdr *dst)
129{
130	bcopy(src->e_ident, dst->e_ident, EI_NIDENT);
131	dst->e_type = src->e_type;
132	dst->e_machine = src->e_machine;
133	dst->e_version = src->e_version;
134	dst->e_entry = (Elf64_Addr)src->e_entry;
135	dst->e_phoff = (Elf64_Off)src->e_phoff;
136	dst->e_shoff = (Elf64_Off)src->e_shoff;
137	dst->e_flags = src->e_flags;
138	dst->e_ehsize = src->e_ehsize;
139	dst->e_phentsize = src->e_phentsize;
140	dst->e_phnum = src->e_phnum;
141	dst->e_shentsize = src->e_shentsize;
142	dst->e_shnum = src->e_shnum;
143	dst->e_shstrndx = src->e_shstrndx;
144}
145
146/*
147 * Convert a 32-bit ELF section header into GElf.
148 */
149static void
150shdr_to_gelf(const Elf32_Shdr *src, GElf_Shdr *dst)
151{
152	dst->sh_name = src->sh_name;
153	dst->sh_type = src->sh_type;
154	dst->sh_flags = src->sh_flags;
155	dst->sh_addr = src->sh_addr;
156	dst->sh_offset = src->sh_offset;
157	dst->sh_size = src->sh_size;
158	dst->sh_link = src->sh_link;
159	dst->sh_info = src->sh_info;
160	dst->sh_addralign = src->sh_addralign;
161	dst->sh_entsize = src->sh_entsize;
162}
163
164/*
165 * In order to mmap a section from the ELF file, we must round down sh_offset
166 * to the previous page boundary, and mmap the surrounding page.  We store
167 * the pointer to the start of the actual section data back into sp->cts_data.
168 */
169const void *
170ctf_sect_mmap(ctf_sect_t *sp, int fd)
171{
172	size_t pageoff = sp->cts_offset & ~_PAGEMASK;
173
174	caddr_t base = mmap64(NULL, sp->cts_size + pageoff, PROT_READ,
175	    MAP_PRIVATE, fd, sp->cts_offset & _PAGEMASK);
176
177	if (base != MAP_FAILED)
178		sp->cts_data = base + pageoff;
179
180	return (base);
181}
182
183/*
184 * Since sp->cts_data has the adjusted offset, we have to again round down
185 * to get the actual mmap address and round up to get the size.
186 */
187void
188ctf_sect_munmap(const ctf_sect_t *sp)
189{
190	uintptr_t addr = (uintptr_t)sp->cts_data;
191	uintptr_t pageoff = addr & ~_PAGEMASK;
192
193	(void) munmap((void *)(addr - pageoff), sp->cts_size + pageoff);
194}
195
196/*
197 * Open the specified file descriptor and return a pointer to a CTF container.
198 * The file can be either an ELF file or raw CTF file.  The caller is
199 * responsible for closing the file descriptor when it is no longer needed.
200 */
201ctf_file_t *
202ctf_fdopen(int fd, int *errp)
203{
204	ctf_sect_t ctfsect, symsect, strsect;
205	ctf_file_t *fp = NULL;
206
207	struct stat64 st;
208	ssize_t nbytes;
209
210	union {
211		ctf_preamble_t ctf;
212		Elf32_Ehdr e32;
213		GElf_Ehdr e64;
214	} hdr;
215
216	bzero(&ctfsect, sizeof (ctf_sect_t));
217	bzero(&symsect, sizeof (ctf_sect_t));
218	bzero(&strsect, sizeof (ctf_sect_t));
219	bzero(&hdr.ctf, sizeof (hdr));
220
221	if (fstat64(fd, &st) == -1)
222		return (ctf_set_open_errno(errp, errno));
223
224	if ((nbytes = pread64(fd, &hdr.ctf, sizeof (hdr), 0)) <= 0)
225		return (ctf_set_open_errno(errp, nbytes < 0? errno : ECTF_FMT));
226
227	/*
228	 * If we have read enough bytes to form a CTF header and the magic
229	 * string matches, attempt to interpret the file as raw CTF.
230	 */
231	if (nbytes >= sizeof (ctf_preamble_t) &&
232	    hdr.ctf.ctp_magic == CTF_MAGIC) {
233		if (hdr.ctf.ctp_version > CTF_VERSION)
234			return (ctf_set_open_errno(errp, ECTF_CTFVERS));
235
236		ctfsect.cts_data = mmap64(NULL, st.st_size, PROT_READ,
237		    MAP_PRIVATE, fd, 0);
238
239		if (ctfsect.cts_data == MAP_FAILED)
240			return (ctf_set_open_errno(errp, errno));
241
242		ctfsect.cts_name = _CTF_SECTION;
243		ctfsect.cts_type = SHT_PROGBITS;
244		ctfsect.cts_flags = SHF_ALLOC;
245		ctfsect.cts_size = (size_t)st.st_size;
246		ctfsect.cts_entsize = 1;
247		ctfsect.cts_offset = 0;
248
249		if ((fp = ctf_bufopen(&ctfsect, NULL, NULL, errp)) == NULL)
250			ctf_sect_munmap(&ctfsect);
251
252		return (fp);
253	}
254
255	/*
256	 * If we have read enough bytes to form an ELF header and the magic
257	 * string matches, attempt to interpret the file as an ELF file.  We
258	 * do our own largefile ELF processing, and convert everything to
259	 * GElf structures so that clients can operate on any data model.
260	 */
261	if (nbytes >= sizeof (Elf32_Ehdr) &&
262	    bcmp(&hdr.e32.e_ident[EI_MAG0], ELFMAG, SELFMAG) == 0) {
263#ifdef	_BIG_ENDIAN
264		uchar_t order = ELFDATA2MSB;
265#else
266		uchar_t order = ELFDATA2LSB;
267#endif
268		GElf_Half i, n;
269		GElf_Shdr *sp;
270
271		void *strs_map;
272		size_t strs_mapsz;
273		const char *strs;
274
275		if (hdr.e32.e_ident[EI_DATA] != order)
276			return (ctf_set_open_errno(errp, ECTF_ENDIAN));
277		if (hdr.e32.e_version != EV_CURRENT)
278			return (ctf_set_open_errno(errp, ECTF_ELFVERS));
279
280		if (hdr.e32.e_ident[EI_CLASS] == ELFCLASS64) {
281			if (nbytes < sizeof (GElf_Ehdr))
282				return (ctf_set_open_errno(errp, ECTF_FMT));
283		} else {
284			Elf32_Ehdr e32 = hdr.e32;
285			ehdr_to_gelf(&e32, &hdr.e64);
286		}
287
288		if (hdr.e64.e_shstrndx >= hdr.e64.e_shnum)
289			return (ctf_set_open_errno(errp, ECTF_CORRUPT));
290
291		n = hdr.e64.e_shnum;
292		nbytes = sizeof (GElf_Shdr) * n;
293
294		if ((sp = malloc(nbytes)) == NULL)
295			return (ctf_set_open_errno(errp, errno));
296
297		/*
298		 * Read in and convert to GElf the array of Shdr structures
299		 * from e_shoff so we can locate sections of interest.
300		 */
301		if (hdr.e32.e_ident[EI_CLASS] == ELFCLASS32) {
302			Elf32_Shdr *sp32;
303
304			nbytes = sizeof (Elf32_Shdr) * n;
305
306			if ((sp32 = malloc(nbytes)) == NULL || pread64(fd,
307			    sp32, nbytes, hdr.e64.e_shoff) != nbytes) {
308				free(sp);
309				return (ctf_set_open_errno(errp, errno));
310			}
311
312			for (i = 0; i < n; i++)
313				shdr_to_gelf(&sp32[i], &sp[i]);
314
315			free(sp32);
316
317		} else if (pread64(fd, sp, nbytes, hdr.e64.e_shoff) != nbytes) {
318			free(sp);
319			return (ctf_set_open_errno(errp, errno));
320		}
321
322		/*
323		 * Now mmap the section header strings section so that we can
324		 * perform string comparison on the section names.
325		 */
326		strs_mapsz = sp[hdr.e64.e_shstrndx].sh_size +
327		    (sp[hdr.e64.e_shstrndx].sh_offset & ~_PAGEMASK);
328
329		strs_map = mmap64(NULL, strs_mapsz, PROT_READ, MAP_PRIVATE,
330		    fd, sp[hdr.e64.e_shstrndx].sh_offset & _PAGEMASK);
331
332		strs = (const char *)strs_map +
333		    (sp[hdr.e64.e_shstrndx].sh_offset & ~_PAGEMASK);
334
335		if (strs_map == MAP_FAILED) {
336			free(sp);
337			return (ctf_set_open_errno(errp, ECTF_MMAP));
338		}
339
340		/*
341		 * Iterate over the section header array looking for the CTF
342		 * section and symbol table.  The strtab is linked to symtab.
343		 */
344		for (i = 0; i < n; i++) {
345			const GElf_Shdr *shp = &sp[i];
346			const GElf_Shdr *lhp = &sp[shp->sh_link];
347
348			if (shp->sh_link >= hdr.e64.e_shnum)
349				continue; /* corrupt sh_link field */
350
351			if (shp->sh_name >= sp[hdr.e64.e_shstrndx].sh_size ||
352			    lhp->sh_name >= sp[hdr.e64.e_shstrndx].sh_size)
353				continue; /* corrupt sh_name field */
354
355			if (shp->sh_type == SHT_PROGBITS &&
356			    strcmp(strs + shp->sh_name, _CTF_SECTION) == 0) {
357				ctfsect.cts_name = strs + shp->sh_name;
358				ctfsect.cts_type = shp->sh_type;
359				ctfsect.cts_flags = shp->sh_flags;
360				ctfsect.cts_size = shp->sh_size;
361				ctfsect.cts_entsize = shp->sh_entsize;
362				ctfsect.cts_offset = (off64_t)shp->sh_offset;
363
364			} else if (shp->sh_type == SHT_SYMTAB) {
365				symsect.cts_name = strs + shp->sh_name;
366				symsect.cts_type = shp->sh_type;
367				symsect.cts_flags = shp->sh_flags;
368				symsect.cts_size = shp->sh_size;
369				symsect.cts_entsize = shp->sh_entsize;
370				symsect.cts_offset = (off64_t)shp->sh_offset;
371
372				strsect.cts_name = strs + lhp->sh_name;
373				strsect.cts_type = lhp->sh_type;
374				strsect.cts_flags = lhp->sh_flags;
375				strsect.cts_size = lhp->sh_size;
376				strsect.cts_entsize = lhp->sh_entsize;
377				strsect.cts_offset = (off64_t)lhp->sh_offset;
378			}
379		}
380
381		free(sp); /* free section header array */
382
383		if (ctfsect.cts_type == SHT_NULL) {
384			(void) munmap(strs_map, strs_mapsz);
385			return (ctf_set_open_errno(errp, ECTF_NOCTFDATA));
386		}
387
388		/*
389		 * Now mmap the CTF data, symtab, and strtab sections and
390		 * call ctf_bufopen() to do the rest of the work.
391		 */
392		if (ctf_sect_mmap(&ctfsect, fd) == MAP_FAILED) {
393			(void) munmap(strs_map, strs_mapsz);
394			return (ctf_set_open_errno(errp, ECTF_MMAP));
395		}
396
397		if (symsect.cts_type != SHT_NULL &&
398		    strsect.cts_type != SHT_NULL) {
399			if (ctf_sect_mmap(&symsect, fd) == MAP_FAILED ||
400			    ctf_sect_mmap(&strsect, fd) == MAP_FAILED) {
401				(void) ctf_set_open_errno(errp, ECTF_MMAP);
402				goto bad; /* unmap all and abort */
403			}
404			fp = ctf_bufopen(&ctfsect, &symsect, &strsect, errp);
405		} else
406			fp = ctf_bufopen(&ctfsect, NULL, NULL, errp);
407bad:
408		if (fp == NULL) {
409			ctf_sect_munmap(&ctfsect);
410			ctf_sect_munmap(&symsect);
411			ctf_sect_munmap(&strsect);
412		} else
413			fp->ctf_flags |= LCTF_MMAP;
414
415		(void) munmap(strs_map, strs_mapsz);
416		return (fp);
417	}
418
419	return (ctf_set_open_errno(errp, ECTF_FMT));
420}
421
422/*
423 * Open the specified file and return a pointer to a CTF container.  The file
424 * can be either an ELF file or raw CTF file.  This is just a convenient
425 * wrapper around ctf_fdopen() for callers.
426 */
427ctf_file_t *
428ctf_open(const char *filename, int *errp)
429{
430	ctf_file_t *fp;
431	int fd;
432
433	if ((fd = open64(filename, O_RDONLY)) == -1) {
434		if (errp != NULL)
435			*errp = errno;
436		return (NULL);
437	}
438
439	fp = ctf_fdopen(fd, errp);
440	(void) close(fd);
441	return (fp);
442}
443
444/*
445 * Write the uncompressed CTF data stream to the specified file descriptor.
446 * This is useful for saving the results of dynamic CTF containers.
447 */
448int
449ctf_write(ctf_file_t *fp, int fd)
450{
451	const uchar_t *buf = fp->ctf_base;
452	ssize_t resid = fp->ctf_size;
453	ssize_t len;
454
455	while (resid != 0) {
456		if ((len = write(fd, buf, resid)) <= 0)
457			return (ctf_set_errno(fp, errno));
458		resid -= len;
459		buf += len;
460	}
461
462	return (0);
463}
464
465/*
466 * Set the CTF library client version to the specified version.  If version is
467 * zero, we just return the default library version number.
468 */
469int
470ctf_version(int version)
471{
472	if (version < 0) {
473		errno = EINVAL;
474		return (-1);
475	}
476
477	if (version > 0) {
478		if (version > CTF_VERSION) {
479			errno = ENOTSUP;
480			return (-1);
481		}
482		ctf_dprintf("ctf_version: client using version %d\n", version);
483		_libctf_version = version;
484	}
485
486	return (_libctf_version);
487}
488