xref: /dragonfly/sys/kern/kern_linker.c (revision 7bc7e232)
1 /*-
2  * Copyright (c) 1997 Doug Rabson
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/kern/kern_linker.c,v 1.41.2.3 2001/11/21 17:50:35 luigi Exp $
27  * $DragonFly: src/sys/kern/kern_linker.c,v 1.39 2007/11/19 18:49:06 swildner Exp $
28  */
29 
30 #include "opt_ddb.h"
31 
32 #include <sys/param.h>
33 #include <sys/kernel.h>
34 #include <sys/systm.h>
35 #include <sys/malloc.h>
36 #include <sys/sysproto.h>
37 #include <sys/sysent.h>
38 #include <sys/proc.h>
39 #include <sys/lock.h>
40 #include <sys/module.h>
41 #include <sys/linker.h>
42 #include <sys/fcntl.h>
43 #include <sys/libkern.h>
44 #include <sys/nlookup.h>
45 #include <sys/vnode.h>
46 #include <sys/sysctl.h>
47 
48 #include <vm/vm_zone.h>
49 
50 #ifdef _KERNEL_VIRTUAL
51 #include <dlfcn.h>
52 #endif
53 
54 #ifdef KLD_DEBUG
55 int kld_debug = 0;
56 #endif
57 
58 /* Metadata from the static kernel */
59 SET_DECLARE(modmetadata_set, struct mod_metadata);
60 MALLOC_DEFINE(M_LINKER, "kld", "kernel linker");
61 
62 linker_file_t linker_current_file;
63 linker_file_t linker_kernel_file;
64 
65 static struct lock lock;	/* lock for the file list */
66 static linker_class_list_t classes;
67 static linker_file_list_t linker_files;
68 static int next_file_id = 1;
69 
70 static void
71 linker_init(void* arg)
72 {
73     lockinit(&lock, "klink", 0, 0);
74     TAILQ_INIT(&classes);
75     TAILQ_INIT(&linker_files);
76 }
77 
78 SYSINIT(linker, SI_BOOT2_KLD, SI_ORDER_FIRST, linker_init, 0);
79 
80 int
81 linker_add_class(const char* desc, void* priv,
82 		 struct linker_class_ops* ops)
83 {
84     linker_class_t lc;
85 
86     lc = kmalloc(sizeof(struct linker_class), M_LINKER, M_NOWAIT);
87     if (!lc)
88 	return ENOMEM;
89     bzero(lc, sizeof(*lc));
90 
91     lc->desc = desc;
92     lc->priv = priv;
93     lc->ops = ops;
94     TAILQ_INSERT_HEAD(&classes, lc, link);
95 
96     return 0;
97 }
98 
99 static int
100 linker_file_sysinit(linker_file_t lf)
101 {
102     struct sysinit** start, ** stop;
103     struct sysinit** sipp;
104     struct sysinit** xipp;
105     struct sysinit* save;
106     const moduledata_t *moddata;
107     int error;
108 
109     KLD_DPF(FILE, ("linker_file_sysinit: calling SYSINITs for %s\n",
110 		   lf->filename));
111 
112     if (linker_file_lookup_set(lf, "sysinit_set", &start, &stop, NULL) != 0)
113 	return 0; /* XXX is this correct ? No sysinit ? */
114 
115     /* HACK ALERT! */
116     for (sipp = start; sipp < stop; sipp++) {
117 	if ((*sipp)->func == module_register_init) {
118 	    moddata = (*sipp)->udata;
119 	    error = module_register(moddata, lf);
120 	    if (error) {
121 		kprintf("linker_file_sysinit \"%s\" failed to register! %d\n",
122 		    lf->filename, error);
123 		return error;
124 	    }
125 	}
126     }
127 
128     /*
129      * Perform a bubble sort of the system initialization objects by
130      * their subsystem (primary key) and order (secondary key).
131      *
132      * Since some things care about execution order, this is the
133      * operation which ensures continued function.
134      */
135     for (sipp = start; sipp < stop; sipp++) {
136 	for (xipp = sipp + 1; xipp < stop; xipp++) {
137 	    if ((*sipp)->subsystem < (*xipp)->subsystem ||
138 		 ((*sipp)->subsystem == (*xipp)->subsystem &&
139 		  (*sipp)->order <= (*xipp)->order))
140 		continue;	/* skip*/
141 	    save = *sipp;
142 	    *sipp = *xipp;
143 	    *xipp = save;
144 	}
145     }
146 
147 
148     /*
149      * Traverse the (now) ordered list of system initialization tasks.
150      * Perform each task, and continue on to the next task.
151      */
152     for (sipp = start; sipp < stop; sipp++) {
153 	if ((*sipp)->subsystem == SI_SPECIAL_DUMMY)
154 	    continue;	/* skip dummy task(s)*/
155 
156 	/* Call function */
157 	(*((*sipp)->func))((*sipp)->udata);
158     }
159     return 0; /* no errors */
160 }
161 
162 static void
163 linker_file_sysuninit(linker_file_t lf)
164 {
165     struct sysinit** start, ** stop;
166     struct sysinit** sipp;
167     struct sysinit** xipp;
168     struct sysinit* save;
169 
170     KLD_DPF(FILE, ("linker_file_sysuninit: calling SYSUNINITs for %s\n",
171 		   lf->filename));
172 
173     if (linker_file_lookup_set(lf, "sysuninit_set", &start, &stop, NULL) != 0)
174 	return;
175 
176     /*
177      * Perform a reverse bubble sort of the system initialization objects
178      * by their subsystem (primary key) and order (secondary key).
179      *
180      * Since some things care about execution order, this is the
181      * operation which ensures continued function.
182      */
183     for (sipp = start; sipp < stop; sipp++) {
184 	for (xipp = sipp + 1; xipp < stop; xipp++) {
185 	    if ((*sipp)->subsystem > (*xipp)->subsystem ||
186 		 ((*sipp)->subsystem == (*xipp)->subsystem &&
187 		  (*sipp)->order >= (*xipp)->order))
188 		continue;	/* skip*/
189 	    save = *sipp;
190 	    *sipp = *xipp;
191 	    *xipp = save;
192 	}
193     }
194 
195 
196     /*
197      * Traverse the (now) ordered list of system initialization tasks.
198      * Perform each task, and continue on to the next task.
199      */
200     for (sipp = start; sipp < stop; sipp++) {
201 	if ((*sipp)->subsystem == SI_SPECIAL_DUMMY)
202 	    continue;	/* skip dummy task(s)*/
203 
204 	/* Call function */
205 	(*((*sipp)->func))((*sipp)->udata);
206     }
207 }
208 
209 static void
210 linker_file_register_sysctls(linker_file_t lf)
211 {
212     struct sysctl_oid **start, **stop, **oidp;
213 
214     KLD_DPF(FILE, ("linker_file_register_sysctls: registering SYSCTLs for %s\n",
215 		   lf->filename));
216 
217     if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
218 	return;
219     for (oidp = start; oidp < stop; oidp++)
220 	sysctl_register_oid(*oidp);
221 }
222 
223 static void
224 linker_file_unregister_sysctls(linker_file_t lf)
225 {
226     struct sysctl_oid **start, **stop, **oidp;
227 
228     KLD_DPF(FILE, ("linker_file_unregister_sysctls: registering SYSCTLs for %s\n",
229 		   lf->filename));
230 
231     if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
232 	return;
233     for (oidp = start; oidp < stop; oidp++)
234 	sysctl_unregister_oid(*oidp);
235 }
236 
237 int
238 linker_load_file(const char* filename, linker_file_t* result)
239 {
240     linker_class_t lc;
241     linker_file_t lf;
242     int foundfile, error = 0;
243     char *koname = NULL;
244 
245     /* Refuse to load modules if securelevel raised */
246     if (securelevel > 0 || kernel_mem_readonly)
247 	return EPERM;
248 
249     lf = linker_find_file_by_name(filename);
250     if (lf) {
251 	KLD_DPF(FILE, ("linker_load_file: file %s is already loaded, incrementing refs\n", filename));
252 	*result = lf;
253 	lf->refs++;
254 	goto out;
255     }
256     if (find_mod_metadata(filename)) {
257 	if (linker_kernel_file)
258 	    ++linker_kernel_file->refs;
259 	*result = linker_kernel_file;
260 	goto out;
261     }
262 
263     koname = kmalloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
264     if (koname == NULL) {
265 	error = ENOMEM;
266 	goto out;
267     }
268     ksprintf(koname, "%s.ko", filename);
269     lf = NULL;
270     foundfile = 0;
271     for (lc = TAILQ_FIRST(&classes); lc; lc = TAILQ_NEXT(lc, link)) {
272 	KLD_DPF(FILE, ("linker_load_file: trying to load %s as %s\n",
273 		       filename, lc->desc));
274 
275 	error = lc->ops->load_file(koname, &lf);	/* First with .ko */
276 	if (lf == NULL && error == ENOENT)
277 	    error = lc->ops->load_file(filename, &lf);	/* Then try without */
278 	/*
279 	 * If we got something other than ENOENT, then it exists but we cannot
280 	 * load it for some other reason.
281 	 */
282 	if (error != ENOENT)
283 	    foundfile = 1;
284 	if (lf) {
285 	    linker_file_register_sysctls(lf);
286 	    error = linker_file_sysinit(lf);
287 
288 	    *result = lf;
289 	    goto out;
290 	}
291     }
292     /*
293      * Less than ideal, but tells the user whether it failed to load or
294      * the module was not found.
295      */
296     if (foundfile) {
297 	    /*
298 	     * Format not recognized or otherwise unloadable.
299 	     * When loading a module that is statically built into
300 	     * the kernel EEXIST percolates back up as the return
301 	     * value.  Preserve this so that apps can recognize this
302 	     * special case.
303 	     */
304 	    if (error != EEXIST)
305 		    error = ENOEXEC;
306     } else {
307 	error = ENOENT;		/* Nothing found */
308     }
309 
310 out:
311     if (koname)
312 	kfree(koname, M_LINKER);
313     return error;
314 }
315 
316 linker_file_t
317 linker_find_file_by_name(const char* filename)
318 {
319     linker_file_t lf = 0;
320     char *koname;
321     int i;
322 
323     for (i = strlen(filename); i > 0 && filename[i-1] != '/'; --i)
324 	;
325     filename += i;
326 
327     koname = kmalloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
328     if (koname == NULL)
329 	goto out;
330     ksprintf(koname, "%s.ko", filename);
331 
332     lockmgr(&lock, LK_SHARED);
333     for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link)) {
334 	if (!strcmp(lf->filename, koname))
335 	    break;
336 	if (!strcmp(lf->filename, filename))
337 	    break;
338     }
339     lockmgr(&lock, LK_RELEASE);
340 
341 out:
342     if (koname)
343 	kfree(koname, M_LINKER);
344     return lf;
345 }
346 
347 linker_file_t
348 linker_find_file_by_id(int fileid)
349 {
350     linker_file_t lf = 0;
351 
352     lockmgr(&lock, LK_SHARED);
353     for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link))
354 	if (lf->id == fileid)
355 	    break;
356     lockmgr(&lock, LK_RELEASE);
357 
358     return lf;
359 }
360 
361 linker_file_t
362 linker_make_file(const char* pathname, void* priv, struct linker_file_ops* ops)
363 {
364     linker_file_t lf = 0;
365     int namelen;
366     const char *filename;
367 
368     filename = rindex(pathname, '/');
369     if (filename && filename[1])
370 	filename++;
371     else
372 	filename = pathname;
373 
374     KLD_DPF(FILE, ("linker_make_file: new file, filename=%s\n", filename));
375     lockmgr(&lock, LK_EXCLUSIVE);
376     namelen = strlen(filename) + 1;
377     lf = kmalloc(sizeof(struct linker_file) + namelen, M_LINKER, M_WAITOK);
378     if (!lf)
379 	goto out;
380     bzero(lf, sizeof(*lf));
381 
382     lf->refs = 1;
383     lf->userrefs = 0;
384     lf->flags = 0;
385     lf->filename = (char*) (lf + 1);
386     strcpy(lf->filename, filename);
387     lf->id = next_file_id++;
388     lf->ndeps = 0;
389     lf->deps = NULL;
390     STAILQ_INIT(&lf->common);
391     TAILQ_INIT(&lf->modules);
392 
393     lf->priv = priv;
394     lf->ops = ops;
395     TAILQ_INSERT_TAIL(&linker_files, lf, link);
396 
397 out:
398     lockmgr(&lock, LK_RELEASE);
399     return lf;
400 }
401 
402 int
403 linker_file_unload(linker_file_t file)
404 {
405     module_t mod, next;
406     struct common_symbol* cp;
407     int error = 0;
408     int i;
409 
410     /* Refuse to unload modules if securelevel raised */
411     if (securelevel > 0 || kernel_mem_readonly)
412 	return EPERM;
413 
414     KLD_DPF(FILE, ("linker_file_unload: lf->refs=%d\n", file->refs));
415     lockmgr(&lock, LK_EXCLUSIVE);
416     if (file->refs == 1) {
417 	KLD_DPF(FILE, ("linker_file_unload: file is unloading, informing modules\n"));
418 	/*
419 	 * Temporarily bump file->refs to prevent recursive unloading
420 	 */
421 	++file->refs;
422 
423 	/*
424 	 * Inform any modules associated with this file.
425 	 */
426 	mod = TAILQ_FIRST(&file->modules);
427 	while (mod) {
428 	    /*
429 	     * Give the module a chance to veto the unload.  Note that the
430 	     * act of unloading the module may cause other modules in the
431 	     * same file list to be unloaded recursively.
432 	     */
433 	    if ((error = module_unload(mod)) != 0) {
434 		KLD_DPF(FILE, ("linker_file_unload: module %x vetoes unload\n",
435 			       mod));
436 		lockmgr(&lock, LK_RELEASE);
437 		file->refs--;
438 		goto out;
439 	    }
440 
441 	    /*
442 	     * Recursive relationships may prevent the release from
443 	     * immediately removing the module, or may remove other
444 	     * modules in the list.
445 	     */
446 	    next = module_getfnext(mod);
447 	    module_release(mod);
448 	    mod = next;
449 	}
450 
451 	/*
452 	 * Since we intend to destroy the file structure, we expect all
453 	 * modules to have been removed by now.
454 	 */
455 	for (mod = TAILQ_FIRST(&file->modules);
456 	     mod;
457 	     mod = module_getfnext(mod)
458 	) {
459 	    kprintf("linker_file_unload: module %p still has refs!\n", mod);
460 	}
461 	--file->refs;
462     }
463 
464     file->refs--;
465     if (file->refs > 0) {
466 	lockmgr(&lock, LK_RELEASE);
467 	goto out;
468     }
469 
470     /* Don't try to run SYSUNINITs if we are unloaded due to a link error */
471     if (file->flags & LINKER_FILE_LINKED) {
472 	linker_file_sysuninit(file);
473 	linker_file_unregister_sysctls(file);
474     }
475 
476     TAILQ_REMOVE(&linker_files, file, link);
477     lockmgr(&lock, LK_RELEASE);
478 
479     for (i = 0; i < file->ndeps; i++)
480 	linker_file_unload(file->deps[i]);
481     kfree(file->deps, M_LINKER);
482 
483     for (cp = STAILQ_FIRST(&file->common); cp;
484 	 cp = STAILQ_FIRST(&file->common)) {
485 	STAILQ_REMOVE(&file->common, cp, common_symbol, link);
486 	kfree(cp, M_LINKER);
487     }
488 
489     file->ops->unload(file);
490     kfree(file, M_LINKER);
491 
492 out:
493     return error;
494 }
495 
496 int
497 linker_file_add_dependancy(linker_file_t file, linker_file_t dep)
498 {
499     linker_file_t* newdeps;
500 
501     newdeps = kmalloc((file->ndeps + 1) * sizeof(linker_file_t*),
502 		     M_LINKER, M_WAITOK);
503     if (newdeps == NULL)
504 	return ENOMEM;
505     bzero(newdeps, (file->ndeps + 1) * sizeof(linker_file_t*));
506 
507     if (file->deps) {
508 	bcopy(file->deps, newdeps, file->ndeps * sizeof(linker_file_t*));
509 	kfree(file->deps, M_LINKER);
510     }
511     file->deps = newdeps;
512     file->deps[file->ndeps] = dep;
513     file->ndeps++;
514 
515     return 0;
516 }
517 
518 /*
519  * Locate a linker set and its contents.
520  * This is a helper function to avoid linker_if.h exposure elsewhere.
521  * Note: firstp and lastp are really void ***
522  */
523 int
524 linker_file_lookup_set(linker_file_t file, const char *name,
525                       void *firstp, void *lastp, int *countp)
526 {
527     return file->ops->lookup_set(file, name, firstp, lastp, countp);
528 }
529 
530 int
531 linker_file_lookup_symbol(linker_file_t file, const char* name, int deps, caddr_t *raddr)
532 {
533     c_linker_sym_t sym;
534     linker_symval_t symval;
535     linker_file_t lf;
536     size_t common_size = 0;
537     int i;
538 
539     KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%x, name=%s, deps=%d\n",
540 		  file, name, deps));
541 
542     if (file->ops->lookup_symbol(file, name, &sym) == 0) {
543 	file->ops->symbol_values(file, sym, &symval);
544 
545 	/*
546 	 * XXX Assume a common symbol if its value is 0 and it has a non-zero
547 	 * size, otherwise it could be an absolute symbol with a value of 0.
548 	 */
549 	if (symval.value == 0 && symval.size != 0) {
550 	    /*
551 	     * For commons, first look them up in the dependancies and
552 	     * only allocate space if not found there.
553 	     */
554 	    common_size = symval.size;
555 	} else {
556 	    KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol.value=%x\n", symval.value));
557 	    *raddr = symval.value;
558 	    return 0;
559 	}
560     }
561     if (deps) {
562 	for (i = 0; i < file->ndeps; i++) {
563 	    if (linker_file_lookup_symbol(file->deps[i], name, 0, raddr) == 0) {
564 		KLD_DPF(SYM, ("linker_file_lookup_symbol: deps value=%x\n", *raddr));
565 		return 0;
566 	    }
567 	}
568 
569 	/* If we have not found it in the dependencies, search globally */
570 	for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link)) {
571 	    /* But skip the current file if it's on the list */
572 	    if (lf == file)
573 		continue;
574 	    /* And skip the files we searched above */
575 	    for (i = 0; i < file->ndeps; i++)
576 		if (lf == file->deps[i])
577 		    break;
578 	    if (i < file->ndeps)
579 		continue;
580 	    if (linker_file_lookup_symbol(lf, name, 0, raddr) == 0) {
581 		KLD_DPF(SYM, ("linker_file_lookup_symbol: global value=%x\n", *raddr));
582 		return 0;
583 	    }
584 	}
585     }
586 
587     if (common_size > 0) {
588 	/*
589 	 * This is a common symbol which was not found in the
590 	 * dependancies.  We maintain a simple common symbol table in
591 	 * the file object.
592 	 */
593 	struct common_symbol* cp;
594 
595 	for (cp = STAILQ_FIRST(&file->common); cp;
596 	     cp = STAILQ_NEXT(cp, link))
597 	    if (!strcmp(cp->name, name)) {
598 		KLD_DPF(SYM, ("linker_file_lookup_symbol: old common value=%x\n", cp->address));
599 		*raddr = cp->address;
600 		return 0;
601 	    }
602 
603 	/*
604 	 * Round the symbol size up to align.
605 	 */
606 	common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
607 	cp = kmalloc(sizeof(struct common_symbol)
608 		    + common_size
609 		    + strlen(name) + 1,
610 		    M_LINKER, M_WAITOK);
611 	if (!cp) {
612 	    KLD_DPF(SYM, ("linker_file_lookup_symbol: nomem\n"));
613 	    return ENOMEM;
614 	}
615 	bzero(cp, sizeof(struct common_symbol) + common_size + strlen(name)+ 1);
616 
617 	cp->address = (caddr_t) (cp + 1);
618 	cp->name = cp->address + common_size;
619 	strcpy(cp->name, name);
620 	bzero(cp->address, common_size);
621 	STAILQ_INSERT_TAIL(&file->common, cp, link);
622 
623 	KLD_DPF(SYM, ("linker_file_lookup_symbol: new common value=%x\n", cp->address));
624 	*raddr = cp->address;
625 	return 0;
626     }
627 
628 #ifdef _KERNEL_VIRTUAL
629     *raddr = dlsym(RTLD_NEXT, name);
630     if (*raddr != NULL) {
631 	KLD_DPF(SYM, ("linker_file_lookup_symbol: found dlsym=%x\n", *raddr));
632 	return 0;
633     }
634 #endif
635 
636     KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
637     return ENOENT;
638 }
639 
640 #ifdef DDB
641 /*
642  * DDB Helpers.  DDB has to look across multiple files with their own
643  * symbol tables and string tables.
644  *
645  * Note that we do not obey list locking protocols here.  We really don't
646  * need DDB to hang because somebody's got the lock held.  We'll take the
647  * chance that the files list is inconsistant instead.
648  */
649 
650 int
651 linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
652 {
653     linker_file_t lf;
654 
655     for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link)) {
656 	if (lf->ops->lookup_symbol(lf, symstr, sym) == 0)
657 	    return 0;
658     }
659     return ENOENT;
660 }
661 
662 int
663 linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
664 {
665     linker_file_t lf;
666     u_long off = (uintptr_t)value;
667     u_long diff, bestdiff;
668     c_linker_sym_t best;
669     c_linker_sym_t es;
670 
671     best = 0;
672     bestdiff = off;
673     for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link)) {
674 	if (lf->ops->search_symbol(lf, value, &es, &diff) != 0)
675 	    continue;
676 	if (es != 0 && diff < bestdiff) {
677 	    best = es;
678 	    bestdiff = diff;
679 	}
680 	if (bestdiff == 0)
681 	    break;
682     }
683     if (best) {
684 	*sym = best;
685 	*diffp = bestdiff;
686 	return 0;
687     } else {
688 	*sym = 0;
689 	*diffp = off;
690 	return ENOENT;
691     }
692 }
693 
694 int
695 linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
696 {
697     linker_file_t lf;
698 
699     for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link)) {
700 	if (lf->ops->symbol_values(lf, sym, symval) == 0)
701 	    return 0;
702     }
703     return ENOENT;
704 }
705 
706 #endif
707 
708 /*
709  * Syscalls.
710  */
711 
712 int
713 sys_kldload(struct kldload_args *uap)
714 {
715     struct thread *td = curthread;
716     char* filename = NULL, *modulename;
717     linker_file_t lf;
718     int error = 0;
719 
720     uap->sysmsg_result = -1;
721 
722     if (securelevel > 0 || kernel_mem_readonly)	/* redundant, but that's OK */
723 	return EPERM;
724 
725     if ((error = suser(td)) != 0)
726 	return error;
727 
728     filename = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
729     if ((error = copyinstr(uap->file, filename, MAXPATHLEN, NULL)) != 0)
730 	goto out;
731 
732     /* Can't load more than one module with the same name */
733     modulename = rindex(filename, '/');
734     if (modulename == NULL)
735 	modulename = filename;
736     else
737 	modulename++;
738     if (linker_find_file_by_name(modulename)) {
739 	error = EEXIST;
740 	goto out;
741     }
742 
743     if ((error = linker_load_file(filename, &lf)) != 0)
744 	goto out;
745 
746     lf->userrefs++;
747     uap->sysmsg_result = lf->id;
748 
749 out:
750     if (filename)
751 	kfree(filename, M_TEMP);
752     return error;
753 }
754 
755 int
756 sys_kldunload(struct kldunload_args *uap)
757 {
758     struct thread *td = curthread;
759     linker_file_t lf;
760     int error = 0;
761 
762     if (securelevel > 0 || kernel_mem_readonly)	/* redundant, but that's OK */
763 	return EPERM;
764 
765     if ((error = suser(td)) != 0)
766 	return error;
767 
768     lf = linker_find_file_by_id(uap->fileid);
769     if (lf) {
770 	KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
771 	if (lf->userrefs == 0) {
772 	    kprintf("linkerunload: attempt to unload file that was loaded by the kernel\n");
773 	    error = EBUSY;
774 	    goto out;
775 	}
776 	lf->userrefs--;
777 	error = linker_file_unload(lf);
778 	if (error)
779 	    lf->userrefs++;
780     } else
781 	error = ENOENT;
782 
783 out:
784     return error;
785 }
786 
787 int
788 sys_kldfind(struct kldfind_args *uap)
789 {
790     char *filename = NULL, *modulename;
791     linker_file_t lf;
792     int error = 0;
793 
794     uap->sysmsg_result = -1;
795 
796     filename = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
797     if ((error = copyinstr(uap->file, filename, MAXPATHLEN, NULL)) != 0)
798 	goto out;
799 
800     modulename = rindex(filename, '/');
801     if (modulename == NULL)
802 	modulename = filename;
803 
804     lf = linker_find_file_by_name(modulename);
805     if (lf)
806 	uap->sysmsg_result = lf->id;
807     else
808 	error = ENOENT;
809 
810 out:
811     if (filename)
812 	kfree(filename, M_TEMP);
813     return error;
814 }
815 
816 int
817 sys_kldnext(struct kldnext_args *uap)
818 {
819     linker_file_t lf;
820     int error = 0;
821 
822     if (uap->fileid == 0) {
823 	if (TAILQ_FIRST(&linker_files))
824 	    uap->sysmsg_result = TAILQ_FIRST(&linker_files)->id;
825 	else
826 	    uap->sysmsg_result = 0;
827 	return 0;
828     }
829 
830     lf = linker_find_file_by_id(uap->fileid);
831     if (lf) {
832 	if (TAILQ_NEXT(lf, link))
833 	    uap->sysmsg_result = TAILQ_NEXT(lf, link)->id;
834 	else
835 	    uap->sysmsg_result = 0;
836     } else
837 	error = ENOENT;
838 
839     return error;
840 }
841 
842 int
843 sys_kldstat(struct kldstat_args *uap)
844 {
845     linker_file_t lf;
846     int error = 0;
847     int version;
848     struct kld_file_stat* stat;
849     int namelen;
850 
851     lf = linker_find_file_by_id(uap->fileid);
852     if (!lf) {
853 	error = ENOENT;
854 	goto out;
855     }
856 
857     stat = uap->stat;
858 
859     /*
860      * Check the version of the user's structure.
861      */
862     if ((error = copyin(&stat->version, &version, sizeof(version))) != 0)
863 	goto out;
864     if (version != sizeof(struct kld_file_stat)) {
865 	error = EINVAL;
866 	goto out;
867     }
868 
869     namelen = strlen(lf->filename) + 1;
870     if (namelen > MAXPATHLEN)
871 	namelen = MAXPATHLEN;
872     if ((error = copyout(lf->filename, &stat->name[0], namelen)) != 0)
873 	goto out;
874     if ((error = copyout(&lf->refs, &stat->refs, sizeof(int))) != 0)
875 	goto out;
876     if ((error = copyout(&lf->id, &stat->id, sizeof(int))) != 0)
877 	goto out;
878     if ((error = copyout(&lf->address, &stat->address, sizeof(caddr_t))) != 0)
879 	goto out;
880     if ((error = copyout(&lf->size, &stat->size, sizeof(size_t))) != 0)
881 	goto out;
882 
883     uap->sysmsg_result = 0;
884 
885 out:
886     return error;
887 }
888 
889 int
890 sys_kldfirstmod(struct kldfirstmod_args *uap)
891 {
892     linker_file_t lf;
893     int error = 0;
894 
895     lf = linker_find_file_by_id(uap->fileid);
896     if (lf) {
897 	if (TAILQ_FIRST(&lf->modules))
898 	    uap->sysmsg_result = module_getid(TAILQ_FIRST(&lf->modules));
899 	else
900 	    uap->sysmsg_result = 0;
901     } else
902 	error = ENOENT;
903 
904     return error;
905 }
906 
907 int
908 sys_kldsym(struct kldsym_args *uap)
909 {
910     char *symstr = NULL;
911     c_linker_sym_t sym;
912     linker_symval_t symval;
913     linker_file_t lf;
914     struct kld_sym_lookup lookup;
915     int error = 0;
916 
917     if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
918 	goto out;
919     if (lookup.version != sizeof(lookup) || uap->cmd != KLDSYM_LOOKUP) {
920 	error = EINVAL;
921 	goto out;
922     }
923 
924     symstr = kmalloc(MAXPATHLEN, M_TEMP, M_WAITOK);
925     if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
926 	goto out;
927 
928     if (uap->fileid != 0) {
929 	lf = linker_find_file_by_id(uap->fileid);
930 	if (lf == NULL) {
931 	    error = ENOENT;
932 	    goto out;
933 	}
934 	if (lf->ops->lookup_symbol(lf, symstr, &sym) == 0 &&
935 	    lf->ops->symbol_values(lf, sym, &symval) == 0) {
936 	    lookup.symvalue = (uintptr_t)symval.value;
937 	    lookup.symsize = symval.size;
938 	    error = copyout(&lookup, uap->data, sizeof(lookup));
939 	} else
940 	    error = ENOENT;
941     } else {
942 	for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link)) {
943 	    if (lf->ops->lookup_symbol(lf, symstr, &sym) == 0 &&
944 		lf->ops->symbol_values(lf, sym, &symval) == 0) {
945 		lookup.symvalue = (uintptr_t)symval.value;
946 		lookup.symsize = symval.size;
947 		error = copyout(&lookup, uap->data, sizeof(lookup));
948 		break;
949 	    }
950 	}
951 	if (!lf)
952 	    error = ENOENT;
953     }
954 out:
955     if (symstr)
956 	kfree(symstr, M_TEMP);
957     return error;
958 }
959 
960 /*
961  * Look for module metadata in the static kernel
962  */
963 struct mod_metadata *
964 find_mod_metadata(const char *modname)
965 {
966     int len;
967     struct mod_metadata **mdp;
968     struct mod_metadata *mdt;
969 
970     /*
971      * Strip path prefixes and any dot extension.  MDT_MODULE names
972      * are just the module name without a path or ".ko".
973      */
974     for (len = strlen(modname) - 1; len >= 0; --len) {
975 	if (modname[len] == '/')
976 	    break;
977     }
978     modname += len + 1;
979     for (len = 0; modname[len] && modname[len] != '.'; ++len)
980 	;
981 
982     /*
983      * Look for the module declaration
984      */
985     SET_FOREACH(mdp, modmetadata_set) {
986 	mdt = *mdp;
987 	if (mdt->md_type != MDT_MODULE)
988 	    continue;
989 	if (strlen(mdt->md_cval) == len &&
990 	    strncmp(mdt->md_cval, modname, len) == 0) {
991 	    return(mdt);
992 	}
993     }
994     return(NULL);
995 }
996 
997 /*
998  * Preloaded module support
999  */
1000 static void
1001 linker_preload(void* arg)
1002 {
1003     caddr_t		modptr;
1004     char		*modname;
1005     char		*modtype;
1006     linker_file_t	lf;
1007     linker_class_t	lc;
1008     int			error;
1009     struct sysinit	**sipp;
1010     const moduledata_t	*moddata;
1011     struct sysinit	**si_start, **si_stop;
1012 
1013     modptr = NULL;
1014     while ((modptr = preload_search_next_name(modptr)) != NULL) {
1015 	modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1016 	modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1017 	if (modname == NULL) {
1018 	    kprintf("Preloaded module at %p does not have a name!\n", modptr);
1019 	    continue;
1020 	}
1021 	if (modtype == NULL) {
1022 	    kprintf("Preloaded module at %p does not have a type!\n", modptr);
1023 	    continue;
1024 	}
1025 
1026 	/*
1027 	 * This is a hack at the moment, but what's in FreeBSD-5 is even
1028 	 * worse so I'd rather the hack.
1029 	 */
1030 	kprintf("Preloaded %s \"%s\" at %p", modtype, modname, modptr);
1031 	if (find_mod_metadata(modname)) {
1032 	    kprintf(" (ignored, already in static kernel)\n");
1033 	    continue;
1034 	}
1035 	kprintf(".\n");
1036 
1037 	lf = linker_find_file_by_name(modname);
1038 	if (lf) {
1039 	    lf->refs++;
1040 	    lf->userrefs++;
1041 	    continue;
1042 	}
1043 	lf = NULL;
1044 	for (lc = TAILQ_FIRST(&classes); lc; lc = TAILQ_NEXT(lc, link)) {
1045 	    error = lc->ops->load_file(modname, &lf);
1046 	    if (error) {
1047 		lf = NULL;
1048 		break;
1049 	    }
1050 	}
1051 	if (lf) {
1052 	    lf->userrefs++;
1053 
1054 	    if (linker_file_lookup_set(lf, "sysinit_set", &si_start, &si_stop, NULL) == 0) {
1055 		/* HACK ALERT!
1056 		 * This is to set the sysinit moduledata so that the module
1057 		 * can attach itself to the correct containing file.
1058 		 * The sysinit could be run at *any* time.
1059 		 */
1060 		for (sipp = si_start; sipp < si_stop; sipp++) {
1061 		    if ((*sipp)->func == module_register_init) {
1062 			moddata = (*sipp)->udata;
1063 			error = module_register(moddata, lf);
1064 			if (error)
1065 			    kprintf("Preloaded %s \"%s\" failed to register: %d\n",
1066 				modtype, modname, error);
1067 		    }
1068 		}
1069 		sysinit_add(si_start, si_stop);
1070 	    }
1071 	    linker_file_register_sysctls(lf);
1072 	}
1073     }
1074 }
1075 
1076 SYSINIT(preload, SI_BOOT2_KLD, SI_ORDER_MIDDLE, linker_preload, 0);
1077 
1078 /*
1079  * Search for a not-loaded module by name.
1080  *
1081  * Modules may be found in the following locations:
1082  *
1083  * - preloaded (result is just the module name)
1084  * - on disk (result is full path to module)
1085  *
1086  * If the module name is qualified in any way (contains path, etc.)
1087  * the we simply return a copy of it.
1088  *
1089  * The search path can be manipulated via sysctl.  Note that we use the ';'
1090  * character as a separator to be consistent with the bootloader.
1091  */
1092 
1093 static char linker_path[MAXPATHLEN] = "/;/boot;/modules";
1094 
1095 SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RW, linker_path,
1096 	      sizeof(linker_path), "module load search path");
1097 TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1098 
1099 static char *
1100 linker_strdup(const char *str)
1101 {
1102     char	*result;
1103 
1104     if ((result = kmalloc((strlen(str) + 1), M_LINKER, M_WAITOK)) != NULL)
1105 	strcpy(result, str);
1106     return(result);
1107 }
1108 
1109 char *
1110 linker_search_path(const char *name)
1111 {
1112     struct nlookupdata	nd;
1113     char		*cp, *ep, *result;
1114     size_t		name_len, prefix_len;
1115     int			sep;
1116     int			error;
1117     enum vtype		type;
1118 
1119     /* qualified at all? */
1120     if (index(name, '/'))
1121 	return(linker_strdup(name));
1122 
1123     /* traverse the linker path */
1124     cp = linker_path;
1125     name_len = strlen(name);
1126     for (;;) {
1127 
1128 	/* find the end of this component */
1129 	for (ep = cp; (*ep != 0) && (*ep != ';'); ep++)
1130 	    ;
1131 	prefix_len = ep - cp;
1132 	/* if this component doesn't end with a slash, add one */
1133 	if (ep == cp || *(ep - 1) != '/')
1134 	    sep = 1;
1135 	else
1136 	    sep = 0;
1137 
1138 	/*
1139 	 * +2 : possible separator, plus terminator.
1140 	 */
1141 	result = kmalloc(prefix_len + name_len + 2, M_LINKER, M_WAITOK);
1142 
1143 	strncpy(result, cp, prefix_len);
1144 	if (sep)
1145 	    result[prefix_len++] = '/';
1146 	strcpy(result + prefix_len, name);
1147 
1148 	/*
1149 	 * Attempt to open the file, and return the path if we succeed and it's
1150 	 * a regular file.
1151 	 */
1152 	error = nlookup_init(&nd, result, UIO_SYSSPACE, NLC_FOLLOW|NLC_LOCKVP);
1153 	if (error == 0)
1154 	    error = vn_open(&nd, NULL, FREAD, 0);
1155 	if (error == 0) {
1156 	    type = nd.nl_open_vp->v_type;
1157 	    if (type == VREG) {
1158 		nlookup_done(&nd);
1159 		return (result);
1160 	    }
1161 	}
1162 	nlookup_done(&nd);
1163 	kfree(result, M_LINKER);
1164 
1165 	if (*ep == 0)
1166 	    break;
1167 	cp = ep + 1;
1168     }
1169     return(NULL);
1170 }
1171