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