xref: /illumos-gate/usr/src/lib/libproc/common/Psymtab.c (revision d51e90740114c60620c0febffd4d3ce6e280a107)
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 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <assert.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stddef.h>
33 #include <unistd.h>
34 #include <ctype.h>
35 #include <fcntl.h>
36 #include <string.h>
37 #include <strings.h>
38 #include <memory.h>
39 #include <errno.h>
40 #include <dirent.h>
41 #include <signal.h>
42 #include <limits.h>
43 #include <libgen.h>
44 #include <zone.h>
45 #include <sys/types.h>
46 #include <sys/stat.h>
47 #include <sys/systeminfo.h>
48 #include <sys/sysmacros.h>
49 
50 #include "libproc.h"
51 #include "Pcontrol.h"
52 #include "Putil.h"
53 #include "Psymtab_machelf.h"
54 
55 static file_info_t *build_map_symtab(struct ps_prochandle *, map_info_t *);
56 static map_info_t *exec_map(struct ps_prochandle *);
57 static map_info_t *object_to_map(struct ps_prochandle *, Lmid_t, const char *);
58 static map_info_t *object_name_to_map(struct ps_prochandle *,
59 	Lmid_t, const char *);
60 static GElf_Sym *sym_by_name(sym_tbl_t *, const char *, GElf_Sym *, uint_t *);
61 static int read_ehdr32(struct ps_prochandle *, Elf32_Ehdr *, uint_t *,
62     uintptr_t);
63 #ifdef _LP64
64 static int read_ehdr64(struct ps_prochandle *, Elf64_Ehdr *, uint_t *,
65     uintptr_t);
66 #endif
67 
68 #define	DATA_TYPES	\
69 	((1 << STT_OBJECT) | (1 << STT_FUNC) | \
70 	(1 << STT_COMMON) | (1 << STT_TLS))
71 #define	IS_DATA_TYPE(tp)	(((1 << (tp)) & DATA_TYPES) != 0)
72 
73 #define	MA_RWX	(MA_READ | MA_WRITE | MA_EXEC)
74 
75 typedef enum {
76 	PRO_NATURAL,
77 	PRO_BYADDR,
78 	PRO_BYNAME
79 } pr_order_t;
80 
81 static int
82 addr_cmp(const void *aa, const void *bb)
83 {
84 	uintptr_t a = *((uintptr_t *)aa);
85 	uintptr_t b = *((uintptr_t *)bb);
86 
87 	if (a > b)
88 		return (1);
89 	if (a < b)
90 		return (-1);
91 	return (0);
92 }
93 
94 /*
95  * This function creates a list of addresses for a load object's sections.
96  * The list is in ascending address order and alternates start address
97  * then end address for each section we're interested in. The function
98  * returns a pointer to the list, which must be freed by the caller.
99  */
100 static uintptr_t *
101 get_saddrs(struct ps_prochandle *P, uintptr_t ehdr_start, uint_t *n)
102 {
103 	uintptr_t a, addr, *addrs, last = 0;
104 	uint_t i, naddrs = 0, unordered = 0;
105 
106 	if (P->status.pr_dmodel == PR_MODEL_ILP32) {
107 		Elf32_Ehdr ehdr;
108 		Elf32_Phdr phdr;
109 		uint_t phnum;
110 
111 		if (read_ehdr32(P, &ehdr, &phnum, ehdr_start) != 0)
112 			return (NULL);
113 
114 		addrs = malloc(sizeof (uintptr_t) * phnum * 2);
115 		a = ehdr_start + ehdr.e_phoff;
116 		for (i = 0; i < phnum; i++, a += ehdr.e_phentsize) {
117 			if (Pread(P, &phdr, sizeof (phdr), a) !=
118 			    sizeof (phdr)) {
119 				free(addrs);
120 				return (NULL);
121 			}
122 			if (phdr.p_type != PT_LOAD || phdr.p_memsz == 0)
123 				continue;
124 
125 			addr = phdr.p_vaddr;
126 			if (ehdr.e_type == ET_DYN)
127 				addr += ehdr_start;
128 			if (last > addr)
129 				unordered = 1;
130 			addrs[naddrs++] = addr;
131 			addrs[naddrs++] = last = addr + phdr.p_memsz - 1;
132 		}
133 #ifdef _LP64
134 	} else {
135 		Elf64_Ehdr ehdr;
136 		Elf64_Phdr phdr;
137 		uint_t phnum;
138 
139 		if (read_ehdr64(P, &ehdr, &phnum, ehdr_start) != 0)
140 			return (NULL);
141 
142 		addrs = malloc(sizeof (uintptr_t) * phnum * 2);
143 		a = ehdr_start + ehdr.e_phoff;
144 		for (i = 0; i < phnum; i++, a += ehdr.e_phentsize) {
145 			if (Pread(P, &phdr, sizeof (phdr), a) !=
146 			    sizeof (phdr)) {
147 				free(addrs);
148 				return (NULL);
149 			}
150 			if (phdr.p_type != PT_LOAD || phdr.p_memsz == 0)
151 				continue;
152 
153 			addr = phdr.p_vaddr;
154 			if (ehdr.e_type == ET_DYN)
155 				addr += ehdr_start;
156 			if (last > addr)
157 				unordered = 1;
158 			addrs[naddrs++] = addr;
159 			addrs[naddrs++] = last = addr + phdr.p_memsz - 1;
160 		}
161 #endif
162 	}
163 
164 	if (unordered)
165 		qsort(addrs, naddrs, sizeof (uintptr_t), addr_cmp);
166 
167 	*n = naddrs;
168 	return (addrs);
169 }
170 
171 /*
172  * Allocation function for a new file_info_t
173  */
174 static file_info_t *
175 file_info_new(struct ps_prochandle *P, map_info_t *mptr)
176 {
177 	file_info_t *fptr;
178 	map_info_t *mp;
179 	uintptr_t addr;
180 	uint_t i, j;
181 
182 	if ((fptr = calloc(1, sizeof (file_info_t))) == NULL)
183 		return (NULL);
184 
185 	list_link(fptr, &P->file_head);
186 	(void) strcpy(fptr->file_pname, mptr->map_pmap.pr_mapname);
187 	mptr->map_file = fptr;
188 	fptr->file_ref = 1;
189 	fptr->file_fd = -1;
190 	P->num_files++;
191 
192 	/*
193 	 * To figure out which map_info_t instances correspond to the mappings
194 	 * for this load object we try to obtain the start and end address
195 	 * for each section of our in-memory ELF image. If successful, we
196 	 * walk down the list of addresses and the list of map_info_t
197 	 * instances in lock step to correctly find the mappings that
198 	 * correspond to this load object.
199 	 */
200 	if ((fptr->file_saddrs = get_saddrs(P, mptr->map_pmap.pr_vaddr,
201 	    &fptr->file_nsaddrs)) == NULL)
202 		return (fptr);
203 
204 	i = j = 0;
205 	mp = P->mappings;
206 	while (j < P->map_count && i < fptr->file_nsaddrs) {
207 		addr = fptr->file_saddrs[i];
208 		if (addr >= mp->map_pmap.pr_vaddr &&
209 		    addr < mp->map_pmap.pr_vaddr + mp->map_pmap.pr_size &&
210 		    mp->map_file == NULL) {
211 			mp->map_file = fptr;
212 			fptr->file_ref++;
213 		}
214 
215 		if (addr < mp->map_pmap.pr_vaddr + mp->map_pmap.pr_size) {
216 			i++;
217 		} else {
218 			mp++;
219 			j++;
220 		}
221 	}
222 
223 	return (fptr);
224 }
225 
226 /*
227  * Deallocation function for a file_info_t
228  */
229 static void
230 file_info_free(struct ps_prochandle *P, file_info_t *fptr)
231 {
232 	if (--fptr->file_ref == 0) {
233 		list_unlink(fptr);
234 		if (fptr->file_symtab.sym_elf) {
235 			(void) elf_end(fptr->file_symtab.sym_elf);
236 			free(fptr->file_symtab.sym_elfmem);
237 		}
238 		if (fptr->file_symtab.sym_byname)
239 			free(fptr->file_symtab.sym_byname);
240 		if (fptr->file_symtab.sym_byaddr)
241 			free(fptr->file_symtab.sym_byaddr);
242 
243 		if (fptr->file_dynsym.sym_elf) {
244 			(void) elf_end(fptr->file_dynsym.sym_elf);
245 			free(fptr->file_dynsym.sym_elfmem);
246 		}
247 		if (fptr->file_dynsym.sym_byname)
248 			free(fptr->file_dynsym.sym_byname);
249 		if (fptr->file_dynsym.sym_byaddr)
250 			free(fptr->file_dynsym.sym_byaddr);
251 
252 		if (fptr->file_lo)
253 			free(fptr->file_lo);
254 		if (fptr->file_lname)
255 			free(fptr->file_lname);
256 		if (fptr->file_elf)
257 			(void) elf_end(fptr->file_elf);
258 		if (fptr->file_elfmem != NULL)
259 			free(fptr->file_elfmem);
260 		if (fptr->file_fd >= 0)
261 			(void) close(fptr->file_fd);
262 		if (fptr->file_ctfp) {
263 			ctf_close(fptr->file_ctfp);
264 			free(fptr->file_ctf_buf);
265 		}
266 		if (fptr->file_saddrs)
267 			free(fptr->file_saddrs);
268 		free(fptr);
269 		P->num_files--;
270 	}
271 }
272 
273 /*
274  * Deallocation function for a map_info_t
275  */
276 static void
277 map_info_free(struct ps_prochandle *P, map_info_t *mptr)
278 {
279 	file_info_t *fptr;
280 
281 	if ((fptr = mptr->map_file) != NULL) {
282 		if (fptr->file_map == mptr)
283 			fptr->file_map = NULL;
284 		file_info_free(P, fptr);
285 	}
286 	if (P->execname && mptr == P->map_exec) {
287 		free(P->execname);
288 		P->execname = NULL;
289 	}
290 	if (P->auxv && (mptr == P->map_exec || mptr == P->map_ldso)) {
291 		free(P->auxv);
292 		P->auxv = NULL;
293 		P->nauxv = 0;
294 	}
295 	if (mptr == P->map_exec)
296 		P->map_exec = NULL;
297 	if (mptr == P->map_ldso)
298 		P->map_ldso = NULL;
299 }
300 
301 /*
302  * Call-back function for librtld_db to iterate through all of its shared
303  * libraries.  We use this to get the load object names for the mappings.
304  */
305 static int
306 map_iter(const rd_loadobj_t *lop, void *cd)
307 {
308 	char buf[PATH_MAX];
309 	struct ps_prochandle *P = cd;
310 	map_info_t *mptr;
311 	file_info_t *fptr;
312 
313 	dprintf("encountered rd object at %p\n", (void *)lop->rl_base);
314 
315 	if ((mptr = Paddr2mptr(P, lop->rl_base)) == NULL) {
316 		dprintf("map_iter: base address doesn't match any mapping\n");
317 		return (1); /* Base address does not match any mapping */
318 	}
319 
320 	if ((fptr = mptr->map_file) == NULL &&
321 	    (fptr = file_info_new(P, mptr)) == NULL) {
322 		dprintf("map_iter: failed to allocate a new file_info_t\n");
323 		return (1); /* Failed to allocate a new file_info_t */
324 	}
325 
326 	if ((fptr->file_lo == NULL) &&
327 	    (fptr->file_lo = malloc(sizeof (rd_loadobj_t))) == NULL) {
328 		dprintf("map_iter: failed to allocate rd_loadobj_t\n");
329 		file_info_free(P, fptr);
330 		return (1); /* Failed to allocate rd_loadobj_t */
331 	}
332 
333 	fptr->file_map = mptr;
334 	*fptr->file_lo = *lop;
335 
336 	fptr->file_lo->rl_plt_base = fptr->file_plt_base;
337 	fptr->file_lo->rl_plt_size = fptr->file_plt_size;
338 
339 	if (fptr->file_lname) {
340 		free(fptr->file_lname);
341 		fptr->file_lname = NULL;
342 	}
343 
344 	if (Pread_string(P, buf, sizeof (buf), lop->rl_nameaddr) > 0) {
345 		if ((fptr->file_lname = strdup(buf)) != NULL)
346 			fptr->file_lbase = basename(fptr->file_lname);
347 	} else {
348 		dprintf("map_iter: failed to read string at %p\n",
349 		    (void *)lop->rl_nameaddr);
350 	}
351 
352 	dprintf("loaded rd object %s lmid %lx\n",
353 	    fptr->file_lname ? fptr->file_lname : "<NULL>", lop->rl_lmident);
354 	return (1);
355 }
356 
357 static void
358 map_set(struct ps_prochandle *P, map_info_t *mptr, const char *lname)
359 {
360 	file_info_t *fptr;
361 
362 	if ((fptr = mptr->map_file) == NULL &&
363 	    (fptr = file_info_new(P, mptr)) == NULL)
364 		return; /* Failed to allocate a new file_info_t */
365 
366 	fptr->file_map = mptr;
367 
368 	if ((fptr->file_lo == NULL) &&
369 	    (fptr->file_lo = malloc(sizeof (rd_loadobj_t))) == NULL) {
370 		file_info_free(P, fptr);
371 		return; /* Failed to allocate rd_loadobj_t */
372 	}
373 
374 	(void) memset(fptr->file_lo, 0, sizeof (rd_loadobj_t));
375 	fptr->file_lo->rl_base = mptr->map_pmap.pr_vaddr;
376 	fptr->file_lo->rl_bend =
377 	    mptr->map_pmap.pr_vaddr + mptr->map_pmap.pr_size;
378 
379 	fptr->file_lo->rl_plt_base = fptr->file_plt_base;
380 	fptr->file_lo->rl_plt_size = fptr->file_plt_size;
381 
382 	if (fptr->file_lname == NULL &&
383 	    (fptr->file_lname = strdup(lname)) != NULL)
384 		fptr->file_lbase = basename(fptr->file_lname);
385 }
386 
387 static void
388 load_static_maps(struct ps_prochandle *P)
389 {
390 	map_info_t *mptr;
391 
392 	/*
393 	 * Construct the map for the a.out.
394 	 */
395 	if ((mptr = object_name_to_map(P, PR_LMID_EVERY, PR_OBJ_EXEC)) != NULL)
396 		map_set(P, mptr, "a.out");
397 
398 	/*
399 	 * If the dynamic linker exists for this process,
400 	 * construct the map for it.
401 	 */
402 	if (Pgetauxval(P, AT_BASE) != -1L &&
403 	    (mptr = object_name_to_map(P, PR_LMID_EVERY, PR_OBJ_LDSO)) != NULL)
404 		map_set(P, mptr, "ld.so.1");
405 }
406 
407 /*
408  * Go through all the address space mappings, validating or updating
409  * the information already gathered, or gathering new information.
410  *
411  * This function is only called when we suspect that the mappings have changed
412  * because this is the first time we're calling it or because of rtld activity.
413  */
414 void
415 Pupdate_maps(struct ps_prochandle *P)
416 {
417 	char mapfile[PATH_MAX];
418 	int mapfd;
419 	struct stat statb;
420 	prmap_t *Pmap = NULL;
421 	prmap_t *pmap;
422 	ssize_t nmap;
423 	int i;
424 	uint_t oldmapcount;
425 	map_info_t *newmap, *newp;
426 	map_info_t *mptr;
427 
428 	if (P->info_valid || P->state == PS_UNDEAD)
429 		return;
430 
431 	Preadauxvec(P);
432 
433 	(void) snprintf(mapfile, sizeof (mapfile), "%s/%d/map",
434 	    procfs_path, (int)P->pid);
435 	if ((mapfd = open(mapfile, O_RDONLY)) < 0 ||
436 	    fstat(mapfd, &statb) != 0 ||
437 	    statb.st_size < sizeof (prmap_t) ||
438 	    (Pmap = malloc(statb.st_size)) == NULL ||
439 	    (nmap = pread(mapfd, Pmap, statb.st_size, 0L)) <= 0 ||
440 	    (nmap /= sizeof (prmap_t)) == 0) {
441 		if (Pmap != NULL)
442 			free(Pmap);
443 		if (mapfd >= 0)
444 			(void) close(mapfd);
445 		Preset_maps(P);	/* utter failure; destroy tables */
446 		return;
447 	}
448 	(void) close(mapfd);
449 
450 	if ((newmap = calloc(1, nmap * sizeof (map_info_t))) == NULL)
451 		return;
452 
453 	/*
454 	 * We try to merge any file information we may have for existing
455 	 * mappings, to avoid having to rebuild the file info.
456 	 */
457 	mptr = P->mappings;
458 	pmap = Pmap;
459 	newp = newmap;
460 	oldmapcount = P->map_count;
461 	for (i = 0; i < nmap; i++, pmap++, newp++) {
462 
463 		if (oldmapcount == 0) {
464 			/*
465 			 * We've exhausted all the old mappings.  Every new
466 			 * mapping should be added.
467 			 */
468 			newp->map_pmap = *pmap;
469 
470 		} else if (pmap->pr_vaddr == mptr->map_pmap.pr_vaddr &&
471 		    pmap->pr_size == mptr->map_pmap.pr_size &&
472 		    pmap->pr_offset == mptr->map_pmap.pr_offset &&
473 		    (pmap->pr_mflags & ~(MA_BREAK | MA_STACK)) ==
474 		    (mptr->map_pmap.pr_mflags & ~(MA_BREAK | MA_STACK)) &&
475 		    pmap->pr_pagesize == mptr->map_pmap.pr_pagesize &&
476 		    pmap->pr_shmid == mptr->map_pmap.pr_shmid &&
477 		    strcmp(pmap->pr_mapname, mptr->map_pmap.pr_mapname) == 0) {
478 
479 			/*
480 			 * This mapping matches exactly.  Copy over the old
481 			 * mapping, taking care to get the latest flags.
482 			 * Make sure the associated file_info_t is updated
483 			 * appropriately.
484 			 */
485 			*newp = *mptr;
486 			if (P->map_exec == mptr)
487 				P->map_exec = newp;
488 			if (P->map_ldso == mptr)
489 				P->map_ldso = newp;
490 			newp->map_pmap.pr_mflags = pmap->pr_mflags;
491 			if (mptr->map_file != NULL &&
492 			    mptr->map_file->file_map == mptr)
493 				mptr->map_file->file_map = newp;
494 			oldmapcount--;
495 			mptr++;
496 
497 		} else if (pmap->pr_vaddr + pmap->pr_size >
498 		    mptr->map_pmap.pr_vaddr) {
499 
500 			/*
501 			 * The old mapping doesn't exist any more, remove it
502 			 * from the list.
503 			 */
504 			map_info_free(P, mptr);
505 			oldmapcount--;
506 			i--;
507 			newp--;
508 			pmap--;
509 			mptr++;
510 
511 		} else {
512 
513 			/*
514 			 * This is a new mapping, add it directly.
515 			 */
516 			newp->map_pmap = *pmap;
517 		}
518 	}
519 
520 	/*
521 	 * Free any old maps
522 	 */
523 	while (oldmapcount) {
524 		map_info_free(P, mptr);
525 		oldmapcount--;
526 		mptr++;
527 	}
528 
529 	free(Pmap);
530 	if (P->mappings != NULL)
531 		free(P->mappings);
532 	P->mappings = newmap;
533 	P->map_count = P->map_alloc = nmap;
534 	P->info_valid = 1;
535 
536 	/*
537 	 * Consult librtld_db to get the load object
538 	 * names for all of the shared libraries.
539 	 */
540 	if (P->rap != NULL)
541 		(void) rd_loadobj_iter(P->rap, map_iter, P);
542 }
543 
544 /*
545  * Update all of the mappings and rtld_db as if by Pupdate_maps(), and then
546  * forcibly cache all of the symbol tables associated with all object files.
547  */
548 void
549 Pupdate_syms(struct ps_prochandle *P)
550 {
551 	file_info_t *fptr = list_next(&P->file_head);
552 	int i;
553 
554 	Pupdate_maps(P);
555 
556 	for (i = 0; i < P->num_files; i++, fptr = list_next(fptr)) {
557 		Pbuild_file_symtab(P, fptr);
558 		(void) Pbuild_file_ctf(P, fptr);
559 	}
560 }
561 
562 /*
563  * Return the librtld_db agent handle for the victim process.
564  * The handle will become invalid at the next successful exec() and the
565  * client (caller of proc_rd_agent()) must not use it beyond that point.
566  * If the process is already dead, we've already tried our best to
567  * create the agent during core file initialization.
568  */
569 rd_agent_t *
570 Prd_agent(struct ps_prochandle *P)
571 {
572 	if (P->rap == NULL && P->state != PS_DEAD && P->state != PS_IDLE) {
573 		Pupdate_maps(P);
574 		if (P->num_files == 0)
575 			load_static_maps(P);
576 		rd_log(_libproc_debug);
577 		if ((P->rap = rd_new(P)) != NULL)
578 			(void) rd_loadobj_iter(P->rap, map_iter, P);
579 	}
580 	return (P->rap);
581 }
582 
583 /*
584  * Return the prmap_t structure containing 'addr', but only if it
585  * is in the dynamic linker's link map and is the text section.
586  */
587 const prmap_t *
588 Paddr_to_text_map(struct ps_prochandle *P, uintptr_t addr)
589 {
590 	map_info_t *mptr;
591 
592 	if (!P->info_valid)
593 		Pupdate_maps(P);
594 
595 	if ((mptr = Paddr2mptr(P, addr)) != NULL) {
596 		file_info_t *fptr = build_map_symtab(P, mptr);
597 		const prmap_t *pmp = &mptr->map_pmap;
598 
599 		if (fptr != NULL && fptr->file_lo != NULL &&
600 		    fptr->file_lo->rl_base >= pmp->pr_vaddr &&
601 		    fptr->file_lo->rl_base < pmp->pr_vaddr + pmp->pr_size)
602 			return (pmp);
603 	}
604 
605 	return (NULL);
606 }
607 
608 /*
609  * Return the prmap_t structure containing 'addr' (no restrictions on
610  * the type of mapping).
611  */
612 const prmap_t *
613 Paddr_to_map(struct ps_prochandle *P, uintptr_t addr)
614 {
615 	map_info_t *mptr;
616 
617 	if (!P->info_valid)
618 		Pupdate_maps(P);
619 
620 	if ((mptr = Paddr2mptr(P, addr)) != NULL)
621 		return (&mptr->map_pmap);
622 
623 	return (NULL);
624 }
625 
626 /*
627  * Convert a full or partial load object name to the prmap_t for its
628  * corresponding primary text mapping.
629  */
630 const prmap_t *
631 Plmid_to_map(struct ps_prochandle *P, Lmid_t lmid, const char *name)
632 {
633 	map_info_t *mptr;
634 
635 	if (name == PR_OBJ_EVERY)
636 		return (NULL); /* A reasonable mistake */
637 
638 	if ((mptr = object_name_to_map(P, lmid, name)) != NULL)
639 		return (&mptr->map_pmap);
640 
641 	return (NULL);
642 }
643 
644 const prmap_t *
645 Pname_to_map(struct ps_prochandle *P, const char *name)
646 {
647 	return (Plmid_to_map(P, PR_LMID_EVERY, name));
648 }
649 
650 const rd_loadobj_t *
651 Paddr_to_loadobj(struct ps_prochandle *P, uintptr_t addr)
652 {
653 	map_info_t *mptr;
654 
655 	if (!P->info_valid)
656 		Pupdate_maps(P);
657 
658 	if ((mptr = Paddr2mptr(P, addr)) == NULL)
659 		return (NULL);
660 
661 	/*
662 	 * By building the symbol table, we implicitly bring the PLT
663 	 * information up to date in the load object.
664 	 */
665 	(void) build_map_symtab(P, mptr);
666 
667 	return (mptr->map_file->file_lo);
668 }
669 
670 const rd_loadobj_t *
671 Plmid_to_loadobj(struct ps_prochandle *P, Lmid_t lmid, const char *name)
672 {
673 	map_info_t *mptr;
674 
675 	if (name == PR_OBJ_EVERY)
676 		return (NULL);
677 
678 	if ((mptr = object_name_to_map(P, lmid, name)) == NULL)
679 		return (NULL);
680 
681 	/*
682 	 * By building the symbol table, we implicitly bring the PLT
683 	 * information up to date in the load object.
684 	 */
685 	(void) build_map_symtab(P, mptr);
686 
687 	return (mptr->map_file->file_lo);
688 }
689 
690 const rd_loadobj_t *
691 Pname_to_loadobj(struct ps_prochandle *P, const char *name)
692 {
693 	return (Plmid_to_loadobj(P, PR_LMID_EVERY, name));
694 }
695 
696 ctf_file_t *
697 Pbuild_file_ctf(struct ps_prochandle *P, file_info_t *fptr)
698 {
699 	ctf_sect_t ctdata, symtab, strtab;
700 	sym_tbl_t *symp;
701 	int err;
702 
703 	if (fptr->file_ctfp != NULL)
704 		return (fptr->file_ctfp);
705 
706 	Pbuild_file_symtab(P, fptr);
707 
708 	if (fptr->file_ctf_size == 0)
709 		return (NULL);
710 
711 	symp = fptr->file_ctf_dyn ? &fptr->file_dynsym : &fptr->file_symtab;
712 	if (symp->sym_data_pri == NULL)
713 		return (NULL);
714 
715 	/*
716 	 * The buffer may alread be allocated if this is a core file that
717 	 * contained CTF data for this file.
718 	 */
719 	if (fptr->file_ctf_buf == NULL) {
720 		fptr->file_ctf_buf = malloc(fptr->file_ctf_size);
721 		if (fptr->file_ctf_buf == NULL) {
722 			dprintf("failed to allocate ctf buffer\n");
723 			return (NULL);
724 		}
725 
726 		if (pread(fptr->file_fd, fptr->file_ctf_buf,
727 		    fptr->file_ctf_size, fptr->file_ctf_off) !=
728 		    fptr->file_ctf_size) {
729 			free(fptr->file_ctf_buf);
730 			fptr->file_ctf_buf = NULL;
731 			dprintf("failed to read ctf data\n");
732 			return (NULL);
733 		}
734 	}
735 
736 	ctdata.cts_name = ".SUNW_ctf";
737 	ctdata.cts_type = SHT_PROGBITS;
738 	ctdata.cts_flags = 0;
739 	ctdata.cts_data = fptr->file_ctf_buf;
740 	ctdata.cts_size = fptr->file_ctf_size;
741 	ctdata.cts_entsize = 1;
742 	ctdata.cts_offset = 0;
743 
744 	symtab.cts_name = fptr->file_ctf_dyn ? ".dynsym" : ".symtab";
745 	symtab.cts_type = symp->sym_hdr_pri.sh_type;
746 	symtab.cts_flags = symp->sym_hdr_pri.sh_flags;
747 	symtab.cts_data = symp->sym_data_pri->d_buf;
748 	symtab.cts_size = symp->sym_hdr_pri.sh_size;
749 	symtab.cts_entsize = symp->sym_hdr_pri.sh_entsize;
750 	symtab.cts_offset = symp->sym_hdr_pri.sh_offset;
751 
752 	strtab.cts_name = fptr->file_ctf_dyn ? ".dynstr" : ".strtab";
753 	strtab.cts_type = symp->sym_strhdr.sh_type;
754 	strtab.cts_flags = symp->sym_strhdr.sh_flags;
755 	strtab.cts_data = symp->sym_strs;
756 	strtab.cts_size = symp->sym_strhdr.sh_size;
757 	strtab.cts_entsize = symp->sym_strhdr.sh_entsize;
758 	strtab.cts_offset = symp->sym_strhdr.sh_offset;
759 
760 	fptr->file_ctfp = ctf_bufopen(&ctdata, &symtab, &strtab, &err);
761 	if (fptr->file_ctfp == NULL) {
762 		free(fptr->file_ctf_buf);
763 		fptr->file_ctf_buf = NULL;
764 		return (NULL);
765 	}
766 
767 	dprintf("loaded %lu bytes of CTF data for %s\n",
768 	    (ulong_t)fptr->file_ctf_size, fptr->file_pname);
769 
770 	return (fptr->file_ctfp);
771 }
772 
773 ctf_file_t *
774 Paddr_to_ctf(struct ps_prochandle *P, uintptr_t addr)
775 {
776 	map_info_t *mptr;
777 	file_info_t *fptr;
778 
779 	if (!P->info_valid)
780 		Pupdate_maps(P);
781 
782 	if ((mptr = Paddr2mptr(P, addr)) == NULL ||
783 	    (fptr = mptr->map_file) == NULL)
784 		return (NULL);
785 
786 	return (Pbuild_file_ctf(P, fptr));
787 }
788 
789 ctf_file_t *
790 Plmid_to_ctf(struct ps_prochandle *P, Lmid_t lmid, const char *name)
791 {
792 	map_info_t *mptr;
793 	file_info_t *fptr;
794 
795 	if (name == PR_OBJ_EVERY)
796 		return (NULL);
797 
798 	if ((mptr = object_name_to_map(P, lmid, name)) == NULL ||
799 	    (fptr = mptr->map_file) == NULL)
800 		return (NULL);
801 
802 	return (Pbuild_file_ctf(P, fptr));
803 }
804 
805 ctf_file_t *
806 Pname_to_ctf(struct ps_prochandle *P, const char *name)
807 {
808 	return (Plmid_to_ctf(P, PR_LMID_EVERY, name));
809 }
810 
811 /*
812  * If we're not a core file, re-read the /proc/<pid>/auxv file and store
813  * its contents in P->auxv.  In the case of a core file, we either
814  * initialized P->auxv in Pcore() from the NT_AUXV, or we don't have an
815  * auxv because the note was missing.
816  */
817 void
818 Preadauxvec(struct ps_prochandle *P)
819 {
820 	char auxfile[64];
821 	struct stat statb;
822 	ssize_t naux;
823 	int fd;
824 
825 	if (P->state == PS_DEAD)
826 		return; /* Already read during Pgrab_core() */
827 	if (P->state == PS_IDLE)
828 		return; /* No aux vec for Pgrab_file() */
829 
830 	if (P->auxv != NULL) {
831 		free(P->auxv);
832 		P->auxv = NULL;
833 		P->nauxv = 0;
834 	}
835 
836 	(void) snprintf(auxfile, sizeof (auxfile), "%s/%d/auxv",
837 	    procfs_path, (int)P->pid);
838 	if ((fd = open(auxfile, O_RDONLY)) < 0)
839 		return;
840 
841 	if (fstat(fd, &statb) == 0 &&
842 	    statb.st_size >= sizeof (auxv_t) &&
843 	    (P->auxv = malloc(statb.st_size + sizeof (auxv_t))) != NULL) {
844 		if ((naux = read(fd, P->auxv, statb.st_size)) < 0 ||
845 		    (naux /= sizeof (auxv_t)) < 1) {
846 			free(P->auxv);
847 			P->auxv = NULL;
848 		} else {
849 			P->auxv[naux].a_type = AT_NULL;
850 			P->auxv[naux].a_un.a_val = 0L;
851 			P->nauxv = (int)naux;
852 		}
853 	}
854 
855 	(void) close(fd);
856 }
857 
858 /*
859  * Return a requested element from the process's aux vector.
860  * Return -1 on failure (this is adequate for our purposes).
861  */
862 long
863 Pgetauxval(struct ps_prochandle *P, int type)
864 {
865 	auxv_t *auxv;
866 
867 	if (P->auxv == NULL)
868 		Preadauxvec(P);
869 
870 	if (P->auxv == NULL)
871 		return (-1);
872 
873 	for (auxv = P->auxv; auxv->a_type != AT_NULL; auxv++) {
874 		if (auxv->a_type == type)
875 			return (auxv->a_un.a_val);
876 	}
877 
878 	return (-1);
879 }
880 
881 /*
882  * Return a pointer to our internal copy of the process's aux vector.
883  * The caller should not hold on to this pointer across any libproc calls.
884  */
885 const auxv_t *
886 Pgetauxvec(struct ps_prochandle *P)
887 {
888 	static const auxv_t empty = { AT_NULL, 0L };
889 
890 	if (P->auxv == NULL)
891 		Preadauxvec(P);
892 
893 	if (P->auxv == NULL)
894 		return (&empty);
895 
896 	return (P->auxv);
897 }
898 
899 /*
900  * Return 1 if the given mapping corresponds to the given file_info_t's
901  * load object; return 0 otherwise.
902  */
903 static int
904 is_mapping_in_file(struct ps_prochandle *P, map_info_t *mptr, file_info_t *fptr)
905 {
906 	prmap_t *pmap = &mptr->map_pmap;
907 	rd_loadobj_t *lop = fptr->file_lo;
908 	uint_t i;
909 
910 	/*
911 	 * We can get for free the start address of the text and data
912 	 * sections of the load object. Start by seeing if the mapping
913 	 * encloses either of these.
914 	 */
915 	if ((pmap->pr_vaddr <= lop->rl_base &&
916 	    lop->rl_base < pmap->pr_vaddr + pmap->pr_size) ||
917 	    (pmap->pr_vaddr <= lop->rl_data_base &&
918 	    lop->rl_data_base < pmap->pr_vaddr + pmap->pr_size))
919 		return (1);
920 
921 	/*
922 	 * It's still possible that this mapping correponds to the load
923 	 * object. Consider the example of a mapping whose start and end
924 	 * addresses correspond to those of the load object's text section.
925 	 * If the mapping splits, e.g. as a result of a segment demotion,
926 	 * then although both mappings are still backed by the same section,
927 	 * only one will be seen to enclose that section's start address.
928 	 * Thus, to be rigorous, we ask not whether this mapping encloses
929 	 * the start of a section, but whether there exists a section that
930 	 * encloses the start of this mapping.
931 	 *
932 	 * If we don't already have the section addresses, and we successfully
933 	 * get them, then we cache them in case we come here again.
934 	 */
935 	if (fptr->file_saddrs == NULL &&
936 	    (fptr->file_saddrs = get_saddrs(P,
937 	    fptr->file_map->map_pmap.pr_vaddr, &fptr->file_nsaddrs)) == NULL)
938 		return (0);
939 	for (i = 0; i < fptr->file_nsaddrs; i += 2) {
940 		/* Does this section enclose the start of the mapping? */
941 		if (fptr->file_saddrs[i] <= pmap->pr_vaddr &&
942 		    fptr->file_saddrs[i + 1] > pmap->pr_vaddr)
943 			return (1);
944 	}
945 
946 	return (0);
947 }
948 
949 /*
950  * Find or build the symbol table for the given mapping.
951  */
952 static file_info_t *
953 build_map_symtab(struct ps_prochandle *P, map_info_t *mptr)
954 {
955 	prmap_t *pmap = &mptr->map_pmap;
956 	file_info_t *fptr;
957 	uint_t i;
958 
959 	if ((fptr = mptr->map_file) != NULL) {
960 		Pbuild_file_symtab(P, fptr);
961 		return (fptr);
962 	}
963 
964 	if (pmap->pr_mapname[0] == '\0')
965 		return (NULL);
966 
967 	/*
968 	 * Attempt to find a matching file.
969 	 * (A file can be mapped at several different addresses.)
970 	 */
971 	for (i = 0, fptr = list_next(&P->file_head); i < P->num_files;
972 	    i++, fptr = list_next(fptr)) {
973 		if (strcmp(fptr->file_pname, pmap->pr_mapname) == 0 &&
974 		    fptr->file_lo && is_mapping_in_file(P, mptr, fptr)) {
975 			mptr->map_file = fptr;
976 			fptr->file_ref++;
977 			Pbuild_file_symtab(P, fptr);
978 			return (fptr);
979 		}
980 	}
981 
982 	/*
983 	 * If we need to create a new file_info structure, iterate
984 	 * through the load objects in order to attempt to connect
985 	 * this new file with its primary text mapping.  We again
986 	 * need to handle ld.so as a special case because we need
987 	 * to be able to bootstrap librtld_db.
988 	 */
989 	if ((fptr = file_info_new(P, mptr)) == NULL)
990 		return (NULL);
991 
992 	if (P->map_ldso != mptr) {
993 		if (P->rap != NULL)
994 			(void) rd_loadobj_iter(P->rap, map_iter, P);
995 		else
996 			(void) Prd_agent(P);
997 	} else {
998 		fptr->file_map = mptr;
999 	}
1000 
1001 	/*
1002 	 * If librtld_db wasn't able to help us connect the file to a primary
1003 	 * text mapping, set file_map to the current mapping because we require
1004 	 * fptr->file_map to be set in Pbuild_file_symtab.  librtld_db may be
1005 	 * unaware of what's going on in the rare case that a legitimate ELF
1006 	 * file has been mmap(2)ed into the process address space *without*
1007 	 * the use of dlopen(3x).
1008 	 */
1009 	if (fptr->file_map == NULL)
1010 		fptr->file_map = mptr;
1011 
1012 	Pbuild_file_symtab(P, fptr);
1013 
1014 	return (fptr);
1015 }
1016 
1017 static int
1018 read_ehdr32(struct ps_prochandle *P, Elf32_Ehdr *ehdr, uint_t *phnum,
1019     uintptr_t addr)
1020 {
1021 	if (Pread(P, ehdr, sizeof (*ehdr), addr) != sizeof (*ehdr))
1022 		return (-1);
1023 
1024 	if (ehdr->e_ident[EI_MAG0] != ELFMAG0 ||
1025 	    ehdr->e_ident[EI_MAG1] != ELFMAG1 ||
1026 	    ehdr->e_ident[EI_MAG2] != ELFMAG2 ||
1027 	    ehdr->e_ident[EI_MAG3] != ELFMAG3 ||
1028 	    ehdr->e_ident[EI_CLASS] != ELFCLASS32 ||
1029 #ifdef _BIG_ENDIAN
1030 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB ||
1031 #else
1032 	    ehdr->e_ident[EI_DATA] != ELFDATA2LSB ||
1033 #endif
1034 	    ehdr->e_ident[EI_VERSION] != EV_CURRENT)
1035 		return (-1);
1036 
1037 	if ((*phnum = ehdr->e_phnum) == PN_XNUM) {
1038 		Elf32_Shdr shdr0;
1039 
1040 		if (ehdr->e_shoff == 0 || ehdr->e_shentsize < sizeof (shdr0) ||
1041 		    Pread(P, &shdr0, sizeof (shdr0), addr + ehdr->e_shoff) !=
1042 		    sizeof (shdr0))
1043 			return (-1);
1044 
1045 		if (shdr0.sh_info != 0)
1046 			*phnum = shdr0.sh_info;
1047 	}
1048 
1049 	return (0);
1050 }
1051 
1052 static int
1053 read_dynamic_phdr32(struct ps_prochandle *P, const Elf32_Ehdr *ehdr,
1054     uint_t phnum, Elf32_Phdr *phdr, uintptr_t addr)
1055 {
1056 	uint_t i;
1057 
1058 	for (i = 0; i < phnum; i++) {
1059 		uintptr_t a = addr + ehdr->e_phoff + i * ehdr->e_phentsize;
1060 		if (Pread(P, phdr, sizeof (*phdr), a) != sizeof (*phdr))
1061 			return (-1);
1062 
1063 		if (phdr->p_type == PT_DYNAMIC)
1064 			return (0);
1065 	}
1066 
1067 	return (-1);
1068 }
1069 
1070 #ifdef _LP64
1071 static int
1072 read_ehdr64(struct ps_prochandle *P, Elf64_Ehdr *ehdr, uint_t *phnum,
1073     uintptr_t addr)
1074 {
1075 	if (Pread(P, ehdr, sizeof (Elf64_Ehdr), addr) != sizeof (Elf64_Ehdr))
1076 		return (-1);
1077 
1078 	if (ehdr->e_ident[EI_MAG0] != ELFMAG0 ||
1079 	    ehdr->e_ident[EI_MAG1] != ELFMAG1 ||
1080 	    ehdr->e_ident[EI_MAG2] != ELFMAG2 ||
1081 	    ehdr->e_ident[EI_MAG3] != ELFMAG3 ||
1082 	    ehdr->e_ident[EI_CLASS] != ELFCLASS64 ||
1083 #ifdef _BIG_ENDIAN
1084 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB ||
1085 #else
1086 	    ehdr->e_ident[EI_DATA] != ELFDATA2LSB ||
1087 #endif
1088 	    ehdr->e_ident[EI_VERSION] != EV_CURRENT)
1089 		return (-1);
1090 
1091 	if ((*phnum = ehdr->e_phnum) == PN_XNUM) {
1092 		Elf64_Shdr shdr0;
1093 
1094 		if (ehdr->e_shoff == 0 || ehdr->e_shentsize < sizeof (shdr0) ||
1095 		    Pread(P, &shdr0, sizeof (shdr0), addr + ehdr->e_shoff) !=
1096 		    sizeof (shdr0))
1097 			return (-1);
1098 
1099 		if (shdr0.sh_info != 0)
1100 			*phnum = shdr0.sh_info;
1101 	}
1102 
1103 	return (0);
1104 }
1105 
1106 static int
1107 read_dynamic_phdr64(struct ps_prochandle *P, const Elf64_Ehdr *ehdr,
1108     uint_t phnum, Elf64_Phdr *phdr, uintptr_t addr)
1109 {
1110 	uint_t i;
1111 
1112 	for (i = 0; i < phnum; i++) {
1113 		uintptr_t a = addr + ehdr->e_phoff + i * ehdr->e_phentsize;
1114 		if (Pread(P, phdr, sizeof (*phdr), a) != sizeof (*phdr))
1115 			return (-1);
1116 
1117 		if (phdr->p_type == PT_DYNAMIC)
1118 			return (0);
1119 	}
1120 
1121 	return (-1);
1122 }
1123 #endif	/* _LP64 */
1124 
1125 /*
1126  * The text segment for each load object contains the elf header and
1127  * program headers. We can use this information to determine if the
1128  * file that corresponds to the load object is the same file that
1129  * was loaded into the process's address space. There can be a discrepency
1130  * if a file is recompiled after the process is started or if the target
1131  * represents a core file from a differently configured system -- two
1132  * common examples. The DT_CHECKSUM entry in the dynamic section
1133  * provides an easy method of comparison. It is important to note that
1134  * the dynamic section usually lives in the data segment, but the meta
1135  * data we use to find the dynamic section lives in the text segment so
1136  * if either of those segments is absent we can't proceed.
1137  *
1138  * We're looking through the elf file for several items: the symbol tables
1139  * (both dynsym and symtab), the procedure linkage table (PLT) base,
1140  * size, and relocation base, and the CTF information. Most of this can
1141  * be recovered from the loaded image of the file itself, the exceptions
1142  * being the symtab and CTF data.
1143  *
1144  * First we try to open the file that we think corresponds to the load
1145  * object, if the DT_CHECKSUM values match, we're all set, and can simply
1146  * recover all the information we need from the file. If the values of
1147  * DT_CHECKSUM don't match, or if we can't access the file for whatever
1148  * reasaon, we fake up a elf file to use in its stead. If we can't read
1149  * the elf data in the process's address space, we fall back to using
1150  * the file even though it may give inaccurate information.
1151  *
1152  * The elf file that we fake up has to consist of sections for the
1153  * dynsym, the PLT and the dynamic section. Note that in the case of a
1154  * core file, we'll get the CTF data in the file_info_t later on from
1155  * a section embedded the core file (if it's present).
1156  *
1157  * file_differs() conservatively looks for mismatched files, identifying
1158  * a match when there is any ambiguity (since that's the legacy behavior).
1159  */
1160 static int
1161 file_differs(struct ps_prochandle *P, Elf *elf, file_info_t *fptr)
1162 {
1163 	Elf_Scn *scn;
1164 	GElf_Shdr shdr;
1165 	GElf_Dyn dyn;
1166 	Elf_Data *data;
1167 	uint_t i, ndyn;
1168 	GElf_Xword cksum;
1169 	uintptr_t addr;
1170 
1171 	if (fptr->file_map == NULL)
1172 		return (0);
1173 
1174 	if ((Pcontent(P) & (CC_CONTENT_TEXT | CC_CONTENT_DATA)) !=
1175 	    (CC_CONTENT_TEXT | CC_CONTENT_DATA))
1176 		return (0);
1177 
1178 	/*
1179 	 * First, we find the checksum value in the elf file.
1180 	 */
1181 	scn = NULL;
1182 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
1183 		if (gelf_getshdr(scn, &shdr) != NULL &&
1184 		    shdr.sh_type == SHT_DYNAMIC)
1185 			goto found_shdr;
1186 	}
1187 	return (0);
1188 
1189 found_shdr:
1190 	if ((data = elf_getdata(scn, NULL)) == NULL)
1191 		return (0);
1192 
1193 	if (P->status.pr_dmodel == PR_MODEL_ILP32)
1194 		ndyn = shdr.sh_size / sizeof (Elf32_Dyn);
1195 #ifdef _LP64
1196 	else if (P->status.pr_dmodel == PR_MODEL_LP64)
1197 		ndyn = shdr.sh_size / sizeof (Elf64_Dyn);
1198 #endif
1199 	else
1200 		return (0);
1201 
1202 	for (i = 0; i < ndyn; i++) {
1203 		if (gelf_getdyn(data, i, &dyn) != NULL &&
1204 		    dyn.d_tag == DT_CHECKSUM)
1205 			goto found_cksum;
1206 	}
1207 
1208 	/*
1209 	 * The in-memory ELF has no DT_CHECKSUM section, but we will report it
1210 	 * as matching the file anyhow.
1211 	 */
1212 	return (0);
1213 
1214 found_cksum:
1215 	cksum = dyn.d_un.d_val;
1216 	dprintf("elf cksum value is %llx\n", (u_longlong_t)cksum);
1217 
1218 	/*
1219 	 * Get the base of the text mapping that corresponds to this file.
1220 	 */
1221 	addr = fptr->file_map->map_pmap.pr_vaddr;
1222 
1223 	if (P->status.pr_dmodel == PR_MODEL_ILP32) {
1224 		Elf32_Ehdr ehdr;
1225 		Elf32_Phdr phdr;
1226 		Elf32_Dyn dync, *dynp;
1227 		uint_t phnum, i;
1228 
1229 		if (read_ehdr32(P, &ehdr, &phnum, addr) != 0 ||
1230 		    read_dynamic_phdr32(P, &ehdr, phnum, &phdr, addr) != 0)
1231 			return (0);
1232 
1233 		if (ehdr.e_type == ET_DYN)
1234 			phdr.p_vaddr += addr;
1235 		if ((dynp = malloc(phdr.p_filesz)) == NULL)
1236 			return (0);
1237 		dync.d_tag = DT_NULL;
1238 		if (Pread(P, dynp, phdr.p_filesz, phdr.p_vaddr) !=
1239 		    phdr.p_filesz) {
1240 			free(dynp);
1241 			return (0);
1242 		}
1243 
1244 		for (i = 0; i < phdr.p_filesz / sizeof (Elf32_Dyn); i++) {
1245 			if (dynp[i].d_tag == DT_CHECKSUM)
1246 				dync = dynp[i];
1247 		}
1248 
1249 		free(dynp);
1250 
1251 		if (dync.d_tag != DT_CHECKSUM)
1252 			return (0);
1253 
1254 		dprintf("image cksum value is %llx\n",
1255 		    (u_longlong_t)dync.d_un.d_val);
1256 		return (dync.d_un.d_val != cksum);
1257 #ifdef _LP64
1258 	} else if (P->status.pr_dmodel == PR_MODEL_LP64) {
1259 		Elf64_Ehdr ehdr;
1260 		Elf64_Phdr phdr;
1261 		Elf64_Dyn dync, *dynp;
1262 		uint_t phnum, i;
1263 
1264 		if (read_ehdr64(P, &ehdr, &phnum, addr) != 0 ||
1265 		    read_dynamic_phdr64(P, &ehdr, phnum, &phdr, addr) != 0)
1266 			return (0);
1267 
1268 		if (ehdr.e_type == ET_DYN)
1269 			phdr.p_vaddr += addr;
1270 		if ((dynp = malloc(phdr.p_filesz)) == NULL)
1271 			return (0);
1272 		dync.d_tag = DT_NULL;
1273 		if (Pread(P, dynp, phdr.p_filesz, phdr.p_vaddr) !=
1274 		    phdr.p_filesz) {
1275 			free(dynp);
1276 			return (0);
1277 		}
1278 
1279 		for (i = 0; i < phdr.p_filesz / sizeof (Elf64_Dyn); i++) {
1280 			if (dynp[i].d_tag == DT_CHECKSUM)
1281 				dync = dynp[i];
1282 		}
1283 
1284 		free(dynp);
1285 
1286 		if (dync.d_tag != DT_CHECKSUM)
1287 			return (0);
1288 
1289 		dprintf("image cksum value is %llx\n",
1290 		    (u_longlong_t)dync.d_un.d_val);
1291 		return (dync.d_un.d_val != cksum);
1292 #endif	/* _LP64 */
1293 	}
1294 
1295 	return (0);
1296 }
1297 
1298 /*
1299  * Read data from the specified process and construct an in memory
1300  * image of an ELF file that represents it well enough to let
1301  * us probe it for information.
1302  */
1303 static Elf *
1304 fake_elf(struct ps_prochandle *P, file_info_t *fptr)
1305 {
1306 	Elf *elf;
1307 	uintptr_t addr;
1308 	uint_t phnum;
1309 
1310 	if (fptr->file_map == NULL)
1311 		return (NULL);
1312 
1313 	if ((Pcontent(P) & (CC_CONTENT_TEXT | CC_CONTENT_DATA)) !=
1314 	    (CC_CONTENT_TEXT | CC_CONTENT_DATA))
1315 		return (NULL);
1316 
1317 	addr = fptr->file_map->map_pmap.pr_vaddr;
1318 
1319 	if (P->status.pr_dmodel == PR_MODEL_ILP32) {
1320 		Elf32_Ehdr ehdr;
1321 		Elf32_Phdr phdr;
1322 
1323 		if ((read_ehdr32(P, &ehdr, &phnum, addr) != 0) ||
1324 		    read_dynamic_phdr32(P, &ehdr, phnum, &phdr, addr) != 0)
1325 			return (NULL);
1326 
1327 		elf = fake_elf32(P, fptr, addr, &ehdr, phnum, &phdr);
1328 #ifdef _LP64
1329 	} else {
1330 		Elf64_Ehdr ehdr;
1331 		Elf64_Phdr phdr;
1332 
1333 		if (read_ehdr64(P, &ehdr, &phnum, addr) != 0 ||
1334 		    read_dynamic_phdr64(P, &ehdr, phnum, &phdr, addr) != 0)
1335 			return (NULL);
1336 
1337 		elf = fake_elf64(P, fptr, addr, &ehdr, phnum, &phdr);
1338 #endif
1339 	}
1340 
1341 	return (elf);
1342 }
1343 
1344 /*
1345  * We wouldn't need these if qsort(3C) took an argument for the callback...
1346  */
1347 static mutex_t sort_mtx = DEFAULTMUTEX;
1348 static char *sort_strs;
1349 static GElf_Sym *sort_syms;
1350 
1351 int
1352 byaddr_cmp_common(GElf_Sym *a, char *aname, GElf_Sym *b, char *bname)
1353 {
1354 	if (a->st_value < b->st_value)
1355 		return (-1);
1356 	if (a->st_value > b->st_value)
1357 		return (1);
1358 
1359 	/*
1360 	 * Prefer the function to the non-function.
1361 	 */
1362 	if (GELF_ST_TYPE(a->st_info) != GELF_ST_TYPE(b->st_info)) {
1363 		if (GELF_ST_TYPE(a->st_info) == STT_FUNC)
1364 			return (-1);
1365 		if (GELF_ST_TYPE(b->st_info) == STT_FUNC)
1366 			return (1);
1367 	}
1368 
1369 	/*
1370 	 * Prefer the weak or strong global symbol to the local symbol.
1371 	 */
1372 	if (GELF_ST_BIND(a->st_info) != GELF_ST_BIND(b->st_info)) {
1373 		if (GELF_ST_BIND(b->st_info) == STB_LOCAL)
1374 			return (-1);
1375 		if (GELF_ST_BIND(a->st_info) == STB_LOCAL)
1376 			return (1);
1377 	}
1378 
1379 	/*
1380 	 * Prefer the symbol that doesn't begin with a '$' since compilers and
1381 	 * other symbol generators often use it as a prefix.
1382 	 */
1383 	if (*bname == '$')
1384 		return (-1);
1385 	if (*aname == '$')
1386 		return (1);
1387 
1388 	/*
1389 	 * Prefer the name with fewer leading underscores in the name.
1390 	 */
1391 	while (*aname == '_' && *bname == '_') {
1392 		aname++;
1393 		bname++;
1394 	}
1395 
1396 	if (*bname == '_')
1397 		return (-1);
1398 	if (*aname == '_')
1399 		return (1);
1400 
1401 	/*
1402 	 * Prefer the symbol with the smaller size.
1403 	 */
1404 	if (a->st_size < b->st_size)
1405 		return (-1);
1406 	if (a->st_size > b->st_size)
1407 		return (1);
1408 
1409 	/*
1410 	 * All other factors being equal, fall back to lexicographic order.
1411 	 */
1412 	return (strcmp(aname, bname));
1413 }
1414 
1415 static int
1416 byaddr_cmp(const void *aa, const void *bb)
1417 {
1418 	GElf_Sym *a = &sort_syms[*(uint_t *)aa];
1419 	GElf_Sym *b = &sort_syms[*(uint_t *)bb];
1420 	char *aname = sort_strs + a->st_name;
1421 	char *bname = sort_strs + b->st_name;
1422 
1423 	return (byaddr_cmp_common(a, aname, b, bname));
1424 }
1425 
1426 static int
1427 byname_cmp(const void *aa, const void *bb)
1428 {
1429 	GElf_Sym *a = &sort_syms[*(uint_t *)aa];
1430 	GElf_Sym *b = &sort_syms[*(uint_t *)bb];
1431 	char *aname = sort_strs + a->st_name;
1432 	char *bname = sort_strs + b->st_name;
1433 
1434 	return (strcmp(aname, bname));
1435 }
1436 
1437 /*
1438  * Given a symbol index, look up the corresponding symbol from the
1439  * given symbol table.
1440  *
1441  * This function allows the caller to treat the symbol table as a single
1442  * logical entity even though there may be 2 actual ELF symbol tables
1443  * involved. See the comments in Pcontrol.h for details.
1444  */
1445 static GElf_Sym *
1446 symtab_getsym(sym_tbl_t *symtab, int ndx, GElf_Sym *dst)
1447 {
1448 	/* If index is in range of primary symtab, look it up there */
1449 	if (ndx >= symtab->sym_symn_aux) {
1450 		return (gelf_getsym(symtab->sym_data_pri,
1451 		    ndx - symtab->sym_symn_aux, dst));
1452 	}
1453 
1454 	/* Not in primary: Look it up in the auxiliary symtab */
1455 	return (gelf_getsym(symtab->sym_data_aux, ndx, dst));
1456 }
1457 
1458 void
1459 optimize_symtab(sym_tbl_t *symtab)
1460 {
1461 	GElf_Sym *symp, *syms;
1462 	uint_t i, *indexa, *indexb;
1463 	size_t symn, strsz, count;
1464 
1465 	if (symtab == NULL || symtab->sym_data_pri == NULL ||
1466 	    symtab->sym_byaddr != NULL)
1467 		return;
1468 
1469 	symn = symtab->sym_symn;
1470 	strsz = symtab->sym_strsz;
1471 
1472 	symp = syms = malloc(sizeof (GElf_Sym) * symn);
1473 	if (symp == NULL) {
1474 		dprintf("optimize_symtab: failed to malloc symbol array");
1475 		return;
1476 	}
1477 
1478 	/*
1479 	 * First record all the symbols into a table and count up the ones
1480 	 * that we're interested in. We mark symbols as invalid by setting
1481 	 * the st_name to an illegal value.
1482 	 */
1483 	for (i = 0, count = 0; i < symn; i++, symp++) {
1484 		if (symtab_getsym(symtab, i, symp) != NULL &&
1485 		    symp->st_name < strsz &&
1486 		    IS_DATA_TYPE(GELF_ST_TYPE(symp->st_info)))
1487 			count++;
1488 		else
1489 			symp->st_name = strsz;
1490 	}
1491 
1492 	/*
1493 	 * Allocate sufficient space for both tables and populate them
1494 	 * with the same symbols we just counted.
1495 	 */
1496 	symtab->sym_count = count;
1497 	indexa = symtab->sym_byaddr = calloc(sizeof (uint_t), count);
1498 	indexb = symtab->sym_byname = calloc(sizeof (uint_t), count);
1499 	if (indexa == NULL || indexb == NULL) {
1500 		dprintf(
1501 		    "optimize_symtab: failed to malloc symbol index arrays");
1502 		symtab->sym_count = 0;
1503 		if (indexa != NULL) {	/* First alloc succeeded. Free it */
1504 			free(indexa);
1505 			symtab->sym_byaddr = NULL;
1506 		}
1507 		free(syms);
1508 		return;
1509 	}
1510 	for (i = 0, symp = syms; i < symn; i++, symp++) {
1511 		if (symp->st_name < strsz)
1512 			*indexa++ = *indexb++ = i;
1513 	}
1514 
1515 	/*
1516 	 * Sort the two tables according to the appropriate criteria.
1517 	 */
1518 	(void) mutex_lock(&sort_mtx);
1519 	sort_strs = symtab->sym_strs;
1520 	sort_syms = syms;
1521 
1522 	qsort(symtab->sym_byaddr, count, sizeof (uint_t), byaddr_cmp);
1523 	qsort(symtab->sym_byname, count, sizeof (uint_t), byname_cmp);
1524 
1525 	sort_strs = NULL;
1526 	sort_syms = NULL;
1527 	(void) mutex_unlock(&sort_mtx);
1528 
1529 	free(syms);
1530 }
1531 
1532 /*
1533  * Build the symbol table for the given mapped file.
1534  */
1535 void
1536 Pbuild_file_symtab(struct ps_prochandle *P, file_info_t *fptr)
1537 {
1538 	char objectfile[PATH_MAX];
1539 	uint_t i;
1540 
1541 	GElf_Ehdr ehdr;
1542 	GElf_Sym s;
1543 
1544 	Elf_Data *shdata;
1545 	Elf_Scn *scn;
1546 	Elf *elf;
1547 	size_t nshdrs, shstrndx;
1548 
1549 	struct {
1550 		GElf_Shdr c_shdr;
1551 		Elf_Data *c_data;
1552 		const char *c_name;
1553 	} *cp, *cache = NULL, *dyn = NULL, *plt = NULL, *ctf = NULL;
1554 
1555 	if (fptr->file_init)
1556 		return;	/* We've already processed this file */
1557 
1558 	/*
1559 	 * Mark the file_info struct as having the symbol table initialized
1560 	 * even if we fail below.  We tried once; we don't try again.
1561 	 */
1562 	fptr->file_init = 1;
1563 
1564 	if (elf_version(EV_CURRENT) == EV_NONE) {
1565 		dprintf("libproc ELF version is more recent than libelf\n");
1566 		return;
1567 	}
1568 
1569 	if (P->state == PS_DEAD || P->state == PS_IDLE) {
1570 		/*
1571 		 * If we're a not live, we can't open files from the /proc
1572 		 * object directory; we have only the mapping and file names
1573 		 * to guide us.  We prefer the file_lname, but need to handle
1574 		 * the case of it being NULL in order to bootstrap: we first
1575 		 * come here during rd_new() when the only information we have
1576 		 * is interpreter name associated with the AT_BASE mapping.
1577 		 */
1578 		(void) snprintf(objectfile, sizeof (objectfile), "%s",
1579 		    fptr->file_lname ? fptr->file_lname : fptr->file_pname);
1580 	} else {
1581 		(void) snprintf(objectfile, sizeof (objectfile),
1582 		    "%s/%d/object/%s",
1583 		    procfs_path, (int)P->pid, fptr->file_pname);
1584 	}
1585 
1586 	/*
1587 	 * Open the object file, create the elf file, and then get the elf
1588 	 * header and .shstrtab data buffer so we can process sections by
1589 	 * name. If anything goes wrong try to fake up an elf file from
1590 	 * the in-core elf image.
1591 	 */
1592 	if ((fptr->file_fd = open(objectfile, O_RDONLY)) < 0) {
1593 		dprintf("Pbuild_file_symtab: failed to open %s: %s\n",
1594 		    objectfile, strerror(errno));
1595 
1596 		if ((elf = fake_elf(P, fptr)) == NULL ||
1597 		    elf_kind(elf) != ELF_K_ELF ||
1598 		    gelf_getehdr(elf, &ehdr) == NULL ||
1599 		    elf_getshnum(elf, &nshdrs) == 0 ||
1600 		    elf_getshstrndx(elf, &shstrndx) == 0 ||
1601 		    (scn = elf_getscn(elf, shstrndx)) == NULL ||
1602 		    (shdata = elf_getdata(scn, NULL)) == NULL) {
1603 			dprintf("failed to fake up ELF file\n");
1604 			return;
1605 		}
1606 
1607 	} else if ((elf = elf_begin(fptr->file_fd, ELF_C_READ, NULL)) == NULL ||
1608 	    elf_kind(elf) != ELF_K_ELF ||
1609 	    gelf_getehdr(elf, &ehdr) == NULL ||
1610 	    elf_getshnum(elf, &nshdrs) == 0 ||
1611 	    elf_getshstrndx(elf, &shstrndx) == 0 ||
1612 	    (scn = elf_getscn(elf, shstrndx)) == NULL ||
1613 	    (shdata = elf_getdata(scn, NULL)) == NULL) {
1614 		int err = elf_errno();
1615 
1616 		dprintf("failed to process ELF file %s: %s\n",
1617 		    objectfile, (err == 0) ? "<null>" : elf_errmsg(err));
1618 
1619 		if ((elf = fake_elf(P, fptr)) == NULL ||
1620 		    elf_kind(elf) != ELF_K_ELF ||
1621 		    gelf_getehdr(elf, &ehdr) == NULL ||
1622 		    elf_getshnum(elf, &nshdrs) == 0 ||
1623 		    elf_getshstrndx(elf, &shstrndx) == 0 ||
1624 		    (scn = elf_getscn(elf, shstrndx)) == NULL ||
1625 		    (shdata = elf_getdata(scn, NULL)) == NULL) {
1626 			dprintf("failed to fake up ELF file\n");
1627 			goto bad;
1628 		}
1629 
1630 	} else if (file_differs(P, elf, fptr)) {
1631 		Elf *newelf;
1632 
1633 		/*
1634 		 * Before we get too excited about this elf file, we'll check
1635 		 * its checksum value against the value we have in memory. If
1636 		 * they don't agree, we try to fake up a new elf file and
1637 		 * proceed with that instead.
1638 		 */
1639 
1640 		dprintf("ELF file %s (%lx) doesn't match in-core image\n",
1641 		    fptr->file_pname,
1642 		    (ulong_t)fptr->file_map->map_pmap.pr_vaddr);
1643 
1644 		if ((newelf = fake_elf(P, fptr)) == NULL ||
1645 		    elf_kind(newelf) != ELF_K_ELF ||
1646 		    gelf_getehdr(newelf, &ehdr) == NULL ||
1647 		    elf_getshnum(newelf, &nshdrs) == 0 ||
1648 		    elf_getshstrndx(newelf, &shstrndx) == 0 ||
1649 		    (scn = elf_getscn(newelf, shstrndx)) == NULL ||
1650 		    (shdata = elf_getdata(scn, NULL)) == NULL) {
1651 			dprintf("failed to fake up ELF file\n");
1652 		} else {
1653 			(void) elf_end(elf);
1654 			elf = newelf;
1655 
1656 			dprintf("switched to faked up ELF file\n");
1657 		}
1658 	}
1659 
1660 	if ((cache = malloc(nshdrs * sizeof (*cache))) == NULL) {
1661 		dprintf("failed to malloc section cache for %s\n", objectfile);
1662 		goto bad;
1663 	}
1664 
1665 	dprintf("processing ELF file %s\n", objectfile);
1666 	fptr->file_class = ehdr.e_ident[EI_CLASS];
1667 	fptr->file_etype = ehdr.e_type;
1668 	fptr->file_elf = elf;
1669 	fptr->file_shstrs = shdata->d_buf;
1670 	fptr->file_shstrsz = shdata->d_size;
1671 
1672 	/*
1673 	 * Iterate through each section, caching its section header, data
1674 	 * pointer, and name.  We use this for handling sh_link values below.
1675 	 */
1676 	for (cp = cache + 1, scn = NULL; scn = elf_nextscn(elf, scn); cp++) {
1677 		if (gelf_getshdr(scn, &cp->c_shdr) == NULL) {
1678 			dprintf("Pbuild_file_symtab: Failed to get section "
1679 			    "header\n");
1680 			goto bad; /* Failed to get section header */
1681 		}
1682 
1683 		if ((cp->c_data = elf_getdata(scn, NULL)) == NULL) {
1684 			dprintf("Pbuild_file_symtab: Failed to get section "
1685 			    "data\n");
1686 			goto bad; /* Failed to get section data */
1687 		}
1688 
1689 		if (cp->c_shdr.sh_name >= shdata->d_size) {
1690 			dprintf("Pbuild_file_symtab: corrupt section name");
1691 			goto bad; /* Corrupt section name */
1692 		}
1693 
1694 		cp->c_name = (const char *)shdata->d_buf + cp->c_shdr.sh_name;
1695 	}
1696 
1697 	/*
1698 	 * Now iterate through the section cache in order to locate info
1699 	 * for the .symtab, .dynsym, .SUNW_ldynsym, .dynamic, .plt,
1700 	 * and .SUNW_ctf sections:
1701 	 */
1702 	for (i = 1, cp = cache + 1; i < nshdrs; i++, cp++) {
1703 		GElf_Shdr *shp = &cp->c_shdr;
1704 
1705 		if (shp->sh_type == SHT_SYMTAB || shp->sh_type == SHT_DYNSYM) {
1706 			sym_tbl_t *symp = shp->sh_type == SHT_SYMTAB ?
1707 			    &fptr->file_symtab : &fptr->file_dynsym;
1708 			/*
1709 			 * It's possible that the we already got the symbol
1710 			 * table from the core file itself. Either the file
1711 			 * differs in which case our faked up elf file will
1712 			 * only contain the dynsym (not the symtab) or the
1713 			 * file matches in which case we'll just be replacing
1714 			 * the symbol table we pulled out of the core file
1715 			 * with an equivalent one. In either case, this
1716 			 * check isn't essential, but it's a good idea.
1717 			 */
1718 			if (symp->sym_data_pri == NULL) {
1719 				dprintf("Symbol table found for %s\n",
1720 				    objectfile);
1721 				symp->sym_data_pri = cp->c_data;
1722 				symp->sym_symn +=
1723 				    shp->sh_size / shp->sh_entsize;
1724 				symp->sym_strs =
1725 				    cache[shp->sh_link].c_data->d_buf;
1726 				symp->sym_strsz =
1727 				    cache[shp->sh_link].c_data->d_size;
1728 				symp->sym_hdr_pri = cp->c_shdr;
1729 				symp->sym_strhdr = cache[shp->sh_link].c_shdr;
1730 			} else {
1731 				dprintf("Symbol table already there for %s\n",
1732 				    objectfile);
1733 			}
1734 		} else if (shp->sh_type == SHT_SUNW_LDYNSYM) {
1735 			/* .SUNW_ldynsym section is auxiliary to .dynsym */
1736 			if (fptr->file_dynsym.sym_data_aux == NULL) {
1737 				dprintf(".SUNW_ldynsym symbol table"
1738 				    " found for %s\n", objectfile);
1739 				fptr->file_dynsym.sym_data_aux = cp->c_data;
1740 				fptr->file_dynsym.sym_symn_aux =
1741 				    shp->sh_size / shp->sh_entsize;
1742 				fptr->file_dynsym.sym_symn +=
1743 				    fptr->file_dynsym.sym_symn_aux;
1744 				fptr->file_dynsym.sym_hdr_aux = cp->c_shdr;
1745 			} else {
1746 				dprintf(".SUNW_ldynsym symbol table already"
1747 				    " there for %s\n", objectfile);
1748 			}
1749 		} else if (shp->sh_type == SHT_DYNAMIC) {
1750 			dyn = cp;
1751 		} else if (strcmp(cp->c_name, ".plt") == 0) {
1752 			plt = cp;
1753 		} else if (strcmp(cp->c_name, ".SUNW_ctf") == 0) {
1754 			/*
1755 			 * Skip over bogus CTF sections so they don't come back
1756 			 * to haunt us later.
1757 			 */
1758 			if (shp->sh_link == 0 ||
1759 			    shp->sh_link >= nshdrs ||
1760 			    (cache[shp->sh_link].c_shdr.sh_type != SHT_DYNSYM &&
1761 			    cache[shp->sh_link].c_shdr.sh_type != SHT_SYMTAB)) {
1762 				dprintf("Bad sh_link %d for "
1763 				    "CTF\n", shp->sh_link);
1764 				continue;
1765 			}
1766 			ctf = cp;
1767 		}
1768 	}
1769 
1770 	/*
1771 	 * At this point, we've found all the symbol tables we're ever going
1772 	 * to find: the ones in the loop above and possibly the symtab that
1773 	 * was included in the core file. Before we perform any lookups, we
1774 	 * create sorted versions to optimize for lookups.
1775 	 */
1776 	optimize_symtab(&fptr->file_symtab);
1777 	optimize_symtab(&fptr->file_dynsym);
1778 
1779 	/*
1780 	 * Fill in the base address of the text mapping for shared libraries.
1781 	 * This allows us to translate symbols before librtld_db is ready.
1782 	 */
1783 	if (fptr->file_etype == ET_DYN) {
1784 		fptr->file_dyn_base = fptr->file_map->map_pmap.pr_vaddr -
1785 		    fptr->file_map->map_pmap.pr_offset;
1786 		dprintf("setting file_dyn_base for %s to %lx\n",
1787 		    objectfile, (long)fptr->file_dyn_base);
1788 	}
1789 
1790 	/*
1791 	 * Record the CTF section information in the file info structure.
1792 	 */
1793 	if (ctf != NULL) {
1794 		fptr->file_ctf_off = ctf->c_shdr.sh_offset;
1795 		fptr->file_ctf_size = ctf->c_shdr.sh_size;
1796 		if (ctf->c_shdr.sh_link != 0 &&
1797 		    cache[ctf->c_shdr.sh_link].c_shdr.sh_type == SHT_DYNSYM)
1798 			fptr->file_ctf_dyn = 1;
1799 	}
1800 
1801 	if (fptr->file_lo == NULL)
1802 		goto done; /* Nothing else to do if no load object info */
1803 
1804 	/*
1805 	 * If the object is a shared library and we have a different rl_base
1806 	 * value, reset file_dyn_base according to librtld_db's information.
1807 	 */
1808 	if (fptr->file_etype == ET_DYN &&
1809 	    fptr->file_lo->rl_base != fptr->file_dyn_base) {
1810 		dprintf("resetting file_dyn_base for %s to %lx\n",
1811 		    objectfile, (long)fptr->file_lo->rl_base);
1812 		fptr->file_dyn_base = fptr->file_lo->rl_base;
1813 	}
1814 
1815 	/*
1816 	 * Fill in the PLT information for this file if a PLT symbol is found.
1817 	 */
1818 	if (sym_by_name(&fptr->file_dynsym, "_PROCEDURE_LINKAGE_TABLE_", &s,
1819 	    NULL) != NULL) {
1820 		fptr->file_plt_base = s.st_value + fptr->file_dyn_base;
1821 		fptr->file_plt_size = (plt != NULL) ? plt->c_shdr.sh_size : 0;
1822 
1823 		/*
1824 		 * Bring the load object up to date; it is the only way the
1825 		 * user has to access the PLT data. The PLT information in the
1826 		 * rd_loadobj_t is not set in the call to map_iter() (the
1827 		 * callback for rd_loadobj_iter) where we set file_lo.
1828 		 */
1829 		fptr->file_lo->rl_plt_base = fptr->file_plt_base;
1830 		fptr->file_lo->rl_plt_size = fptr->file_plt_size;
1831 
1832 		dprintf("PLT found at %p, size = %lu\n",
1833 		    (void *)fptr->file_plt_base, (ulong_t)fptr->file_plt_size);
1834 	}
1835 
1836 	/*
1837 	 * Fill in the PLT information.
1838 	 */
1839 	if (dyn != NULL) {
1840 		uintptr_t dynaddr = dyn->c_shdr.sh_addr + fptr->file_dyn_base;
1841 		size_t ndyn = dyn->c_shdr.sh_size / dyn->c_shdr.sh_entsize;
1842 		GElf_Dyn d;
1843 
1844 		for (i = 0; i < ndyn; i++) {
1845 			if (gelf_getdyn(dyn->c_data, i, &d) != NULL &&
1846 			    d.d_tag == DT_JMPREL) {
1847 				dprintf("DT_JMPREL is %p\n",
1848 				    (void *)(uintptr_t)d.d_un.d_ptr);
1849 				fptr->file_jmp_rel =
1850 				    d.d_un.d_ptr + fptr->file_dyn_base;
1851 				break;
1852 			}
1853 		}
1854 
1855 		dprintf("_DYNAMIC found at %p, %lu entries, DT_JMPREL = %p\n",
1856 		    (void *)dynaddr, (ulong_t)ndyn, (void *)fptr->file_jmp_rel);
1857 	}
1858 
1859 done:
1860 	free(cache);
1861 	return;
1862 
1863 bad:
1864 	if (cache != NULL)
1865 		free(cache);
1866 
1867 	(void) elf_end(elf);
1868 	fptr->file_elf = NULL;
1869 	if (fptr->file_elfmem != NULL) {
1870 		free(fptr->file_elfmem);
1871 		fptr->file_elfmem = NULL;
1872 	}
1873 	(void) close(fptr->file_fd);
1874 	fptr->file_fd = -1;
1875 }
1876 
1877 /*
1878  * Given a process virtual address, return the map_info_t containing it.
1879  * If none found, return NULL.
1880  */
1881 map_info_t *
1882 Paddr2mptr(struct ps_prochandle *P, uintptr_t addr)
1883 {
1884 	int lo = 0;
1885 	int hi = P->map_count - 1;
1886 	int mid;
1887 	map_info_t *mp;
1888 
1889 	while (lo <= hi) {
1890 
1891 		mid = (lo + hi) / 2;
1892 		mp = &P->mappings[mid];
1893 
1894 		/* check that addr is in [vaddr, vaddr + size) */
1895 		if ((addr - mp->map_pmap.pr_vaddr) < mp->map_pmap.pr_size)
1896 			return (mp);
1897 
1898 		if (addr < mp->map_pmap.pr_vaddr)
1899 			hi = mid - 1;
1900 		else
1901 			lo = mid + 1;
1902 	}
1903 
1904 	return (NULL);
1905 }
1906 
1907 /*
1908  * Return the map_info_t for the executable file.
1909  * If not found, return NULL.
1910  */
1911 static map_info_t *
1912 exec_map(struct ps_prochandle *P)
1913 {
1914 	uint_t i;
1915 	map_info_t *mptr;
1916 	map_info_t *mold = NULL;
1917 	file_info_t *fptr;
1918 	uintptr_t base;
1919 
1920 	for (i = 0, mptr = P->mappings; i < P->map_count; i++, mptr++) {
1921 		if (mptr->map_pmap.pr_mapname[0] == '\0')
1922 			continue;
1923 		if (strcmp(mptr->map_pmap.pr_mapname, "a.out") == 0) {
1924 			if ((fptr = mptr->map_file) != NULL &&
1925 			    fptr->file_lo != NULL) {
1926 				base = fptr->file_lo->rl_base;
1927 				if (base >= mptr->map_pmap.pr_vaddr &&
1928 				    base < mptr->map_pmap.pr_vaddr +
1929 				    mptr->map_pmap.pr_size)	/* text space */
1930 					return (mptr);
1931 				mold = mptr;	/* must be the data */
1932 				continue;
1933 			}
1934 			/* This is a poor way to test for text space */
1935 			if (!(mptr->map_pmap.pr_mflags & MA_EXEC) ||
1936 			    (mptr->map_pmap.pr_mflags & MA_WRITE)) {
1937 				mold = mptr;
1938 				continue;
1939 			}
1940 			return (mptr);
1941 		}
1942 	}
1943 
1944 	return (mold);
1945 }
1946 
1947 /*
1948  * Given a shared object name, return the map_info_t for it.  If no matching
1949  * object is found, return NULL.  Normally, the link maps contain the full
1950  * object pathname, e.g. /usr/lib/libc.so.1.  We allow the object name to
1951  * take one of the following forms:
1952  *
1953  * 1. An exact match (i.e. a full pathname): "/usr/lib/libc.so.1"
1954  * 2. An exact basename match: "libc.so.1"
1955  * 3. An initial basename match up to a '.' suffix: "libc.so" or "libc"
1956  * 4. The literal string "a.out" is an alias for the executable mapping
1957  *
1958  * The third case is a convenience for callers and may not be necessary.
1959  *
1960  * As the exact same object name may be loaded on different link maps (see
1961  * dlmopen(3DL)), we also allow the caller to resolve the object name by
1962  * specifying a particular link map id.  If lmid is PR_LMID_EVERY, the
1963  * first matching name will be returned, regardless of the link map id.
1964  */
1965 static map_info_t *
1966 object_to_map(struct ps_prochandle *P, Lmid_t lmid, const char *objname)
1967 {
1968 	map_info_t *mp;
1969 	file_info_t *fp;
1970 	size_t objlen;
1971 	uint_t i;
1972 
1973 	/*
1974 	 * If we have no rtld_db, then always treat a request as one for all
1975 	 * link maps.
1976 	 */
1977 	if (P->rap == NULL)
1978 		lmid = PR_LMID_EVERY;
1979 
1980 	/*
1981 	 * First pass: look for exact matches of the entire pathname or
1982 	 * basename (cases 1 and 2 above):
1983 	 */
1984 	for (i = 0, mp = P->mappings; i < P->map_count; i++, mp++) {
1985 
1986 		if (mp->map_pmap.pr_mapname[0] == '\0' ||
1987 		    (fp = mp->map_file) == NULL || fp->file_lname == NULL)
1988 			continue;
1989 
1990 		if (lmid != PR_LMID_EVERY &&
1991 		    (fp->file_lo == NULL || lmid != fp->file_lo->rl_lmident))
1992 			continue;
1993 
1994 		/*
1995 		 * If we match, return the primary text mapping; otherwise
1996 		 * just return the mapping we matched.
1997 		 */
1998 		if (strcmp(fp->file_lname, objname) == 0 ||
1999 		    strcmp(fp->file_lbase, objname) == 0)
2000 			return (fp->file_map ? fp->file_map : mp);
2001 	}
2002 
2003 	objlen = strlen(objname);
2004 
2005 	/*
2006 	 * Second pass: look for partial matches (case 3 above):
2007 	 */
2008 	for (i = 0, mp = P->mappings; i < P->map_count; i++, mp++) {
2009 
2010 		if (mp->map_pmap.pr_mapname[0] == '\0' ||
2011 		    (fp = mp->map_file) == NULL || fp->file_lname == NULL)
2012 			continue;
2013 
2014 		if (lmid != PR_LMID_EVERY &&
2015 		    (fp->file_lo == NULL || lmid != fp->file_lo->rl_lmident))
2016 			continue;
2017 
2018 		/*
2019 		 * If we match, return the primary text mapping; otherwise
2020 		 * just return the mapping we matched.
2021 		 */
2022 		if (strncmp(fp->file_lbase, objname, objlen) == 0 &&
2023 		    fp->file_lbase[objlen] == '.')
2024 			return (fp->file_map ? fp->file_map : mp);
2025 	}
2026 
2027 	/*
2028 	 * One last check: we allow "a.out" to always alias the executable,
2029 	 * assuming this name was not in use for something else.
2030 	 */
2031 	if ((lmid == PR_LMID_EVERY || lmid == LM_ID_BASE) &&
2032 	    (strcmp(objname, "a.out") == 0))
2033 		return (P->map_exec);
2034 
2035 	return (NULL);
2036 }
2037 
2038 static map_info_t *
2039 object_name_to_map(struct ps_prochandle *P, Lmid_t lmid, const char *name)
2040 {
2041 	map_info_t *mptr;
2042 
2043 	if (!P->info_valid)
2044 		Pupdate_maps(P);
2045 
2046 	if (P->map_exec == NULL && ((mptr = Paddr2mptr(P,
2047 	    Pgetauxval(P, AT_ENTRY))) != NULL || (mptr = exec_map(P)) != NULL))
2048 		P->map_exec = mptr;
2049 
2050 	if (P->map_ldso == NULL && (mptr = Paddr2mptr(P,
2051 	    Pgetauxval(P, AT_BASE))) != NULL)
2052 		P->map_ldso = mptr;
2053 
2054 	if (name == PR_OBJ_EXEC)
2055 		mptr = P->map_exec;
2056 	else if (name == PR_OBJ_LDSO)
2057 		mptr = P->map_ldso;
2058 	else if (Prd_agent(P) != NULL || P->state == PS_IDLE)
2059 		mptr = object_to_map(P, lmid, name);
2060 	else
2061 		mptr = NULL;
2062 
2063 	return (mptr);
2064 }
2065 
2066 /*
2067  * When two symbols are found by address, decide which one is to be preferred.
2068  */
2069 static GElf_Sym *
2070 sym_prefer(GElf_Sym *sym1, char *name1, GElf_Sym *sym2, char *name2)
2071 {
2072 	/*
2073 	 * Prefer the non-NULL symbol.
2074 	 */
2075 	if (sym1 == NULL)
2076 		return (sym2);
2077 	if (sym2 == NULL)
2078 		return (sym1);
2079 
2080 	/*
2081 	 * Defer to the sort ordering...
2082 	 */
2083 	return (byaddr_cmp_common(sym1, name1, sym2, name2) <= 0 ? sym1 : sym2);
2084 }
2085 
2086 /*
2087  * Look up a symbol by address in the specified symbol table.
2088  * Adjustment to 'addr' must already have been made for the
2089  * offset of the symbol if this is a dynamic library symbol table.
2090  */
2091 static GElf_Sym *
2092 sym_by_addr(sym_tbl_t *symtab, GElf_Addr addr, GElf_Sym *symp, uint_t *idp)
2093 {
2094 	GElf_Sym sym, osym;
2095 	uint_t i, oid, *byaddr = symtab->sym_byaddr;
2096 	int min, max, mid, omid, found = 0;
2097 
2098 	if (symtab->sym_data_pri == NULL || symtab->sym_count == 0)
2099 		return (NULL);
2100 
2101 	min = 0;
2102 	max = symtab->sym_count - 1;
2103 	osym.st_value = 0;
2104 
2105 	/*
2106 	 * We can't return when we've found a match, we have to continue
2107 	 * searching for the closest matching symbol.
2108 	 */
2109 	while (min <= max) {
2110 		mid = (max + min) / 2;
2111 
2112 		i = byaddr[mid];
2113 		(void) symtab_getsym(symtab, i, &sym);
2114 
2115 		if (addr >= sym.st_value &&
2116 		    addr < sym.st_value + sym.st_size &&
2117 		    (!found || sym.st_value > osym.st_value)) {
2118 			osym = sym;
2119 			omid = mid;
2120 			oid = i;
2121 			found = 1;
2122 		}
2123 
2124 		if (addr < sym.st_value)
2125 			max = mid - 1;
2126 		else
2127 			min = mid + 1;
2128 	}
2129 
2130 	if (!found)
2131 		return (NULL);
2132 
2133 	/*
2134 	 * There may be many symbols with identical values so we walk
2135 	 * backward in the byaddr table to find the best match.
2136 	 */
2137 	do {
2138 		sym = osym;
2139 		i = oid;
2140 
2141 		if (omid == 0)
2142 			break;
2143 
2144 		oid = byaddr[--omid];
2145 		(void) symtab_getsym(symtab, oid, &osym);
2146 	} while (addr >= osym.st_value &&
2147 	    addr < sym.st_value + osym.st_size &&
2148 	    osym.st_value == sym.st_value);
2149 
2150 	*symp = sym;
2151 	if (idp != NULL)
2152 		*idp = i;
2153 	return (symp);
2154 }
2155 
2156 /*
2157  * Look up a symbol by name in the specified symbol table.
2158  */
2159 static GElf_Sym *
2160 sym_by_name(sym_tbl_t *symtab, const char *name, GElf_Sym *symp, uint_t *idp)
2161 {
2162 	char *strs = symtab->sym_strs;
2163 	uint_t i, *byname = symtab->sym_byname;
2164 	int min, mid, max, cmp;
2165 
2166 	if (symtab->sym_data_pri == NULL || strs == NULL ||
2167 	    symtab->sym_count == 0)
2168 		return (NULL);
2169 
2170 	min = 0;
2171 	max = symtab->sym_count - 1;
2172 
2173 	while (min <= max) {
2174 		mid = (max + min) / 2;
2175 
2176 		i = byname[mid];
2177 		(void) symtab_getsym(symtab, i, symp);
2178 
2179 		if ((cmp = strcmp(name, strs + symp->st_name)) == 0) {
2180 			if (idp != NULL)
2181 				*idp = i;
2182 			return (symp);
2183 		}
2184 
2185 		if (cmp < 0)
2186 			max = mid - 1;
2187 		else
2188 			min = mid + 1;
2189 	}
2190 
2191 	return (NULL);
2192 }
2193 
2194 /*
2195  * Search the process symbol tables looking for a symbol whose
2196  * value to value+size contain the address specified by addr.
2197  * Return values are:
2198  *	sym_name_buffer containing the symbol name
2199  *	GElf_Sym symbol table entry
2200  *	prsyminfo_t ancillary symbol information
2201  * Returns 0 on success, -1 on failure.
2202  */
2203 int
2204 Pxlookup_by_addr(
2205 	struct ps_prochandle *P,
2206 	uintptr_t addr,			/* process address being sought */
2207 	char *sym_name_buffer,		/* buffer for the symbol name */
2208 	size_t bufsize,			/* size of sym_name_buffer */
2209 	GElf_Sym *symbolp,		/* returned symbol table entry */
2210 	prsyminfo_t *sip)		/* returned symbol info */
2211 {
2212 	GElf_Sym	*symp;
2213 	char		*name;
2214 	GElf_Sym	sym1, *sym1p = NULL;
2215 	GElf_Sym	sym2, *sym2p = NULL;
2216 	char		*name1 = NULL;
2217 	char		*name2 = NULL;
2218 	uint_t		i1;
2219 	uint_t		i2;
2220 	map_info_t	*mptr;
2221 	file_info_t	*fptr;
2222 
2223 	(void) Prd_agent(P);
2224 
2225 	if ((mptr = Paddr2mptr(P, addr)) == NULL ||	/* no such address */
2226 	    (fptr = build_map_symtab(P, mptr)) == NULL || /* no mapped file */
2227 	    fptr->file_elf == NULL)			/* not an ELF file */
2228 		return (-1);
2229 
2230 	/*
2231 	 * Adjust the address by the load object base address in
2232 	 * case the address turns out to be in a shared library.
2233 	 */
2234 	addr -= fptr->file_dyn_base;
2235 
2236 	/*
2237 	 * Search both symbol tables, symtab first, then dynsym.
2238 	 */
2239 	if ((sym1p = sym_by_addr(&fptr->file_symtab, addr, &sym1, &i1)) != NULL)
2240 		name1 = fptr->file_symtab.sym_strs + sym1.st_name;
2241 	if ((sym2p = sym_by_addr(&fptr->file_dynsym, addr, &sym2, &i2)) != NULL)
2242 		name2 = fptr->file_dynsym.sym_strs + sym2.st_name;
2243 
2244 	if ((symp = sym_prefer(sym1p, name1, sym2p, name2)) == NULL)
2245 		return (-1);
2246 
2247 	name = (symp == sym1p) ? name1 : name2;
2248 	if (bufsize > 0) {
2249 		(void) strncpy(sym_name_buffer, name, bufsize);
2250 		sym_name_buffer[bufsize - 1] = '\0';
2251 	}
2252 
2253 	*symbolp = *symp;
2254 	if (sip != NULL) {
2255 		sip->prs_name = bufsize == 0 ? NULL : sym_name_buffer;
2256 		sip->prs_object = fptr->file_lbase;
2257 		sip->prs_id = (symp == sym1p) ? i1 : i2;
2258 		sip->prs_table = (symp == sym1p) ? PR_SYMTAB : PR_DYNSYM;
2259 		sip->prs_lmid = (fptr->file_lo == NULL) ? LM_ID_BASE :
2260 		    fptr->file_lo->rl_lmident;
2261 	}
2262 
2263 	if (GELF_ST_TYPE(symbolp->st_info) != STT_TLS)
2264 		symbolp->st_value += fptr->file_dyn_base;
2265 
2266 	return (0);
2267 }
2268 
2269 int
2270 Plookup_by_addr(struct ps_prochandle *P, uintptr_t addr, char *buf, size_t size,
2271     GElf_Sym *symp)
2272 {
2273 	return (Pxlookup_by_addr(P, addr, buf, size, symp, NULL));
2274 }
2275 
2276 /*
2277  * Search the process symbol tables looking for a symbol whose name matches the
2278  * specified name and whose object and link map optionally match the specified
2279  * parameters.  On success, the function returns 0 and fills in the GElf_Sym
2280  * symbol table entry.  On failure, -1 is returned.
2281  */
2282 int
2283 Pxlookup_by_name(
2284 	struct ps_prochandle *P,
2285 	Lmid_t lmid,			/* link map to match, or -1 for any */
2286 	const char *oname,		/* load object name */
2287 	const char *sname,		/* symbol name */
2288 	GElf_Sym *symp,			/* returned symbol table entry */
2289 	prsyminfo_t *sip)		/* returned symbol info */
2290 {
2291 	map_info_t *mptr;
2292 	file_info_t *fptr;
2293 	int cnt;
2294 
2295 	GElf_Sym sym;
2296 	prsyminfo_t si;
2297 	int rv = -1;
2298 	uint_t id;
2299 
2300 	if (oname == PR_OBJ_EVERY) {
2301 		/* create all the file_info_t's for all the mappings */
2302 		(void) Prd_agent(P);
2303 		cnt = P->num_files;
2304 		fptr = list_next(&P->file_head);
2305 	} else {
2306 		cnt = 1;
2307 		if ((mptr = object_name_to_map(P, lmid, oname)) == NULL ||
2308 		    (fptr = build_map_symtab(P, mptr)) == NULL)
2309 			return (-1);
2310 	}
2311 
2312 	/*
2313 	 * Iterate through the loaded object files and look for the symbol
2314 	 * name in the .symtab and .dynsym of each.  If we encounter a match
2315 	 * with SHN_UNDEF, keep looking in hopes of finding a better match.
2316 	 * This means that a name such as "puts" will match the puts function
2317 	 * in libc instead of matching the puts PLT entry in the a.out file.
2318 	 */
2319 	for (; cnt > 0; cnt--, fptr = list_next(fptr)) {
2320 		Pbuild_file_symtab(P, fptr);
2321 
2322 		if (fptr->file_elf == NULL)
2323 			continue;
2324 
2325 		if (lmid != PR_LMID_EVERY && fptr->file_lo != NULL &&
2326 		    lmid != fptr->file_lo->rl_lmident)
2327 			continue;
2328 
2329 		if (fptr->file_symtab.sym_data_pri != NULL &&
2330 		    sym_by_name(&fptr->file_symtab, sname, symp, &id)) {
2331 			if (sip != NULL) {
2332 				sip->prs_id = id;
2333 				sip->prs_table = PR_SYMTAB;
2334 				sip->prs_object = oname;
2335 				sip->prs_name = sname;
2336 				sip->prs_lmid = fptr->file_lo == NULL ?
2337 				    LM_ID_BASE : fptr->file_lo->rl_lmident;
2338 			}
2339 		} else if (fptr->file_dynsym.sym_data_pri != NULL &&
2340 		    sym_by_name(&fptr->file_dynsym, sname, symp, &id)) {
2341 			if (sip != NULL) {
2342 				sip->prs_id = id;
2343 				sip->prs_table = PR_DYNSYM;
2344 				sip->prs_object = oname;
2345 				sip->prs_name = sname;
2346 				sip->prs_lmid = fptr->file_lo == NULL ?
2347 				    LM_ID_BASE : fptr->file_lo->rl_lmident;
2348 			}
2349 		} else {
2350 			continue;
2351 		}
2352 
2353 		if (GELF_ST_TYPE(symp->st_info) != STT_TLS)
2354 			symp->st_value += fptr->file_dyn_base;
2355 
2356 		if (symp->st_shndx != SHN_UNDEF)
2357 			return (0);
2358 
2359 		if (rv != 0) {
2360 			if (sip != NULL)
2361 				si = *sip;
2362 			sym = *symp;
2363 			rv = 0;
2364 		}
2365 	}
2366 
2367 	if (rv == 0) {
2368 		if (sip != NULL)
2369 			*sip = si;
2370 		*symp = sym;
2371 	}
2372 
2373 	return (rv);
2374 }
2375 
2376 /*
2377  * Search the process symbol tables looking for a symbol whose name matches the
2378  * specified name, but without any restriction on the link map id.
2379  */
2380 int
2381 Plookup_by_name(struct ps_prochandle *P, const char *object,
2382 	const char *symbol, GElf_Sym *symp)
2383 {
2384 	return (Pxlookup_by_name(P, PR_LMID_EVERY, object, symbol, symp, NULL));
2385 }
2386 
2387 /*
2388  * Iterate over the process's address space mappings.
2389  */
2390 int
2391 Pmapping_iter(struct ps_prochandle *P, proc_map_f *func, void *cd)
2392 {
2393 	map_info_t *mptr;
2394 	file_info_t *fptr;
2395 	char *object_name;
2396 	int rc = 0;
2397 	int i;
2398 
2399 	/* create all the file_info_t's for all the mappings */
2400 	(void) Prd_agent(P);
2401 
2402 	for (i = 0, mptr = P->mappings; i < P->map_count; i++, mptr++) {
2403 		if ((fptr = mptr->map_file) == NULL)
2404 			object_name = NULL;
2405 		else
2406 			object_name = fptr->file_lname;
2407 		if ((rc = func(cd, &mptr->map_pmap, object_name)) != 0)
2408 			return (rc);
2409 	}
2410 	return (0);
2411 }
2412 
2413 /*
2414  * Iterate over the process's mapped objects.
2415  */
2416 int
2417 Pobject_iter(struct ps_prochandle *P, proc_map_f *func, void *cd)
2418 {
2419 	map_info_t *mptr;
2420 	file_info_t *fptr;
2421 	uint_t cnt;
2422 	int rc = 0;
2423 
2424 	(void) Prd_agent(P); /* create file_info_t's for all the mappings */
2425 	Pupdate_maps(P);
2426 
2427 	for (cnt = P->num_files, fptr = list_next(&P->file_head);
2428 	    cnt; cnt--, fptr = list_next(fptr)) {
2429 
2430 		const char *lname = fptr->file_lname ? fptr->file_lname : "";
2431 
2432 		if ((mptr = fptr->file_map) == NULL)
2433 			continue;
2434 
2435 		if ((rc = func(cd, &mptr->map_pmap, lname)) != 0)
2436 			return (rc);
2437 	}
2438 	return (0);
2439 }
2440 
2441 /*
2442  * Given a virtual address, return the name of the underlying
2443  * mapped object (file), as provided by the dynamic linker.
2444  * Return NULL on failure (no underlying shared library).
2445  */
2446 char *
2447 Pobjname(struct ps_prochandle *P, uintptr_t addr,
2448 	char *buffer, size_t bufsize)
2449 {
2450 	map_info_t *mptr;
2451 	file_info_t *fptr;
2452 
2453 	/* create all the file_info_t's for all the mappings */
2454 	(void) Prd_agent(P);
2455 
2456 	if ((mptr = Paddr2mptr(P, addr)) != NULL &&
2457 	    (fptr = mptr->map_file) != NULL &&
2458 	    fptr->file_lname != NULL) {
2459 		(void) strncpy(buffer, fptr->file_lname, bufsize);
2460 		if (strlen(fptr->file_lname) >= bufsize)
2461 			buffer[bufsize-1] = '\0';
2462 		return (buffer);
2463 	}
2464 	return (NULL);
2465 }
2466 
2467 /*
2468  * Given a virtual address, return the link map id of the underlying mapped
2469  * object (file), as provided by the dynamic linker.  Return -1 on failure.
2470  */
2471 int
2472 Plmid(struct ps_prochandle *P, uintptr_t addr, Lmid_t *lmidp)
2473 {
2474 	map_info_t *mptr;
2475 	file_info_t *fptr;
2476 
2477 	/* create all the file_info_t's for all the mappings */
2478 	(void) Prd_agent(P);
2479 
2480 	if ((mptr = Paddr2mptr(P, addr)) != NULL &&
2481 	    (fptr = mptr->map_file) != NULL && fptr->file_lo != NULL) {
2482 		*lmidp = fptr->file_lo->rl_lmident;
2483 		return (0);
2484 	}
2485 
2486 	return (-1);
2487 }
2488 
2489 /*
2490  * Given an object name and optional lmid, iterate over the object's symbols.
2491  * If which == PR_SYMTAB, search the normal symbol table.
2492  * If which == PR_DYNSYM, search the dynamic symbol table.
2493  */
2494 static int
2495 Psymbol_iter_com(struct ps_prochandle *P, Lmid_t lmid, const char *object_name,
2496     int which, int mask, pr_order_t order, proc_xsym_f *func, void *cd)
2497 {
2498 	GElf_Sym sym;
2499 	GElf_Shdr shdr;
2500 	map_info_t *mptr;
2501 	file_info_t *fptr;
2502 	sym_tbl_t *symtab;
2503 	size_t symn;
2504 	const char *strs;
2505 	size_t strsz;
2506 	prsyminfo_t si;
2507 	int rv;
2508 	uint_t *map, i, count, ndx;
2509 
2510 	if ((mptr = object_name_to_map(P, lmid, object_name)) == NULL)
2511 		return (-1);
2512 
2513 	if ((fptr = build_map_symtab(P, mptr)) == NULL || /* no mapped file */
2514 	    fptr->file_elf == NULL)			/* not an ELF file */
2515 		return (-1);
2516 
2517 	/*
2518 	 * Search the specified symbol table.
2519 	 */
2520 	switch (which) {
2521 	case PR_SYMTAB:
2522 		symtab = &fptr->file_symtab;
2523 		si.prs_table = PR_SYMTAB;
2524 		break;
2525 	case PR_DYNSYM:
2526 		symtab = &fptr->file_dynsym;
2527 		si.prs_table = PR_DYNSYM;
2528 		break;
2529 	default:
2530 		return (-1);
2531 	}
2532 
2533 	si.prs_object = object_name;
2534 	si.prs_lmid = fptr->file_lo == NULL ?
2535 	    LM_ID_BASE : fptr->file_lo->rl_lmident;
2536 
2537 	symn = symtab->sym_symn;
2538 	strs = symtab->sym_strs;
2539 	strsz = symtab->sym_strsz;
2540 
2541 	switch (order) {
2542 	case PRO_NATURAL:
2543 		map = NULL;
2544 		count = symn;
2545 		break;
2546 	case PRO_BYNAME:
2547 		map = symtab->sym_byname;
2548 		count = symtab->sym_count;
2549 		break;
2550 	case PRO_BYADDR:
2551 		map = symtab->sym_byaddr;
2552 		count = symtab->sym_count;
2553 		break;
2554 	default:
2555 		return (-1);
2556 	}
2557 
2558 	if (symtab->sym_data_pri == NULL || strs == NULL || count == 0)
2559 		return (-1);
2560 
2561 	rv = 0;
2562 
2563 	for (i = 0; i < count; i++) {
2564 		ndx = map == NULL ? i : map[i];
2565 		if (symtab_getsym(symtab, ndx, &sym) != NULL) {
2566 			uint_t s_bind, s_type, type;
2567 
2568 			if (sym.st_name >= strsz)	/* invalid st_name */
2569 				continue;
2570 
2571 			s_bind = GELF_ST_BIND(sym.st_info);
2572 			s_type = GELF_ST_TYPE(sym.st_info);
2573 
2574 			/*
2575 			 * In case you haven't already guessed, this relies on
2576 			 * the bitmask used in <libproc.h> for encoding symbol
2577 			 * type and binding matching the order of STB and STT
2578 			 * constants in <sys/elf.h>.  ELF can't change without
2579 			 * breaking binary compatibility, so I think this is
2580 			 * reasonably fair game.
2581 			 */
2582 			if (s_bind < STB_NUM && s_type < STT_NUM) {
2583 				type = (1 << (s_type + 8)) | (1 << s_bind);
2584 				if ((type & ~mask) != 0)
2585 					continue;
2586 			} else
2587 				continue; /* Invalid type or binding */
2588 
2589 			if (GELF_ST_TYPE(sym.st_info) != STT_TLS)
2590 				sym.st_value += fptr->file_dyn_base;
2591 
2592 			si.prs_name = strs + sym.st_name;
2593 
2594 			/*
2595 			 * If symbol's type is STT_SECTION, then try to lookup
2596 			 * the name of the corresponding section.
2597 			 */
2598 			if (GELF_ST_TYPE(sym.st_info) == STT_SECTION &&
2599 			    fptr->file_shstrs != NULL &&
2600 			    gelf_getshdr(elf_getscn(fptr->file_elf,
2601 			    sym.st_shndx), &shdr) != NULL &&
2602 			    shdr.sh_name != 0 &&
2603 			    shdr.sh_name < fptr->file_shstrsz)
2604 				si.prs_name = fptr->file_shstrs + shdr.sh_name;
2605 
2606 			si.prs_id = ndx;
2607 			if ((rv = func(cd, &sym, si.prs_name, &si)) != 0)
2608 				break;
2609 		}
2610 	}
2611 
2612 	return (rv);
2613 }
2614 
2615 int
2616 Pxsymbol_iter(struct ps_prochandle *P, Lmid_t lmid, const char *object_name,
2617     int which, int mask, proc_xsym_f *func, void *cd)
2618 {
2619 	return (Psymbol_iter_com(P, lmid, object_name, which, mask,
2620 	    PRO_NATURAL, func, cd));
2621 }
2622 
2623 int
2624 Psymbol_iter_by_lmid(struct ps_prochandle *P, Lmid_t lmid,
2625     const char *object_name, int which, int mask, proc_sym_f *func, void *cd)
2626 {
2627 	return (Psymbol_iter_com(P, lmid, object_name, which, mask,
2628 	    PRO_NATURAL, (proc_xsym_f *)func, cd));
2629 }
2630 
2631 int
2632 Psymbol_iter(struct ps_prochandle *P,
2633     const char *object_name, int which, int mask, proc_sym_f *func, void *cd)
2634 {
2635 	return (Psymbol_iter_com(P, PR_LMID_EVERY, object_name, which, mask,
2636 	    PRO_NATURAL, (proc_xsym_f *)func, cd));
2637 }
2638 
2639 int
2640 Psymbol_iter_by_addr(struct ps_prochandle *P,
2641     const char *object_name, int which, int mask, proc_sym_f *func, void *cd)
2642 {
2643 	return (Psymbol_iter_com(P, PR_LMID_EVERY, object_name, which, mask,
2644 	    PRO_BYADDR, (proc_xsym_f *)func, cd));
2645 }
2646 
2647 int
2648 Psymbol_iter_by_name(struct ps_prochandle *P,
2649     const char *object_name, int which, int mask, proc_sym_f *func, void *cd)
2650 {
2651 	return (Psymbol_iter_com(P, PR_LMID_EVERY, object_name, which, mask,
2652 	    PRO_BYNAME, (proc_xsym_f *)func, cd));
2653 }
2654 
2655 /*
2656  * Get the platform string from the core file if we have it;
2657  * just perform the system call for the caller if this is a live process.
2658  */
2659 char *
2660 Pplatform(struct ps_prochandle *P, char *s, size_t n)
2661 {
2662 	if (P->state == PS_IDLE) {
2663 		errno = ENODATA;
2664 		return (NULL);
2665 	}
2666 
2667 	if (P->state == PS_DEAD) {
2668 		if (P->core->core_platform == NULL) {
2669 			errno = ENODATA;
2670 			return (NULL);
2671 		}
2672 		(void) strncpy(s, P->core->core_platform, n - 1);
2673 		s[n - 1] = '\0';
2674 
2675 	} else if (sysinfo(SI_PLATFORM, s, n) == -1)
2676 		return (NULL);
2677 
2678 	return (s);
2679 }
2680 
2681 /*
2682  * Get the uname(2) information from the core file if we have it;
2683  * just perform the system call for the caller if this is a live process.
2684  */
2685 int
2686 Puname(struct ps_prochandle *P, struct utsname *u)
2687 {
2688 	if (P->state == PS_IDLE) {
2689 		errno = ENODATA;
2690 		return (-1);
2691 	}
2692 
2693 	if (P->state == PS_DEAD) {
2694 		if (P->core->core_uts == NULL) {
2695 			errno = ENODATA;
2696 			return (-1);
2697 		}
2698 		(void) memcpy(u, P->core->core_uts, sizeof (struct utsname));
2699 		return (0);
2700 	}
2701 	return (uname(u));
2702 }
2703 
2704 /*
2705  * Get the zone name from the core file if we have it; look up the
2706  * name based on the zone id if this is a live process.
2707  */
2708 char *
2709 Pzonename(struct ps_prochandle *P, char *s, size_t n)
2710 {
2711 	if (P->state == PS_IDLE) {
2712 		errno = ENODATA;
2713 		return (NULL);
2714 	}
2715 
2716 	if (P->state == PS_DEAD) {
2717 		if (P->core->core_zonename == NULL) {
2718 			errno = ENODATA;
2719 			return (NULL);
2720 		}
2721 		(void) strlcpy(s, P->core->core_zonename, n);
2722 	} else {
2723 		if (getzonenamebyid(P->status.pr_zoneid, s, n) < 0)
2724 			return (NULL);
2725 		s[n - 1] = '\0';
2726 	}
2727 	return (s);
2728 }
2729 
2730 /*
2731  * Called from Pcreate(), Pgrab(), and Pfgrab_core() to initialize
2732  * the symbol table heads in the new ps_prochandle.
2733  */
2734 void
2735 Pinitsym(struct ps_prochandle *P)
2736 {
2737 	P->num_files = 0;
2738 	list_link(&P->file_head, NULL);
2739 }
2740 
2741 /*
2742  * Called from Prelease() to destroy the symbol tables.
2743  * Must be called by the client after an exec() in the victim process.
2744  */
2745 void
2746 Preset_maps(struct ps_prochandle *P)
2747 {
2748 	int i;
2749 
2750 	if (P->rap != NULL) {
2751 		rd_delete(P->rap);
2752 		P->rap = NULL;
2753 	}
2754 
2755 	if (P->execname != NULL) {
2756 		free(P->execname);
2757 		P->execname = NULL;
2758 	}
2759 
2760 	if (P->auxv != NULL) {
2761 		free(P->auxv);
2762 		P->auxv = NULL;
2763 		P->nauxv = 0;
2764 	}
2765 
2766 	for (i = 0; i < P->map_count; i++)
2767 		map_info_free(P, &P->mappings[i]);
2768 
2769 	if (P->mappings != NULL) {
2770 		free(P->mappings);
2771 		P->mappings = NULL;
2772 	}
2773 	P->map_count = P->map_alloc = 0;
2774 
2775 	P->info_valid = 0;
2776 }
2777 
2778 typedef struct getenv_data {
2779 	char *buf;
2780 	size_t bufsize;
2781 	const char *search;
2782 	size_t searchlen;
2783 } getenv_data_t;
2784 
2785 /*ARGSUSED*/
2786 static int
2787 getenv_func(void *data, struct ps_prochandle *P, uintptr_t addr,
2788     const char *nameval)
2789 {
2790 	getenv_data_t *d = data;
2791 	size_t len;
2792 
2793 	if (nameval == NULL)
2794 		return (0);
2795 
2796 	if (d->searchlen < strlen(nameval) &&
2797 	    strncmp(nameval, d->search, d->searchlen) == 0 &&
2798 	    nameval[d->searchlen] == '=') {
2799 		len = MIN(strlen(nameval), d->bufsize - 1);
2800 		(void) strncpy(d->buf, nameval, len);
2801 		d->buf[len] = '\0';
2802 		return (1);
2803 	}
2804 
2805 	return (0);
2806 }
2807 
2808 char *
2809 Pgetenv(struct ps_prochandle *P, const char *name, char *buf, size_t buflen)
2810 {
2811 	getenv_data_t d;
2812 
2813 	d.buf = buf;
2814 	d.bufsize = buflen;
2815 	d.search = name;
2816 	d.searchlen = strlen(name);
2817 
2818 	if (Penv_iter(P, getenv_func, &d) == 1) {
2819 		char *equals = strchr(d.buf, '=');
2820 
2821 		if (equals != NULL) {
2822 			(void) memmove(d.buf, equals + 1,
2823 			    d.buf + buflen - equals - 1);
2824 			d.buf[d.buf + buflen - equals] = '\0';
2825 
2826 			return (buf);
2827 		}
2828 	}
2829 
2830 	return (NULL);
2831 }
2832 
2833 /* number of argument or environment pointers to read all at once */
2834 #define	NARG	100
2835 
2836 int
2837 Penv_iter(struct ps_prochandle *P, proc_env_f *func, void *data)
2838 {
2839 	const psinfo_t *psp;
2840 	uintptr_t envpoff;
2841 	GElf_Sym sym;
2842 	int ret;
2843 	char *buf, *nameval;
2844 	size_t buflen;
2845 
2846 	int nenv = NARG;
2847 	long envp[NARG];
2848 
2849 	/*
2850 	 * Attempt to find the "_environ" variable in the process.
2851 	 * Failing that, use the original value provided by Ppsinfo().
2852 	 */
2853 	if ((psp = Ppsinfo(P)) == NULL)
2854 		return (-1);
2855 
2856 	envpoff = psp->pr_envp; /* Default if no _environ found */
2857 
2858 	if (Plookup_by_name(P, PR_OBJ_EXEC, "_environ", &sym) == 0) {
2859 		if (P->status.pr_dmodel == PR_MODEL_NATIVE) {
2860 			if (Pread(P, &envpoff, sizeof (envpoff),
2861 			    sym.st_value) != sizeof (envpoff))
2862 				envpoff = psp->pr_envp;
2863 		} else if (P->status.pr_dmodel == PR_MODEL_ILP32) {
2864 			uint32_t envpoff32;
2865 
2866 			if (Pread(P, &envpoff32, sizeof (envpoff32),
2867 			    sym.st_value) != sizeof (envpoff32))
2868 				envpoff = psp->pr_envp;
2869 			else
2870 				envpoff = envpoff32;
2871 		}
2872 	}
2873 
2874 	buflen = 128;
2875 	buf = malloc(buflen);
2876 
2877 	ret = 0;
2878 	for (;;) {
2879 		uintptr_t envoff;
2880 
2881 		if (nenv == NARG) {
2882 			(void) memset(envp, 0, sizeof (envp));
2883 			if (P->status.pr_dmodel == PR_MODEL_NATIVE) {
2884 				if (Pread(P, envp,
2885 				    sizeof (envp), envpoff) <= 0) {
2886 					ret = -1;
2887 					break;
2888 				}
2889 			} else if (P->status.pr_dmodel == PR_MODEL_ILP32) {
2890 				uint32_t e32[NARG];
2891 				int i;
2892 
2893 				(void) memset(e32, 0, sizeof (e32));
2894 				if (Pread(P, e32, sizeof (e32), envpoff) <= 0) {
2895 					ret = -1;
2896 					break;
2897 				}
2898 				for (i = 0; i < NARG; i++)
2899 					envp[i] = e32[i];
2900 			}
2901 			nenv = 0;
2902 		}
2903 
2904 		if ((envoff = envp[nenv++]) == NULL)
2905 			break;
2906 
2907 		/*
2908 		 * Attempt to read the string from the process.
2909 		 */
2910 again:
2911 		ret = Pread_string(P, buf, buflen, envoff);
2912 
2913 		if (ret <= 0) {
2914 			nameval = NULL;
2915 		} else if (ret == buflen - 1) {
2916 			free(buf);
2917 			/*
2918 			 * Bail if we have a corrupted environment
2919 			 */
2920 			if (buflen >= ARG_MAX)
2921 				return (-1);
2922 			buflen *= 2;
2923 			buf = malloc(buflen);
2924 			goto again;
2925 		} else {
2926 			nameval = buf;
2927 		}
2928 
2929 		if ((ret = func(data, P, envoff, nameval)) != 0)
2930 			break;
2931 
2932 		envpoff += (P->status.pr_dmodel == PR_MODEL_LP64)? 8 : 4;
2933 	}
2934 
2935 	free(buf);
2936 
2937 	return (ret);
2938 }
2939