-
Notifications
You must be signed in to change notification settings - Fork 3
/
stacktraces.cpp
1963 lines (1631 loc) · 109 KB
/
stacktraces.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// http://www.dwarfstd.org/doc/DWARF5.pdf
// objdump --dump=info a.out
#include "stacktraces.h"
#ifdef SWITCH_PHAISTOS
// DBG_ST is used for debuging/tracing -- assists development and troubleshooting
//#define DBG_ST 1
#include <text.h>
#else
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <utility>
#include <linux/limits.h>
#include <unistd.h>
#include <sys/mman.h>
#include <algorithm>
#include <cstdio>
#endif
#include <cxxabi.h>
#include <dlfcn.h>
#include <execinfo.h>
#include <elf.h>
#include <link.h>
#include <libdwarf/dwarf.h> // apt-get install -y libdwarf-dev
static constexpr size_t K_max_tracked_frames = 512;
static constexpr size_t K_max_dso_frames = 512;
static constexpr size_t K_max_abbrev_spec_attrs = 128;
static constexpr size_t K_abbr_map_size = 128;
static constexpr size_t K_max_compilation_unit_files = 512;
static constexpr size_t K_max_tracked_dsos = 128;
static constexpr size_t K_max_tracked_refs = 128;
static uint64_t decode_LEB128(const uint8_t *&data) {
const auto *p = data;
uint8_t shift{0}, byte;
int64_t result{0};
do {
byte = *p++;
result |= ((unsigned long int)(byte & 0x7f)) << shift;
shift += 7;
} while (byte & 0x80);
data = p;
return result;
}
static int64_t decode_signed_LEB128(const uint8_t *&data) {
const auto *p = data;
uint8_t shift{0}, byte;
int64_t result{0};
do {
byte = *p++;
result |= ((unsigned long int)(byte & 0x7f)) << shift;
shift += 7;
} while (byte & 0x80);
data = p;
if ((shift < 8 * sizeof(result)) && (byte & 0x40))
result |= -1L << shift;
return result;
}
// http://www.dwarfstd.org/doc/DWARF4.pdf 7.20
// accelerated lookup
// Use -gdwarf-aranges to force compiler to emit this section
// verify with objdump -dwarf=aranges
//
// Attempt to return an offset into debug_info for the CU this address belongs to
static std::pair<int8_t, uint64_t> debug_info_offset_in_aranges(const uint64_t address,
range_base<const uint8_t *, size_t> section,
std::pair<uint64_t, range64_t> *cache) {
if (!section) {
return {0, 0};
}
if (const auto a = cache->second.offset; address >= a && address < a + cache->second.size()) {
// fast-path, in last range
#ifdef DBG_ST
SLog(ansifmt::bold, "FROM CACHE", ansifmt::reset, "\n");
#endif
return {1, cache->first};
}
for (const auto *p = section.offset, *const e = p + section.size(); p < e;) {
// read next chunk
uint64_t unit_len = decode_pod<uint32_t>(p);
bool _64bit;
if (unit_len == static_cast<uint32_t>(-1)) {
unit_len = decode_pod<uint64_t>(p);
_64bit = true;
} else {
_64bit = false;
}
const auto version = decode_pod<uint16_t>(p);
if (version != 2) {
return {-1, 0};
}
// debug info section offset
const uint64_t debug_info_offset = _64bit
? decode_pod<uint64_t>(p)
: decode_pod<uint32_t>(p);
const auto address_size = decode_pod<uint8_t>(p);
if (address_size != sizeof(uint32_t) && address_size != sizeof(uint64_t)) {
return {-1, 0};
}
const auto segment_size = decode_pod<uint8_t>(p);
// padded to a multiple of tuple size
const size_t tuple_size = address_size + address_size + segment_size;
const auto n = tuple_size - (std::distance(section.offset, p) % tuple_size);
for (p += n;;) {
// read next tuple(segmnet, address, length)
uint64_t start, len;
[[maybe_unused]] const uint64_t segment = segment_size == 0
? 0
: (segment_size == sizeof(uint8_t)
? decode_pod<uint8_t>(p)
: (segment_size == sizeof(uint16_t)
? decode_pod<uint16_t>(p)
: (segment_size == sizeof(uint32_t))
? decode_pod<uint32_t>(p)
: decode_pod<uint64_t>(p)));
p += segment_size;
if (address_size == sizeof(uint64_t)) {
start = decode_pod<uint64_t>(p);
len = decode_pod<uint64_t>(p);
} else {
start = decode_pod<uint32_t>(p);
len = decode_pod<uint32_t>(p);
}
if (0 == segment_size && 0 == start && 0 == len) {
break;
} else if (address >= start && address < start + len) {
// address in [start, start + len)
// we got an offset to debug_info
#ifdef DBG_ST
SLog("Matched ", address, " in ", debug_info_offset, " range ", range_base<uint64_t>(start,len), "\n");
#endif
cache->first = debug_info_offset;
cache->second = {start, len};
return {1, debug_info_offset};
}
}
}
return {0, 0};
}
#ifndef DW_FORM_implicit_const
#define DW_FORM_implicit_const 0x21
#endif
#ifndef DW_LNS_extended_op
#define DW_LNS_extended_op 0
#endif
union attr_val final {
uint64_t u64;
str_view32 _str;
attr_val()
: _str{} {
}
auto str() {
if (_str.p && !_str.len) _str.len = strlen(_str.p);
return _str;
}
};
struct attr_spec final {
uint64_t name;
uint64_t form;
uint64_t const_value;
};
struct abbrev_spec final {
uint64_t entry;
uint64_t tag;
uint8_t children;
size_t attrs_cnt;
abbrev_spec *next;
attr_spec attrs[0];
};
static bool parse_attr_value(const uint64_t form, const uint8_t version,
const uint8_t *const debug_str_base,
const uint8_t offset_size, const uint8_t addr_size,
const uint8_t *&p, attr_val *const out) {
out->_str.reset();
switch (form) {
case DW_FORM_ref_addr:
if (version == 3 || version == 4) {
out->u64 = offset_size == sizeof(uint32_t) ? decode_pod<uint32_t>(p) : decode_pod<uint64_t>(p);
break;
}
[[fallthrough]];
case DW_FORM_addr:
// clang-format off
out->u64 = addr_size == sizeof(uint64_t) ? decode_pod<uint64_t>(p)
: (addr_size == sizeof(uint32_t) ? decode_pod<uint32_t>(p)
: (addr_size == sizeof(uint16_t) ? decode_pod<uint16_t>(p) : 0));
// clang-format on
break;
case DW_FORM_GNU_ref_alt:
[[fallthrough]];
case DW_FORM_sec_offset:
out->u64 = offset_size == sizeof(uint32_t) ? decode_pod<uint32_t>(p) : decode_pod<uint64_t>(p);
break;
case DW_FORM_block2:
p += (*reinterpret_cast<const uint16_t *>(p)) + sizeof(uint16_t);
break;
case DW_FORM_block4:
p += (*reinterpret_cast<const uint32_t *>(p)) + sizeof(uint32_t);
break;
case DW_FORM_data2:
out->u64 = decode_pod<uint16_t>(p);
break;
case DW_FORM_data4:
out->u64 = decode_pod<uint32_t>(p);
break;
case DW_FORM_data8:
out->u64 = decode_pod<uint64_t>(p);
break;
case DW_FORM_string:
out->_str.p = reinterpret_cast<const char *>(p);
out->_str.len = strlen(out->_str.p);
p += out->_str.len + 1;
break;
case DW_FORM_strp: {
const auto o = offset_size == sizeof(uint64_t)
? decode_pod<uint64_t>(p)
: decode_pod<uint32_t>(p);
// deferred
out->_str.p = reinterpret_cast<const char *>(debug_str_base + o);
out->_str.len = 0;
} break;
case DW_FORM_GNU_strp_alt:
p += offset_size;
break;
case DW_FORM_exprloc:
[[fallthrough]];
case DW_FORM_block:
p += decode_LEB128(p);
break;
case DW_FORM_block1:
p += (*p) + sizeof(uint8_t);
break;
case DW_FORM_data1:
out->u64 = *p++;
break;
case DW_FORM_flag:
++p;
break;
case DW_FORM_flag_present:
break;
case DW_FORM_sdata:
out->u64 = decode_signed_LEB128(p);
break;
case DW_FORM_udata:
out->u64 = decode_LEB128(p);
break;
case DW_FORM_ref1:
out->u64 = decode_pod<uint8_t>(p);
break;
case DW_FORM_ref2:
out->u64 = decode_pod<uint16_t>(p);
break;
case DW_FORM_ref4:
out->u64 = decode_pod<uint32_t>(p);
break;
case DW_FORM_ref8:
out->u64 = decode_pod<uint64_t>(p);
break;
case DW_FORM_ref_udata:
out->u64 = decode_LEB128(p);
break;
case DW_FORM_indirect: {
const auto f = decode_LEB128(p);
attr_val other;
if (!parse_attr_value(f, version, debug_str_base, offset_size, addr_size, p, &other)) {
return false;
}
} break;
default:
return false;
}
return true;
}
static bool locate_abstract_instance_name(const uint8_t *unit_hdr, const uint8_t *const debug_str_base, const abbrev_spec **dict,
const uint8_t version, const uint8_t offset_size, const uint8_t addr_size,
const uint64_t form, const uint64_t ref, str_view32 *const __restrict res) {
if (form == DW_FORM_ref_addr || form == DW_FORM_GNU_ref_alt) {
return false;
}
const auto *p = unit_hdr + ref;
const auto code = decode_LEB128(p);
if (!code) {
return true;
}
const abbrev_spec *abbr;
for (abbr = dict[code & (K_abbr_map_size - 1)]; abbr && abbr->entry != code; abbr = abbr->next) {
continue;
}
if (!abbr) {
return false;
}
attr_val value;
for (const auto *at = abbr->attrs, *const at_end = at + abbr->attrs_cnt; at < at_end; ++at) {
if (!parse_attr_value(at->form, version, debug_str_base, offset_size, addr_size, p, &value)) {
return false;
}
switch (at->name) {
case DW_AT_name:
if (!res->p) {
// linkage name has precendance over name
*res = value._str;
}
break;
case DW_AT_specification:
if (!locate_abstract_instance_name(unit_hdr, debug_str_base, dict, version, offset_size, addr_size, at->form, value.u64, res)) {
return false;
}
break;
case DW_AT_linkage_name:
[[fallthrough]];
case DW_AT_MIPS_linkage_name:
if (value._str.p)
*res = value._str;
break;
default:
break;
}
}
return true;
}
int Switch::stacktrace(void **frames, const size_t depth, stack_frame *out, const size_t stack_frames_capacity, uint8_t *storage, size_t storage_size) {
// XXX: backtrace() will allocate memory(why?)
// we can't safely allocate memory in the signal handler
// we should look for an alternative way to obtain that backtrace.
//
// Also, note that backtrace() will store RETURN ADDRESSES in frames[], which
// means we need to determine the callsite of the function instead of
// the callsite of whatever the called function returns to.
if (!stack_frames_capacity || storage_size < 1 * 1024) {
#ifdef DBG_ST
SLog("Out Of Memory\n");
#endif
return -StackResolverErrors::OutOfMemory;
}
struct match final {
uintptr_t base_addr; // so that we can use this as a key
const int8_t * q;
Elf64_Phdr phdr;
char path[PATH_MAX];
range_base<const int8_t *, size_t> loadable_progseg_range;
} frame_match;
struct tracked_dso final {
uintptr_t key;
char * path;
uint8_t path_len;
struct {
const uint8_t *addr;
size_t size;
} vma;
struct {
range_base<const uint8_t *, size_t> debug_info, debug_line,
debug_abbrev, debug_ranges, debug_aranges, debug_str, dynstr;
} sections;
str_view32 path_s8() const noexcept {
if (!path)
return {};
else
return {path, path_len};
}
} tracked_dsos[K_max_tracked_dsos];
struct tracked_ref final {
uint32_t frame_index;
uint32_t index;
uint32_t tracked_dsos_index;
str_view32 func_name;
range_base<uintptr_t, size_t> addr_range;
uint64_t line_program_offset;
struct {
str_view32 dir;
str_view32 filename;
uint32_t line;
uint32_t column;
uintptr_t line_addr;
uint32_t call_line;
} src_ref;
struct {
uint32_t line;
uint32_t column;
uint32_t file_id;
str_view32 filename;
} inline_ctx;
struct LPState final {
uint32_t seq_id;
enum class State : uint8_t {
SeqLow,
SeqHigh,
} state;
inline bool on_diff_seq(const uint32_t cur_seq_id) const noexcept {
return cur_seq_id != seq_id;
}
void reset() {
seq_id = 0;
}
} lp_state;
} tracked_refs[K_max_tracked_refs];
#ifdef SWITCH_PHAISTOS
[[maybe_unused]] const auto __start = Timings::Microseconds::Tick();
#endif
size_t tracked_dsos_cnt{0}, tracked_refs_cnt{0};
std::pair<uint32_t, uint32_t> frame_dso[K_max_tracked_frames]; // (frame index, dso index)
std::pair<uintptr_t, std::pair<uint32_t, uint64_t>> dso_frames[K_max_dso_frames];
attr_spec abbreviation_spec_attrs[K_max_abbrev_spec_attrs];
size_t frame_dso_size{0};
str_view32 comp_unit_files[K_max_compilation_unit_files];
const auto tear_down = [&]() {
for (size_t i{0}; i < tracked_dsos_cnt; ++i) {
if (auto addr = tracked_dsos[i].vma.addr) {
munmap(reinterpret_cast<void *>(const_cast<uint8_t *>(addr)), tracked_dsos[i].vma.size);
}
}
};
for (size_t i{0}; i < depth && tracked_dsos_cnt < K_max_tracked_dsos; ++i) {
const auto return_addr = reinterpret_cast<const int8_t *>(frames[i]); // the return address from the corresponding frame
frame_match.q = return_addr;
if (!dl_iterate_phdr([](struct dl_phdr_info *info, size_t size, void *data) {
auto *const frame_match = reinterpret_cast<match *>(data);
const auto base_addr{info->dlpi_addr};
(void)size;
// consider all loadable program segments
for (size_t i{0}; i < info->dlpi_phnum; ++i) {
const auto &phdr = info->dlpi_phdr[i];
if (phdr.p_type == PT_LOAD) {
const auto b = reinterpret_cast<int8_t *>(phdr.p_vaddr + base_addr);
const auto e = b + phdr.p_memsz;
if (frame_match->q >= b && frame_match->q < e) {
frame_match->loadable_progseg_range.set(b, phdr.p_memsz); // not needed, but track it anyway
strcpy(frame_match->path, info->dlpi_name); // only needed because we need to mmap() it
memcpy(&frame_match->phdr, &phdr, sizeof(phdr)); // don't need that either?
frame_match->base_addr = reinterpret_cast<uintptr_t>(info->dlpi_addr); // for tracking distinct DSOs
return 1;
}
}
}
return 0;
},
&frame_match)) {
// this doesn't make any sense
#ifdef DBG_ST
SLog("Unable to match with dl_iterate_phdr()\n");
#endif
tear_down();
return -StackResolverErrors::NoSupport;
}
size_t dso_i{0};
tracked_dso *dso;
while (dso_i < tracked_dsos_cnt && (dso = tracked_dsos + dso_i)->key != frame_match.base_addr) {
++dso_i;
}
if (dso_i == tracked_dsos_cnt) {
// First-seen DSO
dso = &tracked_dsos[tracked_dsos_cnt];
if (!frame_match.path[0]) {
dso->path = nullptr;
dso->path_len = 0;
} else {
const auto len = strlen(frame_match.path);
if (len + 1 > storage_size) {
goto l200;
}
dso->path = reinterpret_cast<char *>(storage);
dso->path_len = len;
memcpy(storage, frame_match.path, len);
storage[len] = '\0';
storage += len + 1;
storage_size -= len + 1;
}
++tracked_dsos_cnt;
dso->key = frame_match.base_addr;
dso->vma.addr = nullptr;
}
frame_dso[frame_dso_size++] = {i, dso_i};
if (frame_dso_size == K_max_tracked_frames) {
// sanity
break;
}
}
l200:
// Group by DSO
std::sort(frame_dso, frame_dso + frame_dso_size, [](const auto &a, const auto &b) noexcept { return a.second < b.second; });
for (size_t tri{0}; tri < frame_dso_size; ++tri) {
const auto dso_i = frame_dso[tri].second;
auto dso = tracked_dsos + dso_i;
int fd = open(dso->path ?: "/proc/self/exe", O_RDONLY | O_LARGEFILE);
if (-1 == fd) {
tear_down();
#if DBG_ST
SLog("open(): ", strerror(errno), "\n");
#endif
return -StackResolverErrors::Sys;
}
const auto file_size = lseek(fd, 0, SEEK_END);
if (file_size < static_cast<off_t>(sizeof(Elf64_Ehdr))) {
close(fd);
tear_down();
#if DBG_ST
SLog("file_size = ", file_size, "\n");
#endif
return -StackResolverErrors::Sys;
}
auto vma_base = mmap(nullptr, file_size, PROT_READ, MAP_SHARED, fd, 0);
close(fd);
if (MAP_FAILED == vma_base) {
tear_down();
#ifdef DBG_ST
SLog("mmap(): ", strerror(errno), "\n");
#endif
return -StackResolverErrors::Sys;
}
dso->vma.addr = reinterpret_cast<const uint8_t *>(vma_base);
dso->vma.size = file_size;
const auto addr = dso->vma.addr;
const auto elf_hdr = reinterpret_cast<const Elf64_Ehdr *>(addr);
const auto sh = reinterpret_cast<const Elf64_Shdr *>(addr + elf_hdr->e_shoff);
const auto &snsth = sh[elf_hdr->e_shstrndx]; // section header table index of the entry associated with the section name string table (could be SHN_UNDEF)
memset(&dso->sections, 0, sizeof(dso->sections));
for (size_t i{0}; i < elf_hdr->e_shnum; ++i) {
const auto & s = sh[i];
const str_view32 name(reinterpret_cast<const char *>(addr + snsth.sh_offset + s.sh_name));
switch (s.sh_type) {
case SHT_SYMTAB:
case SHT_DYNSYM:
break;
case 3:
if (name.Eq(_S(".dynstr")))
dso->sections.dynstr.set(addr + s.sh_offset, s.sh_size);
break;
case 1:
if (name.Eq(_S(".debug_info"))) {
dso->sections.debug_info.set(addr + s.sh_offset, s.sh_size);
} else if (name.Eq(_S(".debug_line"))) {
dso->sections.debug_line.set(addr + s.sh_offset, s.sh_size);
} else if (name.Eq(_S(".debug_abbrev"))) {
dso->sections.debug_abbrev.set(addr + s.sh_offset, s.sh_size);
} else if (name.Eq(_S(".debug_ranges"))) {
dso->sections.debug_ranges.set(addr + s.sh_offset, s.sh_size);
}
else if (name.Eq(_S(".debug_aranges"))) {
// compile with -gdwarf-aranges
dso->sections.debug_aranges.set(addr + s.sh_offset, s.sh_size);
}
else if (name.Eq(_S(".debug_str"))) {
dso->sections.debug_str.set(addr + s.sh_offset, s.sh_size);
}
break;
default:
break;
}
}
if (!dso->sections.debug_info || !dso->sections.debug_line || !dso->sections.debug_abbrev || !dso->sections.debug_ranges || !dso->sections.debug_str) {
// debug info missing; compile with -g3
continue;
}
#ifdef DBG_ST
SLog(ansifmt::bold, ansifmt::color_green, "NEW DSO ", tracked_refs_cnt, ansifmt::reset,"\n");
#endif
auto dso_tracked_ref_base = tracked_refs_cnt;
const auto abbrev_base = dso->sections.debug_abbrev.offset;
[[maybe_unused]] const auto abbrev_end = abbrev_base + dso->sections.debug_abbrev.size();
size_t dso_frames_size{0};
do {
const auto frame_index = frame_dso[tri].first;
const auto ptr = reinterpret_cast<uintptr_t>(frames[frame_index]);
dso_frames[dso_frames_size++] = {ptr, {frame_index, 0}};
if (dso_frames_size == K_max_dso_frames) {
// sanity
#ifdef DBG_ST
SLog(ansifmt::bold, ansifmt::color_red, "Hit limit", ansifmt::reset, "\n");
#endif
break;
}
} while (++tri < frame_dso_size && frame_dso[tri].second == dso_i);
#ifdef DBG_ST
SLog(ansifmt::color_red, "FOR NEW module ", dso_frames_size, ansifmt::reset, "\n");
#endif
std::pair<range32_t, range_base<const uint8_t *, size_t>> chunks[dso_frames_size];
size_t chunks_size{0};
const auto *p = dso->sections.debug_info.offset, *const e = p + dso->sections.debug_info.size();
bool using_aranges{false};
if (dso->sections.debug_aranges) {
// great, we can group by debug_info chunks
// so that we can only consider specific CUs in this DSO
// and for each such CU only the frames that may be relevant to it
std::pair<uint64_t, range64_t> cache;
// sort by address ASC so that we may be able to
// hit debug_info_offset() cache
std::sort(dso_frames, dso_frames + dso_frames_size,
[](const auto &a, const auto &b) noexcept { return a.first < b.first; });
for (uint32_t i{0}; i < dso_frames_size;) {
const auto ptr = dso_frames[i].first;
const auto [res, debug_info_offset] = debug_info_offset_in_aranges(ptr, dso->sections.debug_aranges, &cache);
if (res < 0) {
return -StackResolverErrors::NoSupport;
} else if (0 == res) {
#ifdef DBG_ST
SLog("Nope for ", ptr, "\n");
#endif
dso_frames[i] = dso_frames[--dso_frames_size];
continue;
}
do {
dso_frames[i].second.second = debug_info_offset;
} while (++i < dso_frames_size && dso_frames[i].first == ptr);
}
// group by debug_info chunk offset now
std::sort(dso_frames, dso_frames + dso_frames_size,
[](const auto &a, const auto &b) noexcept { return a.second.second < b.second.second; });
for (uint32_t i{0}; i < dso_frames_size;) {
const auto base = i;
const auto debug_info_offset = dso_frames[i].second.second;
const auto chunk_offset = p + debug_info_offset;
do {
//
} while (++i < dso_frames_size && dso_frames[i].second.second == debug_info_offset);
#ifdef DBG_ST
SLog(ansifmt::bold, ansifmt::color_blue, "<< ", range32_t(base, i - base), ansifmt::reset, "\n");
#endif
chunks[chunks_size++] = {range32_t{base, i - base},
range_base<const uint8_t *, size_t>{chunk_offset,
static_cast<size_t>(std::distance(chunk_offset, e))}};
}
using_aranges = true;
} else {
// We will need to scan all debug_info CUs chunks
chunks_size = 1;
chunks[0] = {
range32_t{0, static_cast<uint32_t>(dso_frames_size)},
range_base<const uint8_t *, size_t>{p, static_cast<size_t>(std::distance(p, e))}};
}
// a simple dictionary for fast access to the abbreviation table
abbrev_spec *abbreviations_map[K_abbr_map_size] = {nullptr};
for (size_t ci{0}; ci < chunks_size; ++ci) {
const auto [dsos_range, chunk_range] = chunks[ci];
const auto *p = chunk_range.offset, *const e = p + chunk_range.size();
const auto dsos_range_start = dsos_range.offset;
const auto dsos_range_end = dsos_range_start + dsos_range.size();
#ifdef DBG_ST
SLog(ansifmt::bold, ansifmt::color_red, "Chunk for dsos_range = ", dsos_range, ansifmt::reset, " at ", ptr_repr(p), " dwarf_info chunk offset\n");
#endif
// http://www.dwarfstd.org/doc/DWARF5.pdf 7.5
while (p < e) {
// 7.5.1.1: Full or Partial Compilation Unit Headers
const auto unit_hdr = p;
[[maybe_unused]] size_t offset_size, initial_len_size;
uint64_t compilation_unit_len = decode_pod<uint32_t>(p);
auto local_storage_next = storage;
const auto local_storage_end = storage + storage_size;
if (compilation_unit_len == 0xffffffff) {
// DWARF3 way of indicating we use 64-bit offsets, instead of 32-bit offsets
compilation_unit_len = decode_pod<uint64_t>(p);
offset_size = sizeof(uint64_t);
} else if (compilation_unit_len == 0) {
// IRIX way of indicating 64-bit offsets, mostly
compilation_unit_len = decode_pod<uint64_t>(p);
offset_size = sizeof(uint64_t);
} else {
offset_size = sizeof(uint32_t);
}
const auto compilation_unit_end = p + compilation_unit_len;
// We are only really doing this in order to determine the
// function name and the address range of the function
// we are going to get the filename from the .debug_line section, and
// we need the range of the function first in order to match the address
// computed while running the line program against the it
if (compilation_unit_len > 0) {
const auto version = decode_pod<uint16_t>(p);
const auto unit_type = version >= 5 ? decode_pod<uint8_t>(p) : 0;
const uint64_t abbrev_offset = offset_size == sizeof(uint64_t)
? decode_pod<uint64_t>(p)
: decode_pod<uint32_t>(p);
const auto addr_size = decode_pod<uint8_t>(p);
[[maybe_unused]] const auto dwo_id = (unit_type == 0x04 || unit_type == 0x05)
? decode_pod<uint64_t>(p)
: 0;
if (unit_type == 0x2) {
[[maybe_unused]] const auto type_signature = decode_pod<uint64_t>(p);
[[maybe_unused]] const uint64_t type_offset = offset_size == sizeof(uint64_t)
? decode_pod<uint64_t>(p)
: decode_pod<uint32_t>(p);
}
if (version < 2 || version > 5) {
tear_down();
#ifdef DBG_ST
SLog("Version ", version, "\n");
#endif
return -StackResolverErrors::NoSupport;
}
switch (addr_size) {
case sizeof(uint16_t):
[[fallthrough]];
case sizeof(uint32_t):
[[fallthrough]];
case sizeof(uint64_t):
break;
default:
tear_down();
#ifdef DBG_ST
SLog("No Support\n");
#endif
return -StackResolverErrors::NoSupport;
}
const auto *first_entry = p;
// Dwarf 7.5.3
// Multiple compilation units(e.g .o files) may share the same abbrevation table.
// The abbreviations table for a single compilation unit consists of a
// series of abbreviation declarations.
//
// Each abbreviation specifies the TAG and ATTRIBUTES for a particular FORM of debugging information
// entry.
// Each declaration begins with LEB128 number representing the abbreviation code itself.
// It is this code that appears in the beginning of debuging information entry in
// the .debug_info section.
// It is followed by another unsigned LEB128 that encode the entry's tag.
//
// Following the tag encoding is a 1-byte value that determines ether the
// debugging information entry using this
// abbreviation has child entries or not. If it is == DW_CHILDREN_yes, the next physically
// succeeding entry of
// any debugging information entry using this abbreviation is the first child of that entry,
// otherwise if if it is
// == DW_CHILDREN_no it is a sibling of that entry.
// Finally, the child encoding is followed by a series of attributes specifications.
// Each consists of two parts. The first represnets the name, and the second the form
// The series of attribute specifications ends with an entry containing 0 for name and 0 for form
//
// We are going to parse the abbreviationt able associated with this compilation unit before
// we iterate the debugging information entries of the compilation unit
p = abbrev_base + abbrev_offset;
// Parse successive abbreviation declarations from the abbreviation table
// TODO: multiple compilation units can be associated with the same abbr.table, so maybe
// we should cache this information if already decoded
//
// TODO: if we can guarantee abbreviations appear in the DIE in the same
// order as they appear in the abbriviations table -- which shouldn't be a safe assumption
// because the same abbreviations table can be shared between multiple CUs,
// then we could just parse abbreviation and its attributes and then the respective attributes values
// as we go, without having to use this hashtable.
while (const auto code = decode_LEB128(p)) {
// tag for this abbreviation declaration
const auto tag = decode_LEB128(p); // e.g DW_TAG_compile_unit, DW_TAG_subprogram, ..
const auto children = decode_pod<uint8_t>(p);
size_t abbreviation_spec_attrs_cnt{0};
// attributes
for (;;) {
const auto attr = decode_LEB128(p); // e.g DW_AT_producer, DW_AT_name, ...
const auto form = decode_LEB128(p);
if (!attr && !form) {
break;
}
if (abbreviation_spec_attrs_cnt < K_max_abbrev_spec_attrs) {
if (form == DW_FORM_implicit_const) {
abbreviation_spec_attrs[abbreviation_spec_attrs_cnt] =
{.name = attr, .form = form, .const_value = decode_LEB128(p)};
} else {
abbreviation_spec_attrs[abbreviation_spec_attrs_cnt] =
{.name = attr, .form = form};
}
++abbreviation_spec_attrs_cnt;
} else {
#ifdef DBG_ST
SLog(ansifmt::bold, ansifmt::color_red, "Hit limit", ansifmt::reset, "\n");
#endif
}
}
const size_t required = sizeof(abbrev_spec) + sizeof(attr_spec) * abbreviation_spec_attrs_cnt;
auto ent = reinterpret_cast<abbrev_spec *>(local_storage_next);
const auto index = code & (sizeof_array(abbreviations_map) - 1);
local_storage_next += required;
if (local_storage_next > local_storage_end) {
tear_down();
#ifdef DBG_ST
SLog("Out of Memory\n");
#endif
return -StackResolverErrors::OutOfMemory;
}
ent->attrs_cnt = abbreviation_spec_attrs_cnt;
ent->tag = tag;
ent->entry = code;
ent->children = children;
memcpy(ent->attrs, abbreviation_spec_attrs, abbreviation_spec_attrs_cnt * sizeof(attr_spec));
ent->next = abbreviations_map[index];
abbreviations_map[index] = ent;
}
int32_t level{1};
str_view32 compilation_unit_name;
attr_val value;
abbrev_spec *abbrev_info;
uint64_t line_offset{std::numeric_limits<uint64_t>::max()};
for (p = first_entry; p < compilation_unit_end;) {
// Dwarf3: 7.5.2
const auto abbrev_num = decode_LEB128(p);
if (!abbrev_num) {
--level;
continue;
}
for (abbrev_info = abbreviations_map[abbrev_num & (sizeof_array(abbreviations_map) - 1)];
abbrev_info && abbrev_info->entry != abbrev_num;
abbrev_info = abbrev_info->next) {
continue;
}
if (!abbrev_info) {
tear_down();
#ifdef DBG_ST
SLog("Unexpected Structure\n");
#endif
return -StackResolverErrors::UnexpectedStruct;
}
str_view32 func_name;
uint64_t low_pc{0}, high_pc{0}, base_range_addr{0}, call_line{0}, call_column{0};
uint32_t decl_line{0};
bool high_pc_relative{false}, in_func;
range64_t func_range;
uint32_t call_file{0};
// Process abbreviation
switch (abbrev_info->tag) {
case DW_TAG_inlined_subroutine:
// See 3.3.8.2
// Each inline subroutine entry may have either a
// DW_AT_low_pc and a DW_AT_high_pc attributes, or
// DW_AT_ranges attribute, whose values encode the contiguous
// or non-contiguous address ranges, respectively, of
// the machine instructions generated for the inline subroutine.
// An inlined subroutine may also contain a
// DW_AT_entry_pc attribute, representing the first
// executable instruction of the inline expansion
//
// An inline subroutine may also have DW_AT_call_file,
// DW_AT_call_line, and DW_AT_call_column attributes
// The locate the statement or expression that caused the inline expansion.
[[fallthrough]];
case DW_TAG_subprogram:
[[fallthrough]];
case DW_TAG_entry_point:
// this abbreviation is specific to a function or program