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