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