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