kern_linker.c revision 325866
1139823Simp/*-
21541Srgrimes * Copyright (c) 1997-2000 Doug Rabson
31541Srgrimes * All rights reserved.
41541Srgrimes *
51541Srgrimes * Redistribution and use in source and binary forms, with or without
61541Srgrimes * modification, are permitted provided that the following conditions
71541Srgrimes * are met:
81541Srgrimes * 1. Redistributions of source code must retain the above copyright
91541Srgrimes *    notice, this list of conditions and the following disclaimer.
101541Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
111541Srgrimes *    notice, this list of conditions and the following disclaimer in the
121541Srgrimes *    documentation and/or other materials provided with the distribution.
131541Srgrimes *
141541Srgrimes * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
151541Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
161541Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
171541Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
181541Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
191541Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
201541Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
211541Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
221541Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
231541Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
241541Srgrimes * SUCH DAMAGE.
251541Srgrimes */
261541Srgrimes
271541Srgrimes#include <sys/cdefs.h>
281541Srgrimes__FBSDID("$FreeBSD: stable/11/sys/kern/kern_linker.c 325866 2017-11-15 22:34:15Z gordon $");
291541Srgrimes
301541Srgrimes#include "opt_ddb.h"
311541Srgrimes#include "opt_kld.h"
321541Srgrimes#include "opt_hwpmc_hooks.h"
331541Srgrimes
341541Srgrimes#include <sys/param.h>
351541Srgrimes#include <sys/kernel.h>
361541Srgrimes#include <sys/systm.h>
37174895Srwatson#include <sys/malloc.h>
38174895Srwatson#include <sys/sysproto.h>
39174895Srwatson#include <sys/sysent.h>
401541Srgrimes#include <sys/priv.h>
411541Srgrimes#include <sys/proc.h>
42182184Sjkim#include <sys/lock.h>
431541Srgrimes#include <sys/mutex.h>
441541Srgrimes#include <sys/sx.h>
451541Srgrimes#include <sys/module.h>
4699419Speter#include <sys/mount.h>
471541Srgrimes#include <sys/linker.h>
481541Srgrimes#include <sys/eventhandler.h>
491541Srgrimes#include <sys/fcntl.h>
501541Srgrimes#include <sys/jail.h>
5140779Sdfr#include <sys/libkern.h>
5240779Sdfr#include <sys/namei.h>
531541Srgrimes#include <sys/vnode.h>
541541Srgrimes#include <sys/syscallsubr.h>
5540779Sdfr#include <sys/sysctl.h>
5640779Sdfr
5740779Sdfr#ifdef DDB
581541Srgrimes#include <ddb/ddb.h>
5940779Sdfr#endif
6040779Sdfr
6140779Sdfr#include <net/vnet.h>
6240779Sdfr
631541Srgrimes#include <security/mac/mac_framework.h>
641541Srgrimes
6555205Speter#include "linker_if.h"
661541Srgrimes
67182184Sjkim#ifdef HWPMC_HOOKS
68182184Sjkim#include <sys/pmckern.h>
6941588Seivind#endif
7041588Seivind
7155205Speter#ifdef KLD_DEBUG
721541Srgrimesint kld_debug = 0;
731541SrgrimesSYSCTL_INT(_debug, OID_AUTO, kld_debug, CTLFLAG_RWTUN,
741541Srgrimes    &kld_debug, 0, "Set various levels of KLD debug");
751541Srgrimes#endif
761541Srgrimes
771541Srgrimes/* These variables are used by kernel debuggers to enumerate loaded files. */
781541Srgrimesconst int kld_off_address = offsetof(struct linker_file, address);
791541Srgrimesconst int kld_off_filename = offsetof(struct linker_file, filename);
80182455Sjkimconst int kld_off_pathname = offsetof(struct linker_file, pathname);
811541Srgrimesconst int kld_off_next = offsetof(struct linker_file, link.tqe_next);
821541Srgrimes
831541Srgrimes/*
841541Srgrimes * static char *linker_search_path(const char *name, struct mod_depend
8592725Salfred * *verinfo);
8692725Salfred */
8712579Sbdestatic const char 	*linker_basename(const char *path);
8841588Seivind
89177003Srwatson/*
901541Srgrimes * Find a currently loaded file given its filename.
91177003Srwatson */
92177003Srwatsonstatic linker_file_t linker_find_file_by_name(const char* _filename);
93177003Srwatson
941541Srgrimes/*
951541Srgrimes * Find a currently loaded file given its file id.
961541Srgrimes */
971541Srgrimesstatic linker_file_t linker_find_file_by_id(int _fileid);
981541Srgrimes
991541Srgrimes/* Metadata from the static kernel */
1001541SrgrimesSET_DECLARE(modmetadata_set, struct mod_metadata);
1011541Srgrimes
1021541SrgrimesMALLOC_DEFINE(M_LINKER, "linker", "kernel linker");
1031541Srgrimes
1041541Srgrimeslinker_file_t linker_kernel_file;
1051541Srgrimes
106182456Sjkimstatic struct sx kld_sx;	/* kernel linker lock */
1071541Srgrimes
1081541Srgrimes/*
1091541Srgrimes * Load counter used by clients to determine if a linker file has been
1101541Srgrimes * re-loaded. This counter is incremented for each file load.
1111541Srgrimes */
1121541Srgrimesstatic int loadcnt;
1131541Srgrimes
1141541Srgrimesstatic linker_class_list_t classes;
115182455Sjkimstatic linker_file_list_t linker_files;
11641588Seivindstatic int next_file_id = 1;
11741588Seivindstatic int linker_no_more_classes = 0;
118182455Sjkim
1191541Srgrimes#define	LINKER_GET_NEXT_FILE_ID(a) do {					\
1201541Srgrimes	linker_file_t lftmp;						\
121182455Sjkim									\
12241588Seivind	if (!cold)							\
12341588Seivind		sx_assert(&kld_sx, SA_XLOCKED);				\
124182455Sjkimretry:									\
1251541Srgrimes	TAILQ_FOREACH(lftmp, &linker_files, link) {			\
1261541Srgrimes		if (next_file_id == lftmp->id) {			\
127182455Sjkim			next_file_id++;					\
12841588Seivind			goto retry;					\
12941588Seivind		}							\
130182455Sjkim	}								\
1311541Srgrimes	(a) = next_file_id;						\
1321541Srgrimes} while(0)
1331541Srgrimes
134177003Srwatson
1351541Srgrimes/* XXX wrong name; we're looking at version provision tags here, not modules */
1361541Srgrimestypedef TAILQ_HEAD(, modlist) modlisthead_t;
13741588Seivindstruct modlist {
138177003Srwatson	TAILQ_ENTRY(modlist) link;	/* chain together all modules */
1391541Srgrimes	linker_file_t   container;
140177003Srwatson	const char 	*name;
141177003Srwatson	int             version;
142177003Srwatson};
1431541Srgrimestypedef struct modlist *modlist_t;
1441541Srgrimesstatic modlisthead_t found_modules;
1451541Srgrimes
1461541Srgrimesstatic int	linker_file_add_dependency(linker_file_t file,
1471541Srgrimes		    linker_file_t dep);
1481541Srgrimesstatic caddr_t	linker_file_lookup_symbol_internal(linker_file_t file,
1491541Srgrimes		    const char* name, int deps);
1501541Srgrimesstatic int	linker_load_module(const char *kldname,
1511541Srgrimes		    const char *modname, struct linker_file *parent,
1521541Srgrimes		    const struct mod_depend *verinfo, struct linker_file **lfpp);
1531541Srgrimesstatic modlist_t modlist_lookup2(const char *name, const struct mod_depend *verinfo);
1541541Srgrimes
155177003Srwatsonstatic void
1561541Srgrimeslinker_init(void *arg)
1571541Srgrimes{
1581541Srgrimes
1591541Srgrimes	sx_init(&kld_sx, "kernel linker");
1601541Srgrimes	TAILQ_INIT(&classes);
161177003Srwatson	TAILQ_INIT(&linker_files);
1621541Srgrimes}
1631541Srgrimes
164177003SrwatsonSYSINIT(linker, SI_SUB_KLD, SI_ORDER_FIRST, linker_init, 0);
1651541Srgrimes
1661541Srgrimesstatic void
1671541Srgrimeslinker_stop_class_add(void *arg)
1681541Srgrimes{
1691541Srgrimes
1701541Srgrimes	linker_no_more_classes = 1;
1711541Srgrimes}
1721541Srgrimes
1731541SrgrimesSYSINIT(linker_class, SI_SUB_KLD, SI_ORDER_ANY, linker_stop_class_add, NULL);
174177003Srwatson
1751541Srgrimesint
176177003Srwatsonlinker_add_class(linker_class_t lc)
177177003Srwatson{
178172154Sdwmalone
1791541Srgrimes	/*
180224044Smp	 * We disallow any class registration past SI_ORDER_ANY
181224044Smp	 * of SI_SUB_KLD.  We bump the reference count to keep the
182177003Srwatson	 * ops from being freed.
1831541Srgrimes	 */
1841541Srgrimes	if (linker_no_more_classes == 1)
1851541Srgrimes		return (EPERM);
186177003Srwatson	kobj_class_compile((kobj_class_t) lc);
1871549Srgrimes	((kobj_class_t)lc)->refs++;	/* XXX: kobj_mtx */
1881541Srgrimes	TAILQ_INSERT_TAIL(&classes, lc, link);
1891541Srgrimes	return (0);
1901541Srgrimes}
1911541Srgrimes
1921541Srgrimesstatic void
19355205Speterlinker_file_sysinit(linker_file_t lf)
194182455Sjkim{
1951541Srgrimes	struct sysinit **start, **stop, **sipp, **xipp, *save;
1961541Srgrimes
1978876Srgrimes	KLD_DPF(FILE, ("linker_file_sysinit: calling SYSINITs for %s\n",
198177003Srwatson	    lf->filename));
1991541Srgrimes
200177003Srwatson	sx_assert(&kld_sx, SA_XLOCKED);
2011541Srgrimes
2021541Srgrimes	if (linker_file_lookup_set(lf, "sysinit_set", &start, &stop, NULL) != 0)
203177003Srwatson		return;
2041541Srgrimes	/*
2051541Srgrimes	 * Perform a bubble sort of the system initialization objects by
2061541Srgrimes	 * their subsystem (primary key) and order (secondary key).
20741588Seivind	 *
20855205Speter	 * Since some things care about execution order, this is the operation
2091541Srgrimes	 * which ensures continued function.
2101541Srgrimes	 */
2111541Srgrimes	for (sipp = start; sipp < stop; sipp++) {
212182455Sjkim		for (xipp = sipp + 1; xipp < stop; xipp++) {
2131541Srgrimes			if ((*sipp)->subsystem < (*xipp)->subsystem ||
2141541Srgrimes			    ((*sipp)->subsystem == (*xipp)->subsystem &&
215182455Sjkim			    (*sipp)->order <= (*xipp)->order))
2161541Srgrimes				continue;	/* skip */
2171541Srgrimes			save = *sipp;
218177003Srwatson			*sipp = *xipp;
2191541Srgrimes			*xipp = save;
2201541Srgrimes		}
2211541Srgrimes	}
22240779Sdfr
2231541Srgrimes	/*
2241541Srgrimes	 * Traverse the (now) ordered list of system initialization tasks.
2251541Srgrimes	 * Perform each task, and continue on to the next task.
22640779Sdfr	 */
2271541Srgrimes	sx_xunlock(&kld_sx);
2281541Srgrimes	mtx_lock(&Giant);
2291541Srgrimes	for (sipp = start; sipp < stop; sipp++) {
2301541Srgrimes		if ((*sipp)->subsystem == SI_SUB_DUMMY)
23141588Seivind			continue;	/* skip dummy task(s) */
23255205Speter
2331541Srgrimes		/* Call function */
2341541Srgrimes		(*((*sipp)->func)) ((*sipp)->udata);
2351541Srgrimes	}
236182455Sjkim	mtx_unlock(&Giant);
2371541Srgrimes	sx_xlock(&kld_sx);
2381541Srgrimes}
2391541Srgrimes
240182455Sjkimstatic void
2411541Srgrimeslinker_file_sysuninit(linker_file_t lf)
2421541Srgrimes{
2431541Srgrimes	struct sysinit **start, **stop, **sipp, **xipp, *save;
2441541Srgrimes
2451541Srgrimes	KLD_DPF(FILE, ("linker_file_sysuninit: calling SYSUNINITs for %s\n",
2461541Srgrimes	    lf->filename));
2471541Srgrimes
2481541Srgrimes	sx_assert(&kld_sx, SA_XLOCKED);
24955205Speter
250177003Srwatson	if (linker_file_lookup_set(lf, "sysuninit_set", &start, &stop,
2511541Srgrimes	    NULL) != 0)
2521541Srgrimes		return;
253182455Sjkim
2541541Srgrimes	/*
2551541Srgrimes	 * Perform a reverse bubble sort of the system initialization objects
2561541Srgrimes	 * by their subsystem (primary key) and order (secondary key).
2571541Srgrimes	 *
2581541Srgrimes	 * Since some things care about execution order, this is the operation
259182455Sjkim	 * which ensures continued function.
2601541Srgrimes	 */
2611541Srgrimes	for (sipp = start; sipp < stop; sipp++) {
2621541Srgrimes		for (xipp = sipp + 1; xipp < stop; xipp++) {
2631541Srgrimes			if ((*sipp)->subsystem > (*xipp)->subsystem ||
2641541Srgrimes			    ((*sipp)->subsystem == (*xipp)->subsystem &&
2651541Srgrimes			    (*sipp)->order >= (*xipp)->order))
2661541Srgrimes				continue;	/* skip */
2671541Srgrimes			save = *sipp;
2681541Srgrimes			*sipp = *xipp;
2691541Srgrimes			*xipp = save;
2701541Srgrimes		}
2711541Srgrimes	}
2721541Srgrimes
2731541Srgrimes	/*
2741541Srgrimes	 * Traverse the (now) ordered list of system initialization tasks.
27545574Seivind	 * Perform each task, and continue on to the next task.
27645574Seivind	 */
27755205Speter	sx_xunlock(&kld_sx);
2781541Srgrimes	mtx_lock(&Giant);
2791541Srgrimes	for (sipp = start; sipp < stop; sipp++) {
2801541Srgrimes		if ((*sipp)->subsystem == SI_SUB_DUMMY)
281177003Srwatson			continue;	/* skip dummy task(s) */
2821541Srgrimes
2831541Srgrimes		/* Call function */
284177003Srwatson		(*((*sipp)->func)) ((*sipp)->udata);
2851541Srgrimes	}
2861541Srgrimes	mtx_unlock(&Giant);
287177003Srwatson	sx_xlock(&kld_sx);
2881541Srgrimes}
2891541Srgrimes
2901541Srgrimesstatic void
29140779Sdfrlinker_file_register_sysctls(linker_file_t lf, bool enable)
2921541Srgrimes{
2931541Srgrimes	struct sysctl_oid **start, **stop, **oidp;
2941541Srgrimes
29540779Sdfr	KLD_DPF(FILE,
2961541Srgrimes	    ("linker_file_register_sysctls: registering SYSCTLs for %s\n",
2971541Srgrimes	    lf->filename));
2981541Srgrimes
2991541Srgrimes	sx_assert(&kld_sx, SA_XLOCKED);
30045574Seivind
30145574Seivind	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
30255205Speter		return;
3031541Srgrimes
3041541Srgrimes	sx_xunlock(&kld_sx);
3051541Srgrimes	sysctl_wlock();
306182455Sjkim	for (oidp = start; oidp < stop; oidp++) {
3071541Srgrimes		if (enable)
3081541Srgrimes			sysctl_register_oid(*oidp);
309177003Srwatson		else
3101541Srgrimes			sysctl_register_disabled_oid(*oidp);
3111541Srgrimes	}
312177003Srwatson	sysctl_wunlock();
3131541Srgrimes	sx_xlock(&kld_sx);
3141541Srgrimes}
3151541Srgrimes
3161541Srgrimesstatic void
3171541Srgrimeslinker_file_enable_sysctls(linker_file_t lf)
3181541Srgrimes{
3191541Srgrimes	struct sysctl_oid **start, **stop, **oidp;
32048548Sbde
32155205Speter	KLD_DPF(FILE,
322177003Srwatson	    ("linker_file_enable_sysctls: enable SYSCTLs for %s\n",
3231541Srgrimes	    lf->filename));
3241541Srgrimes
325182455Sjkim	sx_assert(&kld_sx, SA_XLOCKED);
3261541Srgrimes
3271541Srgrimes	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
328159018Sdwmalone		return;
3291541Srgrimes
3301541Srgrimes	sx_xunlock(&kld_sx);
331177003Srwatson	sysctl_wlock();
3321541Srgrimes	for (oidp = start; oidp < stop; oidp++)
3331541Srgrimes		sysctl_enable_oid(*oidp);
3341541Srgrimes	sysctl_wunlock();
3351541Srgrimes	sx_xlock(&kld_sx);
3361541Srgrimes}
3371541Srgrimes
3381541Srgrimesstatic void
3391541Srgrimeslinker_file_unregister_sysctls(linker_file_t lf)
34055205Speter{
3411541Srgrimes	struct sysctl_oid **start, **stop, **oidp;
3421541Srgrimes
3431541Srgrimes	KLD_DPF(FILE, ("linker_file_unregister_sysctls: unregistering SYSCTLs"
344182455Sjkim	    " for %s\n", lf->filename));
3451541Srgrimes
3461541Srgrimes	sx_assert(&kld_sx, SA_XLOCKED);
347159018Sdwmalone
3481541Srgrimes	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
3491541Srgrimes		return;
350182455Sjkim
3511541Srgrimes	sx_xunlock(&kld_sx);
3521541Srgrimes	sysctl_wlock();
3531541Srgrimes	for (oidp = start; oidp < stop; oidp++)
3541541Srgrimes		sysctl_unregister_oid(*oidp);
3551541Srgrimes	sysctl_wunlock();
3561541Srgrimes	sx_xlock(&kld_sx);
3571541Srgrimes}
3581541Srgrimes
3591541Srgrimesstatic int
3601541Srgrimeslinker_file_register_modules(linker_file_t lf)
3611541Srgrimes{
3621541Srgrimes	struct mod_metadata **start, **stop, **mdp;
3631541Srgrimes	const moduledata_t *moddata;
3641541Srgrimes	int first_error, error;
3651541Srgrimes
3661541Srgrimes	KLD_DPF(FILE, ("linker_file_register_modules: registering modules"
3678876Srgrimes	    " in %s\n", lf->filename));
3681541Srgrimes
3691541Srgrimes	sx_assert(&kld_sx, SA_XLOCKED);
3701541Srgrimes
3711541Srgrimes	if (linker_file_lookup_set(lf, "modmetadata_set", &start,
3721541Srgrimes	    &stop, NULL) != 0) {
3731541Srgrimes		/*
3741541Srgrimes		 * This fallback should be unnecessary, but if we get booted
3751541Srgrimes		 * from boot2 instead of loader and we are missing our
3761541Srgrimes		 * metadata then we have to try the best we can.
3771541Srgrimes		 */
3781541Srgrimes		if (lf == linker_kernel_file) {
3791541Srgrimes			start = SET_BEGIN(modmetadata_set);
3801541Srgrimes			stop = SET_LIMIT(modmetadata_set);
3811541Srgrimes		} else
3821541Srgrimes			return (0);
3831541Srgrimes	}
3841541Srgrimes	first_error = 0;
3851541Srgrimes	for (mdp = start; mdp < stop; mdp++) {
3861541Srgrimes		if ((*mdp)->md_type != MDT_MODULE)
3871541Srgrimes			continue;
3881541Srgrimes		moddata = (*mdp)->md_data;
3891541Srgrimes		KLD_DPF(FILE, ("Registering module %s in %s\n",
3901541Srgrimes		    moddata->name, lf->filename));
3911541Srgrimes		error = module_register(moddata, lf);
3921541Srgrimes		if (error) {
3931541Srgrimes			printf("Module %s failed to register: %d\n",
3941541Srgrimes			    moddata->name, error);
3951541Srgrimes			if (first_error == 0)
3961541Srgrimes				first_error = error;
3971541Srgrimes		}
3981541Srgrimes	}
3991541Srgrimes	return (first_error);
4001541Srgrimes}
4011541Srgrimes
4021541Srgrimesstatic void
4031541Srgrimeslinker_init_kernel_modules(void)
4041541Srgrimes{
4051541Srgrimes
4061541Srgrimes	sx_xlock(&kld_sx);
4071541Srgrimes	linker_file_register_modules(linker_kernel_file);
4081541Srgrimes	sx_xunlock(&kld_sx);
4091541Srgrimes}
4101541Srgrimes
4111541SrgrimesSYSINIT(linker_kernel, SI_SUB_KLD, SI_ORDER_ANY, linker_init_kernel_modules,
4121541Srgrimes    0);
4131541Srgrimes
4141541Srgrimesstatic int
4151541Srgrimeslinker_load_file(const char *filename, linker_file_t *result)
4161541Srgrimes{
4171541Srgrimes	linker_class_t lc;
4181541Srgrimes	linker_file_t lf;
4198876Srgrimes	int foundfile, error, modules;
4201541Srgrimes
4211541Srgrimes	/* Refuse to load modules if securelevel raised */
4221541Srgrimes	if (prison0.pr_securelevel > 0)
4238876Srgrimes		return (EPERM);
4241541Srgrimes
4251541Srgrimes	sx_assert(&kld_sx, SA_XLOCKED);
4261541Srgrimes	lf = linker_find_file_by_name(filename);
4278876Srgrimes	if (lf) {
4281541Srgrimes		KLD_DPF(FILE, ("linker_load_file: file %s is already loaded,"
4291541Srgrimes		    " incrementing refs\n", filename));
430182455Sjkim		*result = lf;
4311541Srgrimes		lf->refs++;
4321541Srgrimes		return (0);
4338876Srgrimes	}
4341541Srgrimes	foundfile = 0;
4351541Srgrimes	error = 0;
4361541Srgrimes
4378876Srgrimes	/*
4381541Srgrimes	 * We do not need to protect (lock) classes here because there is
4391541Srgrimes	 * no class registration past startup (SI_SUB_KLD, SI_ORDER_ANY)
4401541Srgrimes	 * and there is no class deregistration mechanism at this time.
4411541Srgrimes	 */
4421541Srgrimes	TAILQ_FOREACH(lc, &classes, link) {
4431541Srgrimes		KLD_DPF(FILE, ("linker_load_file: trying to load %s\n",
4441541Srgrimes		    filename));
4451541Srgrimes		error = LINKER_LOAD_FILE(lc, filename, &lf);
4461541Srgrimes		/*
4471541Srgrimes		 * If we got something other than ENOENT, then it exists but
4481541Srgrimes		 * we cannot load it for some other reason.
4491541Srgrimes		 */
4501541Srgrimes		if (error != ENOENT)
4511541Srgrimes			foundfile = 1;
4521541Srgrimes		if (lf) {
4538876Srgrimes			error = linker_file_register_modules(lf);
4541541Srgrimes			if (error == EEXIST) {
4551541Srgrimes				linker_file_unload(lf, LINKER_UNLOAD_FORCE);
4561541Srgrimes				return (error);
4578876Srgrimes			}
4581541Srgrimes			modules = !TAILQ_EMPTY(&lf->modules);
4591541Srgrimes			linker_file_register_sysctls(lf, false);
4601541Srgrimes			linker_file_sysinit(lf);
4618876Srgrimes			lf->flags |= LINKER_FILE_LINKED;
4621541Srgrimes
4631541Srgrimes			/*
4641541Srgrimes			 * If all of the modules in this file failed
4658876Srgrimes			 * to load, unload the file and return an
4661541Srgrimes			 * error of ENOEXEC.
4671541Srgrimes			 */
4681541Srgrimes			if (modules && TAILQ_EMPTY(&lf->modules)) {
4698876Srgrimes				linker_file_unload(lf, LINKER_UNLOAD_FORCE);
4701541Srgrimes				return (ENOEXEC);
4711541Srgrimes			}
4721541Srgrimes			linker_file_enable_sysctls(lf);
4731541Srgrimes			EVENTHANDLER_INVOKE(kld_load, lf);
4741541Srgrimes			*result = lf;
4751541Srgrimes			return (0);
4761541Srgrimes		}
4771541Srgrimes	}
4781541Srgrimes	/*
4791541Srgrimes	 * Less than ideal, but tells the user whether it failed to load or
4801541Srgrimes	 * the module was not found.
4811541Srgrimes	 */
4821541Srgrimes	if (foundfile) {
4831541Srgrimes
4841541Srgrimes		/*
4851541Srgrimes		 * If the file type has not been recognized by the last try
4861541Srgrimes		 * printout a message before to fail.
4871541Srgrimes		 */
4881541Srgrimes		if (error == ENOSYS)
4891541Srgrimes			printf("linker_load_file: Unsupported file type\n");
4901541Srgrimes
4911541Srgrimes		/*
4921541Srgrimes		 * Format not recognized or otherwise unloadable.
4931541Srgrimes		 * When loading a module that is statically built into
4941541Srgrimes		 * the kernel EEXIST percolates back up as the return
4951541Srgrimes		 * value.  Preserve this so that apps like sysinstall
4961541Srgrimes		 * can recognize this special case and not post bogus
49755205Speter		 * dialog boxes.
498182454Sjkim		 */
499182412Sjkim		if (error != EEXIST)
500182412Sjkim			error = ENOEXEC;
501182412Sjkim	} else
502182412Sjkim		error = ENOENT;		/* Nothing found */
503182412Sjkim	return (error);
504182412Sjkim}
505182412Sjkim
506182412Sjkimint
507182412Sjkimlinker_reference_module(const char *modname, struct mod_depend *verinfo,
508182412Sjkim    linker_file_t *result)
509182412Sjkim{
510182412Sjkim	modlist_t mod;
511182412Sjkim	int error;
512182412Sjkim
513182412Sjkim	sx_xlock(&kld_sx);
514182412Sjkim	if ((mod = modlist_lookup2(modname, verinfo)) != NULL) {
515182412Sjkim		*result = mod->container;
516182412Sjkim		(*result)->refs++;
517182454Sjkim		sx_xunlock(&kld_sx);
518182454Sjkim		return (0);
519182454Sjkim	}
5201541Srgrimes
5211541Srgrimes	error = linker_load_module(NULL, modname, NULL, verinfo, result);
5221541Srgrimes	sx_xunlock(&kld_sx);
5238876Srgrimes	return (error);
5241541Srgrimes}
5251541Srgrimes
5261541Srgrimesint
5271541Srgrimeslinker_release_module(const char *modname, struct mod_depend *verinfo,
5281541Srgrimes    linker_file_t lf)
529182455Sjkim{
5301541Srgrimes	modlist_t mod;
5311541Srgrimes	int error;
53254038Sarchie
5331541Srgrimes	sx_xlock(&kld_sx);
534153996Sjkim	if (lf == NULL) {
535153996Sjkim		KASSERT(modname != NULL,
536182455Sjkim		    ("linker_release_module: no file or name"));
537153996Sjkim		mod = modlist_lookup2(modname, verinfo);
538153996Sjkim		if (mod == NULL) {
539153996Sjkim			sx_xunlock(&kld_sx);
540182455Sjkim			return (ESRCH);
541153221Sjkim		}
5421541Srgrimes		lf = mod->container;
543182412Sjkim	} else
5441541Srgrimes		KASSERT(modname == NULL && verinfo == NULL,
545182412Sjkim		    ("linker_release_module: both file and name"));
546182412Sjkim	error =	linker_file_unload(lf, LINKER_UNLOAD_NORMAL);
547182454Sjkim	sx_xunlock(&kld_sx);
548182455Sjkim	return (error);
549182412Sjkim}
5508876Srgrimes
5511541Srgrimesstatic linker_file_t
5521541Srgrimeslinker_find_file_by_name(const char *filename)
5531541Srgrimes{
554182425Sjkim	linker_file_t lf;
5551541Srgrimes	char *koname;
556182454Sjkim
557182425Sjkim	koname = malloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
558182425Sjkim	sprintf(koname, "%s.ko", filename);
559182425Sjkim
560182425Sjkim	sx_assert(&kld_sx, SA_XLOCKED);
561182455Sjkim	TAILQ_FOREACH(lf, &linker_files, link) {
562182454Sjkim		if (strcmp(lf->filename, koname) == 0)
5631541Srgrimes			break;
5641541Srgrimes		if (strcmp(lf->filename, filename) == 0)
5651541Srgrimes			break;
5661541Srgrimes	}
567182454Sjkim	free(koname, M_LINKER);
568182454Sjkim	return (lf);
569182454Sjkim}
570182454Sjkim
571182455Sjkimstatic linker_file_t
572182454Sjkimlinker_find_file_by_id(int fileid)
573182454Sjkim{
5741541Srgrimes	linker_file_t lf;
5751541Srgrimes
5761541Srgrimes	sx_assert(&kld_sx, SA_XLOCKED);
5771541Srgrimes	TAILQ_FOREACH(lf, &linker_files, link)
578182455Sjkim		if (lf->id == fileid && lf->flags & LINKER_FILE_LINKED)
5791541Srgrimes			break;
580182455Sjkim	return (lf);
5811541Srgrimes}
5821541Srgrimes
583int
584linker_file_foreach(linker_predicate_t *predicate, void *context)
585{
586	linker_file_t lf;
587	int retval = 0;
588
589	sx_xlock(&kld_sx);
590	TAILQ_FOREACH(lf, &linker_files, link) {
591		retval = predicate(lf, context);
592		if (retval != 0)
593			break;
594	}
595	sx_xunlock(&kld_sx);
596	return (retval);
597}
598
599linker_file_t
600linker_make_file(const char *pathname, linker_class_t lc)
601{
602	linker_file_t lf;
603	const char *filename;
604
605	if (!cold)
606		sx_assert(&kld_sx, SA_XLOCKED);
607	filename = linker_basename(pathname);
608
609	KLD_DPF(FILE, ("linker_make_file: new file, filename='%s' for pathname='%s'\n", filename, pathname));
610	lf = (linker_file_t)kobj_create((kobj_class_t)lc, M_LINKER, M_WAITOK);
611	if (lf == NULL)
612		return (NULL);
613	lf->ctors_addr = 0;
614	lf->ctors_size = 0;
615	lf->refs = 1;
616	lf->userrefs = 0;
617	lf->flags = 0;
618	lf->filename = strdup(filename, M_LINKER);
619	lf->pathname = strdup(pathname, M_LINKER);
620	LINKER_GET_NEXT_FILE_ID(lf->id);
621	lf->ndeps = 0;
622	lf->deps = NULL;
623	lf->loadcnt = ++loadcnt;
624	STAILQ_INIT(&lf->common);
625	TAILQ_INIT(&lf->modules);
626	TAILQ_INSERT_TAIL(&linker_files, lf, link);
627	return (lf);
628}
629
630int
631linker_file_unload(linker_file_t file, int flags)
632{
633	module_t mod, next;
634	modlist_t ml, nextml;
635	struct common_symbol *cp;
636	int error, i;
637
638	/* Refuse to unload modules if securelevel raised. */
639	if (prison0.pr_securelevel > 0)
640		return (EPERM);
641
642	sx_assert(&kld_sx, SA_XLOCKED);
643	KLD_DPF(FILE, ("linker_file_unload: lf->refs=%d\n", file->refs));
644
645	/* Easy case of just dropping a reference. */
646	if (file->refs > 1) {
647		file->refs--;
648		return (0);
649	}
650
651	/* Give eventhandlers a chance to prevent the unload. */
652	error = 0;
653	EVENTHANDLER_INVOKE(kld_unload_try, file, &error);
654	if (error != 0)
655		return (EBUSY);
656
657	KLD_DPF(FILE, ("linker_file_unload: file is unloading,"
658	    " informing modules\n"));
659
660	/*
661	 * Quiesce all the modules to give them a chance to veto the unload.
662	 */
663	MOD_SLOCK;
664	for (mod = TAILQ_FIRST(&file->modules); mod;
665	     mod = module_getfnext(mod)) {
666
667		error = module_quiesce(mod);
668		if (error != 0 && flags != LINKER_UNLOAD_FORCE) {
669			KLD_DPF(FILE, ("linker_file_unload: module %s"
670			    " vetoed unload\n", module_getname(mod)));
671			/*
672			 * XXX: Do we need to tell all the quiesced modules
673			 * that they can resume work now via a new module
674			 * event?
675			 */
676			MOD_SUNLOCK;
677			return (error);
678		}
679	}
680	MOD_SUNLOCK;
681
682	/*
683	 * Inform any modules associated with this file that they are
684	 * being unloaded.
685	 */
686	MOD_XLOCK;
687	for (mod = TAILQ_FIRST(&file->modules); mod; mod = next) {
688		next = module_getfnext(mod);
689		MOD_XUNLOCK;
690
691		/*
692		 * Give the module a chance to veto the unload.
693		 */
694		if ((error = module_unload(mod)) != 0) {
695#ifdef KLD_DEBUG
696			MOD_SLOCK;
697			KLD_DPF(FILE, ("linker_file_unload: module %s"
698			    " failed unload\n", module_getname(mod)));
699			MOD_SUNLOCK;
700#endif
701			return (error);
702		}
703		MOD_XLOCK;
704		module_release(mod);
705	}
706	MOD_XUNLOCK;
707
708	TAILQ_FOREACH_SAFE(ml, &found_modules, link, nextml) {
709		if (ml->container == file) {
710			TAILQ_REMOVE(&found_modules, ml, link);
711			free(ml, M_LINKER);
712		}
713	}
714
715	/*
716	 * Don't try to run SYSUNINITs if we are unloaded due to a
717	 * link error.
718	 */
719	if (file->flags & LINKER_FILE_LINKED) {
720		file->flags &= ~LINKER_FILE_LINKED;
721		linker_file_unregister_sysctls(file);
722		linker_file_sysuninit(file);
723	}
724	TAILQ_REMOVE(&linker_files, file, link);
725
726	if (file->deps) {
727		for (i = 0; i < file->ndeps; i++)
728			linker_file_unload(file->deps[i], flags);
729		free(file->deps, M_LINKER);
730		file->deps = NULL;
731	}
732	while ((cp = STAILQ_FIRST(&file->common)) != NULL) {
733		STAILQ_REMOVE_HEAD(&file->common, link);
734		free(cp, M_LINKER);
735	}
736
737	LINKER_UNLOAD(file);
738
739	EVENTHANDLER_INVOKE(kld_unload, file->filename, file->address,
740	    file->size);
741
742	if (file->filename) {
743		free(file->filename, M_LINKER);
744		file->filename = NULL;
745	}
746	if (file->pathname) {
747		free(file->pathname, M_LINKER);
748		file->pathname = NULL;
749	}
750	kobj_delete((kobj_t) file, M_LINKER);
751	return (0);
752}
753
754int
755linker_ctf_get(linker_file_t file, linker_ctf_t *lc)
756{
757	return (LINKER_CTF_GET(file, lc));
758}
759
760static int
761linker_file_add_dependency(linker_file_t file, linker_file_t dep)
762{
763	linker_file_t *newdeps;
764
765	sx_assert(&kld_sx, SA_XLOCKED);
766	file->deps = realloc(file->deps, (file->ndeps + 1) * sizeof(*newdeps),
767	    M_LINKER, M_WAITOK | M_ZERO);
768	file->deps[file->ndeps] = dep;
769	file->ndeps++;
770	KLD_DPF(FILE, ("linker_file_add_dependency:"
771	    " adding %s as dependency for %s\n",
772	    dep->filename, file->filename));
773	return (0);
774}
775
776/*
777 * Locate a linker set and its contents.  This is a helper function to avoid
778 * linker_if.h exposure elsewhere.  Note: firstp and lastp are really void **.
779 * This function is used in this file so we can avoid having lots of (void **)
780 * casts.
781 */
782int
783linker_file_lookup_set(linker_file_t file, const char *name,
784    void *firstp, void *lastp, int *countp)
785{
786
787	sx_assert(&kld_sx, SA_LOCKED);
788	return (LINKER_LOOKUP_SET(file, name, firstp, lastp, countp));
789}
790
791/*
792 * List all functions in a file.
793 */
794int
795linker_file_function_listall(linker_file_t lf,
796    linker_function_nameval_callback_t callback_func, void *arg)
797{
798	return (LINKER_EACH_FUNCTION_NAMEVAL(lf, callback_func, arg));
799}
800
801caddr_t
802linker_file_lookup_symbol(linker_file_t file, const char *name, int deps)
803{
804	caddr_t sym;
805	int locked;
806
807	locked = sx_xlocked(&kld_sx);
808	if (!locked)
809		sx_xlock(&kld_sx);
810	sym = linker_file_lookup_symbol_internal(file, name, deps);
811	if (!locked)
812		sx_xunlock(&kld_sx);
813	return (sym);
814}
815
816static caddr_t
817linker_file_lookup_symbol_internal(linker_file_t file, const char *name,
818    int deps)
819{
820	c_linker_sym_t sym;
821	linker_symval_t symval;
822	caddr_t address;
823	size_t common_size = 0;
824	int i;
825
826	sx_assert(&kld_sx, SA_XLOCKED);
827	KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%p, name=%s, deps=%d\n",
828	    file, name, deps));
829
830	if (LINKER_LOOKUP_SYMBOL(file, name, &sym) == 0) {
831		LINKER_SYMBOL_VALUES(file, sym, &symval);
832		if (symval.value == 0)
833			/*
834			 * For commons, first look them up in the
835			 * dependencies and only allocate space if not found
836			 * there.
837			 */
838			common_size = symval.size;
839		else {
840			KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol"
841			    ".value=%p\n", symval.value));
842			return (symval.value);
843		}
844	}
845	if (deps) {
846		for (i = 0; i < file->ndeps; i++) {
847			address = linker_file_lookup_symbol_internal(
848			    file->deps[i], name, 0);
849			if (address) {
850				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
851				    " deps value=%p\n", address));
852				return (address);
853			}
854		}
855	}
856	if (common_size > 0) {
857		/*
858		 * This is a common symbol which was not found in the
859		 * dependencies.  We maintain a simple common symbol table in
860		 * the file object.
861		 */
862		struct common_symbol *cp;
863
864		STAILQ_FOREACH(cp, &file->common, link) {
865			if (strcmp(cp->name, name) == 0) {
866				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
867				    " old common value=%p\n", cp->address));
868				return (cp->address);
869			}
870		}
871		/*
872		 * Round the symbol size up to align.
873		 */
874		common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
875		cp = malloc(sizeof(struct common_symbol)
876		    + common_size + strlen(name) + 1, M_LINKER,
877		    M_WAITOK | M_ZERO);
878		cp->address = (caddr_t)(cp + 1);
879		cp->name = cp->address + common_size;
880		strcpy(cp->name, name);
881		bzero(cp->address, common_size);
882		STAILQ_INSERT_TAIL(&file->common, cp, link);
883
884		KLD_DPF(SYM, ("linker_file_lookup_symbol: new common"
885		    " value=%p\n", cp->address));
886		return (cp->address);
887	}
888	KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
889	return (0);
890}
891
892/*
893 * Both DDB and stack(9) rely on the kernel linker to provide forward and
894 * backward lookup of symbols.  However, DDB and sometimes stack(9) need to
895 * do this in a lockfree manner.  We provide a set of internal helper
896 * routines to perform these operations without locks, and then wrappers that
897 * optionally lock.
898 *
899 * linker_debug_lookup() is ifdef DDB as currently it's only used by DDB.
900 */
901#ifdef DDB
902static int
903linker_debug_lookup(const char *symstr, c_linker_sym_t *sym)
904{
905	linker_file_t lf;
906
907	TAILQ_FOREACH(lf, &linker_files, link) {
908		if (LINKER_LOOKUP_SYMBOL(lf, symstr, sym) == 0)
909			return (0);
910	}
911	return (ENOENT);
912}
913#endif
914
915static int
916linker_debug_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
917{
918	linker_file_t lf;
919	c_linker_sym_t best, es;
920	u_long diff, bestdiff, off;
921
922	best = 0;
923	off = (uintptr_t)value;
924	bestdiff = off;
925	TAILQ_FOREACH(lf, &linker_files, link) {
926		if (LINKER_SEARCH_SYMBOL(lf, value, &es, &diff) != 0)
927			continue;
928		if (es != 0 && diff < bestdiff) {
929			best = es;
930			bestdiff = diff;
931		}
932		if (bestdiff == 0)
933			break;
934	}
935	if (best) {
936		*sym = best;
937		*diffp = bestdiff;
938		return (0);
939	} else {
940		*sym = 0;
941		*diffp = off;
942		return (ENOENT);
943	}
944}
945
946static int
947linker_debug_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
948{
949	linker_file_t lf;
950
951	TAILQ_FOREACH(lf, &linker_files, link) {
952		if (LINKER_SYMBOL_VALUES(lf, sym, symval) == 0)
953			return (0);
954	}
955	return (ENOENT);
956}
957
958static int
959linker_debug_search_symbol_name(caddr_t value, char *buf, u_int buflen,
960    long *offset)
961{
962	linker_symval_t symval;
963	c_linker_sym_t sym;
964	int error;
965
966	*offset = 0;
967	error = linker_debug_search_symbol(value, &sym, offset);
968	if (error)
969		return (error);
970	error = linker_debug_symbol_values(sym, &symval);
971	if (error)
972		return (error);
973	strlcpy(buf, symval.name, buflen);
974	return (0);
975}
976
977/*
978 * DDB Helpers.  DDB has to look across multiple files with their own symbol
979 * tables and string tables.
980 *
981 * Note that we do not obey list locking protocols here.  We really don't need
982 * DDB to hang because somebody's got the lock held.  We'll take the chance
983 * that the files list is inconsistent instead.
984 */
985#ifdef DDB
986int
987linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
988{
989
990	return (linker_debug_lookup(symstr, sym));
991}
992#endif
993
994int
995linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
996{
997
998	return (linker_debug_search_symbol(value, sym, diffp));
999}
1000
1001int
1002linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
1003{
1004
1005	return (linker_debug_symbol_values(sym, symval));
1006}
1007
1008int
1009linker_ddb_search_symbol_name(caddr_t value, char *buf, u_int buflen,
1010    long *offset)
1011{
1012
1013	return (linker_debug_search_symbol_name(value, buf, buflen, offset));
1014}
1015
1016/*
1017 * stack(9) helper for non-debugging environemnts.  Unlike DDB helpers, we do
1018 * obey locking protocols, and offer a significantly less complex interface.
1019 */
1020int
1021linker_search_symbol_name(caddr_t value, char *buf, u_int buflen,
1022    long *offset)
1023{
1024	int error;
1025
1026	sx_slock(&kld_sx);
1027	error = linker_debug_search_symbol_name(value, buf, buflen, offset);
1028	sx_sunlock(&kld_sx);
1029	return (error);
1030}
1031
1032/*
1033 * Syscalls.
1034 */
1035int
1036kern_kldload(struct thread *td, const char *file, int *fileid)
1037{
1038	const char *kldname, *modname;
1039	linker_file_t lf;
1040	int error;
1041
1042	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1043		return (error);
1044
1045	if ((error = priv_check(td, PRIV_KLD_LOAD)) != 0)
1046		return (error);
1047
1048	/*
1049	 * It is possible that kldloaded module will attach a new ifnet,
1050	 * so vnet context must be set when this ocurs.
1051	 */
1052	CURVNET_SET(TD_TO_VNET(td));
1053
1054	/*
1055	 * If file does not contain a qualified name or any dot in it
1056	 * (kldname.ko, or kldname.ver.ko) treat it as an interface
1057	 * name.
1058	 */
1059	if (strchr(file, '/') || strchr(file, '.')) {
1060		kldname = file;
1061		modname = NULL;
1062	} else {
1063		kldname = NULL;
1064		modname = file;
1065	}
1066
1067	sx_xlock(&kld_sx);
1068	error = linker_load_module(kldname, modname, NULL, NULL, &lf);
1069	if (error) {
1070		sx_xunlock(&kld_sx);
1071		goto done;
1072	}
1073	lf->userrefs++;
1074	if (fileid != NULL)
1075		*fileid = lf->id;
1076	sx_xunlock(&kld_sx);
1077
1078done:
1079	CURVNET_RESTORE();
1080	return (error);
1081}
1082
1083int
1084sys_kldload(struct thread *td, struct kldload_args *uap)
1085{
1086	char *pathname = NULL;
1087	int error, fileid;
1088
1089	td->td_retval[0] = -1;
1090
1091	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1092	error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL);
1093	if (error == 0) {
1094		error = kern_kldload(td, pathname, &fileid);
1095		if (error == 0)
1096			td->td_retval[0] = fileid;
1097	}
1098	free(pathname, M_TEMP);
1099	return (error);
1100}
1101
1102int
1103kern_kldunload(struct thread *td, int fileid, int flags)
1104{
1105	linker_file_t lf;
1106	int error = 0;
1107
1108	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1109		return (error);
1110
1111	if ((error = priv_check(td, PRIV_KLD_UNLOAD)) != 0)
1112		return (error);
1113
1114	CURVNET_SET(TD_TO_VNET(td));
1115	sx_xlock(&kld_sx);
1116	lf = linker_find_file_by_id(fileid);
1117	if (lf) {
1118		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
1119
1120		if (lf->userrefs == 0) {
1121			/*
1122			 * XXX: maybe LINKER_UNLOAD_FORCE should override ?
1123			 */
1124			printf("kldunload: attempt to unload file that was"
1125			    " loaded by the kernel\n");
1126			error = EBUSY;
1127		} else {
1128			lf->userrefs--;
1129			error = linker_file_unload(lf, flags);
1130			if (error)
1131				lf->userrefs++;
1132		}
1133	} else
1134		error = ENOENT;
1135	sx_xunlock(&kld_sx);
1136
1137	CURVNET_RESTORE();
1138	return (error);
1139}
1140
1141int
1142sys_kldunload(struct thread *td, struct kldunload_args *uap)
1143{
1144
1145	return (kern_kldunload(td, uap->fileid, LINKER_UNLOAD_NORMAL));
1146}
1147
1148int
1149sys_kldunloadf(struct thread *td, struct kldunloadf_args *uap)
1150{
1151
1152	if (uap->flags != LINKER_UNLOAD_NORMAL &&
1153	    uap->flags != LINKER_UNLOAD_FORCE)
1154		return (EINVAL);
1155	return (kern_kldunload(td, uap->fileid, uap->flags));
1156}
1157
1158int
1159sys_kldfind(struct thread *td, struct kldfind_args *uap)
1160{
1161	char *pathname;
1162	const char *filename;
1163	linker_file_t lf;
1164	int error;
1165
1166#ifdef MAC
1167	error = mac_kld_check_stat(td->td_ucred);
1168	if (error)
1169		return (error);
1170#endif
1171
1172	td->td_retval[0] = -1;
1173
1174	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1175	if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
1176		goto out;
1177
1178	filename = linker_basename(pathname);
1179	sx_xlock(&kld_sx);
1180	lf = linker_find_file_by_name(filename);
1181	if (lf)
1182		td->td_retval[0] = lf->id;
1183	else
1184		error = ENOENT;
1185	sx_xunlock(&kld_sx);
1186out:
1187	free(pathname, M_TEMP);
1188	return (error);
1189}
1190
1191int
1192sys_kldnext(struct thread *td, struct kldnext_args *uap)
1193{
1194	linker_file_t lf;
1195	int error = 0;
1196
1197#ifdef MAC
1198	error = mac_kld_check_stat(td->td_ucred);
1199	if (error)
1200		return (error);
1201#endif
1202
1203	sx_xlock(&kld_sx);
1204	if (uap->fileid == 0)
1205		lf = TAILQ_FIRST(&linker_files);
1206	else {
1207		lf = linker_find_file_by_id(uap->fileid);
1208		if (lf == NULL) {
1209			error = ENOENT;
1210			goto out;
1211		}
1212		lf = TAILQ_NEXT(lf, link);
1213	}
1214
1215	/* Skip partially loaded files. */
1216	while (lf != NULL && !(lf->flags & LINKER_FILE_LINKED))
1217		lf = TAILQ_NEXT(lf, link);
1218
1219	if (lf)
1220		td->td_retval[0] = lf->id;
1221	else
1222		td->td_retval[0] = 0;
1223out:
1224	sx_xunlock(&kld_sx);
1225	return (error);
1226}
1227
1228int
1229sys_kldstat(struct thread *td, struct kldstat_args *uap)
1230{
1231	struct kld_file_stat *stat;
1232	int error, version;
1233
1234	/*
1235	 * Check the version of the user's structure.
1236	 */
1237	if ((error = copyin(&uap->stat->version, &version, sizeof(version)))
1238	    != 0)
1239		return (error);
1240	if (version != sizeof(struct kld_file_stat_1) &&
1241	    version != sizeof(struct kld_file_stat))
1242		return (EINVAL);
1243
1244	stat = malloc(sizeof(*stat), M_TEMP, M_WAITOK | M_ZERO);
1245	error = kern_kldstat(td, uap->fileid, stat);
1246	if (error == 0)
1247		error = copyout(stat, uap->stat, version);
1248	free(stat, M_TEMP);
1249	return (error);
1250}
1251
1252int
1253kern_kldstat(struct thread *td, int fileid, struct kld_file_stat *stat)
1254{
1255	linker_file_t lf;
1256	int namelen;
1257#ifdef MAC
1258	int error;
1259
1260	error = mac_kld_check_stat(td->td_ucred);
1261	if (error)
1262		return (error);
1263#endif
1264
1265	sx_xlock(&kld_sx);
1266	lf = linker_find_file_by_id(fileid);
1267	if (lf == NULL) {
1268		sx_xunlock(&kld_sx);
1269		return (ENOENT);
1270	}
1271
1272	/* Version 1 fields: */
1273	namelen = strlen(lf->filename) + 1;
1274	if (namelen > MAXPATHLEN)
1275		namelen = MAXPATHLEN;
1276	bcopy(lf->filename, &stat->name[0], namelen);
1277	stat->refs = lf->refs;
1278	stat->id = lf->id;
1279	stat->address = lf->address;
1280	stat->size = lf->size;
1281	/* Version 2 fields: */
1282	namelen = strlen(lf->pathname) + 1;
1283	if (namelen > MAXPATHLEN)
1284		namelen = MAXPATHLEN;
1285	bcopy(lf->pathname, &stat->pathname[0], namelen);
1286	sx_xunlock(&kld_sx);
1287
1288	td->td_retval[0] = 0;
1289	return (0);
1290}
1291
1292#ifdef DDB
1293DB_COMMAND(kldstat, db_kldstat)
1294{
1295	linker_file_t lf;
1296
1297#define	POINTER_WIDTH	((int)(sizeof(void *) * 2 + 2))
1298	db_printf("Id Refs Address%*c Size     Name\n", POINTER_WIDTH - 7, ' ');
1299#undef	POINTER_WIDTH
1300	TAILQ_FOREACH(lf, &linker_files, link) {
1301		if (db_pager_quit)
1302			return;
1303		db_printf("%2d %4d %p %-8zx %s\n", lf->id, lf->refs,
1304		    lf->address, lf->size, lf->filename);
1305	}
1306}
1307#endif /* DDB */
1308
1309int
1310sys_kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
1311{
1312	linker_file_t lf;
1313	module_t mp;
1314	int error = 0;
1315
1316#ifdef MAC
1317	error = mac_kld_check_stat(td->td_ucred);
1318	if (error)
1319		return (error);
1320#endif
1321
1322	sx_xlock(&kld_sx);
1323	lf = linker_find_file_by_id(uap->fileid);
1324	if (lf) {
1325		MOD_SLOCK;
1326		mp = TAILQ_FIRST(&lf->modules);
1327		if (mp != NULL)
1328			td->td_retval[0] = module_getid(mp);
1329		else
1330			td->td_retval[0] = 0;
1331		MOD_SUNLOCK;
1332	} else
1333		error = ENOENT;
1334	sx_xunlock(&kld_sx);
1335	return (error);
1336}
1337
1338int
1339sys_kldsym(struct thread *td, struct kldsym_args *uap)
1340{
1341	char *symstr = NULL;
1342	c_linker_sym_t sym;
1343	linker_symval_t symval;
1344	linker_file_t lf;
1345	struct kld_sym_lookup lookup;
1346	int error = 0;
1347
1348#ifdef MAC
1349	error = mac_kld_check_stat(td->td_ucred);
1350	if (error)
1351		return (error);
1352#endif
1353
1354	if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
1355		return (error);
1356	if (lookup.version != sizeof(lookup) ||
1357	    uap->cmd != KLDSYM_LOOKUP)
1358		return (EINVAL);
1359	symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1360	if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
1361		goto out;
1362	sx_xlock(&kld_sx);
1363	if (uap->fileid != 0) {
1364		lf = linker_find_file_by_id(uap->fileid);
1365		if (lf == NULL)
1366			error = ENOENT;
1367		else if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1368		    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1369			lookup.symvalue = (uintptr_t) symval.value;
1370			lookup.symsize = symval.size;
1371			error = copyout(&lookup, uap->data, sizeof(lookup));
1372		} else
1373			error = ENOENT;
1374	} else {
1375		TAILQ_FOREACH(lf, &linker_files, link) {
1376			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,
1381				    sizeof(lookup));
1382				break;
1383			}
1384		}
1385		if (lf == NULL)
1386			error = ENOENT;
1387	}
1388	sx_xunlock(&kld_sx);
1389out:
1390	free(symstr, M_TEMP);
1391	return (error);
1392}
1393
1394/*
1395 * Preloaded module support
1396 */
1397
1398static modlist_t
1399modlist_lookup(const char *name, int ver)
1400{
1401	modlist_t mod;
1402
1403	TAILQ_FOREACH(mod, &found_modules, link) {
1404		if (strcmp(mod->name, name) == 0 &&
1405		    (ver == 0 || mod->version == ver))
1406			return (mod);
1407	}
1408	return (NULL);
1409}
1410
1411static modlist_t
1412modlist_lookup2(const char *name, const struct mod_depend *verinfo)
1413{
1414	modlist_t mod, bestmod;
1415	int ver;
1416
1417	if (verinfo == NULL)
1418		return (modlist_lookup(name, 0));
1419	bestmod = NULL;
1420	TAILQ_FOREACH(mod, &found_modules, link) {
1421		if (strcmp(mod->name, name) != 0)
1422			continue;
1423		ver = mod->version;
1424		if (ver == verinfo->md_ver_preferred)
1425			return (mod);
1426		if (ver >= verinfo->md_ver_minimum &&
1427		    ver <= verinfo->md_ver_maximum &&
1428		    (bestmod == NULL || ver > bestmod->version))
1429			bestmod = mod;
1430	}
1431	return (bestmod);
1432}
1433
1434static modlist_t
1435modlist_newmodule(const char *modname, int version, linker_file_t container)
1436{
1437	modlist_t mod;
1438
1439	mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1440	if (mod == NULL)
1441		panic("no memory for module list");
1442	mod->container = container;
1443	mod->name = modname;
1444	mod->version = version;
1445	TAILQ_INSERT_TAIL(&found_modules, mod, link);
1446	return (mod);
1447}
1448
1449static void
1450linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1451    struct mod_metadata **stop, int preload)
1452{
1453	struct mod_metadata *mp, **mdp;
1454	const char *modname;
1455	int ver;
1456
1457	for (mdp = start; mdp < stop; mdp++) {
1458		mp = *mdp;
1459		if (mp->md_type != MDT_VERSION)
1460			continue;
1461		modname = mp->md_cval;
1462		ver = ((const struct mod_version *)mp->md_data)->mv_version;
1463		if (modlist_lookup(modname, ver) != NULL) {
1464			printf("module %s already present!\n", modname);
1465			/* XXX what can we do? this is a build error. :-( */
1466			continue;
1467		}
1468		modlist_newmodule(modname, ver, lf);
1469	}
1470}
1471
1472static void
1473linker_preload(void *arg)
1474{
1475	caddr_t modptr;
1476	const char *modname, *nmodname;
1477	char *modtype;
1478	linker_file_t lf, nlf;
1479	linker_class_t lc;
1480	int error;
1481	linker_file_list_t loaded_files;
1482	linker_file_list_t depended_files;
1483	struct mod_metadata *mp, *nmp;
1484	struct mod_metadata **start, **stop, **mdp, **nmdp;
1485	const struct mod_depend *verinfo;
1486	int nver;
1487	int resolves;
1488	modlist_t mod;
1489	struct sysinit **si_start, **si_stop;
1490
1491	TAILQ_INIT(&loaded_files);
1492	TAILQ_INIT(&depended_files);
1493	TAILQ_INIT(&found_modules);
1494	error = 0;
1495
1496	modptr = NULL;
1497	sx_xlock(&kld_sx);
1498	while ((modptr = preload_search_next_name(modptr)) != NULL) {
1499		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1500		modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1501		if (modname == NULL) {
1502			printf("Preloaded module at %p does not have a"
1503			    " name!\n", modptr);
1504			continue;
1505		}
1506		if (modtype == NULL) {
1507			printf("Preloaded module at %p does not have a type!\n",
1508			    modptr);
1509			continue;
1510		}
1511		if (bootverbose)
1512			printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1513			    modptr);
1514		lf = NULL;
1515		TAILQ_FOREACH(lc, &classes, link) {
1516			error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1517			if (!error)
1518				break;
1519			lf = NULL;
1520		}
1521		if (lf)
1522			TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1523	}
1524
1525	/*
1526	 * First get a list of stuff in the kernel.
1527	 */
1528	if (linker_file_lookup_set(linker_kernel_file, MDT_SETNAME, &start,
1529	    &stop, NULL) == 0)
1530		linker_addmodules(linker_kernel_file, start, stop, 1);
1531
1532	/*
1533	 * This is a once-off kinky bubble sort to resolve relocation
1534	 * dependency requirements.
1535	 */
1536restart:
1537	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1538		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1539		    &stop, NULL);
1540		/*
1541		 * First, look to see if we would successfully link with this
1542		 * stuff.
1543		 */
1544		resolves = 1;	/* unless we know otherwise */
1545		if (!error) {
1546			for (mdp = start; mdp < stop; mdp++) {
1547				mp = *mdp;
1548				if (mp->md_type != MDT_DEPEND)
1549					continue;
1550				modname = mp->md_cval;
1551				verinfo = mp->md_data;
1552				for (nmdp = start; nmdp < stop; nmdp++) {
1553					nmp = *nmdp;
1554					if (nmp->md_type != MDT_VERSION)
1555						continue;
1556					nmodname = nmp->md_cval;
1557					if (strcmp(modname, nmodname) == 0)
1558						break;
1559				}
1560				if (nmdp < stop)   /* it's a self reference */
1561					continue;
1562
1563				/*
1564				 * ok, the module isn't here yet, we
1565				 * are not finished
1566				 */
1567				if (modlist_lookup2(modname, verinfo) == NULL)
1568					resolves = 0;
1569			}
1570		}
1571		/*
1572		 * OK, if we found our modules, we can link.  So, "provide"
1573		 * the modules inside and add it to the end of the link order
1574		 * list.
1575		 */
1576		if (resolves) {
1577			if (!error) {
1578				for (mdp = start; mdp < stop; mdp++) {
1579					mp = *mdp;
1580					if (mp->md_type != MDT_VERSION)
1581						continue;
1582					modname = mp->md_cval;
1583					nver = ((const struct mod_version *)
1584					    mp->md_data)->mv_version;
1585					if (modlist_lookup(modname,
1586					    nver) != NULL) {
1587						printf("module %s already"
1588						    " present!\n", modname);
1589						TAILQ_REMOVE(&loaded_files,
1590						    lf, loaded);
1591						linker_file_unload(lf,
1592						    LINKER_UNLOAD_FORCE);
1593						/* we changed tailq next ptr */
1594						goto restart;
1595					}
1596					modlist_newmodule(modname, nver, lf);
1597				}
1598			}
1599			TAILQ_REMOVE(&loaded_files, lf, loaded);
1600			TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1601			/*
1602			 * Since we provided modules, we need to restart the
1603			 * sort so that the previous files that depend on us
1604			 * have a chance. Also, we've busted the tailq next
1605			 * pointer with the REMOVE.
1606			 */
1607			goto restart;
1608		}
1609	}
1610
1611	/*
1612	 * At this point, we check to see what could not be resolved..
1613	 */
1614	while ((lf = TAILQ_FIRST(&loaded_files)) != NULL) {
1615		TAILQ_REMOVE(&loaded_files, lf, loaded);
1616		printf("KLD file %s is missing dependencies\n", lf->filename);
1617		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1618	}
1619
1620	/*
1621	 * We made it. Finish off the linking in the order we determined.
1622	 */
1623	TAILQ_FOREACH_SAFE(lf, &depended_files, loaded, nlf) {
1624		if (linker_kernel_file) {
1625			linker_kernel_file->refs++;
1626			error = linker_file_add_dependency(lf,
1627			    linker_kernel_file);
1628			if (error)
1629				panic("cannot add dependency");
1630		}
1631		lf->userrefs++;	/* so we can (try to) kldunload it */
1632		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1633		    &stop, NULL);
1634		if (!error) {
1635			for (mdp = start; mdp < stop; mdp++) {
1636				mp = *mdp;
1637				if (mp->md_type != MDT_DEPEND)
1638					continue;
1639				modname = mp->md_cval;
1640				verinfo = mp->md_data;
1641				mod = modlist_lookup2(modname, verinfo);
1642				if (mod == NULL) {
1643					printf("KLD file %s - cannot find "
1644					    "dependency \"%s\"\n",
1645					    lf->filename, modname);
1646					goto fail;
1647				}
1648				/* Don't count self-dependencies */
1649				if (lf == mod->container)
1650					continue;
1651				mod->container->refs++;
1652				error = linker_file_add_dependency(lf,
1653				    mod->container);
1654				if (error)
1655					panic("cannot add dependency");
1656			}
1657		}
1658		/*
1659		 * Now do relocation etc using the symbol search paths
1660		 * established by the dependencies
1661		 */
1662		error = LINKER_LINK_PRELOAD_FINISH(lf);
1663		if (error) {
1664			printf("KLD file %s - could not finalize loading\n",
1665			    lf->filename);
1666			goto fail;
1667		}
1668		linker_file_register_modules(lf);
1669		if (linker_file_lookup_set(lf, "sysinit_set", &si_start,
1670		    &si_stop, NULL) == 0)
1671			sysinit_add(si_start, si_stop);
1672		linker_file_register_sysctls(lf, true);
1673		lf->flags |= LINKER_FILE_LINKED;
1674		continue;
1675fail:
1676		TAILQ_REMOVE(&depended_files, lf, loaded);
1677		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1678	}
1679	sx_xunlock(&kld_sx);
1680	/* woohoo! we made it! */
1681}
1682
1683SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, 0);
1684
1685/*
1686 * Search for a not-loaded module by name.
1687 *
1688 * Modules may be found in the following locations:
1689 *
1690 * - preloaded (result is just the module name) - on disk (result is full path
1691 * to module)
1692 *
1693 * If the module name is qualified in any way (contains path, etc.) the we
1694 * simply return a copy of it.
1695 *
1696 * The search path can be manipulated via sysctl.  Note that we use the ';'
1697 * character as a separator to be consistent with the bootloader.
1698 */
1699
1700static char linker_hintfile[] = "linker.hints";
1701static char linker_path[MAXPATHLEN] = "/boot/kernel;/boot/modules";
1702
1703SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RWTUN, linker_path,
1704    sizeof(linker_path), "module load search path");
1705
1706TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1707
1708static char *linker_ext_list[] = {
1709	"",
1710	".ko",
1711	NULL
1712};
1713
1714/*
1715 * Check if file actually exists either with or without extension listed in
1716 * the linker_ext_list. (probably should be generic for the rest of the
1717 * kernel)
1718 */
1719static char *
1720linker_lookup_file(const char *path, int pathlen, const char *name,
1721    int namelen, struct vattr *vap)
1722{
1723	struct nameidata nd;
1724	struct thread *td = curthread;	/* XXX */
1725	char *result, **cpp, *sep;
1726	int error, len, extlen, reclen, flags;
1727	enum vtype type;
1728
1729	extlen = 0;
1730	for (cpp = linker_ext_list; *cpp; cpp++) {
1731		len = strlen(*cpp);
1732		if (len > extlen)
1733			extlen = len;
1734	}
1735	extlen++;		/* trailing '\0' */
1736	sep = (path[pathlen - 1] != '/') ? "/" : "";
1737
1738	reclen = pathlen + strlen(sep) + namelen + extlen + 1;
1739	result = malloc(reclen, M_LINKER, M_WAITOK);
1740	for (cpp = linker_ext_list; *cpp; cpp++) {
1741		snprintf(result, reclen, "%.*s%s%.*s%s", pathlen, path, sep,
1742		    namelen, name, *cpp);
1743		/*
1744		 * Attempt to open the file, and return the path if
1745		 * we succeed and it's a regular file.
1746		 */
1747		NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, result, td);
1748		flags = FREAD;
1749		error = vn_open(&nd, &flags, 0, NULL);
1750		if (error == 0) {
1751			NDFREE(&nd, NDF_ONLY_PNBUF);
1752			type = nd.ni_vp->v_type;
1753			if (vap)
1754				VOP_GETATTR(nd.ni_vp, vap, td->td_ucred);
1755			VOP_UNLOCK(nd.ni_vp, 0);
1756			vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1757			if (type == VREG)
1758				return (result);
1759		}
1760	}
1761	free(result, M_LINKER);
1762	return (NULL);
1763}
1764
1765#define	INT_ALIGN(base, ptr)	ptr =					\
1766	(base) + roundup2((ptr) - (base), sizeof(int))
1767
1768/*
1769 * Lookup KLD which contains requested module in the "linker.hints" file. If
1770 * version specification is available, then try to find the best KLD.
1771 * Otherwise just find the latest one.
1772 */
1773static char *
1774linker_hints_lookup(const char *path, int pathlen, const char *modname,
1775    int modnamelen, const struct mod_depend *verinfo)
1776{
1777	struct thread *td = curthread;	/* XXX */
1778	struct ucred *cred = td ? td->td_ucred : NULL;
1779	struct nameidata nd;
1780	struct vattr vattr, mattr;
1781	u_char *hints = NULL;
1782	u_char *cp, *recptr, *bufend, *result, *best, *pathbuf, *sep;
1783	int error, ival, bestver, *intp, found, flags, clen, blen;
1784	ssize_t reclen;
1785
1786	result = NULL;
1787	bestver = found = 0;
1788
1789	sep = (path[pathlen - 1] != '/') ? "/" : "";
1790	reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
1791	    strlen(sep) + 1;
1792	pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
1793	snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
1794	    linker_hintfile);
1795
1796	NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, pathbuf, td);
1797	flags = FREAD;
1798	error = vn_open(&nd, &flags, 0, NULL);
1799	if (error)
1800		goto bad;
1801	NDFREE(&nd, NDF_ONLY_PNBUF);
1802	if (nd.ni_vp->v_type != VREG)
1803		goto bad;
1804	best = cp = NULL;
1805	error = VOP_GETATTR(nd.ni_vp, &vattr, cred);
1806	if (error)
1807		goto bad;
1808	/*
1809	 * XXX: we need to limit this number to some reasonable value
1810	 */
1811	if (vattr.va_size > LINKER_HINTS_MAX) {
1812		printf("hints file too large %ld\n", (long)vattr.va_size);
1813		goto bad;
1814	}
1815	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
1816	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
1817	    UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &reclen, td);
1818	if (error)
1819		goto bad;
1820	VOP_UNLOCK(nd.ni_vp, 0);
1821	vn_close(nd.ni_vp, FREAD, cred, td);
1822	nd.ni_vp = NULL;
1823	if (reclen != 0) {
1824		printf("can't read %zd\n", reclen);
1825		goto bad;
1826	}
1827	intp = (int *)hints;
1828	ival = *intp++;
1829	if (ival != LINKER_HINTS_VERSION) {
1830		printf("hints file version mismatch %d\n", ival);
1831		goto bad;
1832	}
1833	bufend = hints + vattr.va_size;
1834	recptr = (u_char *)intp;
1835	clen = blen = 0;
1836	while (recptr < bufend && !found) {
1837		intp = (int *)recptr;
1838		reclen = *intp++;
1839		ival = *intp++;
1840		cp = (char *)intp;
1841		switch (ival) {
1842		case MDT_VERSION:
1843			clen = *cp++;
1844			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1845				break;
1846			cp += clen;
1847			INT_ALIGN(hints, cp);
1848			ival = *(int *)cp;
1849			cp += sizeof(int);
1850			clen = *cp++;
1851			if (verinfo == NULL ||
1852			    ival == verinfo->md_ver_preferred) {
1853				found = 1;
1854				break;
1855			}
1856			if (ival >= verinfo->md_ver_minimum &&
1857			    ival <= verinfo->md_ver_maximum &&
1858			    ival > bestver) {
1859				bestver = ival;
1860				best = cp;
1861				blen = clen;
1862			}
1863			break;
1864		default:
1865			break;
1866		}
1867		recptr += reclen + sizeof(int);
1868	}
1869	/*
1870	 * Finally check if KLD is in the place
1871	 */
1872	if (found)
1873		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
1874	else if (best)
1875		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
1876
1877	/*
1878	 * KLD is newer than hints file. What we should do now?
1879	 */
1880	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
1881		printf("warning: KLD '%s' is newer than the linker.hints"
1882		    " file\n", result);
1883bad:
1884	free(pathbuf, M_LINKER);
1885	if (hints)
1886		free(hints, M_TEMP);
1887	if (nd.ni_vp != NULL) {
1888		VOP_UNLOCK(nd.ni_vp, 0);
1889		vn_close(nd.ni_vp, FREAD, cred, td);
1890	}
1891	/*
1892	 * If nothing found or hints is absent - fallback to the old
1893	 * way by using "kldname[.ko]" as module name.
1894	 */
1895	if (!found && !bestver && result == NULL)
1896		result = linker_lookup_file(path, pathlen, modname,
1897		    modnamelen, NULL);
1898	return (result);
1899}
1900
1901/*
1902 * Lookup KLD which contains requested module in the all directories.
1903 */
1904static char *
1905linker_search_module(const char *modname, int modnamelen,
1906    const struct mod_depend *verinfo)
1907{
1908	char *cp, *ep, *result;
1909
1910	/*
1911	 * traverse the linker path
1912	 */
1913	for (cp = linker_path; *cp; cp = ep + 1) {
1914		/* find the end of this component */
1915		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
1916		result = linker_hints_lookup(cp, ep - cp, modname,
1917		    modnamelen, verinfo);
1918		if (result != NULL)
1919			return (result);
1920		if (*ep == 0)
1921			break;
1922	}
1923	return (NULL);
1924}
1925
1926/*
1927 * Search for module in all directories listed in the linker_path.
1928 */
1929static char *
1930linker_search_kld(const char *name)
1931{
1932	char *cp, *ep, *result;
1933	int len;
1934
1935	/* qualified at all? */
1936	if (strchr(name, '/'))
1937		return (strdup(name, M_LINKER));
1938
1939	/* traverse the linker path */
1940	len = strlen(name);
1941	for (ep = linker_path; *ep; ep++) {
1942		cp = ep;
1943		/* find the end of this component */
1944		for (; *ep != 0 && *ep != ';'; ep++);
1945		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
1946		if (result != NULL)
1947			return (result);
1948	}
1949	return (NULL);
1950}
1951
1952static const char *
1953linker_basename(const char *path)
1954{
1955	const char *filename;
1956
1957	filename = strrchr(path, '/');
1958	if (filename == NULL)
1959		return path;
1960	if (filename[1])
1961		filename++;
1962	return (filename);
1963}
1964
1965#ifdef HWPMC_HOOKS
1966/*
1967 * Inform hwpmc about the set of kernel modules currently loaded.
1968 */
1969void *
1970linker_hwpmc_list_objects(void)
1971{
1972	linker_file_t lf;
1973	struct pmckern_map_in *kobase;
1974	int i, nmappings;
1975
1976	nmappings = 0;
1977	sx_slock(&kld_sx);
1978	TAILQ_FOREACH(lf, &linker_files, link)
1979		nmappings++;
1980
1981	/* Allocate nmappings + 1 entries. */
1982	kobase = malloc((nmappings + 1) * sizeof(struct pmckern_map_in),
1983	    M_LINKER, M_WAITOK | M_ZERO);
1984	i = 0;
1985	TAILQ_FOREACH(lf, &linker_files, link) {
1986
1987		/* Save the info for this linker file. */
1988		kobase[i].pm_file = lf->filename;
1989		kobase[i].pm_address = (uintptr_t)lf->address;
1990		i++;
1991	}
1992	sx_sunlock(&kld_sx);
1993
1994	KASSERT(i > 0, ("linker_hpwmc_list_objects: no kernel objects?"));
1995
1996	/* The last entry of the malloced area comprises of all zeros. */
1997	KASSERT(kobase[i].pm_file == NULL,
1998	    ("linker_hwpmc_list_objects: last object not NULL"));
1999
2000	return ((void *)kobase);
2001}
2002#endif
2003
2004/*
2005 * Find a file which contains given module and load it, if "parent" is not
2006 * NULL, register a reference to it.
2007 */
2008static int
2009linker_load_module(const char *kldname, const char *modname,
2010    struct linker_file *parent, const struct mod_depend *verinfo,
2011    struct linker_file **lfpp)
2012{
2013	linker_file_t lfdep;
2014	const char *filename;
2015	char *pathname;
2016	int error;
2017
2018	sx_assert(&kld_sx, SA_XLOCKED);
2019	if (modname == NULL) {
2020		/*
2021 		 * We have to load KLD
2022 		 */
2023		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
2024		    " is not NULL"));
2025		pathname = linker_search_kld(kldname);
2026	} else {
2027		if (modlist_lookup2(modname, verinfo) != NULL)
2028			return (EEXIST);
2029		if (kldname != NULL)
2030			pathname = strdup(kldname, M_LINKER);
2031		else if (rootvnode == NULL)
2032			pathname = NULL;
2033		else
2034			/*
2035			 * Need to find a KLD with required module
2036			 */
2037			pathname = linker_search_module(modname,
2038			    strlen(modname), verinfo);
2039	}
2040	if (pathname == NULL)
2041		return (ENOENT);
2042
2043	/*
2044	 * Can't load more than one file with the same basename XXX:
2045	 * Actually it should be possible to have multiple KLDs with
2046	 * the same basename but different path because they can
2047	 * provide different versions of the same modules.
2048	 */
2049	filename = linker_basename(pathname);
2050	if (linker_find_file_by_name(filename))
2051		error = EEXIST;
2052	else do {
2053		error = linker_load_file(pathname, &lfdep);
2054		if (error)
2055			break;
2056		if (modname && verinfo &&
2057		    modlist_lookup2(modname, verinfo) == NULL) {
2058			linker_file_unload(lfdep, LINKER_UNLOAD_FORCE);
2059			error = ENOENT;
2060			break;
2061		}
2062		if (parent) {
2063			error = linker_file_add_dependency(parent, lfdep);
2064			if (error)
2065				break;
2066		}
2067		if (lfpp)
2068			*lfpp = lfdep;
2069	} while (0);
2070	free(pathname, M_LINKER);
2071	return (error);
2072}
2073
2074/*
2075 * This routine is responsible for finding dependencies of userland initiated
2076 * kldload(2)'s of files.
2077 */
2078int
2079linker_load_dependencies(linker_file_t lf)
2080{
2081	linker_file_t lfdep;
2082	struct mod_metadata **start, **stop, **mdp, **nmdp;
2083	struct mod_metadata *mp, *nmp;
2084	const struct mod_depend *verinfo;
2085	modlist_t mod;
2086	const char *modname, *nmodname;
2087	int ver, error = 0, count;
2088
2089	/*
2090	 * All files are dependent on /kernel.
2091	 */
2092	sx_assert(&kld_sx, SA_XLOCKED);
2093	if (linker_kernel_file) {
2094		linker_kernel_file->refs++;
2095		error = linker_file_add_dependency(lf, linker_kernel_file);
2096		if (error)
2097			return (error);
2098	}
2099	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
2100	    &count) != 0)
2101		return (0);
2102	for (mdp = start; mdp < stop; mdp++) {
2103		mp = *mdp;
2104		if (mp->md_type != MDT_VERSION)
2105			continue;
2106		modname = mp->md_cval;
2107		ver = ((const struct mod_version *)mp->md_data)->mv_version;
2108		mod = modlist_lookup(modname, ver);
2109		if (mod != NULL) {
2110			printf("interface %s.%d already present in the KLD"
2111			    " '%s'!\n", modname, ver,
2112			    mod->container->filename);
2113			return (EEXIST);
2114		}
2115	}
2116
2117	for (mdp = start; mdp < stop; mdp++) {
2118		mp = *mdp;
2119		if (mp->md_type != MDT_DEPEND)
2120			continue;
2121		modname = mp->md_cval;
2122		verinfo = mp->md_data;
2123		nmodname = NULL;
2124		for (nmdp = start; nmdp < stop; nmdp++) {
2125			nmp = *nmdp;
2126			if (nmp->md_type != MDT_VERSION)
2127				continue;
2128			nmodname = nmp->md_cval;
2129			if (strcmp(modname, nmodname) == 0)
2130				break;
2131		}
2132		if (nmdp < stop)/* early exit, it's a self reference */
2133			continue;
2134		mod = modlist_lookup2(modname, verinfo);
2135		if (mod) {	/* woohoo, it's loaded already */
2136			lfdep = mod->container;
2137			lfdep->refs++;
2138			error = linker_file_add_dependency(lf, lfdep);
2139			if (error)
2140				break;
2141			continue;
2142		}
2143		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
2144		if (error) {
2145			printf("KLD %s: depends on %s - not available or"
2146			    " version mismatch\n", lf->filename, modname);
2147			break;
2148		}
2149	}
2150
2151	if (error)
2152		return (error);
2153	linker_addmodules(lf, start, stop, 0);
2154	return (error);
2155}
2156
2157static int
2158sysctl_kern_function_list_iterate(const char *name, void *opaque)
2159{
2160	struct sysctl_req *req;
2161
2162	req = opaque;
2163	return (SYSCTL_OUT(req, name, strlen(name) + 1));
2164}
2165
2166/*
2167 * Export a nul-separated, double-nul-terminated list of all function names
2168 * in the kernel.
2169 */
2170static int
2171sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
2172{
2173	linker_file_t lf;
2174	int error;
2175
2176#ifdef MAC
2177	error = mac_kld_check_stat(req->td->td_ucred);
2178	if (error)
2179		return (error);
2180#endif
2181	error = sysctl_wire_old_buffer(req, 0);
2182	if (error != 0)
2183		return (error);
2184	sx_xlock(&kld_sx);
2185	TAILQ_FOREACH(lf, &linker_files, link) {
2186		error = LINKER_EACH_FUNCTION_NAME(lf,
2187		    sysctl_kern_function_list_iterate, req);
2188		if (error) {
2189			sx_xunlock(&kld_sx);
2190			return (error);
2191		}
2192	}
2193	sx_xunlock(&kld_sx);
2194	return (SYSCTL_OUT(req, "", 1));
2195}
2196
2197SYSCTL_PROC(_kern, OID_AUTO, function_list, CTLTYPE_OPAQUE | CTLFLAG_RD,
2198    NULL, 0, sysctl_kern_function_list, "", "kernel function list");
2199