xref: /freebsd/sys/kern/kern_linker.c (revision 9889fac5b82c8de5b55c9ae708d57bc64c10c87a)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 1997-2000 Doug Rabson
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 #include "opt_ddb.h"
31 #include "opt_kld.h"
32 #include "opt_hwpmc_hooks.h"
33 #include "opt_hwt_hooks.h"
34 
35 #define EXTERR_CATEGORY EXTERR_CAT_LINKER
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/boottrace.h>
39 #include <sys/eventhandler.h>
40 #include <sys/exterrvar.h>
41 #include <sys/fcntl.h>
42 #include <sys/jail.h>
43 #include <sys/kernel.h>
44 #include <sys/libkern.h>
45 #include <sys/linker.h>
46 #include <sys/lock.h>
47 #include <sys/malloc.h>
48 #include <sys/module.h>
49 #include <sys/mount.h>
50 #include <sys/mutex.h>
51 #include <sys/namei.h>
52 #include <sys/priv.h>
53 #include <sys/proc.h>
54 #include <sys/sx.h>
55 #include <sys/syscallsubr.h>
56 #include <sys/sysctl.h>
57 #include <sys/sysproto.h>
58 #include <sys/vnode.h>
59 
60 #ifdef DDB
61 #include <ddb/ddb.h>
62 #endif
63 
64 #include <net/vnet.h>
65 
66 #include <security/mac/mac_framework.h>
67 
68 #include "linker_if.h"
69 
70 #if defined(HWPMC_HOOKS) || defined(HWT_HOOKS)
71 #include <sys/pmckern.h>
72 #endif
73 
74 #ifdef KLD_DEBUG
75 int kld_debug = 0;
76 SYSCTL_INT(_debug, OID_AUTO, kld_debug, CTLFLAG_RWTUN,
77     &kld_debug, 0, "Set various levels of KLD debug");
78 #endif
79 
80 /* These variables are used by kernel debuggers to enumerate loaded files. */
81 const int kld_off_address = offsetof(struct linker_file, address);
82 const int kld_off_filename = offsetof(struct linker_file, filename);
83 const int kld_off_pathname = offsetof(struct linker_file, pathname);
84 const int kld_off_next = offsetof(struct linker_file, link.tqe_next);
85 
86 /*
87  * static char *linker_search_path(const char *name, struct mod_depend
88  * *verinfo);
89  */
90 static const char 	*linker_basename(const char *path);
91 
92 /*
93  * Find a currently loaded file given its filename.
94  */
95 static linker_file_t linker_find_file_by_name(const char* _filename);
96 
97 /*
98  * Find a currently loaded file given its file id.
99  */
100 static linker_file_t linker_find_file_by_id(int _fileid);
101 
102 /* Metadata from the static kernel */
103 SET_DECLARE(modmetadata_set, struct mod_metadata);
104 
105 MALLOC_DEFINE(M_LINKER, "linker", "kernel linker");
106 
107 linker_file_t linker_kernel_file;
108 
109 static struct sx kld_sx;	/* kernel linker lock */
110 static u_int kld_busy;
111 static struct thread *kld_busy_owner;
112 
113 /*
114  * Load counter used by clients to determine if a linker file has been
115  * re-loaded. This counter is incremented for each file load.
116  */
117 static int loadcnt;
118 
119 static linker_class_list_t classes;
120 static linker_file_list_t linker_files;
121 static int next_file_id = 1;
122 static int linker_no_more_classes = 0;
123 
124 #define	LINKER_GET_NEXT_FILE_ID(a) do {					\
125 	linker_file_t lftmp;						\
126 									\
127 	if (!cold)							\
128 		sx_assert(&kld_sx, SA_XLOCKED);				\
129 retry:									\
130 	TAILQ_FOREACH(lftmp, &linker_files, link) {			\
131 		if (next_file_id == lftmp->id) {			\
132 			next_file_id++;					\
133 			goto retry;					\
134 		}							\
135 	}								\
136 	(a) = next_file_id;						\
137 } while (0)
138 
139 /* XXX wrong name; we're looking at version provision tags here, not modules */
140 typedef TAILQ_HEAD(, modlist) modlisthead_t;
141 struct modlist {
142 	TAILQ_ENTRY(modlist) link;	/* chain together all modules */
143 	linker_file_t   container;
144 	const char 	*name;
145 	int             version;
146 };
147 typedef struct modlist *modlist_t;
148 static modlisthead_t found_modules;
149 
150 static void	linker_file_add_dependency(linker_file_t file,
151 		    linker_file_t dep);
152 static caddr_t	linker_file_lookup_symbol_internal(linker_file_t file,
153 		    const char* name, int deps);
154 static int	linker_load_module(const char *kldname,
155 		    const char *modname, struct linker_file *parent,
156 		    const struct mod_depend *verinfo, struct linker_file **lfpp);
157 static modlist_t modlist_lookup2(const char *name, const struct mod_depend *verinfo);
158 
159 static void
160 linker_init(void *arg)
161 {
162 
163 	sx_init(&kld_sx, "kernel linker");
164 	TAILQ_INIT(&classes);
165 	TAILQ_INIT(&linker_files);
166 }
167 
168 SYSINIT(linker, SI_SUB_KLD, SI_ORDER_FIRST, linker_init, NULL);
169 
170 static void
171 linker_stop_class_add(void *arg)
172 {
173 
174 	linker_no_more_classes = 1;
175 }
176 
177 SYSINIT(linker_class, SI_SUB_KLD, SI_ORDER_ANY, linker_stop_class_add, NULL);
178 
179 int
180 linker_add_class(linker_class_t lc)
181 {
182 
183 	/*
184 	 * We disallow any class registration past SI_ORDER_ANY
185 	 * of SI_SUB_KLD.  We bump the reference count to keep the
186 	 * ops from being freed.
187 	 */
188 	if (linker_no_more_classes == 1)
189 		return (EPERM);
190 	kobj_class_compile((kobj_class_t) lc);
191 	((kobj_class_t)lc)->refs++;	/* XXX: kobj_mtx */
192 	TAILQ_INSERT_TAIL(&classes, lc, link);
193 	return (0);
194 }
195 
196 static void
197 linker_file_sysinit(linker_file_t lf)
198 {
199 	struct sysinit **start, **stop, **sipp, **xipp, *save;
200 	int last;
201 
202 	KLD_DPF(FILE, ("linker_file_sysinit: calling SYSINITs for %s\n",
203 	    lf->filename));
204 
205 	sx_assert(&kld_sx, SA_XLOCKED);
206 
207 	if (linker_file_lookup_set(lf, "sysinit_set", &start, &stop, NULL) != 0)
208 		return;
209 	/*
210 	 * Perform a bubble sort of the system initialization objects by
211 	 * their subsystem (primary key) and order (secondary key).
212 	 *
213 	 * Since some things care about execution order, this is the operation
214 	 * which ensures continued function.
215 	 */
216 	for (sipp = start; sipp < stop; sipp++) {
217 		for (xipp = sipp + 1; xipp < stop; xipp++) {
218 			if ((*sipp)->subsystem < (*xipp)->subsystem ||
219 			    ((*sipp)->subsystem == (*xipp)->subsystem &&
220 			    (*sipp)->order <= (*xipp)->order))
221 				continue;	/* skip */
222 			save = *sipp;
223 			*sipp = *xipp;
224 			*xipp = save;
225 		}
226 	}
227 
228 	/*
229 	 * Traverse the (now) ordered list of system initialization tasks.
230 	 * Perform each task, and continue on to the next task.
231 	 */
232 	last = SI_SUB_DUMMY;
233 	sx_xunlock(&kld_sx);
234 	mtx_lock(&Giant);
235 	for (sipp = start; sipp < stop; sipp++) {
236 		if ((*sipp)->subsystem == SI_SUB_DUMMY)
237 			continue;	/* skip dummy task(s) */
238 
239 		if ((*sipp)->subsystem > last)
240 			BOOTTRACE("%s: sysinit 0x%7x", lf->filename,
241 			    (*sipp)->subsystem);
242 
243 		/* Call function */
244 		(*((*sipp)->func)) ((*sipp)->udata);
245 		last = (*sipp)->subsystem;
246 	}
247 	mtx_unlock(&Giant);
248 	sx_xlock(&kld_sx);
249 }
250 
251 static void
252 linker_file_sysuninit(linker_file_t lf)
253 {
254 	struct sysinit **start, **stop, **sipp, **xipp, *save;
255 	int last;
256 
257 	KLD_DPF(FILE, ("linker_file_sysuninit: calling SYSUNINITs for %s\n",
258 	    lf->filename));
259 
260 	sx_assert(&kld_sx, SA_XLOCKED);
261 
262 	if (linker_file_lookup_set(lf, "sysuninit_set", &start, &stop,
263 	    NULL) != 0)
264 		return;
265 
266 	/*
267 	 * Perform a reverse bubble sort of the system initialization objects
268 	 * by their subsystem (primary key) and order (secondary key).
269 	 *
270 	 * Since some things care about execution order, this is the operation
271 	 * which ensures continued function.
272 	 */
273 	for (sipp = start; sipp < stop; sipp++) {
274 		for (xipp = sipp + 1; xipp < stop; xipp++) {
275 			if ((*sipp)->subsystem > (*xipp)->subsystem ||
276 			    ((*sipp)->subsystem == (*xipp)->subsystem &&
277 			    (*sipp)->order >= (*xipp)->order))
278 				continue;	/* skip */
279 			save = *sipp;
280 			*sipp = *xipp;
281 			*xipp = save;
282 		}
283 	}
284 
285 	/*
286 	 * Traverse the (now) ordered list of system initialization tasks.
287 	 * Perform each task, and continue on to the next task.
288 	 */
289 	sx_xunlock(&kld_sx);
290 	mtx_lock(&Giant);
291 	last = SI_SUB_DUMMY;
292 	for (sipp = start; sipp < stop; sipp++) {
293 		if ((*sipp)->subsystem == SI_SUB_DUMMY)
294 			continue;	/* skip dummy task(s) */
295 
296 		if ((*sipp)->subsystem > last)
297 			BOOTTRACE("%s: sysuninit 0x%7x", lf->filename,
298 			    (*sipp)->subsystem);
299 
300 		/* Call function */
301 		(*((*sipp)->func)) ((*sipp)->udata);
302 		last = (*sipp)->subsystem;
303 	}
304 	mtx_unlock(&Giant);
305 	sx_xlock(&kld_sx);
306 }
307 
308 static void
309 linker_file_register_sysctls(linker_file_t lf, bool enable)
310 {
311 	struct sysctl_oid **start, **stop, **oidp;
312 
313 	KLD_DPF(FILE,
314 	    ("linker_file_register_sysctls: registering SYSCTLs for %s\n",
315 	    lf->filename));
316 
317 	sx_assert(&kld_sx, SA_XLOCKED);
318 
319 	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
320 		return;
321 
322 	sx_xunlock(&kld_sx);
323 	sysctl_wlock();
324 	for (oidp = start; oidp < stop; oidp++) {
325 		if (enable)
326 			sysctl_register_oid(*oidp);
327 		else
328 			sysctl_register_disabled_oid(*oidp);
329 	}
330 	sysctl_wunlock();
331 	sx_xlock(&kld_sx);
332 }
333 
334 /*
335  * Invoke the LINKER_CTF_GET implementation for this file.  Existing
336  * implementations will load CTF info from the filesystem upon the first call
337  * and cache it in the kernel thereafter.
338  */
339 static void
340 linker_ctf_load_file(linker_file_t file)
341 {
342 	linker_ctf_t lc;
343 	int error;
344 
345 	error = linker_ctf_get(file, &lc);
346 	if (error == 0)
347 		return;
348 	if (bootverbose) {
349 		printf("failed to load CTF for %s: %d\n", file->filename,
350 		    error);
351 	}
352 }
353 
354 static void
355 linker_file_enable_sysctls(linker_file_t lf)
356 {
357 	struct sysctl_oid **start, **stop, **oidp;
358 
359 	KLD_DPF(FILE,
360 	    ("linker_file_enable_sysctls: enable SYSCTLs for %s\n",
361 	    lf->filename));
362 
363 	sx_assert(&kld_sx, SA_XLOCKED);
364 
365 	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
366 		return;
367 
368 	sx_xunlock(&kld_sx);
369 	sysctl_wlock();
370 	for (oidp = start; oidp < stop; oidp++)
371 		sysctl_enable_oid(*oidp);
372 	sysctl_wunlock();
373 	sx_xlock(&kld_sx);
374 }
375 
376 static void
377 linker_file_unregister_sysctls(linker_file_t lf)
378 {
379 	struct sysctl_oid **start, **stop, **oidp;
380 
381 	KLD_DPF(FILE, ("linker_file_unregister_sysctls: unregistering SYSCTLs"
382 	    " for %s\n", lf->filename));
383 
384 	sx_assert(&kld_sx, SA_XLOCKED);
385 
386 	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
387 		return;
388 
389 	sx_xunlock(&kld_sx);
390 	sysctl_wlock();
391 	for (oidp = start; oidp < stop; oidp++)
392 		sysctl_unregister_oid(*oidp);
393 	sysctl_wunlock();
394 	sx_xlock(&kld_sx);
395 }
396 
397 static int
398 linker_file_register_modules(linker_file_t lf)
399 {
400 	struct mod_metadata **start, **stop, **mdp;
401 	const moduledata_t *moddata;
402 	int first_error, error;
403 
404 	KLD_DPF(FILE, ("linker_file_register_modules: registering modules"
405 	    " in %s\n", lf->filename));
406 
407 	sx_assert(&kld_sx, SA_XLOCKED);
408 
409 	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop, NULL) != 0) {
410 		/*
411 		 * This fallback should be unnecessary, but if we get booted
412 		 * from boot2 instead of loader and we are missing our
413 		 * metadata then we have to try the best we can.
414 		 */
415 		if (lf == linker_kernel_file) {
416 			start = SET_BEGIN(modmetadata_set);
417 			stop = SET_LIMIT(modmetadata_set);
418 		} else
419 			return (0);
420 	}
421 	first_error = 0;
422 	for (mdp = start; mdp < stop; mdp++) {
423 		if ((*mdp)->md_type != MDT_MODULE)
424 			continue;
425 		moddata = (*mdp)->md_data;
426 		KLD_DPF(FILE, ("Registering module %s in %s\n",
427 		    moddata->name, lf->filename));
428 		error = module_register(moddata, lf);
429 		if (error) {
430 			printf("Module %s failed to register: %d\n",
431 			    moddata->name, error);
432 			if (first_error == 0)
433 				first_error = error;
434 		}
435 	}
436 	return (first_error);
437 }
438 
439 static void
440 linker_init_kernel_modules(void *dummy __unused)
441 {
442 
443 	sx_xlock(&kld_sx);
444 	linker_file_register_modules(linker_kernel_file);
445 	sx_xunlock(&kld_sx);
446 }
447 
448 SYSINIT(linker_kernel, SI_SUB_KLD, SI_ORDER_ANY, linker_init_kernel_modules,
449     NULL);
450 
451 static int
452 linker_load_file(const char *filename, linker_file_t *result)
453 {
454 	linker_class_t lc;
455 	linker_file_t lf;
456 	int foundfile, error, modules;
457 
458 	/* Refuse to load modules if securelevel raised */
459 	if (prison0.pr_securelevel > 0)
460 		return (EPERM);
461 
462 	sx_assert(&kld_sx, SA_XLOCKED);
463 	lf = linker_find_file_by_name(filename);
464 	if (lf) {
465 		KLD_DPF(FILE, ("linker_load_file: file %s is already loaded,"
466 		    " incrementing refs\n", filename));
467 		*result = lf;
468 		lf->refs++;
469 		return (0);
470 	}
471 	foundfile = 0;
472 	error = 0;
473 
474 	/*
475 	 * We do not need to protect (lock) classes here because there is
476 	 * no class registration past startup (SI_SUB_KLD, SI_ORDER_ANY)
477 	 * and there is no class deregistration mechanism at this time.
478 	 */
479 	TAILQ_FOREACH(lc, &classes, link) {
480 		KLD_DPF(FILE, ("linker_load_file: trying to load %s\n",
481 		    filename));
482 		error = LINKER_LOAD_FILE(lc, filename, &lf);
483 		/*
484 		 * If we got something other than ENOENT, then it exists but
485 		 * we cannot load it for some other reason.
486 		 */
487 		if (error != ENOENT) {
488 			foundfile = 1;
489 			if (error == EEXIST)
490 				break;
491 		}
492 		if (lf) {
493 			error = linker_file_register_modules(lf);
494 			if (error == EEXIST) {
495 				linker_file_unload(lf, LINKER_UNLOAD_FORCE);
496 				return (error);
497 			}
498 			modules = !TAILQ_EMPTY(&lf->modules);
499 			linker_file_register_sysctls(lf, false);
500 #ifdef VIMAGE
501 			LINKER_PROPAGATE_VNETS(lf);
502 #endif
503 			linker_file_sysinit(lf);
504 			lf->flags |= LINKER_FILE_LINKED;
505 
506 			/*
507 			 * If all of the modules in this file failed
508 			 * to load, unload the file and return an
509 			 * error of ENOEXEC.
510 			 */
511 			if (modules && TAILQ_EMPTY(&lf->modules)) {
512 				linker_file_unload(lf, LINKER_UNLOAD_FORCE);
513 				return (ENOEXEC);
514 			}
515 			linker_file_enable_sysctls(lf);
516 
517 			/*
518 			 * Ask the linker to load CTF data for this file.
519 			 */
520 			linker_ctf_load_file(lf);
521 			EVENTHANDLER_INVOKE(kld_load, lf);
522 			*result = lf;
523 			return (0);
524 		}
525 	}
526 	/*
527 	 * Less than ideal, but tells the user whether it failed to load or
528 	 * the module was not found.
529 	 */
530 	if (foundfile) {
531 		/*
532 		 * If the file type has not been recognized by the last try
533 		 * printout a message before to fail.
534 		 */
535 		if (error == ENOSYS)
536 			printf("%s: %s - unsupported file type\n",
537 			    __func__, filename);
538 
539 		/*
540 		 * Format not recognized or otherwise unloadable.
541 		 * When loading a module that is statically built into
542 		 * the kernel EEXIST percolates back up as the return
543 		 * value.  Preserve this so that apps like sysinstall
544 		 * can recognize this special case and not post bogus
545 		 * dialog boxes.
546 		 */
547 		if (error != EEXIST)
548 			error = ENOEXEC;
549 	} else
550 		error = ENOENT;		/* Nothing found */
551 	return (error);
552 }
553 
554 int
555 linker_reference_module(const char *modname, struct mod_depend *verinfo,
556     linker_file_t *result)
557 {
558 	modlist_t mod;
559 	int error;
560 
561 	sx_xlock(&kld_sx);
562 	if ((mod = modlist_lookup2(modname, verinfo)) != NULL) {
563 		*result = mod->container;
564 		(*result)->refs++;
565 		sx_xunlock(&kld_sx);
566 		return (0);
567 	}
568 
569 	error = linker_load_module(NULL, modname, NULL, verinfo, result);
570 	sx_xunlock(&kld_sx);
571 	return (error);
572 }
573 
574 int
575 linker_release_module(const char *modname, struct mod_depend *verinfo,
576     linker_file_t lf)
577 {
578 	modlist_t mod;
579 	int error;
580 
581 	sx_xlock(&kld_sx);
582 	if (lf == NULL) {
583 		KASSERT(modname != NULL,
584 		    ("linker_release_module: no file or name"));
585 		mod = modlist_lookup2(modname, verinfo);
586 		if (mod == NULL) {
587 			sx_xunlock(&kld_sx);
588 			return (ESRCH);
589 		}
590 		lf = mod->container;
591 	} else
592 		KASSERT(modname == NULL && verinfo == NULL,
593 		    ("linker_release_module: both file and name"));
594 	error =	linker_file_unload(lf, LINKER_UNLOAD_NORMAL);
595 	sx_xunlock(&kld_sx);
596 	return (error);
597 }
598 
599 static linker_file_t
600 linker_find_file_by_name(const char *filename)
601 {
602 	linker_file_t lf;
603 	char *koname;
604 
605 	koname = malloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
606 	sprintf(koname, "%s.ko", filename);
607 
608 	sx_assert(&kld_sx, SA_XLOCKED);
609 	TAILQ_FOREACH(lf, &linker_files, link) {
610 		if (strcmp(lf->filename, koname) == 0)
611 			break;
612 		if (strcmp(lf->filename, filename) == 0)
613 			break;
614 	}
615 	free(koname, M_LINKER);
616 	return (lf);
617 }
618 
619 static linker_file_t
620 linker_find_file_by_id(int fileid)
621 {
622 	linker_file_t lf;
623 
624 	sx_assert(&kld_sx, SA_XLOCKED);
625 	TAILQ_FOREACH(lf, &linker_files, link)
626 		if (lf->id == fileid && lf->flags & LINKER_FILE_LINKED)
627 			break;
628 	return (lf);
629 }
630 
631 int
632 linker_file_foreach(linker_predicate_t *predicate, void *context)
633 {
634 	linker_file_t lf;
635 	int retval = 0;
636 
637 	sx_xlock(&kld_sx);
638 	TAILQ_FOREACH(lf, &linker_files, link) {
639 		retval = predicate(lf, context);
640 		if (retval != 0)
641 			break;
642 	}
643 	sx_xunlock(&kld_sx);
644 	return (retval);
645 }
646 
647 linker_file_t
648 linker_make_file(const char *pathname, linker_class_t lc)
649 {
650 	linker_file_t lf;
651 	const char *filename;
652 
653 	if (!cold)
654 		sx_assert(&kld_sx, SA_XLOCKED);
655 	filename = linker_basename(pathname);
656 
657 	KLD_DPF(FILE, ("linker_make_file: new file, filename='%s' for pathname='%s'\n", filename, pathname));
658 	lf = (linker_file_t)kobj_create((kobj_class_t)lc, M_LINKER, M_WAITOK);
659 	if (lf == NULL)
660 		return (NULL);
661 	lf->ctors_addr = 0;
662 	lf->ctors_size = 0;
663 	lf->ctors_invoked = LF_NONE;
664 	lf->dtors_addr = 0;
665 	lf->dtors_size = 0;
666 	lf->refs = 1;
667 	lf->userrefs = 0;
668 	lf->flags = 0;
669 	lf->filename = strdup(filename, M_LINKER);
670 	lf->pathname = strdup(pathname, M_LINKER);
671 	LINKER_GET_NEXT_FILE_ID(lf->id);
672 	lf->ndeps = 0;
673 	lf->deps = NULL;
674 	lf->loadcnt = ++loadcnt;
675 #ifdef __arm__
676 	lf->exidx_addr = 0;
677 	lf->exidx_size = 0;
678 #endif
679 	STAILQ_INIT(&lf->common);
680 	TAILQ_INIT(&lf->modules);
681 	TAILQ_INSERT_TAIL(&linker_files, lf, link);
682 	return (lf);
683 }
684 
685 int
686 linker_file_unload(linker_file_t file, int flags)
687 {
688 	module_t mod, next;
689 	modlist_t ml, nextml;
690 	struct common_symbol *cp;
691 	int error, i;
692 
693 	/* Refuse to unload modules if securelevel raised. */
694 	if (prison0.pr_securelevel > 0)
695 		return (EPERM);
696 
697 	sx_assert(&kld_sx, SA_XLOCKED);
698 	KLD_DPF(FILE, ("linker_file_unload: lf->refs=%d\n", file->refs));
699 
700 	/* Easy case of just dropping a reference. */
701 	if (file->refs > 1) {
702 		file->refs--;
703 		return (0);
704 	}
705 
706 	/* Give eventhandlers a chance to prevent the unload. */
707 	error = 0;
708 	if ((file->flags & LINKER_FILE_LINKED) != 0) {
709 		EVENTHANDLER_INVOKE(kld_unload_try, file, &error);
710 		if (error != 0)
711 			return (EBUSY);
712 	}
713 
714 	KLD_DPF(FILE, ("linker_file_unload: file is unloading,"
715 	    " informing modules\n"));
716 
717 	/*
718 	 * Quiesce all the modules to give them a chance to veto the unload.
719 	 */
720 	MOD_SLOCK;
721 	for (mod = TAILQ_FIRST(&file->modules); mod;
722 	     mod = module_getfnext(mod)) {
723 		error = module_quiesce(mod);
724 		if (error != 0 && flags != LINKER_UNLOAD_FORCE) {
725 			KLD_DPF(FILE, ("linker_file_unload: module %s"
726 			    " vetoed unload\n", module_getname(mod)));
727 			/*
728 			 * XXX: Do we need to tell all the quiesced modules
729 			 * that they can resume work now via a new module
730 			 * event?
731 			 */
732 			MOD_SUNLOCK;
733 			return (error);
734 		}
735 	}
736 	MOD_SUNLOCK;
737 
738 	/*
739 	 * Inform any modules associated with this file that they are
740 	 * being unloaded.
741 	 */
742 	MOD_XLOCK;
743 	for (mod = TAILQ_FIRST(&file->modules); mod; mod = next) {
744 		next = module_getfnext(mod);
745 		MOD_XUNLOCK;
746 
747 		/*
748 		 * Give the module a chance to veto the unload.
749 		 */
750 		if ((error = module_unload(mod)) != 0) {
751 #ifdef KLD_DEBUG
752 			MOD_SLOCK;
753 			KLD_DPF(FILE, ("linker_file_unload: module %s"
754 			    " failed unload\n", module_getname(mod)));
755 			MOD_SUNLOCK;
756 #endif
757 			return (error);
758 		}
759 		MOD_XLOCK;
760 		module_release(mod);
761 	}
762 	MOD_XUNLOCK;
763 
764 	TAILQ_FOREACH_SAFE(ml, &found_modules, link, nextml) {
765 		if (ml->container == file) {
766 			TAILQ_REMOVE(&found_modules, ml, link);
767 			free(ml, M_LINKER);
768 		}
769 	}
770 
771 	/*
772 	 * Don't try to run SYSUNINITs if we are unloaded due to a
773 	 * link error.
774 	 */
775 	if ((file->flags & LINKER_FILE_LINKED) != 0) {
776 		file->flags &= ~LINKER_FILE_LINKED;
777 		linker_file_unregister_sysctls(file);
778 		linker_file_sysuninit(file);
779 		EVENTHANDLER_INVOKE(kld_unload, file->filename, file->address,
780 		    file->size);
781 	}
782 	TAILQ_REMOVE(&linker_files, file, link);
783 
784 	if (file->deps) {
785 		for (i = 0; i < file->ndeps; i++)
786 			linker_file_unload(file->deps[i], flags);
787 		free(file->deps, M_LINKER);
788 		file->deps = NULL;
789 	}
790 	while ((cp = STAILQ_FIRST(&file->common)) != NULL) {
791 		STAILQ_REMOVE_HEAD(&file->common, link);
792 		free(cp, M_LINKER);
793 	}
794 
795 	LINKER_UNLOAD(file);
796 
797 	if (file->filename) {
798 		free(file->filename, M_LINKER);
799 		file->filename = NULL;
800 	}
801 	if (file->pathname) {
802 		free(file->pathname, M_LINKER);
803 		file->pathname = NULL;
804 	}
805 	kobj_delete((kobj_t) file, M_LINKER);
806 	return (0);
807 }
808 
809 int
810 linker_ctf_get(linker_file_t file, linker_ctf_t *lc)
811 {
812 	return (LINKER_CTF_GET(file, lc));
813 }
814 
815 int
816 linker_ctf_lookup_typename_ddb(linker_ctf_t *lc, const char *typename)
817 {
818 #ifdef DDB
819 	linker_file_t lf;
820 
821 	TAILQ_FOREACH (lf, &linker_files, link){
822 		if (LINKER_CTF_LOOKUP_TYPENAME(lf, lc, typename) == 0)
823 			return (0);
824 	}
825 #endif
826 	return (ENOENT);
827 }
828 
829 int
830 linker_ctf_lookup_sym_ddb(const char *symname, c_linker_sym_t *sym,
831     linker_ctf_t *lc)
832 {
833 #ifdef DDB
834 	linker_file_t lf;
835 
836 	TAILQ_FOREACH (lf, &linker_files, link){
837 		if (LINKER_LOOKUP_DEBUG_SYMBOL_CTF(lf, symname, sym, lc) == 0)
838 			return (0);
839 	}
840 #endif
841 	return (ENOENT);
842 }
843 
844 static void
845 linker_file_add_dependency(linker_file_t file, linker_file_t dep)
846 {
847 	linker_file_t *newdeps;
848 
849 	sx_assert(&kld_sx, SA_XLOCKED);
850 	file->deps = realloc(file->deps, (file->ndeps + 1) * sizeof(*newdeps),
851 	    M_LINKER, M_WAITOK | M_ZERO);
852 	file->deps[file->ndeps] = dep;
853 	file->ndeps++;
854 	KLD_DPF(FILE, ("linker_file_add_dependency:"
855 	    " adding %s as dependency for %s\n",
856 	    dep->filename, file->filename));
857 }
858 
859 /*
860  * Locate a linker set and its contents.  This is a helper function to avoid
861  * linker_if.h exposure elsewhere.  Note: firstp and lastp are really void **.
862  * This function is used in this file so we can avoid having lots of (void **)
863  * casts.
864  */
865 int
866 linker_file_lookup_set(linker_file_t file, const char *name,
867     void *firstp, void *lastp, int *countp)
868 {
869 
870 	sx_assert(&kld_sx, SA_LOCKED);
871 	return (LINKER_LOOKUP_SET(file, name, firstp, lastp, countp));
872 }
873 
874 /*
875  * List all functions in a file.
876  */
877 int
878 linker_file_function_listall(linker_file_t lf,
879     linker_function_nameval_callback_t callback_func, void *arg)
880 {
881 	return (LINKER_EACH_FUNCTION_NAMEVAL(lf, callback_func, arg));
882 }
883 
884 caddr_t
885 linker_file_lookup_symbol(linker_file_t file, const char *name, int deps)
886 {
887 	caddr_t sym;
888 	int locked;
889 
890 	locked = sx_xlocked(&kld_sx);
891 	if (!locked)
892 		sx_xlock(&kld_sx);
893 	sym = linker_file_lookup_symbol_internal(file, name, deps);
894 	if (!locked)
895 		sx_xunlock(&kld_sx);
896 	return (sym);
897 }
898 
899 static caddr_t
900 linker_file_lookup_symbol_internal(linker_file_t file, const char *name,
901     int deps)
902 {
903 	c_linker_sym_t sym;
904 	linker_symval_t symval;
905 	caddr_t address;
906 	size_t common_size = 0;
907 	int i;
908 
909 	sx_assert(&kld_sx, SA_XLOCKED);
910 	KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%p, name=%s, deps=%d\n",
911 	    file, name, deps));
912 
913 	/*
914 	 * Treat the __this_linker_file as a special symbol. This is a
915 	 * global that linuxkpi uses to populate the THIS_MODULE
916 	 * value.  In this case we can simply return the linker_file_t.
917 	 *
918 	 * Modules compiled statically into the kernel are assigned NULL.
919 	 */
920 	if (strcmp(name, "__this_linker_file") == 0) {
921 		address = (file == linker_kernel_file) ? NULL : (caddr_t)file;
922 		KLD_DPF(SYM, ("linker_file_lookup_symbol: resolving special "
923 		    "symbol __this_linker_file to %p\n", address));
924 		return (address);
925 	}
926 
927 	if (LINKER_LOOKUP_SYMBOL(file, name, &sym) == 0) {
928 		LINKER_SYMBOL_VALUES(file, sym, &symval);
929 		if (symval.value == 0)
930 			/*
931 			 * For commons, first look them up in the
932 			 * dependencies and only allocate space if not found
933 			 * there.
934 			 */
935 			common_size = symval.size;
936 		else {
937 			KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol"
938 			    ".value=%p\n", symval.value));
939 			return (symval.value);
940 		}
941 	}
942 	if (deps) {
943 		for (i = 0; i < file->ndeps; i++) {
944 			address = linker_file_lookup_symbol_internal(
945 			    file->deps[i], name, 0);
946 			if (address) {
947 				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
948 				    " deps value=%p\n", address));
949 				return (address);
950 			}
951 		}
952 	}
953 	if (common_size > 0) {
954 		/*
955 		 * This is a common symbol which was not found in the
956 		 * dependencies.  We maintain a simple common symbol table in
957 		 * the file object.
958 		 */
959 		struct common_symbol *cp;
960 
961 		STAILQ_FOREACH(cp, &file->common, link) {
962 			if (strcmp(cp->name, name) == 0) {
963 				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
964 				    " old common value=%p\n", cp->address));
965 				return (cp->address);
966 			}
967 		}
968 		/*
969 		 * Round the symbol size up to align.
970 		 */
971 		common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
972 		cp = malloc(sizeof(struct common_symbol)
973 		    + common_size + strlen(name) + 1, M_LINKER,
974 		    M_WAITOK | M_ZERO);
975 		cp->address = (caddr_t)(cp + 1);
976 		cp->name = cp->address + common_size;
977 		strcpy(cp->name, name);
978 		bzero(cp->address, common_size);
979 		STAILQ_INSERT_TAIL(&file->common, cp, link);
980 
981 		KLD_DPF(SYM, ("linker_file_lookup_symbol: new common"
982 		    " value=%p\n", cp->address));
983 		return (cp->address);
984 	}
985 	KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
986 	return (0);
987 }
988 
989 /*
990  * Both DDB and stack(9) rely on the kernel linker to provide forward and
991  * backward lookup of symbols.  However, DDB and sometimes stack(9) need to
992  * do this in a lockfree manner.  We provide a set of internal helper
993  * routines to perform these operations without locks, and then wrappers that
994  * optionally lock.
995  *
996  * linker_debug_lookup() is ifdef DDB as currently it's only used by DDB.
997  */
998 #ifdef DDB
999 static int
1000 linker_debug_lookup(const char *symstr, c_linker_sym_t *sym)
1001 {
1002 	linker_file_t lf;
1003 
1004 	TAILQ_FOREACH(lf, &linker_files, link) {
1005 		if (LINKER_LOOKUP_DEBUG_SYMBOL(lf, symstr, sym) == 0)
1006 			return (0);
1007 	}
1008 	return (ENOENT);
1009 }
1010 #endif
1011 
1012 static int
1013 linker_debug_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
1014 {
1015 	linker_file_t lf;
1016 	c_linker_sym_t best, es;
1017 	u_long diff, bestdiff, off;
1018 
1019 	best = 0;
1020 	off = (uintptr_t)value;
1021 	bestdiff = off;
1022 	TAILQ_FOREACH(lf, &linker_files, link) {
1023 		if (LINKER_SEARCH_SYMBOL(lf, value, &es, &diff) != 0)
1024 			continue;
1025 		if (es != 0 && diff < bestdiff) {
1026 			best = es;
1027 			bestdiff = diff;
1028 		}
1029 		if (bestdiff == 0)
1030 			break;
1031 	}
1032 	if (best) {
1033 		*sym = best;
1034 		*diffp = bestdiff;
1035 		return (0);
1036 	} else {
1037 		*sym = 0;
1038 		*diffp = off;
1039 		return (ENOENT);
1040 	}
1041 }
1042 
1043 static int
1044 linker_debug_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
1045 {
1046 	linker_file_t lf;
1047 
1048 	TAILQ_FOREACH(lf, &linker_files, link) {
1049 		if (LINKER_DEBUG_SYMBOL_VALUES(lf, sym, symval) == 0)
1050 			return (0);
1051 	}
1052 	return (ENOENT);
1053 }
1054 
1055 static int
1056 linker_debug_search_symbol_name(caddr_t value, char *buf, u_int buflen,
1057     long *offset)
1058 {
1059 	linker_symval_t symval;
1060 	c_linker_sym_t sym;
1061 	int error;
1062 
1063 	*offset = 0;
1064 	error = linker_debug_search_symbol(value, &sym, offset);
1065 	if (error)
1066 		return (error);
1067 	error = linker_debug_symbol_values(sym, &symval);
1068 	if (error)
1069 		return (error);
1070 	strlcpy(buf, symval.name, buflen);
1071 	return (0);
1072 }
1073 
1074 /*
1075  * DDB Helpers.  DDB has to look across multiple files with their own symbol
1076  * tables and string tables.
1077  *
1078  * Note that we do not obey list locking protocols here.  We really don't need
1079  * DDB to hang because somebody's got the lock held.  We'll take the chance
1080  * that the files list is inconsistent instead.
1081  */
1082 #ifdef DDB
1083 int
1084 linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
1085 {
1086 
1087 	return (linker_debug_lookup(symstr, sym));
1088 }
1089 #endif
1090 
1091 int
1092 linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
1093 {
1094 
1095 	return (linker_debug_search_symbol(value, sym, diffp));
1096 }
1097 
1098 int
1099 linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
1100 {
1101 
1102 	return (linker_debug_symbol_values(sym, symval));
1103 }
1104 
1105 int
1106 linker_ddb_search_symbol_name(caddr_t value, char *buf, u_int buflen,
1107     long *offset)
1108 {
1109 
1110 	return (linker_debug_search_symbol_name(value, buf, buflen, offset));
1111 }
1112 
1113 /*
1114  * stack(9) helper for non-debugging environemnts.  Unlike DDB helpers, we do
1115  * obey locking protocols, and offer a significantly less complex interface.
1116  */
1117 int
1118 linker_search_symbol_name_flags(caddr_t value, char *buf, u_int buflen,
1119     long *offset, int flags)
1120 {
1121 	int error;
1122 
1123 	KASSERT((flags & (M_NOWAIT | M_WAITOK)) != 0 &&
1124 	    (flags & (M_NOWAIT | M_WAITOK)) != (M_NOWAIT | M_WAITOK),
1125 	    ("%s: bad flags: 0x%x", __func__, flags));
1126 
1127 	if (flags & M_NOWAIT) {
1128 		if (!sx_try_slock(&kld_sx))
1129 			return (EWOULDBLOCK);
1130 	} else
1131 		sx_slock(&kld_sx);
1132 
1133 	error = linker_debug_search_symbol_name(value, buf, buflen, offset);
1134 	sx_sunlock(&kld_sx);
1135 	return (error);
1136 }
1137 
1138 int
1139 linker_search_symbol_name(caddr_t value, char *buf, u_int buflen,
1140     long *offset)
1141 {
1142 
1143 	return (linker_search_symbol_name_flags(value, buf, buflen, offset,
1144 	    M_WAITOK));
1145 }
1146 
1147 int
1148 linker_kldload_busy(int flags)
1149 {
1150 	int error;
1151 
1152 	MPASS((flags & ~(LINKER_UB_UNLOCK | LINKER_UB_LOCKED |
1153 	    LINKER_UB_PCATCH)) == 0);
1154 	if ((flags & LINKER_UB_LOCKED) != 0)
1155 		sx_assert(&kld_sx, SA_XLOCKED);
1156 
1157 	if ((flags & LINKER_UB_LOCKED) == 0)
1158 		sx_xlock(&kld_sx);
1159 	while (kld_busy > 0) {
1160 		if (kld_busy_owner == curthread)
1161 			break;
1162 		error = sx_sleep(&kld_busy, &kld_sx,
1163 		    (flags & LINKER_UB_PCATCH) != 0 ? PCATCH : 0,
1164 		    "kldbusy", 0);
1165 		if (error != 0) {
1166 			if ((flags & LINKER_UB_UNLOCK) != 0)
1167 				sx_xunlock(&kld_sx);
1168 			return (error);
1169 		}
1170 	}
1171 	kld_busy++;
1172 	kld_busy_owner = curthread;
1173 	if ((flags & LINKER_UB_UNLOCK) != 0)
1174 		sx_xunlock(&kld_sx);
1175 	return (0);
1176 }
1177 
1178 void
1179 linker_kldload_unbusy(int flags)
1180 {
1181 	MPASS((flags & ~LINKER_UB_LOCKED) == 0);
1182 	if ((flags & LINKER_UB_LOCKED) != 0)
1183 		sx_assert(&kld_sx, SA_XLOCKED);
1184 
1185 	if ((flags & LINKER_UB_LOCKED) == 0)
1186 		sx_xlock(&kld_sx);
1187 	MPASS(kld_busy > 0);
1188 	if (kld_busy_owner != curthread)
1189 		panic("linker_kldload_unbusy done by not owning thread %p",
1190 		    kld_busy_owner);
1191 	kld_busy--;
1192 	if (kld_busy == 0) {
1193 		kld_busy_owner = NULL;
1194 		wakeup(&kld_busy);
1195 	}
1196 	sx_xunlock(&kld_sx);
1197 }
1198 
1199 /*
1200  * Syscalls.
1201  */
1202 int
1203 kern_kldload(struct thread *td, const char *file, int *fileid)
1204 {
1205 	const char *kldname, *modname;
1206 	linker_file_t lf;
1207 	int error;
1208 
1209 	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1210 		return (error);
1211 
1212 	if ((error = priv_check(td, PRIV_KLD_LOAD)) != 0)
1213 		return (error);
1214 
1215 	/*
1216 	 * If file does not contain a qualified name or any dot in it
1217 	 * (kldname.ko, or kldname.ver.ko) treat it as an interface
1218 	 * name.
1219 	 */
1220 	if (strchr(file, '/') || strchr(file, '.')) {
1221 		kldname = file;
1222 		modname = NULL;
1223 	} else {
1224 		kldname = NULL;
1225 		modname = file;
1226 	}
1227 
1228 	error = linker_kldload_busy(LINKER_UB_PCATCH);
1229 	if (error != 0) {
1230 		sx_xunlock(&kld_sx);
1231 		return (error);
1232 	}
1233 
1234 	/*
1235 	 * It is possible that kldloaded module will attach a new ifnet,
1236 	 * so vnet context must be set when this ocurs.
1237 	 */
1238 	CURVNET_SET(TD_TO_VNET(td));
1239 
1240 	error = linker_load_module(kldname, modname, NULL, NULL, &lf);
1241 	CURVNET_RESTORE();
1242 
1243 	if (error == 0) {
1244 		lf->userrefs++;
1245 		if (fileid != NULL)
1246 			*fileid = lf->id;
1247 	}
1248 	linker_kldload_unbusy(LINKER_UB_LOCKED);
1249 	return (error);
1250 }
1251 
1252 int
1253 sys_kldload(struct thread *td, struct kldload_args *uap)
1254 {
1255 	char *pathname = NULL;
1256 	int error, fileid;
1257 
1258 	td->td_retval[0] = -1;
1259 
1260 	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1261 	error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL);
1262 	if (error == 0) {
1263 		error = kern_kldload(td, pathname, &fileid);
1264 		if (error == 0)
1265 			td->td_retval[0] = fileid;
1266 	}
1267 	free(pathname, M_TEMP);
1268 	return (error);
1269 }
1270 
1271 int
1272 kern_kldunload(struct thread *td, int fileid, int flags)
1273 {
1274 	linker_file_t lf;
1275 	int error = 0;
1276 
1277 	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1278 		return (error);
1279 
1280 	if ((error = priv_check(td, PRIV_KLD_UNLOAD)) != 0)
1281 		return (error);
1282 
1283 	error = linker_kldload_busy(LINKER_UB_PCATCH);
1284 	if (error != 0) {
1285 		sx_xunlock(&kld_sx);
1286 		return (error);
1287 	}
1288 
1289 	CURVNET_SET(TD_TO_VNET(td));
1290 	lf = linker_find_file_by_id(fileid);
1291 	if (lf) {
1292 		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
1293 
1294 		if (lf->userrefs == 0) {
1295 			/*
1296 			 * XXX: maybe LINKER_UNLOAD_FORCE should override ?
1297 			 */
1298 			printf("kldunload: attempt to unload file that was"
1299 			    " loaded by the kernel\n");
1300 			error = EBUSY;
1301 		} else if (lf->refs > 1) {
1302 			error = EBUSY;
1303 		} else {
1304 			lf->userrefs--;
1305 			error = linker_file_unload(lf, flags);
1306 			if (error)
1307 				lf->userrefs++;
1308 		}
1309 	} else
1310 		error = ENOENT;
1311 	CURVNET_RESTORE();
1312 	linker_kldload_unbusy(LINKER_UB_LOCKED);
1313 	return (error);
1314 }
1315 
1316 int
1317 sys_kldunload(struct thread *td, struct kldunload_args *uap)
1318 {
1319 
1320 	return (kern_kldunload(td, uap->fileid, LINKER_UNLOAD_NORMAL));
1321 }
1322 
1323 int
1324 sys_kldunloadf(struct thread *td, struct kldunloadf_args *uap)
1325 {
1326 
1327 	if (uap->flags != LINKER_UNLOAD_NORMAL &&
1328 	    uap->flags != LINKER_UNLOAD_FORCE)
1329 		return (EINVAL);
1330 	return (kern_kldunload(td, uap->fileid, uap->flags));
1331 }
1332 
1333 int
1334 sys_kldfind(struct thread *td, struct kldfind_args *uap)
1335 {
1336 	char *pathname;
1337 	const char *filename;
1338 	linker_file_t lf;
1339 	int error;
1340 
1341 #ifdef MAC
1342 	error = mac_kld_check_stat(td->td_ucred);
1343 	if (error)
1344 		return (error);
1345 #endif
1346 
1347 	td->td_retval[0] = -1;
1348 
1349 	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1350 	if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
1351 		goto out;
1352 
1353 	filename = linker_basename(pathname);
1354 	sx_xlock(&kld_sx);
1355 	lf = linker_find_file_by_name(filename);
1356 	if (lf)
1357 		td->td_retval[0] = lf->id;
1358 	else
1359 		error = ENOENT;
1360 	sx_xunlock(&kld_sx);
1361 out:
1362 	free(pathname, M_TEMP);
1363 	return (error);
1364 }
1365 
1366 int
1367 sys_kldnext(struct thread *td, struct kldnext_args *uap)
1368 {
1369 	linker_file_t lf;
1370 	int error = 0;
1371 
1372 #ifdef MAC
1373 	error = mac_kld_check_stat(td->td_ucred);
1374 	if (error)
1375 		return (error);
1376 #endif
1377 
1378 	sx_xlock(&kld_sx);
1379 	if (uap->fileid == 0)
1380 		lf = TAILQ_FIRST(&linker_files);
1381 	else {
1382 		lf = linker_find_file_by_id(uap->fileid);
1383 		if (lf == NULL) {
1384 			error = ENOENT;
1385 			goto out;
1386 		}
1387 		lf = TAILQ_NEXT(lf, link);
1388 	}
1389 
1390 	/* Skip partially loaded files. */
1391 	while (lf != NULL && !(lf->flags & LINKER_FILE_LINKED))
1392 		lf = TAILQ_NEXT(lf, link);
1393 
1394 	if (lf)
1395 		td->td_retval[0] = lf->id;
1396 	else
1397 		td->td_retval[0] = 0;
1398 out:
1399 	sx_xunlock(&kld_sx);
1400 	return (error);
1401 }
1402 
1403 int
1404 sys_kldstat(struct thread *td, struct kldstat_args *uap)
1405 {
1406 	struct kld_file_stat *stat;
1407 	int error, version;
1408 
1409 	/*
1410 	 * Check the version of the user's structure.
1411 	 */
1412 	if ((error = copyin(&uap->stat->version, &version, sizeof(version)))
1413 	    != 0)
1414 		return (error);
1415 	if (version != sizeof(struct kld_file_stat_1) &&
1416 	    version != sizeof(struct kld_file_stat))
1417 		return (EINVAL);
1418 
1419 	stat = malloc(sizeof(*stat), M_TEMP, M_WAITOK | M_ZERO);
1420 	error = kern_kldstat(td, uap->fileid, stat);
1421 	if (error == 0)
1422 		error = copyout(stat, uap->stat, version);
1423 	free(stat, M_TEMP);
1424 	return (error);
1425 }
1426 
1427 int
1428 kern_kldstat(struct thread *td, int fileid, struct kld_file_stat *stat)
1429 {
1430 	linker_file_t lf;
1431 	int namelen;
1432 #ifdef MAC
1433 	int error;
1434 
1435 	error = mac_kld_check_stat(td->td_ucred);
1436 	if (error)
1437 		return (error);
1438 #endif
1439 
1440 	sx_xlock(&kld_sx);
1441 	lf = linker_find_file_by_id(fileid);
1442 	if (lf == NULL) {
1443 		sx_xunlock(&kld_sx);
1444 		return (ENOENT);
1445 	}
1446 
1447 	/* Version 1 fields: */
1448 	namelen = strlen(lf->filename) + 1;
1449 	if (namelen > sizeof(stat->name))
1450 		namelen = sizeof(stat->name);
1451 	bcopy(lf->filename, &stat->name[0], namelen);
1452 	stat->refs = lf->refs;
1453 	stat->id = lf->id;
1454 	stat->address = lf->address;
1455 	stat->size = lf->size;
1456 	/* Version 2 fields: */
1457 	namelen = strlen(lf->pathname) + 1;
1458 	if (namelen > sizeof(stat->pathname))
1459 		namelen = sizeof(stat->pathname);
1460 	bcopy(lf->pathname, &stat->pathname[0], namelen);
1461 	sx_xunlock(&kld_sx);
1462 
1463 	td->td_retval[0] = 0;
1464 	return (0);
1465 }
1466 
1467 #ifdef DDB
1468 DB_COMMAND_FLAGS(kldstat, db_kldstat, DB_CMD_MEMSAFE)
1469 {
1470 	linker_file_t lf;
1471 
1472 #define	POINTER_WIDTH	((int)(sizeof(void *) * 2 + 2))
1473 	db_printf("Id Refs Address%*c Size     Name\n", POINTER_WIDTH - 7, ' ');
1474 #undef	POINTER_WIDTH
1475 	TAILQ_FOREACH(lf, &linker_files, link) {
1476 		if (db_pager_quit)
1477 			return;
1478 		db_printf("%2d %4d %p %-8zx %s\n", lf->id, lf->refs,
1479 		    lf->address, lf->size, lf->filename);
1480 	}
1481 }
1482 #endif /* DDB */
1483 
1484 int
1485 sys_kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
1486 {
1487 	linker_file_t lf;
1488 	module_t mp;
1489 	int error = 0;
1490 
1491 #ifdef MAC
1492 	error = mac_kld_check_stat(td->td_ucred);
1493 	if (error)
1494 		return (error);
1495 #endif
1496 
1497 	sx_xlock(&kld_sx);
1498 	lf = linker_find_file_by_id(uap->fileid);
1499 	if (lf) {
1500 		MOD_SLOCK;
1501 		mp = TAILQ_FIRST(&lf->modules);
1502 		if (mp != NULL)
1503 			td->td_retval[0] = module_getid(mp);
1504 		else
1505 			td->td_retval[0] = 0;
1506 		MOD_SUNLOCK;
1507 	} else
1508 		error = ENOENT;
1509 	sx_xunlock(&kld_sx);
1510 	return (error);
1511 }
1512 
1513 int
1514 sys_kldsym(struct thread *td, struct kldsym_args *uap)
1515 {
1516 	char *symstr = NULL;
1517 	c_linker_sym_t sym;
1518 	linker_symval_t symval;
1519 	linker_file_t lf;
1520 	struct kld_sym_lookup lookup;
1521 	int error = 0;
1522 
1523 #ifdef MAC
1524 	error = mac_kld_check_stat(td->td_ucred);
1525 	if (error)
1526 		return (error);
1527 #endif
1528 
1529 	if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
1530 		return (error);
1531 	if (lookup.version != sizeof(lookup) ||
1532 	    uap->cmd != KLDSYM_LOOKUP)
1533 		return (EINVAL);
1534 	symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1535 	if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
1536 		goto out;
1537 	sx_xlock(&kld_sx);
1538 	if (uap->fileid != 0) {
1539 		lf = linker_find_file_by_id(uap->fileid);
1540 		if (lf == NULL)
1541 			error = ENOENT;
1542 		else if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1543 		    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1544 			lookup.symvalue = (uintptr_t) symval.value;
1545 			lookup.symsize = symval.size;
1546 			error = copyout(&lookup, uap->data, sizeof(lookup));
1547 		} else
1548 			error = ENOENT;
1549 	} else {
1550 		TAILQ_FOREACH(lf, &linker_files, link) {
1551 			if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1552 			    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1553 				lookup.symvalue = (uintptr_t)symval.value;
1554 				lookup.symsize = symval.size;
1555 				error = copyout(&lookup, uap->data,
1556 				    sizeof(lookup));
1557 				break;
1558 			}
1559 		}
1560 		if (lf == NULL)
1561 			error = ENOENT;
1562 	}
1563 	sx_xunlock(&kld_sx);
1564 out:
1565 	free(symstr, M_TEMP);
1566 	return (error);
1567 }
1568 
1569 /*
1570  * Preloaded module support
1571  */
1572 
1573 static modlist_t
1574 modlist_lookup(const char *name, int ver)
1575 {
1576 	modlist_t mod;
1577 
1578 	TAILQ_FOREACH(mod, &found_modules, link) {
1579 		if (strcmp(mod->name, name) == 0 &&
1580 		    (ver == 0 || mod->version == ver))
1581 			return (mod);
1582 	}
1583 	return (NULL);
1584 }
1585 
1586 static modlist_t
1587 modlist_lookup2(const char *name, const struct mod_depend *verinfo)
1588 {
1589 	modlist_t mod, bestmod;
1590 	int ver;
1591 
1592 	if (verinfo == NULL)
1593 		return (modlist_lookup(name, 0));
1594 	bestmod = NULL;
1595 	TAILQ_FOREACH(mod, &found_modules, link) {
1596 		if (strcmp(mod->name, name) != 0)
1597 			continue;
1598 		ver = mod->version;
1599 		if (ver == verinfo->md_ver_preferred)
1600 			return (mod);
1601 		if (ver >= verinfo->md_ver_minimum &&
1602 		    ver <= verinfo->md_ver_maximum &&
1603 		    (bestmod == NULL || ver > bestmod->version))
1604 			bestmod = mod;
1605 	}
1606 	return (bestmod);
1607 }
1608 
1609 static modlist_t
1610 modlist_newmodule(const char *modname, int version, linker_file_t container)
1611 {
1612 	modlist_t mod;
1613 
1614 	mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1615 	if (mod == NULL)
1616 		panic("no memory for module list");
1617 	mod->container = container;
1618 	mod->name = modname;
1619 	mod->version = version;
1620 	TAILQ_INSERT_TAIL(&found_modules, mod, link);
1621 	return (mod);
1622 }
1623 
1624 static void
1625 linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1626     struct mod_metadata **stop, int preload)
1627 {
1628 	struct mod_metadata *mp, **mdp;
1629 	const char *modname;
1630 	int ver;
1631 
1632 	for (mdp = start; mdp < stop; mdp++) {
1633 		mp = *mdp;
1634 		if (mp->md_type != MDT_VERSION)
1635 			continue;
1636 		modname = mp->md_cval;
1637 		ver = ((const struct mod_version *)mp->md_data)->mv_version;
1638 		if (modlist_lookup(modname, ver) != NULL) {
1639 			printf("module %s already present!\n", modname);
1640 			/* XXX what can we do? this is a build error. :-( */
1641 			continue;
1642 		}
1643 		modlist_newmodule(modname, ver, lf);
1644 	}
1645 }
1646 
1647 static void
1648 linker_preload(void *arg)
1649 {
1650 	caddr_t modptr;
1651 	const char *modname, *nmodname;
1652 	char *modtype;
1653 	linker_file_t lf, nlf;
1654 	linker_class_t lc;
1655 	int error;
1656 	linker_file_list_t loaded_files;
1657 	linker_file_list_t depended_files;
1658 	struct mod_metadata *mp, *nmp;
1659 	struct mod_metadata **start, **stop, **mdp, **nmdp;
1660 	const struct mod_depend *verinfo;
1661 	int nver;
1662 	int resolves;
1663 	modlist_t mod;
1664 	struct sysinit **si_start, **si_stop;
1665 
1666 	TAILQ_INIT(&loaded_files);
1667 	TAILQ_INIT(&depended_files);
1668 	TAILQ_INIT(&found_modules);
1669 	error = 0;
1670 
1671 	modptr = NULL;
1672 	sx_xlock(&kld_sx);
1673 	while ((modptr = preload_search_next_name(modptr)) != NULL) {
1674 		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1675 		modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1676 		if (modname == NULL) {
1677 			printf("Preloaded module at %p does not have a"
1678 			    " name!\n", modptr);
1679 			continue;
1680 		}
1681 		if (modtype == NULL) {
1682 			printf("Preloaded module at %p does not have a type!\n",
1683 			    modptr);
1684 			continue;
1685 		}
1686 		if (bootverbose)
1687 			printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1688 			    modptr);
1689 		lf = NULL;
1690 		TAILQ_FOREACH(lc, &classes, link) {
1691 			error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1692 			if (!error)
1693 				break;
1694 			lf = NULL;
1695 		}
1696 		if (lf)
1697 			TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1698 	}
1699 
1700 	/*
1701 	 * First get a list of stuff in the kernel.
1702 	 */
1703 	if (linker_file_lookup_set(linker_kernel_file, MDT_SETNAME, &start,
1704 	    &stop, NULL) == 0)
1705 		linker_addmodules(linker_kernel_file, start, stop, 1);
1706 
1707 	/*
1708 	 * This is a once-off kinky bubble sort to resolve relocation
1709 	 * dependency requirements.
1710 	 */
1711 restart:
1712 	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1713 		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1714 		    &stop, NULL);
1715 		/*
1716 		 * First, look to see if we would successfully link with this
1717 		 * stuff.
1718 		 */
1719 		resolves = 1;	/* unless we know otherwise */
1720 		if (!error) {
1721 			for (mdp = start; mdp < stop; mdp++) {
1722 				mp = *mdp;
1723 				if (mp->md_type != MDT_DEPEND)
1724 					continue;
1725 				modname = mp->md_cval;
1726 				verinfo = mp->md_data;
1727 				for (nmdp = start; nmdp < stop; nmdp++) {
1728 					nmp = *nmdp;
1729 					if (nmp->md_type != MDT_VERSION)
1730 						continue;
1731 					nmodname = nmp->md_cval;
1732 					if (strcmp(modname, nmodname) == 0)
1733 						break;
1734 				}
1735 				if (nmdp < stop)   /* it's a self reference */
1736 					continue;
1737 
1738 				/*
1739 				 * ok, the module isn't here yet, we
1740 				 * are not finished
1741 				 */
1742 				if (modlist_lookup2(modname, verinfo) == NULL)
1743 					resolves = 0;
1744 			}
1745 		}
1746 		/*
1747 		 * OK, if we found our modules, we can link.  So, "provide"
1748 		 * the modules inside and add it to the end of the link order
1749 		 * list.
1750 		 */
1751 		if (resolves) {
1752 			if (!error) {
1753 				for (mdp = start; mdp < stop; mdp++) {
1754 					mp = *mdp;
1755 					if (mp->md_type != MDT_VERSION)
1756 						continue;
1757 					modname = mp->md_cval;
1758 					nver = ((const struct mod_version *)
1759 					    mp->md_data)->mv_version;
1760 					if (modlist_lookup(modname,
1761 					    nver) != NULL) {
1762 						printf("module %s already"
1763 						    " present!\n", modname);
1764 						TAILQ_REMOVE(&loaded_files,
1765 						    lf, loaded);
1766 						linker_file_unload(lf,
1767 						    LINKER_UNLOAD_FORCE);
1768 						/* we changed tailq next ptr */
1769 						goto restart;
1770 					}
1771 					modlist_newmodule(modname, nver, lf);
1772 				}
1773 			}
1774 			TAILQ_REMOVE(&loaded_files, lf, loaded);
1775 			TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1776 			/*
1777 			 * Since we provided modules, we need to restart the
1778 			 * sort so that the previous files that depend on us
1779 			 * have a chance. Also, we've busted the tailq next
1780 			 * pointer with the REMOVE.
1781 			 */
1782 			goto restart;
1783 		}
1784 	}
1785 
1786 	/*
1787 	 * At this point, we check to see what could not be resolved..
1788 	 */
1789 	while ((lf = TAILQ_FIRST(&loaded_files)) != NULL) {
1790 		TAILQ_REMOVE(&loaded_files, lf, loaded);
1791 		printf("KLD file %s is missing dependencies\n", lf->filename);
1792 		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1793 	}
1794 
1795 	/*
1796 	 * We made it. Finish off the linking in the order we determined.
1797 	 */
1798 	TAILQ_FOREACH_SAFE(lf, &depended_files, loaded, nlf) {
1799 		if (linker_kernel_file) {
1800 			linker_kernel_file->refs++;
1801 			linker_file_add_dependency(lf, linker_kernel_file);
1802 		}
1803 		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1804 		    &stop, NULL);
1805 		if (!error) {
1806 			for (mdp = start; mdp < stop; mdp++) {
1807 				mp = *mdp;
1808 				if (mp->md_type != MDT_DEPEND)
1809 					continue;
1810 				modname = mp->md_cval;
1811 				verinfo = mp->md_data;
1812 				mod = modlist_lookup2(modname, verinfo);
1813 				if (mod == NULL) {
1814 					printf("KLD file %s - cannot find "
1815 					    "dependency \"%s\"\n",
1816 					    lf->filename, modname);
1817 					goto fail;
1818 				}
1819 				/* Don't count self-dependencies */
1820 				if (lf == mod->container)
1821 					continue;
1822 				mod->container->refs++;
1823 				linker_file_add_dependency(lf, mod->container);
1824 			}
1825 		}
1826 		/*
1827 		 * Now do relocation etc using the symbol search paths
1828 		 * established by the dependencies
1829 		 */
1830 		error = LINKER_LINK_PRELOAD_FINISH(lf);
1831 		if (error) {
1832 			printf("KLD file %s - could not finalize loading\n",
1833 			    lf->filename);
1834 			goto fail;
1835 		}
1836 		linker_file_register_modules(lf);
1837 		if (!TAILQ_EMPTY(&lf->modules))
1838 			lf->flags |= LINKER_FILE_MODULES;
1839 		if (linker_file_lookup_set(lf, "sysinit_set", &si_start,
1840 		    &si_stop, NULL) == 0)
1841 			sysinit_add(si_start, si_stop);
1842 		linker_file_register_sysctls(lf, true);
1843 		lf->flags |= LINKER_FILE_LINKED;
1844 		continue;
1845 fail:
1846 		TAILQ_REMOVE(&depended_files, lf, loaded);
1847 		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1848 	}
1849 	sx_xunlock(&kld_sx);
1850 	/* woohoo! we made it! */
1851 }
1852 SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, NULL);
1853 
1854 static void
1855 linker_mountroot(void *arg __unused)
1856 {
1857 	linker_file_t lf;
1858 
1859 	sx_xlock(&kld_sx);
1860 	TAILQ_FOREACH (lf, &linker_files, link) {
1861 		linker_ctf_load_file(lf);
1862 	}
1863 	sx_xunlock(&kld_sx);
1864 }
1865 EVENTHANDLER_DEFINE(mountroot, linker_mountroot, NULL, 0);
1866 
1867 /*
1868  * Handle preload files that failed to load any modules.
1869  */
1870 static void
1871 linker_preload_finish(void *arg)
1872 {
1873 	linker_file_t lf, nlf;
1874 
1875 	sx_xlock(&kld_sx);
1876 	TAILQ_FOREACH_SAFE(lf, &linker_files, link, nlf) {
1877 		if (lf == linker_kernel_file)
1878 			continue;
1879 
1880 		/*
1881 		 * If all of the modules in this file failed to load, unload
1882 		 * the file and return an error of ENOEXEC.  (Parity with
1883 		 * linker_load_file.)
1884 		 */
1885 		if ((lf->flags & LINKER_FILE_MODULES) != 0 &&
1886 		    TAILQ_EMPTY(&lf->modules)) {
1887 			linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1888 			continue;
1889 		}
1890 
1891 		lf->flags &= ~LINKER_FILE_MODULES;
1892 		lf->userrefs++;	/* so we can (try to) kldunload it */
1893 	}
1894 	sx_xunlock(&kld_sx);
1895 }
1896 
1897 /*
1898  * Attempt to run after all DECLARE_MODULE SYSINITs.  Unfortunately they can be
1899  * scheduled at any subsystem and order, so run this as late as possible.  init
1900  * becomes runnable in SI_SUB_KTHREAD_INIT, so go slightly before that.
1901  */
1902 SYSINIT(preload_finish, SI_SUB_KTHREAD_INIT - 100, SI_ORDER_MIDDLE,
1903     linker_preload_finish, NULL);
1904 
1905 /*
1906  * Search for a not-loaded module by name.
1907  *
1908  * Modules may be found in the following locations:
1909  *
1910  * - preloaded (result is just the module name) - on disk (result is full path
1911  * to module)
1912  *
1913  * If the module name is qualified in any way (contains path, etc.) the we
1914  * simply return a copy of it.
1915  *
1916  * The search path can be manipulated via sysctl.  Note that we use the ';'
1917  * character as a separator to be consistent with the bootloader.
1918  */
1919 
1920 static char linker_hintfile[] = "linker.hints";
1921 static char linker_path[MAXPATHLEN] = "/boot/kernel;/boot/modules";
1922 
1923 SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RWTUN, linker_path,
1924     sizeof(linker_path), "module load search path");
1925 
1926 TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1927 
1928 static const char * const linker_ext_list[] = {
1929 	"",
1930 	".ko",
1931 	NULL
1932 };
1933 
1934 /*
1935  * Check if file actually exists either with or without extension listed in
1936  * the linker_ext_list. (probably should be generic for the rest of the
1937  * kernel)
1938  */
1939 static char *
1940 linker_lookup_file(const char *path, int pathlen, const char *name,
1941     int namelen, struct vattr *vap)
1942 {
1943 	struct nameidata nd;
1944 	struct thread *td = curthread;	/* XXX */
1945 	const char * const *cpp, *sep;
1946 	char *result;
1947 	int error, len, extlen, reclen, flags;
1948 	__enum_uint8(vtype) type;
1949 
1950 	extlen = 0;
1951 	for (cpp = linker_ext_list; *cpp; cpp++) {
1952 		len = strlen(*cpp);
1953 		if (len > extlen)
1954 			extlen = len;
1955 	}
1956 	extlen++;		/* trailing '\0' */
1957 	sep = (path[pathlen - 1] != '/') ? "/" : "";
1958 
1959 	reclen = pathlen + strlen(sep) + namelen + extlen + 1;
1960 	result = malloc(reclen, M_LINKER, M_WAITOK);
1961 	for (cpp = linker_ext_list; *cpp; cpp++) {
1962 		snprintf(result, reclen, "%.*s%s%.*s%s", pathlen, path, sep,
1963 		    namelen, name, *cpp);
1964 		/*
1965 		 * Attempt to open the file, and return the path if
1966 		 * we succeed and it's a regular file.
1967 		 */
1968 		NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, result);
1969 		flags = FREAD;
1970 		error = vn_open(&nd, &flags, 0, NULL);
1971 		if (error == 0) {
1972 			NDFREE_PNBUF(&nd);
1973 			type = nd.ni_vp->v_type;
1974 			if (vap)
1975 				VOP_GETATTR(nd.ni_vp, vap, td->td_ucred);
1976 			VOP_UNLOCK(nd.ni_vp);
1977 			vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1978 			if (type == VREG)
1979 				return (result);
1980 		}
1981 	}
1982 	free(result, M_LINKER);
1983 	return (NULL);
1984 }
1985 
1986 #define	INT_ALIGN(base, ptr)	ptr =					\
1987 	(base) + roundup2((ptr) - (base), sizeof(int))
1988 
1989 /*
1990  * Lookup KLD which contains requested module in the "linker.hints" file. If
1991  * version specification is available, then try to find the best KLD.
1992  * Otherwise just find the latest one.
1993  */
1994 static char *
1995 linker_hints_lookup(const char *path, int pathlen, const char *modname,
1996     int modnamelen, const struct mod_depend *verinfo)
1997 {
1998 	struct thread *td = curthread;	/* XXX */
1999 	struct ucred *cred = td ? td->td_ucred : NULL;
2000 	struct nameidata nd;
2001 	struct vattr vattr, mattr;
2002 	const char *best, *sep;
2003 	u_char *hints = NULL;
2004 	u_char *cp, *recptr, *bufend, *result, *pathbuf;
2005 	int error, ival, bestver, *intp, found, flags, clen, blen;
2006 	ssize_t reclen;
2007 
2008 	result = NULL;
2009 	bestver = found = 0;
2010 
2011 	sep = (path[pathlen - 1] != '/') ? "/" : "";
2012 	reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
2013 	    strlen(sep) + 1;
2014 	pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
2015 	snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
2016 	    linker_hintfile);
2017 
2018 	NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, pathbuf);
2019 	flags = FREAD;
2020 	error = vn_open(&nd, &flags, 0, NULL);
2021 	if (error)
2022 		goto bad;
2023 	NDFREE_PNBUF(&nd);
2024 	if (nd.ni_vp->v_type != VREG)
2025 		goto bad;
2026 	best = cp = NULL;
2027 	error = VOP_GETATTR(nd.ni_vp, &vattr, cred);
2028 	if (error)
2029 		goto bad;
2030 	/*
2031 	 * XXX: we need to limit this number to some reasonable value
2032 	 */
2033 	if (vattr.va_size > LINKER_HINTS_MAX) {
2034 		printf("linker.hints file too large %ld\n", (long)vattr.va_size);
2035 		goto bad;
2036 	}
2037 	if (vattr.va_size < sizeof(ival)) {
2038 		printf("linker.hints file truncated\n");
2039 		goto bad;
2040 	}
2041 	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
2042 	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
2043 	    UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &reclen, td);
2044 	if (error)
2045 		goto bad;
2046 	VOP_UNLOCK(nd.ni_vp);
2047 	vn_close(nd.ni_vp, FREAD, cred, td);
2048 	nd.ni_vp = NULL;
2049 	if (reclen != 0) {
2050 		printf("can't read %zd\n", reclen);
2051 		goto bad;
2052 	}
2053 	intp = (int *)hints;
2054 	ival = *intp++;
2055 	if (ival != LINKER_HINTS_VERSION) {
2056 		printf("linker.hints file version mismatch %d\n", ival);
2057 		goto bad;
2058 	}
2059 	bufend = hints + vattr.va_size;
2060 	recptr = (u_char *)intp;
2061 	clen = blen = 0;
2062 	while (recptr < bufend && !found) {
2063 		intp = (int *)recptr;
2064 		reclen = *intp++;
2065 		ival = *intp++;
2066 		cp = (char *)intp;
2067 		switch (ival) {
2068 		case MDT_VERSION:
2069 			clen = *cp++;
2070 			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
2071 				break;
2072 			cp += clen;
2073 			INT_ALIGN(hints, cp);
2074 			ival = *(int *)cp;
2075 			cp += sizeof(int);
2076 			clen = *cp++;
2077 			if (verinfo == NULL ||
2078 			    ival == verinfo->md_ver_preferred) {
2079 				found = 1;
2080 				break;
2081 			}
2082 			if (ival >= verinfo->md_ver_minimum &&
2083 			    ival <= verinfo->md_ver_maximum &&
2084 			    ival > bestver) {
2085 				bestver = ival;
2086 				best = cp;
2087 				blen = clen;
2088 			}
2089 			break;
2090 		default:
2091 			break;
2092 		}
2093 		recptr += reclen + sizeof(int);
2094 	}
2095 	/*
2096 	 * Finally check if KLD is in the place
2097 	 */
2098 	if (found)
2099 		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
2100 	else if (best)
2101 		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
2102 
2103 	/*
2104 	 * KLD is newer than hints file. What we should do now?
2105 	 */
2106 	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
2107 		printf("warning: KLD '%s' is newer than the linker.hints"
2108 		    " file\n", result);
2109 bad:
2110 	free(pathbuf, M_LINKER);
2111 	if (hints)
2112 		free(hints, M_TEMP);
2113 	if (nd.ni_vp != NULL) {
2114 		VOP_UNLOCK(nd.ni_vp);
2115 		vn_close(nd.ni_vp, FREAD, cred, td);
2116 	}
2117 	/*
2118 	 * If nothing found or hints is absent - fallback to the old
2119 	 * way by using "kldname[.ko]" as module name.
2120 	 */
2121 	if (!found && !bestver && result == NULL)
2122 		result = linker_lookup_file(path, pathlen, modname,
2123 		    modnamelen, NULL);
2124 	return (result);
2125 }
2126 
2127 /*
2128  * Lookup KLD which contains requested module in the all directories.
2129  */
2130 static char *
2131 linker_search_module(const char *modname, int modnamelen,
2132     const struct mod_depend *verinfo)
2133 {
2134 	char *cp, *ep, *result;
2135 
2136 	/*
2137 	 * traverse the linker path
2138 	 */
2139 	for (cp = linker_path; *cp; cp = ep + 1) {
2140 		/* find the end of this component */
2141 		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
2142 		result = linker_hints_lookup(cp, ep - cp, modname,
2143 		    modnamelen, verinfo);
2144 		if (result != NULL)
2145 			return (result);
2146 		if (*ep == 0)
2147 			break;
2148 	}
2149 	return (NULL);
2150 }
2151 
2152 /*
2153  * Search for module in all directories listed in the linker_path.
2154  */
2155 static char *
2156 linker_search_kld(const char *name)
2157 {
2158 	char *cp, *ep, *result;
2159 	int len;
2160 
2161 	/* qualified at all? */
2162 	if (strchr(name, '/'))
2163 		return (strdup(name, M_LINKER));
2164 
2165 	/* traverse the linker path */
2166 	len = strlen(name);
2167 	for (ep = linker_path; *ep; ep++) {
2168 		cp = ep;
2169 		/* find the end of this component */
2170 		for (; *ep != 0 && *ep != ';'; ep++);
2171 		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
2172 		if (result != NULL)
2173 			return (result);
2174 	}
2175 	return (NULL);
2176 }
2177 
2178 static const char *
2179 linker_basename(const char *path)
2180 {
2181 	const char *filename;
2182 
2183 	filename = strrchr(path, '/');
2184 	if (filename == NULL)
2185 		return path;
2186 	if (filename[1])
2187 		filename++;
2188 	return (filename);
2189 }
2190 
2191 #if defined(HWPMC_HOOKS) || defined(HWT_HOOKS)
2192 /*
2193  * Inform hwpmc about the set of kernel modules currently loaded.
2194  */
2195 void *
2196 linker_hwpmc_list_objects(void)
2197 {
2198 	linker_file_t lf;
2199 	struct pmckern_map_in *kobase;
2200 	int i, nmappings;
2201 
2202 	nmappings = 0;
2203 	sx_slock(&kld_sx);
2204 	TAILQ_FOREACH(lf, &linker_files, link)
2205 		nmappings++;
2206 
2207 	/* Allocate nmappings + 1 entries. */
2208 	kobase = malloc((nmappings + 1) * sizeof(struct pmckern_map_in),
2209 	    M_LINKER, M_WAITOK | M_ZERO);
2210 	i = 0;
2211 	TAILQ_FOREACH(lf, &linker_files, link) {
2212 		/* Save the info for this linker file. */
2213 		kobase[i].pm_file = lf->pathname;
2214 		kobase[i].pm_address = (uintptr_t)lf->address;
2215 		i++;
2216 	}
2217 	sx_sunlock(&kld_sx);
2218 
2219 	KASSERT(i > 0, ("linker_hpwmc_list_objects: no kernel objects?"));
2220 
2221 	/* The last entry of the malloced area comprises of all zeros. */
2222 	KASSERT(kobase[i].pm_file == NULL,
2223 	    ("linker_hwpmc_list_objects: last object not NULL"));
2224 
2225 	return ((void *)kobase);
2226 }
2227 #endif
2228 
2229 /* check if root file system is not mounted */
2230 static bool
2231 linker_root_mounted(void)
2232 {
2233 	struct pwd *pwd;
2234 	bool ret;
2235 
2236 	if (rootvnode == NULL)
2237 		return (false);
2238 
2239 	pwd = pwd_hold(curthread);
2240 	ret = pwd->pwd_rdir != NULL;
2241 	pwd_drop(pwd);
2242 	return (ret);
2243 }
2244 
2245 /*
2246  * Find a file which contains given module and load it, if "parent" is not
2247  * NULL, register a reference to it.
2248  */
2249 static int
2250 linker_load_module(const char *kldname, const char *modname,
2251     struct linker_file *parent, const struct mod_depend *verinfo,
2252     struct linker_file **lfpp)
2253 {
2254 	linker_file_t lfdep;
2255 	const char *filename;
2256 	char *pathname;
2257 	int error;
2258 
2259 	sx_assert(&kld_sx, SA_XLOCKED);
2260 	if (modname == NULL) {
2261 		/*
2262  		 * We have to load KLD
2263  		 */
2264 		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
2265 		    " is not NULL"));
2266 		if (!linker_root_mounted())
2267 			return (ENXIO);
2268 		pathname = linker_search_kld(kldname);
2269 	} else {
2270 		if (modlist_lookup2(modname, verinfo) != NULL)
2271 			return (EEXIST);
2272 		if (!linker_root_mounted())
2273 			return (ENXIO);
2274 		if (kldname != NULL)
2275 			pathname = strdup(kldname, M_LINKER);
2276 		else
2277 			/*
2278 			 * Need to find a KLD with required module
2279 			 */
2280 			pathname = linker_search_module(modname,
2281 			    strlen(modname), verinfo);
2282 	}
2283 	if (pathname == NULL)
2284 		return (ENOENT);
2285 
2286 	/*
2287 	 * Can't load more than one file with the same basename XXX:
2288 	 * Actually it should be possible to have multiple KLDs with
2289 	 * the same basename but different path because they can
2290 	 * provide different versions of the same modules.
2291 	 */
2292 	filename = linker_basename(pathname);
2293 	if (linker_find_file_by_name(filename))
2294 		error = EEXIST;
2295 	else do {
2296 		error = linker_load_file(pathname, &lfdep);
2297 		if (error)
2298 			break;
2299 		if (modname && verinfo &&
2300 		    modlist_lookup2(modname, verinfo) == NULL) {
2301 			linker_file_unload(lfdep, LINKER_UNLOAD_FORCE);
2302 			error = ENOENT;
2303 			break;
2304 		}
2305 		if (parent)
2306 			linker_file_add_dependency(parent, lfdep);
2307 		if (lfpp)
2308 			*lfpp = lfdep;
2309 	} while (0);
2310 	free(pathname, M_LINKER);
2311 	return (error);
2312 }
2313 
2314 /*
2315  * This routine is responsible for finding dependencies of userland initiated
2316  * kldload(2)'s of files.
2317  */
2318 int
2319 linker_load_dependencies(linker_file_t lf)
2320 {
2321 	linker_file_t lfdep;
2322 	struct mod_metadata **start, **stop, **mdp, **nmdp;
2323 	struct mod_metadata *mp, *nmp;
2324 	const struct mod_depend *verinfo;
2325 	modlist_t mod;
2326 	const char *modname, *nmodname;
2327 	int ver, error = 0;
2328 
2329 	/*
2330 	 * All files are dependent on /kernel.
2331 	 */
2332 	sx_assert(&kld_sx, SA_XLOCKED);
2333 	if (linker_kernel_file) {
2334 		linker_kernel_file->refs++;
2335 		linker_file_add_dependency(lf, linker_kernel_file);
2336 	}
2337 	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
2338 	    NULL) != 0)
2339 		return (0);
2340 	for (mdp = start; mdp < stop; mdp++) {
2341 		mp = *mdp;
2342 		if (mp->md_type != MDT_VERSION)
2343 			continue;
2344 		modname = mp->md_cval;
2345 		ver = ((const struct mod_version *)mp->md_data)->mv_version;
2346 		mod = modlist_lookup(modname, ver);
2347 		if (mod != NULL) {
2348 			printf("interface %s.%d already present in the KLD"
2349 			    " '%s'!\n", modname, ver,
2350 			    mod->container->filename);
2351 			return (EEXIST);
2352 		}
2353 	}
2354 
2355 	for (mdp = start; mdp < stop; mdp++) {
2356 		mp = *mdp;
2357 		if (mp->md_type != MDT_DEPEND)
2358 			continue;
2359 		modname = mp->md_cval;
2360 		verinfo = mp->md_data;
2361 		nmodname = NULL;
2362 		for (nmdp = start; nmdp < stop; nmdp++) {
2363 			nmp = *nmdp;
2364 			if (nmp->md_type != MDT_VERSION)
2365 				continue;
2366 			nmodname = nmp->md_cval;
2367 			if (strcmp(modname, nmodname) == 0)
2368 				break;
2369 		}
2370 		if (nmdp < stop)/* early exit, it's a self reference */
2371 			continue;
2372 		mod = modlist_lookup2(modname, verinfo);
2373 		if (mod) {	/* woohoo, it's loaded already */
2374 			lfdep = mod->container;
2375 			lfdep->refs++;
2376 			linker_file_add_dependency(lf, lfdep);
2377 			continue;
2378 		}
2379 		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
2380 		if (error) {
2381 			printf("KLD %s: depends on %s - not available or"
2382 			    " version mismatch\n", lf->filename, modname);
2383 			break;
2384 		}
2385 	}
2386 
2387 	if (error)
2388 		return (error);
2389 	linker_addmodules(lf, start, stop, 0);
2390 	return (error);
2391 }
2392 
2393 static int
2394 sysctl_kern_function_list_iterate(const char *name, void *opaque)
2395 {
2396 	struct sysctl_req *req;
2397 
2398 	req = opaque;
2399 	return (SYSCTL_OUT(req, name, strlen(name) + 1));
2400 }
2401 
2402 /*
2403  * Export a nul-separated, double-nul-terminated list of all function names
2404  * in the kernel.
2405  */
2406 static int
2407 sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
2408 {
2409 	linker_file_t lf;
2410 	int error;
2411 
2412 #ifdef MAC
2413 	error = mac_kld_check_stat(req->td->td_ucred);
2414 	if (error)
2415 		return (error);
2416 #endif
2417 	error = sysctl_wire_old_buffer(req, 0);
2418 	if (error != 0)
2419 		return (error);
2420 	sx_xlock(&kld_sx);
2421 	TAILQ_FOREACH(lf, &linker_files, link) {
2422 		error = LINKER_EACH_FUNCTION_NAME(lf,
2423 		    sysctl_kern_function_list_iterate, req);
2424 		if (error) {
2425 			sx_xunlock(&kld_sx);
2426 			return (error);
2427 		}
2428 	}
2429 	sx_xunlock(&kld_sx);
2430 	return (SYSCTL_OUT(req, "", 1));
2431 }
2432 
2433 SYSCTL_PROC(_kern, OID_AUTO, function_list,
2434     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
2435     sysctl_kern_function_list, "",
2436     "kernel function list");
2437