xref: /freebsd/sys/kern/kern_linker.c (revision ee41f1b1cf5e3d4f586cb85b46123b416275862c)
1 /*-
2  * Copyright (c) 1997-2000 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$
27  */
28 
29 #include "opt_ddb.h"
30 
31 #include <sys/param.h>
32 #include <sys/kernel.h>
33 #include <sys/systm.h>
34 #include <sys/malloc.h>
35 #include <sys/sysproto.h>
36 #include <sys/sysent.h>
37 #include <sys/proc.h>
38 #include <sys/lock.h>
39 #include <sys/module.h>
40 #include <sys/linker.h>
41 #include <sys/fcntl.h>
42 #include <sys/libkern.h>
43 #include <sys/namei.h>
44 #include <sys/vnode.h>
45 #include <sys/sysctl.h>
46 
47 
48 #include "linker_if.h"
49 
50 #ifdef KLD_DEBUG
51 int kld_debug = 0;
52 #endif
53 
54 static char *linker_search_path(const char *name);
55 static const char *linker_basename(const char* path);
56 
57 MALLOC_DEFINE(M_LINKER, "linker", "kernel linker");
58 
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 /* XXX wrong name; we're looking at version provision tags here, not modules */
67 typedef TAILQ_HEAD(, modlist) modlisthead_t;
68 struct modlist {
69     TAILQ_ENTRY(modlist) link;		/* chain together all modules */
70     linker_file_t	container;
71     const char		*name;
72 };
73 typedef struct modlist	*modlist_t;
74 static modlisthead_t	found_modules;
75 
76 static char *
77 linker_strdup(const char *str)
78 {
79     char	*result;
80 
81     if ((result = malloc((strlen(str) + 1), M_LINKER, M_WAITOK)) != NULL)
82 	strcpy(result, str);
83     return(result);
84 }
85 
86 static void
87 linker_init(void* arg)
88 {
89     lockinit(&lock, PVM, "klink", 0, 0);
90     TAILQ_INIT(&classes);
91     TAILQ_INIT(&linker_files);
92 }
93 
94 SYSINIT(linker, SI_SUB_KLD, SI_ORDER_FIRST, linker_init, 0);
95 
96 int
97 linker_add_class(linker_class_t lc)
98 {
99     kobj_class_compile((kobj_class_t) lc);
100     TAILQ_INSERT_TAIL(&classes, lc, link);
101     return 0;
102 }
103 
104 static void
105 linker_file_sysinit(linker_file_t lf)
106 {
107     struct linker_set* sysinits;
108     struct sysinit** sipp;
109     struct sysinit** xipp;
110     struct sysinit* save;
111 
112     KLD_DPF(FILE, ("linker_file_sysinit: calling SYSINITs for %s\n",
113 		   lf->filename));
114 
115     sysinits = (struct linker_set*)
116 	linker_file_lookup_symbol(lf, "sysinit_set", 0);
117 
118     KLD_DPF(FILE, ("linker_file_sysinit: SYSINITs %p\n", sysinits));
119     if (!sysinits)
120 	return;
121     /*
122      * Perform a bubble sort of the system initialization objects by
123      * their subsystem (primary key) and order (secondary key).
124      *
125      * Since some things care about execution order, this is the
126      * operation which ensures continued function.
127      */
128     for (sipp = (struct sysinit **)sysinits->ls_items; *sipp; sipp++) {
129 	for (xipp = sipp + 1; *xipp; xipp++) {
130 	    if ((*sipp)->subsystem < (*xipp)->subsystem ||
131 		 ((*sipp)->subsystem == (*xipp)->subsystem &&
132 		  (*sipp)->order <= (*xipp)->order))
133 		continue;	/* skip*/
134 	    save = *sipp;
135 	    *sipp = *xipp;
136 	    *xipp = save;
137 	}
138     }
139 
140 
141     /*
142      * Traverse the (now) ordered list of system initialization tasks.
143      * Perform each task, and continue on to the next task.
144      */
145     for (sipp = (struct sysinit **)sysinits->ls_items; *sipp; sipp++) {
146 	if ((*sipp)->subsystem == SI_SUB_DUMMY)
147 	    continue;	/* skip dummy task(s)*/
148 
149 	/* Call function */
150 	(*((*sipp)->func))((*sipp)->udata);
151     }
152 }
153 
154 static void
155 linker_file_sysuninit(linker_file_t lf)
156 {
157     struct linker_set* sysuninits;
158     struct sysinit** sipp;
159     struct sysinit** xipp;
160     struct sysinit* save;
161 
162     KLD_DPF(FILE, ("linker_file_sysuninit: calling SYSUNINITs for %s\n",
163 		   lf->filename));
164 
165     sysuninits = (struct linker_set*)
166 	linker_file_lookup_symbol(lf, "sysuninit_set", 0);
167 
168     KLD_DPF(FILE, ("linker_file_sysuninit: SYSUNINITs %p\n", sysuninits));
169     if (!sysuninits)
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 = (struct sysinit **)sysuninits->ls_items; *sipp; sipp++) {
180 	for (xipp = sipp + 1; *xipp; 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      * Traverse the (now) ordered list of system initialization tasks.
193      * Perform each task, and continue on to the next task.
194      */
195     for (sipp = (struct sysinit **)sysuninits->ls_items; *sipp; sipp++) {
196 	if ((*sipp)->subsystem == SI_SUB_DUMMY)
197 	    continue;	/* skip dummy task(s)*/
198 
199 	/* Call function */
200 	(*((*sipp)->func))((*sipp)->udata);
201     }
202 }
203 
204 static void
205 linker_file_register_sysctls(linker_file_t lf)
206 {
207     struct linker_set* sysctls;
208 
209     KLD_DPF(FILE, ("linker_file_register_sysctls: registering SYSCTLs for %s\n",
210 		   lf->filename));
211 
212     sysctls = (struct linker_set*)
213 	linker_file_lookup_symbol(lf, "sysctl_set", 0);
214 
215     KLD_DPF(FILE, ("linker_file_register_sysctls: SYSCTLs %p\n", sysctls));
216     if (!sysctls)
217 	return;
218 
219     sysctl_register_set(sysctls);
220 }
221 
222 static void
223 linker_file_unregister_sysctls(linker_file_t lf)
224 {
225     struct linker_set* sysctls;
226 
227     KLD_DPF(FILE, ("linker_file_unregister_sysctls: registering SYSCTLs for %s\n",
228 		   lf->filename));
229 
230     sysctls = (struct linker_set*)
231 	linker_file_lookup_symbol(lf, "sysctl_set", 0);
232 
233     KLD_DPF(FILE, ("linker_file_unregister_sysctls: SYSCTLs %p\n", sysctls));
234     if (!sysctls)
235 	return;
236 
237     sysctl_unregister_set(sysctls);
238 }
239 
240 extern struct linker_set modmetadata_set;
241 
242 static int
243 linker_file_register_modules(linker_file_t lf)
244 {
245     int error, mcount;
246     struct linker_set *modules;
247     struct mod_metadata **mdpp;
248     const moduledata_t *moddata;
249     struct sysinit **sipp;
250 
251     KLD_DPF(FILE, ("linker_file_register_modules: registering modules in %s\n",
252 		   lf->filename));
253 
254     modules = (struct linker_set*)
255 	linker_file_lookup_symbol(lf, "modmetadata_set", 0);
256 
257     if (!modules && lf == linker_kernel_file)
258 	modules = &modmetadata_set;
259 
260     mcount = 0;
261     if (modules) {
262 	for (mdpp = (struct mod_metadata**)modules->ls_items; *mdpp; mdpp++) {
263 	    if ((*mdpp)->md_type != MDT_MODULE)
264 		continue;
265 	    mcount++;
266 	    moddata = (*mdpp)->md_data;
267 	    KLD_DPF(FILE, ("Registering module %s in %s\n",
268                  moddata->name, lf->filename));
269 	    error = module_register(moddata, lf);
270 	    if (error)
271 		printf("Module %s failed to register: %d\n", moddata->name, error);
272 	}
273     }
274     if (mcount)
275 	return mcount;	/* Do not mix old and new style */
276 
277     /* Hack - handle old kld's without metadata */
278     modules = (struct linker_set*)
279 	linker_file_lookup_symbol(lf, "sysinit_set", 0);
280     if (modules) {
281 	for (sipp = (struct sysinit **)modules->ls_items; *sipp; sipp++) {
282 	    if ((*sipp)->func != module_register_init)
283 		continue;
284 	    mcount++;
285 	    moddata = (*sipp)->udata;
286 	    printf("Old-style KLD file %s found\n", moddata->name);
287 	    error = module_register(moddata, lf);
288 	    if (error)
289 		printf("Old-style KLD file %s failed to register: %d\n", moddata->name, error);
290 	}
291     }
292     return mcount;
293 }
294 
295 static void
296 linker_init_kernel_modules(void)
297 {
298     linker_file_register_modules(linker_kernel_file);
299 }
300 
301 SYSINIT(linker_kernel, SI_SUB_KLD, SI_ORDER_ANY, linker_init_kernel_modules, 0);
302 
303 int
304 linker_load_file(const char* filename, linker_file_t* result)
305 {
306     linker_class_t lc;
307     linker_file_t lf;
308     int foundfile, error = 0;
309 
310     /* Refuse to load modules if securelevel raised */
311     if (securelevel > 0)
312 	return EPERM;
313 
314     lf = linker_find_file_by_name(filename);
315     if (lf) {
316 	KLD_DPF(FILE, ("linker_load_file: file %s is already loaded, incrementing refs\n", filename));
317 	*result = lf;
318 	lf->refs++;
319 	goto out;
320     }
321 
322     lf = NULL;
323     foundfile = 0;
324     TAILQ_FOREACH(lc, &classes, link) {
325 	KLD_DPF(FILE, ("linker_load_file: trying to load %s as %s\n",
326 		       filename, lc->desc));
327 	error = LINKER_LOAD_FILE(lc, filename, &lf);
328 	/*
329 	 * If we got something other than ENOENT, then it exists but we cannot
330 	 * load it for some other reason.
331 	 */
332 	if (error != ENOENT)
333 	    foundfile = 1;
334 	if (lf) {
335 	    linker_file_register_modules(lf);
336 	    linker_file_register_sysctls(lf);
337 	    linker_file_sysinit(lf);
338 	    lf->flags |= LINKER_FILE_LINKED;
339 
340 	    *result = lf;
341 	    error = 0;
342 	    goto out;
343 	}
344     }
345     /*
346      * Less than ideal, but tells the user whether it failed to load or
347      * the module was not found.
348      */
349     if (foundfile)
350 	error = ENOEXEC;	/* Format not recognised (or unloadable) */
351     else
352 	error = ENOENT;		/* Nothing found */
353 
354 out:
355     return error;
356 }
357 
358 linker_file_t
359 linker_find_file_by_name(const char* filename)
360 {
361     linker_file_t lf = 0;
362     char *koname;
363 
364     koname = malloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
365     if (koname == NULL)
366 	goto out;
367     sprintf(koname, "%s.ko", filename);
368 
369     lockmgr(&lock, LK_SHARED, 0, curproc);
370     TAILQ_FOREACH(lf, &linker_files, link) {
371 	if (!strcmp(lf->filename, koname))
372 	    break;
373 	if (!strcmp(lf->filename, filename))
374 	    break;
375     }
376     lockmgr(&lock, LK_RELEASE, 0, curproc);
377 
378 out:
379     if (koname)
380 	free(koname, M_LINKER);
381     return lf;
382 }
383 
384 linker_file_t
385 linker_find_file_by_id(int fileid)
386 {
387     linker_file_t lf = 0;
388 
389     lockmgr(&lock, LK_SHARED, 0, curproc);
390     TAILQ_FOREACH(lf, &linker_files, link)
391 	if (lf->id == fileid)
392 	    break;
393     lockmgr(&lock, LK_RELEASE, 0, curproc);
394 
395     return lf;
396 }
397 
398 linker_file_t
399 linker_make_file(const char* pathname, linker_class_t lc)
400 {
401     linker_file_t lf = 0;
402     const char *filename;
403 
404     filename = linker_basename(pathname);
405 
406     KLD_DPF(FILE, ("linker_make_file: new file, filename=%s\n", filename));
407     lockmgr(&lock, LK_EXCLUSIVE, 0, curproc);
408     lf = (linker_file_t) kobj_create((kobj_class_t) lc, M_LINKER, M_WAITOK);
409     if (!lf)
410 	goto out;
411 
412     lf->refs = 1;
413     lf->userrefs = 0;
414     lf->flags = 0;
415     lf->filename = linker_strdup(filename);
416     lf->id = next_file_id++;
417     lf->ndeps = 0;
418     lf->deps = NULL;
419     STAILQ_INIT(&lf->common);
420     TAILQ_INIT(&lf->modules);
421 
422     TAILQ_INSERT_TAIL(&linker_files, lf, link);
423 
424 out:
425     lockmgr(&lock, LK_RELEASE, 0, curproc);
426     return lf;
427 }
428 
429 int
430 linker_file_unload(linker_file_t file)
431 {
432     module_t mod, next;
433     modlist_t ml, nextml;
434     struct common_symbol* cp;
435     int error = 0;
436     int i;
437 
438     /* Refuse to unload modules if securelevel raised */
439     if (securelevel > 0)
440 	return EPERM;
441 
442     KLD_DPF(FILE, ("linker_file_unload: lf->refs=%d\n", file->refs));
443     lockmgr(&lock, LK_EXCLUSIVE, 0, curproc);
444     if (file->refs == 1) {
445 	KLD_DPF(FILE, ("linker_file_unload: file is unloading, informing modules\n"));
446 	/*
447 	 * Inform any modules associated with this file.
448 	 */
449 	for (mod = TAILQ_FIRST(&file->modules); mod; mod = next) {
450 	    next = module_getfnext(mod);
451 
452 	    /*
453 	     * Give the module a chance to veto the unload.
454 	     */
455 	    if ((error = module_unload(mod)) != 0) {
456 		KLD_DPF(FILE, ("linker_file_unload: module %x vetoes unload\n",
457 			       mod));
458 		lockmgr(&lock, LK_RELEASE, 0, curproc);
459 		goto out;
460 	    }
461 
462 	    module_release(mod);
463 	}
464     }
465 
466     file->refs--;
467     if (file->refs > 0) {
468 	lockmgr(&lock, LK_RELEASE, 0, curproc);
469 	goto out;
470     }
471 
472     for (ml = TAILQ_FIRST(&found_modules); ml; ml = nextml) {
473 	nextml = TAILQ_NEXT(ml, link);
474 	if (ml->container == file) {
475 	    TAILQ_REMOVE(&found_modules, ml, link);
476 	}
477     }
478 
479     /* Don't try to run SYSUNINITs if we are unloaded due to a link error */
480     if (file->flags & LINKER_FILE_LINKED) {
481 	linker_file_sysuninit(file);
482 	linker_file_unregister_sysctls(file);
483     }
484 
485     TAILQ_REMOVE(&linker_files, file, link);
486     lockmgr(&lock, LK_RELEASE, 0, curproc);
487 
488     if (file->deps) {
489 	for (i = 0; i < file->ndeps; i++)
490 	    linker_file_unload(file->deps[i]);
491 	free(file->deps, M_LINKER);
492 	file->deps = NULL;
493     }
494 
495     for (cp = STAILQ_FIRST(&file->common); cp;
496 	 cp = STAILQ_FIRST(&file->common)) {
497 	STAILQ_REMOVE(&file->common, cp, common_symbol, link);
498 	free(cp, M_LINKER);
499     }
500 
501     LINKER_UNLOAD(file);
502     if (file->filename) {
503 	free(file->filename, M_LINKER);
504 	file->filename = NULL;
505     }
506     kobj_delete((kobj_t) file, M_LINKER);
507 
508 out:
509     return error;
510 }
511 
512 int
513 linker_file_add_dependancy(linker_file_t file, linker_file_t dep)
514 {
515     linker_file_t* newdeps;
516 
517     newdeps = malloc((file->ndeps + 1) * sizeof(linker_file_t*),
518 		     M_LINKER, M_WAITOK | M_ZERO);
519     if (newdeps == NULL)
520 	return ENOMEM;
521 
522     if (file->deps) {
523 	bcopy(file->deps, newdeps, file->ndeps * sizeof(linker_file_t*));
524 	free(file->deps, M_LINKER);
525     }
526     file->deps = newdeps;
527     file->deps[file->ndeps] = dep;
528     file->ndeps++;
529 
530     return 0;
531 }
532 
533 caddr_t
534 linker_file_lookup_symbol(linker_file_t file, const char* name, int deps)
535 {
536     c_linker_sym_t sym;
537     linker_symval_t symval;
538     caddr_t address;
539     size_t common_size = 0;
540     int i;
541 
542     KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%x, name=%s, deps=%d\n",
543 		  file, name, deps));
544 
545     if (LINKER_LOOKUP_SYMBOL(file, name, &sym) == 0) {
546 	LINKER_SYMBOL_VALUES(file, sym, &symval);
547 	if (symval.value == 0)
548 	    /*
549 	     * For commons, first look them up in the dependancies and
550 	     * only allocate space if not found there.
551 	     */
552 	    common_size = symval.size;
553 	else {
554 	    KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol.value=%x\n", symval.value));
555 	    return symval.value;
556 	}
557     }
558 
559     if (deps) {
560 	for (i = 0; i < file->ndeps; i++) {
561 	    address = linker_file_lookup_symbol(file->deps[i], name, 0);
562 	    if (address) {
563 		KLD_DPF(SYM, ("linker_file_lookup_symbol: deps value=%x\n", address));
564 		return address;
565 	    }
566 	}
567     }
568 
569     if (common_size > 0) {
570 	/*
571 	 * This is a common symbol which was not found in the
572 	 * dependancies.  We maintain a simple common symbol table in
573 	 * the file object.
574 	 */
575 	struct common_symbol* cp;
576 
577 	STAILQ_FOREACH(cp, &file->common, link)
578 	    if (!strcmp(cp->name, name)) {
579 		KLD_DPF(SYM, ("linker_file_lookup_symbol: old common value=%x\n", cp->address));
580 		return cp->address;
581 	    }
582 
583 	/*
584 	 * Round the symbol size up to align.
585 	 */
586 	common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
587 	cp = malloc(sizeof(struct common_symbol)
588 		    + common_size
589 		    + strlen(name) + 1,
590 		    M_LINKER, M_WAITOK | M_ZERO);
591 	if (!cp) {
592 	    KLD_DPF(SYM, ("linker_file_lookup_symbol: nomem\n"));
593 	    return 0;
594 	}
595 
596 	cp->address = (caddr_t) (cp + 1);
597 	cp->name = cp->address + common_size;
598 	strcpy(cp->name, name);
599 	bzero(cp->address, common_size);
600 	STAILQ_INSERT_TAIL(&file->common, cp, link);
601 
602 	KLD_DPF(SYM, ("linker_file_lookup_symbol: new common value=%x\n", cp->address));
603 	return cp->address;
604     }
605 
606     KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
607     return 0;
608 }
609 
610 #ifdef DDB
611 /*
612  * DDB Helpers.  DDB has to look across multiple files with their own
613  * symbol tables and string tables.
614  *
615  * Note that we do not obey list locking protocols here.  We really don't
616  * need DDB to hang because somebody's got the lock held.  We'll take the
617  * chance that the files list is inconsistant instead.
618  */
619 
620 int
621 linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
622 {
623     linker_file_t lf;
624 
625     TAILQ_FOREACH(lf, &linker_files, link) {
626 	if (LINKER_LOOKUP_SYMBOL(lf, symstr, sym) == 0)
627 	    return 0;
628     }
629     return ENOENT;
630 }
631 
632 int
633 linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
634 {
635     linker_file_t lf;
636     u_long off = (uintptr_t)value;
637     u_long diff, bestdiff;
638     c_linker_sym_t best;
639     c_linker_sym_t es;
640 
641     best = 0;
642     bestdiff = off;
643     TAILQ_FOREACH(lf, &linker_files, link) {
644 	if (LINKER_SEARCH_SYMBOL(lf, value, &es, &diff) != 0)
645 	    continue;
646 	if (es != 0 && diff < bestdiff) {
647 	    best = es;
648 	    bestdiff = diff;
649 	}
650 	if (bestdiff == 0)
651 	    break;
652     }
653     if (best) {
654 	*sym = best;
655 	*diffp = bestdiff;
656 	return 0;
657     } else {
658 	*sym = 0;
659 	*diffp = off;
660 	return ENOENT;
661     }
662 }
663 
664 int
665 linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
666 {
667     linker_file_t lf;
668 
669     TAILQ_FOREACH(lf, &linker_files, link) {
670 	if (LINKER_SYMBOL_VALUES(lf, sym, symval) == 0)
671 	    return 0;
672     }
673     return ENOENT;
674 }
675 
676 #endif
677 
678 /*
679  * Syscalls.
680  */
681 
682 int
683 kldload(struct proc* p, struct kldload_args* uap)
684 {
685     char* pathname, *realpath;
686     const char *filename;
687     linker_file_t lf;
688     int error = 0;
689 
690     p->p_retval[0] = -1;
691 
692     if (securelevel > 0)	/* redundant, but that's OK */
693 	return EPERM;
694 
695     if ((error = suser(p)) != 0)
696 	return error;
697 
698     realpath = NULL;
699     pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
700     if ((error = copyinstr(SCARG(uap, file), pathname, MAXPATHLEN, NULL)) != 0)
701 	goto out;
702 
703     realpath = linker_search_path(pathname);
704     if (realpath == NULL) {
705 	error = ENOENT;
706 	goto out;
707     }
708     /* Can't load more than one file with the same name */
709     filename = linker_basename(realpath);
710     if (linker_find_file_by_name(filename)) {
711 	error = EEXIST;
712 	goto out;
713     }
714 
715     if ((error = linker_load_file(realpath, &lf)) != 0)
716 	goto out;
717 
718     lf->userrefs++;
719     p->p_retval[0] = lf->id;
720 
721 out:
722     if (pathname)
723 	free(pathname, M_TEMP);
724     if (realpath)
725 	free(realpath, M_LINKER);
726     return error;
727 }
728 
729 int
730 kldunload(struct proc* p, struct kldunload_args* uap)
731 {
732     linker_file_t lf;
733     int error = 0;
734 
735     if (securelevel > 0)	/* redundant, but that's OK */
736 	return EPERM;
737 
738     if ((error = suser(p)) != 0)
739 	return error;
740 
741     lf = linker_find_file_by_id(SCARG(uap, fileid));
742     if (lf) {
743 	KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
744 	if (lf->userrefs == 0) {
745 	    printf("kldunload: attempt to unload file that was loaded by the kernel\n");
746 	    error = EBUSY;
747 	    goto out;
748 	}
749 	lf->userrefs--;
750 	error = linker_file_unload(lf);
751 	if (error)
752 	    lf->userrefs++;
753     } else
754 	error = ENOENT;
755 
756 out:
757     return error;
758 }
759 
760 int
761 kldfind(struct proc* p, struct kldfind_args* uap)
762 {
763     char* pathname;
764     const char *filename;
765     linker_file_t lf;
766     int error = 0;
767 
768     p->p_retval[0] = -1;
769 
770     pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
771     if ((error = copyinstr(SCARG(uap, file), pathname, MAXPATHLEN, NULL)) != 0)
772 	goto out;
773 
774     filename = linker_basename(pathname);
775 
776     lf = linker_find_file_by_name(filename);
777     if (lf)
778 	p->p_retval[0] = lf->id;
779     else
780 	error = ENOENT;
781 
782 out:
783     if (pathname)
784 	free(pathname, M_TEMP);
785     return error;
786 }
787 
788 int
789 kldnext(struct proc* p, struct kldnext_args* uap)
790 {
791     linker_file_t lf;
792     int error = 0;
793 
794     if (SCARG(uap, fileid) == 0) {
795 	if (TAILQ_FIRST(&linker_files))
796 	    p->p_retval[0] = TAILQ_FIRST(&linker_files)->id;
797 	else
798 	    p->p_retval[0] = 0;
799 	return 0;
800     }
801 
802     lf = linker_find_file_by_id(SCARG(uap, fileid));
803     if (lf) {
804 	if (TAILQ_NEXT(lf, link))
805 	    p->p_retval[0] = TAILQ_NEXT(lf, link)->id;
806 	else
807 	    p->p_retval[0] = 0;
808     } else
809 	error = ENOENT;
810 
811     return error;
812 }
813 
814 int
815 kldstat(struct proc* p, struct kldstat_args* uap)
816 {
817     linker_file_t lf;
818     int error = 0;
819     int version;
820     struct kld_file_stat* stat;
821     int namelen;
822 
823     lf = linker_find_file_by_id(SCARG(uap, fileid));
824     if (!lf) {
825 	error = ENOENT;
826 	goto out;
827     }
828 
829     stat = SCARG(uap, stat);
830 
831     /*
832      * Check the version of the user's structure.
833      */
834     if ((error = copyin(&stat->version, &version, sizeof(version))) != 0)
835 	goto out;
836     if (version != sizeof(struct kld_file_stat)) {
837 	error = EINVAL;
838 	goto out;
839     }
840 
841     namelen = strlen(lf->filename) + 1;
842     if (namelen > MAXPATHLEN)
843 	namelen = MAXPATHLEN;
844     if ((error = copyout(lf->filename, &stat->name[0], namelen)) != 0)
845 	goto out;
846     if ((error = copyout(&lf->refs, &stat->refs, sizeof(int))) != 0)
847 	goto out;
848     if ((error = copyout(&lf->id, &stat->id, sizeof(int))) != 0)
849 	goto out;
850     if ((error = copyout(&lf->address, &stat->address, sizeof(caddr_t))) != 0)
851 	goto out;
852     if ((error = copyout(&lf->size, &stat->size, sizeof(size_t))) != 0)
853 	goto out;
854 
855     p->p_retval[0] = 0;
856 
857 out:
858     return error;
859 }
860 
861 int
862 kldfirstmod(struct proc* p, struct kldfirstmod_args* uap)
863 {
864     linker_file_t lf;
865     int error = 0;
866 
867     lf = linker_find_file_by_id(SCARG(uap, fileid));
868     if (lf) {
869 	if (TAILQ_FIRST(&lf->modules))
870 	    p->p_retval[0] = module_getid(TAILQ_FIRST(&lf->modules));
871 	else
872 	    p->p_retval[0] = 0;
873     } else
874 	error = ENOENT;
875 
876     return error;
877 }
878 
879 int
880 kldsym(struct proc *p, struct kldsym_args *uap)
881 {
882     char *symstr = NULL;
883     c_linker_sym_t sym;
884     linker_symval_t symval;
885     linker_file_t lf;
886     struct kld_sym_lookup lookup;
887     int error = 0;
888 
889     if ((error = copyin(SCARG(uap, data), &lookup, sizeof(lookup))) != 0)
890 	goto out;
891     if (lookup.version != sizeof(lookup) || SCARG(uap, cmd) != KLDSYM_LOOKUP) {
892 	error = EINVAL;
893 	goto out;
894     }
895 
896     symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
897     if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
898 	goto out;
899 
900     if (SCARG(uap, fileid) != 0) {
901 	lf = linker_find_file_by_id(SCARG(uap, fileid));
902 	if (lf == NULL) {
903 	    error = ENOENT;
904 	    goto out;
905 	}
906 	if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
907 	    LINKER_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 	} else
912 	    error = ENOENT;
913     } else {
914 	TAILQ_FOREACH(lf, &linker_files, link) {
915 	    if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
916 		LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
917 		lookup.symvalue = (uintptr_t)symval.value;
918 		lookup.symsize = symval.size;
919 		error = copyout(&lookup, SCARG(uap, data), sizeof(lookup));
920 		break;
921 	    }
922 	}
923 	if (!lf)
924 	    error = ENOENT;
925     }
926 out:
927     if (symstr)
928 	free(symstr, M_TEMP);
929     return error;
930 }
931 
932 /*
933  * Preloaded module support
934  */
935 
936 static modlist_t
937 modlist_lookup(const char *name)
938 {
939     modlist_t mod;
940 
941     TAILQ_FOREACH(mod, &found_modules, link) {
942 	if (!strcmp(mod->name, name))
943 	    return mod;
944     }
945     return NULL;
946 }
947 
948 /*
949  * This routine is cheap and nasty but will work for data pointers.
950  */
951 static void *
952 linker_reloc_ptr(linker_file_t lf, void *offset)
953 {
954 	return lf->address + (uintptr_t)offset;
955 }
956 
957 static void
958 linker_preload(void* arg)
959 {
960     caddr_t		modptr;
961     char		*modname, *nmodname;
962     char		*modtype;
963     linker_file_t	lf;
964     linker_class_t	lc;
965     int			error, mcount;
966     struct linker_set	*sysinits;
967     linker_file_list_t	loaded_files;
968     linker_file_list_t	depended_files;
969     struct linker_set	*deps;
970     struct mod_metadata	*mp, *nmp;
971     int			i, j;
972     int			resolves;
973     modlist_t		mod;
974 
975     TAILQ_INIT(&loaded_files);
976     TAILQ_INIT(&depended_files);
977     TAILQ_INIT(&found_modules);
978     error = 0;
979 
980     modptr = NULL;
981     while ((modptr = preload_search_next_name(modptr)) != NULL) {
982 	modname = (char *)preload_search_info(modptr, MODINFO_NAME);
983 	modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
984 	if (modname == NULL) {
985 	    printf("Preloaded module at %p does not have a name!\n", modptr);
986 	    continue;
987 	}
988 	if (modtype == NULL) {
989 	    printf("Preloaded module at %p does not have a type!\n", modptr);
990 	    continue;
991 	}
992 	printf("Preloaded %s \"%s\" at %p.\n", modtype, modname, modptr);
993 	lf = NULL;
994 	TAILQ_FOREACH(lc, &classes, link) {
995 	    error = LINKER_LINK_PRELOAD(lc, modname, &lf);
996 	    if (error) {
997 		lf = NULL;
998 		break;
999 	    }
1000 	}
1001 	if (lf)
1002 	    TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1003     }
1004 
1005     /*
1006      * First get a list of stuff in the kernel.
1007      */
1008     deps = (struct linker_set*)
1009 	linker_file_lookup_symbol(linker_kernel_file, MDT_SETNAME, 0);
1010     if (deps) {
1011 	for (i = 0; i < deps->ls_length; i++) {
1012 	    mp = deps->ls_items[i];
1013 	    if (mp->md_type != MDT_VERSION)
1014 		continue;
1015 	    modname = mp->md_cval;
1016 	    if (modlist_lookup(modname) != NULL) {
1017 		printf("module %s already present!\n", modname);
1018 		/* XXX what can we do? this is a build error. :-( */
1019 		continue;
1020 	    }
1021 	    mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT|M_ZERO);
1022 	    if (mod == NULL)
1023 		panic("no memory for module list");
1024 	    mod->container = linker_kernel_file;
1025 	    mod->name = modname;
1026 	    TAILQ_INSERT_TAIL(&found_modules, mod, link);
1027 	}
1028     }
1029 
1030     /*
1031      * this is a once-off kinky bubble sort
1032      * resolve relocation dependency requirements
1033      */
1034 restart:
1035     TAILQ_FOREACH(lf, &loaded_files, loaded) {
1036 	deps = (struct linker_set*)
1037 	    linker_file_lookup_symbol(lf, MDT_SETNAME, 0);
1038 	/*
1039 	 * First, look to see if we would successfully link with this stuff.
1040 	 */
1041 	resolves = 1;	/* unless we know otherwise */
1042 	if (deps) {
1043 	    for (i = 0; i < deps->ls_length; i++) {
1044 		mp = linker_reloc_ptr(lf, deps->ls_items[i]);
1045 		if (mp->md_type != MDT_DEPEND)
1046 		    continue;
1047 		modname = linker_reloc_ptr(lf, mp->md_cval);
1048 		for (j = 0; j < deps->ls_length; j++) {
1049 		    nmp = linker_reloc_ptr(lf, deps->ls_items[j]);
1050 		    if (nmp->md_type != MDT_VERSION)
1051 			continue;
1052 		    nmodname = linker_reloc_ptr(lf, nmp->md_cval);
1053 		    if (strcmp(modname, nmodname) == 0)
1054 			break;
1055 		}
1056 		if (j < deps->ls_length)	/* it's a self reference */
1057 		    continue;
1058 		if (modlist_lookup(modname) == NULL) {
1059 		    /* ok, the module isn't here yet, we are not finished */
1060 		    resolves = 0;
1061 		}
1062 	    }
1063 	}
1064 	/*
1065 	 * OK, if we found our modules, we can link.  So, "provide" the
1066 	 * modules inside and add it to the end of the link order list.
1067 	 */
1068 	if (resolves) {
1069 	    if (deps) {
1070 		for (i = 0; i < deps->ls_length; i++) {
1071 		    mp = linker_reloc_ptr(lf, deps->ls_items[i]);
1072 		    if (mp->md_type != MDT_VERSION)
1073 			continue;
1074 		    modname = linker_reloc_ptr(lf, mp->md_cval);
1075 		    if (modlist_lookup(modname) != NULL) {
1076 			printf("module %s already present!\n", modname);
1077 			linker_file_unload(lf);
1078 			TAILQ_REMOVE(&loaded_files, lf, loaded);
1079 			goto restart;	/* we changed the tailq next ptr */
1080 		    }
1081 		    mod = malloc(sizeof(struct modlist), M_LINKER,
1082 			M_NOWAIT|M_ZERO);
1083 		    if (mod == NULL)
1084 			panic("no memory for module list");
1085 		    mod->container = lf;
1086 		    mod->name = modname;
1087 		    TAILQ_INSERT_TAIL(&found_modules, mod, link);
1088 		}
1089 	    }
1090 	    TAILQ_REMOVE(&loaded_files, lf, loaded);
1091 	    TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1092 	    /*
1093 	     * Since we provided modules, we need to restart the sort so
1094 	     * that the previous files that depend on us have a chance.
1095 	     * Also, we've busted the tailq next pointer with the REMOVE.
1096 	     */
1097 	    goto restart;
1098 	}
1099     }
1100 
1101     /*
1102      * At this point, we check to see what could not be resolved..
1103      */
1104     TAILQ_FOREACH(lf, &loaded_files, loaded) {
1105 	printf("KLD file %s is missing dependencies\n", lf->filename);
1106 	linker_file_unload(lf);
1107 	TAILQ_REMOVE(&loaded_files, lf, loaded);
1108     }
1109 
1110     /*
1111      * We made it. Finish off the linking in the order we determined.
1112      */
1113     TAILQ_FOREACH(lf, &depended_files, loaded) {
1114 	if (linker_kernel_file) {
1115 	    linker_kernel_file->refs++;
1116 	    error = linker_file_add_dependancy(lf, linker_kernel_file);
1117 	    if (error)
1118 		panic("cannot add dependency");
1119 	}
1120 	lf->userrefs++;		/* so we can (try to) kldunload it */
1121 	deps = (struct linker_set*)
1122 	    linker_file_lookup_symbol(lf, MDT_SETNAME, 0);
1123 	if (deps) {
1124 	    for (i = 0; i < deps->ls_length; i++) {
1125 		mp = linker_reloc_ptr(lf, deps->ls_items[i]);
1126 		if (mp->md_type != MDT_DEPEND)
1127 		    continue;
1128 		modname = linker_reloc_ptr(lf, mp->md_cval);
1129 		mod = modlist_lookup(modname);
1130 		mod->container->refs++;
1131 		error = linker_file_add_dependancy(lf, mod->container);
1132 		if (error)
1133 		    panic("cannot add dependency");
1134 	    }
1135 	}
1136 
1137 	/* Now do relocation etc using the symbol search paths established by the dependencies */
1138 	error = LINKER_LINK_PRELOAD_FINISH(lf);
1139 	if (error) {
1140 	    printf("KLD file %s - could not finalize loading\n", lf->filename);
1141 	    linker_file_unload(lf);
1142 	    continue;
1143 	}
1144 
1145 	mcount = linker_file_register_modules(lf);
1146 	sysinits = (struct linker_set*)
1147 	    linker_file_lookup_symbol(lf, "sysinit_set", 0);
1148 	if (sysinits)
1149 	    sysinit_add((struct sysinit **)sysinits->ls_items);
1150 	linker_file_register_sysctls(lf);
1151 	lf->flags |= LINKER_FILE_LINKED;
1152     }
1153     /* woohoo! we made it! */
1154 }
1155 
1156 SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, 0);
1157 
1158 /*
1159  * Search for a not-loaded module by name.
1160  *
1161  * Modules may be found in the following locations:
1162  *
1163  * - preloaded (result is just the module name)
1164  * - on disk (result is full path to module)
1165  *
1166  * If the module name is qualified in any way (contains path, etc.)
1167  * the we simply return a copy of it.
1168  *
1169  * The search path can be manipulated via sysctl.  Note that we use the ';'
1170  * character as a separator to be consistent with the bootloader.
1171  */
1172 
1173 static char def_linker_path[] = "/boot/modules/;/modules/;/boot/kernel/";
1174 static char linker_path[MAXPATHLEN] = "";
1175 
1176 SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RW, linker_path,
1177 	      sizeof(linker_path), "module load search path");
1178 
1179 TUNABLE_STR_DECL("module_path", def_linker_path, linker_path,
1180 		 sizeof(linker_path));
1181 
1182 static char *linker_ext_list[] = {
1183 	".ko",
1184 	"",
1185 	NULL
1186 };
1187 
1188 static char *
1189 linker_search_path(const char *name)
1190 {
1191     struct nameidata	nd;
1192     struct proc		*p = curproc;	/* XXX */
1193     char		*cp, *ep, *result, **cpp;
1194     int			error, extlen, len, flags;
1195     enum vtype		type;
1196 
1197     /* qualified at all? */
1198     if (index(name, '/'))
1199 	return(linker_strdup(name));
1200 
1201     extlen = 0;
1202     for (cpp = linker_ext_list; *cpp; cpp++) {
1203 	len = strlen(*cpp);
1204 	if (len > extlen)
1205 	    extlen = len;
1206     }
1207     extlen++;	/* trailing '\0' */
1208 
1209     /* traverse the linker path */
1210     cp = linker_path;
1211     len = strlen(name);
1212     for (;;) {
1213 
1214 	/* find the end of this component */
1215 	for (ep = cp; (*ep != 0) && (*ep != ';'); ep++)
1216 	    ;
1217 	result = malloc((len + (ep - cp) + extlen + 1), M_LINKER, M_WAITOK);
1218 	if (result == NULL)	/* actually ENOMEM */
1219 	    return(NULL);
1220 	for (cpp = linker_ext_list; *cpp; cpp++) {
1221 	    strncpy(result, cp, ep - cp);
1222 	    strcpy(result + (ep - cp), "/");
1223 	    strcat(result, name);
1224 	    strcat(result, *cpp);
1225 	    /*
1226 	     * Attempt to open the file, and return the path if we succeed
1227 	     * and it's a regular file.
1228 	     */
1229 	    NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, result, p);
1230 	    flags = FREAD;
1231 	    error = vn_open(&nd, &flags, 0);
1232 	    if (error == 0) {
1233 		NDFREE(&nd, NDF_ONLY_PNBUF);
1234 		type = nd.ni_vp->v_type;
1235 		VOP_UNLOCK(nd.ni_vp, 0, p);
1236 		vn_close(nd.ni_vp, FREAD, p->p_ucred, p);
1237 		if (type == VREG)
1238 		    return(result);
1239 	    }
1240 	}
1241 	free(result, M_LINKER);
1242 
1243 	if (*ep == 0)
1244 	    break;
1245 	cp = ep + 1;
1246     }
1247     return(NULL);
1248 }
1249 
1250 static const char *
1251 linker_basename(const char* path)
1252 {
1253     const char *filename;
1254 
1255     filename = rindex(path, '/');
1256     if (filename == NULL)
1257 	return path;
1258     if (filename[1])
1259 	filename++;
1260     return filename;
1261 }
1262 
1263 /*
1264  * Find a file which contains given module and load it,
1265  * if "parent" is not NULL, register a reference to it.
1266  */
1267 static int
1268 linker_load_module(const char *modname, struct linker_file *parent)
1269 {
1270     linker_file_t lfdep;
1271     const char *filename;
1272     char *pathname;
1273     int error;
1274 
1275     /*
1276      * There will be a system to look up or guess a file name from
1277      * a module name.
1278      * For now we just try to load a file with the same name.
1279      */
1280     pathname = linker_search_path(modname);
1281     if (pathname == NULL)
1282 	return ENOENT;
1283 
1284     /* Can't load more than one file with the same basename */
1285     filename = linker_basename(pathname);
1286     if (linker_find_file_by_name(filename)) {
1287 	error = EEXIST;
1288 	goto out;
1289     }
1290 
1291     do {
1292 	error = linker_load_file(pathname, &lfdep);
1293 	if (error)
1294 	    break;
1295 	if (parent) {
1296 	    error = linker_file_add_dependancy(parent, lfdep);
1297 	    if (error)
1298 		break;
1299 	}
1300     } while(0);
1301 out:
1302     if (pathname)
1303 	free(pathname, M_LINKER);
1304     return error;
1305 }
1306 
1307 /*
1308  * This routine is responsible for finding dependencies of userland
1309  * initiated kldload(2)'s of files.
1310  */
1311 int
1312 linker_load_dependancies(linker_file_t lf)
1313 {
1314     linker_file_t lfdep;
1315     struct linker_set *deps;
1316     struct mod_metadata *mp, *nmp;
1317     modlist_t mod;
1318     char *modname, *nmodname;
1319     int i, j, error = 0;
1320 
1321     /*
1322      * All files are dependant on /kernel.
1323      */
1324     if (linker_kernel_file) {
1325 	linker_kernel_file->refs++;
1326 	error = linker_file_add_dependancy(lf, linker_kernel_file);
1327 	if (error)
1328 	    return error;
1329     }
1330 
1331     deps = (struct linker_set*)
1332 	linker_file_lookup_symbol(lf, MDT_SETNAME, 0);
1333     if (deps != NULL) {
1334 	for (i = 0; i < deps->ls_length; i++) {
1335 	    mp = linker_reloc_ptr(lf, deps->ls_items[i]);
1336 	    if (mp->md_type != MDT_VERSION)
1337 		continue;
1338 	    modname = linker_reloc_ptr(lf, mp->md_cval);
1339 	    if (modlist_lookup(modname) != NULL) {
1340 		printf("module %s already present!\n", modname);
1341 		return EEXIST;
1342 	    }
1343 	}
1344     }
1345     if (deps != NULL) {
1346 	for (i = 0; i < deps->ls_length; i++) {
1347 	    mp = linker_reloc_ptr(lf, deps->ls_items[i]);
1348 	    if (mp->md_type != MDT_DEPEND)
1349 		continue;
1350 	    modname = linker_reloc_ptr(lf, mp->md_cval);
1351 	    nmodname = NULL;
1352 	    for (j = 0; j < deps->ls_length; j++) {
1353 		nmp = linker_reloc_ptr(lf, deps->ls_items[j]);
1354 		if (nmp->md_type != MDT_VERSION)
1355 		    continue;
1356 		nmodname = linker_reloc_ptr(lf, nmp->md_cval);
1357 		if (strcmp(modname, nmodname) == 0)
1358 		    break;
1359 	    }
1360 	    if (j < deps->ls_length)	/* early exit, it's a self reference */
1361 		continue;
1362 	    mod = modlist_lookup(modname);
1363 	    if (mod) {		/* woohoo, it's loaded already */
1364 		lfdep = mod->container;
1365 		lfdep->refs++;
1366 		error = linker_file_add_dependancy(lf, lfdep);
1367 		if (error)
1368 		    break;
1369 		continue;
1370 	    }
1371 	    error = linker_load_module(modname, lf);
1372 	    if (error) {
1373 		printf("KLD %s: depends on %s - not available\n",
1374 		       lf->filename, modname);
1375 		break;
1376 	    }
1377 	}
1378 
1379     }
1380     if (error == 0 && deps) {
1381 	for (i = 0; i < deps->ls_length; i++) {
1382 	    mp = linker_reloc_ptr(lf, deps->ls_items[i]);
1383 	    if (mp->md_type != MDT_VERSION)
1384 		continue;
1385 	    modname = linker_reloc_ptr(lf, mp->md_cval);
1386 	    mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT|M_ZERO);
1387 	    if (mod == NULL)
1388 		panic("no memory for module list");
1389 	    mod->container = lf;
1390 	    mod->name = modname;
1391 	    TAILQ_INSERT_TAIL(&found_modules, mod, link);
1392 	}
1393     }
1394     return error;
1395 }
1396