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