xref: /freebsd/sys/kern/kern_linker.c (revision 91c878a6935c5c2e99866eb267e5bc3028bf6d2f)
1 /*-
2  * Copyright (c) 1997-2000 Doug Rabson
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 __FBSDID("$FreeBSD$");
29 
30 #include "opt_ddb.h"
31 #include "opt_hwpmc_hooks.h"
32 #include "opt_mac.h"
33 
34 #include <sys/param.h>
35 #include <sys/kernel.h>
36 #include <sys/systm.h>
37 #include <sys/malloc.h>
38 #include <sys/sysproto.h>
39 #include <sys/sysent.h>
40 #include <sys/proc.h>
41 #include <sys/lock.h>
42 #include <sys/mutex.h>
43 #include <sys/sx.h>
44 #include <sys/module.h>
45 #include <sys/mount.h>
46 #include <sys/linker.h>
47 #include <sys/fcntl.h>
48 #include <sys/libkern.h>
49 #include <sys/namei.h>
50 #include <sys/vnode.h>
51 #include <sys/syscallsubr.h>
52 #include <sys/sysctl.h>
53 
54 #include <security/mac/mac_framework.h>
55 
56 #include "linker_if.h"
57 
58 #ifdef HWPMC_HOOKS
59 #include <sys/pmckern.h>
60 #endif
61 
62 #ifdef KLD_DEBUG
63 int kld_debug = 0;
64 #endif
65 
66 #define	KLD_LOCK()		sx_xlock(&kld_sx)
67 #define	KLD_UNLOCK()		sx_xunlock(&kld_sx)
68 #define	KLD_LOCKED()		sx_xlocked(&kld_sx)
69 #define	KLD_LOCK_ASSERT() do {						\
70 	if (!cold)							\
71 		sx_assert(&kld_sx, SX_XLOCKED);				\
72 } while (0)
73 
74 /*
75  * static char *linker_search_path(const char *name, struct mod_depend
76  * *verinfo);
77  */
78 static const char 	*linker_basename(const char *path);
79 
80 /*
81  * Find a currently loaded file given its filename.
82  */
83 static linker_file_t linker_find_file_by_name(const char* _filename);
84 
85 /*
86  * Find a currently loaded file given its file id.
87  */
88 static linker_file_t linker_find_file_by_id(int _fileid);
89 
90 /* Metadata from the static kernel */
91 SET_DECLARE(modmetadata_set, struct mod_metadata);
92 
93 MALLOC_DEFINE(M_LINKER, "linker", "kernel linker");
94 
95 linker_file_t linker_kernel_file;
96 
97 static struct sx kld_sx;	/* kernel linker lock */
98 
99 static linker_class_list_t classes;
100 static linker_file_list_t linker_files;
101 static int next_file_id = 1;
102 static int linker_no_more_classes = 0;
103 
104 #define	LINKER_GET_NEXT_FILE_ID(a) do {					\
105 	linker_file_t lftmp;						\
106 									\
107 	KLD_LOCK_ASSERT();						\
108 retry:									\
109 	TAILQ_FOREACH(lftmp, &linker_files, link) {			\
110 		if (next_file_id == lftmp->id) {			\
111 			next_file_id++;					\
112 			goto retry;					\
113 		}							\
114 	}								\
115 	(a) = next_file_id;						\
116 } while(0)
117 
118 
119 /* XXX wrong name; we're looking at version provision tags here, not modules */
120 typedef TAILQ_HEAD(, modlist) modlisthead_t;
121 struct modlist {
122 	TAILQ_ENTRY(modlist) link;	/* chain together all modules */
123 	linker_file_t   container;
124 	const char 	*name;
125 	int             version;
126 };
127 typedef struct modlist *modlist_t;
128 static modlisthead_t found_modules;
129 
130 static int	linker_file_add_dependency(linker_file_t file,
131 		    linker_file_t dep);
132 static caddr_t	linker_file_lookup_symbol_internal(linker_file_t file,
133 		    const char* name, int deps);
134 static int	linker_load_module(const char *kldname,
135 		    const char *modname, struct linker_file *parent,
136 		    struct mod_depend *verinfo, struct linker_file **lfpp);
137 static modlist_t modlist_lookup2(const char *name, struct mod_depend *verinfo);
138 
139 static char *
140 linker_strdup(const char *str)
141 {
142 	char *result;
143 
144 	if ((result = malloc((strlen(str) + 1), M_LINKER, M_WAITOK)) != NULL)
145 		strcpy(result, str);
146 	return (result);
147 }
148 
149 static void
150 linker_init(void *arg)
151 {
152 
153 	sx_init(&kld_sx, "kernel linker");
154 	TAILQ_INIT(&classes);
155 	TAILQ_INIT(&linker_files);
156 }
157 
158 SYSINIT(linker, SI_SUB_KLD, SI_ORDER_FIRST, linker_init, 0)
159 
160 static void
161 linker_stop_class_add(void *arg)
162 {
163 
164 	linker_no_more_classes = 1;
165 }
166 
167 SYSINIT(linker_class, SI_SUB_KLD, SI_ORDER_ANY, linker_stop_class_add, NULL)
168 
169 int
170 linker_add_class(linker_class_t lc)
171 {
172 
173 	/*
174 	 * We disallow any class registration past SI_ORDER_ANY
175 	 * of SI_SUB_KLD.  We bump the reference count to keep the
176 	 * ops from being freed.
177 	 */
178 	if (linker_no_more_classes == 1)
179 		return (EPERM);
180 	kobj_class_compile((kobj_class_t) lc);
181 	((kobj_class_t)lc)->refs++;	/* XXX: kobj_mtx */
182 	TAILQ_INSERT_TAIL(&classes, lc, link);
183 	return (0);
184 }
185 
186 static void
187 linker_file_sysinit(linker_file_t lf)
188 {
189 	struct sysinit **start, **stop, **sipp, **xipp, *save;
190 
191 	KLD_DPF(FILE, ("linker_file_sysinit: calling SYSINITs for %s\n",
192 	    lf->filename));
193 
194 	if (linker_file_lookup_set(lf, "sysinit_set", &start, &stop, NULL) != 0)
195 		return;
196 	/*
197 	 * Perform a bubble sort of the system initialization objects by
198 	 * their subsystem (primary key) and order (secondary key).
199 	 *
200 	 * Since some things care about execution order, this is the operation
201 	 * which ensures continued function.
202 	 */
203 	for (sipp = start; sipp < stop; sipp++) {
204 		for (xipp = sipp + 1; xipp < stop; xipp++) {
205 			if ((*sipp)->subsystem < (*xipp)->subsystem ||
206 			    ((*sipp)->subsystem == (*xipp)->subsystem &&
207 			    (*sipp)->order <= (*xipp)->order))
208 				continue;	/* skip */
209 			save = *sipp;
210 			*sipp = *xipp;
211 			*xipp = save;
212 		}
213 	}
214 
215 	/*
216 	 * Traverse the (now) ordered list of system initialization tasks.
217 	 * Perform each task, and continue on to the next task.
218 	 */
219 	mtx_lock(&Giant);
220 	for (sipp = start; sipp < stop; sipp++) {
221 		if ((*sipp)->subsystem == SI_SUB_DUMMY)
222 			continue;	/* skip dummy task(s) */
223 
224 		/* Call function */
225 		(*((*sipp)->func)) ((*sipp)->udata);
226 	}
227 	mtx_unlock(&Giant);
228 }
229 
230 static void
231 linker_file_sysuninit(linker_file_t lf)
232 {
233 	struct sysinit **start, **stop, **sipp, **xipp, *save;
234 
235 	KLD_DPF(FILE, ("linker_file_sysuninit: calling SYSUNINITs for %s\n",
236 	    lf->filename));
237 
238 	if (linker_file_lookup_set(lf, "sysuninit_set", &start, &stop,
239 	    NULL) != 0)
240 		return;
241 
242 	/*
243 	 * Perform a reverse bubble sort of the system initialization objects
244 	 * by their subsystem (primary key) and order (secondary key).
245 	 *
246 	 * Since some things care about execution order, this is the operation
247 	 * which ensures continued function.
248 	 */
249 	for (sipp = start; sipp < stop; sipp++) {
250 		for (xipp = sipp + 1; xipp < stop; xipp++) {
251 			if ((*sipp)->subsystem > (*xipp)->subsystem ||
252 			    ((*sipp)->subsystem == (*xipp)->subsystem &&
253 			    (*sipp)->order >= (*xipp)->order))
254 				continue;	/* skip */
255 			save = *sipp;
256 			*sipp = *xipp;
257 			*xipp = save;
258 		}
259 	}
260 
261 	/*
262 	 * Traverse the (now) ordered list of system initialization tasks.
263 	 * Perform each task, and continue on to the next task.
264 	 */
265 	mtx_lock(&Giant);
266 	for (sipp = start; sipp < stop; sipp++) {
267 		if ((*sipp)->subsystem == SI_SUB_DUMMY)
268 			continue;	/* skip dummy task(s) */
269 
270 		/* Call function */
271 		(*((*sipp)->func)) ((*sipp)->udata);
272 	}
273 	mtx_unlock(&Giant);
274 }
275 
276 static void
277 linker_file_register_sysctls(linker_file_t lf)
278 {
279 	struct sysctl_oid **start, **stop, **oidp;
280 
281 	KLD_DPF(FILE,
282 	    ("linker_file_register_sysctls: registering SYSCTLs for %s\n",
283 	    lf->filename));
284 
285 	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
286 		return;
287 
288 	mtx_lock(&Giant);
289 	for (oidp = start; oidp < stop; oidp++)
290 		sysctl_register_oid(*oidp);
291 	mtx_unlock(&Giant);
292 }
293 
294 static void
295 linker_file_unregister_sysctls(linker_file_t lf)
296 {
297 	struct sysctl_oid **start, **stop, **oidp;
298 
299 	KLD_DPF(FILE, ("linker_file_unregister_sysctls: registering SYSCTLs"
300 	    " for %s\n", lf->filename));
301 
302 	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
303 		return;
304 
305 	mtx_lock(&Giant);
306 	for (oidp = start; oidp < stop; oidp++)
307 		sysctl_unregister_oid(*oidp);
308 	mtx_unlock(&Giant);
309 }
310 
311 static int
312 linker_file_register_modules(linker_file_t lf)
313 {
314 	struct mod_metadata **start, **stop, **mdp;
315 	const moduledata_t *moddata;
316 	int first_error, error;
317 
318 	KLD_DPF(FILE, ("linker_file_register_modules: registering modules"
319 	    " in %s\n", lf->filename));
320 
321 	if (linker_file_lookup_set(lf, "modmetadata_set", &start,
322 	    &stop, NULL) != 0) {
323 		/*
324 		 * This fallback should be unnecessary, but if we get booted
325 		 * from boot2 instead of loader and we are missing our
326 		 * metadata then we have to try the best we can.
327 		 */
328 		if (lf == linker_kernel_file) {
329 			start = SET_BEGIN(modmetadata_set);
330 			stop = SET_LIMIT(modmetadata_set);
331 		} else
332 			return (0);
333 	}
334 	first_error = 0;
335 	for (mdp = start; mdp < stop; mdp++) {
336 		if ((*mdp)->md_type != MDT_MODULE)
337 			continue;
338 		moddata = (*mdp)->md_data;
339 		KLD_DPF(FILE, ("Registering module %s in %s\n",
340 		    moddata->name, lf->filename));
341 		error = module_register(moddata, lf);
342 		if (error) {
343 			printf("Module %s failed to register: %d\n",
344 			    moddata->name, error);
345 			if (first_error == 0)
346 				first_error = error;
347 		}
348 	}
349 	return (first_error);
350 }
351 
352 static void
353 linker_init_kernel_modules(void)
354 {
355 
356 	linker_file_register_modules(linker_kernel_file);
357 }
358 
359 SYSINIT(linker_kernel, SI_SUB_KLD, SI_ORDER_ANY, linker_init_kernel_modules, 0)
360 
361 static int
362 linker_load_file(const char *filename, linker_file_t *result)
363 {
364 	linker_class_t lc;
365 	linker_file_t lf;
366 	int foundfile, error;
367 
368 	/* Refuse to load modules if securelevel raised */
369 	if (securelevel > 0)
370 		return (EPERM);
371 
372 	KLD_LOCK_ASSERT();
373 	lf = linker_find_file_by_name(filename);
374 	if (lf) {
375 		KLD_DPF(FILE, ("linker_load_file: file %s is already loaded,"
376 		    " incrementing refs\n", filename));
377 		*result = lf;
378 		lf->refs++;
379 		return (0);
380 	}
381 	foundfile = 0;
382 	error = 0;
383 
384 	/*
385 	 * We do not need to protect (lock) classes here because there is
386 	 * no class registration past startup (SI_SUB_KLD, SI_ORDER_ANY)
387 	 * and there is no class deregistration mechanism at this time.
388 	 */
389 	TAILQ_FOREACH(lc, &classes, link) {
390 		KLD_DPF(FILE, ("linker_load_file: trying to load %s\n",
391 		    filename));
392 		error = LINKER_LOAD_FILE(lc, filename, &lf);
393 		/*
394 		 * If we got something other than ENOENT, then it exists but
395 		 * we cannot load it for some other reason.
396 		 */
397 		if (error != ENOENT)
398 			foundfile = 1;
399 		if (lf) {
400 			error = linker_file_register_modules(lf);
401 			if (error == EEXIST) {
402 				linker_file_unload(lf, LINKER_UNLOAD_FORCE);
403 				return (error);
404 			}
405 			linker_file_register_sysctls(lf);
406 			linker_file_sysinit(lf);
407 			lf->flags |= LINKER_FILE_LINKED;
408 			*result = lf;
409 			return (0);
410 		}
411 	}
412 	/*
413 	 * Less than ideal, but tells the user whether it failed to load or
414 	 * the module was not found.
415 	 */
416 	if (foundfile) {
417 		/*
418 		 * Format not recognized or otherwise unloadable.
419 		 * When loading a module that is statically built into
420 		 * the kernel EEXIST percolates back up as the return
421 		 * value.  Preserve this so that apps like sysinstall
422 		 * can recognize this special case and not post bogus
423 		 * dialog boxes.
424 		 */
425 		if (error != EEXIST)
426 			error = ENOEXEC;
427 	} else
428 		error = ENOENT;		/* Nothing found */
429 	return (error);
430 }
431 
432 int
433 linker_reference_module(const char *modname, struct mod_depend *verinfo,
434     linker_file_t *result)
435 {
436 	modlist_t mod;
437 	int error;
438 
439 	KLD_LOCK();
440 	if ((mod = modlist_lookup2(modname, verinfo)) != NULL) {
441 		*result = mod->container;
442 		(*result)->refs++;
443 		KLD_UNLOCK();
444 		return (0);
445 	}
446 
447 	error = linker_load_module(NULL, modname, NULL, verinfo, result);
448 	KLD_UNLOCK();
449 	return (error);
450 }
451 
452 int
453 linker_release_module(const char *modname, struct mod_depend *verinfo,
454     linker_file_t lf)
455 {
456 	modlist_t mod;
457 	int error;
458 
459 	KLD_LOCK();
460 	if (lf == NULL) {
461 		KASSERT(modname != NULL,
462 		    ("linker_release_module: no file or name"));
463 		mod = modlist_lookup2(modname, verinfo);
464 		if (mod == NULL) {
465 			KLD_UNLOCK();
466 			return (ESRCH);
467 		}
468 		lf = mod->container;
469 	} else
470 		KASSERT(modname == NULL && verinfo == NULL,
471 		    ("linker_release_module: both file and name"));
472 	error =	linker_file_unload(lf, LINKER_UNLOAD_NORMAL);
473 	KLD_UNLOCK();
474 	return (error);
475 }
476 
477 static linker_file_t
478 linker_find_file_by_name(const char *filename)
479 {
480 	linker_file_t lf;
481 	char *koname;
482 
483 	koname = malloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
484 	sprintf(koname, "%s.ko", filename);
485 
486 	KLD_LOCK_ASSERT();
487 	TAILQ_FOREACH(lf, &linker_files, link) {
488 		if (strcmp(lf->filename, koname) == 0)
489 			break;
490 		if (strcmp(lf->filename, filename) == 0)
491 			break;
492 	}
493 	free(koname, M_LINKER);
494 	return (lf);
495 }
496 
497 static linker_file_t
498 linker_find_file_by_id(int fileid)
499 {
500 	linker_file_t lf;
501 
502 	KLD_LOCK_ASSERT();
503 	TAILQ_FOREACH(lf, &linker_files, link)
504 		if (lf->id == fileid)
505 			break;
506 	return (lf);
507 }
508 
509 int
510 linker_file_foreach(linker_predicate_t *predicate, void *context)
511 {
512 	linker_file_t lf;
513 	int retval = 0;
514 
515 	KLD_LOCK();
516 	TAILQ_FOREACH(lf, &linker_files, link) {
517 		retval = predicate(lf, context);
518 		if (retval != 0)
519 			break;
520 	}
521 	KLD_UNLOCK();
522 	return (retval);
523 }
524 
525 linker_file_t
526 linker_make_file(const char *pathname, linker_class_t lc)
527 {
528 	linker_file_t lf;
529 	const char *filename;
530 
531 	KLD_LOCK_ASSERT();
532 	filename = linker_basename(pathname);
533 
534 	KLD_DPF(FILE, ("linker_make_file: new file, filename=%s\n", filename));
535 	lf = (linker_file_t)kobj_create((kobj_class_t)lc, M_LINKER, M_WAITOK);
536 	if (lf == NULL)
537 		return (NULL);
538 	lf->refs = 1;
539 	lf->userrefs = 0;
540 	lf->flags = 0;
541 	lf->filename = linker_strdup(filename);
542 	LINKER_GET_NEXT_FILE_ID(lf->id);
543 	lf->ndeps = 0;
544 	lf->deps = NULL;
545 	STAILQ_INIT(&lf->common);
546 	TAILQ_INIT(&lf->modules);
547 	TAILQ_INSERT_TAIL(&linker_files, lf, link);
548 	return (lf);
549 }
550 
551 int
552 linker_file_unload(linker_file_t file, int flags)
553 {
554 	module_t mod, next;
555 	modlist_t ml, nextml;
556 	struct common_symbol *cp;
557 	int error, i;
558 
559 	/* Refuse to unload modules if securelevel raised. */
560 	if (securelevel > 0)
561 		return (EPERM);
562 #ifdef MAC
563 	error = mac_check_kld_unload(curthread->td_ucred);
564 	if (error)
565 		return (error);
566 #endif
567 
568 	KLD_LOCK_ASSERT();
569 	KLD_DPF(FILE, ("linker_file_unload: lf->refs=%d\n", file->refs));
570 
571 	/* Easy case of just dropping a reference. */
572 	if (file->refs > 1) {
573 		file->refs--;
574 		return (0);
575 	}
576 
577 	KLD_DPF(FILE, ("linker_file_unload: file is unloading,"
578 	    " informing modules\n"));
579 
580 	/*
581 	 * Inform any modules associated with this file.
582 	 */
583 	MOD_XLOCK;
584 	for (mod = TAILQ_FIRST(&file->modules); mod; mod = next) {
585 		next = module_getfnext(mod);
586 		MOD_XUNLOCK;
587 
588 		/*
589 		 * Give the module a chance to veto the unload.
590 		 */
591 		if ((error = module_unload(mod, flags)) != 0) {
592 			KLD_DPF(FILE, ("linker_file_unload: module %p"
593 			    " vetoes unload\n", mod));
594 			return (error);
595 		}
596 		MOD_XLOCK;
597 		module_release(mod);
598 	}
599 	MOD_XUNLOCK;
600 
601 	TAILQ_FOREACH_SAFE(ml, &found_modules, link, nextml) {
602 		if (ml->container == file) {
603 			TAILQ_REMOVE(&found_modules, ml, link);
604 			free(ml, M_LINKER);
605 		}
606 	}
607 
608 	/*
609 	 * Don't try to run SYSUNINITs if we are unloaded due to a
610 	 * link error.
611 	 */
612 	if (file->flags & LINKER_FILE_LINKED) {
613 		linker_file_sysuninit(file);
614 		linker_file_unregister_sysctls(file);
615 	}
616 	TAILQ_REMOVE(&linker_files, file, link);
617 
618 	if (file->deps) {
619 		for (i = 0; i < file->ndeps; i++)
620 			linker_file_unload(file->deps[i], flags);
621 		free(file->deps, M_LINKER);
622 		file->deps = NULL;
623 	}
624 	while ((cp = STAILQ_FIRST(&file->common)) != NULL) {
625 		STAILQ_REMOVE_HEAD(&file->common, link);
626 		free(cp, M_LINKER);
627 	}
628 
629 	LINKER_UNLOAD(file);
630 	if (file->filename) {
631 		free(file->filename, M_LINKER);
632 		file->filename = NULL;
633 	}
634 	kobj_delete((kobj_t) file, M_LINKER);
635 	return (0);
636 }
637 
638 static int
639 linker_file_add_dependency(linker_file_t file, linker_file_t dep)
640 {
641 	linker_file_t *newdeps;
642 
643 	KLD_LOCK_ASSERT();
644 	newdeps = malloc((file->ndeps + 1) * sizeof(linker_file_t *),
645 	    M_LINKER, M_WAITOK | M_ZERO);
646 	if (newdeps == NULL)
647 		return (ENOMEM);
648 
649 	if (file->deps) {
650 		bcopy(file->deps, newdeps,
651 		    file->ndeps * sizeof(linker_file_t *));
652 		free(file->deps, M_LINKER);
653 	}
654 	file->deps = newdeps;
655 	file->deps[file->ndeps] = dep;
656 	file->ndeps++;
657 	return (0);
658 }
659 
660 /*
661  * Locate a linker set and its contents.  This is a helper function to avoid
662  * linker_if.h exposure elsewhere.  Note: firstp and lastp are really void **.
663  * This function is used in this file so we can avoid having lots of (void **)
664  * casts.
665  */
666 int
667 linker_file_lookup_set(linker_file_t file, const char *name,
668     void *firstp, void *lastp, int *countp)
669 {
670 	int error, locked;
671 
672 	locked = KLD_LOCKED();
673 	if (!locked)
674 		KLD_LOCK();
675 	error = LINKER_LOOKUP_SET(file, name, firstp, lastp, countp);
676 	if (!locked)
677 		KLD_UNLOCK();
678 	return (error);
679 }
680 
681 caddr_t
682 linker_file_lookup_symbol(linker_file_t file, const char *name, int deps)
683 {
684 	caddr_t sym;
685 	int locked;
686 
687 	locked = KLD_LOCKED();
688 	if (!locked)
689 		KLD_LOCK();
690 	sym = linker_file_lookup_symbol_internal(file, name, deps);
691 	if (!locked)
692 		KLD_UNLOCK();
693 	return (sym);
694 }
695 
696 static caddr_t
697 linker_file_lookup_symbol_internal(linker_file_t file, const char *name,
698     int deps)
699 {
700 	c_linker_sym_t sym;
701 	linker_symval_t symval;
702 	caddr_t address;
703 	size_t common_size = 0;
704 	int i;
705 
706 	KLD_LOCK_ASSERT();
707 	KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%p, name=%s, deps=%d\n",
708 	    file, name, deps));
709 
710 	if (LINKER_LOOKUP_SYMBOL(file, name, &sym) == 0) {
711 		LINKER_SYMBOL_VALUES(file, sym, &symval);
712 		if (symval.value == 0)
713 			/*
714 			 * For commons, first look them up in the
715 			 * dependencies and only allocate space if not found
716 			 * there.
717 			 */
718 			common_size = symval.size;
719 		else {
720 			KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol"
721 			    ".value=%p\n", symval.value));
722 			return (symval.value);
723 		}
724 	}
725 	if (deps) {
726 		for (i = 0; i < file->ndeps; i++) {
727 			address = linker_file_lookup_symbol_internal(
728 			    file->deps[i], name, 0);
729 			if (address) {
730 				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
731 				    " deps value=%p\n", address));
732 				return (address);
733 			}
734 		}
735 	}
736 	if (common_size > 0) {
737 		/*
738 		 * This is a common symbol which was not found in the
739 		 * dependencies.  We maintain a simple common symbol table in
740 		 * the file object.
741 		 */
742 		struct common_symbol *cp;
743 
744 		STAILQ_FOREACH(cp, &file->common, link) {
745 			if (strcmp(cp->name, name) == 0) {
746 				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
747 				    " old common value=%p\n", cp->address));
748 				return (cp->address);
749 			}
750 		}
751 		/*
752 		 * Round the symbol size up to align.
753 		 */
754 		common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
755 		cp = malloc(sizeof(struct common_symbol)
756 		    + common_size + strlen(name) + 1, M_LINKER,
757 		    M_WAITOK | M_ZERO);
758 		cp->address = (caddr_t)(cp + 1);
759 		cp->name = cp->address + common_size;
760 		strcpy(cp->name, name);
761 		bzero(cp->address, common_size);
762 		STAILQ_INSERT_TAIL(&file->common, cp, link);
763 
764 		KLD_DPF(SYM, ("linker_file_lookup_symbol: new common"
765 		    " value=%p\n", cp->address));
766 		return (cp->address);
767 	}
768 	KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
769 	return (0);
770 }
771 
772 #ifdef DDB
773 /*
774  * DDB Helpers.  DDB has to look across multiple files with their own symbol
775  * tables and string tables.
776  *
777  * Note that we do not obey list locking protocols here.  We really don't need
778  * DDB to hang because somebody's got the lock held.  We'll take the chance
779  * that the files list is inconsistant instead.
780  */
781 
782 int
783 linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
784 {
785 	linker_file_t lf;
786 
787 	TAILQ_FOREACH(lf, &linker_files, link) {
788 		if (LINKER_LOOKUP_SYMBOL(lf, symstr, sym) == 0)
789 			return (0);
790 	}
791 	return (ENOENT);
792 }
793 
794 int
795 linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
796 {
797 	linker_file_t lf;
798 	c_linker_sym_t best, es;
799 	u_long diff, bestdiff, off;
800 
801 	best = 0;
802 	off = (uintptr_t)value;
803 	bestdiff = off;
804 	TAILQ_FOREACH(lf, &linker_files, link) {
805 		if (LINKER_SEARCH_SYMBOL(lf, value, &es, &diff) != 0)
806 			continue;
807 		if (es != 0 && diff < bestdiff) {
808 			best = es;
809 			bestdiff = diff;
810 		}
811 		if (bestdiff == 0)
812 			break;
813 	}
814 	if (best) {
815 		*sym = best;
816 		*diffp = bestdiff;
817 		return (0);
818 	} else {
819 		*sym = 0;
820 		*diffp = off;
821 		return (ENOENT);
822 	}
823 }
824 
825 int
826 linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
827 {
828 	linker_file_t lf;
829 
830 	TAILQ_FOREACH(lf, &linker_files, link) {
831 		if (LINKER_SYMBOL_VALUES(lf, sym, symval) == 0)
832 			return (0);
833 	}
834 	return (ENOENT);
835 }
836 #endif
837 
838 /*
839  * Syscalls.
840  */
841 /*
842  * MPSAFE
843  */
844 int
845 kern_kldload(struct thread *td, const char *file, int *fileid)
846 {
847 #ifdef HWPMC_HOOKS
848 	struct pmckern_map_in pkm;
849 #endif
850 	const char *kldname, *modname;
851 	linker_file_t lf;
852 	int error;
853 
854 	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
855 		return (error);
856 
857 	if ((error = suser(td)) != 0)
858 		return (error);
859 
860 	/*
861 	 * If file does not contain a qualified name or any dot in it
862 	 * (kldname.ko, or kldname.ver.ko) treat it as an interface
863 	 * name.
864 	 */
865 	if (index(file, '/') || index(file, '.')) {
866 		kldname = file;
867 		modname = NULL;
868 	} else {
869 		kldname = NULL;
870 		modname = file;
871 	}
872 
873 	KLD_LOCK();
874 	error = linker_load_module(kldname, modname, NULL, NULL, &lf);
875 	if (error)
876 		goto unlock;
877 #ifdef HWPMC_HOOKS
878 	pkm.pm_file = lf->filename;
879 	pkm.pm_address = (uintptr_t) lf->address;
880 	PMC_CALL_HOOK(td, PMC_FN_KLD_LOAD, (void *) &pkm);
881 #endif
882 	lf->userrefs++;
883 	if (fileid != NULL)
884 		*fileid = lf->id;
885 unlock:
886 	KLD_UNLOCK();
887 	return (error);
888 }
889 
890 int
891 kldload(struct thread *td, struct kldload_args *uap)
892 {
893 	char *pathname = NULL;
894 	int error, fileid;
895 
896 	td->td_retval[0] = -1;
897 
898 	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
899 	error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL);
900 	if (error == 0) {
901 		error = kern_kldload(td, pathname, &fileid);
902 		if (error == 0)
903 			td->td_retval[0] = fileid;
904 	}
905 	free(pathname, M_TEMP);
906 	return (error);
907 }
908 
909 /*
910  * MPSAFE
911  */
912 int
913 kern_kldunload(struct thread *td, int fileid, int flags)
914 {
915 #ifdef HWPMC_HOOKS
916 	struct pmckern_map_out pkm;
917 #endif
918 	linker_file_t lf;
919 	int error = 0;
920 
921 	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
922 		return (error);
923 
924 	if ((error = suser(td)) != 0)
925 		return (error);
926 
927 	KLD_LOCK();
928 	lf = linker_find_file_by_id(fileid);
929 	if (lf) {
930 		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
931 		if (lf->userrefs == 0) {
932 			/*
933 			 * XXX: maybe LINKER_UNLOAD_FORCE should override ?
934 			 */
935 			printf("kldunload: attempt to unload file that was"
936 			    " loaded by the kernel\n");
937 			error = EBUSY;
938 		} else {
939 #ifdef HWPMC_HOOKS
940 			/* Save data needed by hwpmc(4) before unloading. */
941 			pkm.pm_address = (uintptr_t) lf->address;
942 			pkm.pm_size = lf->size;
943 #endif
944 			lf->userrefs--;
945 			error = linker_file_unload(lf, flags);
946 			if (error)
947 				lf->userrefs++;
948 		}
949 	} else
950 		error = ENOENT;
951 
952 #ifdef HWPMC_HOOKS
953 	if (error == 0)
954 		PMC_CALL_HOOK(td, PMC_FN_KLD_UNLOAD, (void *) &pkm);
955 #endif
956 	KLD_UNLOCK();
957 	return (error);
958 }
959 
960 /*
961  * MPSAFE
962  */
963 int
964 kldunload(struct thread *td, struct kldunload_args *uap)
965 {
966 
967 	return (kern_kldunload(td, uap->fileid, LINKER_UNLOAD_NORMAL));
968 }
969 
970 /*
971  * MPSAFE
972  */
973 int
974 kldunloadf(struct thread *td, struct kldunloadf_args *uap)
975 {
976 
977 	if (uap->flags != LINKER_UNLOAD_NORMAL &&
978 	    uap->flags != LINKER_UNLOAD_FORCE)
979 		return (EINVAL);
980 	return (kern_kldunload(td, uap->fileid, uap->flags));
981 }
982 
983 /*
984  * MPSAFE
985  */
986 int
987 kldfind(struct thread *td, struct kldfind_args *uap)
988 {
989 	char *pathname;
990 	const char *filename;
991 	linker_file_t lf;
992 	int error;
993 
994 #ifdef MAC
995 	error = mac_check_kld_stat(td->td_ucred);
996 	if (error)
997 		return (error);
998 #endif
999 
1000 	td->td_retval[0] = -1;
1001 
1002 	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1003 	if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
1004 		goto out;
1005 
1006 	filename = linker_basename(pathname);
1007 	KLD_LOCK();
1008 	lf = linker_find_file_by_name(filename);
1009 	if (lf)
1010 		td->td_retval[0] = lf->id;
1011 	else
1012 		error = ENOENT;
1013 	KLD_UNLOCK();
1014 out:
1015 	free(pathname, M_TEMP);
1016 	return (error);
1017 }
1018 
1019 /*
1020  * MPSAFE
1021  */
1022 int
1023 kldnext(struct thread *td, struct kldnext_args *uap)
1024 {
1025 	linker_file_t lf;
1026 	int error = 0;
1027 
1028 #ifdef MAC
1029 	error = mac_check_kld_stat(td->td_ucred);
1030 	if (error)
1031 		return (error);
1032 #endif
1033 
1034 	KLD_LOCK();
1035 	if (uap->fileid == 0) {
1036 		if (TAILQ_FIRST(&linker_files))
1037 			td->td_retval[0] = TAILQ_FIRST(&linker_files)->id;
1038 		else
1039 			td->td_retval[0] = 0;
1040 		goto out;
1041 	}
1042 	lf = linker_find_file_by_id(uap->fileid);
1043 	if (lf) {
1044 		if (TAILQ_NEXT(lf, link))
1045 			td->td_retval[0] = TAILQ_NEXT(lf, link)->id;
1046 		else
1047 			td->td_retval[0] = 0;
1048 	} else
1049 		error = ENOENT;
1050 out:
1051 	KLD_UNLOCK();
1052 	return (error);
1053 }
1054 
1055 /*
1056  * MPSAFE
1057  */
1058 int
1059 kldstat(struct thread *td, struct kldstat_args *uap)
1060 {
1061 	struct kld_file_stat stat;
1062 	linker_file_t lf;
1063 	int error, namelen;
1064 
1065 	/*
1066 	 * Check the version of the user's structure.
1067 	 */
1068 	error = copyin(uap->stat, &stat, sizeof(struct kld_file_stat));
1069 	if (error)
1070 		return (error);
1071 	if (stat.version != sizeof(struct kld_file_stat))
1072 		return (EINVAL);
1073 
1074 #ifdef MAC
1075 	error = mac_check_kld_stat(td->td_ucred);
1076 	if (error)
1077 		return (error);
1078 #endif
1079 
1080 	KLD_LOCK();
1081 	lf = linker_find_file_by_id(uap->fileid);
1082 	if (lf == NULL) {
1083 		KLD_UNLOCK();
1084 		return (ENOENT);
1085 	}
1086 
1087 	namelen = strlen(lf->filename) + 1;
1088 	if (namelen > MAXPATHLEN)
1089 		namelen = MAXPATHLEN;
1090 	bcopy(lf->filename, &stat.name[0], namelen);
1091 	stat.refs = lf->refs;
1092 	stat.id = lf->id;
1093 	stat.address = lf->address;
1094 	stat.size = lf->size;
1095 	KLD_UNLOCK();
1096 
1097 	td->td_retval[0] = 0;
1098 
1099 	return (copyout(&stat, uap->stat, sizeof(struct kld_file_stat)));
1100 }
1101 
1102 /*
1103  * MPSAFE
1104  */
1105 int
1106 kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
1107 {
1108 	linker_file_t lf;
1109 	module_t mp;
1110 	int error = 0;
1111 
1112 #ifdef MAC
1113 	error = mac_check_kld_stat(td->td_ucred);
1114 	if (error)
1115 		return (error);
1116 #endif
1117 
1118 	KLD_LOCK();
1119 	lf = linker_find_file_by_id(uap->fileid);
1120 	if (lf) {
1121 		MOD_SLOCK;
1122 		mp = TAILQ_FIRST(&lf->modules);
1123 		if (mp != NULL)
1124 			td->td_retval[0] = module_getid(mp);
1125 		else
1126 			td->td_retval[0] = 0;
1127 		MOD_SUNLOCK;
1128 	} else
1129 		error = ENOENT;
1130 	KLD_UNLOCK();
1131 	return (error);
1132 }
1133 
1134 /*
1135  * MPSAFE
1136  */
1137 int
1138 kldsym(struct thread *td, struct kldsym_args *uap)
1139 {
1140 	char *symstr = NULL;
1141 	c_linker_sym_t sym;
1142 	linker_symval_t symval;
1143 	linker_file_t lf;
1144 	struct kld_sym_lookup lookup;
1145 	int error = 0;
1146 
1147 #ifdef MAC
1148 	error = mac_check_kld_stat(td->td_ucred);
1149 	if (error)
1150 		return (error);
1151 #endif
1152 
1153 	if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
1154 		return (error);
1155 	if (lookup.version != sizeof(lookup) ||
1156 	    uap->cmd != KLDSYM_LOOKUP)
1157 		return (EINVAL);
1158 	symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1159 	if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
1160 		goto out;
1161 	KLD_LOCK();
1162 	if (uap->fileid != 0) {
1163 		lf = linker_find_file_by_id(uap->fileid);
1164 		if (lf == NULL)
1165 			error = ENOENT;
1166 		else if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1167 		    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1168 			lookup.symvalue = (uintptr_t) symval.value;
1169 			lookup.symsize = symval.size;
1170 			error = copyout(&lookup, uap->data, sizeof(lookup));
1171 		} else
1172 			error = ENOENT;
1173 	} else {
1174 		TAILQ_FOREACH(lf, &linker_files, link) {
1175 			if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1176 			    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1177 				lookup.symvalue = (uintptr_t)symval.value;
1178 				lookup.symsize = symval.size;
1179 				error = copyout(&lookup, uap->data,
1180 				    sizeof(lookup));
1181 				break;
1182 			}
1183 		}
1184 		if (lf == NULL)
1185 			error = ENOENT;
1186 	}
1187 	KLD_UNLOCK();
1188 out:
1189 	free(symstr, M_TEMP);
1190 	return (error);
1191 }
1192 
1193 /*
1194  * Preloaded module support
1195  */
1196 
1197 static modlist_t
1198 modlist_lookup(const char *name, int ver)
1199 {
1200 	modlist_t mod;
1201 
1202 	TAILQ_FOREACH(mod, &found_modules, link) {
1203 		if (strcmp(mod->name, name) == 0 &&
1204 		    (ver == 0 || mod->version == ver))
1205 			return (mod);
1206 	}
1207 	return (NULL);
1208 }
1209 
1210 static modlist_t
1211 modlist_lookup2(const char *name, struct mod_depend *verinfo)
1212 {
1213 	modlist_t mod, bestmod;
1214 	int ver;
1215 
1216 	if (verinfo == NULL)
1217 		return (modlist_lookup(name, 0));
1218 	bestmod = NULL;
1219 	TAILQ_FOREACH(mod, &found_modules, link) {
1220 		if (strcmp(mod->name, name) != 0)
1221 			continue;
1222 		ver = mod->version;
1223 		if (ver == verinfo->md_ver_preferred)
1224 			return (mod);
1225 		if (ver >= verinfo->md_ver_minimum &&
1226 		    ver <= verinfo->md_ver_maximum &&
1227 		    (bestmod == NULL || ver > bestmod->version))
1228 			bestmod = mod;
1229 	}
1230 	return (bestmod);
1231 }
1232 
1233 static modlist_t
1234 modlist_newmodule(const char *modname, int version, linker_file_t container)
1235 {
1236 	modlist_t mod;
1237 
1238 	mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1239 	if (mod == NULL)
1240 		panic("no memory for module list");
1241 	mod->container = container;
1242 	mod->name = modname;
1243 	mod->version = version;
1244 	TAILQ_INSERT_TAIL(&found_modules, mod, link);
1245 	return (mod);
1246 }
1247 
1248 static void
1249 linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1250     struct mod_metadata **stop, int preload)
1251 {
1252 	struct mod_metadata *mp, **mdp;
1253 	const char *modname;
1254 	int ver;
1255 
1256 	for (mdp = start; mdp < stop; mdp++) {
1257 		mp = *mdp;
1258 		if (mp->md_type != MDT_VERSION)
1259 			continue;
1260 		modname = mp->md_cval;
1261 		ver = ((struct mod_version *)mp->md_data)->mv_version;
1262 		if (modlist_lookup(modname, ver) != NULL) {
1263 			printf("module %s already present!\n", modname);
1264 			/* XXX what can we do? this is a build error. :-( */
1265 			continue;
1266 		}
1267 		modlist_newmodule(modname, ver, lf);
1268 	}
1269 }
1270 
1271 static void
1272 linker_preload(void *arg)
1273 {
1274 	caddr_t modptr;
1275 	const char *modname, *nmodname;
1276 	char *modtype;
1277 	linker_file_t lf, nlf;
1278 	linker_class_t lc;
1279 	int error;
1280 	linker_file_list_t loaded_files;
1281 	linker_file_list_t depended_files;
1282 	struct mod_metadata *mp, *nmp;
1283 	struct mod_metadata **start, **stop, **mdp, **nmdp;
1284 	struct mod_depend *verinfo;
1285 	int nver;
1286 	int resolves;
1287 	modlist_t mod;
1288 	struct sysinit **si_start, **si_stop;
1289 
1290 	TAILQ_INIT(&loaded_files);
1291 	TAILQ_INIT(&depended_files);
1292 	TAILQ_INIT(&found_modules);
1293 	error = 0;
1294 
1295 	modptr = NULL;
1296 	while ((modptr = preload_search_next_name(modptr)) != NULL) {
1297 		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1298 		modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1299 		if (modname == NULL) {
1300 			printf("Preloaded module at %p does not have a"
1301 			    " name!\n", modptr);
1302 			continue;
1303 		}
1304 		if (modtype == NULL) {
1305 			printf("Preloaded module at %p does not have a type!\n",
1306 			    modptr);
1307 			continue;
1308 		}
1309 		if (bootverbose)
1310 			printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1311 			    modptr);
1312 		lf = NULL;
1313 		TAILQ_FOREACH(lc, &classes, link) {
1314 			error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1315 			if (!error)
1316 				break;
1317 			lf = NULL;
1318 		}
1319 		if (lf)
1320 			TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1321 	}
1322 
1323 	/*
1324 	 * First get a list of stuff in the kernel.
1325 	 */
1326 	if (linker_file_lookup_set(linker_kernel_file, MDT_SETNAME, &start,
1327 	    &stop, NULL) == 0)
1328 		linker_addmodules(linker_kernel_file, start, stop, 1);
1329 
1330 	/*
1331 	 * this is a once-off kinky bubble sort resolve relocation dependency
1332 	 * requirements
1333 	 */
1334 restart:
1335 	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1336 		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1337 		    &stop, NULL);
1338 		/*
1339 		 * First, look to see if we would successfully link with this
1340 		 * stuff.
1341 		 */
1342 		resolves = 1;	/* unless we know otherwise */
1343 		if (!error) {
1344 			for (mdp = start; mdp < stop; mdp++) {
1345 				mp = *mdp;
1346 				if (mp->md_type != MDT_DEPEND)
1347 					continue;
1348 				modname = mp->md_cval;
1349 				verinfo = mp->md_data;
1350 				for (nmdp = start; nmdp < stop; nmdp++) {
1351 					nmp = *nmdp;
1352 					if (nmp->md_type != MDT_VERSION)
1353 						continue;
1354 					nmodname = nmp->md_cval;
1355 					if (strcmp(modname, nmodname) == 0)
1356 						break;
1357 				}
1358 				if (nmdp < stop)   /* it's a self reference */
1359 					continue;
1360 
1361 				/*
1362 				 * ok, the module isn't here yet, we
1363 				 * are not finished
1364 				 */
1365 				if (modlist_lookup2(modname, verinfo) == NULL)
1366 					resolves = 0;
1367 			}
1368 		}
1369 		/*
1370 		 * OK, if we found our modules, we can link.  So, "provide"
1371 		 * the modules inside and add it to the end of the link order
1372 		 * list.
1373 		 */
1374 		if (resolves) {
1375 			if (!error) {
1376 				for (mdp = start; mdp < stop; mdp++) {
1377 					mp = *mdp;
1378 					if (mp->md_type != MDT_VERSION)
1379 						continue;
1380 					modname = mp->md_cval;
1381 					nver = ((struct mod_version *)
1382 					    mp->md_data)->mv_version;
1383 					if (modlist_lookup(modname,
1384 					    nver) != NULL) {
1385 						printf("module %s already"
1386 						    " present!\n", modname);
1387 						TAILQ_REMOVE(&loaded_files,
1388 						    lf, loaded);
1389 						linker_file_unload(lf,
1390 						    LINKER_UNLOAD_FORCE);
1391 						/* we changed tailq next ptr */
1392 						goto restart;
1393 					}
1394 					modlist_newmodule(modname, nver, lf);
1395 				}
1396 			}
1397 			TAILQ_REMOVE(&loaded_files, lf, loaded);
1398 			TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1399 			/*
1400 			 * Since we provided modules, we need to restart the
1401 			 * sort so that the previous files that depend on us
1402 			 * have a chance. Also, we've busted the tailq next
1403 			 * pointer with the REMOVE.
1404 			 */
1405 			goto restart;
1406 		}
1407 	}
1408 
1409 	/*
1410 	 * At this point, we check to see what could not be resolved..
1411 	 */
1412 	while ((lf = TAILQ_FIRST(&loaded_files)) != NULL) {
1413 		TAILQ_REMOVE(&loaded_files, lf, loaded);
1414 		printf("KLD file %s is missing dependencies\n", lf->filename);
1415 		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1416 	}
1417 
1418 	/*
1419 	 * We made it. Finish off the linking in the order we determined.
1420 	 */
1421 	TAILQ_FOREACH_SAFE(lf, &depended_files, loaded, nlf) {
1422 		if (linker_kernel_file) {
1423 			linker_kernel_file->refs++;
1424 			error = linker_file_add_dependency(lf,
1425 			    linker_kernel_file);
1426 			if (error)
1427 				panic("cannot add dependency");
1428 		}
1429 		lf->userrefs++;	/* so we can (try to) kldunload it */
1430 		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1431 		    &stop, NULL);
1432 		if (!error) {
1433 			for (mdp = start; mdp < stop; mdp++) {
1434 				mp = *mdp;
1435 				if (mp->md_type != MDT_DEPEND)
1436 					continue;
1437 				modname = mp->md_cval;
1438 				verinfo = mp->md_data;
1439 				mod = modlist_lookup2(modname, verinfo);
1440 				/* Don't count self-dependencies */
1441 				if (lf == mod->container)
1442 					continue;
1443 				mod->container->refs++;
1444 				error = linker_file_add_dependency(lf,
1445 				    mod->container);
1446 				if (error)
1447 					panic("cannot add dependency");
1448 			}
1449 		}
1450 		/*
1451 		 * Now do relocation etc using the symbol search paths
1452 		 * established by the dependencies
1453 		 */
1454 		error = LINKER_LINK_PRELOAD_FINISH(lf);
1455 		if (error) {
1456 			TAILQ_REMOVE(&depended_files, lf, loaded);
1457 			printf("KLD file %s - could not finalize loading\n",
1458 			    lf->filename);
1459 			linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1460 			continue;
1461 		}
1462 		linker_file_register_modules(lf);
1463 		if (linker_file_lookup_set(lf, "sysinit_set", &si_start,
1464 		    &si_stop, NULL) == 0)
1465 			sysinit_add(si_start, si_stop);
1466 		linker_file_register_sysctls(lf);
1467 		lf->flags |= LINKER_FILE_LINKED;
1468 	}
1469 	/* woohoo! we made it! */
1470 }
1471 
1472 SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, 0)
1473 
1474 /*
1475  * Search for a not-loaded module by name.
1476  *
1477  * Modules may be found in the following locations:
1478  *
1479  * - preloaded (result is just the module name) - on disk (result is full path
1480  * to module)
1481  *
1482  * If the module name is qualified in any way (contains path, etc.) the we
1483  * simply return a copy of it.
1484  *
1485  * The search path can be manipulated via sysctl.  Note that we use the ';'
1486  * character as a separator to be consistent with the bootloader.
1487  */
1488 
1489 static char linker_hintfile[] = "linker.hints";
1490 static char linker_path[MAXPATHLEN] = "/boot/kernel;/boot/modules";
1491 
1492 SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RW, linker_path,
1493     sizeof(linker_path), "module load search path");
1494 
1495 TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1496 
1497 static char *linker_ext_list[] = {
1498 	"",
1499 	".ko",
1500 	NULL
1501 };
1502 
1503 /*
1504  * Check if file actually exists either with or without extension listed in
1505  * the linker_ext_list. (probably should be generic for the rest of the
1506  * kernel)
1507  */
1508 static char *
1509 linker_lookup_file(const char *path, int pathlen, const char *name,
1510     int namelen, struct vattr *vap)
1511 {
1512 	struct nameidata nd;
1513 	struct thread *td = curthread;	/* XXX */
1514 	char *result, **cpp, *sep;
1515 	int error, len, extlen, reclen, flags, vfslocked;
1516 	enum vtype type;
1517 
1518 	extlen = 0;
1519 	for (cpp = linker_ext_list; *cpp; cpp++) {
1520 		len = strlen(*cpp);
1521 		if (len > extlen)
1522 			extlen = len;
1523 	}
1524 	extlen++;		/* trailing '\0' */
1525 	sep = (path[pathlen - 1] != '/') ? "/" : "";
1526 
1527 	reclen = pathlen + strlen(sep) + namelen + extlen + 1;
1528 	result = malloc(reclen, M_LINKER, M_WAITOK);
1529 	for (cpp = linker_ext_list; *cpp; cpp++) {
1530 		snprintf(result, reclen, "%.*s%s%.*s%s", pathlen, path, sep,
1531 		    namelen, name, *cpp);
1532 		/*
1533 		 * Attempt to open the file, and return the path if
1534 		 * we succeed and it's a regular file.
1535 		 */
1536 		NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, result, td);
1537 		flags = FREAD;
1538 		error = vn_open(&nd, &flags, 0, -1);
1539 		if (error == 0) {
1540 			vfslocked = NDHASGIANT(&nd);
1541 			NDFREE(&nd, NDF_ONLY_PNBUF);
1542 			type = nd.ni_vp->v_type;
1543 			if (vap)
1544 				VOP_GETATTR(nd.ni_vp, vap, td->td_ucred, td);
1545 			VOP_UNLOCK(nd.ni_vp, 0, td);
1546 			vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1547 			VFS_UNLOCK_GIANT(vfslocked);
1548 			if (type == VREG)
1549 				return (result);
1550 		}
1551 	}
1552 	free(result, M_LINKER);
1553 	return (NULL);
1554 }
1555 
1556 #define	INT_ALIGN(base, ptr)	ptr =					\
1557 	(base) + (((ptr) - (base) + sizeof(int) - 1) & ~(sizeof(int) - 1))
1558 
1559 /*
1560  * Lookup KLD which contains requested module in the "linker.hints" file. If
1561  * version specification is available, then try to find the best KLD.
1562  * Otherwise just find the latest one.
1563  */
1564 static char *
1565 linker_hints_lookup(const char *path, int pathlen, const char *modname,
1566     int modnamelen, struct mod_depend *verinfo)
1567 {
1568 	struct thread *td = curthread;	/* XXX */
1569 	struct ucred *cred = td ? td->td_ucred : NULL;
1570 	struct nameidata nd;
1571 	struct vattr vattr, mattr;
1572 	u_char *hints = NULL;
1573 	u_char *cp, *recptr, *bufend, *result, *best, *pathbuf, *sep;
1574 	int error, ival, bestver, *intp, reclen, found, flags, clen, blen;
1575 	int vfslocked = 0;
1576 
1577 	result = NULL;
1578 	bestver = found = 0;
1579 
1580 	sep = (path[pathlen - 1] != '/') ? "/" : "";
1581 	reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
1582 	    strlen(sep) + 1;
1583 	pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
1584 	snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
1585 	    linker_hintfile);
1586 
1587 	NDINIT(&nd, LOOKUP, NOFOLLOW | MPSAFE, UIO_SYSSPACE, pathbuf, td);
1588 	flags = FREAD;
1589 	error = vn_open(&nd, &flags, 0, -1);
1590 	if (error)
1591 		goto bad;
1592 	vfslocked = NDHASGIANT(&nd);
1593 	NDFREE(&nd, NDF_ONLY_PNBUF);
1594 	if (nd.ni_vp->v_type != VREG)
1595 		goto bad;
1596 	best = cp = NULL;
1597 	error = VOP_GETATTR(nd.ni_vp, &vattr, cred, td);
1598 	if (error)
1599 		goto bad;
1600 	/*
1601 	 * XXX: we need to limit this number to some reasonable value
1602 	 */
1603 	if (vattr.va_size > 100 * 1024) {
1604 		printf("hints file too large %ld\n", (long)vattr.va_size);
1605 		goto bad;
1606 	}
1607 	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
1608 	if (hints == NULL)
1609 		goto bad;
1610 	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
1611 	    UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &reclen, td);
1612 	if (error)
1613 		goto bad;
1614 	VOP_UNLOCK(nd.ni_vp, 0, td);
1615 	vn_close(nd.ni_vp, FREAD, cred, td);
1616 	VFS_UNLOCK_GIANT(vfslocked);
1617 	nd.ni_vp = NULL;
1618 	if (reclen != 0) {
1619 		printf("can't read %d\n", reclen);
1620 		goto bad;
1621 	}
1622 	intp = (int *)hints;
1623 	ival = *intp++;
1624 	if (ival != LINKER_HINTS_VERSION) {
1625 		printf("hints file version mismatch %d\n", ival);
1626 		goto bad;
1627 	}
1628 	bufend = hints + vattr.va_size;
1629 	recptr = (u_char *)intp;
1630 	clen = blen = 0;
1631 	while (recptr < bufend && !found) {
1632 		intp = (int *)recptr;
1633 		reclen = *intp++;
1634 		ival = *intp++;
1635 		cp = (char *)intp;
1636 		switch (ival) {
1637 		case MDT_VERSION:
1638 			clen = *cp++;
1639 			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1640 				break;
1641 			cp += clen;
1642 			INT_ALIGN(hints, cp);
1643 			ival = *(int *)cp;
1644 			cp += sizeof(int);
1645 			clen = *cp++;
1646 			if (verinfo == NULL ||
1647 			    ival == verinfo->md_ver_preferred) {
1648 				found = 1;
1649 				break;
1650 			}
1651 			if (ival >= verinfo->md_ver_minimum &&
1652 			    ival <= verinfo->md_ver_maximum &&
1653 			    ival > bestver) {
1654 				bestver = ival;
1655 				best = cp;
1656 				blen = clen;
1657 			}
1658 			break;
1659 		default:
1660 			break;
1661 		}
1662 		recptr += reclen + sizeof(int);
1663 	}
1664 	/*
1665 	 * Finally check if KLD is in the place
1666 	 */
1667 	if (found)
1668 		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
1669 	else if (best)
1670 		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
1671 
1672 	/*
1673 	 * KLD is newer than hints file. What we should do now?
1674 	 */
1675 	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
1676 		printf("warning: KLD '%s' is newer than the linker.hints"
1677 		    " file\n", result);
1678 bad:
1679 	free(pathbuf, M_LINKER);
1680 	if (hints)
1681 		free(hints, M_TEMP);
1682 	if (nd.ni_vp != NULL) {
1683 		VOP_UNLOCK(nd.ni_vp, 0, td);
1684 		vn_close(nd.ni_vp, FREAD, cred, td);
1685 		VFS_UNLOCK_GIANT(vfslocked);
1686 	}
1687 	/*
1688 	 * If nothing found or hints is absent - fallback to the old
1689 	 * way by using "kldname[.ko]" as module name.
1690 	 */
1691 	if (!found && !bestver && result == NULL)
1692 		result = linker_lookup_file(path, pathlen, modname,
1693 		    modnamelen, NULL);
1694 	return (result);
1695 }
1696 
1697 /*
1698  * Lookup KLD which contains requested module in the all directories.
1699  */
1700 static char *
1701 linker_search_module(const char *modname, int modnamelen,
1702     struct mod_depend *verinfo)
1703 {
1704 	char *cp, *ep, *result;
1705 
1706 	/*
1707 	 * traverse the linker path
1708 	 */
1709 	for (cp = linker_path; *cp; cp = ep + 1) {
1710 		/* find the end of this component */
1711 		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
1712 		result = linker_hints_lookup(cp, ep - cp, modname,
1713 		    modnamelen, verinfo);
1714 		if (result != NULL)
1715 			return (result);
1716 		if (*ep == 0)
1717 			break;
1718 	}
1719 	return (NULL);
1720 }
1721 
1722 /*
1723  * Search for module in all directories listed in the linker_path.
1724  */
1725 static char *
1726 linker_search_kld(const char *name)
1727 {
1728 	char *cp, *ep, *result;
1729 	int len;
1730 
1731 	/* qualified at all? */
1732 	if (index(name, '/'))
1733 		return (linker_strdup(name));
1734 
1735 	/* traverse the linker path */
1736 	len = strlen(name);
1737 	for (ep = linker_path; *ep; ep++) {
1738 		cp = ep;
1739 		/* find the end of this component */
1740 		for (; *ep != 0 && *ep != ';'; ep++);
1741 		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
1742 		if (result != NULL)
1743 			return (result);
1744 	}
1745 	return (NULL);
1746 }
1747 
1748 static const char *
1749 linker_basename(const char *path)
1750 {
1751 	const char *filename;
1752 
1753 	filename = rindex(path, '/');
1754 	if (filename == NULL)
1755 		return path;
1756 	if (filename[1])
1757 		filename++;
1758 	return (filename);
1759 }
1760 
1761 #ifdef HWPMC_HOOKS
1762 
1763 struct hwpmc_context {
1764 	int	nobjects;
1765 	int	nmappings;
1766 	struct pmckern_map_in *kobase;
1767 };
1768 
1769 static int
1770 linker_hwpmc_list_object(linker_file_t lf, void *arg)
1771 {
1772 	struct hwpmc_context *hc;
1773 
1774 	hc = arg;
1775 
1776 	/* If we run out of mappings, fail. */
1777 	if (hc->nobjects >= hc->nmappings)
1778 		return (1);
1779 
1780 	/* Save the info for this linker file. */
1781 	hc->kobase[hc->nobjects].pm_file = lf->filename;
1782 	hc->kobase[hc->nobjects].pm_address = (uintptr_t)lf->address;
1783 	hc->nobjects++;
1784 	return (0);
1785 }
1786 
1787 /*
1788  * Inform hwpmc about the set of kernel modules currently loaded.
1789  */
1790 void *
1791 linker_hwpmc_list_objects(void)
1792 {
1793 	struct hwpmc_context hc;
1794 
1795 	hc.nmappings = 15;	/* a reasonable default */
1796 
1797  retry:
1798 	/* allocate nmappings+1 entries */
1799 	MALLOC(hc.kobase, struct pmckern_map_in *,
1800 	    (hc.nmappings + 1) * sizeof(struct pmckern_map_in), M_LINKER,
1801 	    M_WAITOK | M_ZERO);
1802 
1803 	hc.nobjects = 0;
1804 	if (linker_file_foreach(linker_hwpmc_list_object, &hc) != 0) {
1805 		hc.nmappings = hc.nobjects;
1806 		FREE(hc.kobase, M_LINKER);
1807 		goto retry;
1808 	}
1809 
1810 	KASSERT(hc.nobjects > 0, ("linker_hpwmc_list_objects: no kernel "
1811 		"objects?"));
1812 
1813 	/* The last entry of the malloced area comprises of all zeros. */
1814 	KASSERT(hc.kobase[hc.nobjects].pm_file == NULL,
1815 	    ("linker_hwpmc_list_objects: last object not NULL"));
1816 
1817 	return ((void *)hc.kobase);
1818 }
1819 #endif
1820 
1821 /*
1822  * Find a file which contains given module and load it, if "parent" is not
1823  * NULL, register a reference to it.
1824  */
1825 static int
1826 linker_load_module(const char *kldname, const char *modname,
1827     struct linker_file *parent, struct mod_depend *verinfo,
1828     struct linker_file **lfpp)
1829 {
1830 	linker_file_t lfdep;
1831 	const char *filename;
1832 	char *pathname;
1833 	int error;
1834 
1835 	KLD_LOCK_ASSERT();
1836 	if (modname == NULL) {
1837 		/*
1838  		 * We have to load KLD
1839  		 */
1840 		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
1841 		    " is not NULL"));
1842 		pathname = linker_search_kld(kldname);
1843 	} else {
1844 		if (modlist_lookup2(modname, verinfo) != NULL)
1845 			return (EEXIST);
1846 		if (kldname != NULL)
1847 			pathname = linker_strdup(kldname);
1848 		else if (rootvnode == NULL)
1849 			pathname = NULL;
1850 		else
1851 			/*
1852 			 * Need to find a KLD with required module
1853 			 */
1854 			pathname = linker_search_module(modname,
1855 			    strlen(modname), verinfo);
1856 	}
1857 	if (pathname == NULL)
1858 		return (ENOENT);
1859 
1860 	/*
1861 	 * Can't load more than one file with the same basename XXX:
1862 	 * Actually it should be possible to have multiple KLDs with
1863 	 * the same basename but different path because they can
1864 	 * provide different versions of the same modules.
1865 	 */
1866 	filename = linker_basename(pathname);
1867 	if (linker_find_file_by_name(filename))
1868 		error = EEXIST;
1869 	else do {
1870 		error = linker_load_file(pathname, &lfdep);
1871 		if (error)
1872 			break;
1873 		if (modname && verinfo &&
1874 		    modlist_lookup2(modname, verinfo) == NULL) {
1875 			linker_file_unload(lfdep, LINKER_UNLOAD_FORCE);
1876 			error = ENOENT;
1877 			break;
1878 		}
1879 		if (parent) {
1880 			error = linker_file_add_dependency(parent, lfdep);
1881 			if (error)
1882 				break;
1883 		}
1884 		if (lfpp)
1885 			*lfpp = lfdep;
1886 	} while (0);
1887 	free(pathname, M_LINKER);
1888 	return (error);
1889 }
1890 
1891 /*
1892  * This routine is responsible for finding dependencies of userland initiated
1893  * kldload(2)'s of files.
1894  */
1895 int
1896 linker_load_dependencies(linker_file_t lf)
1897 {
1898 	linker_file_t lfdep;
1899 	struct mod_metadata **start, **stop, **mdp, **nmdp;
1900 	struct mod_metadata *mp, *nmp;
1901 	struct mod_depend *verinfo;
1902 	modlist_t mod;
1903 	const char *modname, *nmodname;
1904 	int ver, error = 0, count;
1905 
1906 	/*
1907 	 * All files are dependant on /kernel.
1908 	 */
1909 	KLD_LOCK_ASSERT();
1910 	if (linker_kernel_file) {
1911 		linker_kernel_file->refs++;
1912 		error = linker_file_add_dependency(lf, linker_kernel_file);
1913 		if (error)
1914 			return (error);
1915 	}
1916 	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
1917 	    &count) != 0)
1918 		return (0);
1919 	for (mdp = start; mdp < stop; mdp++) {
1920 		mp = *mdp;
1921 		if (mp->md_type != MDT_VERSION)
1922 			continue;
1923 		modname = mp->md_cval;
1924 		ver = ((struct mod_version *)mp->md_data)->mv_version;
1925 		mod = modlist_lookup(modname, ver);
1926 		if (mod != NULL) {
1927 			printf("interface %s.%d already present in the KLD"
1928 			    " '%s'!\n", modname, ver,
1929 			    mod->container->filename);
1930 			return (EEXIST);
1931 		}
1932 	}
1933 
1934 	for (mdp = start; mdp < stop; mdp++) {
1935 		mp = *mdp;
1936 		if (mp->md_type != MDT_DEPEND)
1937 			continue;
1938 		modname = mp->md_cval;
1939 		verinfo = mp->md_data;
1940 		nmodname = NULL;
1941 		for (nmdp = start; nmdp < stop; nmdp++) {
1942 			nmp = *nmdp;
1943 			if (nmp->md_type != MDT_VERSION)
1944 				continue;
1945 			nmodname = nmp->md_cval;
1946 			if (strcmp(modname, nmodname) == 0)
1947 				break;
1948 		}
1949 		if (nmdp < stop)/* early exit, it's a self reference */
1950 			continue;
1951 		mod = modlist_lookup2(modname, verinfo);
1952 		if (mod) {	/* woohoo, it's loaded already */
1953 			lfdep = mod->container;
1954 			lfdep->refs++;
1955 			error = linker_file_add_dependency(lf, lfdep);
1956 			if (error)
1957 				break;
1958 			continue;
1959 		}
1960 		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
1961 		if (error) {
1962 			printf("KLD %s: depends on %s - not available\n",
1963 			    lf->filename, modname);
1964 			break;
1965 		}
1966 	}
1967 
1968 	if (error)
1969 		return (error);
1970 	linker_addmodules(lf, start, stop, 0);
1971 	return (error);
1972 }
1973 
1974 static int
1975 sysctl_kern_function_list_iterate(const char *name, void *opaque)
1976 {
1977 	struct sysctl_req *req;
1978 
1979 	req = opaque;
1980 	return (SYSCTL_OUT(req, name, strlen(name) + 1));
1981 }
1982 
1983 /*
1984  * Export a nul-separated, double-nul-terminated list of all function names
1985  * in the kernel.
1986  */
1987 static int
1988 sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
1989 {
1990 	linker_file_t lf;
1991 	int error;
1992 
1993 #ifdef MAC
1994 	error = mac_check_kld_stat(req->td->td_ucred);
1995 	if (error)
1996 		return (error);
1997 #endif
1998 	error = sysctl_wire_old_buffer(req, 0);
1999 	if (error != 0)
2000 		return (error);
2001 	KLD_LOCK();
2002 	TAILQ_FOREACH(lf, &linker_files, link) {
2003 		error = LINKER_EACH_FUNCTION_NAME(lf,
2004 		    sysctl_kern_function_list_iterate, req);
2005 		if (error) {
2006 			KLD_UNLOCK();
2007 			return (error);
2008 		}
2009 	}
2010 	KLD_UNLOCK();
2011 	return (SYSCTL_OUT(req, "", 1));
2012 }
2013 
2014 SYSCTL_PROC(_kern, OID_AUTO, function_list, CTLFLAG_RD,
2015     NULL, 0, sysctl_kern_function_list, "", "kernel function list");
2016