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