Make ARMv8-M attribute cmse_nonsecure_call work in Ada
[official-gcc.git] / libbacktrace / elf.c
blob181d195fe355fd31bc610d572c66952dfadaecc1
1 /* elf.c -- Get debug data from an ELF file for backtraces.
2 Copyright (C) 2012-2022 Free Software Foundation, Inc.
3 Written by Ian Lance Taylor, Google.
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions are
7 met:
9 (1) Redistributions of source code must retain the above copyright
10 notice, this list of conditions and the following disclaimer.
12 (2) Redistributions in binary form must reproduce the above copyright
13 notice, this list of conditions and the following disclaimer in
14 the documentation and/or other materials provided with the
15 distribution.
17 (3) The name of the author may not be used to
18 endorse or promote products derived from this software without
19 specific prior written permission.
21 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
22 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
24 DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
25 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29 STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
30 IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 POSSIBILITY OF SUCH DAMAGE. */
33 #include "config.h"
35 #include <errno.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <unistd.h>
42 #ifdef HAVE_DL_ITERATE_PHDR
43 #ifdef HAVE_LINK_H
44 #include <link.h>
45 #endif
46 #ifdef HAVE_SYS_LINK_H
47 #include <sys/link.h>
48 #endif
49 #endif
51 #include "backtrace.h"
52 #include "internal.h"
54 #ifndef S_ISLNK
55 #ifndef S_IFLNK
56 #define S_IFLNK 0120000
57 #endif
58 #ifndef S_IFMT
59 #define S_IFMT 0170000
60 #endif
61 #define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
62 #endif
64 #ifndef __GNUC__
65 #define __builtin_prefetch(p, r, l)
66 #define unlikely(x) (x)
67 #else
68 #define unlikely(x) __builtin_expect(!!(x), 0)
69 #endif
71 #if !defined(HAVE_DECL_STRNLEN) || !HAVE_DECL_STRNLEN
73 /* If strnlen is not declared, provide our own version. */
75 static size_t
76 xstrnlen (const char *s, size_t maxlen)
78 size_t i;
80 for (i = 0; i < maxlen; ++i)
81 if (s[i] == '\0')
82 break;
83 return i;
86 #define strnlen xstrnlen
88 #endif
90 #ifndef HAVE_LSTAT
92 /* Dummy version of lstat for systems that don't have it. */
94 static int
95 xlstat (const char *path ATTRIBUTE_UNUSED, struct stat *st ATTRIBUTE_UNUSED)
97 return -1;
100 #define lstat xlstat
102 #endif
104 #ifndef HAVE_READLINK
106 /* Dummy version of readlink for systems that don't have it. */
108 static ssize_t
109 xreadlink (const char *path ATTRIBUTE_UNUSED, char *buf ATTRIBUTE_UNUSED,
110 size_t bufsz ATTRIBUTE_UNUSED)
112 return -1;
115 #define readlink xreadlink
117 #endif
119 #ifndef HAVE_DL_ITERATE_PHDR
121 /* Dummy version of dl_iterate_phdr for systems that don't have it. */
123 #define dl_phdr_info x_dl_phdr_info
124 #define dl_iterate_phdr x_dl_iterate_phdr
126 struct dl_phdr_info
128 uintptr_t dlpi_addr;
129 const char *dlpi_name;
132 static int
133 dl_iterate_phdr (int (*callback) (struct dl_phdr_info *,
134 size_t, void *) ATTRIBUTE_UNUSED,
135 void *data ATTRIBUTE_UNUSED)
137 return 0;
140 #endif /* ! defined (HAVE_DL_ITERATE_PHDR) */
142 /* The configure script must tell us whether we are 32-bit or 64-bit
143 ELF. We could make this code test and support either possibility,
144 but there is no point. This code only works for the currently
145 running executable, which means that we know the ELF mode at
146 configure time. */
148 #if BACKTRACE_ELF_SIZE != 32 && BACKTRACE_ELF_SIZE != 64
149 #error "Unknown BACKTRACE_ELF_SIZE"
150 #endif
152 /* <link.h> might #include <elf.h> which might define our constants
153 with slightly different values. Undefine them to be safe. */
155 #undef EI_NIDENT
156 #undef EI_MAG0
157 #undef EI_MAG1
158 #undef EI_MAG2
159 #undef EI_MAG3
160 #undef EI_CLASS
161 #undef EI_DATA
162 #undef EI_VERSION
163 #undef ELF_MAG0
164 #undef ELF_MAG1
165 #undef ELF_MAG2
166 #undef ELF_MAG3
167 #undef ELFCLASS32
168 #undef ELFCLASS64
169 #undef ELFDATA2LSB
170 #undef ELFDATA2MSB
171 #undef EV_CURRENT
172 #undef ET_DYN
173 #undef EM_PPC64
174 #undef EF_PPC64_ABI
175 #undef SHN_LORESERVE
176 #undef SHN_XINDEX
177 #undef SHN_UNDEF
178 #undef SHT_PROGBITS
179 #undef SHT_SYMTAB
180 #undef SHT_STRTAB
181 #undef SHT_DYNSYM
182 #undef SHF_COMPRESSED
183 #undef STT_OBJECT
184 #undef STT_FUNC
185 #undef NT_GNU_BUILD_ID
186 #undef ELFCOMPRESS_ZLIB
188 /* Basic types. */
190 typedef uint16_t b_elf_half; /* Elf_Half. */
191 typedef uint32_t b_elf_word; /* Elf_Word. */
192 typedef int32_t b_elf_sword; /* Elf_Sword. */
194 #if BACKTRACE_ELF_SIZE == 32
196 typedef uint32_t b_elf_addr; /* Elf_Addr. */
197 typedef uint32_t b_elf_off; /* Elf_Off. */
199 typedef uint32_t b_elf_wxword; /* 32-bit Elf_Word, 64-bit ELF_Xword. */
201 #else
203 typedef uint64_t b_elf_addr; /* Elf_Addr. */
204 typedef uint64_t b_elf_off; /* Elf_Off. */
205 typedef uint64_t b_elf_xword; /* Elf_Xword. */
206 typedef int64_t b_elf_sxword; /* Elf_Sxword. */
208 typedef uint64_t b_elf_wxword; /* 32-bit Elf_Word, 64-bit ELF_Xword. */
210 #endif
212 /* Data structures and associated constants. */
214 #define EI_NIDENT 16
216 typedef struct {
217 unsigned char e_ident[EI_NIDENT]; /* ELF "magic number" */
218 b_elf_half e_type; /* Identifies object file type */
219 b_elf_half e_machine; /* Specifies required architecture */
220 b_elf_word e_version; /* Identifies object file version */
221 b_elf_addr e_entry; /* Entry point virtual address */
222 b_elf_off e_phoff; /* Program header table file offset */
223 b_elf_off e_shoff; /* Section header table file offset */
224 b_elf_word e_flags; /* Processor-specific flags */
225 b_elf_half e_ehsize; /* ELF header size in bytes */
226 b_elf_half e_phentsize; /* Program header table entry size */
227 b_elf_half e_phnum; /* Program header table entry count */
228 b_elf_half e_shentsize; /* Section header table entry size */
229 b_elf_half e_shnum; /* Section header table entry count */
230 b_elf_half e_shstrndx; /* Section header string table index */
231 } b_elf_ehdr; /* Elf_Ehdr. */
233 #define EI_MAG0 0
234 #define EI_MAG1 1
235 #define EI_MAG2 2
236 #define EI_MAG3 3
237 #define EI_CLASS 4
238 #define EI_DATA 5
239 #define EI_VERSION 6
241 #define ELFMAG0 0x7f
242 #define ELFMAG1 'E'
243 #define ELFMAG2 'L'
244 #define ELFMAG3 'F'
246 #define ELFCLASS32 1
247 #define ELFCLASS64 2
249 #define ELFDATA2LSB 1
250 #define ELFDATA2MSB 2
252 #define EV_CURRENT 1
254 #define ET_DYN 3
256 #define EM_PPC64 21
257 #define EF_PPC64_ABI 3
259 typedef struct {
260 b_elf_word sh_name; /* Section name, index in string tbl */
261 b_elf_word sh_type; /* Type of section */
262 b_elf_wxword sh_flags; /* Miscellaneous section attributes */
263 b_elf_addr sh_addr; /* Section virtual addr at execution */
264 b_elf_off sh_offset; /* Section file offset */
265 b_elf_wxword sh_size; /* Size of section in bytes */
266 b_elf_word sh_link; /* Index of another section */
267 b_elf_word sh_info; /* Additional section information */
268 b_elf_wxword sh_addralign; /* Section alignment */
269 b_elf_wxword sh_entsize; /* Entry size if section holds table */
270 } b_elf_shdr; /* Elf_Shdr. */
272 #define SHN_UNDEF 0x0000 /* Undefined section */
273 #define SHN_LORESERVE 0xFF00 /* Begin range of reserved indices */
274 #define SHN_XINDEX 0xFFFF /* Section index is held elsewhere */
276 #define SHT_PROGBITS 1
277 #define SHT_SYMTAB 2
278 #define SHT_STRTAB 3
279 #define SHT_DYNSYM 11
281 #define SHF_COMPRESSED 0x800
283 #if BACKTRACE_ELF_SIZE == 32
285 typedef struct
287 b_elf_word st_name; /* Symbol name, index in string tbl */
288 b_elf_addr st_value; /* Symbol value */
289 b_elf_word st_size; /* Symbol size */
290 unsigned char st_info; /* Symbol binding and type */
291 unsigned char st_other; /* Visibility and other data */
292 b_elf_half st_shndx; /* Symbol section index */
293 } b_elf_sym; /* Elf_Sym. */
295 #else /* BACKTRACE_ELF_SIZE != 32 */
297 typedef struct
299 b_elf_word st_name; /* Symbol name, index in string tbl */
300 unsigned char st_info; /* Symbol binding and type */
301 unsigned char st_other; /* Visibility and other data */
302 b_elf_half st_shndx; /* Symbol section index */
303 b_elf_addr st_value; /* Symbol value */
304 b_elf_xword st_size; /* Symbol size */
305 } b_elf_sym; /* Elf_Sym. */
307 #endif /* BACKTRACE_ELF_SIZE != 32 */
309 #define STT_OBJECT 1
310 #define STT_FUNC 2
312 typedef struct
314 uint32_t namesz;
315 uint32_t descsz;
316 uint32_t type;
317 char name[1];
318 } b_elf_note;
320 #define NT_GNU_BUILD_ID 3
322 #if BACKTRACE_ELF_SIZE == 32
324 typedef struct
326 b_elf_word ch_type; /* Compresstion algorithm */
327 b_elf_word ch_size; /* Uncompressed size */
328 b_elf_word ch_addralign; /* Alignment for uncompressed data */
329 } b_elf_chdr; /* Elf_Chdr */
331 #else /* BACKTRACE_ELF_SIZE != 32 */
333 typedef struct
335 b_elf_word ch_type; /* Compression algorithm */
336 b_elf_word ch_reserved; /* Reserved */
337 b_elf_xword ch_size; /* Uncompressed size */
338 b_elf_xword ch_addralign; /* Alignment for uncompressed data */
339 } b_elf_chdr; /* Elf_Chdr */
341 #endif /* BACKTRACE_ELF_SIZE != 32 */
343 #define ELFCOMPRESS_ZLIB 1
345 /* Names of sections, indexed by enum dwarf_section in internal.h. */
347 static const char * const dwarf_section_names[DEBUG_MAX] =
349 ".debug_info",
350 ".debug_line",
351 ".debug_abbrev",
352 ".debug_ranges",
353 ".debug_str",
354 ".debug_addr",
355 ".debug_str_offsets",
356 ".debug_line_str",
357 ".debug_rnglists"
360 /* Information we gather for the sections we care about. */
362 struct debug_section_info
364 /* Section file offset. */
365 off_t offset;
366 /* Section size. */
367 size_t size;
368 /* Section contents, after read from file. */
369 const unsigned char *data;
370 /* Whether the SHF_COMPRESSED flag is set for the section. */
371 int compressed;
374 /* Information we keep for an ELF symbol. */
376 struct elf_symbol
378 /* The name of the symbol. */
379 const char *name;
380 /* The address of the symbol. */
381 uintptr_t address;
382 /* The size of the symbol. */
383 size_t size;
386 /* Information to pass to elf_syminfo. */
388 struct elf_syminfo_data
390 /* Symbols for the next module. */
391 struct elf_syminfo_data *next;
392 /* The ELF symbols, sorted by address. */
393 struct elf_symbol *symbols;
394 /* The number of symbols. */
395 size_t count;
398 /* A view that works for either a file or memory. */
400 struct elf_view
402 struct backtrace_view view;
403 int release; /* If non-zero, must call backtrace_release_view. */
406 /* Information about PowerPC64 ELFv1 .opd section. */
408 struct elf_ppc64_opd_data
410 /* Address of the .opd section. */
411 b_elf_addr addr;
412 /* Section data. */
413 const char *data;
414 /* Size of the .opd section. */
415 size_t size;
416 /* Corresponding section view. */
417 struct elf_view view;
420 /* Create a view of SIZE bytes from DESCRIPTOR/MEMORY at OFFSET. */
422 static int
423 elf_get_view (struct backtrace_state *state, int descriptor,
424 const unsigned char *memory, size_t memory_size, off_t offset,
425 uint64_t size, backtrace_error_callback error_callback,
426 void *data, struct elf_view *view)
428 if (memory == NULL)
430 view->release = 1;
431 return backtrace_get_view (state, descriptor, offset, size,
432 error_callback, data, &view->view);
434 else
436 if ((uint64_t) offset + size > (uint64_t) memory_size)
438 error_callback (data, "out of range for in-memory file", 0);
439 return 0;
441 view->view.data = (const void *) (memory + offset);
442 view->view.base = NULL;
443 view->view.len = size;
444 view->release = 0;
445 return 1;
449 /* Release a view read by elf_get_view. */
451 static void
452 elf_release_view (struct backtrace_state *state, struct elf_view *view,
453 backtrace_error_callback error_callback, void *data)
455 if (view->release)
456 backtrace_release_view (state, &view->view, error_callback, data);
459 /* Compute the CRC-32 of BUF/LEN. This uses the CRC used for
460 .gnu_debuglink files. */
462 static uint32_t
463 elf_crc32 (uint32_t crc, const unsigned char *buf, size_t len)
465 static const uint32_t crc32_table[256] =
467 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
468 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
469 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
470 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
471 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
472 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
473 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
474 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
475 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
476 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
477 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
478 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
479 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
480 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
481 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
482 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
483 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
484 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
485 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
486 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
487 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
488 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
489 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
490 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
491 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
492 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
493 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
494 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
495 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
496 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
497 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
498 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
499 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
500 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
501 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
502 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
503 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
504 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
505 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
506 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
507 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
508 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
509 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
510 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
511 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
512 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
513 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
514 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
515 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
516 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
517 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
518 0x2d02ef8d
520 const unsigned char *end;
522 crc = ~crc;
523 for (end = buf + len; buf < end; ++ buf)
524 crc = crc32_table[(crc ^ *buf) & 0xff] ^ (crc >> 8);
525 return ~crc;
528 /* Return the CRC-32 of the entire file open at DESCRIPTOR. */
530 static uint32_t
531 elf_crc32_file (struct backtrace_state *state, int descriptor,
532 backtrace_error_callback error_callback, void *data)
534 struct stat st;
535 struct backtrace_view file_view;
536 uint32_t ret;
538 if (fstat (descriptor, &st) < 0)
540 error_callback (data, "fstat", errno);
541 return 0;
544 if (!backtrace_get_view (state, descriptor, 0, st.st_size, error_callback,
545 data, &file_view))
546 return 0;
548 ret = elf_crc32 (0, (const unsigned char *) file_view.data, st.st_size);
550 backtrace_release_view (state, &file_view, error_callback, data);
552 return ret;
555 /* A dummy callback function used when we can't find a symbol
556 table. */
558 static void
559 elf_nosyms (struct backtrace_state *state ATTRIBUTE_UNUSED,
560 uintptr_t addr ATTRIBUTE_UNUSED,
561 backtrace_syminfo_callback callback ATTRIBUTE_UNUSED,
562 backtrace_error_callback error_callback, void *data)
564 error_callback (data, "no symbol table in ELF executable", -1);
567 /* A callback function used when we can't find any debug info. */
569 static int
570 elf_nodebug (struct backtrace_state *state, uintptr_t pc,
571 backtrace_full_callback callback,
572 backtrace_error_callback error_callback, void *data)
574 if (state->syminfo_fn != NULL && state->syminfo_fn != elf_nosyms)
576 struct backtrace_call_full bdata;
578 /* Fetch symbol information so that we can least get the
579 function name. */
581 bdata.full_callback = callback;
582 bdata.full_error_callback = error_callback;
583 bdata.full_data = data;
584 bdata.ret = 0;
585 state->syminfo_fn (state, pc, backtrace_syminfo_to_full_callback,
586 backtrace_syminfo_to_full_error_callback, &bdata);
587 return bdata.ret;
590 error_callback (data, "no debug info in ELF executable", -1);
591 return 0;
594 /* Compare struct elf_symbol for qsort. */
596 static int
597 elf_symbol_compare (const void *v1, const void *v2)
599 const struct elf_symbol *e1 = (const struct elf_symbol *) v1;
600 const struct elf_symbol *e2 = (const struct elf_symbol *) v2;
602 if (e1->address < e2->address)
603 return -1;
604 else if (e1->address > e2->address)
605 return 1;
606 else
607 return 0;
610 /* Compare an ADDR against an elf_symbol for bsearch. We allocate one
611 extra entry in the array so that this can look safely at the next
612 entry. */
614 static int
615 elf_symbol_search (const void *vkey, const void *ventry)
617 const uintptr_t *key = (const uintptr_t *) vkey;
618 const struct elf_symbol *entry = (const struct elf_symbol *) ventry;
619 uintptr_t addr;
621 addr = *key;
622 if (addr < entry->address)
623 return -1;
624 else if (addr >= entry->address + entry->size)
625 return 1;
626 else
627 return 0;
630 /* Initialize the symbol table info for elf_syminfo. */
632 static int
633 elf_initialize_syminfo (struct backtrace_state *state,
634 uintptr_t base_address,
635 const unsigned char *symtab_data, size_t symtab_size,
636 const unsigned char *strtab, size_t strtab_size,
637 backtrace_error_callback error_callback,
638 void *data, struct elf_syminfo_data *sdata,
639 struct elf_ppc64_opd_data *opd)
641 size_t sym_count;
642 const b_elf_sym *sym;
643 size_t elf_symbol_count;
644 size_t elf_symbol_size;
645 struct elf_symbol *elf_symbols;
646 size_t i;
647 unsigned int j;
649 sym_count = symtab_size / sizeof (b_elf_sym);
651 /* We only care about function symbols. Count them. */
652 sym = (const b_elf_sym *) symtab_data;
653 elf_symbol_count = 0;
654 for (i = 0; i < sym_count; ++i, ++sym)
656 int info;
658 info = sym->st_info & 0xf;
659 if ((info == STT_FUNC || info == STT_OBJECT)
660 && sym->st_shndx != SHN_UNDEF)
661 ++elf_symbol_count;
664 elf_symbol_size = elf_symbol_count * sizeof (struct elf_symbol);
665 elf_symbols = ((struct elf_symbol *)
666 backtrace_alloc (state, elf_symbol_size, error_callback,
667 data));
668 if (elf_symbols == NULL)
669 return 0;
671 sym = (const b_elf_sym *) symtab_data;
672 j = 0;
673 for (i = 0; i < sym_count; ++i, ++sym)
675 int info;
677 info = sym->st_info & 0xf;
678 if (info != STT_FUNC && info != STT_OBJECT)
679 continue;
680 if (sym->st_shndx == SHN_UNDEF)
681 continue;
682 if (sym->st_name >= strtab_size)
684 error_callback (data, "symbol string index out of range", 0);
685 backtrace_free (state, elf_symbols, elf_symbol_size, error_callback,
686 data);
687 return 0;
689 elf_symbols[j].name = (const char *) strtab + sym->st_name;
690 /* Special case PowerPC64 ELFv1 symbols in .opd section, if the symbol
691 is a function descriptor, read the actual code address from the
692 descriptor. */
693 if (opd
694 && sym->st_value >= opd->addr
695 && sym->st_value < opd->addr + opd->size)
696 elf_symbols[j].address
697 = *(const b_elf_addr *) (opd->data + (sym->st_value - opd->addr));
698 else
699 elf_symbols[j].address = sym->st_value;
700 elf_symbols[j].address += base_address;
701 elf_symbols[j].size = sym->st_size;
702 ++j;
705 backtrace_qsort (elf_symbols, elf_symbol_count, sizeof (struct elf_symbol),
706 elf_symbol_compare);
708 sdata->next = NULL;
709 sdata->symbols = elf_symbols;
710 sdata->count = elf_symbol_count;
712 return 1;
715 /* Add EDATA to the list in STATE. */
717 static void
718 elf_add_syminfo_data (struct backtrace_state *state,
719 struct elf_syminfo_data *edata)
721 if (!state->threaded)
723 struct elf_syminfo_data **pp;
725 for (pp = (struct elf_syminfo_data **) (void *) &state->syminfo_data;
726 *pp != NULL;
727 pp = &(*pp)->next)
729 *pp = edata;
731 else
733 while (1)
735 struct elf_syminfo_data **pp;
737 pp = (struct elf_syminfo_data **) (void *) &state->syminfo_data;
739 while (1)
741 struct elf_syminfo_data *p;
743 p = backtrace_atomic_load_pointer (pp);
745 if (p == NULL)
746 break;
748 pp = &p->next;
751 if (__sync_bool_compare_and_swap (pp, NULL, edata))
752 break;
757 /* Return the symbol name and value for an ADDR. */
759 static void
760 elf_syminfo (struct backtrace_state *state, uintptr_t addr,
761 backtrace_syminfo_callback callback,
762 backtrace_error_callback error_callback ATTRIBUTE_UNUSED,
763 void *data)
765 struct elf_syminfo_data *edata;
766 struct elf_symbol *sym = NULL;
768 if (!state->threaded)
770 for (edata = (struct elf_syminfo_data *) state->syminfo_data;
771 edata != NULL;
772 edata = edata->next)
774 sym = ((struct elf_symbol *)
775 bsearch (&addr, edata->symbols, edata->count,
776 sizeof (struct elf_symbol), elf_symbol_search));
777 if (sym != NULL)
778 break;
781 else
783 struct elf_syminfo_data **pp;
785 pp = (struct elf_syminfo_data **) (void *) &state->syminfo_data;
786 while (1)
788 edata = backtrace_atomic_load_pointer (pp);
789 if (edata == NULL)
790 break;
792 sym = ((struct elf_symbol *)
793 bsearch (&addr, edata->symbols, edata->count,
794 sizeof (struct elf_symbol), elf_symbol_search));
795 if (sym != NULL)
796 break;
798 pp = &edata->next;
802 if (sym == NULL)
803 callback (data, addr, NULL, 0, 0);
804 else
805 callback (data, addr, sym->name, sym->address, sym->size);
808 /* Return whether FILENAME is a symlink. */
810 static int
811 elf_is_symlink (const char *filename)
813 struct stat st;
815 if (lstat (filename, &st) < 0)
816 return 0;
817 return S_ISLNK (st.st_mode);
820 /* Return the results of reading the symlink FILENAME in a buffer
821 allocated by backtrace_alloc. Return the length of the buffer in
822 *LEN. */
824 static char *
825 elf_readlink (struct backtrace_state *state, const char *filename,
826 backtrace_error_callback error_callback, void *data,
827 size_t *plen)
829 size_t len;
830 char *buf;
832 len = 128;
833 while (1)
835 ssize_t rl;
837 buf = backtrace_alloc (state, len, error_callback, data);
838 if (buf == NULL)
839 return NULL;
840 rl = readlink (filename, buf, len);
841 if (rl < 0)
843 backtrace_free (state, buf, len, error_callback, data);
844 return NULL;
846 if ((size_t) rl < len - 1)
848 buf[rl] = '\0';
849 *plen = len;
850 return buf;
852 backtrace_free (state, buf, len, error_callback, data);
853 len *= 2;
857 #define SYSTEM_BUILD_ID_DIR "/usr/lib/debug/.build-id/"
859 /* Open a separate debug info file, using the build ID to find it.
860 Returns an open file descriptor, or -1.
862 The GDB manual says that the only place gdb looks for a debug file
863 when the build ID is known is in /usr/lib/debug/.build-id. */
865 static int
866 elf_open_debugfile_by_buildid (struct backtrace_state *state,
867 const char *buildid_data, size_t buildid_size,
868 backtrace_error_callback error_callback,
869 void *data)
871 const char * const prefix = SYSTEM_BUILD_ID_DIR;
872 const size_t prefix_len = strlen (prefix);
873 const char * const suffix = ".debug";
874 const size_t suffix_len = strlen (suffix);
875 size_t len;
876 char *bd_filename;
877 char *t;
878 size_t i;
879 int ret;
880 int does_not_exist;
882 len = prefix_len + buildid_size * 2 + suffix_len + 2;
883 bd_filename = backtrace_alloc (state, len, error_callback, data);
884 if (bd_filename == NULL)
885 return -1;
887 t = bd_filename;
888 memcpy (t, prefix, prefix_len);
889 t += prefix_len;
890 for (i = 0; i < buildid_size; i++)
892 unsigned char b;
893 unsigned char nib;
895 b = (unsigned char) buildid_data[i];
896 nib = (b & 0xf0) >> 4;
897 *t++ = nib < 10 ? '0' + nib : 'a' + nib - 10;
898 nib = b & 0x0f;
899 *t++ = nib < 10 ? '0' + nib : 'a' + nib - 10;
900 if (i == 0)
901 *t++ = '/';
903 memcpy (t, suffix, suffix_len);
904 t[suffix_len] = '\0';
906 ret = backtrace_open (bd_filename, error_callback, data, &does_not_exist);
908 backtrace_free (state, bd_filename, len, error_callback, data);
910 /* gdb checks that the debuginfo file has the same build ID note.
911 That seems kind of pointless to me--why would it have the right
912 name but not the right build ID?--so skipping the check. */
914 return ret;
917 /* Try to open a file whose name is PREFIX (length PREFIX_LEN)
918 concatenated with PREFIX2 (length PREFIX2_LEN) concatenated with
919 DEBUGLINK_NAME. Returns an open file descriptor, or -1. */
921 static int
922 elf_try_debugfile (struct backtrace_state *state, const char *prefix,
923 size_t prefix_len, const char *prefix2, size_t prefix2_len,
924 const char *debuglink_name,
925 backtrace_error_callback error_callback, void *data)
927 size_t debuglink_len;
928 size_t try_len;
929 char *try;
930 int does_not_exist;
931 int ret;
933 debuglink_len = strlen (debuglink_name);
934 try_len = prefix_len + prefix2_len + debuglink_len + 1;
935 try = backtrace_alloc (state, try_len, error_callback, data);
936 if (try == NULL)
937 return -1;
939 memcpy (try, prefix, prefix_len);
940 memcpy (try + prefix_len, prefix2, prefix2_len);
941 memcpy (try + prefix_len + prefix2_len, debuglink_name, debuglink_len);
942 try[prefix_len + prefix2_len + debuglink_len] = '\0';
944 ret = backtrace_open (try, error_callback, data, &does_not_exist);
946 backtrace_free (state, try, try_len, error_callback, data);
948 return ret;
951 /* Find a separate debug info file, using the debuglink section data
952 to find it. Returns an open file descriptor, or -1. */
954 static int
955 elf_find_debugfile_by_debuglink (struct backtrace_state *state,
956 const char *filename,
957 const char *debuglink_name,
958 backtrace_error_callback error_callback,
959 void *data)
961 int ret;
962 char *alc;
963 size_t alc_len;
964 const char *slash;
965 int ddescriptor;
966 const char *prefix;
967 size_t prefix_len;
969 /* Resolve symlinks in FILENAME. Since FILENAME is fairly likely to
970 be /proc/self/exe, symlinks are common. We don't try to resolve
971 the whole path name, just the base name. */
972 ret = -1;
973 alc = NULL;
974 alc_len = 0;
975 while (elf_is_symlink (filename))
977 char *new_buf;
978 size_t new_len;
980 new_buf = elf_readlink (state, filename, error_callback, data, &new_len);
981 if (new_buf == NULL)
982 break;
984 if (new_buf[0] == '/')
985 filename = new_buf;
986 else
988 slash = strrchr (filename, '/');
989 if (slash == NULL)
990 filename = new_buf;
991 else
993 size_t clen;
994 char *c;
996 slash++;
997 clen = slash - filename + strlen (new_buf) + 1;
998 c = backtrace_alloc (state, clen, error_callback, data);
999 if (c == NULL)
1000 goto done;
1002 memcpy (c, filename, slash - filename);
1003 memcpy (c + (slash - filename), new_buf, strlen (new_buf));
1004 c[slash - filename + strlen (new_buf)] = '\0';
1005 backtrace_free (state, new_buf, new_len, error_callback, data);
1006 filename = c;
1007 new_buf = c;
1008 new_len = clen;
1012 if (alc != NULL)
1013 backtrace_free (state, alc, alc_len, error_callback, data);
1014 alc = new_buf;
1015 alc_len = new_len;
1018 /* Look for DEBUGLINK_NAME in the same directory as FILENAME. */
1020 slash = strrchr (filename, '/');
1021 if (slash == NULL)
1023 prefix = "";
1024 prefix_len = 0;
1026 else
1028 slash++;
1029 prefix = filename;
1030 prefix_len = slash - filename;
1033 ddescriptor = elf_try_debugfile (state, prefix, prefix_len, "", 0,
1034 debuglink_name, error_callback, data);
1035 if (ddescriptor >= 0)
1037 ret = ddescriptor;
1038 goto done;
1041 /* Look for DEBUGLINK_NAME in a .debug subdirectory of FILENAME. */
1043 ddescriptor = elf_try_debugfile (state, prefix, prefix_len, ".debug/",
1044 strlen (".debug/"), debuglink_name,
1045 error_callback, data);
1046 if (ddescriptor >= 0)
1048 ret = ddescriptor;
1049 goto done;
1052 /* Look for DEBUGLINK_NAME in /usr/lib/debug. */
1054 ddescriptor = elf_try_debugfile (state, "/usr/lib/debug/",
1055 strlen ("/usr/lib/debug/"), prefix,
1056 prefix_len, debuglink_name,
1057 error_callback, data);
1058 if (ddescriptor >= 0)
1059 ret = ddescriptor;
1061 done:
1062 if (alc != NULL && alc_len > 0)
1063 backtrace_free (state, alc, alc_len, error_callback, data);
1064 return ret;
1067 /* Open a separate debug info file, using the debuglink section data
1068 to find it. Returns an open file descriptor, or -1. */
1070 static int
1071 elf_open_debugfile_by_debuglink (struct backtrace_state *state,
1072 const char *filename,
1073 const char *debuglink_name,
1074 uint32_t debuglink_crc,
1075 backtrace_error_callback error_callback,
1076 void *data)
1078 int ddescriptor;
1080 ddescriptor = elf_find_debugfile_by_debuglink (state, filename,
1081 debuglink_name,
1082 error_callback, data);
1083 if (ddescriptor < 0)
1084 return -1;
1086 if (debuglink_crc != 0)
1088 uint32_t got_crc;
1090 got_crc = elf_crc32_file (state, ddescriptor, error_callback, data);
1091 if (got_crc != debuglink_crc)
1093 backtrace_close (ddescriptor, error_callback, data);
1094 return -1;
1098 return ddescriptor;
1101 /* A function useful for setting a breakpoint for an inflation failure
1102 when this code is compiled with -g. */
1104 static void
1105 elf_uncompress_failed(void)
1109 /* *PVAL is the current value being read from the stream, and *PBITS
1110 is the number of valid bits. Ensure that *PVAL holds at least 15
1111 bits by reading additional bits from *PPIN, up to PINEND, as
1112 needed. Updates *PPIN, *PVAL and *PBITS. Returns 1 on success, 0
1113 on error. */
1115 static int
1116 elf_zlib_fetch (const unsigned char **ppin, const unsigned char *pinend,
1117 uint64_t *pval, unsigned int *pbits)
1119 unsigned int bits;
1120 const unsigned char *pin;
1121 uint64_t val;
1122 uint32_t next;
1124 bits = *pbits;
1125 if (bits >= 15)
1126 return 1;
1127 pin = *ppin;
1128 val = *pval;
1130 if (unlikely (pinend - pin < 4))
1132 elf_uncompress_failed ();
1133 return 0;
1136 #if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) \
1137 && defined(__ORDER_BIG_ENDIAN__) \
1138 && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ \
1139 || __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
1140 /* We've ensured that PIN is aligned. */
1141 next = *(const uint32_t *)pin;
1143 #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1144 next = __builtin_bswap32 (next);
1145 #endif
1146 #else
1147 next = pin[0] | (pin[1] << 8) | (pin[2] << 16) | (pin[3] << 24);
1148 #endif
1150 val |= (uint64_t)next << bits;
1151 bits += 32;
1152 pin += 4;
1154 /* We will need the next four bytes soon. */
1155 __builtin_prefetch (pin, 0, 0);
1157 *ppin = pin;
1158 *pval = val;
1159 *pbits = bits;
1160 return 1;
1163 /* Huffman code tables, like the rest of the zlib format, are defined
1164 by RFC 1951. We store a Huffman code table as a series of tables
1165 stored sequentially in memory. Each entry in a table is 16 bits.
1166 The first, main, table has 256 entries. It is followed by a set of
1167 secondary tables of length 2 to 128 entries. The maximum length of
1168 a code sequence in the deflate format is 15 bits, so that is all we
1169 need. Each secondary table has an index, which is the offset of
1170 the table in the overall memory storage.
1172 The deflate format says that all codes of a given bit length are
1173 lexicographically consecutive. Perhaps we could have 130 values
1174 that require a 15-bit code, perhaps requiring three secondary
1175 tables of size 128. I don't know if this is actually possible, but
1176 it suggests that the maximum size required for secondary tables is
1177 3 * 128 + 3 * 64 ... == 768. The zlib enough program reports 660
1178 as the maximum. We permit 768, since in addition to the 256 for
1179 the primary table, with two bytes per entry, and with the two
1180 tables we need, that gives us a page.
1182 A single table entry needs to store a value or (for the main table
1183 only) the index and size of a secondary table. Values range from 0
1184 to 285, inclusive. Secondary table indexes, per above, range from
1185 0 to 510. For a value we need to store the number of bits we need
1186 to determine that value (one value may appear multiple times in the
1187 table), which is 1 to 8. For a secondary table we need to store
1188 the number of bits used to index into the table, which is 1 to 7.
1189 And of course we need 1 bit to decide whether we have a value or a
1190 secondary table index. So each entry needs 9 bits for value/table
1191 index, 3 bits for size, 1 bit what it is. For simplicity we use 16
1192 bits per entry. */
1194 /* Number of entries we allocate to for one code table. We get a page
1195 for the two code tables we need. */
1197 #define HUFFMAN_TABLE_SIZE (1024)
1199 /* Bit masks and shifts for the values in the table. */
1201 #define HUFFMAN_VALUE_MASK 0x01ff
1202 #define HUFFMAN_BITS_SHIFT 9
1203 #define HUFFMAN_BITS_MASK 0x7
1204 #define HUFFMAN_SECONDARY_SHIFT 12
1206 /* For working memory while inflating we need two code tables, we need
1207 an array of code lengths (max value 15, so we use unsigned char),
1208 and an array of unsigned shorts used while building a table. The
1209 latter two arrays must be large enough to hold the maximum number
1210 of code lengths, which RFC 1951 defines as 286 + 30. */
1212 #define ZDEBUG_TABLE_SIZE \
1213 (2 * HUFFMAN_TABLE_SIZE * sizeof (uint16_t) \
1214 + (286 + 30) * sizeof (uint16_t) \
1215 + (286 + 30) * sizeof (unsigned char))
1217 #define ZDEBUG_TABLE_CODELEN_OFFSET \
1218 (2 * HUFFMAN_TABLE_SIZE * sizeof (uint16_t) \
1219 + (286 + 30) * sizeof (uint16_t))
1221 #define ZDEBUG_TABLE_WORK_OFFSET \
1222 (2 * HUFFMAN_TABLE_SIZE * sizeof (uint16_t))
1224 #ifdef BACKTRACE_GENERATE_FIXED_HUFFMAN_TABLE
1226 /* Used by the main function that generates the fixed table to learn
1227 the table size. */
1228 static size_t final_next_secondary;
1230 #endif
1232 /* Build a Huffman code table from an array of lengths in CODES of
1233 length CODES_LEN. The table is stored into *TABLE. ZDEBUG_TABLE
1234 is the same as for elf_zlib_inflate, used to find some work space.
1235 Returns 1 on success, 0 on error. */
1237 static int
1238 elf_zlib_inflate_table (unsigned char *codes, size_t codes_len,
1239 uint16_t *zdebug_table, uint16_t *table)
1241 uint16_t count[16];
1242 uint16_t start[16];
1243 uint16_t prev[16];
1244 uint16_t firstcode[7];
1245 uint16_t *next;
1246 size_t i;
1247 size_t j;
1248 unsigned int code;
1249 size_t next_secondary;
1251 /* Count the number of code of each length. Set NEXT[val] to be the
1252 next value after VAL with the same bit length. */
1254 next = (uint16_t *) (((unsigned char *) zdebug_table)
1255 + ZDEBUG_TABLE_WORK_OFFSET);
1257 memset (&count[0], 0, 16 * sizeof (uint16_t));
1258 for (i = 0; i < codes_len; ++i)
1260 if (unlikely (codes[i] >= 16))
1262 elf_uncompress_failed ();
1263 return 0;
1266 if (count[codes[i]] == 0)
1268 start[codes[i]] = i;
1269 prev[codes[i]] = i;
1271 else
1273 next[prev[codes[i]]] = i;
1274 prev[codes[i]] = i;
1277 ++count[codes[i]];
1280 /* For each length, fill in the table for the codes of that
1281 length. */
1283 memset (table, 0, HUFFMAN_TABLE_SIZE * sizeof (uint16_t));
1285 /* Handle the values that do not require a secondary table. */
1287 code = 0;
1288 for (j = 1; j <= 8; ++j)
1290 unsigned int jcnt;
1291 unsigned int val;
1293 jcnt = count[j];
1294 if (jcnt == 0)
1295 continue;
1297 if (unlikely (jcnt > (1U << j)))
1299 elf_uncompress_failed ();
1300 return 0;
1303 /* There are JCNT values that have this length, the values
1304 starting from START[j] continuing through NEXT[VAL]. Those
1305 values are assigned consecutive values starting at CODE. */
1307 val = start[j];
1308 for (i = 0; i < jcnt; ++i)
1310 uint16_t tval;
1311 size_t ind;
1312 unsigned int incr;
1314 /* In the compressed bit stream, the value VAL is encoded as
1315 J bits with the value C. */
1317 if (unlikely ((val & ~HUFFMAN_VALUE_MASK) != 0))
1319 elf_uncompress_failed ();
1320 return 0;
1323 tval = val | ((j - 1) << HUFFMAN_BITS_SHIFT);
1325 /* The table lookup uses 8 bits. If J is less than 8, we
1326 don't know what the other bits will be. We need to fill
1327 in all possibilities in the table. Since the Huffman
1328 code is unambiguous, those entries can't be used for any
1329 other code. */
1331 for (ind = code; ind < 0x100; ind += 1 << j)
1333 if (unlikely (table[ind] != 0))
1335 elf_uncompress_failed ();
1336 return 0;
1338 table[ind] = tval;
1341 /* Advance to the next value with this length. */
1342 if (i + 1 < jcnt)
1343 val = next[val];
1345 /* The Huffman codes are stored in the bitstream with the
1346 most significant bit first, as is required to make them
1347 unambiguous. The effect is that when we read them from
1348 the bitstream we see the bit sequence in reverse order:
1349 the most significant bit of the Huffman code is the least
1350 significant bit of the value we read from the bitstream.
1351 That means that to make our table lookups work, we need
1352 to reverse the bits of CODE. Since reversing bits is
1353 tedious and in general requires using a table, we instead
1354 increment CODE in reverse order. That is, if the number
1355 of bits we are currently using, here named J, is 3, we
1356 count as 000, 100, 010, 110, 001, 101, 011, 111, which is
1357 to say the numbers from 0 to 7 but with the bits
1358 reversed. Going to more bits, aka incrementing J,
1359 effectively just adds more zero bits as the beginning,
1360 and as such does not change the numeric value of CODE.
1362 To increment CODE of length J in reverse order, find the
1363 most significant zero bit and set it to one while
1364 clearing all higher bits. In other words, add 1 modulo
1365 2^J, only reversed. */
1367 incr = 1U << (j - 1);
1368 while ((code & incr) != 0)
1369 incr >>= 1;
1370 if (incr == 0)
1371 code = 0;
1372 else
1374 code &= incr - 1;
1375 code += incr;
1380 /* Handle the values that require a secondary table. */
1382 /* Set FIRSTCODE, the number at which the codes start, for each
1383 length. */
1385 for (j = 9; j < 16; j++)
1387 unsigned int jcnt;
1388 unsigned int k;
1390 jcnt = count[j];
1391 if (jcnt == 0)
1392 continue;
1394 /* There are JCNT values that have this length, the values
1395 starting from START[j]. Those values are assigned
1396 consecutive values starting at CODE. */
1398 firstcode[j - 9] = code;
1400 /* Reverse add JCNT to CODE modulo 2^J. */
1401 for (k = 0; k < j; ++k)
1403 if ((jcnt & (1U << k)) != 0)
1405 unsigned int m;
1406 unsigned int bit;
1408 bit = 1U << (j - k - 1);
1409 for (m = 0; m < j - k; ++m, bit >>= 1)
1411 if ((code & bit) == 0)
1413 code += bit;
1414 break;
1416 code &= ~bit;
1418 jcnt &= ~(1U << k);
1421 if (unlikely (jcnt != 0))
1423 elf_uncompress_failed ();
1424 return 0;
1428 /* For J from 9 to 15, inclusive, we store COUNT[J] consecutive
1429 values starting at START[J] with consecutive codes starting at
1430 FIRSTCODE[J - 9]. In the primary table we need to point to the
1431 secondary table, and the secondary table will be indexed by J - 9
1432 bits. We count down from 15 so that we install the larger
1433 secondary tables first, as the smaller ones may be embedded in
1434 the larger ones. */
1436 next_secondary = 0; /* Index of next secondary table (after primary). */
1437 for (j = 15; j >= 9; j--)
1439 unsigned int jcnt;
1440 unsigned int val;
1441 size_t primary; /* Current primary index. */
1442 size_t secondary; /* Offset to current secondary table. */
1443 size_t secondary_bits; /* Bit size of current secondary table. */
1445 jcnt = count[j];
1446 if (jcnt == 0)
1447 continue;
1449 val = start[j];
1450 code = firstcode[j - 9];
1451 primary = 0x100;
1452 secondary = 0;
1453 secondary_bits = 0;
1454 for (i = 0; i < jcnt; ++i)
1456 uint16_t tval;
1457 size_t ind;
1458 unsigned int incr;
1460 if ((code & 0xff) != primary)
1462 uint16_t tprimary;
1464 /* Fill in a new primary table entry. */
1466 primary = code & 0xff;
1468 tprimary = table[primary];
1469 if (tprimary == 0)
1471 /* Start a new secondary table. */
1473 if (unlikely ((next_secondary & HUFFMAN_VALUE_MASK)
1474 != next_secondary))
1476 elf_uncompress_failed ();
1477 return 0;
1480 secondary = next_secondary;
1481 secondary_bits = j - 8;
1482 next_secondary += 1 << secondary_bits;
1483 table[primary] = (secondary
1484 + ((j - 8) << HUFFMAN_BITS_SHIFT)
1485 + (1U << HUFFMAN_SECONDARY_SHIFT));
1487 else
1489 /* There is an existing entry. It had better be a
1490 secondary table with enough bits. */
1491 if (unlikely ((tprimary & (1U << HUFFMAN_SECONDARY_SHIFT))
1492 == 0))
1494 elf_uncompress_failed ();
1495 return 0;
1497 secondary = tprimary & HUFFMAN_VALUE_MASK;
1498 secondary_bits = ((tprimary >> HUFFMAN_BITS_SHIFT)
1499 & HUFFMAN_BITS_MASK);
1500 if (unlikely (secondary_bits < j - 8))
1502 elf_uncompress_failed ();
1503 return 0;
1508 /* Fill in secondary table entries. */
1510 tval = val | ((j - 8) << HUFFMAN_BITS_SHIFT);
1512 for (ind = code >> 8;
1513 ind < (1U << secondary_bits);
1514 ind += 1U << (j - 8))
1516 if (unlikely (table[secondary + 0x100 + ind] != 0))
1518 elf_uncompress_failed ();
1519 return 0;
1521 table[secondary + 0x100 + ind] = tval;
1524 if (i + 1 < jcnt)
1525 val = next[val];
1527 incr = 1U << (j - 1);
1528 while ((code & incr) != 0)
1529 incr >>= 1;
1530 if (incr == 0)
1531 code = 0;
1532 else
1534 code &= incr - 1;
1535 code += incr;
1540 #ifdef BACKTRACE_GENERATE_FIXED_HUFFMAN_TABLE
1541 final_next_secondary = next_secondary;
1542 #endif
1544 return 1;
1547 #ifdef BACKTRACE_GENERATE_FIXED_HUFFMAN_TABLE
1549 /* Used to generate the fixed Huffman table for block type 1. */
1551 #include <stdio.h>
1553 static uint16_t table[ZDEBUG_TABLE_SIZE];
1554 static unsigned char codes[288];
1557 main ()
1559 size_t i;
1561 for (i = 0; i <= 143; ++i)
1562 codes[i] = 8;
1563 for (i = 144; i <= 255; ++i)
1564 codes[i] = 9;
1565 for (i = 256; i <= 279; ++i)
1566 codes[i] = 7;
1567 for (i = 280; i <= 287; ++i)
1568 codes[i] = 8;
1569 if (!elf_zlib_inflate_table (&codes[0], 288, &table[0], &table[0]))
1571 fprintf (stderr, "elf_zlib_inflate_table failed\n");
1572 exit (EXIT_FAILURE);
1575 printf ("static const uint16_t elf_zlib_default_table[%#zx] =\n",
1576 final_next_secondary + 0x100);
1577 printf ("{\n");
1578 for (i = 0; i < final_next_secondary + 0x100; i += 8)
1580 size_t j;
1582 printf (" ");
1583 for (j = i; j < final_next_secondary + 0x100 && j < i + 8; ++j)
1584 printf (" %#x,", table[j]);
1585 printf ("\n");
1587 printf ("};\n");
1588 printf ("\n");
1590 for (i = 0; i < 32; ++i)
1591 codes[i] = 5;
1592 if (!elf_zlib_inflate_table (&codes[0], 32, &table[0], &table[0]))
1594 fprintf (stderr, "elf_zlib_inflate_table failed\n");
1595 exit (EXIT_FAILURE);
1598 printf ("static const uint16_t elf_zlib_default_dist_table[%#zx] =\n",
1599 final_next_secondary + 0x100);
1600 printf ("{\n");
1601 for (i = 0; i < final_next_secondary + 0x100; i += 8)
1603 size_t j;
1605 printf (" ");
1606 for (j = i; j < final_next_secondary + 0x100 && j < i + 8; ++j)
1607 printf (" %#x,", table[j]);
1608 printf ("\n");
1610 printf ("};\n");
1612 return 0;
1615 #endif
1617 /* The fixed tables generated by the #ifdef'ed out main function
1618 above. */
1620 static const uint16_t elf_zlib_default_table[0x170] =
1622 0xd00, 0xe50, 0xe10, 0xf18, 0xd10, 0xe70, 0xe30, 0x1230,
1623 0xd08, 0xe60, 0xe20, 0x1210, 0xe00, 0xe80, 0xe40, 0x1250,
1624 0xd04, 0xe58, 0xe18, 0x1200, 0xd14, 0xe78, 0xe38, 0x1240,
1625 0xd0c, 0xe68, 0xe28, 0x1220, 0xe08, 0xe88, 0xe48, 0x1260,
1626 0xd02, 0xe54, 0xe14, 0xf1c, 0xd12, 0xe74, 0xe34, 0x1238,
1627 0xd0a, 0xe64, 0xe24, 0x1218, 0xe04, 0xe84, 0xe44, 0x1258,
1628 0xd06, 0xe5c, 0xe1c, 0x1208, 0xd16, 0xe7c, 0xe3c, 0x1248,
1629 0xd0e, 0xe6c, 0xe2c, 0x1228, 0xe0c, 0xe8c, 0xe4c, 0x1268,
1630 0xd01, 0xe52, 0xe12, 0xf1a, 0xd11, 0xe72, 0xe32, 0x1234,
1631 0xd09, 0xe62, 0xe22, 0x1214, 0xe02, 0xe82, 0xe42, 0x1254,
1632 0xd05, 0xe5a, 0xe1a, 0x1204, 0xd15, 0xe7a, 0xe3a, 0x1244,
1633 0xd0d, 0xe6a, 0xe2a, 0x1224, 0xe0a, 0xe8a, 0xe4a, 0x1264,
1634 0xd03, 0xe56, 0xe16, 0xf1e, 0xd13, 0xe76, 0xe36, 0x123c,
1635 0xd0b, 0xe66, 0xe26, 0x121c, 0xe06, 0xe86, 0xe46, 0x125c,
1636 0xd07, 0xe5e, 0xe1e, 0x120c, 0xd17, 0xe7e, 0xe3e, 0x124c,
1637 0xd0f, 0xe6e, 0xe2e, 0x122c, 0xe0e, 0xe8e, 0xe4e, 0x126c,
1638 0xd00, 0xe51, 0xe11, 0xf19, 0xd10, 0xe71, 0xe31, 0x1232,
1639 0xd08, 0xe61, 0xe21, 0x1212, 0xe01, 0xe81, 0xe41, 0x1252,
1640 0xd04, 0xe59, 0xe19, 0x1202, 0xd14, 0xe79, 0xe39, 0x1242,
1641 0xd0c, 0xe69, 0xe29, 0x1222, 0xe09, 0xe89, 0xe49, 0x1262,
1642 0xd02, 0xe55, 0xe15, 0xf1d, 0xd12, 0xe75, 0xe35, 0x123a,
1643 0xd0a, 0xe65, 0xe25, 0x121a, 0xe05, 0xe85, 0xe45, 0x125a,
1644 0xd06, 0xe5d, 0xe1d, 0x120a, 0xd16, 0xe7d, 0xe3d, 0x124a,
1645 0xd0e, 0xe6d, 0xe2d, 0x122a, 0xe0d, 0xe8d, 0xe4d, 0x126a,
1646 0xd01, 0xe53, 0xe13, 0xf1b, 0xd11, 0xe73, 0xe33, 0x1236,
1647 0xd09, 0xe63, 0xe23, 0x1216, 0xe03, 0xe83, 0xe43, 0x1256,
1648 0xd05, 0xe5b, 0xe1b, 0x1206, 0xd15, 0xe7b, 0xe3b, 0x1246,
1649 0xd0d, 0xe6b, 0xe2b, 0x1226, 0xe0b, 0xe8b, 0xe4b, 0x1266,
1650 0xd03, 0xe57, 0xe17, 0xf1f, 0xd13, 0xe77, 0xe37, 0x123e,
1651 0xd0b, 0xe67, 0xe27, 0x121e, 0xe07, 0xe87, 0xe47, 0x125e,
1652 0xd07, 0xe5f, 0xe1f, 0x120e, 0xd17, 0xe7f, 0xe3f, 0x124e,
1653 0xd0f, 0xe6f, 0xe2f, 0x122e, 0xe0f, 0xe8f, 0xe4f, 0x126e,
1654 0x290, 0x291, 0x292, 0x293, 0x294, 0x295, 0x296, 0x297,
1655 0x298, 0x299, 0x29a, 0x29b, 0x29c, 0x29d, 0x29e, 0x29f,
1656 0x2a0, 0x2a1, 0x2a2, 0x2a3, 0x2a4, 0x2a5, 0x2a6, 0x2a7,
1657 0x2a8, 0x2a9, 0x2aa, 0x2ab, 0x2ac, 0x2ad, 0x2ae, 0x2af,
1658 0x2b0, 0x2b1, 0x2b2, 0x2b3, 0x2b4, 0x2b5, 0x2b6, 0x2b7,
1659 0x2b8, 0x2b9, 0x2ba, 0x2bb, 0x2bc, 0x2bd, 0x2be, 0x2bf,
1660 0x2c0, 0x2c1, 0x2c2, 0x2c3, 0x2c4, 0x2c5, 0x2c6, 0x2c7,
1661 0x2c8, 0x2c9, 0x2ca, 0x2cb, 0x2cc, 0x2cd, 0x2ce, 0x2cf,
1662 0x2d0, 0x2d1, 0x2d2, 0x2d3, 0x2d4, 0x2d5, 0x2d6, 0x2d7,
1663 0x2d8, 0x2d9, 0x2da, 0x2db, 0x2dc, 0x2dd, 0x2de, 0x2df,
1664 0x2e0, 0x2e1, 0x2e2, 0x2e3, 0x2e4, 0x2e5, 0x2e6, 0x2e7,
1665 0x2e8, 0x2e9, 0x2ea, 0x2eb, 0x2ec, 0x2ed, 0x2ee, 0x2ef,
1666 0x2f0, 0x2f1, 0x2f2, 0x2f3, 0x2f4, 0x2f5, 0x2f6, 0x2f7,
1667 0x2f8, 0x2f9, 0x2fa, 0x2fb, 0x2fc, 0x2fd, 0x2fe, 0x2ff,
1670 static const uint16_t elf_zlib_default_dist_table[0x100] =
1672 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c,
1673 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e,
1674 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d,
1675 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f,
1676 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c,
1677 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e,
1678 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d,
1679 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f,
1680 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c,
1681 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e,
1682 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d,
1683 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f,
1684 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c,
1685 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e,
1686 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d,
1687 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f,
1688 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c,
1689 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e,
1690 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d,
1691 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f,
1692 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c,
1693 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e,
1694 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d,
1695 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f,
1696 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c,
1697 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e,
1698 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d,
1699 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f,
1700 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c,
1701 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e,
1702 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d,
1703 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f,
1706 /* Inflate a zlib stream from PIN/SIN to POUT/SOUT. Return 1 on
1707 success, 0 on some error parsing the stream. */
1709 static int
1710 elf_zlib_inflate (const unsigned char *pin, size_t sin, uint16_t *zdebug_table,
1711 unsigned char *pout, size_t sout)
1713 unsigned char *porigout;
1714 const unsigned char *pinend;
1715 unsigned char *poutend;
1717 /* We can apparently see multiple zlib streams concatenated
1718 together, so keep going as long as there is something to read.
1719 The last 4 bytes are the checksum. */
1720 porigout = pout;
1721 pinend = pin + sin;
1722 poutend = pout + sout;
1723 while ((pinend - pin) > 4)
1725 uint64_t val;
1726 unsigned int bits;
1727 int last;
1729 /* Read the two byte zlib header. */
1731 if (unlikely ((pin[0] & 0xf) != 8)) /* 8 is zlib encoding. */
1733 /* Unknown compression method. */
1734 elf_uncompress_failed ();
1735 return 0;
1737 if (unlikely ((pin[0] >> 4) > 7))
1739 /* Window size too large. Other than this check, we don't
1740 care about the window size. */
1741 elf_uncompress_failed ();
1742 return 0;
1744 if (unlikely ((pin[1] & 0x20) != 0))
1746 /* Stream expects a predefined dictionary, but we have no
1747 dictionary. */
1748 elf_uncompress_failed ();
1749 return 0;
1751 val = (pin[0] << 8) | pin[1];
1752 if (unlikely (val % 31 != 0))
1754 /* Header check failure. */
1755 elf_uncompress_failed ();
1756 return 0;
1758 pin += 2;
1760 /* Align PIN to a 32-bit boundary. */
1762 val = 0;
1763 bits = 0;
1764 while ((((uintptr_t) pin) & 3) != 0)
1766 val |= (uint64_t)*pin << bits;
1767 bits += 8;
1768 ++pin;
1771 /* Read blocks until one is marked last. */
1773 last = 0;
1775 while (!last)
1777 unsigned int type;
1778 const uint16_t *tlit;
1779 const uint16_t *tdist;
1781 if (!elf_zlib_fetch (&pin, pinend, &val, &bits))
1782 return 0;
1784 last = val & 1;
1785 type = (val >> 1) & 3;
1786 val >>= 3;
1787 bits -= 3;
1789 if (unlikely (type == 3))
1791 /* Invalid block type. */
1792 elf_uncompress_failed ();
1793 return 0;
1796 if (type == 0)
1798 uint16_t len;
1799 uint16_t lenc;
1801 /* An uncompressed block. */
1803 /* If we've read ahead more than a byte, back up. */
1804 while (bits >= 8)
1806 --pin;
1807 bits -= 8;
1810 val = 0;
1811 bits = 0;
1812 if (unlikely ((pinend - pin) < 4))
1814 /* Missing length. */
1815 elf_uncompress_failed ();
1816 return 0;
1818 len = pin[0] | (pin[1] << 8);
1819 lenc = pin[2] | (pin[3] << 8);
1820 pin += 4;
1821 lenc = ~lenc;
1822 if (unlikely (len != lenc))
1824 /* Corrupt data. */
1825 elf_uncompress_failed ();
1826 return 0;
1828 if (unlikely (len > (unsigned int) (pinend - pin)
1829 || len > (unsigned int) (poutend - pout)))
1831 /* Not enough space in buffers. */
1832 elf_uncompress_failed ();
1833 return 0;
1835 memcpy (pout, pin, len);
1836 pout += len;
1837 pin += len;
1839 /* Align PIN. */
1840 while ((((uintptr_t) pin) & 3) != 0)
1842 val |= (uint64_t)*pin << bits;
1843 bits += 8;
1844 ++pin;
1847 /* Go around to read the next block. */
1848 continue;
1851 if (type == 1)
1853 tlit = elf_zlib_default_table;
1854 tdist = elf_zlib_default_dist_table;
1856 else
1858 unsigned int nlit;
1859 unsigned int ndist;
1860 unsigned int nclen;
1861 unsigned char codebits[19];
1862 unsigned char *plenbase;
1863 unsigned char *plen;
1864 unsigned char *plenend;
1866 /* Read a Huffman encoding table. The various magic
1867 numbers here are from RFC 1951. */
1869 if (!elf_zlib_fetch (&pin, pinend, &val, &bits))
1870 return 0;
1872 nlit = (val & 0x1f) + 257;
1873 val >>= 5;
1874 ndist = (val & 0x1f) + 1;
1875 val >>= 5;
1876 nclen = (val & 0xf) + 4;
1877 val >>= 4;
1878 bits -= 14;
1879 if (unlikely (nlit > 286 || ndist > 30))
1881 /* Values out of range. */
1882 elf_uncompress_failed ();
1883 return 0;
1886 /* Read and build the table used to compress the
1887 literal, length, and distance codes. */
1889 memset(&codebits[0], 0, 19);
1891 /* There are always at least 4 elements in the
1892 table. */
1894 if (!elf_zlib_fetch (&pin, pinend, &val, &bits))
1895 return 0;
1897 codebits[16] = val & 7;
1898 codebits[17] = (val >> 3) & 7;
1899 codebits[18] = (val >> 6) & 7;
1900 codebits[0] = (val >> 9) & 7;
1901 val >>= 12;
1902 bits -= 12;
1904 if (nclen == 4)
1905 goto codebitsdone;
1907 codebits[8] = val & 7;
1908 val >>= 3;
1909 bits -= 3;
1911 if (nclen == 5)
1912 goto codebitsdone;
1914 if (!elf_zlib_fetch (&pin, pinend, &val, &bits))
1915 return 0;
1917 codebits[7] = val & 7;
1918 val >>= 3;
1919 bits -= 3;
1921 if (nclen == 6)
1922 goto codebitsdone;
1924 codebits[9] = val & 7;
1925 val >>= 3;
1926 bits -= 3;
1928 if (nclen == 7)
1929 goto codebitsdone;
1931 codebits[6] = val & 7;
1932 val >>= 3;
1933 bits -= 3;
1935 if (nclen == 8)
1936 goto codebitsdone;
1938 codebits[10] = val & 7;
1939 val >>= 3;
1940 bits -= 3;
1942 if (nclen == 9)
1943 goto codebitsdone;
1945 codebits[5] = val & 7;
1946 val >>= 3;
1947 bits -= 3;
1949 if (nclen == 10)
1950 goto codebitsdone;
1952 if (!elf_zlib_fetch (&pin, pinend, &val, &bits))
1953 return 0;
1955 codebits[11] = val & 7;
1956 val >>= 3;
1957 bits -= 3;
1959 if (nclen == 11)
1960 goto codebitsdone;
1962 codebits[4] = val & 7;
1963 val >>= 3;
1964 bits -= 3;
1966 if (nclen == 12)
1967 goto codebitsdone;
1969 codebits[12] = val & 7;
1970 val >>= 3;
1971 bits -= 3;
1973 if (nclen == 13)
1974 goto codebitsdone;
1976 codebits[3] = val & 7;
1977 val >>= 3;
1978 bits -= 3;
1980 if (nclen == 14)
1981 goto codebitsdone;
1983 codebits[13] = val & 7;
1984 val >>= 3;
1985 bits -= 3;
1987 if (nclen == 15)
1988 goto codebitsdone;
1990 if (!elf_zlib_fetch (&pin, pinend, &val, &bits))
1991 return 0;
1993 codebits[2] = val & 7;
1994 val >>= 3;
1995 bits -= 3;
1997 if (nclen == 16)
1998 goto codebitsdone;
2000 codebits[14] = val & 7;
2001 val >>= 3;
2002 bits -= 3;
2004 if (nclen == 17)
2005 goto codebitsdone;
2007 codebits[1] = val & 7;
2008 val >>= 3;
2009 bits -= 3;
2011 if (nclen == 18)
2012 goto codebitsdone;
2014 codebits[15] = val & 7;
2015 val >>= 3;
2016 bits -= 3;
2018 codebitsdone:
2020 if (!elf_zlib_inflate_table (codebits, 19, zdebug_table,
2021 zdebug_table))
2022 return 0;
2024 /* Read the compressed bit lengths of the literal,
2025 length, and distance codes. We have allocated space
2026 at the end of zdebug_table to hold them. */
2028 plenbase = (((unsigned char *) zdebug_table)
2029 + ZDEBUG_TABLE_CODELEN_OFFSET);
2030 plen = plenbase;
2031 plenend = plen + nlit + ndist;
2032 while (plen < plenend)
2034 uint16_t t;
2035 unsigned int b;
2036 uint16_t v;
2038 if (!elf_zlib_fetch (&pin, pinend, &val, &bits))
2039 return 0;
2041 t = zdebug_table[val & 0xff];
2043 /* The compression here uses bit lengths up to 7, so
2044 a secondary table is never necessary. */
2045 if (unlikely ((t & (1U << HUFFMAN_SECONDARY_SHIFT)) != 0))
2047 elf_uncompress_failed ();
2048 return 0;
2051 b = (t >> HUFFMAN_BITS_SHIFT) & HUFFMAN_BITS_MASK;
2052 val >>= b + 1;
2053 bits -= b + 1;
2055 v = t & HUFFMAN_VALUE_MASK;
2056 if (v < 16)
2057 *plen++ = v;
2058 else if (v == 16)
2060 unsigned int c;
2061 unsigned int prev;
2063 /* Copy previous entry 3 to 6 times. */
2065 if (unlikely (plen == plenbase))
2067 elf_uncompress_failed ();
2068 return 0;
2071 /* We used up to 7 bits since the last
2072 elf_zlib_fetch, so we have at least 8 bits
2073 available here. */
2075 c = 3 + (val & 0x3);
2076 val >>= 2;
2077 bits -= 2;
2078 if (unlikely ((unsigned int) (plenend - plen) < c))
2080 elf_uncompress_failed ();
2081 return 0;
2084 prev = plen[-1];
2085 switch (c)
2087 case 6:
2088 *plen++ = prev;
2089 ATTRIBUTE_FALLTHROUGH;
2090 case 5:
2091 *plen++ = prev;
2092 ATTRIBUTE_FALLTHROUGH;
2093 case 4:
2094 *plen++ = prev;
2096 *plen++ = prev;
2097 *plen++ = prev;
2098 *plen++ = prev;
2100 else if (v == 17)
2102 unsigned int c;
2104 /* Store zero 3 to 10 times. */
2106 /* We used up to 7 bits since the last
2107 elf_zlib_fetch, so we have at least 8 bits
2108 available here. */
2110 c = 3 + (val & 0x7);
2111 val >>= 3;
2112 bits -= 3;
2113 if (unlikely ((unsigned int) (plenend - plen) < c))
2115 elf_uncompress_failed ();
2116 return 0;
2119 switch (c)
2121 case 10:
2122 *plen++ = 0;
2123 ATTRIBUTE_FALLTHROUGH;
2124 case 9:
2125 *plen++ = 0;
2126 ATTRIBUTE_FALLTHROUGH;
2127 case 8:
2128 *plen++ = 0;
2129 ATTRIBUTE_FALLTHROUGH;
2130 case 7:
2131 *plen++ = 0;
2132 ATTRIBUTE_FALLTHROUGH;
2133 case 6:
2134 *plen++ = 0;
2135 ATTRIBUTE_FALLTHROUGH;
2136 case 5:
2137 *plen++ = 0;
2138 ATTRIBUTE_FALLTHROUGH;
2139 case 4:
2140 *plen++ = 0;
2142 *plen++ = 0;
2143 *plen++ = 0;
2144 *plen++ = 0;
2146 else if (v == 18)
2148 unsigned int c;
2150 /* Store zero 11 to 138 times. */
2152 /* We used up to 7 bits since the last
2153 elf_zlib_fetch, so we have at least 8 bits
2154 available here. */
2156 c = 11 + (val & 0x7f);
2157 val >>= 7;
2158 bits -= 7;
2159 if (unlikely ((unsigned int) (plenend - plen) < c))
2161 elf_uncompress_failed ();
2162 return 0;
2165 memset (plen, 0, c);
2166 plen += c;
2168 else
2170 elf_uncompress_failed ();
2171 return 0;
2175 /* Make sure that the stop code can appear. */
2177 plen = plenbase;
2178 if (unlikely (plen[256] == 0))
2180 elf_uncompress_failed ();
2181 return 0;
2184 /* Build the decompression tables. */
2186 if (!elf_zlib_inflate_table (plen, nlit, zdebug_table,
2187 zdebug_table))
2188 return 0;
2189 if (!elf_zlib_inflate_table (plen + nlit, ndist, zdebug_table,
2190 zdebug_table + HUFFMAN_TABLE_SIZE))
2191 return 0;
2192 tlit = zdebug_table;
2193 tdist = zdebug_table + HUFFMAN_TABLE_SIZE;
2196 /* Inflate values until the end of the block. This is the
2197 main loop of the inflation code. */
2199 while (1)
2201 uint16_t t;
2202 unsigned int b;
2203 uint16_t v;
2204 unsigned int lit;
2206 if (!elf_zlib_fetch (&pin, pinend, &val, &bits))
2207 return 0;
2209 t = tlit[val & 0xff];
2210 b = (t >> HUFFMAN_BITS_SHIFT) & HUFFMAN_BITS_MASK;
2211 v = t & HUFFMAN_VALUE_MASK;
2213 if ((t & (1U << HUFFMAN_SECONDARY_SHIFT)) == 0)
2215 lit = v;
2216 val >>= b + 1;
2217 bits -= b + 1;
2219 else
2221 t = tlit[v + 0x100 + ((val >> 8) & ((1U << b) - 1))];
2222 b = (t >> HUFFMAN_BITS_SHIFT) & HUFFMAN_BITS_MASK;
2223 lit = t & HUFFMAN_VALUE_MASK;
2224 val >>= b + 8;
2225 bits -= b + 8;
2228 if (lit < 256)
2230 if (unlikely (pout == poutend))
2232 elf_uncompress_failed ();
2233 return 0;
2236 *pout++ = lit;
2238 /* We will need to write the next byte soon. We ask
2239 for high temporal locality because we will write
2240 to the whole cache line soon. */
2241 __builtin_prefetch (pout, 1, 3);
2243 else if (lit == 256)
2245 /* The end of the block. */
2246 break;
2248 else
2250 unsigned int dist;
2251 unsigned int len;
2253 /* Convert lit into a length. */
2255 if (lit < 265)
2256 len = lit - 257 + 3;
2257 else if (lit == 285)
2258 len = 258;
2259 else if (unlikely (lit > 285))
2261 elf_uncompress_failed ();
2262 return 0;
2264 else
2266 unsigned int extra;
2268 if (!elf_zlib_fetch (&pin, pinend, &val, &bits))
2269 return 0;
2271 /* This is an expression for the table of length
2272 codes in RFC 1951 3.2.5. */
2273 lit -= 265;
2274 extra = (lit >> 2) + 1;
2275 len = (lit & 3) << extra;
2276 len += 11;
2277 len += ((1U << (extra - 1)) - 1) << 3;
2278 len += val & ((1U << extra) - 1);
2279 val >>= extra;
2280 bits -= extra;
2283 if (!elf_zlib_fetch (&pin, pinend, &val, &bits))
2284 return 0;
2286 t = tdist[val & 0xff];
2287 b = (t >> HUFFMAN_BITS_SHIFT) & HUFFMAN_BITS_MASK;
2288 v = t & HUFFMAN_VALUE_MASK;
2290 if ((t & (1U << HUFFMAN_SECONDARY_SHIFT)) == 0)
2292 dist = v;
2293 val >>= b + 1;
2294 bits -= b + 1;
2296 else
2298 t = tdist[v + 0x100 + ((val >> 8) & ((1U << b) - 1))];
2299 b = (t >> HUFFMAN_BITS_SHIFT) & HUFFMAN_BITS_MASK;
2300 dist = t & HUFFMAN_VALUE_MASK;
2301 val >>= b + 8;
2302 bits -= b + 8;
2305 /* Convert dist to a distance. */
2307 if (dist == 0)
2309 /* A distance of 1. A common case, meaning
2310 repeat the last character LEN times. */
2312 if (unlikely (pout == porigout))
2314 elf_uncompress_failed ();
2315 return 0;
2318 if (unlikely ((unsigned int) (poutend - pout) < len))
2320 elf_uncompress_failed ();
2321 return 0;
2324 memset (pout, pout[-1], len);
2325 pout += len;
2327 else if (unlikely (dist > 29))
2329 elf_uncompress_failed ();
2330 return 0;
2332 else
2334 if (dist < 4)
2335 dist = dist + 1;
2336 else
2338 unsigned int extra;
2340 if (!elf_zlib_fetch (&pin, pinend, &val, &bits))
2341 return 0;
2343 /* This is an expression for the table of
2344 distance codes in RFC 1951 3.2.5. */
2345 dist -= 4;
2346 extra = (dist >> 1) + 1;
2347 dist = (dist & 1) << extra;
2348 dist += 5;
2349 dist += ((1U << (extra - 1)) - 1) << 2;
2350 dist += val & ((1U << extra) - 1);
2351 val >>= extra;
2352 bits -= extra;
2355 /* Go back dist bytes, and copy len bytes from
2356 there. */
2358 if (unlikely ((unsigned int) (pout - porigout) < dist))
2360 elf_uncompress_failed ();
2361 return 0;
2364 if (unlikely ((unsigned int) (poutend - pout) < len))
2366 elf_uncompress_failed ();
2367 return 0;
2370 if (dist >= len)
2372 memcpy (pout, pout - dist, len);
2373 pout += len;
2375 else
2377 while (len > 0)
2379 unsigned int copy;
2381 copy = len < dist ? len : dist;
2382 memcpy (pout, pout - dist, copy);
2383 len -= copy;
2384 pout += copy;
2393 /* We should have filled the output buffer. */
2394 if (unlikely (pout != poutend))
2396 elf_uncompress_failed ();
2397 return 0;
2400 return 1;
2403 /* Verify the zlib checksum. The checksum is in the 4 bytes at
2404 CHECKBYTES, and the uncompressed data is at UNCOMPRESSED /
2405 UNCOMPRESSED_SIZE. Returns 1 on success, 0 on failure. */
2407 static int
2408 elf_zlib_verify_checksum (const unsigned char *checkbytes,
2409 const unsigned char *uncompressed,
2410 size_t uncompressed_size)
2412 unsigned int i;
2413 unsigned int cksum;
2414 const unsigned char *p;
2415 uint32_t s1;
2416 uint32_t s2;
2417 size_t hsz;
2419 cksum = 0;
2420 for (i = 0; i < 4; i++)
2421 cksum = (cksum << 8) | checkbytes[i];
2423 s1 = 1;
2424 s2 = 0;
2426 /* Minimize modulo operations. */
2428 p = uncompressed;
2429 hsz = uncompressed_size;
2430 while (hsz >= 5552)
2432 for (i = 0; i < 5552; i += 16)
2434 /* Manually unroll loop 16 times. */
2435 s1 = s1 + *p++;
2436 s2 = s2 + s1;
2437 s1 = s1 + *p++;
2438 s2 = s2 + s1;
2439 s1 = s1 + *p++;
2440 s2 = s2 + s1;
2441 s1 = s1 + *p++;
2442 s2 = s2 + s1;
2443 s1 = s1 + *p++;
2444 s2 = s2 + s1;
2445 s1 = s1 + *p++;
2446 s2 = s2 + s1;
2447 s1 = s1 + *p++;
2448 s2 = s2 + s1;
2449 s1 = s1 + *p++;
2450 s2 = s2 + s1;
2451 s1 = s1 + *p++;
2452 s2 = s2 + s1;
2453 s1 = s1 + *p++;
2454 s2 = s2 + s1;
2455 s1 = s1 + *p++;
2456 s2 = s2 + s1;
2457 s1 = s1 + *p++;
2458 s2 = s2 + s1;
2459 s1 = s1 + *p++;
2460 s2 = s2 + s1;
2461 s1 = s1 + *p++;
2462 s2 = s2 + s1;
2463 s1 = s1 + *p++;
2464 s2 = s2 + s1;
2465 s1 = s1 + *p++;
2466 s2 = s2 + s1;
2468 hsz -= 5552;
2469 s1 %= 65521;
2470 s2 %= 65521;
2473 while (hsz >= 16)
2475 /* Manually unroll loop 16 times. */
2476 s1 = s1 + *p++;
2477 s2 = s2 + s1;
2478 s1 = s1 + *p++;
2479 s2 = s2 + s1;
2480 s1 = s1 + *p++;
2481 s2 = s2 + s1;
2482 s1 = s1 + *p++;
2483 s2 = s2 + s1;
2484 s1 = s1 + *p++;
2485 s2 = s2 + s1;
2486 s1 = s1 + *p++;
2487 s2 = s2 + s1;
2488 s1 = s1 + *p++;
2489 s2 = s2 + s1;
2490 s1 = s1 + *p++;
2491 s2 = s2 + s1;
2492 s1 = s1 + *p++;
2493 s2 = s2 + s1;
2494 s1 = s1 + *p++;
2495 s2 = s2 + s1;
2496 s1 = s1 + *p++;
2497 s2 = s2 + s1;
2498 s1 = s1 + *p++;
2499 s2 = s2 + s1;
2500 s1 = s1 + *p++;
2501 s2 = s2 + s1;
2502 s1 = s1 + *p++;
2503 s2 = s2 + s1;
2504 s1 = s1 + *p++;
2505 s2 = s2 + s1;
2506 s1 = s1 + *p++;
2507 s2 = s2 + s1;
2509 hsz -= 16;
2512 for (i = 0; i < hsz; ++i)
2514 s1 = s1 + *p++;
2515 s2 = s2 + s1;
2518 s1 %= 65521;
2519 s2 %= 65521;
2521 if (unlikely ((s2 << 16) + s1 != cksum))
2523 elf_uncompress_failed ();
2524 return 0;
2527 return 1;
2530 /* Inflate a zlib stream from PIN/SIN to POUT/SOUT, and verify the
2531 checksum. Return 1 on success, 0 on error. */
2533 static int
2534 elf_zlib_inflate_and_verify (const unsigned char *pin, size_t sin,
2535 uint16_t *zdebug_table, unsigned char *pout,
2536 size_t sout)
2538 if (!elf_zlib_inflate (pin, sin, zdebug_table, pout, sout))
2539 return 0;
2540 if (!elf_zlib_verify_checksum (pin + sin - 4, pout, sout))
2541 return 0;
2542 return 1;
2545 /* Uncompress the old compressed debug format, the one emitted by
2546 --compress-debug-sections=zlib-gnu. The compressed data is in
2547 COMPRESSED / COMPRESSED_SIZE, and the function writes to
2548 *UNCOMPRESSED / *UNCOMPRESSED_SIZE. ZDEBUG_TABLE is work space to
2549 hold Huffman tables. Returns 0 on error, 1 on successful
2550 decompression or if something goes wrong. In general we try to
2551 carry on, by returning 1, even if we can't decompress. */
2553 static int
2554 elf_uncompress_zdebug (struct backtrace_state *state,
2555 const unsigned char *compressed, size_t compressed_size,
2556 uint16_t *zdebug_table,
2557 backtrace_error_callback error_callback, void *data,
2558 unsigned char **uncompressed, size_t *uncompressed_size)
2560 size_t sz;
2561 size_t i;
2562 unsigned char *po;
2564 *uncompressed = NULL;
2565 *uncompressed_size = 0;
2567 /* The format starts with the four bytes ZLIB, followed by the 8
2568 byte length of the uncompressed data in big-endian order,
2569 followed by a zlib stream. */
2571 if (compressed_size < 12 || memcmp (compressed, "ZLIB", 4) != 0)
2572 return 1;
2574 sz = 0;
2575 for (i = 0; i < 8; i++)
2576 sz = (sz << 8) | compressed[i + 4];
2578 if (*uncompressed != NULL && *uncompressed_size >= sz)
2579 po = *uncompressed;
2580 else
2582 po = (unsigned char *) backtrace_alloc (state, sz, error_callback, data);
2583 if (po == NULL)
2584 return 0;
2587 if (!elf_zlib_inflate_and_verify (compressed + 12, compressed_size - 12,
2588 zdebug_table, po, sz))
2589 return 1;
2591 *uncompressed = po;
2592 *uncompressed_size = sz;
2594 return 1;
2597 /* Uncompress the new compressed debug format, the official standard
2598 ELF approach emitted by --compress-debug-sections=zlib-gabi. The
2599 compressed data is in COMPRESSED / COMPRESSED_SIZE, and the
2600 function writes to *UNCOMPRESSED / *UNCOMPRESSED_SIZE.
2601 ZDEBUG_TABLE is work space as for elf_uncompress_zdebug. Returns 0
2602 on error, 1 on successful decompression or if something goes wrong.
2603 In general we try to carry on, by returning 1, even if we can't
2604 decompress. */
2606 static int
2607 elf_uncompress_chdr (struct backtrace_state *state,
2608 const unsigned char *compressed, size_t compressed_size,
2609 uint16_t *zdebug_table,
2610 backtrace_error_callback error_callback, void *data,
2611 unsigned char **uncompressed, size_t *uncompressed_size)
2613 const b_elf_chdr *chdr;
2614 unsigned char *po;
2616 *uncompressed = NULL;
2617 *uncompressed_size = 0;
2619 /* The format starts with an ELF compression header. */
2620 if (compressed_size < sizeof (b_elf_chdr))
2621 return 1;
2623 chdr = (const b_elf_chdr *) compressed;
2625 if (chdr->ch_type != ELFCOMPRESS_ZLIB)
2627 /* Unsupported compression algorithm. */
2628 return 1;
2631 if (*uncompressed != NULL && *uncompressed_size >= chdr->ch_size)
2632 po = *uncompressed;
2633 else
2635 po = (unsigned char *) backtrace_alloc (state, chdr->ch_size,
2636 error_callback, data);
2637 if (po == NULL)
2638 return 0;
2641 if (!elf_zlib_inflate_and_verify (compressed + sizeof (b_elf_chdr),
2642 compressed_size - sizeof (b_elf_chdr),
2643 zdebug_table, po, chdr->ch_size))
2644 return 1;
2646 *uncompressed = po;
2647 *uncompressed_size = chdr->ch_size;
2649 return 1;
2652 /* This function is a hook for testing the zlib support. It is only
2653 used by tests. */
2656 backtrace_uncompress_zdebug (struct backtrace_state *state,
2657 const unsigned char *compressed,
2658 size_t compressed_size,
2659 backtrace_error_callback error_callback,
2660 void *data, unsigned char **uncompressed,
2661 size_t *uncompressed_size)
2663 uint16_t *zdebug_table;
2664 int ret;
2666 zdebug_table = ((uint16_t *) backtrace_alloc (state, ZDEBUG_TABLE_SIZE,
2667 error_callback, data));
2668 if (zdebug_table == NULL)
2669 return 0;
2670 ret = elf_uncompress_zdebug (state, compressed, compressed_size,
2671 zdebug_table, error_callback, data,
2672 uncompressed, uncompressed_size);
2673 backtrace_free (state, zdebug_table, ZDEBUG_TABLE_SIZE,
2674 error_callback, data);
2675 return ret;
2678 /* Number of LZMA states. */
2679 #define LZMA_STATES (12)
2681 /* Number of LZMA position states. The pb value of the property byte
2682 is the number of bits to include in these states, and the maximum
2683 value of pb is 4. */
2684 #define LZMA_POS_STATES (16)
2686 /* Number of LZMA distance states. These are used match distances
2687 with a short match length: up to 4 bytes. */
2688 #define LZMA_DIST_STATES (4)
2690 /* Number of LZMA distance slots. LZMA uses six bits to encode larger
2691 match lengths, so 1 << 6 possible probabilities. */
2692 #define LZMA_DIST_SLOTS (64)
2694 /* LZMA distances 0 to 3 are encoded directly, larger values use a
2695 probability model. */
2696 #define LZMA_DIST_MODEL_START (4)
2698 /* The LZMA probability model ends at 14. */
2699 #define LZMA_DIST_MODEL_END (14)
2701 /* LZMA distance slots for distances less than 127. */
2702 #define LZMA_FULL_DISTANCES (128)
2704 /* LZMA uses four alignment bits. */
2705 #define LZMA_ALIGN_SIZE (16)
2707 /* LZMA match length is encoded with 4, 5, or 10 bits, some of which
2708 are already known. */
2709 #define LZMA_LEN_LOW_SYMBOLS (8)
2710 #define LZMA_LEN_MID_SYMBOLS (8)
2711 #define LZMA_LEN_HIGH_SYMBOLS (256)
2713 /* LZMA literal encoding. */
2714 #define LZMA_LITERAL_CODERS_MAX (16)
2715 #define LZMA_LITERAL_CODER_SIZE (0x300)
2717 /* LZMA is based on a large set of probabilities, each managed
2718 independently. Each probability is an 11 bit number that we store
2719 in a uint16_t. We use a single large array of probabilities. */
2721 /* Lengths of entries in the LZMA probabilities array. The names used
2722 here are copied from the Linux kernel implementation. */
2724 #define LZMA_PROB_IS_MATCH_LEN (LZMA_STATES * LZMA_POS_STATES)
2725 #define LZMA_PROB_IS_REP_LEN LZMA_STATES
2726 #define LZMA_PROB_IS_REP0_LEN LZMA_STATES
2727 #define LZMA_PROB_IS_REP1_LEN LZMA_STATES
2728 #define LZMA_PROB_IS_REP2_LEN LZMA_STATES
2729 #define LZMA_PROB_IS_REP0_LONG_LEN (LZMA_STATES * LZMA_POS_STATES)
2730 #define LZMA_PROB_DIST_SLOT_LEN (LZMA_DIST_STATES * LZMA_DIST_SLOTS)
2731 #define LZMA_PROB_DIST_SPECIAL_LEN (LZMA_FULL_DISTANCES - LZMA_DIST_MODEL_END)
2732 #define LZMA_PROB_DIST_ALIGN_LEN LZMA_ALIGN_SIZE
2733 #define LZMA_PROB_MATCH_LEN_CHOICE_LEN 1
2734 #define LZMA_PROB_MATCH_LEN_CHOICE2_LEN 1
2735 #define LZMA_PROB_MATCH_LEN_LOW_LEN (LZMA_POS_STATES * LZMA_LEN_LOW_SYMBOLS)
2736 #define LZMA_PROB_MATCH_LEN_MID_LEN (LZMA_POS_STATES * LZMA_LEN_MID_SYMBOLS)
2737 #define LZMA_PROB_MATCH_LEN_HIGH_LEN LZMA_LEN_HIGH_SYMBOLS
2738 #define LZMA_PROB_REP_LEN_CHOICE_LEN 1
2739 #define LZMA_PROB_REP_LEN_CHOICE2_LEN 1
2740 #define LZMA_PROB_REP_LEN_LOW_LEN (LZMA_POS_STATES * LZMA_LEN_LOW_SYMBOLS)
2741 #define LZMA_PROB_REP_LEN_MID_LEN (LZMA_POS_STATES * LZMA_LEN_MID_SYMBOLS)
2742 #define LZMA_PROB_REP_LEN_HIGH_LEN LZMA_LEN_HIGH_SYMBOLS
2743 #define LZMA_PROB_LITERAL_LEN \
2744 (LZMA_LITERAL_CODERS_MAX * LZMA_LITERAL_CODER_SIZE)
2746 /* Offsets into the LZMA probabilities array. This is mechanically
2747 generated from the above lengths. */
2749 #define LZMA_PROB_IS_MATCH_OFFSET 0
2750 #define LZMA_PROB_IS_REP_OFFSET \
2751 (LZMA_PROB_IS_MATCH_OFFSET + LZMA_PROB_IS_MATCH_LEN)
2752 #define LZMA_PROB_IS_REP0_OFFSET \
2753 (LZMA_PROB_IS_REP_OFFSET + LZMA_PROB_IS_REP_LEN)
2754 #define LZMA_PROB_IS_REP1_OFFSET \
2755 (LZMA_PROB_IS_REP0_OFFSET + LZMA_PROB_IS_REP0_LEN)
2756 #define LZMA_PROB_IS_REP2_OFFSET \
2757 (LZMA_PROB_IS_REP1_OFFSET + LZMA_PROB_IS_REP1_LEN)
2758 #define LZMA_PROB_IS_REP0_LONG_OFFSET \
2759 (LZMA_PROB_IS_REP2_OFFSET + LZMA_PROB_IS_REP2_LEN)
2760 #define LZMA_PROB_DIST_SLOT_OFFSET \
2761 (LZMA_PROB_IS_REP0_LONG_OFFSET + LZMA_PROB_IS_REP0_LONG_LEN)
2762 #define LZMA_PROB_DIST_SPECIAL_OFFSET \
2763 (LZMA_PROB_DIST_SLOT_OFFSET + LZMA_PROB_DIST_SLOT_LEN)
2764 #define LZMA_PROB_DIST_ALIGN_OFFSET \
2765 (LZMA_PROB_DIST_SPECIAL_OFFSET + LZMA_PROB_DIST_SPECIAL_LEN)
2766 #define LZMA_PROB_MATCH_LEN_CHOICE_OFFSET \
2767 (LZMA_PROB_DIST_ALIGN_OFFSET + LZMA_PROB_DIST_ALIGN_LEN)
2768 #define LZMA_PROB_MATCH_LEN_CHOICE2_OFFSET \
2769 (LZMA_PROB_MATCH_LEN_CHOICE_OFFSET + LZMA_PROB_MATCH_LEN_CHOICE_LEN)
2770 #define LZMA_PROB_MATCH_LEN_LOW_OFFSET \
2771 (LZMA_PROB_MATCH_LEN_CHOICE2_OFFSET + LZMA_PROB_MATCH_LEN_CHOICE2_LEN)
2772 #define LZMA_PROB_MATCH_LEN_MID_OFFSET \
2773 (LZMA_PROB_MATCH_LEN_LOW_OFFSET + LZMA_PROB_MATCH_LEN_LOW_LEN)
2774 #define LZMA_PROB_MATCH_LEN_HIGH_OFFSET \
2775 (LZMA_PROB_MATCH_LEN_MID_OFFSET + LZMA_PROB_MATCH_LEN_MID_LEN)
2776 #define LZMA_PROB_REP_LEN_CHOICE_OFFSET \
2777 (LZMA_PROB_MATCH_LEN_HIGH_OFFSET + LZMA_PROB_MATCH_LEN_HIGH_LEN)
2778 #define LZMA_PROB_REP_LEN_CHOICE2_OFFSET \
2779 (LZMA_PROB_REP_LEN_CHOICE_OFFSET + LZMA_PROB_REP_LEN_CHOICE_LEN)
2780 #define LZMA_PROB_REP_LEN_LOW_OFFSET \
2781 (LZMA_PROB_REP_LEN_CHOICE2_OFFSET + LZMA_PROB_REP_LEN_CHOICE2_LEN)
2782 #define LZMA_PROB_REP_LEN_MID_OFFSET \
2783 (LZMA_PROB_REP_LEN_LOW_OFFSET + LZMA_PROB_REP_LEN_LOW_LEN)
2784 #define LZMA_PROB_REP_LEN_HIGH_OFFSET \
2785 (LZMA_PROB_REP_LEN_MID_OFFSET + LZMA_PROB_REP_LEN_MID_LEN)
2786 #define LZMA_PROB_LITERAL_OFFSET \
2787 (LZMA_PROB_REP_LEN_HIGH_OFFSET + LZMA_PROB_REP_LEN_HIGH_LEN)
2789 #define LZMA_PROB_TOTAL_COUNT \
2790 (LZMA_PROB_LITERAL_OFFSET + LZMA_PROB_LITERAL_LEN)
2792 /* Check that the number of LZMA probabilities is the same as the
2793 Linux kernel implementation. */
2795 #if LZMA_PROB_TOTAL_COUNT != 1846 + (1 << 4) * 0x300
2796 #error Wrong number of LZMA probabilities
2797 #endif
2799 /* Expressions for the offset in the LZMA probabilities array of a
2800 specific probability. */
2802 #define LZMA_IS_MATCH(state, pos) \
2803 (LZMA_PROB_IS_MATCH_OFFSET + (state) * LZMA_POS_STATES + (pos))
2804 #define LZMA_IS_REP(state) \
2805 (LZMA_PROB_IS_REP_OFFSET + (state))
2806 #define LZMA_IS_REP0(state) \
2807 (LZMA_PROB_IS_REP0_OFFSET + (state))
2808 #define LZMA_IS_REP1(state) \
2809 (LZMA_PROB_IS_REP1_OFFSET + (state))
2810 #define LZMA_IS_REP2(state) \
2811 (LZMA_PROB_IS_REP2_OFFSET + (state))
2812 #define LZMA_IS_REP0_LONG(state, pos) \
2813 (LZMA_PROB_IS_REP0_LONG_OFFSET + (state) * LZMA_POS_STATES + (pos))
2814 #define LZMA_DIST_SLOT(dist, slot) \
2815 (LZMA_PROB_DIST_SLOT_OFFSET + (dist) * LZMA_DIST_SLOTS + (slot))
2816 #define LZMA_DIST_SPECIAL(dist) \
2817 (LZMA_PROB_DIST_SPECIAL_OFFSET + (dist))
2818 #define LZMA_DIST_ALIGN(dist) \
2819 (LZMA_PROB_DIST_ALIGN_OFFSET + (dist))
2820 #define LZMA_MATCH_LEN_CHOICE \
2821 LZMA_PROB_MATCH_LEN_CHOICE_OFFSET
2822 #define LZMA_MATCH_LEN_CHOICE2 \
2823 LZMA_PROB_MATCH_LEN_CHOICE2_OFFSET
2824 #define LZMA_MATCH_LEN_LOW(pos, sym) \
2825 (LZMA_PROB_MATCH_LEN_LOW_OFFSET + (pos) * LZMA_LEN_LOW_SYMBOLS + (sym))
2826 #define LZMA_MATCH_LEN_MID(pos, sym) \
2827 (LZMA_PROB_MATCH_LEN_MID_OFFSET + (pos) * LZMA_LEN_MID_SYMBOLS + (sym))
2828 #define LZMA_MATCH_LEN_HIGH(sym) \
2829 (LZMA_PROB_MATCH_LEN_HIGH_OFFSET + (sym))
2830 #define LZMA_REP_LEN_CHOICE \
2831 LZMA_PROB_REP_LEN_CHOICE_OFFSET
2832 #define LZMA_REP_LEN_CHOICE2 \
2833 LZMA_PROB_REP_LEN_CHOICE2_OFFSET
2834 #define LZMA_REP_LEN_LOW(pos, sym) \
2835 (LZMA_PROB_REP_LEN_LOW_OFFSET + (pos) * LZMA_LEN_LOW_SYMBOLS + (sym))
2836 #define LZMA_REP_LEN_MID(pos, sym) \
2837 (LZMA_PROB_REP_LEN_MID_OFFSET + (pos) * LZMA_LEN_MID_SYMBOLS + (sym))
2838 #define LZMA_REP_LEN_HIGH(sym) \
2839 (LZMA_PROB_REP_LEN_HIGH_OFFSET + (sym))
2840 #define LZMA_LITERAL(code, size) \
2841 (LZMA_PROB_LITERAL_OFFSET + (code) * LZMA_LITERAL_CODER_SIZE + (size))
2843 /* Read an LZMA varint from BUF, reading and updating *POFFSET,
2844 setting *VAL. Returns 0 on error, 1 on success. */
2846 static int
2847 elf_lzma_varint (const unsigned char *compressed, size_t compressed_size,
2848 size_t *poffset, uint64_t *val)
2850 size_t off;
2851 int i;
2852 uint64_t v;
2853 unsigned char b;
2855 off = *poffset;
2856 i = 0;
2857 v = 0;
2858 while (1)
2860 if (unlikely (off >= compressed_size))
2862 elf_uncompress_failed ();
2863 return 0;
2865 b = compressed[off];
2866 v |= (b & 0x7f) << (i * 7);
2867 ++off;
2868 if ((b & 0x80) == 0)
2870 *poffset = off;
2871 *val = v;
2872 return 1;
2874 ++i;
2875 if (unlikely (i >= 9))
2877 elf_uncompress_failed ();
2878 return 0;
2883 /* Normalize the LZMA range decoder, pulling in an extra input byte if
2884 needed. */
2886 static void
2887 elf_lzma_range_normalize (const unsigned char *compressed,
2888 size_t compressed_size, size_t *poffset,
2889 uint32_t *prange, uint32_t *pcode)
2891 if (*prange < (1U << 24))
2893 if (unlikely (*poffset >= compressed_size))
2895 /* We assume this will be caught elsewhere. */
2896 elf_uncompress_failed ();
2897 return;
2899 *prange <<= 8;
2900 *pcode <<= 8;
2901 *pcode += compressed[*poffset];
2902 ++*poffset;
2906 /* Read and return a single bit from the LZMA stream, reading and
2907 updating *PROB. Each bit comes from the range coder. */
2909 static int
2910 elf_lzma_bit (const unsigned char *compressed, size_t compressed_size,
2911 uint16_t *prob, size_t *poffset, uint32_t *prange,
2912 uint32_t *pcode)
2914 uint32_t bound;
2916 elf_lzma_range_normalize (compressed, compressed_size, poffset,
2917 prange, pcode);
2918 bound = (*prange >> 11) * (uint32_t) *prob;
2919 if (*pcode < bound)
2921 *prange = bound;
2922 *prob += ((1U << 11) - *prob) >> 5;
2923 return 0;
2925 else
2927 *prange -= bound;
2928 *pcode -= bound;
2929 *prob -= *prob >> 5;
2930 return 1;
2934 /* Read an integer of size BITS from the LZMA stream, most significant
2935 bit first. The bits are predicted using PROBS. */
2937 static uint32_t
2938 elf_lzma_integer (const unsigned char *compressed, size_t compressed_size,
2939 uint16_t *probs, uint32_t bits, size_t *poffset,
2940 uint32_t *prange, uint32_t *pcode)
2942 uint32_t sym;
2943 uint32_t i;
2945 sym = 1;
2946 for (i = 0; i < bits; i++)
2948 int bit;
2950 bit = elf_lzma_bit (compressed, compressed_size, probs + sym, poffset,
2951 prange, pcode);
2952 sym <<= 1;
2953 sym += bit;
2955 return sym - (1 << bits);
2958 /* Read an integer of size BITS from the LZMA stream, least
2959 significant bit first. The bits are predicted using PROBS. */
2961 static uint32_t
2962 elf_lzma_reverse_integer (const unsigned char *compressed,
2963 size_t compressed_size, uint16_t *probs,
2964 uint32_t bits, size_t *poffset, uint32_t *prange,
2965 uint32_t *pcode)
2967 uint32_t sym;
2968 uint32_t val;
2969 uint32_t i;
2971 sym = 1;
2972 val = 0;
2973 for (i = 0; i < bits; i++)
2975 int bit;
2977 bit = elf_lzma_bit (compressed, compressed_size, probs + sym, poffset,
2978 prange, pcode);
2979 sym <<= 1;
2980 sym += bit;
2981 val += bit << i;
2983 return val;
2986 /* Read a length from the LZMA stream. IS_REP picks either LZMA_MATCH
2987 or LZMA_REP probabilities. */
2989 static uint32_t
2990 elf_lzma_len (const unsigned char *compressed, size_t compressed_size,
2991 uint16_t *probs, int is_rep, unsigned int pos_state,
2992 size_t *poffset, uint32_t *prange, uint32_t *pcode)
2994 uint16_t *probs_choice;
2995 uint16_t *probs_sym;
2996 uint32_t bits;
2997 uint32_t len;
2999 probs_choice = probs + (is_rep
3000 ? LZMA_REP_LEN_CHOICE
3001 : LZMA_MATCH_LEN_CHOICE);
3002 if (elf_lzma_bit (compressed, compressed_size, probs_choice, poffset,
3003 prange, pcode))
3005 probs_choice = probs + (is_rep
3006 ? LZMA_REP_LEN_CHOICE2
3007 : LZMA_MATCH_LEN_CHOICE2);
3008 if (elf_lzma_bit (compressed, compressed_size, probs_choice,
3009 poffset, prange, pcode))
3011 probs_sym = probs + (is_rep
3012 ? LZMA_REP_LEN_HIGH (0)
3013 : LZMA_MATCH_LEN_HIGH (0));
3014 bits = 8;
3015 len = 2 + 8 + 8;
3017 else
3019 probs_sym = probs + (is_rep
3020 ? LZMA_REP_LEN_MID (pos_state, 0)
3021 : LZMA_MATCH_LEN_MID (pos_state, 0));
3022 bits = 3;
3023 len = 2 + 8;
3026 else
3028 probs_sym = probs + (is_rep
3029 ? LZMA_REP_LEN_LOW (pos_state, 0)
3030 : LZMA_MATCH_LEN_LOW (pos_state, 0));
3031 bits = 3;
3032 len = 2;
3035 len += elf_lzma_integer (compressed, compressed_size, probs_sym, bits,
3036 poffset, prange, pcode);
3037 return len;
3040 /* Uncompress one LZMA block from a minidebug file. The compressed
3041 data is at COMPRESSED + *POFFSET. Update *POFFSET. Store the data
3042 into the memory at UNCOMPRESSED, size UNCOMPRESSED_SIZE. CHECK is
3043 the stream flag from the xz header. Return 1 on successful
3044 decompression. */
3046 static int
3047 elf_uncompress_lzma_block (const unsigned char *compressed,
3048 size_t compressed_size, unsigned char check,
3049 uint16_t *probs, unsigned char *uncompressed,
3050 size_t uncompressed_size, size_t *poffset)
3052 size_t off;
3053 size_t block_header_offset;
3054 size_t block_header_size;
3055 unsigned char block_flags;
3056 uint64_t header_compressed_size;
3057 uint64_t header_uncompressed_size;
3058 unsigned char lzma2_properties;
3059 uint32_t computed_crc;
3060 uint32_t stream_crc;
3061 size_t uncompressed_offset;
3062 size_t dict_start_offset;
3063 unsigned int lc;
3064 unsigned int lp;
3065 unsigned int pb;
3066 uint32_t range;
3067 uint32_t code;
3068 uint32_t lstate;
3069 uint32_t dist[4];
3071 off = *poffset;
3072 block_header_offset = off;
3074 /* Block header size is a single byte. */
3075 if (unlikely (off >= compressed_size))
3077 elf_uncompress_failed ();
3078 return 0;
3080 block_header_size = (compressed[off] + 1) * 4;
3081 if (unlikely (off + block_header_size > compressed_size))
3083 elf_uncompress_failed ();
3084 return 0;
3087 /* Block flags. */
3088 block_flags = compressed[off + 1];
3089 if (unlikely ((block_flags & 0x3c) != 0))
3091 elf_uncompress_failed ();
3092 return 0;
3095 off += 2;
3097 /* Optional compressed size. */
3098 header_compressed_size = 0;
3099 if ((block_flags & 0x40) != 0)
3101 *poffset = off;
3102 if (!elf_lzma_varint (compressed, compressed_size, poffset,
3103 &header_compressed_size))
3104 return 0;
3105 off = *poffset;
3108 /* Optional uncompressed size. */
3109 header_uncompressed_size = 0;
3110 if ((block_flags & 0x80) != 0)
3112 *poffset = off;
3113 if (!elf_lzma_varint (compressed, compressed_size, poffset,
3114 &header_uncompressed_size))
3115 return 0;
3116 off = *poffset;
3119 /* The recipe for creating a minidebug file is to run the xz program
3120 with no arguments, so we expect exactly one filter: lzma2. */
3122 if (unlikely ((block_flags & 0x3) != 0))
3124 elf_uncompress_failed ();
3125 return 0;
3128 if (unlikely (off + 2 >= block_header_offset + block_header_size))
3130 elf_uncompress_failed ();
3131 return 0;
3134 /* The filter ID for LZMA2 is 0x21. */
3135 if (unlikely (compressed[off] != 0x21))
3137 elf_uncompress_failed ();
3138 return 0;
3140 ++off;
3142 /* The size of the filter properties for LZMA2 is 1. */
3143 if (unlikely (compressed[off] != 1))
3145 elf_uncompress_failed ();
3146 return 0;
3148 ++off;
3150 lzma2_properties = compressed[off];
3151 ++off;
3153 if (unlikely (lzma2_properties > 40))
3155 elf_uncompress_failed ();
3156 return 0;
3159 /* The properties describe the dictionary size, but we don't care
3160 what that is. */
3162 /* Block header padding. */
3163 if (unlikely (off + 4 > compressed_size))
3165 elf_uncompress_failed ();
3166 return 0;
3169 off = (off + 3) &~ (size_t) 3;
3171 if (unlikely (off + 4 > compressed_size))
3173 elf_uncompress_failed ();
3174 return 0;
3177 /* Block header CRC. */
3178 computed_crc = elf_crc32 (0, compressed + block_header_offset,
3179 block_header_size - 4);
3180 stream_crc = ((uint32_t)compressed[off]
3181 | ((uint32_t)compressed[off + 1] << 8)
3182 | ((uint32_t)compressed[off + 2] << 16)
3183 | ((uint32_t)compressed[off + 3] << 24));
3184 if (unlikely (computed_crc != stream_crc))
3186 elf_uncompress_failed ();
3187 return 0;
3189 off += 4;
3191 /* Read a sequence of LZMA2 packets. */
3193 uncompressed_offset = 0;
3194 dict_start_offset = 0;
3195 lc = 0;
3196 lp = 0;
3197 pb = 0;
3198 lstate = 0;
3199 while (off < compressed_size)
3201 unsigned char control;
3203 range = 0xffffffff;
3204 code = 0;
3206 control = compressed[off];
3207 ++off;
3208 if (unlikely (control == 0))
3210 /* End of packets. */
3211 break;
3214 if (control == 1 || control >= 0xe0)
3216 /* Reset dictionary to empty. */
3217 dict_start_offset = uncompressed_offset;
3220 if (control < 0x80)
3222 size_t chunk_size;
3224 /* The only valid values here are 1 or 2. A 1 means to
3225 reset the dictionary (done above). Then we see an
3226 uncompressed chunk. */
3228 if (unlikely (control > 2))
3230 elf_uncompress_failed ();
3231 return 0;
3234 /* An uncompressed chunk is a two byte size followed by
3235 data. */
3237 if (unlikely (off + 2 > compressed_size))
3239 elf_uncompress_failed ();
3240 return 0;
3243 chunk_size = compressed[off] << 8;
3244 chunk_size += compressed[off + 1];
3245 ++chunk_size;
3247 off += 2;
3249 if (unlikely (off + chunk_size > compressed_size))
3251 elf_uncompress_failed ();
3252 return 0;
3254 if (unlikely (uncompressed_offset + chunk_size > uncompressed_size))
3256 elf_uncompress_failed ();
3257 return 0;
3260 memcpy (uncompressed + uncompressed_offset, compressed + off,
3261 chunk_size);
3262 uncompressed_offset += chunk_size;
3263 off += chunk_size;
3265 else
3267 size_t uncompressed_chunk_start;
3268 size_t uncompressed_chunk_size;
3269 size_t compressed_chunk_size;
3270 size_t limit;
3272 /* An LZMA chunk. This starts with an uncompressed size and
3273 a compressed size. */
3275 if (unlikely (off + 4 >= compressed_size))
3277 elf_uncompress_failed ();
3278 return 0;
3281 uncompressed_chunk_start = uncompressed_offset;
3283 uncompressed_chunk_size = (control & 0x1f) << 16;
3284 uncompressed_chunk_size += compressed[off] << 8;
3285 uncompressed_chunk_size += compressed[off + 1];
3286 ++uncompressed_chunk_size;
3288 compressed_chunk_size = compressed[off + 2] << 8;
3289 compressed_chunk_size += compressed[off + 3];
3290 ++compressed_chunk_size;
3292 off += 4;
3294 /* Bit 7 (0x80) is set.
3295 Bits 6 and 5 (0x40 and 0x20) are as follows:
3296 0: don't reset anything
3297 1: reset state
3298 2: reset state, read properties
3299 3: reset state, read properties, reset dictionary (done above) */
3301 if (control >= 0xc0)
3303 unsigned char props;
3305 /* Bit 6 is set, read properties. */
3307 if (unlikely (off >= compressed_size))
3309 elf_uncompress_failed ();
3310 return 0;
3312 props = compressed[off];
3313 ++off;
3314 if (unlikely (props > (4 * 5 + 4) * 9 + 8))
3316 elf_uncompress_failed ();
3317 return 0;
3319 pb = 0;
3320 while (props >= 9 * 5)
3322 props -= 9 * 5;
3323 ++pb;
3325 lp = 0;
3326 while (props > 9)
3328 props -= 9;
3329 ++lp;
3331 lc = props;
3332 if (unlikely (lc + lp > 4))
3334 elf_uncompress_failed ();
3335 return 0;
3339 if (control >= 0xa0)
3341 size_t i;
3343 /* Bit 5 or 6 is set, reset LZMA state. */
3345 lstate = 0;
3346 memset (&dist, 0, sizeof dist);
3347 for (i = 0; i < LZMA_PROB_TOTAL_COUNT; i++)
3348 probs[i] = 1 << 10;
3349 range = 0xffffffff;
3350 code = 0;
3353 /* Read the range code. */
3355 if (unlikely (off + 5 > compressed_size))
3357 elf_uncompress_failed ();
3358 return 0;
3361 /* The byte at compressed[off] is ignored for some
3362 reason. */
3364 code = ((compressed[off + 1] << 24)
3365 + (compressed[off + 2] << 16)
3366 + (compressed[off + 3] << 8)
3367 + compressed[off + 4]);
3368 off += 5;
3370 /* This is the main LZMA decode loop. */
3372 limit = off + compressed_chunk_size;
3373 *poffset = off;
3374 while (*poffset < limit)
3376 unsigned int pos_state;
3378 if (unlikely (uncompressed_offset
3379 == (uncompressed_chunk_start
3380 + uncompressed_chunk_size)))
3382 /* We've decompressed all the expected bytes. */
3383 break;
3386 pos_state = ((uncompressed_offset - dict_start_offset)
3387 & ((1 << pb) - 1));
3389 if (elf_lzma_bit (compressed, compressed_size,
3390 probs + LZMA_IS_MATCH (lstate, pos_state),
3391 poffset, &range, &code))
3393 uint32_t len;
3395 if (elf_lzma_bit (compressed, compressed_size,
3396 probs + LZMA_IS_REP (lstate),
3397 poffset, &range, &code))
3399 int short_rep;
3400 uint32_t next_dist;
3402 /* Repeated match. */
3404 short_rep = 0;
3405 if (elf_lzma_bit (compressed, compressed_size,
3406 probs + LZMA_IS_REP0 (lstate),
3407 poffset, &range, &code))
3409 if (elf_lzma_bit (compressed, compressed_size,
3410 probs + LZMA_IS_REP1 (lstate),
3411 poffset, &range, &code))
3413 if (elf_lzma_bit (compressed, compressed_size,
3414 probs + LZMA_IS_REP2 (lstate),
3415 poffset, &range, &code))
3417 next_dist = dist[3];
3418 dist[3] = dist[2];
3420 else
3422 next_dist = dist[2];
3424 dist[2] = dist[1];
3426 else
3428 next_dist = dist[1];
3431 dist[1] = dist[0];
3432 dist[0] = next_dist;
3434 else
3436 if (!elf_lzma_bit (compressed, compressed_size,
3437 (probs
3438 + LZMA_IS_REP0_LONG (lstate,
3439 pos_state)),
3440 poffset, &range, &code))
3441 short_rep = 1;
3444 if (lstate < 7)
3445 lstate = short_rep ? 9 : 8;
3446 else
3447 lstate = 11;
3449 if (short_rep)
3450 len = 1;
3451 else
3452 len = elf_lzma_len (compressed, compressed_size,
3453 probs, 1, pos_state, poffset,
3454 &range, &code);
3456 else
3458 uint32_t dist_state;
3459 uint32_t dist_slot;
3460 uint16_t *probs_dist;
3462 /* Match. */
3464 if (lstate < 7)
3465 lstate = 7;
3466 else
3467 lstate = 10;
3468 dist[3] = dist[2];
3469 dist[2] = dist[1];
3470 dist[1] = dist[0];
3471 len = elf_lzma_len (compressed, compressed_size,
3472 probs, 0, pos_state, poffset,
3473 &range, &code);
3475 if (len < 4 + 2)
3476 dist_state = len - 2;
3477 else
3478 dist_state = 3;
3479 probs_dist = probs + LZMA_DIST_SLOT (dist_state, 0);
3480 dist_slot = elf_lzma_integer (compressed,
3481 compressed_size,
3482 probs_dist, 6,
3483 poffset, &range,
3484 &code);
3485 if (dist_slot < LZMA_DIST_MODEL_START)
3486 dist[0] = dist_slot;
3487 else
3489 uint32_t limit;
3491 limit = (dist_slot >> 1) - 1;
3492 dist[0] = 2 + (dist_slot & 1);
3493 if (dist_slot < LZMA_DIST_MODEL_END)
3495 dist[0] <<= limit;
3496 probs_dist = (probs
3497 + LZMA_DIST_SPECIAL(dist[0]
3498 - dist_slot
3499 - 1));
3500 dist[0] +=
3501 elf_lzma_reverse_integer (compressed,
3502 compressed_size,
3503 probs_dist,
3504 limit, poffset,
3505 &range, &code);
3507 else
3509 uint32_t dist0;
3510 uint32_t i;
3512 dist0 = dist[0];
3513 for (i = 0; i < limit - 4; i++)
3515 uint32_t mask;
3517 elf_lzma_range_normalize (compressed,
3518 compressed_size,
3519 poffset,
3520 &range, &code);
3521 range >>= 1;
3522 code -= range;
3523 mask = -(code >> 31);
3524 code += range & mask;
3525 dist0 <<= 1;
3526 dist0 += mask + 1;
3528 dist0 <<= 4;
3529 probs_dist = probs + LZMA_DIST_ALIGN (0);
3530 dist0 +=
3531 elf_lzma_reverse_integer (compressed,
3532 compressed_size,
3533 probs_dist, 4,
3534 poffset,
3535 &range, &code);
3536 dist[0] = dist0;
3541 if (unlikely (uncompressed_offset
3542 - dict_start_offset < dist[0] + 1))
3544 elf_uncompress_failed ();
3545 return 0;
3547 if (unlikely (uncompressed_offset + len > uncompressed_size))
3549 elf_uncompress_failed ();
3550 return 0;
3553 if (dist[0] == 0)
3555 /* A common case, meaning repeat the last
3556 character LEN times. */
3557 memset (uncompressed + uncompressed_offset,
3558 uncompressed[uncompressed_offset - 1],
3559 len);
3560 uncompressed_offset += len;
3562 else if (dist[0] + 1 >= len)
3564 memcpy (uncompressed + uncompressed_offset,
3565 uncompressed + uncompressed_offset - dist[0] - 1,
3566 len);
3567 uncompressed_offset += len;
3569 else
3571 while (len > 0)
3573 uint32_t copy;
3575 copy = len < dist[0] + 1 ? len : dist[0] + 1;
3576 memcpy (uncompressed + uncompressed_offset,
3577 (uncompressed + uncompressed_offset
3578 - dist[0] - 1),
3579 copy);
3580 len -= copy;
3581 uncompressed_offset += copy;
3585 else
3587 unsigned char prev;
3588 unsigned char low;
3589 size_t high;
3590 uint16_t *lit_probs;
3591 unsigned int sym;
3593 /* Literal value. */
3595 if (uncompressed_offset > 0)
3596 prev = uncompressed[uncompressed_offset - 1];
3597 else
3598 prev = 0;
3599 low = prev >> (8 - lc);
3600 high = (((uncompressed_offset - dict_start_offset)
3601 & ((1 << lp) - 1))
3602 << lc);
3603 lit_probs = probs + LZMA_LITERAL (low + high, 0);
3604 if (lstate < 7)
3605 sym = elf_lzma_integer (compressed, compressed_size,
3606 lit_probs, 8, poffset, &range,
3607 &code);
3608 else
3610 unsigned int match;
3611 unsigned int bit;
3612 unsigned int match_bit;
3613 unsigned int idx;
3615 sym = 1;
3616 if (uncompressed_offset >= dist[0] + 1)
3617 match = uncompressed[uncompressed_offset - dist[0] - 1];
3618 else
3619 match = 0;
3620 match <<= 1;
3621 bit = 0x100;
3624 match_bit = match & bit;
3625 match <<= 1;
3626 idx = bit + match_bit + sym;
3627 sym <<= 1;
3628 if (elf_lzma_bit (compressed, compressed_size,
3629 lit_probs + idx, poffset,
3630 &range, &code))
3632 ++sym;
3633 bit &= match_bit;
3635 else
3637 bit &= ~ match_bit;
3640 while (sym < 0x100);
3643 if (unlikely (uncompressed_offset >= uncompressed_size))
3645 elf_uncompress_failed ();
3646 return 0;
3649 uncompressed[uncompressed_offset] = (unsigned char) sym;
3650 ++uncompressed_offset;
3651 if (lstate <= 3)
3652 lstate = 0;
3653 else if (lstate <= 9)
3654 lstate -= 3;
3655 else
3656 lstate -= 6;
3660 elf_lzma_range_normalize (compressed, compressed_size, poffset,
3661 &range, &code);
3663 off = *poffset;
3667 /* We have reached the end of the block. Pad to four byte
3668 boundary. */
3669 off = (off + 3) &~ (size_t) 3;
3670 if (unlikely (off > compressed_size))
3672 elf_uncompress_failed ();
3673 return 0;
3676 switch (check)
3678 case 0:
3679 /* No check. */
3680 break;
3682 case 1:
3683 /* CRC32 */
3684 if (unlikely (off + 4 > compressed_size))
3686 elf_uncompress_failed ();
3687 return 0;
3689 computed_crc = elf_crc32 (0, uncompressed, uncompressed_offset);
3690 stream_crc = (compressed[off]
3691 | (compressed[off + 1] << 8)
3692 | (compressed[off + 2] << 16)
3693 | (compressed[off + 3] << 24));
3694 if (computed_crc != stream_crc)
3696 elf_uncompress_failed ();
3697 return 0;
3699 off += 4;
3700 break;
3702 case 4:
3703 /* CRC64. We don't bother computing a CRC64 checksum. */
3704 if (unlikely (off + 8 > compressed_size))
3706 elf_uncompress_failed ();
3707 return 0;
3709 off += 8;
3710 break;
3712 case 10:
3713 /* SHA. We don't bother computing a SHA checksum. */
3714 if (unlikely (off + 32 > compressed_size))
3716 elf_uncompress_failed ();
3717 return 0;
3719 off += 32;
3720 break;
3722 default:
3723 elf_uncompress_failed ();
3724 return 0;
3727 *poffset = off;
3729 return 1;
3732 /* Uncompress LZMA data found in a minidebug file. The minidebug
3733 format is described at
3734 https://sourceware.org/gdb/current/onlinedocs/gdb/MiniDebugInfo.html.
3735 Returns 0 on error, 1 on successful decompression. For this
3736 function we return 0 on failure to decompress, as the calling code
3737 will carry on in that case. */
3739 static int
3740 elf_uncompress_lzma (struct backtrace_state *state,
3741 const unsigned char *compressed, size_t compressed_size,
3742 backtrace_error_callback error_callback, void *data,
3743 unsigned char **uncompressed, size_t *uncompressed_size)
3745 size_t header_size;
3746 size_t footer_size;
3747 unsigned char check;
3748 uint32_t computed_crc;
3749 uint32_t stream_crc;
3750 size_t offset;
3751 size_t index_size;
3752 size_t footer_offset;
3753 size_t index_offset;
3754 uint64_t index_compressed_size;
3755 uint64_t index_uncompressed_size;
3756 unsigned char *mem;
3757 uint16_t *probs;
3758 size_t compressed_block_size;
3760 /* The format starts with a stream header and ends with a stream
3761 footer. */
3762 header_size = 12;
3763 footer_size = 12;
3764 if (unlikely (compressed_size < header_size + footer_size))
3766 elf_uncompress_failed ();
3767 return 0;
3770 /* The stream header starts with a magic string. */
3771 if (unlikely (memcmp (compressed, "\375" "7zXZ\0", 6) != 0))
3773 elf_uncompress_failed ();
3774 return 0;
3777 /* Next come stream flags. The first byte is zero, the second byte
3778 is the check. */
3779 if (unlikely (compressed[6] != 0))
3781 elf_uncompress_failed ();
3782 return 0;
3784 check = compressed[7];
3785 if (unlikely ((check & 0xf8) != 0))
3787 elf_uncompress_failed ();
3788 return 0;
3791 /* Next comes a CRC of the stream flags. */
3792 computed_crc = elf_crc32 (0, compressed + 6, 2);
3793 stream_crc = ((uint32_t)compressed[8]
3794 | ((uint32_t)compressed[9] << 8)
3795 | ((uint32_t)compressed[10] << 16)
3796 | ((uint32_t)compressed[11] << 24));
3797 if (unlikely (computed_crc != stream_crc))
3799 elf_uncompress_failed ();
3800 return 0;
3803 /* Now that we've parsed the header, parse the footer, so that we
3804 can get the uncompressed size. */
3806 /* The footer ends with two magic bytes. */
3808 offset = compressed_size;
3809 if (unlikely (memcmp (compressed + offset - 2, "YZ", 2) != 0))
3811 elf_uncompress_failed ();
3812 return 0;
3814 offset -= 2;
3816 /* Before that are the stream flags, which should be the same as the
3817 flags in the header. */
3818 if (unlikely (compressed[offset - 2] != 0
3819 || compressed[offset - 1] != check))
3821 elf_uncompress_failed ();
3822 return 0;
3824 offset -= 2;
3826 /* Before that is the size of the index field, which precedes the
3827 footer. */
3828 index_size = (compressed[offset - 4]
3829 | (compressed[offset - 3] << 8)
3830 | (compressed[offset - 2] << 16)
3831 | (compressed[offset - 1] << 24));
3832 index_size = (index_size + 1) * 4;
3833 offset -= 4;
3835 /* Before that is a footer CRC. */
3836 computed_crc = elf_crc32 (0, compressed + offset, 6);
3837 stream_crc = ((uint32_t)compressed[offset - 4]
3838 | ((uint32_t)compressed[offset - 3] << 8)
3839 | ((uint32_t)compressed[offset - 2] << 16)
3840 | ((uint32_t)compressed[offset - 1] << 24));
3841 if (unlikely (computed_crc != stream_crc))
3843 elf_uncompress_failed ();
3844 return 0;
3846 offset -= 4;
3848 /* The index comes just before the footer. */
3849 if (unlikely (offset < index_size + header_size))
3851 elf_uncompress_failed ();
3852 return 0;
3855 footer_offset = offset;
3856 offset -= index_size;
3857 index_offset = offset;
3859 /* The index starts with a zero byte. */
3860 if (unlikely (compressed[offset] != 0))
3862 elf_uncompress_failed ();
3863 return 0;
3865 ++offset;
3867 /* Next is the number of blocks. We expect zero blocks for an empty
3868 stream, and otherwise a single block. */
3869 if (unlikely (compressed[offset] == 0))
3871 *uncompressed = NULL;
3872 *uncompressed_size = 0;
3873 return 1;
3875 if (unlikely (compressed[offset] != 1))
3877 elf_uncompress_failed ();
3878 return 0;
3880 ++offset;
3882 /* Next is the compressed size and the uncompressed size. */
3883 if (!elf_lzma_varint (compressed, compressed_size, &offset,
3884 &index_compressed_size))
3885 return 0;
3886 if (!elf_lzma_varint (compressed, compressed_size, &offset,
3887 &index_uncompressed_size))
3888 return 0;
3890 /* Pad to a four byte boundary. */
3891 offset = (offset + 3) &~ (size_t) 3;
3893 /* Next is a CRC of the index. */
3894 computed_crc = elf_crc32 (0, compressed + index_offset,
3895 offset - index_offset);
3896 stream_crc = ((uint32_t)compressed[offset]
3897 | ((uint32_t)compressed[offset + 1] << 8)
3898 | ((uint32_t)compressed[offset + 2] << 16)
3899 | ((uint32_t)compressed[offset + 3] << 24));
3900 if (unlikely (computed_crc != stream_crc))
3902 elf_uncompress_failed ();
3903 return 0;
3905 offset += 4;
3907 /* We should now be back at the footer. */
3908 if (unlikely (offset != footer_offset))
3910 elf_uncompress_failed ();
3911 return 0;
3914 /* Allocate space to hold the uncompressed data. If we succeed in
3915 uncompressing the LZMA data, we never free this memory. */
3916 mem = (unsigned char *) backtrace_alloc (state, index_uncompressed_size,
3917 error_callback, data);
3918 if (unlikely (mem == NULL))
3919 return 0;
3920 *uncompressed = mem;
3921 *uncompressed_size = index_uncompressed_size;
3923 /* Allocate space for probabilities. */
3924 probs = ((uint16_t *)
3925 backtrace_alloc (state,
3926 LZMA_PROB_TOTAL_COUNT * sizeof (uint16_t),
3927 error_callback, data));
3928 if (unlikely (probs == NULL))
3930 backtrace_free (state, mem, index_uncompressed_size, error_callback,
3931 data);
3932 return 0;
3935 /* Uncompress the block, which follows the header. */
3936 offset = 12;
3937 if (!elf_uncompress_lzma_block (compressed, compressed_size, check, probs,
3938 mem, index_uncompressed_size, &offset))
3940 backtrace_free (state, mem, index_uncompressed_size, error_callback,
3941 data);
3942 return 0;
3945 compressed_block_size = offset - 12;
3946 if (unlikely (compressed_block_size
3947 != ((index_compressed_size + 3) &~ (size_t) 3)))
3949 elf_uncompress_failed ();
3950 backtrace_free (state, mem, index_uncompressed_size, error_callback,
3951 data);
3952 return 0;
3955 offset = (offset + 3) &~ (size_t) 3;
3956 if (unlikely (offset != index_offset))
3958 elf_uncompress_failed ();
3959 backtrace_free (state, mem, index_uncompressed_size, error_callback,
3960 data);
3961 return 0;
3964 return 1;
3967 /* This function is a hook for testing the LZMA support. It is only
3968 used by tests. */
3971 backtrace_uncompress_lzma (struct backtrace_state *state,
3972 const unsigned char *compressed,
3973 size_t compressed_size,
3974 backtrace_error_callback error_callback,
3975 void *data, unsigned char **uncompressed,
3976 size_t *uncompressed_size)
3978 return elf_uncompress_lzma (state, compressed, compressed_size,
3979 error_callback, data, uncompressed,
3980 uncompressed_size);
3983 /* Add the backtrace data for one ELF file. Returns 1 on success,
3984 0 on failure (in both cases descriptor is closed) or -1 if exe
3985 is non-zero and the ELF file is ET_DYN, which tells the caller that
3986 elf_add will need to be called on the descriptor again after
3987 base_address is determined. */
3989 static int
3990 elf_add (struct backtrace_state *state, const char *filename, int descriptor,
3991 const unsigned char *memory, size_t memory_size,
3992 uintptr_t base_address, backtrace_error_callback error_callback,
3993 void *data, fileline *fileline_fn, int *found_sym, int *found_dwarf,
3994 struct dwarf_data **fileline_entry, int exe, int debuginfo,
3995 const char *with_buildid_data, uint32_t with_buildid_size)
3997 struct elf_view ehdr_view;
3998 b_elf_ehdr ehdr;
3999 off_t shoff;
4000 unsigned int shnum;
4001 unsigned int shstrndx;
4002 struct elf_view shdrs_view;
4003 int shdrs_view_valid;
4004 const b_elf_shdr *shdrs;
4005 const b_elf_shdr *shstrhdr;
4006 size_t shstr_size;
4007 off_t shstr_off;
4008 struct elf_view names_view;
4009 int names_view_valid;
4010 const char *names;
4011 unsigned int symtab_shndx;
4012 unsigned int dynsym_shndx;
4013 unsigned int i;
4014 struct debug_section_info sections[DEBUG_MAX];
4015 struct debug_section_info zsections[DEBUG_MAX];
4016 struct elf_view symtab_view;
4017 int symtab_view_valid;
4018 struct elf_view strtab_view;
4019 int strtab_view_valid;
4020 struct elf_view buildid_view;
4021 int buildid_view_valid;
4022 const char *buildid_data;
4023 uint32_t buildid_size;
4024 struct elf_view debuglink_view;
4025 int debuglink_view_valid;
4026 const char *debuglink_name;
4027 uint32_t debuglink_crc;
4028 struct elf_view debugaltlink_view;
4029 int debugaltlink_view_valid;
4030 const char *debugaltlink_name;
4031 const char *debugaltlink_buildid_data;
4032 uint32_t debugaltlink_buildid_size;
4033 struct elf_view gnu_debugdata_view;
4034 int gnu_debugdata_view_valid;
4035 size_t gnu_debugdata_size;
4036 unsigned char *gnu_debugdata_uncompressed;
4037 size_t gnu_debugdata_uncompressed_size;
4038 off_t min_offset;
4039 off_t max_offset;
4040 off_t debug_size;
4041 struct elf_view debug_view;
4042 int debug_view_valid;
4043 unsigned int using_debug_view;
4044 uint16_t *zdebug_table;
4045 struct elf_view split_debug_view[DEBUG_MAX];
4046 unsigned char split_debug_view_valid[DEBUG_MAX];
4047 struct elf_ppc64_opd_data opd_data, *opd;
4048 struct dwarf_sections dwarf_sections;
4050 if (!debuginfo)
4052 *found_sym = 0;
4053 *found_dwarf = 0;
4056 shdrs_view_valid = 0;
4057 names_view_valid = 0;
4058 symtab_view_valid = 0;
4059 strtab_view_valid = 0;
4060 buildid_view_valid = 0;
4061 buildid_data = NULL;
4062 buildid_size = 0;
4063 debuglink_view_valid = 0;
4064 debuglink_name = NULL;
4065 debuglink_crc = 0;
4066 debugaltlink_view_valid = 0;
4067 debugaltlink_name = NULL;
4068 debugaltlink_buildid_data = NULL;
4069 debugaltlink_buildid_size = 0;
4070 gnu_debugdata_view_valid = 0;
4071 gnu_debugdata_size = 0;
4072 debug_view_valid = 0;
4073 memset (&split_debug_view_valid[0], 0, sizeof split_debug_view_valid);
4074 opd = NULL;
4076 if (!elf_get_view (state, descriptor, memory, memory_size, 0, sizeof ehdr,
4077 error_callback, data, &ehdr_view))
4078 goto fail;
4080 memcpy (&ehdr, ehdr_view.view.data, sizeof ehdr);
4082 elf_release_view (state, &ehdr_view, error_callback, data);
4084 if (ehdr.e_ident[EI_MAG0] != ELFMAG0
4085 || ehdr.e_ident[EI_MAG1] != ELFMAG1
4086 || ehdr.e_ident[EI_MAG2] != ELFMAG2
4087 || ehdr.e_ident[EI_MAG3] != ELFMAG3)
4089 error_callback (data, "executable file is not ELF", 0);
4090 goto fail;
4092 if (ehdr.e_ident[EI_VERSION] != EV_CURRENT)
4094 error_callback (data, "executable file is unrecognized ELF version", 0);
4095 goto fail;
4098 #if BACKTRACE_ELF_SIZE == 32
4099 #define BACKTRACE_ELFCLASS ELFCLASS32
4100 #else
4101 #define BACKTRACE_ELFCLASS ELFCLASS64
4102 #endif
4104 if (ehdr.e_ident[EI_CLASS] != BACKTRACE_ELFCLASS)
4106 error_callback (data, "executable file is unexpected ELF class", 0);
4107 goto fail;
4110 if (ehdr.e_ident[EI_DATA] != ELFDATA2LSB
4111 && ehdr.e_ident[EI_DATA] != ELFDATA2MSB)
4113 error_callback (data, "executable file has unknown endianness", 0);
4114 goto fail;
4117 /* If the executable is ET_DYN, it is either a PIE, or we are running
4118 directly a shared library with .interp. We need to wait for
4119 dl_iterate_phdr in that case to determine the actual base_address. */
4120 if (exe && ehdr.e_type == ET_DYN)
4121 return -1;
4123 shoff = ehdr.e_shoff;
4124 shnum = ehdr.e_shnum;
4125 shstrndx = ehdr.e_shstrndx;
4127 if ((shnum == 0 || shstrndx == SHN_XINDEX)
4128 && shoff != 0)
4130 struct elf_view shdr_view;
4131 const b_elf_shdr *shdr;
4133 if (!elf_get_view (state, descriptor, memory, memory_size, shoff,
4134 sizeof shdr, error_callback, data, &shdr_view))
4135 goto fail;
4137 shdr = (const b_elf_shdr *) shdr_view.view.data;
4139 if (shnum == 0)
4140 shnum = shdr->sh_size;
4142 if (shstrndx == SHN_XINDEX)
4144 shstrndx = shdr->sh_link;
4146 /* Versions of the GNU binutils between 2.12 and 2.18 did
4147 not handle objects with more than SHN_LORESERVE sections
4148 correctly. All large section indexes were offset by
4149 0x100. There is more information at
4150 http://sourceware.org/bugzilla/show_bug.cgi?id-5900 .
4151 Fortunately these object files are easy to detect, as the
4152 GNU binutils always put the section header string table
4153 near the end of the list of sections. Thus if the
4154 section header string table index is larger than the
4155 number of sections, then we know we have to subtract
4156 0x100 to get the real section index. */
4157 if (shstrndx >= shnum && shstrndx >= SHN_LORESERVE + 0x100)
4158 shstrndx -= 0x100;
4161 elf_release_view (state, &shdr_view, error_callback, data);
4164 if (shnum == 0 || shstrndx == 0)
4165 goto fail;
4167 /* To translate PC to file/line when using DWARF, we need to find
4168 the .debug_info and .debug_line sections. */
4170 /* Read the section headers, skipping the first one. */
4172 if (!elf_get_view (state, descriptor, memory, memory_size,
4173 shoff + sizeof (b_elf_shdr),
4174 (shnum - 1) * sizeof (b_elf_shdr),
4175 error_callback, data, &shdrs_view))
4176 goto fail;
4177 shdrs_view_valid = 1;
4178 shdrs = (const b_elf_shdr *) shdrs_view.view.data;
4180 /* Read the section names. */
4182 shstrhdr = &shdrs[shstrndx - 1];
4183 shstr_size = shstrhdr->sh_size;
4184 shstr_off = shstrhdr->sh_offset;
4186 if (!elf_get_view (state, descriptor, memory, memory_size, shstr_off,
4187 shstrhdr->sh_size, error_callback, data, &names_view))
4188 goto fail;
4189 names_view_valid = 1;
4190 names = (const char *) names_view.view.data;
4192 symtab_shndx = 0;
4193 dynsym_shndx = 0;
4195 memset (sections, 0, sizeof sections);
4196 memset (zsections, 0, sizeof zsections);
4198 /* Look for the symbol table. */
4199 for (i = 1; i < shnum; ++i)
4201 const b_elf_shdr *shdr;
4202 unsigned int sh_name;
4203 const char *name;
4204 int j;
4206 shdr = &shdrs[i - 1];
4208 if (shdr->sh_type == SHT_SYMTAB)
4209 symtab_shndx = i;
4210 else if (shdr->sh_type == SHT_DYNSYM)
4211 dynsym_shndx = i;
4213 sh_name = shdr->sh_name;
4214 if (sh_name >= shstr_size)
4216 error_callback (data, "ELF section name out of range", 0);
4217 goto fail;
4220 name = names + sh_name;
4222 for (j = 0; j < (int) DEBUG_MAX; ++j)
4224 if (strcmp (name, dwarf_section_names[j]) == 0)
4226 sections[j].offset = shdr->sh_offset;
4227 sections[j].size = shdr->sh_size;
4228 sections[j].compressed = (shdr->sh_flags & SHF_COMPRESSED) != 0;
4229 break;
4233 if (name[0] == '.' && name[1] == 'z')
4235 for (j = 0; j < (int) DEBUG_MAX; ++j)
4237 if (strcmp (name + 2, dwarf_section_names[j] + 1) == 0)
4239 zsections[j].offset = shdr->sh_offset;
4240 zsections[j].size = shdr->sh_size;
4241 break;
4246 /* Read the build ID if present. This could check for any
4247 SHT_NOTE section with the right note name and type, but gdb
4248 looks for a specific section name. */
4249 if ((!debuginfo || with_buildid_data != NULL)
4250 && !buildid_view_valid
4251 && strcmp (name, ".note.gnu.build-id") == 0)
4253 const b_elf_note *note;
4255 if (!elf_get_view (state, descriptor, memory, memory_size,
4256 shdr->sh_offset, shdr->sh_size, error_callback,
4257 data, &buildid_view))
4258 goto fail;
4260 buildid_view_valid = 1;
4261 note = (const b_elf_note *) buildid_view.view.data;
4262 if (note->type == NT_GNU_BUILD_ID
4263 && note->namesz == 4
4264 && strncmp (note->name, "GNU", 4) == 0
4265 && shdr->sh_size <= 12 + ((note->namesz + 3) & ~ 3) + note->descsz)
4267 buildid_data = &note->name[0] + ((note->namesz + 3) & ~ 3);
4268 buildid_size = note->descsz;
4271 if (with_buildid_size != 0)
4273 if (buildid_size != with_buildid_size)
4274 goto fail;
4276 if (memcmp (buildid_data, with_buildid_data, buildid_size) != 0)
4277 goto fail;
4281 /* Read the debuglink file if present. */
4282 if (!debuginfo
4283 && !debuglink_view_valid
4284 && strcmp (name, ".gnu_debuglink") == 0)
4286 const char *debuglink_data;
4287 size_t crc_offset;
4289 if (!elf_get_view (state, descriptor, memory, memory_size,
4290 shdr->sh_offset, shdr->sh_size, error_callback,
4291 data, &debuglink_view))
4292 goto fail;
4294 debuglink_view_valid = 1;
4295 debuglink_data = (const char *) debuglink_view.view.data;
4296 crc_offset = strnlen (debuglink_data, shdr->sh_size);
4297 crc_offset = (crc_offset + 3) & ~3;
4298 if (crc_offset + 4 <= shdr->sh_size)
4300 debuglink_name = debuglink_data;
4301 debuglink_crc = *(const uint32_t*)(debuglink_data + crc_offset);
4305 if (!debugaltlink_view_valid
4306 && strcmp (name, ".gnu_debugaltlink") == 0)
4308 const char *debugaltlink_data;
4309 size_t debugaltlink_name_len;
4311 if (!elf_get_view (state, descriptor, memory, memory_size,
4312 shdr->sh_offset, shdr->sh_size, error_callback,
4313 data, &debugaltlink_view))
4314 goto fail;
4316 debugaltlink_view_valid = 1;
4317 debugaltlink_data = (const char *) debugaltlink_view.view.data;
4318 debugaltlink_name = debugaltlink_data;
4319 debugaltlink_name_len = strnlen (debugaltlink_data, shdr->sh_size);
4320 if (debugaltlink_name_len < shdr->sh_size)
4322 /* Include terminating zero. */
4323 debugaltlink_name_len += 1;
4325 debugaltlink_buildid_data
4326 = debugaltlink_data + debugaltlink_name_len;
4327 debugaltlink_buildid_size = shdr->sh_size - debugaltlink_name_len;
4331 if (!gnu_debugdata_view_valid
4332 && strcmp (name, ".gnu_debugdata") == 0)
4334 if (!elf_get_view (state, descriptor, memory, memory_size,
4335 shdr->sh_offset, shdr->sh_size, error_callback,
4336 data, &gnu_debugdata_view))
4337 goto fail;
4339 gnu_debugdata_size = shdr->sh_size;
4340 gnu_debugdata_view_valid = 1;
4343 /* Read the .opd section on PowerPC64 ELFv1. */
4344 if (ehdr.e_machine == EM_PPC64
4345 && (ehdr.e_flags & EF_PPC64_ABI) < 2
4346 && shdr->sh_type == SHT_PROGBITS
4347 && strcmp (name, ".opd") == 0)
4349 if (!elf_get_view (state, descriptor, memory, memory_size,
4350 shdr->sh_offset, shdr->sh_size, error_callback,
4351 data, &opd_data.view))
4352 goto fail;
4354 opd = &opd_data;
4355 opd->addr = shdr->sh_addr;
4356 opd->data = (const char *) opd_data.view.view.data;
4357 opd->size = shdr->sh_size;
4361 if (symtab_shndx == 0)
4362 symtab_shndx = dynsym_shndx;
4363 if (symtab_shndx != 0 && !debuginfo)
4365 const b_elf_shdr *symtab_shdr;
4366 unsigned int strtab_shndx;
4367 const b_elf_shdr *strtab_shdr;
4368 struct elf_syminfo_data *sdata;
4370 symtab_shdr = &shdrs[symtab_shndx - 1];
4371 strtab_shndx = symtab_shdr->sh_link;
4372 if (strtab_shndx >= shnum)
4374 error_callback (data,
4375 "ELF symbol table strtab link out of range", 0);
4376 goto fail;
4378 strtab_shdr = &shdrs[strtab_shndx - 1];
4380 if (!elf_get_view (state, descriptor, memory, memory_size,
4381 symtab_shdr->sh_offset, symtab_shdr->sh_size,
4382 error_callback, data, &symtab_view))
4383 goto fail;
4384 symtab_view_valid = 1;
4386 if (!elf_get_view (state, descriptor, memory, memory_size,
4387 strtab_shdr->sh_offset, strtab_shdr->sh_size,
4388 error_callback, data, &strtab_view))
4389 goto fail;
4390 strtab_view_valid = 1;
4392 sdata = ((struct elf_syminfo_data *)
4393 backtrace_alloc (state, sizeof *sdata, error_callback, data));
4394 if (sdata == NULL)
4395 goto fail;
4397 if (!elf_initialize_syminfo (state, base_address,
4398 symtab_view.view.data, symtab_shdr->sh_size,
4399 strtab_view.view.data, strtab_shdr->sh_size,
4400 error_callback, data, sdata, opd))
4402 backtrace_free (state, sdata, sizeof *sdata, error_callback, data);
4403 goto fail;
4406 /* We no longer need the symbol table, but we hold on to the
4407 string table permanently. */
4408 elf_release_view (state, &symtab_view, error_callback, data);
4409 symtab_view_valid = 0;
4410 strtab_view_valid = 0;
4412 *found_sym = 1;
4414 elf_add_syminfo_data (state, sdata);
4417 elf_release_view (state, &shdrs_view, error_callback, data);
4418 shdrs_view_valid = 0;
4419 elf_release_view (state, &names_view, error_callback, data);
4420 names_view_valid = 0;
4422 /* If the debug info is in a separate file, read that one instead. */
4424 if (buildid_data != NULL)
4426 int d;
4428 d = elf_open_debugfile_by_buildid (state, buildid_data, buildid_size,
4429 error_callback, data);
4430 if (d >= 0)
4432 int ret;
4434 elf_release_view (state, &buildid_view, error_callback, data);
4435 if (debuglink_view_valid)
4436 elf_release_view (state, &debuglink_view, error_callback, data);
4437 if (debugaltlink_view_valid)
4438 elf_release_view (state, &debugaltlink_view, error_callback, data);
4439 ret = elf_add (state, "", d, NULL, 0, base_address, error_callback,
4440 data, fileline_fn, found_sym, found_dwarf, NULL, 0,
4441 1, NULL, 0);
4442 if (ret < 0)
4443 backtrace_close (d, error_callback, data);
4444 else if (descriptor >= 0)
4445 backtrace_close (descriptor, error_callback, data);
4446 return ret;
4450 if (buildid_view_valid)
4452 elf_release_view (state, &buildid_view, error_callback, data);
4453 buildid_view_valid = 0;
4456 if (opd)
4458 elf_release_view (state, &opd->view, error_callback, data);
4459 opd = NULL;
4462 if (debuglink_name != NULL)
4464 int d;
4466 d = elf_open_debugfile_by_debuglink (state, filename, debuglink_name,
4467 debuglink_crc, error_callback,
4468 data);
4469 if (d >= 0)
4471 int ret;
4473 elf_release_view (state, &debuglink_view, error_callback, data);
4474 if (debugaltlink_view_valid)
4475 elf_release_view (state, &debugaltlink_view, error_callback, data);
4476 ret = elf_add (state, "", d, NULL, 0, base_address, error_callback,
4477 data, fileline_fn, found_sym, found_dwarf, NULL, 0,
4478 1, NULL, 0);
4479 if (ret < 0)
4480 backtrace_close (d, error_callback, data);
4481 else if (descriptor >= 0)
4482 backtrace_close(descriptor, error_callback, data);
4483 return ret;
4487 if (debuglink_view_valid)
4489 elf_release_view (state, &debuglink_view, error_callback, data);
4490 debuglink_view_valid = 0;
4493 struct dwarf_data *fileline_altlink = NULL;
4494 if (debugaltlink_name != NULL)
4496 int d;
4498 d = elf_open_debugfile_by_debuglink (state, filename, debugaltlink_name,
4499 0, error_callback, data);
4500 if (d >= 0)
4502 int ret;
4504 ret = elf_add (state, filename, d, NULL, 0, base_address,
4505 error_callback, data, fileline_fn, found_sym,
4506 found_dwarf, &fileline_altlink, 0, 1,
4507 debugaltlink_buildid_data, debugaltlink_buildid_size);
4508 elf_release_view (state, &debugaltlink_view, error_callback, data);
4509 debugaltlink_view_valid = 0;
4510 if (ret < 0)
4512 backtrace_close (d, error_callback, data);
4513 return ret;
4518 if (debugaltlink_view_valid)
4520 elf_release_view (state, &debugaltlink_view, error_callback, data);
4521 debugaltlink_view_valid = 0;
4524 if (gnu_debugdata_view_valid)
4526 int ret;
4528 ret = elf_uncompress_lzma (state,
4529 ((const unsigned char *)
4530 gnu_debugdata_view.view.data),
4531 gnu_debugdata_size, error_callback, data,
4532 &gnu_debugdata_uncompressed,
4533 &gnu_debugdata_uncompressed_size);
4535 elf_release_view (state, &gnu_debugdata_view, error_callback, data);
4536 gnu_debugdata_view_valid = 0;
4538 if (ret)
4540 ret = elf_add (state, filename, -1, gnu_debugdata_uncompressed,
4541 gnu_debugdata_uncompressed_size, base_address,
4542 error_callback, data, fileline_fn, found_sym,
4543 found_dwarf, NULL, 0, 0, NULL, 0);
4544 if (ret >= 0 && descriptor >= 0)
4545 backtrace_close(descriptor, error_callback, data);
4546 return ret;
4550 /* Read all the debug sections in a single view, since they are
4551 probably adjacent in the file. If any of sections are
4552 uncompressed, we never release this view. */
4554 min_offset = 0;
4555 max_offset = 0;
4556 debug_size = 0;
4557 for (i = 0; i < (int) DEBUG_MAX; ++i)
4559 off_t end;
4561 if (sections[i].size != 0)
4563 if (min_offset == 0 || sections[i].offset < min_offset)
4564 min_offset = sections[i].offset;
4565 end = sections[i].offset + sections[i].size;
4566 if (end > max_offset)
4567 max_offset = end;
4568 debug_size += sections[i].size;
4570 if (zsections[i].size != 0)
4572 if (min_offset == 0 || zsections[i].offset < min_offset)
4573 min_offset = zsections[i].offset;
4574 end = zsections[i].offset + zsections[i].size;
4575 if (end > max_offset)
4576 max_offset = end;
4577 debug_size += zsections[i].size;
4580 if (min_offset == 0 || max_offset == 0)
4582 if (descriptor >= 0)
4584 if (!backtrace_close (descriptor, error_callback, data))
4585 goto fail;
4587 return 1;
4590 /* If the total debug section size is large, assume that there are
4591 gaps between the sections, and read them individually. */
4593 if (max_offset - min_offset < 0x20000000
4594 || max_offset - min_offset < debug_size + 0x10000)
4596 if (!elf_get_view (state, descriptor, memory, memory_size, min_offset,
4597 max_offset - min_offset, error_callback, data,
4598 &debug_view))
4599 goto fail;
4600 debug_view_valid = 1;
4602 else
4604 memset (&split_debug_view[0], 0, sizeof split_debug_view);
4605 for (i = 0; i < (int) DEBUG_MAX; ++i)
4607 struct debug_section_info *dsec;
4609 if (sections[i].size != 0)
4610 dsec = &sections[i];
4611 else if (zsections[i].size != 0)
4612 dsec = &zsections[i];
4613 else
4614 continue;
4616 if (!elf_get_view (state, descriptor, memory, memory_size,
4617 dsec->offset, dsec->size, error_callback, data,
4618 &split_debug_view[i]))
4619 goto fail;
4620 split_debug_view_valid[i] = 1;
4622 if (sections[i].size != 0)
4623 sections[i].data = ((const unsigned char *)
4624 split_debug_view[i].view.data);
4625 else
4626 zsections[i].data = ((const unsigned char *)
4627 split_debug_view[i].view.data);
4631 /* We've read all we need from the executable. */
4632 if (descriptor >= 0)
4634 if (!backtrace_close (descriptor, error_callback, data))
4635 goto fail;
4636 descriptor = -1;
4639 using_debug_view = 0;
4640 if (debug_view_valid)
4642 for (i = 0; i < (int) DEBUG_MAX; ++i)
4644 if (sections[i].size == 0)
4645 sections[i].data = NULL;
4646 else
4648 sections[i].data = ((const unsigned char *) debug_view.view.data
4649 + (sections[i].offset - min_offset));
4650 ++using_debug_view;
4653 if (zsections[i].size == 0)
4654 zsections[i].data = NULL;
4655 else
4656 zsections[i].data = ((const unsigned char *) debug_view.view.data
4657 + (zsections[i].offset - min_offset));
4661 /* Uncompress the old format (--compress-debug-sections=zlib-gnu). */
4663 zdebug_table = NULL;
4664 for (i = 0; i < (int) DEBUG_MAX; ++i)
4666 if (sections[i].size == 0 && zsections[i].size > 0)
4668 unsigned char *uncompressed_data;
4669 size_t uncompressed_size;
4671 if (zdebug_table == NULL)
4673 zdebug_table = ((uint16_t *)
4674 backtrace_alloc (state, ZDEBUG_TABLE_SIZE,
4675 error_callback, data));
4676 if (zdebug_table == NULL)
4677 goto fail;
4680 uncompressed_data = NULL;
4681 uncompressed_size = 0;
4682 if (!elf_uncompress_zdebug (state, zsections[i].data,
4683 zsections[i].size, zdebug_table,
4684 error_callback, data,
4685 &uncompressed_data, &uncompressed_size))
4686 goto fail;
4687 sections[i].data = uncompressed_data;
4688 sections[i].size = uncompressed_size;
4689 sections[i].compressed = 0;
4691 if (split_debug_view_valid[i])
4693 elf_release_view (state, &split_debug_view[i],
4694 error_callback, data);
4695 split_debug_view_valid[i] = 0;
4700 /* Uncompress the official ELF format
4701 (--compress-debug-sections=zlib-gabi). */
4702 for (i = 0; i < (int) DEBUG_MAX; ++i)
4704 unsigned char *uncompressed_data;
4705 size_t uncompressed_size;
4707 if (sections[i].size == 0 || !sections[i].compressed)
4708 continue;
4710 if (zdebug_table == NULL)
4712 zdebug_table = ((uint16_t *)
4713 backtrace_alloc (state, ZDEBUG_TABLE_SIZE,
4714 error_callback, data));
4715 if (zdebug_table == NULL)
4716 goto fail;
4719 uncompressed_data = NULL;
4720 uncompressed_size = 0;
4721 if (!elf_uncompress_chdr (state, sections[i].data, sections[i].size,
4722 zdebug_table, error_callback, data,
4723 &uncompressed_data, &uncompressed_size))
4724 goto fail;
4725 sections[i].data = uncompressed_data;
4726 sections[i].size = uncompressed_size;
4727 sections[i].compressed = 0;
4729 if (debug_view_valid)
4730 --using_debug_view;
4731 else if (split_debug_view_valid[i])
4733 elf_release_view (state, &split_debug_view[i], error_callback, data);
4734 split_debug_view_valid[i] = 0;
4738 if (zdebug_table != NULL)
4739 backtrace_free (state, zdebug_table, ZDEBUG_TABLE_SIZE,
4740 error_callback, data);
4742 if (debug_view_valid && using_debug_view == 0)
4744 elf_release_view (state, &debug_view, error_callback, data);
4745 debug_view_valid = 0;
4748 for (i = 0; i < (int) DEBUG_MAX; ++i)
4750 dwarf_sections.data[i] = sections[i].data;
4751 dwarf_sections.size[i] = sections[i].size;
4754 if (!backtrace_dwarf_add (state, base_address, &dwarf_sections,
4755 ehdr.e_ident[EI_DATA] == ELFDATA2MSB,
4756 fileline_altlink,
4757 error_callback, data, fileline_fn,
4758 fileline_entry))
4759 goto fail;
4761 *found_dwarf = 1;
4763 return 1;
4765 fail:
4766 if (shdrs_view_valid)
4767 elf_release_view (state, &shdrs_view, error_callback, data);
4768 if (names_view_valid)
4769 elf_release_view (state, &names_view, error_callback, data);
4770 if (symtab_view_valid)
4771 elf_release_view (state, &symtab_view, error_callback, data);
4772 if (strtab_view_valid)
4773 elf_release_view (state, &strtab_view, error_callback, data);
4774 if (debuglink_view_valid)
4775 elf_release_view (state, &debuglink_view, error_callback, data);
4776 if (debugaltlink_view_valid)
4777 elf_release_view (state, &debugaltlink_view, error_callback, data);
4778 if (gnu_debugdata_view_valid)
4779 elf_release_view (state, &gnu_debugdata_view, error_callback, data);
4780 if (buildid_view_valid)
4781 elf_release_view (state, &buildid_view, error_callback, data);
4782 if (debug_view_valid)
4783 elf_release_view (state, &debug_view, error_callback, data);
4784 for (i = 0; i < (int) DEBUG_MAX; ++i)
4786 if (split_debug_view_valid[i])
4787 elf_release_view (state, &split_debug_view[i], error_callback, data);
4789 if (opd)
4790 elf_release_view (state, &opd->view, error_callback, data);
4791 if (descriptor >= 0)
4792 backtrace_close (descriptor, error_callback, data);
4793 return 0;
4796 /* Data passed to phdr_callback. */
4798 struct phdr_data
4800 struct backtrace_state *state;
4801 backtrace_error_callback error_callback;
4802 void *data;
4803 fileline *fileline_fn;
4804 int *found_sym;
4805 int *found_dwarf;
4806 const char *exe_filename;
4807 int exe_descriptor;
4810 /* Callback passed to dl_iterate_phdr. Load debug info from shared
4811 libraries. */
4813 static int
4814 #ifdef __i386__
4815 __attribute__ ((__force_align_arg_pointer__))
4816 #endif
4817 phdr_callback (struct dl_phdr_info *info, size_t size ATTRIBUTE_UNUSED,
4818 void *pdata)
4820 struct phdr_data *pd = (struct phdr_data *) pdata;
4821 const char *filename;
4822 int descriptor;
4823 int does_not_exist;
4824 fileline elf_fileline_fn;
4825 int found_dwarf;
4827 /* There is not much we can do if we don't have the module name,
4828 unless executable is ET_DYN, where we expect the very first
4829 phdr_callback to be for the PIE. */
4830 if (info->dlpi_name == NULL || info->dlpi_name[0] == '\0')
4832 if (pd->exe_descriptor == -1)
4833 return 0;
4834 filename = pd->exe_filename;
4835 descriptor = pd->exe_descriptor;
4836 pd->exe_descriptor = -1;
4838 else
4840 if (pd->exe_descriptor != -1)
4842 backtrace_close (pd->exe_descriptor, pd->error_callback, pd->data);
4843 pd->exe_descriptor = -1;
4846 filename = info->dlpi_name;
4847 descriptor = backtrace_open (info->dlpi_name, pd->error_callback,
4848 pd->data, &does_not_exist);
4849 if (descriptor < 0)
4850 return 0;
4853 if (elf_add (pd->state, filename, descriptor, NULL, 0, info->dlpi_addr,
4854 pd->error_callback, pd->data, &elf_fileline_fn, pd->found_sym,
4855 &found_dwarf, NULL, 0, 0, NULL, 0))
4857 if (found_dwarf)
4859 *pd->found_dwarf = 1;
4860 *pd->fileline_fn = elf_fileline_fn;
4864 return 0;
4867 /* Initialize the backtrace data we need from an ELF executable. At
4868 the ELF level, all we need to do is find the debug info
4869 sections. */
4872 backtrace_initialize (struct backtrace_state *state, const char *filename,
4873 int descriptor, backtrace_error_callback error_callback,
4874 void *data, fileline *fileline_fn)
4876 int ret;
4877 int found_sym;
4878 int found_dwarf;
4879 fileline elf_fileline_fn = elf_nodebug;
4880 struct phdr_data pd;
4882 ret = elf_add (state, filename, descriptor, NULL, 0, 0, error_callback, data,
4883 &elf_fileline_fn, &found_sym, &found_dwarf, NULL, 1, 0, NULL,
4885 if (!ret)
4886 return 0;
4888 pd.state = state;
4889 pd.error_callback = error_callback;
4890 pd.data = data;
4891 pd.fileline_fn = &elf_fileline_fn;
4892 pd.found_sym = &found_sym;
4893 pd.found_dwarf = &found_dwarf;
4894 pd.exe_filename = filename;
4895 pd.exe_descriptor = ret < 0 ? descriptor : -1;
4897 dl_iterate_phdr (phdr_callback, (void *) &pd);
4899 if (!state->threaded)
4901 if (found_sym)
4902 state->syminfo_fn = elf_syminfo;
4903 else if (state->syminfo_fn == NULL)
4904 state->syminfo_fn = elf_nosyms;
4906 else
4908 if (found_sym)
4909 backtrace_atomic_store_pointer (&state->syminfo_fn, elf_syminfo);
4910 else
4911 (void) __sync_bool_compare_and_swap (&state->syminfo_fn, NULL,
4912 elf_nosyms);
4915 if (!state->threaded)
4916 *fileline_fn = state->fileline_fn;
4917 else
4918 *fileline_fn = backtrace_atomic_load_pointer (&state->fileline_fn);
4920 if (*fileline_fn == NULL || *fileline_fn == elf_nodebug)
4921 *fileline_fn = elf_fileline_fn;
4923 return 1;