-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdwarf.cc
2093 lines (1879 loc) · 67.1 KB
/
dwarf.cc
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
// $Header$
//
// @Copyright (C) 2002 - 2007, 2023 Carlo Wood.
//
// pub dsa3072/C155A4EEE4E527A2 2018-08-16 Carlo Wood (CarloWood on Libera) <carlo@alinoe.com>
// fingerprint: 8020 B266 6305 EE2F D53E 6827 C155 A4EE E4E5 27A2
//
// This file may be distributed under the terms of the Q Public License
// version 1.0 as appearing in the file LICENSE.QPL included in the
// packaging of this file.
//
#include "sys.h"
#include <libcwd/config.h>
#if CWDEBUG_LOCATION
#include <cstdarg>
#include <inttypes.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <link.h>
#include <new>
#include <string>
#include <fstream>
#include <sys/param.h> // Needed for realpath(3)
#include <unistd.h> // Needed for getpid(2) and realpath(3)
#if defined(__FreeBSD__) || defined(__OpenBSD__)
#include <stdlib.h> // Needed for realpath(3)
#endif
#ifdef HAVE_DLOPEN
#include <dlfcn.h>
#include <cstring>
#include <cstdlib>
#include <map>
#endif
#include <algorithm>
#include <iomanip>
#include "cwd_debug.h"
#include "ios_base_Init.h"
#include "exec_prog.h"
#include "match.h"
#include "cwd_dwarf.h"
#include <libcwd/class_object_file.h>
#include <libcwd/class_channel.h>
#include <libcwd/private_string.h>
#include <libcwd/core_dump.h>
#ifndef LIBCWD_PRIVATE_MUTEX_INSTANCES_H
#include "libcwd/private_mutex_instances.h"
#endif
#include "libcwd/debug.h"
#include "elfutils/known-dwarf.h"
#include <elf.h>
#include <functional>
#if CWDEBUG_DEBUG
#include "libcwd/buf2str.h"
#endif
namespace libcwd {
namespace _private_ {
extern void demangle_symbol(char const* in, _private_::internal_string& out);
#if LIBCWD_THREAD_SAFE && CWDEBUG_ALLOC && __GNUC__ == 3 && __GNUC_MINOR__ == 4
extern char* pool_allocator_lock_symbol_ptr;
#endif
#if CWDEBUG_ALLOC
extern void remove_type_info_references(object_file_ct const* object_file_ptr LIBCWD_COMMA_TSD_PARAM);
#endif
} // namespace _private_
// New debug channel.
namespace channels {
namespace dc {
/** \addtogroup group_default_dc */
/** \{ */
/** The BFD channel. */
channel_ct bfd
#ifndef HIDE_FROM_DOXYGEN
("BFD")
#endif
;
/** \} */
} // namespace dc
} // namespace channels
using _private_::set_alloc_checking_on;
using _private_::set_alloc_checking_off;
#ifdef HAVE_DLOPEN
extern "C" {
// dlopen and dlclose function pointers into libdl.
static union { void* symptr; void* (*func)(char const*, int); } real_dlopen;
static union { void* symptr; int (*func)(void*); } real_dlclose;
}
#endif
char const* const location_ct::S_uninitialized_location_ct_c = "<uninitialized location_ct>";
char const* const location_ct::S_pre_ios_initialization_c = "<pre ios initialization>";
char const* const location_ct::S_pre_libcwd_initialization_c = "<pre libcwd initialization>";
char const* const location_ct::S_cleared_location_ct_c = "<cleared location ct>";
namespace dwarf {
// Detect if this libcwd library is static or not.
#ifdef __PIC__
constexpr bool statically_linked = false;
#else
constexpr bool statically_linked = true;
#endif
bool is_group_member(gid_t gid)
{
#if defined(HAVE_GETGID) && defined(HAVE_GETEGID)
if (gid == getgid() || gid == getegid())
#endif
return true;
#ifdef HAVE_GETGROUPS
int ngroups = 0;
int default_group_array_size = 0;
getgroups_t* group_array = (getgroups_t*)nullptr;
while (ngroups == default_group_array_size)
{
default_group_array_size += 64;
group_array = (getgroups_t*)realloc(group_array, default_group_array_size * sizeof(getgroups_t));
ngroups = getgroups(default_group_array_size, group_array);
}
if (ngroups > 0)
for (int i = 0; i < ngroups; i++)
if (gid == group_array[i])
{
free(group_array);
return true;
}
free(group_array);
#endif // HAVE_GETGROUPS
return false;
}
//
// Find the full path to the current running process.
// This needs to work before we reach main, therefore
// it uses the /proc filesystem. In order to be as
// portable as possible the most general trick is used:
// reading "/proc/PID/cmdline". It expects that the
// name of the program (argv[0] in main()) is returned
// as a zero terminated string when reading this file.
//
// If "/proc/PID/cmdline" doesn't exist, then we run
// `ps' in order to find the name of the running
// program.
//
void ST_get_full_path_to_executable(_private_::internal_string& result LIBCWD_COMMA_TSD_PARAM)
{
_private_::string argv0; // Like main()s argv[0], thus must be zero terminated.
char buf[11];
char* p = &buf[10];
*p = 0;
int pid = getpid();
do { *--p = '0' + (pid % 10); } while ((pid /= 10) > 0);
size_t const max_proc_path = sizeof("/proc/2147483647/cmdline\0");
char proc_path[max_proc_path];
strcpy(proc_path, "/proc/");
strcpy(proc_path + 6, p);
strcat(proc_path, "/cmdline");
std::ifstream proc_file(proc_path);
if (proc_file)
{
proc_file >> argv0;
proc_file.close();
}
else
DoutFatal(dc::fatal, "Can't find \"" << proc_path << "\". Try -DEnableLibcwdLocation:BOOL=OFF.");
argv0 += '\0';
// argv0 now contains a zero terminated string optionally followed by the command line
// arguments (which is why we can't use argv0.find('/') here), all seperated by the 0 character.
if (!strchr(argv0.data(), '/'))
{
_private_::string prog_name(argv0);
_private_::string path_list(getenv("PATH"));
_private_::string::size_type start_pos = 0, end_pos;
_private_::string path;
struct stat finfo;
for (;;)
{
end_pos = path_list.find(':', start_pos);
path = path_list.substr(start_pos, end_pos - start_pos) + '/' + prog_name + '\0';
if (stat(path.data(), &finfo) == 0 && !S_ISDIR(finfo.st_mode))
{
uid_t user_id = geteuid();
if ((user_id == 0 && (finfo.st_mode & 0111)) ||
(user_id == finfo.st_uid && (finfo.st_mode & 0100)) ||
(is_group_member(finfo.st_gid) && (finfo.st_mode & 0010)) ||
(finfo.st_mode & 0001))
{
argv0 = path;
break;
}
}
if (end_pos == _private_::string::npos)
break;
start_pos = end_pos + 1;
}
}
char full_path_buf[MAXPATHLEN];
char* full_path = realpath(argv0.data(), full_path_buf);
if (!full_path)
DoutFatal(dc::fatal|error_cf, "realpath(\"" << argv0.data() << "\", full_path_buf)");
Dout(dc::debug, "Full path to executable is \"" << full_path << "\".");
set_alloc_checking_off(LIBCWD_TSD);
result.assign(full_path);
result += '\0'; // Make string null terminated so we can use data().
set_alloc_checking_on(LIBCWD_TSD);
}
static bool WST_initialized = false; // MT: Set here to false, set to `true' once in `cwbfd::ST_init'.
struct objfile_ct;
class symbol_ct
{
private:
Dwarf_Addr real_start_; // Key
Dwarf_Addr real_end_;
mutable objfile_ct* objfile_; // Data
mutable Dwarf_Die die_;
mutable char const* cu_name_;
mutable char const* func_name_;
mutable char const* linkage_name_;
public:
inline symbol_ct(Dwarf_Addr start, Dwarf_Addr end,
objfile_ct* objfile, Dwarf_Die const* die, char const* cu_name, char const* func_name, char const* linkage_name);
// Create a symbol from an .symtab entry.
symbol_ct(Dwarf_Addr start, Dwarf_Addr end, objfile_ct* objfile, char const* linkage_name);
// Create a dummy symbol to be used as search key.
symbol_ct(Dwarf_Addr start) : real_start_(start), real_end_(start + 1) { }
Dwarf_Addr real_start() const { return real_start_; }
Dwarf_Addr real_end() const { return real_end_; }
objfile_ct const* objfile() const { return objfile_; }
Dwarf_Die const* die() const { return &die_; }
bool diecu(Dwarf_Die* cu_die_out) const
{
// die_.addr should only be NULL when the .symtab constructor was used, in which case die_ is uninitialized.
return die_.addr ? dwarf_diecu(&die_, cu_die_out, NULL, NULL) != nullptr : false;
}
char const* cu_name() const { return cu_name_; }
char const* func_name() const { return func_name_; }
char const* linkage_name() const { return linkage_name_; }
char const* name() const { return linkage_name_ ? linkage_name_ : func_name_; }
void set_func_name(char const* func_name) const { func_name_ = func_name; }
void set_linkage_name(char const* linkage_name) const { linkage_name_ = linkage_name; }
void set_real_end(Dwarf_Addr real_end) { real_end_ = real_end; }
bool operator==(symbol_ct const&) const { DoutFatal(dc::core, "Calling operator=="); }
friend struct symbol_key_greater;
};
struct symbol_key_greater
{
// Returns true when the start of a lays beyond the end of b (ie, no overlap).
bool operator()(symbol_ct const& a, symbol_ct const& b) const
{
return a.real_start() >= b.real_end();
}
};
#if CWDEBUG_ALLOC
using function_symbols_ct = std::set<symbol_ct, symbol_key_greater, _private_::object_files_allocator::rebind<symbol_ct>::other>;
#else
using function_symbols_ct = std::set<symbol_ct, symbol_key_greater>;
#endif
class Elf;
// All allocations related to objfile_ct must be `internal'.
class objfile_ct : public objfiles_ct
{
friend class libcwd::location_ct;
private:
Dwarf* dwarf_handle_;
int dwarf_fd_;
uintptr_t M_lbase;
uintptr_t M_start_addr;
uintptr_t M_end_addr;
function_symbols_ct M_function_symbols;
public:
objfile_ct(char const* filename, uintptr_t base_addr, uintptr_t start_addr, uintptr_t end_addr);
~objfile_ct();
bool initialize(char const* filename LIBCWD_COMMA_ALLOC_OPT(bool is_libc) LIBCWD_COMMA_TSD_PARAM);
void deinitialize(LIBCWD_TSD_PARAM);
uintptr_t get_lbase() const { return M_lbase; }
uintptr_t get_start_addr() const { return M_start_addr; }
uintptr_t get_end_addr() const { return M_end_addr; }
symbol_ct const* find_symbol(symbol_ct const& search_key) const;
bool is_initialized() const
{
return dwarf_fd_ != -1;
}
private:
void extract_and_add_function_symbols(char const* cu_name, Elf& elf, Dwarf_Die* die_ptr LIBCWD_COMMA_TSD_PARAM);
void open_dwarf(LIBCWD_TSD_PARAM);
void close_dwarf(LIBCWD_TSD_PARAM);
};
struct object_file_greater {
bool operator()(objfiles_ct const* a, objfiles_ct const* b) const
{
return static_cast<objfile_ct const*>(a)->get_lbase() > static_cast<objfile_ct const*>(b)->get_lbase();
}
};
symbol_ct::symbol_ct(Dwarf_Addr start, Dwarf_Addr end,
objfile_ct* objfile, Dwarf_Die const* die, char const* cu_name, char const* func_name, char const* linkage_name) :
real_start_(start + objfile->get_lbase()), real_end_(end + objfile->get_lbase()),
objfile_(objfile), die_(*die), cu_name_(cu_name), func_name_(func_name), linkage_name_(linkage_name)
{
}
symbol_ct::symbol_ct(Dwarf_Addr start, Dwarf_Addr end, objfile_ct* objfile, char const* linkage_name) :
real_start_(start + objfile->get_lbase()), real_end_(end + objfile->get_lbase()),
objfile_(objfile), die_{}, cu_name_(nullptr), func_name_(nullptr), linkage_name_(linkage_name)
{
}
objfile_ct* load_object_file(char const* name, uintptr_t base_addr, uintptr_t start_addr, uintptr_t end_addr, bool initialized = false)
{
static bool WST_initialized = false;
LIBCWD_TSD_DECLARATION;
// If dlopen is called as very first function (instead of malloc), we get here
// as first function inside libcwd. In that case, initialize libcwd first.
if (!WST_initialized)
{
if (initialized)
WST_initialized = true;
else if (!ST_init(LIBCWD_TSD))
return nullptr;
}
#if CWDEBUG_DEBUGM
LIBCWD_ASSERT( !__libcwd_tsd.internal );
#endif
objfile_ct* object_file;
char const* slash = strrchr(name, '/');
if (!slash)
slash = name - 1;
#if LIBCWD_THREAD_SAFE && CWDEBUG_ALLOC && __GNUC__ == 3 && __GNUC_MINOR__ == 4
bool is_libstdcpp;
is_libstdcpp = (strncmp("libstdc++.so", slash + 1, 12) == 0);
#endif
#if CWDEBUG_ALLOC
bool is_libc = (strncmp("libc.so", slash + 1, 7) == 0);
#endif
bool failure;
LIBCWD_DEFER_CANCEL;
DWARF_ACQUIRE_WRITE_LOCK;
set_alloc_checking_off(LIBCWD_TSD);
object_file = new objfile_ct(name, base_addr, start_addr, end_addr); // LEAK6
set_alloc_checking_on(LIBCWD_TSD);
DWARF_RELEASE_WRITE_LOCK;
failure = object_file->initialize(name LIBCWD_COMMA_ALLOC_OPT(is_libc) LIBCWD_COMMA_TSD);
LIBCWD_RESTORE_CANCEL;
if (failure)
{
set_alloc_checking_off(LIBCWD_TSD);
delete object_file;
set_alloc_checking_on(LIBCWD_TSD);
return nullptr;
}
return object_file;
}
static int dl_iterate_phdr_callback(dl_phdr_info* info, size_t size, void* fullpath)
{
uintptr_t base_address = info->dlpi_addr;
uintptr_t start_addr = (uintptr_t)0 - 1;
uintptr_t end_addr = 0;
for (int i = 0; i < info->dlpi_phnum; ++i)
{
if (info->dlpi_phdr[i].p_type == PT_LOAD && (info->dlpi_phdr[i].p_flags & PF_X))
{
if (end_addr != 0)
// This isn't really a problem. All we need an address range that uniquely determines this object file.
Dout(dc::warning, "Object file \"" << info->dlpi_name << "\" has more than one executable PT_LOAD segments!");
uintptr_t current_start_addr = base_address + info->dlpi_phdr[i].p_vaddr;
uintptr_t current_end_addr = current_start_addr + info->dlpi_phdr[i].p_memsz;
start_addr = std::min(start_addr, current_start_addr);
end_addr = std::max(end_addr, current_end_addr);
}
}
if (end_addr != 0)
{
[[maybe_unused]] objfile_ct* objfile;
if (info->dlpi_name[0] == 0)
objfile = load_object_file(reinterpret_cast<char const*>(fullpath), base_address, start_addr, end_addr, true);
else if (info->dlpi_name[0] == '/' || info->dlpi_name[0] == '.')
objfile = load_object_file(info->dlpi_name, base_address, start_addr, end_addr);
}
return 0;
}
struct Data2
{
uintptr_t addr;
objfile_ct* object_file;
};
static int dl_iterate_phdr_callback2(dl_phdr_info* info, size_t size, void* userdata)
{
Data2* data = reinterpret_cast<Data2*>(userdata);
uintptr_t int_addr = data->addr;
uintptr_t base_address = info->dlpi_addr;
uintptr_t start_addr = (uintptr_t)0 - 1;
uintptr_t end_addr = 0;
for (int i = 0; i < info->dlpi_phnum; ++i)
{
if (info->dlpi_phdr[i].p_type == PT_LOAD && (info->dlpi_phdr[i].p_flags & PF_X))
{
if (end_addr != 0)
// This isn't really a problem. All we need an address range that uniquely determines this object file.
Dout(dc::warning, "Object file \"" << info->dlpi_name << "\" has more than one executable PT_LOAD segments!");
uintptr_t current_start_addr = base_address + info->dlpi_phdr[i].p_vaddr;
uintptr_t current_end_addr = current_start_addr + info->dlpi_phdr[i].p_memsz;
start_addr = std::min(start_addr, current_start_addr);
end_addr = std::max(end_addr, current_end_addr);
}
}
bool found = start_addr <= int_addr && int_addr < end_addr;
if (found)
{
// We already have the executable; only check for shared libraries.
if (info->dlpi_name[0] == '/' || info->dlpi_name[0] == '.')
data->object_file = load_object_file(info->dlpi_name, base_address, start_addr, end_addr);
return 1;
}
// Continue with the next object file.
return 0;
}
static int dl_iterate_phdr_callback3(dl_phdr_info* info, size_t size, void* userdata)
{
Data2* data = reinterpret_cast<Data2*>(userdata);
uintptr_t base_address = info->dlpi_addr;
if (base_address != data->addr)
return 0;
uintptr_t start_addr = (uintptr_t)0 - 1;
uintptr_t end_addr = 0;
for (int i = 0; i < info->dlpi_phnum; ++i)
{
if (info->dlpi_phdr[i].p_type == PT_LOAD && (info->dlpi_phdr[i].p_flags & PF_X))
{
if (end_addr != 0)
// This isn't really a problem. All we need an address range that uniquely determines this object file.
Dout(dc::warning, "Object file \"" << info->dlpi_name << "\" has more than one executable PT_LOAD segments!");
uintptr_t current_start_addr = base_address + info->dlpi_phdr[i].p_vaddr;
uintptr_t current_end_addr = current_start_addr + info->dlpi_phdr[i].p_memsz;
start_addr = std::min(start_addr, current_start_addr);
end_addr = std::max(end_addr, current_end_addr);
}
}
// We already have the executable; only check for shared libraries.
if (info->dlpi_name[0] == '/' || info->dlpi_name[0] == '.')
data->object_file = load_object_file(info->dlpi_name, base_address, start_addr, end_addr);
return 1;
}
static void resort_object_files(LIBCWD_TSD_PARAM)
{
objfile_ct* object_file = nullptr;
LIBCWD_DEFER_CANCEL;
DWARF_ACQUIRE_WRITE_LOCK;
set_alloc_checking_off(LIBCWD_TSD);
NEEDS_WRITE_LOCK_object_files().sort(object_file_greater());
set_alloc_checking_on(LIBCWD_TSD);
DWARF_RELEASE_WRITE_LOCK;
LIBCWD_RESTORE_CANCEL;
}
bool ST_init(LIBCWD_TSD_PARAM)
{
static bool WST_being_initialized = false;
// This should catch it when we call new or malloc while 'internal'.
if (WST_being_initialized)
return false;
WST_being_initialized = true;
// This must be called before calling ST_init().
if (!libcw_do.NS_init(LIBCWD_TSD))
return false;
// MT: We assume this is called before reaching main().
// Therefore, no synchronisation is required.
#if CWDEBUG_DEBUG && LIBCWD_THREAD_SAFE
if (_private_::WST_multi_threaded)
core_dump();
#endif
#if CWDEBUG_DEBUG && CWDEBUG_ALLOC
LIBCWD_ASSERT( !__libcwd_tsd.internal );
#endif
#if CWDEBUG_ALLOC
// Initialize the malloc library if not done yet.
init_debugmalloc();
#endif
// ****************************************************************************
// Start INTERNAL!
set_alloc_checking_off(LIBCWD_TSD);
// new (fake_ST_shared_libs) ST_shared_libs_vector_ct;
libcwd::debug_ct::OnOffState state;
libcwd::channel_ct::OnOffState state2;
if (_private_::always_print_loading && !_private_::suppress_startup_msgs)
{
// We want debug output to BFD
Debug( libcw_do.force_on(state) );
Debug( dc::bfd.force_on(state2, "BFD") );
}
// Initialize object files list, we don't really need the
// write lock because this function is Single Threaded.
LIBCWD_DEFER_CANCEL;
DWARF_ACQUIRE_WRITE_LOCK;
new (&NEEDS_WRITE_LOCK_object_files()) object_files_ct;
DWARF_RELEASE_WRITE_LOCK;
set_alloc_checking_on(LIBCWD_TSD);
LIBCWD_RESTORE_CANCEL;
set_alloc_checking_off(LIBCWD_TSD);
// Start a new scope for 'fullpath': it needs to be destructed while internal.
{
// Get the full path and name of executable
_private_::internal_string fullpath;
set_alloc_checking_on(LIBCWD_TSD);
// End INTERNAL!
// ****************************************************************************
ST_get_full_path_to_executable(fullpath LIBCWD_COMMA_TSD);
// Result is '\0' terminated so we can use data() as a C string.
// Load executable and shared objects.
DWARF_INITIALIZE_LOCK;
if (!statically_linked)
{
// Call load_object_file for everything..
dl_iterate_phdr(dl_iterate_phdr_callback, fullpath.data());
resort_object_files(LIBCWD_TSD);
}
if (_private_::always_print_loading)
{
Debug( dc::bfd.restore(state2) );
Debug( libcw_do.restore(state) );
}
WST_initialized = true; // MT: Safe, this function is Single Threaded.
set_alloc_checking_off(LIBCWD_TSD);
} // Destruct fullpath
set_alloc_checking_on(LIBCWD_TSD);
return true;
}
char objfiles_ct::ST_list_instance[sizeof(object_files_ct)] __attribute__((__aligned__));
objfile_ct::objfile_ct(char const* filename, uintptr_t base_addr, uintptr_t start_addr, uintptr_t end_addr) :
objfiles_ct(filename), dwarf_fd_(-1), dwarf_handle_(nullptr), M_lbase(base_addr), M_start_addr(start_addr), M_end_addr(end_addr)
{
#if CWDEBUG_DEBUGM
LIBCWD_TSD_DECLARATION;
LIBCWD_ASSERT( __libcwd_tsd.internal );
#if CWDEBUG_DEBUGT
LIBCWD_ASSERT( _private_::is_locked(object_files_instance) );
#endif
#endif
}
objfile_ct::~objfile_ct()
{
LIBCWD_TSD_DECLARATION;
set_alloc_checking_on(LIBCWD_TSD);
close_dwarf(LIBCWD_TSD);
set_alloc_checking_off(LIBCWD_TSD);
}
#if CWDEBUG_DEBUG
#define DWARF_ONE_KNOWN_DW_TAG(tag_, tag_name_) \
case tag_name_: \
tag_name = #tag_name_; \
break;
static void print_die_info(Dwarf_Die* die)
{
// 1. Print DIE Tag.
char const* tag_name = "<unknown>";
Dwarf_Half tag = dwarf_tag(die);
switch (tag)
{
DWARF_ALL_KNOWN_DW_TAG
}
Dout(dc::bfd, "DIE Tag: " << tag_name);
// 2. Print DIE Offset.
Dwarf_Off die_offset = dwarf_dieoffset(die);
Dout(dc::bfd, "DIE Offset: 0x" << std::hex << die_offset);
// 3. Print DIE Name (if available).
char const* name = dwarf_diename(die);
if (name) {
Dout(dc::bfd, "DIE Name: " << name);
}
// 4. Print Parent DIE Offset (if applicable).
Dwarf_Die parent_die;
if (dwarf_diecu(die, &parent_die, nullptr, nullptr))
{
die_offset = dwarf_dieoffset(&parent_die);
Dout(dc::bfd, "Parent DIE Offset: 0x" << std::hex << die_offset);
}
}
void dump_shdr(Elf64_Shdr const* shdr)
{
Dout(dc::bfd,
"{sh_name=" << shdr->sh_name << std::hex << // Section name (string tbl index).
", sh_type=0x" << shdr->sh_type << // Section type.
", sh_flags=0x" << shdr->sh_flags << // Section flags.
", sh_addr=0x" << shdr->sh_addr << // Section virtual addr at execution.
", sh_offset=0x" << shdr->sh_offset << std::dec << // Section file offset.
", sh_size=" << shdr->sh_size << // Section size in bytes.
", sh_link=" << shdr->sh_link << // Link to another section.
", sh_info=" << shdr->sh_info << // Additional section information.
", sh_addralign=" << shdr->sh_addralign << // Section alignment.
", sh_entsize=" << shdr->sh_entsize << '}'); // Entry size if section holds table.
}
#endif // CWDEBUG_DEBUG
struct SymbolNameCompare
{
bool operator()(char const* name1, char const* name2) const
{
return strcmp(name1, name2) < 0;
}
};
class Elf
{
private:
GElf_Addr lbase_;
int fd_;
::Elf* elf_;
size_t shstrndx_;
#if CWDEBUG_DEBUG
char const* filepath_;
#endif
struct Range
{
GElf_Addr start_;
GElf_Addr end_;
};
using relocation_map_ct = std::map<char const*, Range, SymbolNameCompare
#if CWDEBUG_ALLOC
, _private_::internal_allocator::rebind<std::pair<char const* const, Range>>::other
#endif
>;
relocation_map_ct relocation_map_;
public:
Elf(char const* filepath, GElf_Addr lbase) :
lbase_(lbase)
#if CWDEBUG_DEBUG
, filepath_(filepath)
#endif
{
// Open the object file for reading.
if ((fd_ = open(filepath, O_RDONLY)) == -1)
Dout(dc::warning|error_cf, "Failed to open file \"" << filepath << "\"");
// Open an ELF descriptor for reading.
else if (!(elf_ = elf_begin(fd_, ELF_C_READ, NULL)))
{
::close(fd_);
Dout(dc::warning, filepath << ": elf_begin returned NULL: " << elf_errmsg(-1));
}
// Check if it is an ELF file.
else if (elf_kind(elf_) != ELF_K_ELF)
Dout(dc::bfd, filepath << ": skipping, not an ELF file.");
// Get the section header string table index.
else if (elf_getshdrstrndx(elf_, &shstrndx_) != 0)
Dout(dc::warning, filepath << ": elf_getshdrstrndx couldn't find the section header string index: " << elf_errmsg(-1));
else
// Success.
return;
throw std::runtime_error("error");
}
~Elf()
{
elf_end(elf_);
::close(fd_);
LIBCWD_TSD_DECLARATION;
{
relocation_map_ct empty_dummy;
std::swap(relocation_map_, empty_dummy);
#if CWDEBUG_ALLOC
__libcwd_tsd.internal = 1;
#endif
}
#if CWDEBUG_ALLOC
__libcwd_tsd.internal = 0;
#endif
}
int process_relocs();
void add_symtab(std::function<void(Dwarf_Addr start, Dwarf_Addr end, char const* linkage_name LIBCWD_COMMA_TSD_PARAM)> symbol_cb) const;
void add_backup(char const* linkage_name, GElf_Addr start, GElf_Addr end);
bool apply_relocation(char const* linkage_name, GElf_Addr& start_out, GElf_Addr& end_out) const;
#if CWDEBUG_DEBUG
// Print all section header names (for debugging purposes).
void print_section_header_names() const
{
Dout(dc::bfd, "Section headers of \"" << filepath_ << "\":");
int count = 0;
Elf_Scn* section = nullptr;
while ((section = elf_nextscn(elf_, section)) != nullptr)
{
GElf_Shdr shdr;
if (gelf_getshdr(section, &shdr))
{
++count;
//dump_shdr(&shdr);
char const* section_name = elf_strptr(elf_, shstrndx_, shdr.sh_name);
Dout(dc::bfd, " [" << count << "] \"" << section_name << "\"");
}
}
}
#endif // CWDEBUG_DEBUG
private:
void add_symbol(GElf_Sym* sym, size_t symstrndx, bool is_reloc, GElf_Sxword r_addend = 0);
void process_relocs_x(GElf_Shdr* shdr, Elf_Data* symdata, Elf_Data *xndxdata, size_t symstrndx,
GElf_Addr r_offset, GElf_Xword r_info, GElf_Sxword r_addend);
void process_relocs_rel(GElf_Shdr* shdr, Elf_Data* data, Elf_Data* symdata, Elf_Data* xndxdata, size_t symstrndx);
void process_relocs_rela(GElf_Shdr* shdr, Elf_Data* data, Elf_Data* symdata, Elf_Data* xndxdata, size_t symstrndx);
};
void Elf::add_symbol(GElf_Sym* sym, size_t symstrndx, bool is_reloc, GElf_Sxword r_addend)
{
char const* name = elf_strptr(elf_, symstrndx, sym->st_name);
GElf_Addr start = sym->st_value + r_addend;
GElf_Addr end = start + sym->st_size;
if (GELF_ST_TYPE(sym->st_info) == STT_FUNC && sym->st_shndx != SHN_UNDEF && sym->st_size > 0)
{
#if CWDEBUG_DEBUG
Dout(dc::bfd|continued_cf, "Adding \"" << libcwd::buf2str(name, std::strlen(name)) <<
"\" range [0x" << std::hex << (lbase_ + start) << "-0x" << (lbase_ + end) << "] to relocation_map_...");
#endif
LIBCWD_TSD_DECLARATION;
#if CWDEBUG_ALLOC
__libcwd_tsd.internal = 1;
#endif
#if CWDEBUG_DEBUG
auto ibp =
#endif
relocation_map_.emplace(std::make_pair(name, Range{start, end}));
#if CWDEBUG_ALLOC
__libcwd_tsd.internal = 0;
#endif
#if CWDEBUG_DEBUG
if (ibp.second)
Dout(dc::finish, " done");
else if (is_reloc || start != ibp.first->second.start_ || end > ibp.first->second.end_)
Dout(dc::finish, " failed! Collision with \"" << ibp.first->first << std::hex <<
"\" [0x" << (lbase_ + ibp.first->second.start_) << "-0x" << (lbase_ + ibp.first->second.end_) << "]");
else
Dout(dc::finish, " existed");
#endif
}
}
void Elf::process_relocs_x(GElf_Shdr* shdr, Elf_Data* symdata, Elf_Data *xndxdata, size_t symstrndx,
GElf_Addr r_offset, GElf_Xword r_info, GElf_Sxword r_addend)
{
Elf32_Word xndx;
GElf_Sym symmem;
GElf_Sym* sym = gelf_getsymshndx(symdata, xndxdata, GELF_R_SYM(r_info), &symmem, &xndx);
if (!sym)
{
#if CWDEBUG_DEBUG
Dout(dc::bfd, filepath_ << ": gelf_getsymshndx: INVALID SYMBOL");
#else
Dout(dc::bfd, "gelf_getsymshndx: INVALID SYMBOL");
#endif
return;
}
else if (GELF_ST_TYPE(sym->st_info) == STT_SECTION)
{
return;
#if 0
// The symbol refers to a section header.
GElf_Shdr destshdr_mem;
GElf_Shdr* destshdr;
destshdr = gelf_getshdr(elf_getscn(elf_, sym->st_shndx == SHN_XINDEX ? xndx : sym->st_shndx), &destshdr_mem);
if (shdr == nullptr || destshdr == nullptr)
Dout(dc::bfd, "INVALID SECTION");
else
Dout(dc::bfd, "shstrndx: " << shstrndx_ << ": value: 0x" << std::hex << sym->st_value << ": " << elf_strptr(elf_, shstrndx_, destshdr->sh_name));
#endif
}
// Found a symbol.
add_symbol(sym, symstrndx, true, r_addend);
}
void Elf::add_symtab(std::function<void(Dwarf_Addr start, Dwarf_Addr end, char const* linkage_name LIBCWD_COMMA_TSD_PARAM)> symbol_cb) const
{
LIBCWD_TSD_DECLARATION;
for (relocation_map_ct::value_type const& value : relocation_map_)
symbol_cb(value.second.start_, value.second.end_, value.first LIBCWD_COMMA_TSD);
}
void Elf::process_relocs_rel(GElf_Shdr* shdr, Elf_Data* data, Elf_Data* symdata, Elf_Data* xndxdata, size_t symstrndx)
{
size_t sh_entsize = gelf_fsize(elf_, ELF_T_REL, 1, EV_CURRENT);
int nentries = shdr->sh_size / sh_entsize;
for (int cnt = 0; cnt < nentries; ++cnt)
{
GElf_Rel relmem;
GElf_Rel* rel;
rel = gelf_getrel(data, cnt, &relmem);
if (rel != nullptr)
process_relocs_x(shdr, symdata, xndxdata, symstrndx, rel->r_offset, rel->r_info, 0);
}
}
void Elf::process_relocs_rela(GElf_Shdr* shdr, Elf_Data* data, Elf_Data* symdata, Elf_Data* xndxdata, size_t symstrndx)
{
size_t sh_entsize = gelf_fsize(elf_, ELF_T_RELA, 1, EV_CURRENT);
int nentries = shdr->sh_size / sh_entsize;
for (int cnt = 0; cnt < nentries; ++cnt)
{
GElf_Rela relmem;
GElf_Rela* rel;
rel = gelf_getrela(data, cnt, &relmem);
if (rel != nullptr)
process_relocs_x(shdr, symdata, xndxdata, symstrndx, rel->r_offset, rel->r_info, rel->r_addend);
}
}
int Elf::process_relocs()
{
Elf_Scn* scn = nullptr;
while ((scn = elf_nextscn(elf_, scn)) != nullptr)
{
GElf_Shdr shdr_mem;
GElf_Shdr* shdr = gelf_getshdr(scn, &shdr_mem);
if (shdr == nullptr)
{
#if CWDEBUG_DEBUG
Dout(dc::warning, filepath_ << ": gelf_getshdr returned NULL");
#else
Dout(dc::warning, "gelf_getshdr returned NULL!");
#endif
// Looks like a fatal error, but try to continue anyway.
continue;
}
if (shdr->sh_type == SHT_REL || shdr->sh_type == SHT_RELA)
{
#if 0
GElf_Shdr destshdr_mem;
GElf_Shdr* destshdr = gelf_getshdr(elf_getscn(elf_, shdr->sh_info), &destshdr_mem);
if (destshdr == nullptr)
continue;
#endif
// Get the data of the section.
Elf_Data* data = elf_getdata(scn, nullptr);
if (data == nullptr)
continue;
// Get the symbol table information.
Elf_Scn* symscn = elf_getscn(elf_, shdr->sh_link);
GElf_Shdr symshdr_mem;
GElf_Shdr* symshdr = gelf_getshdr(symscn, &symshdr_mem);
Elf_Data* symdata = elf_getdata(symscn, nullptr);
if (symshdr == nullptr || symdata == nullptr)
continue;
// Search for the optional extended section index table.
Elf_Data* xndxdata = nullptr;
Elf_Scn* xndxscn = nullptr;
while ((xndxscn = elf_nextscn(elf_, xndxscn)) != nullptr)
{
GElf_Shdr xndxshdr_mem;
GElf_Shdr* xndxshdr;
xndxshdr = gelf_getshdr(xndxscn, &xndxshdr_mem);
if (xndxshdr != nullptr && xndxshdr->sh_type == SHT_SYMTAB_SHNDX && xndxshdr->sh_link == elf_ndxscn(symscn))
{
// Found it.
xndxdata = elf_getdata(xndxscn, nullptr);
break;
}
}
if (shdr->sh_type == SHT_REL)
process_relocs_rel(shdr, data, symdata, xndxdata, symshdr->sh_link);
else
process_relocs_rela(shdr, data, symdata, xndxdata, symshdr->sh_link);
}
}
//Dout(dc::bfd, "Adding .symtab:");
scn = nullptr;
while ((scn = elf_nextscn(elf_, scn)) != nullptr)
{
GElf_Shdr shdr_mem;
GElf_Shdr* shdr = gelf_getshdr(scn, &shdr_mem);
if (shdr == nullptr)
{
#if CWDEBUG_DEBUG
Dout(dc::warning, filepath_ << ": gelf_getshdr returned NULL");
#else
Dout(dc::warning, "gelf_getshdr returned NULL!");
#endif
return -1;
}
if (shdr->sh_type == SHT_SYMTAB)
{
// Get the data of the section.
Elf_Data* data = elf_getdata(scn, nullptr);
if (data == nullptr)
continue;
// Calculate the number of symbol entries in the .symtab section.
size_t num_syms = shdr->sh_size / shdr->sh_entsize;
// Process each symbol entry in the .symtab section.
for (size_t i = 0; i < num_syms; ++i)
{
GElf_Sym sym_mem;
GElf_Sym* sym = gelf_getsym(data, static_cast<int>(i), &sym_mem);
if (sym != nullptr)
add_symbol(sym, shdr->sh_link, false);
}
break; // We found and processed the .symtab section, so exit the loop.
}
}
// Success.
return 0;
}
void Elf::add_backup(char const* linkage_name, GElf_Addr start, GElf_Addr end)
{
auto it = relocation_map_.find(linkage_name);
if (it == relocation_map_.end())
{
LIBCWD_TSD_DECLARATION;
#if CWDEBUG_ALLOC
__libcwd_tsd.internal = 1;