forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuilder.cpp
More file actions
1266 lines (1070 loc) · 41.5 KB
/
Copy pathBuilder.cpp
File metadata and controls
1266 lines (1070 loc) · 41.5 KB
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 - 2025 R. Thomas
* Copyright 2017 - 2025 Quarkslab
*
* 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 <cstring>
#include <algorithm>
#include <fstream>
#include <iterator>
#include "logging.hpp"
#include "LIEF/PE/Builder.hpp"
#include "LIEF/PE/ResourceData.hpp"
#include "LIEF/PE/utils.hpp"
#include "LIEF/PE/ImportEntry.hpp"
#include "LIEF/PE/Import.hpp"
#include "LIEF/PE/Debug.hpp"
#include "LIEF/PE/debug/PDBChecksum.hpp"
#include "LIEF/PE/debug/ExDllCharacteristics.hpp"
#include "LIEF/PE/debug/FPO.hpp"
#include "LIEF/PE/Section.hpp"
#include "LIEF/PE/ResourceDirectory.hpp"
#include "LIEF/PE/DataDirectory.hpp"
#include "LIEF/PE/Relocation.hpp"
#include "LIEF/PE/RelocationEntry.hpp"
#include "LIEF/PE/Export.hpp"
#include "LIEF/PE/ExportEntry.hpp"
#include "LIEF/utils.hpp"
#include "PE/Structures.hpp"
#include "Builder.tcc"
#include "internal_utils.hpp"
namespace LIEF {
namespace PE {
Builder::~Builder() = default;
void Builder::write(const std::string& filename) const {
static constexpr auto DEFAULT_MODE = std::ios::out |
std::ios::binary |
std::ios::trunc;
std::ofstream output_file(filename, DEFAULT_MODE);
if (!output_file) {
LIEF_ERR("Can't write in {}", filename);
return;
}
write(output_file);
}
void Builder::write(std::ostream& os) const {
std::vector<uint8_t> content;
ios_.move(content);
os.write(reinterpret_cast<const char*>(content.data()), content.size());
}
ok_error_t Builder::build() {
LIEF_DEBUG("Build process started");
const bool is_64bit = binary_->type() == PE_TYPE::PE32_PLUS;
if (config_.tls) {
// TLS reconstruction could change relocations. Thus, it needs to be done
// BEFORE build_relocations. Moreover, because of some relocation
// optimization, it should be done as early as possible.
auto res = is_64bit ? build_tls<details::PE64>() :
build_tls<details::PE32>();
if (!res) {
LIEF_WARN("Something went wrong while re-building TLS: {}",
to_string(res.error()));
}
}
if (config_.resources) {
auto is_ok = build_resources();
if (!is_ok) {
LIEF_WARN("Something went wrong while re-building resource tree: {}",
to_string(is_ok.error()));
}
}
if (config_.relocations) {
auto is_ok = build_relocations();
if (!is_ok) {
LIEF_WARN("Something went wrong while re-building relocations: {}",
to_string(is_ok.error()));
}
}
if (config_.imports) {
auto is_ok = is_64bit ? build_imports<details::PE64>() :
build_imports<details::PE32>();
if (!is_ok) {
LIEF_WARN("Something went wrong while re-building imports: {}",
to_string(is_ok.error()));
}
}
if (config_.exports) {
auto is_ok = build_exports();
if (!is_ok) {
LIEF_WARN("Something went wrong while re-building exports: {}",
to_string(is_ok.error()));
}
}
if (config_.load_configuration) {
auto is_ok = is_64bit ? build_load_config<details::PE64>() :
build_load_config<details::PE32>();
if (!is_ok) {
LIEF_WARN("Something went wrong while re-building load config: {}",
to_string(is_ok.error()));
}
}
if (config_.debug) {
auto is_ok = build_debug_info();
if (!is_ok) {
LIEF_WARN("Something went wrong while re-building debug entries: {}",
to_string(is_ok.error()));
}
}
auto is_ok = build(binary_->dos_header());
if (!is_ok) {
LIEF_WARN("Something went wrong while re-building DOS header: {}",
to_string(is_ok.error()));
}
is_ok = build(binary_->header());
if (!is_ok) {
LIEF_WARN("Something went wrong while re-building regular header: {}",
to_string(is_ok.error()));
}
is_ok = build(binary_->optional_header());
if (!is_ok) {
LIEF_WARN("Something went wrong while re-building optional header: {}",
to_string(is_ok.error()));
}
for (const DataDirectory& dir : binary_->data_directories()) {
auto is_ok = build(dir);
if (!is_ok) {
LIEF_WARN("Something went wrong while re-building data directory '{}': {}",
to_string(dir.type()), to_string(is_ok.error()));
}
}
for (const Section& sec : binary_->sections()) {
auto is_ok = build(sec);
if (!is_ok) {
LIEF_WARN("Something went wrong while re-building section '{}': {}",
sec.name(), to_string(is_ok.error()));
}
}
if (!binary_->overlay().empty() && config_.overlay) {
build_overlay();
}
return ok();
}
ok_error_t Builder::build(const DosHeader& dos_header) {
vector_iostream dos_hdr_strm;
dos_hdr_strm.reserve(sizeof(details::pe_dos_header));
dos_hdr_strm
.write<uint16_t>(dos_header.magic())
.write<uint16_t>(dos_header.used_bytes_in_last_page())
.write<uint16_t>(dos_header.file_size_in_pages())
.write<uint16_t>(dos_header.numberof_relocation())
.write<uint16_t>(dos_header.header_size_in_paragraphs())
.write<uint16_t>(dos_header.minimum_extra_paragraphs())
.write<uint16_t>(dos_header.maximum_extra_paragraphs())
.write<uint16_t>(dos_header.initial_relative_ss())
.write<uint16_t>(dos_header.initial_sp())
.write<uint16_t>(dos_header.checksum())
.write<uint16_t>(dos_header.initial_ip())
.write<uint16_t>(dos_header.initial_relative_cs())
.write<uint16_t>(dos_header.addressof_relocation_table())
.write<uint16_t>(dos_header.overlay_number())
.write<uint16_t>(dos_header.reserved())
.write<uint16_t>(dos_header.oem_id())
.write<uint16_t>(dos_header.oem_info())
.write<uint16_t>(dos_header.reserved2())
.write<uint32_t>(dos_header.addressof_new_exeheader())
;
assert(dos_hdr_strm.size() == sizeof(details::pe_dos_header));
ios_.seekp(0);
ios_.write(dos_hdr_strm);
if (!binary_->dos_stub().empty() && config_.dos_stub) {
const uint64_t e_lfanew = sizeof(details::pe_dos_header) +
binary_->dos_stub().size();
if (e_lfanew > dos_header.addressof_new_exeheader()) {
LIEF_WARN("Inconsistent 'addressof_new_exeheader': 0x{:x}",
dos_header.addressof_new_exeheader());
} else {
ios_.write(binary_->dos_stub());
}
}
return ok();
}
ok_error_t Builder::build(const Header& header) {
vector_iostream pe_hdr_strm;
pe_hdr_strm.reserve(sizeof(details::pe_header));
pe_hdr_strm
.write(header.signature())
.write<uint16_t>((int)header.machine())
.write<uint16_t>(binary_->sections_.size())
.write<uint32_t>(header.time_date_stamp())
.write<uint32_t>(header.pointerto_symbol_table())
.write<uint32_t>(header.numberof_symbols())
.write<uint16_t>(header.sizeof_optional_header())
.write<uint16_t>(header.characteristics())
;
assert(pe_hdr_strm.size() == sizeof(details::pe_header));
ios_
.seekp(binary_->dos_header().addressof_new_exeheader())
.write(pe_hdr_strm);
return ok();
}
ok_error_t Builder::build(const OptionalHeader& optional_header) {
return binary_->type() == PE_TYPE::PE32 ?
build_optional_header<details::PE32>(optional_header) :
build_optional_header<details::PE64>(optional_header);
}
ok_error_t Builder::build(const DataDirectory& data_directory) {
ios_
.write<uint32_t>(data_directory.RVA())
.write<uint32_t>(data_directory.size());
return ok();
}
ok_error_t Builder::build(const Section& section) {
std::array<char, 8> section_name;
std::memset(section_name.data(), 0, section_name.size());
const std::string& sec_name = section.fullname();
uint32_t name_length = std::min<uint32_t>(sec_name.size() + 1, section_name.size());
std::copy(sec_name.c_str(), sec_name.c_str() + name_length,
std::begin(section_name));
ios_
.increase_capacity(sizeof(details::pe_section))
.write(section_name)
.write<uint32_t>(section.virtual_size())
.write<uint32_t>(section.virtual_address())
.write<uint32_t>(section.size())
.write<uint32_t>(section.pointerto_raw_data())
.write<uint32_t>(section.pointerto_relocation())
.write<uint32_t>(section.pointerto_line_numbers())
.write<uint16_t>(section.numberof_relocations())
.write<uint16_t>(section.numberof_line_numbers())
.write<uint32_t>(section.characteristics())
;
size_t pad_length = 0;
if (section.content().size() > section.size()) {
LIEF_WARN("{} content size is bigger than section's header size",
section.name());
}
else {
pad_length = section.size() - section.content().size();
}
{
ScopeOStream scoped(ios_, section.offset());
(*scoped)
.write(section.content())
.pad(pad_length);
}
return ok();
}
ok_error_t Builder::build_overlay() {
const uint64_t last_section_offset = binary_->last_section_offset();
LIEF_DEBUG("Overlay offset: 0x{:x}", last_section_offset);
LIEF_DEBUG("Overlay size: 0x{:x}", binary_->overlay().size());
ScopeOStream scoped(ios_, last_section_offset);
(*scoped)
.write(binary_->overlay());
return ok();
}
ok_error_t Builder::build_relocations() {
vector_iostream ios;
DataDirectory* reloc_dir = binary_->relocation_dir();
const uint32_t original_size = reloc_dir->size();
ios.reserve(original_size);
for (const Relocation& reloc : binary_->relocations()) {
if (reloc.entries_.empty()) {
continue;
}
const uint32_t block_size =
static_cast<uint32_t>((reloc.entries().size()) * sizeof(uint16_t) +
sizeof(details::pe_base_relocation_block));
ios
.write<uint32_t>(reloc.virtual_address())
.write<uint32_t>(align(block_size, sizeof(uint32_t)))
;
for (const RelocationEntry& entry : reloc.entries()) {
ios.write(entry.data());
}
}
ios
.align(sizeof(uint32_t))
.move(reloc_data_);
if (reloc_data_.size() > original_size || config_.force_relocating) {
LIEF_DEBUG("Need to relocated BASE_RELOCATION_TABLE (0x{:06x} new bytes)",
reloc_data_.size() - original_size);
Section reloc_section(config_.reloc_section);
const size_t relocated_size =
align(reloc_data_.size(), binary_->optional_header().file_alignment());
reloc_section
.reserve(relocated_size)
.add_characteristic(Section::CHARACTERISTICS::CNT_INITIALIZED_DATA)
.add_characteristic(Section::CHARACTERISTICS::MEM_READ)
.add_characteristic(Section::CHARACTERISTICS::MEM_DISCARDABLE);
Section* new_reloc_section = binary_->add_section(reloc_section);
new_reloc_section->edit().write(reloc_data_);
reloc_dir->RVA(new_reloc_section->virtual_address());
reloc_dir->size(reloc_data_.size());
} else {
LIEF_DEBUG("BASE_RELOCATION_TABLE -0x{:06x}",
original_size - reloc_data_.size());
binary_->patch_address(reloc_dir->RVA(), reloc_data_);
}
return ok();
}
ok_error_t Builder::build_resources() {
DataDirectory* rsrc_dir = binary_->rsrc_dir();
ResourceNode* node = binary_->resources();
if (node == nullptr) {
if (rsrc_dir->RVA() == 0 && rsrc_dir->size() == 0) {
return ok();
}
binary_->fill_address(rsrc_dir->RVA(), rsrc_dir->size());
rsrc_dir->RVA(0);
rsrc_dir->size(0);
return ok();
}
rsrc_sizing_info_t sizes_info;
if (!compute_resources_size(*node, sizes_info)) {
return make_error_code(lief_errors::build_error);
}
vector_iostream rsrc_stream;
rsrc_build_context_t ctx;
ctx.offset_header = 0;
ctx.offset_name = ctx.offset_header + sizes_info.header_size;
ctx.offset_data = align(ctx.offset_name + sizes_info.name_size, 4);
LIEF_DEBUG(".rsrc[header].offset: 0x{:04x}", ctx.offset_header);
LIEF_DEBUG(".rsrc[names].offset: 0x{:04x}", ctx.offset_name);
LIEF_DEBUG(".rsrc[data].offset: 0x{:04x}", ctx.offset_data);
construct_resource(rsrc_stream, *node, ctx);
rsrc_stream.align(sizeof(uint32_t));
const uint32_t original_size = rsrc_dir->size();
const uint32_t new_size = rsrc_stream.size();
const uint32_t expected_size = align(sizes_info.data_size + sizes_info.header_size + sizes_info.name_size, 4);
LIEF_DEBUG("New size: new_size=0x{:016x} vs original_size=0x{:016x} vs expected_size=0x{:016x}", new_size, original_size, expected_size);
if (new_size > original_size || config_.force_relocating) {
const uint64_t delta = new_size - original_size;
LIEF_DEBUG("Need to relocate RESOURCE_TABLE (0x{:06x} new bytes)", delta);
Section* section = rsrc_dir->section();
if (section == nullptr) {
LIEF_ERR("Can't find section associated with the RESOURCE_TABLE");
return make_error_code(lief_errors::build_error);
}
// Note(romain): We could/should leverage this optimization:
//
// If the the `.rsrc` section has some kind of padding that is large
// enough, then we can use this area to avoid relocating the `.rsrc` location
//
// const bool padding_is_large = section->padding().size() >= delta;
// if (padding_is_large) {
// LIEF_DEBUG("large padding for new rsrc");
// // Now check that the rsrc content is at the "end" of the section
// const uint64_t rsrc_offset = binary_->rva_to_offset(rsrc_dir->RVA());
// const uint64_t section_size = section->virtual_size() > 0 ?
// std::min(section->virtual_size(), section->sizeof_raw_data()) :
// section->sizeof_raw_data();
// if ((section->offset() + section_size) - (rsrc_offset + original_size) == 0) {
// LIEF_ERR("ok");
// }
// }
rsrc_stream.align(binary_->optional_header().file_alignment());
Section rsrc_section(config_.rsrc_section);
rsrc_section.reserve(rsrc_stream.size());
rsrc_section
.add_characteristic(Section::CHARACTERISTICS::CNT_INITIALIZED_DATA)
.add_characteristic(Section::CHARACTERISTICS::MEM_READ);
// TODO(romain): Make sure we add this section before the FIRST
// MEM_DISCARDABLE section.
Section* new_rsrc_section = binary_->add_section(rsrc_section);
if (new_rsrc_section == nullptr) {
LIEF_ERR("Can't add a new rsrc section");
return make_error_code(lief_errors::build_error);
}
rsrc_dir->RVA(new_rsrc_section->virtual_address());
rsrc_dir->size(new_rsrc_section->size());
const uint64_t rsrc_rva = rsrc_dir->RVA();
for (uint64_t fixup : ctx.rva_fixups) {
rsrc_stream.reloc<uint32_t>(fixup, rsrc_rva, vector_iostream::RELOC_OP::ADD);
}
rsrc_stream.move(rsrc_data_);
new_rsrc_section->content(rsrc_data_);
return ok();
}
LIEF_DEBUG("RESOURCE_TABLE: -0x{:06x}", original_size - new_size);
// Fill the original content with 0
const uint64_t rva = rsrc_dir->RVA();
binary_->patch_address(
rva, std::vector<uint8_t>(original_size, 0), Binary::VA_TYPES::RVA);
const uint64_t rsrc_rva = rsrc_dir->RVA();
for (uint64_t fixup : ctx.rva_fixups) {
rsrc_stream.reloc<uint32_t>(fixup, rsrc_rva, vector_iostream::RELOC_OP::ADD);
}
rsrc_stream.move(rsrc_data_);
binary_->patch_address(rsrc_dir->RVA(), rsrc_data_, Binary::VA_TYPES::RVA);
rsrc_dir->size(rsrc_data_.size());
return ok();
}
ok_error_t Builder::compute_resources_size(
const ResourceNode& node, rsrc_sizing_info_t& info)
{
if (!node.name().empty() || node.has_name()) {
LIEF_DEBUG("{}", u16tou8(node.name()));
info.name_size += sizeof(uint16_t) + node.name().size() * sizeof(char16_t);
}
if (const auto* _ = node.cast<ResourceDirectory>()) {
info.header_size += sizeof(details::pe_resource_directory_table) +
sizeof(details::pe_resource_directory_entries) * node.childs().size();
for (const ResourceNode& child : node.childs()) {
compute_resources_size(child, info);
}
return ok();
}
if (const auto* data = node.cast<ResourceData>()) {
info.header_size += sizeof(details::pe_resource_data_entry);
info.data_size += align(data->content().size(), sizeof(uint32_t));
return ok();
}
return ok();
}
ok_error_t Builder::construct_resource(
vector_iostream& ios, ResourceDirectory& dir, rsrc_build_context_t& ctx)
{
LIEF_DEBUG("[rsrc] writing directory header at 0x{:04x} (depth={}, id={}, #children={})",
ctx.offset_header, dir.depth(), dir.id(), dir.childs().size());
ios
.seekp(ctx.offset_header)
.increase_capacity(sizeof(details::pe_resource_directory_table))
.write<uint32_t>(dir.characteristics())
.write<uint32_t>(dir.time_date_stamp())
.write<uint16_t>(dir.major_version())
.write<uint16_t>(dir.minor_version())
.write<uint16_t>(dir.numberof_name_entries())
.write<uint16_t>(dir.numberof_id_entries())
;
ctx.offset_header = ios.tellp();
uint32_t current_offset = ctx.offset_header;
ctx.offset_header += dir.childs().size() * sizeof(details::pe_resource_directory_entries);
for (ResourceNode& child : dir.childs()) {
if (child.has_name() || !child.name().empty()) {
const std::u16string& name = child.name();
child.id(0x80000000 | ctx.offset_name);
LIEF_DEBUG("[rsrc] writing name '{}' at 0x{:04x} (depth={}, id={})",
u16tou8(child.name()), ctx.offset_name,
dir.depth(), dir.id());
ios
.seekp(ctx.offset_name)
.write<uint16_t>(name.size())
.write(name, /*with_null_char=*/false);
ctx.offset_name = ios.tellp();
}
const uint32_t mask = child.is_directory() ? 0x80000000 : 0;
ios
.seekp(current_offset)
.write<uint32_t>(child.id())
.write<uint32_t>(mask | ctx.offset_header)
;
current_offset = ios.tellp();
++ctx.depth;
construct_resource(ios, child, ctx);
}
return ok();
}
ok_error_t Builder::construct_resource(
vector_iostream& ios, ResourceData& data, rsrc_build_context_t& ctx)
{
span<const uint8_t> content = data.content();
ctx.rva_fixups.push_back(ctx.offset_header);
LIEF_DEBUG("[rsrc] writing data header at 0x{:04x} (depth={}, id={})",
ctx.offset_header, data.depth(), data.id());
ios
.seekp(ctx.offset_header)
.increase_capacity(sizeof(details::pe_resource_data_entry))
.write<uint32_t>(ctx.offset_data)
.write<uint32_t>(content.size())
.write<uint32_t>(data.code_page())
.write<uint32_t>(data.reserved())
;
ctx.offset_header = ios.tellp();
LIEF_DEBUG("[rsrc] writing data content at 0x{:04x} (depth={}, id={}, size=0x{:04x})",
ctx.offset_data, data.depth(), data.id(), content.size());
ios
.seekp(ctx.offset_data)
.write(content.data(), content.size())
.align(sizeof(uint32_t));
ctx.offset_data = ios.tellp();
return ok();
}
ok_error_t Builder::construct_resource(
vector_iostream& ios, ResourceNode& node, rsrc_build_context_t& ctx)
{
if (auto* dir = node.cast<ResourceDirectory>()) {
return construct_resource(ios, *dir, ctx);
}
if (auto* data = node.cast<ResourceData>()) {
return construct_resource(ios, *data, ctx);
}
return make_error_code(lief_errors::conversion_error);
}
ok_error_t build_codeview(const CodeView& CV, vector_iostream& ios) {
const auto* cv_pdb = CV.as<CodeViewPDB>();
if (cv_pdb == nullptr) {
return make_error_code(lief_errors::not_supported);
}
ios
.write<uint32_t>((uint32_t)CV.signature())
.write(cv_pdb->signature())
.write<uint32_t>(cv_pdb->age())
.write(cv_pdb->filename())
;
return ok();
}
ok_error_t build_pogo(const Pogo& pgo, vector_iostream& ios) {
switch (pgo.signature()) {
default:
return make_error_code(lief_errors::not_supported);
case Pogo::SIGNATURES::ZERO:
case Pogo::SIGNATURES::LCTG:
{
ios.write<uint32_t>((uint32_t)pgo.signature());
for (const PogoEntry& entry : pgo.entries()) {
ios
.write<uint32_t>(entry.start_rva())
.write<uint32_t>(entry.size())
.write(entry.name())
.align(4)
;
}
return ok();
}
}
return ok();
}
ok_error_t build_repro(const Repro& repro, vector_iostream& ios) {
span<const uint8_t> hash = repro.hash();
ios
.write<uint32_t>(hash.size())
.write(hash)
;
return ok();
}
ok_error_t build_pdbchecksum(const PDBChecksum& checksum, vector_iostream& ios) {
if (checksum.algorithm() == PDBChecksum::HASH_ALGO::UNKNOWN) {
return make_error_code(lief_errors::not_supported);
}
const std::string& algo_name = to_string(checksum.algorithm());
assert(algo_name != "UNKNOWN");
ios
.write(algo_name)
.write(checksum.hash())
;
return ok();
}
ok_error_t build_vcfeatures(const VCFeature& vcfeature, vector_iostream& ios) {
const size_t original_size = vcfeature.sizeof_data();
if ((size_t)ios.tellp() + sizeof(uint32_t) > original_size) {
return ok();
}
ios.write<uint32_t>(vcfeature.pre_vcpp());
if ((size_t)ios.tellp() + sizeof(uint32_t) > original_size) {
return ok();
}
ios.write<uint32_t>(vcfeature.c_cpp());
if ((size_t)ios.tellp() + sizeof(uint32_t) > original_size) {
return ok();
}
ios.write<uint32_t>(vcfeature.gs());
if ((size_t)ios.tellp() + sizeof(uint32_t) > original_size) {
return ok();
}
ios.write<uint32_t>(vcfeature.sdl());
if ((size_t)ios.tellp() + sizeof(uint32_t) > original_size) {
return ok();
}
ios.write<uint32_t>(vcfeature.guards());
return ok();
}
ok_error_t build_exdllcharacteristics(const ExDllCharacteristics& characteristics,
vector_iostream& ios)
{
if (characteristics.sizeof_data() != sizeof(uint32_t)) {
return make_error_code(lief_errors::not_supported);
}
ios.write<uint32_t>((uint32_t)characteristics.characteristics());
return ok();
}
ok_error_t Builder::build_debug_info() {
LIEF_DEBUG("Writing back debug info");
static constexpr auto FX_BASE_RVA = 0;
static constexpr auto FX_BASE_OFFSET = 1;
DataDirectory* debug_dir = binary_->debug_dir();
if (binary_->debug_.empty()) {
if (debug_dir->RVA() > 0 && debug_dir->size() > 0) {
binary_->fill_address(debug_dir->RVA(), debug_dir->size());
}
debug_dir->RVA(0);
debug_dir->size(0);
return ok();
}
// Check if we need to relocate the headers
const size_t hdr_size = binary_->debug_.size() * sizeof(details::pe_debug);
vector_iostream payload_stream;
vector_iostream header_stream;
header_stream.reserve(debug_dir->size());
header_stream.init_fixups(2);
const uint32_t hdr_start = 0;
const uint32_t payload_start = hdr_start + hdr_size;
uint32_t payload_offset = payload_start;
for (size_t i = 0; i < binary_->debug_.size(); ++i) {
const std::unique_ptr<Debug>& dbg = binary_->debug_[i];
LIEF_DEBUG("debug[{:02}]: {}", i, to_string(dbg->type()));
uint32_t hdr_pos = hdr_start + i * sizeof(details::pe_debug);
span<uint8_t> payload = dbg->payload();
header_stream
.write<uint32_t>(dbg->characteristics())
.write<uint32_t>(dbg->timestamp())
.write<uint16_t>(dbg->major_version())
.write<uint16_t>(dbg->minor_version())
.write<uint32_t>((uint32_t)dbg->type())
;
LIEF_DEBUG(" - Header pos: 0x{:06x}", hdr_pos);
LIEF_DEBUG(" - Payload pos: 0x{:06x}", payload_offset);
const bool has_offset_rva = dbg->addressof_rawdata() != 0 ||
dbg->pointerto_rawdata() != 0;
if (payload.empty() && has_offset_rva) {
LIEF_INFO("Empty payload. Can't rebuild the content of {}",
to_string(dbg->type()));
header_stream
.write<uint32_t>(dbg->sizeof_data())
.write<uint32_t>(dbg->addressof_rawdata())
.write<uint32_t>(dbg->pointerto_rawdata())
;
continue;
}
if (const auto* codeview = dbg->as<CodeView>()) {
vector_iostream ios_cv;
ios_cv.reserve(codeview->sizeof_data());
if (auto is_ok = build_codeview(*codeview, ios_cv); !is_ok) {
ios_cv.clear().write(payload);
}
header_stream.write<uint32_t>(ios_cv.size());
LIEF_DEBUG("codeview - original size 0x{:06x}", dbg->sizeof_data());
LIEF_DEBUG("codeview - new size 0x{:06x}", ios_cv.size());
const int32_t delta = (int32_t)ios_cv.size() - dbg->sizeof_data();
if (delta <= 0) {
std::memset(payload.data(), 0, payload.size());
std::copy(ios_cv.begin(), ios_cv.end(), payload.begin());
header_stream
.write<uint32_t>(dbg->addressof_rawdata())
.write<uint32_t>(dbg->pointerto_rawdata())
;
} else {
LIEF_DEBUG("Need to relocate entry #{} +{} bytes", i, delta);
const size_t payload_off = payload_stream.tellp();
payload_stream.write(ios_cv);
header_stream
.record_fixup(FX_BASE_RVA)
.write<uint32_t>(payload_off)
.record_fixup(FX_BASE_OFFSET)
.write<uint32_t>(payload_off)
;
}
continue;
}
if (const auto* pogo = dbg->as<Pogo>()) {
vector_iostream ios_pogo;
ios_pogo.reserve(pogo->sizeof_data());
if (auto is_ok = build_pogo(*pogo, ios_pogo); !is_ok) {
ios_pogo.clear().write(payload);
}
header_stream.write<uint32_t>(ios_pogo.size());
LIEF_DEBUG("pogo - original size 0x{:06x}", dbg->sizeof_data());
LIEF_DEBUG("pogo - new size 0x{:06x}", ios_pogo.size());
const int32_t delta = (int32_t)ios_pogo.size() - dbg->sizeof_data();
if (delta <= 0) {
std::memset(payload.data(), 0, payload.size());
std::copy(ios_pogo.begin(), ios_pogo.end(), payload.begin());
header_stream
.write<uint32_t>(dbg->addressof_rawdata())
.write<uint32_t>(dbg->pointerto_rawdata())
;
} else {
LIEF_DEBUG("Need to relocate entry #{} +{} bytes", i, delta);
const size_t payload_off = payload_stream.tellp();
payload_stream.write(ios_pogo);
header_stream
.record_fixup(FX_BASE_RVA)
.write<uint32_t>(payload_off)
.record_fixup(FX_BASE_OFFSET)
.write<uint32_t>(payload_off)
;
}
continue;
}
if (const auto* repro = dbg->as<Repro>()) {
vector_iostream ios_repro;
ios_repro.reserve(repro->sizeof_data());
if (auto is_ok = build_repro(*repro, ios_repro); !is_ok) {
ios_repro.clear().write(payload);
}
header_stream.write<uint32_t>(ios_repro.size());
LIEF_DEBUG("repro - original size 0x{:06x}", dbg->sizeof_data());
LIEF_DEBUG("repro - new size 0x{:06x}", ios_repro.size());
const int32_t delta = (int32_t)ios_repro.size() - dbg->sizeof_data();
if (delta <= 0) {
std::memset(payload.data(), 0, payload.size());
std::copy(ios_repro.begin(), ios_repro.end(), payload.begin());
header_stream
.write<uint32_t>(dbg->addressof_rawdata())
.write<uint32_t>(dbg->pointerto_rawdata())
;
} else {
LIEF_DEBUG("Need to relocate entry #{} +{} bytes", i, delta);
const size_t payload_off = payload_stream.tellp();
payload_stream.write(ios_repro);
header_stream
.record_fixup(FX_BASE_RVA)
.write<uint32_t>(payload_off)
.record_fixup(FX_BASE_OFFSET)
.write<uint32_t>(payload_off)
;
}
continue;
}
if (const auto* repro = dbg->as<PDBChecksum>()) {
vector_iostream ios_repro;
ios_repro.reserve(repro->sizeof_data());
if (auto is_ok = build_pdbchecksum(*repro, ios_repro); !is_ok) {
ios_repro.clear().write(payload);
}
header_stream.write<uint32_t>(ios_repro.size());
LIEF_DEBUG("pdbchecksum - original size 0x{:06x}", dbg->sizeof_data());
LIEF_DEBUG("pdbchecksum - new size 0x{:06x}", ios_repro.size());
const int32_t delta = (int32_t)ios_repro.size() - dbg->sizeof_data();
if (delta <= 0) {
std::memset(payload.data(), 0, payload.size());
std::copy(ios_repro.begin(), ios_repro.end(), payload.begin());
header_stream
.write<uint32_t>(dbg->addressof_rawdata())
.write<uint32_t>(dbg->pointerto_rawdata())
;
} else {
LIEF_DEBUG("Need to relocate entry #{} +{} bytes", i, delta);
const size_t payload_off = payload_stream.tellp();
payload_stream.write(ios_repro);
header_stream
.record_fixup(FX_BASE_RVA)
.write<uint32_t>(payload_off)
.record_fixup(FX_BASE_OFFSET)
.write<uint32_t>(payload_off)
;
}
continue;
}
if (const auto* vcfeat = dbg->as<VCFeature>()) {
vector_iostream ios_vcfeat;
ios_vcfeat.reserve(vcfeat->sizeof_data());
if (auto is_ok = build_vcfeatures(*vcfeat, ios_vcfeat); !is_ok) {
ios_vcfeat.clear().write(payload);
}
header_stream.write<uint32_t>(ios_vcfeat.size());
LIEF_DEBUG("vcfeature - original size 0x{:06x}", dbg->sizeof_data());
LIEF_DEBUG("vcfeature - new size 0x{:06x}", ios_vcfeat.size());
const int32_t delta = (int32_t)ios_vcfeat.size() - dbg->sizeof_data();
if (delta <= 0) {
std::memset(payload.data(), 0, payload.size());
std::copy(ios_vcfeat.begin(), ios_vcfeat.end(), payload.begin());
header_stream
.write<uint32_t>(dbg->addressof_rawdata())
.write<uint32_t>(dbg->pointerto_rawdata())
;
} else {
LIEF_DEBUG("Need to relocate entry #{} +{} bytes", i, delta);
const size_t payload_off = payload_stream.tellp();
payload_stream.write(ios_vcfeat);
header_stream
.record_fixup(FX_BASE_RVA)
.write<uint32_t>(payload_off)
.record_fixup(FX_BASE_OFFSET)
.write<uint32_t>(payload_off)
;
}
continue;
}
if (const auto* exdllchar = dbg->as<ExDllCharacteristics>()) {
vector_iostream ios_exdll;
ios_exdll.reserve(exdllchar->sizeof_data());
if (auto is_ok = build_exdllcharacteristics(*exdllchar, ios_exdll); !is_ok) {
ios_exdll.clear().write(payload);
}
header_stream.write<uint32_t>(ios_exdll.size());
LIEF_DEBUG("ExDllCharacteristics - original size 0x{:06x}", dbg->sizeof_data());
LIEF_DEBUG("ExDllCharacteristics - new size 0x{:06x}", ios_exdll.size());
const int32_t delta = (int32_t)ios_exdll.size() - dbg->sizeof_data();
if (delta <= 0) {
std::memset(payload.data(), 0, payload.size());
std::copy(ios_exdll.begin(), ios_exdll.end(), payload.begin());
header_stream
.write<uint32_t>(dbg->addressof_rawdata())
.write<uint32_t>(dbg->pointerto_rawdata())
;
} else {
LIEF_DEBUG("Need to relocate entry #{} +{} bytes", i, delta);
const size_t payload_off = payload_stream.tellp();
payload_stream.write(ios_exdll);
header_stream
.record_fixup(FX_BASE_RVA)
.write<uint32_t>(payload_off)
.record_fixup(FX_BASE_OFFSET)
.write<uint32_t>(payload_off)
;
}
continue;
}
LIEF_DEBUG("original size 0x{:06x}", dbg->sizeof_data());
LIEF_DEBUG("new size 0x{:06x}", payload.size());
header_stream.write<uint32_t>(payload.size());
header_stream
.write<uint32_t>(dbg->addressof_rawdata())
.write<uint32_t>(dbg->pointerto_rawdata())
;
continue;
}
payload_stream.align(sizeof(uint32_t));
size_t relocated_size = payload_stream.size();
bool relocate_hdr = false;
{
// Clear the original headers since it will be either: relocated or
// overwritten
span<uint8_t> raw = debug_dir->content();
std::memset(raw.data(), 0, raw.size());
}
if (hdr_size > debug_dir->size()) {
LIEF_DEBUG("Need to relocated debug directory (for headers)");
relocated_size += header_stream.size();
relocate_hdr = true;
}