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