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