v2 / thirdparty / libbacktrace / linux.c
7807 lines · 6683 sloc · 195.45 KB · e78481994a892734d00a24a16951a2df75f76631
Raw
1// elf.c:
2#include <errno.h>
3#include <stdlib.h>
4#include <string.h>
5#include <sys/types.h>
6#include <sys/stat.h>
7#include <unistd.h>
8
9#ifdef HAVE_DL_ITERATE_PHDR
10 #ifdef HAVE_LINK_H
11 #include <link.h>
12 #endif
13 #ifdef HAVE_SYS_LINK_H
14 #include <sys/link.h>
15 #endif
16#endif
17
18
19#ifndef S_ISLNK
20 #ifndef S_IFLNK
21 #define S_IFLNK 0120000
22 #endif
23 #ifndef S_IFMT
24 #define S_IFMT 0170000
25 #endif
26 #define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
27#endif
28
29#ifndef __GNUC__
30#define __builtin_prefetch(p, r, l)
31#define unlikely(x) (x)
32#else
33#define unlikely(x) __builtin_expect(!!(x), 0)
34#endif
35
36#if !defined(HAVE_DECL_STRNLEN) || !HAVE_DECL_STRNLEN
37
38/* If strnlen is not declared, provide our own version. */
39
40static size_t
41xstrnlen (const char *s, size_t maxlen)
42{
43 size_t i;
44
45 for (i = 0; i < maxlen; ++i)
46 if (s[i] == '\0')
47 break;
48 return i;
49}
50
51#define strnlen xstrnlen
52
53#endif
54
55#ifndef HAVE_LSTAT
56
57/* Dummy version of lstat for systems that don't have it. */
58
59static int
60xlstat (const char *path ATTRIBUTE_UNUSED, struct stat *st ATTRIBUTE_UNUSED)
61{
62 return -1;
63}
64
65#define lstat xlstat
66
67#endif
68
69#ifndef HAVE_READLINK
70
71/* Dummy version of readlink for systems that don't have it. */
72
73static ssize_t
74xreadlink (const char *path ATTRIBUTE_UNUSED, char *buf ATTRIBUTE_UNUSED,
75 size_t bufsz ATTRIBUTE_UNUSED)
76{
77 return -1;
78}
79
80#define readlink xreadlink
81
82#endif
83
84#ifndef HAVE_DL_ITERATE_PHDR
85
86/* Dummy version of dl_iterate_phdr for systems that don't have it. */
87
88#define dl_phdr_info x_dl_phdr_info
89#define dl_iterate_phdr x_dl_iterate_phdr
90
91struct dl_phdr_info
92{
93 uintptr_t dlpi_addr;
94 const char *dlpi_name;
95};
96
97static int
98dl_iterate_phdr (int (*callback) (struct dl_phdr_info *,
99 size_t, void *) ATTRIBUTE_UNUSED,
100 void *data ATTRIBUTE_UNUSED)
101{
102 return 0;
103}
104
105#endif /* ! defined (HAVE_DL_ITERATE_PHDR) */
106
107/* The configure script must tell us whether we are 32-bit or 64-bit
108 ELF. We could make this code test and support either possibility,
109 but there is no point. This code only works for the currently
110 running executable, which means that we know the ELF mode at
111 configure time. */
112
113#if BACKTRACE_ELF_SIZE != 32 && BACKTRACE_ELF_SIZE != 64
114#error "Unknown BACKTRACE_ELF_SIZE"
115#endif
116
117/* <link.h> might #include <elf.h> which might define our constants
118 with slightly different values. Undefine them to be safe. */
119
120#undef EI_NIDENT
121#undef EI_MAG0
122#undef EI_MAG1
123#undef EI_MAG2
124#undef EI_MAG3
125#undef EI_CLASS
126#undef EI_DATA
127#undef EI_VERSION
128#undef ELFMAG0
129#undef ELFMAG1
130#undef ELFMAG2
131#undef ELFMAG3
132#undef ELFCLASS32
133#undef ELFCLASS64
134#undef ELFDATA2LSB
135#undef ELFDATA2MSB
136#undef EV_CURRENT
137#undef ET_DYN
138#undef EM_PPC64
139#undef EF_PPC64_ABI
140#undef SHN_LORESERVE
141#undef SHN_XINDEX
142#undef SHN_UNDEF
143#undef SHT_PROGBITS
144#undef SHT_SYMTAB
145#undef SHT_STRTAB
146#undef SHT_DYNSYM
147#undef SHF_COMPRESSED
148#undef STT_OBJECT
149#undef STT_FUNC
150#undef NT_GNU_BUILD_ID
151#undef ELFCOMPRESS_ZLIB
152#undef ELFCOMPRESS_ZSTD
153
154/* Basic types. */
155
156typedef uint16_t b_elf_half; /* Elf_Half. */
157typedef uint32_t b_elf_word; /* Elf_Word. */
158typedef int32_t b_elf_sword; /* Elf_Sword. */
159
160#if BACKTRACE_ELF_SIZE == 32
161
162typedef uint32_t b_elf_addr; /* Elf_Addr. */
163typedef uint32_t b_elf_off; /* Elf_Off. */
164
165typedef uint32_t b_elf_wxword; /* 32-bit Elf_Word, 64-bit ELF_Xword. */
166
167#else
168
169typedef uint64_t b_elf_addr; /* Elf_Addr. */
170typedef uint64_t b_elf_off; /* Elf_Off. */
171typedef uint64_t b_elf_xword; /* Elf_Xword. */
172typedef int64_t b_elf_sxword; /* Elf_Sxword. */
173
174typedef uint64_t b_elf_wxword; /* 32-bit Elf_Word, 64-bit ELF_Xword. */
175
176#endif
177
178/* Data structures and associated constants. */
179
180#define EI_NIDENT 16
181
182typedef struct {
183 unsigned char e_ident[EI_NIDENT]; /* ELF "magic number" */
184 b_elf_half e_type; /* Identifies object file type */
185 b_elf_half e_machine; /* Specifies required architecture */
186 b_elf_word e_version; /* Identifies object file version */
187 b_elf_addr e_entry; /* Entry point virtual address */
188 b_elf_off e_phoff; /* Program header table file offset */
189 b_elf_off e_shoff; /* Section header table file offset */
190 b_elf_word e_flags; /* Processor-specific flags */
191 b_elf_half e_ehsize; /* ELF header size in bytes */
192 b_elf_half e_phentsize; /* Program header table entry size */
193 b_elf_half e_phnum; /* Program header table entry count */
194 b_elf_half e_shentsize; /* Section header table entry size */
195 b_elf_half e_shnum; /* Section header table entry count */
196 b_elf_half e_shstrndx; /* Section header string table index */
197} b_elf_ehdr; /* Elf_Ehdr. */
198
199#define EI_MAG0 0
200#define EI_MAG1 1
201#define EI_MAG2 2
202#define EI_MAG3 3
203#define EI_CLASS 4
204#define EI_DATA 5
205#define EI_VERSION 6
206
207#define ELFMAG0 0x7f
208#define ELFMAG1 'E'
209#define ELFMAG2 'L'
210#define ELFMAG3 'F'
211
212#define ELFCLASS32 1
213#define ELFCLASS64 2
214
215#define ELFDATA2LSB 1
216#define ELFDATA2MSB 2
217
218#define EV_CURRENT 1
219
220#define ET_DYN 3
221
222#define EM_PPC64 21
223#define EF_PPC64_ABI 3
224
225typedef struct {
226 b_elf_word sh_name; /* Section name, index in string tbl */
227 b_elf_word sh_type; /* Type of section */
228 b_elf_wxword sh_flags; /* Miscellaneous section attributes */
229 b_elf_addr sh_addr; /* Section virtual addr at execution */
230 b_elf_off sh_offset; /* Section file offset */
231 b_elf_wxword sh_size; /* Size of section in bytes */
232 b_elf_word sh_link; /* Index of another section */
233 b_elf_word sh_info; /* Additional section information */
234 b_elf_wxword sh_addralign; /* Section alignment */
235 b_elf_wxword sh_entsize; /* Entry size if section holds table */
236} b_elf_shdr; /* Elf_Shdr. */
237
238#define SHN_UNDEF 0x0000 /* Undefined section */
239#define SHN_LORESERVE 0xFF00 /* Begin range of reserved indices */
240#define SHN_XINDEX 0xFFFF /* Section index is held elsewhere */
241
242#define SHT_PROGBITS 1
243#define SHT_SYMTAB 2
244#define SHT_STRTAB 3
245#define SHT_DYNSYM 11
246
247#define SHF_COMPRESSED 0x800
248
249#if BACKTRACE_ELF_SIZE == 32
250
251typedef struct
252{
253 b_elf_word st_name; /* Symbol name, index in string tbl */
254 b_elf_addr st_value; /* Symbol value */
255 b_elf_word st_size; /* Symbol size */
256 unsigned char st_info; /* Symbol binding and type */
257 unsigned char st_other; /* Visibility and other data */
258 b_elf_half st_shndx; /* Symbol section index */
259} b_elf_sym; /* Elf_Sym. */
260
261#else /* BACKTRACE_ELF_SIZE != 32 */
262
263typedef struct
264{
265 b_elf_word st_name; /* Symbol name, index in string tbl */
266 unsigned char st_info; /* Symbol binding and type */
267 unsigned char st_other; /* Visibility and other data */
268 b_elf_half st_shndx; /* Symbol section index */
269 b_elf_addr st_value; /* Symbol value */
270 b_elf_xword st_size; /* Symbol size */
271} b_elf_sym; /* Elf_Sym. */
272
273#endif /* BACKTRACE_ELF_SIZE != 32 */
274
275#define STT_OBJECT 1
276#define STT_FUNC 2
277
278typedef struct
279{
280 uint32_t namesz;
281 uint32_t descsz;
282 uint32_t type;
283 char name[1];
284} b_elf_note;
285
286#define NT_GNU_BUILD_ID 3
287
288#if BACKTRACE_ELF_SIZE == 32
289
290typedef struct
291{
292 b_elf_word ch_type; /* Compresstion algorithm */
293 b_elf_word ch_size; /* Uncompressed size */
294 b_elf_word ch_addralign; /* Alignment for uncompressed data */
295} b_elf_chdr; /* Elf_Chdr */
296
297#else /* BACKTRACE_ELF_SIZE != 32 */
298
299typedef struct
300{
301 b_elf_word ch_type; /* Compression algorithm */
302 b_elf_word ch_reserved; /* Reserved */
303 b_elf_xword ch_size; /* Uncompressed size */
304 b_elf_xword ch_addralign; /* Alignment for uncompressed data */
305} b_elf_chdr; /* Elf_Chdr */
306
307#endif /* BACKTRACE_ELF_SIZE != 32 */
308
309#define ELFCOMPRESS_ZLIB 1
310#define ELFCOMPRESS_ZSTD 2
311
312/* Names of sections, indexed by enum dwarf_section in internal.h. */
313
314static const char * const dwarf_section_names[DEBUG_MAX] =
315{
316 ".debug_info",
317 ".debug_line",
318 ".debug_abbrev",
319 ".debug_ranges",
320 ".debug_str",
321 ".debug_addr",
322 ".debug_str_offsets",
323 ".debug_line_str",
324 ".debug_rnglists"
325};
326
327/* Information we gather for the sections we care about. */
328
329struct debug_section_info
330{
331 /* Section file offset. */
332 off_t offset;
333 /* Section size. */
334 size_t size;
335 /* Section contents, after read from file. */
336 const unsigned char *data;
337 /* Whether the SHF_COMPRESSED flag is set for the section. */
338 int compressed;
339};
340
341/* Information we keep for an ELF symbol. */
342
343struct elf_symbol
344{
345 /* The name of the symbol. */
346 const char *name;
347 /* The address of the symbol. */
348 uintptr_t address;
349 /* The size of the symbol. */
350 size_t size;
351};
352
353/* Information to pass to elf_syminfo. */
354
355struct elf_syminfo_data
356{
357 /* Symbols for the next module. */
358 struct elf_syminfo_data *next;
359 /* The ELF symbols, sorted by address. */
360 struct elf_symbol *symbols;
361 /* The number of symbols. */
362 size_t count;
363};
364
365/* A view that works for either a file or memory. */
366
367struct elf_view
368{
369 struct backtrace_view view;
370 int release; /* If non-zero, must call backtrace_release_view. */
371};
372
373/* Information about PowerPC64 ELFv1 .opd section. */
374
375struct elf_ppc64_opd_data
376{
377 /* Address of the .opd section. */
378 b_elf_addr addr;
379 /* Section data. */
380 const char *data;
381 /* Size of the .opd section. */
382 size_t size;
383 /* Corresponding section view. */
384 struct elf_view view;
385};
386
387/* Create a view of SIZE bytes from DESCRIPTOR/MEMORY at OFFSET. */
388
389static int
390elf_get_view (struct backtrace_state *state, int descriptor,
391 const unsigned char *memory, size_t memory_size, off_t offset,
392 uint64_t size, backtrace_error_callback error_callback,
393 void *data, struct elf_view *view)
394{
395 if (memory == NULL)
396 {
397 view->release = 1;
398 return backtrace_get_view (state, descriptor, offset, size,
399 error_callback, data, &view->view);
400 }
401 else
402 {
403 if ((uint64_t) offset + size > (uint64_t) memory_size)
404 {
405 error_callback (data, "out of range for in-memory file", 0);
406 return 0;
407 }
408 view->view.data = (const void *) (memory + offset);
409 view->view.base = NULL;
410 view->view.len = size;
411 view->release = 0;
412 return 1;
413 }
414}
415
416/* Release a view read by elf_get_view. */
417
418static void
419elf_release_view (struct backtrace_state *state, struct elf_view *view,
420 backtrace_error_callback error_callback, void *data)
421{
422 if (view->release)
423 backtrace_release_view (state, &view->view, error_callback, data);
424}
425
426/* Compute the CRC-32 of BUF/LEN. This uses the CRC used for
427 .gnu_debuglink files. */
428
429static uint32_t
430elf_crc32 (uint32_t crc, const unsigned char *buf, size_t len)
431{
432 static const uint32_t crc32_table[256] =
433 {
434 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
435 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
436 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
437 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
438 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
439 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
440 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
441 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
442 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
443 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
444 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
445 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
446 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
447 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
448 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
449 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
450 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
451 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
452 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
453 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
454 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
455 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
456 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
457 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
458 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
459 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
460 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
461 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
462 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
463 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
464 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
465 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
466 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
467 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
468 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
469 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
470 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
471 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
472 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
473 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
474 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
475 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
476 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
477 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
478 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
479 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
480 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
481 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
482 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
483 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
484 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
485 0x2d02ef8d
486 };
487 const unsigned char *end;
488
489 crc = ~crc;
490 for (end = buf + len; buf < end; ++ buf)
491 crc = crc32_table[(crc ^ *buf) & 0xff] ^ (crc >> 8);
492 return ~crc;
493}
494
495/* Return the CRC-32 of the entire file open at DESCRIPTOR. */
496
497static uint32_t
498elf_crc32_file (struct backtrace_state *state, int descriptor,
499 backtrace_error_callback error_callback, void *data)
500{
501 struct stat st;
502 struct backtrace_view file_view;
503 uint32_t ret;
504
505 if (fstat (descriptor, &st) < 0)
506 {
507 error_callback (data, "fstat", errno);
508 return 0;
509 }
510
511 if (!backtrace_get_view (state, descriptor, 0, st.st_size, error_callback,
512 data, &file_view))
513 return 0;
514
515 ret = elf_crc32 (0, (const unsigned char *) file_view.data, st.st_size);
516
517 backtrace_release_view (state, &file_view, error_callback, data);
518
519 return ret;
520}
521
522/* A dummy callback function used when we can't find a symbol
523 table. */
524
525static void
526elf_nosyms (struct backtrace_state *state ATTRIBUTE_UNUSED,
527 uintptr_t addr ATTRIBUTE_UNUSED,
528 backtrace_syminfo_callback callback ATTRIBUTE_UNUSED,
529 backtrace_error_callback error_callback, void *data)
530{
531 error_callback (data, "no symbol table in ELF executable", -1);
532}
533
534/* A callback function used when we can't find any debug info. */
535
536static int
537elf_nodebug (struct backtrace_state *state, uintptr_t pc,
538 backtrace_full_callback callback,
539 backtrace_error_callback error_callback, void *data)
540{
541 if (state->syminfo_fn != NULL && state->syminfo_fn != elf_nosyms)
542 {
543 struct backtrace_call_full bdata;
544
545 /* Fetch symbol information so that we can least get the
546 function name. */
547
548 bdata.full_callback = callback;
549 bdata.full_error_callback = error_callback;
550 bdata.full_data = data;
551 bdata.ret = 0;
552 state->syminfo_fn (state, pc, backtrace_syminfo_to_full_callback,
553 backtrace_syminfo_to_full_error_callback, &bdata);
554 return bdata.ret;
555 }
556
557 error_callback (data, "no debug info in ELF executable (make sure to compile with -g)", -1);
558 return 0;
559}
560
561/* Compare struct elf_symbol for qsort. */
562
563static int
564elf_symbol_compare (const void *v1, const void *v2)
565{
566 const struct elf_symbol *e1 = (const struct elf_symbol *) v1;
567 const struct elf_symbol *e2 = (const struct elf_symbol *) v2;
568
569 if (e1->address < e2->address)
570 return -1;
571 else if (e1->address > e2->address)
572 return 1;
573 else
574 return 0;
575}
576
577/* Compare an ADDR against an elf_symbol for bsearch. We allocate one
578 extra entry in the array so that this can look safely at the next
579 entry. */
580
581static int
582elf_symbol_search (const void *vkey, const void *ventry)
583{
584 const uintptr_t *key = (const uintptr_t *) vkey;
585 const struct elf_symbol *entry = (const struct elf_symbol *) ventry;
586 uintptr_t addr;
587
588 addr = *key;
589 if (addr < entry->address)
590 return -1;
591 else if (addr >= entry->address + entry->size)
592 return 1;
593 else
594 return 0;
595}
596
597/* Initialize the symbol table info for elf_syminfo. */
598
599static int
600elf_initialize_syminfo (struct backtrace_state *state,
601 struct libbacktrace_base_address base_address,
602 const unsigned char *symtab_data, size_t symtab_size,
603 const unsigned char *strtab, size_t strtab_size,
604 backtrace_error_callback error_callback,
605 void *data, struct elf_syminfo_data *sdata,
606 struct elf_ppc64_opd_data *opd)
607{
608 size_t sym_count;
609 const b_elf_sym *sym;
610 size_t elf_symbol_count;
611 size_t elf_symbol_size;
612 struct elf_symbol *elf_symbols;
613 size_t i;
614 unsigned int j;
615
616 sym_count = symtab_size / sizeof (b_elf_sym);
617
618 /* We only care about function symbols. Count them. */
619 sym = (const b_elf_sym *) symtab_data;
620 elf_symbol_count = 0;
621 for (i = 0; i < sym_count; ++i, ++sym)
622 {
623 int info;
624
625 info = sym->st_info & 0xf;
626 if ((info == STT_FUNC || info == STT_OBJECT)
627 && sym->st_shndx != SHN_UNDEF)
628 ++elf_symbol_count;
629 }
630
631 elf_symbol_size = elf_symbol_count * sizeof (struct elf_symbol);
632 elf_symbols = ((struct elf_symbol *)
633 backtrace_alloc (state, elf_symbol_size, error_callback,
634 data));
635 if (elf_symbols == NULL)
636 return 0;
637
638 sym = (const b_elf_sym *) symtab_data;
639 j = 0;
640 for (i = 0; i < sym_count; ++i, ++sym)
641 {
642 int info;
643
644 info = sym->st_info & 0xf;
645 if (info != STT_FUNC && info != STT_OBJECT)
646 continue;
647 if (sym->st_shndx == SHN_UNDEF)
648 continue;
649 if (sym->st_name >= strtab_size)
650 {
651 error_callback (data, "symbol string index out of range", 0);
652 backtrace_free (state, elf_symbols, elf_symbol_size, error_callback,
653 data);
654 return 0;
655 }
656 elf_symbols[j].name = (const char *) strtab + sym->st_name;
657 /* Special case PowerPC64 ELFv1 symbols in .opd section, if the symbol
658 is a function descriptor, read the actual code address from the
659 descriptor. */
660 if (opd
661 && sym->st_value >= opd->addr
662 && sym->st_value < opd->addr + opd->size)
663 elf_symbols[j].address
664 = *(const b_elf_addr *) (opd->data + (sym->st_value - opd->addr));
665 else
666 elf_symbols[j].address = sym->st_value;
667 elf_symbols[j].address =
668 libbacktrace_add_base (elf_symbols[j].address, base_address);
669 elf_symbols[j].size = sym->st_size;
670 ++j;
671 }
672
673 backtrace_qsort (elf_symbols, elf_symbol_count, sizeof (struct elf_symbol),
674 elf_symbol_compare);
675
676 sdata->next = NULL;
677 sdata->symbols = elf_symbols;
678 sdata->count = elf_symbol_count;
679
680 return 1;
681}
682
683/* Add EDATA to the list in STATE. */
684
685static void
686elf_add_syminfo_data (struct backtrace_state *state,
687 struct elf_syminfo_data *edata)
688{
689 if (!state->threaded)
690 {
691 struct elf_syminfo_data **pp;
692
693 for (pp = (struct elf_syminfo_data **) (void *) &state->syminfo_data;
694 *pp != NULL;
695 pp = &(*pp)->next)
696 ;
697 *pp = edata;
698 }
699 else
700 {
701 while (1)
702 {
703 struct elf_syminfo_data **pp;
704
705 pp = (struct elf_syminfo_data **) (void *) &state->syminfo_data;
706
707 while (1)
708 {
709 struct elf_syminfo_data *p;
710
711 p = backtrace_atomic_load_pointer (pp);
712
713 if (p == NULL)
714 break;
715
716 pp = &p->next;
717 }
718
719 if (__sync_bool_compare_and_swap (pp, NULL, edata))
720 break;
721 }
722 }
723}
724
725/* Return the symbol name and value for an ADDR. */
726
727static void
728elf_syminfo (struct backtrace_state *state, uintptr_t addr,
729 backtrace_syminfo_callback callback,
730 backtrace_error_callback error_callback ATTRIBUTE_UNUSED,
731 void *data)
732{
733 struct elf_syminfo_data *edata;
734 struct elf_symbol *sym = NULL;
735
736 if (!state->threaded)
737 {
738 for (edata = (struct elf_syminfo_data *) state->syminfo_data;
739 edata != NULL;
740 edata = edata->next)
741 {
742 sym = ((struct elf_symbol *)
743 bsearch (&addr, edata->symbols, edata->count,
744 sizeof (struct elf_symbol), elf_symbol_search));
745 if (sym != NULL)
746 break;
747 }
748 }
749 else
750 {
751 struct elf_syminfo_data **pp;
752
753 pp = (struct elf_syminfo_data **) (void *) &state->syminfo_data;
754 while (1)
755 {
756 edata = backtrace_atomic_load_pointer (pp);
757 if (edata == NULL)
758 break;
759
760 sym = ((struct elf_symbol *)
761 bsearch (&addr, edata->symbols, edata->count,
762 sizeof (struct elf_symbol), elf_symbol_search));
763 if (sym != NULL)
764 break;
765
766 pp = &edata->next;
767 }
768 }
769
770 if (sym == NULL)
771 callback (data, addr, NULL, 0, 0);
772 else
773 callback (data, addr, sym->name, sym->address, sym->size);
774}
775
776/* Return whether FILENAME is a symlink. */
777
778static int
779elf_is_symlink (const char *filename)
780{
781 struct stat st;
782
783 if (lstat (filename, &st) < 0)
784 return 0;
785 return S_ISLNK (st.st_mode);
786}
787
788/* Return the results of reading the symlink FILENAME in a buffer
789 allocated by backtrace_alloc. Return the length of the buffer in
790 *LEN. */
791
792static char *
793elf_readlink (struct backtrace_state *state, const char *filename,
794 backtrace_error_callback error_callback, void *data,
795 size_t *plen)
796{
797 size_t len;
798 char *buf;
799
800 len = 128;
801 while (1)
802 {
803 ssize_t rl;
804
805 buf = backtrace_alloc (state, len, error_callback, data);
806 if (buf == NULL)
807 return NULL;
808 rl = readlink (filename, buf, len);
809 if (rl < 0)
810 {
811 backtrace_free (state, buf, len, error_callback, data);
812 return NULL;
813 }
814 if ((size_t) rl < len - 1)
815 {
816 buf[rl] = '\0';
817 *plen = len;
818 return buf;
819 }
820 backtrace_free (state, buf, len, error_callback, data);
821 len *= 2;
822 }
823}
824
825#define SYSTEM_BUILD_ID_DIR "/usr/lib/debug/.build-id/"
826
827/* Open a separate debug info file, using the build ID to find it.
828 Returns an open file descriptor, or -1.
829
830 The GDB manual says that the only place gdb looks for a debug file
831 when the build ID is known is in /usr/lib/debug/.build-id. */
832
833static int
834elf_open_debugfile_by_buildid (struct backtrace_state *state,
835 const char *buildid_data, size_t buildid_size,
836 backtrace_error_callback error_callback,
837 void *data)
838{
839 const char * const prefix = SYSTEM_BUILD_ID_DIR;
840 const size_t prefix_len = strlen (prefix);
841 const char * const suffix = ".debug";
842 const size_t suffix_len = strlen (suffix);
843 size_t len;
844 char *bd_filename;
845 char *t;
846 size_t i;
847 int ret;
848 int does_not_exist;
849
850 len = prefix_len + buildid_size * 2 + suffix_len + 2;
851 bd_filename = backtrace_alloc (state, len, error_callback, data);
852 if (bd_filename == NULL)
853 return -1;
854
855 t = bd_filename;
856 memcpy (t, prefix, prefix_len);
857 t += prefix_len;
858 for (i = 0; i < buildid_size; i++)
859 {
860 unsigned char b;
861 unsigned char nib;
862
863 b = (unsigned char) buildid_data[i];
864 nib = (b & 0xf0) >> 4;
865 *t++ = nib < 10 ? '0' + nib : 'a' + nib - 10;
866 nib = b & 0x0f;
867 *t++ = nib < 10 ? '0' + nib : 'a' + nib - 10;
868 if (i == 0)
869 *t++ = '/';
870 }
871 memcpy (t, suffix, suffix_len);
872 t[suffix_len] = '\0';
873
874 ret = backtrace_open (bd_filename, error_callback, data, &does_not_exist);
875
876 backtrace_free (state, bd_filename, len, error_callback, data);
877
878 /* gdb checks that the debuginfo file has the same build ID note.
879 That seems kind of pointless to me--why would it have the right
880 name but not the right build ID?--so skipping the check. */
881
882 return ret;
883}
884
885/* Try to open a file whose name is PREFIX (length PREFIX_LEN)
886 concatenated with PREFIX2 (length PREFIX2_LEN) concatenated with
887 DEBUGLINK_NAME. Returns an open file descriptor, or -1. */
888
889static int
890elf_try_debugfile (struct backtrace_state *state, const char *prefix,
891 size_t prefix_len, const char *prefix2, size_t prefix2_len,
892 const char *debuglink_name,
893 backtrace_error_callback error_callback, void *data)
894{
895 size_t debuglink_len;
896 size_t try_len;
897 char *try;
898 int does_not_exist;
899 int ret;
900
901 debuglink_len = strlen (debuglink_name);
902 try_len = prefix_len + prefix2_len + debuglink_len + 1;
903 try = backtrace_alloc (state, try_len, error_callback, data);
904 if (try == NULL)
905 return -1;
906
907 memcpy (try, prefix, prefix_len);
908 memcpy (try + prefix_len, prefix2, prefix2_len);
909 memcpy (try + prefix_len + prefix2_len, debuglink_name, debuglink_len);
910 try[prefix_len + prefix2_len + debuglink_len] = '\0';
911
912 ret = backtrace_open (try, error_callback, data, &does_not_exist);
913
914 backtrace_free (state, try, try_len, error_callback, data);
915
916 return ret;
917}
918
919/* Find a separate debug info file, using the debuglink section data
920 to find it. Returns an open file descriptor, or -1. */
921
922static int
923elf_find_debugfile_by_debuglink (struct backtrace_state *state,
924 const char *filename,
925 const char *debuglink_name,
926 backtrace_error_callback error_callback,
927 void *data)
928{
929 int ret;
930 char *alc;
931 size_t alc_len;
932 const char *slash;
933 int ddescriptor;
934 const char *prefix;
935 size_t prefix_len;
936
937 /* Resolve symlinks in FILENAME. Since FILENAME is fairly likely to
938 be /proc/self/exe, symlinks are common. We don't try to resolve
939 the whole path name, just the base name. */
940 ret = -1;
941 alc = NULL;
942 alc_len = 0;
943 while (elf_is_symlink (filename))
944 {
945 char *new_buf;
946 size_t new_len;
947
948 new_buf = elf_readlink (state, filename, error_callback, data, &new_len);
949 if (new_buf == NULL)
950 break;
951
952 if (new_buf[0] == '/')
953 filename = new_buf;
954 else
955 {
956 slash = strrchr (filename, '/');
957 if (slash == NULL)
958 filename = new_buf;
959 else
960 {
961 size_t clen;
962 char *c;
963
964 slash++;
965 clen = slash - filename + strlen (new_buf) + 1;
966 c = backtrace_alloc (state, clen, error_callback, data);
967 if (c == NULL)
968 goto done;
969
970 memcpy (c, filename, slash - filename);
971 memcpy (c + (slash - filename), new_buf, strlen (new_buf));
972 c[slash - filename + strlen (new_buf)] = '\0';
973 backtrace_free (state, new_buf, new_len, error_callback, data);
974 filename = c;
975 new_buf = c;
976 new_len = clen;
977 }
978 }
979
980 if (alc != NULL)
981 backtrace_free (state, alc, alc_len, error_callback, data);
982 alc = new_buf;
983 alc_len = new_len;
984 }
985
986 /* Look for DEBUGLINK_NAME in the same directory as FILENAME. */
987
988 slash = strrchr (filename, '/');
989 if (slash == NULL)
990 {
991 prefix = "";
992 prefix_len = 0;
993 }
994 else
995 {
996 slash++;
997 prefix = filename;
998 prefix_len = slash - filename;
999 }
1000
1001 ddescriptor = elf_try_debugfile (state, prefix, prefix_len, "", 0,
1002 debuglink_name, error_callback, data);
1003 if (ddescriptor >= 0)
1004 {
1005 ret = ddescriptor;
1006 goto done;
1007 }
1008
1009 /* Look for DEBUGLINK_NAME in a .debug subdirectory of FILENAME. */
1010
1011 ddescriptor = elf_try_debugfile (state, prefix, prefix_len, ".debug/",
1012 strlen (".debug/"), debuglink_name,
1013 error_callback, data);
1014 if (ddescriptor >= 0)
1015 {
1016 ret = ddescriptor;
1017 goto done;
1018 }
1019
1020 /* Look for DEBUGLINK_NAME in /usr/lib/debug. */
1021
1022 ddescriptor = elf_try_debugfile (state, "/usr/lib/debug/",
1023 strlen ("/usr/lib/debug/"), prefix,
1024 prefix_len, debuglink_name,
1025 error_callback, data);
1026 if (ddescriptor >= 0)
1027 ret = ddescriptor;
1028
1029 done:
1030 if (alc != NULL && alc_len > 0)
1031 backtrace_free (state, alc, alc_len, error_callback, data);
1032 return ret;
1033}
1034
1035/* Open a separate debug info file, using the debuglink section data
1036 to find it. Returns an open file descriptor, or -1. */
1037
1038static int
1039elf_open_debugfile_by_debuglink (struct backtrace_state *state,
1040 const char *filename,
1041 const char *debuglink_name,
1042 uint32_t debuglink_crc,
1043 backtrace_error_callback error_callback,
1044 void *data)
1045{
1046 int ddescriptor;
1047
1048 ddescriptor = elf_find_debugfile_by_debuglink (state, filename,
1049 debuglink_name,
1050 error_callback, data);
1051 if (ddescriptor < 0)
1052 return -1;
1053
1054 if (debuglink_crc != 0)
1055 {
1056 uint32_t got_crc;
1057
1058 got_crc = elf_crc32_file (state, ddescriptor, error_callback, data);
1059 if (got_crc != debuglink_crc)
1060 {
1061 backtrace_close (ddescriptor, error_callback, data);
1062 return -1;
1063 }
1064 }
1065
1066 return ddescriptor;
1067}
1068
1069/* A function useful for setting a breakpoint for an inflation failure
1070 when this code is compiled with -g. */
1071
1072static void
1073elf_uncompress_failed(void)
1074{
1075}
1076
1077/* *PVAL is the current value being read from the stream, and *PBITS
1078 is the number of valid bits. Ensure that *PVAL holds at least 15
1079 bits by reading additional bits from *PPIN, up to PINEND, as
1080 needed. Updates *PPIN, *PVAL and *PBITS. Returns 1 on success, 0
1081 on error. */
1082
1083static int
1084elf_fetch_bits (const unsigned char **ppin, const unsigned char *pinend,
1085 uint64_t *pval, unsigned int *pbits)
1086{
1087 unsigned int bits;
1088 const unsigned char *pin;
1089 uint64_t val;
1090 uint32_t next;
1091
1092 bits = *pbits;
1093 if (bits >= 15)
1094 return 1;
1095 pin = *ppin;
1096 val = *pval;
1097
1098 if (unlikely (pinend - pin < 4))
1099 {
1100 elf_uncompress_failed ();
1101 return 0;
1102 }
1103
1104#if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) \
1105 && defined(__ORDER_BIG_ENDIAN__) \
1106 && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ \
1107 || __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
1108 /* We've ensured that PIN is aligned. */
1109 next = *(const uint32_t *)pin;
1110
1111#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1112 next = __builtin_bswap32 (next);
1113#endif
1114#else
1115 next = ((uint32_t)pin[0]
1116 | ((uint32_t)pin[1] << 8)
1117 | ((uint32_t)pin[2] << 16)
1118 | ((uint32_t)pin[3] << 24));
1119#endif
1120
1121 val |= (uint64_t)next << bits;
1122 bits += 32;
1123 pin += 4;
1124
1125 /* We will need the next four bytes soon. */
1126 __builtin_prefetch (pin, 0, 0);
1127
1128 *ppin = pin;
1129 *pval = val;
1130 *pbits = bits;
1131 return 1;
1132}
1133
1134/* This is like elf_fetch_bits, but it fetchs the bits backward, and ensures at
1135 least 16 bits. This is for zstd. */
1136
1137static int
1138elf_fetch_bits_backward (const unsigned char **ppin,
1139 const unsigned char *pinend,
1140 uint64_t *pval, unsigned int *pbits)
1141{
1142 unsigned int bits;
1143 const unsigned char *pin;
1144 uint64_t val;
1145 uint32_t next;
1146
1147 bits = *pbits;
1148 if (bits >= 16)
1149 return 1;
1150 pin = *ppin;
1151 val = *pval;
1152
1153 if (unlikely (pin <= pinend))
1154 return 1;
1155
1156 pin -= 4;
1157
1158#if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) \
1159 && defined(__ORDER_BIG_ENDIAN__) \
1160 && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ \
1161 || __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
1162 /* We've ensured that PIN is aligned. */
1163 next = *(const uint32_t *)pin;
1164
1165#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1166 next = __builtin_bswap32 (next);
1167#endif
1168#else
1169 next = ((uint32_t)pin[0]
1170 | ((uint32_t)pin[1] << 8)
1171 | ((uint32_t)pin[2] << 16)
1172 | ((uint32_t)pin[3] << 24));
1173#endif
1174
1175 val <<= 32;
1176 val |= next;
1177 bits += 32;
1178
1179 if (unlikely (pin < pinend))
1180 {
1181 val >>= (pinend - pin) * 8;
1182 bits -= (pinend - pin) * 8;
1183 }
1184
1185 *ppin = pin;
1186 *pval = val;
1187 *pbits = bits;
1188 return 1;
1189}
1190
1191/* Initialize backward fetching when the bitstream starts with a 1 bit in the
1192 last byte in memory (which is the first one that we read). This is used by
1193 zstd decompression. Returns 1 on success, 0 on error. */
1194
1195static int
1196elf_fetch_backward_init (const unsigned char **ppin,
1197 const unsigned char *pinend,
1198 uint64_t *pval, unsigned int *pbits)
1199{
1200 const unsigned char *pin;
1201 unsigned int stream_start;
1202 uint64_t val;
1203 unsigned int bits;
1204
1205 pin = *ppin;
1206 stream_start = (unsigned int)*pin;
1207 if (unlikely (stream_start == 0))
1208 {
1209 elf_uncompress_failed ();
1210 return 0;
1211 }
1212 val = 0;
1213 bits = 0;
1214
1215 /* Align to a 32-bit boundary. */
1216 while ((((uintptr_t)pin) & 3) != 0)
1217 {
1218 val <<= 8;
1219 val |= (uint64_t)*pin;
1220 bits += 8;
1221 --pin;
1222 }
1223
1224 val <<= 8;
1225 val |= (uint64_t)*pin;
1226 bits += 8;
1227
1228 *ppin = pin;
1229 *pval = val;
1230 *pbits = bits;
1231 if (!elf_fetch_bits_backward (ppin, pinend, pval, pbits))
1232 return 0;
1233
1234 *pbits -= __builtin_clz (stream_start) - (sizeof (unsigned int) - 1) * 8 + 1;
1235
1236 if (!elf_fetch_bits_backward (ppin, pinend, pval, pbits))
1237 return 0;
1238
1239 return 1;
1240}
1241
1242/* Huffman code tables, like the rest of the zlib format, are defined
1243 by RFC 1951. We store a Huffman code table as a series of tables
1244 stored sequentially in memory. Each entry in a table is 16 bits.
1245 The first, main, table has 256 entries. It is followed by a set of
1246 secondary tables of length 2 to 128 entries. The maximum length of
1247 a code sequence in the deflate format is 15 bits, so that is all we
1248 need. Each secondary table has an index, which is the offset of
1249 the table in the overall memory storage.
1250
1251 The deflate format says that all codes of a given bit length are
1252 lexicographically consecutive. Perhaps we could have 130 values
1253 that require a 15-bit code, perhaps requiring three secondary
1254 tables of size 128. I don't know if this is actually possible, but
1255 it suggests that the maximum size required for secondary tables is
1256 3 * 128 + 3 * 64 ... == 768. The zlib enough program reports 660
1257 as the maximum. We permit 768, since in addition to the 256 for
1258 the primary table, with two bytes per entry, and with the two
1259 tables we need, that gives us a page.
1260
1261 A single table entry needs to store a value or (for the main table
1262 only) the index and size of a secondary table. Values range from 0
1263 to 285, inclusive. Secondary table indexes, per above, range from
1264 0 to 510. For a value we need to store the number of bits we need
1265 to determine that value (one value may appear multiple times in the
1266 table), which is 1 to 8. For a secondary table we need to store
1267 the number of bits used to index into the table, which is 1 to 7.
1268 And of course we need 1 bit to decide whether we have a value or a
1269 secondary table index. So each entry needs 9 bits for value/table
1270 index, 3 bits for size, 1 bit what it is. For simplicity we use 16
1271 bits per entry. */
1272
1273/* Number of entries we allocate to for one code table. We get a page
1274 for the two code tables we need. */
1275
1276#define ZLIB_HUFFMAN_TABLE_SIZE (1024)
1277
1278/* Bit masks and shifts for the values in the table. */
1279
1280#define ZLIB_HUFFMAN_VALUE_MASK 0x01ff
1281#define ZLIB_HUFFMAN_BITS_SHIFT 9
1282#define ZLIB_HUFFMAN_BITS_MASK 0x7
1283#define ZLIB_HUFFMAN_SECONDARY_SHIFT 12
1284
1285/* For working memory while inflating we need two code tables, we need
1286 an array of code lengths (max value 15, so we use unsigned char),
1287 and an array of unsigned shorts used while building a table. The
1288 latter two arrays must be large enough to hold the maximum number
1289 of code lengths, which RFC 1951 defines as 286 + 30. */
1290
1291#define ZLIB_TABLE_SIZE \
1292 (2 * ZLIB_HUFFMAN_TABLE_SIZE * sizeof (uint16_t) \
1293 + (286 + 30) * sizeof (uint16_t) \
1294 + (286 + 30) * sizeof (unsigned char))
1295
1296#define ZLIB_TABLE_CODELEN_OFFSET \
1297 (2 * ZLIB_HUFFMAN_TABLE_SIZE * sizeof (uint16_t) \
1298 + (286 + 30) * sizeof (uint16_t))
1299
1300#define ZLIB_TABLE_WORK_OFFSET \
1301 (2 * ZLIB_HUFFMAN_TABLE_SIZE * sizeof (uint16_t))
1302
1303#ifdef BACKTRACE_GENERATE_FIXED_HUFFMAN_TABLE
1304
1305/* Used by the main function that generates the fixed table to learn
1306 the table size. */
1307static size_t final_next_secondary;
1308
1309#endif
1310
1311/* Build a Huffman code table from an array of lengths in CODES of
1312 length CODES_LEN. The table is stored into *TABLE. ZDEBUG_TABLE
1313 is the same as for elf_zlib_inflate, used to find some work space.
1314 Returns 1 on success, 0 on error. */
1315
1316static int
1317elf_zlib_inflate_table (unsigned char *codes, size_t codes_len,
1318 uint16_t *zdebug_table, uint16_t *table)
1319{
1320 uint16_t count[16];
1321 uint16_t start[16];
1322 uint16_t prev[16];
1323 uint16_t firstcode[7];
1324 uint16_t *next;
1325 size_t i;
1326 size_t j;
1327 unsigned int code;
1328 size_t next_secondary;
1329
1330 /* Count the number of code of each length. Set NEXT[val] to be the
1331 next value after VAL with the same bit length. */
1332
1333 next = (uint16_t *) (((unsigned char *) zdebug_table)
1334 + ZLIB_TABLE_WORK_OFFSET);
1335
1336 memset (&count[0], 0, 16 * sizeof (uint16_t));
1337 for (i = 0; i < codes_len; ++i)
1338 {
1339 if (unlikely (codes[i] >= 16))
1340 {
1341 elf_uncompress_failed ();
1342 return 0;
1343 }
1344
1345 if (count[codes[i]] == 0)
1346 {
1347 start[codes[i]] = i;
1348 prev[codes[i]] = i;
1349 }
1350 else
1351 {
1352 next[prev[codes[i]]] = i;
1353 prev[codes[i]] = i;
1354 }
1355
1356 ++count[codes[i]];
1357 }
1358
1359 /* For each length, fill in the table for the codes of that
1360 length. */
1361
1362 memset (table, 0, ZLIB_HUFFMAN_TABLE_SIZE * sizeof (uint16_t));
1363
1364 /* Handle the values that do not require a secondary table. */
1365
1366 code = 0;
1367 for (j = 1; j <= 8; ++j)
1368 {
1369 unsigned int jcnt;
1370 unsigned int val;
1371
1372 jcnt = count[j];
1373 if (jcnt == 0)
1374 continue;
1375
1376 if (unlikely (jcnt > (1U << j)))
1377 {
1378 elf_uncompress_failed ();
1379 return 0;
1380 }
1381
1382 /* There are JCNT values that have this length, the values
1383 starting from START[j] continuing through NEXT[VAL]. Those
1384 values are assigned consecutive values starting at CODE. */
1385
1386 val = start[j];
1387 for (i = 0; i < jcnt; ++i)
1388 {
1389 uint16_t tval;
1390 size_t ind;
1391 unsigned int incr;
1392
1393 /* In the compressed bit stream, the value VAL is encoded as
1394 J bits with the value C. */
1395
1396 if (unlikely ((val & ~ZLIB_HUFFMAN_VALUE_MASK) != 0))
1397 {
1398 elf_uncompress_failed ();
1399 return 0;
1400 }
1401
1402 tval = val | ((j - 1) << ZLIB_HUFFMAN_BITS_SHIFT);
1403
1404 /* The table lookup uses 8 bits. If J is less than 8, we
1405 don't know what the other bits will be. We need to fill
1406 in all possibilities in the table. Since the Huffman
1407 code is unambiguous, those entries can't be used for any
1408 other code. */
1409
1410 for (ind = code; ind < 0x100; ind += 1 << j)
1411 {
1412 if (unlikely (table[ind] != 0))
1413 {
1414 elf_uncompress_failed ();
1415 return 0;
1416 }
1417 table[ind] = tval;
1418 }
1419
1420 /* Advance to the next value with this length. */
1421 if (i + 1 < jcnt)
1422 val = next[val];
1423
1424 /* The Huffman codes are stored in the bitstream with the
1425 most significant bit first, as is required to make them
1426 unambiguous. The effect is that when we read them from
1427 the bitstream we see the bit sequence in reverse order:
1428 the most significant bit of the Huffman code is the least
1429 significant bit of the value we read from the bitstream.
1430 That means that to make our table lookups work, we need
1431 to reverse the bits of CODE. Since reversing bits is
1432 tedious and in general requires using a table, we instead
1433 increment CODE in reverse order. That is, if the number
1434 of bits we are currently using, here named J, is 3, we
1435 count as 000, 100, 010, 110, 001, 101, 011, 111, which is
1436 to say the numbers from 0 to 7 but with the bits
1437 reversed. Going to more bits, aka incrementing J,
1438 effectively just adds more zero bits as the beginning,
1439 and as such does not change the numeric value of CODE.
1440
1441 To increment CODE of length J in reverse order, find the
1442 most significant zero bit and set it to one while
1443 clearing all higher bits. In other words, add 1 modulo
1444 2^J, only reversed. */
1445
1446 incr = 1U << (j - 1);
1447 while ((code & incr) != 0)
1448 incr >>= 1;
1449 if (incr == 0)
1450 code = 0;
1451 else
1452 {
1453 code &= incr - 1;
1454 code += incr;
1455 }
1456 }
1457 }
1458
1459 /* Handle the values that require a secondary table. */
1460
1461 /* Set FIRSTCODE, the number at which the codes start, for each
1462 length. */
1463
1464 for (j = 9; j < 16; j++)
1465 {
1466 unsigned int jcnt;
1467 unsigned int k;
1468
1469 jcnt = count[j];
1470 if (jcnt == 0)
1471 continue;
1472
1473 /* There are JCNT values that have this length, the values
1474 starting from START[j]. Those values are assigned
1475 consecutive values starting at CODE. */
1476
1477 firstcode[j - 9] = code;
1478
1479 /* Reverse add JCNT to CODE modulo 2^J. */
1480 for (k = 0; k < j; ++k)
1481 {
1482 if ((jcnt & (1U << k)) != 0)
1483 {
1484 unsigned int m;
1485 unsigned int bit;
1486
1487 bit = 1U << (j - k - 1);
1488 for (m = 0; m < j - k; ++m, bit >>= 1)
1489 {
1490 if ((code & bit) == 0)
1491 {
1492 code += bit;
1493 break;
1494 }
1495 code &= ~bit;
1496 }
1497 jcnt &= ~(1U << k);
1498 }
1499 }
1500 if (unlikely (jcnt != 0))
1501 {
1502 elf_uncompress_failed ();
1503 return 0;
1504 }
1505 }
1506
1507 /* For J from 9 to 15, inclusive, we store COUNT[J] consecutive
1508 values starting at START[J] with consecutive codes starting at
1509 FIRSTCODE[J - 9]. In the primary table we need to point to the
1510 secondary table, and the secondary table will be indexed by J - 9
1511 bits. We count down from 15 so that we install the larger
1512 secondary tables first, as the smaller ones may be embedded in
1513 the larger ones. */
1514
1515 next_secondary = 0; /* Index of next secondary table (after primary). */
1516 for (j = 15; j >= 9; j--)
1517 {
1518 unsigned int jcnt;
1519 unsigned int val;
1520 size_t primary; /* Current primary index. */
1521 size_t secondary; /* Offset to current secondary table. */
1522 size_t secondary_bits; /* Bit size of current secondary table. */
1523
1524 jcnt = count[j];
1525 if (jcnt == 0)
1526 continue;
1527
1528 val = start[j];
1529 code = firstcode[j - 9];
1530 primary = 0x100;
1531 secondary = 0;
1532 secondary_bits = 0;
1533 for (i = 0; i < jcnt; ++i)
1534 {
1535 uint16_t tval;
1536 size_t ind;
1537 unsigned int incr;
1538
1539 if ((code & 0xff) != primary)
1540 {
1541 uint16_t tprimary;
1542
1543 /* Fill in a new primary table entry. */
1544
1545 primary = code & 0xff;
1546
1547 tprimary = table[primary];
1548 if (tprimary == 0)
1549 {
1550 /* Start a new secondary table. */
1551
1552 if (unlikely ((next_secondary & ZLIB_HUFFMAN_VALUE_MASK)
1553 != next_secondary))
1554 {
1555 elf_uncompress_failed ();
1556 return 0;
1557 }
1558
1559 secondary = next_secondary;
1560 secondary_bits = j - 8;
1561 next_secondary += 1 << secondary_bits;
1562 table[primary] = (secondary
1563 + ((j - 8) << ZLIB_HUFFMAN_BITS_SHIFT)
1564 + (1U << ZLIB_HUFFMAN_SECONDARY_SHIFT));
1565 }
1566 else
1567 {
1568 /* There is an existing entry. It had better be a
1569 secondary table with enough bits. */
1570 if (unlikely ((tprimary
1571 & (1U << ZLIB_HUFFMAN_SECONDARY_SHIFT))
1572 == 0))
1573 {
1574 elf_uncompress_failed ();
1575 return 0;
1576 }
1577 secondary = tprimary & ZLIB_HUFFMAN_VALUE_MASK;
1578 secondary_bits = ((tprimary >> ZLIB_HUFFMAN_BITS_SHIFT)
1579 & ZLIB_HUFFMAN_BITS_MASK);
1580 if (unlikely (secondary_bits < j - 8))
1581 {
1582 elf_uncompress_failed ();
1583 return 0;
1584 }
1585 }
1586 }
1587
1588 /* Fill in secondary table entries. */
1589
1590 tval = val | ((j - 8) << ZLIB_HUFFMAN_BITS_SHIFT);
1591
1592 for (ind = code >> 8;
1593 ind < (1U << secondary_bits);
1594 ind += 1U << (j - 8))
1595 {
1596 if (unlikely (table[secondary + 0x100 + ind] != 0))
1597 {
1598 elf_uncompress_failed ();
1599 return 0;
1600 }
1601 table[secondary + 0x100 + ind] = tval;
1602 }
1603
1604 if (i + 1 < jcnt)
1605 val = next[val];
1606
1607 incr = 1U << (j - 1);
1608 while ((code & incr) != 0)
1609 incr >>= 1;
1610 if (incr == 0)
1611 code = 0;
1612 else
1613 {
1614 code &= incr - 1;
1615 code += incr;
1616 }
1617 }
1618 }
1619
1620#ifdef BACKTRACE_GENERATE_FIXED_HUFFMAN_TABLE
1621 final_next_secondary = next_secondary;
1622#endif
1623
1624 return 1;
1625}
1626
1627#ifdef BACKTRACE_GENERATE_FIXED_HUFFMAN_TABLE
1628
1629/* Used to generate the fixed Huffman table for block type 1. */
1630
1631#include <stdio.h>
1632
1633static uint16_t table[ZLIB_TABLE_SIZE];
1634static unsigned char codes[288];
1635
1636int
1637main ()
1638{
1639 size_t i;
1640
1641 for (i = 0; i <= 143; ++i)
1642 codes[i] = 8;
1643 for (i = 144; i <= 255; ++i)
1644 codes[i] = 9;
1645 for (i = 256; i <= 279; ++i)
1646 codes[i] = 7;
1647 for (i = 280; i <= 287; ++i)
1648 codes[i] = 8;
1649 if (!elf_zlib_inflate_table (&codes[0], 288, &table[0], &table[0]))
1650 {
1651 fprintf (stderr, "elf_zlib_inflate_table failed\n");
1652 exit (EXIT_FAILURE);
1653 }
1654
1655 printf ("static const uint16_t elf_zlib_default_table[%#zx] =\n",
1656 final_next_secondary + 0x100);
1657 printf ("{\n");
1658 for (i = 0; i < final_next_secondary + 0x100; i += 8)
1659 {
1660 size_t j;
1661
1662 printf (" ");
1663 for (j = i; j < final_next_secondary + 0x100 && j < i + 8; ++j)
1664 printf (" %#x,", table[j]);
1665 printf ("\n");
1666 }
1667 printf ("};\n");
1668 printf ("\n");
1669
1670 for (i = 0; i < 32; ++i)
1671 codes[i] = 5;
1672 if (!elf_zlib_inflate_table (&codes[0], 32, &table[0], &table[0]))
1673 {
1674 fprintf (stderr, "elf_zlib_inflate_table failed\n");
1675 exit (EXIT_FAILURE);
1676 }
1677
1678 printf ("static const uint16_t elf_zlib_default_dist_table[%#zx] =\n",
1679 final_next_secondary + 0x100);
1680 printf ("{\n");
1681 for (i = 0; i < final_next_secondary + 0x100; i += 8)
1682 {
1683 size_t j;
1684
1685 printf (" ");
1686 for (j = i; j < final_next_secondary + 0x100 && j < i + 8; ++j)
1687 printf (" %#x,", table[j]);
1688 printf ("\n");
1689 }
1690 printf ("};\n");
1691
1692 return 0;
1693}
1694
1695#endif
1696
1697/* The fixed tables generated by the #ifdef'ed out main function
1698 above. */
1699
1700static const uint16_t elf_zlib_default_table[0x170] =
1701{
1702 0xd00, 0xe50, 0xe10, 0xf18, 0xd10, 0xe70, 0xe30, 0x1230,
1703 0xd08, 0xe60, 0xe20, 0x1210, 0xe00, 0xe80, 0xe40, 0x1250,
1704 0xd04, 0xe58, 0xe18, 0x1200, 0xd14, 0xe78, 0xe38, 0x1240,
1705 0xd0c, 0xe68, 0xe28, 0x1220, 0xe08, 0xe88, 0xe48, 0x1260,
1706 0xd02, 0xe54, 0xe14, 0xf1c, 0xd12, 0xe74, 0xe34, 0x1238,
1707 0xd0a, 0xe64, 0xe24, 0x1218, 0xe04, 0xe84, 0xe44, 0x1258,
1708 0xd06, 0xe5c, 0xe1c, 0x1208, 0xd16, 0xe7c, 0xe3c, 0x1248,
1709 0xd0e, 0xe6c, 0xe2c, 0x1228, 0xe0c, 0xe8c, 0xe4c, 0x1268,
1710 0xd01, 0xe52, 0xe12, 0xf1a, 0xd11, 0xe72, 0xe32, 0x1234,
1711 0xd09, 0xe62, 0xe22, 0x1214, 0xe02, 0xe82, 0xe42, 0x1254,
1712 0xd05, 0xe5a, 0xe1a, 0x1204, 0xd15, 0xe7a, 0xe3a, 0x1244,
1713 0xd0d, 0xe6a, 0xe2a, 0x1224, 0xe0a, 0xe8a, 0xe4a, 0x1264,
1714 0xd03, 0xe56, 0xe16, 0xf1e, 0xd13, 0xe76, 0xe36, 0x123c,
1715 0xd0b, 0xe66, 0xe26, 0x121c, 0xe06, 0xe86, 0xe46, 0x125c,
1716 0xd07, 0xe5e, 0xe1e, 0x120c, 0xd17, 0xe7e, 0xe3e, 0x124c,
1717 0xd0f, 0xe6e, 0xe2e, 0x122c, 0xe0e, 0xe8e, 0xe4e, 0x126c,
1718 0xd00, 0xe51, 0xe11, 0xf19, 0xd10, 0xe71, 0xe31, 0x1232,
1719 0xd08, 0xe61, 0xe21, 0x1212, 0xe01, 0xe81, 0xe41, 0x1252,
1720 0xd04, 0xe59, 0xe19, 0x1202, 0xd14, 0xe79, 0xe39, 0x1242,
1721 0xd0c, 0xe69, 0xe29, 0x1222, 0xe09, 0xe89, 0xe49, 0x1262,
1722 0xd02, 0xe55, 0xe15, 0xf1d, 0xd12, 0xe75, 0xe35, 0x123a,
1723 0xd0a, 0xe65, 0xe25, 0x121a, 0xe05, 0xe85, 0xe45, 0x125a,
1724 0xd06, 0xe5d, 0xe1d, 0x120a, 0xd16, 0xe7d, 0xe3d, 0x124a,
1725 0xd0e, 0xe6d, 0xe2d, 0x122a, 0xe0d, 0xe8d, 0xe4d, 0x126a,
1726 0xd01, 0xe53, 0xe13, 0xf1b, 0xd11, 0xe73, 0xe33, 0x1236,
1727 0xd09, 0xe63, 0xe23, 0x1216, 0xe03, 0xe83, 0xe43, 0x1256,
1728 0xd05, 0xe5b, 0xe1b, 0x1206, 0xd15, 0xe7b, 0xe3b, 0x1246,
1729 0xd0d, 0xe6b, 0xe2b, 0x1226, 0xe0b, 0xe8b, 0xe4b, 0x1266,
1730 0xd03, 0xe57, 0xe17, 0xf1f, 0xd13, 0xe77, 0xe37, 0x123e,
1731 0xd0b, 0xe67, 0xe27, 0x121e, 0xe07, 0xe87, 0xe47, 0x125e,
1732 0xd07, 0xe5f, 0xe1f, 0x120e, 0xd17, 0xe7f, 0xe3f, 0x124e,
1733 0xd0f, 0xe6f, 0xe2f, 0x122e, 0xe0f, 0xe8f, 0xe4f, 0x126e,
1734 0x290, 0x291, 0x292, 0x293, 0x294, 0x295, 0x296, 0x297,
1735 0x298, 0x299, 0x29a, 0x29b, 0x29c, 0x29d, 0x29e, 0x29f,
1736 0x2a0, 0x2a1, 0x2a2, 0x2a3, 0x2a4, 0x2a5, 0x2a6, 0x2a7,
1737 0x2a8, 0x2a9, 0x2aa, 0x2ab, 0x2ac, 0x2ad, 0x2ae, 0x2af,
1738 0x2b0, 0x2b1, 0x2b2, 0x2b3, 0x2b4, 0x2b5, 0x2b6, 0x2b7,
1739 0x2b8, 0x2b9, 0x2ba, 0x2bb, 0x2bc, 0x2bd, 0x2be, 0x2bf,
1740 0x2c0, 0x2c1, 0x2c2, 0x2c3, 0x2c4, 0x2c5, 0x2c6, 0x2c7,
1741 0x2c8, 0x2c9, 0x2ca, 0x2cb, 0x2cc, 0x2cd, 0x2ce, 0x2cf,
1742 0x2d0, 0x2d1, 0x2d2, 0x2d3, 0x2d4, 0x2d5, 0x2d6, 0x2d7,
1743 0x2d8, 0x2d9, 0x2da, 0x2db, 0x2dc, 0x2dd, 0x2de, 0x2df,
1744 0x2e0, 0x2e1, 0x2e2, 0x2e3, 0x2e4, 0x2e5, 0x2e6, 0x2e7,
1745 0x2e8, 0x2e9, 0x2ea, 0x2eb, 0x2ec, 0x2ed, 0x2ee, 0x2ef,
1746 0x2f0, 0x2f1, 0x2f2, 0x2f3, 0x2f4, 0x2f5, 0x2f6, 0x2f7,
1747 0x2f8, 0x2f9, 0x2fa, 0x2fb, 0x2fc, 0x2fd, 0x2fe, 0x2ff,
1748};
1749
1750static const uint16_t elf_zlib_default_dist_table[0x100] =
1751{
1752 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c,
1753 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e,
1754 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d,
1755 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f,
1756 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c,
1757 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e,
1758 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d,
1759 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f,
1760 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c,
1761 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e,
1762 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d,
1763 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f,
1764 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c,
1765 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e,
1766 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d,
1767 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f,
1768 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c,
1769 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e,
1770 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d,
1771 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f,
1772 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c,
1773 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e,
1774 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d,
1775 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f,
1776 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c,
1777 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e,
1778 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d,
1779 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f,
1780 0x800, 0x810, 0x808, 0x818, 0x804, 0x814, 0x80c, 0x81c,
1781 0x802, 0x812, 0x80a, 0x81a, 0x806, 0x816, 0x80e, 0x81e,
1782 0x801, 0x811, 0x809, 0x819, 0x805, 0x815, 0x80d, 0x81d,
1783 0x803, 0x813, 0x80b, 0x81b, 0x807, 0x817, 0x80f, 0x81f,
1784};
1785
1786/* Inflate a zlib stream from PIN/SIN to POUT/SOUT. Return 1 on
1787 success, 0 on some error parsing the stream. */
1788
1789static int
1790elf_zlib_inflate (const unsigned char *pin, size_t sin, uint16_t *zdebug_table,
1791 unsigned char *pout, size_t sout)
1792{
1793 unsigned char *porigout;
1794 const unsigned char *pinend;
1795 unsigned char *poutend;
1796
1797 /* We can apparently see multiple zlib streams concatenated
1798 together, so keep going as long as there is something to read.
1799 The last 4 bytes are the checksum. */
1800 porigout = pout;
1801 pinend = pin + sin;
1802 poutend = pout + sout;
1803 while ((pinend - pin) > 4)
1804 {
1805 uint64_t val;
1806 unsigned int bits;
1807 int last;
1808
1809 /* Read the two byte zlib header. */
1810
1811 if (unlikely ((pin[0] & 0xf) != 8)) /* 8 is zlib encoding. */
1812 {
1813 /* Unknown compression method. */
1814 elf_uncompress_failed ();
1815 return 0;
1816 }
1817 if (unlikely ((pin[0] >> 4) > 7))
1818 {
1819 /* Window size too large. Other than this check, we don't
1820 care about the window size. */
1821 elf_uncompress_failed ();
1822 return 0;
1823 }
1824 if (unlikely ((pin[1] & 0x20) != 0))
1825 {
1826 /* Stream expects a predefined dictionary, but we have no
1827 dictionary. */
1828 elf_uncompress_failed ();
1829 return 0;
1830 }
1831 val = (pin[0] << 8) | pin[1];
1832 if (unlikely (val % 31 != 0))
1833 {
1834 /* Header check failure. */
1835 elf_uncompress_failed ();
1836 return 0;
1837 }
1838 pin += 2;
1839
1840 /* Align PIN to a 32-bit boundary. */
1841
1842 val = 0;
1843 bits = 0;
1844 while ((((uintptr_t) pin) & 3) != 0)
1845 {
1846 val |= (uint64_t)*pin << bits;
1847 bits += 8;
1848 ++pin;
1849 }
1850
1851 /* Read blocks until one is marked last. */
1852
1853 last = 0;
1854
1855 while (!last)
1856 {
1857 unsigned int type;
1858 const uint16_t *tlit;
1859 const uint16_t *tdist;
1860
1861 if (!elf_fetch_bits (&pin, pinend, &val, &bits))
1862 return 0;
1863
1864 last = val & 1;
1865 type = (val >> 1) & 3;
1866 val >>= 3;
1867 bits -= 3;
1868
1869 if (unlikely (type == 3))
1870 {
1871 /* Invalid block type. */
1872 elf_uncompress_failed ();
1873 return 0;
1874 }
1875
1876 if (type == 0)
1877 {
1878 uint16_t len;
1879 uint16_t lenc;
1880
1881 /* An uncompressed block. */
1882
1883 /* If we've read ahead more than a byte, back up. */
1884 while (bits >= 8)
1885 {
1886 --pin;
1887 bits -= 8;
1888 }
1889
1890 val = 0;
1891 bits = 0;
1892 if (unlikely ((pinend - pin) < 4))
1893 {
1894 /* Missing length. */
1895 elf_uncompress_failed ();
1896 return 0;
1897 }
1898 len = pin[0] | (pin[1] << 8);
1899 lenc = pin[2] | (pin[3] << 8);
1900 pin += 4;
1901 lenc = ~lenc;
1902 if (unlikely (len != lenc))
1903 {
1904 /* Corrupt data. */
1905 elf_uncompress_failed ();
1906 return 0;
1907 }
1908 if (unlikely (len > (unsigned int) (pinend - pin)
1909 || len > (unsigned int) (poutend - pout)))
1910 {
1911 /* Not enough space in buffers. */
1912 elf_uncompress_failed ();
1913 return 0;
1914 }
1915 memcpy (pout, pin, len);
1916 pout += len;
1917 pin += len;
1918
1919 /* Align PIN. */
1920 while ((((uintptr_t) pin) & 3) != 0)
1921 {
1922 val |= (uint64_t)*pin << bits;
1923 bits += 8;
1924 ++pin;
1925 }
1926
1927 /* Go around to read the next block. */
1928 continue;
1929 }
1930
1931 if (type == 1)
1932 {
1933 tlit = elf_zlib_default_table;
1934 tdist = elf_zlib_default_dist_table;
1935 }
1936 else
1937 {
1938 unsigned int nlit;
1939 unsigned int ndist;
1940 unsigned int nclen;
1941 unsigned char codebits[19];
1942 unsigned char *plenbase;
1943 unsigned char *plen;
1944 unsigned char *plenend;
1945
1946 /* Read a Huffman encoding table. The various magic
1947 numbers here are from RFC 1951. */
1948
1949 if (!elf_fetch_bits (&pin, pinend, &val, &bits))
1950 return 0;
1951
1952 nlit = (val & 0x1f) + 257;
1953 val >>= 5;
1954 ndist = (val & 0x1f) + 1;
1955 val >>= 5;
1956 nclen = (val & 0xf) + 4;
1957 val >>= 4;
1958 bits -= 14;
1959 if (unlikely (nlit > 286 || ndist > 30))
1960 {
1961 /* Values out of range. */
1962 elf_uncompress_failed ();
1963 return 0;
1964 }
1965
1966 /* Read and build the table used to compress the
1967 literal, length, and distance codes. */
1968
1969 memset(&codebits[0], 0, 19);
1970
1971 /* There are always at least 4 elements in the
1972 table. */
1973
1974 if (!elf_fetch_bits (&pin, pinend, &val, &bits))
1975 return 0;
1976
1977 codebits[16] = val & 7;
1978 codebits[17] = (val >> 3) & 7;
1979 codebits[18] = (val >> 6) & 7;
1980 codebits[0] = (val >> 9) & 7;
1981 val >>= 12;
1982 bits -= 12;
1983
1984 if (nclen == 4)
1985 goto codebitsdone;
1986
1987 codebits[8] = val & 7;
1988 val >>= 3;
1989 bits -= 3;
1990
1991 if (nclen == 5)
1992 goto codebitsdone;
1993
1994 if (!elf_fetch_bits (&pin, pinend, &val, &bits))
1995 return 0;
1996
1997 codebits[7] = val & 7;
1998 val >>= 3;
1999 bits -= 3;
2000
2001 if (nclen == 6)
2002 goto codebitsdone;
2003
2004 codebits[9] = val & 7;
2005 val >>= 3;
2006 bits -= 3;
2007
2008 if (nclen == 7)
2009 goto codebitsdone;
2010
2011 codebits[6] = val & 7;
2012 val >>= 3;
2013 bits -= 3;
2014
2015 if (nclen == 8)
2016 goto codebitsdone;
2017
2018 codebits[10] = val & 7;
2019 val >>= 3;
2020 bits -= 3;
2021
2022 if (nclen == 9)
2023 goto codebitsdone;
2024
2025 codebits[5] = val & 7;
2026 val >>= 3;
2027 bits -= 3;
2028
2029 if (nclen == 10)
2030 goto codebitsdone;
2031
2032 if (!elf_fetch_bits (&pin, pinend, &val, &bits))
2033 return 0;
2034
2035 codebits[11] = val & 7;
2036 val >>= 3;
2037 bits -= 3;
2038
2039 if (nclen == 11)
2040 goto codebitsdone;
2041
2042 codebits[4] = val & 7;
2043 val >>= 3;
2044 bits -= 3;
2045
2046 if (nclen == 12)
2047 goto codebitsdone;
2048
2049 codebits[12] = val & 7;
2050 val >>= 3;
2051 bits -= 3;
2052
2053 if (nclen == 13)
2054 goto codebitsdone;
2055
2056 codebits[3] = val & 7;
2057 val >>= 3;
2058 bits -= 3;
2059
2060 if (nclen == 14)
2061 goto codebitsdone;
2062
2063 codebits[13] = val & 7;
2064 val >>= 3;
2065 bits -= 3;
2066
2067 if (nclen == 15)
2068 goto codebitsdone;
2069
2070 if (!elf_fetch_bits (&pin, pinend, &val, &bits))
2071 return 0;
2072
2073 codebits[2] = val & 7;
2074 val >>= 3;
2075 bits -= 3;
2076
2077 if (nclen == 16)
2078 goto codebitsdone;
2079
2080 codebits[14] = val & 7;
2081 val >>= 3;
2082 bits -= 3;
2083
2084 if (nclen == 17)
2085 goto codebitsdone;
2086
2087 codebits[1] = val & 7;
2088 val >>= 3;
2089 bits -= 3;
2090
2091 if (nclen == 18)
2092 goto codebitsdone;
2093
2094 codebits[15] = val & 7;
2095 val >>= 3;
2096 bits -= 3;
2097
2098 codebitsdone:
2099
2100 if (!elf_zlib_inflate_table (codebits, 19, zdebug_table,
2101 zdebug_table))
2102 return 0;
2103
2104 /* Read the compressed bit lengths of the literal,
2105 length, and distance codes. We have allocated space
2106 at the end of zdebug_table to hold them. */
2107
2108 plenbase = (((unsigned char *) zdebug_table)
2109 + ZLIB_TABLE_CODELEN_OFFSET);
2110 plen = plenbase;
2111 plenend = plen + nlit + ndist;
2112 while (plen < plenend)
2113 {
2114 uint16_t t;
2115 unsigned int b;
2116 uint16_t v;
2117
2118 if (!elf_fetch_bits (&pin, pinend, &val, &bits))
2119 return 0;
2120
2121 t = zdebug_table[val & 0xff];
2122
2123 /* The compression here uses bit lengths up to 7, so
2124 a secondary table is never necessary. */
2125 if (unlikely ((t & (1U << ZLIB_HUFFMAN_SECONDARY_SHIFT))
2126 != 0))
2127 {
2128 elf_uncompress_failed ();
2129 return 0;
2130 }
2131
2132 b = (t >> ZLIB_HUFFMAN_BITS_SHIFT) & ZLIB_HUFFMAN_BITS_MASK;
2133 val >>= b + 1;
2134 bits -= b + 1;
2135
2136 v = t & ZLIB_HUFFMAN_VALUE_MASK;
2137 if (v < 16)
2138 *plen++ = v;
2139 else if (v == 16)
2140 {
2141 unsigned int c;
2142 unsigned int prev;
2143
2144 /* Copy previous entry 3 to 6 times. */
2145
2146 if (unlikely (plen == plenbase))
2147 {
2148 elf_uncompress_failed ();
2149 return 0;
2150 }
2151
2152 /* We used up to 7 bits since the last
2153 elf_fetch_bits, so we have at least 8 bits
2154 available here. */
2155
2156 c = 3 + (val & 0x3);
2157 val >>= 2;
2158 bits -= 2;
2159 if (unlikely ((unsigned int) (plenend - plen) < c))
2160 {
2161 elf_uncompress_failed ();
2162 return 0;
2163 }
2164
2165 prev = plen[-1];
2166 switch (c)
2167 {
2168 case 6:
2169 *plen++ = prev;
2170 ATTRIBUTE_FALLTHROUGH;
2171 case 5:
2172 *plen++ = prev;
2173 ATTRIBUTE_FALLTHROUGH;
2174 case 4:
2175 *plen++ = prev;
2176 }
2177 *plen++ = prev;
2178 *plen++ = prev;
2179 *plen++ = prev;
2180 }
2181 else if (v == 17)
2182 {
2183 unsigned int c;
2184
2185 /* Store zero 3 to 10 times. */
2186
2187 /* We used up to 7 bits since the last
2188 elf_fetch_bits, so we have at least 8 bits
2189 available here. */
2190
2191 c = 3 + (val & 0x7);
2192 val >>= 3;
2193 bits -= 3;
2194 if (unlikely ((unsigned int) (plenend - plen) < c))
2195 {
2196 elf_uncompress_failed ();
2197 return 0;
2198 }
2199
2200 switch (c)
2201 {
2202 case 10:
2203 *plen++ = 0;
2204 ATTRIBUTE_FALLTHROUGH;
2205 case 9:
2206 *plen++ = 0;
2207 ATTRIBUTE_FALLTHROUGH;
2208 case 8:
2209 *plen++ = 0;
2210 ATTRIBUTE_FALLTHROUGH;
2211 case 7:
2212 *plen++ = 0;
2213 ATTRIBUTE_FALLTHROUGH;
2214 case 6:
2215 *plen++ = 0;
2216 ATTRIBUTE_FALLTHROUGH;
2217 case 5:
2218 *plen++ = 0;
2219 ATTRIBUTE_FALLTHROUGH;
2220 case 4:
2221 *plen++ = 0;
2222 }
2223 *plen++ = 0;
2224 *plen++ = 0;
2225 *plen++ = 0;
2226 }
2227 else if (v == 18)
2228 {
2229 unsigned int c;
2230
2231 /* Store zero 11 to 138 times. */
2232
2233 /* We used up to 7 bits since the last
2234 elf_fetch_bits, so we have at least 8 bits
2235 available here. */
2236
2237 c = 11 + (val & 0x7f);
2238 val >>= 7;
2239 bits -= 7;
2240 if (unlikely ((unsigned int) (plenend - plen) < c))
2241 {
2242 elf_uncompress_failed ();
2243 return 0;
2244 }
2245
2246 memset (plen, 0, c);
2247 plen += c;
2248 }
2249 else
2250 {
2251 elf_uncompress_failed ();
2252 return 0;
2253 }
2254 }
2255
2256 /* Make sure that the stop code can appear. */
2257
2258 plen = plenbase;
2259 if (unlikely (plen[256] == 0))
2260 {
2261 elf_uncompress_failed ();
2262 return 0;
2263 }
2264
2265 /* Build the decompression tables. */
2266
2267 if (!elf_zlib_inflate_table (plen, nlit, zdebug_table,
2268 zdebug_table))
2269 return 0;
2270 if (!elf_zlib_inflate_table (plen + nlit, ndist, zdebug_table,
2271 (zdebug_table
2272 + ZLIB_HUFFMAN_TABLE_SIZE)))
2273 return 0;
2274 tlit = zdebug_table;
2275 tdist = zdebug_table + ZLIB_HUFFMAN_TABLE_SIZE;
2276 }
2277
2278 /* Inflate values until the end of the block. This is the
2279 main loop of the inflation code. */
2280
2281 while (1)
2282 {
2283 uint16_t t;
2284 unsigned int b;
2285 uint16_t v;
2286 unsigned int lit;
2287
2288 if (!elf_fetch_bits (&pin, pinend, &val, &bits))
2289 return 0;
2290
2291 t = tlit[val & 0xff];
2292 b = (t >> ZLIB_HUFFMAN_BITS_SHIFT) & ZLIB_HUFFMAN_BITS_MASK;
2293 v = t & ZLIB_HUFFMAN_VALUE_MASK;
2294
2295 if ((t & (1U << ZLIB_HUFFMAN_SECONDARY_SHIFT)) == 0)
2296 {
2297 lit = v;
2298 val >>= b + 1;
2299 bits -= b + 1;
2300 }
2301 else
2302 {
2303 t = tlit[v + 0x100 + ((val >> 8) & ((1U << b) - 1))];
2304 b = (t >> ZLIB_HUFFMAN_BITS_SHIFT) & ZLIB_HUFFMAN_BITS_MASK;
2305 lit = t & ZLIB_HUFFMAN_VALUE_MASK;
2306 val >>= b + 8;
2307 bits -= b + 8;
2308 }
2309
2310 if (lit < 256)
2311 {
2312 if (unlikely (pout == poutend))
2313 {
2314 elf_uncompress_failed ();
2315 return 0;
2316 }
2317
2318 *pout++ = lit;
2319
2320 /* We will need to write the next byte soon. We ask
2321 for high temporal locality because we will write
2322 to the whole cache line soon. */
2323 __builtin_prefetch (pout, 1, 3);
2324 }
2325 else if (lit == 256)
2326 {
2327 /* The end of the block. */
2328 break;
2329 }
2330 else
2331 {
2332 unsigned int dist;
2333 unsigned int len;
2334
2335 /* Convert lit into a length. */
2336
2337 if (lit < 265)
2338 len = lit - 257 + 3;
2339 else if (lit == 285)
2340 len = 258;
2341 else if (unlikely (lit > 285))
2342 {
2343 elf_uncompress_failed ();
2344 return 0;
2345 }
2346 else
2347 {
2348 unsigned int extra;
2349
2350 if (!elf_fetch_bits (&pin, pinend, &val, &bits))
2351 return 0;
2352
2353 /* This is an expression for the table of length
2354 codes in RFC 1951 3.2.5. */
2355 lit -= 265;
2356 extra = (lit >> 2) + 1;
2357 len = (lit & 3) << extra;
2358 len += 11;
2359 len += ((1U << (extra - 1)) - 1) << 3;
2360 len += val & ((1U << extra) - 1);
2361 val >>= extra;
2362 bits -= extra;
2363 }
2364
2365 if (!elf_fetch_bits (&pin, pinend, &val, &bits))
2366 return 0;
2367
2368 t = tdist[val & 0xff];
2369 b = (t >> ZLIB_HUFFMAN_BITS_SHIFT) & ZLIB_HUFFMAN_BITS_MASK;
2370 v = t & ZLIB_HUFFMAN_VALUE_MASK;
2371
2372 if ((t & (1U << ZLIB_HUFFMAN_SECONDARY_SHIFT)) == 0)
2373 {
2374 dist = v;
2375 val >>= b + 1;
2376 bits -= b + 1;
2377 }
2378 else
2379 {
2380 t = tdist[v + 0x100 + ((val >> 8) & ((1U << b) - 1))];
2381 b = ((t >> ZLIB_HUFFMAN_BITS_SHIFT)
2382 & ZLIB_HUFFMAN_BITS_MASK);
2383 dist = t & ZLIB_HUFFMAN_VALUE_MASK;
2384 val >>= b + 8;
2385 bits -= b + 8;
2386 }
2387
2388 /* Convert dist to a distance. */
2389
2390 if (dist == 0)
2391 {
2392 /* A distance of 1. A common case, meaning
2393 repeat the last character LEN times. */
2394
2395 if (unlikely (pout == porigout))
2396 {
2397 elf_uncompress_failed ();
2398 return 0;
2399 }
2400
2401 if (unlikely ((unsigned int) (poutend - pout) < len))
2402 {
2403 elf_uncompress_failed ();
2404 return 0;
2405 }
2406
2407 memset (pout, pout[-1], len);
2408 pout += len;
2409 }
2410 else if (unlikely (dist > 29))
2411 {
2412 elf_uncompress_failed ();
2413 return 0;
2414 }
2415 else
2416 {
2417 if (dist < 4)
2418 dist = dist + 1;
2419 else
2420 {
2421 unsigned int extra;
2422
2423 if (!elf_fetch_bits (&pin, pinend, &val, &bits))
2424 return 0;
2425
2426 /* This is an expression for the table of
2427 distance codes in RFC 1951 3.2.5. */
2428 dist -= 4;
2429 extra = (dist >> 1) + 1;
2430 dist = (dist & 1) << extra;
2431 dist += 5;
2432 dist += ((1U << (extra - 1)) - 1) << 2;
2433 dist += val & ((1U << extra) - 1);
2434 val >>= extra;
2435 bits -= extra;
2436 }
2437
2438 /* Go back dist bytes, and copy len bytes from
2439 there. */
2440
2441 if (unlikely ((unsigned int) (pout - porigout) < dist))
2442 {
2443 elf_uncompress_failed ();
2444 return 0;
2445 }
2446
2447 if (unlikely ((unsigned int) (poutend - pout) < len))
2448 {
2449 elf_uncompress_failed ();
2450 return 0;
2451 }
2452
2453 if (dist >= len)
2454 {
2455 memcpy (pout, pout - dist, len);
2456 pout += len;
2457 }
2458 else
2459 {
2460 while (len > 0)
2461 {
2462 unsigned int copy;
2463
2464 copy = len < dist ? len : dist;
2465 memcpy (pout, pout - dist, copy);
2466 len -= copy;
2467 pout += copy;
2468 }
2469 }
2470 }
2471 }
2472 }
2473 }
2474 }
2475
2476 /* We should have filled the output buffer. */
2477 if (unlikely (pout != poutend))
2478 {
2479 elf_uncompress_failed ();
2480 return 0;
2481 }
2482
2483 return 1;
2484}
2485
2486/* Verify the zlib checksum. The checksum is in the 4 bytes at
2487 CHECKBYTES, and the uncompressed data is at UNCOMPRESSED /
2488 UNCOMPRESSED_SIZE. Returns 1 on success, 0 on failure. */
2489
2490static int
2491elf_zlib_verify_checksum (const unsigned char *checkbytes,
2492 const unsigned char *uncompressed,
2493 size_t uncompressed_size)
2494{
2495 unsigned int i;
2496 unsigned int cksum;
2497 const unsigned char *p;
2498 uint32_t s1;
2499 uint32_t s2;
2500 size_t hsz;
2501
2502 cksum = 0;
2503 for (i = 0; i < 4; i++)
2504 cksum = (cksum << 8) | checkbytes[i];
2505
2506 s1 = 1;
2507 s2 = 0;
2508
2509 /* Minimize modulo operations. */
2510
2511 p = uncompressed;
2512 hsz = uncompressed_size;
2513 while (hsz >= 5552)
2514 {
2515 for (i = 0; i < 5552; i += 16)
2516 {
2517 /* Manually unroll loop 16 times. */
2518 s1 = s1 + *p++;
2519 s2 = s2 + s1;
2520 s1 = s1 + *p++;
2521 s2 = s2 + s1;
2522 s1 = s1 + *p++;
2523 s2 = s2 + s1;
2524 s1 = s1 + *p++;
2525 s2 = s2 + s1;
2526 s1 = s1 + *p++;
2527 s2 = s2 + s1;
2528 s1 = s1 + *p++;
2529 s2 = s2 + s1;
2530 s1 = s1 + *p++;
2531 s2 = s2 + s1;
2532 s1 = s1 + *p++;
2533 s2 = s2 + s1;
2534 s1 = s1 + *p++;
2535 s2 = s2 + s1;
2536 s1 = s1 + *p++;
2537 s2 = s2 + s1;
2538 s1 = s1 + *p++;
2539 s2 = s2 + s1;
2540 s1 = s1 + *p++;
2541 s2 = s2 + s1;
2542 s1 = s1 + *p++;
2543 s2 = s2 + s1;
2544 s1 = s1 + *p++;
2545 s2 = s2 + s1;
2546 s1 = s1 + *p++;
2547 s2 = s2 + s1;
2548 s1 = s1 + *p++;
2549 s2 = s2 + s1;
2550 }
2551 hsz -= 5552;
2552 s1 %= 65521;
2553 s2 %= 65521;
2554 }
2555
2556 while (hsz >= 16)
2557 {
2558 /* Manually unroll loop 16 times. */
2559 s1 = s1 + *p++;
2560 s2 = s2 + s1;
2561 s1 = s1 + *p++;
2562 s2 = s2 + s1;
2563 s1 = s1 + *p++;
2564 s2 = s2 + s1;
2565 s1 = s1 + *p++;
2566 s2 = s2 + s1;
2567 s1 = s1 + *p++;
2568 s2 = s2 + s1;
2569 s1 = s1 + *p++;
2570 s2 = s2 + s1;
2571 s1 = s1 + *p++;
2572 s2 = s2 + s1;
2573 s1 = s1 + *p++;
2574 s2 = s2 + s1;
2575 s1 = s1 + *p++;
2576 s2 = s2 + s1;
2577 s1 = s1 + *p++;
2578 s2 = s2 + s1;
2579 s1 = s1 + *p++;
2580 s2 = s2 + s1;
2581 s1 = s1 + *p++;
2582 s2 = s2 + s1;
2583 s1 = s1 + *p++;
2584 s2 = s2 + s1;
2585 s1 = s1 + *p++;
2586 s2 = s2 + s1;
2587 s1 = s1 + *p++;
2588 s2 = s2 + s1;
2589 s1 = s1 + *p++;
2590 s2 = s2 + s1;
2591
2592 hsz -= 16;
2593 }
2594
2595 for (i = 0; i < hsz; ++i)
2596 {
2597 s1 = s1 + *p++;
2598 s2 = s2 + s1;
2599 }
2600
2601 s1 %= 65521;
2602 s2 %= 65521;
2603
2604 if (unlikely ((s2 << 16) + s1 != cksum))
2605 {
2606 elf_uncompress_failed ();
2607 return 0;
2608 }
2609
2610 return 1;
2611}
2612
2613/* Inflate a zlib stream from PIN/SIN to POUT/SOUT, and verify the
2614 checksum. Return 1 on success, 0 on error. */
2615
2616static int
2617elf_zlib_inflate_and_verify (const unsigned char *pin, size_t sin,
2618 uint16_t *zdebug_table, unsigned char *pout,
2619 size_t sout)
2620{
2621 if (!elf_zlib_inflate (pin, sin, zdebug_table, pout, sout))
2622 return 0;
2623 if (!elf_zlib_verify_checksum (pin + sin - 4, pout, sout))
2624 return 0;
2625 return 1;
2626}
2627
2628/* For working memory during zstd compression, we need
2629 - a literal length FSE table: 512 64-bit values == 4096 bytes
2630 - a match length FSE table: 512 64-bit values == 4096 bytes
2631 - a offset FSE table: 256 64-bit values == 2048 bytes
2632 - a Huffman tree: 2048 uint16_t values == 4096 bytes
2633 - scratch space, one of
2634 - to build an FSE table: 512 uint16_t values == 1024 bytes
2635 - to build a Huffman tree: 512 uint16_t + 256 uint32_t == 2048 bytes
2636*/
2637
2638#define ZSTD_TABLE_SIZE \
2639 (2 * 512 * sizeof (struct elf_zstd_fse_baseline_entry) \
2640 + 256 * sizeof (struct elf_zstd_fse_baseline_entry) \
2641 + 2048 * sizeof (uint16_t) \
2642 + 512 * sizeof (uint16_t) + 256 * sizeof (uint32_t))
2643
2644#define ZSTD_TABLE_LITERAL_FSE_OFFSET (0)
2645
2646#define ZSTD_TABLE_MATCH_FSE_OFFSET \
2647 (512 * sizeof (struct elf_zstd_fse_baseline_entry))
2648
2649#define ZSTD_TABLE_OFFSET_FSE_OFFSET \
2650 (ZSTD_TABLE_MATCH_FSE_OFFSET \
2651 + 512 * sizeof (struct elf_zstd_fse_baseline_entry))
2652
2653#define ZSTD_TABLE_HUFFMAN_OFFSET \
2654 (ZSTD_TABLE_OFFSET_FSE_OFFSET \
2655 + 256 * sizeof (struct elf_zstd_fse_baseline_entry))
2656
2657#define ZSTD_TABLE_WORK_OFFSET \
2658 (ZSTD_TABLE_HUFFMAN_OFFSET + 2048 * sizeof (uint16_t))
2659
2660/* An entry in a zstd FSE table. */
2661
2662struct elf_zstd_fse_entry
2663{
2664 /* The value that this FSE entry represents. */
2665 unsigned char symbol;
2666 /* The number of bits to read to determine the next state. */
2667 unsigned char bits;
2668 /* Add the bits to this base to get the next state. */
2669 uint16_t base;
2670};
2671
2672static int
2673elf_zstd_build_fse (const int16_t *, int, uint16_t *, int,
2674 struct elf_zstd_fse_entry *);
2675
2676/* Read a zstd FSE table and build the decoding table in *TABLE, updating *PPIN
2677 as it reads. ZDEBUG_TABLE is scratch space; it must be enough for 512
2678 uint16_t values (1024 bytes). MAXIDX is the maximum number of symbols
2679 permitted. *TABLE_BITS is the maximum number of bits for symbols in the
2680 table: the size of *TABLE is at least 1 << *TABLE_BITS. This updates
2681 *TABLE_BITS to the actual number of bits. Returns 1 on success, 0 on
2682 error. */
2683
2684static int
2685elf_zstd_read_fse (const unsigned char **ppin, const unsigned char *pinend,
2686 uint16_t *zdebug_table, int maxidx,
2687 struct elf_zstd_fse_entry *table, int *table_bits)
2688{
2689 const unsigned char *pin;
2690 int16_t *norm;
2691 uint16_t *next;
2692 uint64_t val;
2693 unsigned int bits;
2694 int accuracy_log;
2695 uint32_t remaining;
2696 uint32_t threshold;
2697 int bits_needed;
2698 int idx;
2699 int prev0;
2700
2701 pin = *ppin;
2702
2703 norm = (int16_t *) zdebug_table;
2704 next = zdebug_table + 256;
2705
2706 if (unlikely (pin + 3 >= pinend))
2707 {
2708 elf_uncompress_failed ();
2709 return 0;
2710 }
2711
2712 /* Align PIN to a 32-bit boundary. */
2713
2714 val = 0;
2715 bits = 0;
2716 while ((((uintptr_t) pin) & 3) != 0)
2717 {
2718 val |= (uint64_t)*pin << bits;
2719 bits += 8;
2720 ++pin;
2721 }
2722
2723 if (!elf_fetch_bits (&pin, pinend, &val, &bits))
2724 return 0;
2725
2726 accuracy_log = (val & 0xf) + 5;
2727 if (accuracy_log > *table_bits)
2728 {
2729 elf_uncompress_failed ();
2730 return 0;
2731 }
2732 *table_bits = accuracy_log;
2733 val >>= 4;
2734 bits -= 4;
2735
2736 /* This code is mostly copied from the reference implementation. */
2737
2738 /* The number of remaining probabilities, plus 1. This sets the number of
2739 bits that need to be read for the next value. */
2740 remaining = (1 << accuracy_log) + 1;
2741
2742 /* The current difference between small and large values, which depends on
2743 the number of remaining values. Small values use one less bit. */
2744 threshold = 1 << accuracy_log;
2745
2746 /* The number of bits used to compute threshold. */
2747 bits_needed = accuracy_log + 1;
2748
2749 /* The next character value. */
2750 idx = 0;
2751
2752 /* Whether the last count was 0. */
2753 prev0 = 0;
2754
2755 while (remaining > 1 && idx <= maxidx)
2756 {
2757 uint32_t max;
2758 int32_t count;
2759
2760 if (!elf_fetch_bits (&pin, pinend, &val, &bits))
2761 return 0;
2762
2763 if (prev0)
2764 {
2765 int zidx;
2766
2767 /* Previous count was 0, so there is a 2-bit repeat flag. If the
2768 2-bit flag is 0b11, it adds 3 and then there is another repeat
2769 flag. */
2770 zidx = idx;
2771 while ((val & 0xfff) == 0xfff)
2772 {
2773 zidx += 3 * 6;
2774 val >>= 12;
2775 bits -= 12;
2776 if (!elf_fetch_bits (&pin, pinend, &val, &bits))
2777 return 0;
2778 }
2779 while ((val & 3) == 3)
2780 {
2781 zidx += 3;
2782 val >>= 2;
2783 bits -= 2;
2784 if (!elf_fetch_bits (&pin, pinend, &val, &bits))
2785 return 0;
2786 }
2787 /* We have at least 13 bits here, don't need to fetch. */
2788 zidx += val & 3;
2789 val >>= 2;
2790 bits -= 2;
2791
2792 if (unlikely (zidx > maxidx))
2793 {
2794 elf_uncompress_failed ();
2795 return 0;
2796 }
2797
2798 for (; idx < zidx; idx++)
2799 norm[idx] = 0;
2800
2801 prev0 = 0;
2802 continue;
2803 }
2804
2805 max = (2 * threshold - 1) - remaining;
2806 if ((val & (threshold - 1)) < max)
2807 {
2808 /* A small value. */
2809 count = (int32_t) ((uint32_t) val & (threshold - 1));
2810 val >>= bits_needed - 1;
2811 bits -= bits_needed - 1;
2812 }
2813 else
2814 {
2815 /* A large value. */
2816 count = (int32_t) ((uint32_t) val & (2 * threshold - 1));
2817 if (count >= (int32_t) threshold)
2818 count -= (int32_t) max;
2819 val >>= bits_needed;
2820 bits -= bits_needed;
2821 }
2822
2823 count--;
2824 if (count >= 0)
2825 remaining -= count;
2826 else
2827 remaining--;
2828 if (unlikely (idx >= 256))
2829 {
2830 elf_uncompress_failed ();
2831 return 0;
2832 }
2833 norm[idx] = (int16_t) count;
2834 ++idx;
2835
2836 prev0 = count == 0;
2837
2838 while (remaining < threshold)
2839 {
2840 bits_needed--;
2841 threshold >>= 1;
2842 }
2843 }
2844
2845 if (unlikely (remaining != 1))
2846 {
2847 elf_uncompress_failed ();
2848 return 0;
2849 }
2850
2851 /* If we've read ahead more than a byte, back up. */
2852 while (bits >= 8)
2853 {
2854 --pin;
2855 bits -= 8;
2856 }
2857
2858 *ppin = pin;
2859
2860 for (; idx <= maxidx; idx++)
2861 norm[idx] = 0;
2862
2863 return elf_zstd_build_fse (norm, idx, next, *table_bits, table);
2864}
2865
2866/* Build the FSE decoding table from a list of probabilities. This reads from
2867 NORM of length IDX, uses NEXT as scratch space, and writes to *TABLE, whose
2868 size is TABLE_BITS. */
2869
2870static int
2871elf_zstd_build_fse (const int16_t *norm, int idx, uint16_t *next,
2872 int table_bits, struct elf_zstd_fse_entry *table)
2873{
2874 int table_size;
2875 int high_threshold;
2876 int i;
2877 int pos;
2878 int step;
2879 int mask;
2880
2881 table_size = 1 << table_bits;
2882 high_threshold = table_size - 1;
2883 for (i = 0; i < idx; i++)
2884 {
2885 int16_t n;
2886
2887 n = norm[i];
2888 if (n >= 0)
2889 next[i] = (uint16_t) n;
2890 else
2891 {
2892 table[high_threshold].symbol = (unsigned char) i;
2893 high_threshold--;
2894 next[i] = 1;
2895 }
2896 }
2897
2898 pos = 0;
2899 step = (table_size >> 1) + (table_size >> 3) + 3;
2900 mask = table_size - 1;
2901 for (i = 0; i < idx; i++)
2902 {
2903 int n;
2904 int j;
2905
2906 n = (int) norm[i];
2907 for (j = 0; j < n; j++)
2908 {
2909 table[pos].symbol = (unsigned char) i;
2910 pos = (pos + step) & mask;
2911 while (unlikely (pos > high_threshold))
2912 pos = (pos + step) & mask;
2913 }
2914 }
2915 if (unlikely (pos != 0))
2916 {
2917 elf_uncompress_failed ();
2918 return 0;
2919 }
2920
2921 for (i = 0; i < table_size; i++)
2922 {
2923 unsigned char sym;
2924 uint16_t next_state;
2925 int high_bit;
2926 int bits;
2927
2928 sym = table[i].symbol;
2929 next_state = next[sym];
2930 ++next[sym];
2931
2932 if (next_state == 0)
2933 {
2934 elf_uncompress_failed ();
2935 return 0;
2936 }
2937 high_bit = 31 - __builtin_clz (next_state);
2938
2939 bits = table_bits - high_bit;
2940 table[i].bits = (unsigned char) bits;
2941 table[i].base = (uint16_t) ((next_state << bits) - table_size);
2942 }
2943
2944 return 1;
2945}
2946
2947/* Encode the baseline and bits into a single 32-bit value. */
2948
2949#define ZSTD_ENCODE_BASELINE_BITS(baseline, basebits) \
2950 ((uint32_t)(baseline) | ((uint32_t)(basebits) << 24))
2951
2952#define ZSTD_DECODE_BASELINE(baseline_basebits) \
2953 ((uint32_t)(baseline_basebits) & 0xffffff)
2954
2955#define ZSTD_DECODE_BASEBITS(baseline_basebits) \
2956 ((uint32_t)(baseline_basebits) >> 24)
2957
2958/* Given a literal length code, we need to read a number of bits and add that
2959 to a baseline. For states 0 to 15 the baseline is the state and the number
2960 of bits is zero. */
2961
2962#define ZSTD_LITERAL_LENGTH_BASELINE_OFFSET (16)
2963
2964static const uint32_t elf_zstd_literal_length_base[] =
2965{
2966 ZSTD_ENCODE_BASELINE_BITS(16, 1),
2967 ZSTD_ENCODE_BASELINE_BITS(18, 1),
2968 ZSTD_ENCODE_BASELINE_BITS(20, 1),
2969 ZSTD_ENCODE_BASELINE_BITS(22, 1),
2970 ZSTD_ENCODE_BASELINE_BITS(24, 2),
2971 ZSTD_ENCODE_BASELINE_BITS(28, 2),
2972 ZSTD_ENCODE_BASELINE_BITS(32, 3),
2973 ZSTD_ENCODE_BASELINE_BITS(40, 3),
2974 ZSTD_ENCODE_BASELINE_BITS(48, 4),
2975 ZSTD_ENCODE_BASELINE_BITS(64, 6),
2976 ZSTD_ENCODE_BASELINE_BITS(128, 7),
2977 ZSTD_ENCODE_BASELINE_BITS(256, 8),
2978 ZSTD_ENCODE_BASELINE_BITS(512, 9),
2979 ZSTD_ENCODE_BASELINE_BITS(1024, 10),
2980 ZSTD_ENCODE_BASELINE_BITS(2048, 11),
2981 ZSTD_ENCODE_BASELINE_BITS(4096, 12),
2982 ZSTD_ENCODE_BASELINE_BITS(8192, 13),
2983 ZSTD_ENCODE_BASELINE_BITS(16384, 14),
2984 ZSTD_ENCODE_BASELINE_BITS(32768, 15),
2985 ZSTD_ENCODE_BASELINE_BITS(65536, 16)
2986};
2987
2988/* The same applies to match length codes. For states 0 to 31 the baseline is
2989 the state + 3 and the number of bits is zero. */
2990
2991#define ZSTD_MATCH_LENGTH_BASELINE_OFFSET (32)
2992
2993static const uint32_t elf_zstd_match_length_base[] =
2994{
2995 ZSTD_ENCODE_BASELINE_BITS(35, 1),
2996 ZSTD_ENCODE_BASELINE_BITS(37, 1),
2997 ZSTD_ENCODE_BASELINE_BITS(39, 1),
2998 ZSTD_ENCODE_BASELINE_BITS(41, 1),
2999 ZSTD_ENCODE_BASELINE_BITS(43, 2),
3000 ZSTD_ENCODE_BASELINE_BITS(47, 2),
3001 ZSTD_ENCODE_BASELINE_BITS(51, 3),
3002 ZSTD_ENCODE_BASELINE_BITS(59, 3),
3003 ZSTD_ENCODE_BASELINE_BITS(67, 4),
3004 ZSTD_ENCODE_BASELINE_BITS(83, 4),
3005 ZSTD_ENCODE_BASELINE_BITS(99, 5),
3006 ZSTD_ENCODE_BASELINE_BITS(131, 7),
3007 ZSTD_ENCODE_BASELINE_BITS(259, 8),
3008 ZSTD_ENCODE_BASELINE_BITS(515, 9),
3009 ZSTD_ENCODE_BASELINE_BITS(1027, 10),
3010 ZSTD_ENCODE_BASELINE_BITS(2051, 11),
3011 ZSTD_ENCODE_BASELINE_BITS(4099, 12),
3012 ZSTD_ENCODE_BASELINE_BITS(8195, 13),
3013 ZSTD_ENCODE_BASELINE_BITS(16387, 14),
3014 ZSTD_ENCODE_BASELINE_BITS(32771, 15),
3015 ZSTD_ENCODE_BASELINE_BITS(65539, 16)
3016};
3017
3018/* An entry in an FSE table used for literal/match/length values. For these we
3019 have to map the symbol to a baseline value, and we have to read zero or more
3020 bits and add that value to the baseline value. Rather than look the values
3021 up in a separate table, we grow the FSE table so that we get better memory
3022 caching. */
3023
3024struct elf_zstd_fse_baseline_entry
3025{
3026 /* The baseline for the value that this FSE entry represents.. */
3027 uint32_t baseline;
3028 /* The number of bits to read to add to the baseline. */
3029 unsigned char basebits;
3030 /* The number of bits to read to determine the next state. */
3031 unsigned char bits;
3032 /* Add the bits to this base to get the next state. */
3033 uint16_t base;
3034};
3035
3036/* Convert the literal length FSE table FSE_TABLE to an FSE baseline table at
3037 BASELINE_TABLE. Note that FSE_TABLE and BASELINE_TABLE will overlap. */
3038
3039static int
3040elf_zstd_make_literal_baseline_fse (
3041 const struct elf_zstd_fse_entry *fse_table,
3042 int table_bits,
3043 struct elf_zstd_fse_baseline_entry *baseline_table)
3044{
3045 size_t count;
3046 const struct elf_zstd_fse_entry *pfse;
3047 struct elf_zstd_fse_baseline_entry *pbaseline;
3048
3049 /* Convert backward to avoid overlap. */
3050
3051 count = 1U << table_bits;
3052 pfse = fse_table + count;
3053 pbaseline = baseline_table + count;
3054 while (pfse > fse_table)
3055 {
3056 unsigned char symbol;
3057 unsigned char bits;
3058 uint16_t base;
3059
3060 --pfse;
3061 --pbaseline;
3062 symbol = pfse->symbol;
3063 bits = pfse->bits;
3064 base = pfse->base;
3065 if (symbol < ZSTD_LITERAL_LENGTH_BASELINE_OFFSET)
3066 {
3067 pbaseline->baseline = (uint32_t)symbol;
3068 pbaseline->basebits = 0;
3069 }
3070 else
3071 {
3072 unsigned int idx;
3073 uint32_t basebits;
3074
3075 if (unlikely (symbol > 35))
3076 {
3077 elf_uncompress_failed ();
3078 return 0;
3079 }
3080 idx = symbol - ZSTD_LITERAL_LENGTH_BASELINE_OFFSET;
3081 basebits = elf_zstd_literal_length_base[idx];
3082 pbaseline->baseline = ZSTD_DECODE_BASELINE(basebits);
3083 pbaseline->basebits = ZSTD_DECODE_BASEBITS(basebits);
3084 }
3085 pbaseline->bits = bits;
3086 pbaseline->base = base;
3087 }
3088
3089 return 1;
3090}
3091
3092/* Convert the offset length FSE table FSE_TABLE to an FSE baseline table at
3093 BASELINE_TABLE. Note that FSE_TABLE and BASELINE_TABLE will overlap. */
3094
3095static int
3096elf_zstd_make_offset_baseline_fse (
3097 const struct elf_zstd_fse_entry *fse_table,
3098 int table_bits,
3099 struct elf_zstd_fse_baseline_entry *baseline_table)
3100{
3101 size_t count;
3102 const struct elf_zstd_fse_entry *pfse;
3103 struct elf_zstd_fse_baseline_entry *pbaseline;
3104
3105 /* Convert backward to avoid overlap. */
3106
3107 count = 1U << table_bits;
3108 pfse = fse_table + count;
3109 pbaseline = baseline_table + count;
3110 while (pfse > fse_table)
3111 {
3112 unsigned char symbol;
3113 unsigned char bits;
3114 uint16_t base;
3115
3116 --pfse;
3117 --pbaseline;
3118 symbol = pfse->symbol;
3119 bits = pfse->bits;
3120 base = pfse->base;
3121 if (unlikely (symbol > 31))
3122 {
3123 elf_uncompress_failed ();
3124 return 0;
3125 }
3126
3127 /* The simple way to write this is
3128
3129 pbaseline->baseline = (uint32_t)1 << symbol;
3130 pbaseline->basebits = symbol;
3131
3132 That will give us an offset value that corresponds to the one
3133 described in the RFC. However, for offset values > 3, we have to
3134 subtract 3. And for offset values 1, 2, 3 we use a repeated offset.
3135 The baseline is always a power of 2, and is never 0, so for these low
3136 values we will see one entry that is baseline 1, basebits 0, and one
3137 entry that is baseline 2, basebits 1. All other entries will have
3138 baseline >= 4 and basebits >= 2.
3139
3140 So we can check for RFC offset <= 3 by checking for basebits <= 1.
3141 And that means that we can subtract 3 here and not worry about doing
3142 it in the hot loop. */
3143
3144 pbaseline->baseline = (uint32_t)1 << symbol;
3145 if (symbol >= 2)
3146 pbaseline->baseline -= 3;
3147 pbaseline->basebits = symbol;
3148 pbaseline->bits = bits;
3149 pbaseline->base = base;
3150 }
3151
3152 return 1;
3153}
3154
3155/* Convert the match length FSE table FSE_TABLE to an FSE baseline table at
3156 BASELINE_TABLE. Note that FSE_TABLE and BASELINE_TABLE will overlap. */
3157
3158static int
3159elf_zstd_make_match_baseline_fse (
3160 const struct elf_zstd_fse_entry *fse_table,
3161 int table_bits,
3162 struct elf_zstd_fse_baseline_entry *baseline_table)
3163{
3164 size_t count;
3165 const struct elf_zstd_fse_entry *pfse;
3166 struct elf_zstd_fse_baseline_entry *pbaseline;
3167
3168 /* Convert backward to avoid overlap. */
3169
3170 count = 1U << table_bits;
3171 pfse = fse_table + count;
3172 pbaseline = baseline_table + count;
3173 while (pfse > fse_table)
3174 {
3175 unsigned char symbol;
3176 unsigned char bits;
3177 uint16_t base;
3178
3179 --pfse;
3180 --pbaseline;
3181 symbol = pfse->symbol;
3182 bits = pfse->bits;
3183 base = pfse->base;
3184 if (symbol < ZSTD_MATCH_LENGTH_BASELINE_OFFSET)
3185 {
3186 pbaseline->baseline = (uint32_t)symbol + 3;
3187 pbaseline->basebits = 0;
3188 }
3189 else
3190 {
3191 unsigned int idx;
3192 uint32_t basebits;
3193
3194 if (unlikely (symbol > 52))
3195 {
3196 elf_uncompress_failed ();
3197 return 0;
3198 }
3199 idx = symbol - ZSTD_MATCH_LENGTH_BASELINE_OFFSET;
3200 basebits = elf_zstd_match_length_base[idx];
3201 pbaseline->baseline = ZSTD_DECODE_BASELINE(basebits);
3202 pbaseline->basebits = ZSTD_DECODE_BASEBITS(basebits);
3203 }
3204 pbaseline->bits = bits;
3205 pbaseline->base = base;
3206 }
3207
3208 return 1;
3209}
3210
3211#ifdef BACKTRACE_GENERATE_ZSTD_FSE_TABLES
3212
3213/* Used to generate the predefined FSE decoding tables for zstd. */
3214
3215#include <stdio.h>
3216
3217/* These values are straight from RFC 8878. */
3218
3219static int16_t lit[36] =
3220{
3221 4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1,
3222 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1,
3223 -1,-1,-1,-1
3224};
3225
3226static int16_t match[53] =
3227{
3228 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1,
3229 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
3230 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,-1,-1,
3231 -1,-1,-1,-1,-1
3232};
3233
3234static int16_t offset[29] =
3235{
3236 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1,
3237 1, 1, 1, 1, 1, 1, 1, 1,-1,-1,-1,-1,-1
3238};
3239
3240static uint16_t next[256];
3241
3242static void
3243print_table (const struct elf_zstd_fse_baseline_entry *table, size_t size)
3244{
3245 size_t i;
3246
3247 printf ("{\n");
3248 for (i = 0; i < size; i += 3)
3249 {
3250 int j;
3251
3252 printf (" ");
3253 for (j = 0; j < 3 && i + j < size; ++j)
3254 printf (" { %u, %d, %d, %d },", table[i + j].baseline,
3255 table[i + j].basebits, table[i + j].bits,
3256 table[i + j].base);
3257 printf ("\n");
3258 }
3259 printf ("};\n");
3260}
3261
3262int
3263main ()
3264{
3265 struct elf_zstd_fse_entry lit_table[64];
3266 struct elf_zstd_fse_baseline_entry lit_baseline[64];
3267 struct elf_zstd_fse_entry match_table[64];
3268 struct elf_zstd_fse_baseline_entry match_baseline[64];
3269 struct elf_zstd_fse_entry offset_table[32];
3270 struct elf_zstd_fse_baseline_entry offset_baseline[32];
3271
3272 if (!elf_zstd_build_fse (lit, sizeof lit / sizeof lit[0], next,
3273 6, lit_table))
3274 {
3275 fprintf (stderr, "elf_zstd_build_fse failed\n");
3276 exit (EXIT_FAILURE);
3277 }
3278
3279 if (!elf_zstd_make_literal_baseline_fse (lit_table, 6, lit_baseline))
3280 {
3281 fprintf (stderr, "elf_zstd_make_literal_baseline_fse failed\n");
3282 exit (EXIT_FAILURE);
3283 }
3284
3285 printf ("static const struct elf_zstd_fse_baseline_entry "
3286 "elf_zstd_lit_table[64] =\n");
3287 print_table (lit_baseline,
3288 sizeof lit_baseline / sizeof lit_baseline[0]);
3289 printf ("\n");
3290
3291 if (!elf_zstd_build_fse (match, sizeof match / sizeof match[0], next,
3292 6, match_table))
3293 {
3294 fprintf (stderr, "elf_zstd_build_fse failed\n");
3295 exit (EXIT_FAILURE);
3296 }
3297
3298 if (!elf_zstd_make_match_baseline_fse (match_table, 6, match_baseline))
3299 {
3300 fprintf (stderr, "elf_zstd_make_match_baseline_fse failed\n");
3301 exit (EXIT_FAILURE);
3302 }
3303
3304 printf ("static const struct elf_zstd_fse_baseline_entry "
3305 "elf_zstd_match_table[64] =\n");
3306 print_table (match_baseline,
3307 sizeof match_baseline / sizeof match_baseline[0]);
3308 printf ("\n");
3309
3310 if (!elf_zstd_build_fse (offset, sizeof offset / sizeof offset[0], next,
3311 5, offset_table))
3312 {
3313 fprintf (stderr, "elf_zstd_build_fse failed\n");
3314 exit (EXIT_FAILURE);
3315 }
3316
3317 if (!elf_zstd_make_offset_baseline_fse (offset_table, 5, offset_baseline))
3318 {
3319 fprintf (stderr, "elf_zstd_make_offset_baseline_fse failed\n");
3320 exit (EXIT_FAILURE);
3321 }
3322
3323 printf ("static const struct elf_zstd_fse_baseline_entry "
3324 "elf_zstd_offset_table[32] =\n");
3325 print_table (offset_baseline,
3326 sizeof offset_baseline / sizeof offset_baseline[0]);
3327 printf ("\n");
3328
3329 return 0;
3330}
3331
3332#endif
3333
3334/* The fixed tables generated by the #ifdef'ed out main function
3335 above. */
3336
3337static const struct elf_zstd_fse_baseline_entry elf_zstd_lit_table[64] =
3338{
3339 { 0, 0, 4, 0 }, { 0, 0, 4, 16 }, { 1, 0, 5, 32 },
3340 { 3, 0, 5, 0 }, { 4, 0, 5, 0 }, { 6, 0, 5, 0 },
3341 { 7, 0, 5, 0 }, { 9, 0, 5, 0 }, { 10, 0, 5, 0 },
3342 { 12, 0, 5, 0 }, { 14, 0, 6, 0 }, { 16, 1, 5, 0 },
3343 { 20, 1, 5, 0 }, { 22, 1, 5, 0 }, { 28, 2, 5, 0 },
3344 { 32, 3, 5, 0 }, { 48, 4, 5, 0 }, { 64, 6, 5, 32 },
3345 { 128, 7, 5, 0 }, { 256, 8, 6, 0 }, { 1024, 10, 6, 0 },
3346 { 4096, 12, 6, 0 }, { 0, 0, 4, 32 }, { 1, 0, 4, 0 },
3347 { 2, 0, 5, 0 }, { 4, 0, 5, 32 }, { 5, 0, 5, 0 },
3348 { 7, 0, 5, 32 }, { 8, 0, 5, 0 }, { 10, 0, 5, 32 },
3349 { 11, 0, 5, 0 }, { 13, 0, 6, 0 }, { 16, 1, 5, 32 },
3350 { 18, 1, 5, 0 }, { 22, 1, 5, 32 }, { 24, 2, 5, 0 },
3351 { 32, 3, 5, 32 }, { 40, 3, 5, 0 }, { 64, 6, 4, 0 },
3352 { 64, 6, 4, 16 }, { 128, 7, 5, 32 }, { 512, 9, 6, 0 },
3353 { 2048, 11, 6, 0 }, { 0, 0, 4, 48 }, { 1, 0, 4, 16 },
3354 { 2, 0, 5, 32 }, { 3, 0, 5, 32 }, { 5, 0, 5, 32 },
3355 { 6, 0, 5, 32 }, { 8, 0, 5, 32 }, { 9, 0, 5, 32 },
3356 { 11, 0, 5, 32 }, { 12, 0, 5, 32 }, { 15, 0, 6, 0 },
3357 { 18, 1, 5, 32 }, { 20, 1, 5, 32 }, { 24, 2, 5, 32 },
3358 { 28, 2, 5, 32 }, { 40, 3, 5, 32 }, { 48, 4, 5, 32 },
3359 { 65536, 16, 6, 0 }, { 32768, 15, 6, 0 }, { 16384, 14, 6, 0 },
3360 { 8192, 13, 6, 0 },
3361};
3362
3363static const struct elf_zstd_fse_baseline_entry elf_zstd_match_table[64] =
3364{
3365 { 3, 0, 6, 0 }, { 4, 0, 4, 0 }, { 5, 0, 5, 32 },
3366 { 6, 0, 5, 0 }, { 8, 0, 5, 0 }, { 9, 0, 5, 0 },
3367 { 11, 0, 5, 0 }, { 13, 0, 6, 0 }, { 16, 0, 6, 0 },
3368 { 19, 0, 6, 0 }, { 22, 0, 6, 0 }, { 25, 0, 6, 0 },
3369 { 28, 0, 6, 0 }, { 31, 0, 6, 0 }, { 34, 0, 6, 0 },
3370 { 37, 1, 6, 0 }, { 41, 1, 6, 0 }, { 47, 2, 6, 0 },
3371 { 59, 3, 6, 0 }, { 83, 4, 6, 0 }, { 131, 7, 6, 0 },
3372 { 515, 9, 6, 0 }, { 4, 0, 4, 16 }, { 5, 0, 4, 0 },
3373 { 6, 0, 5, 32 }, { 7, 0, 5, 0 }, { 9, 0, 5, 32 },
3374 { 10, 0, 5, 0 }, { 12, 0, 6, 0 }, { 15, 0, 6, 0 },
3375 { 18, 0, 6, 0 }, { 21, 0, 6, 0 }, { 24, 0, 6, 0 },
3376 { 27, 0, 6, 0 }, { 30, 0, 6, 0 }, { 33, 0, 6, 0 },
3377 { 35, 1, 6, 0 }, { 39, 1, 6, 0 }, { 43, 2, 6, 0 },
3378 { 51, 3, 6, 0 }, { 67, 4, 6, 0 }, { 99, 5, 6, 0 },
3379 { 259, 8, 6, 0 }, { 4, 0, 4, 32 }, { 4, 0, 4, 48 },
3380 { 5, 0, 4, 16 }, { 7, 0, 5, 32 }, { 8, 0, 5, 32 },
3381 { 10, 0, 5, 32 }, { 11, 0, 5, 32 }, { 14, 0, 6, 0 },
3382 { 17, 0, 6, 0 }, { 20, 0, 6, 0 }, { 23, 0, 6, 0 },
3383 { 26, 0, 6, 0 }, { 29, 0, 6, 0 }, { 32, 0, 6, 0 },
3384 { 65539, 16, 6, 0 }, { 32771, 15, 6, 0 }, { 16387, 14, 6, 0 },
3385 { 8195, 13, 6, 0 }, { 4099, 12, 6, 0 }, { 2051, 11, 6, 0 },
3386 { 1027, 10, 6, 0 },
3387};
3388
3389static const struct elf_zstd_fse_baseline_entry elf_zstd_offset_table[32] =
3390{
3391 { 1, 0, 5, 0 }, { 61, 6, 4, 0 }, { 509, 9, 5, 0 },
3392 { 32765, 15, 5, 0 }, { 2097149, 21, 5, 0 }, { 5, 3, 5, 0 },
3393 { 125, 7, 4, 0 }, { 4093, 12, 5, 0 }, { 262141, 18, 5, 0 },
3394 { 8388605, 23, 5, 0 }, { 29, 5, 5, 0 }, { 253, 8, 4, 0 },
3395 { 16381, 14, 5, 0 }, { 1048573, 20, 5, 0 }, { 1, 2, 5, 0 },
3396 { 125, 7, 4, 16 }, { 2045, 11, 5, 0 }, { 131069, 17, 5, 0 },
3397 { 4194301, 22, 5, 0 }, { 13, 4, 5, 0 }, { 253, 8, 4, 16 },
3398 { 8189, 13, 5, 0 }, { 524285, 19, 5, 0 }, { 2, 1, 5, 0 },
3399 { 61, 6, 4, 16 }, { 1021, 10, 5, 0 }, { 65533, 16, 5, 0 },
3400 { 268435453, 28, 5, 0 }, { 134217725, 27, 5, 0 }, { 67108861, 26, 5, 0 },
3401 { 33554429, 25, 5, 0 }, { 16777213, 24, 5, 0 },
3402};
3403
3404/* Read a zstd Huffman table and build the decoding table in *TABLE, reading
3405 and updating *PPIN. This sets *PTABLE_BITS to the number of bits of the
3406 table, such that the table length is 1 << *TABLE_BITS. ZDEBUG_TABLE is
3407 scratch space; it must be enough for 512 uint16_t values + 256 32-bit values
3408 (2048 bytes). Returns 1 on success, 0 on error. */
3409
3410static int
3411elf_zstd_read_huff (const unsigned char **ppin, const unsigned char *pinend,
3412 uint16_t *zdebug_table, uint16_t *table, int *ptable_bits)
3413{
3414 const unsigned char *pin;
3415 unsigned char hdr;
3416 unsigned char *weights;
3417 size_t count;
3418 uint32_t *weight_mark;
3419 size_t i;
3420 uint32_t weight_mask;
3421 size_t table_bits;
3422
3423 pin = *ppin;
3424 if (unlikely (pin >= pinend))
3425 {
3426 elf_uncompress_failed ();
3427 return 0;
3428 }
3429 hdr = *pin;
3430 ++pin;
3431
3432 weights = (unsigned char *) zdebug_table;
3433
3434 if (hdr < 128)
3435 {
3436 /* Table is compressed using FSE. */
3437
3438 struct elf_zstd_fse_entry *fse_table;
3439 int fse_table_bits;
3440 uint16_t *scratch;
3441 const unsigned char *pfse;
3442 const unsigned char *pback;
3443 uint64_t val;
3444 unsigned int bits;
3445 unsigned int state1, state2;
3446
3447 /* SCRATCH is used temporarily by elf_zstd_read_fse. It overlaps
3448 WEIGHTS. */
3449 scratch = zdebug_table;
3450 fse_table = (struct elf_zstd_fse_entry *) (scratch + 512);
3451 fse_table_bits = 6;
3452
3453 pfse = pin;
3454 if (!elf_zstd_read_fse (&pfse, pinend, scratch, 255, fse_table,
3455 &fse_table_bits))
3456 return 0;
3457
3458 if (unlikely (pin + hdr > pinend))
3459 {
3460 elf_uncompress_failed ();
3461 return 0;
3462 }
3463
3464 /* We no longer need SCRATCH. Start recording weights. We need up to
3465 256 bytes of weights and 64 bytes of rank counts, so it won't overlap
3466 FSE_TABLE. */
3467
3468 pback = pin + hdr - 1;
3469
3470 if (!elf_fetch_backward_init (&pback, pfse, &val, &bits))
3471 return 0;
3472
3473 bits -= fse_table_bits;
3474 state1 = (val >> bits) & ((1U << fse_table_bits) - 1);
3475 bits -= fse_table_bits;
3476 state2 = (val >> bits) & ((1U << fse_table_bits) - 1);
3477
3478 /* There are two independent FSE streams, tracked by STATE1 and STATE2.
3479 We decode them alternately. */
3480
3481 count = 0;
3482 while (1)
3483 {
3484 struct elf_zstd_fse_entry *pt;
3485 uint64_t v;
3486
3487 pt = &fse_table[state1];
3488
3489 if (unlikely (pin < pinend) && bits < pt->bits)
3490 {
3491 if (unlikely (count >= 254))
3492 {
3493 elf_uncompress_failed ();
3494 return 0;
3495 }
3496 weights[count] = (unsigned char) pt->symbol;
3497 weights[count + 1] = (unsigned char) fse_table[state2].symbol;
3498 count += 2;
3499 break;
3500 }
3501
3502 if (unlikely (pt->bits == 0))
3503 v = 0;
3504 else
3505 {
3506 if (!elf_fetch_bits_backward (&pback, pfse, &val, &bits))
3507 return 0;
3508
3509 bits -= pt->bits;
3510 v = (val >> bits) & (((uint64_t)1 << pt->bits) - 1);
3511 }
3512
3513 state1 = pt->base + v;
3514
3515 if (unlikely (count >= 255))
3516 {
3517 elf_uncompress_failed ();
3518 return 0;
3519 }
3520
3521 weights[count] = pt->symbol;
3522 ++count;
3523
3524 pt = &fse_table[state2];
3525
3526 if (unlikely (pin < pinend && bits < pt->bits))
3527 {
3528 if (unlikely (count >= 254))
3529 {
3530 elf_uncompress_failed ();
3531 return 0;
3532 }
3533 weights[count] = (unsigned char) pt->symbol;
3534 weights[count + 1] = (unsigned char) fse_table[state1].symbol;
3535 count += 2;
3536 break;
3537 }
3538
3539 if (unlikely (pt->bits == 0))
3540 v = 0;
3541 else
3542 {
3543 if (!elf_fetch_bits_backward (&pback, pfse, &val, &bits))
3544 return 0;
3545
3546 bits -= pt->bits;
3547 v = (val >> bits) & (((uint64_t)1 << pt->bits) - 1);
3548 }
3549
3550 state2 = pt->base + v;
3551
3552 if (unlikely (count >= 255))
3553 {
3554 elf_uncompress_failed ();
3555 return 0;
3556 }
3557
3558 weights[count] = pt->symbol;
3559 ++count;
3560 }
3561
3562 pin += hdr;
3563 }
3564 else
3565 {
3566 /* Table is not compressed. Each weight is 4 bits. */
3567
3568 count = hdr - 127;
3569 if (unlikely (pin + ((count + 1) / 2) >= pinend))
3570 {
3571 elf_uncompress_failed ();
3572 return 0;
3573 }
3574 for (i = 0; i < count; i += 2)
3575 {
3576 unsigned char b;
3577
3578 b = *pin;
3579 ++pin;
3580 weights[i] = b >> 4;
3581 weights[i + 1] = b & 0xf;
3582 }
3583 }
3584
3585 weight_mark = (uint32_t *) (weights + 256);
3586 memset (weight_mark, 0, 13 * sizeof (uint32_t));
3587 weight_mask = 0;
3588 for (i = 0; i < count; ++i)
3589 {
3590 unsigned char w;
3591
3592 w = weights[i];
3593 if (unlikely (w > 12))
3594 {
3595 elf_uncompress_failed ();
3596 return 0;
3597 }
3598 ++weight_mark[w];
3599 if (w > 0)
3600 weight_mask += 1U << (w - 1);
3601 }
3602 if (unlikely (weight_mask == 0))
3603 {
3604 elf_uncompress_failed ();
3605 return 0;
3606 }
3607
3608 table_bits = 32 - __builtin_clz (weight_mask);
3609 if (unlikely (table_bits > 11))
3610 {
3611 elf_uncompress_failed ();
3612 return 0;
3613 }
3614
3615 /* Work out the last weight value, which is omitted because the weights must
3616 sum to a power of two. */
3617 {
3618 uint32_t left;
3619 uint32_t high_bit;
3620
3621 left = ((uint32_t)1 << table_bits) - weight_mask;
3622 if (left == 0)
3623 {
3624 elf_uncompress_failed ();
3625 return 0;
3626 }
3627 high_bit = 31 - __builtin_clz (left);
3628 if (((uint32_t)1 << high_bit) != left)
3629 {
3630 elf_uncompress_failed ();
3631 return 0;
3632 }
3633
3634 if (unlikely (count >= 256))
3635 {
3636 elf_uncompress_failed ();
3637 return 0;
3638 }
3639
3640 weights[count] = high_bit + 1;
3641 ++count;
3642 ++weight_mark[high_bit + 1];
3643 }
3644
3645 if (weight_mark[1] < 2 || (weight_mark[1] & 1) != 0)
3646 {
3647 elf_uncompress_failed ();
3648 return 0;
3649 }
3650
3651 /* Change WEIGHT_MARK from a count of weights to the index of the first
3652 symbol for that weight. We shift the indexes to also store how many we
3653 have seen so far, below. */
3654 {
3655 uint32_t next;
3656
3657 next = 0;
3658 for (i = 0; i < table_bits; ++i)
3659 {
3660 uint32_t cur;
3661
3662 cur = next;
3663 next += weight_mark[i + 1] << i;
3664 weight_mark[i + 1] = cur;
3665 }
3666 }
3667
3668 for (i = 0; i < count; ++i)
3669 {
3670 unsigned char weight;
3671 uint32_t length;
3672 uint16_t tval;
3673 size_t start;
3674 uint32_t j;
3675
3676 weight = weights[i];
3677 if (weight == 0)
3678 continue;
3679
3680 length = 1U << (weight - 1);
3681 tval = (i << 8) | (table_bits + 1 - weight);
3682 start = weight_mark[weight];
3683 for (j = 0; j < length; ++j)
3684 table[start + j] = tval;
3685 weight_mark[weight] += length;
3686 }
3687
3688 *ppin = pin;
3689 *ptable_bits = (int)table_bits;
3690
3691 return 1;
3692}
3693
3694/* Read and decompress the literals and store them ending at POUTEND. This
3695 works because we are going to use all the literals in the output, so they
3696 must fit into the output buffer. HUFFMAN_TABLE, and PHUFFMAN_TABLE_BITS
3697 store the Huffman table across calls. SCRATCH is used to read a Huffman
3698 table. Store the start of the decompressed literals in *PPLIT. Update
3699 *PPIN. Return 1 on success, 0 on error. */
3700
3701static int
3702elf_zstd_read_literals (const unsigned char **ppin,
3703 const unsigned char *pinend,
3704 unsigned char *pout,
3705 unsigned char *poutend,
3706 uint16_t *scratch,
3707 uint16_t *huffman_table,
3708 int *phuffman_table_bits,
3709 unsigned char **pplit)
3710{
3711 const unsigned char *pin;
3712 unsigned char *plit;
3713 unsigned char hdr;
3714 uint32_t regenerated_size;
3715 uint32_t compressed_size;
3716 int streams;
3717 uint32_t total_streams_size;
3718 unsigned int huffman_table_bits;
3719 uint64_t huffman_mask;
3720
3721 pin = *ppin;
3722 if (unlikely (pin >= pinend))
3723 {
3724 elf_uncompress_failed ();
3725 return 0;
3726 }
3727 hdr = *pin;
3728 ++pin;
3729
3730 if ((hdr & 3) == 0 || (hdr & 3) == 1)
3731 {
3732 int raw;
3733
3734 /* Raw_Literals_Block or RLE_Literals_Block */
3735
3736 raw = (hdr & 3) == 0;
3737
3738 switch ((hdr >> 2) & 3)
3739 {
3740 case 0: case 2:
3741 regenerated_size = hdr >> 3;
3742 break;
3743 case 1:
3744 if (unlikely (pin >= pinend))
3745 {
3746 elf_uncompress_failed ();
3747 return 0;
3748 }
3749 regenerated_size = (hdr >> 4) + ((uint32_t)(*pin) << 4);
3750 ++pin;
3751 break;
3752 case 3:
3753 if (unlikely (pin + 1 >= pinend))
3754 {
3755 elf_uncompress_failed ();
3756 return 0;
3757 }
3758 regenerated_size = ((hdr >> 4)
3759 + ((uint32_t)*pin << 4)
3760 + ((uint32_t)pin[1] << 12));
3761 pin += 2;
3762 break;
3763 default:
3764 elf_uncompress_failed ();
3765 return 0;
3766 }
3767
3768 if (unlikely ((size_t)(poutend - pout) < regenerated_size))
3769 {
3770 elf_uncompress_failed ();
3771 return 0;
3772 }
3773
3774 plit = poutend - regenerated_size;
3775
3776 if (raw)
3777 {
3778 if (unlikely (pin + regenerated_size >= pinend))
3779 {
3780 elf_uncompress_failed ();
3781 return 0;
3782 }
3783 memcpy (plit, pin, regenerated_size);
3784 pin += regenerated_size;
3785 }
3786 else
3787 {
3788 if (pin >= pinend)
3789 {
3790 elf_uncompress_failed ();
3791 return 0;
3792 }
3793 memset (plit, *pin, regenerated_size);
3794 ++pin;
3795 }
3796
3797 *ppin = pin;
3798 *pplit = plit;
3799
3800 return 1;
3801 }
3802
3803 /* Compressed_Literals_Block or Treeless_Literals_Block */
3804
3805 switch ((hdr >> 2) & 3)
3806 {
3807 case 0: case 1:
3808 if (unlikely (pin + 1 >= pinend))
3809 {
3810 elf_uncompress_failed ();
3811 return 0;
3812 }
3813 regenerated_size = (hdr >> 4) | ((uint32_t)(*pin & 0x3f) << 4);
3814 compressed_size = (uint32_t)*pin >> 6 | ((uint32_t)pin[1] << 2);
3815 pin += 2;
3816 streams = ((hdr >> 2) & 3) == 0 ? 1 : 4;
3817 break;
3818 case 2:
3819 if (unlikely (pin + 2 >= pinend))
3820 {
3821 elf_uncompress_failed ();
3822 return 0;
3823 }
3824 regenerated_size = (((uint32_t)hdr >> 4)
3825 | ((uint32_t)*pin << 4)
3826 | (((uint32_t)pin[1] & 3) << 12));
3827 compressed_size = (((uint32_t)pin[1] >> 2)
3828 | ((uint32_t)pin[2] << 6));
3829 pin += 3;
3830 streams = 4;
3831 break;
3832 case 3:
3833 if (unlikely (pin + 3 >= pinend))
3834 {
3835 elf_uncompress_failed ();
3836 return 0;
3837 }
3838 regenerated_size = (((uint32_t)hdr >> 4)
3839 | ((uint32_t)*pin << 4)
3840 | (((uint32_t)pin[1] & 0x3f) << 12));
3841 compressed_size = (((uint32_t)pin[1] >> 6)
3842 | ((uint32_t)pin[2] << 2)
3843 | ((uint32_t)pin[3] << 10));
3844 pin += 4;
3845 streams = 4;
3846 break;
3847 default:
3848 elf_uncompress_failed ();
3849 return 0;
3850 }
3851
3852 if (unlikely (pin + compressed_size > pinend))
3853 {
3854 elf_uncompress_failed ();
3855 return 0;
3856 }
3857
3858 pinend = pin + compressed_size;
3859 *ppin = pinend;
3860
3861 if (unlikely ((size_t)(poutend - pout) < regenerated_size))
3862 {
3863 elf_uncompress_failed ();
3864 return 0;
3865 }
3866
3867 plit = poutend - regenerated_size;
3868
3869 *pplit = plit;
3870
3871 total_streams_size = compressed_size;
3872 if ((hdr & 3) == 2)
3873 {
3874 const unsigned char *ptable;
3875
3876 /* Compressed_Literals_Block. Read Huffman tree. */
3877
3878 ptable = pin;
3879 if (!elf_zstd_read_huff (&ptable, pinend, scratch, huffman_table,
3880 phuffman_table_bits))
3881 return 0;
3882
3883 if (unlikely (total_streams_size < (size_t)(ptable - pin)))
3884 {
3885 elf_uncompress_failed ();
3886 return 0;
3887 }
3888
3889 total_streams_size -= ptable - pin;
3890 pin = ptable;
3891 }
3892 else
3893 {
3894 /* Treeless_Literals_Block. Reuse previous Huffman tree. */
3895 if (unlikely (*phuffman_table_bits == 0))
3896 {
3897 elf_uncompress_failed ();
3898 return 0;
3899 }
3900 }
3901
3902 /* Decompress COMPRESSED_SIZE bytes of data at PIN using the huffman table,
3903 storing REGENERATED_SIZE bytes of decompressed data at PLIT. */
3904
3905 huffman_table_bits = (unsigned int)*phuffman_table_bits;
3906 huffman_mask = ((uint64_t)1 << huffman_table_bits) - 1;
3907
3908 if (streams == 1)
3909 {
3910 const unsigned char *pback;
3911 const unsigned char *pbackend;
3912 uint64_t val;
3913 unsigned int bits;
3914 uint32_t i;
3915
3916 pback = pin + total_streams_size - 1;
3917 pbackend = pin;
3918 if (!elf_fetch_backward_init (&pback, pbackend, &val, &bits))
3919 return 0;
3920
3921 /* This is one of the inner loops of the decompression algorithm, so we
3922 put some effort into optimization. We can't get more than 64 bytes
3923 from a single call to elf_fetch_bits_backward, and we can't subtract
3924 more than 11 bits at a time. */
3925
3926 if (regenerated_size >= 64)
3927 {
3928 unsigned char *plitstart;
3929 unsigned char *plitstop;
3930
3931 plitstart = plit;
3932 plitstop = plit + regenerated_size - 64;
3933 while (plit < plitstop)
3934 {
3935 uint16_t t;
3936
3937 if (!elf_fetch_bits_backward (&pback, pbackend, &val, &bits))
3938 return 0;
3939
3940 if (bits < 16)
3941 break;
3942
3943 while (bits >= 33)
3944 {
3945 t = huffman_table[(val >> (bits - huffman_table_bits))
3946 & huffman_mask];
3947 *plit = t >> 8;
3948 ++plit;
3949 bits -= t & 0xff;
3950
3951 t = huffman_table[(val >> (bits - huffman_table_bits))
3952 & huffman_mask];
3953 *plit = t >> 8;
3954 ++plit;
3955 bits -= t & 0xff;
3956
3957 t = huffman_table[(val >> (bits - huffman_table_bits))
3958 & huffman_mask];
3959 *plit = t >> 8;
3960 ++plit;
3961 bits -= t & 0xff;
3962 }
3963
3964 while (bits > 11)
3965 {
3966 t = huffman_table[(val >> (bits - huffman_table_bits))
3967 & huffman_mask];
3968 *plit = t >> 8;
3969 ++plit;
3970 bits -= t & 0xff;
3971 }
3972 }
3973
3974 regenerated_size -= plit - plitstart;
3975 }
3976
3977 for (i = 0; i < regenerated_size; ++i)
3978 {
3979 uint16_t t;
3980
3981 if (!elf_fetch_bits_backward (&pback, pbackend, &val, &bits))
3982 return 0;
3983
3984 if (unlikely (bits < huffman_table_bits))
3985 {
3986 t = huffman_table[(val << (huffman_table_bits - bits))
3987 & huffman_mask];
3988 if (unlikely (bits < (t & 0xff)))
3989 {
3990 elf_uncompress_failed ();
3991 return 0;
3992 }
3993 }
3994 else
3995 t = huffman_table[(val >> (bits - huffman_table_bits))
3996 & huffman_mask];
3997
3998 *plit = t >> 8;
3999 ++plit;
4000 bits -= t & 0xff;
4001 }
4002
4003 return 1;
4004 }
4005
4006 {
4007 uint32_t stream_size1, stream_size2, stream_size3, stream_size4;
4008 uint32_t tot;
4009 const unsigned char *pback1, *pback2, *pback3, *pback4;
4010 const unsigned char *pbackend1, *pbackend2, *pbackend3, *pbackend4;
4011 uint64_t val1, val2, val3, val4;
4012 unsigned int bits1, bits2, bits3, bits4;
4013 unsigned char *plit1, *plit2, *plit3, *plit4;
4014 uint32_t regenerated_stream_size;
4015 uint32_t regenerated_stream_size4;
4016 uint16_t t1, t2, t3, t4;
4017 uint32_t i;
4018 uint32_t limit;
4019
4020 /* Read jump table. */
4021 if (unlikely (pin + 5 >= pinend))
4022 {
4023 elf_uncompress_failed ();
4024 return 0;
4025 }
4026 stream_size1 = (uint32_t)*pin | ((uint32_t)pin[1] << 8);
4027 pin += 2;
4028 stream_size2 = (uint32_t)*pin | ((uint32_t)pin[1] << 8);
4029 pin += 2;
4030 stream_size3 = (uint32_t)*pin | ((uint32_t)pin[1] << 8);
4031 pin += 2;
4032 tot = stream_size1 + stream_size2 + stream_size3;
4033 if (unlikely (tot > total_streams_size - 6))
4034 {
4035 elf_uncompress_failed ();
4036 return 0;
4037 }
4038 stream_size4 = total_streams_size - 6 - tot;
4039
4040 pback1 = pin + stream_size1 - 1;
4041 pbackend1 = pin;
4042
4043 pback2 = pback1 + stream_size2;
4044 pbackend2 = pback1 + 1;
4045
4046 pback3 = pback2 + stream_size3;
4047 pbackend3 = pback2 + 1;
4048
4049 pback4 = pback3 + stream_size4;
4050 pbackend4 = pback3 + 1;
4051
4052 if (!elf_fetch_backward_init (&pback1, pbackend1, &val1, &bits1))
4053 return 0;
4054 if (!elf_fetch_backward_init (&pback2, pbackend2, &val2, &bits2))
4055 return 0;
4056 if (!elf_fetch_backward_init (&pback3, pbackend3, &val3, &bits3))
4057 return 0;
4058 if (!elf_fetch_backward_init (&pback4, pbackend4, &val4, &bits4))
4059 return 0;
4060
4061 regenerated_stream_size = (regenerated_size + 3) / 4;
4062
4063 plit1 = plit;
4064 plit2 = plit1 + regenerated_stream_size;
4065 plit3 = plit2 + regenerated_stream_size;
4066 plit4 = plit3 + regenerated_stream_size;
4067
4068 regenerated_stream_size4 = regenerated_size - regenerated_stream_size * 3;
4069
4070 /* We can't get more than 64 literal bytes from a single call to
4071 elf_fetch_bits_backward. The fourth stream can be up to 3 bytes less,
4072 so use as the limit. */
4073
4074 limit = regenerated_stream_size4 <= 64 ? 0 : regenerated_stream_size4 - 64;
4075 i = 0;
4076 while (i < limit)
4077 {
4078 if (!elf_fetch_bits_backward (&pback1, pbackend1, &val1, &bits1))
4079 return 0;
4080 if (!elf_fetch_bits_backward (&pback2, pbackend2, &val2, &bits2))
4081 return 0;
4082 if (!elf_fetch_bits_backward (&pback3, pbackend3, &val3, &bits3))
4083 return 0;
4084 if (!elf_fetch_bits_backward (&pback4, pbackend4, &val4, &bits4))
4085 return 0;
4086
4087 /* We can't subtract more than 11 bits at a time. */
4088
4089 do
4090 {
4091 t1 = huffman_table[(val1 >> (bits1 - huffman_table_bits))
4092 & huffman_mask];
4093 t2 = huffman_table[(val2 >> (bits2 - huffman_table_bits))
4094 & huffman_mask];
4095 t3 = huffman_table[(val3 >> (bits3 - huffman_table_bits))
4096 & huffman_mask];
4097 t4 = huffman_table[(val4 >> (bits4 - huffman_table_bits))
4098 & huffman_mask];
4099
4100 *plit1 = t1 >> 8;
4101 ++plit1;
4102 bits1 -= t1 & 0xff;
4103
4104 *plit2 = t2 >> 8;
4105 ++plit2;
4106 bits2 -= t2 & 0xff;
4107
4108 *plit3 = t3 >> 8;
4109 ++plit3;
4110 bits3 -= t3 & 0xff;
4111
4112 *plit4 = t4 >> 8;
4113 ++plit4;
4114 bits4 -= t4 & 0xff;
4115
4116 ++i;
4117 }
4118 while (bits1 > 11 && bits2 > 11 && bits3 > 11 && bits4 > 11);
4119 }
4120
4121 while (i < regenerated_stream_size)
4122 {
4123 int use4;
4124
4125 use4 = i < regenerated_stream_size4;
4126
4127 if (!elf_fetch_bits_backward (&pback1, pbackend1, &val1, &bits1))
4128 return 0;
4129 if (!elf_fetch_bits_backward (&pback2, pbackend2, &val2, &bits2))
4130 return 0;
4131 if (!elf_fetch_bits_backward (&pback3, pbackend3, &val3, &bits3))
4132 return 0;
4133 if (use4)
4134 {
4135 if (!elf_fetch_bits_backward (&pback4, pbackend4, &val4, &bits4))
4136 return 0;
4137 }
4138
4139 if (unlikely (bits1 < huffman_table_bits))
4140 {
4141 t1 = huffman_table[(val1 << (huffman_table_bits - bits1))
4142 & huffman_mask];
4143 if (unlikely (bits1 < (t1 & 0xff)))
4144 {
4145 elf_uncompress_failed ();
4146 return 0;
4147 }
4148 }
4149 else
4150 t1 = huffman_table[(val1 >> (bits1 - huffman_table_bits))
4151 & huffman_mask];
4152
4153 if (unlikely (bits2 < huffman_table_bits))
4154 {
4155 t2 = huffman_table[(val2 << (huffman_table_bits - bits2))
4156 & huffman_mask];
4157 if (unlikely (bits2 < (t2 & 0xff)))
4158 {
4159 elf_uncompress_failed ();
4160 return 0;
4161 }
4162 }
4163 else
4164 t2 = huffman_table[(val2 >> (bits2 - huffman_table_bits))
4165 & huffman_mask];
4166
4167 if (unlikely (bits3 < huffman_table_bits))
4168 {
4169 t3 = huffman_table[(val3 << (huffman_table_bits - bits3))
4170 & huffman_mask];
4171 if (unlikely (bits3 < (t3 & 0xff)))
4172 {
4173 elf_uncompress_failed ();
4174 return 0;
4175 }
4176 }
4177 else
4178 t3 = huffman_table[(val3 >> (bits3 - huffman_table_bits))
4179 & huffman_mask];
4180
4181 if (use4)
4182 {
4183 if (unlikely (bits4 < huffman_table_bits))
4184 {
4185 t4 = huffman_table[(val4 << (huffman_table_bits - bits4))
4186 & huffman_mask];
4187 if (unlikely (bits4 < (t4 & 0xff)))
4188 {
4189 elf_uncompress_failed ();
4190 return 0;
4191 }
4192 }
4193 else
4194 t4 = huffman_table[(val4 >> (bits4 - huffman_table_bits))
4195 & huffman_mask];
4196
4197 *plit4 = t4 >> 8;
4198 ++plit4;
4199 bits4 -= t4 & 0xff;
4200 }
4201
4202 *plit1 = t1 >> 8;
4203 ++plit1;
4204 bits1 -= t1 & 0xff;
4205
4206 *plit2 = t2 >> 8;
4207 ++plit2;
4208 bits2 -= t2 & 0xff;
4209
4210 *plit3 = t3 >> 8;
4211 ++plit3;
4212 bits3 -= t3 & 0xff;
4213
4214 ++i;
4215 }
4216 }
4217
4218 return 1;
4219}
4220
4221/* The information used to decompress a sequence code, which can be a literal
4222 length, an offset, or a match length. */
4223
4224struct elf_zstd_seq_decode
4225{
4226 const struct elf_zstd_fse_baseline_entry *table;
4227 int table_bits;
4228};
4229
4230/* Unpack a sequence code compression mode. */
4231
4232static int
4233elf_zstd_unpack_seq_decode (int mode,
4234 const unsigned char **ppin,
4235 const unsigned char *pinend,
4236 const struct elf_zstd_fse_baseline_entry *predef,
4237 int predef_bits,
4238 uint16_t *scratch,
4239 int maxidx,
4240 struct elf_zstd_fse_baseline_entry *table,
4241 int table_bits,
4242 int (*conv)(const struct elf_zstd_fse_entry *,
4243 int,
4244 struct elf_zstd_fse_baseline_entry *),
4245 struct elf_zstd_seq_decode *decode)
4246{
4247 switch (mode)
4248 {
4249 case 0:
4250 decode->table = predef;
4251 decode->table_bits = predef_bits;
4252 break;
4253
4254 case 1:
4255 {
4256 struct elf_zstd_fse_entry entry;
4257
4258 if (unlikely (*ppin >= pinend))
4259 {
4260 elf_uncompress_failed ();
4261 return 0;
4262 }
4263 entry.symbol = **ppin;
4264 ++*ppin;
4265 entry.bits = 0;
4266 entry.base = 0;
4267 decode->table_bits = 0;
4268 if (!conv (&entry, 0, table))
4269 return 0;
4270 }
4271 break;
4272
4273 case 2:
4274 {
4275 struct elf_zstd_fse_entry *fse_table;
4276
4277 /* We use the same space for the simple FSE table and the baseline
4278 table. */
4279 fse_table = (struct elf_zstd_fse_entry *)table;
4280 decode->table_bits = table_bits;
4281 if (!elf_zstd_read_fse (ppin, pinend, scratch, maxidx, fse_table,
4282 &decode->table_bits))
4283 return 0;
4284 if (!conv (fse_table, decode->table_bits, table))
4285 return 0;
4286 decode->table = table;
4287 }
4288 break;
4289
4290 case 3:
4291 if (unlikely (decode->table_bits == -1))
4292 {
4293 elf_uncompress_failed ();
4294 return 0;
4295 }
4296 break;
4297
4298 default:
4299 elf_uncompress_failed ();
4300 return 0;
4301 }
4302
4303 return 1;
4304}
4305
4306/* Decompress a zstd stream from PIN/SIN to POUT/SOUT. Code based on RFC 8878.
4307 Return 1 on success, 0 on error. */
4308
4309static int
4310elf_zstd_decompress (const unsigned char *pin, size_t sin,
4311 unsigned char *zdebug_table, unsigned char *pout,
4312 size_t sout)
4313{
4314 const unsigned char *pinend;
4315 unsigned char *poutstart;
4316 unsigned char *poutend;
4317 struct elf_zstd_seq_decode literal_decode;
4318 struct elf_zstd_fse_baseline_entry *literal_fse_table;
4319 struct elf_zstd_seq_decode match_decode;
4320 struct elf_zstd_fse_baseline_entry *match_fse_table;
4321 struct elf_zstd_seq_decode offset_decode;
4322 struct elf_zstd_fse_baseline_entry *offset_fse_table;
4323 uint16_t *huffman_table;
4324 int huffman_table_bits;
4325 uint32_t repeated_offset1;
4326 uint32_t repeated_offset2;
4327 uint32_t repeated_offset3;
4328 uint16_t *scratch;
4329 unsigned char hdr;
4330 int has_checksum;
4331 uint64_t content_size;
4332 int last_block;
4333
4334 pinend = pin + sin;
4335 poutstart = pout;
4336 poutend = pout + sout;
4337
4338 literal_decode.table = NULL;
4339 literal_decode.table_bits = -1;
4340 literal_fse_table = ((struct elf_zstd_fse_baseline_entry *)
4341 (zdebug_table + ZSTD_TABLE_LITERAL_FSE_OFFSET));
4342
4343 match_decode.table = NULL;
4344 match_decode.table_bits = -1;
4345 match_fse_table = ((struct elf_zstd_fse_baseline_entry *)
4346 (zdebug_table + ZSTD_TABLE_MATCH_FSE_OFFSET));
4347
4348 offset_decode.table = NULL;
4349 offset_decode.table_bits = -1;
4350 offset_fse_table = ((struct elf_zstd_fse_baseline_entry *)
4351 (zdebug_table + ZSTD_TABLE_OFFSET_FSE_OFFSET));
4352 huffman_table = ((uint16_t *)
4353 (zdebug_table + ZSTD_TABLE_HUFFMAN_OFFSET));
4354 huffman_table_bits = 0;
4355 scratch = ((uint16_t *)
4356 (zdebug_table + ZSTD_TABLE_WORK_OFFSET));
4357
4358 repeated_offset1 = 1;
4359 repeated_offset2 = 4;
4360 repeated_offset3 = 8;
4361
4362 if (unlikely (sin < 4))
4363 {
4364 elf_uncompress_failed ();
4365 return 0;
4366 }
4367
4368 /* These values are the zstd magic number. */
4369 if (unlikely (pin[0] != 0x28
4370 || pin[1] != 0xb5
4371 || pin[2] != 0x2f
4372 || pin[3] != 0xfd))
4373 {
4374 elf_uncompress_failed ();
4375 return 0;
4376 }
4377
4378 pin += 4;
4379
4380 if (unlikely (pin >= pinend))
4381 {
4382 elf_uncompress_failed ();
4383 return 0;
4384 }
4385
4386 hdr = *pin++;
4387
4388 /* We expect a single frame. */
4389 if (unlikely ((hdr & (1 << 5)) == 0))
4390 {
4391 elf_uncompress_failed ();
4392 return 0;
4393 }
4394 /* Reserved bit must be zero. */
4395 if (unlikely ((hdr & (1 << 3)) != 0))
4396 {
4397 elf_uncompress_failed ();
4398 return 0;
4399 }
4400 /* We do not expect a dictionary. */
4401 if (unlikely ((hdr & 3) != 0))
4402 {
4403 elf_uncompress_failed ();
4404 return 0;
4405 }
4406 has_checksum = (hdr & (1 << 2)) != 0;
4407 switch (hdr >> 6)
4408 {
4409 case 0:
4410 if (unlikely (pin >= pinend))
4411 {
4412 elf_uncompress_failed ();
4413 return 0;
4414 }
4415 content_size = (uint64_t) *pin++;
4416 break;
4417 case 1:
4418 if (unlikely (pin + 1 >= pinend))
4419 {
4420 elf_uncompress_failed ();
4421 return 0;
4422 }
4423 content_size = (((uint64_t) pin[0]) | (((uint64_t) pin[1]) << 8)) + 256;
4424 pin += 2;
4425 break;
4426 case 2:
4427 if (unlikely (pin + 3 >= pinend))
4428 {
4429 elf_uncompress_failed ();
4430 return 0;
4431 }
4432 content_size = ((uint64_t) pin[0]
4433 | (((uint64_t) pin[1]) << 8)
4434 | (((uint64_t) pin[2]) << 16)
4435 | (((uint64_t) pin[3]) << 24));
4436 pin += 4;
4437 break;
4438 case 3:
4439 if (unlikely (pin + 7 >= pinend))
4440 {
4441 elf_uncompress_failed ();
4442 return 0;
4443 }
4444 content_size = ((uint64_t) pin[0]
4445 | (((uint64_t) pin[1]) << 8)
4446 | (((uint64_t) pin[2]) << 16)
4447 | (((uint64_t) pin[3]) << 24)
4448 | (((uint64_t) pin[4]) << 32)
4449 | (((uint64_t) pin[5]) << 40)
4450 | (((uint64_t) pin[6]) << 48)
4451 | (((uint64_t) pin[7]) << 56));
4452 pin += 8;
4453 break;
4454 default:
4455 elf_uncompress_failed ();
4456 return 0;
4457 }
4458
4459 if (unlikely (content_size != (size_t) content_size
4460 || (size_t) content_size != sout))
4461 {
4462 elf_uncompress_failed ();
4463 return 0;
4464 }
4465
4466 last_block = 0;
4467 while (!last_block)
4468 {
4469 uint32_t block_hdr;
4470 int block_type;
4471 uint32_t block_size;
4472
4473 if (unlikely (pin + 2 >= pinend))
4474 {
4475 elf_uncompress_failed ();
4476 return 0;
4477 }
4478 block_hdr = ((uint32_t) pin[0]
4479 | (((uint32_t) pin[1]) << 8)
4480 | (((uint32_t) pin[2]) << 16));
4481 pin += 3;
4482
4483 last_block = block_hdr & 1;
4484 block_type = (block_hdr >> 1) & 3;
4485 block_size = block_hdr >> 3;
4486
4487 switch (block_type)
4488 {
4489 case 0:
4490 /* Raw_Block */
4491 if (unlikely ((size_t) block_size > (size_t) (pinend - pin)))
4492 {
4493 elf_uncompress_failed ();
4494 return 0;
4495 }
4496 if (unlikely ((size_t) block_size > (size_t) (poutend - pout)))
4497 {
4498 elf_uncompress_failed ();
4499 return 0;
4500 }
4501 memcpy (pout, pin, block_size);
4502 pout += block_size;
4503 pin += block_size;
4504 break;
4505
4506 case 1:
4507 /* RLE_Block */
4508 if (unlikely (pin >= pinend))
4509 {
4510 elf_uncompress_failed ();
4511 return 0;
4512 }
4513 if (unlikely ((size_t) block_size > (size_t) (poutend - pout)))
4514 {
4515 elf_uncompress_failed ();
4516 return 0;
4517 }
4518 memset (pout, *pin, block_size);
4519 pout += block_size;
4520 pin++;
4521 break;
4522
4523 case 2:
4524 {
4525 const unsigned char *pblockend;
4526 unsigned char *plitstack;
4527 unsigned char *plit;
4528 uint32_t literal_count;
4529 unsigned char seq_hdr;
4530 size_t seq_count;
4531 size_t seq;
4532 const unsigned char *pback;
4533 uint64_t val;
4534 unsigned int bits;
4535 unsigned int literal_state;
4536 unsigned int offset_state;
4537 unsigned int match_state;
4538
4539 /* Compressed_Block */
4540 if (unlikely ((size_t) block_size > (size_t) (pinend - pin)))
4541 {
4542 elf_uncompress_failed ();
4543 return 0;
4544 }
4545
4546 pblockend = pin + block_size;
4547
4548 /* Read the literals into the end of the output space, and leave
4549 PLIT pointing at them. */
4550
4551 if (!elf_zstd_read_literals (&pin, pblockend, pout, poutend,
4552 scratch, huffman_table,
4553 &huffman_table_bits,
4554 &plitstack))
4555 return 0;
4556 plit = plitstack;
4557 literal_count = poutend - plit;
4558
4559 seq_hdr = *pin;
4560 pin++;
4561 if (seq_hdr < 128)
4562 seq_count = seq_hdr;
4563 else if (seq_hdr < 255)
4564 {
4565 if (unlikely (pin >= pinend))
4566 {
4567 elf_uncompress_failed ();
4568 return 0;
4569 }
4570 seq_count = ((seq_hdr - 128) << 8) + *pin;
4571 pin++;
4572 }
4573 else
4574 {
4575 if (unlikely (pin + 1 >= pinend))
4576 {
4577 elf_uncompress_failed ();
4578 return 0;
4579 }
4580 seq_count = *pin + (pin[1] << 8) + 0x7f00;
4581 pin += 2;
4582 }
4583
4584 if (seq_count > 0)
4585 {
4586 int (*pfn)(const struct elf_zstd_fse_entry *,
4587 int, struct elf_zstd_fse_baseline_entry *);
4588
4589 if (unlikely (pin >= pinend))
4590 {
4591 elf_uncompress_failed ();
4592 return 0;
4593 }
4594 seq_hdr = *pin;
4595 ++pin;
4596
4597 pfn = elf_zstd_make_literal_baseline_fse;
4598 if (!elf_zstd_unpack_seq_decode ((seq_hdr >> 6) & 3,
4599 &pin, pinend,
4600 &elf_zstd_lit_table[0], 6,
4601 scratch, 35,
4602 literal_fse_table, 9, pfn,
4603 &literal_decode))
4604 return 0;
4605
4606 pfn = elf_zstd_make_offset_baseline_fse;
4607 if (!elf_zstd_unpack_seq_decode ((seq_hdr >> 4) & 3,
4608 &pin, pinend,
4609 &elf_zstd_offset_table[0], 5,
4610 scratch, 31,
4611 offset_fse_table, 8, pfn,
4612 &offset_decode))
4613 return 0;
4614
4615 pfn = elf_zstd_make_match_baseline_fse;
4616 if (!elf_zstd_unpack_seq_decode ((seq_hdr >> 2) & 3,
4617 &pin, pinend,
4618 &elf_zstd_match_table[0], 6,
4619 scratch, 52,
4620 match_fse_table, 9, pfn,
4621 &match_decode))
4622 return 0;
4623 }
4624
4625 pback = pblockend - 1;
4626 if (!elf_fetch_backward_init (&pback, pin, &val, &bits))
4627 return 0;
4628
4629 bits -= literal_decode.table_bits;
4630 literal_state = ((val >> bits)
4631 & ((1U << literal_decode.table_bits) - 1));
4632
4633 if (!elf_fetch_bits_backward (&pback, pin, &val, &bits))
4634 return 0;
4635 bits -= offset_decode.table_bits;
4636 offset_state = ((val >> bits)
4637 & ((1U << offset_decode.table_bits) - 1));
4638
4639 if (!elf_fetch_bits_backward (&pback, pin, &val, &bits))
4640 return 0;
4641 bits -= match_decode.table_bits;
4642 match_state = ((val >> bits)
4643 & ((1U << match_decode.table_bits) - 1));
4644
4645 seq = 0;
4646 while (1)
4647 {
4648 const struct elf_zstd_fse_baseline_entry *pt;
4649 uint32_t offset_basebits;
4650 uint32_t offset_baseline;
4651 uint32_t offset_bits;
4652 uint32_t offset_base;
4653 uint32_t offset;
4654 uint32_t match_baseline;
4655 uint32_t match_bits;
4656 uint32_t match_base;
4657 uint32_t match;
4658 uint32_t literal_baseline;
4659 uint32_t literal_bits;
4660 uint32_t literal_base;
4661 uint32_t literal;
4662 uint32_t need;
4663 uint32_t add;
4664
4665 pt = &offset_decode.table[offset_state];
4666 offset_basebits = pt->basebits;
4667 offset_baseline = pt->baseline;
4668 offset_bits = pt->bits;
4669 offset_base = pt->base;
4670
4671 /* This case can be more than 16 bits, which is all that
4672 elf_fetch_bits_backward promises. */
4673 need = offset_basebits;
4674 add = 0;
4675 if (unlikely (need > 16))
4676 {
4677 if (!elf_fetch_bits_backward (&pback, pin, &val, &bits))
4678 return 0;
4679 bits -= 16;
4680 add = (val >> bits) & ((1U << 16) - 1);
4681 need -= 16;
4682 add <<= need;
4683 }
4684 if (need > 0)
4685 {
4686 if (!elf_fetch_bits_backward (&pback, pin, &val, &bits))
4687 return 0;
4688 bits -= need;
4689 add += (val >> bits) & ((1U << need) - 1);
4690 }
4691
4692 offset = offset_baseline + add;
4693
4694 pt = &match_decode.table[match_state];
4695 need = pt->basebits;
4696 match_baseline = pt->baseline;
4697 match_bits = pt->bits;
4698 match_base = pt->base;
4699
4700 add = 0;
4701 if (need > 0)
4702 {
4703 if (!elf_fetch_bits_backward (&pback, pin, &val, &bits))
4704 return 0;
4705 bits -= need;
4706 add = (val >> bits) & ((1U << need) - 1);
4707 }
4708
4709 match = match_baseline + add;
4710
4711 pt = &literal_decode.table[literal_state];
4712 need = pt->basebits;
4713 literal_baseline = pt->baseline;
4714 literal_bits = pt->bits;
4715 literal_base = pt->base;
4716
4717 add = 0;
4718 if (need > 0)
4719 {
4720 if (!elf_fetch_bits_backward (&pback, pin, &val, &bits))
4721 return 0;
4722 bits -= need;
4723 add = (val >> bits) & ((1U << need) - 1);
4724 }
4725
4726 literal = literal_baseline + add;
4727
4728 /* See the comment in elf_zstd_make_offset_baseline_fse. */
4729 if (offset_basebits > 1)
4730 {
4731 repeated_offset3 = repeated_offset2;
4732 repeated_offset2 = repeated_offset1;
4733 repeated_offset1 = offset;
4734 }
4735 else
4736 {
4737 if (unlikely (literal == 0))
4738 ++offset;
4739 switch (offset)
4740 {
4741 case 1:
4742 offset = repeated_offset1;
4743 break;
4744 case 2:
4745 offset = repeated_offset2;
4746 repeated_offset2 = repeated_offset1;
4747 repeated_offset1 = offset;
4748 break;
4749 case 3:
4750 offset = repeated_offset3;
4751 repeated_offset3 = repeated_offset2;
4752 repeated_offset2 = repeated_offset1;
4753 repeated_offset1 = offset;
4754 break;
4755 case 4:
4756 offset = repeated_offset1 - 1;
4757 repeated_offset3 = repeated_offset2;
4758 repeated_offset2 = repeated_offset1;
4759 repeated_offset1 = offset;
4760 break;
4761 }
4762 }
4763
4764 ++seq;
4765 if (seq < seq_count)
4766 {
4767 uint32_t v;
4768
4769 /* Update the three states. */
4770
4771 if (!elf_fetch_bits_backward (&pback, pin, &val, &bits))
4772 return 0;
4773
4774 need = literal_bits;
4775 bits -= need;
4776 v = (val >> bits) & (((uint32_t)1 << need) - 1);
4777
4778 literal_state = literal_base + v;
4779
4780 if (!elf_fetch_bits_backward (&pback, pin, &val, &bits))
4781 return 0;
4782
4783 need = match_bits;
4784 bits -= need;
4785 v = (val >> bits) & (((uint32_t)1 << need) - 1);
4786
4787 match_state = match_base + v;
4788
4789 if (!elf_fetch_bits_backward (&pback, pin, &val, &bits))
4790 return 0;
4791
4792 need = offset_bits;
4793 bits -= need;
4794 v = (val >> bits) & (((uint32_t)1 << need) - 1);
4795
4796 offset_state = offset_base + v;
4797 }
4798
4799 /* The next sequence is now in LITERAL, OFFSET, MATCH. */
4800
4801 /* Copy LITERAL bytes from the literals. */
4802
4803 if (unlikely ((size_t)(poutend - pout) < literal))
4804 {
4805 elf_uncompress_failed ();
4806 return 0;
4807 }
4808
4809 if (unlikely (literal_count < literal))
4810 {
4811 elf_uncompress_failed ();
4812 return 0;
4813 }
4814
4815 literal_count -= literal;
4816
4817 /* Often LITERAL is small, so handle small cases quickly. */
4818 switch (literal)
4819 {
4820 case 8:
4821 *pout++ = *plit++;
4822 ATTRIBUTE_FALLTHROUGH;
4823 case 7:
4824 *pout++ = *plit++;
4825 ATTRIBUTE_FALLTHROUGH;
4826 case 6:
4827 *pout++ = *plit++;
4828 ATTRIBUTE_FALLTHROUGH;
4829 case 5:
4830 *pout++ = *plit++;
4831 ATTRIBUTE_FALLTHROUGH;
4832 case 4:
4833 *pout++ = *plit++;
4834 ATTRIBUTE_FALLTHROUGH;
4835 case 3:
4836 *pout++ = *plit++;
4837 ATTRIBUTE_FALLTHROUGH;
4838 case 2:
4839 *pout++ = *plit++;
4840 ATTRIBUTE_FALLTHROUGH;
4841 case 1:
4842 *pout++ = *plit++;
4843 break;
4844
4845 case 0:
4846 break;
4847
4848 default:
4849 if (unlikely ((size_t)(plit - pout) < literal))
4850 {
4851 uint32_t move;
4852
4853 move = plit - pout;
4854 while (literal > move)
4855 {
4856 memcpy (pout, plit, move);
4857 pout += move;
4858 plit += move;
4859 literal -= move;
4860 }
4861 }
4862
4863 memcpy (pout, plit, literal);
4864 pout += literal;
4865 plit += literal;
4866 }
4867
4868 if (match > 0)
4869 {
4870 /* Copy MATCH bytes from the decoded output at OFFSET. */
4871
4872 if (unlikely ((size_t)(poutend - pout) < match))
4873 {
4874 elf_uncompress_failed ();
4875 return 0;
4876 }
4877
4878 if (unlikely ((size_t)(pout - poutstart) < offset))
4879 {
4880 elf_uncompress_failed ();
4881 return 0;
4882 }
4883
4884 if (offset >= match)
4885 {
4886 memcpy (pout, pout - offset, match);
4887 pout += match;
4888 }
4889 else
4890 {
4891 while (match > 0)
4892 {
4893 uint32_t copy;
4894
4895 copy = match < offset ? match : offset;
4896 memcpy (pout, pout - offset, copy);
4897 match -= copy;
4898 pout += copy;
4899 }
4900 }
4901 }
4902
4903 if (unlikely (seq >= seq_count))
4904 {
4905 /* Copy remaining literals. */
4906 if (literal_count > 0 && plit != pout)
4907 {
4908 if (unlikely ((size_t)(poutend - pout)
4909 < literal_count))
4910 {
4911 elf_uncompress_failed ();
4912 return 0;
4913 }
4914
4915 if ((size_t)(plit - pout) < literal_count)
4916 {
4917 uint32_t move;
4918
4919 move = plit - pout;
4920 while (literal_count > move)
4921 {
4922 memcpy (pout, plit, move);
4923 pout += move;
4924 plit += move;
4925 literal_count -= move;
4926 }
4927 }
4928
4929 memcpy (pout, plit, literal_count);
4930 }
4931
4932 pout += literal_count;
4933
4934 break;
4935 }
4936 }
4937
4938 pin = pblockend;
4939 }
4940 break;
4941
4942 case 3:
4943 default:
4944 elf_uncompress_failed ();
4945 return 0;
4946 }
4947 }
4948
4949 if (has_checksum)
4950 {
4951 if (unlikely (pin + 4 > pinend))
4952 {
4953 elf_uncompress_failed ();
4954 return 0;
4955 }
4956
4957 /* We don't currently verify the checksum. Currently running GNU ld with
4958 --compress-debug-sections=zstd does not seem to generate a
4959 checksum. */
4960
4961 pin += 4;
4962 }
4963
4964 if (pin != pinend)
4965 {
4966 elf_uncompress_failed ();
4967 return 0;
4968 }
4969
4970 return 1;
4971}
4972
4973#define ZDEBUG_TABLE_SIZE \
4974 (ZLIB_TABLE_SIZE > ZSTD_TABLE_SIZE ? ZLIB_TABLE_SIZE : ZSTD_TABLE_SIZE)
4975
4976/* Uncompress the old compressed debug format, the one emitted by
4977 --compress-debug-sections=zlib-gnu. The compressed data is in
4978 COMPRESSED / COMPRESSED_SIZE, and the function writes to
4979 *UNCOMPRESSED / *UNCOMPRESSED_SIZE. ZDEBUG_TABLE is work space to
4980 hold Huffman tables. Returns 0 on error, 1 on successful
4981 decompression or if something goes wrong. In general we try to
4982 carry on, by returning 1, even if we can't decompress. */
4983
4984static int
4985elf_uncompress_zdebug (struct backtrace_state *state,
4986 const unsigned char *compressed, size_t compressed_size,
4987 uint16_t *zdebug_table,
4988 backtrace_error_callback error_callback, void *data,
4989 unsigned char **uncompressed, size_t *uncompressed_size)
4990{
4991 size_t sz;
4992 size_t i;
4993 unsigned char *po;
4994
4995 *uncompressed = NULL;
4996 *uncompressed_size = 0;
4997
4998 /* The format starts with the four bytes ZLIB, followed by the 8
4999 byte length of the uncompressed data in big-endian order,
5000 followed by a zlib stream. */
5001
5002 if (compressed_size < 12 || memcmp (compressed, "ZLIB", 4) != 0)
5003 return 1;
5004
5005 sz = 0;
5006 for (i = 0; i < 8; i++)
5007 sz = (sz << 8) | compressed[i + 4];
5008
5009 if (*uncompressed != NULL && *uncompressed_size >= sz)
5010 po = *uncompressed;
5011 else
5012 {
5013 po = (unsigned char *) backtrace_alloc (state, sz, error_callback, data);
5014 if (po == NULL)
5015 return 0;
5016 }
5017
5018 if (!elf_zlib_inflate_and_verify (compressed + 12, compressed_size - 12,
5019 zdebug_table, po, sz))
5020 return 1;
5021
5022 *uncompressed = po;
5023 *uncompressed_size = sz;
5024
5025 return 1;
5026}
5027
5028/* Uncompress the new compressed debug format, the official standard
5029 ELF approach emitted by --compress-debug-sections=zlib-gabi. The
5030 compressed data is in COMPRESSED / COMPRESSED_SIZE, and the
5031 function writes to *UNCOMPRESSED / *UNCOMPRESSED_SIZE.
5032 ZDEBUG_TABLE is work space as for elf_uncompress_zdebug. Returns 0
5033 on error, 1 on successful decompression or if something goes wrong.
5034 In general we try to carry on, by returning 1, even if we can't
5035 decompress. */
5036
5037static int
5038elf_uncompress_chdr (struct backtrace_state *state,
5039 const unsigned char *compressed, size_t compressed_size,
5040 uint16_t *zdebug_table,
5041 backtrace_error_callback error_callback, void *data,
5042 unsigned char **uncompressed, size_t *uncompressed_size)
5043{
5044 b_elf_chdr chdr;
5045 char *alc;
5046 size_t alc_len;
5047 unsigned char *po;
5048
5049 *uncompressed = NULL;
5050 *uncompressed_size = 0;
5051
5052 /* The format starts with an ELF compression header. */
5053 if (compressed_size < sizeof (b_elf_chdr))
5054 return 1;
5055
5056 /* The lld linker can misalign a compressed section, so we can't safely read
5057 the fields directly as we can for other ELF sections. See
5058 https://github.com/ianlancetaylor/libbacktrace/pull/120. */
5059 memcpy (&chdr, compressed, sizeof (b_elf_chdr));
5060
5061 alc = NULL;
5062 alc_len = 0;
5063 if (*uncompressed != NULL && *uncompressed_size >= chdr.ch_size)
5064 po = *uncompressed;
5065 else
5066 {
5067 alc_len = chdr.ch_size;
5068 alc = backtrace_alloc (state, alc_len, error_callback, data);
5069 if (alc == NULL)
5070 return 0;
5071 po = (unsigned char *) alc;
5072 }
5073
5074 switch (chdr.ch_type)
5075 {
5076 case ELFCOMPRESS_ZLIB:
5077 if (!elf_zlib_inflate_and_verify (compressed + sizeof (b_elf_chdr),
5078 compressed_size - sizeof (b_elf_chdr),
5079 zdebug_table, po, chdr.ch_size))
5080 goto skip;
5081 break;
5082
5083 case ELFCOMPRESS_ZSTD:
5084 if (!elf_zstd_decompress (compressed + sizeof (b_elf_chdr),
5085 compressed_size - sizeof (b_elf_chdr),
5086 (unsigned char *)zdebug_table, po,
5087 chdr.ch_size))
5088 goto skip;
5089 break;
5090
5091 default:
5092 /* Unsupported compression algorithm. */
5093 goto skip;
5094 }
5095
5096 *uncompressed = po;
5097 *uncompressed_size = chdr.ch_size;
5098
5099 return 1;
5100
5101 skip:
5102 if (alc != NULL && alc_len > 0)
5103 backtrace_free (state, alc, alc_len, error_callback, data);
5104 return 1;
5105}
5106
5107/* This function is a hook for testing the zlib support. It is only
5108 used by tests. */
5109
5110int
5111backtrace_uncompress_zdebug (struct backtrace_state *state,
5112 const unsigned char *compressed,
5113 size_t compressed_size,
5114 backtrace_error_callback error_callback,
5115 void *data, unsigned char **uncompressed,
5116 size_t *uncompressed_size)
5117{
5118 uint16_t *zdebug_table;
5119 int ret;
5120
5121 zdebug_table = ((uint16_t *) backtrace_alloc (state, ZDEBUG_TABLE_SIZE,
5122 error_callback, data));
5123 if (zdebug_table == NULL)
5124 return 0;
5125 ret = elf_uncompress_zdebug (state, compressed, compressed_size,
5126 zdebug_table, error_callback, data,
5127 uncompressed, uncompressed_size);
5128 backtrace_free (state, zdebug_table, ZDEBUG_TABLE_SIZE,
5129 error_callback, data);
5130 return ret;
5131}
5132
5133/* This function is a hook for testing the zstd support. It is only used by
5134 tests. */
5135
5136int
5137backtrace_uncompress_zstd (struct backtrace_state *state,
5138 const unsigned char *compressed,
5139 size_t compressed_size,
5140 backtrace_error_callback error_callback,
5141 void *data, unsigned char *uncompressed,
5142 size_t uncompressed_size)
5143{
5144 unsigned char *zdebug_table;
5145 int ret;
5146
5147 zdebug_table = ((unsigned char *) backtrace_alloc (state, ZDEBUG_TABLE_SIZE,
5148 error_callback, data));
5149 if (zdebug_table == NULL)
5150 return 0;
5151 ret = elf_zstd_decompress (compressed, compressed_size,
5152 zdebug_table, uncompressed, uncompressed_size);
5153 backtrace_free (state, zdebug_table, ZDEBUG_TABLE_SIZE,
5154 error_callback, data);
5155 return ret;
5156}
5157
5158/* Number of LZMA states. */
5159#define LZMA_STATES (12)
5160
5161/* Number of LZMA position states. The pb value of the property byte
5162 is the number of bits to include in these states, and the maximum
5163 value of pb is 4. */
5164#define LZMA_POS_STATES (16)
5165
5166/* Number of LZMA distance states. These are used match distances
5167 with a short match length: up to 4 bytes. */
5168#define LZMA_DIST_STATES (4)
5169
5170/* Number of LZMA distance slots. LZMA uses six bits to encode larger
5171 match lengths, so 1 << 6 possible probabilities. */
5172#define LZMA_DIST_SLOTS (64)
5173
5174/* LZMA distances 0 to 3 are encoded directly, larger values use a
5175 probability model. */
5176#define LZMA_DIST_MODEL_START (4)
5177
5178/* The LZMA probability model ends at 14. */
5179#define LZMA_DIST_MODEL_END (14)
5180
5181/* LZMA distance slots for distances less than 127. */
5182#define LZMA_FULL_DISTANCES (128)
5183
5184/* LZMA uses four alignment bits. */
5185#define LZMA_ALIGN_SIZE (16)
5186
5187/* LZMA match length is encoded with 4, 5, or 10 bits, some of which
5188 are already known. */
5189#define LZMA_LEN_LOW_SYMBOLS (8)
5190#define LZMA_LEN_MID_SYMBOLS (8)
5191#define LZMA_LEN_HIGH_SYMBOLS (256)
5192
5193/* LZMA literal encoding. */
5194#define LZMA_LITERAL_CODERS_MAX (16)
5195#define LZMA_LITERAL_CODER_SIZE (0x300)
5196
5197/* LZMA is based on a large set of probabilities, each managed
5198 independently. Each probability is an 11 bit number that we store
5199 in a uint16_t. We use a single large array of probabilities. */
5200
5201/* Lengths of entries in the LZMA probabilities array. The names used
5202 here are copied from the Linux kernel implementation. */
5203
5204#define LZMA_PROB_IS_MATCH_LEN (LZMA_STATES * LZMA_POS_STATES)
5205#define LZMA_PROB_IS_REP_LEN LZMA_STATES
5206#define LZMA_PROB_IS_REP0_LEN LZMA_STATES
5207#define LZMA_PROB_IS_REP1_LEN LZMA_STATES
5208#define LZMA_PROB_IS_REP2_LEN LZMA_STATES
5209#define LZMA_PROB_IS_REP0_LONG_LEN (LZMA_STATES * LZMA_POS_STATES)
5210#define LZMA_PROB_DIST_SLOT_LEN (LZMA_DIST_STATES * LZMA_DIST_SLOTS)
5211#define LZMA_PROB_DIST_SPECIAL_LEN (LZMA_FULL_DISTANCES - LZMA_DIST_MODEL_END)
5212#define LZMA_PROB_DIST_ALIGN_LEN LZMA_ALIGN_SIZE
5213#define LZMA_PROB_MATCH_LEN_CHOICE_LEN 1
5214#define LZMA_PROB_MATCH_LEN_CHOICE2_LEN 1
5215#define LZMA_PROB_MATCH_LEN_LOW_LEN (LZMA_POS_STATES * LZMA_LEN_LOW_SYMBOLS)
5216#define LZMA_PROB_MATCH_LEN_MID_LEN (LZMA_POS_STATES * LZMA_LEN_MID_SYMBOLS)
5217#define LZMA_PROB_MATCH_LEN_HIGH_LEN LZMA_LEN_HIGH_SYMBOLS
5218#define LZMA_PROB_REP_LEN_CHOICE_LEN 1
5219#define LZMA_PROB_REP_LEN_CHOICE2_LEN 1
5220#define LZMA_PROB_REP_LEN_LOW_LEN (LZMA_POS_STATES * LZMA_LEN_LOW_SYMBOLS)
5221#define LZMA_PROB_REP_LEN_MID_LEN (LZMA_POS_STATES * LZMA_LEN_MID_SYMBOLS)
5222#define LZMA_PROB_REP_LEN_HIGH_LEN LZMA_LEN_HIGH_SYMBOLS
5223#define LZMA_PROB_LITERAL_LEN \
5224 (LZMA_LITERAL_CODERS_MAX * LZMA_LITERAL_CODER_SIZE)
5225
5226/* Offsets into the LZMA probabilities array. This is mechanically
5227 generated from the above lengths. */
5228
5229#define LZMA_PROB_IS_MATCH_OFFSET 0
5230#define LZMA_PROB_IS_REP_OFFSET \
5231 (LZMA_PROB_IS_MATCH_OFFSET + LZMA_PROB_IS_MATCH_LEN)
5232#define LZMA_PROB_IS_REP0_OFFSET \
5233 (LZMA_PROB_IS_REP_OFFSET + LZMA_PROB_IS_REP_LEN)
5234#define LZMA_PROB_IS_REP1_OFFSET \
5235 (LZMA_PROB_IS_REP0_OFFSET + LZMA_PROB_IS_REP0_LEN)
5236#define LZMA_PROB_IS_REP2_OFFSET \
5237 (LZMA_PROB_IS_REP1_OFFSET + LZMA_PROB_IS_REP1_LEN)
5238#define LZMA_PROB_IS_REP0_LONG_OFFSET \
5239 (LZMA_PROB_IS_REP2_OFFSET + LZMA_PROB_IS_REP2_LEN)
5240#define LZMA_PROB_DIST_SLOT_OFFSET \
5241 (LZMA_PROB_IS_REP0_LONG_OFFSET + LZMA_PROB_IS_REP0_LONG_LEN)
5242#define LZMA_PROB_DIST_SPECIAL_OFFSET \
5243 (LZMA_PROB_DIST_SLOT_OFFSET + LZMA_PROB_DIST_SLOT_LEN)
5244#define LZMA_PROB_DIST_ALIGN_OFFSET \
5245 (LZMA_PROB_DIST_SPECIAL_OFFSET + LZMA_PROB_DIST_SPECIAL_LEN)
5246#define LZMA_PROB_MATCH_LEN_CHOICE_OFFSET \
5247 (LZMA_PROB_DIST_ALIGN_OFFSET + LZMA_PROB_DIST_ALIGN_LEN)
5248#define LZMA_PROB_MATCH_LEN_CHOICE2_OFFSET \
5249 (LZMA_PROB_MATCH_LEN_CHOICE_OFFSET + LZMA_PROB_MATCH_LEN_CHOICE_LEN)
5250#define LZMA_PROB_MATCH_LEN_LOW_OFFSET \
5251 (LZMA_PROB_MATCH_LEN_CHOICE2_OFFSET + LZMA_PROB_MATCH_LEN_CHOICE2_LEN)
5252#define LZMA_PROB_MATCH_LEN_MID_OFFSET \
5253 (LZMA_PROB_MATCH_LEN_LOW_OFFSET + LZMA_PROB_MATCH_LEN_LOW_LEN)
5254#define LZMA_PROB_MATCH_LEN_HIGH_OFFSET \
5255 (LZMA_PROB_MATCH_LEN_MID_OFFSET + LZMA_PROB_MATCH_LEN_MID_LEN)
5256#define LZMA_PROB_REP_LEN_CHOICE_OFFSET \
5257 (LZMA_PROB_MATCH_LEN_HIGH_OFFSET + LZMA_PROB_MATCH_LEN_HIGH_LEN)
5258#define LZMA_PROB_REP_LEN_CHOICE2_OFFSET \
5259 (LZMA_PROB_REP_LEN_CHOICE_OFFSET + LZMA_PROB_REP_LEN_CHOICE_LEN)
5260#define LZMA_PROB_REP_LEN_LOW_OFFSET \
5261 (LZMA_PROB_REP_LEN_CHOICE2_OFFSET + LZMA_PROB_REP_LEN_CHOICE2_LEN)
5262#define LZMA_PROB_REP_LEN_MID_OFFSET \
5263 (LZMA_PROB_REP_LEN_LOW_OFFSET + LZMA_PROB_REP_LEN_LOW_LEN)
5264#define LZMA_PROB_REP_LEN_HIGH_OFFSET \
5265 (LZMA_PROB_REP_LEN_MID_OFFSET + LZMA_PROB_REP_LEN_MID_LEN)
5266#define LZMA_PROB_LITERAL_OFFSET \
5267 (LZMA_PROB_REP_LEN_HIGH_OFFSET + LZMA_PROB_REP_LEN_HIGH_LEN)
5268
5269#define LZMA_PROB_TOTAL_COUNT \
5270 (LZMA_PROB_LITERAL_OFFSET + LZMA_PROB_LITERAL_LEN)
5271
5272/* Check that the number of LZMA probabilities is the same as the
5273 Linux kernel implementation. */
5274
5275#if LZMA_PROB_TOTAL_COUNT != 1846 + (1 << 4) * 0x300
5276 #error Wrong number of LZMA probabilities
5277#endif
5278
5279/* Expressions for the offset in the LZMA probabilities array of a
5280 specific probability. */
5281
5282#define LZMA_IS_MATCH(state, pos) \
5283 (LZMA_PROB_IS_MATCH_OFFSET + (state) * LZMA_POS_STATES + (pos))
5284#define LZMA_IS_REP(state) \
5285 (LZMA_PROB_IS_REP_OFFSET + (state))
5286#define LZMA_IS_REP0(state) \
5287 (LZMA_PROB_IS_REP0_OFFSET + (state))
5288#define LZMA_IS_REP1(state) \
5289 (LZMA_PROB_IS_REP1_OFFSET + (state))
5290#define LZMA_IS_REP2(state) \
5291 (LZMA_PROB_IS_REP2_OFFSET + (state))
5292#define LZMA_IS_REP0_LONG(state, pos) \
5293 (LZMA_PROB_IS_REP0_LONG_OFFSET + (state) * LZMA_POS_STATES + (pos))
5294#define LZMA_DIST_SLOT(dist, slot) \
5295 (LZMA_PROB_DIST_SLOT_OFFSET + (dist) * LZMA_DIST_SLOTS + (slot))
5296#define LZMA_DIST_SPECIAL(dist) \
5297 (LZMA_PROB_DIST_SPECIAL_OFFSET + (dist))
5298#define LZMA_DIST_ALIGN(dist) \
5299 (LZMA_PROB_DIST_ALIGN_OFFSET + (dist))
5300#define LZMA_MATCH_LEN_CHOICE \
5301 LZMA_PROB_MATCH_LEN_CHOICE_OFFSET
5302#define LZMA_MATCH_LEN_CHOICE2 \
5303 LZMA_PROB_MATCH_LEN_CHOICE2_OFFSET
5304#define LZMA_MATCH_LEN_LOW(pos, sym) \
5305 (LZMA_PROB_MATCH_LEN_LOW_OFFSET + (pos) * LZMA_LEN_LOW_SYMBOLS + (sym))
5306#define LZMA_MATCH_LEN_MID(pos, sym) \
5307 (LZMA_PROB_MATCH_LEN_MID_OFFSET + (pos) * LZMA_LEN_MID_SYMBOLS + (sym))
5308#define LZMA_MATCH_LEN_HIGH(sym) \
5309 (LZMA_PROB_MATCH_LEN_HIGH_OFFSET + (sym))
5310#define LZMA_REP_LEN_CHOICE \
5311 LZMA_PROB_REP_LEN_CHOICE_OFFSET
5312#define LZMA_REP_LEN_CHOICE2 \
5313 LZMA_PROB_REP_LEN_CHOICE2_OFFSET
5314#define LZMA_REP_LEN_LOW(pos, sym) \
5315 (LZMA_PROB_REP_LEN_LOW_OFFSET + (pos) * LZMA_LEN_LOW_SYMBOLS + (sym))
5316#define LZMA_REP_LEN_MID(pos, sym) \
5317 (LZMA_PROB_REP_LEN_MID_OFFSET + (pos) * LZMA_LEN_MID_SYMBOLS + (sym))
5318#define LZMA_REP_LEN_HIGH(sym) \
5319 (LZMA_PROB_REP_LEN_HIGH_OFFSET + (sym))
5320#define LZMA_LITERAL(code, size) \
5321 (LZMA_PROB_LITERAL_OFFSET + (code) * LZMA_LITERAL_CODER_SIZE + (size))
5322
5323/* Read an LZMA varint from BUF, reading and updating *POFFSET,
5324 setting *VAL. Returns 0 on error, 1 on success. */
5325
5326static int
5327elf_lzma_varint (const unsigned char *compressed, size_t compressed_size,
5328 size_t *poffset, uint64_t *val)
5329{
5330 size_t off;
5331 int i;
5332 uint64_t v;
5333 unsigned char b;
5334
5335 off = *poffset;
5336 i = 0;
5337 v = 0;
5338 while (1)
5339 {
5340 if (unlikely (off >= compressed_size))
5341 {
5342 elf_uncompress_failed ();
5343 return 0;
5344 }
5345 b = compressed[off];
5346 v |= (b & 0x7f) << (i * 7);
5347 ++off;
5348 if ((b & 0x80) == 0)
5349 {
5350 *poffset = off;
5351 *val = v;
5352 return 1;
5353 }
5354 ++i;
5355 if (unlikely (i >= 9))
5356 {
5357 elf_uncompress_failed ();
5358 return 0;
5359 }
5360 }
5361}
5362
5363/* Normalize the LZMA range decoder, pulling in an extra input byte if
5364 needed. */
5365
5366static void
5367elf_lzma_range_normalize (const unsigned char *compressed,
5368 size_t compressed_size, size_t *poffset,
5369 uint32_t *prange, uint32_t *pcode)
5370{
5371 if (*prange < (1U << 24))
5372 {
5373 if (unlikely (*poffset >= compressed_size))
5374 {
5375 /* We assume this will be caught elsewhere. */
5376 elf_uncompress_failed ();
5377 return;
5378 }
5379 *prange <<= 8;
5380 *pcode <<= 8;
5381 *pcode += compressed[*poffset];
5382 ++*poffset;
5383 }
5384}
5385
5386/* Read and return a single bit from the LZMA stream, reading and
5387 updating *PROB. Each bit comes from the range coder. */
5388
5389static int
5390elf_lzma_bit (const unsigned char *compressed, size_t compressed_size,
5391 uint16_t *prob, size_t *poffset, uint32_t *prange,
5392 uint32_t *pcode)
5393{
5394 uint32_t bound;
5395
5396 elf_lzma_range_normalize (compressed, compressed_size, poffset,
5397 prange, pcode);
5398 bound = (*prange >> 11) * (uint32_t) *prob;
5399 if (*pcode < bound)
5400 {
5401 *prange = bound;
5402 *prob += ((1U << 11) - *prob) >> 5;
5403 return 0;
5404 }
5405 else
5406 {
5407 *prange -= bound;
5408 *pcode -= bound;
5409 *prob -= *prob >> 5;
5410 return 1;
5411 }
5412}
5413
5414/* Read an integer of size BITS from the LZMA stream, most significant
5415 bit first. The bits are predicted using PROBS. */
5416
5417static uint32_t
5418elf_lzma_integer (const unsigned char *compressed, size_t compressed_size,
5419 uint16_t *probs, uint32_t bits, size_t *poffset,
5420 uint32_t *prange, uint32_t *pcode)
5421{
5422 uint32_t sym;
5423 uint32_t i;
5424
5425 sym = 1;
5426 for (i = 0; i < bits; i++)
5427 {
5428 int bit;
5429
5430 bit = elf_lzma_bit (compressed, compressed_size, probs + sym, poffset,
5431 prange, pcode);
5432 sym <<= 1;
5433 sym += bit;
5434 }
5435 return sym - (1 << bits);
5436}
5437
5438/* Read an integer of size BITS from the LZMA stream, least
5439 significant bit first. The bits are predicted using PROBS. */
5440
5441static uint32_t
5442elf_lzma_reverse_integer (const unsigned char *compressed,
5443 size_t compressed_size, uint16_t *probs,
5444 uint32_t bits, size_t *poffset, uint32_t *prange,
5445 uint32_t *pcode)
5446{
5447 uint32_t sym;
5448 uint32_t val;
5449 uint32_t i;
5450
5451 sym = 1;
5452 val = 0;
5453 for (i = 0; i < bits; i++)
5454 {
5455 int bit;
5456
5457 bit = elf_lzma_bit (compressed, compressed_size, probs + sym, poffset,
5458 prange, pcode);
5459 sym <<= 1;
5460 sym += bit;
5461 val += bit << i;
5462 }
5463 return val;
5464}
5465
5466/* Read a length from the LZMA stream. IS_REP picks either LZMA_MATCH
5467 or LZMA_REP probabilities. */
5468
5469static uint32_t
5470elf_lzma_len (const unsigned char *compressed, size_t compressed_size,
5471 uint16_t *probs, int is_rep, unsigned int pos_state,
5472 size_t *poffset, uint32_t *prange, uint32_t *pcode)
5473{
5474 uint16_t *probs_choice;
5475 uint16_t *probs_sym;
5476 uint32_t bits;
5477 uint32_t len;
5478
5479 probs_choice = probs + (is_rep
5480 ? LZMA_REP_LEN_CHOICE
5481 : LZMA_MATCH_LEN_CHOICE);
5482 if (elf_lzma_bit (compressed, compressed_size, probs_choice, poffset,
5483 prange, pcode))
5484 {
5485 probs_choice = probs + (is_rep
5486 ? LZMA_REP_LEN_CHOICE2
5487 : LZMA_MATCH_LEN_CHOICE2);
5488 if (elf_lzma_bit (compressed, compressed_size, probs_choice,
5489 poffset, prange, pcode))
5490 {
5491 probs_sym = probs + (is_rep
5492 ? LZMA_REP_LEN_HIGH (0)
5493 : LZMA_MATCH_LEN_HIGH (0));
5494 bits = 8;
5495 len = 2 + 8 + 8;
5496 }
5497 else
5498 {
5499 probs_sym = probs + (is_rep
5500 ? LZMA_REP_LEN_MID (pos_state, 0)
5501 : LZMA_MATCH_LEN_MID (pos_state, 0));
5502 bits = 3;
5503 len = 2 + 8;
5504 }
5505 }
5506 else
5507 {
5508 probs_sym = probs + (is_rep
5509 ? LZMA_REP_LEN_LOW (pos_state, 0)
5510 : LZMA_MATCH_LEN_LOW (pos_state, 0));
5511 bits = 3;
5512 len = 2;
5513 }
5514
5515 len += elf_lzma_integer (compressed, compressed_size, probs_sym, bits,
5516 poffset, prange, pcode);
5517 return len;
5518}
5519
5520/* Uncompress one LZMA block from a minidebug file. The compressed
5521 data is at COMPRESSED + *POFFSET. Update *POFFSET. Store the data
5522 into the memory at UNCOMPRESSED, size UNCOMPRESSED_SIZE. CHECK is
5523 the stream flag from the xz header. Return 1 on successful
5524 decompression. */
5525
5526static int
5527elf_uncompress_lzma_block (const unsigned char *compressed,
5528 size_t compressed_size, unsigned char check,
5529 uint16_t *probs, unsigned char *uncompressed,
5530 size_t uncompressed_size, size_t *poffset)
5531{
5532 size_t off;
5533 size_t block_header_offset;
5534 size_t block_header_size;
5535 unsigned char block_flags;
5536 uint64_t header_compressed_size;
5537 uint64_t header_uncompressed_size;
5538 unsigned char lzma2_properties;
5539 size_t crc_offset;
5540 uint32_t computed_crc;
5541 uint32_t stream_crc;
5542 size_t uncompressed_offset;
5543 size_t dict_start_offset;
5544 unsigned int lc;
5545 unsigned int lp;
5546 unsigned int pb;
5547 uint32_t range;
5548 uint32_t code;
5549 uint32_t lstate;
5550 uint32_t dist[4];
5551
5552 off = *poffset;
5553 block_header_offset = off;
5554
5555 /* Block header size is a single byte. */
5556 if (unlikely (off >= compressed_size))
5557 {
5558 elf_uncompress_failed ();
5559 return 0;
5560 }
5561 block_header_size = (compressed[off] + 1) * 4;
5562 if (unlikely (off + block_header_size > compressed_size))
5563 {
5564 elf_uncompress_failed ();
5565 return 0;
5566 }
5567
5568 /* Block flags. */
5569 block_flags = compressed[off + 1];
5570 if (unlikely ((block_flags & 0x3c) != 0))
5571 {
5572 elf_uncompress_failed ();
5573 return 0;
5574 }
5575
5576 off += 2;
5577
5578 /* Optional compressed size. */
5579 header_compressed_size = 0;
5580 if ((block_flags & 0x40) != 0)
5581 {
5582 *poffset = off;
5583 if (!elf_lzma_varint (compressed, compressed_size, poffset,
5584 &header_compressed_size))
5585 return 0;
5586 off = *poffset;
5587 }
5588
5589 /* Optional uncompressed size. */
5590 header_uncompressed_size = 0;
5591 if ((block_flags & 0x80) != 0)
5592 {
5593 *poffset = off;
5594 if (!elf_lzma_varint (compressed, compressed_size, poffset,
5595 &header_uncompressed_size))
5596 return 0;
5597 off = *poffset;
5598 }
5599
5600 /* The recipe for creating a minidebug file is to run the xz program
5601 with no arguments, so we expect exactly one filter: lzma2. */
5602
5603 if (unlikely ((block_flags & 0x3) != 0))
5604 {
5605 elf_uncompress_failed ();
5606 return 0;
5607 }
5608
5609 if (unlikely (off + 2 >= block_header_offset + block_header_size))
5610 {
5611 elf_uncompress_failed ();
5612 return 0;
5613 }
5614
5615 /* The filter ID for LZMA2 is 0x21. */
5616 if (unlikely (compressed[off] != 0x21))
5617 {
5618 elf_uncompress_failed ();
5619 return 0;
5620 }
5621 ++off;
5622
5623 /* The size of the filter properties for LZMA2 is 1. */
5624 if (unlikely (compressed[off] != 1))
5625 {
5626 elf_uncompress_failed ();
5627 return 0;
5628 }
5629 ++off;
5630
5631 lzma2_properties = compressed[off];
5632 ++off;
5633
5634 if (unlikely (lzma2_properties > 40))
5635 {
5636 elf_uncompress_failed ();
5637 return 0;
5638 }
5639
5640 /* The properties describe the dictionary size, but we don't care
5641 what that is. */
5642
5643 /* Skip to just before CRC, verifying zero bytes in between. */
5644 crc_offset = block_header_offset + block_header_size - 4;
5645 if (unlikely (crc_offset + 4 > compressed_size))
5646 {
5647 elf_uncompress_failed ();
5648 return 0;
5649 }
5650 for (; off < crc_offset; off++)
5651 {
5652 if (compressed[off] != 0)
5653 {
5654 elf_uncompress_failed ();
5655 return 0;
5656 }
5657 }
5658
5659 /* Block header CRC. */
5660 computed_crc = elf_crc32 (0, compressed + block_header_offset,
5661 block_header_size - 4);
5662 stream_crc = ((uint32_t)compressed[off]
5663 | ((uint32_t)compressed[off + 1] << 8)
5664 | ((uint32_t)compressed[off + 2] << 16)
5665 | ((uint32_t)compressed[off + 3] << 24));
5666 if (unlikely (computed_crc != stream_crc))
5667 {
5668 elf_uncompress_failed ();
5669 return 0;
5670 }
5671 off += 4;
5672
5673 /* Read a sequence of LZMA2 packets. */
5674
5675 uncompressed_offset = 0;
5676 dict_start_offset = 0;
5677 lc = 0;
5678 lp = 0;
5679 pb = 0;
5680 lstate = 0;
5681 while (off < compressed_size)
5682 {
5683 unsigned char control;
5684
5685 range = 0xffffffff;
5686 code = 0;
5687
5688 control = compressed[off];
5689 ++off;
5690 if (unlikely (control == 0))
5691 {
5692 /* End of packets. */
5693 break;
5694 }
5695
5696 if (control == 1 || control >= 0xe0)
5697 {
5698 /* Reset dictionary to empty. */
5699 dict_start_offset = uncompressed_offset;
5700 }
5701
5702 if (control < 0x80)
5703 {
5704 size_t chunk_size;
5705
5706 /* The only valid values here are 1 or 2. A 1 means to
5707 reset the dictionary (done above). Then we see an
5708 uncompressed chunk. */
5709
5710 if (unlikely (control > 2))
5711 {
5712 elf_uncompress_failed ();
5713 return 0;
5714 }
5715
5716 /* An uncompressed chunk is a two byte size followed by
5717 data. */
5718
5719 if (unlikely (off + 2 > compressed_size))
5720 {
5721 elf_uncompress_failed ();
5722 return 0;
5723 }
5724
5725 chunk_size = compressed[off] << 8;
5726 chunk_size += compressed[off + 1];
5727 ++chunk_size;
5728
5729 off += 2;
5730
5731 if (unlikely (off + chunk_size > compressed_size))
5732 {
5733 elf_uncompress_failed ();
5734 return 0;
5735 }
5736 if (unlikely (uncompressed_offset + chunk_size > uncompressed_size))
5737 {
5738 elf_uncompress_failed ();
5739 return 0;
5740 }
5741
5742 memcpy (uncompressed + uncompressed_offset, compressed + off,
5743 chunk_size);
5744 uncompressed_offset += chunk_size;
5745 off += chunk_size;
5746 }
5747 else
5748 {
5749 size_t uncompressed_chunk_start;
5750 size_t uncompressed_chunk_size;
5751 size_t compressed_chunk_size;
5752 size_t limit;
5753
5754 /* An LZMA chunk. This starts with an uncompressed size and
5755 a compressed size. */
5756
5757 if (unlikely (off + 4 >= compressed_size))
5758 {
5759 elf_uncompress_failed ();
5760 return 0;
5761 }
5762
5763 uncompressed_chunk_start = uncompressed_offset;
5764
5765 uncompressed_chunk_size = (control & 0x1f) << 16;
5766 uncompressed_chunk_size += compressed[off] << 8;
5767 uncompressed_chunk_size += compressed[off + 1];
5768 ++uncompressed_chunk_size;
5769
5770 compressed_chunk_size = compressed[off + 2] << 8;
5771 compressed_chunk_size += compressed[off + 3];
5772 ++compressed_chunk_size;
5773
5774 off += 4;
5775
5776 /* Bit 7 (0x80) is set.
5777 Bits 6 and 5 (0x40 and 0x20) are as follows:
5778 0: don't reset anything
5779 1: reset state
5780 2: reset state, read properties
5781 3: reset state, read properties, reset dictionary (done above) */
5782
5783 if (control >= 0xc0)
5784 {
5785 unsigned char props;
5786
5787 /* Bit 6 is set, read properties. */
5788
5789 if (unlikely (off >= compressed_size))
5790 {
5791 elf_uncompress_failed ();
5792 return 0;
5793 }
5794 props = compressed[off];
5795 ++off;
5796 if (unlikely (props > (4 * 5 + 4) * 9 + 8))
5797 {
5798 elf_uncompress_failed ();
5799 return 0;
5800 }
5801 pb = 0;
5802 while (props >= 9 * 5)
5803 {
5804 props -= 9 * 5;
5805 ++pb;
5806 }
5807 lp = 0;
5808 while (props > 9)
5809 {
5810 props -= 9;
5811 ++lp;
5812 }
5813 lc = props;
5814 if (unlikely (lc + lp > 4))
5815 {
5816 elf_uncompress_failed ();
5817 return 0;
5818 }
5819 }
5820
5821 if (control >= 0xa0)
5822 {
5823 size_t i;
5824
5825 /* Bit 5 or 6 is set, reset LZMA state. */
5826
5827 lstate = 0;
5828 memset (&dist, 0, sizeof dist);
5829 for (i = 0; i < LZMA_PROB_TOTAL_COUNT; i++)
5830 probs[i] = 1 << 10;
5831 range = 0xffffffff;
5832 code = 0;
5833 }
5834
5835 /* Read the range code. */
5836
5837 if (unlikely (off + 5 > compressed_size))
5838 {
5839 elf_uncompress_failed ();
5840 return 0;
5841 }
5842
5843 /* The byte at compressed[off] is ignored for some
5844 reason. */
5845
5846 code = (((uint32_t)compressed[off + 1] << 24)
5847 + ((uint32_t)compressed[off + 2] << 16)
5848 + ((uint32_t)compressed[off + 3] << 8)
5849 + (uint32_t)compressed[off + 4]);
5850 off += 5;
5851
5852 /* This is the main LZMA decode loop. */
5853
5854 limit = off + compressed_chunk_size;
5855 *poffset = off;
5856 while (*poffset < limit)
5857 {
5858 unsigned int pos_state;
5859
5860 if (unlikely (uncompressed_offset
5861 == (uncompressed_chunk_start
5862 + uncompressed_chunk_size)))
5863 {
5864 /* We've decompressed all the expected bytes. */
5865 break;
5866 }
5867
5868 pos_state = ((uncompressed_offset - dict_start_offset)
5869 & ((1 << pb) - 1));
5870
5871 if (elf_lzma_bit (compressed, compressed_size,
5872 probs + LZMA_IS_MATCH (lstate, pos_state),
5873 poffset, &range, &code))
5874 {
5875 uint32_t len;
5876
5877 if (elf_lzma_bit (compressed, compressed_size,
5878 probs + LZMA_IS_REP (lstate),
5879 poffset, &range, &code))
5880 {
5881 int short_rep;
5882 uint32_t next_dist;
5883
5884 /* Repeated match. */
5885
5886 short_rep = 0;
5887 if (elf_lzma_bit (compressed, compressed_size,
5888 probs + LZMA_IS_REP0 (lstate),
5889 poffset, &range, &code))
5890 {
5891 if (elf_lzma_bit (compressed, compressed_size,
5892 probs + LZMA_IS_REP1 (lstate),
5893 poffset, &range, &code))
5894 {
5895 if (elf_lzma_bit (compressed, compressed_size,
5896 probs + LZMA_IS_REP2 (lstate),
5897 poffset, &range, &code))
5898 {
5899 next_dist = dist[3];
5900 dist[3] = dist[2];
5901 }
5902 else
5903 {
5904 next_dist = dist[2];
5905 }
5906 dist[2] = dist[1];
5907 }
5908 else
5909 {
5910 next_dist = dist[1];
5911 }
5912
5913 dist[1] = dist[0];
5914 dist[0] = next_dist;
5915 }
5916 else
5917 {
5918 if (!elf_lzma_bit (compressed, compressed_size,
5919 (probs
5920 + LZMA_IS_REP0_LONG (lstate,
5921 pos_state)),
5922 poffset, &range, &code))
5923 short_rep = 1;
5924 }
5925
5926 if (lstate < 7)
5927 lstate = short_rep ? 9 : 8;
5928 else
5929 lstate = 11;
5930
5931 if (short_rep)
5932 len = 1;
5933 else
5934 len = elf_lzma_len (compressed, compressed_size,
5935 probs, 1, pos_state, poffset,
5936 &range, &code);
5937 }
5938 else
5939 {
5940 uint32_t dist_state;
5941 uint32_t dist_slot;
5942 uint16_t *probs_dist;
5943
5944 /* Match. */
5945
5946 if (lstate < 7)
5947 lstate = 7;
5948 else
5949 lstate = 10;
5950 dist[3] = dist[2];
5951 dist[2] = dist[1];
5952 dist[1] = dist[0];
5953 len = elf_lzma_len (compressed, compressed_size,
5954 probs, 0, pos_state, poffset,
5955 &range, &code);
5956
5957 if (len < 4 + 2)
5958 dist_state = len - 2;
5959 else
5960 dist_state = 3;
5961 probs_dist = probs + LZMA_DIST_SLOT (dist_state, 0);
5962 dist_slot = elf_lzma_integer (compressed,
5963 compressed_size,
5964 probs_dist, 6,
5965 poffset, &range,
5966 &code);
5967 if (dist_slot < LZMA_DIST_MODEL_START)
5968 dist[0] = dist_slot;
5969 else
5970 {
5971 uint32_t limit;
5972
5973 limit = (dist_slot >> 1) - 1;
5974 dist[0] = 2 + (dist_slot & 1);
5975 if (dist_slot < LZMA_DIST_MODEL_END)
5976 {
5977 dist[0] <<= limit;
5978 probs_dist = (probs
5979 + LZMA_DIST_SPECIAL(dist[0]
5980 - dist_slot
5981 - 1));
5982 dist[0] +=
5983 elf_lzma_reverse_integer (compressed,
5984 compressed_size,
5985 probs_dist,
5986 limit, poffset,
5987 &range, &code);
5988 }
5989 else
5990 {
5991 uint32_t dist0;
5992 uint32_t i;
5993
5994 dist0 = dist[0];
5995 for (i = 0; i < limit - 4; i++)
5996 {
5997 uint32_t mask;
5998
5999 elf_lzma_range_normalize (compressed,
6000 compressed_size,
6001 poffset,
6002 &range, &code);
6003 range >>= 1;
6004 code -= range;
6005 mask = -(code >> 31);
6006 code += range & mask;
6007 dist0 <<= 1;
6008 dist0 += mask + 1;
6009 }
6010 dist0 <<= 4;
6011 probs_dist = probs + LZMA_DIST_ALIGN (0);
6012 dist0 +=
6013 elf_lzma_reverse_integer (compressed,
6014 compressed_size,
6015 probs_dist, 4,
6016 poffset,
6017 &range, &code);
6018 dist[0] = dist0;
6019 }
6020 }
6021 }
6022
6023 if (unlikely (uncompressed_offset
6024 - dict_start_offset < dist[0] + 1))
6025 {
6026 elf_uncompress_failed ();
6027 return 0;
6028 }
6029 if (unlikely (uncompressed_offset + len > uncompressed_size))
6030 {
6031 elf_uncompress_failed ();
6032 return 0;
6033 }
6034
6035 if (dist[0] == 0)
6036 {
6037 /* A common case, meaning repeat the last
6038 character LEN times. */
6039 memset (uncompressed + uncompressed_offset,
6040 uncompressed[uncompressed_offset - 1],
6041 len);
6042 uncompressed_offset += len;
6043 }
6044 else if (dist[0] + 1 >= len)
6045 {
6046 memcpy (uncompressed + uncompressed_offset,
6047 uncompressed + uncompressed_offset - dist[0] - 1,
6048 len);
6049 uncompressed_offset += len;
6050 }
6051 else
6052 {
6053 while (len > 0)
6054 {
6055 uint32_t copy;
6056
6057 copy = len < dist[0] + 1 ? len : dist[0] + 1;
6058 memcpy (uncompressed + uncompressed_offset,
6059 (uncompressed + uncompressed_offset
6060 - dist[0] - 1),
6061 copy);
6062 len -= copy;
6063 uncompressed_offset += copy;
6064 }
6065 }
6066 }
6067 else
6068 {
6069 unsigned char prev;
6070 unsigned char low;
6071 size_t high;
6072 uint16_t *lit_probs;
6073 unsigned int sym;
6074
6075 /* Literal value. */
6076
6077 if (uncompressed_offset > 0)
6078 prev = uncompressed[uncompressed_offset - 1];
6079 else
6080 prev = 0;
6081 low = prev >> (8 - lc);
6082 high = (((uncompressed_offset - dict_start_offset)
6083 & ((1 << lp) - 1))
6084 << lc);
6085 lit_probs = probs + LZMA_LITERAL (low + high, 0);
6086 if (lstate < 7)
6087 sym = elf_lzma_integer (compressed, compressed_size,
6088 lit_probs, 8, poffset, &range,
6089 &code);
6090 else
6091 {
6092 unsigned int match;
6093 unsigned int bit;
6094 unsigned int match_bit;
6095 unsigned int idx;
6096
6097 sym = 1;
6098 if (uncompressed_offset >= dist[0] + 1)
6099 match = uncompressed[uncompressed_offset - dist[0] - 1];
6100 else
6101 match = 0;
6102 match <<= 1;
6103 bit = 0x100;
6104 do
6105 {
6106 match_bit = match & bit;
6107 match <<= 1;
6108 idx = bit + match_bit + sym;
6109 sym <<= 1;
6110 if (elf_lzma_bit (compressed, compressed_size,
6111 lit_probs + idx, poffset,
6112 &range, &code))
6113 {
6114 ++sym;
6115 bit &= match_bit;
6116 }
6117 else
6118 {
6119 bit &= ~ match_bit;
6120 }
6121 }
6122 while (sym < 0x100);
6123 }
6124
6125 if (unlikely (uncompressed_offset >= uncompressed_size))
6126 {
6127 elf_uncompress_failed ();
6128 return 0;
6129 }
6130
6131 uncompressed[uncompressed_offset] = (unsigned char) sym;
6132 ++uncompressed_offset;
6133 if (lstate <= 3)
6134 lstate = 0;
6135 else if (lstate <= 9)
6136 lstate -= 3;
6137 else
6138 lstate -= 6;
6139 }
6140 }
6141
6142 elf_lzma_range_normalize (compressed, compressed_size, poffset,
6143 &range, &code);
6144
6145 off = *poffset;
6146 }
6147 }
6148
6149 /* We have reached the end of the block. Pad to four byte
6150 boundary. */
6151 off = (off + 3) &~ (size_t) 3;
6152 if (unlikely (off > compressed_size))
6153 {
6154 elf_uncompress_failed ();
6155 return 0;
6156 }
6157
6158 switch (check)
6159 {
6160 case 0:
6161 /* No check. */
6162 break;
6163
6164 case 1:
6165 /* CRC32 */
6166 if (unlikely (off + 4 > compressed_size))
6167 {
6168 elf_uncompress_failed ();
6169 return 0;
6170 }
6171 computed_crc = elf_crc32 (0, uncompressed, uncompressed_offset);
6172 stream_crc = ((uint32_t)compressed[off]
6173 | ((uint32_t)compressed[off + 1] << 8)
6174 | ((uint32_t)compressed[off + 2] << 16)
6175 | ((uint32_t)compressed[off + 3] << 24));
6176 if (computed_crc != stream_crc)
6177 {
6178 elf_uncompress_failed ();
6179 return 0;
6180 }
6181 off += 4;
6182 break;
6183
6184 case 4:
6185 /* CRC64. We don't bother computing a CRC64 checksum. */
6186 if (unlikely (off + 8 > compressed_size))
6187 {
6188 elf_uncompress_failed ();
6189 return 0;
6190 }
6191 off += 8;
6192 break;
6193
6194 case 10:
6195 /* SHA. We don't bother computing a SHA checksum. */
6196 if (unlikely (off + 32 > compressed_size))
6197 {
6198 elf_uncompress_failed ();
6199 return 0;
6200 }
6201 off += 32;
6202 break;
6203
6204 default:
6205 elf_uncompress_failed ();
6206 return 0;
6207 }
6208
6209 *poffset = off;
6210
6211 return 1;
6212}
6213
6214/* Uncompress LZMA data found in a minidebug file. The minidebug
6215 format is described at
6216 https://sourceware.org/gdb/current/onlinedocs/gdb/MiniDebugInfo.html.
6217 Returns 0 on error, 1 on successful decompression. For this
6218 function we return 0 on failure to decompress, as the calling code
6219 will carry on in that case. */
6220
6221static int
6222elf_uncompress_lzma (struct backtrace_state *state,
6223 const unsigned char *compressed, size_t compressed_size,
6224 backtrace_error_callback error_callback, void *data,
6225 unsigned char **uncompressed, size_t *uncompressed_size)
6226{
6227 size_t header_size;
6228 size_t footer_size;
6229 unsigned char check;
6230 uint32_t computed_crc;
6231 uint32_t stream_crc;
6232 size_t offset;
6233 size_t index_size;
6234 size_t footer_offset;
6235 size_t index_offset;
6236 uint64_t index_compressed_size;
6237 uint64_t index_uncompressed_size;
6238 unsigned char *mem;
6239 uint16_t *probs;
6240 size_t compressed_block_size;
6241
6242 /* The format starts with a stream header and ends with a stream
6243 footer. */
6244 header_size = 12;
6245 footer_size = 12;
6246 if (unlikely (compressed_size < header_size + footer_size))
6247 {
6248 elf_uncompress_failed ();
6249 return 0;
6250 }
6251
6252 /* The stream header starts with a magic string. */
6253 if (unlikely (memcmp (compressed, "\375" "7zXZ\0", 6) != 0))
6254 {
6255 elf_uncompress_failed ();
6256 return 0;
6257 }
6258
6259 /* Next come stream flags. The first byte is zero, the second byte
6260 is the check. */
6261 if (unlikely (compressed[6] != 0))
6262 {
6263 elf_uncompress_failed ();
6264 return 0;
6265 }
6266 check = compressed[7];
6267 if (unlikely ((check & 0xf8) != 0))
6268 {
6269 elf_uncompress_failed ();
6270 return 0;
6271 }
6272
6273 /* Next comes a CRC of the stream flags. */
6274 computed_crc = elf_crc32 (0, compressed + 6, 2);
6275 stream_crc = ((uint32_t)compressed[8]
6276 | ((uint32_t)compressed[9] << 8)
6277 | ((uint32_t)compressed[10] << 16)
6278 | ((uint32_t)compressed[11] << 24));
6279 if (unlikely (computed_crc != stream_crc))
6280 {
6281 elf_uncompress_failed ();
6282 return 0;
6283 }
6284
6285 /* Now that we've parsed the header, parse the footer, so that we
6286 can get the uncompressed size. */
6287
6288 /* The footer ends with two magic bytes. */
6289
6290 offset = compressed_size;
6291 if (unlikely (memcmp (compressed + offset - 2, "YZ", 2) != 0))
6292 {
6293 elf_uncompress_failed ();
6294 return 0;
6295 }
6296 offset -= 2;
6297
6298 /* Before that are the stream flags, which should be the same as the
6299 flags in the header. */
6300 if (unlikely (compressed[offset - 2] != 0
6301 || compressed[offset - 1] != check))
6302 {
6303 elf_uncompress_failed ();
6304 return 0;
6305 }
6306 offset -= 2;
6307
6308 /* Before that is the size of the index field, which precedes the
6309 footer. */
6310 index_size = ((size_t)compressed[offset - 4]
6311 | ((size_t)compressed[offset - 3] << 8)
6312 | ((size_t)compressed[offset - 2] << 16)
6313 | ((size_t)compressed[offset - 1] << 24));
6314 index_size = (index_size + 1) * 4;
6315 offset -= 4;
6316
6317 /* Before that is a footer CRC. */
6318 computed_crc = elf_crc32 (0, compressed + offset, 6);
6319 stream_crc = ((uint32_t)compressed[offset - 4]
6320 | ((uint32_t)compressed[offset - 3] << 8)
6321 | ((uint32_t)compressed[offset - 2] << 16)
6322 | ((uint32_t)compressed[offset - 1] << 24));
6323 if (unlikely (computed_crc != stream_crc))
6324 {
6325 elf_uncompress_failed ();
6326 return 0;
6327 }
6328 offset -= 4;
6329
6330 /* The index comes just before the footer. */
6331 if (unlikely (offset < index_size + header_size))
6332 {
6333 elf_uncompress_failed ();
6334 return 0;
6335 }
6336
6337 footer_offset = offset;
6338 offset -= index_size;
6339 index_offset = offset;
6340
6341 /* The index starts with a zero byte. */
6342 if (unlikely (compressed[offset] != 0))
6343 {
6344 elf_uncompress_failed ();
6345 return 0;
6346 }
6347 ++offset;
6348
6349 /* Next is the number of blocks. We expect zero blocks for an empty
6350 stream, and otherwise a single block. */
6351 if (unlikely (compressed[offset] == 0))
6352 {
6353 *uncompressed = NULL;
6354 *uncompressed_size = 0;
6355 return 1;
6356 }
6357 if (unlikely (compressed[offset] != 1))
6358 {
6359 elf_uncompress_failed ();
6360 return 0;
6361 }
6362 ++offset;
6363
6364 /* Next is the compressed size and the uncompressed size. */
6365 if (!elf_lzma_varint (compressed, compressed_size, &offset,
6366 &index_compressed_size))
6367 return 0;
6368 if (!elf_lzma_varint (compressed, compressed_size, &offset,
6369 &index_uncompressed_size))
6370 return 0;
6371
6372 /* Pad to a four byte boundary. */
6373 offset = (offset + 3) &~ (size_t) 3;
6374
6375 /* Next is a CRC of the index. */
6376 computed_crc = elf_crc32 (0, compressed + index_offset,
6377 offset - index_offset);
6378 stream_crc = ((uint32_t)compressed[offset]
6379 | ((uint32_t)compressed[offset + 1] << 8)
6380 | ((uint32_t)compressed[offset + 2] << 16)
6381 | ((uint32_t)compressed[offset + 3] << 24));
6382 if (unlikely (computed_crc != stream_crc))
6383 {
6384 elf_uncompress_failed ();
6385 return 0;
6386 }
6387 offset += 4;
6388
6389 /* We should now be back at the footer. */
6390 if (unlikely (offset != footer_offset))
6391 {
6392 elf_uncompress_failed ();
6393 return 0;
6394 }
6395
6396 /* Allocate space to hold the uncompressed data. If we succeed in
6397 uncompressing the LZMA data, we never free this memory. */
6398 mem = (unsigned char *) backtrace_alloc (state, index_uncompressed_size,
6399 error_callback, data);
6400 if (unlikely (mem == NULL))
6401 return 0;
6402 *uncompressed = mem;
6403 *uncompressed_size = index_uncompressed_size;
6404
6405 /* Allocate space for probabilities. */
6406 probs = ((uint16_t *)
6407 backtrace_alloc (state,
6408 LZMA_PROB_TOTAL_COUNT * sizeof (uint16_t),
6409 error_callback, data));
6410 if (unlikely (probs == NULL))
6411 {
6412 backtrace_free (state, mem, index_uncompressed_size, error_callback,
6413 data);
6414 return 0;
6415 }
6416
6417 /* Uncompress the block, which follows the header. */
6418 offset = 12;
6419 if (!elf_uncompress_lzma_block (compressed, compressed_size, check, probs,
6420 mem, index_uncompressed_size, &offset))
6421 {
6422 backtrace_free (state, mem, index_uncompressed_size, error_callback,
6423 data);
6424 return 0;
6425 }
6426
6427 compressed_block_size = offset - 12;
6428 if (unlikely (compressed_block_size
6429 != ((index_compressed_size + 3) &~ (size_t) 3)))
6430 {
6431 elf_uncompress_failed ();
6432 backtrace_free (state, mem, index_uncompressed_size, error_callback,
6433 data);
6434 return 0;
6435 }
6436
6437 offset = (offset + 3) &~ (size_t) 3;
6438 if (unlikely (offset != index_offset))
6439 {
6440 elf_uncompress_failed ();
6441 backtrace_free (state, mem, index_uncompressed_size, error_callback,
6442 data);
6443 return 0;
6444 }
6445
6446 return 1;
6447}
6448
6449/* This function is a hook for testing the LZMA support. It is only
6450 used by tests. */
6451
6452int
6453backtrace_uncompress_lzma (struct backtrace_state *state,
6454 const unsigned char *compressed,
6455 size_t compressed_size,
6456 backtrace_error_callback error_callback,
6457 void *data, unsigned char **uncompressed,
6458 size_t *uncompressed_size)
6459{
6460 return elf_uncompress_lzma (state, compressed, compressed_size,
6461 error_callback, data, uncompressed,
6462 uncompressed_size);
6463}
6464
6465/* Add the backtrace data for one ELF file. Returns 1 on success,
6466 0 on failure (in both cases descriptor is closed) or -1 if exe
6467 is non-zero and the ELF file is ET_DYN, which tells the caller that
6468 elf_add will need to be called on the descriptor again after
6469 base_address is determined. */
6470
6471static int
6472elf_add (struct backtrace_state *state, const char *filename, int descriptor,
6473 const unsigned char *memory, size_t memory_size,
6474 struct libbacktrace_base_address base_address,
6475 struct elf_ppc64_opd_data *caller_opd,
6476 backtrace_error_callback error_callback, void *data,
6477 fileline *fileline_fn, int *found_sym, int *found_dwarf,
6478 struct dwarf_data **fileline_entry, int exe, int debuginfo,
6479 const char *with_buildid_data, uint32_t with_buildid_size)
6480{
6481 struct elf_view ehdr_view;
6482 b_elf_ehdr ehdr;
6483 off_t shoff;
6484 unsigned int shnum;
6485 unsigned int shstrndx;
6486 struct elf_view shdrs_view;
6487 int shdrs_view_valid;
6488 const b_elf_shdr *shdrs;
6489 const b_elf_shdr *shstrhdr;
6490 size_t shstr_size;
6491 off_t shstr_off;
6492 struct elf_view names_view;
6493 int names_view_valid;
6494 const char *names;
6495 unsigned int symtab_shndx;
6496 unsigned int dynsym_shndx;
6497 unsigned int i;
6498 struct debug_section_info sections[DEBUG_MAX];
6499 struct debug_section_info zsections[DEBUG_MAX];
6500 struct elf_view symtab_view;
6501 int symtab_view_valid;
6502 struct elf_view strtab_view;
6503 int strtab_view_valid;
6504 struct elf_view buildid_view;
6505 int buildid_view_valid;
6506 const char *buildid_data;
6507 uint32_t buildid_size;
6508 struct elf_view debuglink_view;
6509 int debuglink_view_valid;
6510 const char *debuglink_name;
6511 uint32_t debuglink_crc;
6512 struct elf_view debugaltlink_view;
6513 int debugaltlink_view_valid;
6514 const char *debugaltlink_name;
6515 const char *debugaltlink_buildid_data;
6516 uint32_t debugaltlink_buildid_size;
6517 struct elf_view gnu_debugdata_view;
6518 int gnu_debugdata_view_valid;
6519 size_t gnu_debugdata_size;
6520 unsigned char *gnu_debugdata_uncompressed;
6521 size_t gnu_debugdata_uncompressed_size;
6522 off_t min_offset;
6523 off_t max_offset;
6524 off_t debug_size;
6525 struct elf_view debug_view;
6526 int debug_view_valid;
6527 unsigned int using_debug_view;
6528 uint16_t *zdebug_table;
6529 struct elf_view split_debug_view[DEBUG_MAX];
6530 unsigned char split_debug_view_valid[DEBUG_MAX];
6531 struct elf_ppc64_opd_data opd_data, *opd;
6532 int opd_view_valid;
6533 struct dwarf_sections dwarf_sections;
6534
6535 if (!debuginfo)
6536 {
6537 *found_sym = 0;
6538 *found_dwarf = 0;
6539 }
6540
6541 shdrs_view_valid = 0;
6542 names_view_valid = 0;
6543 symtab_view_valid = 0;
6544 strtab_view_valid = 0;
6545 buildid_view_valid = 0;
6546 buildid_data = NULL;
6547 buildid_size = 0;
6548 debuglink_view_valid = 0;
6549 debuglink_name = NULL;
6550 debuglink_crc = 0;
6551 debugaltlink_view_valid = 0;
6552 debugaltlink_name = NULL;
6553 debugaltlink_buildid_data = NULL;
6554 debugaltlink_buildid_size = 0;
6555 gnu_debugdata_view_valid = 0;
6556 gnu_debugdata_size = 0;
6557 debug_view_valid = 0;
6558 memset (&split_debug_view_valid[0], 0, sizeof split_debug_view_valid);
6559 opd = NULL;
6560 opd_view_valid = 0;
6561
6562 if (!elf_get_view (state, descriptor, memory, memory_size, 0, sizeof ehdr,
6563 error_callback, data, &ehdr_view))
6564 goto fail;
6565
6566 memcpy (&ehdr, ehdr_view.view.data, sizeof ehdr);
6567
6568 elf_release_view (state, &ehdr_view, error_callback, data);
6569
6570 if (ehdr.e_ident[EI_MAG0] != ELFMAG0
6571 || ehdr.e_ident[EI_MAG1] != ELFMAG1
6572 || ehdr.e_ident[EI_MAG2] != ELFMAG2
6573 || ehdr.e_ident[EI_MAG3] != ELFMAG3)
6574 {
6575 error_callback (data, "executable file is not ELF", 0);
6576 goto fail;
6577 }
6578 if (ehdr.e_ident[EI_VERSION] != EV_CURRENT)
6579 {
6580 error_callback (data, "executable file is unrecognized ELF version", 0);
6581 goto fail;
6582 }
6583
6584#if BACKTRACE_ELF_SIZE == 32
6585#define BACKTRACE_ELFCLASS ELFCLASS32
6586#else
6587#define BACKTRACE_ELFCLASS ELFCLASS64
6588#endif
6589
6590 if (ehdr.e_ident[EI_CLASS] != BACKTRACE_ELFCLASS)
6591 {
6592 error_callback (data, "executable file is unexpected ELF class", 0);
6593 goto fail;
6594 }
6595
6596 if (ehdr.e_ident[EI_DATA] != ELFDATA2LSB
6597 && ehdr.e_ident[EI_DATA] != ELFDATA2MSB)
6598 {
6599 error_callback (data, "executable file has unknown endianness", 0);
6600 goto fail;
6601 }
6602
6603 /* If the executable is ET_DYN, it is either a PIE, or we are running
6604 directly a shared library with .interp. We need to wait for
6605 dl_iterate_phdr in that case to determine the actual base_address. */
6606 if (exe && ehdr.e_type == ET_DYN)
6607 return -1;
6608
6609 shoff = ehdr.e_shoff;
6610 shnum = ehdr.e_shnum;
6611 shstrndx = ehdr.e_shstrndx;
6612
6613 if ((shnum == 0 || shstrndx == SHN_XINDEX)
6614 && shoff != 0)
6615 {
6616 struct elf_view shdr_view;
6617 const b_elf_shdr *shdr;
6618
6619 if (!elf_get_view (state, descriptor, memory, memory_size, shoff,
6620 sizeof shdr, error_callback, data, &shdr_view))
6621 goto fail;
6622
6623 shdr = (const b_elf_shdr *) shdr_view.view.data;
6624
6625 if (shnum == 0)
6626 shnum = shdr->sh_size;
6627
6628 if (shstrndx == SHN_XINDEX)
6629 {
6630 shstrndx = shdr->sh_link;
6631
6632 /* Versions of the GNU binutils between 2.12 and 2.18 did
6633 not handle objects with more than SHN_LORESERVE sections
6634 correctly. All large section indexes were offset by
6635 0x100. There is more information at
6636 http://sourceware.org/bugzilla/show_bug.cgi?id-5900 .
6637 Fortunately these object files are easy to detect, as the
6638 GNU binutils always put the section header string table
6639 near the end of the list of sections. Thus if the
6640 section header string table index is larger than the
6641 number of sections, then we know we have to subtract
6642 0x100 to get the real section index. */
6643 if (shstrndx >= shnum && shstrndx >= SHN_LORESERVE + 0x100)
6644 shstrndx -= 0x100;
6645 }
6646
6647 elf_release_view (state, &shdr_view, error_callback, data);
6648 }
6649
6650 if (shnum == 0 || shstrndx == 0)
6651 goto fail;
6652
6653 /* To translate PC to file/line when using DWARF, we need to find
6654 the .debug_info and .debug_line sections. */
6655
6656 /* Read the section headers, skipping the first one. */
6657
6658 if (!elf_get_view (state, descriptor, memory, memory_size,
6659 shoff + sizeof (b_elf_shdr),
6660 (shnum - 1) * sizeof (b_elf_shdr),
6661 error_callback, data, &shdrs_view))
6662 goto fail;
6663 shdrs_view_valid = 1;
6664 shdrs = (const b_elf_shdr *) shdrs_view.view.data;
6665
6666 /* Read the section names. */
6667
6668 shstrhdr = &shdrs[shstrndx - 1];
6669 shstr_size = shstrhdr->sh_size;
6670 shstr_off = shstrhdr->sh_offset;
6671
6672 if (!elf_get_view (state, descriptor, memory, memory_size, shstr_off,
6673 shstrhdr->sh_size, error_callback, data, &names_view))
6674 goto fail;
6675 names_view_valid = 1;
6676 names = (const char *) names_view.view.data;
6677
6678 symtab_shndx = 0;
6679 dynsym_shndx = 0;
6680
6681 memset (sections, 0, sizeof sections);
6682 memset (zsections, 0, sizeof zsections);
6683
6684 /* Look for the symbol table. */
6685 for (i = 1; i < shnum; ++i)
6686 {
6687 const b_elf_shdr *shdr;
6688 unsigned int sh_name;
6689 const char *name;
6690 int j;
6691
6692 shdr = &shdrs[i - 1];
6693
6694 if (shdr->sh_type == SHT_SYMTAB)
6695 symtab_shndx = i;
6696 else if (shdr->sh_type == SHT_DYNSYM)
6697 dynsym_shndx = i;
6698
6699 sh_name = shdr->sh_name;
6700 if (sh_name >= shstr_size)
6701 {
6702 error_callback (data, "ELF section name out of range", 0);
6703 goto fail;
6704 }
6705
6706 name = names + sh_name;
6707
6708 for (j = 0; j < (int) DEBUG_MAX; ++j)
6709 {
6710 if (strcmp (name, dwarf_section_names[j]) == 0)
6711 {
6712 sections[j].offset = shdr->sh_offset;
6713 sections[j].size = shdr->sh_size;
6714 sections[j].compressed = (shdr->sh_flags & SHF_COMPRESSED) != 0;
6715 break;
6716 }
6717 }
6718
6719 if (name[0] == '.' && name[1] == 'z')
6720 {
6721 for (j = 0; j < (int) DEBUG_MAX; ++j)
6722 {
6723 if (strcmp (name + 2, dwarf_section_names[j] + 1) == 0)
6724 {
6725 zsections[j].offset = shdr->sh_offset;
6726 zsections[j].size = shdr->sh_size;
6727 break;
6728 }
6729 }
6730 }
6731
6732 /* Read the build ID if present. This could check for any
6733 SHT_NOTE section with the right note name and type, but gdb
6734 looks for a specific section name. */
6735 if ((!debuginfo || with_buildid_data != NULL)
6736 && !buildid_view_valid
6737 && strcmp (name, ".note.gnu.build-id") == 0)
6738 {
6739 const b_elf_note *note;
6740
6741 if (!elf_get_view (state, descriptor, memory, memory_size,
6742 shdr->sh_offset, shdr->sh_size, error_callback,
6743 data, &buildid_view))
6744 goto fail;
6745
6746 buildid_view_valid = 1;
6747 note = (const b_elf_note *) buildid_view.view.data;
6748 if (note->type == NT_GNU_BUILD_ID
6749 && note->namesz == 4
6750 && strncmp (note->name, "GNU", 4) == 0
6751 && shdr->sh_size <= 12 + ((note->namesz + 3) & ~ 3) + note->descsz)
6752 {
6753 buildid_data = ¬e->name[0] + ((note->namesz + 3) & ~ 3);
6754 buildid_size = note->descsz;
6755 }
6756
6757 if (with_buildid_size != 0)
6758 {
6759 if (buildid_size != with_buildid_size)
6760 goto fail;
6761
6762 if (memcmp (buildid_data, with_buildid_data, buildid_size) != 0)
6763 goto fail;
6764 }
6765 }
6766
6767 /* Read the debuglink file if present. */
6768 if (!debuginfo
6769 && !debuglink_view_valid
6770 && strcmp (name, ".gnu_debuglink") == 0)
6771 {
6772 const char *debuglink_data;
6773 size_t crc_offset;
6774
6775 if (!elf_get_view (state, descriptor, memory, memory_size,
6776 shdr->sh_offset, shdr->sh_size, error_callback,
6777 data, &debuglink_view))
6778 goto fail;
6779
6780 debuglink_view_valid = 1;
6781 debuglink_data = (const char *) debuglink_view.view.data;
6782 crc_offset = strnlen (debuglink_data, shdr->sh_size);
6783 crc_offset = (crc_offset + 3) & ~3;
6784 if (crc_offset + 4 <= shdr->sh_size)
6785 {
6786 debuglink_name = debuglink_data;
6787 debuglink_crc = *(const uint32_t*)(debuglink_data + crc_offset);
6788 }
6789 }
6790
6791 if (!debugaltlink_view_valid
6792 && strcmp (name, ".gnu_debugaltlink") == 0)
6793 {
6794 const char *debugaltlink_data;
6795 size_t debugaltlink_name_len;
6796
6797 if (!elf_get_view (state, descriptor, memory, memory_size,
6798 shdr->sh_offset, shdr->sh_size, error_callback,
6799 data, &debugaltlink_view))
6800 goto fail;
6801
6802 debugaltlink_view_valid = 1;
6803 debugaltlink_data = (const char *) debugaltlink_view.view.data;
6804 debugaltlink_name = debugaltlink_data;
6805 debugaltlink_name_len = strnlen (debugaltlink_data, shdr->sh_size);
6806 if (debugaltlink_name_len < shdr->sh_size)
6807 {
6808 /* Include terminating zero. */
6809 debugaltlink_name_len += 1;
6810
6811 debugaltlink_buildid_data
6812 = debugaltlink_data + debugaltlink_name_len;
6813 debugaltlink_buildid_size = shdr->sh_size - debugaltlink_name_len;
6814 }
6815 }
6816
6817 if (!debuginfo
6818 && !gnu_debugdata_view_valid
6819 && strcmp (name, ".gnu_debugdata") == 0)
6820 {
6821 if (!elf_get_view (state, descriptor, memory, memory_size,
6822 shdr->sh_offset, shdr->sh_size, error_callback,
6823 data, &gnu_debugdata_view))
6824 goto fail;
6825
6826 gnu_debugdata_size = shdr->sh_size;
6827 gnu_debugdata_view_valid = 1;
6828 }
6829
6830 /* Read the .opd section on PowerPC64 ELFv1. */
6831 if (ehdr.e_machine == EM_PPC64
6832 && (ehdr.e_flags & EF_PPC64_ABI) < 2
6833 && shdr->sh_type == SHT_PROGBITS
6834 && strcmp (name, ".opd") == 0)
6835 {
6836 if (!elf_get_view (state, descriptor, memory, memory_size,
6837 shdr->sh_offset, shdr->sh_size, error_callback,
6838 data, &opd_data.view))
6839 goto fail;
6840
6841 opd = &opd_data;
6842 opd->addr = shdr->sh_addr;
6843 opd->data = (const char *) opd_data.view.view.data;
6844 opd->size = shdr->sh_size;
6845 opd_view_valid = 1;
6846 }
6847 }
6848
6849 /* A debuginfo file may not have a useful .opd section, but we can use the
6850 one from the original executable. */
6851 if (opd == NULL)
6852 opd = caller_opd;
6853
6854 if (symtab_shndx == 0)
6855 symtab_shndx = dynsym_shndx;
6856 if (symtab_shndx != 0)
6857 {
6858 const b_elf_shdr *symtab_shdr;
6859 unsigned int strtab_shndx;
6860 const b_elf_shdr *strtab_shdr;
6861 struct elf_syminfo_data *sdata;
6862
6863 symtab_shdr = &shdrs[symtab_shndx - 1];
6864 strtab_shndx = symtab_shdr->sh_link;
6865 if (strtab_shndx >= shnum)
6866 {
6867 error_callback (data,
6868 "ELF symbol table strtab link out of range", 0);
6869 goto fail;
6870 }
6871 strtab_shdr = &shdrs[strtab_shndx - 1];
6872
6873 if (!elf_get_view (state, descriptor, memory, memory_size,
6874 symtab_shdr->sh_offset, symtab_shdr->sh_size,
6875 error_callback, data, &symtab_view))
6876 goto fail;
6877 symtab_view_valid = 1;
6878
6879 if (!elf_get_view (state, descriptor, memory, memory_size,
6880 strtab_shdr->sh_offset, strtab_shdr->sh_size,
6881 error_callback, data, &strtab_view))
6882 goto fail;
6883 strtab_view_valid = 1;
6884
6885 sdata = ((struct elf_syminfo_data *)
6886 backtrace_alloc (state, sizeof *sdata, error_callback, data));
6887 if (sdata == NULL)
6888 goto fail;
6889
6890 if (!elf_initialize_syminfo (state, base_address,
6891 symtab_view.view.data, symtab_shdr->sh_size,
6892 strtab_view.view.data, strtab_shdr->sh_size,
6893 error_callback, data, sdata, opd))
6894 {
6895 backtrace_free (state, sdata, sizeof *sdata, error_callback, data);
6896 goto fail;
6897 }
6898
6899 /* We no longer need the symbol table, but we hold on to the
6900 string table permanently. */
6901 elf_release_view (state, &symtab_view, error_callback, data);
6902 symtab_view_valid = 0;
6903 strtab_view_valid = 0;
6904
6905 *found_sym = 1;
6906
6907 elf_add_syminfo_data (state, sdata);
6908 }
6909
6910 elf_release_view (state, &shdrs_view, error_callback, data);
6911 shdrs_view_valid = 0;
6912 elf_release_view (state, &names_view, error_callback, data);
6913 names_view_valid = 0;
6914
6915 /* If the debug info is in a separate file, read that one instead. */
6916
6917 if (buildid_data != NULL)
6918 {
6919 int d;
6920
6921 d = elf_open_debugfile_by_buildid (state, buildid_data, buildid_size,
6922 error_callback, data);
6923 if (d >= 0)
6924 {
6925 int ret;
6926
6927 elf_release_view (state, &buildid_view, error_callback, data);
6928 if (debuglink_view_valid)
6929 elf_release_view (state, &debuglink_view, error_callback, data);
6930 if (debugaltlink_view_valid)
6931 elf_release_view (state, &debugaltlink_view, error_callback, data);
6932 ret = elf_add (state, "", d, NULL, 0, base_address, opd,
6933 error_callback, data, fileline_fn, found_sym,
6934 found_dwarf, NULL, 0, 1, NULL, 0);
6935 if (ret < 0)
6936 backtrace_close (d, error_callback, data);
6937 else if (descriptor >= 0)
6938 backtrace_close (descriptor, error_callback, data);
6939 return ret;
6940 }
6941 }
6942
6943 if (buildid_view_valid)
6944 {
6945 elf_release_view (state, &buildid_view, error_callback, data);
6946 buildid_view_valid = 0;
6947 }
6948
6949 if (debuglink_name != NULL)
6950 {
6951 int d;
6952
6953 d = elf_open_debugfile_by_debuglink (state, filename, debuglink_name,
6954 debuglink_crc, error_callback,
6955 data);
6956 if (d >= 0)
6957 {
6958 int ret;
6959
6960 elf_release_view (state, &debuglink_view, error_callback, data);
6961 if (debugaltlink_view_valid)
6962 elf_release_view (state, &debugaltlink_view, error_callback, data);
6963 ret = elf_add (state, "", d, NULL, 0, base_address, opd,
6964 error_callback, data, fileline_fn, found_sym,
6965 found_dwarf, NULL, 0, 1, NULL, 0);
6966 if (ret < 0)
6967 backtrace_close (d, error_callback, data);
6968 else if (descriptor >= 0)
6969 backtrace_close(descriptor, error_callback, data);
6970 return ret;
6971 }
6972 }
6973
6974 if (debuglink_view_valid)
6975 {
6976 elf_release_view (state, &debuglink_view, error_callback, data);
6977 debuglink_view_valid = 0;
6978 }
6979
6980 struct dwarf_data *fileline_altlink = NULL;
6981 if (debugaltlink_name != NULL)
6982 {
6983 int d;
6984
6985 d = elf_open_debugfile_by_debuglink (state, filename, debugaltlink_name,
6986 0, error_callback, data);
6987 if (d >= 0)
6988 {
6989 int ret;
6990
6991 ret = elf_add (state, filename, d, NULL, 0, base_address, opd,
6992 error_callback, data, fileline_fn, found_sym,
6993 found_dwarf, &fileline_altlink, 0, 1,
6994 debugaltlink_buildid_data, debugaltlink_buildid_size);
6995 elf_release_view (state, &debugaltlink_view, error_callback, data);
6996 debugaltlink_view_valid = 0;
6997 if (ret < 0)
6998 {
6999 backtrace_close (d, error_callback, data);
7000 return ret;
7001 }
7002 }
7003 }
7004
7005 if (debugaltlink_view_valid)
7006 {
7007 elf_release_view (state, &debugaltlink_view, error_callback, data);
7008 debugaltlink_view_valid = 0;
7009 }
7010
7011 if (gnu_debugdata_view_valid)
7012 {
7013 int ret;
7014
7015 ret = elf_uncompress_lzma (state,
7016 ((const unsigned char *)
7017 gnu_debugdata_view.view.data),
7018 gnu_debugdata_size, error_callback, data,
7019 &gnu_debugdata_uncompressed,
7020 &gnu_debugdata_uncompressed_size);
7021
7022 elf_release_view (state, &gnu_debugdata_view, error_callback, data);
7023 gnu_debugdata_view_valid = 0;
7024
7025 if (ret)
7026 {
7027 ret = elf_add (state, filename, -1, gnu_debugdata_uncompressed,
7028 gnu_debugdata_uncompressed_size, base_address, opd,
7029 error_callback, data, fileline_fn, found_sym,
7030 found_dwarf, NULL, 0, 0, NULL, 0);
7031 if (ret >= 0 && descriptor >= 0)
7032 backtrace_close(descriptor, error_callback, data);
7033 return ret;
7034 }
7035 }
7036
7037 if (opd_view_valid)
7038 {
7039 elf_release_view (state, &opd->view, error_callback, data);
7040 opd_view_valid = 0;
7041 opd = NULL;
7042 }
7043
7044 /* Read all the debug sections in a single view, since they are
7045 probably adjacent in the file. If any of sections are
7046 uncompressed, we never release this view. */
7047
7048 min_offset = 0;
7049 max_offset = 0;
7050 debug_size = 0;
7051 for (i = 0; i < (int) DEBUG_MAX; ++i)
7052 {
7053 off_t end;
7054
7055 if (sections[i].size != 0)
7056 {
7057 if (min_offset == 0 || sections[i].offset < min_offset)
7058 min_offset = sections[i].offset;
7059 end = sections[i].offset + sections[i].size;
7060 if (end > max_offset)
7061 max_offset = end;
7062 debug_size += sections[i].size;
7063 }
7064 if (zsections[i].size != 0)
7065 {
7066 if (min_offset == 0 || zsections[i].offset < min_offset)
7067 min_offset = zsections[i].offset;
7068 end = zsections[i].offset + zsections[i].size;
7069 if (end > max_offset)
7070 max_offset = end;
7071 debug_size += zsections[i].size;
7072 }
7073 }
7074 if (min_offset == 0 || max_offset == 0)
7075 {
7076 if (descriptor >= 0)
7077 {
7078 if (!backtrace_close (descriptor, error_callback, data))
7079 goto fail;
7080 }
7081 return 1;
7082 }
7083
7084 /* If the total debug section size is large, assume that there are
7085 gaps between the sections, and read them individually. */
7086
7087 if (max_offset - min_offset < 0x20000000
7088 || max_offset - min_offset < debug_size + 0x10000)
7089 {
7090 if (!elf_get_view (state, descriptor, memory, memory_size, min_offset,
7091 max_offset - min_offset, error_callback, data,
7092 &debug_view))
7093 goto fail;
7094 debug_view_valid = 1;
7095 }
7096 else
7097 {
7098 memset (&split_debug_view[0], 0, sizeof split_debug_view);
7099 for (i = 0; i < (int) DEBUG_MAX; ++i)
7100 {
7101 struct debug_section_info *dsec;
7102
7103 if (sections[i].size != 0)
7104 dsec = §ions[i];
7105 else if (zsections[i].size != 0)
7106 dsec = &zsections[i];
7107 else
7108 continue;
7109
7110 if (!elf_get_view (state, descriptor, memory, memory_size,
7111 dsec->offset, dsec->size, error_callback, data,
7112 &split_debug_view[i]))
7113 goto fail;
7114 split_debug_view_valid[i] = 1;
7115
7116 if (sections[i].size != 0)
7117 sections[i].data = ((const unsigned char *)
7118 split_debug_view[i].view.data);
7119 else
7120 zsections[i].data = ((const unsigned char *)
7121 split_debug_view[i].view.data);
7122 }
7123 }
7124
7125 /* We've read all we need from the executable. */
7126 if (descriptor >= 0)
7127 {
7128 if (!backtrace_close (descriptor, error_callback, data))
7129 goto fail;
7130 descriptor = -1;
7131 }
7132
7133 using_debug_view = 0;
7134 if (debug_view_valid)
7135 {
7136 for (i = 0; i < (int) DEBUG_MAX; ++i)
7137 {
7138 if (sections[i].size == 0)
7139 sections[i].data = NULL;
7140 else
7141 {
7142 sections[i].data = ((const unsigned char *) debug_view.view.data
7143 + (sections[i].offset - min_offset));
7144 ++using_debug_view;
7145 }
7146
7147 if (zsections[i].size == 0)
7148 zsections[i].data = NULL;
7149 else
7150 zsections[i].data = ((const unsigned char *) debug_view.view.data
7151 + (zsections[i].offset - min_offset));
7152 }
7153 }
7154
7155 /* Uncompress the old format (--compress-debug-sections=zlib-gnu). */
7156
7157 zdebug_table = NULL;
7158 for (i = 0; i < (int) DEBUG_MAX; ++i)
7159 {
7160 if (sections[i].size == 0 && zsections[i].size > 0)
7161 {
7162 unsigned char *uncompressed_data;
7163 size_t uncompressed_size;
7164
7165 if (zdebug_table == NULL)
7166 {
7167 zdebug_table = ((uint16_t *)
7168 backtrace_alloc (state, ZLIB_TABLE_SIZE,
7169 error_callback, data));
7170 if (zdebug_table == NULL)
7171 goto fail;
7172 }
7173
7174 uncompressed_data = NULL;
7175 uncompressed_size = 0;
7176 if (!elf_uncompress_zdebug (state, zsections[i].data,
7177 zsections[i].size, zdebug_table,
7178 error_callback, data,
7179 &uncompressed_data, &uncompressed_size))
7180 goto fail;
7181 sections[i].data = uncompressed_data;
7182 sections[i].size = uncompressed_size;
7183 sections[i].compressed = 0;
7184
7185 if (split_debug_view_valid[i])
7186 {
7187 elf_release_view (state, &split_debug_view[i],
7188 error_callback, data);
7189 split_debug_view_valid[i] = 0;
7190 }
7191 }
7192 }
7193
7194 if (zdebug_table != NULL)
7195 {
7196 backtrace_free (state, zdebug_table, ZLIB_TABLE_SIZE,
7197 error_callback, data);
7198 zdebug_table = NULL;
7199 }
7200
7201 /* Uncompress the official ELF format
7202 (--compress-debug-sections=zlib-gabi, --compress-debug-sections=zstd). */
7203 for (i = 0; i < (int) DEBUG_MAX; ++i)
7204 {
7205 unsigned char *uncompressed_data;
7206 size_t uncompressed_size;
7207
7208 if (sections[i].size == 0 || !sections[i].compressed)
7209 continue;
7210
7211 if (zdebug_table == NULL)
7212 {
7213 zdebug_table = ((uint16_t *)
7214 backtrace_alloc (state, ZDEBUG_TABLE_SIZE,
7215 error_callback, data));
7216 if (zdebug_table == NULL)
7217 goto fail;
7218 }
7219
7220 uncompressed_data = NULL;
7221 uncompressed_size = 0;
7222 if (!elf_uncompress_chdr (state, sections[i].data, sections[i].size,
7223 zdebug_table, error_callback, data,
7224 &uncompressed_data, &uncompressed_size))
7225 goto fail;
7226 sections[i].data = uncompressed_data;
7227 sections[i].size = uncompressed_size;
7228 sections[i].compressed = 0;
7229
7230 if (debug_view_valid)
7231 --using_debug_view;
7232 else if (split_debug_view_valid[i])
7233 {
7234 elf_release_view (state, &split_debug_view[i], error_callback, data);
7235 split_debug_view_valid[i] = 0;
7236 }
7237 }
7238
7239 if (zdebug_table != NULL)
7240 backtrace_free (state, zdebug_table, ZDEBUG_TABLE_SIZE,
7241 error_callback, data);
7242
7243 if (debug_view_valid && using_debug_view == 0)
7244 {
7245 elf_release_view (state, &debug_view, error_callback, data);
7246 debug_view_valid = 0;
7247 }
7248
7249 for (i = 0; i < (int) DEBUG_MAX; ++i)
7250 {
7251 dwarf_sections.data[i] = sections[i].data;
7252 dwarf_sections.size[i] = sections[i].size;
7253 }
7254
7255 if (!backtrace_dwarf_add (state, base_address, &dwarf_sections,
7256 ehdr.e_ident[EI_DATA] == ELFDATA2MSB,
7257 fileline_altlink,
7258 error_callback, data, fileline_fn,
7259 fileline_entry))
7260 goto fail;
7261
7262 *found_dwarf = 1;
7263
7264 return 1;
7265
7266 fail:
7267 if (shdrs_view_valid)
7268 elf_release_view (state, &shdrs_view, error_callback, data);
7269 if (names_view_valid)
7270 elf_release_view (state, &names_view, error_callback, data);
7271 if (symtab_view_valid)
7272 elf_release_view (state, &symtab_view, error_callback, data);
7273 if (strtab_view_valid)
7274 elf_release_view (state, &strtab_view, error_callback, data);
7275 if (debuglink_view_valid)
7276 elf_release_view (state, &debuglink_view, error_callback, data);
7277 if (debugaltlink_view_valid)
7278 elf_release_view (state, &debugaltlink_view, error_callback, data);
7279 if (gnu_debugdata_view_valid)
7280 elf_release_view (state, &gnu_debugdata_view, error_callback, data);
7281 if (buildid_view_valid)
7282 elf_release_view (state, &buildid_view, error_callback, data);
7283 if (debug_view_valid)
7284 elf_release_view (state, &debug_view, error_callback, data);
7285 for (i = 0; i < (int) DEBUG_MAX; ++i)
7286 {
7287 if (split_debug_view_valid[i])
7288 elf_release_view (state, &split_debug_view[i], error_callback, data);
7289 }
7290 if (opd_view_valid)
7291 elf_release_view (state, &opd->view, error_callback, data);
7292 if (descriptor >= 0)
7293 backtrace_close (descriptor, error_callback, data);
7294 return 0;
7295}
7296
7297/* Data passed to phdr_callback. */
7298
7299struct phdr_data
7300{
7301 struct backtrace_state *state;
7302 backtrace_error_callback error_callback;
7303 void *data;
7304 fileline *fileline_fn;
7305 int *found_sym;
7306 int *found_dwarf;
7307 const char *exe_filename;
7308 int exe_descriptor;
7309};
7310
7311/* Callback passed to dl_iterate_phdr. Load debug info from shared
7312 libraries. */
7313
7314static int
7315#ifdef __i386__
7316__attribute__ ((__force_align_arg_pointer__))
7317#endif
7318phdr_callback (struct dl_phdr_info *info, size_t size ATTRIBUTE_UNUSED,
7319 void *pdata)
7320{
7321 struct phdr_data *pd = (struct phdr_data *) pdata;
7322 const char *filename;
7323 int descriptor;
7324 int does_not_exist;
7325 struct libbacktrace_base_address base_address;
7326 fileline elf_fileline_fn;
7327 int found_dwarf;
7328
7329 /* There is not much we can do if we don't have the module name,
7330 unless executable is ET_DYN, where we expect the very first
7331 phdr_callback to be for the PIE. */
7332 if (info->dlpi_name == NULL || info->dlpi_name[0] == '\0')
7333 {
7334 if (pd->exe_descriptor == -1)
7335 return 0;
7336 filename = pd->exe_filename;
7337 descriptor = pd->exe_descriptor;
7338 pd->exe_descriptor = -1;
7339 }
7340 else
7341 {
7342 if (pd->exe_descriptor != -1)
7343 {
7344 backtrace_close (pd->exe_descriptor, pd->error_callback, pd->data);
7345 pd->exe_descriptor = -1;
7346 }
7347
7348 filename = info->dlpi_name;
7349 descriptor = backtrace_open (info->dlpi_name, pd->error_callback,
7350 pd->data, &does_not_exist);
7351 if (descriptor < 0)
7352 return 0;
7353 }
7354
7355 base_address.m = info->dlpi_addr;
7356 if (elf_add (pd->state, filename, descriptor, NULL, 0, base_address, NULL,
7357 pd->error_callback, pd->data, &elf_fileline_fn, pd->found_sym,
7358 &found_dwarf, NULL, 0, 0, NULL, 0))
7359 {
7360 if (found_dwarf)
7361 {
7362 *pd->found_dwarf = 1;
7363 *pd->fileline_fn = elf_fileline_fn;
7364 }
7365 }
7366
7367 return 0;
7368}
7369
7370/* Initialize the backtrace data we need from an ELF executable. At
7371 the ELF level, all we need to do is find the debug info
7372 sections. */
7373
7374int
7375backtrace_initialize (struct backtrace_state *state, const char *filename,
7376 int descriptor, backtrace_error_callback error_callback,
7377 void *data, fileline *fileline_fn)
7378{
7379 int ret;
7380 int found_sym;
7381 int found_dwarf;
7382 fileline elf_fileline_fn = elf_nodebug;
7383 struct phdr_data pd;
7384
7385 /* When using fdpic we must use dl_iterate_phdr for all modules, including
7386 the main executable, so that we can get the right base address
7387 mapping. */
7388 if (!libbacktrace_using_fdpic ())
7389 {
7390 struct libbacktrace_base_address zero_base_address;
7391
7392 memset (&zero_base_address, 0, sizeof zero_base_address);
7393 ret = elf_add (state, filename, descriptor, NULL, 0, zero_base_address,
7394 NULL, error_callback, data, &elf_fileline_fn, &found_sym,
7395 &found_dwarf, NULL, 1, 0, NULL, 0);
7396 if (!ret)
7397 return 0;
7398 }
7399
7400 pd.state = state;
7401 pd.error_callback = error_callback;
7402 pd.data = data;
7403 pd.fileline_fn = &elf_fileline_fn;
7404 pd.found_sym = &found_sym;
7405 pd.found_dwarf = &found_dwarf;
7406 pd.exe_filename = filename;
7407 pd.exe_descriptor = ret < 0 ? descriptor : -1;
7408
7409 dl_iterate_phdr (phdr_callback, (void *) &pd);
7410
7411 if (!state->threaded)
7412 {
7413 if (found_sym)
7414 state->syminfo_fn = elf_syminfo;
7415 else if (state->syminfo_fn == NULL)
7416 state->syminfo_fn = elf_nosyms;
7417 }
7418 else
7419 {
7420 if (found_sym)
7421 backtrace_atomic_store_pointer (&state->syminfo_fn, elf_syminfo);
7422 else
7423 (void) __sync_bool_compare_and_swap (&state->syminfo_fn, NULL,
7424 elf_nosyms);
7425 }
7426
7427 if (!state->threaded)
7428 *fileline_fn = state->fileline_fn;
7429 else
7430 *fileline_fn = backtrace_atomic_load_pointer (&state->fileline_fn);
7431
7432 if (*fileline_fn == NULL || *fileline_fn == elf_nodebug)
7433 *fileline_fn = elf_fileline_fn;
7434
7435 return 1;
7436}
7437// mmapio.c:
7438#include <errno.h>
7439#include <sys/types.h>
7440#include <sys/mman.h>
7441#include <unistd.h>
7442
7443
7444#ifndef HAVE_DECL_GETPAGESIZE
7445extern int getpagesize (void);
7446#endif
7447
7448#ifndef MAP_FAILED
7449#define MAP_FAILED ((void *)-1)
7450#endif
7451
7452/* This file implements file views and memory allocation when mmap is
7453 available. */
7454
7455/* Create a view of SIZE bytes from DESCRIPTOR at OFFSET. */
7456
7457int
7458backtrace_get_view (struct backtrace_state *state ATTRIBUTE_UNUSED,
7459 int descriptor, off_t offset, uint64_t size,
7460 backtrace_error_callback error_callback,
7461 void *data, struct backtrace_view *view)
7462{
7463 size_t pagesize;
7464 unsigned int inpage;
7465 off_t pageoff;
7466 void *map;
7467
7468 if ((uint64_t) (size_t) size != size)
7469 {
7470 error_callback (data, "file size too large", 0);
7471 return 0;
7472 }
7473
7474 pagesize = getpagesize ();
7475 inpage = offset % pagesize;
7476 pageoff = offset - inpage;
7477
7478 size += inpage;
7479 size = (size + (pagesize - 1)) & ~ (pagesize - 1);
7480
7481 map = mmap (NULL, size, PROT_READ, MAP_PRIVATE, descriptor, pageoff);
7482 if (map == MAP_FAILED)
7483 {
7484 error_callback (data, "mmap", errno);
7485 return 0;
7486 }
7487
7488 view->data = (char *) map + inpage;
7489 view->base = map;
7490 view->len = size;
7491
7492 return 1;
7493}
7494
7495/* Release a view read by backtrace_get_view. */
7496
7497void
7498backtrace_release_view (struct backtrace_state *state ATTRIBUTE_UNUSED,
7499 struct backtrace_view *view,
7500 backtrace_error_callback error_callback,
7501 void *data)
7502{
7503 union {
7504 const void *cv;
7505 void *v;
7506 } const_cast;
7507
7508 const_cast.cv = view->base;
7509 if (munmap (const_cast.v, view->len) < 0)
7510 error_callback (data, "munmap", errno);
7511}
7512// mmap.c:
7513#include <errno.h>
7514#include <string.h>
7515#include <stdlib.h>
7516#include <unistd.h>
7517#include <sys/types.h>
7518#include <sys/mman.h>
7519
7520
7521#ifndef HAVE_DECL_GETPAGESIZE
7522extern int getpagesize (void);
7523#endif
7524
7525/* Memory allocation on systems that provide anonymous mmap. This
7526 permits the backtrace functions to be invoked from a signal
7527 handler, assuming that mmap is async-signal safe. */
7528
7529#ifndef MAP_ANONYMOUS
7530#define MAP_ANONYMOUS MAP_ANON
7531#endif
7532
7533#ifndef MAP_FAILED
7534#define MAP_FAILED ((void *)-1)
7535#endif
7536
7537/* A list of free memory blocks. */
7538
7539struct backtrace_freelist_struct
7540{
7541 /* Next on list. */
7542 struct backtrace_freelist_struct *next;
7543 /* Size of this block, including this structure. */
7544 size_t size;
7545};
7546
7547/* Free memory allocated by backtrace_alloc. */
7548
7549static void
7550backtrace_free_locked (struct backtrace_state *state, void *addr, size_t size)
7551{
7552 /* Just leak small blocks. We don't have to be perfect. Don't put
7553 more than 16 entries on the free list, to avoid wasting time
7554 searching when allocating a block. If we have more than 16
7555 entries, leak the smallest entry. */
7556
7557 if (size >= sizeof (struct backtrace_freelist_struct))
7558 {
7559 size_t c;
7560 struct backtrace_freelist_struct **ppsmall;
7561 struct backtrace_freelist_struct **pp;
7562 struct backtrace_freelist_struct *p;
7563
7564 c = 0;
7565 ppsmall = NULL;
7566 for (pp = &state->freelist; *pp != NULL; pp = &(*pp)->next)
7567 {
7568 if (ppsmall == NULL || (*pp)->size < (*ppsmall)->size)
7569 ppsmall = pp;
7570 ++c;
7571 }
7572 if (c >= 16)
7573 {
7574 if (size <= (*ppsmall)->size)
7575 return;
7576 *ppsmall = (*ppsmall)->next;
7577 }
7578
7579 p = (struct backtrace_freelist_struct *) addr;
7580 p->next = state->freelist;
7581 p->size = size;
7582 state->freelist = p;
7583 }
7584}
7585
7586/* Allocate memory like malloc. If ERROR_CALLBACK is NULL, don't
7587 report an error. */
7588
7589void *
7590backtrace_alloc (struct backtrace_state *state,
7591 size_t size, backtrace_error_callback error_callback,
7592 void *data)
7593{
7594 void *ret;
7595 int locked;
7596 struct backtrace_freelist_struct **pp;
7597 size_t pagesize;
7598 size_t asksize;
7599 void *page;
7600
7601 ret = NULL;
7602
7603 /* If we can acquire the lock, then see if there is space on the
7604 free list. If we can't acquire the lock, drop straight into
7605 using mmap. __sync_lock_test_and_set returns the old state of
7606 the lock, so we have acquired it if it returns 0. */
7607
7608 if (!state->threaded)
7609 locked = 1;
7610 else
7611 locked = __sync_lock_test_and_set (&state->lock_alloc, 1) == 0;
7612
7613 if (locked)
7614 {
7615 for (pp = &state->freelist; *pp != NULL; pp = &(*pp)->next)
7616 {
7617 if ((*pp)->size >= size)
7618 {
7619 struct backtrace_freelist_struct *p;
7620
7621 p = *pp;
7622 *pp = p->next;
7623
7624 /* Round for alignment; we assume that no type we care about
7625 is more than 8 bytes. */
7626 size = (size + 7) & ~ (size_t) 7;
7627 if (size < p->size)
7628 backtrace_free_locked (state, (char *) p + size,
7629 p->size - size);
7630
7631 ret = (void *) p;
7632
7633 break;
7634 }
7635 }
7636
7637 if (state->threaded)
7638 __sync_lock_release (&state->lock_alloc);
7639 }
7640
7641 if (ret == NULL)
7642 {
7643 /* Allocate a new page. */
7644
7645 pagesize = getpagesize ();
7646 asksize = (size + pagesize - 1) & ~ (pagesize - 1);
7647 page = mmap (NULL, asksize, PROT_READ | PROT_WRITE,
7648 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
7649 if (page == MAP_FAILED)
7650 {
7651 if (error_callback)
7652 error_callback (data, "mmap", errno);
7653 }
7654 else
7655 {
7656 size = (size + 7) & ~ (size_t) 7;
7657 if (size < asksize)
7658 backtrace_free (state, (char *) page + size, asksize - size,
7659 error_callback, data);
7660
7661 ret = page;
7662 }
7663 }
7664
7665 return ret;
7666}
7667
7668/* Free memory allocated by backtrace_alloc. */
7669
7670void
7671backtrace_free (struct backtrace_state *state, void *addr, size_t size,
7672 backtrace_error_callback error_callback ATTRIBUTE_UNUSED,
7673 void *data ATTRIBUTE_UNUSED)
7674{
7675 int locked;
7676
7677 /* If we are freeing a large aligned block, just release it back to
7678 the system. This case arises when growing a vector for a large
7679 binary with lots of debug info. Calling munmap here may cause us
7680 to call mmap again if there is also a large shared library; we
7681 just live with that. */
7682 if (size >= 16 * 4096)
7683 {
7684 size_t pagesize;
7685
7686 pagesize = getpagesize ();
7687 if (((uintptr_t) addr & (pagesize - 1)) == 0
7688 && (size & (pagesize - 1)) == 0)
7689 {
7690 /* If munmap fails for some reason, just add the block to
7691 the freelist. */
7692 if (munmap (addr, size) == 0)
7693 return;
7694 }
7695 }
7696
7697 /* If we can acquire the lock, add the new space to the free list.
7698 If we can't acquire the lock, just leak the memory.
7699 __sync_lock_test_and_set returns the old state of the lock, so we
7700 have acquired it if it returns 0. */
7701
7702 if (!state->threaded)
7703 locked = 1;
7704 else
7705 locked = __sync_lock_test_and_set (&state->lock_alloc, 1) == 0;
7706
7707 if (locked)
7708 {
7709 backtrace_free_locked (state, addr, size);
7710
7711 if (state->threaded)
7712 __sync_lock_release (&state->lock_alloc);
7713 }
7714}
7715
7716/* Grow VEC by SIZE bytes. */
7717
7718void *
7719backtrace_vector_grow (struct backtrace_state *state,size_t size,
7720 backtrace_error_callback error_callback,
7721 void *data, struct backtrace_vector *vec)
7722{
7723 void *ret;
7724
7725 if (size > vec->alc)
7726 {
7727 size_t pagesize;
7728 size_t alc;
7729 void *base;
7730
7731 pagesize = getpagesize ();
7732 alc = vec->size + size;
7733 if (vec->size == 0)
7734 alc = 16 * size;
7735 else if (alc < pagesize)
7736 {
7737 alc *= 2;
7738 if (alc > pagesize)
7739 alc = pagesize;
7740 }
7741 else
7742 {
7743 alc *= 2;
7744 alc = (alc + pagesize - 1) & ~ (pagesize - 1);
7745 }
7746 base = backtrace_alloc (state, alc, error_callback, data);
7747 if (base == NULL)
7748 return NULL;
7749 if (vec->base != NULL)
7750 {
7751 memcpy (base, vec->base, vec->size);
7752 backtrace_free (state, vec->base, vec->size + vec->alc,
7753 error_callback, data);
7754 }
7755 vec->base = base;
7756 vec->alc = alc - vec->size;
7757 }
7758
7759 ret = (char *) vec->base + vec->size;
7760 vec->size += size;
7761 vec->alc -= size;
7762 return ret;
7763}
7764
7765/* Finish the current allocation on VEC. */
7766
7767void *
7768backtrace_vector_finish (
7769 struct backtrace_state *state ATTRIBUTE_UNUSED,
7770 struct backtrace_vector *vec,
7771 backtrace_error_callback error_callback ATTRIBUTE_UNUSED,
7772 void *data ATTRIBUTE_UNUSED)
7773{
7774 void *ret;
7775
7776 ret = vec->base;
7777 vec->base = (char *) vec->base + vec->size;
7778 vec->size = 0;
7779 return ret;
7780}
7781
7782/* Release any extra space allocated for VEC. */
7783
7784int
7785backtrace_vector_release (struct backtrace_state *state,
7786 struct backtrace_vector *vec,
7787 backtrace_error_callback error_callback,
7788 void *data)
7789{
7790 size_t size;
7791 size_t alc;
7792 size_t aligned;
7793
7794 /* Make sure that the block that we free is aligned on an 8-byte
7795 boundary. */
7796 size = vec->size;
7797 alc = vec->alc;
7798 aligned = (size + 7) & ~ (size_t) 7;
7799 alc -= aligned - size;
7800
7801 backtrace_free (state, (char *) vec->base + aligned, alc,
7802 error_callback, data);
7803 vec->alc = 0;
7804 if (vec->size == 0)
7805 vec->base = NULL;
7806 return 1;
7807}
7808