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