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