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