xref: /netbsd/lib/librumpuser/rumpuser_dl.c (revision 6550d01e)
1 /*      $NetBSD: rumpuser_dl.c,v 1.5 2010/12/30 15:47:30 pooka Exp $	*/
2 
3 /*
4  * Copyright (c) 2009 Antti Kantee.  All Rights Reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
16  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18  * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 /*
29  * Load all module link sets and feed symbol table to the kernel.
30  * Called during rump bootstrap.
31  */
32 
33 #include <sys/cdefs.h>
34 __RCSID("$NetBSD: rumpuser_dl.c,v 1.5 2010/12/30 15:47:30 pooka Exp $");
35 
36 #include <sys/types.h>
37 #include <sys/time.h>
38 
39 #include <assert.h>
40 #include <dlfcn.h>
41 #include <elf.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <link.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <unistd.h>
49 
50 #include <rump/rumpuser.h>
51 
52 #if defined(__ELF__) && (defined(__NetBSD__) || defined(__FreeBSD__)	\
53     || (defined(__sun__) && defined(__svr4__)))
54 static size_t symtabsize = 0, strtabsize = 0;
55 static size_t symtaboff = 0, strtaboff = 0;
56 static uint8_t *symtab = NULL;
57 static char *strtab = NULL;
58 static unsigned char eident;
59 
60 static void *
61 reservespace(void *store, size_t *storesize,
62 	size_t storeoff, size_t required)
63 {
64 	size_t chunk, newsize;
65 
66 	assert(storeoff <= *storesize);
67 	chunk = *storesize - storeoff;
68 
69 	if (chunk >= required)
70 		return store;
71 
72 	newsize = *storesize + ((size_t)required - chunk);
73 	store = realloc(store, newsize);
74 	if (store == NULL) {
75 		return NULL;
76 	}
77 	*((uint8_t *)store + storeoff) = '\0';
78 	*storesize = newsize;
79 
80 	return store;
81 }
82 
83 /*
84  * Macros to make handling elf32/64 in the code a little saner.
85  */
86 
87 #define DYNn_GETMEMBER(base, n, thevar, result)				\
88 do {									\
89 	if (eident == ELFCLASS32) {					\
90 		Elf32_Dyn *dyn = base;					\
91 		/*LINTED*/						\
92 		result = dyn[n].thevar;					\
93 	} else {							\
94 		Elf64_Dyn *dyn = base;					\
95 		/*LINTED*/						\
96 		result = dyn[n].thevar;					\
97 	}								\
98 } while (/*CONSTCOND*/0)
99 
100 #define SYMn_GETMEMBER(base, n, thevar, result)				\
101 do {									\
102 	if (eident == ELFCLASS32) {					\
103 		const Elf32_Sym *sym = base;				\
104 		/*LINTED*/						\
105 		result = sym[n].thevar;					\
106 	} else {							\
107 		const Elf64_Sym *sym = base;				\
108 		/*LINTED*/						\
109 		result = sym[n].thevar;					\
110 	}								\
111 } while (/*CONSTCOND*/0)
112 
113 #define SYMn_SETMEMBER(base, n, thevar, value)				\
114 do {									\
115 	if (eident == ELFCLASS32) {					\
116 		Elf32_Sym *sym = base;					\
117 		/*LINTED*/						\
118 		sym[n].thevar = value;					\
119 	} else {							\
120 		Elf64_Sym *sym = base;					\
121 		/*LINTED*/						\
122 		sym[n].thevar = value;					\
123 	}								\
124 } while (/*CONSTCOND*/0)
125 
126 #define GETVECWORDn(base, n, result)					\
127 do {									\
128 	if (eident == ELFCLASS32) {					\
129 		Elf32_Word *vec = base;					\
130 		result = vec[n];					\
131 	} else {							\
132 		Elf64_Word *vec = base;					\
133 		result = vec[n];					\
134 	}								\
135 } while (/*CONSTCOND*/0)
136 
137 #define SYM_GETSIZE() ((eident==ELFCLASS32)?sizeof(Elf32_Sym):sizeof(Elf64_Sym))
138 
139 static int
140 getsymbols(struct link_map *map)
141 {
142 	char *str_base;
143 	void *syms_base = NULL; /* XXXgcc */
144 	size_t curstrsize;
145 	void *ed_base;
146 	uint64_t ed_tag;
147 	size_t cursymcount;
148 	unsigned i;
149 
150 	if (map->l_addr) {
151 		if (memcmp(map->l_addr, ELFMAG, SELFMAG) != 0)
152 			return ENOEXEC;
153 		eident = *(unsigned char *)(map->l_addr + EI_CLASS);
154 		if (eident != ELFCLASS32 && eident != ELFCLASS64)
155 			return ENOEXEC;
156 	}
157 
158 	/*
159 	 * ok, we probably have only the main object.  instead of going
160 	 * to disk and reading the ehdr, just try to guess the size.
161 	 */
162 	if (eident == 0) {
163 		if (/*CONSTCOND*/sizeof(void *) == 4)
164 			eident = ELFCLASS32;
165 		else
166 			eident = ELFCLASS64;
167 	}
168 
169 	/*
170 	 * Find symtab and strtab and their sizes.
171 	 */
172 	str_base = NULL;
173 	curstrsize = 0;
174 	cursymcount = 0;
175 	ed_base = map->l_ld;
176 	DYNn_GETMEMBER(ed_base, 0, d_tag, ed_tag);
177 	for (i = 0; ed_tag != DT_NULL;) {
178 		uintptr_t edptr;
179 		size_t edval;
180 		void *hashtab;
181 
182 		switch (ed_tag) {
183 		case DT_SYMTAB:
184 			DYNn_GETMEMBER(ed_base, i, d_un.d_ptr, edptr);
185 			syms_base = map->l_addr + edptr;
186 			break;
187 		case DT_STRTAB:
188 			DYNn_GETMEMBER(ed_base, i, d_un.d_ptr, edptr);
189 			str_base = map->l_addr + edptr;
190 			break;
191 		case DT_STRSZ:
192 			DYNn_GETMEMBER(ed_base, i, d_un.d_val, edval);
193 			curstrsize = edval;
194 			break;
195 		case DT_HASH:
196 			DYNn_GETMEMBER(ed_base, i, d_un.d_ptr, edptr);
197 			hashtab = map->l_addr + edptr;
198 			GETVECWORDn(hashtab, 1, cursymcount);
199 			break;
200 		case DT_SYMENT:
201 			DYNn_GETMEMBER(ed_base, i, d_un.d_val, edval);
202 			assert(edval == SYM_GETSIZE());
203 			break;
204 		default:
205 			break;
206 		}
207 		i++;
208 		DYNn_GETMEMBER(ed_base, i, d_tag, ed_tag);
209 	}
210 
211 	if (str_base == NULL || syms_base == NULL ||
212 	    curstrsize == 0 || cursymcount == 0) {
213 		fprintf(stderr, "could not find strtab, symtab or their sizes "
214 		    "in %s\n", map->l_name);
215 		return ENOEXEC;
216 	}
217 
218 	/*
219 	 * Make sure we have enough space for the contents of the symbol
220 	 * and string tables we are currently processing.  The total used
221 	 * space will be smaller due to undefined symbols we are not
222 	 * interested in.
223 	 */
224 	symtab = reservespace(symtab, &symtabsize,
225 	    symtaboff, cursymcount * SYM_GETSIZE());
226 	strtab = reservespace(strtab, &strtabsize, strtaboff, curstrsize);
227 	if (symtab == NULL || strtab == NULL) {
228 		fprintf(stderr, "failed to reserve memory");
229 		return ENOMEM;
230 	}
231 
232 	/* iterate over all symbols in current symtab */
233 	for (i = 0; i < cursymcount; i++) {
234 		const char *cursymname;
235 		int shndx, name;
236 		uintptr_t value;
237 		void *csym;
238 
239 		SYMn_GETMEMBER(syms_base, i, st_shndx, shndx);
240 		SYMn_GETMEMBER(syms_base, i, st_value, value);
241 		if (shndx == SHN_UNDEF || value == 0)
242 			continue;
243 
244 		/* get symbol name */
245 		SYMn_GETMEMBER(syms_base, i, st_name, name);
246 		cursymname = name + str_base;
247 
248 		/*
249 		 * Only accept symbols which are decidedly in
250 		 * the rump kernel namespace.
251 		 * XXX: quirks, but they wouldn't matter here
252 		 */
253 		if (strncmp(cursymname, "rump", 4) != 0 &&
254 		    strncmp(cursymname, "RUMP", 4) != 0 &&
255 		    strncmp(cursymname, "__", 2) != 0) {
256 			continue;
257 		}
258 
259 		memcpy(symtab + symtaboff,
260 		    (const uint8_t *)syms_base + i*SYM_GETSIZE(),SYM_GETSIZE());
261 
262 		/*
263 		 * set name to point at new strtab, offset symbol value
264 		 * with lib base address.
265 		 */
266 		csym = symtab + symtaboff;
267 		SYMn_SETMEMBER(csym, 0, st_name, strtaboff);
268 		SYMn_GETMEMBER(csym, 0, st_value, value);
269 		SYMn_SETMEMBER(csym, 0, st_value,(intptr_t)(value+map->l_addr));
270 		symtaboff += SYM_GETSIZE();
271 
272 		strcpy(strtab + strtaboff, cursymname);
273 		strtaboff += strlen(cursymname)+1;
274 	}
275 
276 	return 0;
277 }
278 
279 static void
280 process(const char *soname, rump_modinit_fn domodinit)
281 {
282 	void *handle;
283 	const struct modinfo *const *mi_start, *const *mi_end;
284 
285 	if (strstr(soname, "librump") == NULL)
286 		return;
287 
288 	handle = dlopen(soname, RTLD_LAZY);
289 	if (handle == NULL)
290 		return;
291 
292 	mi_start = dlsym(handle, "__start_link_set_modules");
293 	if (!mi_start)
294 		goto out;
295 	mi_end = dlsym(handle, "__stop_link_set_modules");
296 	if (!mi_end)
297 		goto out;
298 
299 	domodinit(mi_start, (size_t)(mi_end-mi_start));
300 
301  out:
302 	dlclose(handle);
303 }
304 
305 /*
306  * Get the linkmap from the dynlinker.  Try to load kernel modules
307  * from all objects in the linkmap.
308  */
309 void
310 rumpuser_dl_bootstrap(rump_modinit_fn domodinit,
311 	rump_symload_fn symload)
312 {
313 	struct link_map *map, *origmap;
314 	int error;
315 
316 	if (dlinfo(RTLD_SELF, RTLD_DI_LINKMAP, &origmap) == -1) {
317 		fprintf(stderr, "warning: rumpuser module bootstrap "
318 		    "failed: %s\n", dlerror());
319 		return;
320 	}
321 	/*
322 	 * Process last->first because that's the most probable
323 	 * order for dependencies
324 	 */
325 	for (; origmap->l_next; origmap = origmap->l_next)
326 		continue;
327 
328 	/*
329 	 * Build symbol table to hand to the rump kernel.  Do this by
330 	 * iterating over all rump libraries and collecting symbol
331 	 * addresses and relocation info.
332 	 */
333 	error = 0;
334 	for (map = origmap; map && !error; map = map->l_prev) {
335 		if (strstr(map->l_name, "librump") != NULL)
336 			error = getsymbols(map);
337 		/* this should be the main object */
338 		else if (map->l_addr == NULL && map->l_prev == NULL)
339 			error = getsymbols(map);
340 	}
341 
342 	if (error == 0) {
343 		void *trimmedsym, *trimmedstr;
344 
345 		/*
346 		 * Allocate optimum-sized memory for storing tables
347 		 * and feed to kernel.  If memory allocation fails,
348 		 * just give the ones with extra context (although
349 		 * I'm pretty sure we'll die moments later due to
350 		 * memory running out).
351 		 */
352 		if ((trimmedsym = malloc(symtaboff)) != NULL) {
353 			memcpy(trimmedsym, symtab, symtaboff);
354 		} else {
355 			trimmedsym = symtab;
356 			symtab = NULL;
357 		}
358 		if ((trimmedstr = malloc(strtaboff)) != NULL) {
359 			memcpy(trimmedstr, strtab, strtaboff);
360 		} else {
361 			trimmedstr = strtab;
362 			strtab = NULL;
363 		}
364 		symload(trimmedsym, symtaboff, trimmedstr, strtaboff);
365 	}
366 	free(symtab);
367 	free(strtab);
368 
369 	/*
370 	 * Next, load modules from dynlibs.
371 	 */
372 	for (map = origmap; map; map = map->l_prev)
373 		process(map->l_name, domodinit);
374 }
375 
376 void
377 rumpuser_dl_component_init(int type, rump_component_init_fn compinit)
378 {
379 	struct link_map *map;
380 
381 	if (dlinfo(RTLD_SELF, RTLD_DI_LINKMAP, &map) == -1) {
382 		fprintf(stderr, "warning: rumpuser module bootstrap "
383 		    "failed: %s\n", dlerror());
384 		return;
385 	}
386 
387 	for (; map->l_next; map = map->l_next)
388 		continue;
389 	for (; map; map = map->l_prev) {
390 		if (strstr(map->l_name, "librump") != NULL) {
391 			void *handle;
392 			struct rump_component **rc, **rc_end;
393 
394 			handle = dlopen(map->l_name, RTLD_LAZY);
395 			if (handle == NULL)
396 				continue;
397 
398 			rc = dlsym(handle,
399 			    "__start_link_set_rump_components");
400 			if (!rc)
401 				goto loop;
402 			rc_end = dlsym(handle,
403 			    "__stop_link_set_rump_components");
404 			if (!rc_end)
405 				goto loop;
406 
407 			for (; rc < rc_end; rc++)
408 				compinit(*rc, type);
409 			assert(rc == rc_end);
410  loop:
411 			dlclose(handle);
412 		}
413 	}
414 }
415 #else
416 void
417 rumpuser_dl_bootstrap(rump_modinit_fn domodinit,
418 	rump_symload_fn symload)
419 {
420 
421 	fprintf(stderr, "Warning, dlinfo() unsupported on host?\n");
422 }
423 
424 void
425 rumpuser_dl_component_init(int type, rump_component_init_fn compinit)
426 {
427 
428 	fprintf(stderr, "Warning, dlinfo() unsupported on host?\n");
429 }
430 #endif
431 
432 void *
433 rumpuser_dl_globalsym(const char *symname)
434 {
435 
436 	return dlsym(RTLD_DEFAULT, symname);
437 }
438