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