Merge branch 'vendor/OPENSSL'
[dragonfly.git] / sys / boot / common / module.c
1 /*-
2  * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
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/boot/common/module.c,v 1.25 2003/08/25 23:30:41 obrien Exp $
27  * $DragonFly: src/sys/boot/common/module.c,v 1.6 2008/09/02 17:21:12 dillon Exp $
28  */
29
30 /*
31  * file/module function dispatcher, support, etc.
32  */
33
34 #include <stand.h>
35 #include <string.h>
36 #include <sys/param.h>
37 #include <sys/linker.h>
38 #include <sys/module.h>
39 #include <sys/queue.h>
40
41 #include "bootstrap.h"
42
43 #define MDIR_REMOVED    0x0001
44 #define MDIR_NOHINTS    0x0002
45
46 struct moduledir {
47         char    *d_path;        /* path of modules directory */
48         u_char  *d_hints;       /* content of linker.hints file */
49         int     d_hintsz;       /* size of hints data */
50         int     d_flags;
51         STAILQ_ENTRY(moduledir) d_link;
52 };
53
54 static int                      file_load(char *filename, vm_offset_t dest, struct preloaded_file **result);
55 static int                      file_loadraw(char *type, char *name);
56 static int                      file_load_dependencies(struct preloaded_file *base_mod);
57 static char *                   file_search(const char *name, char **extlist);
58 static struct kernel_module *   file_findmodule(struct preloaded_file *fp, char *modname, struct mod_depend *verinfo);
59 static int                      file_havepath(const char *name);
60 static char                     *mod_searchmodule(char *name, struct mod_depend *verinfo);
61 static void                     file_insert_tail(struct preloaded_file *mp);
62 struct file_metadata*           metadata_next(struct file_metadata *base_mp, int type);
63 static void                     moduledir_readhints(struct moduledir *mdp);
64 static void                     moduledir_rebuild(void);
65
66 /* load address should be tweaked by first module loaded (kernel) */
67 static vm_offset_t      loadaddr = 0;
68
69 static const char       *default_searchpath ="modules;KERNEL";
70
71 static STAILQ_HEAD(, moduledir) moduledir_list = STAILQ_HEAD_INITIALIZER(moduledir_list);
72
73 struct preloaded_file *preloaded_files = NULL;
74
75 static char *kld_ext_list[] = {
76     ".ko",
77     "",
78     NULL
79 };
80
81 COMMAND_SET(slow, "slow", "slow print", command_slow);
82
83 static int slomode;
84
85 static int
86 command_slow(int argc, char *argv[])
87 {
88         slomode = 1;
89         return CMD_OK;
90 }
91
92 void
93 slowprint(char c)
94 {
95     int i;
96
97     if (slomode) {
98         printf("SP-%c\n", c);
99         for (i = 0; i < 10; ++i)
100             delay(100000);
101     }
102 }
103
104 /*
105  * load an object, either a disk file or code module.
106  *
107  * To load a file, the syntax is:
108  *
109  * load -t <type> <path>
110  *
111  * code modules are loaded as:
112  *
113  * load <path> <options>
114  */
115 COMMAND_SET(load, "load", "load a kernel or module", command_load);
116
117 static int
118 command_load(int argc, char *argv[])
119 {
120     char        *typestr;
121     int         dofile, dokld, ch, error;
122     
123     dokld = dofile = 0;
124     optind = 1;
125     optreset = 1;
126     typestr = NULL;
127     if (argc == 1) {
128         command_errmsg = "no filename specified";
129         return(CMD_ERROR);
130     }
131     while ((ch = getopt(argc, argv, "kt:")) != -1) {
132         switch(ch) {
133         case 'k':
134             dokld = 1;
135             break;
136         case 't':
137             typestr = optarg;
138             dofile = 1;
139             break;
140         case '?':
141         default:
142             /* getopt has already reported an error */
143             return(CMD_OK);
144         }
145     }
146     argv += (optind - 1);
147     argc -= (optind - 1);
148
149     /*
150      * Request to load a raw file?
151      */
152     if (dofile) {
153         if ((argc != 2) || (typestr == NULL) || (*typestr == 0)) {
154             command_errmsg = "invalid load type";
155             return(CMD_ERROR);
156         }
157         return(file_loadraw(typestr, argv[1]));
158     }
159     /*
160      * Do we have explicit KLD load ?
161      */
162     if (dokld || file_havepath(argv[1])) {
163         error = mod_loadkld(argv[1], argc - 2, argv + 2);
164         if (error == EEXIST)
165             sprintf(command_errbuf, "warning: KLD '%s' already loaded", argv[1]);
166         return (error == 0 ? CMD_OK : CMD_ERROR);
167     }
168     /*
169      * Looks like a request for a module.
170      */
171     error = mod_load(argv[1], NULL, argc - 2, argv + 2);
172     if (error == EEXIST)
173         sprintf(command_errbuf, "warning: module '%s' already loaded", argv[1]);
174     return (error == 0 ? CMD_OK : CMD_ERROR);
175 }
176
177 COMMAND_SET(unload, "unload", "unload all modules", command_unload);
178
179 static int
180 command_unload(int argc, char *argv[])
181 {
182     struct preloaded_file       *fp;
183     
184     while (preloaded_files != NULL) {
185         fp = preloaded_files;
186         preloaded_files = preloaded_files->f_next;
187         file_discard(fp);
188     }
189     loadaddr = 0;
190     unsetenv("kernelname");
191     return(CMD_OK);
192 }
193
194 COMMAND_SET(lsmod, "lsmod", "list loaded modules", command_lsmod);
195
196 static int
197 command_lsmod(int argc, char *argv[])
198 {
199     struct preloaded_file       *fp;
200     struct kernel_module        *mp;
201     struct file_metadata        *md;
202     char                        lbuf[80];
203     int                         ch, verbose;
204
205     verbose = 0;
206     optind = 1;
207     optreset = 1;
208     while ((ch = getopt(argc, argv, "v")) != -1) {
209         switch(ch) {
210         case 'v':
211             verbose = 1;
212             break;
213         case '?':
214         default:
215             /* getopt has already reported an error */
216             return(CMD_OK);
217         }
218     }
219
220     pager_open();
221     for (fp = preloaded_files; fp; fp = fp->f_next) {
222         sprintf(lbuf, " %p: %s (%s, 0x%lx)\n", 
223                 (void *) fp->f_addr, fp->f_name, fp->f_type, (long) fp->f_size);
224         pager_output(lbuf);
225         if (fp->f_args != NULL) {
226             pager_output("    args: ");
227             pager_output(fp->f_args);
228             pager_output("\n");
229         }
230         if (fp->f_modules) {
231             pager_output("  modules: ");
232             for (mp = fp->f_modules; mp; mp = mp->m_next) {
233                 sprintf(lbuf, "%s.%d ", mp->m_name, mp->m_version);
234                 pager_output(lbuf);
235             }
236             pager_output("\n");
237         }
238         if (verbose) {
239             /* XXX could add some formatting smarts here to display some better */
240             for (md = fp->f_metadata; md != NULL; md = md->md_next) {
241                 sprintf(lbuf, "      0x%04x, 0x%lx\n", md->md_type, (long) md->md_size);
242                 pager_output(lbuf);
243             }
244         }
245     }
246     pager_close();
247     return(CMD_OK);
248 }
249
250 /*
251  * File level interface, functions file_*
252  */
253 int
254 file_load(char *filename, vm_offset_t dest, struct preloaded_file **result)
255 {
256     struct preloaded_file *fp;
257     int error;
258     int i;
259
260     error = EFTYPE;
261     for (i = 0, fp = NULL; file_formats[i] && fp == NULL; i++) {
262         error = (file_formats[i]->l_load)(filename, loadaddr, &fp);
263         if (error == 0) {
264             fp->f_loader = i;           /* remember the loader */
265             *result = fp;
266             break;
267         }
268         if (error == EFTYPE)
269             continue;           /* Unknown to this handler? */
270         if (error) {
271             sprintf(command_errbuf, "can't load file '%s': %s",
272                 filename, strerror(error));
273             break;
274         }
275     }
276     return (error);
277 }
278
279 static int
280 file_load_dependencies(struct preloaded_file *base_file) {
281     struct file_metadata *md;
282     struct preloaded_file *fp;
283     struct mod_depend *verinfo;
284     struct kernel_module *mp;
285     char *dmodname;
286     int error;
287
288     md = file_findmetadata(base_file, MODINFOMD_DEPLIST);
289     if (md == NULL)
290         return (0);
291     error = 0;
292     do {
293         verinfo = (struct mod_depend*)md->md_data;
294         dmodname = (char *)(verinfo + 1);
295         if (file_findmodule(NULL, dmodname, verinfo) == NULL) {
296             printf("loading required module '%s'\n", dmodname);
297             error = mod_load(dmodname, verinfo, 0, NULL);
298             if (error)
299                 break;
300             /*
301              * If module loaded via kld name which isn't listed
302              * in the linker.hints file, we should check if it have
303              * required version.
304              */
305             mp = file_findmodule(NULL, dmodname, verinfo);
306             if (mp == NULL) {
307                 sprintf(command_errbuf, "module '%s' exists but with wrong version",
308                     dmodname);
309                 error = ENOENT;
310                 break;
311             }
312         }
313         md = metadata_next(md, MODINFOMD_DEPLIST);
314     } while (md);
315     if (!error)
316         return (0);
317     /* Load failed; discard everything */
318     while (base_file != NULL) {
319         fp = base_file;
320         base_file = base_file->f_next;
321         file_discard(fp);
322     }
323     return (error);
324 }
325 /*
326  * We've been asked to load (name) as (type), so just suck it in,
327  * no arguments or anything.
328  */
329 int
330 file_loadraw(char *type, char *name)
331 {
332     struct preloaded_file       *fp;
333     char                        *cp;
334     int                         fd, got;
335     vm_offset_t                 laddr;
336
337     /* We can't load first */
338     if ((file_findfile(NULL, NULL)) == NULL) {
339         command_errmsg = "can't load file before kernel";
340         return(CMD_ERROR);
341     }
342
343     /* locate the file on the load path */
344     cp = file_search(name, NULL);
345     if (cp == NULL) {
346         sprintf(command_errbuf, "can't find '%s'", name);
347         return(CMD_ERROR);
348     }
349     name = cp;
350     
351     if ((fd = rel_open(name, NULL, O_RDONLY)) < 0) {
352         sprintf(command_errbuf, "can't open '%s': %s", name, strerror(errno));
353         free(name);
354         return(CMD_ERROR);
355     }
356
357     laddr = loadaddr;
358     for (;;) {
359         /* read in 4k chunks; size is not really important */
360         got = archsw.arch_readin(fd, laddr, 4096);
361         if (got == 0)                           /* end of file */
362             break;
363         if (got < 0) {                          /* error */
364             sprintf(command_errbuf, "error reading '%s': %s", name, strerror(errno));
365             free(name);
366             close(fd);
367             return(CMD_ERROR);
368         }
369         laddr += got;
370     }
371     
372     /* Looks OK so far; create & populate control structure */
373     fp = file_alloc();
374     fp->f_name = name;
375     fp->f_type = strdup(type);
376     fp->f_args = NULL;
377     fp->f_metadata = NULL;
378     fp->f_loader = -1;
379     fp->f_addr = loadaddr;
380     fp->f_size = laddr - loadaddr;
381
382     /* recognise space consumption */
383     loadaddr = laddr;
384
385     /* Add to the list of loaded files */
386     file_insert_tail(fp);
387     close(fd);
388     return(CMD_OK);
389 }
390
391 /*
392  * Load the module (name), pass it (argc),(argv), add container file
393  * to the list of loaded files.
394  * If module is already loaded just assign new argc/argv.
395  */
396 int
397 mod_load(char *modname, struct mod_depend *verinfo, int argc, char *argv[])
398 {
399     struct kernel_module        *mp;
400     int                         err;
401     char                        *filename;
402
403     if (file_havepath(modname)) {
404         printf("Warning: mod_load() called instead of mod_loadkld() for module '%s'\n", modname);
405         return (mod_loadkld(modname, argc, argv));
406     }
407     /* see if module is already loaded */
408     mp = file_findmodule(NULL, modname, verinfo);
409     if (mp) {
410 #ifdef moduleargs
411         if (mp->m_args)
412             free(mp->m_args);
413         mp->m_args = unargv(argc, argv);
414 #endif
415         sprintf(command_errbuf, "warning: module '%s' already loaded", mp->m_name);
416         return (0);
417     }
418     /* locate file with the module on the search path */
419     filename = mod_searchmodule(modname, verinfo);
420     if (filename == NULL) {
421         sprintf(command_errbuf, "can't find '%s'", modname);
422         return (ENOENT);
423     }
424     err = mod_loadkld(filename, argc, argv);
425     return (err);
426 }
427
428 /*
429  * Load specified KLD. If path is omitted, then try to locate it via
430  * search path.
431  */
432 int
433 mod_loadkld(const char *kldname, int argc, char *argv[])
434 {
435     struct preloaded_file       *fp, *last_file;
436     int                         err;
437     char                        *filename;
438
439     /*
440      * Get fully qualified KLD name
441      */
442     filename = file_search(kldname, kld_ext_list);
443     if (filename == NULL) {
444         sprintf(command_errbuf, "can't find '%s'", kldname);
445         return (ENOENT);
446     }
447     /* 
448      * Check if KLD already loaded
449      */
450     fp = file_findfile(filename, NULL);
451     if (fp) {
452         sprintf(command_errbuf, "warning: KLD '%s' already loaded", filename);
453         free(filename);
454         return (0);
455     }
456     for (last_file = preloaded_files; 
457          last_file != NULL && last_file->f_next != NULL;
458          last_file = last_file->f_next)
459         ;
460
461     do {
462         err = file_load(filename, loadaddr, &fp);
463         if (err)
464             break;
465         fp->f_args = unargv(argc, argv);
466         loadaddr = fp->f_addr + fp->f_size;
467         file_insert_tail(fp);           /* Add to the list of loaded files */
468         if (file_load_dependencies(fp) != 0) {
469             err = ENOENT;
470             last_file->f_next = NULL;
471             loadaddr = last_file->f_addr + last_file->f_size;
472             fp = NULL;
473             break;
474         }
475     } while(0);
476     if (err == EFTYPE)
477         sprintf(command_errbuf, "don't know how to load module '%s'", filename);
478     if (err && fp)
479         file_discard(fp);
480     free(filename);
481     return (err);
482 }
483
484 /*
485  * Find a file matching (name) and (type).
486  * NULL may be passed as a wildcard to either.
487  */
488 struct preloaded_file *
489 file_findfile(char *name, char *type)
490 {
491     struct preloaded_file *fp;
492
493     for (fp = preloaded_files; fp != NULL; fp = fp->f_next) {
494         if (((name == NULL) || !strcmp(name, fp->f_name)) &&
495             ((type == NULL) || !strcmp(type, fp->f_type)))
496             break;
497     }
498     return (fp);
499 }
500
501 /*
502  * Find a module matching (name) inside of given file.
503  * NULL may be passed as a wildcard.
504  */
505 struct kernel_module *
506 file_findmodule(struct preloaded_file *fp, char *modname,
507         struct mod_depend *verinfo)
508 {
509     struct kernel_module *mp, *best;
510     int bestver, mver;
511
512     if (fp == NULL) {
513         for (fp = preloaded_files; fp; fp = fp->f_next) {
514             mp = file_findmodule(fp, modname, verinfo);
515             if (mp)
516                 return (mp);
517         }
518         return (NULL);
519     }
520     best = NULL;
521     bestver = 0;
522     for (mp = fp->f_modules; mp; mp = mp->m_next) {
523         if (strcmp(modname, mp->m_name) == 0) {
524             if (verinfo == NULL)
525                 return (mp);
526             mver = mp->m_version;
527             if (mver == verinfo->md_ver_preferred)
528                 return (mp);
529             if (mver >= verinfo->md_ver_minimum && 
530                 mver <= verinfo->md_ver_maximum &&
531                 mver > bestver) {
532                 best = mp;
533                 bestver = mver;
534             }
535         }
536     }
537     return (best);
538 }
539 /*
540  * Make a copy of (size) bytes of data from (p), and associate them as
541  * metadata of (type) to the module (mp).
542  */
543 void
544 file_addmetadata(struct preloaded_file *fp, int type, size_t size, void *p)
545 {
546     struct file_metadata        *md;
547
548     md = malloc(sizeof(struct file_metadata) - sizeof(md->md_data) + size);
549     md->md_size = size;
550     md->md_type = type;
551     bcopy(p, md->md_data, size);
552     md->md_next = fp->f_metadata;
553     fp->f_metadata = md;
554 }
555
556 /*
557  * Find a metadata object of (type) associated with the file (fp)
558  */
559 struct file_metadata *
560 file_findmetadata(struct preloaded_file *fp, int type)
561 {
562     struct file_metadata *md;
563
564     for (md = fp->f_metadata; md != NULL; md = md->md_next)
565         if (md->md_type == type)
566             break;
567     return(md);
568 }
569
570 struct file_metadata *
571 metadata_next(struct file_metadata *md, int type)
572 {
573     if (md == NULL)
574         return (NULL);
575     while((md = md->md_next) != NULL)
576         if (md->md_type == type)
577             break;
578     return (md);
579 }
580
581 static char *emptyextlist[] = { "", NULL };
582
583 /*
584  * Check if the given file is in place and return full path to it.
585  */
586 static char *
587 file_lookup(const char *path, const char *name, int namelen, char **extlist)
588 {
589     struct stat st;
590     char        *result, *cp, **cpp;
591     int         pathlen, extlen, len;
592
593     pathlen = strlen(path);
594     extlen = 0;
595     if (extlist == NULL)
596         extlist = emptyextlist;
597     for (cpp = extlist; *cpp; cpp++) {
598         len = strlen(*cpp);
599         if (len > extlen)
600             extlen = len;
601     }
602     result = malloc(pathlen + namelen + extlen + 2 + 7 + 1);
603     if (result == NULL)
604         return (NULL);
605     bcopy(path, result, pathlen);
606     if (pathlen > 0 && result[pathlen - 1] != '/')
607         result[pathlen++] = '/';
608     cp = result + pathlen;
609     bcopy(name, cp, namelen);
610     cp += namelen;
611     for (cpp = extlist; *cpp; cpp++) {
612         strcpy(cp, *cpp);
613         if (rel_stat(result, &st) == 0) {
614             if (S_ISREG(st.st_mode)) {
615                 return result;
616             } else if (S_ISDIR(st.st_mode)) {
617                 strcat(result, "/kernel");
618                 if (rel_stat(result, &st) == 0 && S_ISREG(st.st_mode)) {
619                     return result;
620                 }
621             }
622         }
623     }
624     free(result);
625     return NULL;
626 }
627
628 /*
629  * Check if file name have any qualifiers
630  */
631 static int
632 file_havepath(const char *name)
633 {
634     const char          *cp;
635
636     archsw.arch_getdev(NULL, name, &cp);
637     return (cp != name || strchr(name, '/') != NULL);
638 }
639
640 /*
641  * Attempt to find the file (name) on the module searchpath.
642  * If (name) is qualified in any way, we simply check it and
643  * return it or NULL.  If it is not qualified, then we attempt
644  * to construct a path using entries in the environment variable
645  * module_path.
646  *
647  * The path we return a pointer to need never be freed, as we manage
648  * it internally.
649  */
650 static char *
651 file_search(const char *name, char **extlist)
652 {
653     struct moduledir    *mdp;
654     struct stat         sb;
655     char                *result;
656     int                 namelen;
657
658     /* Don't look for nothing */
659     if (name == NULL)
660         return(NULL);
661
662     if (*name == 0)
663         return(strdup(name));
664
665     /*
666      * Qualified name.  If it is a directory tag on
667      * a "/kernel" to it.
668      */
669     if (file_havepath(name)) {
670         /* Qualified, so just see if it exists */
671         if (rel_stat(name, &sb) == 0) {
672             if (S_ISDIR(sb.st_mode)) {
673                 result = malloc(strlen(name) + 7 + 1);
674                 sprintf(result, "%s/kernel", name);
675                 return(result);
676             } else {
677                 return(strdup(name));
678             }
679         }
680         return(NULL);
681     }
682     moduledir_rebuild();
683     result = NULL;
684     namelen = strlen(name);
685     STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
686         result = file_lookup(mdp->d_path, name, namelen, extlist);
687         if (result)
688             break;
689     }
690     return(result);
691 }
692
693 #define INT_ALIGN(base, ptr)    ptr = \
694         (base) + (((ptr) - (base) + sizeof(int) - 1) & ~(sizeof(int) - 1))
695
696 static char *
697 mod_search_hints(struct moduledir *mdp, const char *modname,
698         struct mod_depend *verinfo)
699 {
700     u_char      *cp, *recptr, *bufend, *best;
701     char        *result;
702     int         *intp, bestver, blen, clen, found, ival, modnamelen, reclen;
703
704     moduledir_readhints(mdp);
705     modnamelen = strlen(modname);
706     found = 0;
707     result = NULL;
708     bestver = 0;
709     if (mdp->d_hints == NULL)
710         goto bad;
711     recptr = mdp->d_hints;
712     bufend = recptr + mdp->d_hintsz;
713     clen = blen = 0;
714     best = cp = NULL;
715     while (recptr < bufend && !found) {
716         intp = (int*)recptr;
717         reclen = *intp++;
718         ival = *intp++;
719         cp = (char*)intp;
720         switch (ival) {
721         case MDT_VERSION:
722             clen = *cp++;
723             if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
724                 break;
725             cp += clen;
726             INT_ALIGN(mdp->d_hints, cp);
727             ival = *(int*)cp;
728             cp += sizeof(int);
729             clen = *cp++;
730             if (verinfo == NULL || ival == verinfo->md_ver_preferred) {
731                 found = 1;
732                 break;
733             }
734             if (ival >= verinfo->md_ver_minimum && 
735                 ival <= verinfo->md_ver_maximum &&
736                 ival > bestver) {
737                 bestver = ival;
738                 best = cp;
739                 blen = clen;
740             }
741             break;
742         default:
743             break;
744         }
745         recptr += reclen + sizeof(int);
746     }
747     /*
748      * Finally check if KLD is in the place
749      */
750     if (found)
751         result = file_lookup(mdp->d_path, cp, clen, NULL);
752     else if (best)
753         result = file_lookup(mdp->d_path, best, blen, NULL);
754 bad:
755     /*
756      * If nothing found or hints is absent - fallback to the old way
757      * by using "kldname[.ko]" as module name.
758      */
759     if (!found && !bestver && result == NULL)
760         result = file_lookup(mdp->d_path, modname, modnamelen, kld_ext_list);
761     return result;
762 }
763
764 /*
765  * Attempt to locate the file containing the module (name)
766  */
767 static char *
768 mod_searchmodule(char *name, struct mod_depend *verinfo)
769 {
770     struct      moduledir *mdp;
771     char        *result;
772
773     moduledir_rebuild();
774     /*
775      * Now we ready to lookup module in the given directories
776      */
777     result = NULL;
778     STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
779         result = mod_search_hints(mdp, name, verinfo);
780         if (result)
781             break;
782     }
783
784     return(result);
785 }
786
787 int
788 file_addmodule(struct preloaded_file *fp, char *modname, int version,
789         struct kernel_module **newmp)
790 {
791     struct kernel_module *mp;
792     struct mod_depend mdepend;
793
794     bzero(&mdepend, sizeof(mdepend));
795     mdepend.md_ver_preferred = version;
796     mp = file_findmodule(fp, modname, &mdepend);
797     if (mp)
798         return (EEXIST);
799     mp = malloc(sizeof(struct kernel_module));
800     if (mp == NULL)
801         return (ENOMEM);
802     bzero(mp, sizeof(struct kernel_module));
803     mp->m_name = strdup(modname);
804     mp->m_version = version;
805     mp->m_fp = fp;
806     mp->m_next = fp->f_modules;
807     fp->f_modules = mp;
808     if (newmp)
809         *newmp = mp;
810     return (0);
811 }
812
813 /*
814  * Throw a file away
815  */
816 void
817 file_discard(struct preloaded_file *fp)
818 {
819     struct file_metadata        *md, *md1;
820     struct kernel_module        *mp, *mp1;
821     if (fp == NULL)
822         return;
823     md = fp->f_metadata;
824     while (md) {
825         md1 = md;
826         md = md->md_next;
827         free(md1);
828     }
829     mp = fp->f_modules;
830     while (mp) {
831         if (mp->m_name)
832             free(mp->m_name);
833         mp1 = mp;
834         mp = mp->m_next;
835         free(mp1);
836     }   
837     if (fp->f_name != NULL)
838         free(fp->f_name);
839     if (fp->f_type != NULL)
840         free(fp->f_type);
841     if (fp->f_args != NULL)
842         free(fp->f_args);
843     free(fp);
844 }
845
846 /*
847  * Allocate a new file; must be used instead of malloc()
848  * to ensure safe initialisation.
849  */
850 struct preloaded_file *
851 file_alloc(void)
852 {
853     struct preloaded_file       *fp;
854     
855     if ((fp = malloc(sizeof(struct preloaded_file))) != NULL) {
856         bzero(fp, sizeof(struct preloaded_file));
857     }
858     return (fp);
859 }
860
861 /*
862  * Add a module to the chain
863  */
864 static void
865 file_insert_tail(struct preloaded_file *fp)
866 {
867     struct preloaded_file       *cm;
868     
869     /* Append to list of loaded file */
870     fp->f_next = NULL;
871     if (preloaded_files == NULL) {
872         preloaded_files = fp;
873     } else {
874         for (cm = preloaded_files; cm->f_next != NULL; cm = cm->f_next)
875             ;
876         cm->f_next = fp;
877     }
878 }
879
880 static char *
881 moduledir_fullpath(struct moduledir *mdp, const char *fname)
882 {
883     char *cp;
884
885     cp = malloc(strlen(mdp->d_path) + strlen(fname) + 2);
886     if (cp == NULL)
887         return NULL;
888     strcpy(cp, mdp->d_path);
889     strcat(cp, "/");
890     strcat(cp, fname);
891     return (cp);
892 }
893
894 /*
895  * Read linker.hints file into memory performing some sanity checks.
896  */
897 static void
898 moduledir_readhints(struct moduledir *mdp)
899 {
900     struct stat st;
901     char        *path;
902     int         fd, size, version;
903
904     if (mdp->d_hints != NULL || (mdp->d_flags & MDIR_NOHINTS))
905         return;
906     path = moduledir_fullpath(mdp, "linker.hints");
907     if (rel_stat(path, &st) != 0 || st.st_size < (sizeof(version) + sizeof(int)) ||
908         st.st_size > 100 * 1024 || (fd = rel_open(path, NULL, O_RDONLY)) < 0) {
909         free(path);
910         mdp->d_flags |= MDIR_NOHINTS;
911         return;
912     }
913     free(path);
914     size = read(fd, &version, sizeof(version));
915     if (size != sizeof(version) || version != LINKER_HINTS_VERSION)
916         goto bad;
917     size = st.st_size - size;
918     mdp->d_hints = malloc(size);
919     if (mdp->d_hints == NULL)
920         goto bad;
921     if (read(fd, mdp->d_hints, size) != size)
922         goto bad;
923     mdp->d_hintsz = size;
924     close(fd);
925     return;
926 bad:
927     close(fd);
928     if (mdp->d_hints) {
929         free(mdp->d_hints);
930         mdp->d_hints = NULL;
931     }
932     mdp->d_flags |= MDIR_NOHINTS;
933     return;
934 }
935
936 /*
937  * Extract directories from the ';' separated list, remove duplicates.
938  */
939 static void
940 moduledir_rebuild(void)
941 {
942     struct      moduledir *mdp, *mtmp;
943     const char  *path, *cp, *ep;
944     int         cplen;
945
946     path = getenv("module_path");
947     if (path == NULL)
948         path = default_searchpath;
949     /*
950      * Rebuild list of module directories if it changed
951      */
952     STAILQ_FOREACH(mdp, &moduledir_list, d_link)
953         mdp->d_flags |= MDIR_REMOVED;
954
955     for (ep = path; *ep != 0;  ep++) {
956         cp = ep;
957         for (; *ep != 0 && *ep != ';'; ep++)
958             ;
959         /*
960          * Ignore trailing slashes
961          */
962         for (cplen = ep - cp; cplen > 1 && cp[cplen - 1] == '/'; cplen--)
963             ;
964         STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
965             if (strlen(mdp->d_path) != cplen || bcmp(cp, mdp->d_path, cplen) != 0)
966                 continue;
967             mdp->d_flags &= ~MDIR_REMOVED;
968             break;
969         }
970         if (mdp == NULL) {
971             mdp = malloc(sizeof(*mdp) + cplen + 1);
972             if (mdp == NULL)
973                 return;
974             mdp->d_path = (char*)(mdp + 1);
975             bcopy(cp, mdp->d_path, cplen);
976             mdp->d_path[cplen] = 0;
977             mdp->d_hints = NULL;
978             mdp->d_flags = 0;
979             STAILQ_INSERT_TAIL(&moduledir_list, mdp, d_link);
980         }
981         if (*ep == 0)
982             break;
983     }
984     /*
985      * Delete unused directories if any
986      */
987     mdp = STAILQ_FIRST(&moduledir_list);
988     while (mdp) {
989         if ((mdp->d_flags & MDIR_REMOVED) == 0) {
990             mdp = STAILQ_NEXT(mdp, d_link);
991         } else {
992             if (mdp->d_hints)
993                 free(mdp->d_hints);
994             mtmp = mdp;
995             mdp = STAILQ_NEXT(mdp, d_link);
996             STAILQ_REMOVE(&moduledir_list, mtmp, moduledir, d_link);
997             free(mtmp);
998         }
999     }
1000     return;
1001 }