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