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