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