-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathmain.cpp
More file actions
996 lines (845 loc) · 30.1 KB
/
Copy pathmain.cpp
File metadata and controls
996 lines (845 loc) · 30.1 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
#include "elf.h"
#include "utils.h"
#include "rplwrap.h"
#include <algorithm>
#include <excmd.h>
#include <fmt/format.h>
#include <fstream>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include <math.h>
#include <zlib.h>
constexpr auto DeflateMinSectionSize = 0x18u;
constexpr auto CodeBaseAddress = 0x02000000u;
constexpr auto DataBaseAddress = 0x10000000u;
constexpr auto LoadBaseAddress = 0xC0000000u;
struct ElfFile
{
struct Section
{
elf::SectionHeader header;
std::string name;
std::vector<char> data;
};
elf::Header header;
std::vector<std::unique_ptr<Section>> sections;
};
static int
getSectionIndex(ElfFile &file, const char *name)
{
int index = 0;
for (const auto §ion : file.sections) {
if (section->name == name) {
return index;
}
++index;
}
return -1;
}
static ElfFile::Section *
getSectionByType(ElfFile &file, elf::SectionType type)
{
for (const auto §ion : file.sections) {
if (section->header.type == type) {
return section.get();
}
}
return nullptr;
}
/**
* Read the .elf file generated by compiler.
*/
static bool
readElf(ElfFile &file, const std::string &filename)
{
std::ifstream in { filename, std::ifstream::binary };
if (!in.is_open()) {
fmt::print("Could not open {} for reading\n", filename);
return false;
}
// Read header
in.read(reinterpret_cast<char *>(&file.header), sizeof(elf::Header));
if (file.header.magic != elf::HeaderMagic) {
fmt::print("Invalid ELF magic header {:08X}\n", elf::HeaderMagic);
return false;
}
if (file.header.fileClass != elf::ELFCLASS32) {
fmt::print("Unexpected ELF file class {}, expected {}\n", file.header.fileClass, elf::ELFCLASS32);
return false;
}
if (file.header.encoding != elf::ELFDATA2MSB) {
fmt::print("Unexpected ELF encoding {}, expected {}\n", file.header.encoding, elf::ELFDATA2MSB);
return false;
}
if (file.header.machine != elf::EM_PPC) {
fmt::print("Unexpected ELF machine type {}, expected {}\n", file.header.machine, elf::EM_PPC);
return false;
}
if (file.header.elfVersion != elf::EV_CURRENT) {
fmt::print("Unexpected ELF version {}, expected {}\n", file.header.elfVersion, elf::EV_CURRENT);
return false;
}
// Read section headers and data
in.seekg(static_cast<size_t>(file.header.shoff));
for (auto i = 0u; i < file.header.shnum; ++i) {
file.sections.emplace_back(std::make_unique<ElfFile::Section>());
auto §ion = *file.sections.back();
in.read(reinterpret_cast<char *>(§ion.header), sizeof(elf::SectionHeader));
if (!section.header.size || section.header.type == elf::SHT_NOBITS) {
continue;
}
if (section.header.addr >= DataBaseAddress && section.header.addr < LoadBaseAddress) {
section.header.flags |= elf::SHF_WRITE;
}
if (section.header.flags & elf::SHF_TLS) {
section.header.flags &= ~elf::SHF_TLS;
section.header.flags |= elf::SHF_RPL_TLS;
}
auto pos = in.tellg();
in.seekg(static_cast<size_t>(section.header.offset));
section.data.resize(section.header.size);
in.read(section.data.data(), section.data.size());
in.seekg(pos);
}
// Set section header names
auto shStrTab = file.sections[file.header.shstrndx]->data.data();
for (auto §ion : file.sections) {
section->name = shStrTab + section->header.name;
}
return true;
}
/**
* Generate SHT_RPL_FILEINFO section.
*/
static bool
generateFileInfoSection(ElfFile &file,
uint32_t flags)
{
elf::RplFileInfo info;
info.version = 0xCAFE0402u;
info.textSize = 0u;
info.textAlign = 32u;
info.dataSize = 0u;
info.dataAlign = 4096u;
info.loadSize = 0u;
info.loadAlign = 4u;
info.tempSize = 0u;
info.trampAdjust = 0u;
info.trampAddition = 0u;
info.sdaBase = 0u;
info.sda2Base = 0u;
info.stackSize = 0x10000u;
info.heapSize = 0x8000u;
info.filename = 0u;
info.flags = flags;
info.minVersion = 0x5078u;
info.compressionLevel = 6;
info.fileInfoPad = 0u;
info.cafeSdkVersion = 0x5335u;
info.cafeSdkRevision = 0x10D4Bu;
info.tlsAlignShift = uint16_t { 0u };
info.tlsModuleIndex = uint16_t { 0u };
info.runtimeFileInfoSize = 0u;
info.tagOffset = 0u;
// Count file info textSize, dataSize, loadSize
for (auto §ion : file.sections) {
auto size = static_cast<uint32_t>(section->data.size());
if (section->header.type == elf::SHT_NOBITS) {
size = section->header.size;
}
if (section->header.flags & elf::SHF_RPL_TLS) {
info.flags |= elf::RPL_TLS;
if ((1 << info.tlsAlignShift) < section->header.addralign)
info.tlsAlignShift = (uint16_t)log2((float)section->header.addralign);
}
if (section->header.addr >= CodeBaseAddress &&
section->header.addr < DataBaseAddress) {
auto val = section->header.addr + section->header.size - CodeBaseAddress;
if (val > info.textSize) {
info.textSize = val;
}
} else if (section->header.addr >= DataBaseAddress &&
section->header.addr < LoadBaseAddress) {
auto val = section->header.addr + section->header.size - DataBaseAddress;
if (val > info.dataSize) {
info.dataSize = val;
}
} else if (section->header.addr >= LoadBaseAddress) {
auto val = section->header.addr + section->header.size - LoadBaseAddress;
if (val > info.loadSize) {
info.loadSize = val;
}
} else if (section->header.addr == 0 &&
section->header.type != elf::SHT_RPL_CRCS &&
section->header.type != elf::SHT_RPL_FILEINFO) {
info.tempSize += (size + 128);
}
}
info.textSize = align_up(info.textSize, info.textAlign);
info.dataSize = align_up(info.dataSize, info.dataAlign);
info.loadSize = align_up(info.loadSize, info.loadAlign);
auto section = std::make_unique<ElfFile::Section>();
section->header.name = 0u;
section->header.type = elf::SHT_RPL_FILEINFO;
section->header.flags = 0u;
section->header.addr = 0u;
section->header.offset = 0u;
section->header.size = 0u;
section->header.link = 0u;
section->header.info = 0u;
section->header.addralign = 4u;
section->header.entsize = 0u;
section->data.insert(section->data.end(),
reinterpret_cast<char *>(&info),
reinterpret_cast<char *>(&info + 1));
file.sections.emplace_back(std::move(section));
return true;
}
/**
* Generate SHT_RPL_CRCS section.
*/
static bool
generateCrcSection(ElfFile &file)
{
std::vector<be_val<uint32_t>> crcs;
for (auto §ion : file.sections) {
auto crc = uint32_t { 0u };
if (section->data.size()) {
crc = crc32(0, Z_NULL, 0);
crc = crc32(crc, reinterpret_cast<Bytef *>(section->data.data()), section->data.size());
}
crcs.push_back(crc);
}
// Insert a 0 crc for this section
crcs.insert(crcs.end() - 1, 0);
auto section = std::make_unique<ElfFile::Section>();
section->header.name = 0u;
section->header.type = elf::SHT_RPL_CRCS;
section->header.flags = 0u;
section->header.addr = 0u;
section->header.offset = 0u;
section->header.size = 0u;
section->header.link = 0u;
section->header.info = 0u;
section->header.addralign = 4u;
section->header.entsize = 4u;
section->data.insert(section->data.end(),
reinterpret_cast<char *>(crcs.data()),
reinterpret_cast<char *>(crcs.data() + crcs.size()));
// Insert before FILEINFO
file.sections.insert(file.sections.end() - 1, std::move(section));
return true;
}
static bool
getSymbol(ElfFile::Section §ion,
size_t index,
elf::Symbol &symbol)
{
auto symbols = reinterpret_cast<elf::Symbol *>(section.data.data());
auto numSymbols = section.data.size() / sizeof(elf::Symbol);
if (index >= numSymbols) {
return false;
}
symbol = symbols[index];
return true;
}
/**
* Fix relocations.
*
* The Wii U does not support every type of relocation.
*/
static bool
fixRelocations(ElfFile &file)
{
std::set<unsigned int> unsupportedTypes;
auto result = true;
for (auto §ion : file.sections) {
std::vector<elf::Rela> newRelocations;
if (section->header.type != elf::SHT_RELA) {
continue;
}
// Clear flags
section->header.flags = 0u;
auto &symbolSection = file.sections[section->header.link];
auto &targetSection = file.sections[section->header.info];
auto rels = reinterpret_cast<elf::Rela *>(section->data.data());
auto numRels = section->data.size() / sizeof(elf::Rela);
for (auto i = 0u; i < numRels; ++i) {
auto info = rels[i].info;
auto addend = rels[i].addend;
auto offset = rels[i].offset;
auto index = info >> 8;
auto type = info & 0xFF;
switch (type) {
case elf::R_PPC_NONE:
case elf::R_PPC_ADDR32:
case elf::R_PPC_ADDR16_LO:
case elf::R_PPC_ADDR16_HI:
case elf::R_PPC_ADDR16_HA:
case elf::R_PPC_REL24:
case elf::R_PPC_REL14:
case elf::R_PPC_DTPMOD32:
case elf::R_PPC_DTPREL32:
case elf::R_PPC_EMB_SDA21:
case elf::R_PPC_EMB_RELSDA:
case elf::R_PPC_DIAB_SDA21_LO:
case elf::R_PPC_DIAB_SDA21_HI:
case elf::R_PPC_DIAB_SDA21_HA:
case elf::R_PPC_DIAB_RELSDA_LO:
case elf::R_PPC_DIAB_RELSDA_HI:
case elf::R_PPC_DIAB_RELSDA_HA:
// All valid relocations on Wii U, do nothing
break;
/*
* Convert a R_PPC_REL32 into two GHS_REL16
*/
case elf::R_PPC_REL32:
{
elf::Symbol symbol;
if (!getSymbol(*symbolSection, index, symbol)) {
fmt::print("ERROR: Could not find symbol {} for fixing a R_PPC_REL32 relocation\n", index);
result = false;
} else {
newRelocations.emplace_back();
auto &newRel = newRelocations.back();
// Modify current relocation to R_PPC_GHS_REL16_HI
rels[i].info = (index << 8) | elf::R_PPC_GHS_REL16_HI;
rels[i].addend = addend;
rels[i].offset = offset;
// Create a R_PPC_GHS_REL16_LO
newRel.info = (index << 8) | elf::R_PPC_GHS_REL16_LO;
newRel.addend = addend + 2;
newRel.offset = offset + 2;
}
break;
}
/*
* Convert R_PPC_GOT_TLSGD16/R_PPC_TLSGD into R_PPC_DTPMOD32/R_PPC_DTPREL32
*/
case elf::R_PPC_TLSGD:
case elf::R_PPC_GOT_TLSGD16: {
uint32_t gotAddr = 0;
bool gotFound = false;
auto strTab = file.sections[symbolSection->header.link]->data.data();
for (int j = 0; j < symbolSection->data.size() / sizeof(elf::Symbol); j++) {
elf::Symbol symbol;
getSymbol(*symbolSection, j, symbol);
if (!strcmp(strTab + symbol.name, "_GLOBAL_OFFSET_TABLE_")) {
gotFound = true;
gotAddr = symbol.value;
if (targetSection->name != file.sections[symbol.shndx]->name) {
fmt::print("ERROR: \"_GLOBAL_OFFSET_TABLE_\" found in section \"{}\" instead of \"{}\", "
"cannot fix a R_PPC_GOT_TLSGD16 relocation\n",
file.sections[symbol.shndx]->name, targetSection->name);
result = false;
}
break;
}
}
if (!gotFound) {
fmt::print("ERROR: Could not find symbol \"_GLOBAL_OFFSET_TABLE_\" for fixing a R_PPC_GOT_TLSGD16 relocation\n");
result = false;
break;
}
/* tls_index is stored in GOT as 8 bytes (DTPMOD32 + DTPREL32)
* GOT_TLSGD16 points to the offset of tls_index in GOT
* for R_PPC_TLSGD, the offset is in the previous instruction
*/
be_val<int16_t> *tlsIndexOffset = (be_val<int16_t> *)(targetSection->data.data() + offset - targetSection->header.addr);
if (type == elf::R_PPC_GOT_TLSGD16) {
rels[i].info = (index << 8) | elf::R_PPC_DTPMOD32;
rels[i].offset = gotAddr + *tlsIndexOffset;
} else {
tlsIndexOffset--;
rels[i].info = (index << 8) | elf::R_PPC_DTPREL32;
rels[i].offset = gotAddr + *tlsIndexOffset + 4;
}
break;
}
default:
// Only print error once per type
if (!unsupportedTypes.count(type)) {
fmt::print("ERROR: Unsupported relocation type {}\n", type);
unsupportedTypes.insert(type);
}
}
}
section->data.insert(section->data.end(),
reinterpret_cast<char *>(newRelocations.data()),
reinterpret_cast<char *>(newRelocations.data() + newRelocations.size()));
}
return result && unsupportedTypes.size() == 0;
}
/**
* Fix file header to look like an RPL file!
*/
static bool
fixFileHeader(ElfFile &file)
{
file.header.magic = elf::HeaderMagic;
file.header.fileClass = uint8_t { 1 };
file.header.encoding = elf::ELFDATA2MSB;
file.header.elfVersion = elf::EV_CURRENT;
file.header.abi = elf::EABI_CAFE;
memset(&file.header.pad, 0, 7);
file.header.type = uint16_t { 0xFE01 };
file.header.machine = elf::EM_PPC;
file.header.version = 1u;
file.header.flags = 0u;
file.header.phoff = 0u;
file.header.phentsize = uint16_t { 0 };
file.header.phnum = uint16_t { 0 };
file.header.shoff = align_up(static_cast<uint32_t>(sizeof(elf::Header)), 64);
file.header.shnum = static_cast<uint16_t>(file.sections.size());
file.header.shentsize = static_cast<uint16_t>(sizeof(elf::SectionHeader));
file.header.ehsize = static_cast<uint16_t>(sizeof(elf::Header));
file.header.shstrndx = static_cast<uint16_t>(getSectionIndex(file, ".shstrtab"));
return true;
}
/**
* Relocate a section to a new address.
*/
static bool
relocateSection(ElfFile &file,
ElfFile::Section §ion,
uint32_t sectionIndex,
uint32_t newSectionAddress)
{
auto sectionSize = section.data.size() ? section.data.size() : static_cast<size_t>(section.header.size);
auto oldSectionAddress = section.header.addr;
auto oldSectionAddressEnd = section.header.addr + sectionSize;
// Relocate symbols pointing into this section
for (auto &symSection : file.sections) {
if (symSection->header.type != elf::SectionType::SHT_SYMTAB) {
continue;
}
auto symbols = reinterpret_cast<elf::Symbol *>(symSection->data.data());
auto numSymbols = symSection->data.size() / sizeof(elf::Symbol);
for (auto i = 0u; i < numSymbols; ++i) {
auto type = symbols[i].info & 0xf;
auto value = symbols[i].value;
// Only relocate data, func, section symbols
if (type != elf::STT_OBJECT &&
type != elf::STT_FUNC &&
type != elf::STT_SECTION) {
continue;
}
if (value >= oldSectionAddress && value <= oldSectionAddressEnd) {
symbols[i].value = (value - oldSectionAddress) + newSectionAddress;
}
}
}
// Relocate relocations pointing into this section
for (auto &relaSection : file.sections) {
if (relaSection->header.type != elf::SectionType::SHT_RELA ||
relaSection->header.info != sectionIndex) {
continue;
}
auto rela = reinterpret_cast<elf::Rela *>(relaSection->data.data());
auto numRelas = relaSection->data.size() / sizeof(elf::Rela);
for (auto i = 0u; i < numRelas; ++i) {
auto offset = rela[i].offset;
if (offset >= oldSectionAddress && offset <= oldSectionAddressEnd) {
rela[i].offset = (offset - oldSectionAddress) + newSectionAddress;
}
}
}
section.header.addr = newSectionAddress;
return true;
}
const static std::string rplwrap_prefix(RPLWRAP_PREFIX);
/**
* Rename __rplwrap_<name> to <name>, and if <name> already exists rename it to
* __rplwrap_<name>.
*
* This is useful in situations where the imported libraries have names that
* conflict with existing ones.
*/
static bool
renameRplWrap(ElfFile &file)
{
auto strtabIndex = getSectionIndex(file, ".strtab");
if (strtabIndex < 0) return false;
auto& strtab = file.sections[strtabIndex];
auto strtabd = reinterpret_cast<char *>(strtab->data.data());
for (auto &symSection : file.sections) {
if (symSection->header.type != elf::SectionType::SHT_SYMTAB) {
continue;
}
auto symbols = reinterpret_cast<elf::Symbol *>(symSection->data.data());
auto numSymbols = symSection->data.size() / sizeof(elf::Symbol);
// First pass - find all the symbols prefixed with __rplwrap_, don't do
// anything yet
std::vector<elf::Symbol*> foundRplWraps;
for (auto i = 0u; i < numSymbols; ++i) {
auto type = symbols[i].info & 0xf;
// Only rename functions, data
if (type != elf::STT_OBJECT &&
type != elf::STT_FUNC) {
continue;
}
std::string name = &strtabd[symbols[i].name];
if (!name.compare(0, rplwrap_prefix.size(), rplwrap_prefix)) {
foundRplWraps.push_back(&symbols[i]);
}
}
// Second pass - Find any symbols that would conflict if __rplwrap_<name>
// got renamed to <name>, and if so, swap the names
for (auto i = 0u; i < numSymbols; ++i) {
auto type = symbols[i].info & 0xf;
std::string symName = &strtabd[symbols[i].name];
// Only rename functions, data
if (type != elf::STT_OBJECT &&
type != elf::STT_FUNC) {
continue;
}
auto rplWrap = foundRplWraps.begin();
while (rplWrap != foundRplWraps.end()) {
std::string wrapName = &strtabd[(*rplWrap)->name];
// Get the <name> part of __rplwrap_<name>
std::string wrapNameBase = wrapName.substr(rplwrap_prefix.size());
if (wrapNameBase == symName) {
// both __rplwrap_<name> and <name> exist, we can just swap their
// name pointers
#ifdef DEBUG
fmt::print("DEBUG: renameRplWrap: {} <-> {}\n",
wrapName, symName);
#endif //DEBUG
std::swap((*rplWrap)->name, symbols[i].name);
// We're done, remove symbol from foundRplWraps
rplWrap = foundRplWraps.erase(rplWrap);
// Otherwise, increment the iterator and go around again
} else ++rplWrap;
}
}
// Final pass: rename any remaining (non-conflicting) __rplwrap_<name>
// symbols to <name>
for (auto symbol : foundRplWraps) {
#ifdef DEBUG
fmt::print("DEBUG: renameRplWrap: {} -> {}\n",
std::string(&strtabd[symbol->name]),
std::string(&strtabd[symbol->name] + rplwrap_prefix.length()));
#endif //DEBUG
symbol->name += (uint32_t)rplwrap_prefix.length();
}
}
return true;
}
/**
* Fix the loader virtual addresses.
*
* Linker script won't put symtab & strtab sections in our loader address, so
* we must fix that.
*/
static bool
fixLoaderVirtualAddresses(ElfFile &file)
{
auto loadMax = LoadBaseAddress;
for (auto §ion : file.sections) {
if (section->header.addr >= loadMax) {
loadMax = section->header.addr + section->data.size();
}
}
// Relocate .symtab and .strtab to be in loader memory
for (auto i = 0u; i < file.sections.size(); ++i) {
auto §ion = file.sections[i];
if (section->header.type == elf::SHT_SYMTAB ||
section->header.type == elf::SHT_STRTAB) {
loadMax = align_up(loadMax, section->header.addralign);
relocateSection(file, *section, i, loadMax);
section->header.flags |= elf::SHF_ALLOC;
loadMax += section->data.size();
}
}
return true;
}
/**
* zlib deflate any suitable section.
*/
static bool
deflateSections(ElfFile &file)
{
std::vector<char> chunk;
chunk.resize(16 * 1024);
for (auto §ion : file.sections) {
if (section->data.size() < DeflateMinSectionSize ||
section->header.type == elf::SHT_RPL_CRCS ||
section->header.type == elf::SHT_RPL_FILEINFO) {
continue;
}
// Allocate space for the 4 bytes inflated size
std::vector<char> deflated;
deflated.resize(4);
// Deflate section data
auto stream = z_stream { };
memset(&stream, 0, sizeof(stream));
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
deflateInit(&stream, 6);
stream.avail_in = section->data.size();
stream.next_in = reinterpret_cast<Bytef *>(section->data.data());
do {
stream.avail_out = static_cast<uInt>(chunk.size());
stream.next_out = reinterpret_cast<Bytef *>(chunk.data());
auto ret = deflate(&stream, Z_FINISH);
if (ret == Z_STREAM_ERROR) {
deflateEnd(&stream);
return false;
}
deflated.insert(deflated.end(),
chunk.data(),
reinterpret_cast<char *>(stream.next_out));
} while (stream.avail_out == 0);
deflateEnd(&stream);
// Set the inflated size at start of section
*reinterpret_cast<be_val<uint32_t> *>(&deflated[0]) =
static_cast<uint32_t>(section->data.size());
// Update the section data
section->data = std::move(deflated);
section->header.flags |= elf::SHF_DEFLATED;
}
return true;
}
/**
* Calculate section file offsets.
*
* Expected order:
* RPL_CRCS > RPL_FILEINFO >
* Data sections > Read sections > Text sections > Temp sections
*/
static bool
calculateSectionOffsets(ElfFile &file)
{
auto offset = file.header.shoff;
offset += align_up(static_cast<uint32_t>(file.sections.size() * sizeof(elf::SectionHeader)), 64);
for (auto §ion : file.sections) {
if (section->header.type == elf::SHT_NOBITS ||
section->header.type == elf::SHT_NULL) {
section->header.offset = 0u;
section->data.clear();
}
}
for (auto §ion : file.sections) {
if (section->header.type == elf::SHT_RPL_CRCS) {
section->header.offset = offset;
section->header.size = static_cast<uint32_t>(section->data.size());
offset += section->header.size;
}
}
for (auto §ion : file.sections) {
if (section->header.type == elf::SHT_RPL_FILEINFO) {
section->header.offset = offset;
section->header.size = static_cast<uint32_t>(section->data.size());
offset += section->header.size;
}
}
// First the "dataMin / dataMax" sections, which are:
// - !(flags & SHF_EXECINSTR)
// - flags & SHF_WRITE
// - flags & SHF_ALLOC
for (auto §ion : file.sections) {
if (section->header.size == 0 ||
section->header.type == elf::SHT_RPL_FILEINFO ||
section->header.type == elf::SHT_RPL_IMPORTS ||
section->header.type == elf::SHT_RPL_CRCS ||
section->header.type == elf::SHT_NOBITS) {
continue;
}
if (!(section->header.flags & elf::SHF_EXECINSTR) &&
(section->header.flags & elf::SHF_WRITE) &&
(section->header.flags & elf::SHF_ALLOC)) {
section->header.offset = offset;
section->header.size = static_cast<uint32_t>(section->data.size());
offset += section->header.size;
}
}
// Next the "readMin / readMax" sections, which are:
// - !(flags & SHF_EXECINSTR) || type == SHT_RPL_EXPORTS
// - !(flags & SHF_WRITE)
// - flags & SHF_ALLOC
for (auto §ion : file.sections) {
if (section->header.size == 0 ||
section->header.type == elf::SHT_RPL_FILEINFO ||
section->header.type == elf::SHT_RPL_IMPORTS ||
section->header.type == elf::SHT_RPL_CRCS ||
section->header.type == elf::SHT_NOBITS) {
continue;
}
if ((!(section->header.flags & elf::SHF_EXECINSTR) ||
section->header.type == elf::SHT_RPL_EXPORTS) &&
!(section->header.flags & elf::SHF_WRITE) &&
(section->header.flags & elf::SHF_ALLOC)) {
section->header.offset = offset;
section->header.size = static_cast<uint32_t>(section->data.size());
offset += section->header.size;
}
}
// Import sections are part of the read sections, but have execinstr flag set
// so let's insert them here to avoid complicating the above logic.
for (auto §ion : file.sections) {
if (section->header.type == elf::SHT_RPL_IMPORTS) {
section->header.offset = offset;
section->header.size = static_cast<uint32_t>(section->data.size());
offset += section->header.size;
}
}
// Next the "textMin / textMax" sections, which are:
// - flags & SHF_EXECINSTR
// - type != SHT_RPL_EXPORTS
for (auto §ion : file.sections) {
if (section->header.size == 0 ||
section->header.type == elf::SHT_RPL_FILEINFO ||
section->header.type == elf::SHT_RPL_IMPORTS ||
section->header.type == elf::SHT_RPL_CRCS ||
section->header.type == elf::SHT_NOBITS) {
continue;
}
if ((section->header.flags & elf::SHF_EXECINSTR) &&
section->header.type != elf::SHT_RPL_EXPORTS) {
section->header.offset = offset;
section->header.size = static_cast<uint32_t>(section->data.size());
offset += section->header.size;
}
}
// Next the "tempMin / tempMax" sections, which are:
// - !(flags & SHF_EXECINSTR)
// - !(flags & SHF_ALLOC)
for (auto §ion : file.sections) {
if (section->header.size == 0 ||
section->header.type == elf::SHT_RPL_FILEINFO ||
section->header.type == elf::SHT_RPL_IMPORTS ||
section->header.type == elf::SHT_RPL_CRCS ||
section->header.type == elf::SHT_NOBITS) {
continue;
}
if (!(section->header.flags & elf::SHF_EXECINSTR) &&
!(section->header.flags & elf::SHF_ALLOC)) {
section->header.offset = offset;
section->header.size = static_cast<uint32_t>(section->data.size());
offset += section->header.size;
}
}
auto index = 0u;
for (auto §ion : file.sections) {
if (section->header.offset == 0 &&
section->header.type != elf::SHT_NULL &&
section->header.type != elf::SHT_NOBITS) {
fmt::print("Failed to calculate offset for section {}\n", index);
return false;
}
++index;
}
return true;
}
/**
* Write out the final RPL.
*/
static bool
writeRpl(ElfFile &file, const std::string &filename)
{
auto shoff = file.header.shoff;
// Write the file out
std::ofstream out { filename, std::ofstream::binary };
if (!out.is_open()) {
fmt::print("Could not open {} for writing\n", filename);
return false;
}
// Write file header
out.seekp(0, std::ios::beg);
out.write(reinterpret_cast<const char *>(&file.header), sizeof(elf::Header));
// Write section headers
out.seekp(shoff, std::ios::beg);
for (const auto §ion : file.sections) {
out.write(reinterpret_cast<const char *>(§ion->header), sizeof(elf::SectionHeader));
}
// Write sections
for (const auto §ion : file.sections) {
if (section->data.size()) {
out.seekp(section->header.offset, std::ios::beg);
out.write(section->data.data(), section->data.size());
}
}
return true;
}
int main(int argc, char **argv)
{
excmd::parser parser;
excmd::option_state options;
using excmd::description;
using excmd::value;
try {
parser.global_options()
.add_option("H,help",
description { "Show help." })
.add_option("r,rpl",
description { "Generate an RPL instead of an RPX" });
parser.default_command()
.add_argument("src",
description { "Path to input elf file" },
value<std::string> {})
.add_argument("dst",
description { "Path to output rpl file" },
value<std::string> {});
options = parser.parse(argc, argv);
} catch (excmd::exception ex) {
fmt::print("Error parsing options: {}\n", ex.what());
return -1;
}
if (options.empty()
|| options.has("help")
|| !options.has("src")
|| !options.has("dst")) {
fmt::print("{} <options> src dst\n", argv[0]);
fmt::print("{}\n", parser.format_help(argv[0]));
return 0;
}
auto src = options.get<std::string>("src");
auto dst = options.get<std::string>("dst");
auto isRpl = options.has("rpl");
// Read elf into memory object!
ElfFile elf;
if (!readElf(elf, src)) {
fmt::print("ERROR: readElf failed.\n");
return -1;
}
if (!fixRelocations(elf)) {
fmt::print("ERROR: fixRelocations failed.\n");
return -1;
}
if (!renameRplWrap(elf)) {
fmt::print("ERROR: renameRplWrap failed.\n");
return -1;
}
if (!fixLoaderVirtualAddresses(elf)) {
fmt::print("ERROR: fixLoaderVirtualAddresses failed.\n");
return -1;
}
if (!generateFileInfoSection(elf, isRpl ? 0 : elf::RPL_IS_RPX)) {
fmt::print("ERROR: generateFileInfoSection failed.\n");
return -1;
}
if (!generateCrcSection(elf)) {
fmt::print("ERROR: generateCrcSection failed.\n");
return -1;
}
if (!fixFileHeader(elf)) {
fmt::print("ERROR: fixFileHeader faile.\n");
return -1;
}
if (!deflateSections(elf)) {
fmt::print("ERROR: deflateSections failed.\n");
return -1;
}
if (!calculateSectionOffsets(elf)) {
fmt::print("ERROR: calculateSectionOffsets failed.\n");
return -1;
}
if (!writeRpl(elf, dst)) {
fmt::print("ERROR: writeRpl failed.\n");
return -1;
}
return 0;
}