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