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