Home | History | Annotate | Download | only in libdwfl
      1 /* Report modules by examining dynamic linker data structures.
      2    Copyright (C) 2008-2015 Red Hat, Inc.
      3    This file is part of elfutils.
      4 
      5    This file is free software; you can redistribute it and/or modify
      6    it under the terms of either
      7 
      8      * the GNU Lesser General Public License as published by the Free
      9        Software Foundation; either version 3 of the License, or (at
     10        your option) any later version
     11 
     12    or
     13 
     14      * the GNU General Public License as published by the Free
     15        Software Foundation; either version 2 of the License, or (at
     16        your option) any later version
     17 
     18    or both in parallel, as here.
     19 
     20    elfutils is distributed in the hope that it will be useful, but
     21    WITHOUT ANY WARRANTY; without even the implied warranty of
     22    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     23    General Public License for more details.
     24 
     25    You should have received copies of the GNU General Public License and
     26    the GNU Lesser General Public License along with this program.  If
     27    not, see <http://www.gnu.org/licenses/>.  */
     28 
     29 #include <config.h>
     30 #include "libdwflP.h"
     31 #include "../libdw/memory-access.h"
     32 #include "system.h"
     33 
     34 #include <byteswap.h>
     35 #include <endian.h>
     36 #include <fcntl.h>
     37 
     38 /* This element is always provided and always has a constant value.
     39    This makes it an easy thing to scan for to discern the format.  */
     40 #define PROBE_TYPE	AT_PHENT
     41 #define PROBE_VAL32	sizeof (Elf32_Phdr)
     42 #define PROBE_VAL64	sizeof (Elf64_Phdr)
     43 
     44 
     45 static inline bool
     46 do_check64 (size_t i, const Elf64_auxv_t (*a64)[], uint_fast8_t *elfdata)
     47 {
     48   /* The AUXV pointer might not even be naturally aligned for 64-bit
     49      data, because note payloads in a core file are not aligned.  */
     50 
     51   uint64_t type = read_8ubyte_unaligned_noncvt (&(*a64)[i].a_type);
     52   uint64_t val = read_8ubyte_unaligned_noncvt (&(*a64)[i].a_un.a_val);
     53 
     54   if (type == BE64 (PROBE_TYPE)
     55       && val == BE64 (PROBE_VAL64))
     56     {
     57       *elfdata = ELFDATA2MSB;
     58       return true;
     59     }
     60 
     61   if (type == LE64 (PROBE_TYPE)
     62       && val == LE64 (PROBE_VAL64))
     63     {
     64       *elfdata = ELFDATA2LSB;
     65       return true;
     66     }
     67 
     68   return false;
     69 }
     70 
     71 #define check64(n) do_check64 (n, a64, elfdata)
     72 
     73 static inline bool
     74 do_check32 (size_t i, const Elf32_auxv_t (*a32)[], uint_fast8_t *elfdata)
     75 {
     76   /* The AUXV pointer might not even be naturally aligned for 32-bit
     77      data, because note payloads in a core file are not aligned.  */
     78 
     79   uint32_t type = read_4ubyte_unaligned_noncvt (&(*a32)[i].a_type);
     80   uint32_t val = read_4ubyte_unaligned_noncvt (&(*a32)[i].a_un.a_val);
     81 
     82   if (type == BE32 (PROBE_TYPE)
     83       && val == BE32 (PROBE_VAL32))
     84     {
     85       *elfdata = ELFDATA2MSB;
     86       return true;
     87     }
     88 
     89   if (type == LE32 (PROBE_TYPE)
     90       && val == LE32 (PROBE_VAL32))
     91     {
     92       *elfdata = ELFDATA2LSB;
     93       return true;
     94     }
     95 
     96   return false;
     97 }
     98 
     99 #define check32(n) do_check32 (n, a32, elfdata)
    100 
    101 /* Examine an auxv data block and determine its format.
    102    Return true iff we figured it out.  */
    103 static bool
    104 auxv_format_probe (const void *auxv, size_t size,
    105 		   uint_fast8_t *elfclass, uint_fast8_t *elfdata)
    106 {
    107   const Elf32_auxv_t (*a32)[size / sizeof (Elf32_auxv_t)] = (void *) auxv;
    108   const Elf64_auxv_t (*a64)[size / sizeof (Elf64_auxv_t)] = (void *) auxv;
    109 
    110   for (size_t i = 0; i < size / sizeof (Elf64_auxv_t); ++i)
    111     {
    112       if (check64 (i))
    113 	{
    114 	  *elfclass = ELFCLASS64;
    115 	  return true;
    116 	}
    117 
    118       if (check32 (i * 2) || check32 (i * 2 + 1))
    119 	{
    120 	  *elfclass = ELFCLASS32;
    121 	  return true;
    122 	}
    123     }
    124 
    125   return false;
    126 }
    127 
    128 /* This is a Dwfl_Memory_Callback that wraps another memory callback.
    130    If the underlying callback cannot fill the data, then this will
    131    fall back to fetching data from module files.  */
    132 
    133 struct integrated_memory_callback
    134 {
    135   Dwfl_Memory_Callback *memory_callback;
    136   void *memory_callback_arg;
    137   void *buffer;
    138 };
    139 
    140 static bool
    141 integrated_memory_callback (Dwfl *dwfl, int ndx,
    142 			       void **buffer, size_t *buffer_available,
    143 			       GElf_Addr vaddr,
    144 			       size_t minread,
    145 			       void *arg)
    146 {
    147   struct integrated_memory_callback *info = arg;
    148 
    149   if (ndx == -1)
    150     {
    151       /* Called for cleanup.  */
    152       if (info->buffer != NULL)
    153 	{
    154 	  /* The last probe buffer came from the underlying callback.
    155 	     Let it do its cleanup.  */
    156 	  assert (*buffer == info->buffer); /* XXX */
    157 	  *buffer = info->buffer;
    158 	  info->buffer = NULL;
    159 	  return (*info->memory_callback) (dwfl, ndx, buffer, buffer_available,
    160 					   vaddr, minread,
    161 					   info->memory_callback_arg);
    162 	}
    163       *buffer = NULL;
    164       *buffer_available = 0;
    165       return false;
    166     }
    167 
    168   if (*buffer != NULL)
    169     /* For a final-read request, we only use the underlying callback.  */
    170     return (*info->memory_callback) (dwfl, ndx, buffer, buffer_available,
    171 				     vaddr, minread, info->memory_callback_arg);
    172 
    173   /* Let the underlying callback try to fill this request.  */
    174   if ((*info->memory_callback) (dwfl, ndx, &info->buffer, buffer_available,
    175 				vaddr, minread, info->memory_callback_arg))
    176     {
    177       *buffer = info->buffer;
    178       return true;
    179     }
    180 
    181   /* Now look for module text covering this address.  */
    182 
    183   Dwfl_Module *mod;
    184   (void) INTUSE(dwfl_addrsegment) (dwfl, vaddr, &mod);
    185   if (mod == NULL)
    186     return false;
    187 
    188   Dwarf_Addr bias;
    189   Elf_Scn *scn = INTUSE(dwfl_module_address_section) (mod, &vaddr, &bias);
    190   if (unlikely (scn == NULL))
    191     {
    192 #if 0 // XXX would have to handle ndx=-1 cleanup calls passed down.
    193       /* If we have no sections we can try to fill it from the module file
    194 	 based on its phdr mappings.  */
    195       if (likely (mod->e_type != ET_REL) && mod->main.elf != NULL)
    196 	return INTUSE(dwfl_elf_phdr_memory_callback)
    197 	  (dwfl, 0, buffer, buffer_available,
    198 	   vaddr - mod->main.bias, minread, mod->main.elf);
    199 #endif
    200       return false;
    201     }
    202 
    203   Elf_Data *data = elf_rawdata (scn, NULL);
    204   if (unlikely (data == NULL))
    205     // XXX throw error?
    206     return false;
    207 
    208   if (unlikely (data->d_size < vaddr))
    209     return false;
    210 
    211   /* Provide as much data as we have.  */
    212   void *contents = data->d_buf + vaddr;
    213   size_t avail = data->d_size - vaddr;
    214   if (unlikely (avail < minread))
    215     return false;
    216 
    217   /* If probing for a string, make sure it's terminated.  */
    218   if (minread == 0 && unlikely (memchr (contents, '\0', avail) == NULL))
    219     return false;
    220 
    221   /* We have it! */
    222   *buffer = contents;
    223   *buffer_available = avail;
    224   return true;
    225 }
    226 
    227 static size_t
    229 addrsize (uint_fast8_t elfclass)
    230 {
    231   return elfclass * 4;
    232 }
    233 
    234 /* Report a module for each struct link_map in the linked list at r_map
    235    in the struct r_debug at R_DEBUG_VADDR.  For r_debug_info description
    236    see dwfl_link_map_report in libdwflP.h.  If R_DEBUG_INFO is not NULL then no
    237    modules get added to DWFL, caller has to add them from filled in
    238    R_DEBUG_INFO.
    239 
    240    For each link_map entry, if an existing module resides at its address,
    241    this just modifies that module's name and suggested file name.  If
    242    no such module exists, this calls dwfl_report_elf on the l_name string.
    243 
    244    Returns the number of modules found, or -1 for errors.  */
    245 
    246 static int
    247 report_r_debug (uint_fast8_t elfclass, uint_fast8_t elfdata,
    248 		Dwfl *dwfl, GElf_Addr r_debug_vaddr,
    249 		Dwfl_Memory_Callback *memory_callback,
    250 		void *memory_callback_arg,
    251 		struct r_debug_info *r_debug_info)
    252 {
    253   /* Skip r_version, to aligned r_map field.  */
    254   GElf_Addr read_vaddr = r_debug_vaddr + addrsize (elfclass);
    255 
    256   void *buffer = NULL;
    257   size_t buffer_available = 0;
    258   inline int release_buffer (int result)
    259   {
    260     if (buffer != NULL)
    261       (void) (*memory_callback) (dwfl, -1, &buffer, &buffer_available, 0, 0,
    262 				 memory_callback_arg);
    263     return result;
    264   }
    265 
    266   GElf_Addr addrs[4];
    267   inline bool read_addrs (GElf_Addr vaddr, size_t n)
    268   {
    269     size_t nb = n * addrsize (elfclass); /* Address words -> bytes to read.  */
    270 
    271     /* Read a new buffer if the old one doesn't cover these words.  */
    272     if (buffer == NULL
    273 	|| vaddr < read_vaddr
    274 	|| vaddr - read_vaddr + nb > buffer_available)
    275       {
    276 	release_buffer (0);
    277 
    278 	read_vaddr = vaddr;
    279 	int segndx = INTUSE(dwfl_addrsegment) (dwfl, vaddr, NULL);
    280 	if (unlikely (segndx < 0)
    281 	    || unlikely (! (*memory_callback) (dwfl, segndx,
    282 					       &buffer, &buffer_available,
    283 					       vaddr, nb, memory_callback_arg)))
    284 	  return true;
    285       }
    286 
    287     Elf32_Addr (*a32)[n] = vaddr - read_vaddr + buffer;
    288     Elf64_Addr (*a64)[n] = (void *) a32;
    289 
    290     if (elfclass == ELFCLASS32)
    291       {
    292 	if (elfdata == ELFDATA2MSB)
    293 	  for (size_t i = 0; i < n; ++i)
    294 	    addrs[i] = BE32 (read_4ubyte_unaligned_noncvt (&(*a32)[i]));
    295 	else
    296 	  for (size_t i = 0; i < n; ++i)
    297 	    addrs[i] = LE32 (read_4ubyte_unaligned_noncvt (&(*a32)[i]));
    298       }
    299     else
    300       {
    301 	if (elfdata == ELFDATA2MSB)
    302 	  for (size_t i = 0; i < n; ++i)
    303 	    addrs[i] = BE64 (read_8ubyte_unaligned_noncvt (&(*a64)[i]));
    304 	else
    305 	  for (size_t i = 0; i < n; ++i)
    306 	    addrs[i] = LE64 (read_8ubyte_unaligned_noncvt (&(*a64)[i]));
    307       }
    308 
    309     return false;
    310   }
    311 
    312   if (unlikely (read_addrs (read_vaddr, 1)))
    313     return release_buffer (-1);
    314 
    315   GElf_Addr next = addrs[0];
    316 
    317   Dwfl_Module **lastmodp = &dwfl->modulelist;
    318   int result = 0;
    319 
    320   /* There can't be more elements in the link_map list than there are
    321      segments.  DWFL->lookup_elts is probably twice that number, so it
    322      is certainly above the upper bound.  If we iterate too many times,
    323      there must be a loop in the pointers due to link_map clobberation.  */
    324   size_t iterations = 0;
    325   while (next != 0 && ++iterations < dwfl->lookup_elts)
    326     {
    327       if (read_addrs (next, 4))
    328 	return release_buffer (-1);
    329 
    330       /* Unused: l_addr is the difference between the address in memory
    331          and the ELF file when the core was created. We need to
    332          recalculate the difference below because the ELF file we use
    333          might be differently pre-linked.  */
    334       // GElf_Addr l_addr = addrs[0];
    335       GElf_Addr l_name = addrs[1];
    336       GElf_Addr l_ld = addrs[2];
    337       next = addrs[3];
    338 
    339       /* If a clobbered or truncated memory image has no useful pointer,
    340 	 just skip this element.  */
    341       if (l_ld == 0)
    342 	continue;
    343 
    344       /* Fetch the string at the l_name address.  */
    345       const char *name = NULL;
    346       if (buffer != NULL
    347 	  && read_vaddr <= l_name
    348 	  && l_name + 1 - read_vaddr < buffer_available
    349 	  && memchr (l_name - read_vaddr + buffer, '\0',
    350 		     buffer_available - (l_name - read_vaddr)) != NULL)
    351 	name = l_name - read_vaddr + buffer;
    352       else
    353 	{
    354 	  release_buffer (0);
    355 	  read_vaddr = l_name;
    356 	  int segndx = INTUSE(dwfl_addrsegment) (dwfl, l_name, NULL);
    357 	  if (likely (segndx >= 0)
    358 	      && (*memory_callback) (dwfl, segndx,
    359 				     &buffer, &buffer_available,
    360 				     l_name, 0, memory_callback_arg))
    361 	    name = buffer;
    362 	}
    363 
    364       if (name != NULL && name[0] == '\0')
    365 	name = NULL;
    366 
    367       if (iterations == 1
    368 	  && dwfl->user_core != NULL
    369 	  && dwfl->user_core->executable_for_core != NULL)
    370 	name = dwfl->user_core->executable_for_core;
    371 
    372       struct r_debug_info_module *r_debug_info_module = NULL;
    373       if (r_debug_info != NULL)
    374 	{
    375 	  /* Save link map information about valid shared library (or
    376 	     executable) which has not been found on disk.  */
    377 	  const char *name1 = name == NULL ? "" : name;
    378 	  r_debug_info_module = malloc (sizeof (*r_debug_info_module)
    379 					+ strlen (name1) + 1);
    380 	  if (unlikely (r_debug_info_module == NULL))
    381 	    return release_buffer (result);
    382 	  r_debug_info_module->fd = -1;
    383 	  r_debug_info_module->elf = NULL;
    384 	  r_debug_info_module->l_ld = l_ld;
    385 	  r_debug_info_module->start = 0;
    386 	  r_debug_info_module->end = 0;
    387 	  r_debug_info_module->disk_file_has_build_id = false;
    388 	  strcpy (r_debug_info_module->name, name1);
    389 	  r_debug_info_module->next = r_debug_info->module;
    390 	  r_debug_info->module = r_debug_info_module;
    391 	}
    392 
    393       Dwfl_Module *mod = NULL;
    394       if (name != NULL)
    395 	{
    396 	  /* This code is mostly inlined dwfl_report_elf.  */
    397 	  // XXX hook for sysroot
    398 	  int fd = open (name, O_RDONLY);
    399 	  if (fd >= 0)
    400 	    {
    401 	      Elf *elf;
    402 	      Dwfl_Error error = __libdw_open_file (&fd, &elf, true, false);
    403 	      GElf_Addr elf_dynamic_vaddr;
    404 	      if (error == DWFL_E_NOERROR
    405 		  && __libdwfl_dynamic_vaddr_get (elf, &elf_dynamic_vaddr))
    406 		{
    407 		  const void *build_id_bits;
    408 		  GElf_Addr build_id_elfaddr;
    409 		  int build_id_len;
    410 		  bool valid = true;
    411 
    412 		  if (__libdwfl_find_elf_build_id (NULL, elf, &build_id_bits,
    413 						   &build_id_elfaddr,
    414 						   &build_id_len) > 0
    415 		      && build_id_elfaddr != 0)
    416 		    {
    417 		      if (r_debug_info_module != NULL)
    418 			r_debug_info_module->disk_file_has_build_id = true;
    419 		      GElf_Addr build_id_vaddr = (build_id_elfaddr
    420 						  - elf_dynamic_vaddr + l_ld);
    421 
    422 		      release_buffer (0);
    423 		      int segndx = INTUSE(dwfl_addrsegment) (dwfl,
    424 							     build_id_vaddr,
    425 							     NULL);
    426 		      if (! (*memory_callback) (dwfl, segndx,
    427 						&buffer, &buffer_available,
    428 						build_id_vaddr, build_id_len,
    429 						memory_callback_arg))
    430 			{
    431 			  /* File has valid build-id which cannot be read from
    432 			     memory.  This happens for core files without bit 4
    433 			     (0x10) set in Linux /proc/PID/coredump_filter.  */
    434 			}
    435 		      else
    436 			{
    437 			  if (memcmp (build_id_bits, buffer, build_id_len) != 0)
    438 			    /* File has valid build-id which does not match
    439 			       the one in memory.  */
    440 			    valid = false;
    441 			  release_buffer (0);
    442 			}
    443 		    }
    444 
    445 		  if (valid)
    446 		    {
    447 		      // It is like l_addr but it handles differently prelinked
    448 		      // files at core dumping vs. core loading time.
    449 		      GElf_Addr base = l_ld - elf_dynamic_vaddr;
    450 		      if (r_debug_info_module == NULL)
    451 			{
    452 			  // XXX hook for sysroot
    453 			  mod = __libdwfl_report_elf (dwfl, basename (name),
    454 						      name, fd, elf, base,
    455 						      true, true);
    456 			  if (mod != NULL)
    457 			    {
    458 			      elf = NULL;
    459 			      fd = -1;
    460 			    }
    461 			}
    462 		      else if (__libdwfl_elf_address_range (elf, base, true,
    463 							    true, NULL, NULL,
    464 						    &r_debug_info_module->start,
    465 						    &r_debug_info_module->end,
    466 							    NULL, NULL))
    467 			{
    468 			  r_debug_info_module->elf = elf;
    469 			  r_debug_info_module->fd = fd;
    470 			  elf = NULL;
    471 			  fd = -1;
    472 			}
    473 		    }
    474 		  if (elf != NULL)
    475 		    elf_end (elf);
    476 		  if (fd != -1)
    477 		    close (fd);
    478 		}
    479 	    }
    480 	}
    481 
    482       if (mod != NULL)
    483 	{
    484 	  ++result;
    485 
    486 	  /* Move this module to the end of the list, so that we end
    487 	     up with a list in the same order as the link_map chain.  */
    488 	  if (mod->next != NULL)
    489 	    {
    490 	      if (*lastmodp != mod)
    491 		{
    492 		  lastmodp = &dwfl->modulelist;
    493 		  while (*lastmodp != mod)
    494 		    lastmodp = &(*lastmodp)->next;
    495 		}
    496 	      *lastmodp = mod->next;
    497 	      mod->next = NULL;
    498 	      while (*lastmodp != NULL)
    499 		lastmodp = &(*lastmodp)->next;
    500 	      *lastmodp = mod;
    501 	    }
    502 
    503 	  lastmodp = &mod->next;
    504 	}
    505     }
    506 
    507   return release_buffer (result);
    508 }
    509 
    510 static GElf_Addr
    512 consider_executable (Dwfl_Module *mod, GElf_Addr at_phdr, GElf_Addr at_entry,
    513 		     uint_fast8_t *elfclass, uint_fast8_t *elfdata,
    514 		     Dwfl_Memory_Callback *memory_callback,
    515 		     void *memory_callback_arg)
    516 {
    517   GElf_Ehdr ehdr;
    518   if (unlikely (gelf_getehdr (mod->main.elf, &ehdr) == NULL))
    519     return 0;
    520 
    521   if (at_entry != 0)
    522     {
    523       /* If we have an AT_ENTRY value, reject this executable if
    524 	 its entry point address could not have supplied that.  */
    525 
    526       if (ehdr.e_entry == 0)
    527 	return 0;
    528 
    529       if (mod->e_type == ET_EXEC)
    530 	{
    531 	  if (ehdr.e_entry != at_entry)
    532 	    return 0;
    533 	}
    534       else
    535 	{
    536 	  /* It could be a PIE.  */
    537 	}
    538     }
    539 
    540   // XXX this could be saved in the file cache: phdr vaddr, DT_DEBUG d_val vaddr
    541   /* Find the vaddr of the DT_DEBUG's d_ptr.  This is the memory
    542      address where &r_debug was written at runtime.  */
    543   GElf_Xword align = mod->dwfl->segment_align;
    544   GElf_Addr d_val_vaddr = 0;
    545   size_t phnum;
    546   if (elf_getphdrnum (mod->main.elf, &phnum) != 0)
    547     return 0;
    548 
    549   for (size_t i = 0; i < phnum; ++i)
    550     {
    551       GElf_Phdr phdr_mem;
    552       GElf_Phdr *phdr = gelf_getphdr (mod->main.elf, i, &phdr_mem);
    553       if (phdr == NULL)
    554 	break;
    555 
    556       if (phdr->p_align > 1 && (align == 0 || phdr->p_align < align))
    557 	align = phdr->p_align;
    558 
    559       if (at_phdr != 0
    560 	  && phdr->p_type == PT_LOAD
    561 	  && (phdr->p_offset & -align) == (ehdr.e_phoff & -align))
    562 	{
    563 	  /* This is the segment that would map the phdrs.
    564 	     If we have an AT_PHDR value, reject this executable
    565 	     if its phdr mapping could not have supplied that.  */
    566 	  if (mod->e_type == ET_EXEC)
    567 	    {
    568 	      if (ehdr.e_phoff - phdr->p_offset + phdr->p_vaddr != at_phdr)
    569 		return 0;
    570 	    }
    571 	  else
    572 	    {
    573 	      /* It could be a PIE.  If the AT_PHDR value and our
    574 		 phdr address don't match modulo ALIGN, then this
    575 		 could not have been the right PIE.  */
    576 	      if (((ehdr.e_phoff - phdr->p_offset + phdr->p_vaddr) & -align)
    577 		  != (at_phdr & -align))
    578 		return 0;
    579 
    580 	      /* Calculate the bias applied to the PIE's p_vaddr values.  */
    581 	      GElf_Addr bias = (at_phdr - (ehdr.e_phoff - phdr->p_offset
    582 					   + phdr->p_vaddr));
    583 
    584 	      /* Final sanity check: if we have an AT_ENTRY value,
    585 		 reject this PIE unless its biased e_entry matches.  */
    586 	      if (at_entry != 0 && at_entry != ehdr.e_entry + bias)
    587 		return 0;
    588 
    589 	      /* If we're changing the module's address range,
    590 		 we've just invalidated the module lookup table.  */
    591 	      GElf_Addr mod_bias = dwfl_adjusted_address (mod, 0);
    592 	      if (bias != mod_bias)
    593 		{
    594 		  mod->low_addr -= mod_bias;
    595 		  mod->high_addr -= mod_bias;
    596 		  mod->low_addr += bias;
    597 		  mod->high_addr += bias;
    598 
    599 		  free (mod->dwfl->lookup_module);
    600 		  mod->dwfl->lookup_module = NULL;
    601 		}
    602 	    }
    603 	}
    604 
    605       if (phdr->p_type == PT_DYNAMIC)
    606 	{
    607 	  Elf_Data *data = elf_getdata_rawchunk (mod->main.elf, phdr->p_offset,
    608 						 phdr->p_filesz, ELF_T_DYN);
    609 	  if (data == NULL)
    610 	    continue;
    611 	  const size_t entsize = gelf_fsize (mod->main.elf,
    612 					     ELF_T_DYN, 1, EV_CURRENT);
    613 	  const size_t n = data->d_size / entsize;
    614 	  for (size_t j = 0; j < n; ++j)
    615 	    {
    616 	      GElf_Dyn dyn_mem;
    617 	      GElf_Dyn *dyn = gelf_getdyn (data, j, &dyn_mem);
    618 	      if (dyn != NULL && dyn->d_tag == DT_DEBUG)
    619 		{
    620 		  d_val_vaddr = phdr->p_vaddr + entsize * j + entsize / 2;
    621 		  break;
    622 		}
    623 	    }
    624 	}
    625     }
    626 
    627   if (d_val_vaddr != 0)
    628     {
    629       /* Now we have the final address from which to read &r_debug.  */
    630       d_val_vaddr = dwfl_adjusted_address (mod, d_val_vaddr);
    631 
    632       void *buffer = NULL;
    633       size_t buffer_available = addrsize (ehdr.e_ident[EI_CLASS]);
    634 
    635       int segndx = INTUSE(dwfl_addrsegment) (mod->dwfl, d_val_vaddr, NULL);
    636 
    637       if ((*memory_callback) (mod->dwfl, segndx,
    638 			      &buffer, &buffer_available,
    639 			      d_val_vaddr, buffer_available,
    640 			      memory_callback_arg))
    641 	{
    642 	  const union
    643 	  {
    644 	    Elf32_Addr a32;
    645 	    Elf64_Addr a64;
    646 	  } *u = buffer;
    647 
    648 	  GElf_Addr vaddr;
    649 	  if (ehdr.e_ident[EI_CLASS] == ELFCLASS32)
    650 	    vaddr = (ehdr.e_ident[EI_DATA] == ELFDATA2MSB
    651 		     ? BE32 (u->a32) : LE32 (u->a32));
    652 	  else
    653 	    vaddr = (ehdr.e_ident[EI_DATA] == ELFDATA2MSB
    654 		     ? BE64 (u->a64) : LE64 (u->a64));
    655 
    656 	  (*memory_callback) (mod->dwfl, -1, &buffer, &buffer_available, 0, 0,
    657 			      memory_callback_arg);
    658 
    659 	  if (*elfclass == ELFCLASSNONE)
    660 	    *elfclass = ehdr.e_ident[EI_CLASS];
    661 	  else if (*elfclass != ehdr.e_ident[EI_CLASS])
    662 	    return 0;
    663 
    664 	  if (*elfdata == ELFDATANONE)
    665 	    *elfdata = ehdr.e_ident[EI_DATA];
    666 	  else if (*elfdata != ehdr.e_ident[EI_DATA])
    667 	    return 0;
    668 
    669 	  return vaddr;
    670 	}
    671     }
    672 
    673   return 0;
    674 }
    675 
    676 /* Try to find an existing executable module with a DT_DEBUG.  */
    677 static GElf_Addr
    678 find_executable (Dwfl *dwfl, GElf_Addr at_phdr, GElf_Addr at_entry,
    679 		 uint_fast8_t *elfclass, uint_fast8_t *elfdata,
    680 		 Dwfl_Memory_Callback *memory_callback,
    681 		 void *memory_callback_arg)
    682 {
    683   for (Dwfl_Module *mod = dwfl->modulelist; mod != NULL; mod = mod->next)
    684     if (mod->main.elf != NULL)
    685       {
    686 	GElf_Addr r_debug_vaddr = consider_executable (mod, at_phdr, at_entry,
    687 						       elfclass, elfdata,
    688 						       memory_callback,
    689 						       memory_callback_arg);
    690 	if (r_debug_vaddr != 0)
    691 	  return r_debug_vaddr;
    692       }
    693 
    694   return 0;
    695 }
    696 
    697 
    699 int
    700 dwfl_link_map_report (Dwfl *dwfl, const void *auxv, size_t auxv_size,
    701 		      Dwfl_Memory_Callback *memory_callback,
    702 		      void *memory_callback_arg,
    703 		      struct r_debug_info *r_debug_info)
    704 {
    705   GElf_Addr r_debug_vaddr = 0;
    706 
    707   uint_fast8_t elfclass = ELFCLASSNONE;
    708   uint_fast8_t elfdata = ELFDATANONE;
    709   if (likely (auxv != NULL)
    710       && likely (auxv_format_probe (auxv, auxv_size, &elfclass, &elfdata)))
    711     {
    712       GElf_Addr entry = 0;
    713       GElf_Addr phdr = 0;
    714       GElf_Xword phent = 0;
    715       GElf_Xword phnum = 0;
    716 
    717 #define READ_AUXV32(ptr)	read_4ubyte_unaligned_noncvt (ptr)
    718 #define READ_AUXV64(ptr)	read_8ubyte_unaligned_noncvt (ptr)
    719 #define AUXV_SCAN(NN, BL) do                                            \
    720 	{                                                               \
    721 	  const Elf##NN##_auxv_t *av = auxv;                            \
    722 	  for (size_t i = 0; i < auxv_size / sizeof av[0]; ++i)         \
    723 	    {                                                           \
    724               uint##NN##_t type = READ_AUXV##NN (&av[i].a_type);        \
    725               uint##NN##_t val = BL##NN (READ_AUXV##NN (&av[i].a_un.a_val)); \
    726 	      if (type == BL##NN (AT_ENTRY))                            \
    727 		entry = val;                                            \
    728 	      else if (type == BL##NN (AT_PHDR))                        \
    729 		phdr = val;                                             \
    730 	      else if (type == BL##NN (AT_PHNUM))                       \
    731 		phnum = val;                                            \
    732 	      else if (type == BL##NN (AT_PHENT))                       \
    733 		phent = val;                                            \
    734 	      else if (type == BL##NN (AT_PAGESZ))                      \
    735 		{                                                       \
    736 		  if (val > 1                                           \
    737 		      && (dwfl->segment_align == 0                      \
    738 			  || val < dwfl->segment_align))                \
    739 		    dwfl->segment_align = val;                          \
    740 		}                                                       \
    741 	    }                                                           \
    742 	}                                                               \
    743       while (0)
    744 
    745       if (elfclass == ELFCLASS32)
    746 	{
    747 	  if (elfdata == ELFDATA2MSB)
    748 	    AUXV_SCAN (32, BE);
    749 	  else
    750 	    AUXV_SCAN (32, LE);
    751 	}
    752       else
    753 	{
    754 	  if (elfdata == ELFDATA2MSB)
    755 	    AUXV_SCAN (64, BE);
    756 	  else
    757 	    AUXV_SCAN (64, LE);
    758 	}
    759 
    760       /* If we found the phdr dimensions, search phdrs for PT_DYNAMIC.  */
    761       GElf_Addr dyn_vaddr = 0;
    762       GElf_Xword dyn_filesz = 0;
    763       GElf_Addr dyn_bias = (GElf_Addr) -1;
    764 
    765       inline bool consider_phdr (GElf_Word type,
    766 				 GElf_Addr vaddr, GElf_Xword filesz)
    767       {
    768 	switch (type)
    769 	  {
    770 	  case PT_PHDR:
    771 	    if (dyn_bias == (GElf_Addr) -1
    772 		/* Do a sanity check on the putative address.  */
    773 		&& ((vaddr & (dwfl->segment_align - 1))
    774 		    == (phdr & (dwfl->segment_align - 1))))
    775 	      {
    776 		dyn_bias = phdr - vaddr;
    777 		return dyn_vaddr != 0;
    778 	      }
    779 	    break;
    780 
    781 	  case PT_DYNAMIC:
    782 	    dyn_vaddr = vaddr;
    783 	    dyn_filesz = filesz;
    784 	    return dyn_bias != (GElf_Addr) -1;
    785 	  }
    786 
    787 	return false;
    788       }
    789 
    790       if (phdr != 0 && phnum != 0)
    791 	{
    792 	  Dwfl_Module *phdr_mod;
    793 	  int phdr_segndx = INTUSE(dwfl_addrsegment) (dwfl, phdr, &phdr_mod);
    794 	  Elf_Data in =
    795 	    {
    796 	      .d_type = ELF_T_PHDR,
    797 	      .d_version = EV_CURRENT,
    798 	      .d_size = phnum * phent,
    799 	      .d_buf = NULL
    800 	    };
    801 	  bool in_ok = (*memory_callback) (dwfl, phdr_segndx, &in.d_buf,
    802 					   &in.d_size, phdr, phnum * phent,
    803 					   memory_callback_arg);
    804 	  bool in_from_exec = false;
    805 	  if (! in_ok
    806 	      && dwfl->user_core != NULL
    807 	      && dwfl->user_core->executable_for_core != NULL)
    808 	    {
    809 	      /* AUXV -> PHDR -> DYNAMIC
    810 		 Both AUXV and DYNAMIC should be always present in a core file.
    811 		 PHDR may be missing in core file, try to read it from
    812 		 EXECUTABLE_FOR_CORE to find where DYNAMIC is located in the
    813 		 core file.  */
    814 
    815 	      int fd = open (dwfl->user_core->executable_for_core, O_RDONLY);
    816 	      Elf *elf;
    817 	      Dwfl_Error error = DWFL_E_ERRNO;
    818 	      if (fd != -1)
    819 		error = __libdw_open_file (&fd, &elf, true, false);
    820 	      if (error != DWFL_E_NOERROR)
    821 		{
    822 		  __libdwfl_seterrno (error);
    823 		  return false;
    824 		}
    825 	      GElf_Ehdr ehdr_mem, *ehdr = gelf_getehdr (elf, &ehdr_mem);
    826 	      if (ehdr == NULL)
    827 		{
    828 		  elf_end (elf);
    829 		  close (fd);
    830 		  __libdwfl_seterrno (DWFL_E_LIBELF);
    831 		  return false;
    832 		}
    833 	      size_t e_phnum;
    834 	      if (elf_getphdrnum (elf, &e_phnum) != 0)
    835 		{
    836 		  elf_end (elf);
    837 		  close (fd);
    838 		  __libdwfl_seterrno (DWFL_E_LIBELF);
    839 		  return false;
    840 		}
    841 	      if (e_phnum != phnum || ehdr->e_phentsize != phent)
    842 		{
    843 		  elf_end (elf);
    844 		  close (fd);
    845 		  __libdwfl_seterrno (DWFL_E_BADELF);
    846 		  return false;
    847 		}
    848 	      off_t off = ehdr->e_phoff;
    849 	      assert (in.d_buf == NULL);
    850 	      assert (in.d_size == phnum * phent);
    851 	      in.d_buf = malloc (in.d_size);
    852 	      if (unlikely (in.d_buf == NULL))
    853 		{
    854 		  elf_end (elf);
    855 		  close (fd);
    856 		  __libdwfl_seterrno (DWFL_E_NOMEM);
    857 		  return false;
    858 		}
    859 	      ssize_t nread = pread_retry (fd, in.d_buf, in.d_size, off);
    860 	      elf_end (elf);
    861 	      close (fd);
    862 	      if (nread != (ssize_t) in.d_size)
    863 		{
    864 		  free (in.d_buf);
    865 		  __libdwfl_seterrno (DWFL_E_ERRNO);
    866 		  return false;
    867 		}
    868 	      in_ok = true;
    869 	      in_from_exec = true;
    870 	    }
    871 	  if (in_ok)
    872 	    {
    873 	      if (unlikely (phnum > SIZE_MAX / phent))
    874 		{
    875 		  __libdwfl_seterrno (DWFL_E_NOMEM);
    876 		  return false;
    877 		}
    878 	      size_t nbytes = phnum * phent;
    879 	      void *buf = malloc (nbytes);
    880 	      Elf32_Phdr (*p32)[phnum] = buf;
    881 	      Elf64_Phdr (*p64)[phnum] = buf;
    882 	      if (unlikely (buf == NULL))
    883 		{
    884 		  __libdwfl_seterrno (DWFL_E_NOMEM);
    885 		  return false;
    886 		}
    887 	      Elf_Data out =
    888 		{
    889 		  .d_type = ELF_T_PHDR,
    890 		  .d_version = EV_CURRENT,
    891 		  .d_size = phnum * phent,
    892 		  .d_buf = buf
    893 		};
    894 	      in.d_size = out.d_size;
    895 	      if (likely ((elfclass == ELFCLASS32
    896 			   ? elf32_xlatetom : elf64_xlatetom)
    897 			  (&out, &in, elfdata) != NULL))
    898 		{
    899 		  /* We are looking for PT_DYNAMIC.  */
    900 		  if (elfclass == ELFCLASS32)
    901 		    {
    902 		      for (size_t i = 0; i < phnum; ++i)
    903 			if (consider_phdr ((*p32)[i].p_type,
    904 					   (*p32)[i].p_vaddr,
    905 					   (*p32)[i].p_filesz))
    906 			  break;
    907 		    }
    908 		  else
    909 		    {
    910 		      for (size_t i = 0; i < phnum; ++i)
    911 			if (consider_phdr ((*p64)[i].p_type,
    912 					   (*p64)[i].p_vaddr,
    913 					   (*p64)[i].p_filesz))
    914 			  break;
    915 		    }
    916 		}
    917 
    918 	      if (in_from_exec)
    919 		free (in.d_buf);
    920 	      else
    921 		(*memory_callback) (dwfl, -1, &in.d_buf, &in.d_size, 0, 0,
    922 				    memory_callback_arg);
    923 	      free (buf);
    924 	    }
    925 	  else
    926 	    /* We could not read the executable's phdrs from the
    927 	       memory image.  If we have a presupplied executable,
    928 	       we can still use the AT_PHDR and AT_ENTRY values to
    929 	       verify it, and to adjust its bias if it's a PIE.
    930 
    931 	       If there was an ET_EXEC module presupplied that contains
    932 	       the AT_PHDR address, then we only consider that one.
    933 	       We'll either accept it if its phdr location and e_entry
    934 	       make sense or reject it if they don't.  If there is no
    935 	       presupplied ET_EXEC, then look for a presupplied module,
    936 	       which might be a PIE (ET_DYN) that needs its bias adjusted.  */
    937 	    r_debug_vaddr = ((phdr_mod == NULL
    938 			      || phdr_mod->main.elf == NULL
    939 			      || phdr_mod->e_type != ET_EXEC)
    940 			     ? find_executable (dwfl, phdr, entry,
    941 						&elfclass, &elfdata,
    942 						memory_callback,
    943 						memory_callback_arg)
    944 			     : consider_executable (phdr_mod, phdr, entry,
    945 						    &elfclass, &elfdata,
    946 						    memory_callback,
    947 						    memory_callback_arg));
    948 	}
    949 
    950       /* If we found PT_DYNAMIC, search it for DT_DEBUG.  */
    951       if (dyn_filesz != 0)
    952 	{
    953 	  if (dyn_bias != (GElf_Addr) -1)
    954 	    dyn_vaddr += dyn_bias;
    955 
    956 	  Elf_Data in =
    957 	    {
    958 	      .d_type = ELF_T_DYN,
    959 	      .d_version = EV_CURRENT,
    960 	      .d_size = dyn_filesz,
    961 	      .d_buf = NULL
    962 	    };
    963 	  int dyn_segndx = dwfl_addrsegment (dwfl, dyn_vaddr, NULL);
    964 	  if ((*memory_callback) (dwfl, dyn_segndx, &in.d_buf, &in.d_size,
    965 				  dyn_vaddr, dyn_filesz, memory_callback_arg))
    966 	    {
    967 	      void *buf = malloc (dyn_filesz);
    968 	      Elf32_Dyn (*d32)[dyn_filesz / sizeof (Elf32_Dyn)] = buf;
    969 	      Elf64_Dyn (*d64)[dyn_filesz / sizeof (Elf64_Dyn)] = buf;
    970 	      if (unlikely (buf == NULL))
    971 		{
    972 		  __libdwfl_seterrno (DWFL_E_NOMEM);
    973 		  return false;
    974 		}
    975 	      Elf_Data out =
    976 		{
    977 		  .d_type = ELF_T_DYN,
    978 		  .d_version = EV_CURRENT,
    979 		  .d_size = dyn_filesz,
    980 		  .d_buf = buf
    981 		};
    982 	      in.d_size = out.d_size;
    983 	      if (likely ((elfclass == ELFCLASS32
    984 			   ? elf32_xlatetom : elf64_xlatetom)
    985 			  (&out, &in, elfdata) != NULL))
    986 		{
    987 		  /* We are looking for DT_DEBUG.  */
    988 		  if (elfclass == ELFCLASS32)
    989 		    {
    990 		      size_t n = dyn_filesz / sizeof (Elf32_Dyn);
    991 		      for (size_t i = 0; i < n; ++i)
    992 			if ((*d32)[i].d_tag == DT_DEBUG)
    993 			  {
    994 			    r_debug_vaddr = (*d32)[i].d_un.d_val;
    995 			    break;
    996 			  }
    997 		    }
    998 		  else
    999 		    {
   1000 		      size_t n = dyn_filesz / sizeof (Elf64_Dyn);
   1001 		      for (size_t i = 0; i < n; ++i)
   1002 			if ((*d64)[i].d_tag == DT_DEBUG)
   1003 			  {
   1004 			    r_debug_vaddr = (*d64)[i].d_un.d_val;
   1005 			    break;
   1006 			  }
   1007 		    }
   1008 		}
   1009 
   1010 	      (*memory_callback) (dwfl, -1, &in.d_buf, &in.d_size, 0, 0,
   1011 				  memory_callback_arg);
   1012 	      free (buf);
   1013 	    }
   1014 	}
   1015     }
   1016   else
   1017     /* We have to look for a presupplied executable file to determine
   1018        the vaddr of its dynamic section and DT_DEBUG therein.  */
   1019     r_debug_vaddr = find_executable (dwfl, 0, 0, &elfclass, &elfdata,
   1020 				     memory_callback, memory_callback_arg);
   1021 
   1022   if (r_debug_vaddr == 0)
   1023     return 0;
   1024 
   1025   /* For following pointers from struct link_map, we will use an
   1026      integrated memory access callback that can consult module text
   1027      elided from the core file.  This is necessary when the l_name
   1028      pointer for the dynamic linker's own entry is a pointer into the
   1029      executable's .interp section.  */
   1030   struct integrated_memory_callback mcb =
   1031     {
   1032       .memory_callback = memory_callback,
   1033       .memory_callback_arg = memory_callback_arg
   1034     };
   1035 
   1036   /* Now we can follow the dynamic linker's library list.  */
   1037   return report_r_debug (elfclass, elfdata, dwfl, r_debug_vaddr,
   1038 			 &integrated_memory_callback, &mcb, r_debug_info);
   1039 }
   1040 INTDEF (dwfl_link_map_report)
   1041