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