Home | History | Annotate | Line # | Download | only in kern
subr_kobj.c revision 1.50.4.2
      1 /*	$NetBSD: subr_kobj.c,v 1.50.4.2 2016/07/09 20:25:20 skrll Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2008 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software developed for The NetBSD Foundation
      8  * by Andrew Doran.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*-
     33  * Copyright (c) 1998-2000 Doug Rabson
     34  * Copyright (c) 2004 Peter Wemm
     35  * All rights reserved.
     36  *
     37  * Redistribution and use in source and binary forms, with or without
     38  * modification, are permitted provided that the following conditions
     39  * are met:
     40  * 1. Redistributions of source code must retain the above copyright
     41  *    notice, this list of conditions and the following disclaimer.
     42  * 2. Redistributions in binary form must reproduce the above copyright
     43  *    notice, this list of conditions and the following disclaimer in the
     44  *    documentation and/or other materials provided with the distribution.
     45  *
     46  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
     47  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     48  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     49  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     50  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     51  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     52  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     53  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     54  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     55  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     56  * SUCH DAMAGE.
     57  */
     58 
     59 /*
     60  * Kernel loader for ELF objects.
     61  *
     62  * TODO: adjust kmem_alloc() calls to avoid needless fragmentation.
     63  */
     64 
     65 #include <sys/cdefs.h>
     66 __KERNEL_RCSID(0, "$NetBSD: subr_kobj.c,v 1.50.4.2 2016/07/09 20:25:20 skrll Exp $");
     67 
     68 #ifdef _KERNEL_OPT
     69 #include "opt_modular.h"
     70 #endif
     71 
     72 #include <sys/kobj_impl.h>
     73 
     74 #ifdef MODULAR
     75 
     76 #include <sys/param.h>
     77 #include <sys/kernel.h>
     78 #include <sys/kmem.h>
     79 #include <sys/proc.h>
     80 #include <sys/ksyms.h>
     81 #include <sys/module.h>
     82 
     83 #include <uvm/uvm_extern.h>
     84 
     85 #define kobj_error(_kobj, ...) \
     86 	kobj_out(__func__, __LINE__, _kobj, __VA_ARGS__)
     87 
     88 static int	kobj_relocate(kobj_t, bool);
     89 static int	kobj_checksyms(kobj_t, bool);
     90 static void	kobj_out(const char *, int, kobj_t, const char *, ...)
     91     __printflike(4, 5);
     92 static void	kobj_jettison(kobj_t);
     93 static void	kobj_free(kobj_t, void *, size_t);
     94 static void	kobj_close(kobj_t);
     95 static int	kobj_read_mem(kobj_t, void **, size_t, off_t, bool);
     96 static void	kobj_close_mem(kobj_t);
     97 
     98 extern struct vm_map *module_map;
     99 
    100 /*
    101  * kobj_load_mem:
    102  *
    103  *	Load an object already resident in memory.  If size is not -1,
    104  *	the complete size of the object is known.
    105  */
    106 int
    107 kobj_load_mem(kobj_t *kop, const char *name, void *base, ssize_t size)
    108 {
    109 	kobj_t ko;
    110 
    111 	ko = kmem_zalloc(sizeof(*ko), KM_SLEEP);
    112 	if (ko == NULL) {
    113 		return ENOMEM;
    114 	}
    115 
    116 	ko->ko_type = KT_MEMORY;
    117 	kobj_setname(ko, name);
    118 	ko->ko_source = base;
    119 	ko->ko_memsize = size;
    120 	ko->ko_read = kobj_read_mem;
    121 	ko->ko_close = kobj_close_mem;
    122 
    123 	*kop = ko;
    124 	return kobj_load(ko);
    125 }
    126 
    127 /*
    128  * kobj_close:
    129  *
    130  *	Close an open ELF object.
    131  */
    132 static void
    133 kobj_close(kobj_t ko)
    134 {
    135 
    136 	if (ko->ko_source == NULL) {
    137 		return;
    138 	}
    139 
    140 	ko->ko_close(ko);
    141 	ko->ko_source = NULL;
    142 }
    143 
    144 static void
    145 kobj_close_mem(kobj_t ko)
    146 {
    147 
    148 	return;
    149 }
    150 
    151 /*
    152  * kobj_load:
    153  *
    154  *	Load an ELF object and prepare to link into the running kernel
    155  *	image.
    156  */
    157 int
    158 kobj_load(kobj_t ko)
    159 {
    160 	Elf_Ehdr *hdr;
    161 	Elf_Shdr *shdr;
    162 	Elf_Sym *es;
    163 	vaddr_t map_text_base;
    164 	vaddr_t map_data_base;
    165 	size_t map_text_size;
    166 	size_t map_data_size;
    167 	int error;
    168 	int symtabindex;
    169 	int symstrindex;
    170 	int nsym;
    171 	int pb, rl, ra;
    172 	int alignmask;
    173 	int i, j;
    174 	void *addr;
    175 
    176 	KASSERT(ko->ko_type != KT_UNSET);
    177 	KASSERT(ko->ko_source != NULL);
    178 
    179 	shdr = NULL;
    180 	error = 0;
    181 	hdr = NULL;
    182 
    183 	/*
    184 	 * Read the elf header from the file.
    185 	 */
    186 	error = ko->ko_read(ko, (void **)&hdr, sizeof(*hdr), 0, true);
    187 	if (error != 0) {
    188 		kobj_error(ko, "read failed %d", error);
    189 		goto out;
    190 	}
    191 	if (memcmp(hdr->e_ident, ELFMAG, SELFMAG) != 0) {
    192 		kobj_error(ko, "not an ELF object");
    193 		error = ENOEXEC;
    194 		goto out;
    195 	}
    196 
    197 	if (hdr->e_ident[EI_VERSION] != EV_CURRENT ||
    198 	    hdr->e_version != EV_CURRENT) {
    199 		kobj_error(ko, "unsupported file version %d",
    200 		    hdr->e_ident[EI_VERSION]);
    201 		error = ENOEXEC;
    202 		goto out;
    203 	}
    204 	if (hdr->e_type != ET_REL) {
    205 		kobj_error(ko, "unsupported file type %d", hdr->e_type);
    206 		error = ENOEXEC;
    207 		goto out;
    208 	}
    209 	switch (hdr->e_machine) {
    210 #if ELFSIZE == 32
    211 	ELF32_MACHDEP_ID_CASES
    212 #elif ELFSIZE == 64
    213 	ELF64_MACHDEP_ID_CASES
    214 #else
    215 #error not defined
    216 #endif
    217 	default:
    218 		kobj_error(ko, "unsupported machine %d", hdr->e_machine);
    219 		error = ENOEXEC;
    220 		goto out;
    221 	}
    222 
    223 	ko->ko_nprogtab = 0;
    224 	ko->ko_shdr = 0;
    225 	ko->ko_nrel = 0;
    226 	ko->ko_nrela = 0;
    227 
    228 	/*
    229 	 * Allocate and read in the section header.
    230 	 */
    231 	if (hdr->e_shnum == 0 || hdr->e_shnum > ELF_MAXSHNUM ||
    232 	    hdr->e_shoff == 0 || hdr->e_shentsize != sizeof(Elf_Shdr)) {
    233 		kobj_error(ko, "bad sizes");
    234 		error = ENOEXEC;
    235 		goto out;
    236 	}
    237 	ko->ko_shdrsz = hdr->e_shnum * sizeof(Elf_Shdr);
    238 	error = ko->ko_read(ko, (void **)&shdr, ko->ko_shdrsz, hdr->e_shoff,
    239 	    true);
    240 	if (error != 0) {
    241 		kobj_error(ko, "read failed %d", error);
    242 		goto out;
    243 	}
    244 	ko->ko_shdr = shdr;
    245 
    246 	/*
    247 	 * Scan the section header for information and table sizing.
    248 	 */
    249 	nsym = 0;
    250 	symtabindex = symstrindex = -1;
    251 	for (i = 0; i < hdr->e_shnum; i++) {
    252 		switch (shdr[i].sh_type) {
    253 		case SHT_PROGBITS:
    254 		case SHT_NOBITS:
    255 			ko->ko_nprogtab++;
    256 			break;
    257 		case SHT_SYMTAB:
    258 			nsym++;
    259 			symtabindex = i;
    260 			symstrindex = shdr[i].sh_link;
    261 			break;
    262 		case SHT_REL:
    263 			if (shdr[shdr[i].sh_info].sh_type != SHT_PROGBITS)
    264 				continue;
    265 			ko->ko_nrel++;
    266 			break;
    267 		case SHT_RELA:
    268 			if (shdr[shdr[i].sh_info].sh_type != SHT_PROGBITS)
    269 				continue;
    270 			ko->ko_nrela++;
    271 			break;
    272 		case SHT_STRTAB:
    273 			break;
    274 		}
    275 	}
    276 	if (ko->ko_nprogtab == 0) {
    277 		kobj_error(ko, "file has no contents");
    278 		error = ENOEXEC;
    279 		goto out;
    280 	}
    281 	if (nsym != 1) {
    282 		/* Only allow one symbol table for now */
    283 		kobj_error(ko, "file has no valid symbol table");
    284 		error = ENOEXEC;
    285 		goto out;
    286 	}
    287 	KASSERT(symtabindex != -1);
    288 	KASSERT(symstrindex != -1);
    289 
    290 	if (symstrindex == SHN_UNDEF || symstrindex >= hdr->e_shnum ||
    291 	    shdr[symstrindex].sh_type != SHT_STRTAB) {
    292 		kobj_error(ko, "file has invalid symbol strings");
    293 		error = ENOEXEC;
    294 		goto out;
    295 	}
    296 
    297 	/*
    298 	 * Allocate space for tracking the load chunks.
    299 	 */
    300 	if (ko->ko_nprogtab != 0) {
    301 		ko->ko_progtab = kmem_zalloc(ko->ko_nprogtab *
    302 		    sizeof(*ko->ko_progtab), KM_SLEEP);
    303 		if (ko->ko_progtab == NULL) {
    304 			error = ENOMEM;
    305 			kobj_error(ko, "out of memory");
    306 			goto out;
    307 		}
    308 	}
    309 	if (ko->ko_nrel != 0) {
    310 		ko->ko_reltab = kmem_zalloc(ko->ko_nrel *
    311 		    sizeof(*ko->ko_reltab), KM_SLEEP);
    312 		if (ko->ko_reltab == NULL) {
    313 			error = ENOMEM;
    314 			kobj_error(ko, "out of memory");
    315 			goto out;
    316 		}
    317 	}
    318 	if (ko->ko_nrela != 0) {
    319 		ko->ko_relatab = kmem_zalloc(ko->ko_nrela *
    320 		    sizeof(*ko->ko_relatab), KM_SLEEP);
    321 		if (ko->ko_relatab == NULL) {
    322 			error = ENOMEM;
    323 			kobj_error(ko, "out of memory");
    324 			goto out;
    325 		}
    326 	}
    327 
    328 	/*
    329 	 * Allocate space for and load the symbol table.
    330 	 */
    331 	ko->ko_symcnt = shdr[symtabindex].sh_size / sizeof(Elf_Sym);
    332 	if (ko->ko_symcnt == 0) {
    333 		kobj_error(ko, "no symbol table");
    334 		error = ENOEXEC;
    335 		goto out;
    336 	}
    337 	error = ko->ko_read(ko, (void **)&ko->ko_symtab,
    338 	    ko->ko_symcnt * sizeof(Elf_Sym),
    339 	    shdr[symtabindex].sh_offset, true);
    340 	if (error != 0) {
    341 		kobj_error(ko, "read failed %d", error);
    342 		goto out;
    343 	}
    344 
    345 	/*
    346 	 * Allocate space for and load the symbol strings.
    347 	 */
    348 	ko->ko_strtabsz = shdr[symstrindex].sh_size;
    349 	if (ko->ko_strtabsz == 0) {
    350 		kobj_error(ko, "no symbol strings");
    351 		error = ENOEXEC;
    352 		goto out;
    353 	}
    354 	error = ko->ko_read(ko, (void *)&ko->ko_strtab, ko->ko_strtabsz,
    355 	    shdr[symstrindex].sh_offset, true);
    356 	if (error != 0) {
    357 		kobj_error(ko, "read failed %d", error);
    358 		goto out;
    359 	}
    360 
    361 	/*
    362 	 * Adjust module symbol namespace, if necessary (e.g. with rump)
    363 	 */
    364 	error = kobj_renamespace(ko->ko_symtab, ko->ko_symcnt,
    365 	    &ko->ko_strtab, &ko->ko_strtabsz);
    366 	if (error != 0) {
    367 		kobj_error(ko, "renamespace failed %d", error);
    368 		goto out;
    369 	}
    370 
    371 	/*
    372 	 * Do we have a string table for the section names?
    373 	 */
    374 	if (hdr->e_shstrndx != SHN_UNDEF) {
    375 		if (hdr->e_shstrndx >= hdr->e_shnum) {
    376 			kobj_error(ko, "bad shstrndx");
    377 			error = ENOEXEC;
    378 			goto out;
    379 		}
    380 		if (shdr[hdr->e_shstrndx].sh_size != 0 &&
    381 		    shdr[hdr->e_shstrndx].sh_type == SHT_STRTAB) {
    382 			ko->ko_shstrtabsz = shdr[hdr->e_shstrndx].sh_size;
    383 			error = ko->ko_read(ko, (void **)&ko->ko_shstrtab,
    384 			    shdr[hdr->e_shstrndx].sh_size,
    385 			    shdr[hdr->e_shstrndx].sh_offset, true);
    386 			if (error != 0) {
    387 				kobj_error(ko, "read failed %d", error);
    388 				goto out;
    389 			}
    390 		}
    391 	}
    392 
    393 	/*
    394 	 * Size up code/data(progbits) and bss(nobits).
    395 	 */
    396 	alignmask = 0;
    397 	map_text_size = 0;
    398 	map_data_size = 0;
    399 	for (i = 0; i < hdr->e_shnum; i++) {
    400 		if (shdr[i].sh_type != SHT_PROGBITS &&
    401 		    shdr[i].sh_type != SHT_NOBITS)
    402 			continue;
    403 		alignmask = shdr[i].sh_addralign - 1;
    404 		if ((shdr[i].sh_flags & SHF_EXECINSTR)) {
    405 			map_text_size += alignmask;
    406 			map_text_size &= ~alignmask;
    407 			map_text_size += shdr[i].sh_size;
    408 		} else {
    409 			map_data_size += alignmask;
    410 			map_data_size &= ~alignmask;
    411 			map_data_size += shdr[i].sh_size;
    412 		}
    413 	}
    414 
    415 	if (map_text_size == 0) {
    416 		kobj_error(ko, "no text");
    417 		error = ENOEXEC;
    418  		goto out;
    419  	}
    420 	if (map_data_size == 0) {
    421 		kobj_error(ko, "no data/bss");
    422 		error = ENOEXEC;
    423  		goto out;
    424  	}
    425 
    426 	map_text_base = uvm_km_alloc(module_map, round_page(map_text_size),
    427 	    0, UVM_KMF_WIRED | UVM_KMF_EXEC);
    428 	if (map_text_base == 0) {
    429 		kobj_error(ko, "out of memory");
    430 		error = ENOMEM;
    431 		goto out;
    432 	}
    433 	ko->ko_text_address = map_text_base;
    434 	ko->ko_text_size = map_text_size;
    435 
    436 	map_data_base = uvm_km_alloc(module_map, round_page(map_data_size),
    437 	    0, UVM_KMF_WIRED);
    438 	if (map_data_base == 0) {
    439 		kobj_error(ko, "out of memory");
    440 		error = ENOMEM;
    441 		goto out;
    442 	}
    443 	ko->ko_data_address = map_data_base;
    444 	ko->ko_data_size = map_data_size;
    445 
    446 	/*
    447 	 * Now load code/data(progbits), zero bss(nobits), allocate space
    448 	 * for and load relocs
    449 	 */
    450 	pb = 0;
    451 	rl = 0;
    452 	ra = 0;
    453 	alignmask = 0;
    454 	for (i = 0; i < hdr->e_shnum; i++) {
    455 		switch (shdr[i].sh_type) {
    456 		case SHT_PROGBITS:
    457 		case SHT_NOBITS:
    458 			alignmask = shdr[i].sh_addralign - 1;
    459 			if ((shdr[i].sh_flags & SHF_EXECINSTR)) {
    460 				map_text_base += alignmask;
    461 				map_text_base &= ~alignmask;
    462 				addr = (void *)map_text_base;
    463 				map_text_base += shdr[i].sh_size;
    464  			} else {
    465 				map_data_base += alignmask;
    466 				map_data_base &= ~alignmask;
    467 				addr = (void *)map_data_base;
    468 				map_data_base += shdr[i].sh_size;
    469  			}
    470 
    471 			ko->ko_progtab[pb].addr = addr;
    472 			if (shdr[i].sh_type == SHT_PROGBITS) {
    473 				ko->ko_progtab[pb].name = "<<PROGBITS>>";
    474 				error = ko->ko_read(ko, &addr,
    475 				    shdr[i].sh_size, shdr[i].sh_offset, false);
    476 				if (error != 0) {
    477 					kobj_error(ko, "read failed %d", error);
    478 					goto out;
    479 				}
    480 			} else { /* SHT_NOBITS */
    481 				ko->ko_progtab[pb].name = "<<NOBITS>>";
    482 				memset(addr, 0, shdr[i].sh_size);
    483 			}
    484 
    485 			ko->ko_progtab[pb].size = shdr[i].sh_size;
    486 			ko->ko_progtab[pb].sec = i;
    487 			if (ko->ko_shstrtab != NULL && shdr[i].sh_name != 0) {
    488 				ko->ko_progtab[pb].name =
    489 				    ko->ko_shstrtab + shdr[i].sh_name;
    490 			}
    491 
    492 			/* Update all symbol values with the offset. */
    493 			for (j = 0; j < ko->ko_symcnt; j++) {
    494 				es = &ko->ko_symtab[j];
    495 				if (es->st_shndx != i) {
    496 					continue;
    497 				}
    498 				es->st_value += (Elf_Addr)addr;
    499 			}
    500 			pb++;
    501 			break;
    502 		case SHT_REL:
    503 			if (shdr[shdr[i].sh_info].sh_type != SHT_PROGBITS)
    504 				break;
    505 			ko->ko_reltab[rl].size = shdr[i].sh_size;
    506 			ko->ko_reltab[rl].size -=
    507 			    shdr[i].sh_size % sizeof(Elf_Rel);
    508 			if (ko->ko_reltab[rl].size != 0) {
    509 				ko->ko_reltab[rl].nrel =
    510 				    shdr[i].sh_size / sizeof(Elf_Rel);
    511 				ko->ko_reltab[rl].sec = shdr[i].sh_info;
    512 				error = ko->ko_read(ko,
    513 				    (void **)&ko->ko_reltab[rl].rel,
    514 				    ko->ko_reltab[rl].size,
    515 				    shdr[i].sh_offset, true);
    516 				if (error != 0) {
    517 					kobj_error(ko, "read failed %d",
    518 					    error);
    519 					goto out;
    520 				}
    521 			}
    522 			rl++;
    523 			break;
    524 		case SHT_RELA:
    525 			if (shdr[shdr[i].sh_info].sh_type != SHT_PROGBITS)
    526 				break;
    527 			ko->ko_relatab[ra].size = shdr[i].sh_size;
    528 			ko->ko_relatab[ra].size -=
    529 			    shdr[i].sh_size % sizeof(Elf_Rela);
    530 			if (ko->ko_relatab[ra].size != 0) {
    531 				ko->ko_relatab[ra].nrela =
    532 				    shdr[i].sh_size / sizeof(Elf_Rela);
    533 				ko->ko_relatab[ra].sec = shdr[i].sh_info;
    534 				error = ko->ko_read(ko,
    535 				    (void **)&ko->ko_relatab[ra].rela,
    536 				    shdr[i].sh_size,
    537 				    shdr[i].sh_offset, true);
    538 				if (error != 0) {
    539 					kobj_error(ko, "read failed %d", error);
    540 					goto out;
    541 				}
    542 			}
    543 			ra++;
    544 			break;
    545 		default:
    546 			break;
    547 		}
    548 	}
    549 	if (pb != ko->ko_nprogtab) {
    550 		panic("%s:%d: %s: lost progbits", __func__, __LINE__,
    551 		   ko->ko_name);
    552 	}
    553 	if (rl != ko->ko_nrel) {
    554 		panic("%s:%d: %s: lost rel", __func__, __LINE__,
    555 		   ko->ko_name);
    556 	}
    557 	if (ra != ko->ko_nrela) {
    558 		panic("%s:%d: %s: lost rela", __func__, __LINE__,
    559 		   ko->ko_name);
    560 	}
    561 	if (map_text_base != ko->ko_text_address + map_text_size) {
    562 		panic("%s:%d: %s: map_text_base 0x%lx != address %lx "
    563 		    "+ map_text_size %ld (0x%lx)\n",
    564 		    __func__, __LINE__, ko->ko_name, (long)map_text_base,
    565 		    (long)ko->ko_text_address, (long)map_text_size,
    566 		    (long)ko->ko_text_address + map_text_size);
    567 	}
    568 	if (map_data_base != ko->ko_data_address + map_data_size) {
    569 		panic("%s:%d: %s: map_data_base 0x%lx != address %lx "
    570 		    "+ map_data_size %ld (0x%lx)\n",
    571 		    __func__, __LINE__, ko->ko_name, (long)map_data_base,
    572 		    (long)ko->ko_data_address, (long)map_data_size,
    573 		    (long)ko->ko_data_address + map_data_size);
    574 	}
    575 
    576 	/*
    577 	 * Perform local relocations only.  Relocations relating to global
    578 	 * symbols will be done by kobj_affix().
    579 	 */
    580 	error = kobj_checksyms(ko, false);
    581 	if (error == 0) {
    582 		error = kobj_relocate(ko, true);
    583 	}
    584  out:
    585 	if (hdr != NULL) {
    586 		kobj_free(ko, hdr, sizeof(*hdr));
    587 	}
    588 	kobj_close(ko);
    589 	if (error != 0) {
    590 		kobj_unload(ko);
    591 	}
    592 
    593 	return error;
    594 }
    595 
    596 /*
    597  * kobj_unload:
    598  *
    599  *	Unload an object previously loaded by kobj_load().
    600  */
    601 void
    602 kobj_unload(kobj_t ko)
    603 {
    604 	int error;
    605 
    606 	kobj_close(ko);
    607 	kobj_jettison(ko);
    608 
    609 	/*
    610 	 * Notify MD code that a module has been unloaded.
    611 	 */
    612 	if (ko->ko_loaded) {
    613 		error = kobj_machdep(ko, (void *)ko->ko_text_address,
    614 		    ko->ko_text_size, false);
    615 		if (error != 0)
    616 			kobj_error(ko, "machine dependent deinit failed (text) %d",
    617 			    error);
    618 		error = kobj_machdep(ko, (void *)ko->ko_data_address,
    619 		    ko->ko_data_size, false);
    620  		if (error != 0)
    621 			kobj_error(ko, "machine dependent deinit failed (data) %d",
    622  			    error);
    623 	}
    624 	if (ko->ko_text_address != 0) {
    625 		uvm_km_free(module_map, ko->ko_text_address,
    626 		    round_page(ko->ko_text_size), UVM_KMF_WIRED);
    627 	}
    628 	if (ko->ko_data_address != 0) {
    629 		uvm_km_free(module_map, ko->ko_data_address,
    630 		    round_page(ko->ko_data_size), UVM_KMF_WIRED);
    631  	}
    632 	if (ko->ko_ksyms == true) {
    633 		ksyms_modunload(ko->ko_name);
    634 	}
    635 	if (ko->ko_symtab != NULL) {
    636 		kobj_free(ko, ko->ko_symtab, ko->ko_symcnt * sizeof(Elf_Sym));
    637 	}
    638 	if (ko->ko_strtab != NULL) {
    639 		kobj_free(ko, ko->ko_strtab, ko->ko_strtabsz);
    640 	}
    641 	if (ko->ko_progtab != NULL) {
    642 		kobj_free(ko, ko->ko_progtab, ko->ko_nprogtab *
    643 		    sizeof(*ko->ko_progtab));
    644 		ko->ko_progtab = NULL;
    645 	}
    646 	if (ko->ko_shstrtab) {
    647 		kobj_free(ko, ko->ko_shstrtab, ko->ko_shstrtabsz);
    648 		ko->ko_shstrtab = NULL;
    649 	}
    650 
    651 	kmem_free(ko, sizeof(*ko));
    652 }
    653 
    654 /*
    655  * kobj_stat:
    656  *
    657  *	Return size and load address of an object.
    658  */
    659 int
    660 kobj_stat(kobj_t ko, vaddr_t *address, size_t *size)
    661 {
    662 
    663 	if (address != NULL) {
    664 		*address = ko->ko_text_address;
    665 	}
    666 	if (size != NULL) {
    667 		*size = ko->ko_text_size;
    668 	}
    669 	return 0;
    670 }
    671 
    672 /*
    673  * kobj_affix:
    674  *
    675  *	Set an object's name and perform global relocs.  May only be
    676  *	called after the module and any requisite modules are loaded.
    677  */
    678 int
    679 kobj_affix(kobj_t ko, const char *name)
    680 {
    681 	int error;
    682 
    683 	KASSERT(ko->ko_ksyms == false);
    684 	KASSERT(ko->ko_loaded == false);
    685 
    686 	kobj_setname(ko, name);
    687 
    688 	/* Cache addresses of undefined symbols. */
    689 	error = kobj_checksyms(ko, true);
    690 
    691 	/* Now do global relocations. */
    692 	if (error == 0)
    693 		error = kobj_relocate(ko, false);
    694 
    695 	/*
    696 	 * Now that we know the name, register the symbol table.
    697 	 * Do after global relocations because ksyms will pack
    698 	 * the table.
    699 	 */
    700 	if (error == 0) {
    701 		ksyms_modload(ko->ko_name, ko->ko_symtab, ko->ko_symcnt *
    702 		    sizeof(Elf_Sym), ko->ko_strtab, ko->ko_strtabsz);
    703 		ko->ko_ksyms = true;
    704 	}
    705 
    706 	/* Jettison unneeded memory post-link. */
    707 	kobj_jettison(ko);
    708 
    709 	/*
    710 	 * Notify MD code that a module has been loaded.
    711 	 *
    712 	 * Most architectures use this opportunity to flush their caches.
    713 	 */
    714 	if (error == 0) {
    715 		error = kobj_machdep(ko, (void *)ko->ko_text_address,
    716 		    ko->ko_text_size, true);
    717 		if (error != 0)
    718 			kobj_error(ko, "machine dependent init failed (text) %d",
    719 			    error);
    720 		error = kobj_machdep(ko, (void *)ko->ko_data_address,
    721 		    ko->ko_data_size, true);
    722 		if (error != 0)
    723 			kobj_error(ko, "machine dependent init failed (data) %d",
    724 			    error);
    725 		ko->ko_loaded = true;
    726 	}
    727 
    728 	/* If there was an error, destroy the whole object. */
    729 	if (error != 0) {
    730 		kobj_unload(ko);
    731 	}
    732 
    733 	return error;
    734 }
    735 
    736 /*
    737  * kobj_find_section:
    738  *
    739  *	Given a section name, search the loaded object and return
    740  *	virtual address if present and loaded.
    741  */
    742 int
    743 kobj_find_section(kobj_t ko, const char *name, void **addr, size_t *size)
    744 {
    745 	int i;
    746 
    747 	KASSERT(ko->ko_progtab != NULL);
    748 
    749 	for (i = 0; i < ko->ko_nprogtab; i++) {
    750 		if (strcmp(ko->ko_progtab[i].name, name) == 0) {
    751 			if (addr != NULL) {
    752 				*addr = ko->ko_progtab[i].addr;
    753 			}
    754 			if (size != NULL) {
    755 				*size = ko->ko_progtab[i].size;
    756 			}
    757 			return 0;
    758 		}
    759 	}
    760 
    761 	return ENOENT;
    762 }
    763 
    764 /*
    765  * kobj_jettison:
    766  *
    767  *	Release object data not needed after performing relocations.
    768  */
    769 static void
    770 kobj_jettison(kobj_t ko)
    771 {
    772 	int i;
    773 
    774 	if (ko->ko_reltab != NULL) {
    775 		for (i = 0; i < ko->ko_nrel; i++) {
    776 			if (ko->ko_reltab[i].rel) {
    777 				kobj_free(ko, ko->ko_reltab[i].rel,
    778 				    ko->ko_reltab[i].size);
    779 			}
    780 		}
    781 		kobj_free(ko, ko->ko_reltab, ko->ko_nrel *
    782 		    sizeof(*ko->ko_reltab));
    783 		ko->ko_reltab = NULL;
    784 		ko->ko_nrel = 0;
    785 	}
    786 	if (ko->ko_relatab != NULL) {
    787 		for (i = 0; i < ko->ko_nrela; i++) {
    788 			if (ko->ko_relatab[i].rela) {
    789 				kobj_free(ko, ko->ko_relatab[i].rela,
    790 				    ko->ko_relatab[i].size);
    791 			}
    792 		}
    793 		kobj_free(ko, ko->ko_relatab, ko->ko_nrela *
    794 		    sizeof(*ko->ko_relatab));
    795 		ko->ko_relatab = NULL;
    796 		ko->ko_nrela = 0;
    797 	}
    798 	if (ko->ko_shdr != NULL) {
    799 		kobj_free(ko, ko->ko_shdr, ko->ko_shdrsz);
    800 		ko->ko_shdr = NULL;
    801 	}
    802 }
    803 
    804 /*
    805  * kobj_sym_lookup:
    806  *
    807  *	Symbol lookup function to be used when the symbol index
    808  *	is known (ie during relocation).
    809  */
    810 uintptr_t
    811 kobj_sym_lookup(kobj_t ko, uintptr_t symidx)
    812 {
    813 	const Elf_Sym *sym;
    814 	const char *symbol;
    815 
    816 	/* Don't even try to lookup the symbol if the index is bogus. */
    817 	if (symidx >= ko->ko_symcnt)
    818 		return 0;
    819 
    820 	sym = ko->ko_symtab + symidx;
    821 
    822 	/* Quick answer if there is a definition included. */
    823 	if (sym->st_shndx != SHN_UNDEF) {
    824 		return (uintptr_t)sym->st_value;
    825 	}
    826 
    827 	/* If we get here, then it is undefined and needs a lookup. */
    828 	switch (ELF_ST_BIND(sym->st_info)) {
    829 	case STB_LOCAL:
    830 		/* Local, but undefined? huh? */
    831 		kobj_error(ko, "local symbol undefined");
    832 		return 0;
    833 
    834 	case STB_GLOBAL:
    835 		/* Relative to Data or Function name */
    836 		symbol = ko->ko_strtab + sym->st_name;
    837 
    838 		/* Force a lookup failure if the symbol name is bogus. */
    839 		if (*symbol == 0) {
    840 			kobj_error(ko, "bad symbol name");
    841 			return 0;
    842 		}
    843 
    844 		return (uintptr_t)sym->st_value;
    845 
    846 	case STB_WEAK:
    847 		kobj_error(ko, "weak symbols not supported");
    848 		return 0;
    849 
    850 	default:
    851 		return 0;
    852 	}
    853 }
    854 
    855 /*
    856  * kobj_findbase:
    857  *
    858  *	Return base address of the given section.
    859  */
    860 static uintptr_t
    861 kobj_findbase(kobj_t ko, int sec)
    862 {
    863 	int i;
    864 
    865 	for (i = 0; i < ko->ko_nprogtab; i++) {
    866 		if (sec == ko->ko_progtab[i].sec) {
    867 			return (uintptr_t)ko->ko_progtab[i].addr;
    868 		}
    869 	}
    870 	return 0;
    871 }
    872 
    873 /*
    874  * kobj_checksyms:
    875  *
    876  *	Scan symbol table for duplicates or resolve references to
    877  *	exernal symbols.
    878  */
    879 static int
    880 kobj_checksyms(kobj_t ko, bool undefined)
    881 {
    882 	unsigned long rval;
    883 	Elf_Sym *sym, *ms;
    884 	const char *name;
    885 	int error;
    886 
    887 	error = 0;
    888 
    889 	for (ms = (sym = ko->ko_symtab) + ko->ko_symcnt; sym < ms; sym++) {
    890 		/* Check validity of the symbol. */
    891 		if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL ||
    892 		    sym->st_name == 0)
    893 			continue;
    894 		if (undefined != (sym->st_shndx == SHN_UNDEF)) {
    895 			continue;
    896 		}
    897 
    898 		/*
    899 		 * Look it up.  Don't need to lock, as it is known that
    900 		 * the symbol tables aren't going to change (we hold
    901 		 * module_lock).
    902 		 */
    903 		name = ko->ko_strtab + sym->st_name;
    904 		if (ksyms_getval_unlocked(NULL, name, &rval,
    905 		    KSYMS_EXTERN) != 0) {
    906 			if (undefined) {
    907 				kobj_error(ko, "symbol `%s' not found",
    908 				    name);
    909 				error = ENOEXEC;
    910 			}
    911 			continue;
    912 		}
    913 
    914 		/* Save values of undefined globals. */
    915 		if (undefined) {
    916 			sym->st_value = (Elf_Addr)rval;
    917 			continue;
    918 		}
    919 
    920 		/* Check (and complain) about differing values. */
    921 		if (sym->st_value == rval) {
    922 			continue;
    923 		}
    924 		if (strcmp(name, "_bss_start") == 0 ||
    925 		    strcmp(name, "__bss_start") == 0 ||
    926 		    strcmp(name, "_bss_end__") == 0 ||
    927 		    strcmp(name, "__bss_end__") == 0 ||
    928 		    strcmp(name, "_edata") == 0 ||
    929 		    strcmp(name, "_end") == 0 ||
    930 		    strcmp(name, "__end") == 0 ||
    931 		    strcmp(name, "__end__") == 0 ||
    932 		    strncmp(name, "__start_link_set_", 17) == 0 ||
    933 		    strncmp(name, "__stop_link_set_", 16) == 0) {
    934 		    	continue;
    935 		}
    936 		kobj_error(ko, "global symbol `%s' redefined",
    937 		    name);
    938 		error = ENOEXEC;
    939 	}
    940 
    941 	return error;
    942 }
    943 
    944 /*
    945  * kobj_relocate:
    946  *
    947  *	Resolve relocations for the loaded object.
    948  */
    949 static int
    950 kobj_relocate(kobj_t ko, bool local)
    951 {
    952 	const Elf_Rel *rellim;
    953 	const Elf_Rel *rel;
    954 	const Elf_Rela *relalim;
    955 	const Elf_Rela *rela;
    956 	const Elf_Sym *sym;
    957 	uintptr_t base;
    958 	int i, error;
    959 	uintptr_t symidx;
    960 
    961 	/*
    962 	 * Perform relocations without addend if there are any.
    963 	 */
    964 	for (i = 0; i < ko->ko_nrel; i++) {
    965 		rel = ko->ko_reltab[i].rel;
    966 		if (rel == NULL) {
    967 			continue;
    968 		}
    969 		rellim = rel + ko->ko_reltab[i].nrel;
    970 		base = kobj_findbase(ko, ko->ko_reltab[i].sec);
    971 		if (base == 0) {
    972 			panic("%s:%d: %s: lost base for e_reltab[%d] sec %d",
    973 			   __func__, __LINE__, ko->ko_name, i,
    974 			   ko->ko_reltab[i].sec);
    975 		}
    976 		for (; rel < rellim; rel++) {
    977 			symidx = ELF_R_SYM(rel->r_info);
    978 			if (symidx >= ko->ko_symcnt) {
    979 				continue;
    980 			}
    981 			sym = ko->ko_symtab + symidx;
    982 			if (local != (ELF_ST_BIND(sym->st_info) == STB_LOCAL)) {
    983 				continue;
    984 			}
    985 			error = kobj_reloc(ko, base, rel, false, local);
    986 			if (error != 0) {
    987 				return ENOENT;
    988 			}
    989 		}
    990 	}
    991 
    992 	/*
    993 	 * Perform relocations with addend if there are any.
    994 	 */
    995 	for (i = 0; i < ko->ko_nrela; i++) {
    996 		rela = ko->ko_relatab[i].rela;
    997 		if (rela == NULL) {
    998 			continue;
    999 		}
   1000 		relalim = rela + ko->ko_relatab[i].nrela;
   1001 		base = kobj_findbase(ko, ko->ko_relatab[i].sec);
   1002 		if (base == 0) {
   1003 			panic("%s:%d: %s: lost base for e_relatab[%d] sec %d",
   1004 			   __func__, __LINE__, ko->ko_name, i,
   1005 			   ko->ko_relatab[i].sec);
   1006 		}
   1007 		for (; rela < relalim; rela++) {
   1008 			symidx = ELF_R_SYM(rela->r_info);
   1009 			if (symidx >= ko->ko_symcnt) {
   1010 				continue;
   1011 			}
   1012 			sym = ko->ko_symtab + symidx;
   1013 			if (local != (ELF_ST_BIND(sym->st_info) == STB_LOCAL)) {
   1014 				continue;
   1015 			}
   1016 			error = kobj_reloc(ko, base, rela, true, local);
   1017 			if (error != 0) {
   1018 				return ENOENT;
   1019 			}
   1020 		}
   1021 	}
   1022 
   1023 	return 0;
   1024 }
   1025 
   1026 /*
   1027  * kobj_out:
   1028  *
   1029  *	Utility function: log an error.
   1030  */
   1031 static void
   1032 kobj_out(const char *fname, int lnum, kobj_t ko, const char *fmt, ...)
   1033 {
   1034 	va_list ap;
   1035 
   1036 	printf("%s, %d: [%s]: linker error: ", fname, lnum, ko->ko_name);
   1037 	va_start(ap, fmt);
   1038 	vprintf(fmt, ap);
   1039 	va_end(ap);
   1040 	printf("\n");
   1041 }
   1042 
   1043 static int
   1044 kobj_read_mem(kobj_t ko, void **basep, size_t size, off_t off,
   1045     bool allocate)
   1046 {
   1047 	void *base = *basep;
   1048 	int error;
   1049 
   1050 	KASSERT(ko->ko_source != NULL);
   1051 
   1052 	if (ko->ko_memsize != -1 && off + size > ko->ko_memsize) {
   1053 		kobj_error(ko, "preloaded object short");
   1054 		error = EINVAL;
   1055 		base = NULL;
   1056 	} else if (allocate) {
   1057 		base = kmem_alloc(size, KM_SLEEP);
   1058 		error = 0;
   1059 	} else {
   1060 		error = 0;
   1061 	}
   1062 
   1063 	if (error == 0) {
   1064 		/* Copy the section */
   1065 		memcpy(base, (uint8_t *)ko->ko_source + off, size);
   1066 	}
   1067 
   1068 	if (allocate && error != 0) {
   1069 		kmem_free(base, size);
   1070 		base = NULL;
   1071 	}
   1072 
   1073 	if (allocate)
   1074 		*basep = base;
   1075 
   1076 	return error;
   1077 }
   1078 
   1079 /*
   1080  * kobj_free:
   1081  *
   1082  *	Utility function: free memory if it was allocated from the heap.
   1083  */
   1084 static void
   1085 kobj_free(kobj_t ko, void *base, size_t size)
   1086 {
   1087 
   1088 	kmem_free(base, size);
   1089 }
   1090 
   1091 extern char module_base[];
   1092 
   1093 void
   1094 kobj_setname(kobj_t ko, const char *name)
   1095 {
   1096 	const char *d = name, *dots = "";
   1097 	size_t len, dlen;
   1098 
   1099 	for (char *s = module_base; *d == *s; d++, s++)
   1100 		continue;
   1101 
   1102 	if (d == name)
   1103 		name = "";
   1104 	else
   1105 		name = "%M";
   1106 	dlen = strlen(d);
   1107 	len = dlen + strlen(name);
   1108 	if (len >= sizeof(ko->ko_name)) {
   1109 		len = (len - sizeof(ko->ko_name)) + 5; /* dots + NUL */
   1110 		if (dlen >= len) {
   1111 			d += len;
   1112 			dots = "/...";
   1113 		}
   1114 	}
   1115 	snprintf(ko->ko_name, sizeof(ko->ko_name), "%s%s%s", name, dots, d);
   1116 }
   1117 
   1118 #else	/* MODULAR */
   1119 
   1120 int
   1121 kobj_load_mem(kobj_t *kop, const char *name, void *base, ssize_t size)
   1122 {
   1123 
   1124 	return ENOSYS;
   1125 }
   1126 
   1127 void
   1128 kobj_unload(kobj_t ko)
   1129 {
   1130 
   1131 	panic("not modular");
   1132 }
   1133 
   1134 int
   1135 kobj_stat(kobj_t ko, vaddr_t *base, size_t *size)
   1136 {
   1137 
   1138 	return ENOSYS;
   1139 }
   1140 
   1141 int
   1142 kobj_affix(kobj_t ko, const char *name)
   1143 {
   1144 
   1145 	panic("not modular");
   1146 }
   1147 
   1148 int
   1149 kobj_find_section(kobj_t ko, const char *name, void **addr, size_t *size)
   1150 {
   1151 
   1152 	panic("not modular");
   1153 }
   1154 
   1155 void
   1156 kobj_setname(kobj_t ko, const char *name)
   1157 {
   1158 
   1159 	panic("not modular");
   1160 }
   1161 
   1162 #endif	/* MODULAR */
   1163