1 /* Sniff out modules from ELF headers visible in memory segments.
2 Copyright (C) 2008-2012, 2014, 2015, 2018 Red Hat, Inc.
3 Copyright (C) 2021 Mark J. Wielaard <mark@klomp.org>
4 This file is part of elfutils.
5
6 This file is free software; you can redistribute it and/or modify
7 it under the terms of either
8
9 * the GNU Lesser General Public License as published by the Free
10 Software Foundation; either version 3 of the License, or (at
11 your option) any later version
12
13 or
14
15 * the GNU General Public License as published by the Free
16 Software Foundation; either version 2 of the License, or (at
17 your option) any later version
18
19 or both in parallel, as here.
20
21 elfutils is distributed in the hope that it will be useful, but
22 WITHOUT ANY WARRANTY; without even the implied warranty of
23 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24 General Public License for more details.
25
26 You should have received copies of the GNU General Public License and
27 the GNU Lesser General Public License along with this program. If
28 not, see <http://www.gnu.org/licenses/>. */
29
30 #include <config.h>
31 #include "../libelf/libelfP.h" /* For NOTE_ALIGN4 and NOTE_ALIGN8. */
32 #undef _
33 #include "libdwflP.h"
34 #include "common.h"
35
36 #include <elf.h>
37 #include <gelf.h>
38 #include <inttypes.h>
39 #include <fcntl.h>
40
41 #include <system.h>
42
43
44 /* A good size for the initial read from memory, if it's not too costly.
45 This more than covers the phdrs and note segment in the average 64-bit
46 binary. */
47
48 #define INITIAL_READ 1024
49
50 #if BYTE_ORDER == LITTLE_ENDIAN
51 # define MY_ELFDATA ELFDATA2LSB
52 #else
53 # define MY_ELFDATA ELFDATA2MSB
54 #endif
55
56 struct elf_build_id
57 {
58 void *memory;
59 size_t len;
60 GElf_Addr vaddr;
61 };
62
63 struct read_state
64 {
65 Dwfl *dwfl;
66 Dwfl_Memory_Callback *memory_callback;
67 void *memory_callback_arg;
68 void **buffer;
69 size_t *buffer_available;
70 };
71
72 /* Return user segment index closest to ADDR but not above it.
73 If NEXT, return the closest to ADDR but not below it. */
74 static int
addr_segndx(Dwfl *dwfl, size_t segment, GElf_Addr addr, bool next)75 addr_segndx (Dwfl *dwfl, size_t segment, GElf_Addr addr, bool next)
76 {
77 int ndx = -1;
78 do
79 {
80 if (dwfl->lookup_segndx[segment] >= 0)
81 ndx = dwfl->lookup_segndx[segment];
82 if (++segment >= dwfl->lookup_elts - 1)
83 return next ? ndx + 1 : ndx;
84 }
85 while (dwfl->lookup_addr[segment] < addr);
86
87 if (next)
88 {
89 while (dwfl->lookup_segndx[segment] < 0)
90 if (++segment >= dwfl->lookup_elts - 1)
91 return ndx + 1;
92 ndx = dwfl->lookup_segndx[segment];
93 }
94
95 return ndx;
96 }
97
98 /* Return whether there is SZ bytes available at PTR till END. */
99
100 static bool
buf_has_data(const void *ptr, const void *end, size_t sz)101 buf_has_data (const void *ptr, const void *end, size_t sz)
102 {
103 return ptr < end && (size_t) (end - ptr) >= sz;
104 }
105
106 /* Read SZ bytes into *RETP from *PTRP (limited by END) in format EI_DATA.
107 Function comes from src/readelf.c . */
108
109 static bool
buf_read_ulong(unsigned char ei_data, size_t sz, const void **ptrp, const void *end, uint64_t *retp)110 buf_read_ulong (unsigned char ei_data, size_t sz,
111 const void **ptrp, const void *end, uint64_t *retp)
112 {
113 if (! buf_has_data (*ptrp, end, sz))
114 return false;
115
116 union
117 {
118 uint64_t u64;
119 uint32_t u32;
120 } u;
121
122 memcpy (&u, *ptrp, sz);
123 (*ptrp) += sz;
124
125 if (retp == NULL)
126 return true;
127
128 if (MY_ELFDATA != ei_data)
129 {
130 if (sz == 4)
131 CONVERT (u.u32);
132 else
133 CONVERT (u.u64);
134 }
135 if (sz == 4)
136 *retp = u.u32;
137 else
138 *retp = u.u64;
139 return true;
140 }
141
142 /* Try to find matching entry for module from address MODULE_START to
143 MODULE_END in NT_FILE note located at NOTE_FILE of NOTE_FILE_SIZE
144 bytes in format EI_CLASS and EI_DATA. */
145
146 static const char *
handle_file_note(GElf_Addr module_start, GElf_Addr module_end, unsigned char ei_class, unsigned char ei_data, const void *note_file, size_t note_file_size)147 handle_file_note (GElf_Addr module_start, GElf_Addr module_end,
148 unsigned char ei_class, unsigned char ei_data,
149 const void *note_file, size_t note_file_size)
150 {
151 if (note_file == NULL)
152 return NULL;
153
154 size_t sz;
155 switch (ei_class)
156 {
157 case ELFCLASS32:
158 sz = 4;
159 break;
160 case ELFCLASS64:
161 sz = 8;
162 break;
163 default:
164 return NULL;
165 }
166
167 const void *ptr = note_file;
168 const void *end = note_file + note_file_size;
169 uint64_t count;
170 if (! buf_read_ulong (ei_data, sz, &ptr, end, &count))
171 return NULL;
172 if (! buf_read_ulong (ei_data, sz, &ptr, end, NULL)) // page_size
173 return NULL;
174
175 uint64_t maxcount = (size_t) (end - ptr) / (3 * sz);
176 if (count > maxcount)
177 return NULL;
178
179 /* Where file names are stored. */
180 const char *fptr = ptr + 3 * count * sz;
181
182 ssize_t firstix = -1;
183 ssize_t lastix = -1;
184 for (size_t mix = 0; mix < count; mix++)
185 {
186 uint64_t mstart, mend, moffset;
187 if (! buf_read_ulong (ei_data, sz, &ptr, fptr, &mstart)
188 || ! buf_read_ulong (ei_data, sz, &ptr, fptr, &mend)
189 || ! buf_read_ulong (ei_data, sz, &ptr, fptr, &moffset))
190 return NULL;
191 if (mstart == module_start && moffset == 0)
192 firstix = lastix = mix;
193 if (firstix != -1 && mstart < module_end)
194 lastix = mix;
195 if (mend >= module_end)
196 break;
197 }
198 if (firstix == -1)
199 return NULL;
200
201 const char *retval = NULL;
202 for (ssize_t mix = 0; mix <= lastix; mix++)
203 {
204 const char *fnext = memchr (fptr, 0, (const char *) end - fptr);
205 if (fnext == NULL)
206 return NULL;
207 if (mix == firstix)
208 retval = fptr;
209 if (firstix < mix && mix <= lastix && strcmp (fptr, retval) != 0)
210 return NULL;
211 fptr = fnext + 1;
212 }
213 return retval;
214 }
215
216 /* Return true iff we are certain ELF cannot match BUILD_ID of
217 BUILD_ID_LEN bytes. Pass DISK_FILE_HAS_BUILD_ID as false if it is
218 certain ELF does not contain build-id (it is only a performance hit
219 to pass it always as true). */
220
221 static bool
invalid_elf(Elf *elf, bool disk_file_has_build_id, struct elf_build_id *build_id)222 invalid_elf (Elf *elf, bool disk_file_has_build_id,
223 struct elf_build_id *build_id)
224 {
225 if (! disk_file_has_build_id && build_id->len > 0)
226 {
227 /* Module found in segments with build-id is more reliable
228 than a module found via DT_DEBUG on disk without any
229 build-id. */
230 return true;
231 }
232 if (disk_file_has_build_id && build_id->len > 0)
233 {
234 const void *elf_build_id;
235 ssize_t elf_build_id_len;
236
237 /* If there is a build id in the elf file, check it. */
238 elf_build_id_len = INTUSE(dwelf_elf_gnu_build_id) (elf, &elf_build_id);
239 if (elf_build_id_len > 0)
240 {
241 if (build_id->len != (size_t) elf_build_id_len
242 || memcmp (build_id->memory, elf_build_id, build_id->len) != 0)
243 return true;
244 }
245 }
246 return false;
247 }
248
249 static void
finish_portion(struct read_state *read_state, void **data, size_t *data_size)250 finish_portion (struct read_state *read_state,
251 void **data, size_t *data_size)
252 {
253 if (*data_size != 0 && *data != NULL)
254 (*read_state->memory_callback) (read_state->dwfl, -1, data, data_size,
255 0, 0, read_state->memory_callback_arg);
256 }
257
258 static inline bool
read_portion(struct read_state *read_state, void **data, size_t *data_size, GElf_Addr start, size_t segment, GElf_Addr vaddr, size_t filesz)259 read_portion (struct read_state *read_state,
260 void **data, size_t *data_size,
261 GElf_Addr start, size_t segment,
262 GElf_Addr vaddr, size_t filesz)
263 {
264 /* Check whether we will have to read the segment data, or if it
265 can be returned from the existing buffer. */
266 if (filesz > *read_state->buffer_available
267 || vaddr - start > *read_state->buffer_available - filesz
268 /* If we're in string mode, then don't consider the buffer we have
269 sufficient unless it contains the terminator of the string. */
270 || (filesz == 0 && memchr (vaddr - start + *read_state->buffer, '\0',
271 (*read_state->buffer_available
272 - (vaddr - start))) == NULL))
273 {
274 *data = NULL;
275 *data_size = filesz;
276 return !(*read_state->memory_callback) (read_state->dwfl,
277 addr_segndx (read_state->dwfl,
278 segment, vaddr,
279 false),
280 data, data_size, vaddr, filesz,
281 read_state->memory_callback_arg);
282 }
283
284 /* We already have this whole note segment from our initial read. */
285 *data = vaddr - start + (*read_state->buffer);
286 *data_size = 0;
287 return false;
288 }
289
290 int
dwfl_segment_report_module(Dwfl *dwfl, int ndx, const char *name, Dwfl_Memory_Callback *memory_callback, void *memory_callback_arg, Dwfl_Module_Callback *read_eagerly, void *read_eagerly_arg, size_t maxread, const void *note_file, size_t note_file_size, const struct r_debug_info *r_debug_info)291 dwfl_segment_report_module (Dwfl *dwfl, int ndx, const char *name,
292 Dwfl_Memory_Callback *memory_callback,
293 void *memory_callback_arg,
294 Dwfl_Module_Callback *read_eagerly,
295 void *read_eagerly_arg,
296 size_t maxread,
297 const void *note_file, size_t note_file_size,
298 const struct r_debug_info *r_debug_info)
299 {
300 size_t segment = ndx;
301 struct read_state read_state;
302
303 if (segment >= dwfl->lookup_elts)
304 segment = dwfl->lookup_elts - 1;
305
306 while (segment > 0
307 && (dwfl->lookup_segndx[segment] > ndx
308 || dwfl->lookup_segndx[segment] == -1))
309 --segment;
310
311 while (dwfl->lookup_segndx[segment] < ndx)
312 if (++segment == dwfl->lookup_elts)
313 return 0;
314
315 GElf_Addr start = dwfl->lookup_addr[segment];
316
317 /* First read in the file header and check its sanity. */
318
319 void *buffer = NULL;
320 size_t buffer_available = INITIAL_READ;
321 Elf *elf = NULL;
322 int fd = -1;
323
324 read_state.dwfl = dwfl;
325 read_state.memory_callback = memory_callback;
326 read_state.memory_callback_arg = memory_callback_arg;
327 read_state.buffer = &buffer;
328 read_state.buffer_available = &buffer_available;
329
330 /* We might have to reserve some memory for the phdrs. Set to NULL
331 here so we can always safely free it. */
332 void *phdrsp = NULL;
333
334 /* Collect the build ID bits here. */
335 struct elf_build_id build_id;
336 build_id.memory = NULL;
337 build_id.len = 0;
338 build_id.vaddr = 0;
339
340 if (! (*memory_callback) (dwfl, ndx, &buffer, &buffer_available,
341 start, sizeof (Elf64_Ehdr), memory_callback_arg)
342 || memcmp (buffer, ELFMAG, SELFMAG) != 0)
343 goto out;
344
345 /* Extract the information we need from the file header. */
346 const unsigned char *e_ident;
347 unsigned char ei_class;
348 unsigned char ei_data;
349 uint16_t e_type;
350 union
351 {
352 Elf32_Ehdr e32;
353 Elf64_Ehdr e64;
354 } ehdr;
355 GElf_Off phoff;
356 uint_fast16_t phnum;
357 uint_fast16_t phentsize;
358 GElf_Off shdrs_end;
359 Elf_Data xlatefrom =
360 {
361 .d_type = ELF_T_EHDR,
362 .d_buf = (void *) buffer,
363 .d_version = EV_CURRENT,
364 };
365 Elf_Data xlateto =
366 {
367 .d_type = ELF_T_EHDR,
368 .d_buf = &ehdr,
369 .d_size = sizeof ehdr,
370 .d_version = EV_CURRENT,
371 };
372 e_ident = ((const unsigned char *) buffer);
373 ei_class = e_ident[EI_CLASS];
374 ei_data = e_ident[EI_DATA];
375 /* buffer may be unaligned, in which case xlatetom would not work.
376 xlatetom does work when the in and out d_buf are equal (but not
377 for any other overlap). */
378 size_t ehdr_align = (ei_class == ELFCLASS32
379 ? __alignof__ (Elf32_Ehdr)
380 : __alignof__ (Elf64_Ehdr));
381 if (((uintptr_t) buffer & (ehdr_align - 1)) != 0)
382 {
383 memcpy (&ehdr, buffer,
384 (ei_class == ELFCLASS32
385 ? sizeof (Elf32_Ehdr)
386 : sizeof (Elf64_Ehdr)));
387 xlatefrom.d_buf = &ehdr;
388 }
389 switch (ei_class)
390 {
391 case ELFCLASS32:
392 xlatefrom.d_size = sizeof (Elf32_Ehdr);
393 if (elf32_xlatetom (&xlateto, &xlatefrom, ei_data) == NULL)
394 goto out;
395 e_type = ehdr.e32.e_type;
396 phoff = ehdr.e32.e_phoff;
397 phnum = ehdr.e32.e_phnum;
398 phentsize = ehdr.e32.e_phentsize;
399 if (phentsize != sizeof (Elf32_Phdr))
400 goto out;
401 /* NOTE if the number of sections is > 0xff00 then e_shnum
402 is zero and the actual number would come from the section
403 zero sh_size field. We ignore this here because getting shdrs
404 is just a nice bonus (see below in the type == PT_LOAD case
405 where we trim the last segment). */
406 shdrs_end = ehdr.e32.e_shoff + ehdr.e32.e_shnum * sizeof (Elf32_Shdr);
407 break;
408
409 case ELFCLASS64:
410 xlatefrom.d_size = sizeof (Elf64_Ehdr);
411 if (elf64_xlatetom (&xlateto, &xlatefrom, ei_data) == NULL)
412 goto out;
413 e_type = ehdr.e64.e_type;
414 phoff = ehdr.e64.e_phoff;
415 phnum = ehdr.e64.e_phnum;
416 phentsize = ehdr.e64.e_phentsize;
417 if (phentsize != sizeof (Elf64_Phdr))
418 goto out;
419 /* See the NOTE above for shdrs_end and ehdr.e32.e_shnum. */
420 shdrs_end = ehdr.e64.e_shoff + ehdr.e64.e_shnum * sizeof (Elf64_Shdr);
421 break;
422
423 default:
424 goto out;
425 }
426
427 /* The file header tells where to find the program headers.
428 These are what we need to find the boundaries of the module.
429 Without them, we don't have a module to report. */
430
431 if (phnum == 0)
432 goto out;
433
434 xlatefrom.d_type = xlateto.d_type = ELF_T_PHDR;
435 xlatefrom.d_size = phnum * phentsize;
436
437 void *ph_buffer = NULL;
438 size_t ph_buffer_size = 0;
439 if (read_portion (&read_state, &ph_buffer, &ph_buffer_size,
440 start, segment,
441 start + phoff, xlatefrom.d_size))
442 goto out;
443
444 /* ph_buffer_size will be zero if we got everything from the initial
445 buffer, otherwise it will be the size of the new buffer that
446 could be read. */
447 if (ph_buffer_size != 0)
448 {
449 phnum = ph_buffer_size / phentsize;
450 if (phnum == 0)
451 goto out;
452 xlatefrom.d_size = ph_buffer_size;
453 }
454
455 xlatefrom.d_buf = ph_buffer;
456
457 bool class32 = ei_class == ELFCLASS32;
458 size_t phdr_size = class32 ? sizeof (Elf32_Phdr) : sizeof (Elf64_Phdr);
459 if (unlikely (phnum > SIZE_MAX / phdr_size))
460 goto out;
461 const size_t phdrsp_bytes = phnum * phdr_size;
462 phdrsp = malloc (phdrsp_bytes);
463 if (unlikely (phdrsp == NULL))
464 goto out;
465
466 xlateto.d_buf = phdrsp;
467 xlateto.d_size = phdrsp_bytes;
468
469 /* ph_ buffer may be unaligned, in which case xlatetom would not work.
470 xlatetom does work when the in and out d_buf are equal (but not
471 for any other overlap). */
472 size_t phdr_align = (class32
473 ? __alignof__ (Elf32_Phdr)
474 : __alignof__ (Elf64_Phdr));
475 if (((uintptr_t) ph_buffer & (phdr_align - 1)) != 0)
476 {
477 memcpy (phdrsp, ph_buffer, phdrsp_bytes);
478 xlatefrom.d_buf = phdrsp;
479 }
480
481 /* Track the bounds of the file visible in memory. */
482 GElf_Off file_trimmed_end = 0; /* Proper p_vaddr + p_filesz end. */
483 GElf_Off file_end = 0; /* Rounded up to effective page size. */
484 GElf_Off contiguous = 0; /* Visible as contiguous file from START. */
485 GElf_Off total_filesz = 0; /* Total size of data to read. */
486
487 /* Collect the bias between START and the containing PT_LOAD's p_vaddr. */
488 GElf_Addr bias = 0;
489 bool found_bias = false;
490
491 /* Collect the unbiased bounds of the module here. */
492 GElf_Addr module_start = -1l;
493 GElf_Addr module_end = 0;
494 GElf_Addr module_address_sync = 0;
495
496 /* If we see PT_DYNAMIC, record it here. */
497 GElf_Addr dyn_vaddr = 0;
498 GElf_Xword dyn_filesz = 0;
499
500 Elf32_Phdr *p32 = phdrsp;
501 Elf64_Phdr *p64 = phdrsp;
502 if ((ei_class == ELFCLASS32
503 && elf32_xlatetom (&xlateto, &xlatefrom, ei_data) == NULL)
504 || (ei_class == ELFCLASS64
505 && elf64_xlatetom (&xlateto, &xlatefrom, ei_data) == NULL))
506 {
507 found_bias = false; /* Trigger error check */
508 }
509 else
510 {
511 /* Consider each of the program headers we've read from the image. */
512 for (uint_fast16_t i = 0; i < phnum; ++i)
513 {
514 bool is32 = (ei_class == ELFCLASS32);
515 GElf_Word type = is32 ? p32[i].p_type : p64[i].p_type;
516 GElf_Addr vaddr = is32 ? p32[i].p_vaddr : p64[i].p_vaddr;
517 GElf_Xword memsz = is32 ? p32[i].p_memsz : p64[i].p_memsz;
518 GElf_Off offset = is32 ? p32[i].p_offset : p64[i].p_offset;
519 GElf_Xword filesz = is32 ? p32[i].p_filesz : p64[i].p_filesz;
520 GElf_Xword align = is32 ? p32[i].p_align : p64[i].p_align;
521
522 if (type == PT_DYNAMIC)
523 {
524 dyn_vaddr = vaddr;
525 dyn_filesz = filesz;
526 }
527 else if (type == PT_NOTE)
528 {
529 /* If we have already seen a build ID, we don't care any more. */
530 if (build_id.memory != NULL || filesz == 0)
531 continue; /* Next header */
532
533 /* We calculate from the p_offset of the note segment,
534 because we don't yet know the bias for its p_vaddr. */
535 const GElf_Addr note_vaddr = start + offset;
536 void *data;
537 size_t data_size;
538 if (read_portion (&read_state, &data, &data_size,
539 start, segment, note_vaddr, filesz))
540 continue; /* Next header */
541
542 /* data_size will be zero if we got everything from the initial
543 buffer, otherwise it will be the size of the new buffer that
544 could be read. */
545 if (data_size != 0)
546 filesz = data_size;
547
548 if (filesz > SIZE_MAX / sizeof (Elf32_Nhdr))
549 continue;
550
551 assert (sizeof (Elf32_Nhdr) == sizeof (Elf64_Nhdr));
552
553 void *notes;
554 if (ei_data == MY_ELFDATA
555 && (uintptr_t) data == (align == 8
556 ? NOTE_ALIGN8 ((uintptr_t) data)
557 : NOTE_ALIGN4 ((uintptr_t) data)))
558 notes = data;
559 else
560 {
561 const unsigned int xencoding = ehdr.e32.e_ident[EI_DATA];
562
563 if (filesz > SIZE_MAX / sizeof (Elf32_Nhdr))
564 continue;
565 notes = malloc (filesz);
566 if (unlikely (notes == NULL))
567 continue; /* Next header */
568 xlatefrom.d_type = xlateto.d_type = (align == 8
569 ? ELF_T_NHDR8
570 : ELF_T_NHDR);
571 xlatefrom.d_buf = (void *) data;
572 xlatefrom.d_size = filesz;
573 xlateto.d_buf = notes;
574 xlateto.d_size = filesz;
575
576 /* data may be unaligned, in which case xlatetom would not work.
577 xlatetom does work when the in and out d_buf are equal (but not
578 for any other overlap). */
579 if ((uintptr_t) data != (align == 8
580 ? NOTE_ALIGN8 ((uintptr_t) data)
581 : NOTE_ALIGN4 ((uintptr_t) data)))
582 {
583 memcpy (notes, data, filesz);
584 xlatefrom.d_buf = notes;
585 }
586
587 if (elf32_xlatetom (&xlateto, &xlatefrom, xencoding) == NULL)
588 {
589 free (notes);
590 finish_portion (&read_state, &data, &data_size);
591 continue;
592 }
593 }
594
595 const GElf_Nhdr *nh = notes;
596 size_t len = 0;
597 while (filesz - len > sizeof (*nh))
598 {
599 len += sizeof (*nh);
600
601 size_t namesz = nh->n_namesz;
602 namesz = align == 8 ? NOTE_ALIGN8 (namesz) : NOTE_ALIGN4 (namesz);
603 if (namesz > filesz - len || len + namesz < namesz)
604 break;
605
606 void *note_name = notes + len;
607 len += namesz;
608
609 size_t descsz = nh->n_descsz;
610 descsz = align == 8 ? NOTE_ALIGN8 (descsz) : NOTE_ALIGN4 (descsz);
611 if (descsz > filesz - len || len + descsz < descsz)
612 break;
613
614 void *note_desc = notes + len;
615 len += descsz;
616
617 /* We don't handle very short or really large build-ids. We need at
618 at least 3 and allow for up to 64 (normally ids are 20 long). */
619 #define MIN_BUILD_ID_BYTES 3
620 #define MAX_BUILD_ID_BYTES 64
621 if (nh->n_type == NT_GNU_BUILD_ID
622 && nh->n_descsz >= MIN_BUILD_ID_BYTES
623 && nh->n_descsz <= MAX_BUILD_ID_BYTES
624 && nh->n_namesz == sizeof "GNU"
625 && !memcmp (note_name, "GNU", sizeof "GNU"))
626 {
627 build_id.vaddr = (note_desc
628 - (const void *) notes
629 + note_vaddr);
630 build_id.len = nh->n_descsz;
631 build_id.memory = malloc (build_id.len);
632 if (likely (build_id.memory != NULL))
633 memcpy (build_id.memory, note_desc, build_id.len);
634 break;
635 }
636
637 nh = (void *) notes + len;
638 }
639
640 if (notes != data)
641 free (notes);
642 finish_portion (&read_state, &data, &data_size);
643 }
644 else if (type == PT_LOAD)
645 {
646 align = (dwfl->segment_align > 1
647 ? dwfl->segment_align : (align ?: 1));
648
649 GElf_Addr vaddr_end = (vaddr + memsz + align - 1) & -align;
650 GElf_Addr filesz_vaddr = (filesz < memsz
651 ? vaddr + filesz : vaddr_end);
652 GElf_Off filesz_offset = filesz_vaddr - vaddr + offset;
653
654 if (file_trimmed_end < offset + filesz)
655 {
656 file_trimmed_end = offset + filesz;
657
658 /* Trim the last segment so we don't bother with zeros
659 in the last page that are off the end of the file.
660 However, if the extra bit in that page includes the
661 section headers, keep them. */
662 if (shdrs_end <= filesz_offset
663 && shdrs_end > file_trimmed_end)
664 {
665 filesz += shdrs_end - file_trimmed_end;
666 file_trimmed_end = shdrs_end;
667 }
668 }
669
670 total_filesz += filesz;
671
672 if (file_end < filesz_offset)
673 {
674 file_end = filesz_offset;
675 if (filesz_vaddr - start == filesz_offset)
676 contiguous = file_end;
677 }
678
679 if (!found_bias && (offset & -align) == 0
680 && likely (filesz_offset >= phoff + phnum * phentsize))
681 {
682 bias = start - vaddr;
683 found_bias = true;
684 }
685
686 if ((vaddr & -align) < module_start)
687 {
688 module_start = vaddr & -align;
689 module_address_sync = vaddr + memsz;
690 }
691
692 if (module_end < vaddr_end)
693 module_end = vaddr_end;
694 }
695 }
696 }
697
698 finish_portion (&read_state, &ph_buffer, &ph_buffer_size);
699
700 /* We must have seen the segment covering offset 0, or else the ELF
701 header we read at START was not produced by these program headers. */
702 if (unlikely (!found_bias))
703 goto out;
704
705 /* Now we know enough to report a module for sure: its bounds. */
706 module_start += bias;
707 module_end += bias;
708
709 dyn_vaddr += bias;
710
711 /* NAME found from link map has precedence over DT_SONAME possibly read
712 below. */
713 bool name_is_final = false;
714
715 /* Try to match up DYN_VADDR against L_LD as found in link map.
716 Segments sniffing may guess invalid address as the first read-only memory
717 mapping may not be dumped to the core file (if ELF headers are not dumped)
718 and the ELF header is dumped first with the read/write mapping of the same
719 file at higher addresses. */
720 if (r_debug_info != NULL)
721 for (const struct r_debug_info_module *module = r_debug_info->module;
722 module != NULL; module = module->next)
723 if (module_start <= module->l_ld && module->l_ld < module_end)
724 {
725 /* L_LD read from link map must be right while DYN_VADDR is unsafe.
726 Therefore subtract DYN_VADDR and add L_LD to get a possibly
727 corrective displacement for all addresses computed so far. */
728 GElf_Addr fixup = module->l_ld - dyn_vaddr;
729 if ((fixup & (dwfl->segment_align - 1)) == 0
730 && module_start + fixup <= module->l_ld
731 && module->l_ld < module_end + fixup)
732 {
733 module_start += fixup;
734 module_end += fixup;
735 dyn_vaddr += fixup;
736 bias += fixup;
737 if (module->name[0] != '\0')
738 {
739 name = basename (module->name);
740 name_is_final = true;
741 }
742 break;
743 }
744 }
745
746 if (r_debug_info != NULL)
747 {
748 bool skip_this_module = false;
749 for (struct r_debug_info_module *module = r_debug_info->module;
750 module != NULL; module = module->next)
751 if ((module_end > module->start && module_start < module->end)
752 || dyn_vaddr == module->l_ld)
753 {
754 if (module->elf != NULL
755 && invalid_elf (module->elf, module->disk_file_has_build_id,
756 &build_id))
757 {
758 elf_end (module->elf);
759 close (module->fd);
760 module->elf = NULL;
761 module->fd = -1;
762 }
763 if (module->elf != NULL)
764 {
765 /* Ignore this found module if it would conflict in address
766 space with any already existing module of DWFL. */
767 skip_this_module = true;
768 }
769 }
770 if (skip_this_module)
771 goto out;
772 }
773
774 const char *file_note_name = handle_file_note (module_start, module_end,
775 ei_class, ei_data,
776 note_file, note_file_size);
777 if (file_note_name)
778 {
779 name = file_note_name;
780 name_is_final = true;
781 bool invalid = false;
782 fd = open (name, O_RDONLY);
783 if (fd >= 0)
784 {
785 Dwfl_Error error = __libdw_open_file (&fd, &elf, true, false);
786 if (error == DWFL_E_NOERROR)
787 invalid = invalid_elf (elf, true /* disk_file_has_build_id */,
788 &build_id);
789 }
790 if (invalid)
791 {
792 /* The file was there, but the build_id didn't match. We
793 still want to report the module, but need to get the ELF
794 some other way if possible. */
795 close (fd);
796 fd = -1;
797 elf_end (elf);
798 elf = NULL;
799 }
800 }
801
802 /* Our return value now says to skip the segments contained
803 within the module. */
804 ndx = addr_segndx (dwfl, segment, module_end, true);
805
806 /* Examine its .dynamic section to get more interesting details.
807 If it has DT_SONAME, we'll use that as the module name.
808 If it has a DT_DEBUG, then it's actually a PIE rather than a DSO.
809 We need its DT_STRTAB and DT_STRSZ to decipher DT_SONAME,
810 and they also tell us the essential portion of the file
811 for fetching symbols. */
812 GElf_Addr soname_stroff = 0;
813 GElf_Addr dynstr_vaddr = 0;
814 GElf_Xword dynstrsz = 0;
815 bool execlike = false;
816 const size_t dyn_entsize = (ei_class == ELFCLASS32
817 ? sizeof (Elf32_Dyn) : sizeof (Elf64_Dyn));
818 void *dyn_data = NULL;
819 size_t dyn_data_size = 0;
820 if (dyn_filesz != 0 && dyn_filesz % dyn_entsize == 0
821 && ! read_portion (&read_state, &dyn_data, &dyn_data_size,
822 start, segment, dyn_vaddr, dyn_filesz))
823 {
824 /* dyn_data_size will be zero if we got everything from the initial
825 buffer, otherwise it will be the size of the new buffer that
826 could be read. */
827 if (dyn_data_size != 0)
828 dyn_filesz = dyn_data_size;
829
830 if ((dyn_filesz / dyn_entsize) == 0
831 || dyn_filesz > (SIZE_MAX / dyn_entsize))
832 goto out;
833 void *dyns = malloc (dyn_filesz);
834 Elf32_Dyn *d32 = dyns;
835 Elf64_Dyn *d64 = dyns;
836 if (unlikely (dyns == NULL))
837 goto out;
838
839 xlatefrom.d_type = xlateto.d_type = ELF_T_DYN;
840 xlatefrom.d_buf = (void *) dyn_data;
841 xlatefrom.d_size = dyn_filesz;
842 xlateto.d_buf = dyns;
843 xlateto.d_size = dyn_filesz;
844
845 /* dyn_data may be unaligned, in which case xlatetom would not work.
846 xlatetom does work when the in and out d_buf are equal (but not
847 for any other overlap). */
848 bool is32 = (ei_class == ELFCLASS32);
849 size_t dyn_align = (is32
850 ? __alignof__ (Elf32_Dyn)
851 : __alignof__ (Elf64_Dyn));
852 if (((uintptr_t) dyn_data & (dyn_align - 1)) != 0)
853 {
854 memcpy (dyns, dyn_data, dyn_filesz);
855 xlatefrom.d_buf = dyns;
856 }
857
858 if ((is32 && elf32_xlatetom (&xlateto, &xlatefrom, ei_data) != NULL)
859 || (!is32 && elf64_xlatetom (&xlateto, &xlatefrom, ei_data) != NULL))
860 {
861 size_t n = (is32
862 ? (dyn_filesz / sizeof (Elf32_Dyn))
863 : (dyn_filesz / sizeof (Elf64_Dyn)));
864 for (size_t i = 0; i < n; ++i)
865 {
866 GElf_Sxword tag = is32 ? d32[i].d_tag : d64[i].d_tag;
867 GElf_Xword val = is32 ? d32[i].d_un.d_val : d64[i].d_un.d_val;
868
869 if (tag == DT_DEBUG)
870 execlike = true;
871 else if (tag == DT_SONAME)
872 soname_stroff = val;
873 else if (tag == DT_STRTAB)
874 dynstr_vaddr = val;
875 else if (tag == DT_STRSZ)
876 dynstrsz = val;
877 else
878 continue;
879
880 if (soname_stroff != 0 && dynstr_vaddr != 0 && dynstrsz != 0)
881 break;
882 }
883 }
884 free (dyns);
885 }
886 finish_portion (&read_state, &dyn_data, &dyn_data_size);
887
888 /* We'll use the name passed in or a stupid default if not DT_SONAME. */
889 if (name == NULL)
890 name = e_type == ET_EXEC ? "[exe]" : execlike ? "[pie]" : "[dso]";
891
892 void *soname = NULL;
893 size_t soname_size = 0;
894 if (! name_is_final && dynstrsz != 0 && dynstr_vaddr != 0)
895 {
896 /* We know the bounds of the .dynstr section.
897
898 The DYNSTR_VADDR pointer comes from the .dynamic section
899 (DT_STRTAB, detected above). Ordinarily the dynamic linker
900 will have adjusted this pointer in place so it's now an
901 absolute address. But sometimes .dynamic is read-only (in
902 vDSOs and odd architectures), and sometimes the adjustment
903 just hasn't happened yet in the memory image we looked at.
904 So treat DYNSTR_VADDR as an absolute address if it falls
905 within the module bounds, or try applying the phdr bias
906 when that adjusts it to fall within the module bounds. */
907
908 if ((dynstr_vaddr < module_start || dynstr_vaddr >= module_end)
909 && dynstr_vaddr + bias >= module_start
910 && dynstr_vaddr + bias < module_end)
911 dynstr_vaddr += bias;
912
913 if (unlikely (dynstr_vaddr + dynstrsz > module_end))
914 dynstrsz = 0;
915
916 /* Try to get the DT_SONAME string. */
917 if (soname_stroff != 0 && soname_stroff + 1 < dynstrsz
918 && ! read_portion (&read_state, &soname, &soname_size,
919 start, segment,
920 dynstr_vaddr + soname_stroff, 0))
921 name = soname;
922 }
923
924 /* Now that we have chosen the module's name and bounds, report it.
925 If we found a build ID, report that too. */
926
927 Dwfl_Module *mod = INTUSE(dwfl_report_module) (dwfl, name,
928 module_start, module_end);
929
930 // !execlike && ET_EXEC is PIE.
931 // execlike && !ET_EXEC is a static executable.
932 if (mod != NULL && (execlike || ehdr.e32.e_type == ET_EXEC))
933 mod->is_executable = true;
934
935 if (likely (mod != NULL) && build_id.memory != NULL
936 && unlikely (INTUSE(dwfl_module_report_build_id) (mod,
937 build_id.memory,
938 build_id.len,
939 build_id.vaddr)))
940 {
941 mod->gc = true;
942 mod = NULL;
943 }
944
945 /* At this point we do not need BUILD_ID or NAME any more.
946 They have been copied. */
947 free (build_id.memory);
948 build_id.memory = NULL;
949 finish_portion (&read_state, &soname, &soname_size);
950
951 if (unlikely (mod == NULL))
952 {
953 ndx = -1;
954 goto out;
955 }
956
957 /* We have reported the module. Now let the caller decide whether we
958 should read the whole thing in right now. */
959
960 const GElf_Off cost = (contiguous < file_trimmed_end ? total_filesz
961 : buffer_available >= contiguous ? 0
962 : contiguous - buffer_available);
963 const GElf_Off worthwhile = ((dynstr_vaddr == 0 || dynstrsz == 0) ? 0
964 : dynstr_vaddr + dynstrsz - start);
965 const GElf_Off whole = MAX (file_trimmed_end, shdrs_end);
966
967 if (elf == NULL
968 && (*read_eagerly) (MODCB_ARGS (mod), &buffer, &buffer_available,
969 cost, worthwhile, whole, contiguous,
970 read_eagerly_arg, &elf)
971 && elf == NULL)
972 {
973 /* The caller wants to read the whole file in right now, but hasn't
974 done it for us. Fill in a local image of the virtual file. */
975
976 if (file_trimmed_end > maxread)
977 file_trimmed_end = maxread;
978
979 void *contents = calloc (1, file_trimmed_end);
980 if (unlikely (contents == NULL))
981 goto out;
982
983 if (contiguous < file_trimmed_end)
984 {
985 /* We can't use the memory image verbatim as the file image.
986 So we'll be reading into a local image of the virtual file. */
987 for (uint_fast16_t i = 0; i < phnum; ++i)
988 {
989 bool is32 = (ei_class == ELFCLASS32);
990 GElf_Word type = is32 ? p32[i].p_type : p64[i].p_type;
991
992 if (type != PT_LOAD)
993 continue;
994
995 GElf_Addr vaddr = is32 ? p32[i].p_vaddr : p64[i].p_vaddr;
996 GElf_Off offset = is32 ? p32[i].p_offset : p64[i].p_offset;
997 GElf_Xword filesz = is32 ? p32[i].p_filesz : p64[i].p_filesz;
998
999 /* Don't try to read beyond the actual end of file. */
1000 if (offset >= file_trimmed_end)
1001 continue;
1002
1003 void *into = contents + offset;
1004 size_t read_size = MIN (filesz, file_trimmed_end - offset);
1005 (*memory_callback) (dwfl, addr_segndx (dwfl, segment,
1006 vaddr + bias, false),
1007 &into, &read_size, vaddr + bias, read_size,
1008 memory_callback_arg);
1009 }
1010 }
1011 else
1012 {
1013 /* The whole file sits contiguous in memory,
1014 but the caller didn't want to just do it. */
1015
1016 const size_t have = MIN (buffer_available, file_trimmed_end);
1017 memcpy (contents, buffer, have);
1018
1019 if (have < file_trimmed_end)
1020 {
1021 void *into = contents + have;
1022 size_t read_size = file_trimmed_end - have;
1023 (*memory_callback) (dwfl,
1024 addr_segndx (dwfl, segment,
1025 start + have, false),
1026 &into, &read_size, start + have,
1027 read_size, memory_callback_arg);
1028 }
1029 }
1030
1031 elf = elf_memory (contents, file_trimmed_end);
1032 if (unlikely (elf == NULL))
1033 free (contents);
1034 else
1035 elf->flags |= ELF_F_MALLOCED;
1036 }
1037
1038 if (elf != NULL && mod->main.elf == NULL)
1039 {
1040 /* Install the file in the module. */
1041 mod->main.elf = elf;
1042 mod->main.fd = fd;
1043 elf = NULL;
1044 fd = -1;
1045 mod->main.vaddr = module_start - bias;
1046 mod->main.address_sync = module_address_sync;
1047 mod->main_bias = bias;
1048 }
1049
1050 out:
1051 if (build_id.memory != NULL)
1052 free (build_id.memory);
1053 free (phdrsp);
1054 if (buffer != NULL)
1055 (*memory_callback) (dwfl, -1, &buffer, &buffer_available, 0, 0,
1056 memory_callback_arg);
1057
1058 if (elf != NULL)
1059 elf_end (elf);
1060 if (fd != -1)
1061 close (fd);
1062 return ndx;
1063 }
1064