xref: /freebsd/sys/kern/kern_linker.c (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
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 void	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 void
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 }
853 
854 /*
855  * Locate a linker set and its contents.  This is a helper function to avoid
856  * linker_if.h exposure elsewhere.  Note: firstp and lastp are really void **.
857  * This function is used in this file so we can avoid having lots of (void **)
858  * casts.
859  */
860 int
861 linker_file_lookup_set(linker_file_t file, const char *name,
862     void *firstp, void *lastp, int *countp)
863 {
864 
865 	sx_assert(&kld_sx, SA_LOCKED);
866 	return (LINKER_LOOKUP_SET(file, name, firstp, lastp, countp));
867 }
868 
869 /*
870  * List all functions in a file.
871  */
872 int
873 linker_file_function_listall(linker_file_t lf,
874     linker_function_nameval_callback_t callback_func, void *arg)
875 {
876 	return (LINKER_EACH_FUNCTION_NAMEVAL(lf, callback_func, arg));
877 }
878 
879 caddr_t
880 linker_file_lookup_symbol(linker_file_t file, const char *name, int deps)
881 {
882 	caddr_t sym;
883 	int locked;
884 
885 	locked = sx_xlocked(&kld_sx);
886 	if (!locked)
887 		sx_xlock(&kld_sx);
888 	sym = linker_file_lookup_symbol_internal(file, name, deps);
889 	if (!locked)
890 		sx_xunlock(&kld_sx);
891 	return (sym);
892 }
893 
894 static caddr_t
895 linker_file_lookup_symbol_internal(linker_file_t file, const char *name,
896     int deps)
897 {
898 	c_linker_sym_t sym;
899 	linker_symval_t symval;
900 	caddr_t address;
901 	size_t common_size = 0;
902 	int i;
903 
904 	sx_assert(&kld_sx, SA_XLOCKED);
905 	KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%p, name=%s, deps=%d\n",
906 	    file, name, deps));
907 
908 	if (LINKER_LOOKUP_SYMBOL(file, name, &sym) == 0) {
909 		LINKER_SYMBOL_VALUES(file, sym, &symval);
910 		if (symval.value == 0)
911 			/*
912 			 * For commons, first look them up in the
913 			 * dependencies and only allocate space if not found
914 			 * there.
915 			 */
916 			common_size = symval.size;
917 		else {
918 			KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol"
919 			    ".value=%p\n", symval.value));
920 			return (symval.value);
921 		}
922 	}
923 	if (deps) {
924 		for (i = 0; i < file->ndeps; i++) {
925 			address = linker_file_lookup_symbol_internal(
926 			    file->deps[i], name, 0);
927 			if (address) {
928 				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
929 				    " deps value=%p\n", address));
930 				return (address);
931 			}
932 		}
933 	}
934 	if (common_size > 0) {
935 		/*
936 		 * This is a common symbol which was not found in the
937 		 * dependencies.  We maintain a simple common symbol table in
938 		 * the file object.
939 		 */
940 		struct common_symbol *cp;
941 
942 		STAILQ_FOREACH(cp, &file->common, link) {
943 			if (strcmp(cp->name, name) == 0) {
944 				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
945 				    " old common value=%p\n", cp->address));
946 				return (cp->address);
947 			}
948 		}
949 		/*
950 		 * Round the symbol size up to align.
951 		 */
952 		common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
953 		cp = malloc(sizeof(struct common_symbol)
954 		    + common_size + strlen(name) + 1, M_LINKER,
955 		    M_WAITOK | M_ZERO);
956 		cp->address = (caddr_t)(cp + 1);
957 		cp->name = cp->address + common_size;
958 		strcpy(cp->name, name);
959 		bzero(cp->address, common_size);
960 		STAILQ_INSERT_TAIL(&file->common, cp, link);
961 
962 		KLD_DPF(SYM, ("linker_file_lookup_symbol: new common"
963 		    " value=%p\n", cp->address));
964 		return (cp->address);
965 	}
966 	KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
967 	return (0);
968 }
969 
970 /*
971  * Both DDB and stack(9) rely on the kernel linker to provide forward and
972  * backward lookup of symbols.  However, DDB and sometimes stack(9) need to
973  * do this in a lockfree manner.  We provide a set of internal helper
974  * routines to perform these operations without locks, and then wrappers that
975  * optionally lock.
976  *
977  * linker_debug_lookup() is ifdef DDB as currently it's only used by DDB.
978  */
979 #ifdef DDB
980 static int
981 linker_debug_lookup(const char *symstr, c_linker_sym_t *sym)
982 {
983 	linker_file_t lf;
984 
985 	TAILQ_FOREACH(lf, &linker_files, link) {
986 		if (LINKER_LOOKUP_DEBUG_SYMBOL(lf, symstr, sym) == 0)
987 			return (0);
988 	}
989 	return (ENOENT);
990 }
991 #endif
992 
993 static int
994 linker_debug_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
995 {
996 	linker_file_t lf;
997 	c_linker_sym_t best, es;
998 	u_long diff, bestdiff, off;
999 
1000 	best = 0;
1001 	off = (uintptr_t)value;
1002 	bestdiff = off;
1003 	TAILQ_FOREACH(lf, &linker_files, link) {
1004 		if (LINKER_SEARCH_SYMBOL(lf, value, &es, &diff) != 0)
1005 			continue;
1006 		if (es != 0 && diff < bestdiff) {
1007 			best = es;
1008 			bestdiff = diff;
1009 		}
1010 		if (bestdiff == 0)
1011 			break;
1012 	}
1013 	if (best) {
1014 		*sym = best;
1015 		*diffp = bestdiff;
1016 		return (0);
1017 	} else {
1018 		*sym = 0;
1019 		*diffp = off;
1020 		return (ENOENT);
1021 	}
1022 }
1023 
1024 static int
1025 linker_debug_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
1026 {
1027 	linker_file_t lf;
1028 
1029 	TAILQ_FOREACH(lf, &linker_files, link) {
1030 		if (LINKER_DEBUG_SYMBOL_VALUES(lf, sym, symval) == 0)
1031 			return (0);
1032 	}
1033 	return (ENOENT);
1034 }
1035 
1036 static int
1037 linker_debug_search_symbol_name(caddr_t value, char *buf, u_int buflen,
1038     long *offset)
1039 {
1040 	linker_symval_t symval;
1041 	c_linker_sym_t sym;
1042 	int error;
1043 
1044 	*offset = 0;
1045 	error = linker_debug_search_symbol(value, &sym, offset);
1046 	if (error)
1047 		return (error);
1048 	error = linker_debug_symbol_values(sym, &symval);
1049 	if (error)
1050 		return (error);
1051 	strlcpy(buf, symval.name, buflen);
1052 	return (0);
1053 }
1054 
1055 /*
1056  * DDB Helpers.  DDB has to look across multiple files with their own symbol
1057  * tables and string tables.
1058  *
1059  * Note that we do not obey list locking protocols here.  We really don't need
1060  * DDB to hang because somebody's got the lock held.  We'll take the chance
1061  * that the files list is inconsistent instead.
1062  */
1063 #ifdef DDB
1064 int
1065 linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
1066 {
1067 
1068 	return (linker_debug_lookup(symstr, sym));
1069 }
1070 #endif
1071 
1072 int
1073 linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
1074 {
1075 
1076 	return (linker_debug_search_symbol(value, sym, diffp));
1077 }
1078 
1079 int
1080 linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
1081 {
1082 
1083 	return (linker_debug_symbol_values(sym, symval));
1084 }
1085 
1086 int
1087 linker_ddb_search_symbol_name(caddr_t value, char *buf, u_int buflen,
1088     long *offset)
1089 {
1090 
1091 	return (linker_debug_search_symbol_name(value, buf, buflen, offset));
1092 }
1093 
1094 /*
1095  * stack(9) helper for non-debugging environemnts.  Unlike DDB helpers, we do
1096  * obey locking protocols, and offer a significantly less complex interface.
1097  */
1098 int
1099 linker_search_symbol_name_flags(caddr_t value, char *buf, u_int buflen,
1100     long *offset, int flags)
1101 {
1102 	int error;
1103 
1104 	KASSERT((flags & (M_NOWAIT | M_WAITOK)) != 0 &&
1105 	    (flags & (M_NOWAIT | M_WAITOK)) != (M_NOWAIT | M_WAITOK),
1106 	    ("%s: bad flags: 0x%x", __func__, flags));
1107 
1108 	if (flags & M_NOWAIT) {
1109 		if (!sx_try_slock(&kld_sx))
1110 			return (EWOULDBLOCK);
1111 	} else
1112 		sx_slock(&kld_sx);
1113 
1114 	error = linker_debug_search_symbol_name(value, buf, buflen, offset);
1115 	sx_sunlock(&kld_sx);
1116 	return (error);
1117 }
1118 
1119 int
1120 linker_search_symbol_name(caddr_t value, char *buf, u_int buflen,
1121     long *offset)
1122 {
1123 
1124 	return (linker_search_symbol_name_flags(value, buf, buflen, offset,
1125 	    M_WAITOK));
1126 }
1127 
1128 int
1129 linker_kldload_busy(int flags)
1130 {
1131 	int error;
1132 
1133 	MPASS((flags & ~(LINKER_UB_UNLOCK | LINKER_UB_LOCKED |
1134 	    LINKER_UB_PCATCH)) == 0);
1135 	if ((flags & LINKER_UB_LOCKED) != 0)
1136 		sx_assert(&kld_sx, SA_XLOCKED);
1137 
1138 	if ((flags & LINKER_UB_LOCKED) == 0)
1139 		sx_xlock(&kld_sx);
1140 	while (kld_busy > 0) {
1141 		if (kld_busy_owner == curthread)
1142 			break;
1143 		error = sx_sleep(&kld_busy, &kld_sx,
1144 		    (flags & LINKER_UB_PCATCH) != 0 ? PCATCH : 0,
1145 		    "kldbusy", 0);
1146 		if (error != 0) {
1147 			if ((flags & LINKER_UB_UNLOCK) != 0)
1148 				sx_xunlock(&kld_sx);
1149 			return (error);
1150 		}
1151 	}
1152 	kld_busy++;
1153 	kld_busy_owner = curthread;
1154 	if ((flags & LINKER_UB_UNLOCK) != 0)
1155 		sx_xunlock(&kld_sx);
1156 	return (0);
1157 }
1158 
1159 void
1160 linker_kldload_unbusy(int flags)
1161 {
1162 	MPASS((flags & ~LINKER_UB_LOCKED) == 0);
1163 	if ((flags & LINKER_UB_LOCKED) != 0)
1164 		sx_assert(&kld_sx, SA_XLOCKED);
1165 
1166 	if ((flags & LINKER_UB_LOCKED) == 0)
1167 		sx_xlock(&kld_sx);
1168 	MPASS(kld_busy > 0);
1169 	if (kld_busy_owner != curthread)
1170 		panic("linker_kldload_unbusy done by not owning thread %p",
1171 		    kld_busy_owner);
1172 	kld_busy--;
1173 	if (kld_busy == 0) {
1174 		kld_busy_owner = NULL;
1175 		wakeup(&kld_busy);
1176 	}
1177 	sx_xunlock(&kld_sx);
1178 }
1179 
1180 /*
1181  * Syscalls.
1182  */
1183 int
1184 kern_kldload(struct thread *td, const char *file, int *fileid)
1185 {
1186 	const char *kldname, *modname;
1187 	linker_file_t lf;
1188 	int error;
1189 
1190 	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1191 		return (error);
1192 
1193 	if ((error = priv_check(td, PRIV_KLD_LOAD)) != 0)
1194 		return (error);
1195 
1196 	/*
1197 	 * If file does not contain a qualified name or any dot in it
1198 	 * (kldname.ko, or kldname.ver.ko) treat it as an interface
1199 	 * name.
1200 	 */
1201 	if (strchr(file, '/') || strchr(file, '.')) {
1202 		kldname = file;
1203 		modname = NULL;
1204 	} else {
1205 		kldname = NULL;
1206 		modname = file;
1207 	}
1208 
1209 	error = linker_kldload_busy(LINKER_UB_PCATCH);
1210 	if (error != 0) {
1211 		sx_xunlock(&kld_sx);
1212 		return (error);
1213 	}
1214 
1215 	/*
1216 	 * It is possible that kldloaded module will attach a new ifnet,
1217 	 * so vnet context must be set when this ocurs.
1218 	 */
1219 	CURVNET_SET(TD_TO_VNET(td));
1220 
1221 	error = linker_load_module(kldname, modname, NULL, NULL, &lf);
1222 	CURVNET_RESTORE();
1223 
1224 	if (error == 0) {
1225 		lf->userrefs++;
1226 		if (fileid != NULL)
1227 			*fileid = lf->id;
1228 	}
1229 	linker_kldload_unbusy(LINKER_UB_LOCKED);
1230 	return (error);
1231 }
1232 
1233 int
1234 sys_kldload(struct thread *td, struct kldload_args *uap)
1235 {
1236 	char *pathname = NULL;
1237 	int error, fileid;
1238 
1239 	td->td_retval[0] = -1;
1240 
1241 	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1242 	error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL);
1243 	if (error == 0) {
1244 		error = kern_kldload(td, pathname, &fileid);
1245 		if (error == 0)
1246 			td->td_retval[0] = fileid;
1247 	}
1248 	free(pathname, M_TEMP);
1249 	return (error);
1250 }
1251 
1252 int
1253 kern_kldunload(struct thread *td, int fileid, int flags)
1254 {
1255 	linker_file_t lf;
1256 	int error = 0;
1257 
1258 	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1259 		return (error);
1260 
1261 	if ((error = priv_check(td, PRIV_KLD_UNLOAD)) != 0)
1262 		return (error);
1263 
1264 	error = linker_kldload_busy(LINKER_UB_PCATCH);
1265 	if (error != 0) {
1266 		sx_xunlock(&kld_sx);
1267 		return (error);
1268 	}
1269 
1270 	CURVNET_SET(TD_TO_VNET(td));
1271 	lf = linker_find_file_by_id(fileid);
1272 	if (lf) {
1273 		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
1274 
1275 		if (lf->userrefs == 0) {
1276 			/*
1277 			 * XXX: maybe LINKER_UNLOAD_FORCE should override ?
1278 			 */
1279 			printf("kldunload: attempt to unload file that was"
1280 			    " loaded by the kernel\n");
1281 			error = EBUSY;
1282 		} else if (lf->refs > 1) {
1283 			error = EBUSY;
1284 		} else {
1285 			lf->userrefs--;
1286 			error = linker_file_unload(lf, flags);
1287 			if (error)
1288 				lf->userrefs++;
1289 		}
1290 	} else
1291 		error = ENOENT;
1292 	CURVNET_RESTORE();
1293 	linker_kldload_unbusy(LINKER_UB_LOCKED);
1294 	return (error);
1295 }
1296 
1297 int
1298 sys_kldunload(struct thread *td, struct kldunload_args *uap)
1299 {
1300 
1301 	return (kern_kldunload(td, uap->fileid, LINKER_UNLOAD_NORMAL));
1302 }
1303 
1304 int
1305 sys_kldunloadf(struct thread *td, struct kldunloadf_args *uap)
1306 {
1307 
1308 	if (uap->flags != LINKER_UNLOAD_NORMAL &&
1309 	    uap->flags != LINKER_UNLOAD_FORCE)
1310 		return (EINVAL);
1311 	return (kern_kldunload(td, uap->fileid, uap->flags));
1312 }
1313 
1314 int
1315 sys_kldfind(struct thread *td, struct kldfind_args *uap)
1316 {
1317 	char *pathname;
1318 	const char *filename;
1319 	linker_file_t lf;
1320 	int error;
1321 
1322 #ifdef MAC
1323 	error = mac_kld_check_stat(td->td_ucred);
1324 	if (error)
1325 		return (error);
1326 #endif
1327 
1328 	td->td_retval[0] = -1;
1329 
1330 	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1331 	if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
1332 		goto out;
1333 
1334 	filename = linker_basename(pathname);
1335 	sx_xlock(&kld_sx);
1336 	lf = linker_find_file_by_name(filename);
1337 	if (lf)
1338 		td->td_retval[0] = lf->id;
1339 	else
1340 		error = ENOENT;
1341 	sx_xunlock(&kld_sx);
1342 out:
1343 	free(pathname, M_TEMP);
1344 	return (error);
1345 }
1346 
1347 int
1348 sys_kldnext(struct thread *td, struct kldnext_args *uap)
1349 {
1350 	linker_file_t lf;
1351 	int error = 0;
1352 
1353 #ifdef MAC
1354 	error = mac_kld_check_stat(td->td_ucred);
1355 	if (error)
1356 		return (error);
1357 #endif
1358 
1359 	sx_xlock(&kld_sx);
1360 	if (uap->fileid == 0)
1361 		lf = TAILQ_FIRST(&linker_files);
1362 	else {
1363 		lf = linker_find_file_by_id(uap->fileid);
1364 		if (lf == NULL) {
1365 			error = ENOENT;
1366 			goto out;
1367 		}
1368 		lf = TAILQ_NEXT(lf, link);
1369 	}
1370 
1371 	/* Skip partially loaded files. */
1372 	while (lf != NULL && !(lf->flags & LINKER_FILE_LINKED))
1373 		lf = TAILQ_NEXT(lf, link);
1374 
1375 	if (lf)
1376 		td->td_retval[0] = lf->id;
1377 	else
1378 		td->td_retval[0] = 0;
1379 out:
1380 	sx_xunlock(&kld_sx);
1381 	return (error);
1382 }
1383 
1384 int
1385 sys_kldstat(struct thread *td, struct kldstat_args *uap)
1386 {
1387 	struct kld_file_stat *stat;
1388 	int error, version;
1389 
1390 	/*
1391 	 * Check the version of the user's structure.
1392 	 */
1393 	if ((error = copyin(&uap->stat->version, &version, sizeof(version)))
1394 	    != 0)
1395 		return (error);
1396 	if (version != sizeof(struct kld_file_stat_1) &&
1397 	    version != sizeof(struct kld_file_stat))
1398 		return (EINVAL);
1399 
1400 	stat = malloc(sizeof(*stat), M_TEMP, M_WAITOK | M_ZERO);
1401 	error = kern_kldstat(td, uap->fileid, stat);
1402 	if (error == 0)
1403 		error = copyout(stat, uap->stat, version);
1404 	free(stat, M_TEMP);
1405 	return (error);
1406 }
1407 
1408 int
1409 kern_kldstat(struct thread *td, int fileid, struct kld_file_stat *stat)
1410 {
1411 	linker_file_t lf;
1412 	int namelen;
1413 #ifdef MAC
1414 	int error;
1415 
1416 	error = mac_kld_check_stat(td->td_ucred);
1417 	if (error)
1418 		return (error);
1419 #endif
1420 
1421 	sx_xlock(&kld_sx);
1422 	lf = linker_find_file_by_id(fileid);
1423 	if (lf == NULL) {
1424 		sx_xunlock(&kld_sx);
1425 		return (ENOENT);
1426 	}
1427 
1428 	/* Version 1 fields: */
1429 	namelen = strlen(lf->filename) + 1;
1430 	if (namelen > sizeof(stat->name))
1431 		namelen = sizeof(stat->name);
1432 	bcopy(lf->filename, &stat->name[0], namelen);
1433 	stat->refs = lf->refs;
1434 	stat->id = lf->id;
1435 	stat->address = lf->address;
1436 	stat->size = lf->size;
1437 	/* Version 2 fields: */
1438 	namelen = strlen(lf->pathname) + 1;
1439 	if (namelen > sizeof(stat->pathname))
1440 		namelen = sizeof(stat->pathname);
1441 	bcopy(lf->pathname, &stat->pathname[0], namelen);
1442 	sx_xunlock(&kld_sx);
1443 
1444 	td->td_retval[0] = 0;
1445 	return (0);
1446 }
1447 
1448 #ifdef DDB
1449 DB_COMMAND_FLAGS(kldstat, db_kldstat, DB_CMD_MEMSAFE)
1450 {
1451 	linker_file_t lf;
1452 
1453 #define	POINTER_WIDTH	((int)(sizeof(void *) * 2 + 2))
1454 	db_printf("Id Refs Address%*c Size     Name\n", POINTER_WIDTH - 7, ' ');
1455 #undef	POINTER_WIDTH
1456 	TAILQ_FOREACH(lf, &linker_files, link) {
1457 		if (db_pager_quit)
1458 			return;
1459 		db_printf("%2d %4d %p %-8zx %s\n", lf->id, lf->refs,
1460 		    lf->address, lf->size, lf->filename);
1461 	}
1462 }
1463 #endif /* DDB */
1464 
1465 int
1466 sys_kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
1467 {
1468 	linker_file_t lf;
1469 	module_t mp;
1470 	int error = 0;
1471 
1472 #ifdef MAC
1473 	error = mac_kld_check_stat(td->td_ucred);
1474 	if (error)
1475 		return (error);
1476 #endif
1477 
1478 	sx_xlock(&kld_sx);
1479 	lf = linker_find_file_by_id(uap->fileid);
1480 	if (lf) {
1481 		MOD_SLOCK;
1482 		mp = TAILQ_FIRST(&lf->modules);
1483 		if (mp != NULL)
1484 			td->td_retval[0] = module_getid(mp);
1485 		else
1486 			td->td_retval[0] = 0;
1487 		MOD_SUNLOCK;
1488 	} else
1489 		error = ENOENT;
1490 	sx_xunlock(&kld_sx);
1491 	return (error);
1492 }
1493 
1494 int
1495 sys_kldsym(struct thread *td, struct kldsym_args *uap)
1496 {
1497 	char *symstr = NULL;
1498 	c_linker_sym_t sym;
1499 	linker_symval_t symval;
1500 	linker_file_t lf;
1501 	struct kld_sym_lookup lookup;
1502 	int error = 0;
1503 
1504 #ifdef MAC
1505 	error = mac_kld_check_stat(td->td_ucred);
1506 	if (error)
1507 		return (error);
1508 #endif
1509 
1510 	if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
1511 		return (error);
1512 	if (lookup.version != sizeof(lookup) ||
1513 	    uap->cmd != KLDSYM_LOOKUP)
1514 		return (EINVAL);
1515 	symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1516 	if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
1517 		goto out;
1518 	sx_xlock(&kld_sx);
1519 	if (uap->fileid != 0) {
1520 		lf = linker_find_file_by_id(uap->fileid);
1521 		if (lf == NULL)
1522 			error = ENOENT;
1523 		else if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1524 		    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1525 			lookup.symvalue = (uintptr_t) symval.value;
1526 			lookup.symsize = symval.size;
1527 			error = copyout(&lookup, uap->data, sizeof(lookup));
1528 		} else
1529 			error = ENOENT;
1530 	} else {
1531 		TAILQ_FOREACH(lf, &linker_files, link) {
1532 			if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1533 			    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1534 				lookup.symvalue = (uintptr_t)symval.value;
1535 				lookup.symsize = symval.size;
1536 				error = copyout(&lookup, uap->data,
1537 				    sizeof(lookup));
1538 				break;
1539 			}
1540 		}
1541 		if (lf == NULL)
1542 			error = ENOENT;
1543 	}
1544 	sx_xunlock(&kld_sx);
1545 out:
1546 	free(symstr, M_TEMP);
1547 	return (error);
1548 }
1549 
1550 /*
1551  * Preloaded module support
1552  */
1553 
1554 static modlist_t
1555 modlist_lookup(const char *name, int ver)
1556 {
1557 	modlist_t mod;
1558 
1559 	TAILQ_FOREACH(mod, &found_modules, link) {
1560 		if (strcmp(mod->name, name) == 0 &&
1561 		    (ver == 0 || mod->version == ver))
1562 			return (mod);
1563 	}
1564 	return (NULL);
1565 }
1566 
1567 static modlist_t
1568 modlist_lookup2(const char *name, const struct mod_depend *verinfo)
1569 {
1570 	modlist_t mod, bestmod;
1571 	int ver;
1572 
1573 	if (verinfo == NULL)
1574 		return (modlist_lookup(name, 0));
1575 	bestmod = NULL;
1576 	TAILQ_FOREACH(mod, &found_modules, link) {
1577 		if (strcmp(mod->name, name) != 0)
1578 			continue;
1579 		ver = mod->version;
1580 		if (ver == verinfo->md_ver_preferred)
1581 			return (mod);
1582 		if (ver >= verinfo->md_ver_minimum &&
1583 		    ver <= verinfo->md_ver_maximum &&
1584 		    (bestmod == NULL || ver > bestmod->version))
1585 			bestmod = mod;
1586 	}
1587 	return (bestmod);
1588 }
1589 
1590 static modlist_t
1591 modlist_newmodule(const char *modname, int version, linker_file_t container)
1592 {
1593 	modlist_t mod;
1594 
1595 	mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1596 	if (mod == NULL)
1597 		panic("no memory for module list");
1598 	mod->container = container;
1599 	mod->name = modname;
1600 	mod->version = version;
1601 	TAILQ_INSERT_TAIL(&found_modules, mod, link);
1602 	return (mod);
1603 }
1604 
1605 static void
1606 linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1607     struct mod_metadata **stop, int preload)
1608 {
1609 	struct mod_metadata *mp, **mdp;
1610 	const char *modname;
1611 	int ver;
1612 
1613 	for (mdp = start; mdp < stop; mdp++) {
1614 		mp = *mdp;
1615 		if (mp->md_type != MDT_VERSION)
1616 			continue;
1617 		modname = mp->md_cval;
1618 		ver = ((const struct mod_version *)mp->md_data)->mv_version;
1619 		if (modlist_lookup(modname, ver) != NULL) {
1620 			printf("module %s already present!\n", modname);
1621 			/* XXX what can we do? this is a build error. :-( */
1622 			continue;
1623 		}
1624 		modlist_newmodule(modname, ver, lf);
1625 	}
1626 }
1627 
1628 static void
1629 linker_preload(void *arg)
1630 {
1631 	caddr_t modptr;
1632 	const char *modname, *nmodname;
1633 	char *modtype;
1634 	linker_file_t lf, nlf;
1635 	linker_class_t lc;
1636 	int error;
1637 	linker_file_list_t loaded_files;
1638 	linker_file_list_t depended_files;
1639 	struct mod_metadata *mp, *nmp;
1640 	struct mod_metadata **start, **stop, **mdp, **nmdp;
1641 	const struct mod_depend *verinfo;
1642 	int nver;
1643 	int resolves;
1644 	modlist_t mod;
1645 	struct sysinit **si_start, **si_stop;
1646 
1647 	TAILQ_INIT(&loaded_files);
1648 	TAILQ_INIT(&depended_files);
1649 	TAILQ_INIT(&found_modules);
1650 	error = 0;
1651 
1652 	modptr = NULL;
1653 	sx_xlock(&kld_sx);
1654 	while ((modptr = preload_search_next_name(modptr)) != NULL) {
1655 		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1656 		modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1657 		if (modname == NULL) {
1658 			printf("Preloaded module at %p does not have a"
1659 			    " name!\n", modptr);
1660 			continue;
1661 		}
1662 		if (modtype == NULL) {
1663 			printf("Preloaded module at %p does not have a type!\n",
1664 			    modptr);
1665 			continue;
1666 		}
1667 		if (bootverbose)
1668 			printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1669 			    modptr);
1670 		lf = NULL;
1671 		TAILQ_FOREACH(lc, &classes, link) {
1672 			error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1673 			if (!error)
1674 				break;
1675 			lf = NULL;
1676 		}
1677 		if (lf)
1678 			TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1679 	}
1680 
1681 	/*
1682 	 * First get a list of stuff in the kernel.
1683 	 */
1684 	if (linker_file_lookup_set(linker_kernel_file, MDT_SETNAME, &start,
1685 	    &stop, NULL) == 0)
1686 		linker_addmodules(linker_kernel_file, start, stop, 1);
1687 
1688 	/*
1689 	 * This is a once-off kinky bubble sort to resolve relocation
1690 	 * dependency requirements.
1691 	 */
1692 restart:
1693 	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1694 		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1695 		    &stop, NULL);
1696 		/*
1697 		 * First, look to see if we would successfully link with this
1698 		 * stuff.
1699 		 */
1700 		resolves = 1;	/* unless we know otherwise */
1701 		if (!error) {
1702 			for (mdp = start; mdp < stop; mdp++) {
1703 				mp = *mdp;
1704 				if (mp->md_type != MDT_DEPEND)
1705 					continue;
1706 				modname = mp->md_cval;
1707 				verinfo = mp->md_data;
1708 				for (nmdp = start; nmdp < stop; nmdp++) {
1709 					nmp = *nmdp;
1710 					if (nmp->md_type != MDT_VERSION)
1711 						continue;
1712 					nmodname = nmp->md_cval;
1713 					if (strcmp(modname, nmodname) == 0)
1714 						break;
1715 				}
1716 				if (nmdp < stop)   /* it's a self reference */
1717 					continue;
1718 
1719 				/*
1720 				 * ok, the module isn't here yet, we
1721 				 * are not finished
1722 				 */
1723 				if (modlist_lookup2(modname, verinfo) == NULL)
1724 					resolves = 0;
1725 			}
1726 		}
1727 		/*
1728 		 * OK, if we found our modules, we can link.  So, "provide"
1729 		 * the modules inside and add it to the end of the link order
1730 		 * list.
1731 		 */
1732 		if (resolves) {
1733 			if (!error) {
1734 				for (mdp = start; mdp < stop; mdp++) {
1735 					mp = *mdp;
1736 					if (mp->md_type != MDT_VERSION)
1737 						continue;
1738 					modname = mp->md_cval;
1739 					nver = ((const struct mod_version *)
1740 					    mp->md_data)->mv_version;
1741 					if (modlist_lookup(modname,
1742 					    nver) != NULL) {
1743 						printf("module %s already"
1744 						    " present!\n", modname);
1745 						TAILQ_REMOVE(&loaded_files,
1746 						    lf, loaded);
1747 						linker_file_unload(lf,
1748 						    LINKER_UNLOAD_FORCE);
1749 						/* we changed tailq next ptr */
1750 						goto restart;
1751 					}
1752 					modlist_newmodule(modname, nver, lf);
1753 				}
1754 			}
1755 			TAILQ_REMOVE(&loaded_files, lf, loaded);
1756 			TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1757 			/*
1758 			 * Since we provided modules, we need to restart the
1759 			 * sort so that the previous files that depend on us
1760 			 * have a chance. Also, we've busted the tailq next
1761 			 * pointer with the REMOVE.
1762 			 */
1763 			goto restart;
1764 		}
1765 	}
1766 
1767 	/*
1768 	 * At this point, we check to see what could not be resolved..
1769 	 */
1770 	while ((lf = TAILQ_FIRST(&loaded_files)) != NULL) {
1771 		TAILQ_REMOVE(&loaded_files, lf, loaded);
1772 		printf("KLD file %s is missing dependencies\n", lf->filename);
1773 		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1774 	}
1775 
1776 	/*
1777 	 * We made it. Finish off the linking in the order we determined.
1778 	 */
1779 	TAILQ_FOREACH_SAFE(lf, &depended_files, loaded, nlf) {
1780 		if (linker_kernel_file) {
1781 			linker_kernel_file->refs++;
1782 			linker_file_add_dependency(lf, linker_kernel_file);
1783 		}
1784 		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1785 		    &stop, NULL);
1786 		if (!error) {
1787 			for (mdp = start; mdp < stop; mdp++) {
1788 				mp = *mdp;
1789 				if (mp->md_type != MDT_DEPEND)
1790 					continue;
1791 				modname = mp->md_cval;
1792 				verinfo = mp->md_data;
1793 				mod = modlist_lookup2(modname, verinfo);
1794 				if (mod == NULL) {
1795 					printf("KLD file %s - cannot find "
1796 					    "dependency \"%s\"\n",
1797 					    lf->filename, modname);
1798 					goto fail;
1799 				}
1800 				/* Don't count self-dependencies */
1801 				if (lf == mod->container)
1802 					continue;
1803 				mod->container->refs++;
1804 				linker_file_add_dependency(lf, mod->container);
1805 			}
1806 		}
1807 		/*
1808 		 * Now do relocation etc using the symbol search paths
1809 		 * established by the dependencies
1810 		 */
1811 		error = LINKER_LINK_PRELOAD_FINISH(lf);
1812 		if (error) {
1813 			printf("KLD file %s - could not finalize loading\n",
1814 			    lf->filename);
1815 			goto fail;
1816 		}
1817 		linker_file_register_modules(lf);
1818 		if (!TAILQ_EMPTY(&lf->modules))
1819 			lf->flags |= LINKER_FILE_MODULES;
1820 		if (linker_file_lookup_set(lf, "sysinit_set", &si_start,
1821 		    &si_stop, NULL) == 0)
1822 			sysinit_add(si_start, si_stop);
1823 		linker_file_register_sysctls(lf, true);
1824 		lf->flags |= LINKER_FILE_LINKED;
1825 		continue;
1826 fail:
1827 		TAILQ_REMOVE(&depended_files, lf, loaded);
1828 		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1829 	}
1830 	sx_xunlock(&kld_sx);
1831 	/* woohoo! we made it! */
1832 }
1833 SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, NULL);
1834 
1835 static void
1836 linker_mountroot(void *arg __unused)
1837 {
1838 	linker_file_t lf;
1839 
1840 	sx_xlock(&kld_sx);
1841 	TAILQ_FOREACH (lf, &linker_files, link) {
1842 		linker_ctf_load_file(lf);
1843 	}
1844 	sx_xunlock(&kld_sx);
1845 }
1846 EVENTHANDLER_DEFINE(mountroot, linker_mountroot, NULL, 0);
1847 
1848 /*
1849  * Handle preload files that failed to load any modules.
1850  */
1851 static void
1852 linker_preload_finish(void *arg)
1853 {
1854 	linker_file_t lf, nlf;
1855 
1856 	sx_xlock(&kld_sx);
1857 	TAILQ_FOREACH_SAFE(lf, &linker_files, link, nlf) {
1858 		if (lf == linker_kernel_file)
1859 			continue;
1860 
1861 		/*
1862 		 * If all of the modules in this file failed to load, unload
1863 		 * the file and return an error of ENOEXEC.  (Parity with
1864 		 * linker_load_file.)
1865 		 */
1866 		if ((lf->flags & LINKER_FILE_MODULES) != 0 &&
1867 		    TAILQ_EMPTY(&lf->modules)) {
1868 			linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1869 			continue;
1870 		}
1871 
1872 		lf->flags &= ~LINKER_FILE_MODULES;
1873 		lf->userrefs++;	/* so we can (try to) kldunload it */
1874 	}
1875 	sx_xunlock(&kld_sx);
1876 }
1877 
1878 /*
1879  * Attempt to run after all DECLARE_MODULE SYSINITs.  Unfortunately they can be
1880  * scheduled at any subsystem and order, so run this as late as possible.  init
1881  * becomes runnable in SI_SUB_KTHREAD_INIT, so go slightly before that.
1882  */
1883 SYSINIT(preload_finish, SI_SUB_KTHREAD_INIT - 100, SI_ORDER_MIDDLE,
1884     linker_preload_finish, NULL);
1885 
1886 /*
1887  * Search for a not-loaded module by name.
1888  *
1889  * Modules may be found in the following locations:
1890  *
1891  * - preloaded (result is just the module name) - on disk (result is full path
1892  * to module)
1893  *
1894  * If the module name is qualified in any way (contains path, etc.) the we
1895  * simply return a copy of it.
1896  *
1897  * The search path can be manipulated via sysctl.  Note that we use the ';'
1898  * character as a separator to be consistent with the bootloader.
1899  */
1900 
1901 static char linker_hintfile[] = "linker.hints";
1902 static char linker_path[MAXPATHLEN] = "/boot/kernel;/boot/modules";
1903 
1904 SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RWTUN, linker_path,
1905     sizeof(linker_path), "module load search path");
1906 
1907 TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1908 
1909 static const char * const linker_ext_list[] = {
1910 	"",
1911 	".ko",
1912 	NULL
1913 };
1914 
1915 /*
1916  * Check if file actually exists either with or without extension listed in
1917  * the linker_ext_list. (probably should be generic for the rest of the
1918  * kernel)
1919  */
1920 static char *
1921 linker_lookup_file(const char *path, int pathlen, const char *name,
1922     int namelen, struct vattr *vap)
1923 {
1924 	struct nameidata nd;
1925 	struct thread *td = curthread;	/* XXX */
1926 	const char * const *cpp, *sep;
1927 	char *result;
1928 	int error, len, extlen, reclen, flags;
1929 	__enum_uint8(vtype) type;
1930 
1931 	extlen = 0;
1932 	for (cpp = linker_ext_list; *cpp; cpp++) {
1933 		len = strlen(*cpp);
1934 		if (len > extlen)
1935 			extlen = len;
1936 	}
1937 	extlen++;		/* trailing '\0' */
1938 	sep = (path[pathlen - 1] != '/') ? "/" : "";
1939 
1940 	reclen = pathlen + strlen(sep) + namelen + extlen + 1;
1941 	result = malloc(reclen, M_LINKER, M_WAITOK);
1942 	for (cpp = linker_ext_list; *cpp; cpp++) {
1943 		snprintf(result, reclen, "%.*s%s%.*s%s", pathlen, path, sep,
1944 		    namelen, name, *cpp);
1945 		/*
1946 		 * Attempt to open the file, and return the path if
1947 		 * we succeed and it's a regular file.
1948 		 */
1949 		NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, result);
1950 		flags = FREAD;
1951 		error = vn_open(&nd, &flags, 0, NULL);
1952 		if (error == 0) {
1953 			NDFREE_PNBUF(&nd);
1954 			type = nd.ni_vp->v_type;
1955 			if (vap)
1956 				VOP_GETATTR(nd.ni_vp, vap, td->td_ucred);
1957 			VOP_UNLOCK(nd.ni_vp);
1958 			vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1959 			if (type == VREG)
1960 				return (result);
1961 		}
1962 	}
1963 	free(result, M_LINKER);
1964 	return (NULL);
1965 }
1966 
1967 #define	INT_ALIGN(base, ptr)	ptr =					\
1968 	(base) + roundup2((ptr) - (base), sizeof(int))
1969 
1970 /*
1971  * Lookup KLD which contains requested module in the "linker.hints" file. If
1972  * version specification is available, then try to find the best KLD.
1973  * Otherwise just find the latest one.
1974  */
1975 static char *
1976 linker_hints_lookup(const char *path, int pathlen, const char *modname,
1977     int modnamelen, const struct mod_depend *verinfo)
1978 {
1979 	struct thread *td = curthread;	/* XXX */
1980 	struct ucred *cred = td ? td->td_ucred : NULL;
1981 	struct nameidata nd;
1982 	struct vattr vattr, mattr;
1983 	const char *best, *sep;
1984 	u_char *hints = NULL;
1985 	u_char *cp, *recptr, *bufend, *result, *pathbuf;
1986 	int error, ival, bestver, *intp, found, flags, clen, blen;
1987 	ssize_t reclen;
1988 
1989 	result = NULL;
1990 	bestver = found = 0;
1991 
1992 	sep = (path[pathlen - 1] != '/') ? "/" : "";
1993 	reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
1994 	    strlen(sep) + 1;
1995 	pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
1996 	snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
1997 	    linker_hintfile);
1998 
1999 	NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, pathbuf);
2000 	flags = FREAD;
2001 	error = vn_open(&nd, &flags, 0, NULL);
2002 	if (error)
2003 		goto bad;
2004 	NDFREE_PNBUF(&nd);
2005 	if (nd.ni_vp->v_type != VREG)
2006 		goto bad;
2007 	best = cp = NULL;
2008 	error = VOP_GETATTR(nd.ni_vp, &vattr, cred);
2009 	if (error)
2010 		goto bad;
2011 	/*
2012 	 * XXX: we need to limit this number to some reasonable value
2013 	 */
2014 	if (vattr.va_size > LINKER_HINTS_MAX) {
2015 		printf("linker.hints file too large %ld\n", (long)vattr.va_size);
2016 		goto bad;
2017 	}
2018 	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
2019 	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
2020 	    UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &reclen, td);
2021 	if (error)
2022 		goto bad;
2023 	VOP_UNLOCK(nd.ni_vp);
2024 	vn_close(nd.ni_vp, FREAD, cred, td);
2025 	nd.ni_vp = NULL;
2026 	if (reclen != 0) {
2027 		printf("can't read %zd\n", reclen);
2028 		goto bad;
2029 	}
2030 	intp = (int *)hints;
2031 	ival = *intp++;
2032 	if (ival != LINKER_HINTS_VERSION) {
2033 		printf("linker.hints file version mismatch %d\n", ival);
2034 		goto bad;
2035 	}
2036 	bufend = hints + vattr.va_size;
2037 	recptr = (u_char *)intp;
2038 	clen = blen = 0;
2039 	while (recptr < bufend && !found) {
2040 		intp = (int *)recptr;
2041 		reclen = *intp++;
2042 		ival = *intp++;
2043 		cp = (char *)intp;
2044 		switch (ival) {
2045 		case MDT_VERSION:
2046 			clen = *cp++;
2047 			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
2048 				break;
2049 			cp += clen;
2050 			INT_ALIGN(hints, cp);
2051 			ival = *(int *)cp;
2052 			cp += sizeof(int);
2053 			clen = *cp++;
2054 			if (verinfo == NULL ||
2055 			    ival == verinfo->md_ver_preferred) {
2056 				found = 1;
2057 				break;
2058 			}
2059 			if (ival >= verinfo->md_ver_minimum &&
2060 			    ival <= verinfo->md_ver_maximum &&
2061 			    ival > bestver) {
2062 				bestver = ival;
2063 				best = cp;
2064 				blen = clen;
2065 			}
2066 			break;
2067 		default:
2068 			break;
2069 		}
2070 		recptr += reclen + sizeof(int);
2071 	}
2072 	/*
2073 	 * Finally check if KLD is in the place
2074 	 */
2075 	if (found)
2076 		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
2077 	else if (best)
2078 		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
2079 
2080 	/*
2081 	 * KLD is newer than hints file. What we should do now?
2082 	 */
2083 	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
2084 		printf("warning: KLD '%s' is newer than the linker.hints"
2085 		    " file\n", result);
2086 bad:
2087 	free(pathbuf, M_LINKER);
2088 	if (hints)
2089 		free(hints, M_TEMP);
2090 	if (nd.ni_vp != NULL) {
2091 		VOP_UNLOCK(nd.ni_vp);
2092 		vn_close(nd.ni_vp, FREAD, cred, td);
2093 	}
2094 	/*
2095 	 * If nothing found or hints is absent - fallback to the old
2096 	 * way by using "kldname[.ko]" as module name.
2097 	 */
2098 	if (!found && !bestver && result == NULL)
2099 		result = linker_lookup_file(path, pathlen, modname,
2100 		    modnamelen, NULL);
2101 	return (result);
2102 }
2103 
2104 /*
2105  * Lookup KLD which contains requested module in the all directories.
2106  */
2107 static char *
2108 linker_search_module(const char *modname, int modnamelen,
2109     const struct mod_depend *verinfo)
2110 {
2111 	char *cp, *ep, *result;
2112 
2113 	/*
2114 	 * traverse the linker path
2115 	 */
2116 	for (cp = linker_path; *cp; cp = ep + 1) {
2117 		/* find the end of this component */
2118 		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
2119 		result = linker_hints_lookup(cp, ep - cp, modname,
2120 		    modnamelen, verinfo);
2121 		if (result != NULL)
2122 			return (result);
2123 		if (*ep == 0)
2124 			break;
2125 	}
2126 	return (NULL);
2127 }
2128 
2129 /*
2130  * Search for module in all directories listed in the linker_path.
2131  */
2132 static char *
2133 linker_search_kld(const char *name)
2134 {
2135 	char *cp, *ep, *result;
2136 	int len;
2137 
2138 	/* qualified at all? */
2139 	if (strchr(name, '/'))
2140 		return (strdup(name, M_LINKER));
2141 
2142 	/* traverse the linker path */
2143 	len = strlen(name);
2144 	for (ep = linker_path; *ep; ep++) {
2145 		cp = ep;
2146 		/* find the end of this component */
2147 		for (; *ep != 0 && *ep != ';'; ep++);
2148 		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
2149 		if (result != NULL)
2150 			return (result);
2151 	}
2152 	return (NULL);
2153 }
2154 
2155 static const char *
2156 linker_basename(const char *path)
2157 {
2158 	const char *filename;
2159 
2160 	filename = strrchr(path, '/');
2161 	if (filename == NULL)
2162 		return path;
2163 	if (filename[1])
2164 		filename++;
2165 	return (filename);
2166 }
2167 
2168 #ifdef HWPMC_HOOKS
2169 /*
2170  * Inform hwpmc about the set of kernel modules currently loaded.
2171  */
2172 void *
2173 linker_hwpmc_list_objects(void)
2174 {
2175 	linker_file_t lf;
2176 	struct pmckern_map_in *kobase;
2177 	int i, nmappings;
2178 
2179 	nmappings = 0;
2180 	sx_slock(&kld_sx);
2181 	TAILQ_FOREACH(lf, &linker_files, link)
2182 		nmappings++;
2183 
2184 	/* Allocate nmappings + 1 entries. */
2185 	kobase = malloc((nmappings + 1) * sizeof(struct pmckern_map_in),
2186 	    M_LINKER, M_WAITOK | M_ZERO);
2187 	i = 0;
2188 	TAILQ_FOREACH(lf, &linker_files, link) {
2189 		/* Save the info for this linker file. */
2190 		kobase[i].pm_file = lf->pathname;
2191 		kobase[i].pm_address = (uintptr_t)lf->address;
2192 		i++;
2193 	}
2194 	sx_sunlock(&kld_sx);
2195 
2196 	KASSERT(i > 0, ("linker_hpwmc_list_objects: no kernel objects?"));
2197 
2198 	/* The last entry of the malloced area comprises of all zeros. */
2199 	KASSERT(kobase[i].pm_file == NULL,
2200 	    ("linker_hwpmc_list_objects: last object not NULL"));
2201 
2202 	return ((void *)kobase);
2203 }
2204 #endif
2205 
2206 /* check if root file system is not mounted */
2207 static bool
2208 linker_root_mounted(void)
2209 {
2210 	struct pwd *pwd;
2211 	bool ret;
2212 
2213 	if (rootvnode == NULL)
2214 		return (false);
2215 
2216 	pwd = pwd_hold(curthread);
2217 	ret = pwd->pwd_rdir != NULL;
2218 	pwd_drop(pwd);
2219 	return (ret);
2220 }
2221 
2222 /*
2223  * Find a file which contains given module and load it, if "parent" is not
2224  * NULL, register a reference to it.
2225  */
2226 static int
2227 linker_load_module(const char *kldname, const char *modname,
2228     struct linker_file *parent, const struct mod_depend *verinfo,
2229     struct linker_file **lfpp)
2230 {
2231 	linker_file_t lfdep;
2232 	const char *filename;
2233 	char *pathname;
2234 	int error;
2235 
2236 	sx_assert(&kld_sx, SA_XLOCKED);
2237 	if (modname == NULL) {
2238 		/*
2239  		 * We have to load KLD
2240  		 */
2241 		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
2242 		    " is not NULL"));
2243 		if (!linker_root_mounted())
2244 			return (ENXIO);
2245 		pathname = linker_search_kld(kldname);
2246 	} else {
2247 		if (modlist_lookup2(modname, verinfo) != NULL)
2248 			return (EEXIST);
2249 		if (!linker_root_mounted())
2250 			return (ENXIO);
2251 		if (kldname != NULL)
2252 			pathname = strdup(kldname, M_LINKER);
2253 		else
2254 			/*
2255 			 * Need to find a KLD with required module
2256 			 */
2257 			pathname = linker_search_module(modname,
2258 			    strlen(modname), verinfo);
2259 	}
2260 	if (pathname == NULL)
2261 		return (ENOENT);
2262 
2263 	/*
2264 	 * Can't load more than one file with the same basename XXX:
2265 	 * Actually it should be possible to have multiple KLDs with
2266 	 * the same basename but different path because they can
2267 	 * provide different versions of the same modules.
2268 	 */
2269 	filename = linker_basename(pathname);
2270 	if (linker_find_file_by_name(filename))
2271 		error = EEXIST;
2272 	else do {
2273 		error = linker_load_file(pathname, &lfdep);
2274 		if (error)
2275 			break;
2276 		if (modname && verinfo &&
2277 		    modlist_lookup2(modname, verinfo) == NULL) {
2278 			linker_file_unload(lfdep, LINKER_UNLOAD_FORCE);
2279 			error = ENOENT;
2280 			break;
2281 		}
2282 		if (parent)
2283 			linker_file_add_dependency(parent, lfdep);
2284 		if (lfpp)
2285 			*lfpp = lfdep;
2286 	} while (0);
2287 	free(pathname, M_LINKER);
2288 	return (error);
2289 }
2290 
2291 /*
2292  * This routine is responsible for finding dependencies of userland initiated
2293  * kldload(2)'s of files.
2294  */
2295 int
2296 linker_load_dependencies(linker_file_t lf)
2297 {
2298 	linker_file_t lfdep;
2299 	struct mod_metadata **start, **stop, **mdp, **nmdp;
2300 	struct mod_metadata *mp, *nmp;
2301 	const struct mod_depend *verinfo;
2302 	modlist_t mod;
2303 	const char *modname, *nmodname;
2304 	int ver, error = 0;
2305 
2306 	/*
2307 	 * All files are dependent on /kernel.
2308 	 */
2309 	sx_assert(&kld_sx, SA_XLOCKED);
2310 	if (linker_kernel_file) {
2311 		linker_kernel_file->refs++;
2312 		linker_file_add_dependency(lf, linker_kernel_file);
2313 	}
2314 	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
2315 	    NULL) != 0)
2316 		return (0);
2317 	for (mdp = start; mdp < stop; mdp++) {
2318 		mp = *mdp;
2319 		if (mp->md_type != MDT_VERSION)
2320 			continue;
2321 		modname = mp->md_cval;
2322 		ver = ((const struct mod_version *)mp->md_data)->mv_version;
2323 		mod = modlist_lookup(modname, ver);
2324 		if (mod != NULL) {
2325 			printf("interface %s.%d already present in the KLD"
2326 			    " '%s'!\n", modname, ver,
2327 			    mod->container->filename);
2328 			return (EEXIST);
2329 		}
2330 	}
2331 
2332 	for (mdp = start; mdp < stop; mdp++) {
2333 		mp = *mdp;
2334 		if (mp->md_type != MDT_DEPEND)
2335 			continue;
2336 		modname = mp->md_cval;
2337 		verinfo = mp->md_data;
2338 		nmodname = NULL;
2339 		for (nmdp = start; nmdp < stop; nmdp++) {
2340 			nmp = *nmdp;
2341 			if (nmp->md_type != MDT_VERSION)
2342 				continue;
2343 			nmodname = nmp->md_cval;
2344 			if (strcmp(modname, nmodname) == 0)
2345 				break;
2346 		}
2347 		if (nmdp < stop)/* early exit, it's a self reference */
2348 			continue;
2349 		mod = modlist_lookup2(modname, verinfo);
2350 		if (mod) {	/* woohoo, it's loaded already */
2351 			lfdep = mod->container;
2352 			lfdep->refs++;
2353 			linker_file_add_dependency(lf, lfdep);
2354 			continue;
2355 		}
2356 		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
2357 		if (error) {
2358 			printf("KLD %s: depends on %s - not available or"
2359 			    " version mismatch\n", lf->filename, modname);
2360 			break;
2361 		}
2362 	}
2363 
2364 	if (error)
2365 		return (error);
2366 	linker_addmodules(lf, start, stop, 0);
2367 	return (error);
2368 }
2369 
2370 static int
2371 sysctl_kern_function_list_iterate(const char *name, void *opaque)
2372 {
2373 	struct sysctl_req *req;
2374 
2375 	req = opaque;
2376 	return (SYSCTL_OUT(req, name, strlen(name) + 1));
2377 }
2378 
2379 /*
2380  * Export a nul-separated, double-nul-terminated list of all function names
2381  * in the kernel.
2382  */
2383 static int
2384 sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
2385 {
2386 	linker_file_t lf;
2387 	int error;
2388 
2389 #ifdef MAC
2390 	error = mac_kld_check_stat(req->td->td_ucred);
2391 	if (error)
2392 		return (error);
2393 #endif
2394 	error = sysctl_wire_old_buffer(req, 0);
2395 	if (error != 0)
2396 		return (error);
2397 	sx_xlock(&kld_sx);
2398 	TAILQ_FOREACH(lf, &linker_files, link) {
2399 		error = LINKER_EACH_FUNCTION_NAME(lf,
2400 		    sysctl_kern_function_list_iterate, req);
2401 		if (error) {
2402 			sx_xunlock(&kld_sx);
2403 			return (error);
2404 		}
2405 	}
2406 	sx_xunlock(&kld_sx);
2407 	return (SYSCTL_OUT(req, "", 1));
2408 }
2409 
2410 SYSCTL_PROC(_kern, OID_AUTO, function_list,
2411     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
2412     sysctl_kern_function_list, "",
2413     "kernel function list");
2414