-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathpe.c
1267 lines (1133 loc) · 41.8 KB
/
pe.c
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
/* https://docs.microsoft.com/en-us/windows/win32/debug/pe-format
MSDOS stub
PE signature
COFF file header
optional header
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "backend.h"
#include "config.h"
#pragma pack(1)
#define PE_MAGIC "PE\0\0"
#define MAGIC_SIZE 4
#define MAGIC_LOCATOR 0x3C
#define STATE_ID_NORMAL 0x10B
#define STATE_ID_ROM 0x107
#define STATE_ID_PE32PLUS 0x20B
#define IMAGE_FILE_MACHINE_UNKNOWN 0x0 //The contents of this field are assumed to be applicable to any machine type
#define IMAGE_FILE_MACHINE_AM33 0x1d3 //Matsushita AM33
#define IMAGE_FILE_MACHINE_AMD64 0x8664 //x64
#define IMAGE_FILE_MACHINE_ARM 0x1c0 //ARM little endian
#define IMAGE_FILE_MACHINE_ARM64 0xaa64 //ARM64 little endian
#define IMAGE_FILE_MACHINE_ARMNT 0x1c4 //ARM Thumb-2 little endian
#define IMAGE_FILE_MACHINE_EBC 0xebc //EFI byte code
#define IMAGE_FILE_MACHINE_I386 0x14c //Intel 386 or later processors and compatible processors
#define IMAGE_FILE_MACHINE_IA64 0x200 //Intel Itanium processor family
#define IMAGE_FILE_MACHINE_M32R 0x9041 //Mitsubishi M32R little endian
#define IMAGE_FILE_MACHINE_MIPS16 0x266 //MIPS16
#define IMAGE_FILE_MACHINE_MIPSFPU 0x366 //MIPS with FPU
#define IMAGE_FILE_MACHINE_MIPSFPU16 0x466 //MIPS16 with FPU
#define IMAGE_FILE_MACHINE_POWERPC 0x1f0 //Power PC little endian
#define IMAGE_FILE_MACHINE_POWERPCFP 0x1f1 //Power PC with floating point support
#define IMAGE_FILE_MACHINE_R4000 0x166 //MIPS little endian
#define IMAGE_FILE_MACHINE_RISCV32 0x5032 //RISC-V 32-bit address space
#define IMAGE_FILE_MACHINE_RISCV64 0x5064 //RISC-V 64-bit address space
#define IMAGE_FILE_MACHINE_RISCV128 0x5128 //RISC-V 128-bit address space
#define IMAGE_FILE_MACHINE_SH3 0x1a2 //Hitachi SH3
#define IMAGE_FILE_MACHINE_SH3DSP 0x1a3 //Hitachi SH3 DSP
#define IMAGE_FILE_MACHINE_SH4 0x1a6 //Hitachi SH4
#define IMAGE_FILE_MACHINE_SH5 0x1a8 //Hitachi SH5
#define IMAGE_FILE_MACHINE_THUMB 0x1c2 //Thumb
#define IMAGE_FILE_MACHINE_WCEMIPSV2 0x169 //MIPS little-endian WCE v2
// Flags
#define COFF_FLAG_RELOCS_STRIPPED 0 //Does not contain base relocations and must therefore be loaded at its preferred base address
#define COFF_FLAG_EXECUTABLE_IMAGE 1 //The image file is valid and can be run
#define COFF_FLAG_LINE_NUMS_STRIPPED 2 //COFF line numbers have been removed
#define COFF_FLAG_LOCAL_SYMS_STRIPPED 3 //COFF symbol table entries for local symbols have been removed
#define COFF_FLAG_AGGRESSIVE_WS_TRIM 4 //Obsolete. Aggressively trim working set
#define COFF_FLAG_LARGE_ADDRESS 5 //Application can handle > 2-GB addresses.
#define COFF_FLAG_BYTES_REVERSED_LO 7 //Little endian
#define COFF_FLAG_32BIT_MACHINE 8 //Machine is based on a 32-bit-word architecture.
#define COFF_FLAG_DEBUG_STRIPPED 9 //Debugging information is removed from the image file.
#define COFF_FLAG_REMOVABLE_RUN_FROM_SWAP 10 //If the image is on removable media, fully load it and copy it to the swap file.
#define COFF_FLAG_NET_RUN_FROM_SWAP 11 //If the image is on network media, fully load it and copy it to the swap file.
#define COFF_FLAG_SYSTEM 12 //The image file is a system file, not a user program.
#define COFF_FLAG_DLL 13 //The image file is a dynamic-link library (DLL)
#define COFF_FLAG_UP_SYSTEM_ONLY 14 //The file should be run only on a uniprocessor machine.
#define COFF_FLAG_BYTES_REVERSED_HI 15 //Big endian
// the symbol classes
#define SYM_CLASS_EXTERNAL 2
#define SYM_CLASS_STATIC 3 // The offset of the symbol within the section. If the Value field is zero, then the symbol represents a section name.
#define SYM_CLASS_FUNCTION 101
#define SYM_CLASS_FILE 103
#define SYM_CLASS_SECTION 104
// section flags
#define SCN_CNT_CODE (1<<SCN_SHIFT_CNT_CODE) // The section contains executable code
#define SCN_CNT_INIT_DATA (1<<SCN_SHIFT_CNT_INIT_DATA) // The section contains initialized data
#define SCN_CNT_UNINIT_DATA (1<<SCN_SHIFT_CNT_UNINIT_DATA) // The section contains uninitialized data
#define SCN_LNK_INFO (1<<SCN_SHIFT_LNK_INFO) // The section contains comments or other information.
#define SCN_LNK_REMOVE (1<<SCN_SHIFT_LNK_REMOVE) // The section will not become part of the image. This is valid only for object files.
#define SCN_LNK_COMDAT (1<<SCN_SHIFT_LNK_COMDAT) // The section contains COMDAT data. This is valid only for object files.
#define SCN_ALIGN (0xF<<SCN_SHIFT_ALIGN)
#define SCN_LNK_NRELOC_OVFL (1<<SCN_SHIFT_LNK_NRELOC_OVFL) // The section contains extended relocations
#define SCN_MEM_DISCARDABLE (1<<SCN_SHIFT_MEM_DISCARDABLE) // The section can be discarded as needed
#define SCN_MEM_NOT_CACHED (1<<SCN_SHIFT_MEM_NOT_CACHED) // The section cannot be cached
#define SCN_MEM_NOT_PAGED (1<<SCN_SHIFT_MEM_NOT_PAGED) // The section is not pageable
#define SCN_MEM_SHARED (1<<SCN_SHIFT_MEM_SHARED) // The section can be shared in memory
#define SCN_MEM_EXECUTE (1<<SCN_SHIFT_MEM_EXECUTE) // The section can be executed as code
#define SCN_MEM_READ (1<<SCN_SHIFT_MEM_READ) // The section can be read
#define SCN_MEM_WRITE (1<<SCN_SHIFT_MEM_WRITE) // The section can be written to
#define IMPORT_BY_ORDINAL 0x80000000
#define IMPORT_HINT_ENTRY_MASK (~IMPORT_BY_ORDINAL)
enum section_flags
{
SCN_SHIFT_CNT_CODE = 5,
SCN_SHIFT_CNT_INIT_DATA,
SCN_SHIFT_CNT_UNINIT_DATA,
SCN_SHIFT_FLAG_8,
SCN_SHIFT_LNK_INFO,
SCN_SHIFT_FLAG_10,
SCN_SHIFT_LNK_REMOVE,
SCN_SHIFT_LNK_COMDAT,
SCN_SHIFT_ALIGN = 20,
SCN_SHIFT_LNK_NRELOC_OVFL = 24,
SCN_SHIFT_MEM_DISCARDABLE,
SCN_SHIFT_MEM_NOT_CACHED,
SCN_SHIFT_MEM_NOT_PAGED,
SCN_SHIFT_MEM_SHARED,
SCN_SHIFT_MEM_EXECUTE,
SCN_SHIFT_MEM_READ,
SCN_SHIFT_MEM_WRITE
};
typedef enum subsystem
{
IMAGE_SUBSYSTEM_UNKNOWN, //0 An unknown subsystem
IMAGE_SUBSYSTEM_NATIVE, //1 Device drivers and native Windows processes
IMAGE_SUBSYSTEM_WINDOWS_GUI, //2 The Windows graphical user interface (GUI) subsystem
IMAGE_SUBSYSTEM_WINDOWS_CUI, //3 The Windows character subsystem
IMAGE_SUBSYSTEM_4,
IMAGE_SUBSYSTEM_OS2_CUI, //5 The OS/2 character subsystem
IMAGE_SUBSYSTEM_6,
IMAGE_SUBSYSTEM_POSIX_CUI, //7 The Posix character subsystem
IMAGE_SUBSYSTEM_NATIVE_WINDOWS, //8 Native Win9x driver
IMAGE_SUBSYSTEM_WINDOWS_CE_GUI, //9 Windows CE
IMAGE_SUBSYSTEM_EFI_APPLICATION, //10 An Extensible Firmware Interface (EFI) application
IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER, //11 An EFI driver with boot services
IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER, //12 An EFI driver with run-time services
IMAGE_SUBSYSTEM_EFI_ROM, //13 An EFI ROM image
IMAGE_SUBSYSTEM_XBOX, //14 XBOX
IMAGE_SUBSYSTEM_15, //15 unknown
IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION, //16 Windows boot application.
IMAGE_SUBSYSTEM_MAX
} subsystem;
typedef struct coff_header
{
unsigned short machine; // see IMAGE_FILE_MACHINE_
unsigned short num_sections;
unsigned int time_created;
unsigned int offset_symtab; // offset to symbol table
unsigned int num_symbols; // number of entries in symbol table
unsigned short size_optional_hdr;
unsigned short flags; // see COFF_FLAG_
} coff_header;
typedef struct optional_header
{
unsigned char major_linker_ver;
unsigned char minor_linker_ver;
unsigned int code_size;
unsigned int data_size;
unsigned int uninit_data_size;
unsigned int entry;
unsigned int code_base;
unsigned int data_base;
} optional_header;
typedef struct pe32_windows_header
{
unsigned int base;
unsigned int section_alignment;
unsigned int file_alignment;
unsigned short os_major;
unsigned short os_minor;
unsigned short image_major;
unsigned short image_minor;
unsigned short subsys_major;
unsigned short subsys_minor;
unsigned int win32ver;
unsigned int image_size;
unsigned int header_size;
unsigned int checksum;
unsigned short subsystem; // see IMAGE_SUBSYSTEM_
unsigned short dll_chars;
unsigned int stack_size;
unsigned int stack_commit_size;
unsigned int heap_size;
unsigned int heap_commit_size;
unsigned int loader_flags;
unsigned int num_rva;
} pe32_windows_header;
typedef struct section_header
{
char name[8];
unsigned int size_in_mem;
unsigned int address;
unsigned int size_on_disk;
unsigned int data_offset;
unsigned int reloc;
unsigned int linenums;
unsigned short num_reloc;
unsigned short num_lines;
unsigned int flags; // see SCN_
} section_header;
typedef struct data_dir
{
unsigned int offset;
unsigned int size;
} data_dir;
typedef struct data_dirs
{
data_dir exports;
data_dir imports;
data_dir resource;
data_dir exception;
data_dir certificate;
data_dir relocation;
data_dir debug;
data_dir arch;
data_dir ptr;
data_dir tls;
data_dir load;
data_dir bound;
data_dir iat;
data_dir delay;
data_dir clr;
data_dir reserved;
} data_dirs;
typedef struct debug_dir_header
{
int characteristics;
int timestamp;
short major;
short minor;
int type;
int size;
int address;
int offset;
} debug_dir_header;
typedef struct symbol
{
union
{
char str[8];
struct
{
unsigned int zeros;
unsigned int index;
} ptr;
} name;
unsigned int val;
short section; // index, 0=external, -1=abs, -2=debugging (file)
unsigned short type; // LSB: base type MSB: complex type
unsigned char symclass;
unsigned char auxsymbols;
} symbol;
typedef struct import_dir_entry
{
unsigned int lu_table;
unsigned int timestamp;
unsigned int forwarder;
unsigned int name;
unsigned int addr_table;
} import_dir_entry;
struct machine_name
{
unsigned short id;
char name[31+1];
};
static const struct machine_name machine_lookup[] =
{
{ IMAGE_FILE_MACHINE_UNKNOWN, "Unknown machine" },
{ IMAGE_FILE_MACHINE_AMD64, "x64" },
{ IMAGE_FILE_MACHINE_ARM, "ARM little endian" },
{ IMAGE_FILE_MACHINE_ARM64, "ARM64 little endian" },
{ IMAGE_FILE_MACHINE_ARMNT, "ARM Thumb-2 little endian" },
{ IMAGE_FILE_MACHINE_EBC, "EFI byte code" },
{ IMAGE_FILE_MACHINE_I386, "Intel 386 or later" },
{ IMAGE_FILE_MACHINE_IA64, "Intel Itanium" },
{ IMAGE_FILE_MACHINE_M32R, "Mitsubishi M32R little endian" },
{ IMAGE_FILE_MACHINE_MIPS16, "MIPS16" },
{ IMAGE_FILE_MACHINE_MIPSFPU, "MIPS with FPU" },
{ IMAGE_FILE_MACHINE_MIPSFPU16, "MIPS16 with FPU" },
{ IMAGE_FILE_MACHINE_POWERPC, "Power PC little endian" },
{ IMAGE_FILE_MACHINE_POWERPCFP, "Power PC with floating point" },
{ IMAGE_FILE_MACHINE_R4000, "MIPS little endian" },
{ IMAGE_FILE_MACHINE_RISCV32, "RISC-V 32-bit address space" },
{ IMAGE_FILE_MACHINE_RISCV64, "RISC-V 64-bit address space" },
{ IMAGE_FILE_MACHINE_RISCV128, "RISC-V 128-bit address space" },
{ IMAGE_FILE_MACHINE_SH3, "Hitachi SH3" },
{ IMAGE_FILE_MACHINE_SH3DSP, "Hitachi SH3 DSP" },
{ IMAGE_FILE_MACHINE_SH4, "Hitachi SH4" },
{ IMAGE_FILE_MACHINE_SH5, "Hitachi SH5" },
{ IMAGE_FILE_MACHINE_THUMB, "Thumb" },
{ IMAGE_FILE_MACHINE_WCEMIPSV2, "MIPS little-endian WCE v2" },
};
static const char* flags_lookup[] =
{
"Does not contain base relocations and must therefore be loaded at its preferred base address",
"The image file is valid and can be run",
"COFF line numbers have been removed",
"COFF symbol table entries for local symbols have been removed",
"Obsolete. Aggressively trim working set",
"Application can handle > 2-GB addresses",
"RESERVED",
"Little endian",
"Machine is based on a 32-bit-word architecture",
"Debugging information is removed from the image file.",
"If the image is on removable media, fully load it and copy it to the swap file",
"If the image is on network media, fully load it and copy it to the swap file",
"The image file is a system file, not a user program",
"The image file is a dynamic-link library (DLL)",
"The file should be run only on a uniprocessor machine",
"Big endian"
};
static const char* subsystem_lookup[] =
{
"An unknown subsystem",
"Device drivers and native Windows processes",
"The Windows graphical user interface (GUI) subsystem",
"The Windows character subsystem",
"IMAGE_SUBSYSTEM_4",
"The OS/2 character subsystem",
"IMAGE_SUBSYSTEM_6",
"The Posix character subsystem",
"Native Win9x driver",
"Windows CE",
"An Extensible Firmware Interface (EFI) application",
"An EFI driver with boot services",
"An EFI driver with run-time services",
"An EFI ROM image",
"XBOX",
"unknown",
"Windows boot application"
};
static const char* section_flags_lookup[] =
{
"",
"",
"",
"",
"",
"executable code",
"initialized data",
"uninitialized data",
"comments or other information",
"will not become part of the image",
"COMDAT data",
0,0,0,0,0,0,0,0,0,0,0,0,0,
"extended relocations",
"can be discarded as needed",
"cannot be cached",
"is not pageable",
"can be shared in memory",
"can be executed as code",
"can be read",
"can be written to"
};
const char* pe32_name(void)
{
return "pe32";
}
static unsigned int read_import_dir(import_dir_entry *d, FILE *f, unsigned int base, backend_section
*sec, backend_object* obj, backend_section *sec_text, backend_import* mod)
{
char *name; // name of the imported function
unsigned int lu;
printf("Address table @ 0x%x\n", d->addr_table);
fseek(f, d->addr_table, SEEK_SET);
fread(&lu, sizeof(unsigned int), 1, f);
unsigned long val = (unsigned long)sec->address + (d->addr_table - base);
printf("Val: 0x%lx\n", val);
while (lu)
{
// if the MSB is set, import by ordinal. Otherwise, import by name
if (lu & IMPORT_BY_ORDINAL)
{
char tmp_name[16];
sprintf(tmp_name, "0x%x", lu & 0xFFFF);
printf("%s: import by ordinal: %s\n", mod->name, tmp_name);
}
else
{
printf("import by name lu=0x%x base=0x%x\n", lu, base);
name = (char*)sec->data + ((lu & IMPORT_HINT_ENTRY_MASK) - base) + 2;
if (config.verbose)
fprintf(stderr, "Adding function: %s\n", name);
backend_add_import_function(mod, name, val);
}
backend_add_symbol(obj, name, 0, SYMBOL_TYPE_NONE, 0, SYMBOL_FLAG_GLOBAL | SYMBOL_FLAG_EXTERNAL, sec_text);
fread(&lu, sizeof(unsigned int), 1, f);
val += sizeof(unsigned int);
}
return 0;
}
const char* lookup_machine(unsigned short machine)
{
for (int i=0; i < sizeof(machine_lookup)/sizeof(struct machine_name); i++)
if (machine_lookup[i].id == machine)
return machine_lookup[i].name;
return machine_lookup[0].name;
}
void dump_coff(coff_header* h)
{
printf("\nCOFF Header\n");
printf("machine: %s\n", lookup_machine(h->machine));
printf("num sections: %u\n", h->num_sections);
time_t creat = h->time_created;
printf("created: %s", ctime(&creat));
printf("symtab offset: %u\n", h->offset_symtab);
printf("num symbols: %u\n", h->num_symbols);
printf("exe header size: %u\n", h->size_optional_hdr);
printf("flags: 0x%X\n", h->flags);
for (int i=0; i < sizeof(h->flags)*8; i++)
if (h->flags & 1<<i)
printf(" - %s\n", flags_lookup[i]);
}
void dump_optional(optional_header* h, unsigned short state)
{
printf("state: ");
switch(state)
{
case STATE_ID_NORMAL:
printf("PE32\n");
break;
case STATE_ID_ROM:
printf("PE ROM\n");
break;
case STATE_ID_PE32PLUS:
printf("PE32+\n");
break;
default:
printf("Unknown\n");
}
printf("link ver: %i.%i\n", h->major_linker_ver, h->minor_linker_ver);
printf("code size: %i\n", h->code_size);
printf("data size: %i\n", h->data_size);
printf("uninit data size: %i\n", h->uninit_data_size);
printf("entry: 0x%x\n", h->entry);
printf("code base: 0x%x\n", h->code_base);
if (state == STATE_ID_NORMAL)
printf("date base: 0x%x\n", h->data_base);
}
void dump_pe32_windows(pe32_windows_header* h)
{
printf("\nPE 32 Windows header\n");
printf("Base: 0x%x\n", h->base);
printf("Section alignment: %u\n", h->section_alignment);
unsigned int file_alignment;
printf("OS version: %u.%u\n", h->os_major, h->os_minor);
printf("Image version: %u.%u\n", h->image_major, h->image_minor);
printf("Subsystem version: %u.%u\n", h->subsys_major, h->subsys_minor);
//unsigned int image_size;
//unsigned int header_size;
//unsigned int checksum;
if (h->subsystem >= IMAGE_SUBSYSTEM_MAX)
h->subsystem = 0;
printf("Subsystem: %s\n", subsystem_lookup[h->subsystem]); // see IMAGE_SUBSYSTEM_
//unsigned short dll_chars;
//unsigned int stack_size;
//unsigned int stack_commit_size;
//unsigned int heap_size;
//unsigned int heap_commit_size;
//unsigned int loader_flags;
//unsigned int num_rva;
}
void dump_data_dirs(data_dirs* h)
{
printf("\nData Directories\n");
printf("Export: 0x%x (%u)\n", h->exports.offset, h->exports.size);
printf("Import: 0x%x (%u)\n", h->imports.offset, h->imports.size);
printf("Resource: 0x%x (%u)\n", h->resource.offset, h->resource.size);
printf("Exception: 0x%x (%u)\n", h->exception.offset, h->exception.size);
printf("Certificate: 0x%x (%u)\n", h->certificate.offset, h->certificate.size);
printf("Relocation: 0x%x (%u)\n", h->relocation.offset, h->relocation.size);
printf("Debug: 0x%x (%u)\n", h->debug.offset, h->debug.size);
printf("Arch: 0x%x (%u)\n", h->arch.offset, h->arch.size);
printf("Ptr: 0x%x (%u)\n", h->ptr.offset, h->ptr.size);
printf("TLS: 0x%x (%u)\n", h->tls.offset, h->tls.size);
printf("Load Config: 0x%x (%u)\n", h->load.offset, h->load.size);
printf("Bound Import: 0x%x (%u)\n", h->bound.offset, h->bound.size);
printf("Import Address: 0x%x (%u)\n", h->iat.offset, h->iat.size);
printf("Delay Import: 0x%x (%u)\n", h->delay.offset, h->delay.size);
printf("CLR Runtime: 0x%x (%u)\n", h->clr.offset, h->clr.size);
}
void dump_import_dirent(import_dir_entry *d)
{
printf("lu_table=0x%x\n", d->lu_table);
//printf("timestamp=0x%x\n", d->timestamp);
//printf("forwarder=0x%x\n", d->forwarder);
printf("DLL name=0x%x\n", d->name);
printf("first thunk=0x%x\n\n", d->addr_table);
}
static char* coff_symbol_name(symbol* s, char* stringtab)
{
static char nametmp[10];
char* name;
if (s->name.ptr.zeros == 0)
name = stringtab + s->name.ptr.index;
else
{
memcpy(nametmp, s->name.str, 8);
nametmp[8] = 0;
name = nametmp;
}
return name;
}
void dump_symtab(symbol* symtab, unsigned int count, char* stringtab)
{
int aux=0;
for (unsigned int i=0; i< count; i++)
{
symbol* s = &(symtab[i]);
char* name=coff_symbol_name(s, stringtab);
aux = s->auxsymbols;
while (aux)
{
// decode as aux
i++;
if (s->symclass == SYM_CLASS_FILE)
{
char nametmp[19];
// COFF symbols of type file should have the name ".file"
if (strcmp(name, ".file"))
printf("Got a symbol of type file without name .file! (named %s)\n", name);
// now get its real name
memcpy(nametmp, (char*)(&symtab[i]), 18);
nametmp[18] = 0;
name = nametmp;
}
//AUX tagndx 0 ttlsiz 0x0 lnnos 0 next 0
aux--;
}
printf("[%3u](sec %2i)(fl 0x00)(ty %3x)(scl %3i) (nx %i) 0x%08x %s\n", i, s->section, s->type, s->symclass, s->auxsymbols, s->val, name);
}
}
static void dump_sections(section_header* secs, unsigned int nsec)
{
printf("There are %u sections\n", nsec);
for (unsigned int i=0; i < nsec; i++)
{
printf("Index: %i\n", i+1);
printf("Section Name: %s\n", secs[i].name);
printf("Size in mem: %u\n", secs[i].size_in_mem);
printf("Address: 0x%x\n", secs[i].address);
printf("Data ptr: %u\n", secs[i].data_offset);
printf("Flags: 0x%x\n", secs[i].flags);
for (int f=0; f < 19; f++)
if (secs[i].flags & (1<<f))
printf(" - %s\n", section_flags_lookup[f]);
for (int f=24; f < 31; f++)
if (secs[i].flags & (1<<f))
printf(" - %s\n", section_flags_lookup[f]);
printf("Alignment: %i\n\n", (secs[i].flags >> SCN_SHIFT_ALIGN) & SCN_ALIGN);
}
}
/* identifies the file format we can write */
backend_type pe32_format(void)
{
return OBJECT_TYPE_PE32;
}
backend_type pe32plus_format(void)
{
return OBJECT_TYPE_PE32PLUS;
}
static backend_object* pe_read_file(const char* filename)
{
char* buff = (char*)malloc(sizeof(coff_header));
FILE* f = fopen(filename, "rb");
if (!f)
{
printf("can't open file\n");
free(buff);
return 0;
}
// get size of the file
fseek(f, 0, SEEK_END);
int fsize = ftell(f);
if (MAGIC_LOCATOR >= fsize)
{
free(buff);
return 0;
}
// read location 0x3C to find the offset of the magic number
fseek(f, MAGIC_LOCATOR, SEEK_SET);
if ((fread(buff, MAGIC_SIZE, 1, f) != 1) ||
(*(unsigned int*)buff >= fsize))
{
free(buff);
return 0;
}
fseek(f, *(unsigned int*)buff, SEEK_SET);
if ((fread(buff, MAGIC_SIZE, 1, f) != 1) ||
(memcmp(buff, PE_MAGIC, 4) != 0))
{
free(buff);
return 0;
}
printf("found PE magic number\n");
backend_object* obj = backend_create();
if (!obj)
{
free(buff);
return 0;
}
// read the coff header
coff_header ch;
int fpos = ftell(f);
//printf("COFF header @ 0x%x\n", fpos);
if (fread(&ch, sizeof(coff_header), 1, f) != 1)
printf("Error reading COFF header\n");
//dump_coff(&ch);
unsigned short state; // STATE_ID_
if (fread(&state, sizeof(state), 1, f) != 1)
printf("Error reading state\n");
unsigned int entry_offset;
unsigned int base_address;
backend_arch be_arch;
switch(ch.machine)
{
case IMAGE_FILE_MACHINE_ARM:
be_arch = OBJECT_ARCH_ARM;
break;
case IMAGE_FILE_MACHINE_ARM64:
be_arch = OBJECT_ARCH_ARM64;
break;
case IMAGE_FILE_MACHINE_I386:
be_arch = OBJECT_ARCH_X86;
break;
}
backend_set_arch(obj, be_arch);
// read the optional header
free(buff);
switch(state)
{
case STATE_ID_NORMAL:
backend_set_type(obj, OBJECT_TYPE_PE32);
// read the optional header
buff = (char*)malloc(sizeof(optional_header));
if (fread(buff, sizeof(optional_header), 1, f) != 1)
printf("Error reading optional header\n");
//dump_optional((optional_header*)buff, state);
entry_offset = ((optional_header*)buff)->entry;
// read the windows-specific header
free(buff);
buff = (char*)malloc(sizeof(pe32_windows_header));
if (fread(buff, sizeof(pe32_windows_header), 1, f) != 1)
printf("Error reading windows header\n");
//dump_pe32_windows((pe32_windows_header*)buff);
// add generic object information
base_address = ((pe32_windows_header*)buff)->base;
backend_set_entry_point(obj, base_address + entry_offset);
break;
case STATE_ID_ROM:
backend_set_type(obj, OBJECT_TYPE_PE_ROM);
break;
case STATE_ID_PE32PLUS:
backend_set_type(obj, OBJECT_TYPE_PE32PLUS);
free(buff);
//buff = (char*)malloc(sizeof(pe32_windows_header));
//fread(buff, sizeof(pe32_windows_header), 1, f);
//dump_pe32plus_windows((pe32_windows_header*)buff);
break;
default:
printf("Unknown\n");
}
// read the data directories
data_dirs* dd = (data_dirs*)malloc(sizeof(data_dirs));
if (fread(dd, sizeof(data_dirs), 1, f) != 1)
printf("Error reading data directories\n");
//dump_data_dirs(dd);
// read the sections - they are immediately after the optional header
char tmp_name[32];
unsigned int import_file_base; // file offset of section containing the import info
backend_section* import_sec=NULL; // pointer to the section containing the import info
int sectabsize = sizeof(section_header) * ch.num_sections;
section_header* secs = (section_header*)malloc(sectabsize);
if (fread(secs, sectabsize, 1 ,f) != 1)
printf("Error reading section table\n");
//dump_sections(secs, ch.num_sections);
for (unsigned int i=0; i < ch.num_sections; i++)
{
unsigned char* data = (unsigned char*)malloc(secs[i].size_on_disk);
// load the data
fseek(f, secs[i].data_offset, SEEK_SET);
if (fread(data, secs[i].size_on_disk, 1, f) != 1)
printf("Error reading section %i\n", i);
// convert the flags
unsigned int flags=0;
if (secs[i].flags & SCN_CNT_CODE)
flags |= SECTION_FLAG_EXECUTE;
if (secs[i].flags & SCN_CNT_INIT_DATA)
flags |= SECTION_FLAG_INIT_DATA;
if (secs[i].flags & SCN_CNT_UNINIT_DATA)
flags |= SECTION_FLAG_UNINIT_DATA;
if (secs[i].flags & SCN_LNK_INFO)
flags |= SECTION_FLAG_COMMENTS;
if (secs[i].flags & SCN_LNK_REMOVE)
flags |= SECTION_FLAG_DISCARDABLE;
if (secs[i].flags & SCN_MEM_EXECUTE)
flags |= SECTION_FLAG_EXECUTE;
if (secs[i].flags & SCN_MEM_READ)
flags |= SECTION_FLAG_READ;
if (secs[i].flags & SCN_MEM_WRITE)
flags |= SECTION_FLAG_WRITE;
strncpy(tmp_name, secs[i].name, 8);
tmp_name[8] = 0;
// update the known names to have a consistent naming in the backend
if (strcmp(tmp_name, ".rdata") == 0)
strcpy(tmp_name, ".rodata");
// add the backend section
backend_section* sec = backend_add_section(obj, tmp_name, secs[i].size_in_mem, base_address + secs[i].address, data, 0, (secs[i].flags >> SCN_SHIFT_ALIGN) & SCN_ALIGN, flags);
}
// read the symbol table
symbol* symtab = NULL;
if (ch.offset_symtab && ch.num_symbols)
{
int symtabsize = ch.num_symbols * sizeof(symbol);
symtab = (symbol*)malloc(symtabsize);
//printf("seeking to 0x%x\n", ch.offset_symtab);
fseek(f, ch.offset_symtab, SEEK_SET);
fpos = ftell(f);
//printf("symtab @ 0x%x\n", fpos);
if (fread(symtab, symtabsize, 1, f) != 1)
printf("Error reading symbol table\n");
}
// can't dump the symbol table until the string table is read
// read the string table
int strtabsize=0;
if (fread(&strtabsize, 4, 1, f) != 1)
printf("Error reading size of string table\n");
//printf("string table is %i bytes long\n", strtabsize);
char* strtab = (char*)malloc(strtabsize + sizeof(strtabsize));
if (fread(strtab+sizeof(strtabsize), strtabsize, 1, f) != 1)
printf("Error reading string table size\n");
//dump_symtab(symtab, ch.num_symbols, strtab);
// fill the generic symbol table
for (unsigned int i=0; i< ch.num_symbols; i++)
{
symbol* s = &(symtab[i]);
char* name = coff_symbol_name(s, strtab);
// is this a function?
if (s->type == 0x20)
{
if (s->symclass == SYM_CLASS_EXTERNAL && s->section <= 0)
{
printf("Warning: external symbol %s does not have a valid section number\n", name);
break;
}
if (s->auxsymbols == 1)
i++; // the aux doesn't seem to be in use by MSFT, so I'm not going to bother reading it now
// this strndup is leaking memory - fix it. It is duplicated again inside the call. also a few more down below in calls to add_symbol.
backend_add_symbol(obj, strndup(name, 8), s->val, SYMBOL_TYPE_FUNCTION, 0, 0, backend_get_section_by_index(obj, s->section));
}
else
{
switch (s->symclass)
{
case SYM_CLASS_FILE:
if (strcmp(name, ".file"))
printf("Warning: 'file' symbol is not named '.file'!\n");
backend_add_symbol(obj, strndup((char*)&symtab[++i], 18), s->val, SYMBOL_TYPE_FILE, 0, 0, NULL);
break;
case SYM_CLASS_SECTION:
break;
case SYM_CLASS_STATIC:
if (s->auxsymbols == 1)
{
// read the number of relocations
//symbol_aux_sec* a = &(symtab[++i]);
i++; // remove this when uncommenting previous line
}
backend_add_symbol(obj, strndup(name, 8), s->val, SYMBOL_TYPE_SECTION, 0, 0, NULL);
// here we probably need to update the section object as well
break;
case SYM_CLASS_FUNCTION:
// these are the .bf (begin function) and .ef (end function) symbols - ignore them for now
break;
case SYM_CLASS_EXTERNAL:
break;
}
}
}
// find the text section - we'll need it to add symbols
backend_import* mod;
backend_section *imports_sec=NULL;
backend_section* sec_text = backend_get_section_by_name(obj, ".text");
unsigned int imports_start = base_address + dd->imports.offset;
if (!sec_text)
{
printf("Can't find code section!\n");
goto done;
}
if (config.verbose)
printf("Imports are at address 0x%x size=0x%x\n", imports_start, dd->imports.size);
// find out which section contains the import names (if we have imports)
if (imports_start)
imports_sec = backend_find_section_by_val(obj, imports_start);
if (imports_sec)
{
import_dir_entry *d;
unsigned int offset;
// The contents of the imports are an "Import Directory Table", followed
// by some "DLL Import Lookup Tables" and finally The "Hint-Name Table"
// The import directory table is null-terminated, and contains pointers
// into the other parts.
offset = imports_sec->address - base_address;
d = (import_dir_entry*)((unsigned long)imports_start - imports_sec->address + imports_sec->data);
// iterate over directory table entries
while (d->lu_table)
{
char tmp_name[16];
char *import_name;
//dump_import_dirent(d);
if (d->name < offset)
printf("WARNING: going negative d->name=0x%x offset=0x%x\n", d->name, offset);
// calculate the pointer to the module name
char* mod_name = (char*)imports_sec->data + (d->name - offset);
if (d->lu_table < offset)
printf("WARNING: going negative d->lu_table=0x%x offset=0x%x\n", d->lu_table, offset);
// calculate the pointer to the table in memory - each entry is 4 bytes
unsigned int *lu_entry = (unsigned int*)(imports_sec->data + (d->lu_table - offset));
unsigned int val = imports_sec->address + (d->lu_table - offset);
if (config.verbose)
printf("Module: %s Table @ 0x%x\n", mod_name, d->lu_table - offset);
// add the module to the backend
mod = backend_add_import_module(obj, mod_name);
// iterate over all functions belonging to this module
while (*lu_entry)
{
if (*lu_entry < offset)
printf("Warning: lu_entry=0x%x offset=0x%x\n", *lu_entry, offset);
// if the MSB is set, import by ordinal. Otherwise, import by name
if (*lu_entry & IMPORT_BY_ORDINAL)
{
sprintf(tmp_name, "0x%x", *lu_entry & IMPORT_HINT_ENTRY_MASK);
//printf("import by ordinal: %s\n", tmp_name);
import_name = tmp_name;
}
else
{
unsigned int lu;
lu = *lu_entry - offset;
import_name = (char*)imports_sec->data + lu + 2;
//printf("Name: %s\n", import_name);
backend_add_symbol(obj, import_name, 0, SYMBOL_TYPE_NONE, 0, SYMBOL_FLAG_GLOBAL | SYMBOL_FLAG_EXTERNAL, sec_text);
}
backend_add_import_function(mod, import_name, val);
lu_entry++;
val += sizeof(unsigned int);
}
d++;
}
}
else
{
fprintf(stderr, "Can't find imports section\n");
}
// read the debug info
printf("checking for debug info\n");
if (dd->debug.size && dd->debug.offset)
{
debug_dir_header ddh;
printf("Has debug info\n");
if (dd->debug.size != sizeof(debug_dir_header))
{
printf("Unusual size %i (expected %lu)\n", dd->debug.size, sizeof(debug_dir_header));
}
fseek(f, dd->debug.offset, SEEK_SET);
if (fread(&ddh, sizeof(ddh), 1, f) != 1)
printf("Error reading debug info header\n");
printf("debug type: %i\n", ddh.type);
printf("debug size: %i\n", ddh.size);
printf("debug offset: 0x%x\n", ddh.offset);
fseek(f, ddh.offset, SEEK_SET);
}
done:
// clean up
free(strtab);
free(symtab);
free(buff);
printf("PE32 loading done (%i symbols, %i relocs)\n", backend_symbol_count(obj), backend_relocation_count(obj));
printf("-----------------------------------------\n");
return obj;
}
/* We must calculate the symbol count differently in COFF in order to take AUX
symbols into account. Some symbols are written using multiple entries, so there
can be a primary entry and 0 or more aux entries for each symbol */
static unsigned int coff_symbol_count(backend_object* obj)
{
unsigned int count=0;
backend_symbol* sym = backend_get_first_symbol(obj);
while (sym)
{
count++; // for the primary symbol
switch (sym->type)
{
case SYMBOL_TYPE_FILE:
if (sym->section == 0)
count++; // aux type 4
break;
case SYMBOL_TYPE_SECTION:
count++; // aux type 5
break;
case SYMBOL_TYPE_FUNCTION:
count++; // aux format 1
break;
}
//printf("counting symbol %s (%u)\n", sym->name, count);
sym = backend_get_next_symbol(obj);
}
return count;
}
static int coff_write_file(backend_object* obj, const char* filename)