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