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