xref: /haiku/src/system/runtime_loader/elf.cpp (revision adcf5b05a8ca9e17407aa4640675c3873c9f0a6c)
1 /*
2  * Copyright 2008-2010, Ingo Weinhold, ingo_weinhold@gmx.de.
3  * Copyright 2003-2011, Axel Dörfler, axeld@pinc-software.de.
4  * Distributed under the terms of the MIT License.
5  *
6  * Copyright 2002, Manuel J. Petit. All rights reserved.
7  * Copyright 2001, Travis Geiselbrecht. All rights reserved.
8  * Distributed under the terms of the NewOS License.
9  */
10 
11 #include "runtime_loader_private.h"
12 
13 #include <ctype.h>
14 #include <dlfcn.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 
19 #include <OS.h>
20 
21 #include <syscalls.h>
22 #include <util/kernel_cpp.h>
23 
24 #include <locks.h>
25 
26 #include "add_ons.h"
27 #include "elf_load_image.h"
28 #include "elf_symbol_lookup.h"
29 #include "elf_tls.h"
30 #include "elf_versioning.h"
31 #include "errors.h"
32 #include "images.h"
33 
34 
35 // TODO: implement better locking strategy
36 // TODO: implement lazy binding
37 
38 // a handle returned by load_library() (dlopen())
39 #define RLD_GLOBAL_SCOPE	((void*)-2l)
40 
41 static const char* const kLockName = "runtime loader";
42 
43 
44 typedef void (*init_term_function)(image_id);
45 typedef void (*initfini_array_function)();
46 
47 bool gProgramLoaded = false;
48 image_t* gProgramImage;
49 
50 static image_t** sPreloadedAddons = NULL;
51 static uint32 sPreloadedAddonCount = 0;
52 
53 static recursive_lock sLock = RECURSIVE_LOCK_INITIALIZER(kLockName);
54 
55 
56 static const char *
57 find_dt_rpath(image_t *image)
58 {
59 	int i;
60 	elf_dyn *d = (elf_dyn *)image->dynamic_ptr;
61 
62 	for (i = 0; d[i].d_tag != DT_NULL; i++) {
63 		if (d[i].d_tag == DT_RPATH)
64 			return STRING(image, d[i].d_un.d_val);
65 	}
66 
67 	return NULL;
68 }
69 
70 
71 image_id
72 preload_image(char const* path, image_t **image)
73 {
74 	if (path == NULL)
75 		return B_BAD_VALUE;
76 
77 	KTRACE("rld: preload_image(\"%s\")", path);
78 
79 	status_t status = load_image(path, B_LIBRARY_IMAGE, NULL, NULL, image);
80 	if (status < B_OK) {
81 		KTRACE("rld: preload_image(\"%s\") failed to load container: %s", path,
82 			strerror(status));
83 		return status;
84 	}
85 
86 	if ((*image)->find_undefined_symbol == NULL)
87 		(*image)->find_undefined_symbol = find_undefined_symbol_global;
88 
89 	KTRACE("rld: preload_image(\"%s\") done: id: %" B_PRId32, path, (*image)->id);
90 
91 	return (*image)->id;
92 }
93 
94 
95 static void
96 preload_images(image_t **image, int32 *_count = NULL)
97 {
98 	const char* imagePaths = getenv("LD_PRELOAD");
99 	if (imagePaths == NULL) {
100 		if (_count != NULL)
101 			*_count = 0;
102 		return;
103 	}
104 
105 	int32 count = 0;
106 
107 	while (*imagePaths != '\0') {
108 		// find begin of image path
109 		while (*imagePaths != '\0' && isspace(*imagePaths))
110 			imagePaths++;
111 
112 		if (*imagePaths == '\0')
113 			break;
114 
115 		// find end of image path
116 		const char* imagePath = imagePaths;
117 		while (*imagePaths != '\0' && !isspace(*imagePaths))
118 			imagePaths++;
119 
120 		// extract the path
121 		char path[B_PATH_NAME_LENGTH];
122 		size_t pathLen = imagePaths - imagePath;
123 		if (pathLen > sizeof(path) - 1)
124 			continue;
125 
126 		if (image == NULL) {
127 			count++;
128 			continue;
129 		}
130 		memcpy(path, imagePath, pathLen);
131 		path[pathLen] = '\0';
132 
133 		// load the image
134 		preload_image(path, &image[count++]);
135 	}
136 
137 	KTRACE("rld: preload_images count: %d", count);
138 
139 	if (_count != NULL)
140 		*_count = count;
141 }
142 
143 
144 static status_t
145 load_immediate_dependencies(image_t *image, bool preload)
146 {
147 	elf_dyn *d = (elf_dyn *)image->dynamic_ptr;
148 	bool reportErrors = report_errors();
149 	status_t status = B_OK;
150 	uint32 i, j;
151 	const char *rpath;
152 
153 	if (!d || (image->flags & RFLAG_DEPENDENCIES_LOADED))
154 		return B_OK;
155 
156 	image->flags |= RFLAG_DEPENDENCIES_LOADED;
157 
158 	int32 preloadedCount = 0;
159 	if (preload) {
160 		preload_images(NULL, &preloadedCount);
161 		image->num_needed += preloadedCount;
162 	}
163 	if (image->num_needed == 0)
164 		return B_OK;
165 
166 	KTRACE("rld: load_dependencies(\"%s\", id: %" B_PRId32 ")", image->name,
167 		image->id);
168 
169 	image->needed = (image_t**)malloc(image->num_needed * sizeof(image_t *));
170 	if (image->needed == NULL) {
171 		FATAL("%s: Failed to allocate needed struct\n", image->path);
172 		KTRACE("rld: load_dependencies(\"%s\", id: %" B_PRId32
173 			") failed: no memory", image->name, image->id);
174 		return B_NO_MEMORY;
175 	}
176 
177 	memset(image->needed, 0, image->num_needed * sizeof(image_t *));
178 	if (preload)
179 		preload_images(image->needed);
180 	rpath = find_dt_rpath(image);
181 
182 	for (i = 0, j = preloadedCount; d[i].d_tag != DT_NULL; i++) {
183 		switch (d[i].d_tag) {
184 			case DT_NEEDED:
185 			{
186 				int32 neededOffset = d[i].d_un.d_val;
187 				const char *name = STRING(image, neededOffset);
188 
189 				status_t loadStatus = load_image(name, B_LIBRARY_IMAGE,
190 					rpath, image->path, &image->needed[j]);
191 				if (loadStatus < B_OK) {
192 					status = loadStatus;
193 					// correct error code in case the file could not been found
194 					if (status == B_ENTRY_NOT_FOUND) {
195 						status = B_MISSING_LIBRARY;
196 
197 						if (reportErrors)
198 							gErrorMessage.AddString("missing library", name);
199 					}
200 
201 					// Collect all missing libraries in case we report back
202 					if (!reportErrors) {
203 						KTRACE("rld: load_dependencies(\"%s\", id: %" B_PRId32
204 							") failed: %s", image->name, image->id,
205 							strerror(status));
206 						return status;
207 					}
208 				}
209 
210 				j += 1;
211 				break;
212 			}
213 
214 			default:
215 				// ignore any other tag
216 				continue;
217 		}
218 	}
219 
220 	if (status < B_OK) {
221 		KTRACE("rld: load_dependencies(\"%s\", id: %" B_PRId32 ") "
222 			"failed: %s", image->name, image->id,
223 			strerror(status));
224 		return status;
225 	}
226 
227 	if (j != image->num_needed) {
228 		FATAL("Internal error at load_dependencies()");
229 		KTRACE("rld: load_dependencies(\"%s\", id: %" B_PRId32 ") "
230 			"failed: internal error", image->name, image->id);
231 		return B_ERROR;
232 	}
233 
234 	KTRACE("rld: load_dependencies(\"%s\", id: %" B_PRId32 ") done",
235 		image->name, image->id);
236 
237 	return B_OK;
238 }
239 
240 
241 static status_t
242 load_dependencies(image_t* image, bool preload = false)
243 {
244 	// load dependencies (breadth-first)
245 	for (image_t* otherImage = image; otherImage != NULL;
246 			otherImage = otherImage->next) {
247 		status_t status = load_immediate_dependencies(otherImage, preload);
248 		if (status != B_OK)
249 			return status;
250 		preload = false;
251 	}
252 
253 	// Check the needed versions for the given image and all newly loaded
254 	// dependencies.
255 	for (image_t* otherImage = image; otherImage != NULL;
256 			otherImage = otherImage->next) {
257 		status_t status = check_needed_image_versions(otherImage);
258 		if (status != B_OK)
259 			return status;
260 	}
261 
262 	return B_OK;
263 }
264 
265 
266 static status_t
267 relocate_image(image_t *rootImage, image_t *image)
268 {
269 	SymbolLookupCache cache(image);
270 
271 	status_t status = arch_relocate_image(rootImage, image, &cache);
272 	if (status < B_OK) {
273 		FATAL("%s: Troubles relocating: %s\n", image->path, strerror(status));
274 		return status;
275 	}
276 
277 	_kern_image_relocated(image->id);
278 	image_event(image, IMAGE_EVENT_RELOCATED);
279 	return B_OK;
280 }
281 
282 
283 static status_t
284 relocate_dependencies(image_t *image)
285 {
286 	// get the images that still have to be relocated
287 	image_t **list;
288 	ssize_t count = get_sorted_image_list(image, &list, RFLAG_RELOCATED);
289 	if (count < B_OK)
290 		return count;
291 
292 	// relocate
293 	for (ssize_t i = 0; i < count; i++) {
294 		status_t status = relocate_image(image, list[i]);
295 		if (status < B_OK) {
296 			free(list);
297 			return status;
298 		}
299 	}
300 
301 	free(list);
302 	return B_OK;
303 }
304 
305 
306 static void
307 init_dependencies(image_t *image, bool initHead)
308 {
309 	image_t **initList;
310 	ssize_t count, i;
311 
312 	if (initHead && image->preinit_array) {
313 		uint count_preinit = image->preinit_array_len / sizeof(addr_t);
314 		for (uint j = 0; j < count_preinit; j++)
315 			((initfini_array_function)image->preinit_array[j])();
316 	}
317 
318 	count = get_sorted_image_list(image, &initList, RFLAG_INITIALIZED);
319 	if (count <= 0)
320 		return;
321 
322 	if (!initHead) {
323 		// this removes the "calling" image
324 		image->flags &= ~RFLAG_INITIALIZED;
325 		initList[--count] = NULL;
326 	}
327 
328 	TRACE(("%ld: init dependencies\n", find_thread(NULL)));
329 	for (i = 0; i < count; i++) {
330 		image = initList[i];
331 
332 		TRACE(("%ld:  init: %s\n", find_thread(NULL), image->name));
333 
334 		init_term_function before;
335 		if (find_symbol(image,
336 				SymbolLookupInfo(B_INIT_BEFORE_FUNCTION_NAME, B_SYMBOL_TYPE_TEXT),
337 				(void**)&before) == B_OK) {
338 			before(image->id);
339 		}
340 
341 		if (image->init_routine != 0)
342 			((init_term_function)image->init_routine)(image->id);
343 
344 		if (image->init_array) {
345 			uint count_init = image->init_array_len / sizeof(addr_t);
346 			for (uint j = 0; j < count_init; j++)
347 				((initfini_array_function)image->init_array[j])();
348 		}
349 
350 		init_term_function after;
351 		if (find_symbol(image,
352 				SymbolLookupInfo(B_INIT_AFTER_FUNCTION_NAME, B_SYMBOL_TYPE_TEXT),
353 				(void**)&after) == B_OK) {
354 			after(image->id);
355 		}
356 
357 		image_event(image, IMAGE_EVENT_INITIALIZED);
358 	}
359 	TRACE(("%ld: init done.\n", find_thread(NULL)));
360 
361 	free(initList);
362 }
363 
364 
365 static void
366 call_term_functions(image_t* image)
367 {
368 	init_term_function before;
369 	if (find_symbol(image,
370 			SymbolLookupInfo(B_TERM_BEFORE_FUNCTION_NAME, B_SYMBOL_TYPE_TEXT),
371 			(void**)&before) == B_OK) {
372 		before(image->id);
373 	}
374 
375 	if (image->term_array) {
376 		uint count_term = image->term_array_len / sizeof(addr_t);
377 		for (uint i = count_term; i-- > 0;)
378 			((initfini_array_function)image->term_array[i])();
379 	}
380 
381 	if (image->term_routine)
382 		((init_term_function)image->term_routine)(image->id);
383 
384 	init_term_function after;
385 	if (find_symbol(image,
386 			SymbolLookupInfo(B_TERM_AFTER_FUNCTION_NAME, B_SYMBOL_TYPE_TEXT),
387 			(void**)&after) == B_OK) {
388 		after(image->id);
389 	}
390 }
391 
392 
393 static void
394 inject_runtime_loader_api(image_t* rootImage)
395 {
396 	// We patch any exported __gRuntimeLoader symbols to point to our private
397 	// API.
398 	image_t* image;
399 	void* _export;
400 	if (find_symbol_breadth_first(rootImage,
401 			SymbolLookupInfo("__gRuntimeLoader", B_SYMBOL_TYPE_DATA), &image,
402 			&_export) == B_OK) {
403 		*(void**)_export = &gRuntimeLoader;
404 	}
405 }
406 
407 
408 static status_t
409 add_preloaded_addon(image_t* image)
410 {
411 	// We realloc() everytime -- not particularly efficient, but good enough for
412 	// small number of preloaded addons.
413 	image_t** newArray = (image_t**)realloc(sPreloadedAddons,
414 		sizeof(image_t*) * (sPreloadedAddonCount + 1));
415 	if (newArray == NULL)
416 		return B_NO_MEMORY;
417 
418 	sPreloadedAddons = newArray;
419 	newArray[sPreloadedAddonCount++] = image;
420 
421 	return B_OK;
422 }
423 
424 
425 image_id
426 preload_addon(char const* path)
427 {
428 	if (path == NULL)
429 		return B_BAD_VALUE;
430 
431 	KTRACE("rld: preload_addon(\"%s\")", path);
432 
433 	image_t *image = NULL;
434 	status_t status = load_image(path, B_LIBRARY_IMAGE, NULL, NULL, &image);
435 	if (status < B_OK) {
436 		KTRACE("rld: preload_addon(\"%s\") failed to load container: %s", path,
437 			strerror(status));
438 		return status;
439 	}
440 
441 	if (image->find_undefined_symbol == NULL)
442 		image->find_undefined_symbol = find_undefined_symbol_global;
443 
444 	status = load_dependencies(image);
445 	if (status < B_OK)
446 		goto err;
447 
448 	set_image_flags_recursively(image, RTLD_GLOBAL);
449 
450 	status = relocate_dependencies(image);
451 	if (status < B_OK)
452 		goto err;
453 
454 	status = add_preloaded_addon(image);
455 	if (status < B_OK)
456 		goto err;
457 
458 	inject_runtime_loader_api(image);
459 
460 	remap_images();
461 	init_dependencies(image, true);
462 
463 	// if the image contains an add-on, register it
464 	runtime_loader_add_on* addOnStruct;
465 	if (find_symbol(image,
466 			SymbolLookupInfo("__gRuntimeLoaderAddOn", B_SYMBOL_TYPE_DATA),
467 			(void**)&addOnStruct) == B_OK) {
468 		add_add_on(image, addOnStruct);
469 	}
470 
471 	KTRACE("rld: preload_addon(\"%s\") done: id: %" B_PRId32, path, image->id);
472 
473 	return image->id;
474 
475 err:
476 	KTRACE("rld: preload_addon(\"%s\") failed: %s", path, strerror(status));
477 
478 	dequeue_loaded_image(image);
479 	delete_image(image);
480 	return status;
481 }
482 
483 
484 static void
485 preload_addons()
486 {
487 	const char* imagePaths = getenv("LD_PRELOAD_ADDONS");
488 	if (imagePaths == NULL)
489 		return;
490 
491 	while (*imagePaths != '\0') {
492 		// find begin of image path
493 		while (*imagePaths != '\0' && isspace(*imagePaths))
494 			imagePaths++;
495 
496 		if (*imagePaths == '\0')
497 			break;
498 
499 		// find end of image path
500 		const char* imagePath = imagePaths;
501 		while (*imagePaths != '\0' && !isspace(*imagePaths))
502 			imagePaths++;
503 
504 		// extract the path
505 		char path[B_PATH_NAME_LENGTH];
506 		size_t pathLen = imagePaths - imagePath;
507 		if (pathLen > sizeof(path) - 1)
508 			continue;
509 		memcpy(path, imagePath, pathLen);
510 		path[pathLen] = '\0';
511 
512 		// load the image
513 		preload_addon(path);
514 	}
515 }
516 
517 
518 //	#pragma mark - libroot.so exported functions
519 
520 
521 image_id
522 load_program(char const *path, void **_entry)
523 {
524 	status_t status;
525 	image_t *image;
526 
527 	KTRACE("rld: load_program(\"%s\")", path);
528 
529 	RecursiveLocker _(sLock);
530 		// for now, just do stupid simple global locking
531 
532 	preload_addons();
533 
534 	TRACE(("rld: load %s\n", path));
535 
536 	status = load_image(path, B_APP_IMAGE, NULL, NULL, &gProgramImage);
537 	if (status < B_OK)
538 		goto err;
539 
540 	if (gProgramImage->find_undefined_symbol == NULL)
541 		gProgramImage->find_undefined_symbol = find_undefined_symbol_global;
542 
543 	status = load_dependencies(gProgramImage, true);
544 	if (status < B_OK)
545 		goto err;
546 
547 	// Set RTLD_GLOBAL on all libraries including the program.
548 	// This results in the desired symbol resolution for dlopen()ed libraries.
549 	set_image_flags_recursively(gProgramImage, RTLD_GLOBAL);
550 
551 	status = relocate_dependencies(gProgramImage);
552 	if (status < B_OK)
553 		goto err;
554 
555 	inject_runtime_loader_api(gProgramImage);
556 
557 	remap_images();
558 	init_dependencies(gProgramImage, true);
559 
560 	// Since the images are initialized now, we no longer should use our
561 	// getenv(), but use the one from libroot.so
562 	find_symbol_breadth_first(gProgramImage,
563 		SymbolLookupInfo("getenv", B_SYMBOL_TYPE_TEXT), &image,
564 		(void**)&gGetEnv);
565 
566 	if (gProgramImage->entry_point == 0) {
567 		status = B_NOT_AN_EXECUTABLE;
568 		goto err;
569 	}
570 
571 	*_entry = (void *)(gProgramImage->entry_point);
572 
573 	gProgramLoaded = true;
574 
575 	KTRACE("rld: load_program(\"%s\") done: entry: %p, id: %" B_PRId32 , path,
576 		*_entry, gProgramImage->id);
577 
578 	return gProgramImage->id;
579 
580 err:
581 	KTRACE("rld: load_program(\"%s\") failed: %s", path, strerror(status));
582 
583 	delete_image(gProgramImage);
584 
585 	if (report_errors()) {
586 		// send error message
587 		gErrorMessage.AddInt32("error", status);
588 		gErrorMessage.SetDeliveryInfo(gProgramArgs->error_token,
589 			-1, 0, find_thread(NULL));
590 
591 		_kern_write_port_etc(gProgramArgs->error_port, 'KMSG',
592 			gErrorMessage.Buffer(), gErrorMessage.ContentSize(), 0, 0);
593 	}
594 	_kern_loading_app_failed(status);
595 
596 	return status;
597 }
598 
599 
600 image_id
601 load_library(char const *path, uint32 flags, bool addOn, void** _handle)
602 {
603 	image_t *image = NULL;
604 	image_type type = (addOn ? B_ADD_ON_IMAGE : B_LIBRARY_IMAGE);
605 	status_t status;
606 
607 	if (path == NULL && addOn)
608 		return B_BAD_VALUE;
609 
610 	KTRACE("rld: load_library(\"%s\", %#" B_PRIx32 ", %d)", path, flags, addOn);
611 
612 	RecursiveLocker _(sLock);
613 		// for now, just do stupid simple global locking
614 
615 	// have we already loaded this library?
616 	// Checking it at this stage saves loading its dependencies again
617 	if (!addOn) {
618 		// a NULL path is fine -- it means the global scope shall be opened
619 		if (path == NULL) {
620 			*_handle = RLD_GLOBAL_SCOPE;
621 			return 0;
622 		}
623 
624 		image = find_loaded_image_by_name(path, APP_OR_LIBRARY_TYPE);
625 		if (image != NULL && (flags & RTLD_GLOBAL) != 0)
626 			set_image_flags_recursively(image, RTLD_GLOBAL);
627 
628 		if (image) {
629 			atomic_add(&image->ref_count, 1);
630 			KTRACE("rld: load_library(\"%s\"): already loaded: %" B_PRId32,
631 				path, image->id);
632 			*_handle = image;
633 			return image->id;
634 		}
635 	}
636 
637 	status = load_image(path, type, NULL, NULL, &image);
638 	if (status < B_OK) {
639 		KTRACE("rld: load_library(\"%s\") failed to load container: %s", path,
640 			strerror(status));
641 		return status;
642 	}
643 
644 	if (image->find_undefined_symbol == NULL) {
645 		if (addOn)
646 			image->find_undefined_symbol = find_undefined_symbol_add_on;
647 		else
648 			image->find_undefined_symbol = find_undefined_symbol_global;
649 	}
650 
651 	status = load_dependencies(image);
652 	if (status < B_OK)
653 		goto err;
654 
655 	// If specified, set the RTLD_GLOBAL flag recursively on this image and all
656 	// dependencies. If not specified, we temporarily set
657 	// RFLAG_USE_FOR_RESOLVING so that the dependencies will correctly be used
658 	// for undefined symbol resolution.
659 	if ((flags & RTLD_GLOBAL) != 0)
660 		set_image_flags_recursively(image, RTLD_GLOBAL);
661 	else
662 		set_image_flags_recursively(image, RFLAG_USE_FOR_RESOLVING);
663 
664 	status = relocate_dependencies(image);
665 	if (status < B_OK)
666 		goto err;
667 
668 	if ((flags & RTLD_GLOBAL) == 0)
669 		clear_image_flags_recursively(image, RFLAG_USE_FOR_RESOLVING);
670 
671 	remap_images();
672 	init_dependencies(image, true);
673 
674 	KTRACE("rld: load_library(\"%s\") done: id: %" B_PRId32, path, image->id);
675 
676 	*_handle = image;
677 	return image->id;
678 
679 err:
680 	KTRACE("rld: load_library(\"%s\") failed: %s", path, strerror(status));
681 
682 	dequeue_loaded_image(image);
683 	delete_image(image);
684 	return status;
685 }
686 
687 
688 status_t
689 unload_library(void* handle, image_id imageID, bool addOn)
690 {
691 	image_t *image;
692 	image_type type = addOn ? B_ADD_ON_IMAGE : B_LIBRARY_IMAGE;
693 
694 	if (handle == NULL && imageID < 0)
695 		return B_BAD_IMAGE_ID;
696 
697 	if (handle == RLD_GLOBAL_SCOPE)
698 		return B_OK;
699 
700 	RecursiveLocker _(sLock);
701 		// for now, just do stupid simple global locking
702 
703 	if (gInvalidImageIDs) {
704 		// After fork, we lazily rebuild the image IDs of all loaded images
705 		update_image_ids();
706 	}
707 
708 	// we only check images that have been already initialized
709 
710 	status_t status = B_BAD_IMAGE_ID;
711 
712 	if (handle != NULL) {
713 		image = (image_t*)handle;
714 		put_image(image);
715 		status = B_OK;
716 	} else {
717 		image = find_loaded_image_by_id(imageID, true);
718 		if (image != NULL) {
719 			// unload image
720 			if (type == image->type) {
721 				put_image(image);
722 				status = B_OK;
723 			} else
724 				status = B_BAD_VALUE;
725 		}
726 	}
727 
728 	if (status == B_OK) {
729 		while ((image = get_disposable_images().head) != NULL) {
730 			// Call the exit hooks that live in this image.
731 			// Note: With the Itanium ABI this shouldn't really be done this
732 			// way anymore, since global destructors are registered via
733 			// __cxa_atexit() (the ones that are registered dynamically) and the
734 			// termination routine should call __cxa_finalize() for the image.
735 			// The reason why we still do it is that hooks registered with
736 			// atexit() aren't associated with the image. We could find out
737 			// there which image the hooks lives in and register it
738 			// respectively, but since that would be done always, that's
739 			// probably more expensive than calling
740 			// call_atexit_hooks_for_range() only here, which happens only when
741 			// libraries are unloaded dynamically.
742 			if (gRuntimeLoader.call_atexit_hooks_for_range) {
743 				gRuntimeLoader.call_atexit_hooks_for_range(
744 					image->regions[0].vmstart, image->regions[0].vmsize);
745 			}
746 
747 			image_event(image, IMAGE_EVENT_UNINITIALIZING);
748 
749 			call_term_functions(image);
750 
751 			TLSBlockTemplates::Get().Unregister(image->dso_tls_id);
752 
753 			dequeue_disposable_image(image);
754 			unmap_image(image);
755 
756 			image_event(image, IMAGE_EVENT_UNLOADING);
757 
758 			delete_image(image);
759 		}
760 	}
761 
762 	return status;
763 }
764 
765 
766 status_t
767 get_nth_symbol(image_id imageID, int32 num, char *nameBuffer,
768 	int32 *_nameLength, int32 *_type, void **_location)
769 {
770 	int32 count = 0, j;
771 	uint32 i;
772 	image_t *image;
773 
774 	RecursiveLocker _(sLock);
775 
776 	// get the image from those who have been already initialized
777 	image = find_loaded_image_by_id(imageID, false);
778 	if (image == NULL)
779 		return B_BAD_IMAGE_ID;
780 
781 	// iterate through all the hash buckets until we've found the one
782 	for (i = 0; i < HASHTABSIZE(image); i++) {
783 		for (j = HASHBUCKETS(image)[i]; j != STN_UNDEF; j = HASHCHAINS(image)[j]) {
784 			elf_sym *symbol = &image->syms[j];
785 
786 			if (count == num) {
787 				const char* symbolName = SYMNAME(image, symbol);
788 				strlcpy(nameBuffer, symbolName, *_nameLength);
789 				*_nameLength = strlen(symbolName);
790 
791 				void* location = (void*)(symbol->st_value
792 					+ image->regions[0].delta);
793 				int32 type;
794 				if (symbol->Type() == STT_FUNC)
795 					type = B_SYMBOL_TYPE_TEXT;
796 				else if (symbol->Type() == STT_OBJECT)
797 					type = B_SYMBOL_TYPE_DATA;
798 				else
799 					type = B_SYMBOL_TYPE_ANY;
800 					// TODO: check with the return types of that BeOS function
801 
802 				patch_defined_symbol(image, symbolName, &location, &type);
803 
804 				if (_type != NULL)
805 					*_type = type;
806 				if (_location != NULL)
807 					*_location = location;
808 				goto out;
809 			}
810 			count++;
811 		}
812 	}
813 out:
814 	if (num != count)
815 		return B_BAD_INDEX;
816 
817 	return B_OK;
818 }
819 
820 
821 status_t
822 get_nearest_symbol_at_address(void* address, image_id* _imageID,
823 	char** _imagePath, char** _imageName, char** _symbolName, int32* _type,
824 	void** _location, bool* _exactMatch)
825 {
826 	RecursiveLocker _(sLock);
827 
828 	image_t* image = find_loaded_image_by_address((addr_t)address);
829 	if (image == NULL)
830 		return B_BAD_VALUE;
831 
832 	if (_imageID != NULL)
833 		*_imageID = image->id;
834 	if (_imagePath != NULL)
835 		*_imagePath = image->path;
836 	if (_imageName != NULL)
837 		*_imageName = image->name;
838 
839 	// If the caller does not want the actual symbol name, only the image,
840 	// we can just return immediately.
841 	if (_symbolName == NULL && _type == NULL && _location == NULL)
842 		return B_OK;
843 
844 	bool exactMatch = false;
845 	elf_sym* foundSymbol = NULL;
846 	addr_t foundLocation = (addr_t)NULL;
847 
848 	for (uint32 i = 0; i < HASHTABSIZE(image) && !exactMatch; i++) {
849 		for (int32 j = HASHBUCKETS(image)[i]; j != STN_UNDEF;
850 				j = HASHCHAINS(image)[j]) {
851 			elf_sym *symbol = &image->syms[j];
852 			addr_t location = symbol->st_value + image->regions[0].delta;
853 
854 			if (location <= (addr_t)address	&& location >= foundLocation) {
855 				foundSymbol = symbol;
856 				foundLocation = location;
857 
858 				// jump out if we have an exact match
859 				if (location + symbol->st_size > (addr_t)address) {
860 					exactMatch = true;
861 					break;
862 				}
863 			}
864 		}
865 	}
866 
867 	if (_exactMatch != NULL)
868 		*_exactMatch = exactMatch;
869 
870 	if (foundSymbol != NULL) {
871 		*_symbolName = SYMNAME(image, foundSymbol);
872 
873 		if (_type != NULL) {
874 			if (foundSymbol->Type() == STT_FUNC)
875 				*_type = B_SYMBOL_TYPE_TEXT;
876 			else if (foundSymbol->Type() == STT_OBJECT)
877 				*_type = B_SYMBOL_TYPE_DATA;
878 			else
879 				*_type = B_SYMBOL_TYPE_ANY;
880 			// TODO: check with the return types of that BeOS function
881 		}
882 
883 		if (_location != NULL)
884 			*_location = (void*)foundLocation;
885 	} else {
886 		*_symbolName = NULL;
887 		if (_location != NULL)
888 			*_location = NULL;
889 	}
890 
891 	return B_OK;
892 }
893 
894 
895 status_t
896 get_symbol(image_id imageID, char const *symbolName, int32 symbolType,
897 	bool recursive, image_id *_inImage, void **_location)
898 {
899 	status_t status = B_OK;
900 	image_t *image;
901 
902 	if (imageID < B_OK)
903 		return B_BAD_IMAGE_ID;
904 	if (symbolName == NULL)
905 		return B_BAD_VALUE;
906 
907 	// Previously, these functions were called in __haiku_init_before
908 	// and __haiku_init_after. Now we call them inside runtime_loader,
909 	// so we prevent applications from fetching them.
910 	if (strcmp(symbolName, B_INIT_BEFORE_FUNCTION_NAME) == 0
911 		|| strcmp(symbolName, B_INIT_AFTER_FUNCTION_NAME) == 0
912 		|| strcmp(symbolName, B_TERM_BEFORE_FUNCTION_NAME) == 0
913 		|| strcmp(symbolName, B_TERM_AFTER_FUNCTION_NAME) == 0)
914 		return B_BAD_VALUE;
915 
916 	RecursiveLocker _(sLock);
917 		// for now, just do stupid simple global locking
918 
919 	// get the image from those who have been already initialized
920 	image = find_loaded_image_by_id(imageID, false);
921 	if (image != NULL) {
922 		if (recursive) {
923 			// breadth-first search in the given image and its dependencies
924 			status = find_symbol_breadth_first(image,
925 				SymbolLookupInfo(symbolName, symbolType, NULL,
926 					LOOKUP_FLAG_DEFAULT_VERSION),
927 				&image, _location);
928 		} else {
929 			status = find_symbol(image,
930 				SymbolLookupInfo(symbolName, symbolType, NULL,
931 					LOOKUP_FLAG_DEFAULT_VERSION),
932 				_location);
933 		}
934 
935 		if (status == B_OK && _inImage != NULL)
936 			*_inImage = image->id;
937 	} else
938 		status = B_BAD_IMAGE_ID;
939 
940 	return status;
941 }
942 
943 
944 status_t
945 get_library_symbol(void* handle, void* caller, const char* symbolName,
946 	void **_location)
947 {
948 	status_t status = B_ENTRY_NOT_FOUND;
949 
950 	if (symbolName == NULL)
951 		return B_BAD_VALUE;
952 
953 	RecursiveLocker _(sLock);
954 		// for now, just do stupid simple global locking
955 
956 	if (handle == RTLD_DEFAULT || handle == RLD_GLOBAL_SCOPE) {
957 		// look in the default scope
958 		image_t* image;
959 		elf_sym* symbol = find_undefined_symbol_global(gProgramImage,
960 			gProgramImage,
961 			SymbolLookupInfo(symbolName, B_SYMBOL_TYPE_ANY, NULL,
962 				LOOKUP_FLAG_DEFAULT_VERSION),
963 			&image);
964 		if (symbol != NULL) {
965 			*_location = (void*)(symbol->st_value + image->regions[0].delta);
966 			int32 symbolType = symbol->Type() == STT_FUNC
967 				? B_SYMBOL_TYPE_TEXT : B_SYMBOL_TYPE_DATA;
968 			patch_defined_symbol(image, symbolName, _location, &symbolType);
969 			status = B_OK;
970 		}
971 	} else if (handle == RTLD_NEXT) {
972 		// Look in the default scope, but also in the dependencies of the
973 		// calling image. Return the next after the caller symbol.
974 
975 		// First of all, find the caller image.
976 		image_t* callerImage = get_loaded_images().head;
977 		for (; callerImage != NULL; callerImage = callerImage->next) {
978 			elf_region_t& text = callerImage->regions[0];
979 			if ((addr_t)caller >= text.vmstart
980 				&& (addr_t)caller < text.vmstart + text.vmsize) {
981 				// found the image
982 				break;
983 			}
984 		}
985 
986 		if (callerImage != NULL) {
987 			// found the caller -- now search the global scope until we find
988 			// the next symbol
989 			bool hitCallerImage = false;
990 			set_image_flags_recursively(callerImage, RFLAG_USE_FOR_RESOLVING);
991 
992 			elf_sym* candidateSymbol = NULL;
993 			image_t* candidateImage = NULL;
994 
995 			image_t* image = get_loaded_images().head;
996 			for (; image != NULL; image = image->next) {
997 				// skip the caller image
998 				if (image == callerImage) {
999 					hitCallerImage = true;
1000 					continue;
1001 				}
1002 
1003 				// skip all images up to the caller image; also skip add-on
1004 				// images and those not marked above for resolution
1005 				if (!hitCallerImage || image->type == B_ADD_ON_IMAGE
1006 					|| (image->flags
1007 						& (RTLD_GLOBAL | RFLAG_USE_FOR_RESOLVING)) == 0) {
1008 					continue;
1009 				}
1010 
1011 				elf_sym *symbol = find_symbol(image,
1012 					SymbolLookupInfo(symbolName, B_SYMBOL_TYPE_TEXT, NULL,
1013 						LOOKUP_FLAG_DEFAULT_VERSION));
1014 				if (symbol == NULL)
1015 					continue;
1016 
1017 				// found a symbol
1018 				bool isWeak = symbol->Bind() == STB_WEAK;
1019 				if (candidateImage == NULL || !isWeak) {
1020 					candidateSymbol = symbol;
1021 					candidateImage = image;
1022 
1023 					if (!isWeak)
1024 						break;
1025 				}
1026 
1027 				// symbol is weak, so we need to continue
1028 			}
1029 
1030 			if (candidateSymbol != NULL) {
1031 				// found the symbol
1032 				*_location = (void*)(candidateSymbol->st_value
1033 					+ candidateImage->regions[0].delta);
1034 				int32 symbolType = B_SYMBOL_TYPE_TEXT;
1035 				patch_defined_symbol(candidateImage, symbolName, _location,
1036 					&symbolType);
1037 				status = B_OK;
1038 			}
1039 
1040 			clear_image_flags_recursively(callerImage, RFLAG_USE_FOR_RESOLVING);
1041 		}
1042 	} else {
1043 		// breadth-first search in the given image and its dependencies
1044 		image_t* inImage;
1045 		status = find_symbol_breadth_first((image_t*)handle,
1046 			SymbolLookupInfo(symbolName, B_SYMBOL_TYPE_ANY, NULL,
1047 				LOOKUP_FLAG_DEFAULT_VERSION),
1048 			&inImage, _location);
1049 	}
1050 
1051 	return status;
1052 }
1053 
1054 
1055 status_t
1056 get_next_image_dependency(image_id id, uint32 *cookie, const char **_name)
1057 {
1058 	uint32 i, j, searchIndex = *cookie;
1059 	elf_dyn *dynamicSection;
1060 	image_t *image;
1061 
1062 	if (_name == NULL)
1063 		return B_BAD_VALUE;
1064 
1065 	RecursiveLocker _(sLock);
1066 
1067 	image = find_loaded_image_by_id(id, false);
1068 	if (image == NULL)
1069 		return B_BAD_IMAGE_ID;
1070 
1071 	dynamicSection = (elf_dyn *)image->dynamic_ptr;
1072 	if (dynamicSection == NULL || image->num_needed <= searchIndex)
1073 		return B_ENTRY_NOT_FOUND;
1074 
1075 	for (i = 0, j = 0; dynamicSection[i].d_tag != DT_NULL; i++) {
1076 		if (dynamicSection[i].d_tag != DT_NEEDED)
1077 			continue;
1078 
1079 		if (j++ == searchIndex) {
1080 			int32 neededOffset = dynamicSection[i].d_un.d_val;
1081 
1082 			*_name = STRING(image, neededOffset);
1083 			*cookie = searchIndex + 1;
1084 			return B_OK;
1085 		}
1086 	}
1087 
1088 	return B_ENTRY_NOT_FOUND;
1089 }
1090 
1091 
1092 //	#pragma mark - runtime_loader private exports
1093 
1094 
1095 /*! Read and verify the ELF header */
1096 status_t
1097 elf_verify_header(void *header, size_t length)
1098 {
1099 	int32 programSize, sectionSize;
1100 
1101 	if (length < sizeof(elf_ehdr))
1102 		return B_NOT_AN_EXECUTABLE;
1103 
1104 	return parse_elf_header((elf_ehdr *)header, &programSize, &sectionSize);
1105 }
1106 
1107 
1108 #ifdef _COMPAT_MODE
1109 #ifdef __x86_64__
1110 status_t
1111 elf32_verify_header(void *header, size_t length)
1112 {
1113 	int32 programSize, sectionSize;
1114 
1115 	if (length < sizeof(Elf32_Ehdr))
1116 		return B_NOT_AN_EXECUTABLE;
1117 
1118 	return parse_elf32_header((Elf32_Ehdr *)header, &programSize, &sectionSize);
1119 }
1120 #else
1121 status_t
1122 elf64_verify_header(void *header, size_t length)
1123 {
1124 	int32 programSize, sectionSize;
1125 
1126 	if (length < sizeof(Elf64_Ehdr))
1127 		return B_NOT_AN_EXECUTABLE;
1128 
1129 	return parse_elf64_header((Elf64_Ehdr *)header, &programSize, &sectionSize);
1130 }
1131 #endif	// __x86_64__
1132 #endif	// _COMPAT_MODE
1133 
1134 
1135 void
1136 terminate_program(void)
1137 {
1138 	image_t **termList;
1139 	ssize_t count, i;
1140 
1141 	count = get_sorted_image_list(NULL, &termList, RFLAG_TERMINATED);
1142 	if (count < B_OK)
1143 		return;
1144 
1145 	if (gInvalidImageIDs) {
1146 		// After fork, we lazily rebuild the image IDs of all loaded images
1147 		update_image_ids();
1148 	}
1149 
1150 	TRACE(("%ld: terminate dependencies\n", find_thread(NULL)));
1151 	for (i = count; i-- > 0;) {
1152 		image_t *image = termList[i];
1153 
1154 		TRACE(("%ld:  term: %s\n", find_thread(NULL), image->name));
1155 
1156 		image_event(image, IMAGE_EVENT_UNINITIALIZING);
1157 
1158 		call_term_functions(image);
1159 
1160 		image_event(image, IMAGE_EVENT_UNLOADING);
1161 	}
1162 	TRACE(("%ld:  term done.\n", find_thread(NULL)));
1163 
1164 	free(termList);
1165 }
1166 
1167 
1168 void
1169 rldelf_init(void)
1170 {
1171 	init_add_ons();
1172 
1173 	// create the debug area
1174 	{
1175 		size_t size = TO_PAGE_SIZE(sizeof(runtime_loader_debug_area));
1176 
1177 		runtime_loader_debug_area *area;
1178 		area_id areaID = _kern_create_area(RUNTIME_LOADER_DEBUG_AREA_NAME,
1179 			(void **)&area, B_RANDOMIZED_ANY_ADDRESS, size, B_NO_LOCK,
1180 			B_READ_AREA | B_WRITE_AREA | B_CLONEABLE_AREA);
1181 		if (areaID < B_OK) {
1182 			FATAL("Failed to create debug area.\n");
1183 			_kern_loading_app_failed(areaID);
1184 		}
1185 
1186 		area->loaded_images = &get_loaded_images();
1187 	}
1188 
1189 	// initialize error message if needed
1190 	if (report_errors()) {
1191 		void *buffer = malloc(1024);
1192 		if (buffer == NULL)
1193 			return;
1194 
1195 		gErrorMessage.SetTo(buffer, 1024, 'Rler');
1196 	}
1197 }
1198 
1199 
1200 status_t
1201 elf_reinit_after_fork(void)
1202 {
1203 	recursive_lock_init(&sLock, kLockName);
1204 
1205 	// We also need to update the IDs of our images. We are the child and
1206 	// and have cloned images with different IDs. Since in most cases (fork()
1207 	// + exec*()) this would just increase the fork() overhead with no one
1208 	// caring, we do that lazily, when first doing something different.
1209 	gInvalidImageIDs = true;
1210 
1211 	return B_OK;
1212 }
1213