9a17d120109bbf7c101a984bac059c88fd404b95
[dragonfly.git] / sys / kern / kern_linker.c
1 /*-
2  * Copyright (c) 1997 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  * $FreeBSD: src/sys/kern/kern_linker.c,v 1.41.2.3 2001/11/21 17:50:35 luigi Exp $
27  * $DragonFly: src/sys/kern/kern_linker.c,v 1.37 2007/05/19 19:33:02 dillon Exp $
28  */
29
30 #include "opt_ddb.h"
31
32 #include <sys/param.h>
33 #include <sys/kernel.h>
34 #include <sys/systm.h>
35 #include <sys/malloc.h>
36 #include <sys/sysproto.h>
37 #include <sys/sysent.h>
38 #include <sys/proc.h>
39 #include <sys/lock.h>
40 #include <sys/module.h>
41 #include <sys/linker.h>
42 #include <sys/fcntl.h>
43 #include <sys/libkern.h>
44 #include <sys/nlookup.h>
45 #include <sys/vnode.h>
46 #include <sys/sysctl.h>
47
48 #include <vm/vm_zone.h>
49
50 #ifdef KLD_DEBUG
51 int kld_debug = 0;
52 #endif
53
54 /* Metadata from the static kernel */
55 SET_DECLARE(modmetadata_set, struct mod_metadata);
56 MALLOC_DEFINE(M_LINKER, "kld", "kernel linker");
57
58 linker_file_t linker_current_file;
59 linker_file_t linker_kernel_file;
60
61 static struct lock lock;        /* lock for the file list */
62 static linker_class_list_t classes;
63 static linker_file_list_t linker_files;
64 static int next_file_id = 1;
65
66 static void
67 linker_init(void* arg)
68 {
69     lockinit(&lock, "klink", 0, 0);
70     TAILQ_INIT(&classes);
71     TAILQ_INIT(&linker_files);
72 }
73
74 SYSINIT(linker, SI_BOOT2_KLD, SI_ORDER_FIRST, linker_init, 0);
75
76 int
77 linker_add_class(const char* desc, void* priv,
78                  struct linker_class_ops* ops)
79 {
80     linker_class_t lc;
81
82     lc = kmalloc(sizeof(struct linker_class), M_LINKER, M_NOWAIT);
83     if (!lc)
84         return ENOMEM;
85     bzero(lc, sizeof(*lc));
86
87     lc->desc = desc;
88     lc->priv = priv;
89     lc->ops = ops;
90     TAILQ_INSERT_HEAD(&classes, lc, link);
91
92     return 0;
93 }
94
95 static int
96 linker_file_sysinit(linker_file_t lf)
97 {
98     struct sysinit** start, ** stop;
99     struct sysinit** sipp;
100     struct sysinit** xipp;
101     struct sysinit* save;
102     const moduledata_t *moddata;
103     int error;
104
105     KLD_DPF(FILE, ("linker_file_sysinit: calling SYSINITs for %s\n",
106                    lf->filename));
107
108     if (linker_file_lookup_set(lf, "sysinit_set", &start, &stop, NULL) != 0)
109         return 0; /* XXX is this correct ? No sysinit ? */
110
111     /* HACK ALERT! */
112     for (sipp = start; sipp < stop; sipp++) {
113         if ((*sipp)->func == module_register_init) {
114             moddata = (*sipp)->udata;
115             error = module_register(moddata, lf);
116             if (error) {
117                 kprintf("linker_file_sysinit \"%s\" failed to register! %d\n",
118                     lf->filename, error);
119                 return error;
120             }
121         }
122     }
123             
124     /*
125      * Perform a bubble sort of the system initialization objects by
126      * their subsystem (primary key) and order (secondary key).
127      *
128      * Since some things care about execution order, this is the
129      * operation which ensures continued function.
130      */
131     for (sipp = start; sipp < stop; sipp++) {
132         for (xipp = sipp + 1; xipp < stop; xipp++) {
133             if ((*sipp)->subsystem < (*xipp)->subsystem ||
134                  ((*sipp)->subsystem == (*xipp)->subsystem &&
135                   (*sipp)->order <= (*xipp)->order))
136                 continue;       /* skip*/
137             save = *sipp;
138             *sipp = *xipp;
139             *xipp = save;
140         }
141     }
142
143
144     /*
145      * Traverse the (now) ordered list of system initialization tasks.
146      * Perform each task, and continue on to the next task.
147      */
148     for (sipp = start; sipp < stop; sipp++) {
149         if ((*sipp)->subsystem == SI_SPECIAL_DUMMY)
150             continue;   /* skip dummy task(s)*/
151
152         /* Call function */
153         (*((*sipp)->func))((*sipp)->udata);
154     }
155     return 0; /* no errors */
156 }
157
158 static void
159 linker_file_sysuninit(linker_file_t lf)
160 {
161     struct sysinit** start, ** stop;
162     struct sysinit** sipp;
163     struct sysinit** xipp;
164     struct sysinit* save;
165
166     KLD_DPF(FILE, ("linker_file_sysuninit: calling SYSUNINITs for %s\n",
167                    lf->filename));
168
169     if (linker_file_lookup_set(lf, "sysuninit_set", &start, &stop, NULL) != 0)
170         return;
171
172     /*
173      * Perform a reverse bubble sort of the system initialization objects
174      * by their subsystem (primary key) and order (secondary key).
175      *
176      * Since some things care about execution order, this is the
177      * operation which ensures continued function.
178      */
179     for (sipp = start; sipp < stop; sipp++) {
180         for (xipp = sipp + 1; xipp < stop; xipp++) {
181             if ((*sipp)->subsystem > (*xipp)->subsystem ||
182                  ((*sipp)->subsystem == (*xipp)->subsystem &&
183                   (*sipp)->order >= (*xipp)->order))
184                 continue;       /* skip*/
185             save = *sipp;
186             *sipp = *xipp;
187             *xipp = save;
188         }
189     }
190
191
192     /*
193      * Traverse the (now) ordered list of system initialization tasks.
194      * Perform each task, and continue on to the next task.
195      */
196     for (sipp = start; sipp < stop; sipp++) {
197         if ((*sipp)->subsystem == SI_SPECIAL_DUMMY)
198             continue;   /* skip dummy task(s)*/
199
200         /* Call function */
201         (*((*sipp)->func))((*sipp)->udata);
202     }
203 }
204
205 static void
206 linker_file_register_sysctls(linker_file_t lf)
207 {
208     struct sysctl_oid **start, **stop, **oidp;
209
210     KLD_DPF(FILE, ("linker_file_register_sysctls: registering SYSCTLs for %s\n",
211                    lf->filename));
212
213     if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
214         return;
215     for (oidp = start; oidp < stop; oidp++)
216         sysctl_register_oid(*oidp);
217 }
218
219 static void
220 linker_file_unregister_sysctls(linker_file_t lf)
221 {
222     struct sysctl_oid **start, **stop, **oidp;
223
224     KLD_DPF(FILE, ("linker_file_unregister_sysctls: registering SYSCTLs for %s\n",
225                    lf->filename));
226
227     if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
228         return;
229     for (oidp = start; oidp < stop; oidp++)
230         sysctl_unregister_oid(*oidp);
231 }
232
233 int
234 linker_load_file(const char* filename, linker_file_t* result)
235 {
236     linker_class_t lc;
237     linker_file_t lf;
238     int foundfile, error = 0;
239     char *koname = NULL;
240
241     /* Refuse to load modules if securelevel raised */
242     if (securelevel > 0 || kernel_mem_readonly)
243         return EPERM; 
244
245     lf = linker_find_file_by_name(filename);
246     if (lf) {
247         KLD_DPF(FILE, ("linker_load_file: file %s is already loaded, incrementing refs\n", filename));
248         *result = lf;
249         lf->refs++;
250         goto out;
251     }
252     if (find_mod_metadata(filename)) {
253         if (linker_kernel_file)
254             ++linker_kernel_file->refs;
255         *result = linker_kernel_file;
256         goto out;
257     }
258
259     koname = kmalloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
260     if (koname == NULL) {
261         error = ENOMEM;
262         goto out;
263     }
264     ksprintf(koname, "%s.ko", filename);
265     lf = NULL;
266     foundfile = 0;
267     for (lc = TAILQ_FIRST(&classes); lc; lc = TAILQ_NEXT(lc, link)) {
268         KLD_DPF(FILE, ("linker_load_file: trying to load %s as %s\n",
269                        filename, lc->desc));
270
271         error = lc->ops->load_file(koname, &lf);        /* First with .ko */
272         if (lf == NULL && error == ENOENT)
273             error = lc->ops->load_file(filename, &lf);  /* Then try without */
274         /*
275          * If we got something other than ENOENT, then it exists but we cannot
276          * load it for some other reason.
277          */
278         if (error != ENOENT)
279             foundfile = 1;
280         if (lf) {
281             linker_file_register_sysctls(lf);
282             error = linker_file_sysinit(lf);
283
284             *result = lf;
285             goto out;
286         }
287     }
288     /*
289      * Less than ideal, but tells the user whether it failed to load or
290      * the module was not found.
291      */
292     if (foundfile) {
293             /*
294              * Format not recognized or otherwise unloadable.
295              * When loading a module that is statically built into
296              * the kernel EEXIST percolates back up as the return
297              * value.  Preserve this so that apps like sysinstall
298              * can recognize this special case and not post bogus
299              * dialog messages.
300              */
301             if (error != EEXIST)
302                     error = ENOEXEC;
303     } else {
304         error = ENOENT;         /* Nothing found */
305     }
306
307 out:
308     if (koname)
309         kfree(koname, M_LINKER);
310     return error;
311 }
312
313 linker_file_t
314 linker_find_file_by_name(const char* filename)
315 {
316     linker_file_t lf = 0;
317     char *koname;
318     int i;
319
320     for (i = strlen(filename); i > 0 && filename[i-1] != '/'; --i)
321         ;
322     filename += i;
323
324     koname = kmalloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
325     if (koname == NULL)
326         goto out;
327     ksprintf(koname, "%s.ko", filename);
328
329     lockmgr(&lock, LK_SHARED);
330     for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link)) {
331         if (!strcmp(lf->filename, koname))
332             break;
333         if (!strcmp(lf->filename, filename))
334             break;
335     }
336     lockmgr(&lock, LK_RELEASE);
337
338 out:
339     if (koname)
340         kfree(koname, M_LINKER);
341     return lf;
342 }
343
344 linker_file_t
345 linker_find_file_by_id(int fileid)
346 {
347     linker_file_t lf = 0;
348
349     lockmgr(&lock, LK_SHARED);
350     for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link))
351         if (lf->id == fileid)
352             break;
353     lockmgr(&lock, LK_RELEASE);
354
355     return lf;
356 }
357
358 linker_file_t
359 linker_make_file(const char* pathname, void* priv, struct linker_file_ops* ops)
360 {
361     linker_file_t lf = 0;
362     int namelen;
363     const char *filename;
364
365     filename = rindex(pathname, '/');
366     if (filename && filename[1])
367         filename++;
368     else
369         filename = pathname;
370
371     KLD_DPF(FILE, ("linker_make_file: new file, filename=%s\n", filename));
372     lockmgr(&lock, LK_EXCLUSIVE);
373     namelen = strlen(filename) + 1;
374     lf = kmalloc(sizeof(struct linker_file) + namelen, M_LINKER, M_WAITOK);
375     if (!lf)
376         goto out;
377     bzero(lf, sizeof(*lf));
378
379     lf->refs = 1;
380     lf->userrefs = 0;
381     lf->flags = 0;
382     lf->filename = (char*) (lf + 1);
383     strcpy(lf->filename, filename);
384     lf->id = next_file_id++;
385     lf->ndeps = 0;
386     lf->deps = NULL;
387     STAILQ_INIT(&lf->common);
388     TAILQ_INIT(&lf->modules);
389
390     lf->priv = priv;
391     lf->ops = ops;
392     TAILQ_INSERT_TAIL(&linker_files, lf, link);
393
394 out:
395     lockmgr(&lock, LK_RELEASE);
396     return lf;
397 }
398
399 int
400 linker_file_unload(linker_file_t file)
401 {
402     module_t mod, next;
403     struct common_symbol* cp;
404     int error = 0;
405     int i;
406
407     /* Refuse to unload modules if securelevel raised */
408     if (securelevel > 0 || kernel_mem_readonly)
409         return EPERM; 
410
411     KLD_DPF(FILE, ("linker_file_unload: lf->refs=%d\n", file->refs));
412     lockmgr(&lock, LK_EXCLUSIVE);
413     if (file->refs == 1) {
414         KLD_DPF(FILE, ("linker_file_unload: file is unloading, informing modules\n"));
415         /*
416          * Temporarily bump file->refs to prevent recursive unloading
417          */
418         ++file->refs;
419
420         /*
421          * Inform any modules associated with this file.
422          */
423         mod = TAILQ_FIRST(&file->modules);
424         while (mod) {
425             /*
426              * Give the module a chance to veto the unload.  Note that the
427              * act of unloading the module may cause other modules in the
428              * same file list to be unloaded recursively.
429              */
430             if ((error = module_unload(mod)) != 0) {
431                 KLD_DPF(FILE, ("linker_file_unload: module %x vetoes unload\n",
432                                mod));
433                 lockmgr(&lock, LK_RELEASE);
434                 file->refs--;
435                 goto out;
436             }
437
438             /*
439              * Recursive relationships may prevent the release from
440              * immediately removing the module, or may remove other
441              * modules in the list.
442              */
443             next = module_getfnext(mod);
444             module_release(mod);
445             mod = next;
446         }
447
448         /*
449          * Since we intend to destroy the file structure, we expect all
450          * modules to have been removed by now.
451          */
452         for (mod = TAILQ_FIRST(&file->modules); 
453              mod; 
454              mod = module_getfnext(mod)
455         ) {
456             kprintf("linker_file_unload: module %p still has refs!\n", mod);
457         }
458         --file->refs;
459     }
460
461     file->refs--;
462     if (file->refs > 0) {
463         lockmgr(&lock, LK_RELEASE);
464         goto out;
465     }
466
467     /* Don't try to run SYSUNINITs if we are unloaded due to a link error */
468     if (file->flags & LINKER_FILE_LINKED) {
469         linker_file_sysuninit(file);
470         linker_file_unregister_sysctls(file);
471     }
472
473     TAILQ_REMOVE(&linker_files, file, link);
474     lockmgr(&lock, LK_RELEASE);
475
476     for (i = 0; i < file->ndeps; i++)
477         linker_file_unload(file->deps[i]);
478     kfree(file->deps, M_LINKER);
479
480     for (cp = STAILQ_FIRST(&file->common); cp;
481          cp = STAILQ_FIRST(&file->common)) {
482         STAILQ_REMOVE(&file->common, cp, common_symbol, link);
483         kfree(cp, M_LINKER);
484     }
485
486     file->ops->unload(file);
487     kfree(file, M_LINKER);
488
489 out:
490     return error;
491 }
492
493 int
494 linker_file_add_dependancy(linker_file_t file, linker_file_t dep)
495 {
496     linker_file_t* newdeps;
497
498     newdeps = kmalloc((file->ndeps + 1) * sizeof(linker_file_t*),
499                      M_LINKER, M_WAITOK);
500     if (newdeps == NULL)
501         return ENOMEM;
502     bzero(newdeps, (file->ndeps + 1) * sizeof(linker_file_t*));
503
504     if (file->deps) {
505         bcopy(file->deps, newdeps, file->ndeps * sizeof(linker_file_t*));
506         kfree(file->deps, M_LINKER);
507     }
508     file->deps = newdeps;
509     file->deps[file->ndeps] = dep;
510     file->ndeps++;
511
512     return 0;
513 }
514
515 /*
516  * Locate a linker set and its contents.
517  * This is a helper function to avoid linker_if.h exposure elsewhere.
518  * Note: firstp and lastp are really void ***
519  */
520 int
521 linker_file_lookup_set(linker_file_t file, const char *name,
522                       void *firstp, void *lastp, int *countp)
523 {
524     return file->ops->lookup_set(file, name, firstp, lastp, countp);
525 }
526
527 int
528 linker_file_lookup_symbol(linker_file_t file, const char* name, int deps, caddr_t *raddr)
529 {
530     c_linker_sym_t sym;
531     linker_symval_t symval;
532     linker_file_t lf;
533     size_t common_size = 0;
534     int i;
535
536     KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%x, name=%s, deps=%d\n",
537                   file, name, deps));
538
539     if (file->ops->lookup_symbol(file, name, &sym) == 0) {
540         file->ops->symbol_values(file, sym, &symval);
541
542         /*
543          * XXX Assume a common symbol if its value is 0 and it has a non-zero
544          * size, otherwise it could be an absolute symbol with a value of 0.
545          */
546         if (symval.value == 0 && symval.size != 0) {
547             /*
548              * For commons, first look them up in the dependancies and
549              * only allocate space if not found there.
550              */
551             common_size = symval.size;
552         } else {
553             KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol.value=%x\n", symval.value));
554             *raddr = symval.value;
555             return 0;
556         }
557     }
558     if (deps) {
559         for (i = 0; i < file->ndeps; i++) {
560             if (linker_file_lookup_symbol(file->deps[i], name, 0, raddr) == 0) {
561                 KLD_DPF(SYM, ("linker_file_lookup_symbol: deps value=%x\n", *raddr));
562                 return 0;
563             }
564         }
565
566         /* If we have not found it in the dependencies, search globally */
567         for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link)) {
568             /* But skip the current file if it's on the list */
569             if (lf == file)
570                 continue;
571             /* And skip the files we searched above */
572             for (i = 0; i < file->ndeps; i++)
573                 if (lf == file->deps[i])
574                     break;
575             if (i < file->ndeps)
576                 continue;
577             if (linker_file_lookup_symbol(lf, name, 0, raddr) == 0) {
578                 KLD_DPF(SYM, ("linker_file_lookup_symbol: global value=%x\n", *raddr));
579                 return 0;
580             }
581         }
582     }
583
584     if (common_size > 0) {
585         /*
586          * This is a common symbol which was not found in the
587          * dependancies.  We maintain a simple common symbol table in
588          * the file object.
589          */
590         struct common_symbol* cp;
591
592         for (cp = STAILQ_FIRST(&file->common); cp;
593              cp = STAILQ_NEXT(cp, link))
594             if (!strcmp(cp->name, name)) {
595                 KLD_DPF(SYM, ("linker_file_lookup_symbol: old common value=%x\n", cp->address));
596                 *raddr = cp->address;
597                 return 0;
598             }
599
600         /*
601          * Round the symbol size up to align.
602          */
603         common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
604         cp = kmalloc(sizeof(struct common_symbol)
605                     + common_size
606                     + strlen(name) + 1,
607                     M_LINKER, M_WAITOK);
608         if (!cp) {
609             KLD_DPF(SYM, ("linker_file_lookup_symbol: nomem\n"));
610             return ENOMEM;
611         }
612         bzero(cp, sizeof(struct common_symbol) + common_size + strlen(name)+ 1);
613
614         cp->address = (caddr_t) (cp + 1);
615         cp->name = cp->address + common_size;
616         strcpy(cp->name, name);
617         bzero(cp->address, common_size);
618         STAILQ_INSERT_TAIL(&file->common, cp, link);
619
620         KLD_DPF(SYM, ("linker_file_lookup_symbol: new common value=%x\n", cp->address));
621         *raddr = cp->address;
622         return 0;
623     }
624
625     KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
626     return ENOENT;
627 }
628
629 #ifdef DDB
630 /*
631  * DDB Helpers.  DDB has to look across multiple files with their own
632  * symbol tables and string tables.
633  *
634  * Note that we do not obey list locking protocols here.  We really don't
635  * need DDB to hang because somebody's got the lock held.  We'll take the
636  * chance that the files list is inconsistant instead.
637  */
638
639 int
640 linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
641 {
642     linker_file_t lf;
643
644     for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link)) {
645         if (lf->ops->lookup_symbol(lf, symstr, sym) == 0)
646             return 0;
647     }
648     return ENOENT;
649 }
650
651 int
652 linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
653 {
654     linker_file_t lf;
655     u_long off = (uintptr_t)value;
656     u_long diff, bestdiff;
657     c_linker_sym_t best;
658     c_linker_sym_t es;
659
660     best = 0;
661     bestdiff = off;
662     for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link)) {
663         if (lf->ops->search_symbol(lf, value, &es, &diff) != 0)
664             continue;
665         if (es != 0 && diff < bestdiff) {
666             best = es;
667             bestdiff = diff;
668         }
669         if (bestdiff == 0)
670             break;
671     }
672     if (best) {
673         *sym = best;
674         *diffp = bestdiff;
675         return 0;
676     } else {
677         *sym = 0;
678         *diffp = off;
679         return ENOENT;
680     }
681 }
682
683 int
684 linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
685 {
686     linker_file_t lf;
687
688     for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link)) {
689         if (lf->ops->symbol_values(lf, sym, symval) == 0)
690             return 0;
691     }
692     return ENOENT;
693 }
694
695 #endif
696
697 /*
698  * Syscalls.
699  */
700
701 int
702 sys_kldload(struct kldload_args *uap)
703 {
704     struct thread *td = curthread;
705     char* filename = NULL, *modulename;
706     linker_file_t lf;
707     int error = 0;
708
709     uap->sysmsg_result = -1;
710
711     if (securelevel > 0 || kernel_mem_readonly) /* redundant, but that's OK */
712         return EPERM;
713
714     if ((error = suser(td)) != 0)
715         return error;
716
717     filename = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
718     if ((error = copyinstr(uap->file, filename, MAXPATHLEN, NULL)) != 0)
719         goto out;
720
721     /* Can't load more than one module with the same name */
722     modulename = rindex(filename, '/');
723     if (modulename == NULL)
724         modulename = filename;
725     else
726         modulename++;
727     if (linker_find_file_by_name(modulename)) {
728         error = EEXIST;
729         goto out;
730     }
731
732     if ((error = linker_load_file(filename, &lf)) != 0)
733         goto out;
734
735     lf->userrefs++;
736     uap->sysmsg_result = lf->id;
737
738 out:
739     if (filename)
740         kfree(filename, M_TEMP);
741     return error;
742 }
743
744 int
745 sys_kldunload(struct kldunload_args *uap)
746 {
747     struct thread *td = curthread;
748     linker_file_t lf;
749     int error = 0;
750
751     if (securelevel > 0 || kernel_mem_readonly) /* redundant, but that's OK */
752         return EPERM;
753
754     if ((error = suser(td)) != 0)
755         return error;
756
757     lf = linker_find_file_by_id(uap->fileid);
758     if (lf) {
759         KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
760         if (lf->userrefs == 0) {
761             kprintf("linkerunload: attempt to unload file that was loaded by the kernel\n");
762             error = EBUSY;
763             goto out;
764         }
765         lf->userrefs--;
766         error = linker_file_unload(lf);
767         if (error)
768             lf->userrefs++;
769     } else
770         error = ENOENT;
771
772 out:
773     return error;
774 }
775
776 int
777 sys_kldfind(struct kldfind_args *uap)
778 {
779     char *filename = NULL, *modulename;
780     linker_file_t lf;
781     int error = 0;
782
783     uap->sysmsg_result = -1;
784
785     filename = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
786     if ((error = copyinstr(uap->file, filename, MAXPATHLEN, NULL)) != 0)
787         goto out;
788
789     modulename = rindex(filename, '/');
790     if (modulename == NULL)
791         modulename = filename;
792
793     lf = linker_find_file_by_name(modulename);
794     if (lf)
795         uap->sysmsg_result = lf->id;
796     else
797         error = ENOENT;
798
799 out:
800     if (filename)
801         kfree(filename, M_TEMP);
802     return error;
803 }
804
805 int
806 sys_kldnext(struct kldnext_args *uap)
807 {
808     linker_file_t lf;
809     int error = 0;
810
811     if (uap->fileid == 0) {
812         if (TAILQ_FIRST(&linker_files))
813             uap->sysmsg_result = TAILQ_FIRST(&linker_files)->id;
814         else
815             uap->sysmsg_result = 0;
816         return 0;
817     }
818
819     lf = linker_find_file_by_id(uap->fileid);
820     if (lf) {
821         if (TAILQ_NEXT(lf, link))
822             uap->sysmsg_result = TAILQ_NEXT(lf, link)->id;
823         else
824             uap->sysmsg_result = 0;
825     } else
826         error = ENOENT;
827
828     return error;
829 }
830
831 int
832 sys_kldstat(struct kldstat_args *uap)
833 {
834     linker_file_t lf;
835     int error = 0;
836     int version;
837     struct kld_file_stat* stat;
838     int namelen;
839
840     lf = linker_find_file_by_id(uap->fileid);
841     if (!lf) {
842         error = ENOENT;
843         goto out;
844     }
845
846     stat = uap->stat;
847
848     /*
849      * Check the version of the user's structure.
850      */
851     if ((error = copyin(&stat->version, &version, sizeof(version))) != 0)
852         goto out;
853     if (version != sizeof(struct kld_file_stat)) {
854         error = EINVAL;
855         goto out;
856     }
857
858     namelen = strlen(lf->filename) + 1;
859     if (namelen > MAXPATHLEN)
860         namelen = MAXPATHLEN;
861     if ((error = copyout(lf->filename, &stat->name[0], namelen)) != 0)
862         goto out;
863     if ((error = copyout(&lf->refs, &stat->refs, sizeof(int))) != 0)
864         goto out;
865     if ((error = copyout(&lf->id, &stat->id, sizeof(int))) != 0)
866         goto out;
867     if ((error = copyout(&lf->address, &stat->address, sizeof(caddr_t))) != 0)
868         goto out;
869     if ((error = copyout(&lf->size, &stat->size, sizeof(size_t))) != 0)
870         goto out;
871
872     uap->sysmsg_result = 0;
873
874 out:
875     return error;
876 }
877
878 int
879 sys_kldfirstmod(struct kldfirstmod_args *uap)
880 {
881     linker_file_t lf;
882     int error = 0;
883
884     lf = linker_find_file_by_id(uap->fileid);
885     if (lf) {
886         if (TAILQ_FIRST(&lf->modules))
887             uap->sysmsg_result = module_getid(TAILQ_FIRST(&lf->modules));
888         else
889             uap->sysmsg_result = 0;
890     } else
891         error = ENOENT;
892
893     return error;
894 }
895
896 int
897 sys_kldsym(struct kldsym_args *uap)
898 {
899     char *symstr = NULL;
900     c_linker_sym_t sym;
901     linker_symval_t symval;
902     linker_file_t lf;
903     struct kld_sym_lookup lookup;
904     int error = 0;
905
906     if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
907         goto out;
908     if (lookup.version != sizeof(lookup) || uap->cmd != KLDSYM_LOOKUP) {
909         error = EINVAL;
910         goto out;
911     }
912
913     symstr = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
914     if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
915         goto out;
916
917     if (uap->fileid != 0) {
918         lf = linker_find_file_by_id(uap->fileid);
919         if (lf == NULL) {
920             error = ENOENT;
921             goto out;
922         }
923         if (lf->ops->lookup_symbol(lf, symstr, &sym) == 0 &&
924             lf->ops->symbol_values(lf, sym, &symval) == 0) {
925             lookup.symvalue = (uintptr_t)symval.value;
926             lookup.symsize = symval.size;
927             error = copyout(&lookup, uap->data, sizeof(lookup));
928         } else
929             error = ENOENT;
930     } else {
931         for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link)) {
932             if (lf->ops->lookup_symbol(lf, symstr, &sym) == 0 &&
933                 lf->ops->symbol_values(lf, sym, &symval) == 0) {
934                 lookup.symvalue = (uintptr_t)symval.value;
935                 lookup.symsize = symval.size;
936                 error = copyout(&lookup, uap->data, sizeof(lookup));
937                 break;
938             }
939         }
940         if (!lf)
941             error = ENOENT;
942     }
943 out:
944     if (symstr)
945         kfree(symstr, M_TEMP);
946     return error;
947 }
948
949 /*
950  * Look for module metadata in the static kernel
951  */
952 struct mod_metadata *
953 find_mod_metadata(const char *modname)
954 {
955     int len;
956     struct mod_metadata **mdp;
957     struct mod_metadata *mdt;
958
959     /*
960      * Strip path prefixes and any dot extension.  MDT_MODULE names
961      * are just the module name without a path or ".ko".
962      */
963     for (len = strlen(modname) - 1; len >= 0; --len) {
964         if (modname[len] == '/')
965             break;
966     }
967     modname += len + 1;
968     for (len = 0; modname[len] && modname[len] != '.'; ++len)
969         ;
970
971     /*
972      * Look for the module declaration
973      */
974     SET_FOREACH(mdp, modmetadata_set) {
975         mdt = *mdp;
976         if (mdt->md_type != MDT_MODULE)
977             continue;
978         if (strlen(mdt->md_cval) == len &&
979             strncmp(mdt->md_cval, modname, len) == 0) {
980             return(mdt);
981         }
982     }
983     return(NULL);
984 }
985
986 /*
987  * Preloaded module support
988  */
989 static void
990 linker_preload(void* arg)
991 {
992     caddr_t             modptr;
993     char                *modname;
994     char                *modtype;
995     linker_file_t       lf;
996     linker_class_t      lc;
997     int                 error;
998     struct sysinit      **sipp;
999     const moduledata_t  *moddata;
1000     struct sysinit      **si_start, **si_stop;
1001
1002     modptr = NULL;
1003     while ((modptr = preload_search_next_name(modptr)) != NULL) {
1004         modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1005         modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1006         if (modname == NULL) {
1007             kprintf("Preloaded module at %p does not have a name!\n", modptr);
1008             continue;
1009         }
1010         if (modtype == NULL) {
1011             kprintf("Preloaded module at %p does not have a type!\n", modptr);
1012             continue;
1013         }
1014
1015         /*
1016          * This is a hack at the moment, but what's in FreeBSD-5 is even 
1017          * worse so I'd rather the hack.
1018          */
1019         kprintf("Preloaded %s \"%s\" at %p", modtype, modname, modptr);
1020         if (find_mod_metadata(modname)) {
1021             kprintf(" (ignored, already in static kernel)\n");
1022             continue;
1023         }
1024         kprintf(".\n");
1025
1026         lf = linker_find_file_by_name(modname);
1027         if (lf) {
1028             lf->refs++;
1029             lf->userrefs++;
1030             continue;
1031         }
1032         lf = NULL;
1033         for (lc = TAILQ_FIRST(&classes); lc; lc = TAILQ_NEXT(lc, link)) {
1034             error = lc->ops->load_file(modname, &lf);
1035             if (error) {
1036                 lf = NULL;
1037                 break;
1038             }
1039         }
1040         if (lf) {
1041             lf->userrefs++;
1042
1043             if (linker_file_lookup_set(lf, "sysinit_set", &si_start, &si_stop, NULL) == 0) {
1044                 /* HACK ALERT!
1045                  * This is to set the sysinit moduledata so that the module
1046                  * can attach itself to the correct containing file.
1047                  * The sysinit could be run at *any* time.
1048                  */
1049                 for (sipp = si_start; sipp < si_stop; sipp++) {
1050                     if ((*sipp)->func == module_register_init) {
1051                         moddata = (*sipp)->udata;
1052                         error = module_register(moddata, lf);
1053                         if (error)
1054                             kprintf("Preloaded %s \"%s\" failed to register: %d\n",
1055                                 modtype, modname, error);
1056                     }
1057                 }
1058                 sysinit_add(si_start, si_stop);
1059             }
1060             linker_file_register_sysctls(lf);
1061         }
1062     }
1063 }
1064
1065 SYSINIT(preload, SI_BOOT2_KLD, SI_ORDER_MIDDLE, linker_preload, 0);
1066
1067 /*
1068  * Search for a not-loaded module by name.
1069  *
1070  * Modules may be found in the following locations:
1071  *
1072  * - preloaded (result is just the module name)
1073  * - on disk (result is full path to module)
1074  *
1075  * If the module name is qualified in any way (contains path, etc.)
1076  * the we simply return a copy of it.
1077  *
1078  * The search path can be manipulated via sysctl.  Note that we use the ';'
1079  * character as a separator to be consistent with the bootloader.
1080  */
1081
1082 static char linker_path[MAXPATHLEN] = "/;/boot;/modules";
1083
1084 SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RW, linker_path,
1085               sizeof(linker_path), "module load search path");
1086 TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1087
1088 static char *
1089 linker_strdup(const char *str)
1090 {
1091     char        *result;
1092
1093     if ((result = kmalloc((strlen(str) + 1), M_LINKER, M_WAITOK)) != NULL)
1094         strcpy(result, str);
1095     return(result);
1096 }
1097
1098 char *
1099 linker_search_path(const char *name)
1100 {
1101     struct nlookupdata  nd;
1102     char                *cp, *ep, *result;
1103     size_t              name_len, prefix_len;
1104     int                 sep;
1105     int                 error;
1106     enum vtype          type;
1107
1108     /* qualified at all? */
1109     if (index(name, '/'))
1110         return(linker_strdup(name));
1111
1112     /* traverse the linker path */
1113     cp = linker_path;
1114     name_len = strlen(name);
1115     for (;;) {
1116
1117         /* find the end of this component */
1118         for (ep = cp; (*ep != 0) && (*ep != ';'); ep++)
1119             ;
1120         prefix_len = ep - cp;
1121         /* if this component doesn't end with a slash, add one */
1122         if (ep == cp || *(ep - 1) != '/')
1123             sep = 1;
1124         else
1125             sep = 0;
1126
1127         /*
1128          * +2 : possible separator, plus terminator.
1129          */
1130         result = kmalloc(prefix_len + name_len + 2, M_LINKER, M_WAITOK);
1131
1132         strncpy(result, cp, prefix_len);
1133         if (sep)
1134             result[prefix_len++] = '/';
1135         strcpy(result + prefix_len, name);
1136
1137         /*
1138          * Attempt to open the file, and return the path if we succeed and it's
1139          * a regular file.
1140          */
1141         error = nlookup_init(&nd, result, UIO_SYSSPACE, NLC_FOLLOW|NLC_LOCKVP);
1142         if (error == 0)
1143             error = vn_open(&nd, NULL, FREAD, 0);
1144         if (error == 0) {
1145             type = nd.nl_open_vp->v_type;
1146             if (type == VREG) {
1147                 nlookup_done(&nd);
1148                 return (result);
1149             }
1150         }
1151         nlookup_done(&nd);
1152         kfree(result, M_LINKER);
1153
1154         if (*ep == 0)
1155             break;
1156         cp = ep + 1;
1157     }
1158     return(NULL);
1159 }