kern_linker.c revision 66630
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 66630 2000-10-04 17:40:24Z dfr $
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
51int kld_debug = 0;
52#endif
53
54static char *linker_search_path(const char *name);
55static const char *linker_basename(const char* path);
56
57MALLOC_DEFINE(M_LINKER, "linker", "kernel linker");
58
59linker_file_t linker_kernel_file;
60
61static struct lock lock;	/* lock for the file list */
62static linker_class_list_t classes;
63static linker_file_list_t linker_files;
64static int next_file_id = 1;
65
66/* XXX wrong name; we're looking at version provision tags here, not modules */
67typedef TAILQ_HEAD(, modlist) modlisthead_t;
68struct modlist {
69    TAILQ_ENTRY(modlist) link;		/* chain together all modules */
70    linker_file_t	container;
71    const char		*name;
72};
73typedef struct modlist	*modlist_t;
74static modlisthead_t	found_modules;
75
76static char *
77linker_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
86static void
87linker_init(void* arg)
88{
89    lockinit(&lock, PVM, "klink", 0, 0);
90    TAILQ_INIT(&classes);
91    TAILQ_INIT(&linker_files);
92}
93
94SYSINIT(linker, SI_SUB_KLD, SI_ORDER_FIRST, linker_init, 0);
95
96int
97linker_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
104static void
105linker_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
154static void
155linker_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
204static void
205linker_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
222static void
223linker_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
240extern struct linker_set modmetadata_set;
241
242static int
243linker_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
295static void
296linker_init_kernel_modules(void)
297{
298    linker_file_register_modules(linker_kernel_file);
299}
300
301SYSINIT(linker_kernel, SI_SUB_KLD, SI_ORDER_ANY, linker_init_kernel_modules, 0);
302
303int
304linker_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    for (lc = TAILQ_FIRST(&classes); lc; lc = TAILQ_NEXT(lc, 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
354out:
355    return error;
356}
357
358linker_file_t
359linker_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    for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, 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
378out:
379    if (koname)
380	free(koname, M_LINKER);
381    return lf;
382}
383
384linker_file_t
385linker_find_file_by_id(int fileid)
386{
387    linker_file_t lf = 0;
388
389    lockmgr(&lock, LK_SHARED, 0, curproc);
390    for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link))
391	if (lf->id == fileid)
392	    break;
393    lockmgr(&lock, LK_RELEASE, 0, curproc);
394
395    return lf;
396}
397
398linker_file_t
399linker_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
424out:
425    lockmgr(&lock, LK_RELEASE, 0, curproc);
426    return lf;
427}
428
429int
430linker_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
508out:
509    return error;
510}
511
512int
513linker_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);
519    if (newdeps == NULL)
520	return ENOMEM;
521    bzero(newdeps, (file->ndeps + 1) * sizeof(linker_file_t*));
522
523    if (file->deps) {
524	bcopy(file->deps, newdeps, file->ndeps * sizeof(linker_file_t*));
525	free(file->deps, M_LINKER);
526    }
527    file->deps = newdeps;
528    file->deps[file->ndeps] = dep;
529    file->ndeps++;
530
531    return 0;
532}
533
534caddr_t
535linker_file_lookup_symbol(linker_file_t file, const char* name, int deps)
536{
537    c_linker_sym_t sym;
538    linker_symval_t symval;
539    caddr_t address;
540    size_t common_size = 0;
541    int i;
542
543    KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%x, name=%s, deps=%d\n",
544		  file, name, deps));
545
546    if (LINKER_LOOKUP_SYMBOL(file, name, &sym) == 0) {
547	LINKER_SYMBOL_VALUES(file, sym, &symval);
548	if (symval.value == 0)
549	    /*
550	     * For commons, first look them up in the dependancies and
551	     * only allocate space if not found there.
552	     */
553	    common_size = symval.size;
554	else {
555	    KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol.value=%x\n", symval.value));
556	    return symval.value;
557	}
558    }
559
560    if (deps) {
561	for (i = 0; i < file->ndeps; i++) {
562	    address = linker_file_lookup_symbol(file->deps[i], name, 0);
563	    if (address) {
564		KLD_DPF(SYM, ("linker_file_lookup_symbol: deps value=%x\n", address));
565		return address;
566	    }
567	}
568    }
569
570    if (common_size > 0) {
571	/*
572	 * This is a common symbol which was not found in the
573	 * dependancies.  We maintain a simple common symbol table in
574	 * the file object.
575	 */
576	struct common_symbol* cp;
577
578	for (cp = STAILQ_FIRST(&file->common); cp;
579	     cp = STAILQ_NEXT(cp, link))
580	    if (!strcmp(cp->name, name)) {
581		KLD_DPF(SYM, ("linker_file_lookup_symbol: old common value=%x\n", cp->address));
582		return cp->address;
583	    }
584
585	/*
586	 * Round the symbol size up to align.
587	 */
588	common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
589	cp = malloc(sizeof(struct common_symbol)
590		    + common_size
591		    + strlen(name) + 1,
592		    M_LINKER, M_WAITOK);
593	if (!cp) {
594	    KLD_DPF(SYM, ("linker_file_lookup_symbol: nomem\n"));
595	    return 0;
596	}
597	bzero(cp, sizeof(struct common_symbol) + common_size + strlen(name)+ 1);
598
599	cp->address = (caddr_t) (cp + 1);
600	cp->name = cp->address + common_size;
601	strcpy(cp->name, name);
602	bzero(cp->address, common_size);
603	STAILQ_INSERT_TAIL(&file->common, cp, link);
604
605	KLD_DPF(SYM, ("linker_file_lookup_symbol: new common value=%x\n", cp->address));
606	return cp->address;
607    }
608
609    KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
610    return 0;
611}
612
613#ifdef DDB
614/*
615 * DDB Helpers.  DDB has to look across multiple files with their own
616 * symbol tables and string tables.
617 *
618 * Note that we do not obey list locking protocols here.  We really don't
619 * need DDB to hang because somebody's got the lock held.  We'll take the
620 * chance that the files list is inconsistant instead.
621 */
622
623int
624linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
625{
626    linker_file_t lf;
627
628    for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link)) {
629	if (LINKER_LOOKUP_SYMBOL(lf, symstr, sym) == 0)
630	    return 0;
631    }
632    return ENOENT;
633}
634
635int
636linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
637{
638    linker_file_t lf;
639    u_long off = (uintptr_t)value;
640    u_long diff, bestdiff;
641    c_linker_sym_t best;
642    c_linker_sym_t es;
643
644    best = 0;
645    bestdiff = off;
646    for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link)) {
647	if (LINKER_SEARCH_SYMBOL(lf, value, &es, &diff) != 0)
648	    continue;
649	if (es != 0 && diff < bestdiff) {
650	    best = es;
651	    bestdiff = diff;
652	}
653	if (bestdiff == 0)
654	    break;
655    }
656    if (best) {
657	*sym = best;
658	*diffp = bestdiff;
659	return 0;
660    } else {
661	*sym = 0;
662	*diffp = off;
663	return ENOENT;
664    }
665}
666
667int
668linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
669{
670    linker_file_t lf;
671
672    for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link)) {
673	if (LINKER_SYMBOL_VALUES(lf, sym, symval) == 0)
674	    return 0;
675    }
676    return ENOENT;
677}
678
679#endif
680
681/*
682 * Syscalls.
683 */
684
685int
686kldload(struct proc* p, struct kldload_args* uap)
687{
688    char* pathname, *realpath;
689    const char *filename;
690    linker_file_t lf;
691    int error = 0;
692
693    p->p_retval[0] = -1;
694
695    if (securelevel > 0)	/* redundant, but that's OK */
696	return EPERM;
697
698    if ((error = suser(p)) != 0)
699	return error;
700
701    realpath = NULL;
702    pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
703    if ((error = copyinstr(SCARG(uap, file), pathname, MAXPATHLEN, NULL)) != 0)
704	goto out;
705
706    realpath = linker_search_path(pathname);
707    if (realpath == NULL) {
708	error = ENOENT;
709	goto out;
710    }
711    /* Can't load more than one file with the same name */
712    filename = linker_basename(realpath);
713    if (linker_find_file_by_name(filename)) {
714	error = EEXIST;
715	goto out;
716    }
717
718    if ((error = linker_load_file(realpath, &lf)) != 0)
719	goto out;
720
721    lf->userrefs++;
722    p->p_retval[0] = lf->id;
723
724out:
725    if (pathname)
726	free(pathname, M_TEMP);
727    if (realpath)
728	free(realpath, M_LINKER);
729    return error;
730}
731
732int
733kldunload(struct proc* p, struct kldunload_args* uap)
734{
735    linker_file_t lf;
736    int error = 0;
737
738    if (securelevel > 0)	/* redundant, but that's OK */
739	return EPERM;
740
741    if ((error = suser(p)) != 0)
742	return error;
743
744    lf = linker_find_file_by_id(SCARG(uap, fileid));
745    if (lf) {
746	KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
747	if (lf->userrefs == 0) {
748	    printf("kldunload: attempt to unload file that was loaded by the kernel\n");
749	    error = EBUSY;
750	    goto out;
751	}
752	lf->userrefs--;
753	error = linker_file_unload(lf);
754	if (error)
755	    lf->userrefs++;
756    } else
757	error = ENOENT;
758
759out:
760    return error;
761}
762
763int
764kldfind(struct proc* p, struct kldfind_args* uap)
765{
766    char* pathname;
767    const char *filename;
768    linker_file_t lf;
769    int error = 0;
770
771    p->p_retval[0] = -1;
772
773    pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
774    if ((error = copyinstr(SCARG(uap, file), pathname, MAXPATHLEN, NULL)) != 0)
775	goto out;
776
777    filename = linker_basename(pathname);
778
779    lf = linker_find_file_by_name(filename);
780    if (lf)
781	p->p_retval[0] = lf->id;
782    else
783	error = ENOENT;
784
785out:
786    if (pathname)
787	free(pathname, M_TEMP);
788    return error;
789}
790
791int
792kldnext(struct proc* p, struct kldnext_args* uap)
793{
794    linker_file_t lf;
795    int error = 0;
796
797    if (SCARG(uap, fileid) == 0) {
798	if (TAILQ_FIRST(&linker_files))
799	    p->p_retval[0] = TAILQ_FIRST(&linker_files)->id;
800	else
801	    p->p_retval[0] = 0;
802	return 0;
803    }
804
805    lf = linker_find_file_by_id(SCARG(uap, fileid));
806    if (lf) {
807	if (TAILQ_NEXT(lf, link))
808	    p->p_retval[0] = TAILQ_NEXT(lf, link)->id;
809	else
810	    p->p_retval[0] = 0;
811    } else
812	error = ENOENT;
813
814    return error;
815}
816
817int
818kldstat(struct proc* p, struct kldstat_args* uap)
819{
820    linker_file_t lf;
821    int error = 0;
822    int version;
823    struct kld_file_stat* stat;
824    int namelen;
825
826    lf = linker_find_file_by_id(SCARG(uap, fileid));
827    if (!lf) {
828	error = ENOENT;
829	goto out;
830    }
831
832    stat = SCARG(uap, stat);
833
834    /*
835     * Check the version of the user's structure.
836     */
837    if ((error = copyin(&stat->version, &version, sizeof(version))) != 0)
838	goto out;
839    if (version != sizeof(struct kld_file_stat)) {
840	error = EINVAL;
841	goto out;
842    }
843
844    namelen = strlen(lf->filename) + 1;
845    if (namelen > MAXPATHLEN)
846	namelen = MAXPATHLEN;
847    if ((error = copyout(lf->filename, &stat->name[0], namelen)) != 0)
848	goto out;
849    if ((error = copyout(&lf->refs, &stat->refs, sizeof(int))) != 0)
850	goto out;
851    if ((error = copyout(&lf->id, &stat->id, sizeof(int))) != 0)
852	goto out;
853    if ((error = copyout(&lf->address, &stat->address, sizeof(caddr_t))) != 0)
854	goto out;
855    if ((error = copyout(&lf->size, &stat->size, sizeof(size_t))) != 0)
856	goto out;
857
858    p->p_retval[0] = 0;
859
860out:
861    return error;
862}
863
864int
865kldfirstmod(struct proc* p, struct kldfirstmod_args* uap)
866{
867    linker_file_t lf;
868    int error = 0;
869
870    lf = linker_find_file_by_id(SCARG(uap, fileid));
871    if (lf) {
872	if (TAILQ_FIRST(&lf->modules))
873	    p->p_retval[0] = module_getid(TAILQ_FIRST(&lf->modules));
874	else
875	    p->p_retval[0] = 0;
876    } else
877	error = ENOENT;
878
879    return error;
880}
881
882int
883kldsym(struct proc *p, struct kldsym_args *uap)
884{
885    char *symstr = NULL;
886    c_linker_sym_t sym;
887    linker_symval_t symval;
888    linker_file_t lf;
889    struct kld_sym_lookup lookup;
890    int error = 0;
891
892    if ((error = copyin(SCARG(uap, data), &lookup, sizeof(lookup))) != 0)
893	goto out;
894    if (lookup.version != sizeof(lookup) || SCARG(uap, cmd) != KLDSYM_LOOKUP) {
895	error = EINVAL;
896	goto out;
897    }
898
899    symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
900    if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
901	goto out;
902
903    if (SCARG(uap, fileid) != 0) {
904	lf = linker_find_file_by_id(SCARG(uap, fileid));
905	if (lf == NULL) {
906	    error = ENOENT;
907	    goto out;
908	}
909	if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
910	    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
911	    lookup.symvalue = (uintptr_t)symval.value;
912	    lookup.symsize = symval.size;
913	    error = copyout(&lookup, SCARG(uap, data), sizeof(lookup));
914	} else
915	    error = ENOENT;
916    } else {
917	for (lf = TAILQ_FIRST(&linker_files); lf; lf = TAILQ_NEXT(lf, link)) {
918	    if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
919		LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
920		lookup.symvalue = (uintptr_t)symval.value;
921		lookup.symsize = symval.size;
922		error = copyout(&lookup, SCARG(uap, data), sizeof(lookup));
923		break;
924	    }
925	}
926	if (!lf)
927	    error = ENOENT;
928    }
929out:
930    if (symstr)
931	free(symstr, M_TEMP);
932    return error;
933}
934
935/*
936 * Preloaded module support
937 */
938
939static modlist_t
940modlist_lookup(const char *name)
941{
942    modlist_t mod;
943
944    for (mod = TAILQ_FIRST(&found_modules); mod; mod = TAILQ_NEXT(mod, link)) {
945	if (!strcmp(mod->name, name))
946	    return mod;
947    }
948    return NULL;
949}
950
951/*
952 * This routine is cheap and nasty but will work for data pointers.
953 */
954static void *
955linker_reloc_ptr(linker_file_t lf, void *offset)
956{
957	return lf->address + (uintptr_t)offset;
958}
959
960static void
961linker_preload(void* arg)
962{
963    caddr_t		modptr;
964    char		*modname, *nmodname;
965    char		*modtype;
966    linker_file_t	lf;
967    linker_class_t	lc;
968    int			error, mcount;
969    struct linker_set	*sysinits;
970    linker_file_list_t	loaded_files;
971    linker_file_list_t	depended_files;
972    struct linker_set	*deps;
973    struct mod_metadata	*mp, *nmp;
974    int			i, j;
975    int			resolves;
976    modlist_t		mod;
977
978    TAILQ_INIT(&loaded_files);
979    TAILQ_INIT(&depended_files);
980    TAILQ_INIT(&found_modules);
981    error = 0;
982
983    modptr = NULL;
984    while ((modptr = preload_search_next_name(modptr)) != NULL) {
985	modname = (char *)preload_search_info(modptr, MODINFO_NAME);
986	modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
987	if (modname == NULL) {
988	    printf("Preloaded module at %p does not have a name!\n", modptr);
989	    continue;
990	}
991	if (modtype == NULL) {
992	    printf("Preloaded module at %p does not have a type!\n", modptr);
993	    continue;
994	}
995	printf("Preloaded %s \"%s\" at %p.\n", modtype, modname, modptr);
996	lf = NULL;
997	for (lc = TAILQ_FIRST(&classes); lc; lc = TAILQ_NEXT(lc, link)) {
998	    error = LINKER_LINK_PRELOAD(lc, modname, &lf);
999	    if (error) {
1000		lf = NULL;
1001		break;
1002	    }
1003	}
1004	if (lf)
1005	    TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1006    }
1007
1008    /*
1009     * First get a list of stuff in the kernel.
1010     */
1011    deps = (struct linker_set*)
1012	linker_file_lookup_symbol(linker_kernel_file, MDT_SETNAME, 0);
1013    if (deps) {
1014	for (i = 0; i < deps->ls_length; i++) {
1015	    mp = deps->ls_items[i];
1016	    if (mp->md_type != MDT_VERSION)
1017		continue;
1018	    modname = mp->md_cval;
1019	    if (modlist_lookup(modname) != NULL) {
1020		printf("module %s already present!\n", modname);
1021		/* XXX what can we do? this is a build error. :-( */
1022		continue;
1023	    }
1024	    mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT);
1025	    if (mod == NULL)
1026		panic("no memory for module list");
1027	    bzero(mod, sizeof(*mod));
1028	    mod->container = linker_kernel_file;
1029	    mod->name = modname;
1030	    TAILQ_INSERT_TAIL(&found_modules, mod, link);
1031	}
1032    }
1033
1034    /*
1035     * this is a once-off kinky bubble sort
1036     * resolve relocation dependency requirements
1037     */
1038restart:
1039    for (lf = TAILQ_FIRST(&loaded_files); lf; lf = TAILQ_NEXT(lf, loaded)) {
1040	deps = (struct linker_set*)
1041	    linker_file_lookup_symbol(lf, MDT_SETNAME, 0);
1042	/*
1043	 * First, look to see if we would successfully link with this stuff.
1044	 */
1045	resolves = 1;	/* unless we know otherwise */
1046	if (deps) {
1047	    for (i = 0; i < deps->ls_length; i++) {
1048		mp = linker_reloc_ptr(lf, deps->ls_items[i]);
1049		if (mp->md_type != MDT_DEPEND)
1050		    continue;
1051		modname = linker_reloc_ptr(lf, mp->md_cval);
1052		for (j = 0; j < deps->ls_length; j++) {
1053		    nmp = linker_reloc_ptr(lf, deps->ls_items[j]);
1054		    if (nmp->md_type != MDT_VERSION)
1055			continue;
1056		    nmodname = linker_reloc_ptr(lf, nmp->md_cval);
1057		    if (strcmp(modname, nmodname) == 0)
1058			break;
1059		}
1060		if (j < deps->ls_length)	/* it's a self reference */
1061		    continue;
1062		if (modlist_lookup(modname) == NULL) {
1063		    /* ok, the module isn't here yet, we are not finished */
1064		    resolves = 0;
1065		}
1066	    }
1067	}
1068	/*
1069	 * OK, if we found our modules, we can link.  So, "provide" the
1070	 * modules inside and add it to the end of the link order list.
1071	 */
1072	if (resolves) {
1073	    if (deps) {
1074		for (i = 0; i < deps->ls_length; i++) {
1075		    mp = linker_reloc_ptr(lf, deps->ls_items[i]);
1076		    if (mp->md_type != MDT_VERSION)
1077			continue;
1078		    modname = linker_reloc_ptr(lf, mp->md_cval);
1079		    if (modlist_lookup(modname) != NULL) {
1080			printf("module %s already present!\n", modname);
1081			linker_file_unload(lf);
1082			TAILQ_REMOVE(&loaded_files, lf, loaded);
1083			goto restart;	/* we changed the tailq next ptr */
1084		    }
1085		    mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT);
1086		    if (mod == NULL)
1087			panic("no memory for module list");
1088		    bzero(mod, sizeof(*mod));
1089		    mod->container = lf;
1090		    mod->name = modname;
1091		    TAILQ_INSERT_TAIL(&found_modules, mod, link);
1092		}
1093	    }
1094	    TAILQ_REMOVE(&loaded_files, lf, loaded);
1095	    TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1096	    /*
1097	     * Since we provided modules, we need to restart the sort so
1098	     * that the previous files that depend on us have a chance.
1099	     * Also, we've busted the tailq next pointer with the REMOVE.
1100	     */
1101	    goto restart;
1102	}
1103    }
1104
1105    /*
1106     * At this point, we check to see what could not be resolved..
1107     */
1108    for (lf = TAILQ_FIRST(&loaded_files); lf; lf = TAILQ_NEXT(lf, loaded)) {
1109	printf("KLD file %s is missing dependencies\n", lf->filename);
1110	linker_file_unload(lf);
1111	TAILQ_REMOVE(&loaded_files, lf, loaded);
1112    }
1113
1114    /*
1115     * We made it. Finish off the linking in the order we determined.
1116     */
1117    for (lf = TAILQ_FIRST(&depended_files); lf; lf = TAILQ_NEXT(lf, loaded)) {
1118	if (linker_kernel_file) {
1119	    linker_kernel_file->refs++;
1120	    error = linker_file_add_dependancy(lf, linker_kernel_file);
1121	    if (error)
1122		panic("cannot add dependency");
1123	}
1124	lf->userrefs++;		/* so we can (try to) kldunload it */
1125	deps = (struct linker_set*)
1126	    linker_file_lookup_symbol(lf, MDT_SETNAME, 0);
1127	if (deps) {
1128	    for (i = 0; i < deps->ls_length; i++) {
1129		mp = linker_reloc_ptr(lf, deps->ls_items[i]);
1130		if (mp->md_type != MDT_DEPEND)
1131		    continue;
1132		modname = linker_reloc_ptr(lf, mp->md_cval);
1133		mod = modlist_lookup(modname);
1134		mod->container->refs++;
1135		error = linker_file_add_dependancy(lf, mod->container);
1136		if (error)
1137		    panic("cannot add dependency");
1138	    }
1139	}
1140
1141	/* Now do relocation etc using the symbol search paths established by the dependencies */
1142	error = LINKER_LINK_PRELOAD_FINISH(lf);
1143	if (error) {
1144	    printf("KLD file %s - could not finalize loading\n", lf->filename);
1145	    linker_file_unload(lf);
1146	    continue;
1147	}
1148
1149	mcount = linker_file_register_modules(lf);
1150	sysinits = (struct linker_set*)
1151	    linker_file_lookup_symbol(lf, "sysinit_set", 0);
1152	if (sysinits)
1153	    sysinit_add((struct sysinit **)sysinits->ls_items);
1154	linker_file_register_sysctls(lf);
1155	lf->flags |= LINKER_FILE_LINKED;
1156    }
1157    /* woohoo! we made it! */
1158}
1159
1160SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, 0);
1161
1162/*
1163 * Search for a not-loaded module by name.
1164 *
1165 * Modules may be found in the following locations:
1166 *
1167 * - preloaded (result is just the module name)
1168 * - on disk (result is full path to module)
1169 *
1170 * If the module name is qualified in any way (contains path, etc.)
1171 * the we simply return a copy of it.
1172 *
1173 * The search path can be manipulated via sysctl.  Note that we use the ';'
1174 * character as a separator to be consistent with the bootloader.
1175 */
1176
1177static char linker_path[MAXPATHLEN] = "/boot/modules/;/modules/;/boot/kernel/";
1178
1179SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RW, linker_path,
1180	      sizeof(linker_path), "module load search path");
1181
1182static char *linker_ext_list[] = {
1183	".ko",
1184	"",
1185	NULL
1186};
1187
1188static char *
1189linker_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), 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), name);
1223	    strcat(result, *cpp);
1224
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
1250static const char *
1251linker_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 */
1267static int
1268linker_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);
1301out:
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 */
1311int
1312linker_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);
1387	    if (mod == NULL)
1388		panic("no memory for module list");
1389	    bzero(mod, sizeof(*mod));
1390	    mod->container = lf;
1391	    mod->name = modname;
1392	    TAILQ_INSERT_TAIL(&found_modules, mod, link);
1393	}
1394    }
1395    return error;
1396}
1397