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