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