-
Notifications
You must be signed in to change notification settings - Fork 13
/
Builder.tcc
1768 lines (1490 loc) · 64.6 KB
/
Builder.tcc
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
/* Copyright 2017 - 2022 R. Thomas
* Copyright 2017 - 2022 Quarkslab
* Copyright 2017 - 2021, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cassert>
#include <numeric>
#include <unordered_map>
#include "logging.hpp"
#include "LIEF/BinaryStream/VectorStream.hpp"
#include "LIEF/ELF/utils.hpp"
#include "LIEF/ELF/EnumToString.hpp"
#include "LIEF/ELF/Builder.hpp"
#include "LIEF/ELF/Binary.hpp"
#include "LIEF/ELF/Section.hpp"
#include "LIEF/ELF/Segment.hpp"
#include "LIEF/ELF/Symbol.hpp"
#include "LIEF/ELF/DynamicEntry.hpp"
#include "LIEF/ELF/DynamicEntryArray.hpp"
#include "LIEF/ELF/DynamicEntryLibrary.hpp"
#include "LIEF/ELF/DynamicSharedObject.hpp"
#include "LIEF/ELF/DynamicEntryRunPath.hpp"
#include "LIEF/ELF/DynamicEntryRpath.hpp"
#include "LIEF/ELF/Relocation.hpp"
#include "LIEF/ELF/SymbolVersion.hpp"
#include "LIEF/ELF/SymbolVersionDefinition.hpp"
#include "LIEF/ELF/SymbolVersionAux.hpp"
#include "LIEF/ELF/SymbolVersionRequirement.hpp"
#include "LIEF/ELF/SymbolVersionAuxRequirement.hpp"
#include "LIEF/ELF/Note.hpp"
#include "LIEF/ELF/Builder.hpp"
#include "LIEF/errors.hpp"
#include "ELF/Structures.hpp"
#include "ELF/SizingInfo.hpp"
#include "Object.tcc"
#include "ExeLayout.hpp"
#include "ObjectFileLayout.hpp"
namespace LIEF {
namespace ELF {
template<class ELF_T>
ok_error_t Builder::build() {
const char* type = ((binary_->type_ == ELF_CLASS::ELFCLASS32) ? "ELF32" : "ELF64");
LIEF_DEBUG("== Re-building {} ==", type);
const E_TYPE file_type = binary_->header().file_type();
switch (file_type) {
case E_TYPE::ET_DYN:
case E_TYPE::ET_EXEC:
case E_TYPE::ET_CORE:
{
auto res = build_exe_lib<ELF_T>();
if (!res) {
LIEF_ERR("The builder failed for the given executable/library. "
"Check the error output");
return make_error_code(lief_errors::build_error);
}
return ok();
}
case E_TYPE::ET_REL:
{
auto res = build_relocatable<ELF_T>();
if (!res) {
LIEF_ERR("The builder failed for the given object file. "
"Check the error output");
return make_error_code(lief_errors::build_error);
}
return ok();
}
default:
{
LIEF_ERR("ELF file '{}' are not supported by LIEF", to_string(file_type));
return make_error_code(lief_errors::not_supported);
}
}
}
template<typename ELF_T>
ok_error_t Builder::build_exe_lib() {
auto* layout = static_cast<ExeLayout*>(layout_.get());
// Sort dynamic symbols
uint32_t new_symndx = sort_dynamic_symbols();
layout->set_dyn_sym_idx(new_symndx);
Segment* pt_interp = binary_->get(SEGMENT_TYPES::PT_INTERP);
if (config_.interpreter) {
if (pt_interp != nullptr) {
const size_t interpt_size = layout->interpreter_size<ELF_T>();
const uint64_t osize = binary_->sizing_info_->interpreter;
if (interpt_size > osize || config_.force_relocate) {
LIEF_DEBUG("[-] Need to relocate .interp section (0x{:x} new bytes)", interpt_size - osize);
layout->relocate_interpreter(interpt_size);
} else { LIEF_DEBUG(".interp: -0x{:x} bytes", osize - interpt_size); }
} else if (!binary_->interpreter_.empty()) { // Directly access private field as we want to avoid
// has_interpreter() check
// In this case, the original ELF file didn't have an interpreter
// and the user added one.
const size_t interpt_size = layout->interpreter_size<ELF_T>();
LIEF_DEBUG("[-] Need to create an .interp section / segment");
layout->relocate_interpreter(interpt_size);
}
}
if (binary_->has(SEGMENT_TYPES::PT_NOTE) && config_.notes) {
const size_t notes_size = layout->note_size<ELF_T>();
std::vector<Segment*> note_segments;
for (std::unique_ptr<Segment>& seg : binary_->segments_) {
if (seg->type() == SEGMENT_TYPES::PT_NOTE) {
note_segments.push_back(seg.get());
}
}
// TODO(romain): should we try to find the largest one?
const size_t nb_segment_notes = note_segments.size();
if (nb_segment_notes > 1) {
while (note_segments.size() > 1) {
binary_->remove(*note_segments.back());
note_segments.pop_back();
}
}
Segment& note_segment = *note_segments.back();
if (notes_size > note_segment.physical_size() || nb_segment_notes > 1 || config_.force_relocate) {
LIEF_DEBUG("[-] Need to relocate .note.* segments (0x{:x} new bytes)",
notes_size - note_segment.physical_size());
layout->relocate_notes(true);
} else { /*LIEF_DEBUG(".notes: -0x{:x} bytes", note_segment.physical_size() - notes_size);*/ }
}
if (binary_->has(DYNAMIC_TAGS::DT_GNU_HASH) && config_.gnu_hash) {
const size_t needed_size = layout->symbol_gnu_hash_size<ELF_T>();
const uint64_t osize = binary_->sizing_info_->gnu_hash;
const bool should_relocate = needed_size > osize || config_.force_relocate;
if (should_relocate) {
LIEF_DEBUG("[-] Need to relocate DT_GNU_HASH (0x{:x} new bytes)", needed_size - osize);
layout->relocate_gnu_hash(true);
} else { LIEF_DEBUG("DT_GNU_HASH: -0x{:x} bytes", osize - needed_size); }
}
if (binary_->has(DYNAMIC_TAGS::DT_HASH) && config_.dt_hash) {
const size_t needed_size = layout->symbol_sysv_hash_size<ELF_T>();
const uint64_t osize = binary_->sizing_info_->hash;
const bool should_relocate = needed_size > osize || config_.force_relocate;
if (should_relocate) {
LIEF_DEBUG("[-] Need to relocate DT_HASH (0x{:x} new bytes)", needed_size - osize);
layout->relocate_sysv_hash(needed_size);
} else { LIEF_DEBUG("DT_HASH: -0x{:x} bytes", osize - needed_size); }
}
if (binary_->has(SEGMENT_TYPES::PT_DYNAMIC) && config_.dynamic_section) {
const size_t dynamic_needed_size = layout->dynamic_size<ELF_T>();
const uint64_t osize = binary_->sizing_info_->dynamic;
const bool should_relocate = dynamic_needed_size > osize || config_.force_relocate;
if (should_relocate) {
LIEF_DEBUG("[-] Need to relocate .dynamic section (0x{:x} new bytes)", dynamic_needed_size - osize);
layout->relocate_dynamic(dynamic_needed_size);
} else { LIEF_DEBUG("PT_DYNAMIC: -0x{:x} bytes", osize - dynamic_needed_size); }
}
if (binary_->has(DYNAMIC_TAGS::DT_RELA) || binary_->has(DYNAMIC_TAGS::DT_REL)) {
const size_t dyn_reloc_needed_size = layout->dynamic_relocations_size<ELF_T>();
if (config_.rela) {
const uint64_t osize = binary_->sizing_info_->rela;
const bool should_relocate = dyn_reloc_needed_size > osize || config_.force_relocate;
if (should_relocate) {
LIEF_DEBUG("[-] Need to relocate DT_REL(A) (0x{:x} new bytes)", dyn_reloc_needed_size - osize);
layout->relocate_dyn_reloc(dyn_reloc_needed_size);
} else { LIEF_DEBUG("DT_REL(A): -0x{:x} bytes", osize - dyn_reloc_needed_size); }
}
}
if (config_.jmprel && binary_->has(DYNAMIC_TAGS::DT_JMPREL)) {
const size_t plt_reloc_needed_size = layout->pltgot_relocations_size<ELF_T>();
const uint64_t osize = binary_->sizing_info_->jmprel;
const bool should_relocate = plt_reloc_needed_size > osize || config_.force_relocate;
if (should_relocate) {
LIEF_DEBUG("[-] Need to relocate DT_JMPREL section (0x{:x} new bytes)", plt_reloc_needed_size - osize);
layout->relocate_plt_reloc(plt_reloc_needed_size);
} else { LIEF_DEBUG("DT_JMPREL: -0x{:x} bytes", osize - plt_reloc_needed_size); }
}
if (config_.dyn_str && binary_->has(DYNAMIC_TAGS::DT_STRTAB)) {
const size_t needed_size = layout->dynstr_size<ELF_T>();
const uint64_t osize = binary_->sizing_info_->dynstr;
const bool should_relocate = needed_size > osize || config_.force_relocate;
if (should_relocate) {
LIEF_DEBUG("[-] Need to relocate DT_STRTAB (0x{:x} new bytes)", needed_size - osize);
layout->relocate_dynstr(true);
} else { LIEF_DEBUG("DT_STRTAB: -0x{:x} bytes", osize - needed_size); }
}
if (config_.symtab && binary_->has(DYNAMIC_TAGS::DT_SYMTAB)) {
const size_t dynsym_needed_size = layout->dynsym_size<ELF_T>();
const uint64_t osize = binary_->sizing_info_->dynsym;
const bool should_relocate = dynsym_needed_size > osize || config_.force_relocate;
if (should_relocate) {
LIEF_DEBUG("[-] Need to relocate DT_SYMTAB (0x{:x} new bytes)", dynsym_needed_size - osize);
layout->relocate_dynsym(dynsym_needed_size);
} else { LIEF_DEBUG("DT_SYMTAB: -0x{:x} bytes", osize - dynsym_needed_size); }
}
if (binary_->has(DYNAMIC_TAGS::DT_INIT_ARRAY) && binary_->has(DYNAMIC_TAGS::DT_INIT_ARRAYSZ) &&
config_.init_array)
{
const size_t needed_size = layout->dynamic_arraysize<ELF_T>(DYNAMIC_TAGS::DT_INIT_ARRAY);
const uint64_t osize = binary_->sizing_info_->init_array;
const bool should_relocate = needed_size > osize;
if (should_relocate) {
if (binary_->has_symbol("__libc_start_main")) {
LIEF_WARN("Relocating DT_INIT_ARRAY on Linux may corrupt the final binary");
}
LIEF_DEBUG("[-] Need to relocate DT_INIT_ARRAY (0x{:x} new bytes)", osize - needed_size);
layout->relocate_init_array(needed_size);
} else { LIEF_DEBUG("DT_INIT_ARRAY: -0x{:x} bytes", osize - needed_size); }
}
if (binary_->has(DYNAMIC_TAGS::DT_PREINIT_ARRAY) && binary_->has(DYNAMIC_TAGS::DT_PREINIT_ARRAYSZ) &&
config_.preinit_array)
{
const size_t needed_size = layout->dynamic_arraysize<ELF_T>(DYNAMIC_TAGS::DT_PREINIT_ARRAY);
const uint64_t osize = binary_->sizing_info_->preinit_array;
const bool should_relocate = needed_size > osize;
if (should_relocate) {
LIEF_DEBUG("[-] Need to relocate DT_PREINIT_ARRAY (0x{:x} new bytes)", osize - needed_size);
layout->relocate_preinit_array(needed_size);
} else { LIEF_DEBUG("DT_PREINIT_ARRAY: -0x{:x} bytes", osize - needed_size); }
}
if (binary_->has(DYNAMIC_TAGS::DT_FINI_ARRAY) && binary_->has(DYNAMIC_TAGS::DT_FINI_ARRAYSZ) &&
config_.fini_array)
{
const size_t needed_size = layout->dynamic_arraysize<ELF_T>(DYNAMIC_TAGS::DT_FINI_ARRAY);
const uint64_t osize = binary_->sizing_info_->fini_array;
const bool should_relocate = needed_size > osize;
if (should_relocate) {
if (binary_->has_symbol("__libc_start_main")) {
LIEF_WARN("Relocating .fini_array on Linux may corrupt the final binary");
}
LIEF_DEBUG("[-] Need to relocate DT_FINI_ARRAY (0x{:x} new bytes)", osize - needed_size);
layout->relocate_fini_array(needed_size);
} else { LIEF_DEBUG("DT_FINI_ARRAY: -0x{:x} bytes", osize - needed_size); }
}
if (binary_->has(DYNAMIC_TAGS::DT_VERSYM) && config_.sym_versym) {
const size_t symver_needed_size = layout->symbol_version<ELF_T>();
const uint64_t osize = binary_->sizing_info_->versym;
const bool should_relocate = symver_needed_size > osize || config_.force_relocate;
if (should_relocate) {
LIEF_DEBUG("[-] Need to relocate DT_VERSYM (0x{:x} new bytes)", symver_needed_size - osize);
layout->relocate_symver(symver_needed_size);
} else { LIEF_DEBUG("DT_VERSYM: -0x{:x} bytes", osize - symver_needed_size); }
}
if (binary_->has(DYNAMIC_TAGS::DT_VERDEF) && config_.sym_verdef) {
const size_t symvdef_needed_size = layout->symbol_vdef_size<ELF_T>();
const uint64_t osize = binary_->sizing_info_->verdef;
const bool should_relocate = symvdef_needed_size > osize || config_.force_relocate;
if (should_relocate) {
LIEF_DEBUG("[-] Need to relocate DT_VERDEF (0x{:x} new bytes)", symvdef_needed_size - osize);
layout->relocate_symverd(symvdef_needed_size);
} else { LIEF_DEBUG("DT_VERDEF: -0x{:x} bytes", osize - symvdef_needed_size); }
}
if (binary_->has(DYNAMIC_TAGS::DT_VERNEED) && config_.sym_verneed) {
const size_t symvreq_needed_size = layout->symbol_vreq_size<ELF_T>();
const uint64_t osize = binary_->sizing_info_->verneed;
const bool should_relocate = symvreq_needed_size > osize || config_.force_relocate;
if (should_relocate) {
LIEF_DEBUG("[-] Need to relocate DT_VERNEED (0x{:x} new bytes)", symvreq_needed_size - osize);
layout->relocate_symverr(symvreq_needed_size);
} else { LIEF_DEBUG("DT_VERNEED: -0x{:x} bytes", osize - symvreq_needed_size); }
}
const Header& header = binary_->header();
if (header.section_name_table_idx() > 0 && !binary_->sections_.empty() ) {
if (header.section_name_table_idx() >= binary_->sections_.size()) {
LIEF_ERR("Section string table out of bound");
} else {
std::unique_ptr<Section>& string_names_section = binary_->sections_[header.section_name_table_idx()];
const size_t shstr_size = layout->section_shstr_size();
if (shstr_size > string_names_section->size() || config_.force_relocate) {
LIEF_DEBUG("[-] Need to relocate '{}' section (0x{:x} new bytes)",
string_names_section->name(), shstr_size - string_names_section->size());
layout->relocate_shstr(true);
}
}
}
// Check if we should relocate or create the .strtab section
Section* sec_symtab = binary_->get(ELF_SECTION_TYPES::SHT_SYMTAB);
if (!layout->is_strtab_shared_shstrtab() && !binary_->static_symbols_.empty()) {
// There is no .symtab section => create .strtab
if (sec_symtab == nullptr) {
// Required since it writes the .strtab content in cache
LIEF_DEBUG("[-] Missing .symtab, need to relocate the .strtab section");
layout->relocate_strtab(layout->section_strtab_size());
} else {
// The .symtab exists
const auto sections = binary_->sections();
const size_t strtab_idx = sec_symtab->link();
if (strtab_idx == 0 || strtab_idx >= sections.size()) {
LIEF_ERR("The .strtab index seems corrupted");
layout->relocate_strtab(layout->section_strtab_size());
} else {
Section& strtab = sections[strtab_idx];
const size_t strtab_needed_size = layout->section_strtab_size();
if (strtab_needed_size > strtab.size() || config_.force_relocate) {
LIEF_DEBUG("[-] Need to relocate .strtab section (0x{:x} new bytes)",
strtab_needed_size - strtab.size());
layout->relocate_strtab(layout->section_strtab_size());
}
LIEF_DEBUG("strtab section: {}", strtab.name());
layout->set_strtab_section(strtab);
}
}
}
if (sec_symtab != nullptr) {
const size_t needed_size = layout->static_sym_size<ELF_T>();
if (needed_size > sec_symtab->size() || config_.force_relocate) {
LIEF_DEBUG("[-] Need to relocate '{}' section (0x{:x} new bytes)",
sec_symtab->name(), needed_size - sec_symtab->size());
layout->relocate_symtab(needed_size);
}
}
else if (!binary_->static_symbols_.empty()) {
// In this case the binary was stripped but the user
// added symbols => We have to craft a new section that will contain the symtab
LIEF_DEBUG("Need to create a new .symtab section");
const size_t needed_size = layout->static_sym_size<ELF_T>();
layout->relocate_symtab(needed_size);
}
auto res = layout->relocate();
if (!res) {
LIEF_ERR("Failing to create a new layout for this binary");
return make_error_code(lief_errors::build_error);
}
// ----------------------------------------------------------------
// At this point all the VAs are consistent with the new layout
// and we have enough space to write ELF elements
// ----------------------------------------------------------------
if (config_.gnu_hash || config_.dt_hash) {
LIEF_SW_START(sw);
build_hash_table<ELF_T>();
LIEF_SW_END("hast table built in {}", duration_cast<std::chrono::milliseconds>(sw.elapsed()));
}
if (config_.dyn_str) {
if (DynamicEntry* dt_strtab = binary_->get(DYNAMIC_TAGS::DT_STRTAB)) {
binary_->patch_address(dt_strtab->value(), layout->raw_dynstr());
}
}
if (config_.interpreter && binary_->has(SEGMENT_TYPES::PT_INTERP)) {
LIEF_SW_START(sw);
build_interpreter<ELF_T>();
LIEF_SW_END(".interp built in {}", duration_cast<std::chrono::milliseconds>(sw.elapsed()));
}
if (config_.notes && binary_->has(SEGMENT_TYPES::PT_NOTE)) {
LIEF_SW_START(sw);
build_notes<ELF_T>();
LIEF_SW_END(".note built in {}", duration_cast<std::chrono::milliseconds>(sw.elapsed()));
}
if (config_.dynamic_section && binary_->has(SEGMENT_TYPES::PT_DYNAMIC)) {
LIEF_SW_START(sw);
build_dynamic_section<ELF_T>();
LIEF_SW_END(".dynamic built in {}", duration_cast<std::chrono::milliseconds>(sw.elapsed()));
}
if (config_.symtab && binary_->has(DYNAMIC_TAGS::DT_SYMTAB)) {
LIEF_SW_START(sw);
build_dynamic_symbols<ELF_T>();
LIEF_SW_END(".dynsym built in {}", duration_cast<std::chrono::milliseconds>(sw.elapsed()));
}
if (config_.sym_versym && binary_->has(DYNAMIC_TAGS::DT_VERSYM)) {
LIEF_SW_START(sw);
build_symbol_version<ELF_T>();
LIEF_SW_END(".gnu.version built in {}", duration_cast<std::chrono::milliseconds>(sw.elapsed()));
}
if (config_.sym_verdef && binary_->has(DYNAMIC_TAGS::DT_VERDEF)) {
LIEF_SW_START(sw);
build_symbol_definition<ELF_T>();
LIEF_SW_END(".gnu.version_d built in {}", duration_cast<std::chrono::milliseconds>(sw.elapsed()));
}
if (config_.sym_verneed && binary_->has(DYNAMIC_TAGS::DT_VERNEED)) {
LIEF_SW_START(sw);
build_symbol_requirement<ELF_T>();
LIEF_SW_END(".gnu.version_r built in {}", duration_cast<std::chrono::milliseconds>(sw.elapsed()));
}
if (config_.rela) {
LIEF_SW_START(sw);
build_dynamic_relocations<ELF_T>();
LIEF_SW_END(".rela.dyn built in {}", duration_cast<std::chrono::milliseconds>(sw.elapsed()));
}
if (config_.jmprel) {
LIEF_SW_START(sw);
build_pltgot_relocations<ELF_T>();
LIEF_SW_END(".rela.plt built in {}", duration_cast<std::chrono::milliseconds>(sw.elapsed()));
}
if (config_.static_symtab && binary_->has(ELF_SECTION_TYPES::SHT_SYMTAB)) {
LIEF_SW_START(sw);
build_static_symbols<ELF_T>();
LIEF_SW_END(".symtab built in {}", duration_cast<std::chrono::milliseconds>(sw.elapsed()));
}
// Build sections
if (!binary_->sections_.empty()) {
build_sections<ELF_T>();
}
// Build PHDR
if (binary_->header().program_headers_offset() > 0) {
build_segments<ELF_T>();
} else {
LIEF_WARN("Segments offset is null");
}
build<ELF_T>(binary_->header());
build_overlay<ELF_T>();
return ok();
}
template<class ELF_T>
ok_error_t Builder::process_object_relocations() {
auto* layout = static_cast<ObjectFileLayout*>(layout_.get());
const auto it_relocations = binary_->object_relocations();
if (it_relocations.empty()) {
LIEF_DEBUG("No relocations. Nothing to do");
return ok();
}
using Elf_Rela = typename ELF_T::Elf_Rela;
using Elf_Rel = typename ELF_T::Elf_Rel;
bool is_rela = it_relocations[0].is_rela();
const size_t sizeof_rel = is_rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
const auto sections = binary_->sections();
ObjectFileLayout::sections_reloc_map_t& sections_reloc_map = layout->sections_reloc_map();
ObjectFileLayout::relocations_map_t& relocations_map = layout->relocation_map();
ObjectFileLayout::rel_sections_size_t& rel_sections_size = layout->rel_sections_size();
for (Section& sec : sections) {
const ELF_SECTION_TYPES type = sec.type();
if (type != ELF_SECTION_TYPES::SHT_RELA && type != ELF_SECTION_TYPES::SHT_REL) {
continue;
}
const size_t sh_info = sec.information();
if (sh_info == 0 || sh_info >= sections.size()) {
LIEF_WARN("Relocation index for section '{}' is corrupted");
continue;
}
Section& associated = sections[sh_info];
sections_reloc_map[&associated] = &sec; // e.g (.text, .text.rela)
}
for (Relocation& reloc : it_relocations) {
Section* sec = reloc.section();
if (sec == nullptr) {
LIEF_WARN("Relocation @0x{:x} misses a section", reloc.address());
continue;
}
LIEF_DEBUG("Section for reloc 0x{:x} -> {}", reloc.address(), sec->name());
relocations_map[sec].push_back(&reloc);
auto it_reloc_sec = sections_reloc_map.find(sec);
if (it_reloc_sec == std::end(sections_reloc_map)) {
LIEF_WARN("Can find the relocation section associated with '{}'", sec->name());
continue;
}
Section* reloc_section = it_reloc_sec->second;
rel_sections_size[reloc_section] += sizeof_rel;
}
for (const auto& p : rel_sections_size) {
const Section* section = p.first;
const size_t need_size = p.second;
if (need_size > section->size()) {
LIEF_DEBUG("Need to relocate '{}'", section->name());
layout->relocate_section(*section, need_size);
}
}
return ok();
}
template<class ELF_T>
ok_error_t Builder::build_relocatable() {
auto* layout = static_cast<ObjectFileLayout*>(layout_.get());
Header& header = binary_->header();
uint32_t new_symndx = sort_dynamic_symbols();
layout->set_dyn_sym_idx(new_symndx);
// Check if we should relocate the .shstrtab
if (header.section_name_table_idx() > 0) {
if (header.section_name_table_idx() >= binary_->sections_.size()) {
LIEF_ERR("Section string table out of bound");
return make_error_code(lief_errors::file_format_error);
}
std::unique_ptr<Section>& string_names_section = binary_->sections_[header.section_name_table_idx()];
const size_t shstr_size = layout->section_shstr_size();
if (shstr_size > string_names_section->size() || config_.force_relocate) {
LIEF_DEBUG("[-] Need to relocate '{}' section (0x{:x} new bytes)",
string_names_section->name(), shstr_size - string_names_section->size());
layout->relocate_section(*string_names_section, shstr_size);
}
}
// Check the .symtab section
Section* symtab = binary_->get(ELF_SECTION_TYPES::SHT_SYMTAB);
if (symtab != nullptr) {
const size_t needed_size = layout->symtab_size<ELF_T>();
if (needed_size > symtab->size() || config_.force_relocate) {
LIEF_DEBUG("[-] Need to relocate '{}' section (0x{:x} new bytes)",
symtab->name(), symtab->size() - needed_size);
layout->relocate_section(*symtab, needed_size);
}
}
// Check if we should relocate or create a .strtab section.
// We assume that a .shstrtab is always prensent
if (!layout->is_strtab_shared_shstrtab() && !binary_->static_symbols_.empty()) {
Section* sec_symtab = binary_->get(ELF_SECTION_TYPES::SHT_SYMTAB);
if (sec_symtab == nullptr) {
LIEF_ERR("Object file without a symtab section is not supported. Please consider submitting an issue.");
return make_error_code(lief_errors::not_supported);
}
// The .symtab exists
const auto sections = binary_->sections();
const size_t strtab_idx = sec_symtab->link();
if (strtab_idx == 0 || strtab_idx >= sections.size()) {
LIEF_ERR("The .strtab index is corrupted");
} else {
Section& strtab = sections[strtab_idx];
const size_t strtab_needed_size = layout->section_strtab_size();
if (strtab_needed_size > strtab.size() || config_.force_relocate) {
LIEF_DEBUG("[-] Need to relocate .strtab section (0x{:x} new bytes)",
strtab_needed_size - strtab.size());
layout->relocate_section(strtab, strtab_needed_size);
}
layout->set_strtab_section(strtab);
}
}
process_object_relocations<ELF_T>();
auto res = layout->relocate();
if (!res) {
LIEF_ERR("Error(s) occurred during the layout relocation.");
return make_error_code(lief_errors::build_error);
}
if (binary_->has(ELF_SECTION_TYPES::SHT_SYMTAB)) {
build_obj_symbols<ELF_T>();
}
build_section_relocations<ELF_T>();
// Since object file only have sections, we don't have to process segments
if (!binary_->sections_.empty()) {
build_sections<ELF_T>();
}
build<ELF_T>(binary_->header());
build_overlay<ELF_T>();
return ok();
}
template<typename ELF_T>
ok_error_t Builder::build(const Header& header) {;
using Elf_Half = typename ELF_T::Elf_Half;
using Elf_Word = typename ELF_T::Elf_Word;
using Elf_Addr = typename ELF_T::Elf_Addr;
using Elf_Off = typename ELF_T::Elf_Off;
using Elf_Word = typename ELF_T::Elf_Word;
using Elf_Ehdr = typename ELF_T::Elf_Ehdr;
Elf_Ehdr ehdr;
ehdr.e_type = static_cast<Elf_Half>(header.file_type());
ehdr.e_machine = static_cast<Elf_Half>(header.machine_type());
ehdr.e_version = static_cast<Elf_Word>(header.object_file_version());
ehdr.e_entry = static_cast<Elf_Addr>(header.entrypoint());
ehdr.e_phoff = static_cast<Elf_Off>(header.program_headers_offset());
ehdr.e_shoff = static_cast<Elf_Off>(header.section_headers_offset());
ehdr.e_flags = static_cast<Elf_Word>(header.processor_flag());
ehdr.e_ehsize = static_cast<Elf_Half>(header.header_size());
ehdr.e_phentsize = static_cast<Elf_Half>(header.program_header_size());
ehdr.e_phnum = static_cast<Elf_Half>(header.numberof_segments());
ehdr.e_shentsize = static_cast<Elf_Half>(header.section_header_size());
ehdr.e_shnum = static_cast<Elf_Half>(header.numberof_sections());
ehdr.e_shstrndx = static_cast<Elf_Half>(header.section_name_table_idx());
std::copy(std::begin(header.identity()), std::end(header.identity()),
std::begin(ehdr.e_ident));
ios_.seekp(0);
ios_.write_conv<Elf_Ehdr>(ehdr);
return ok();
}
template<typename ELF_T>
ok_error_t Builder::build_sections() {
using Elf_Word = typename ELF_T::Elf_Word;
using Elf_Addr = typename ELF_T::Elf_Addr;
using Elf_Off = typename ELF_T::Elf_Off;
using Elf_Word = typename ELF_T::Elf_Word;
using Elf_Shdr = typename ELF_T::Elf_Shdr;
if (binary_->sections_.empty()) {
return ok();
}
LIEF_DEBUG("[+] Build sections");
const Header& header = binary_->header();
const Elf_Off section_headers_offset = header.section_headers_offset();
if (section_headers_offset == 0) {
return ok();
}
if (header.section_name_table_idx() < binary_->sections_.size()) {
std::unique_ptr<Section>& string_names_section = binary_->sections_[header.section_name_table_idx()];
string_names_section->content(layout_->raw_shstr());
}
const std::unordered_map<std::string, size_t>& shstr_map = layout_->shstr_map();
for (size_t i = 0; i < binary_->sections_.size(); ++i) {
const std::unique_ptr<Section>& section = binary_->sections_[i];
LIEF_DEBUG("[FRAME ] {}", section->is_frame());
if (!section->is_frame() &&
section->size() > 0 &&
section->file_offset() > 0 &&
// SHT_NOTBITS sections should not be considered.
// Nevertheless, some (malformed or tricky) ELF binaries
// might use this type to put content.
section->type() != ELF_SECTION_TYPES::SHT_NOBITS) {
span<const uint8_t> content = section->content();
LIEF_DEBUG("[Content] {:20}: 0x{:010x} - 0x{:010x} (0x{:x})",
section->name(), section->file_offset(),
section->file_offset() + content.size(), content.size());
ios_.seekp(section->file_offset());
ios_.write(content);
}
Elf_Off offset_name = 0;
const auto& it = shstr_map.find(section->name());
if (it == std::end(shstr_map)) {
LIEF_WARN("Can't find string offset for section name '{}'", section->name());
} else {
offset_name = it->second;
}
Elf_Shdr shdr;
shdr.sh_name = static_cast<Elf_Word>(offset_name);
shdr.sh_type = static_cast<Elf_Word>(section->type());
shdr.sh_flags = static_cast<Elf_Word>(section->flags());
shdr.sh_addr = static_cast<Elf_Addr>(section->virtual_address());
shdr.sh_offset = static_cast<Elf_Off>(section->file_offset());
shdr.sh_size = static_cast<Elf_Word>(section->size());
shdr.sh_link = static_cast<Elf_Word>(section->link());
shdr.sh_info = static_cast<Elf_Word>(section->information());
shdr.sh_addralign = static_cast<Elf_Word>(section->alignment());
shdr.sh_entsize = static_cast<Elf_Word>(section->entry_size());
// Write Section'header
if (section_headers_offset > 0) {
const uint64_t offset = section_headers_offset + i * sizeof(Elf_Shdr);
LIEF_DEBUG("[Header ] {:20}: 0x{:010x} - 0x{:010x}",
section->name(),
offset, offset + sizeof(Elf_Shdr));
ios_.seekp(offset);
ios_.write_conv<Elf_Shdr>(shdr);
}
}
return ok();
}
template<typename ELF_T>
ok_error_t Builder::build_segments() {
using Elf_Word = typename ELF_T::Elf_Word;
using Elf_Addr = typename ELF_T::Elf_Addr;
using Elf_Off = typename ELF_T::Elf_Off;
using Elf_Word = typename ELF_T::Elf_Word;
using Elf_Phdr = typename ELF_T::Elf_Phdr;
LIEF_DEBUG("== Build segments ==");
vector_iostream pheaders(should_swap());
pheaders.reserve(binary_->segments_.size() * sizeof(Elf_Phdr));
LIEF_DEBUG("sizeof(PHDR): 0x{:x}", binary_->segments_.size() * sizeof(Elf_Phdr));
for (const std::unique_ptr<Segment>& segment : binary_->segments_) {
Elf_Phdr phdr;
phdr.p_type = static_cast<Elf_Word>(segment->type());
phdr.p_flags = static_cast<Elf_Word>(segment->flags());
phdr.p_offset = static_cast<Elf_Off>(segment->file_offset());
phdr.p_vaddr = static_cast<Elf_Addr>(segment->virtual_address());
phdr.p_paddr = static_cast<Elf_Addr>(segment->physical_address());
phdr.p_filesz = static_cast<Elf_Word>(segment->physical_size());
phdr.p_memsz = static_cast<Elf_Word>(segment->virtual_size());
phdr.p_align = static_cast<Elf_Word>(segment->alignment());
pheaders.write_conv<Elf_Phdr>(phdr);
}
Segment* phdr_segment = binary_->get(SEGMENT_TYPES::PT_PHDR);
if (phdr_segment != nullptr) {
phdr_segment->content(pheaders.raw());
}
// Write segment content
for (const std::unique_ptr<Segment>& segment : binary_->segments_) {
if (segment->physical_size() > 0) {
span<const uint8_t> content = segment->content();
LIEF_DEBUG("[W] {:<13} 0x{:016x}: 0x{:010x} - 0x{:010x} (0x{:x})",
to_string(segment->type()), segment->virtual_address(),
segment->file_offset(), segment->file_offset() + content.size(),
content.size());
ios_.seekp(segment->file_offset());
ios_.write(content);
}
}
const Elf_Off segment_header_offset = binary_->header().program_headers_offset();
LIEF_DEBUG("Write segments header 0x{} -> 0x{}",
segment_header_offset, segment_header_offset + pheaders.size());
ios_.seekp(segment_header_offset);
ios_.write(std::move(pheaders.raw()));
return ok();
}
template<typename ELF_T>
ok_error_t Builder::build_static_symbols() {
using Elf_Half = typename ELF_T::Elf_Half;
using Elf_Word = typename ELF_T::Elf_Word;
using Elf_Addr = typename ELF_T::Elf_Addr;
using Elf_Off = typename ELF_T::Elf_Off;
using Elf_Sym = typename ELF_T::Elf_Sym;
auto* layout = static_cast<ExeLayout*>(layout_.get());
LIEF_DEBUG("== Build static symbols ==");
Section* symbol_section = binary_->static_symbols_section();
if (symbol_section == nullptr) {
LIEF_ERR("Can't find the .symtab section");
return make_error_code(lief_errors::file_format_error);
}
LIEF_DEBUG(".symtab section: '{}'", symbol_section->name());
std::stable_sort(std::begin(binary_->static_symbols_), std::end(binary_->static_symbols_),
[](const std::unique_ptr<Symbol>& lhs, const std::unique_ptr<Symbol>& rhs) {
return lhs->binding() == SYMBOL_BINDINGS::STB_LOCAL &&
(
rhs->binding() == SYMBOL_BINDINGS::STB_GLOBAL ||
rhs->binding() == SYMBOL_BINDINGS::STB_WEAK
);
});
const auto it_first_exported_symbol =
std::find_if(std::begin(binary_->static_symbols_), std::end(binary_->static_symbols_),
[](const std::unique_ptr<Symbol>& sym) {
return sym->is_exported();
});
const auto first_exported_symbol_index =
static_cast<uint32_t>(std::distance(std::begin(binary_->static_symbols_), it_first_exported_symbol));
if (first_exported_symbol_index != symbol_section->information()) {
LIEF_INFO("information of .symtab section changes from {:d} to {:d}",
symbol_section->information(),
first_exported_symbol_index);
symbol_section->information(first_exported_symbol_index);
}
if (symbol_section->link() == 0 || symbol_section->link() >= binary_->sections_.size()) {
LIEF_ERR("Unable to find a string section associated with the symbol section (sh_link)");
return make_error_code(lief_errors::file_format_error);
}
vector_iostream content(should_swap());
content.reserve(layout->static_sym_size<ELF_T>());
// On recent compilers, the symtab string table is merged with the section name table
const std::unordered_map<std::string, size_t>* str_map = nullptr;
if (layout->is_strtab_shared_shstrtab()) {
str_map = &layout->shstr_map();
} else {
str_map = &layout->strtab_map();
}
for (const std::unique_ptr<Symbol>& symbol : binary_->static_symbols_) {
const std::string& name = symbol->name();
Elf_Off offset_name = 0;
const auto it = str_map->find(name);
if (it == std::end(*str_map)) {
LIEF_ERR("Can't find string offset for static symbol name '{}'", name);
} else {
offset_name = it->second;
}
Elf_Sym sym_hdr;
memset(&sym_hdr, 0, sizeof(Elf_Sym));
sym_hdr.st_name = static_cast<Elf_Word>(offset_name);
sym_hdr.st_info = static_cast<unsigned char>(symbol->information());
sym_hdr.st_other = static_cast<unsigned char>(symbol->other());
sym_hdr.st_shndx = static_cast<Elf_Half>(symbol->shndx());
sym_hdr.st_value = static_cast<Elf_Addr>(symbol->value());
sym_hdr.st_size = static_cast<Elf_Word>(symbol->size());
content.write_conv<Elf_Sym>(sym_hdr);
}
symbol_section->content(std::move(content.raw()));
return ok();
}
template<typename ELF_T>
ok_error_t Builder::build_dynamic_section() {
using Elf_Addr = typename ELF_T::Elf_Addr;
using Elf_Sxword = typename ELF_T::Elf_Sxword;
using Elf_Xword = typename ELF_T::Elf_Xword;
using Elf_Dyn = typename ELF_T::Elf_Dyn;
LIEF_DEBUG("[+] Building .dynamic");
const auto& dynstr_map = static_cast<ExeLayout*>(layout_.get())->dynstr_map();
vector_iostream dynamic_table_raw;
for (std::unique_ptr<DynamicEntry>& entry : binary_->dynamic_entries_) {
switch (entry->tag()) {
case DYNAMIC_TAGS::DT_NEEDED:
{
const std::string& name = entry->as<DynamicEntryLibrary>()->name();
const auto& it = dynstr_map.find(name);
if (it == std::end(dynstr_map)) {
LIEF_ERR("Can't find string offset in .dynstr for {}", name);
break;
}
entry->value(it->second);
break;
}
case DYNAMIC_TAGS::DT_SONAME:
{
const std::string& name = entry->as<DynamicSharedObject>()->name();
const auto& it = dynstr_map.find(name);
if (it == std::end(dynstr_map)) {
LIEF_ERR("Can't find string offset in .dynstr for {}", name);
break;
}
entry->value(it->second);
break;
}
case DYNAMIC_TAGS::DT_RPATH:
{
const std::string& name = entry->as<DynamicEntryRpath>()->name();
const auto& it = dynstr_map.find(name);
if (it == std::end(dynstr_map)) {
LIEF_ERR("Can't find string offset in .dynstr for {}", name);
break;
}
entry->value(it->second);
break;
}
case DYNAMIC_TAGS::DT_RUNPATH:
{
const std::string& name = entry->as<DynamicEntryRunPath>()->name();
const auto& it = dynstr_map.find(name);
if (it == std::end(dynstr_map)) {
LIEF_ERR("Can't find string offset in .dynstr for {}", name);
break;
}
entry->value(it->second);
break;
}
case DYNAMIC_TAGS::DT_INIT_ARRAY:
{
if (config_.init_array) {
DynamicEntry* dt_array_size = binary_->get(DYNAMIC_TAGS::DT_INIT_ARRAYSZ);
if (dt_array_size == nullptr) {
LIEF_ERR("Can't find the DT_INIT_ARRAYSZ / .init_array");
break;
}
const std::vector<uint64_t>& array = entry->as<DynamicEntryArray>()->array();
std::vector<uint8_t> array_content(array.size() * sizeof(Elf_Addr), 0);
auto* raw_array = reinterpret_cast<Elf_Addr*>(array_content.data());
for (size_t i = 0; i < array.size(); ++i) {
raw_array[i] = static_cast<Elf_Addr>(array[i]);
}
dt_array_size->value(array_content.size());
binary_->patch_address(entry->value(), array_content);
}
break;
}
case DYNAMIC_TAGS::DT_FINI_ARRAY:
{
if (config_.fini_array) {
DynamicEntry* dt_array_size = binary_->get(DYNAMIC_TAGS::DT_FINI_ARRAYSZ);
if (dt_array_size == nullptr) {
LIEF_ERR("Can't find the DT_FINI_ARRAYSZ / .fini_array");
break;
}
const std::vector<uint64_t>& array = entry->as<DynamicEntryArray>()->array();
std::vector<uint8_t> array_content(array.size() * sizeof(Elf_Addr), 0);
auto* raw_array = reinterpret_cast<Elf_Addr*>(array_content.data());
for (size_t i = 0; i < array.size(); ++i) {
raw_array[i] = static_cast<Elf_Addr>(array[i]);
}
dt_array_size->value(array_content.size());
binary_->patch_address(entry->value(), array_content);
}
break;
}
case DYNAMIC_TAGS::DT_PREINIT_ARRAY:
{
if (config_.fini_array) {
DynamicEntry* dt_array_size = binary_->get(DYNAMIC_TAGS::DT_PREINIT_ARRAYSZ);
if (dt_array_size == nullptr) {
LIEF_ERR("Can't find the DT_PREINIT_ARRAYSZ / .preinit_array");
break;
}
const std::vector<uint64_t>& array = entry->as<DynamicEntryArray>()->array();
std::vector<uint8_t> array_content(array.size() * sizeof(Elf_Addr), 0);
auto* raw_array = reinterpret_cast<Elf_Addr*>(array_content.data());
for (size_t i = 0; i < array.size(); ++i) {
raw_array[i] = static_cast<Elf_Addr>(array[i]);
}
dt_array_size->value(array_content.size());
binary_->patch_address(entry->value(), array_content);
}
break;
}
default:
{
// TODO(romain): Support DT_AUXILIARY
}
}
Elf_Dyn dynhdr;