xref: /openbsd/libexec/ld.so/library_subr.c (revision ba367c05)
1 /*	$OpenBSD: library_subr.c,v 1.55 2023/04/27 12:27:56 robert Exp $ */
2 
3 /*
4  * Copyright (c) 2002 Dale Rahn
5  * Copyright (c) 1998 Per Fogelstrom, Opsycon AB
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
17  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
20  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  */
29 
30 #define _DYN_LOADER
31 
32 #include <sys/types.h>
33 #include <sys/queue.h>
34 #include <limits.h>
35 #include <dirent.h>
36 
37 #include "util.h"
38 #include "resolve.h"
39 #include "dir.h"
40 #include "sod.h"
41 
42 char * _dl_default_path[2] = { "/usr/lib", NULL };
43 
44 
45 /* STATIC DATA */
46 struct dlochld _dlopened_child_list;
47 
48 
49 /*
50  * _dl_match_file()
51  *
52  * This function determines if a given name matches what is specified
53  * in a struct sod. The major must match exactly, and the minor must
54  * be same or larger.
55  *
56  * sodp is updated with the minor if this matches.
57  */
58 
59 int
_dl_match_file(struct sod * sodp,const char * name,int namelen)60 _dl_match_file(struct sod *sodp, const char *name, int namelen)
61 {
62 	int match;
63 	struct sod lsod;
64 	const char *lname;
65 
66 	lname = name;
67 	if (sodp->sod_library) {
68 		if (_dl_strncmp(name, "lib", 3))
69 			return 0;
70 		lname += 3;
71 	}
72 	if (_dl_strncmp(lname, (char *)sodp->sod_name,
73 	    _dl_strlen((char *)sodp->sod_name)))
74 		return 0;
75 
76 	_dl_build_sod(name, &lsod);
77 
78 	match = 0;
79 	if ((_dl_strcmp((char *)lsod.sod_name, (char *)sodp->sod_name) == 0) &&
80 	    (lsod.sod_library == sodp->sod_library) &&
81 	    ((sodp->sod_major == -1) || (sodp->sod_major == lsod.sod_major)) &&
82 	    ((sodp->sod_minor == -1) ||
83 	    (lsod.sod_minor >= sodp->sod_minor))) {
84 		match = 1;
85 
86 		/* return version matched */
87 		sodp->sod_major = lsod.sod_major;
88 		sodp->sod_minor = lsod.sod_minor;
89 	}
90 	_dl_free((char *)lsod.sod_name);
91 	return match;
92 }
93 
94 /*
95  * _dl_cmp_sod()
96  *
97  * This function compares sod structs. The major must match exactly,
98  * and the minor must be same or larger.
99  *
100  * sodp is updated with the minor if this matches.
101  */
102 
103 static int
_dl_cmp_sod(struct sod * sodp,const struct sod * lsod)104 _dl_cmp_sod(struct sod *sodp, const struct sod *lsod)
105 {
106 	int match;
107 
108 	match = 1;
109 	if ((_dl_strcmp((char *)lsod->sod_name, (char *)sodp->sod_name) == 0) &&
110 	    (lsod->sod_library == sodp->sod_library) &&
111 	    ((sodp->sod_major == -1) || (sodp->sod_major == lsod->sod_major)) &&
112 	    ((sodp->sod_minor == -1) ||
113 	    (lsod->sod_minor >= sodp->sod_minor))) {
114 		match = 0;
115 
116 		/* return version matched */
117 		sodp->sod_major = lsod->sod_major;
118 		sodp->sod_minor = lsod->sod_minor;
119 	}
120 	return match;
121 }
122 
123 char _dl_hint_store[PATH_MAX];
124 
125 char *
_dl_find_shlib(struct sod * sodp,char ** searchpath,int nohints)126 _dl_find_shlib(struct sod *sodp, char **searchpath, int nohints)
127 {
128 	char *hint, **pp;
129 	struct dirent *dp;
130 	int match, len;
131 	_dl_DIR *dd;
132 	struct sod tsod, bsod;		/* transient and best sod */
133 
134 	/* if we are to search default directories, and hints
135 	 * are not to be used, search the standard path from ldconfig
136 	 * (_dl_hint_search_path) or use the default path
137 	 */
138 	if (nohints)
139 		goto nohints;
140 
141 	if (searchpath == NULL) {
142 		/* search 'standard' locations, find any match in the hints */
143 		hint = _dl_findhint((char *)sodp->sod_name, sodp->sod_major,
144 		    sodp->sod_minor, NULL);
145 		if (hint)
146 			return hint;
147 	} else {
148 		/* search hints requesting matches for only
149 		 * the searchpath directories,
150 		 */
151 		for (pp = searchpath; *pp != NULL; pp++) {
152 			hint = _dl_findhint((char *)sodp->sod_name,
153 			    sodp->sod_major, sodp->sod_minor, *pp);
154 			if (hint != NULL)
155 				return hint;
156 		}
157 	}
158 
159 	/*
160 	 * For each directory in the searchpath, read the directory
161 	 * entries looking for a match to sod. filename compare is
162 	 * done by _dl_match_file()
163 	 */
164 nohints:
165 	if (searchpath == NULL) {
166 		if (_dl_hint_search_path != NULL)
167 			searchpath = _dl_hint_search_path;
168 		else
169 			searchpath = _dl_default_path;
170 	}
171 	_dl_memset(&bsod, 0, sizeof(bsod));
172 	for (pp = searchpath; *pp != NULL; pp++) {
173 		if ((dd = _dl_opendir(*pp)) != NULL) {
174 			match = 0;
175 			while ((dp = _dl_readdir(dd)) != NULL) {
176 				tsod = *sodp;
177 				if (_dl_match_file(&tsod, dp->d_name,
178 				    dp->d_namlen)) {
179 					/*
180 					 * When a match is found, tsod is
181 					 * updated with the major+minor found.
182 					 * This version is compared with the
183 					 * largest so far (kept in bsod),
184 					 * and saved if larger.
185 					 */
186 					if (!match ||
187 					    tsod.sod_major == -1 ||
188 					    tsod.sod_major > bsod.sod_major ||
189 					    ((tsod.sod_major ==
190 					    bsod.sod_major) &&
191 					    tsod.sod_minor > bsod.sod_minor)) {
192 						bsod = tsod;
193 						match = 1;
194 						len = _dl_strlcpy(
195 						    _dl_hint_store, *pp,
196 						    PATH_MAX);
197 						if (pp[0][len-1] != '/') {
198 							_dl_hint_store[len] =
199 							    '/';
200 							len++;
201 						}
202 						_dl_strlcpy(
203 						    &_dl_hint_store[len],
204 						    dp->d_name,
205 						    PATH_MAX-len);
206 						if (tsod.sod_major == -1)
207 							break;
208 					}
209 				}
210 			}
211 			_dl_closedir(dd);
212 			if (match) {
213 				*sodp = bsod;
214 				return (_dl_hint_store);
215 			}
216 		}
217 	}
218 	return NULL;
219 }
220 
221 static elf_object_t *
_dl_lookup_object(const char * req_name,struct sod * req_sod)222 _dl_lookup_object(const char *req_name, struct sod *req_sod)
223 {
224 	elf_object_t *object = _dl_objects;
225 
226 	while (object) {
227 		char *soname;
228 
229 		if (_dl_cmp_sod(req_sod, &object->sod) == 0)
230 			return(object);
231 
232 		soname = (char *)object->Dyn.info[DT_SONAME];
233 		if (soname != NULL) {
234 			if (_dl_strcmp(req_name, soname) == 0)
235 				return(object);
236 		}
237 
238 		object = object->next;
239 	}
240 
241 	return(NULL);
242 }
243 
244 void
_dl_handle_already_loaded(elf_object_t * object,int flags)245 _dl_handle_already_loaded(elf_object_t *object, int flags)
246 {
247 	object->obj_flags |= flags & DF_1_GLOBAL;
248 	if (_dl_loading_object == NULL)
249 		_dl_loading_object = object;
250 	if (object->load_object != _dl_objects &&
251 	    object->load_object != _dl_loading_object) {
252 		_dl_link_grpref(object->load_object, _dl_loading_object);
253 	}
254 }
255 
256 static elf_object_t *
_dl_find_loaded_shlib(const char * req_name,struct sod req_sod,int flags)257 _dl_find_loaded_shlib(const char *req_name, struct sod req_sod, int flags)
258 {
259 	elf_object_t *object;
260 
261 	object = _dl_lookup_object(req_name, &req_sod);
262 
263 	/* if not found retry with any minor */
264 	if (object == NULL && req_sod.sod_library && req_sod.sod_minor != -1) {
265 		short orig_minor = req_sod.sod_minor;
266 		req_sod.sod_minor = -1;
267 		object = _dl_lookup_object(req_name, &req_sod);
268 
269 		if (object != NULL && req_sod.sod_minor < orig_minor)
270 			_dl_printf("warning: lib%s.so.%d.%d: "
271 			    "minor version >= %d expected, "
272 			    "using it anyway\n",
273 			    req_sod.sod_name, req_sod.sod_major,
274 			    req_sod.sod_minor, orig_minor);
275 	}
276 
277 	if (object)
278 		_dl_handle_already_loaded(object, flags);
279 
280 	return (object);
281 }
282 
283 /*
284  *  Load a shared object. Search order is:
285  *      First check loaded objects for a matching shlib, otherwise:
286  *
287  *	If the name contains a '/' use only the path preceding the
288  *	library name and do not continue on to other methods if not
289  *	found.
290  *	   search hints for match in path preceding library name
291  *	     this will only match specific library version.
292  *	   search path preceding library name
293  *	     this will find largest minor version in path provided
294  *
295  *	Otherwise, the name doesn't contain a '/':
296  *	search hints for the specific library version, trying in turn
297  *	paths from the following:
298  *	  - the LD_LIBRARY_PATH environment variable (if set)
299  *	  - the library's own DT_RUNPATH
300  *	  - if DT_RUNPATH wasn't set, then:
301  *	    - the library's own DT_RPATH
302  *	    - the executable's own DT_RPATH
303  *	  - the default search path set by ldconfig, or /usr/lib if unset
304  *
305  *	If the hints doesn't have an exact match, then we search
306  *	that exact same list of directories again, looking for a
307  *	lib with the correct major version.  If we find a match on
308  *	the major, then we take the match *in that directory* which
309  *	has the largest minor version
310  */
311 
312 elf_object_t *
_dl_load_shlib(const char * libname,elf_object_t * parent,int type,int flags,int nodelete)313 _dl_load_shlib(const char *libname, elf_object_t *parent, int type, int flags,
314     int nodelete)
315 {
316 	int try_any_minor, ignore_hints;
317 	struct sod sod, req_sod;
318 	elf_object_t *object = NULL;
319 	char *hint;
320 
321 	try_any_minor = 0;
322 	ignore_hints = 0;
323 
324 	if (_dl_strchr(libname, '/')) {
325 		char *paths[2];
326 		char *lpath, *lname;
327 		lpath = _dl_strdup(libname);
328 		if (lpath == NULL)
329 			_dl_oom();
330 		lname = _dl_strrchr(lpath, '/');
331 		if (lname == NULL) {
332 			_dl_free(lpath);
333 			_dl_errno = DL_NOT_FOUND;
334 			return (object);
335 		}
336 		*lname = '\0';
337 		lname++;
338 		if (*lname  == '\0') {
339 			_dl_free(lpath);
340 			_dl_errno = DL_NOT_FOUND;
341 			return (object);
342 		}
343 
344 		_dl_build_sod(lname, &sod);
345 		req_sod = sod;
346 
347 		paths[0] = lpath;
348 		paths[1] = NULL;
349 fullpathagain:
350 		hint = _dl_find_shlib(&req_sod, paths, ignore_hints);
351 		if (hint != NULL)
352 			goto fullpathdone;
353 
354 		if (try_any_minor == 0) {
355 			try_any_minor = 1;
356 			ignore_hints = 1;
357 			req_sod.sod_minor = -1;
358 			goto fullpathagain;
359 		}
360 		_dl_errno = DL_NOT_FOUND;
361 fullpathdone:
362 		_dl_free(lpath);
363 		goto done;
364 	}
365 
366 	_dl_build_sod(libname, &sod);
367 	req_sod = sod;
368 
369 	object = _dl_find_loaded_shlib(libname, req_sod, flags);
370 	if (object) {
371 		_dl_free((char *)sod.sod_name);
372 		return (object);
373 	}
374 
375 again:
376 	/* No '/' in name. Scan the known places, LD_LIBRARY_PATH first.  */
377 	if (_dl_libpath != NULL) {
378 		hint = _dl_find_shlib(&req_sod, _dl_libpath, ignore_hints);
379 		if (hint != NULL)
380 			goto done;
381 	}
382 
383 	/* Check DT_RUNPATH */
384 	if (parent->runpath != NULL) {
385 		hint = _dl_find_shlib(&req_sod, parent->runpath, ignore_hints);
386 		if (hint != NULL)
387 			goto done;
388 	} else {
389 		/*
390 		 * If DT_RUNPATH wasn't set then first check DT_RPATH,
391 		 * followed by the main program's DT_RPATH.
392 		 */
393 		if (parent->rpath != NULL) {
394 			hint = _dl_find_shlib(&req_sod, parent->rpath,
395 			    ignore_hints);
396 			if (hint != NULL)
397 				goto done;
398 		}
399 		if (parent != _dl_objects && _dl_objects->rpath != NULL) {
400 			hint = _dl_find_shlib(&req_sod, _dl_objects->rpath,
401 			    ignore_hints);
402 			if (hint != NULL)
403 				goto done;
404 		}
405 	}
406 
407 	/* check 'standard' locations */
408 	hint = _dl_find_shlib(&req_sod, NULL, ignore_hints);
409 	if (hint != NULL)
410 		goto done;
411 
412 	if (try_any_minor == 0) {
413 		try_any_minor = 1;
414 		ignore_hints = 1;
415 		req_sod.sod_minor = -1;
416 		goto again;
417 	}
418 	_dl_errno = DL_NOT_FOUND;
419 done:
420 	if (hint != NULL) {
421 		if (req_sod.sod_minor < sod.sod_minor)
422 			_dl_printf("warning: lib%s.so.%d.%d: "
423 			    "minor version >= %d expected, "
424 			    "using it anyway\n",
425 			    sod.sod_name, sod.sod_major,
426 			    req_sod.sod_minor, sod.sod_minor);
427 		object = _dl_tryload_shlib(hint, type, flags, nodelete);
428 	}
429 	_dl_free((char *)sod.sod_name);
430 	return(object);
431 }
432 
433 
434 void
_dl_link_dlopen(elf_object_t * dep)435 _dl_link_dlopen(elf_object_t *dep)
436 {
437 	struct dep_node *n;
438 
439 	dep->opencount++;
440 
441 	if (OBJECT_DLREF_CNT(dep) > 1)
442 		return;
443 
444 	n = _dl_malloc(sizeof *n);
445 	if (n == NULL)
446 		_dl_oom();
447 
448 	n->data = dep;
449 	TAILQ_INSERT_TAIL(&_dlopened_child_list, n, next_sib);
450 
451 	DL_DEB(("linking %s as dlopen()ed\n", dep->load_name));
452 }
453 
454 static void
_dl_child_refcnt_decrement(elf_object_t * object)455 _dl_child_refcnt_decrement(elf_object_t *object)
456 {
457 	struct object_vector vec;
458 	int i;
459 
460 	object->refcount--;
461 	if (OBJECT_REF_CNT(object) == 0)
462 		for (vec = object->child_vec, i = 0; i < vec.len; i++)
463 			_dl_child_refcnt_decrement(vec.vec[i]);
464 }
465 
466 void
_dl_notify_unload_shlib(elf_object_t * object)467 _dl_notify_unload_shlib(elf_object_t *object)
468 {
469 	struct object_vector vec;
470 	struct dep_node *n;
471 	int i;
472 
473 	if (OBJECT_REF_CNT(object) == 0)
474 		for (vec = object->child_vec, i = 0; i < vec.len; i++)
475 			_dl_child_refcnt_decrement(vec.vec[i]);
476 
477 	if (OBJECT_DLREF_CNT(object) == 0) {
478 		while ((n = TAILQ_FIRST(&object->grpref_list)) != NULL) {
479 			TAILQ_REMOVE(&object->grpref_list, n, next_sib);
480 			n->data->grprefcount--;
481 			_dl_notify_unload_shlib(n->data);
482 			_dl_free(n);
483 		}
484 	}
485 }
486 
487 void
_dl_unload_dlopen(void)488 _dl_unload_dlopen(void)
489 {
490 	struct dep_node *node;
491 
492 	TAILQ_FOREACH_REVERSE(node, &_dlopened_child_list, dlochld, next_sib) {
493 		/* dont dlclose the main program */
494 		if (node->data == _dl_objects)
495 			continue;
496 
497 		while (node->data->opencount > 0) {
498 			node->data->opencount--;
499 			_dl_notify_unload_shlib(node->data);
500 			_dl_run_all_dtors();
501 		}
502 	}
503 }
504 
505 void
_dl_link_grpref(elf_object_t * load_group,elf_object_t * load_object)506 _dl_link_grpref(elf_object_t *load_group, elf_object_t *load_object)
507 {
508 	struct dep_node *n;
509 
510 	n = _dl_malloc(sizeof *n);
511 	if (n == NULL)
512 		_dl_oom();
513 	n->data = load_group;
514 	TAILQ_INSERT_TAIL(&load_object->grpref_list, n, next_sib);
515 	load_group->grprefcount++;
516 }
517 
518 void
_dl_link_child(elf_object_t * dep,elf_object_t * p)519 _dl_link_child(elf_object_t *dep, elf_object_t *p)
520 {
521 	int i;
522 
523 	i = p->child_vec.len++;
524 	if (i == p->child_vec.alloc)
525 		_dl_die("child appeared  %d > %d", p->child_vec.len,
526 		    p->child_vec.alloc);
527 	p->child_vec.vec[i] = dep;
528 
529 	dep->refcount++;
530 
531 	DL_DEB(("linking dep %s as child of %s\n", dep->load_name,
532 	    p->load_name));
533 }
534 
535 void
object_vec_grow(struct object_vector * vec,int more)536 object_vec_grow(struct object_vector *vec, int more)
537 {
538 	vec->alloc += more;
539 	vec->vec = _dl_reallocarray(vec->vec, vec->alloc, sizeof(*vec->vec));
540 	if (vec->vec == NULL)
541 		_dl_oom();
542 }
543 
544 /* Generation number of the current grpsym insertion/caching */
545 static unsigned int _dl_grpsym_gen = 0;
546 
547 void
_dl_link_grpsym(elf_object_t * object)548 _dl_link_grpsym(elf_object_t *object)
549 {
550 	struct object_vector *vec;
551 	int len;
552 
553 	if (object->grpsym_gen == _dl_grpsym_gen)
554 		return;
555 	object->grpsym_gen = _dl_grpsym_gen;
556 
557 	vec = &_dl_loading_object->grpsym_vec;
558 	len = vec->len++;
559 	if (len >= vec->alloc)
560 		_dl_die("more grpsym than objects?!  %d > %d", vec->len,
561 		    vec->alloc);
562 	vec->vec[len] = object;
563 }
564 
565 void
_dl_cache_grpsym_list_setup(elf_object_t * object)566 _dl_cache_grpsym_list_setup(elf_object_t *object)
567 {
568 	struct object_vector *vec;
569 	int next;
570 
571 	_dl_grpsym_gen += 1;
572 
573 	if (_dl_grpsym_gen == 0) {
574 		/*
575 		 * If the count rolls over, reset all counters so
576 		 * we don't get accidental collision.
577 		 */
578 		elf_object_t *walkobj;
579 		for (walkobj = _dl_objects;
580 		    walkobj != NULL;
581 		    walkobj = walkobj->next) {
582 			walkobj->grpsym_gen = 0;
583 		}
584 		_dl_grpsym_gen = 1;
585 	}
586 
587 	/*
588 	 * grpsym_vec is a vector of all child libs of the
589 	 * _dl_loading_object with no dups. The order is equivalent
590 	 * to a breadth-first traversal of the child list without dups.
591 	 */
592 
593 	vec = &object->grpsym_vec;
594 	object_vec_grow(vec, object_count);
595 	next = 0;
596 
597 	/* add first object manually */
598 	_dl_link_grpsym(object);
599 
600 	while (next < vec->len) {
601 		struct object_vector child_vec;
602 		int i;
603 
604 		child_vec = vec->vec[next++]->child_vec;
605 		for (i = 0; i < child_vec.len; i++)
606 			_dl_link_grpsym(child_vec.vec[i]);
607 	}
608 }
609