-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathelf.cpp
More file actions
1661 lines (1536 loc) · 74.5 KB
/
elf.cpp
File metadata and controls
1661 lines (1536 loc) · 74.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
/**************************** elf.cpp *********************************
* Author: Agner Fog
* Date created: 2006-07-18
* Last modified: 2021-05-28
* Version: 1.13
* Project: Binary tools for ForwardCom instruction set
* Module: elf.cpp
* Description:
* Module for manipulating ForwardCom ELF files
*
* Class CELF is used for manipulating ELF files.
* It includes functions for reading, interpreting, dumping files,
* splitting into containers or joining containers into an ELF file
*
* This code is based on the ForwardCom ELF specification in elf_forwardcom.h.
* I have included limited support for x86-64 ELF (e_machine == EM_X86_64) for
* testing purposes. This may be removed.
*
* Copyright 2006-2024 GNU General Public License v. 3 http://www.gnu.org/licenses
*****************************************************************************/
#include "stdafx.h"
// File class names
SIntTxt ELFFileClassNames[] = {
{ELFCLASSNONE, "None"},
{ELFCLASS32, "32-bit object"},
{ELFCLASS64, "64-bit object"}
};
// Data encoding names
SIntTxt ELFDataEncodeNames[] = {
{ELFDATANONE, "None"},
{ELFDATA2LSB, "Little Endian"},
{ELFDATA2MSB, "Big Endian"}
};
// ABI names
SIntTxt ELFABINames[] = {
{ELFOSABI_SYSV, "System V"},
{ELFOSABI_HPUX, "HP-UX"},
{ELFOSABI_ARM, "ARM"},
{ELFOSABI_STANDALONE,"Embedded"},
{ELFOSABI_FORWARDCOM,"ForwardCom"}
};
// File type names
SIntTxt ELFFileTypeNames[] = {
{ET_NONE, "None"},
{ET_REL, "Relocatable"},
{ET_EXEC, "Executable"},
{ET_DYN, "Shared object"},
{ET_CORE, "Core file"}
};
// File header flag names
SIntTxt ELFFileFlagNames[] = {
{EF_INCOMPLETE, "Has unresolved references"},
{EF_RELINKABLE, "Relinkable"},
{EF_RELOCATE, "Relocate when loading"},
{EF_POSITION_DEPENDENT, "Position dependent"}
};
// Section type names
SIntTxt ELFSectionTypeNames[] = {
{SHT_NULL, "None"},
{SHT_PROGBITS, "Program data"},
{SHT_SYMTAB, "Symbol table"},
{SHT_STRTAB, "String table"},
{SHT_RELA, "Relocation w addends"},
{SHT_NOTE, "Notes"},
{SHT_NOBITS, "uinitialized"},
{SHT_COMDAT, "Communal section"},
{SHT_LIST, "List"}
// {SHT_HASH, "Symbol hash table"},
// {SHT_DYNAMIC, "Dynamic linking info"},
// {SHT_REL, "Relocation entries"},
// {SHT_SHLIB, "Reserved"},
// {SHT_DYNSYM, "Dynamic linker symbol table"},
// {SHT_GROUP, "Section group"},
};
// Program header type names
SIntTxt ELFPTypeNames[] = {
{PT_NULL, "Unused"},
{PT_LOAD, "Loadable program segment"},
{PT_DYNAMIC, "Dynamic linking information"},
{PT_INTERP, "Program interpreter"},
{PT_NOTE, "Auxiliary information"},
{PT_SHLIB, "Reserved"},
{PT_PHDR, "Entry for header table itself"}
};
// Section flag names
SIntTxt ELFSectionFlagNames[] = {
{SHF_EXEC, "executable"},
{SHF_WRITE, "writeable"},
{SHF_READ, "readable"},
{SHF_ALLOC, "allocate"},
{SHF_IP, "IP"},
{SHF_DATAP, "DATAP"},
{SHF_THREADP, "THREADP"},
{SHF_MERGE, "merge"},
{SHF_STRINGS, "strings"},
{SHF_INFO_LINK, "sh_info"},
{SHF_EVENT_HND, "event handler"},
{SHF_DEBUG_INFO, "debug info"},
{SHF_COMMENT, "comment"},
{SHF_RELINK, "relinkable"},
{SHF_AUTOGEN, "auto-generated"}
};
// Symbol binding names
SIntTxt ELFSymbolBindingNames[] = {
{STB_LOCAL, "local"},
{STB_GLOBAL, "global"},
{STB_WEAK, "weak"},
{STB_WEAK2, "weak2"},
{STB_UNRESOLVED, "unresolved"}
};
// Symbol Type names
SIntTxt ELFSymbolTypeNames[] = {
{STT_NOTYPE, "None"},
{STT_OBJECT, "Object"},
{STT_FUNC, "Function"},
{STT_SECTION, "Section"},
{STT_FILE, "File"},
{STT_CONSTANT, "Constant"}
};
// Symbol st_other info names
SIntTxt ELFSymbolInfoNames[] = {
{STV_EXEC, "executable"},
{STV_READ, "read"},
{STV_WRITE, "write"},
{STV_IP, "ip"},
{STV_DATAP, "datap"},
{STV_THREADP, "threadp"},
{STV_REGUSE, "reguse"},
{STV_FLOAT, "float"},
{STV_STRING, "string"},
{STV_UNWIND, "unwind"},
{STV_DEBUG, "debug"},
{STV_COMMON, "communal"},
{STV_RELINK, "relinkable"},
{STV_MAIN, "main"},
{STV_EXPORTED, "exported"},
{STV_THREAD, "thread"}
};
// Relocation type names x86 64 bit
SIntTxt ELF64RelocationNames[] = {
{R_X86_64_NONE, "None"},
{R_X86_64_64, "Direct 64 bit"},
{R_X86_64_PC32, "Self relative 32 bit signed"},
{R_X86_64_GOT32, "32 bit GOT entry"},
{R_X86_64_PLT32, "32 bit PLT address"},
{R_X86_64_COPY, "Copy symbol at runtime"},
{R_X86_64_GLOB_DAT, "Create GOT entry"},
{R_X86_64_JUMP_SLOT, "Create PLT entry"},
{R_X86_64_RELATIVE, "Adjust by program base"},
{R_X86_64_GOTPCREL, "32 bit signed pc relative offset to GOT"},
{R_X86_64_32, "Direct 32 bit zero extended"},
{R_X86_64_32S, "Direct 32 bit sign extended"},
{R_X86_64_16, "Direct 16 bit zero extended"},
{R_X86_64_PC16, "16 bit sign extended pc relative"},
{R_X86_64_8, "Direct 8 bit sign extended"},
{R_X86_64_PC8, "8 bit sign extended pc relative"},
{R_X86_64_IRELATIVE, "32 bit ref. to indirect function PLT"}
};
// Relocation type names for ForwardCom
SIntTxt ELFFwcRelocationTypes[] = {
{R_FORW_ABS, "Absolute address"},
{R_FORW_SELFREL, "Self relative"},
{R_FORW_IP_BASE, "Relative to __ip_base"},
{R_FORW_DATAP, "Relative to __datap_base"},
{R_FORW_THREADP, "Relative to __threadp_base"},
{R_FORW_REFP, "Relative to arbitrary reference point"},
{R_FORW_SYSFUNC, "System function ID"},
{R_FORW_SYSMODUL, "System module ID"},
{R_FORW_SYSCALL, "System module and function ID"},
{R_FORW_DATASTACK, "Size of data stack"},
{R_FORW_CALLSTACK, "Size of call stack"},
{R_FORW_REGUSE, "Register use"}
};
// Relocation sizes for ForwardCom
SIntTxt ELFFwcRelocationSizes[] = {
{R_FORW_NONE, "None"},
{R_FORW_8, "8 bit"},
{R_FORW_16, "16 bit"},
{R_FORW_24, "24 bit"},
{R_FORW_32, "32 bit"},
{R_FORW_64, "64 bit"},
{R_FORW_32LO, "Low 16 of 32 bits"},
{R_FORW_32HI, "High 16 of 32 bits"},
{R_FORW_64LO, "Low 32 of 64 bits"},
{R_FORW_64HI, "High 32 of 64 bits"}
};
// Machine names
SIntTxt ELFMachineNames[] = {
{EM_NONE, "None"}, // No machine
{EM_FORWARDCOM, "ForwardCom"},
{EM_M32, "AT&T WE 32100"},
{EM_SPARC, "SPARC"},
{EM_386, "Intel x86"},
{EM_68K, "Motorola m68k"},
{EM_88K, "Motorola m88k"},
{EM_860, "MIPS R3000 big-endian"},
{EM_MIPS, "MIPS R3000 big-endian"},
{EM_S370, "IBM System/370"},
{EM_MIPS_RS3_LE, "NMIPS R3000 little-endianone"},
{EM_PARISC, "HPPA"},
{EM_VPP500, "Fujitsu VPP500"},
{EM_SPARC32PLUS, "Sun v8plus"},
{EM_960, "Intel 80960"},
{EM_PPC, "PowerPC"},
{EM_PPC64, "PowerPC 64-bit"},
{EM_S390, "IBM S390"},
{EM_V800, "NEC V800"},
{EM_FR20, "Fujitsu FR20"},
{EM_RH32, "TRW RH-32"},
{EM_RCE, "Motorola RCE"},
{EM_ARM, "ARM"},
{EM_FAKE_ALPHA, "Digital Alpha"},
{EM_SH, "Hitachi SH"},
{EM_SPARCV9, "SPARC v9 64-bit"},
{EM_TRICORE, "Siemens Tricore"},
{EM_ARC, "Argonaut RISC"},
{EM_H8_300, "Hitachi H8/300"},
{EM_H8_300H, "Hitachi H8/300H"},
{EM_H8S, "Hitachi H8S"},
{EM_H8_500, "EM_H8_500"},
{EM_IA_64, "Intel IA64"},
{EM_MIPS_X, "Stanford MIPS-X"},
{EM_COLDFIRE, "Motorola Coldfire"},
{EM_68HC12, "Motorola M68HC12"},
{EM_MMA, "Fujitsu MMA"},
{EM_PCP, "Siemens PCP"},
{EM_NCPU, "Sony nCPU"},
{EM_NDR1, "Denso NDR1"},
{EM_STARCORE, "Motorola Start*Core"},
{EM_ME16, "Toyota ME16"},
{EM_ST100, "ST100"},
{EM_TINYJ, "Tinyj"},
{EM_X86_64, "x86-64"},
{EM_PDSP, "Sony DSP"},
{EM_FX66, "Siemens FX66"},
{EM_ST9PLUS, "ST9+ 8/16"},
{EM_ST7, "ST7 8"},
{EM_68HC16, "MC68HC16"},
{EM_68HC11, "MC68HC11"},
{EM_68HC08, "MC68HC08"},
{EM_68HC05, "MC68HC05"},
{EM_SVX, "SVx"},
{EM_AT19, "ST19"},
{EM_VAX, "VAX"},
{EM_CRIS, "Axis"},
{EM_JAVELIN, "Infineon"},
{EM_FIREPATH, "Element 14"},
{EM_ZSP, "LSI Logic"},
{EM_HUANY, "Harvard"},
{EM_PRISM, "SiTera Prism"},
{EM_AVR, "Atmel AVR"},
{EM_FR30, "FR30"},
{EM_D10V, "D10V"},
{EM_D30V, "D30V"},
{EM_V850, "NEC v850"},
{EM_M32R, "M32R"},
{EM_MN10300, "MN10300"},
{EM_MN10200, "MN10200"},
{EM_PJ, "picoJava"},
{EM_ALPHA, "Alpha"}
};
// Class CELF members:
// Constructor
CELF::CELF() {
zeroAllMembers(*this);
}
// ParseFile
void CELF::parseFile() {
// Load and parse file buffer
uint32_t i;
if (dataSize() == 0) {
nSections = 0;
return;
}
fileHeader = *(ElfFwcEhdr*)buf(); // Copy file header
nSections = fileHeader.e_shnum;
sectionHeaders.setNum(nSections); // Allocate space for section headers
uint32_t symtabi = 0; // Index to symbol table
// Find section headers
sectionHeaderSize = fileHeader.e_shentsize;
if (sectionHeaderSize <= 0) err.submit(ERR_ELF_RECORD_SIZE);
uint32_t SectionOffset = uint32_t(fileHeader.e_shoff);
// check header integrity
if (fileHeader.e_phoff >= dataSize() || fileHeader.e_phoff + (uint32_t)fileHeader.e_phentsize * fileHeader.e_phnum > dataSize()) err.submit(ERR_ELF_INDEX_RANGE);
if (fileHeader.e_shoff >= dataSize() || fileHeader.e_shoff + (uint32_t)fileHeader.e_shentsize * fileHeader.e_shnum > dataSize()) err.submit(ERR_ELF_INDEX_RANGE);
if (fileHeader.e_shstrndx >= dataSize()) err.submit(ERR_ELF_INDEX_RANGE);
if (err.number())
return;
for (i = 0; i < nSections; i++) {
sectionHeaders[i] = get<ElfFwcShdr>(SectionOffset);
// check section header integrity
if (sectionHeaders[i].sh_offset > dataSize()
|| (sectionHeaders[i].sh_offset + sectionHeaders[i].sh_size > dataSize() && sectionHeaders[i].sh_type != SHT_NOBITS)
|| sectionHeaders[i].sh_offset + sectionHeaders[i].sh_entsize > dataSize()) {
err.submit(ERR_ELF_INDEX_RANGE);
}
SectionOffset += sectionHeaderSize;
if (sectionHeaders[i].sh_type == SHT_SYMTAB) {
// Symbol table found
symtabi = i;
}
}
if (SectionOffset > dataSize()) err.submit(ERR_ELF_INDEX_RANGE); // Section table points to outside file
if (buf() && dataSize()) { // string table
uint64_t offset = sectionHeaders[fileHeader.e_shstrndx].sh_offset;
secStringTable = (char*)buf() + uint32_t(offset);
secStringTableLen = uint32_t(sectionHeaders[fileHeader.e_shstrndx].sh_size);
if (offset > dataSize() || offset + secStringTableLen > dataSize()) err.submit(ERR_ELF_INDEX_RANGE);
}
// check section names
for (i = 0; i < nSections; i++) {
if (sectionHeaders[i].sh_name >= secStringTableLen) { err.submit(ERR_ELF_STRING_TABLE); break; }
}
if (symtabi) {
// Save offset to symbol table
uint64_t offset = sectionHeaders[symtabi].sh_offset;
symbolTableOffset = (uint32_t)offset;
symbolTableEntrySize = (uint32_t)(sectionHeaders[symtabi].sh_entsize); // Entry size of symbol table
if (symbolTableEntrySize == 0) { err.submit(ERR_ELF_SYMTAB_MISSING); return; } // Avoid division by zero
symbolTableEntries = uint32_t(sectionHeaders[symtabi].sh_size) / symbolTableEntrySize;
if (offset > dataSize() || offset > 0xFFFFFFFFU || offset + sectionHeaders[symtabi].sh_entsize > dataSize()
|| offset + sectionHeaders[symtabi].sh_size > dataSize()) err.submit(ERR_ELF_INDEX_RANGE);
// Find associated string table
uint32_t stringtabi = sectionHeaders[symtabi].sh_link;
if (stringtabi >= nSections) {
err.submit(ERR_ELF_INDEX_RANGE);
return;
}
offset = sectionHeaders[stringtabi].sh_offset;
symbolStringTableOffset = (uint32_t)offset;
symbolStringTableSize = (uint32_t)(sectionHeaders[stringtabi].sh_size);
if (offset > dataSize() || offset > 0xFFFFFFFFU || offset + sectionHeaders[stringtabi].sh_size > dataSize()) err.submit(ERR_ELF_INDEX_RANGE);
// check all symbol names
int8_t * symtab = buf() + symbolTableOffset;
uint32_t symname = 0;
for (uint32_t symi = 0; symi < symbolTableEntries; symi++) {
// Copy ElfFwcSym symbol or convert Elf64_Sym symbol
if (fileHeader.e_machine == EM_FORWARDCOM) {
symname = ((ElfFwcSym*)symtab)[symi].st_name;
}
else {
// x64 type symbol table entry
symname = ((Elf64_Sym*)symtab)[symi].st_name;
}
if (symname >= symbolStringTableSize) err.submit(ERR_ELF_STRING_TABLE);
}
}
}
// Dump
void CELF::dump(int options) {
printf("\nDump of ELF file %s", cmd.getFilename(cmd.inputFile));
if (options == 0) options = DUMP_FILEHDR;
if (options & DUMP_FILEHDR) {
// File header
printf("\n-----------------------------------------------");
printf("\nFile size: %i", dataSize());
printf("\nFile header:");
printf("\nFile class: %s, Data encoding: %s, ELF version %i, ABI: %s, ABI version %i",
Lookup(ELFFileClassNames, fileHeader.e_ident[EI_CLASS]),
Lookup(ELFDataEncodeNames, fileHeader.e_ident[EI_DATA]),
fileHeader.e_ident[EI_VERSION],
Lookup(ELFABINames, fileHeader.e_ident[EI_OSABI]),
fileHeader.e_ident[EI_ABIVERSION]);
printf("\nFile type: %s, Machine: %s, version: %i",
Lookup(ELFFileTypeNames, fileHeader.e_type),
Lookup(ELFMachineNames, fileHeader.e_machine),
fileHeader.e_version);
printf("\nNumber of sections: %2i", nSections);
if (fileHeader.e_machine == EM_FORWARDCOM) {
printf("\nip_base: 0x%X, datap_base: 0x%X, threadp_base: 0x%X, entry_point: 0x%X",
(uint32_t)fileHeader.e_ip_base, (uint32_t)fileHeader.e_datap_base, (uint32_t)fileHeader.e_threadp_base, (uint32_t)fileHeader.e_entry);
}
}
// Always show flags
if (fileHeader.e_flags) {
printf("\nFlags:");
for (int i = 0; i < 32; i++) {
if (fileHeader.e_flags & (1 << i)) {
printf(" %s,", Lookup(ELFFileFlagNames, 1 << i));
}
}
}
if (options & DUMP_LINKMAP) {
fprintf(stdout, "\nLink map:\n");
makeLinkMap(stdout);
}
if (options & DUMP_RELINKABLE) {
// Show names of relinkable modules and libraries
CDynamicArray<SLCommand> mnames; // list of relinkable modules
CDynamicArray<SLCommand> lnames; // list of relinkable libraries
SLCommand nameRec; // record containing name
uint32_t r; // record index
uint32_t sec; // section index
const char * modName; // module name
const char * libName; // library name
// loop through sections
for (sec = 0; sec < sectionHeaders.numEntries(); sec++) {
ElfFwcShdr & secHdr = sectionHeaders[sec];
if (secHdr.sh_type == 0) continue;
if (secHdr.sh_flags & SHF_RELINK) {
// section is relinkable
if (secHdr.sh_library && secHdr.sh_library < secStringTableLen) {
libName = secStringTable + secHdr.sh_library; // library name
nameRec.value = cmd.fileNameBuffer.pushString(libName);
lnames.addUnique(nameRec); // add only one instance to lnames
}
if (secHdr.sh_module && secHdr.sh_module < secStringTableLen) {
modName = secStringTable + secHdr.sh_module; // module name
nameRec.value = cmd.fileNameBuffer.pushString(modName);
mnames.addUnique(nameRec); // add only one instance to mnames
}
}
}
if (lnames.numEntries()) {
printf("\n\nRelinkable libraries:");
for (r = 0; r < lnames.numEntries(); r++) {
printf("\n %s", cmd.getFilename((uint32_t)lnames[r].value));
}
}
if (mnames.numEntries()) {
printf("\n\nRelinkable modules:");
for (r = 0; r < mnames.numEntries(); r++) {
printf("\n %s", cmd.getFilename((uint32_t)mnames[r].value));
}
}
}
if ((options & DUMP_SECTHDR) && fileHeader.e_phnum) {
// Dump program headers
printf("\n\nProgram headers:");
uint32_t nProgramHeaders = fileHeader.e_phnum;
uint32_t programHeaderSize = fileHeader.e_phentsize;
if (nProgramHeaders && programHeaderSize <= 0) err.submit(ERR_ELF_RECORD_SIZE);
uint32_t programHeaderOffset = (uint32_t)fileHeader.e_phoff;
ElfFwcPhdr pHeader;
for (uint32_t i = 0; i < nProgramHeaders; i++) {
pHeader = get<ElfFwcPhdr>(programHeaderOffset);
printf("\nProgram header Type: %s, flags 0x%X",
Lookup(ELFPTypeNames, (uint32_t)pHeader.p_type), (uint32_t)pHeader.p_flags);
printf("\noffset = 0x%X, vaddr = 0x%X, paddr = 0x%X, filesize = 0x%X, memsize = 0x%X, align = 0x%X",
(uint32_t)pHeader.p_offset, (uint32_t)pHeader.p_vaddr, (uint32_t)pHeader.p_paddr, (uint32_t)pHeader.p_filesz, (uint32_t)pHeader.p_memsz, 1 << pHeader.p_align);
programHeaderOffset += programHeaderSize;
if (pHeader.p_filesz < 0x100 && (uint32_t)pHeader.p_offset < dataSize() && (pHeader.p_flags & SHF_STRINGS)) {
printf("\nContents: %s", buf() + (int)pHeader.p_offset);
}
}
}
if (options & DUMP_SECTHDR) {
// Dump section headers
printf("\n\nSection headers:");
for (uint32_t sc = 0; sc < nSections; sc++) {
// Get copy of 32-bit header or converted 64-bit header
ElfFwcShdr sheader = sectionHeaders[sc];
uint32_t entrysize = (uint32_t)(sheader.sh_entsize);
uint32_t namei = sheader.sh_name;
if (namei >= secStringTableLen) { err.submit(ERR_ELF_STRING_TABLE); break; }
printf("\n%2i Name: %-18s Type: %s", sc, secStringTable + namei,
Lookup(ELFSectionTypeNames, sheader.sh_type));
if (sheader.sh_flags) {
printf("\n Flags: 0x%X:", uint32_t(sheader.sh_flags));
for (uint32_t fi = 1; fi != 0; fi <<= 1) {
if (uint32_t(sheader.sh_flags) & fi) {
printf(" %s", Lookup(ELFSectionFlagNames, fi));
}
}
}
//if (sheader.sh_addr)
printf("\n Address: 0x%X", uint32_t(sheader.sh_addr));
if (sheader.sh_offset || sheader.sh_size) {
printf("\n FileOffset: 0x%X, Size: 0x%X",
uint32_t(sheader.sh_offset), uint32_t(sheader.sh_size));
}
if (sheader.sh_align) {
printf("\n Alignment: 0x%X", 1 << sheader.sh_align);
}
if (sheader.sh_entsize) {
printf("\n Entry size: 0x%X", uint32_t(sheader.sh_entsize));
switch (sheader.sh_type) {
/*
case SHT_DYNAMIC:
printf("\n String table: %i", sheader.sh_link);
break;
case SHT_HASH:
printf("\n Symbol table: %i", sheader.sh_link);
break; */
case SHT_RELA: // case SHT_REL:
printf("\n Symbol table: %i",
sheader.sh_link);
break;
case SHT_SYMTAB: //case SHT_DYNSYM:
printf("\n Symbol string table: %i, First global symbol: %i",
sheader.sh_link, sheader.sh_module);
break;
default:
if (sheader.sh_link) {
printf("\n Link: %i", sheader.sh_link);
}
if (sheader.sh_module) {
printf("\n Info: %i", sheader.sh_module);
}
}
}
if (sheader.sh_module && sheader.sh_module < secStringTableLen) {
printf("\n Module: %s", secStringTable + sheader.sh_module);
if (sheader.sh_library) printf(", Library: %s", secStringTable + sheader.sh_library);
}
if (sheader.sh_type == SHT_STRTAB && (options & DUMP_STRINGTB)) {
// Print string table
printf("\n String table:");
char * p = (char*)buf() + uint32_t(sheader.sh_offset) + 1;
uint32_t nread = 1, len;
while (nread < uint32_t(sheader.sh_size)) {
len = (uint32_t)strlen(p);
printf(" >>%s<<", p);
nread += len + 1;
p += len + 1;
}
}
if ((sheader.sh_type == SHT_SYMTAB) && (options & DUMP_SYMTAB)) {
// Dump symbol table
// Find associated string table
if (sheader.sh_link >= (uint32_t)nSections) { err.submit(ERR_ELF_INDEX_RANGE); sheader.sh_link = 0; }
uint64_t strtabOffset = sectionHeaders[sheader.sh_link].sh_offset;
if (strtabOffset >= dataSize()) {
err.submit(ERR_ELF_INDEX_RANGE); return;
}
int8_t * strtab = buf() + strtabOffset;
// Find symbol table
uint32_t symtabsize = (uint32_t)(sheader.sh_size);
int8_t * symtab = buf() + uint32_t(sheader.sh_offset);
int8_t * symtabend = symtab + symtabsize;
if (entrysize < sizeof(Elf64_Sym)) { err.submit(ERR_ELF_RECORD_SIZE); entrysize = sizeof(Elf64_Sym); }
printf("\n Symbols:");
// Loop through symbol table
int symi; // Symbol number
for (symi = 0; symtab < symtabend; symtab += entrysize, symi++) {
// Copy ElfFwcSym symbol or convert Elf64_Sym symbol
ElfFwcSym sym;
if (fileHeader.e_machine == EM_FORWARDCOM) {
sym = *(ElfFwcSym*)symtab;
}
else {
// Translate x64 type symbol table entry
Elf64_Sym sym64 = *(Elf64_Sym*)symtab;
sym.st_name = sym64.st_name;
sym.st_type = sym64.st_type;
sym.st_bind = sym64.st_bind;
sym.st_other = sym64.st_other;
sym.st_section = sym64.st_section;
sym.st_value = sym64.st_value;
sym.st_unitsize = (uint32_t)sym64.st_size;
sym.st_unitnum = 1;
sym.st_reguse1 = sym.st_reguse2 = 0;
}
int type = sym.st_type;
int binding = sym.st_bind;
if (strtabOffset + sym.st_name >= dataSize()) err.submit(ERR_ELF_INDEX_RANGE);
else if (*(strtab + sym.st_name)) {
printf("\n %2i Name: %s,", symi, strtab + sym.st_name);
}
else {
printf("\n %2i Unnamed,", symi);
}
if (sym.st_value || type == STT_OBJECT || type == STT_FUNC || (int16_t)sym.st_section == SHN_ABS_X86) {
printf(" Value: 0x%X", uint32_t(sym.st_value));
}
if (sym.st_unitsize) printf(" size: %X*%X", sym.st_unitsize, sym.st_unitnum);
if (sym.st_other) {
for (int i = 0; i < 32; i++) {
if (sym.st_other & 1 << i) {
printf(" %s", Lookup(ELFSymbolInfoNames, 1 << i));
}
}
}
if (sym.st_reguse1 | sym.st_reguse2) {
printf(", register use 0x%X, 0x%X", sym.st_reguse1, sym.st_reguse2);
}
//if (int32_t(sym.st_section) > 0) printf(", section: %i", sym.st_section);
//else { // Special segment values
if (sym.st_section == 0) {
printf(" extern,");
}
else if (sym.st_type == STT_CONSTANT) {
printf(", absolute,");
}
else {
printf(", section: 0x%X", sym.st_section);
}
if (sym.st_type || sym.st_bind) {
printf(" type: %s, binding: %s",
Lookup(ELFSymbolTypeNames, type),
Lookup(ELFSymbolBindingNames, binding));
}
}
}
// Dump relocation table
if ((sheader.sh_type == SHT_RELA) && (options & DUMP_RELTAB)) {
printf("\n Relocations:");
int8_t * reltab = buf() + uint32_t(sheader.sh_offset);
int8_t * reltabend = reltab + uint32_t(sheader.sh_size);
/*
uint32_t expectedentrysize = sheader.sh_type == SHT_RELA ?
sizeof(Elf64_Rela) : // Elf32_Rela, Elf64_Rela
sizeof(Elf64_Rela) - wordSize / 8; // Elf32_Rel, Elf64_Rel
*/
uint32_t expectedentrysize = sizeof(Elf64_Rela);
if (entrysize < expectedentrysize) { err.submit(ERR_ELF_RECORD_SIZE); entrysize = expectedentrysize; }
// Loop through entries
for (; reltab < reltabend; reltab += entrysize) {
// Copy relocation table entry with or without addend
ElfFwcReloc rel = *(ElfFwcReloc*)reltab;
const char * relocationName, *relocationSize;
char text[128];
if (machineType == EM_X86_64) {
relocationName = Lookup(ELF64RelocationNames, rel.r_type);
}
else if (machineType == EM_FORWARDCOM) {
relocationName = Lookup(ELFFwcRelocationTypes, rel.r_type & R_FORW_RELTYPEMASK);
relocationSize = Lookup(ELFFwcRelocationSizes, rel.r_type & R_FORW_RELSIZEMASK);
sprintf(text, "%s, %s, scale by %i", relocationName, relocationSize,
1 << (rel.r_type & 0xFF));
relocationName = text;
}
else {
relocationName = "unknown";
}
memcpy(&rel, reltab, entrysize);
printf("\n Section: %i, Offset: 0x%X, Symbol: %i, Name: %s\n Type: %s", rel.r_section,
uint32_t(rel.r_offset), rel.r_sym, symbolName(rel.r_sym), relocationName);
if (machineType == EM_FORWARDCOM && rel.r_type >> 16 == 8) {
printf(", ref. point %i", rel.r_refsym);
}
if (uint32_t(rel.r_addend)) {
printf(", Addend: 0x%X", uint32_t(rel.r_addend));
}
/* Inline addend not used by ForwardCom
// Find inline addend
ElfFwcShdr relsheader = sectionHeaders[rel.r_section];
uint32_t relsoffset = uint32_t(relsheader.sh_offset);
if (relsoffset + rel.r_offset < dataSize() && relsheader.sh_type != SHT_NOBITS) {
int32_t * piaddend = (int32_t*)(buf() + relsoffset + rel.r_offset);
if (*piaddend) printf(", Inline value: 0x%X", *piaddend);
}*/
}
}
}
}
}
// PublicNames
void CELF::listSymbols(CMemoryBuffer * strings, CDynamicArray<SSymbolEntry> * index, uint32_t m, uint32_t l, int scope) {
// Make list of public and external symbols, including weak symbols
// SStringEntry::member is set to m and library is set to l;
// scope: 1: exported,
// 2: imported (includes STB_WEAK2),
// 3: both
// Interpret header:
parseFile();
if (err.number()) return;
// Loop through section headers
for (uint32_t sc = 0; sc < nSections; sc++) {
// Get copy of 32-bit header or converted 64-bit header
ElfFwcShdr sheader = sectionHeaders[sc];
uint32_t entrysize = uint32_t(sheader.sh_entsize);
if (sheader.sh_type == SHT_SYMTAB) {
// Find associated string table
if (sheader.sh_link >= (uint32_t)nSections) { err.submit(ERR_ELF_INDEX_RANGE); sheader.sh_link = 0; }
int8_t * strtab = buf() + uint32_t(sectionHeaders[sheader.sh_link].sh_offset);
// Find symbol table
uint32_t symtabsize = uint32_t(sheader.sh_size);
int8_t * symtab = buf() + uint32_t(sheader.sh_offset);
int8_t * symtabend = symtab + symtabsize;
if (entrysize < sizeof(Elf64_Sym)) { err.submit(ERR_ELF_RECORD_SIZE); entrysize = sizeof(Elf64_Sym); }
// Loop through symbol table
for (int symi = 0; symtab < symtabend; symtab += entrysize, symi++) {
// Copy ElfFwcSym symbol table entry or convert Elf64_Sym bit entry
ElfFwcSym sym;
if (fileHeader.e_machine == EM_FORWARDCOM) {
sym = *(ElfFwcSym*)symtab;
}
else {
// Translate x64 type symbol table entry
Elf64_Sym sym64 = *(Elf64_Sym*)symtab;
sym.st_name = sym64.st_name;
sym.st_type = sym64.st_type;
sym.st_bind = sym64.st_bind;
sym.st_other = sym64.st_other;
sym.st_section = sym64.st_section;
sym.st_value = sym64.st_value;
sym.st_unitsize = (uint32_t)sym64.st_size;
sym.st_unitnum = 1;
sym.st_reguse1 = sym.st_reguse2 = 0;
}
int type = sym.st_type;
int binding = sym.st_bind;
if (type != STT_SECTION && type != STT_FILE && (binding & (STB_GLOBAL | STB_WEAK))) {
// Public or external symbol found
if (((scope & 1) && (sym.st_section != 0)) // scope 1: public
|| ((scope & 2) && (sym.st_section == 0 || binding == STB_WEAK2))) { // scope 2: external
SSymbolEntry se;
se.member = m;
se.library = l;
se.st_type = type;
se.st_bind = binding;
se.symindex = symi;
se.sectioni = sym.st_section;
se.st_other = (uint16_t)sym.st_other;
se.status = (scope & 1) << 1;
// Store name
const char * name = (char*)strtab + sym.st_name;
se.name = strings->pushString(name);
// Store name index
index->push(se);
}
}
}
}
}
}
// get a symbol record
ElfFwcSym * CELF::getSymbol(uint32_t symindex) {
if (symbolTableOffset) {
uint32_t symi = symbolTableOffset + symindex * symbolTableEntrySize;
if (symi < dataSize()) {
return &get<ElfFwcSym>(symi);
}
}
return 0;
}
// SymbolName
const char * CELF::symbolName(uint32_t index) {
// Get name of symbol. (ParseFile() must be called first)
const char * symname = 0; // Symbol name
uint32_t symi; // Symbol index
uint32_t stri; // String index
if (symbolTableOffset) {
symi = symbolTableOffset + index * symbolTableEntrySize;
if (symi < dataSize()) {
stri = get<Elf64_Sym>(symi).st_name;
if (stri < symbolStringTableSize) {
symname = (char*)buf() + symbolStringTableOffset + stri;
}
}
}
return symname;
}
// split ELF file into container classes
int CELF::split() {
uint32_t sc; // Section index
uint32_t type; // Section type
if (dataSize() == 0) return 0;
parseFile(); // Parse file, get section headers, check integrity
CDynamicArray<ElfFwcShdr> newSectionHeaders; // Remake list of section headers
newSectionHeaders.setSize(nSections*(uint32_t)sizeof(ElfFwcShdr)); // Reserve space but leave getNumEntries() zero
CDynamicArray<uint32_t> sectionIndexTrans; // Translate old section indices to new indices
sectionIndexTrans.setNum(nSections + 2);
// Make program headers list
uint32_t nProgramHeaders = fileHeader.e_phnum;
uint32_t programHeaderSize = fileHeader.e_phentsize;
if (nProgramHeaders && programHeaderSize <= 0) err.submit(ERR_ELF_RECORD_SIZE);
uint32_t programHeaderOffset = (uint32_t)fileHeader.e_phoff;
ElfFwcPhdr pHeader;
for (uint32_t i = 0; i < nProgramHeaders; i++) {
pHeader = get<ElfFwcPhdr>(programHeaderOffset + i * programHeaderSize);
if (pHeader.p_filesz > 0 && (uint32_t)pHeader.p_offset < dataSize()) {
uint32_t phOffset = dataBuffer.push(buf() + (uint32_t)pHeader.p_offset, (uint32_t)pHeader.p_filesz);
pHeader.p_offset = phOffset; // New offset refers to dataBuffer
}
programHeaders.push(pHeader); // Save in programHeaders list
}
// Make section list
// Make dummy empty section
ElfFwcShdr sheader2;
zeroAllMembers(sheader2);
newSectionHeaders.push(sheader2);
for (sc = 0; sc < nSections; sc++) {
// Copy section header
sheader2 = sectionHeaders[sc]; // sectionHeaders[] was filled by ParseFile()
type = sheader2.sh_type; // Section type
if (type == SHT_NULL /* && sc == 0 */) continue; // skip first/all empty section headers
// Skip symbol, relocation, and string tables. They are converted to containers:
if (type == SHT_SYMTAB || type == SHT_STRTAB || type == SHT_RELA) continue;
// Get section name
uint32_t namei = sheader2.sh_name;
if (namei >= secStringTableLen) { err.submit(ERR_ELF_STRING_TABLE); return ERR_ELF_STRING_TABLE; }
const char * Name = secStringTableLen ? secStringTable + namei : "???";
// Copy name to sectionNameBuffer
uint32_t nameo = stringBuffer.pushString(Name);
sheader2.sh_name = nameo; // New name index refers to sectionNameBuffer
// Get section data
int8_t * sectionData = buf() + sheader2.sh_offset;
uint32_t InitSize = (sheader2.sh_type == SHT_NOBITS) ? 0 : (uint32_t)sheader2.sh_size;
if (InitSize) {
// Copy data to dataBuffer
uint32_t newOffset = dataBuffer.push(sectionData, InitSize);
sheader2.sh_offset = newOffset; // New offset refers to dataBuffer
}
else {
sheader2.sh_offset = dataBuffer.dataSize();
}
// Save modified header and new index
sectionIndexTrans[sc] = newSectionHeaders.numEntries();
newSectionHeaders.push(sheader2);
}
// Make symbol list
// Allocate array for translating symbol indices for multiple symbol tables
// in source file to a single symbol table in the symbols container
CDynamicArray<uint32_t> SymbolTableOffset; // Offset of new symbol table indices relative to old indices
SymbolTableOffset.setNum(nSections + 1);
uint32_t NumSymbols = 0;
for (sc = 0; sc < nSections; sc++) {
ElfFwcShdr & sheader = sectionHeaders[sc];
uint32_t entrysize = (uint32_t)(sheader.sh_entsize);
if (sheader.sh_type == SHT_SYMTAB) {
// This is a symbol table
// Offset for symbols in this symbol table = number of preceding symbols from other symbol tables
// Symbol number in joined table = symi1 + number of symbols in preceding tables
SymbolTableOffset[sc] = NumSymbols;
// Find associated string table
if (sheader.sh_link >= nSections) { err.submit(ERR_ELF_INDEX_RANGE); sheader.sh_link = 0; }
uint32_t strtabOffset = (uint32_t)sectionHeaders[sheader.sh_link].sh_offset;
if (sectionHeaders[sheader.sh_link].sh_offset >= dataSize()) err.submit(ERR_ELF_INDEX_RANGE);
// Find symbol table
uint32_t symtabsize = (uint32_t)(sheader.sh_size);
int8_t * symtab = buf() + uint32_t(sheader.sh_offset);
int8_t * symtabend = symtab + symtabsize;
if (entrysize < (uint32_t)sizeof(Elf64_Sym)) {
err.submit(ERR_ELF_RECORD_SIZE); entrysize = (uint32_t)sizeof(ElfFwcSym);
}
// Loop through symbol table
uint32_t symi1; // Symbol number in this table
ElfFwcSym sym; // copy of symbol table entry
for (symi1 = 0; symtab < symtabend; symtab += entrysize, symi1++) {
// Copy or convert symbol table entry
if (fileHeader.e_machine == EM_FORWARDCOM) {
sym = *(ElfFwcSym*)symtab;
}
else {
// Translate x64 type symbol table entry
Elf64_Sym sym64 = *(Elf64_Sym*)symtab;
sym.st_name = sym64.st_name;
sym.st_type = sym64.st_type;
sym.st_bind = sym64.st_bind;
sym.st_other = sym64.st_other;
sym.st_section = sym64.st_section;
sym.st_value = sym64.st_value;
sym.st_unitsize = (uint32_t)sym64.st_size;
sym.st_unitnum = 1;
sym.st_reguse1 = sym.st_reguse2 = 0;
}
// if (sym.st_type == STT_NOTYPE && symi1 == 0) continue; // Include empty symbols to avoid changing indexes
// Translate section index in symbol record
if (sym.st_section < sectionIndexTrans.numEntries()) {
sym.st_section = sectionIndexTrans[sym.st_section];
}
// Get name
if (sym.st_name) {
if ((uint64_t)strtabOffset + sym.st_name > dataSize()) err.submit(ERR_ELF_INDEX_RANGE);
else {
const char * symName = (char*)buf() + strtabOffset + sym.st_name;
sym.st_name = stringBuffer.pushString(symName);
}
}
// Put name in symbolNameBuffer and update string index
symbols.push(sym);
// Count symbols
NumSymbols++;
}
}
}
// Make relocation list
union {
Elf64_Rela a;
ElfFwcReloc r2;
} rel;
// Loop through sections
for (sc = 0; sc < nSections; sc++) {
// Get section header
ElfFwcShdr & sheader = sectionHeaders[sc];
if (sheader.sh_type == SHT_RELA) {
// Relocations section
int8_t * reltab = buf() + uint32_t(sheader.sh_offset);
int8_t * reltabend = reltab + uint32_t(sheader.sh_size);
int entrysize = (uint32_t)(sheader.sh_entsize);
//int expectedentrysize = sheader.sh_type == SHT_RELA ? sizeof(Elf64_Rela) : 16; // Elf64_Rela : Elf64_Rel
int expectedentrysize = sizeof(Elf64_Rela);
if (entrysize < expectedentrysize) {
err.submit(ERR_ELF_RECORD_SIZE); entrysize = expectedentrysize;
}
int32_t symbolSection = (int32_t)sheader.sh_link; // Symbol section, old index
if (symbolSection <= 0 || (uint32_t)symbolSection >= nSections) {
err.submit(ERR_ELF_SYMTAB_MISSING); return ERR_ELF_SYMTAB_MISSING;
}
// Symbol offset is zero if there is only one symbol section, which is the normal case
uint32_t symbolOffset = SymbolTableOffset[symbolSection];
// Loop through entries
for (; reltab < reltabend; reltab += entrysize) {
// Copy or translate relocation table entry
if (fileHeader.e_machine == EM_X86_64) {
// Translate relocation type
rel.a = *(Elf64_Rela*)reltab;
//if (sheader.sh_type == SHT_REL) rel.a.r_addend = 0;
switch (rel.a.r_type) {
case R_X86_64_64: // Direct 64 bit
rel.a.r_type = R_FORW_ABS | R_FORW_64;
break;
case R_X86_64_PC32: // Self relative 32 bit signed (not RIP relative in the sense used in COFF files)
rel.a.r_type = R_FORW_SELFREL | R_FORW_32;
break;
case R_X86_64_32: // Direct 32 bit zero extended
case R_X86_64_32S: // Direct 32 bit sign extended
rel.a.r_type = R_FORW_ABS | R_FORW_32;
break;
}
rel.r2.r_refsym = 0;
rel.r2.r_section = sheader.sh_module; // sh_module = sh_info in x86
}
else {
rel.r2 = *(ElfFwcReloc*)reltab;
}
// Target symbol
rel.r2.r_sym += symbolOffset;
if (rel.r2.r_refsym) rel.r2.r_refsym += symbolOffset;