xref: /illumos-gate/usr/src/uts/common/krtld/kobj.c (revision 23690bf77a6b57ae5a2927ea6d4fdab770d0af97)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 /*
26  * Copyright 2011 Bayard G. Bell <buffer.g.overflow@gmail.com>.
27  * All rights reserved. Use is subject to license terms.
28  * Copyright 2020 Joyent, Inc.
29  * Copyright 2025 MNX Cloud, Inc.
30  * Copyright 2025 Oxide Computer Company
31  */
32 
33 /*
34  * Kernel's linker/loader
35  */
36 
37 #include <sys/types.h>
38 #include <sys/param.h>
39 #include <sys/sysmacros.h>
40 #include <sys/systm.h>
41 #include <sys/user.h>
42 #include <sys/kmem.h>
43 #include <sys/reboot.h>
44 #include <sys/bootconf.h>
45 #include <sys/debug.h>
46 #include <sys/uio.h>
47 #include <sys/file.h>
48 #include <sys/vnode.h>
49 #include <sys/user.h>
50 #include <sys/mman.h>
51 #include <vm/as.h>
52 #include <vm/seg_kp.h>
53 #include <vm/seg_kmem.h>
54 #include <sys/elf.h>
55 #include <sys/elf_notes.h>
56 #include <sys/vmsystm.h>
57 #include <sys/kdi.h>
58 #include <sys/atomic.h>
59 #include <sys/kmdb.h>
60 
61 #include <sys/link.h>
62 #include <sys/kobj.h>
63 #include <sys/ksyms.h>
64 #include <sys/disp.h>
65 #include <sys/modctl.h>
66 #include <sys/varargs.h>
67 #include <sys/kstat.h>
68 #include <sys/kobj_impl.h>
69 #include <sys/fs/decomp.h>
70 #include <sys/callb.h>
71 #include <sys/cmn_err.h>
72 #include <sys/zmod.h>
73 
74 #include <krtld/reloc.h>
75 #include <krtld/kobj_kdi.h>
76 #include <sys/sha1.h>
77 #include <sys/crypto/elfsign.h>
78 
79 #if !defined(_OBP)
80 #include <sys/bootvfs.h>
81 #endif
82 
83 /*
84  * do_symbols() error codes
85  */
86 #define	DOSYM_UNDEF		-1	/* undefined symbol */
87 #define	DOSYM_UNSAFE		-2	/* MT-unsafe driver symbol */
88 
89 #if !defined(_OBP)
90 static void synthetic_bootaux(char *, val_t *);
91 #endif
92 
93 static struct module *load_exec(val_t *, char *);
94 static void load_linker(val_t *);
95 static struct modctl *add_primary(const char *filename, int);
96 static int bind_primary(val_t *, int);
97 static int load_primary(struct module *, int);
98 static int load_kmdb(val_t *);
99 static int get_progbits(struct module *, struct _buf *);
100 static int get_syms(struct module *, struct _buf *);
101 static int get_ctf(struct module *, struct _buf *);
102 static void get_signature(struct module *, struct _buf *);
103 static int do_common(struct module *);
104 static void add_dependent(struct module *, struct module *);
105 static int do_dependents(struct modctl *, char *, size_t);
106 static int do_symbols(struct module *, Elf64_Addr);
107 static void module_assign(struct modctl *, struct module *);
108 static void free_module_data(struct module *);
109 static char *depends_on(struct module *);
110 static char *getmodpath(const char *);
111 static char *basename(char *);
112 static void attr_val(val_t *);
113 static char *find_libmacro(char *);
114 static char *expand_libmacro(char *, char *, char *);
115 static int read_bootflags(void);
116 static int kobj_comp_setup(struct _buf *, struct compinfo *);
117 static int kobj_uncomp_blk(struct _buf *, caddr_t, uint_t);
118 static int kobj_read_blks(struct _buf *, caddr_t, uint_t, uint_t);
119 static int kobj_boot_open(char *, int);
120 static int kobj_boot_close(int);
121 static int kobj_boot_seek(int, off_t, off_t);
122 static int kobj_boot_read(int, caddr_t, size_t);
123 static int kobj_boot_fstat(int, struct bootstat *);
124 static int kobj_boot_compinfo(int, struct compinfo *);
125 
126 static Sym *lookup_one(struct module *, const char *);
127 static void sym_insert(struct module *, char *, symid_t);
128 static Sym *sym_lookup(struct module *, Sym *);
129 
130 static struct kobjopen_tctl *kobjopen_alloc(char *filename);
131 static void kobjopen_free(struct kobjopen_tctl *ltp);
132 static void kobjopen_thread(struct kobjopen_tctl *ltp);
133 static int kobj_is_compressed(intptr_t);
134 
135 extern int kcopy(const void *, void *, size_t);
136 extern int elf_mach_ok(Ehdr *);
137 extern int alloc_gottable(struct module *, caddr_t *, caddr_t *);
138 
139 #if !defined(_OBP)
140 extern int kobj_boot_mountroot(void);
141 #endif
142 
143 extern int modrootloaded;
144 extern int swaploaded;
145 extern int bop_io_quiesced;
146 extern int last_module_id;
147 
148 extern char stubs_base[];
149 extern char stubs_end[];
150 
151 #ifdef KOBJ_DEBUG
152 /*
153  * Values that can be or'd in to kobj_debug and their effects:
154  *
155  *	D_DEBUG		- misc. debugging information.
156  *	D_SYMBOLS	- list symbols and their values as they are entered
157  *			  into the hash table
158  *	D_RELOCATIONS	- display relocation processing information
159  *	D_LOADING	- display information about each module as it
160  *			  is loaded.
161  */
162 int kobj_debug = 0;
163 
164 #define	KOBJ_MARK(s)	if (kobj_debug & D_DEBUG)	\
165 	(_kobj_printf(ops, "%d", __LINE__), _kobj_printf(ops, ": %s\n", s))
166 #else
167 #define	KOBJ_MARK(s)	/* discard */
168 #endif
169 
170 #define	MODPATH_PROPNAME	"module-path"
171 
172 #ifdef MODDIR_SUFFIX
173 static char slash_moddir_suffix_slash[] = MODDIR_SUFFIX "/";
174 #else
175 #define	slash_moddir_suffix_slash	""
176 #endif
177 
178 #define	_moddebug	get_weakish_int(&moddebug)
179 #define	_modrootloaded	get_weakish_int(&modrootloaded)
180 #define	_swaploaded	get_weakish_int(&swaploaded)
181 #define	_ioquiesced	get_weakish_int(&bop_io_quiesced)
182 
183 #define	mod(X)		(struct module *)((X)->modl_modp->mod_mp)
184 
185 void	*romp;		/* rom vector (opaque to us) */
186 struct bootops *ops;	/* bootops vector */
187 void *dbvec;		/* debug vector */
188 
189 /*
190  * kobjopen thread control structure
191  */
192 struct kobjopen_tctl {
193 	ksema_t		sema;
194 	char		*name;		/* name of file */
195 	struct vnode	*vp;		/* vnode return from vn_open() */
196 	int		Errno;		/* error return from vnopen    */
197 };
198 
199 /*
200  * Structure for defining dynamically expandable library macros
201  */
202 
203 struct lib_macro_info {
204 	char	*lmi_list;		/* ptr to list of possible choices */
205 	char	*lmi_macroname;		/* pointer to macro name */
206 	ushort_t lmi_ba_index;		/* index into bootaux vector */
207 	ushort_t lmi_macrolen;		/* macro length */
208 } libmacros[] = {
209 	{ NULL, "CPU", BA_CPU, 0 },
210 	{ NULL, "MMU", BA_MMU, 0 }
211 };
212 
213 #define	NLIBMACROS	sizeof (libmacros) / sizeof (struct lib_macro_info)
214 
215 char *boot_cpu_compatible_list;			/* make $CPU available */
216 
217 char *kobj_module_path;				/* module search path */
218 vmem_t	*text_arena;				/* module text arena */
219 static vmem_t *data_arena;			/* module data & bss arena */
220 static vmem_t *ctf_arena;			/* CTF debug data arena */
221 static struct modctl *kobj_modules = NULL;	/* modules loaded */
222 int kobj_mmu_pagesize;				/* system pagesize */
223 static int lg_pagesize;				/* "large" pagesize */
224 static int kobj_last_module_id = 0;		/* id assignment */
225 static kmutex_t kobj_lock;			/* protects mach memory list */
226 
227 /*
228  * The following functions have been implemented by the kernel.
229  * However, many 3rd party drivers provide their own implementations
230  * of these functions.  When such drivers are loaded, messages
231  * indicating that these symbols have been multiply defined will be
232  * emitted to the console.  To avoid alarming customers for no good
233  * reason, we simply suppress such warnings for the following set of
234  * functions.
235  */
236 static char *suppress_sym_list[] =
237 {
238 	"strstr",
239 	"strncat",
240 	"strlcat",
241 	"strlcpy",
242 	"strspn",
243 	"memcpy",
244 	"memset",
245 	"memmove",
246 	"memcmp",
247 	"memchr",
248 	"__udivdi3",
249 	"__divdi3",
250 	"__umoddi3",
251 	"__moddi3",
252 	NULL		/* This entry must exist */
253 };
254 
255 /* indexed by KOBJ_NOTIFY_* */
256 static kobj_notify_list_t *kobj_notifiers[KOBJ_NOTIFY_MAX + 1];
257 
258 /*
259  * Prefix for statically defined tracing (SDT) DTrace probes.
260  */
261 const char		*sdt_prefix = "__dtrace_probe_";
262 
263 /*
264  * Beginning and end of the kernel's dynamic text/data segments.
265  */
266 static caddr_t _text;
267 static caddr_t _etext;
268 static caddr_t _data;
269 
270 /*
271  * The sparc linker doesn't create a memory location
272  * for a variable named _edata, so _edata can only be
273  * referred to, not modified.  krtld needs a static
274  * variable to modify it - within krtld, of course -
275  * outside of krtld, e_data is used in all kernels.
276  */
277 #if defined(__sparc)
278 static caddr_t _edata;
279 #else
280 extern caddr_t _edata;
281 #endif
282 
283 Addr dynseg = 0;	/* load address of "dynamic" segment */
284 size_t dynsize;		/* "dynamic" segment size */
285 
286 
287 int standalone = 1;			/* an unwholey kernel? */
288 int use_iflush;				/* iflush after relocations */
289 
290 /*
291  * _kobj_printf() and _vkobj_printf()
292  *
293  * Common printf function pointer. Can handle only one conversion
294  * specification in the format string. Some of the functions invoked
295  * through this function pointer cannot handle more that one conversion
296  * specification in the format string.
297  */
298 void (*_kobj_printf)(void *, const char *, ...) __KPRINTFLIKE(2);
299 void (*_vkobj_printf)(void *, const char *, va_list) __KVPRINTFLIKE(2);
300 
301 /*
302  * Standalone function pointers for use within krtld.
303  * Many platforms implement optimized platmod versions of
304  * utilities such as bcopy and any such are not yet available
305  * until the kernel is more completely stitched together.
306  * See kobj_impl.h
307  */
308 void (*kobj_bcopy)(const void *, void *, size_t);
309 void (*kobj_bzero)(void *, size_t);
310 size_t (*kobj_strlcat)(char *, const char *, size_t);
311 
312 static kobj_stat_t kobj_stat;
313 
314 #define	MINALIGN	8	/* at least a double-word */
315 
316 int
get_weakish_int(int * ip)317 get_weakish_int(int *ip)
318 {
319 	if (standalone)
320 		return (0);
321 	return (ip == NULL ? 0 : *ip);
322 }
323 
324 static void *
get_weakish_pointer(void ** ptrp)325 get_weakish_pointer(void **ptrp)
326 {
327 	if (standalone)
328 		return (0);
329 	return (ptrp == NULL ? 0 : *ptrp);
330 }
331 
332 /*
333  * XXX fix dependencies on "kernel"; this should work
334  * for other standalone binaries as well.
335  *
336  * XXX Fix hashing code to use one pointer to
337  * hash entries.
338  *	|----------|
339  *	| nbuckets |
340  *	|----------|
341  *	| nchains  |
342  *	|----------|
343  *	| bucket[] |
344  *	|----------|
345  *	| chain[]  |
346  *	|----------|
347  */
348 
349 /*
350  * Load, bind and relocate all modules that
351  * form the primary kernel. At this point, our
352  * externals have not been relocated.
353  */
354 void
kobj_init(void * romvec,void * dvec,struct bootops * bootvec,val_t * bootaux)355 kobj_init(
356 	void *romvec,
357 	void *dvec,
358 	struct bootops *bootvec,
359 	val_t *bootaux)
360 {
361 	struct module *mp;
362 	struct modctl *modp;
363 	Addr entry;
364 	char filename[MAXPATHLEN];
365 
366 	/*
367 	 * Save these to pass on to
368 	 * the booted standalone.
369 	 */
370 	romp = romvec;
371 	dbvec = dvec;
372 
373 	ops = bootvec;
374 	kobj_setup_standalone_vectors();
375 
376 	KOBJ_MARK("Entered kobj_init()");
377 
378 	(void) BOP_GETPROP(ops, "whoami", filename);
379 
380 	/*
381 	 * We don't support standalone debuggers anymore.  The use of kadb
382 	 * will interfere with the later use of kmdb.  Let the user mend
383 	 * their ways now.  Users will reach this message if they still
384 	 * have the kadb binary on their system (perhaps they used an old
385 	 * bfu, or maybe they intentionally copied it there) and have
386 	 * specified its use in a way that eluded our checking in the boot
387 	 * program.
388 	 */
389 	if (dvec != NULL) {
390 		_kobj_printf(ops, "\nWARNING: Standalone debuggers such as "
391 		    "kadb are no longer supported\n\n");
392 		goto fail;
393 	}
394 
395 #if defined(_OBP)
396 	/*
397 	 * OBP allows us to read both the ramdisk and
398 	 * the underlying root fs when root is a disk.
399 	 * This can lower incidences of unbootable systems
400 	 * when the archive is out-of-date with the /etc
401 	 * state files.
402 	 */
403 	if (BOP_MOUNTROOT() != BOOT_SVC_OK) {
404 		_kobj_printf(ops, "can't mount boot fs\n");
405 		goto fail;
406 	}
407 #else
408 	/* on x86, we always boot with a ramdisk */
409 	if (kobj_boot_mountroot() != 0) {
410 		goto fail;
411 	}
412 
413 	/*
414 	 * Now that the ramdisk is mounted, finish boot property
415 	 * initialization.
416 	 */
417 	read_bootenvrc();
418 
419 #if !defined(_UNIX_KRTLD)
420 	/*
421 	 * 'unix' is linked together with 'krtld' into one executable and
422 	 * the early boot code does -not- hand us any of the dynamic metadata
423 	 * about the executable. In particular, it does not read in, map or
424 	 * otherwise look at the program headers. We fake all that up now.
425 	 *
426 	 * We do this early as DTrace static probes call undefined references.
427 	 * We have to process those relocations before calling any of them.
428 	 *
429 	 * OBP tells kobj_start() where the ELF image is in memory, so it
430 	 * synthesized bootaux before kobj_init() was called
431 	 */
432 	if (bootaux[BA_PHDR].ba_ptr == NULL)
433 		synthetic_bootaux(filename, bootaux);
434 
435 #endif	/* !_UNIX_KRTLD */
436 #endif	/* _OBP */
437 
438 	/*
439 	 * Save the interesting attribute-values
440 	 * (scanned by kobj_boot).
441 	 */
442 	attr_val(bootaux);
443 
444 	/*
445 	 * Set the module search path.
446 	 */
447 	kobj_module_path = getmodpath(filename);
448 
449 	boot_cpu_compatible_list = find_libmacro("CPU");
450 
451 	/*
452 	 * These two modules have actually been
453 	 * loaded by boot, but we finish the job
454 	 * by introducing them into the world of
455 	 * loadable modules.
456 	 */
457 
458 	mp = load_exec(bootaux, filename);
459 	load_linker(bootaux);
460 
461 	/*
462 	 * Load all the primary dependent modules.
463 	 */
464 	if (load_primary(mp, KOBJ_LM_PRIMARY) == -1)
465 		goto fail;
466 
467 	/*
468 	 * Glue it together.
469 	 */
470 	if (bind_primary(bootaux, KOBJ_LM_PRIMARY) == -1)
471 		goto fail;
472 
473 	entry = bootaux[BA_ENTRY].ba_val;
474 
475 	/*
476 	 * Get the boot flags
477 	 */
478 	bootflags(ops);
479 
480 	if (boothowto & RB_VERBOSE)
481 		kobj_lm_dump(KOBJ_LM_PRIMARY);
482 
483 	kobj_kdi_init();
484 
485 	if (boothowto & RB_KMDB) {
486 		if (load_kmdb(bootaux) < 0)
487 			goto fail;
488 	}
489 
490 	/*
491 	 * Post setup.
492 	 */
493 	s_text = _text;
494 	e_text = _etext;
495 	s_data = _data;
496 	e_data = _edata;
497 
498 	kobj_sync_instruction_memory(s_text, e_text - s_text);
499 
500 #ifdef	KOBJ_DEBUG
501 	if (kobj_debug & D_DEBUG)
502 		_kobj_printf(ops,
503 		    "krtld: transferring control to: 0x%lx\n", entry);
504 #endif
505 
506 	/*
507 	 * Make sure the mod system knows about the modules already loaded.
508 	 */
509 	last_module_id = kobj_last_module_id;
510 	bcopy(kobj_modules, &modules, sizeof (modules));
511 	modp = &modules;
512 	do {
513 		if (modp->mod_next == kobj_modules)
514 			modp->mod_next = &modules;
515 		if (modp->mod_prev == kobj_modules)
516 			modp->mod_prev = &modules;
517 	} while ((modp = modp->mod_next) != &modules);
518 
519 	standalone = 0;
520 
521 #ifdef	KOBJ_DEBUG
522 	if (kobj_debug & D_DEBUG)
523 		_kobj_printf(ops,
524 		    "krtld: really transferring control to: 0x%lx\n", entry);
525 #endif
526 
527 	/* restore printf/bcopy/bzero vectors before returning */
528 	kobj_restore_vectors();
529 
530 #if defined(_DBOOT)
531 	/*
532 	 * krtld was called from a dboot ELF section, the embedded
533 	 * dboot code contains the real entry via bootaux
534 	 */
535 	exitto((caddr_t)entry);
536 #else
537 	/*
538 	 * krtld was directly called from startup
539 	 */
540 	return;
541 #endif
542 
543 fail:
544 
545 	_kobj_printf(ops, "krtld: error during initial load/link phase\n");
546 
547 #if !defined(_UNIX_KRTLD)
548 	_kobj_printf(ops, "\n");
549 	_kobj_printf(ops, "krtld could neither locate nor resolve symbols"
550 	    " for:\n");
551 	_kobj_printf(ops, "    %s\n", filename);
552 	_kobj_printf(ops, "in the boot archive. Please verify that this"
553 	    " file\n");
554 	_kobj_printf(ops, "matches what is found in the boot archive.\n");
555 	_kobj_printf(ops, "You may need to boot using the Solaris failsafe to"
556 	    " fix this.\n");
557 	bop_panic("Unable to boot");
558 #endif
559 }
560 
561 #if !defined(_UNIX_KRTLD) && !defined(_OBP)
562 /*
563  * Synthesize additional metadata that describes the executable if
564  * krtld's caller didn't do it.
565  *
566  * (When the dynamic executable has an interpreter, the boot program
567  * does all this for us.  Where we don't have an interpreter, (or a
568  * even a boot program, perhaps) we have to do this for ourselves.)
569  */
570 static void
synthetic_bootaux(char * filename,val_t * bootaux)571 synthetic_bootaux(char *filename, val_t *bootaux)
572 {
573 	Ehdr ehdr;
574 	caddr_t phdrbase;
575 	struct _buf *file;
576 	int i, n;
577 
578 	/*
579 	 * Elf header
580 	 */
581 	KOBJ_MARK("synthetic_bootaux()");
582 	KOBJ_MARK(filename);
583 	file = kobj_open_file(filename);
584 	if (file == (struct _buf *)-1) {
585 		_kobj_printf(ops, "krtld: failed to open '%s'\n", filename);
586 		return;
587 	}
588 	KOBJ_MARK("reading program headers");
589 	if (kobj_read_file(file, (char *)&ehdr, sizeof (ehdr), 0) < 0) {
590 		_kobj_printf(ops, "krtld: %s: failed to read ehder\n",
591 		    filename);
592 		return;
593 	}
594 
595 	/*
596 	 * Program headers
597 	 */
598 	bootaux[BA_PHNUM].ba_val = ehdr.e_phnum;
599 	bootaux[BA_PHENT].ba_val = ehdr.e_phentsize;
600 	n = ehdr.e_phentsize * ehdr.e_phnum;
601 
602 	phdrbase = kobj_alloc(n, KM_WAIT | KM_TMP);
603 
604 	if (kobj_read_file(file, phdrbase, n, ehdr.e_phoff) < 0) {
605 		_kobj_printf(ops, "krtld: %s: failed to read phdrs\n",
606 		    filename);
607 		return;
608 	}
609 	bootaux[BA_PHDR].ba_ptr = phdrbase;
610 	kobj_close_file(file);
611 	KOBJ_MARK("closed file");
612 
613 	/*
614 	 * Find the dynamic section address
615 	 */
616 	for (i = 0; i < ehdr.e_phnum; i++) {
617 		Phdr *phdr = (Phdr *)(phdrbase + ehdr.e_phentsize * i);
618 
619 		if (phdr->p_type == PT_DYNAMIC) {
620 			bootaux[BA_DYNAMIC].ba_ptr = (void *)phdr->p_vaddr;
621 			break;
622 		}
623 	}
624 	KOBJ_MARK("synthetic_bootaux() done");
625 }
626 #endif	/* !_UNIX_KRTLD && !_OBP */
627 
628 /*
629  * Set up any global information derived
630  * from attribute/values in the boot or
631  * aux vector.
632  */
633 static void
attr_val(val_t * bootaux)634 attr_val(val_t *bootaux)
635 {
636 	Phdr *phdr;
637 	int phnum, phsize;
638 	int i;
639 
640 	KOBJ_MARK("attr_val()");
641 	kobj_mmu_pagesize = bootaux[BA_PAGESZ].ba_val;
642 	lg_pagesize = bootaux[BA_LPAGESZ].ba_val;
643 	use_iflush = bootaux[BA_IFLUSH].ba_val;
644 
645 	phdr = (Phdr *)bootaux[BA_PHDR].ba_ptr;
646 	phnum = bootaux[BA_PHNUM].ba_val;
647 	phsize = bootaux[BA_PHENT].ba_val;
648 	for (i = 0; i < phnum; i++) {
649 		phdr = (Phdr *)(bootaux[BA_PHDR].ba_val + i * phsize);
650 
651 		if (phdr->p_type != PT_LOAD) {
652 			continue;
653 		}
654 		/*
655 		 * Bounds of the various segments.
656 		 */
657 		if (!(phdr->p_flags & PF_X)) {
658 #if defined(_RELSEG)
659 			/*
660 			 * sparc kernel puts the dynamic info
661 			 * into a separate segment, which is
662 			 * free'd in bop_fini()
663 			 */
664 			ASSERT(phdr->p_vaddr != 0);
665 			dynseg = phdr->p_vaddr;
666 			dynsize = phdr->p_memsz;
667 #else
668 			ASSERT(phdr->p_vaddr == 0);
669 #endif
670 		} else {
671 			if (phdr->p_flags & PF_W) {
672 				_data = (caddr_t)phdr->p_vaddr;
673 				_edata = _data + phdr->p_memsz;
674 			} else {
675 				_text = (caddr_t)phdr->p_vaddr;
676 				_etext = _text + phdr->p_memsz;
677 			}
678 		}
679 	}
680 
681 	/* To do the kobj_alloc, _edata needs to be set. */
682 	for (i = 0; i < NLIBMACROS; i++) {
683 		if (bootaux[libmacros[i].lmi_ba_index].ba_ptr != NULL) {
684 			libmacros[i].lmi_list = kobj_alloc(
685 			    strlen(bootaux[libmacros[i].lmi_ba_index].ba_ptr) +
686 			    1, KM_WAIT);
687 			(void) strcpy(libmacros[i].lmi_list,
688 			    bootaux[libmacros[i].lmi_ba_index].ba_ptr);
689 		}
690 		libmacros[i].lmi_macrolen = strlen(libmacros[i].lmi_macroname);
691 	}
692 }
693 
694 /*
695  * Set up the booted executable.
696  */
697 static struct module *
load_exec(val_t * bootaux,char * filename)698 load_exec(val_t *bootaux, char *filename)
699 {
700 	struct modctl *cp;
701 	struct module *mp;
702 	Dyn *dyn;
703 	Sym *sp;
704 	int i, lsize, osize, nsize, allocsize;
705 	char *libname, *tmp;
706 	char path[MAXPATHLEN];
707 
708 #ifdef KOBJ_DEBUG
709 	if (kobj_debug & D_DEBUG)
710 		_kobj_printf(ops, "module path '%s'\n", kobj_module_path);
711 #endif
712 
713 	KOBJ_MARK("add_primary");
714 	cp = add_primary(filename, KOBJ_LM_PRIMARY);
715 
716 	KOBJ_MARK("struct module");
717 	mp = kobj_zalloc(sizeof (struct module), KM_WAIT);
718 	cp->mod_mp = mp;
719 
720 	/*
721 	 * We don't have the following information
722 	 * since this module is an executable and not
723 	 * a relocatable .o.
724 	 */
725 	mp->symtbl_section = 0;
726 	mp->shdrs = NULL;
727 	mp->strhdr = NULL;
728 
729 	/*
730 	 * Since this module is the only exception,
731 	 * we cons up some section headers.
732 	 */
733 	KOBJ_MARK("symhdr");
734 	mp->symhdr = kobj_zalloc(sizeof (Shdr), KM_WAIT);
735 
736 	KOBJ_MARK("strhdr");
737 	mp->strhdr = kobj_zalloc(sizeof (Shdr), KM_WAIT);
738 
739 	mp->symhdr->sh_type = SHT_SYMTAB;
740 	mp->strhdr->sh_type = SHT_STRTAB;
741 	/*
742 	 * Scan the dynamic structure.
743 	 */
744 	for (dyn = (Dyn *) bootaux[BA_DYNAMIC].ba_ptr;
745 	    dyn->d_tag != DT_NULL; dyn++) {
746 		switch (dyn->d_tag) {
747 		case DT_SYMTAB:
748 			mp->symspace = mp->symtbl = (char *)dyn->d_un.d_ptr;
749 			mp->symhdr->sh_addr = dyn->d_un.d_ptr;
750 			break;
751 		case DT_HASH:
752 			mp->nsyms = *((uint_t *)dyn->d_un.d_ptr + 1);
753 			mp->hashsize = *(uint_t *)dyn->d_un.d_ptr;
754 			break;
755 		case DT_STRTAB:
756 			mp->strings = (char *)dyn->d_un.d_ptr;
757 			mp->strhdr->sh_addr = dyn->d_un.d_ptr;
758 			break;
759 		case DT_STRSZ:
760 			mp->strhdr->sh_size = dyn->d_un.d_val;
761 			break;
762 		case DT_SYMENT:
763 			mp->symhdr->sh_entsize = dyn->d_un.d_val;
764 			break;
765 		}
766 	}
767 
768 	/*
769 	 * Collapse any DT_NEEDED entries into one string.
770 	 */
771 	nsize = osize = 0;
772 	allocsize = MAXPATHLEN;
773 
774 	KOBJ_MARK("depends_on");
775 	mp->depends_on = kobj_alloc(allocsize, KM_WAIT);
776 
777 	for (dyn = (Dyn *) bootaux[BA_DYNAMIC].ba_ptr;
778 	    dyn->d_tag != DT_NULL; dyn++)
779 		if (dyn->d_tag == DT_NEEDED) {
780 			char *_lib;
781 
782 			libname = mp->strings + dyn->d_un.d_val;
783 			if (strchr(libname, '$') != NULL) {
784 				if ((_lib = expand_libmacro(libname,
785 				    path, path)) != NULL)
786 					libname = _lib;
787 				else
788 					_kobj_printf(ops, "krtld: "
789 					    "load_exec: fail to "
790 					    "expand %s\n", libname);
791 			}
792 			lsize = strlen(libname);
793 			nsize += lsize;
794 			if (nsize + 1 > allocsize) {
795 				KOBJ_MARK("grow depends_on");
796 				tmp = kobj_alloc(allocsize + MAXPATHLEN,
797 				    KM_WAIT);
798 				bcopy(mp->depends_on, tmp, osize);
799 				kobj_free(mp->depends_on, allocsize);
800 				mp->depends_on = tmp;
801 				allocsize += MAXPATHLEN;
802 			}
803 			bcopy(libname, mp->depends_on + osize, lsize);
804 			*(mp->depends_on + nsize) = ' '; /* separate */
805 			nsize++;
806 			osize = nsize;
807 		}
808 	if (nsize) {
809 		mp->depends_on[nsize - 1] = '\0'; /* terminate the string */
810 		/*
811 		 * alloc with exact size and copy whatever it got over
812 		 */
813 		KOBJ_MARK("realloc depends_on");
814 		tmp = kobj_alloc(nsize, KM_WAIT);
815 		bcopy(mp->depends_on, tmp, nsize);
816 		kobj_free(mp->depends_on, allocsize);
817 		mp->depends_on = tmp;
818 	} else {
819 		kobj_free(mp->depends_on, allocsize);
820 		mp->depends_on = NULL;
821 	}
822 
823 	mp->flags = KOBJ_EXEC|KOBJ_PRIM;	/* NOT a relocatable .o */
824 	mp->symhdr->sh_size = mp->nsyms * mp->symhdr->sh_entsize;
825 	/*
826 	 * We allocate our own table since we don't
827 	 * hash undefined references.
828 	 */
829 	KOBJ_MARK("chains");
830 	mp->chains = kobj_zalloc(mp->nsyms * sizeof (symid_t), KM_WAIT);
831 	KOBJ_MARK("buckets");
832 	mp->buckets = kobj_zalloc(mp->hashsize * sizeof (symid_t), KM_WAIT);
833 
834 	mp->text = _text;
835 	mp->data = _data;
836 
837 	mp->text_size = _etext - _text;
838 	mp->data_size = _edata - _data;
839 
840 	cp->mod_text = mp->text;
841 	cp->mod_text_size = mp->text_size;
842 
843 	mp->filename = cp->mod_filename;
844 
845 #ifdef	KOBJ_DEBUG
846 	if (kobj_debug & D_LOADING) {
847 		_kobj_printf(ops, "krtld: file=%s\n", mp->filename);
848 		_kobj_printf(ops, "\ttext: 0x%p", mp->text);
849 		_kobj_printf(ops, " size: 0x%lx\n", mp->text_size);
850 		_kobj_printf(ops, "\tdata: 0x%p", mp->data);
851 		_kobj_printf(ops, " dsize: 0x%lx\n", mp->data_size);
852 	}
853 #endif /* KOBJ_DEBUG */
854 
855 	/*
856 	 * Insert symbols into the hash table.
857 	 */
858 	for (i = 0; i < mp->nsyms; i++) {
859 		sp = (Sym *)(mp->symtbl + i * mp->symhdr->sh_entsize);
860 
861 		if (sp->st_name == 0 || sp->st_shndx == SHN_UNDEF)
862 			continue;
863 #if defined(__sparc)
864 		/*
865 		 * Register symbols are ignored in the kernel
866 		 */
867 		if (ELF_ST_TYPE(sp->st_info) == STT_SPARC_REGISTER)
868 			continue;
869 #endif	/* __sparc */
870 
871 		sym_insert(mp, mp->strings + sp->st_name, i);
872 	}
873 
874 	KOBJ_MARK("load_exec done");
875 	return (mp);
876 }
877 
878 static boolean_t
is_extended_ehdr(const Ehdr * hdr)879 is_extended_ehdr(const Ehdr *hdr)
880 {
881 	/*
882 	 * If any of e_shnum, e_shstrndx, or e_phnum are at their sentinel
883 	 * value, this indicates that an extended ELF header is in use. That
884 	 * means that one or more of these values is too large to fit in the
885 	 * elf header and the true values for those are in the first section
886 	 * header.
887 	 */
888 	return ((hdr->e_shnum == 0 && hdr->e_shoff != 0) ||
889 	    hdr->e_phnum == PN_XNUM || hdr->e_shstrndx == SHN_XINDEX);
890 }
891 
892 /*
893  * Set up the linker module (if it's compiled in, LDNAME is NULL)
894  */
895 static void
load_linker(val_t * bootaux)896 load_linker(val_t *bootaux)
897 {
898 	struct module *kmp = (struct module *)kobj_modules->mod_mp;
899 	struct module *mp;
900 	struct modctl *cp;
901 	int i;
902 	Shdr *shp;
903 	Sym *sp;
904 	int shsize;
905 	char *dlname = (char *)bootaux[BA_LDNAME].ba_ptr;
906 	Ehdr *ehdr = (Ehdr *)bootaux[BA_LDELF].ba_ptr;
907 
908 	/*
909 	 * On some architectures, krtld is compiled into the kernel.
910 	 */
911 	if (dlname == NULL)
912 		return;
913 
914 	/*
915 	 * We don't support loading the linker from an ELF object which uses an
916 	 * extended header. That's identified by looking for sentinel values in
917 	 * selected header fields.
918 	 */
919 	if (is_extended_ehdr(ehdr)) {
920 		bop_panic(
921 		    "linker %s has an extended ELF header; unable to load.",
922 		    dlname);
923 	}
924 
925 	cp = add_primary(dlname, KOBJ_LM_PRIMARY);
926 
927 	mp = kobj_zalloc(sizeof (struct module), KM_WAIT);
928 
929 	cp->mod_mp = mp;
930 	mp->hdr = *ehdr;
931 	mp->shnum = mp->hdr.e_shnum;
932 	mp->phnum = mp->hdr.e_phnum;
933 	mp->shstrndx = mp->hdr.e_shstrndx;
934 	shsize = mp->hdr.e_shentsize * mp->shnum;
935 	mp->shdrs = kobj_alloc(shsize, KM_WAIT);
936 	bcopy(bootaux[BA_LDSHDR].ba_ptr, mp->shdrs, shsize);
937 
938 	for (i = 1; i < (int)mp->shnum; i++) {
939 		shp = (Shdr *)(mp->shdrs + (i * mp->hdr.e_shentsize));
940 
941 		if (shp->sh_flags & SHF_ALLOC) {
942 			if (shp->sh_flags & SHF_WRITE) {
943 				if (mp->data == NULL)
944 					mp->data = (char *)shp->sh_addr;
945 			} else if (mp->text == NULL) {
946 				mp->text = (char *)shp->sh_addr;
947 			}
948 		}
949 		if (shp->sh_type == SHT_SYMTAB) {
950 			mp->symtbl_section = i;
951 			mp->symhdr = shp;
952 			mp->symspace = mp->symtbl = (char *)shp->sh_addr;
953 		}
954 	}
955 	mp->nsyms = mp->symhdr->sh_size / mp->symhdr->sh_entsize;
956 	mp->flags = KOBJ_INTERP|KOBJ_PRIM;
957 	mp->strhdr = (Shdr *)
958 	    (mp->shdrs + mp->symhdr->sh_link * mp->hdr.e_shentsize);
959 	mp->strings = (char *)mp->strhdr->sh_addr;
960 	mp->hashsize = kobj_gethashsize(mp->nsyms);
961 
962 	mp->symsize = mp->symhdr->sh_size + mp->strhdr->sh_size + sizeof (int) +
963 	    (mp->hashsize + mp->nsyms) * sizeof (symid_t);
964 
965 	mp->chains = kobj_zalloc(mp->nsyms * sizeof (symid_t), KM_WAIT);
966 	mp->buckets = kobj_zalloc(mp->hashsize * sizeof (symid_t), KM_WAIT);
967 
968 	mp->bss = bootaux[BA_BSS].ba_val;
969 	mp->bss_align = 0;	/* pre-aligned during allocation */
970 	mp->bss_size = (uintptr_t)_edata - mp->bss;
971 	mp->text_size = _etext - mp->text;
972 	mp->data_size = _edata - mp->data;
973 	mp->filename = cp->mod_filename;
974 	cp->mod_text = mp->text;
975 	cp->mod_text_size = mp->text_size;
976 
977 	/*
978 	 * Now that we've figured out where the linker is,
979 	 * set the limits for the booted object.
980 	 */
981 	kmp->text_size = (size_t)(mp->text - kmp->text);
982 	kmp->data_size = (size_t)(mp->data - kmp->data);
983 	kobj_modules->mod_text_size = kmp->text_size;
984 
985 #ifdef	KOBJ_DEBUG
986 	if (kobj_debug & D_LOADING) {
987 		_kobj_printf(ops, "krtld: file=%s\n", mp->filename);
988 		_kobj_printf(ops, "\ttext:0x%p", mp->text);
989 		_kobj_printf(ops, " size: 0x%lx\n", mp->text_size);
990 		_kobj_printf(ops, "\tdata:0x%p", mp->data);
991 		_kobj_printf(ops, " dsize: 0x%lx\n", mp->data_size);
992 	}
993 #endif /* KOBJ_DEBUG */
994 
995 	/*
996 	 * Insert the symbols into the hash table.
997 	 */
998 	for (i = 0; i < mp->nsyms; i++) {
999 		sp = (Sym *)(mp->symtbl + i * mp->symhdr->sh_entsize);
1000 
1001 		if (sp->st_name == 0 || sp->st_shndx == SHN_UNDEF)
1002 			continue;
1003 		if (ELF_ST_BIND(sp->st_info) == STB_GLOBAL) {
1004 			if (sp->st_shndx == SHN_COMMON)
1005 				sp->st_shndx = SHN_ABS;
1006 		}
1007 		sym_insert(mp, mp->strings + sp->st_name, i);
1008 	}
1009 
1010 }
1011 
1012 static kobj_notify_list_t **
kobj_notify_lookup(uint_t type)1013 kobj_notify_lookup(uint_t type)
1014 {
1015 	ASSERT(type != 0 && type < sizeof (kobj_notifiers) /
1016 	    sizeof (kobj_notify_list_t *));
1017 
1018 	return (&kobj_notifiers[type]);
1019 }
1020 
1021 int
kobj_notify_add(kobj_notify_list_t * knp)1022 kobj_notify_add(kobj_notify_list_t *knp)
1023 {
1024 	kobj_notify_list_t **knl;
1025 
1026 	knl = kobj_notify_lookup(knp->kn_type);
1027 
1028 	knp->kn_next = NULL;
1029 	knp->kn_prev = NULL;
1030 
1031 	mutex_enter(&kobj_lock);
1032 
1033 	if (*knl != NULL) {
1034 		(*knl)->kn_prev = knp;
1035 		knp->kn_next = *knl;
1036 	}
1037 	(*knl) = knp;
1038 
1039 	mutex_exit(&kobj_lock);
1040 	return (0);
1041 }
1042 
1043 int
kobj_notify_remove(kobj_notify_list_t * knp)1044 kobj_notify_remove(kobj_notify_list_t *knp)
1045 {
1046 	kobj_notify_list_t **knl = kobj_notify_lookup(knp->kn_type);
1047 	kobj_notify_list_t *tknp;
1048 
1049 	mutex_enter(&kobj_lock);
1050 
1051 	if ((tknp = knp->kn_next) != NULL)
1052 		tknp->kn_prev = knp->kn_prev;
1053 
1054 	if ((tknp = knp->kn_prev) != NULL)
1055 		tknp->kn_next = knp->kn_next;
1056 	else
1057 		*knl = knp->kn_next;
1058 
1059 	mutex_exit(&kobj_lock);
1060 
1061 	return (0);
1062 }
1063 
1064 /*
1065  * Notify all interested callbacks of a specified change in module state.
1066  */
1067 static void
kobj_notify(int type,struct modctl * modp)1068 kobj_notify(int type, struct modctl *modp)
1069 {
1070 	kobj_notify_list_t *knp;
1071 
1072 	if (modp->mod_loadflags & MOD_NONOTIFY || standalone)
1073 		return;
1074 
1075 	mutex_enter(&kobj_lock);
1076 
1077 	for (knp = *(kobj_notify_lookup(type)); knp != NULL; knp = knp->kn_next)
1078 		knp->kn_func(type, modp);
1079 
1080 	/*
1081 	 * KDI notification must be last (it has to allow for work done by the
1082 	 * other notification callbacks), so we call it manually.
1083 	 */
1084 	kobj_kdi_mod_notify(type, modp);
1085 
1086 	mutex_exit(&kobj_lock);
1087 }
1088 
1089 /*
1090  * Create the module path.
1091  */
1092 static char *
getmodpath(const char * filename)1093 getmodpath(const char *filename)
1094 {
1095 	char *path = kobj_zalloc(MAXPATHLEN, KM_WAIT);
1096 
1097 	/*
1098 	 * Platform code gets first crack, then add
1099 	 * the default components
1100 	 */
1101 	mach_modpath(path, filename);
1102 	if (*path != '\0')
1103 		(void) strcat(path, " ");
1104 	return (strcat(path, MOD_DEFPATH));
1105 }
1106 
1107 static struct modctl *
add_primary(const char * filename,int lmid)1108 add_primary(const char *filename, int lmid)
1109 {
1110 	struct modctl *cp;
1111 
1112 	cp = kobj_zalloc(sizeof (struct modctl), KM_WAIT);
1113 
1114 	cp->mod_filename = kobj_alloc(strlen(filename) + 1, KM_WAIT);
1115 
1116 	/*
1117 	 * For symbol lookup, we assemble our own
1118 	 * modctl list of the primary modules.
1119 	 */
1120 
1121 	(void) strcpy(cp->mod_filename, filename);
1122 	cp->mod_modname = basename(cp->mod_filename);
1123 
1124 	/* set values for modinfo assuming that the load will work */
1125 	cp->mod_prim = 1;
1126 	cp->mod_loaded = 1;
1127 	cp->mod_installed = 1;
1128 	cp->mod_loadcnt = 1;
1129 	cp->mod_loadflags = MOD_NOAUTOUNLOAD;
1130 
1131 	cp->mod_id = kobj_last_module_id++;
1132 
1133 	/*
1134 	 * Link the module in. We'll pass this info on
1135 	 * to the mod squad later.
1136 	 */
1137 	if (kobj_modules == NULL) {
1138 		kobj_modules = cp;
1139 		cp->mod_prev = cp->mod_next = cp;
1140 	} else {
1141 		cp->mod_prev = kobj_modules->mod_prev;
1142 		cp->mod_next = kobj_modules;
1143 		kobj_modules->mod_prev->mod_next = cp;
1144 		kobj_modules->mod_prev = cp;
1145 	}
1146 
1147 	kobj_lm_append(lmid, cp);
1148 
1149 	return (cp);
1150 }
1151 
1152 static int
kobj_load_elfhdr(struct _buf * file,struct module * mp)1153 kobj_load_elfhdr(struct _buf *file, struct module *mp)
1154 {
1155 	if (kobj_read_file(file, (char *)&mp->hdr, sizeof (mp->hdr), 0) < 0) {
1156 		_kobj_printf(ops, "kobj_load_elfhdr: %s read header failed\n",
1157 		    mp->filename);
1158 		return (-1);
1159 	}
1160 
1161 	mp->shnum = mp->hdr.e_shnum;
1162 	mp->shstrndx = mp->hdr.e_shstrndx;
1163 	mp->phnum = mp->hdr.e_phnum;
1164 
1165 	/*
1166 	 * If there is an extended ELF header we need to read in the first
1167 	 * section header to access the values for fields that don't fit in
1168 	 * the standard header.
1169 	 */
1170 	if (is_extended_ehdr(&mp->hdr)) {
1171 		Shdr hdr0;
1172 
1173 		if (mp->hdr.e_shoff == 0 ||
1174 		    kobj_read_file(file, (char *)&hdr0, sizeof (hdr0),
1175 		    mp->hdr.e_shoff) < 0) {
1176 			_kobj_printf(ops,
1177 			    "kobj_load_elfhdr: %s read ext header failed\n",
1178 			    mp->filename);
1179 			return (-1);
1180 		}
1181 
1182 		if (mp->shnum == 0)
1183 			mp->shnum = hdr0.sh_size;
1184 		if (mp->shstrndx == SHN_XINDEX)
1185 			mp->shstrndx = hdr0.sh_link;
1186 		if (mp->phnum == PN_XNUM && hdr0.sh_info != 0)
1187 			mp->phnum = hdr0.sh_info;
1188 	}
1189 
1190 	return (0);
1191 }
1192 
1193 static int
bind_primary(val_t * bootaux,int lmid)1194 bind_primary(val_t *bootaux, int lmid)
1195 {
1196 	struct modctl_list *linkmap = kobj_lm_lookup(lmid);
1197 	struct modctl_list *lp;
1198 	struct module *mp;
1199 
1200 	/*
1201 	 * Do common symbols.
1202 	 */
1203 	for (lp = linkmap; lp; lp = lp->modl_next) {
1204 		mp = mod(lp);
1205 
1206 		/*
1207 		 * Don't do common section relocations for modules that
1208 		 * don't need it.
1209 		 */
1210 		if (mp->flags & (KOBJ_EXEC|KOBJ_INTERP))
1211 			continue;
1212 
1213 		if (do_common(mp) < 0)
1214 			return (-1);
1215 	}
1216 
1217 	/*
1218 	 * Resolve symbols.
1219 	 */
1220 	for (lp = linkmap; lp; lp = lp->modl_next) {
1221 		mp = mod(lp);
1222 
1223 		if (do_symbols(mp, 0) < 0)
1224 			return (-1);
1225 	}
1226 
1227 	/*
1228 	 * Do relocations.
1229 	 */
1230 	for (lp = linkmap; lp; lp = lp->modl_next) {
1231 		mp = mod(lp);
1232 
1233 		if (mp->flags & KOBJ_EXEC) {
1234 			Dyn *dyn;
1235 			Word relasz = 0, relaent = 0;
1236 			char *rela = NULL;
1237 
1238 			for (dyn = (Dyn *)bootaux[BA_DYNAMIC].ba_ptr;
1239 			    dyn->d_tag != DT_NULL; dyn++) {
1240 				switch (dyn->d_tag) {
1241 				case DT_RELASZ:
1242 				case DT_RELSZ:
1243 					relasz = dyn->d_un.d_val;
1244 					break;
1245 				case DT_RELAENT:
1246 				case DT_RELENT:
1247 					relaent = dyn->d_un.d_val;
1248 					break;
1249 				case DT_RELA:
1250 					rela = (char *)dyn->d_un.d_ptr;
1251 					break;
1252 				case DT_REL:
1253 					rela = (char *)dyn->d_un.d_ptr;
1254 					break;
1255 				}
1256 			}
1257 			if (relasz == 0 ||
1258 			    relaent == 0 || rela == NULL) {
1259 				_kobj_printf(ops, "krtld: bind_primary(): "
1260 				    "no relocation information found for "
1261 				    "module %s\n", mp->filename);
1262 				return (-1);
1263 			}
1264 #ifdef	KOBJ_DEBUG
1265 			if (kobj_debug & D_RELOCATIONS)
1266 				_kobj_printf(ops, "krtld: relocating: file=%s "
1267 				    "KOBJ_EXEC\n", mp->filename);
1268 #endif
1269 			if (do_relocate(mp, rela, relasz/relaent, relaent,
1270 			    (Addr)mp->text) < 0)
1271 				return (-1);
1272 		} else {
1273 			if (do_relocations(mp) < 0)
1274 				return (-1);
1275 		}
1276 
1277 		kobj_sync_instruction_memory(mp->text, mp->text_size);
1278 	}
1279 
1280 	for (lp = linkmap; lp; lp = lp->modl_next) {
1281 		mp = mod(lp);
1282 
1283 		/*
1284 		 * We need to re-read the full symbol table for the boot file,
1285 		 * since we couldn't use the full one before.  We also need to
1286 		 * load the CTF sections of both the boot file and the
1287 		 * interpreter (us).
1288 		 */
1289 		if (mp->flags & KOBJ_EXEC) {
1290 			struct _buf *file;
1291 			int n;
1292 
1293 			file = kobj_open_file(mp->filename);
1294 			if (file == (struct _buf *)-1)
1295 				return (-1);
1296 			if (kobj_load_elfhdr(file, mp) < 0)
1297 				return (-1);
1298 			n = mp->hdr.e_shentsize * mp->shnum;
1299 			mp->shdrs = kobj_alloc(n, KM_WAIT);
1300 			if (kobj_read_file(file, mp->shdrs, n,
1301 			    mp->hdr.e_shoff) < 0)
1302 				return (-1);
1303 			if (get_syms(mp, file) < 0)
1304 				return (-1);
1305 			if (get_ctf(mp, file) < 0)
1306 				return (-1);
1307 			kobj_close_file(file);
1308 			mp->flags |= KOBJ_RELOCATED;
1309 
1310 		} else if (mp->flags & KOBJ_INTERP) {
1311 			struct _buf *file;
1312 
1313 			/*
1314 			 * The interpreter path fragment in mp->filename
1315 			 * will already have the module directory suffix
1316 			 * in it (if appropriate).
1317 			 */
1318 			file = kobj_open_path(mp->filename, 1, 0);
1319 			if (file == (struct _buf *)-1)
1320 				return (-1);
1321 			if (get_ctf(mp, file) < 0)
1322 				return (-1);
1323 			kobj_close_file(file);
1324 			mp->flags |= KOBJ_RELOCATED;
1325 		}
1326 	}
1327 
1328 	return (0);
1329 }
1330 
1331 static struct modctl *
mod_already_loaded(char * modname)1332 mod_already_loaded(char *modname)
1333 {
1334 	struct modctl *mctl = kobj_modules;
1335 
1336 	do {
1337 		if (strcmp(modname, mctl->mod_filename) == 0)
1338 			return (mctl);
1339 		mctl = mctl->mod_next;
1340 
1341 	} while (mctl != kobj_modules);
1342 
1343 	return (NULL);
1344 }
1345 
1346 /*
1347  * Load all the primary dependent modules.
1348  */
1349 static int
load_primary(struct module * mp,int lmid)1350 load_primary(struct module *mp, int lmid)
1351 {
1352 	struct modctl *cp;
1353 	struct module *dmp;
1354 	char *p, *q;
1355 	char modname[MODMAXNAMELEN];
1356 
1357 	if ((p = mp->depends_on) == NULL)
1358 		return (0);
1359 
1360 	/* CONSTANTCONDITION */
1361 	while (1) {
1362 		/*
1363 		 * Skip space.
1364 		 */
1365 		while (*p && (*p == ' ' || *p == '\t'))
1366 			p++;
1367 		/*
1368 		 * Get module name.
1369 		 */
1370 		q = modname;
1371 		while (*p && *p != ' ' && *p != '\t')
1372 			*q++ = *p++;
1373 
1374 		if (q == modname)
1375 			break;
1376 
1377 		*q = '\0';
1378 		/*
1379 		 * Check for dup dependencies.
1380 		 */
1381 		if (strcmp(modname, "dtracestubs") == 0 ||
1382 		    mod_already_loaded(modname) != NULL)
1383 			continue;
1384 
1385 		cp = add_primary(modname, lmid);
1386 		cp->mod_busy = 1;
1387 		/*
1388 		 * Load it.
1389 		 */
1390 		(void) kobj_load_module(cp, 1);
1391 		cp->mod_busy = 0;
1392 
1393 		if ((dmp = cp->mod_mp) == NULL) {
1394 			cp->mod_loaded = 0;
1395 			cp->mod_installed = 0;
1396 			cp->mod_loadcnt = 0;
1397 			return (-1);
1398 		}
1399 
1400 		add_dependent(mp, dmp);
1401 		dmp->flags |= KOBJ_PRIM;
1402 
1403 		/*
1404 		 * Recurse.
1405 		 */
1406 		if (load_primary(dmp, lmid) == -1) {
1407 			cp->mod_loaded = 0;
1408 			cp->mod_installed = 0;
1409 			cp->mod_loadcnt = 0;
1410 			return (-1);
1411 		}
1412 	}
1413 	return (0);
1414 }
1415 
1416 static int
console_is_usb_serial(void)1417 console_is_usb_serial(void)
1418 {
1419 	char *console;
1420 	int len, ret;
1421 
1422 	if ((len = BOP_GETPROPLEN(ops, "console")) == -1)
1423 		return (0);
1424 
1425 	console = kobj_zalloc(len, KM_WAIT|KM_TMP);
1426 	(void) BOP_GETPROP(ops, "console", console);
1427 	ret = (strcmp(console, "usb-serial") == 0);
1428 	kobj_free(console, len);
1429 
1430 	return (ret);
1431 }
1432 
1433 static int
load_kmdb(val_t * bootaux)1434 load_kmdb(val_t *bootaux)
1435 {
1436 	struct modctl *mctl;
1437 	struct module *mp;
1438 	Sym *sym;
1439 
1440 	if (console_is_usb_serial()) {
1441 		_kobj_printf(ops, "kmdb not loaded "
1442 		    "(unsupported on usb serial console)\n");
1443 		return (0);
1444 	}
1445 
1446 	_kobj_printf(ops, "Loading kmdb...\n");
1447 
1448 	if ((mctl = add_primary("misc/kmdbmod", KOBJ_LM_DEBUGGER)) == NULL)
1449 		return (-1);
1450 
1451 	mctl->mod_busy = 1;
1452 	(void) kobj_load_module(mctl, 1);
1453 	mctl->mod_busy = 0;
1454 
1455 	if ((mp = mctl->mod_mp) == NULL)
1456 		return (-1);
1457 
1458 	mp->flags |= KOBJ_PRIM;
1459 
1460 	if (load_primary(mp, KOBJ_LM_DEBUGGER) < 0)
1461 		return (-1);
1462 
1463 	if (boothowto & RB_VERBOSE)
1464 		kobj_lm_dump(KOBJ_LM_DEBUGGER);
1465 
1466 	if (bind_primary(bootaux, KOBJ_LM_DEBUGGER) < 0)
1467 		return (-1);
1468 
1469 	if ((sym = lookup_one(mctl->mod_mp, "kctl_boot_activate")) == NULL)
1470 		return (-1);
1471 
1472 #ifdef	KOBJ_DEBUG
1473 	if (kobj_debug & D_DEBUG) {
1474 		_kobj_printf(ops, "calling kctl_boot_activate() @ 0x%lx\n",
1475 		    sym->st_value);
1476 		_kobj_printf(ops, "\tops 0x%p\n", ops);
1477 		_kobj_printf(ops, "\tromp 0x%p\n", romp);
1478 	}
1479 #endif
1480 
1481 	if (((kctl_boot_activate_f *)sym->st_value)(ops, romp, 0,
1482 	    (const char **)kobj_kmdb_argv) < 0)
1483 		return (-1);
1484 
1485 	return (0);
1486 }
1487 
1488 /*
1489  * Return a string listing module dependencies.
1490  */
1491 static char *
depends_on(struct module * mp)1492 depends_on(struct module *mp)
1493 {
1494 	Sym *sp;
1495 	char *depstr, *q;
1496 
1497 	/*
1498 	 * The module doesn't have a depends_on value, so let's try it the
1499 	 * old-fashioned way - via "_depends_on"
1500 	 */
1501 	if ((sp = lookup_one(mp, "_depends_on")) == NULL)
1502 		return (NULL);
1503 
1504 	q = (char *)sp->st_value;
1505 
1506 #ifdef KOBJ_DEBUG
1507 	/*
1508 	 * _depends_on is a deprecated interface, so we warn about its use
1509 	 * irrespective of subsequent processing errors. How else are we going
1510 	 * to be able to deco this interface completely?
1511 	 * Changes initially limited to DEBUG because third-party modules
1512 	 * should be flagged to developers before general use base.
1513 	 */
1514 	_kobj_printf(ops,
1515 	    "Warning: %s uses deprecated _depends_on interface.\n",
1516 	    mp->filename);
1517 	_kobj_printf(ops, "Please notify module developer or vendor.\n");
1518 #endif
1519 
1520 	/*
1521 	 * Idiot checks. Make sure it's
1522 	 * in-bounds and NULL terminated.
1523 	 */
1524 	if (kobj_addrcheck(mp, q) || q[sp->st_size - 1] != '\0') {
1525 		_kobj_printf(ops, "Error processing dependency for %s\n",
1526 		    mp->filename);
1527 		return (NULL);
1528 	}
1529 
1530 	depstr = (char *)kobj_alloc(strlen(q) + 1, KM_WAIT);
1531 	(void) strcpy(depstr, q);
1532 
1533 	return (depstr);
1534 }
1535 
1536 void
kobj_getmodinfo(void * xmp,struct modinfo * modinfo)1537 kobj_getmodinfo(void *xmp, struct modinfo *modinfo)
1538 {
1539 	struct module *mp;
1540 	mp = (struct module *)xmp;
1541 
1542 	modinfo->mi_base = mp->text;
1543 	modinfo->mi_size = mp->text_size + mp->data_size;
1544 }
1545 
1546 /*
1547  * kobj_export_ksyms() performs the following services:
1548  *
1549  * (1) Migrates the symbol table from boot/kobj memory to the ksyms arena.
1550  * (2) Removes unneeded symbols to save space.
1551  * (3) Reduces memory footprint by using VM_BESTFIT allocations.
1552  * (4) Makes the symbol table visible to /dev/ksyms.
1553  */
1554 static void
kobj_export_ksyms(struct module * mp)1555 kobj_export_ksyms(struct module *mp)
1556 {
1557 	Sym *esp = (Sym *)(mp->symtbl + mp->symhdr->sh_size);
1558 	Sym *sp, *osp;
1559 	char *name;
1560 	size_t namelen;
1561 	struct module *omp;
1562 	uint_t nsyms;
1563 	size_t symsize = mp->symhdr->sh_entsize;
1564 	size_t locals = 1;
1565 	size_t strsize;
1566 
1567 	/*
1568 	 * Make a copy of the original module structure.
1569 	 */
1570 	omp = kobj_alloc(sizeof (struct module), KM_WAIT);
1571 	bcopy(mp, omp, sizeof (struct module));
1572 
1573 	/*
1574 	 * Compute the sizes of the new symbol table sections.
1575 	 */
1576 	for (nsyms = strsize = 1, osp = (Sym *)omp->symtbl; osp < esp; osp++) {
1577 		if (osp->st_value == 0)
1578 			continue;
1579 		if (sym_lookup(omp, osp) == NULL)
1580 			continue;
1581 		name = omp->strings + osp->st_name;
1582 		namelen = strlen(name);
1583 		if (ELF_ST_BIND(osp->st_info) == STB_LOCAL)
1584 			locals++;
1585 		nsyms++;
1586 		strsize += namelen + 1;
1587 	}
1588 
1589 	mp->nsyms = nsyms;
1590 	mp->hashsize = kobj_gethashsize(mp->nsyms);
1591 
1592 	/*
1593 	 * ksyms_lock must be held as writer during any operation that
1594 	 * modifies ksyms_arena, including allocation from same, and
1595 	 * must not be dropped until the arena is vmem_walk()able.
1596 	 */
1597 	rw_enter(&ksyms_lock, RW_WRITER);
1598 
1599 	/*
1600 	 * Allocate space for the new section headers (symtab and strtab),
1601 	 * symbol table, buckets, chains, and strings.
1602 	 */
1603 	mp->symsize = (2 * sizeof (Shdr)) + (nsyms * symsize) +
1604 	    (mp->hashsize + mp->nsyms) * sizeof (symid_t) + strsize;
1605 
1606 	if (mp->flags & KOBJ_NOKSYMS) {
1607 		mp->symspace = kobj_alloc(mp->symsize, KM_WAIT);
1608 	} else {
1609 		mp->symspace = vmem_alloc(ksyms_arena, mp->symsize,
1610 		    VM_BESTFIT | VM_SLEEP);
1611 	}
1612 	bzero(mp->symspace, mp->symsize);
1613 
1614 	/*
1615 	 * Divvy up symspace.
1616 	 */
1617 	mp->shdrs = mp->symspace;
1618 	mp->symhdr = (Shdr *)mp->shdrs;
1619 	mp->strhdr = (Shdr *)(mp->symhdr + 1);
1620 	mp->symtbl = (char *)(mp->strhdr + 1);
1621 	mp->buckets = (symid_t *)(mp->symtbl + (nsyms * symsize));
1622 	mp->chains = (symid_t *)(mp->buckets + mp->hashsize);
1623 	mp->strings = (char *)(mp->chains + nsyms);
1624 
1625 	/*
1626 	 * Fill in the new section headers (symtab and strtab).
1627 	 */
1628 	mp->shnum = 2;
1629 	mp->symtbl_section = 0;
1630 
1631 	mp->symhdr->sh_type = SHT_SYMTAB;
1632 	mp->symhdr->sh_addr = (Addr)mp->symtbl;
1633 	mp->symhdr->sh_size = nsyms * symsize;
1634 	mp->symhdr->sh_link = 1;
1635 	mp->symhdr->sh_info = locals;
1636 	mp->symhdr->sh_addralign = sizeof (Addr);
1637 	mp->symhdr->sh_entsize = symsize;
1638 
1639 	mp->strhdr->sh_type = SHT_STRTAB;
1640 	mp->strhdr->sh_addr = (Addr)mp->strings;
1641 	mp->strhdr->sh_size = strsize;
1642 	mp->strhdr->sh_addralign = 1;
1643 
1644 	/*
1645 	 * Construct the new symbol table.
1646 	 */
1647 	for (nsyms = strsize = 1, osp = (Sym *)omp->symtbl; osp < esp; osp++) {
1648 		if (osp->st_value == 0)
1649 			continue;
1650 		if (sym_lookup(omp, osp) == NULL)
1651 			continue;
1652 		name = omp->strings + osp->st_name;
1653 		namelen = strlen(name);
1654 		sp = (Sym *)(mp->symtbl + symsize * nsyms);
1655 		bcopy(osp, sp, symsize);
1656 		bcopy(name, mp->strings + strsize, namelen);
1657 		sp->st_name = strsize;
1658 		sym_insert(mp, name, nsyms);
1659 		nsyms++;
1660 		strsize += namelen + 1;
1661 	}
1662 
1663 	rw_exit(&ksyms_lock);
1664 
1665 	/*
1666 	 * Free the old section headers -- we'll never need them again.
1667 	 */
1668 	if (!(mp->flags & KOBJ_PRIM)) {
1669 		uint_t	shn;
1670 		Shdr	*shp;
1671 
1672 		for (shn = 1; shn < omp->shnum; shn++) {
1673 			shp = (Shdr *)(omp->shdrs + shn * omp->hdr.e_shentsize);
1674 			switch (shp->sh_type) {
1675 			case SHT_RELA:
1676 			case SHT_REL:
1677 				if (shp->sh_addr != 0) {
1678 					kobj_free((void *)shp->sh_addr,
1679 					    shp->sh_size);
1680 				}
1681 				break;
1682 			}
1683 		}
1684 		kobj_free(omp->shdrs, omp->hdr.e_shentsize * omp->shnum);
1685 	}
1686 	/*
1687 	 * Discard the old symbol table and our copy of the module strucure.
1688 	 */
1689 	if (!(mp->flags & KOBJ_PRIM))
1690 		kobj_free(omp->symspace, omp->symsize);
1691 	kobj_free(omp, sizeof (struct module));
1692 }
1693 
1694 static void
kobj_export_ctf(struct module * mp)1695 kobj_export_ctf(struct module *mp)
1696 {
1697 	char *data = mp->ctfdata;
1698 	size_t size = mp->ctfsize;
1699 
1700 	if (data != NULL) {
1701 		if (_moddebug & MODDEBUG_NOCTF) {
1702 			mp->ctfdata = NULL;
1703 			mp->ctfsize = 0;
1704 		} else {
1705 			mp->ctfdata = vmem_alloc(ctf_arena, size,
1706 			    VM_BESTFIT | VM_SLEEP);
1707 			bcopy(data, mp->ctfdata, size);
1708 		}
1709 
1710 		if (!(mp->flags & KOBJ_PRIM))
1711 			kobj_free(data, size);
1712 	}
1713 }
1714 
1715 void
kobj_export_module(struct module * mp)1716 kobj_export_module(struct module *mp)
1717 {
1718 	kobj_export_ksyms(mp);
1719 	kobj_export_ctf(mp);
1720 
1721 	mp->flags |= KOBJ_EXPORTED;
1722 }
1723 
1724 static int
process_dynamic(struct module * mp,char * dyndata,char * strdata)1725 process_dynamic(struct module *mp, char *dyndata, char *strdata)
1726 {
1727 	char *path = NULL, *depstr = NULL;
1728 	int allocsize = 0, osize = 0, nsize = 0;
1729 	char *libname, *tmp;
1730 	int lsize;
1731 	Dyn *dynp;
1732 
1733 	for (dynp = (Dyn *)dyndata; dynp && dynp->d_tag != DT_NULL; dynp++) {
1734 		switch (dynp->d_tag) {
1735 		case DT_NEEDED:
1736 			/*
1737 			 * Read the DT_NEEDED entries, expanding the macros they
1738 			 * contain (if any), and concatenating them into a
1739 			 * single space-separated dependency list.
1740 			 */
1741 			libname = (ulong_t)dynp->d_un.d_ptr + strdata;
1742 
1743 			if (strchr(libname, '$') != NULL) {
1744 				char *_lib;
1745 
1746 				if (path == NULL)
1747 					path = kobj_alloc(MAXPATHLEN, KM_WAIT);
1748 				if ((_lib = expand_libmacro(libname, path,
1749 				    path)) != NULL)
1750 					libname = _lib;
1751 				else {
1752 					_kobj_printf(ops, "krtld: "
1753 					    "process_dynamic: failed to expand "
1754 					    "%s\n", libname);
1755 				}
1756 			}
1757 
1758 			lsize = strlen(libname);
1759 			nsize += lsize;
1760 			if (nsize + 1 > allocsize) {
1761 				tmp = kobj_alloc(allocsize + MAXPATHLEN,
1762 				    KM_WAIT);
1763 				if (depstr != NULL) {
1764 					bcopy(depstr, tmp, osize);
1765 					kobj_free(depstr, allocsize);
1766 				}
1767 				depstr = tmp;
1768 				allocsize += MAXPATHLEN;
1769 			}
1770 			bcopy(libname, depstr + osize, lsize);
1771 			*(depstr + nsize) = ' '; /* separator */
1772 			nsize++;
1773 			osize = nsize;
1774 			break;
1775 
1776 		case DT_FLAGS_1:
1777 			if (dynp->d_un.d_val & DF_1_IGNMULDEF)
1778 				mp->flags |= KOBJ_IGNMULDEF;
1779 			if (dynp->d_un.d_val & DF_1_NOKSYMS)
1780 				mp->flags |= KOBJ_NOKSYMS;
1781 
1782 			break;
1783 		}
1784 	}
1785 
1786 	/*
1787 	 * finish up the depends string (if any)
1788 	 */
1789 	if (depstr != NULL) {
1790 		*(depstr + nsize - 1) = '\0'; /* overwrite separator w/term */
1791 		if (path != NULL)
1792 			kobj_free(path, MAXPATHLEN);
1793 
1794 		tmp = kobj_alloc(nsize, KM_WAIT);
1795 		bcopy(depstr, tmp, nsize);
1796 		kobj_free(depstr, allocsize);
1797 		depstr = tmp;
1798 
1799 		mp->depends_on = depstr;
1800 	}
1801 
1802 	return (0);
1803 }
1804 
1805 static int
do_dynamic(struct module * mp,struct _buf * file)1806 do_dynamic(struct module *mp, struct _buf *file)
1807 {
1808 	Shdr *dshp, *dstrp, *shp;
1809 	char *dyndata, *dstrdata;
1810 	int dshn, shn, rc;
1811 
1812 	/* find and validate the dynamic section (if any) */
1813 
1814 	for (dshp = NULL, shn = 1; shn < mp->shnum; shn++) {
1815 		shp = (Shdr *)(mp->shdrs + shn * mp->hdr.e_shentsize);
1816 		switch (shp->sh_type) {
1817 		case SHT_DYNAMIC:
1818 			if (dshp != NULL) {
1819 				_kobj_printf(ops, "krtld: get_dynamic: %s, ",
1820 				    mp->filename);
1821 				_kobj_printf(ops,
1822 				    "multiple dynamic sections\n");
1823 				return (-1);
1824 			} else {
1825 				dshp = shp;
1826 				dshn = shn;
1827 			}
1828 			break;
1829 		}
1830 	}
1831 
1832 	if (dshp == NULL)
1833 		return (0);
1834 
1835 	if (dshp->sh_link > mp->shnum) {
1836 		_kobj_printf(ops, "krtld: get_dynamic: %s, ", mp->filename);
1837 		_kobj_printf(ops, "no section for sh_link %d\n", dshp->sh_link);
1838 		return (-1);
1839 	}
1840 	dstrp = (Shdr *)(mp->shdrs + dshp->sh_link * mp->hdr.e_shentsize);
1841 
1842 	if (dstrp->sh_type != SHT_STRTAB) {
1843 		_kobj_printf(ops, "krtld: get_dynamic: %s, ", mp->filename);
1844 		_kobj_printf(ops, "sh_link not a string table for section %d\n",
1845 		    dshn);
1846 		return (-1);
1847 	}
1848 
1849 	/* read it from disk */
1850 
1851 	dyndata = kobj_alloc(dshp->sh_size, KM_WAIT|KM_TMP);
1852 	if (kobj_read_file(file, dyndata, dshp->sh_size, dshp->sh_offset) < 0) {
1853 		_kobj_printf(ops, "krtld: get_dynamic: %s, ", mp->filename);
1854 		_kobj_printf(ops, "error reading section %d\n", dshn);
1855 
1856 		kobj_free(dyndata, dshp->sh_size);
1857 		return (-1);
1858 	}
1859 
1860 	dstrdata = kobj_alloc(dstrp->sh_size, KM_WAIT|KM_TMP);
1861 	if (kobj_read_file(file, dstrdata, dstrp->sh_size,
1862 	    dstrp->sh_offset) < 0) {
1863 		_kobj_printf(ops, "krtld: get_dynamic: %s, ", mp->filename);
1864 		_kobj_printf(ops, "error reading section %d\n", dshp->sh_link);
1865 
1866 		kobj_free(dyndata, dshp->sh_size);
1867 		kobj_free(dstrdata, dstrp->sh_size);
1868 		return (-1);
1869 	}
1870 
1871 	/* pull the interesting pieces out */
1872 
1873 	rc = process_dynamic(mp, dyndata, dstrdata);
1874 
1875 	kobj_free(dyndata, dshp->sh_size);
1876 	kobj_free(dstrdata, dstrp->sh_size);
1877 
1878 	return (rc);
1879 }
1880 
1881 void
kobj_set_ctf(struct module * mp,caddr_t data,size_t size)1882 kobj_set_ctf(struct module *mp, caddr_t data, size_t size)
1883 {
1884 	if (!standalone) {
1885 		if (mp->ctfdata != NULL) {
1886 			if (vmem_contains(ctf_arena, mp->ctfdata,
1887 			    mp->ctfsize)) {
1888 				vmem_free(ctf_arena, mp->ctfdata, mp->ctfsize);
1889 			} else {
1890 				kobj_free(mp->ctfdata, mp->ctfsize);
1891 			}
1892 		}
1893 	}
1894 
1895 	/*
1896 	 * The order is very important here.  We need to make sure that
1897 	 * consumers, at any given instant, see a consistent state.  We'd
1898 	 * rather they see no CTF data than the address of one buffer and the
1899 	 * size of another.
1900 	 */
1901 	mp->ctfdata = NULL;
1902 	membar_producer();
1903 	mp->ctfsize = size;
1904 	mp->ctfdata = data;
1905 	membar_producer();
1906 }
1907 
1908 int
kobj_load_module(struct modctl * modp,int use_path)1909 kobj_load_module(struct modctl *modp, int use_path)
1910 {
1911 	char *filename = modp->mod_filename;
1912 	char *modname = modp->mod_modname;
1913 	int i;
1914 	int n;
1915 	struct _buf *file;
1916 	struct module *mp = NULL;
1917 #ifdef MODDIR_SUFFIX
1918 	int no_suffixdir_drv = 0;
1919 #endif
1920 
1921 	mp = kobj_zalloc(sizeof (struct module), KM_WAIT);
1922 
1923 	/*
1924 	 * We need to prevent kmdb's symbols from leaking into /dev/ksyms.
1925 	 * kmdb contains a bunch of symbols with well-known names, symbols
1926 	 * which will mask the real versions, thus causing no end of trouble
1927 	 * for mdb.
1928 	 */
1929 	if (strcmp(modp->mod_modname, "kmdbmod") == 0)
1930 		mp->flags |= KOBJ_NOKSYMS;
1931 
1932 	file = kobj_open_path(filename, use_path, 1);
1933 	if (file == (struct _buf *)-1) {
1934 #ifdef MODDIR_SUFFIX
1935 		file = kobj_open_path(filename, use_path, 0);
1936 #endif
1937 		if (file == (struct _buf *)-1) {
1938 			kobj_free(mp, sizeof (*mp));
1939 			goto bad;
1940 		}
1941 #ifdef MODDIR_SUFFIX
1942 		/*
1943 		 * There is no driver module in the ISA specific (suffix)
1944 		 * subdirectory but there is a module in the parent directory.
1945 		 */
1946 		if (strncmp(filename, "drv/", 4) == 0) {
1947 			no_suffixdir_drv = 1;
1948 		}
1949 #endif
1950 	}
1951 
1952 	mp->filename = kobj_alloc(strlen(file->_name) + 1, KM_WAIT);
1953 	(void) strcpy(mp->filename, file->_name);
1954 
1955 	if (kobj_load_elfhdr(file, mp) != 0) {
1956 		kobj_free(mp->filename, strlen(file->_name) + 1);
1957 		kobj_free(mp, sizeof (*mp));
1958 		goto bad;
1959 	}
1960 
1961 	for (i = 0; i < SELFMAG; i++) {
1962 		if (mp->hdr.e_ident[i] != ELFMAG[i]) {
1963 			if (_moddebug & MODDEBUG_ERRMSG)
1964 				_kobj_printf(ops, "%s not an elf module\n",
1965 				    modname);
1966 			kobj_free(mp->filename, strlen(file->_name) + 1);
1967 			kobj_free(mp, sizeof (*mp));
1968 			goto bad;
1969 		}
1970 	}
1971 	/*
1972 	 * It's ELF, but is it our ISA?  Interpreting the header
1973 	 * from a file for a byte-swapped ISA could cause a huge
1974 	 * and unsatisfiable value to be passed to kobj_alloc below
1975 	 * and therefore hang booting.
1976 	 */
1977 	if (!elf_mach_ok(&mp->hdr)) {
1978 		if (_moddebug & MODDEBUG_ERRMSG)
1979 			_kobj_printf(ops, "%s not an elf module for this ISA\n",
1980 			    modname);
1981 		kobj_free(mp->filename, strlen(file->_name) + 1);
1982 		kobj_free(mp, sizeof (*mp));
1983 #ifdef MODDIR_SUFFIX
1984 		/*
1985 		 * The driver mod is not in the ISA specific subdirectory
1986 		 * and the module in the parent directory is not our ISA.
1987 		 * If it is our ISA, for now we will silently succeed.
1988 		 */
1989 		if (no_suffixdir_drv == 1) {
1990 			cmn_err(CE_CONT, "?NOTICE: %s: 64-bit driver module"
1991 			    " not found\n", modname);
1992 		}
1993 #endif
1994 		goto bad;
1995 	}
1996 
1997 	/*
1998 	 * All modules, save for unix, should be relocatable (as opposed to
1999 	 * dynamic).  Dynamic modules come with PLTs and GOTs, which can't
2000 	 * currently be processed by krtld.
2001 	 */
2002 	if (mp->hdr.e_type != ET_REL) {
2003 		if (_moddebug & MODDEBUG_ERRMSG)
2004 			_kobj_printf(ops, "%s isn't a relocatable (ET_REL) "
2005 			    "module\n", modname);
2006 		kobj_free(mp->filename, strlen(file->_name) + 1);
2007 		kobj_free(mp, sizeof (*mp));
2008 		goto bad;
2009 	}
2010 
2011 	n = mp->hdr.e_shentsize * mp->shnum;
2012 	mp->shdrs = kobj_alloc(n, KM_WAIT);
2013 
2014 	if (kobj_read_file(file, mp->shdrs, n, mp->hdr.e_shoff) < 0) {
2015 		_kobj_printf(ops, "kobj_load_module: %s error reading "
2016 		    "section headers\n", modname);
2017 		kobj_free(mp->shdrs, n);
2018 		kobj_free(mp->filename, strlen(file->_name) + 1);
2019 		kobj_free(mp, sizeof (*mp));
2020 		goto bad;
2021 	}
2022 
2023 	kobj_notify(KOBJ_NOTIFY_MODLOADING, modp);
2024 	module_assign(modp, mp);
2025 
2026 	/* read in sections */
2027 	if (get_progbits(mp, file) < 0) {
2028 		_kobj_printf(ops, "%s error reading sections\n", modname);
2029 		goto bad;
2030 	}
2031 
2032 	if (do_dynamic(mp, file) < 0) {
2033 		_kobj_printf(ops, "%s error reading dynamic section\n",
2034 		    modname);
2035 		goto bad;
2036 	}
2037 
2038 	modp->mod_text = mp->text;
2039 	modp->mod_text_size = mp->text_size;
2040 
2041 	/* read in symbols; adjust values for each section's real address */
2042 	if (get_syms(mp, file) < 0) {
2043 		_kobj_printf(ops, "%s error reading symbols\n",
2044 		    modname);
2045 		goto bad;
2046 	}
2047 
2048 	/*
2049 	 * If we didn't dependency information from the dynamic section, look
2050 	 * for it the old-fashioned way.
2051 	 */
2052 	if (mp->depends_on == NULL)
2053 		mp->depends_on = depends_on(mp);
2054 
2055 	if (get_ctf(mp, file) < 0) {
2056 		_kobj_printf(ops, "%s debug information will not "
2057 		    "be available\n", modname);
2058 	}
2059 
2060 	/* primary kernel modules do not have a signature section */
2061 	if (!(mp->flags & KOBJ_PRIM))
2062 		get_signature(mp, file);
2063 
2064 #ifdef	KOBJ_DEBUG
2065 	if (kobj_debug & D_LOADING) {
2066 		_kobj_printf(ops, "krtld: file=%s\n", mp->filename);
2067 		_kobj_printf(ops, "\ttext:0x%p", mp->text);
2068 		_kobj_printf(ops, " size: 0x%lx\n", mp->text_size);
2069 		_kobj_printf(ops, "\tdata:0x%p", mp->data);
2070 		_kobj_printf(ops, " dsize: 0x%lx\n", mp->data_size);
2071 	}
2072 #endif /* KOBJ_DEBUG */
2073 
2074 	/*
2075 	 * For primary kernel modules, we defer
2076 	 * symbol resolution and relocation until
2077 	 * all primary objects have been loaded.
2078 	 */
2079 	if (!standalone) {
2080 		int ddrval, dcrval;
2081 		char *dependent_modname;
2082 		/* load all dependents */
2083 		dependent_modname = kobj_zalloc(MODMAXNAMELEN, KM_WAIT);
2084 		ddrval = do_dependents(modp, dependent_modname, MODMAXNAMELEN);
2085 
2086 		/*
2087 		 * resolve undefined and common symbols,
2088 		 * also allocates common space
2089 		 */
2090 		if ((dcrval = do_common(mp)) < 0) {
2091 			switch (dcrval) {
2092 			case DOSYM_UNSAFE:
2093 				_kobj_printf(ops, "WARNING: mod_load: "
2094 				    "MT-unsafe module '%s' rejected\n",
2095 				    modname);
2096 				break;
2097 			case DOSYM_UNDEF:
2098 				_kobj_printf(ops, "WARNING: mod_load: "
2099 				    "cannot load module '%s'\n",
2100 				    modname);
2101 				if (ddrval == -1) {
2102 					_kobj_printf(ops, "WARNING: %s: ",
2103 					    modname);
2104 					_kobj_printf(ops,
2105 					    "unable to resolve dependency, "
2106 					    "module '%s' not found\n",
2107 					    dependent_modname);
2108 				}
2109 				break;
2110 			}
2111 		}
2112 		kobj_free(dependent_modname, MODMAXNAMELEN);
2113 		if (dcrval < 0)
2114 			goto bad;
2115 
2116 		/* process relocation tables */
2117 		if (do_relocations(mp) < 0) {
2118 			_kobj_printf(ops, "%s error doing relocations\n",
2119 			    modname);
2120 			goto bad;
2121 		}
2122 
2123 		if (mp->destination) {
2124 			off_t	off = (uintptr_t)mp->destination & PAGEOFFSET;
2125 			caddr_t	base = (caddr_t)mp->destination - off;
2126 			size_t	size = P2ROUNDUP(mp->text_size + off, PAGESIZE);
2127 
2128 			hat_unload(kas.a_hat, base, size, HAT_UNLOAD_UNLOCK);
2129 			vmem_free(heap_arena, base, size);
2130 		}
2131 
2132 		/* sync_instruction_memory */
2133 		kobj_sync_instruction_memory(mp->text, mp->text_size);
2134 		kobj_export_module(mp);
2135 		kobj_notify(KOBJ_NOTIFY_MODLOADED, modp);
2136 	}
2137 	kobj_close_file(file);
2138 	return (0);
2139 bad:
2140 	if (file != (struct _buf *)-1)
2141 		kobj_close_file(file);
2142 	if (modp->mod_mp != NULL)
2143 		free_module_data(modp->mod_mp);
2144 
2145 	module_assign(modp, NULL);
2146 	return ((file == (struct _buf *)-1) ? ENOENT : EINVAL);
2147 }
2148 
2149 int
kobj_load_primary_module(struct modctl * modp)2150 kobj_load_primary_module(struct modctl *modp)
2151 {
2152 	struct modctl *dep;
2153 	struct module *mp;
2154 
2155 	if (kobj_load_module(modp, 0) != 0)
2156 		return (-1);
2157 
2158 	dep = NULL;
2159 	mp = modp->mod_mp;
2160 	mp->flags |= KOBJ_PRIM;
2161 
2162 	/* Bind new module to its dependents */
2163 	if (mp->depends_on != NULL && (dep =
2164 	    mod_already_loaded(mp->depends_on)) == NULL) {
2165 #ifdef	KOBJ_DEBUG
2166 		if (kobj_debug & D_DEBUG) {
2167 			_kobj_printf(ops, "krtld: failed to resolve deps "
2168 			    "for primary %s\n", modp->mod_modname);
2169 		}
2170 #endif
2171 		return (-1);
2172 	}
2173 
2174 	if (dep != NULL)
2175 		add_dependent(mp, dep->mod_mp);
2176 
2177 	/*
2178 	 * Relocate it.  This module may not be part of a link map, so we
2179 	 * can't use bind_primary.
2180 	 */
2181 	if (do_common(mp) < 0 || do_symbols(mp, 0) < 0 ||
2182 	    do_relocations(mp) < 0) {
2183 #ifdef	KOBJ_DEBUG
2184 		if (kobj_debug & D_DEBUG) {
2185 			_kobj_printf(ops, "krtld: failed to relocate "
2186 			    "primary %s\n", modp->mod_modname);
2187 		}
2188 #endif
2189 		return (-1);
2190 	}
2191 
2192 	return (0);
2193 }
2194 
2195 static void
module_assign(struct modctl * cp,struct module * mp)2196 module_assign(struct modctl *cp, struct module *mp)
2197 {
2198 	if (standalone) {
2199 		cp->mod_mp = mp;
2200 		return;
2201 	}
2202 	mutex_enter(&mod_lock);
2203 	cp->mod_mp = mp;
2204 	cp->mod_gencount++;
2205 	mutex_exit(&mod_lock);
2206 }
2207 
2208 void
kobj_unload_module(struct modctl * modp)2209 kobj_unload_module(struct modctl *modp)
2210 {
2211 	struct module *mp = modp->mod_mp;
2212 
2213 	if ((_moddebug & MODDEBUG_KEEPTEXT) && mp) {
2214 		_kobj_printf(ops, "text for %s ", mp->filename);
2215 		_kobj_printf(ops, "was at %p\n", mp->text);
2216 		mp->text = NULL;	/* don't actually free it */
2217 	}
2218 
2219 	kobj_notify(KOBJ_NOTIFY_MODUNLOADING, modp);
2220 
2221 	/*
2222 	 * Null out mod_mp first, so consumers (debuggers) know not to look
2223 	 * at the module structure any more.
2224 	 */
2225 	mutex_enter(&mod_lock);
2226 	modp->mod_mp = NULL;
2227 	mutex_exit(&mod_lock);
2228 
2229 	kobj_notify(KOBJ_NOTIFY_MODUNLOADED, modp);
2230 	free_module_data(mp);
2231 }
2232 
2233 static void
free_module_data(struct module * mp)2234 free_module_data(struct module *mp)
2235 {
2236 	struct module_list *lp, *tmp;
2237 	hotinline_desc_t *hid, *next;
2238 	int ksyms_exported = 0;
2239 
2240 	lp = mp->head;
2241 	while (lp) {
2242 		tmp = lp;
2243 		lp = lp->next;
2244 		kobj_free((char *)tmp, sizeof (*tmp));
2245 	}
2246 
2247 	/* release hotinlines */
2248 	hid = mp->hi_calls;
2249 	while (hid != NULL) {
2250 		next = hid->hid_next;
2251 		kobj_free(hid->hid_symname, strlen(hid->hid_symname) + 1);
2252 		kobj_free(hid, sizeof (hotinline_desc_t));
2253 		hid = next;
2254 	}
2255 
2256 	rw_enter(&ksyms_lock, RW_WRITER);
2257 	if (mp->symspace) {
2258 		if (vmem_contains(ksyms_arena, mp->symspace, mp->symsize)) {
2259 			vmem_free(ksyms_arena, mp->symspace, mp->symsize);
2260 			ksyms_exported = 1;
2261 		} else {
2262 			if (mp->flags & KOBJ_NOKSYMS)
2263 				ksyms_exported = 1;
2264 			kobj_free(mp->symspace, mp->symsize);
2265 		}
2266 	}
2267 	rw_exit(&ksyms_lock);
2268 
2269 	if (mp->ctfdata) {
2270 		if (vmem_contains(ctf_arena, mp->ctfdata, mp->ctfsize))
2271 			vmem_free(ctf_arena, mp->ctfdata, mp->ctfsize);
2272 		else
2273 			kobj_free(mp->ctfdata, mp->ctfsize);
2274 	}
2275 
2276 	if (mp->sigdata)
2277 		kobj_free(mp->sigdata, mp->sigsize);
2278 
2279 	/*
2280 	 * We did not get far enough into kobj_export_ksyms() to free allocated
2281 	 * buffers because we encounted error conditions. Free the buffers.
2282 	 */
2283 	if ((ksyms_exported == 0) && (mp->shdrs != NULL)) {
2284 		uint_t shn;
2285 		Shdr *shp;
2286 
2287 		for (shn = 1; shn < mp->shnum; shn++) {
2288 			shp = (Shdr *)(mp->shdrs + shn * mp->hdr.e_shentsize);
2289 			switch (shp->sh_type) {
2290 			case SHT_RELA:
2291 			case SHT_REL:
2292 				if (shp->sh_addr != 0)
2293 					kobj_free((void *)shp->sh_addr,
2294 					    shp->sh_size);
2295 				break;
2296 			}
2297 		}
2298 
2299 		if (!(mp->flags & KOBJ_PRIM)) {
2300 			kobj_free(mp->shdrs, mp->hdr.e_shentsize * mp->shnum);
2301 		}
2302 	}
2303 
2304 	if (mp->bss)
2305 		vmem_free(data_arena, (void *)mp->bss, mp->bss_size);
2306 
2307 	if (mp->fbt_tab)
2308 		kobj_texthole_free(mp->fbt_tab, mp->fbt_size);
2309 
2310 	if (mp->textwin_base)
2311 		kobj_textwin_free(mp);
2312 
2313 	if (mp->sdt_probes != NULL) {
2314 		sdt_probedesc_t *sdp = mp->sdt_probes, *next;
2315 
2316 		while (sdp != NULL) {
2317 			next = sdp->sdpd_next;
2318 			kobj_free(sdp->sdpd_name, strlen(sdp->sdpd_name) + 1);
2319 			kobj_free(sdp, sizeof (sdt_probedesc_t));
2320 			sdp = next;
2321 		}
2322 	}
2323 
2324 	if (mp->sdt_tab)
2325 		kobj_texthole_free(mp->sdt_tab, mp->sdt_size);
2326 	if (mp->text)
2327 		vmem_free(text_arena, mp->text, mp->text_size);
2328 	if (mp->data)
2329 		vmem_free(data_arena, mp->data, mp->data_size);
2330 	if (mp->depends_on)
2331 		kobj_free(mp->depends_on, strlen(mp->depends_on)+1);
2332 	if (mp->filename)
2333 		kobj_free(mp->filename, strlen(mp->filename)+1);
2334 
2335 	kobj_free((char *)mp, sizeof (*mp));
2336 }
2337 
2338 static int
get_progbits(struct module * mp,struct _buf * file)2339 get_progbits(struct module *mp, struct _buf *file)
2340 {
2341 	struct proginfo *tp, *dp, *sdp;
2342 	Shdr *shp;
2343 	reloc_dest_t dest = NULL;
2344 	uintptr_t bits_ptr;
2345 	uintptr_t text = 0, data, textptr;
2346 	uint_t shn;
2347 	int err = -1;
2348 
2349 	tp = kobj_zalloc(sizeof (struct proginfo), KM_WAIT|KM_TMP);
2350 	dp = kobj_zalloc(sizeof (struct proginfo), KM_WAIT|KM_TMP);
2351 	sdp = kobj_zalloc(sizeof (struct proginfo), KM_WAIT|KM_TMP);
2352 	/*
2353 	 * loop through sections to find out how much space we need
2354 	 * for text, data, (also bss that is already assigned)
2355 	 */
2356 	if (get_progbits_size(mp, tp, dp, sdp) < 0)
2357 		goto done;
2358 
2359 	mp->text_size = tp->size;
2360 	mp->data_size = dp->size;
2361 
2362 	if (standalone) {
2363 		caddr_t limit = _data;
2364 
2365 		if (lg_pagesize && _text + lg_pagesize < limit)
2366 			limit = _text + lg_pagesize;
2367 
2368 		mp->text = kobj_segbrk(&_etext, mp->text_size,
2369 		    tp->align, limit);
2370 		/*
2371 		 * If we can't grow the text segment, try the
2372 		 * data segment before failing.
2373 		 */
2374 		if (mp->text == NULL) {
2375 			mp->text = kobj_segbrk(&_edata, mp->text_size,
2376 			    tp->align, 0);
2377 		}
2378 
2379 		mp->data = kobj_segbrk(&_edata, mp->data_size, dp->align, 0);
2380 
2381 		if (mp->text == NULL || mp->data == NULL)
2382 			goto done;
2383 
2384 	} else {
2385 		if (text_arena == NULL)
2386 			kobj_vmem_init(&text_arena, &data_arena);
2387 
2388 		/*
2389 		 * some architectures may want to load the module on a
2390 		 * page that is currently read only. It may not be
2391 		 * possible for those architectures to remap their page
2392 		 * on the fly. So we provide a facility for them to hang
2393 		 * a private hook where the memory they assign the module
2394 		 * is not the actual place where the module loads.
2395 		 *
2396 		 * In this case there are two addresses that deal with the
2397 		 * modload.
2398 		 * 1) the final destination of the module
2399 		 * 2) the address that is used to view the newly
2400 		 * loaded module until all the relocations relative to 1
2401 		 * above are completed.
2402 		 *
2403 		 * That is what dest is used for below.
2404 		 */
2405 		mp->text_size += tp->align;
2406 		mp->data_size += dp->align;
2407 
2408 		mp->text = kobj_text_alloc(text_arena, mp->text_size);
2409 
2410 		/*
2411 		 * a remap is taking place. Align the text ptr relative
2412 		 * to the secondary mapping. That is where the bits will
2413 		 * be read in.
2414 		 */
2415 		if (kvseg.s_base != NULL && !vmem_contains(heaptext_arena,
2416 		    mp->text, mp->text_size)) {
2417 			off_t	off = (uintptr_t)mp->text & PAGEOFFSET;
2418 			size_t	size = P2ROUNDUP(mp->text_size + off, PAGESIZE);
2419 			caddr_t	map = vmem_alloc(heap_arena, size, VM_SLEEP);
2420 			caddr_t orig = mp->text - off;
2421 			pgcnt_t pages = size / PAGESIZE;
2422 
2423 			dest = (reloc_dest_t)(map + off);
2424 			text = ALIGN((uintptr_t)dest, tp->align);
2425 
2426 			while (pages--) {
2427 				hat_devload(kas.a_hat, map, PAGESIZE,
2428 				    hat_getpfnum(kas.a_hat, orig),
2429 				    PROT_READ | PROT_WRITE | PROT_EXEC,
2430 				    HAT_LOAD_NOCONSIST | HAT_LOAD_LOCK);
2431 				map += PAGESIZE;
2432 				orig += PAGESIZE;
2433 			}
2434 			/*
2435 			 * Since we set up a non-cacheable mapping, we need
2436 			 * to flush any old entries in the cache that might
2437 			 * be left around from the read-only mapping.
2438 			 */
2439 			dcache_flushall();
2440 		}
2441 		if (mp->data_size)
2442 			mp->data = vmem_alloc(data_arena, mp->data_size,
2443 			    VM_SLEEP | VM_BESTFIT);
2444 	}
2445 	textptr = (uintptr_t)mp->text;
2446 	textptr = ALIGN(textptr, tp->align);
2447 	mp->destination = dest;
2448 
2449 	/*
2450 	 * This is the case where a remap is not being done.
2451 	 */
2452 	if (text == 0)
2453 		text = ALIGN((uintptr_t)mp->text, tp->align);
2454 	data = ALIGN((uintptr_t)mp->data, dp->align);
2455 
2456 	/* now loop though sections assigning addresses and loading the data */
2457 	for (shn = 1; shn < mp->shnum; shn++) {
2458 		shp = (Shdr *)(mp->shdrs + shn * mp->hdr.e_shentsize);
2459 		if (!(shp->sh_flags & SHF_ALLOC))
2460 			continue;
2461 
2462 		if ((shp->sh_flags & SHF_WRITE) == 0)
2463 			bits_ptr = text;
2464 		else
2465 			bits_ptr = data;
2466 
2467 		bits_ptr = ALIGN(bits_ptr, shp->sh_addralign);
2468 
2469 		if (shp->sh_type == SHT_NOBITS) {
2470 			/*
2471 			 * Zero bss.
2472 			 */
2473 			bzero((caddr_t)bits_ptr, shp->sh_size);
2474 			shp->sh_type = SHT_PROGBITS;
2475 		} else {
2476 			if (kobj_read_file(file, (char *)bits_ptr,
2477 			    shp->sh_size, shp->sh_offset) < 0)
2478 				goto done;
2479 		}
2480 
2481 		if (shp->sh_flags & SHF_WRITE) {
2482 			shp->sh_addr = bits_ptr;
2483 		} else {
2484 			textptr = ALIGN(textptr, shp->sh_addralign);
2485 			shp->sh_addr = textptr;
2486 			textptr += shp->sh_size;
2487 		}
2488 
2489 		bits_ptr += shp->sh_size;
2490 		if ((shp->sh_flags & SHF_WRITE) == 0)
2491 			text = bits_ptr;
2492 		else
2493 			data = bits_ptr;
2494 	}
2495 
2496 	err = 0;
2497 done:
2498 	/*
2499 	 * Free and mark as freed the section headers here so that
2500 	 * free_module_data() does not have to worry about this buffer.
2501 	 *
2502 	 * This buffer is freed here because one of the possible reasons
2503 	 * for error is a section with non-zero sh_addr and in that case
2504 	 * free_module_data() would have no way of recognizing that this
2505 	 * buffer was unallocated.
2506 	 */
2507 	if (err != 0) {
2508 		kobj_free(mp->shdrs, mp->hdr.e_shentsize * mp->shnum);
2509 		mp->shdrs = NULL;
2510 	}
2511 
2512 	(void) kobj_free(tp, sizeof (struct proginfo));
2513 	(void) kobj_free(dp, sizeof (struct proginfo));
2514 	(void) kobj_free(sdp, sizeof (struct proginfo));
2515 
2516 	return (err);
2517 }
2518 
2519 /*
2520  * Go through suppress_sym_list to see if "multiply defined"
2521  * warning of this symbol should be suppressed.  Return 1 if
2522  * warning should be suppressed, 0 otherwise.
2523  */
2524 static int
kobj_suppress_warning(char * symname)2525 kobj_suppress_warning(char *symname)
2526 {
2527 	int	i;
2528 
2529 	for (i = 0; suppress_sym_list[i] != NULL; i++) {
2530 		if (strcmp(suppress_sym_list[i], symname) == 0)
2531 			return (1);
2532 	}
2533 
2534 	return (0);
2535 }
2536 
2537 static int
get_syms(struct module * mp,struct _buf * file)2538 get_syms(struct module *mp, struct _buf *file)
2539 {
2540 	uint_t		shn;
2541 	Shdr		*shp;
2542 	uint_t		i;
2543 	Sym		*sp, *ksp;
2544 	Shdr		*symxhdr = NULL;
2545 	Elf32_Word	*symxtbl = NULL;
2546 	char		*symname;
2547 	int		dosymtab = 0;
2548 	int		err = -1;
2549 
2550 	/*
2551 	 * Find the interesting sections.
2552 	 */
2553 	for (shn = 1; shn < mp->shnum; shn++) {
2554 		shp = (Shdr *)(mp->shdrs + shn * mp->hdr.e_shentsize);
2555 		switch (shp->sh_type) {
2556 		case SHT_SYMTAB:
2557 			mp->symtbl_section = shn;
2558 			mp->symhdr = shp;
2559 			dosymtab++;
2560 			break;
2561 
2562 		case SHT_SYMTAB_SHNDX:
2563 			symxhdr = shp;
2564 			break;
2565 
2566 		case SHT_RELA:
2567 		case SHT_REL:
2568 			/*
2569 			 * Already loaded.
2570 			 */
2571 			if (shp->sh_addr)
2572 				continue;
2573 
2574 			/* KM_TMP since kobj_free'd in do_relocations */
2575 			shp->sh_addr = (Addr)
2576 			    kobj_alloc(shp->sh_size, KM_WAIT|KM_TMP);
2577 
2578 			if (kobj_read_file(file, (char *)shp->sh_addr,
2579 			    shp->sh_size, shp->sh_offset) < 0) {
2580 				_kobj_printf(ops, "krtld: get_syms: %s, ",
2581 				    mp->filename);
2582 				_kobj_printf(ops, "error reading section %d\n",
2583 				    shn);
2584 				return (-1);
2585 			}
2586 			break;
2587 		}
2588 	}
2589 
2590 	/*
2591 	 * This is true for a stripped executable.  In the case of
2592 	 * 'unix' it can be stripped but it still contains the SHT_DYNSYM,
2593 	 * and since that symbol information is still present everything
2594 	 * is just fine.
2595 	 */
2596 	if (!dosymtab) {
2597 		if (mp->flags & KOBJ_EXEC)
2598 			return (0);
2599 		_kobj_printf(ops, "krtld: get_syms: %s ",
2600 		    mp->filename);
2601 		_kobj_printf(ops, "no SHT_SYMTAB symbol table found\n");
2602 		return (-1);
2603 	}
2604 
2605 	/*
2606 	 * get the associated string table header
2607 	 */
2608 	if (mp->symhdr == NULL || mp->symhdr->sh_link >= mp->shnum)
2609 		return (-1);
2610 	mp->strhdr = (Shdr *)
2611 	    (mp->shdrs + mp->symhdr->sh_link * mp->hdr.e_shentsize);
2612 
2613 	mp->nsyms = mp->symhdr->sh_size / mp->symhdr->sh_entsize;
2614 	mp->hashsize = kobj_gethashsize(mp->nsyms);
2615 
2616 	/*
2617 	 * Allocate space for the symbol table, buckets, chains, and strings.
2618 	 */
2619 	mp->symsize = mp->symhdr->sh_size +
2620 	    (mp->hashsize + mp->nsyms) * sizeof (symid_t) + mp->strhdr->sh_size;
2621 	mp->symspace = kobj_zalloc(mp->symsize, KM_WAIT|KM_SCRATCH);
2622 
2623 	mp->symtbl = mp->symspace;
2624 	mp->buckets = (symid_t *)(mp->symtbl + mp->symhdr->sh_size);
2625 	mp->chains = mp->buckets + mp->hashsize;
2626 	mp->strings = (char *)(mp->chains + mp->nsyms);
2627 
2628 	if (kobj_read_file(file, mp->symtbl,
2629 	    mp->symhdr->sh_size, mp->symhdr->sh_offset) < 0) {
2630 		_kobj_printf(ops, "%s failed to read symbol table\n",
2631 		    file->_name);
2632 		return (-1);
2633 	}
2634 	if (kobj_read_file(file, mp->strings,
2635 	    mp->strhdr->sh_size, mp->strhdr->sh_offset) < 0) {
2636 		_kobj_printf(ops, "%s failed to read string table\n",
2637 		    file->_name);
2638 		return (-1);
2639 	}
2640 
2641 	if (symxhdr != NULL) {
2642 		symxtbl = kobj_zalloc(symxhdr->sh_size, KM_WAIT|KM_SCRATCH);
2643 		if (kobj_read_file(file, (char *)symxtbl, symxhdr->sh_size,
2644 		    symxhdr->sh_offset) < 0) {
2645 			_kobj_printf(ops,
2646 			    "%s failed to read symbol shndx table\n",
2647 			    file->_name);
2648 			goto out;
2649 		}
2650 	}
2651 
2652 	/*
2653 	 * loop through the symbol table adjusting values to account
2654 	 * for where each section got loaded into memory.  Also
2655 	 * fill in the hash table.
2656 	 */
2657 	for (i = 1; i < mp->nsyms; i++) {
2658 		Elf32_Word shndx;
2659 
2660 		sp = (Sym *)(mp->symtbl + i * mp->symhdr->sh_entsize);
2661 
2662 		/*
2663 		 * If the section header value is the sentinel value SHN_XINDEX
2664 		 * and we found a SHT_SYMTAB_SHNDX section, look up the
2665 		 * real index from there.
2666 		 */
2667 		shndx = sp->st_shndx;
2668 		if (shndx == SHN_XINDEX && symxhdr != NULL) {
2669 			if (i * sizeof (Elf32_Word) >= symxhdr->sh_size) {
2670 				_kobj_printf(ops,
2671 				    "%s extended shndx out of range ",
2672 				    file->_name);
2673 				_kobj_printf(ops, "in symbol %d\n", i);
2674 				goto out;
2675 			}
2676 			shndx = symxtbl[i];
2677 		}
2678 
2679 		if (shndx < SHN_LORESERVE) {
2680 			if (shndx >= mp->shnum) {
2681 				_kobj_printf(ops, "%s bad shndx ",
2682 				    file->_name);
2683 				_kobj_printf(ops, "in symbol %d\n", i);
2684 				goto out;
2685 			}
2686 			shp = (Shdr *)(mp->shdrs + shndx * mp->hdr.e_shentsize);
2687 			if (!(mp->flags & KOBJ_EXEC))
2688 				sp->st_value += shp->sh_addr;
2689 		}
2690 
2691 		if (sp->st_name == 0 || shndx == SHN_UNDEF)
2692 			continue;
2693 		if (sp->st_name >= mp->strhdr->sh_size)
2694 			goto out;
2695 
2696 		symname = mp->strings + sp->st_name;
2697 
2698 		if (!(mp->flags & KOBJ_EXEC) &&
2699 		    ELF_ST_BIND(sp->st_info) == STB_GLOBAL) {
2700 			ksp = kobj_lookup_all(mp, symname, 0);
2701 
2702 			if (ksp && ELF_ST_BIND(ksp->st_info) == STB_GLOBAL &&
2703 			    !kobj_suppress_warning(symname) &&
2704 			    sp->st_shndx != SHN_UNDEF &&
2705 			    sp->st_shndx != SHN_COMMON &&
2706 			    ksp->st_shndx != SHN_UNDEF &&
2707 			    ksp->st_shndx != SHN_COMMON) {
2708 				/*
2709 				 * Unless this symbol is a stub, it's multiply
2710 				 * defined.  Multiply-defined symbols are
2711 				 * usually bad, but some objects (kmdb) have
2712 				 * a legitimate need to have their own
2713 				 * copies of common functions.
2714 				 */
2715 				if ((standalone ||
2716 				    ksp->st_value < (uintptr_t)stubs_base ||
2717 				    ksp->st_value >= (uintptr_t)stubs_end) &&
2718 				    !(mp->flags & KOBJ_IGNMULDEF)) {
2719 					_kobj_printf(ops,
2720 					    "%s symbol ", file->_name);
2721 					_kobj_printf(ops,
2722 					    "%s multiply defined\n", symname);
2723 				}
2724 			}
2725 		}
2726 
2727 		sym_insert(mp, symname, i);
2728 	}
2729 
2730 	err = 0;
2731 
2732 out:
2733 	if (symxhdr != NULL)
2734 		kobj_free(symxtbl, symxhdr->sh_size);
2735 
2736 	return (err);
2737 }
2738 
2739 static int
get_ctf(struct module * mp,struct _buf * file)2740 get_ctf(struct module *mp, struct _buf *file)
2741 {
2742 	char *shstrtab, *ctfdata;
2743 	size_t shstrlen;
2744 	Shdr *shp;
2745 	uint_t i;
2746 
2747 	if (_moddebug & MODDEBUG_NOCTF)
2748 		return (0); /* do not attempt to even load CTF data */
2749 
2750 	if (mp->shstrndx >= mp->shnum) {
2751 		_kobj_printf(ops, "krtld: get_ctf: %s, ",
2752 		    mp->filename);
2753 		_kobj_printf(ops, "corrupt shstrndx %u\n",
2754 		    mp->shstrndx);
2755 		return (-1);
2756 	}
2757 
2758 	shp = (Shdr *)(mp->shdrs + mp->shstrndx * mp->hdr.e_shentsize);
2759 	shstrlen = shp->sh_size;
2760 	shstrtab = kobj_alloc(shstrlen, KM_WAIT|KM_TMP);
2761 
2762 	if (kobj_read_file(file, shstrtab, shstrlen, shp->sh_offset) < 0) {
2763 		_kobj_printf(ops, "krtld: get_ctf: %s, ",
2764 		    mp->filename);
2765 		_kobj_printf(ops, "error reading section %u\n",
2766 		    mp->shstrndx);
2767 		kobj_free(shstrtab, shstrlen);
2768 		return (-1);
2769 	}
2770 
2771 	for (i = 0; i < mp->shnum; i++) {
2772 		shp = (Shdr *)(mp->shdrs + i * mp->hdr.e_shentsize);
2773 
2774 		if (shp->sh_size != 0 && shp->sh_name < shstrlen &&
2775 		    strcmp(shstrtab + shp->sh_name, ".SUNW_ctf") == 0) {
2776 			ctfdata = kobj_alloc(shp->sh_size, KM_WAIT|KM_SCRATCH);
2777 
2778 			if (kobj_read_file(file, ctfdata, shp->sh_size,
2779 			    shp->sh_offset) < 0) {
2780 				_kobj_printf(ops, "krtld: get_ctf: %s, error "
2781 				    "reading .SUNW_ctf data\n", mp->filename);
2782 				kobj_free(ctfdata, shp->sh_size);
2783 				kobj_free(shstrtab, shstrlen);
2784 				return (-1);
2785 			}
2786 
2787 			mp->ctfdata = ctfdata;
2788 			mp->ctfsize = shp->sh_size;
2789 			break;
2790 		}
2791 	}
2792 
2793 	kobj_free(shstrtab, shstrlen);
2794 	return (0);
2795 }
2796 
2797 #define	SHA1_DIGEST_LENGTH	20	/* SHA1 digest length in bytes */
2798 
2799 /*
2800  * Return the hash of the ELF sections that are memory resident.
2801  * i.e. text and data.  We skip a SHT_NOBITS section since it occupies
2802  * no space in the file. We use SHA1 here since libelfsign uses
2803  * it and both places need to use the same algorithm.
2804  */
2805 static void
crypto_es_hash(struct module * mp,char * hash,char * shstrtab)2806 crypto_es_hash(struct module *mp, char *hash, char *shstrtab)
2807 {
2808 	uint_t shn;
2809 	Shdr *shp;
2810 	SHA1_CTX ctx;
2811 
2812 	SHA1Init(&ctx);
2813 
2814 	for (shn = 1; shn < mp->shnum; shn++) {
2815 		shp = (Shdr *)(mp->shdrs + shn * mp->hdr.e_shentsize);
2816 		if (!(shp->sh_flags & SHF_ALLOC) || shp->sh_size == 0)
2817 			continue;
2818 
2819 		/*
2820 		 * The check should ideally be shp->sh_type == SHT_NOBITS.
2821 		 * However, we can't do that check here as get_progbits()
2822 		 * resets the type.
2823 		 */
2824 		if (strcmp(shstrtab + shp->sh_name, ".bss") == 0)
2825 			continue;
2826 #ifdef	KOBJ_DEBUG
2827 		if (kobj_debug & D_DEBUG)
2828 			_kobj_printf(ops,
2829 			    "krtld: crypto_es_hash: updating hash with"
2830 			    " %s data size=%lx\n", shstrtab + shp->sh_name,
2831 			    (size_t)shp->sh_size);
2832 #endif
2833 		ASSERT(shp->sh_addr != 0);
2834 		SHA1Update(&ctx, (const uint8_t *)shp->sh_addr, shp->sh_size);
2835 	}
2836 
2837 	SHA1Final((uchar_t *)hash, &ctx);
2838 }
2839 
2840 /*
2841  * Get the .SUNW_signature section for the module, it it exists.
2842  *
2843  * This section exists only for crypto modules. None of the
2844  * primary modules have this section currently.
2845  */
2846 static void
get_signature(struct module * mp,struct _buf * file)2847 get_signature(struct module *mp, struct _buf *file)
2848 {
2849 	char *shstrtab, *sigdata = NULL;
2850 	size_t shstrlen;
2851 	Shdr *shp;
2852 	uint_t i;
2853 
2854 	if (mp->shstrndx >= mp->shnum) {
2855 		_kobj_printf(ops, "krtld: get_signature: %s, ",
2856 		    mp->filename);
2857 		_kobj_printf(ops, "corrupt shstrndx %u\n",
2858 		    mp->shstrndx);
2859 		return;
2860 	}
2861 
2862 	shp = (Shdr *)(mp->shdrs + mp->shstrndx * mp->hdr.e_shentsize);
2863 	shstrlen = shp->sh_size;
2864 	shstrtab = kobj_alloc(shstrlen, KM_WAIT|KM_TMP);
2865 
2866 	if (kobj_read_file(file, shstrtab, shstrlen, shp->sh_offset) < 0) {
2867 		_kobj_printf(ops, "krtld: get_signature: %s, ",
2868 		    mp->filename);
2869 		_kobj_printf(ops, "error reading section %u\n",
2870 		    mp->shstrndx);
2871 		kobj_free(shstrtab, shstrlen);
2872 		return;
2873 	}
2874 
2875 	for (i = 0; i < mp->shnum; i++) {
2876 		shp = (Shdr *)(mp->shdrs + i * mp->hdr.e_shentsize);
2877 		if (shp->sh_size != 0 && shp->sh_name < shstrlen &&
2878 		    strcmp(shstrtab + shp->sh_name,
2879 		    ELF_SIGNATURE_SECTION) == 0) {
2880 			filesig_vers_t filesig_version;
2881 			size_t sigsize = shp->sh_size + SHA1_DIGEST_LENGTH;
2882 			sigdata = kobj_alloc(sigsize, KM_WAIT|KM_SCRATCH);
2883 
2884 			if (kobj_read_file(file, sigdata, shp->sh_size,
2885 			    shp->sh_offset) < 0) {
2886 				_kobj_printf(ops, "krtld: get_signature: %s,"
2887 				    " error reading .SUNW_signature data\n",
2888 				    mp->filename);
2889 				kobj_free(sigdata, sigsize);
2890 				kobj_free(shstrtab, shstrlen);
2891 				return;
2892 			}
2893 			filesig_version = ((struct filesignatures *)sigdata)->
2894 			    filesig_sig.filesig_version;
2895 			if (!(filesig_version == FILESIG_VERSION1 ||
2896 			    filesig_version == FILESIG_VERSION3)) {
2897 				/* skip versions we don't understand */
2898 				kobj_free(sigdata, sigsize);
2899 				kobj_free(shstrtab, shstrlen);
2900 				return;
2901 			}
2902 
2903 			mp->sigdata = sigdata;
2904 			mp->sigsize = sigsize;
2905 			break;
2906 		}
2907 	}
2908 
2909 	if (sigdata != NULL) {
2910 		crypto_es_hash(mp, sigdata + shp->sh_size, shstrtab);
2911 	}
2912 
2913 	kobj_free(shstrtab, shstrlen);
2914 }
2915 
2916 static void
add_dependent(struct module * mp,struct module * dep)2917 add_dependent(struct module *mp, struct module *dep)
2918 {
2919 	struct module_list *lp;
2920 
2921 	for (lp = mp->head; lp; lp = lp->next) {
2922 		if (lp->mp == dep)
2923 			return;	/* already on the list */
2924 	}
2925 
2926 	if (lp == NULL) {
2927 		lp = kobj_zalloc(sizeof (*lp), KM_WAIT);
2928 
2929 		lp->mp = dep;
2930 		lp->next = NULL;
2931 		if (mp->tail)
2932 			mp->tail->next = lp;
2933 		else
2934 			mp->head = lp;
2935 		mp->tail = lp;
2936 	}
2937 }
2938 
2939 static int
do_dependents(struct modctl * modp,char * modname,size_t modnamelen)2940 do_dependents(struct modctl *modp, char *modname, size_t modnamelen)
2941 {
2942 	struct module *mp;
2943 	struct modctl *req;
2944 	char *d, *p, *q;
2945 	int c;
2946 	char *err_modname = NULL;
2947 
2948 	mp = modp->mod_mp;
2949 
2950 	if ((p = mp->depends_on) == NULL)
2951 		return (0);
2952 
2953 	for (;;) {
2954 		/*
2955 		 * Skip space.
2956 		 */
2957 		while (*p && (*p == ' ' || *p == '\t'))
2958 			p++;
2959 		/*
2960 		 * Get module name.
2961 		 */
2962 		d = p;
2963 		q = modname;
2964 		c = 0;
2965 		while (*p && *p != ' ' && *p != '\t') {
2966 			if (c < modnamelen - 1) {
2967 				*q++ = *p;
2968 				c++;
2969 			}
2970 			p++;
2971 		}
2972 
2973 		if (q == modname)
2974 			break;
2975 
2976 		if (c == modnamelen - 1) {
2977 			char *dep = kobj_alloc(p - d + 1, KM_WAIT|KM_TMP);
2978 
2979 			(void) strncpy(dep, d,  p - d + 1);
2980 			dep[p - d] = '\0';
2981 
2982 			_kobj_printf(ops, "%s: dependency ", modp->mod_modname);
2983 			_kobj_printf(ops, "'%s' too long ", dep);
2984 			_kobj_printf(ops, "(max %d chars)\n", (int)modnamelen);
2985 
2986 			kobj_free(dep, p - d + 1);
2987 
2988 			return (-1);
2989 		}
2990 
2991 		*q = '\0';
2992 		if ((req = mod_load_requisite(modp, modname)) == NULL) {
2993 #ifndef	KOBJ_DEBUG
2994 			if (_moddebug & MODDEBUG_LOADMSG) {
2995 #endif	/* KOBJ_DEBUG */
2996 				_kobj_printf(ops,
2997 				    "%s: unable to resolve dependency, ",
2998 				    modp->mod_modname);
2999 				_kobj_printf(ops, "cannot load module '%s'\n",
3000 				    modname);
3001 #ifndef	KOBJ_DEBUG
3002 			}
3003 #endif	/* KOBJ_DEBUG */
3004 			if (err_modname == NULL) {
3005 				/*
3006 				 * This must be the same size as the modname
3007 				 * one.
3008 				 */
3009 				err_modname = kobj_zalloc(MODMAXNAMELEN,
3010 				    KM_WAIT);
3011 
3012 				/*
3013 				 * We can use strcpy() here without fearing
3014 				 * the NULL terminator because the size of
3015 				 * err_modname is the same as one of modname,
3016 				 * and it's filled with zeros.
3017 				 */
3018 				(void) strcpy(err_modname, modname);
3019 			}
3020 			continue;
3021 		}
3022 
3023 		add_dependent(mp, req->mod_mp);
3024 		mod_release_mod(req);
3025 
3026 	}
3027 
3028 	if (err_modname != NULL) {
3029 		/*
3030 		 * Copy the first module name where you detect an error to keep
3031 		 * its behavior the same as before.
3032 		 * This way keeps minimizing the memory use for error
3033 		 * modules, and this might be important at boot time because
3034 		 * the memory usage is a crucial factor for booting in most
3035 		 * cases. You can expect more verbose messages when using
3036 		 * a debug kernel or setting a bit in moddebug.
3037 		 */
3038 		bzero(modname, MODMAXNAMELEN);
3039 		(void) strcpy(modname, err_modname);
3040 		kobj_free(err_modname, MODMAXNAMELEN);
3041 		return (-1);
3042 	}
3043 
3044 	return (0);
3045 }
3046 
3047 static int
do_common(struct module * mp)3048 do_common(struct module *mp)
3049 {
3050 	int err;
3051 
3052 	/*
3053 	 * first time through, assign all symbols defined in other
3054 	 * modules, and count up how much common space will be needed
3055 	 * (bss_size and bss_align)
3056 	 */
3057 	if ((err = do_symbols(mp, 0)) < 0)
3058 		return (err);
3059 	/*
3060 	 * increase bss_size by the maximum delta that could be
3061 	 * computed by the ALIGN below
3062 	 */
3063 	mp->bss_size += mp->bss_align;
3064 	if (mp->bss_size) {
3065 		if (standalone)
3066 			mp->bss = (uintptr_t)kobj_segbrk(&_edata, mp->bss_size,
3067 			    MINALIGN, 0);
3068 		else
3069 			mp->bss = (uintptr_t)vmem_alloc(data_arena,
3070 			    mp->bss_size, VM_SLEEP | VM_BESTFIT);
3071 		bzero((void *)mp->bss, mp->bss_size);
3072 		/* now assign addresses to all common symbols */
3073 		if ((err = do_symbols(mp, ALIGN(mp->bss, mp->bss_align))) < 0)
3074 			return (err);
3075 	}
3076 	return (0);
3077 }
3078 
3079 static int
do_symbols(struct module * mp,Elf64_Addr bss_base)3080 do_symbols(struct module *mp, Elf64_Addr bss_base)
3081 {
3082 	int bss_align;
3083 	uintptr_t bss_ptr;
3084 	int err;
3085 	int i;
3086 	Sym *sp, *sp1;
3087 	char *name;
3088 	int assign;
3089 	int resolved = 1;
3090 
3091 	/*
3092 	 * Nothing left to do (optimization).
3093 	 */
3094 	if (mp->flags & KOBJ_RESOLVED)
3095 		return (0);
3096 
3097 	assign = (bss_base) ? 1 : 0;
3098 	bss_ptr = bss_base;
3099 	bss_align = 0;
3100 	err = 0;
3101 
3102 	for (i = 1; i < mp->nsyms; i++) {
3103 		sp = (Sym *)(mp->symtbl + mp->symhdr->sh_entsize * i);
3104 		/*
3105 		 * we know that st_name is in bounds, since get_sections
3106 		 * has already checked all of the symbols
3107 		 */
3108 		name = mp->strings + sp->st_name;
3109 		if (sp->st_shndx != SHN_UNDEF && sp->st_shndx != SHN_COMMON)
3110 			continue;
3111 #if defined(__sparc)
3112 		/*
3113 		 * Register symbols are ignored in the kernel
3114 		 */
3115 		if (ELF_ST_TYPE(sp->st_info) == STT_SPARC_REGISTER) {
3116 			if (*name != '\0') {
3117 				_kobj_printf(ops, "%s: named REGISTER symbol ",
3118 				    mp->filename);
3119 				_kobj_printf(ops, "not supported '%s'\n",
3120 				    name);
3121 				err = DOSYM_UNDEF;
3122 			}
3123 			continue;
3124 		}
3125 #endif	/* __sparc */
3126 		/*
3127 		 * TLS symbols are ignored in the kernel
3128 		 */
3129 		if (ELF_ST_TYPE(sp->st_info) == STT_TLS) {
3130 			_kobj_printf(ops, "%s: TLS symbol ",
3131 			    mp->filename);
3132 			_kobj_printf(ops, "not supported '%s'\n",
3133 			    name);
3134 			err = DOSYM_UNDEF;
3135 			continue;
3136 		}
3137 
3138 		if (ELF_ST_BIND(sp->st_info) != STB_LOCAL) {
3139 			if ((sp1 = kobj_lookup_all(mp, name, 0)) != NULL) {
3140 				sp->st_shndx = SHN_ABS;
3141 				sp->st_value = sp1->st_value;
3142 				continue;
3143 			}
3144 		}
3145 
3146 		if (sp->st_shndx == SHN_UNDEF) {
3147 			resolved = 0;
3148 
3149 			/*
3150 			 * Skip over sdt probes and smap calls,
3151 			 * they're relocated later.
3152 			 */
3153 			if (strncmp(name, sdt_prefix, strlen(sdt_prefix)) == 0)
3154 				continue;
3155 #if defined(__x86)
3156 			if (strcmp(name, "smap_enable") == 0 ||
3157 			    strcmp(name, "smap_disable") == 0)
3158 				continue;
3159 #endif /* defined(__x86) */
3160 
3161 
3162 			/*
3163 			 * If it's not a weak reference and it's
3164 			 * not a primary object, it's an error.
3165 			 * (Primary objects may take more than
3166 			 * one pass to resolve)
3167 			 */
3168 			if (!(mp->flags & KOBJ_PRIM) &&
3169 			    ELF_ST_BIND(sp->st_info) != STB_WEAK) {
3170 				_kobj_printf(ops, "%s: undefined symbol",
3171 				    mp->filename);
3172 				_kobj_printf(ops, " '%s'\n", name);
3173 				/*
3174 				 * Try to determine whether this symbol
3175 				 * represents a dependency on obsolete
3176 				 * unsafe driver support.  This is just
3177 				 * to make the warning more informative.
3178 				 */
3179 				if (strcmp(name, "sleep") == 0 ||
3180 				    strcmp(name, "unsleep") == 0 ||
3181 				    strcmp(name, "wakeup") == 0 ||
3182 				    strcmp(name, "bsd_compat_ioctl") == 0 ||
3183 				    strcmp(name, "unsafe_driver") == 0 ||
3184 				    strncmp(name, "spl", 3) == 0 ||
3185 				    strncmp(name, "i_ddi_spl", 9) == 0)
3186 					err = DOSYM_UNSAFE;
3187 				if (err == 0)
3188 					err = DOSYM_UNDEF;
3189 			}
3190 			continue;
3191 		}
3192 		/*
3193 		 * It's a common symbol - st_value is the
3194 		 * required alignment.
3195 		 */
3196 		if (sp->st_value > bss_align)
3197 			bss_align = sp->st_value;
3198 		bss_ptr = ALIGN(bss_ptr, sp->st_value);
3199 		if (assign) {
3200 			sp->st_shndx = SHN_ABS;
3201 			sp->st_value = bss_ptr;
3202 		}
3203 		bss_ptr += sp->st_size;
3204 	}
3205 	if (err)
3206 		return (err);
3207 	if (assign == 0 && mp->bss == 0) {
3208 		mp->bss_align = bss_align;
3209 		mp->bss_size = bss_ptr;
3210 	} else if (resolved) {
3211 		mp->flags |= KOBJ_RESOLVED;
3212 	}
3213 
3214 	return (0);
3215 }
3216 
3217 uint_t
kobj_hash_name(const char * p)3218 kobj_hash_name(const char *p)
3219 {
3220 	uint_t g;
3221 	uint_t hval;
3222 
3223 	hval = 0;
3224 	while (*p) {
3225 		hval = (hval << 4) + *p++;
3226 		if ((g = (hval & 0xf0000000)) != 0)
3227 			hval ^= g >> 24;
3228 		hval &= ~g;
3229 	}
3230 	return (hval);
3231 }
3232 
3233 /* look for name in all modules */
3234 uintptr_t
kobj_getsymvalue(char * name,int kernelonly)3235 kobj_getsymvalue(char *name, int kernelonly)
3236 {
3237 	Sym		*sp;
3238 	struct modctl	*modp;
3239 	struct module	*mp;
3240 	uintptr_t	value = 0;
3241 
3242 	if ((sp = kobj_lookup_kernel(name)) != NULL)
3243 		return ((uintptr_t)sp->st_value);
3244 
3245 	if (kernelonly)
3246 		return (0);	/* didn't find it in the kernel so give up */
3247 
3248 	mutex_enter(&mod_lock);
3249 	modp = &modules;
3250 	do {
3251 		mp = (struct module *)modp->mod_mp;
3252 		if (mp && !(mp->flags & KOBJ_PRIM) && modp->mod_loaded &&
3253 		    (sp = lookup_one(mp, name))) {
3254 			value = (uintptr_t)sp->st_value;
3255 			break;
3256 		}
3257 	} while ((modp = modp->mod_next) != &modules);
3258 	mutex_exit(&mod_lock);
3259 	return (value);
3260 }
3261 
3262 /* look for a symbol near value. */
3263 char *
kobj_getsymname(uintptr_t value,ulong_t * offset)3264 kobj_getsymname(uintptr_t value, ulong_t *offset)
3265 {
3266 	char *name = NULL;
3267 	struct modctl *modp;
3268 
3269 	struct modctl_list *lp;
3270 	struct module *mp;
3271 
3272 	/*
3273 	 * Trap handler got us there, but we may not have whole kernel yet.
3274 	 */
3275 	if (standalone)
3276 		return (NULL);
3277 
3278 	/*
3279 	 * Loop through the primary kernel modules.
3280 	 */
3281 	for (lp = kobj_lm_lookup(KOBJ_LM_PRIMARY); lp; lp = lp->modl_next) {
3282 		mp = mod(lp);
3283 
3284 		if ((name = kobj_searchsym(mp, value, offset)) != NULL)
3285 			return (name);
3286 	}
3287 
3288 	mutex_enter(&mod_lock);
3289 	modp = &modules;
3290 	do {
3291 		mp = (struct module *)modp->mod_mp;
3292 		if (mp && !(mp->flags & KOBJ_PRIM) && modp->mod_loaded &&
3293 		    (name = kobj_searchsym(mp, value, offset)))
3294 			break;
3295 	} while ((modp = modp->mod_next) != &modules);
3296 	mutex_exit(&mod_lock);
3297 	return (name);
3298 }
3299 
3300 /* return address of symbol and size */
3301 
3302 uintptr_t
kobj_getelfsym(char * name,void * mp,int * size)3303 kobj_getelfsym(char *name, void *mp, int *size)
3304 {
3305 	Sym *sp;
3306 
3307 	if (mp == NULL)
3308 		sp = kobj_lookup_kernel(name);
3309 	else
3310 		sp = lookup_one(mp, name);
3311 
3312 	if (sp == NULL)
3313 		return (0);
3314 
3315 	*size = (int)sp->st_size;
3316 	return ((uintptr_t)sp->st_value);
3317 }
3318 
3319 uintptr_t
kobj_lookup(struct module * mod,const char * name)3320 kobj_lookup(struct module *mod, const char *name)
3321 {
3322 	Sym *sp;
3323 
3324 	sp = lookup_one(mod, name);
3325 
3326 	if (sp == NULL)
3327 		return (0);
3328 
3329 	return ((uintptr_t)sp->st_value);
3330 }
3331 
3332 char *
kobj_searchsym(struct module * mp,uintptr_t value,ulong_t * offset)3333 kobj_searchsym(struct module *mp, uintptr_t value, ulong_t *offset)
3334 {
3335 	Sym *symtabptr;
3336 	char *strtabptr;
3337 	int symnum;
3338 	Sym *sym;
3339 	Sym *cursym;
3340 	uintptr_t curval;
3341 
3342 	*offset = (ulong_t)-1l;		/* assume not found */
3343 	cursym  = NULL;
3344 
3345 	if (kobj_addrcheck(mp, (void *)value) != 0)
3346 		return (NULL);		/* not in this module */
3347 
3348 	strtabptr  = mp->strings;
3349 	symtabptr  = (Sym *)mp->symtbl;
3350 
3351 	/*
3352 	 * Scan the module's symbol table for a symbol <= value
3353 	 */
3354 	for (symnum = 1, sym = symtabptr + 1;
3355 	    symnum < mp->nsyms; symnum++, sym = (Sym *)
3356 	    ((uintptr_t)sym + mp->symhdr->sh_entsize)) {
3357 		if (ELF_ST_BIND(sym->st_info) != STB_GLOBAL) {
3358 			if (ELF_ST_BIND(sym->st_info) != STB_LOCAL)
3359 				continue;
3360 			if (ELF_ST_TYPE(sym->st_info) != STT_OBJECT &&
3361 			    ELF_ST_TYPE(sym->st_info) != STT_FUNC)
3362 				continue;
3363 		}
3364 
3365 		curval = (uintptr_t)sym->st_value;
3366 
3367 		if (curval > value)
3368 			continue;
3369 
3370 		/*
3371 		 * If one or both are functions...
3372 		 */
3373 		if (ELF_ST_TYPE(sym->st_info) == STT_FUNC || (cursym != NULL &&
3374 		    ELF_ST_TYPE(cursym->st_info) == STT_FUNC)) {
3375 			/* Ignore if the address is out of the bounds */
3376 			if (value - sym->st_value >= sym->st_size)
3377 				continue;
3378 
3379 			if (cursym != NULL &&
3380 			    ELF_ST_TYPE(cursym->st_info) == STT_FUNC) {
3381 				/* Prefer the function to the non-function */
3382 				if (ELF_ST_TYPE(sym->st_info) != STT_FUNC)
3383 					continue;
3384 
3385 				/* Prefer the larger of the two functions */
3386 				if (sym->st_size <= cursym->st_size)
3387 					continue;
3388 			}
3389 		} else if (value - curval >= *offset) {
3390 			continue;
3391 		}
3392 
3393 		*offset = (ulong_t)(value - curval);
3394 		cursym = sym;
3395 	}
3396 	if (cursym == NULL)
3397 		return (NULL);
3398 
3399 	return (strtabptr + cursym->st_name);
3400 }
3401 
3402 Sym *
kobj_lookup_all(struct module * mp,char * name,int include_self)3403 kobj_lookup_all(struct module *mp, char *name, int include_self)
3404 {
3405 	Sym *sp;
3406 	struct module_list *mlp;
3407 	struct modctl_list *clp;
3408 	struct module *mmp;
3409 
3410 	if (include_self && (sp = lookup_one(mp, name)) != NULL)
3411 		return (sp);
3412 
3413 	for (mlp = mp->head; mlp; mlp = mlp->next) {
3414 		if ((sp = lookup_one(mlp->mp, name)) != NULL &&
3415 		    ELF_ST_BIND(sp->st_info) != STB_LOCAL)
3416 			return (sp);
3417 	}
3418 
3419 	/*
3420 	 * Loop through the primary kernel modules.
3421 	 */
3422 	for (clp = kobj_lm_lookup(KOBJ_LM_PRIMARY); clp; clp = clp->modl_next) {
3423 		mmp = mod(clp);
3424 
3425 		if (mmp == NULL || mp == mmp)
3426 			continue;
3427 
3428 		if ((sp = lookup_one(mmp, name)) != NULL &&
3429 		    ELF_ST_BIND(sp->st_info) != STB_LOCAL)
3430 			return (sp);
3431 	}
3432 	return (NULL);
3433 }
3434 
3435 Sym *
kobj_lookup_kernel(const char * name)3436 kobj_lookup_kernel(const char *name)
3437 {
3438 	struct modctl_list *lp;
3439 	struct module *mp;
3440 	Sym *sp;
3441 
3442 	/*
3443 	 * Loop through the primary kernel modules.
3444 	 */
3445 	for (lp = kobj_lm_lookup(KOBJ_LM_PRIMARY); lp; lp = lp->modl_next) {
3446 		mp = mod(lp);
3447 
3448 		if (mp == NULL)
3449 			continue;
3450 
3451 		if ((sp = lookup_one(mp, name)) != NULL)
3452 			return (sp);
3453 	}
3454 	return (NULL);
3455 }
3456 
3457 static Sym *
lookup_one(struct module * mp,const char * name)3458 lookup_one(struct module *mp, const char *name)
3459 {
3460 	symid_t *ip;
3461 	char *name1;
3462 	Sym *sp;
3463 
3464 	for (ip = &mp->buckets[kobj_hash_name(name) % mp->hashsize]; *ip;
3465 	    ip = &mp->chains[*ip]) {
3466 		sp = (Sym *)(mp->symtbl +
3467 		    mp->symhdr->sh_entsize * *ip);
3468 		name1 = mp->strings + sp->st_name;
3469 		if (strcmp(name, name1) == 0 &&
3470 		    ELF_ST_TYPE(sp->st_info) != STT_FILE &&
3471 		    sp->st_shndx != SHN_UNDEF &&
3472 		    sp->st_shndx != SHN_COMMON)
3473 			return (sp);
3474 	}
3475 	return (NULL);
3476 }
3477 
3478 /*
3479  * Lookup a given symbol pointer in the module's symbol hash.  If the symbol
3480  * is hashed, return the symbol pointer; otherwise return NULL.
3481  */
3482 static Sym *
sym_lookup(struct module * mp,Sym * ksp)3483 sym_lookup(struct module *mp, Sym *ksp)
3484 {
3485 	char *name = mp->strings + ksp->st_name;
3486 	symid_t *ip;
3487 	Sym *sp;
3488 
3489 	for (ip = &mp->buckets[kobj_hash_name(name) % mp->hashsize]; *ip;
3490 	    ip = &mp->chains[*ip]) {
3491 		sp = (Sym *)(mp->symtbl + mp->symhdr->sh_entsize * *ip);
3492 		if (sp == ksp)
3493 			return (ksp);
3494 	}
3495 	return (NULL);
3496 }
3497 
3498 static void
sym_insert(struct module * mp,char * name,symid_t index)3499 sym_insert(struct module *mp, char *name, symid_t index)
3500 {
3501 	symid_t *ip;
3502 
3503 #ifdef KOBJ_DEBUG
3504 	if (kobj_debug & D_SYMBOLS) {
3505 		static struct module *lastmp = NULL;
3506 		Sym *sp;
3507 		if (lastmp != mp) {
3508 			_kobj_printf(ops,
3509 			    "krtld: symbol entry: file=%s\n",
3510 			    mp->filename);
3511 			_kobj_printf(ops,
3512 			    "krtld:\tsymndx\tvalue\t\t"
3513 			    "symbol name\n");
3514 			lastmp = mp;
3515 		}
3516 		sp = (Sym *)(mp->symtbl +
3517 		    index * mp->symhdr->sh_entsize);
3518 		_kobj_printf(ops, "krtld:\t[%3d]", index);
3519 		_kobj_printf(ops, "\t0x%lx", sp->st_value);
3520 		_kobj_printf(ops, "\t%s\n", name);
3521 	}
3522 #endif
3523 
3524 	for (ip = &mp->buckets[kobj_hash_name(name) % mp->hashsize]; *ip;
3525 	    ip = &mp->chains[*ip]) {
3526 		;
3527 	}
3528 	*ip = index;
3529 }
3530 
3531 struct modctl *
kobj_boot_mod_lookup(const char * modname)3532 kobj_boot_mod_lookup(const char *modname)
3533 {
3534 	struct modctl *mctl = kobj_modules;
3535 
3536 	do {
3537 		if (strcmp(modname, mctl->mod_modname) == 0)
3538 			return (mctl);
3539 	} while ((mctl = mctl->mod_next) != kobj_modules);
3540 
3541 	return (NULL);
3542 }
3543 
3544 /*
3545  * Determine if the module exists.
3546  */
3547 int
kobj_path_exists(char * name,int use_path)3548 kobj_path_exists(char *name, int use_path)
3549 {
3550 	struct _buf *file;
3551 
3552 	file = kobj_open_path(name, use_path, 1);
3553 #ifdef	MODDIR_SUFFIX
3554 	if (file == (struct _buf *)-1)
3555 		file = kobj_open_path(name, use_path, 0);
3556 #endif	/* MODDIR_SUFFIX */
3557 	if (file == (struct _buf *)-1)
3558 		return (0);
3559 	kobj_close_file(file);
3560 	return (1);
3561 }
3562 
3563 /*
3564  * fullname is dynamically allocated to be able to hold the
3565  * maximum size string that can be constructed from name.
3566  * path is exactly like the shell PATH variable.
3567  */
3568 struct _buf *
kobj_open_path(char * name,int use_path,int use_moddir_suffix)3569 kobj_open_path(char *name, int use_path, int use_moddir_suffix)
3570 {
3571 	char *p, *q;
3572 	char *pathp;
3573 	char *pathpsave;
3574 	char *fullname;
3575 	int maxpathlen;
3576 	struct _buf *file;
3577 
3578 #if !defined(MODDIR_SUFFIX)
3579 	use_moddir_suffix = B_FALSE;
3580 #endif
3581 
3582 	if (!use_path)
3583 		pathp = "";		/* use name as specified */
3584 	else
3585 		pathp = kobj_module_path;
3586 					/* use configured default path */
3587 
3588 	pathpsave = pathp;		/* keep this for error reporting */
3589 
3590 	/*
3591 	 * Allocate enough space for the largest possible fullname.
3592 	 * since path is of the form <directory> : <directory> : ...
3593 	 * we're potentially allocating a little more than we need to
3594 	 * but we'll allocate the exact amount when we find the right directory.
3595 	 * (The + 3 below is one for NULL terminator and one for the '/'
3596 	 * we might have to add at the beginning of path and one for
3597 	 * the '/' between path and name.)
3598 	 */
3599 	maxpathlen = strlen(pathp) + strlen(name) + 3;
3600 	/* sizeof includes null */
3601 	maxpathlen += sizeof (slash_moddir_suffix_slash) - 1;
3602 	fullname = kobj_zalloc(maxpathlen, KM_WAIT);
3603 
3604 	for (;;) {
3605 		p = fullname;
3606 		if (*pathp != '\0' && *pathp != '/')
3607 			*p++ = '/';	/* path must start with '/' */
3608 		while (*pathp && *pathp != ':' && *pathp != ' ')
3609 			*p++ = *pathp++;
3610 		if (p != fullname && p[-1] != '/')
3611 			*p++ = '/';
3612 		if (use_moddir_suffix) {
3613 			char *b = basename(name);
3614 			char *s;
3615 
3616 			/* copy everything up to the base name */
3617 			q = name;
3618 			while (q != b && *q)
3619 				*p++ = *q++;
3620 			s = slash_moddir_suffix_slash;
3621 			while (*s)
3622 				*p++ = *s++;
3623 			/* copy the rest */
3624 			while (*b)
3625 				*p++ = *b++;
3626 		} else {
3627 			q = name;
3628 			while (*q)
3629 				*p++ = *q++;
3630 		}
3631 		*p = 0;
3632 		if ((file = kobj_open_file(fullname)) != (struct _buf *)-1) {
3633 			kobj_free(fullname, maxpathlen);
3634 			return (file);
3635 		}
3636 		while (*pathp == ' ' || *pathp == ':')
3637 			pathp++;
3638 		if (*pathp == 0)
3639 			break;
3640 
3641 	}
3642 	kobj_free(fullname, maxpathlen);
3643 	if (_moddebug & MODDEBUG_ERRMSG) {
3644 		_kobj_printf(ops, "can't open %s,", name);
3645 		_kobj_printf(ops, " path is %s\n", pathpsave);
3646 	}
3647 	return ((struct _buf *)-1);
3648 }
3649 
3650 intptr_t
kobj_open(char * filename)3651 kobj_open(char *filename)
3652 {
3653 	struct vnode *vp;
3654 	int fd;
3655 
3656 	if (_modrootloaded) {
3657 		struct kobjopen_tctl *ltp = kobjopen_alloc(filename);
3658 		int Errno;
3659 
3660 		/*
3661 		 * Hand off the open to a thread who has a
3662 		 * stack size capable handling the request.
3663 		 */
3664 		if (curthread != &t0) {
3665 			(void) thread_create(NULL, DEFAULTSTKSZ * 2,
3666 			    kobjopen_thread, ltp, 0, &p0, TS_RUN, maxclsyspri);
3667 			sema_p(&ltp->sema);
3668 			Errno = ltp->Errno;
3669 			vp = ltp->vp;
3670 		} else {
3671 			/*
3672 			 * 1098067: module creds should not be those of the
3673 			 * caller
3674 			 */
3675 			cred_t *saved_cred = curthread->t_cred;
3676 			curthread->t_cred = kcred;
3677 			Errno = vn_openat(filename, UIO_SYSSPACE, FREAD, 0, &vp,
3678 			    0, 0, rootdir, -1);
3679 			curthread->t_cred = saved_cred;
3680 		}
3681 		kobjopen_free(ltp);
3682 
3683 		if (Errno) {
3684 			if (_moddebug & MODDEBUG_ERRMSG) {
3685 				_kobj_printf(ops,
3686 				    "kobj_open: vn_open of %s fails, ",
3687 				    filename);
3688 				_kobj_printf(ops, "Errno = %d\n", Errno);
3689 			}
3690 			return (-1);
3691 		} else {
3692 			if (_moddebug & MODDEBUG_ERRMSG) {
3693 				_kobj_printf(ops, "kobj_open: '%s'", filename);
3694 				_kobj_printf(ops, " vp = %p\n", vp);
3695 			}
3696 			return ((intptr_t)vp);
3697 		}
3698 	} else {
3699 		fd = kobj_boot_open(filename, 0);
3700 
3701 		if (_moddebug & MODDEBUG_ERRMSG) {
3702 			if (fd < 0)
3703 				_kobj_printf(ops,
3704 				    "kobj_open: can't open %s\n", filename);
3705 			else {
3706 				_kobj_printf(ops, "kobj_open: '%s'", filename);
3707 				_kobj_printf(ops, " descr = 0x%x\n", fd);
3708 			}
3709 		}
3710 		return ((intptr_t)fd);
3711 	}
3712 }
3713 
3714 /*
3715  * Calls to kobj_open() are handled off to this routine as a separate thread.
3716  */
3717 static void
kobjopen_thread(struct kobjopen_tctl * ltp)3718 kobjopen_thread(struct kobjopen_tctl *ltp)
3719 {
3720 	kmutex_t	cpr_lk;
3721 	callb_cpr_t	cpr_i;
3722 
3723 	mutex_init(&cpr_lk, NULL, MUTEX_DEFAULT, NULL);
3724 	CALLB_CPR_INIT(&cpr_i, &cpr_lk, callb_generic_cpr, "kobjopen");
3725 	ltp->Errno = vn_open(ltp->name, UIO_SYSSPACE, FREAD, 0, &(ltp->vp),
3726 	    0, 0);
3727 	sema_v(&ltp->sema);
3728 	mutex_enter(&cpr_lk);
3729 	CALLB_CPR_EXIT(&cpr_i);
3730 	mutex_destroy(&cpr_lk);
3731 	thread_exit();
3732 }
3733 
3734 /*
3735  * allocate and initialize a kobjopen thread structure
3736  */
3737 static struct kobjopen_tctl *
kobjopen_alloc(char * filename)3738 kobjopen_alloc(char *filename)
3739 {
3740 	struct kobjopen_tctl *ltp = kmem_zalloc(sizeof (*ltp), KM_SLEEP);
3741 
3742 	ASSERT(filename != NULL);
3743 
3744 	ltp->name = kmem_alloc(strlen(filename) + 1, KM_SLEEP);
3745 	bcopy(filename, ltp->name, strlen(filename) + 1);
3746 	sema_init(&ltp->sema, 0, NULL, SEMA_DEFAULT, NULL);
3747 	return (ltp);
3748 }
3749 
3750 /*
3751  * free a kobjopen thread control structure
3752  */
3753 static void
kobjopen_free(struct kobjopen_tctl * ltp)3754 kobjopen_free(struct kobjopen_tctl *ltp)
3755 {
3756 	sema_destroy(&ltp->sema);
3757 	kmem_free(ltp->name, strlen(ltp->name) + 1);
3758 	kmem_free(ltp, sizeof (*ltp));
3759 }
3760 
3761 int
kobj_read(intptr_t descr,char * buf,uint_t size,uint_t offset)3762 kobj_read(intptr_t descr, char *buf, uint_t size, uint_t offset)
3763 {
3764 	int stat;
3765 	ssize_t resid;
3766 
3767 	if (_modrootloaded) {
3768 		if ((stat = vn_rdwr(UIO_READ, (struct vnode *)descr, buf, size,
3769 		    (offset_t)offset, UIO_SYSSPACE, 0, (rlim64_t)0, CRED(),
3770 		    &resid)) != 0) {
3771 			_kobj_printf(ops,
3772 			    "vn_rdwr failed with error 0x%x\n", stat);
3773 			return (-1);
3774 		}
3775 		return (size - resid);
3776 	} else {
3777 		int count = 0;
3778 
3779 		if (kobj_boot_seek((int)descr, (off_t)0, offset) != 0) {
3780 			_kobj_printf(ops,
3781 			    "kobj_read: seek 0x%x failed\n", offset);
3782 			return (-1);
3783 		}
3784 
3785 		count = kobj_boot_read((int)descr, buf, size);
3786 		if (count < size) {
3787 			if (_moddebug & MODDEBUG_ERRMSG) {
3788 				_kobj_printf(ops,
3789 				    "kobj_read: req %d bytes, ", size);
3790 				_kobj_printf(ops, "got %d\n", count);
3791 			}
3792 		}
3793 		return (count);
3794 	}
3795 }
3796 
3797 void
kobj_close(intptr_t descr)3798 kobj_close(intptr_t descr)
3799 {
3800 	if (_moddebug & MODDEBUG_ERRMSG)
3801 		_kobj_printf(ops, "kobj_close: 0x%lx\n", descr);
3802 
3803 	if (_modrootloaded) {
3804 		struct vnode *vp = (struct vnode *)descr;
3805 		(void) VOP_CLOSE(vp, FREAD, 1, (offset_t)0, CRED(), NULL);
3806 		VN_RELE(vp);
3807 	} else
3808 		(void) kobj_boot_close((int)descr);
3809 }
3810 
3811 int
kobj_fstat(intptr_t descr,struct bootstat * buf)3812 kobj_fstat(intptr_t descr, struct bootstat *buf)
3813 {
3814 	if (buf == NULL)
3815 		return (-1);
3816 
3817 	if (_modrootloaded) {
3818 		vattr_t vattr;
3819 		struct vnode *vp = (struct vnode *)descr;
3820 		if (VOP_GETATTR(vp, &vattr, 0, kcred, NULL) != 0)
3821 			return (-1);
3822 
3823 		/*
3824 		 * The vattr and bootstat structures are similar, but not
3825 		 * identical.  We do our best to fill in the bootstat structure
3826 		 * from the contents of vattr (transfering only the ones that
3827 		 * are obvious.
3828 		 */
3829 
3830 		buf->st_mode = (uint32_t)vattr.va_mode;
3831 		buf->st_nlink = (uint32_t)vattr.va_nlink;
3832 		buf->st_uid = (int32_t)vattr.va_uid;
3833 		buf->st_gid = (int32_t)vattr.va_gid;
3834 		buf->st_rdev = (uint64_t)vattr.va_rdev;
3835 		buf->st_size = (uint64_t)vattr.va_size;
3836 		buf->st_atim.tv_sec = (int64_t)vattr.va_atime.tv_sec;
3837 		buf->st_atim.tv_nsec = (int64_t)vattr.va_atime.tv_nsec;
3838 		buf->st_mtim.tv_sec = (int64_t)vattr.va_mtime.tv_sec;
3839 		buf->st_mtim.tv_nsec = (int64_t)vattr.va_mtime.tv_nsec;
3840 		buf->st_ctim.tv_sec = (int64_t)vattr.va_ctime.tv_sec;
3841 		buf->st_ctim.tv_nsec = (int64_t)vattr.va_ctime.tv_nsec;
3842 		buf->st_blksize = (int32_t)vattr.va_blksize;
3843 		buf->st_blocks = (int64_t)vattr.va_nblocks;
3844 
3845 		return (0);
3846 	}
3847 
3848 	return (kobj_boot_fstat((int)descr, buf));
3849 }
3850 
3851 
3852 struct _buf *
kobj_open_file(char * name)3853 kobj_open_file(char *name)
3854 {
3855 	struct _buf *file;
3856 	struct compinfo cbuf;
3857 	intptr_t fd;
3858 
3859 	if ((fd = kobj_open(name)) == -1) {
3860 		return ((struct _buf *)-1);
3861 	}
3862 
3863 	file = kobj_zalloc(sizeof (struct _buf), KM_WAIT|KM_TMP);
3864 	file->_fd = fd;
3865 	file->_name = kobj_alloc(strlen(name)+1, KM_WAIT|KM_TMP);
3866 	file->_cnt = file->_size = file->_off = 0;
3867 	file->_ln = 1;
3868 	file->_ptr = file->_base;
3869 	(void) strcpy(file->_name, name);
3870 
3871 	/*
3872 	 * Before root is mounted, we must check
3873 	 * for a compressed file and do our own
3874 	 * buffering.
3875 	 */
3876 	if (_modrootloaded) {
3877 		file->_base = kobj_zalloc(MAXBSIZE, KM_WAIT);
3878 		file->_bsize = MAXBSIZE;
3879 
3880 		/* Check if the file is compressed */
3881 		file->_iscmp = kobj_is_compressed(fd);
3882 	} else {
3883 		if (kobj_boot_compinfo(fd, &cbuf) != 0) {
3884 			kobj_close_file(file);
3885 			return ((struct _buf *)-1);
3886 		}
3887 		file->_iscmp = cbuf.iscmp;
3888 		if (file->_iscmp) {
3889 			if (kobj_comp_setup(file, &cbuf) != 0) {
3890 				kobj_close_file(file);
3891 				return ((struct _buf *)-1);
3892 			}
3893 		} else {
3894 			file->_base = kobj_zalloc(cbuf.blksize, KM_WAIT|KM_TMP);
3895 			file->_bsize = cbuf.blksize;
3896 		}
3897 	}
3898 	return (file);
3899 }
3900 
3901 static int
kobj_comp_setup(struct _buf * file,struct compinfo * cip)3902 kobj_comp_setup(struct _buf *file, struct compinfo *cip)
3903 {
3904 	struct comphdr *hdr;
3905 
3906 	/*
3907 	 * read the compressed image into memory,
3908 	 * so we can deompress from there
3909 	 */
3910 	file->_dsize = cip->fsize;
3911 	file->_dbuf = kobj_alloc(cip->fsize, KM_WAIT|KM_TMP);
3912 	if (kobj_read(file->_fd, file->_dbuf, cip->fsize, 0) != cip->fsize) {
3913 		kobj_free(file->_dbuf, cip->fsize);
3914 		return (-1);
3915 	}
3916 
3917 	hdr = kobj_comphdr(file);
3918 	if (hdr->ch_magic != CH_MAGIC_ZLIB || hdr->ch_version != CH_VERSION ||
3919 	    hdr->ch_algorithm != CH_ALG_ZLIB || hdr->ch_fsize == 0 ||
3920 	    !ISP2(hdr->ch_blksize)) {
3921 		kobj_free(file->_dbuf, cip->fsize);
3922 		return (-1);
3923 	}
3924 	file->_base = kobj_alloc(hdr->ch_blksize, KM_WAIT|KM_TMP);
3925 	file->_bsize = hdr->ch_blksize;
3926 	return (0);
3927 }
3928 
3929 void
kobj_close_file(struct _buf * file)3930 kobj_close_file(struct _buf *file)
3931 {
3932 	kobj_close(file->_fd);
3933 	if (file->_base != NULL)
3934 		kobj_free(file->_base, file->_bsize);
3935 	if (file->_dbuf != NULL)
3936 		kobj_free(file->_dbuf, file->_dsize);
3937 	kobj_free(file->_name, strlen(file->_name)+1);
3938 	kobj_free(file, sizeof (struct _buf));
3939 }
3940 
3941 int
kobj_read_file(struct _buf * file,char * buf,uint_t size,uint_t off)3942 kobj_read_file(struct _buf *file, char *buf, uint_t size, uint_t off)
3943 {
3944 	int b_size, c_size;
3945 	int b_off;	/* Offset into buffer for start of bcopy */
3946 	int count = 0;
3947 	int page_addr;
3948 
3949 	if (_moddebug & MODDEBUG_ERRMSG) {
3950 		_kobj_printf(ops, "kobj_read_file: size=%x,", size);
3951 		_kobj_printf(ops, " offset=%x at", off);
3952 		_kobj_printf(ops, " buf=%lx\n", (uintptr_t)buf);
3953 	}
3954 
3955 	/*
3956 	 * Handle compressed (gzip for now) file here. First get the
3957 	 * compressed size, then read the image into memory and finally
3958 	 * call zlib to decompress the image at the supplied memory buffer.
3959 	 */
3960 	if (file->_iscmp == CH_MAGIC_GZIP) {
3961 		ulong_t dlen;
3962 		vattr_t vattr;
3963 		struct vnode *vp = (struct vnode *)file->_fd;
3964 		ssize_t resid;
3965 		int err = 0;
3966 
3967 		if (VOP_GETATTR(vp, &vattr, 0, kcred, NULL) != 0)
3968 			return (-1);
3969 
3970 		file->_dbuf = kobj_alloc(vattr.va_size, KM_WAIT|KM_TMP);
3971 		file->_dsize = vattr.va_size;
3972 
3973 		/* Read the compressed file into memory */
3974 		if ((err = vn_rdwr(UIO_READ, vp, file->_dbuf, vattr.va_size,
3975 		    (offset_t)(0), UIO_SYSSPACE, 0, (rlim64_t)0, CRED(),
3976 		    &resid)) != 0) {
3977 
3978 			_kobj_printf(ops, "kobj_read_file :vn_rdwr() failed, "
3979 			    "error code 0x%x\n", err);
3980 			return (-1);
3981 		}
3982 
3983 		dlen = size;
3984 
3985 		/* Decompress the image at the supplied memory buffer */
3986 		if ((err = z_uncompress(buf, &dlen, file->_dbuf,
3987 		    vattr.va_size)) != Z_OK) {
3988 			_kobj_printf(ops, "kobj_read_file: z_uncompress "
3989 			    "failed, error code : 0x%x\n", err);
3990 			return (-1);
3991 		}
3992 
3993 		if (dlen != size) {
3994 			_kobj_printf(ops, "kobj_read_file: z_uncompress "
3995 			    "failed to uncompress (size returned 0x%lx , "
3996 			    "expected size: 0x%x)\n", dlen, size);
3997 			return (-1);
3998 		}
3999 
4000 		return (0);
4001 	}
4002 
4003 	while (size) {
4004 		page_addr = F_PAGE(file, off);
4005 		b_size = file->_size;
4006 		/*
4007 		 * If we have the filesystem page the caller's referring to
4008 		 * and we have something in the buffer,
4009 		 * satisfy as much of the request from the buffer as we can.
4010 		 */
4011 		if (page_addr == file->_off && b_size > 0) {
4012 			b_off = B_OFFSET(file, off);
4013 			c_size = b_size - b_off;
4014 			/*
4015 			 * If there's nothing to copy, we're at EOF.
4016 			 */
4017 			if (c_size <= 0)
4018 				break;
4019 			if (c_size > size)
4020 				c_size = size;
4021 			if (buf) {
4022 				if (_moddebug & MODDEBUG_ERRMSG)
4023 					_kobj_printf(ops, "copying %x bytes\n",
4024 					    c_size);
4025 				bcopy(file->_base+b_off, buf, c_size);
4026 				size -= c_size;
4027 				off += c_size;
4028 				buf += c_size;
4029 				count += c_size;
4030 			} else {
4031 				_kobj_printf(ops, "kobj_read: system error");
4032 				count = -1;
4033 				break;
4034 			}
4035 		} else {
4036 			/*
4037 			 * If the caller's offset is page aligned and
4038 			 * the caller want's at least a filesystem page and
4039 			 * the caller provided a buffer,
4040 			 * read directly into the caller's buffer.
4041 			 */
4042 			if (page_addr == off &&
4043 			    (c_size = F_BLKS(file, size)) && buf) {
4044 				c_size = kobj_read_blks(file, buf, c_size,
4045 				    page_addr);
4046 				if (c_size < 0) {
4047 					count = -1;
4048 					break;
4049 				}
4050 				count += c_size;
4051 				if (c_size != F_BLKS(file, size))
4052 					break;
4053 				size -= c_size;
4054 				off += c_size;
4055 				buf += c_size;
4056 			/*
4057 			 * Otherwise, read into our buffer and copy next time
4058 			 * around the loop.
4059 			 */
4060 			} else {
4061 				file->_off = page_addr;
4062 				c_size = kobj_read_blks(file, file->_base,
4063 				    file->_bsize, page_addr);
4064 				file->_ptr = file->_base;
4065 				file->_cnt = c_size;
4066 				file->_size = c_size;
4067 				/*
4068 				 * If a _filbuf call or nothing read, break.
4069 				 */
4070 				if (buf == NULL || c_size <= 0) {
4071 					count = c_size;
4072 					break;
4073 				}
4074 			}
4075 			if (_moddebug & MODDEBUG_ERRMSG)
4076 				_kobj_printf(ops, "read %x bytes\n", c_size);
4077 		}
4078 	}
4079 	if (_moddebug & MODDEBUG_ERRMSG)
4080 		_kobj_printf(ops, "count = %x\n", count);
4081 
4082 	return (count);
4083 }
4084 
4085 static int
kobj_read_blks(struct _buf * file,char * buf,uint_t size,uint_t off)4086 kobj_read_blks(struct _buf *file, char *buf, uint_t size, uint_t off)
4087 {
4088 	int ret;
4089 
4090 	ASSERT(B_OFFSET(file, size) == 0 && B_OFFSET(file, off) == 0);
4091 	if (file->_iscmp) {
4092 		uint_t blks;
4093 		int nret;
4094 
4095 		ret = 0;
4096 		for (blks = size / file->_bsize; blks != 0; blks--) {
4097 			nret = kobj_uncomp_blk(file, buf, off);
4098 			if (nret == -1)
4099 				return (-1);
4100 			buf += nret;
4101 			off += nret;
4102 			ret += nret;
4103 			if (nret < file->_bsize)
4104 				break;
4105 		}
4106 	} else
4107 		ret = kobj_read(file->_fd, buf, size, off);
4108 	return (ret);
4109 }
4110 
4111 static int
kobj_uncomp_blk(struct _buf * file,char * buf,uint_t off)4112 kobj_uncomp_blk(struct _buf *file, char *buf, uint_t off)
4113 {
4114 	struct comphdr *hdr = kobj_comphdr(file);
4115 	ulong_t dlen, slen;
4116 	caddr_t src;
4117 	int i;
4118 
4119 	dlen = file->_bsize;
4120 	i = off / file->_bsize;
4121 	src = file->_dbuf + hdr->ch_blkmap[i];
4122 	if (i == hdr->ch_fsize / file->_bsize)
4123 		slen = file->_dsize - hdr->ch_blkmap[i];
4124 	else
4125 		slen = hdr->ch_blkmap[i + 1] - hdr->ch_blkmap[i];
4126 	if (z_uncompress(buf, &dlen, src, slen) != Z_OK)
4127 		return (-1);
4128 	return (dlen);
4129 }
4130 
4131 int
kobj_filbuf(struct _buf * f)4132 kobj_filbuf(struct _buf *f)
4133 {
4134 	if (kobj_read_file(f, NULL, f->_bsize, f->_off + f->_size) > 0)
4135 		return (kobj_getc(f));
4136 	return (-1);
4137 }
4138 
4139 void
kobj_free(void * address,size_t size)4140 kobj_free(void *address, size_t size)
4141 {
4142 	if (standalone)
4143 		return;
4144 
4145 	kmem_free(address, size);
4146 	kobj_stat.nfree_calls++;
4147 	kobj_stat.nfree += size;
4148 }
4149 
4150 void *
kobj_zalloc(size_t size,int flag)4151 kobj_zalloc(size_t size, int flag)
4152 {
4153 	void *v;
4154 
4155 	if ((v = kobj_alloc(size, flag)) != 0) {
4156 		bzero(v, size);
4157 	}
4158 
4159 	return (v);
4160 }
4161 
4162 void *
kobj_alloc(size_t size,int flag)4163 kobj_alloc(size_t size, int flag)
4164 {
4165 	/*
4166 	 * If we are running standalone in the
4167 	 * linker, we ask boot for memory.
4168 	 * Either it's temporary memory that we lose
4169 	 * once boot is mapped out or we allocate it
4170 	 * permanently using the dynamic data segment.
4171 	 */
4172 	if (standalone) {
4173 #if defined(_OBP)
4174 		if (flag & (KM_TMP | KM_SCRATCH))
4175 			return (bop_temp_alloc(size, MINALIGN));
4176 #else
4177 		if (flag & (KM_TMP | KM_SCRATCH))
4178 			return (BOP_ALLOC(ops, 0, size, MINALIGN));
4179 #endif
4180 		return (kobj_segbrk(&_edata, size, MINALIGN, 0));
4181 	}
4182 
4183 	kobj_stat.nalloc_calls++;
4184 	kobj_stat.nalloc += size;
4185 
4186 	return (kmem_alloc(size, (flag & KM_NOWAIT) ? KM_NOSLEEP : KM_SLEEP));
4187 }
4188 
4189 /*
4190  * Allow the "mod" system to sync up with the work
4191  * already done by kobj during the initial loading
4192  * of the kernel.  This also gives us a chance
4193  * to reallocate memory that belongs to boot.
4194  */
4195 void
kobj_sync(void)4196 kobj_sync(void)
4197 {
4198 	struct modctl_list *lp, **lpp;
4199 
4200 	/*
4201 	 * The module path can be set in /etc/system via 'moddir' commands
4202 	 */
4203 	if (default_path != NULL)
4204 		kobj_module_path = default_path;
4205 	else
4206 		default_path = kobj_module_path;
4207 
4208 	ksyms_arena = vmem_create("ksyms", NULL, 0, sizeof (uint64_t),
4209 	    segkmem_alloc, segkmem_free, heap_arena, 0, VM_SLEEP);
4210 
4211 	ctf_arena = vmem_create("ctf", NULL, 0, sizeof (uint_t),
4212 	    segkmem_alloc, segkmem_free, heap_arena, 0, VM_SLEEP);
4213 
4214 	/*
4215 	 * Move symbol tables from boot memory to ksyms_arena.
4216 	 */
4217 	for (lpp = kobj_linkmaps; *lpp != NULL; lpp++) {
4218 		for (lp = *lpp; lp != NULL; lp = lp->modl_next)
4219 			kobj_export_module(mod(lp));
4220 	}
4221 }
4222 
4223 caddr_t
kobj_segbrk(caddr_t * spp,size_t size,size_t align,caddr_t limit)4224 kobj_segbrk(caddr_t *spp, size_t size, size_t align, caddr_t limit)
4225 {
4226 	uintptr_t va, pva;
4227 	size_t alloc_pgsz = kobj_mmu_pagesize;
4228 	size_t alloc_align = BO_NO_ALIGN;
4229 	size_t alloc_size;
4230 
4231 	/*
4232 	 * If we are using "large" mappings for the kernel,
4233 	 * request aligned memory from boot using the
4234 	 * "large" pagesize.
4235 	 */
4236 	if (lg_pagesize) {
4237 		alloc_align = lg_pagesize;
4238 		alloc_pgsz = lg_pagesize;
4239 	}
4240 
4241 #if defined(__sparc)
4242 	/* account for redzone */
4243 	if (limit)
4244 		limit -= alloc_pgsz;
4245 #endif	/* __sparc */
4246 
4247 	va = ALIGN((uintptr_t)*spp, align);
4248 	pva = P2ROUNDUP((uintptr_t)*spp, alloc_pgsz);
4249 	/*
4250 	 * Need more pages?
4251 	 */
4252 	if (va + size > pva) {
4253 		uintptr_t npva;
4254 
4255 		alloc_size = P2ROUNDUP(size - (pva - va), alloc_pgsz);
4256 		/*
4257 		 * Check for overlapping segments.
4258 		 */
4259 		if (limit && limit <= *spp + alloc_size) {
4260 			return ((caddr_t)0);
4261 		}
4262 
4263 		npva = (uintptr_t)BOP_ALLOC(ops, (caddr_t)pva,
4264 		    alloc_size, alloc_align);
4265 
4266 		if (npva == 0) {
4267 			_kobj_printf(ops, "BOP_ALLOC failed, 0x%lx bytes",
4268 			    alloc_size);
4269 			_kobj_printf(ops, " aligned %lx", alloc_align);
4270 			_kobj_printf(ops, " at 0x%lx\n", pva);
4271 			return (NULL);
4272 		}
4273 	}
4274 	*spp = (caddr_t)(va + size);
4275 
4276 	return ((caddr_t)va);
4277 }
4278 
4279 /*
4280  * Calculate the number of output hash buckets.
4281  * We use the next prime larger than n / 4,
4282  * so the average hash chain is about 4 entries.
4283  * More buckets would just be a waste of memory.
4284  */
4285 uint_t
kobj_gethashsize(uint_t n)4286 kobj_gethashsize(uint_t n)
4287 {
4288 	int f;
4289 	int hsize = MAX(n / 4, 2);
4290 
4291 	for (f = 2; f * f <= hsize; f++)
4292 		if (hsize % f == 0)
4293 			hsize += f = 1;
4294 
4295 	return (hsize);
4296 }
4297 
4298 /*
4299  * Get the file size.
4300  *
4301  * Before root is mounted, files are compressed in the boot_archive ramdisk
4302  * (in the memory). kobj_fstat would return the compressed file size.
4303  * In order to get the uncompressed file size, read the file to the end and
4304  * count its size.
4305  */
4306 int
kobj_get_filesize(struct _buf * file,uint64_t * size)4307 kobj_get_filesize(struct _buf *file, uint64_t *size)
4308 {
4309 	int err = 0;
4310 	ssize_t resid;
4311 	uint32_t buf;
4312 
4313 	if (_modrootloaded) {
4314 		struct bootstat bst;
4315 
4316 		if (kobj_fstat(file->_fd, &bst) != 0)
4317 			return (EIO);
4318 		*size = bst.st_size;
4319 
4320 		if (file->_iscmp == CH_MAGIC_GZIP) {
4321 			/*
4322 			 * Read the last 4 bytes of the compressed (gzip)
4323 			 * image to get the size of its uncompressed
4324 			 * version.
4325 			 */
4326 			if ((err = vn_rdwr(UIO_READ, (struct vnode *)file->_fd,
4327 			    (char *)(&buf), 4, (offset_t)(*size - 4),
4328 			    UIO_SYSSPACE, 0, (rlim64_t)0, CRED(), &resid))
4329 			    != 0) {
4330 				_kobj_printf(ops, "kobj_get_filesize: "
4331 				    "vn_rdwr() failed with error 0x%x\n", err);
4332 				return (-1);
4333 			}
4334 
4335 			*size =  (uint64_t)buf;
4336 		}
4337 	} else {
4338 
4339 #if defined(_OBP)
4340 		struct bootstat bsb;
4341 
4342 		if (file->_iscmp) {
4343 			struct comphdr *hdr = kobj_comphdr(file);
4344 
4345 			*size = hdr->ch_fsize;
4346 		} else if (kobj_boot_fstat(file->_fd, &bsb) != 0)
4347 			return (EIO);
4348 		else
4349 			*size = bsb.st_size;
4350 #else
4351 		char *buf;
4352 		int count;
4353 		uint64_t offset = 0;
4354 
4355 		buf = kmem_alloc(MAXBSIZE, KM_SLEEP);
4356 		do {
4357 			count = kobj_read_file(file, buf, MAXBSIZE, offset);
4358 			if (count < 0) {
4359 				kmem_free(buf, MAXBSIZE);
4360 				return (EIO);
4361 			}
4362 			offset += count;
4363 		} while (count == MAXBSIZE);
4364 		kmem_free(buf, MAXBSIZE);
4365 
4366 		*size = offset;
4367 #endif
4368 	}
4369 
4370 	return (0);
4371 }
4372 
4373 static char *
basename(char * s)4374 basename(char *s)
4375 {
4376 	char *p, *q;
4377 
4378 	q = NULL;
4379 	p = s;
4380 	do {
4381 		if (*p == '/')
4382 			q = p;
4383 	} while (*p++);
4384 	return (q ? q + 1 : s);
4385 }
4386 
4387 void
kobj_stat_get(kobj_stat_t * kp)4388 kobj_stat_get(kobj_stat_t *kp)
4389 {
4390 	*kp = kobj_stat;
4391 }
4392 
4393 int
kobj_getpagesize()4394 kobj_getpagesize()
4395 {
4396 	return (lg_pagesize);
4397 }
4398 
4399 void
kobj_textwin_alloc(struct module * mp)4400 kobj_textwin_alloc(struct module *mp)
4401 {
4402 	ASSERT(MUTEX_HELD(&mod_lock));
4403 
4404 	if (mp->textwin != NULL)
4405 		return;
4406 
4407 	/*
4408 	 * If the text is not contained in the heap, then it is not contained
4409 	 * by a writable mapping.  (Specifically, it's on the nucleus page.)
4410 	 * We allocate a read/write mapping for this module's text to allow
4411 	 * the text to be patched without calling hot_patch_kernel_text()
4412 	 * (which is quite slow).
4413 	 */
4414 	if (!vmem_contains(heaptext_arena, mp->text, mp->text_size)) {
4415 		uintptr_t text = (uintptr_t)mp->text;
4416 		uintptr_t size = (uintptr_t)mp->text_size;
4417 		uintptr_t i;
4418 		caddr_t va;
4419 		size_t sz = ((text + size + PAGESIZE - 1) & PAGEMASK) -
4420 		    (text & PAGEMASK);
4421 
4422 		va = mp->textwin_base = vmem_alloc(heap_arena, sz, VM_SLEEP);
4423 
4424 		for (i = text & PAGEMASK; i < text + size; i += PAGESIZE) {
4425 			hat_devload(kas.a_hat, va, PAGESIZE,
4426 			    hat_getpfnum(kas.a_hat, (caddr_t)i),
4427 			    PROT_READ | PROT_WRITE,
4428 			    HAT_LOAD_LOCK | HAT_LOAD_NOCONSIST);
4429 			va += PAGESIZE;
4430 		}
4431 
4432 		mp->textwin = mp->textwin_base + (text & PAGEOFFSET);
4433 	} else {
4434 		mp->textwin = mp->text;
4435 	}
4436 }
4437 
4438 void
kobj_textwin_free(struct module * mp)4439 kobj_textwin_free(struct module *mp)
4440 {
4441 	uintptr_t text = (uintptr_t)mp->text;
4442 	uintptr_t tsize = (uintptr_t)mp->text_size;
4443 	size_t size = (((text + tsize + PAGESIZE - 1) & PAGEMASK) -
4444 	    (text & PAGEMASK));
4445 
4446 	mp->textwin = NULL;
4447 
4448 	if (mp->textwin_base == NULL)
4449 		return;
4450 
4451 	hat_unload(kas.a_hat, mp->textwin_base, size, HAT_UNLOAD_UNLOCK);
4452 	vmem_free(heap_arena, mp->textwin_base, size);
4453 	mp->textwin_base = NULL;
4454 }
4455 
4456 static char *
find_libmacro(char * name)4457 find_libmacro(char *name)
4458 {
4459 	int lmi;
4460 
4461 	for (lmi = 0; lmi < NLIBMACROS; lmi++) {
4462 		if (strcmp(name, libmacros[lmi].lmi_macroname) == 0)
4463 			return (libmacros[lmi].lmi_list);
4464 	}
4465 	return (NULL);
4466 }
4467 
4468 /*
4469  * Check for $MACRO in tail (string to expand) and expand it in path at pathend
4470  * returns path if successful, else NULL
4471  * Support multiple $MACROs expansion and the first valid path will be returned
4472  * Caller's responsibility to provide enough space in path to expand
4473  */
4474 char *
expand_libmacro(char * tail,char * path,char * pathend)4475 expand_libmacro(char *tail, char *path, char *pathend)
4476 {
4477 	char c, *p, *p1, *p2, *path2, *endp;
4478 	int diff, lmi, macrolen, valid_macro, more_macro;
4479 	struct _buf *file;
4480 
4481 	/*
4482 	 * check for $MACROS between nulls or slashes
4483 	 */
4484 	p = strchr(tail, '$');
4485 	if (p == NULL)
4486 		return (NULL);
4487 	for (lmi = 0; lmi < NLIBMACROS; lmi++) {
4488 		macrolen = libmacros[lmi].lmi_macrolen;
4489 		if (strncmp(p + 1, libmacros[lmi].lmi_macroname, macrolen) == 0)
4490 			break;
4491 	}
4492 
4493 	valid_macro = 0;
4494 	if (lmi < NLIBMACROS) {
4495 		/*
4496 		 * The following checks are used to restrict expansion of
4497 		 * macros to those that form a full directory/file name
4498 		 * and to keep the behavior same as before.  If this
4499 		 * restriction is removed or no longer valid in the future,
4500 		 * the checks below can be deleted.
4501 		 */
4502 		if ((p == tail) || (*(p - 1) == '/')) {
4503 			c = *(p + macrolen + 1);
4504 			if (c == '/' || c == '\0')
4505 				valid_macro = 1;
4506 		}
4507 	}
4508 
4509 	if (!valid_macro) {
4510 		p2 = strchr(p, '/');
4511 		/*
4512 		 * if no more macro to expand, then just copy whatever left
4513 		 * and check whether it exists
4514 		 */
4515 		if (p2 == NULL || strchr(p2, '$') == NULL) {
4516 			(void) strcpy(pathend, tail);
4517 			if ((file = kobj_open_path(path, 1, 1)) !=
4518 			    (struct _buf *)-1) {
4519 				kobj_close_file(file);
4520 				return (path);
4521 			} else
4522 				return (NULL);
4523 		} else {
4524 			/*
4525 			 * copy all chars before '/' and call expand_libmacro()
4526 			 * again
4527 			 */
4528 			diff = p2 - tail;
4529 			bcopy(tail, pathend, diff);
4530 			pathend += diff;
4531 			*(pathend) = '\0';
4532 			return (expand_libmacro(p2, path, pathend));
4533 		}
4534 	}
4535 
4536 	more_macro = 0;
4537 	if (c != '\0') {
4538 		endp = p + macrolen + 1;
4539 		if (strchr(endp, '$') != NULL)
4540 			more_macro = 1;
4541 	} else
4542 		endp = NULL;
4543 
4544 	/*
4545 	 * copy lmi_list and split it into components.
4546 	 * then put the part of tail before $MACRO into path
4547 	 * at pathend
4548 	 */
4549 	diff = p - tail;
4550 	if (diff > 0)
4551 		bcopy(tail, pathend, diff);
4552 	path2 = pathend + diff;
4553 	p1 = libmacros[lmi].lmi_list;
4554 	while (p1 && (*p1 != '\0')) {
4555 		p2 = strchr(p1, ':');
4556 		if (p2) {
4557 			diff = p2 - p1;
4558 			bcopy(p1, path2, diff);
4559 			*(path2 + diff) = '\0';
4560 		} else {
4561 			diff = strlen(p1);
4562 			bcopy(p1, path2, diff + 1);
4563 		}
4564 		/* copy endp only if there isn't any more macro to expand */
4565 		if (!more_macro && (endp != NULL))
4566 			(void) strcat(path2, endp);
4567 		file = kobj_open_path(path, 1, 1);
4568 		if (file != (struct _buf *)-1) {
4569 			kobj_close_file(file);
4570 			/*
4571 			 * if more macros to expand then call expand_libmacro(),
4572 			 * else return path which has the whole path
4573 			 */
4574 			if (!more_macro || (expand_libmacro(endp, path,
4575 			    path2 + diff) != NULL)) {
4576 				return (path);
4577 			}
4578 		}
4579 		if (p2)
4580 			p1 = ++p2;
4581 		else
4582 			return (NULL);
4583 	}
4584 	return (NULL);
4585 }
4586 
4587 char *kobj_file_buf;
4588 int kobj_file_bufsize;
4589 
4590 /*
4591  * This code is for the purpose of manually recording which files
4592  * needs to go into the boot archive on any given system.
4593  *
4594  * To enable the code, set kobj_file_bufsize in /etc/system
4595  * and reboot the system, then use mdb to look at kobj_file_buf.
4596  */
4597 static void
kobj_record_file(char * filename)4598 kobj_record_file(char *filename)
4599 {
4600 	static char *buf;
4601 	static int size = 0;
4602 	int n;
4603 
4604 	if (kobj_file_bufsize == 0)	/* don't bother */
4605 		return;
4606 
4607 	if (kobj_file_buf == NULL) {	/* allocate buffer */
4608 		size = kobj_file_bufsize;
4609 		buf = kobj_file_buf = kobj_alloc(size, KM_WAIT|KM_TMP);
4610 	}
4611 
4612 	n = snprintf(buf, size, "%s\n", filename);
4613 	if (n > size)
4614 		n = size;
4615 	size -= n;
4616 	buf += n;
4617 }
4618 
4619 static int
kobj_boot_fstat(int fd,struct bootstat * stp)4620 kobj_boot_fstat(int fd, struct bootstat *stp)
4621 {
4622 #if defined(_OBP)
4623 	if (!standalone && _ioquiesced)
4624 		return (-1);
4625 	return (BOP_FSTAT(ops, fd, stp));
4626 #else
4627 	return (BRD_FSTAT(bfs_ops, fd, stp));
4628 #endif
4629 }
4630 
4631 static int
kobj_boot_open(char * filename,int flags)4632 kobj_boot_open(char *filename, int flags)
4633 {
4634 #if defined(_OBP)
4635 
4636 	/*
4637 	 * If io via bootops is quiesced, it means boot is no longer
4638 	 * available to us.  We make it look as if we can't open the
4639 	 * named file - which is reasonably accurate.
4640 	 */
4641 	if (!standalone && _ioquiesced)
4642 		return (-1);
4643 
4644 	kobj_record_file(filename);
4645 	return (BOP_OPEN(filename, flags));
4646 #else /* x86 */
4647 	kobj_record_file(filename);
4648 	return (BRD_OPEN(bfs_ops, filename, flags));
4649 #endif
4650 }
4651 
4652 static int
kobj_boot_close(int fd)4653 kobj_boot_close(int fd)
4654 {
4655 #if defined(_OBP)
4656 	if (!standalone && _ioquiesced)
4657 		return (-1);
4658 
4659 	return (BOP_CLOSE(fd));
4660 #else /* x86 */
4661 	return (BRD_CLOSE(bfs_ops, fd));
4662 #endif
4663 }
4664 
4665 static int
kobj_boot_seek(int fd,off_t hi __unused,off_t lo)4666 kobj_boot_seek(int fd, off_t hi __unused, off_t lo)
4667 {
4668 #if defined(_OBP)
4669 	return (BOP_SEEK(fd, lo) == -1 ? -1 : 0);
4670 #else
4671 	return (BRD_SEEK(bfs_ops, fd, lo, SEEK_SET));
4672 #endif
4673 }
4674 
4675 static int
kobj_boot_read(int fd,caddr_t buf,size_t size)4676 kobj_boot_read(int fd, caddr_t buf, size_t size)
4677 {
4678 #if defined(_OBP)
4679 	return (BOP_READ(fd, buf, size));
4680 #else
4681 	return (BRD_READ(bfs_ops, fd, buf, size));
4682 #endif
4683 }
4684 
4685 static int
kobj_boot_compinfo(int fd,struct compinfo * cb)4686 kobj_boot_compinfo(int fd, struct compinfo *cb)
4687 {
4688 	return (boot_compinfo(fd, cb));
4689 }
4690 
4691 /*
4692  * Check if the file is compressed (for now we handle only gzip).
4693  * It returns CH_MAGIC_GZIP if the file is compressed and 0 otherwise.
4694  */
4695 static int
kobj_is_compressed(intptr_t fd)4696 kobj_is_compressed(intptr_t fd)
4697 {
4698 	struct vnode *vp = (struct vnode *)fd;
4699 	ssize_t resid;
4700 	uint16_t magic_buf;
4701 	int err = 0;
4702 
4703 	if ((err = vn_rdwr(UIO_READ, vp, (caddr_t)((intptr_t)&magic_buf),
4704 	    sizeof (magic_buf), (offset_t)(0),
4705 	    UIO_SYSSPACE, 0, (rlim64_t)0, CRED(), &resid)) != 0) {
4706 
4707 		_kobj_printf(ops, "kobj_is_compressed: vn_rdwr() failed, "
4708 		    "error code 0x%x\n", err);
4709 		return (0);
4710 	}
4711 
4712 	if (magic_buf == CH_MAGIC_GZIP)
4713 		return (CH_MAGIC_GZIP);
4714 
4715 	return (0);
4716 }
4717