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