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