1 /*-
2  * Copyright (c) 2006,2008,2010 Joseph Koshy
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS `AS IS' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 
29 #include <assert.h>
30 #include <ctype.h>
31 #include <libelf.h>
32 #include <stdlib.h>
33 #include <string.h>
34 
35 #include "_libelf.h"
36 #include "_libelf_ar.h"
37 
38 ELFTC_VCSID("$Id$");
39 
40 #define	LIBELF_NALLOC_SIZE	16
41 
42 /*
43  * `ar' archive handling.
44  *
45  * `ar' archives start with signature `ARMAG'.  Each archive member is
46  * preceded by a header containing meta-data for the member.  This
47  * header is described in <ar.h> (struct ar_hdr).  The header always
48  * starts on an even address.  File data is padded with "\n"
49  * characters to keep this invariant.
50  *
51  * Special considerations for `ar' archives:
52  *
53  * There are two variants of the `ar' archive format: traditional BSD
54  * and SVR4.  These differ in the way long file names are treated, and
55  * in the layout of the archive symbol table.
56  *
57  * The `ar' header only has space for a 16 character file name.
58  *
59  * In the SVR4 format, file names are terminated with a '/', so this
60  * effectively leaves 15 characters for the actual file name.  Longer
61  * file names stored in a separate 'string table' and referenced
62  * indirectly from the name field.  The string table itself appears as
63  * an archive member with name "// ".  An `indirect' file name in an
64  * `ar' header matches the pattern "/[0-9]*". The digits form a
65  * decimal number that corresponds to a byte offset into the string
66  * table where the actual file name of the object starts.  Strings in
67  * the string table are padded to start on even addresses.
68  *
69  * In the BSD format, file names can be upto 16 characters.  File
70  * names shorter than 16 characters are padded to 16 characters using
71  * (ASCII) space characters.  File names with embedded spaces and file
72  * names longer than 16 characters are stored immediately after the
73  * archive header and the name field set to a special indirect name
74  * matching the pattern "#1/[0-9]+".  The digits form a decimal number
75  * that corresponds to the actual length of the file name following
76  * the archive header.  The content of the archive member immediately
77  * follows the file name, and the size field of the archive member
78  * holds the sum of the sizes of the member and of the appended file
79  * name.
80  *
81  * Archives may also have a symbol table (see ranlib(1)), mapping
82  * program symbols to object files inside the archive.
83  *
84  * In the SVR4 format, a symbol table uses a file name of "/ " in its
85  * archive header.  The symbol table is structured as:
86  *  - a 4-byte count of entries stored as a binary value, MSB first
87  *  - 'n' 4-byte offsets, stored as binary values, MSB first
88  *  - 'n' NUL-terminated strings, for ELF symbol names, stored unpadded.
89  *
90  * In the BSD format, the symbol table uses a file name of "__.SYMDEF".
91  * It is structured as two parts:
92  *  - The first part is an array of "ranlib" structures preceded by
93  *    the size of the array in bytes.  Each "ranlib" structure
94  *    describes one symbol.  Each structure contains an offset into
95  *    the string table for the symbol name, and a file offset into the
96  *    archive for the member defining the symbol.
97  *  - The second part is a string table containing NUL-terminated
98  *    strings, preceded by the size of the string table in bytes.
99  *
100  * If the symbol table and string table are is present in an archive
101  * they must be the very first objects and in that order.
102  */
103 
104 
105 /*
106  * Retrieve an archive header descriptor.
107  */
108 
109 Elf_Arhdr *
_libelf_ar_gethdr(Elf * e)110 _libelf_ar_gethdr(Elf *e)
111 {
112 	Elf *parent;
113 	Elf_Arhdr *eh;
114 	char *namelen;
115 	size_t n, nlen;
116 	struct ar_hdr *arh;
117 
118 	if ((parent = e->e_parent) == NULL) {
119 		LIBELF_SET_ERROR(ARGUMENT, 0);
120 		return (NULL);
121 	}
122 
123 	assert((e->e_flags & LIBELF_F_AR_HEADER) == 0);
124 
125 	arh = (struct ar_hdr *) (uintptr_t) e->e_hdr.e_rawhdr;
126 
127 	assert((uintptr_t) arh >= (uintptr_t) parent->e_rawfile + SARMAG);
128 	assert((uintptr_t) arh <= (uintptr_t) parent->e_rawfile +
129 	    parent->e_rawsize - sizeof(struct ar_hdr));
130 
131 	if ((eh = malloc(sizeof(Elf_Arhdr))) == NULL) {
132 		LIBELF_SET_ERROR(RESOURCE, 0);
133 		return (NULL);
134 	}
135 
136 	e->e_hdr.e_arhdr = eh;
137 	e->e_flags |= LIBELF_F_AR_HEADER;
138 
139 	eh->ar_name = eh->ar_rawname = NULL;
140 
141 	if ((eh->ar_name = _libelf_ar_get_translated_name(arh, parent)) ==
142 	    NULL)
143 		goto error;
144 
145 	if (_libelf_ar_get_number(arh->ar_uid, sizeof(arh->ar_uid), 10,
146 	    &n) == 0)
147 		goto error;
148 	eh->ar_uid = (uid_t) n;
149 
150 	if (_libelf_ar_get_number(arh->ar_gid, sizeof(arh->ar_gid), 10,
151 	    &n) == 0)
152 		goto error;
153 	eh->ar_gid = (gid_t) n;
154 
155 	if (_libelf_ar_get_number(arh->ar_mode, sizeof(arh->ar_mode), 8,
156 	    &n) == 0)
157 		goto error;
158 	eh->ar_mode = (mode_t) n;
159 
160 	if (_libelf_ar_get_number(arh->ar_size, sizeof(arh->ar_size), 10,
161 	    &n) == 0)
162 		goto error;
163 
164 	/*
165 	 * Get the true size of the member if extended naming is being used.
166 	 */
167 	if (IS_EXTENDED_BSD_NAME(arh->ar_name)) {
168 		namelen = arh->ar_name +
169 		    LIBELF_AR_BSD_EXTENDED_NAME_PREFIX_SIZE;
170 		if (_libelf_ar_get_number(namelen, sizeof(arh->ar_name) -
171 		    LIBELF_AR_BSD_EXTENDED_NAME_PREFIX_SIZE, 10, &nlen) == 0)
172 			goto error;
173 		n -= nlen;
174 	}
175 
176 	eh->ar_size = n;
177 
178 	if ((eh->ar_rawname = _libelf_ar_get_raw_name(arh)) == NULL)
179 		goto error;
180 
181 	eh->ar_flags = 0;
182 
183 	return (eh);
184 
185  error:
186 	if (eh) {
187 		if (eh->ar_name)
188 			free(eh->ar_name);
189 		if (eh->ar_rawname)
190 			free(eh->ar_rawname);
191 		free(eh);
192 	}
193 
194 	e->e_flags &= ~LIBELF_F_AR_HEADER;
195 	e->e_hdr.e_rawhdr = (unsigned char *) arh;
196 
197 	return (NULL);
198 }
199 
200 Elf *
_libelf_ar_open_member(int fd,Elf_Cmd c,Elf * elf)201 _libelf_ar_open_member(int fd, Elf_Cmd c, Elf *elf)
202 {
203 	Elf *e;
204 	off_t next;
205 	size_t nsz, sz;
206 	struct ar_hdr *arh;
207 	char *member, *namelen;
208 
209 	assert(elf->e_kind == ELF_K_AR);
210 
211 	next = elf->e_u.e_ar.e_next;
212 
213 	/*
214 	 * `next' is only set to zero by elf_next() when the last
215 	 * member of an archive is processed.
216 	 */
217 	if (next == (off_t) 0)
218 		return (NULL);
219 
220 	assert((next & 1) == 0);
221 
222 	arh = (struct ar_hdr *) (elf->e_rawfile + next);
223 
224 	/*
225 	 * Retrieve the size of the member.
226 	 */
227 	if (_libelf_ar_get_number(arh->ar_size, sizeof(arh->ar_size), 10,
228 	    &sz) == 0) {
229 		LIBELF_SET_ERROR(ARCHIVE, 0);
230 		return (NULL);
231 	}
232 
233 	/*
234 	 * Adjust the size field for members in BSD archives using
235 	 * extended naming.
236 	 */
237 	if (IS_EXTENDED_BSD_NAME(arh->ar_name)) {
238 		namelen = arh->ar_name +
239 		    LIBELF_AR_BSD_EXTENDED_NAME_PREFIX_SIZE;
240 		if (_libelf_ar_get_number(namelen, sizeof(arh->ar_name) -
241 		    LIBELF_AR_BSD_EXTENDED_NAME_PREFIX_SIZE, 10, &nsz) == 0) {
242 			LIBELF_SET_ERROR(ARCHIVE, 0);
243 			return (NULL);
244 		}
245 
246 		member = (char *) (arh + 1) + nsz;
247 		sz -= nsz;
248 	} else
249 		member = (char *) (arh + 1);
250 
251 
252 	if ((e = elf_memory(member, sz)) == NULL)
253 		return (NULL);
254 
255 	e->e_fd = fd;
256 	e->e_cmd = c;
257 	e->e_hdr.e_rawhdr = (unsigned char *) arh;
258 
259 	elf->e_u.e_ar.e_nchildren++;
260 	e->e_parent = elf;
261 
262 	return (e);
263 }
264 
265 /*
266  * A BSD-style ar(1) symbol table has the following layout:
267  *
268  * - A count of bytes used by the following array of 'ranlib'
269  *   structures, stored as a 'long'.
270  * - An array of 'ranlib' structures.  Each array element is
271  *   two 'long's in size.
272  * - A count of bytes used for the following symbol table.
273  * - The symbol table itself.
274  */
275 
276 /*
277  * A helper macro to read in a 'long' value from the archive.
278  *
279  * We use memcpy() since the source pointer may be misaligned with
280  * respect to the natural alignment for a C 'long'.
281  */
282 #define	GET_LONG(P, V)do {				\
283 		memcpy(&(V), (P), sizeof(long));	\
284 		(P) += sizeof(long);			\
285 	} while (0)
286 
287 Elf_Arsym *
_libelf_ar_process_bsd_symtab(Elf * e,size_t * count)288 _libelf_ar_process_bsd_symtab(Elf *e, size_t *count)
289 {
290 	Elf_Arsym *symtab, *sym;
291 	unsigned int n, nentries;
292 	unsigned char *end, *p, *p0, *s, *s0;
293 	const size_t entrysize = 2 * sizeof(long);
294 	long arraysize, fileoffset, stroffset, strtabsize;
295 
296 	assert(e != NULL);
297 	assert(count != NULL);
298 	assert(e->e_u.e_ar.e_symtab == NULL);
299 
300 	symtab = NULL;
301 
302 	/*
303 	 * The BSD symbol table always contains the count fields even
304 	 * if there are no entries in it.
305 	 */
306 	if (e->e_u.e_ar.e_rawsymtabsz < 2 * sizeof(long))
307 		goto symtaberror;
308 
309 	p = p0 = (unsigned char *) e->e_u.e_ar.e_rawsymtab;
310 	end = p0 + e->e_u.e_ar.e_rawsymtabsz;
311 
312 	/*
313 	 * Retrieve the size of the array of ranlib descriptors and
314 	 * check it for validity.
315 	 */
316 	GET_LONG(p, arraysize);
317 
318 	if (arraysize < 0 || p0 + arraysize >= end ||
319 	    ((size_t) arraysize % entrysize != 0))
320 		goto symtaberror;
321 
322 	/*
323 	 * Check the value of the string table size.
324 	 */
325 	s = p + arraysize;
326 	GET_LONG(s, strtabsize);
327 
328 	s0 = s;			/* Start of string table. */
329 	if (strtabsize < 0 || s0 + strtabsize > end)
330 		goto symtaberror;
331 
332 	nentries = (size_t) arraysize / entrysize;
333 
334 	/*
335 	 * Allocate space for the returned Elf_Arsym array.
336 	 */
337 	if ((symtab = malloc(sizeof(Elf_Arsym) * (nentries + 1))) == NULL) {
338 		LIBELF_SET_ERROR(RESOURCE, 0);
339 		return (NULL);
340 	}
341 
342 	/* Read in symbol table entries. */
343 	for (n = 0, sym = symtab; n < nentries; n++, sym++) {
344 		GET_LONG(p, stroffset);
345 		GET_LONG(p, fileoffset);
346 
347 		if (stroffset < 0 || fileoffset <  0 ||
348 		    (size_t) fileoffset >= e->e_rawsize)
349 			goto symtaberror;
350 
351 		s = s0 + stroffset;
352 
353 		if (s >= end)
354 			goto symtaberror;
355 
356 		sym->as_off = (off_t) fileoffset;
357 		sym->as_hash = elf_hash((char *) s);
358 		sym->as_name = (char *) s;
359 	}
360 
361 	/* Fill up the sentinel entry. */
362 	sym->as_name = NULL;
363 	sym->as_hash = ~0UL;
364 	sym->as_off = (off_t) 0;
365 
366 	/* Remember the processed symbol table. */
367 	e->e_u.e_ar.e_symtab = symtab;
368 
369 	*count = e->e_u.e_ar.e_symtabsz = nentries + 1;
370 
371 	return (symtab);
372 
373 symtaberror:
374 	if (symtab)
375 		free(symtab);
376 	LIBELF_SET_ERROR(ARCHIVE, 0);
377 	return (NULL);
378 }
379 
380 /*
381  * An SVR4-style ar(1) symbol table has the following layout:
382  *
383  * - The first 4 bytes are a binary count of the number of entries in the
384  *   symbol table, stored MSB-first.
385  * - Then there are 'n' 4-byte binary offsets, also stored MSB first.
386  * - Following this, there are 'n' null-terminated strings.
387  */
388 
389 #define	GET_WORD(P, V) do {			\
390 		(V) = 0;			\
391 		(V) = (P)[0]; (V) <<= 8;	\
392 		(V) += (P)[1]; (V) <<= 8;	\
393 		(V) += (P)[2]; (V) <<= 8;	\
394 		(V) += (P)[3];			\
395 	} while (0)
396 
397 #define	INTSZ	4
398 
399 
400 Elf_Arsym *
_libelf_ar_process_svr4_symtab(Elf * e,size_t * count)401 _libelf_ar_process_svr4_symtab(Elf *e, size_t *count)
402 {
403 	uint32_t off;
404 	size_t n, nentries;
405 	Elf_Arsym *symtab, *sym;
406 	unsigned char *p, *s, *end;
407 
408 	assert(e != NULL);
409 	assert(count != NULL);
410 	assert(e->e_u.e_ar.e_symtab == NULL);
411 
412 	symtab = NULL;
413 
414 	if (e->e_u.e_ar.e_rawsymtabsz < INTSZ)
415 		goto symtaberror;
416 
417 	p = (unsigned char *) e->e_u.e_ar.e_rawsymtab;
418 	end = p + e->e_u.e_ar.e_rawsymtabsz;
419 
420 	GET_WORD(p, nentries);
421 	p += INTSZ;
422 
423 	if (nentries == 0 || p + nentries * INTSZ >= end)
424 		goto symtaberror;
425 
426 	/* Allocate space for a nentries + a sentinel. */
427 	if ((symtab = malloc(sizeof(Elf_Arsym) * (nentries+1))) == NULL) {
428 		LIBELF_SET_ERROR(RESOURCE, 0);
429 		return (NULL);
430 	}
431 
432 	s = p + (nentries * INTSZ); /* start of the string table. */
433 
434 	for (n = nentries, sym = symtab; n > 0; n--) {
435 		if (s >= end)
436 			goto symtaberror;
437 
438 		GET_WORD(p, off);
439 		if (off >= e->e_rawsize)
440 			goto symtaberror;
441 
442 		sym->as_off = (off_t) off;
443 		sym->as_hash = elf_hash((char *) s);
444 		sym->as_name = (char *) s;
445 
446 		p += INTSZ;
447 		sym++;
448 
449 		for (; s < end && *s++ != '\0';) /* skip to next string */
450 			;
451 	}
452 
453 	/* Fill up the sentinel entry. */
454 	sym->as_name = NULL;
455 	sym->as_hash = ~0UL;
456 	sym->as_off = (off_t) 0;
457 
458 	*count = e->e_u.e_ar.e_symtabsz = nentries + 1;
459 	e->e_u.e_ar.e_symtab = symtab;
460 
461 	return (symtab);
462 
463 symtaberror:
464 	if (symtab)
465 		free(symtab);
466 	LIBELF_SET_ERROR(ARCHIVE, 0);
467 	return (NULL);
468 }
469