This repository has been archived by the owner on Oct 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
tccpe.c
2045 lines (1809 loc) · 61.4 KB
/
tccpe.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
/*
* TCCPE.C - PE file output for the Tiny C Compiler
*
* Copyright (c) 2005-2007 grischka
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "tcc.h"
#define PE_MERGE_DATA 1
#define PE_PRINT_SECTIONS 0
#ifndef _WIN32
#define stricmp strcasecmp
#define strnicmp strncasecmp
#include <sys/stat.h> /* chmod() */
#endif
#ifdef TCC_TARGET_X86_64
# define ADDR3264 ULONGLONG
# define PE_IMAGE_REL IMAGE_REL_BASED_DIR64
# define REL_TYPE_DIRECT R_X86_64_64
# define R_XXX_THUNKFIX R_X86_64_PC32
# define R_XXX_RELATIVE R_X86_64_RELATIVE
# define R_XXX_FUNCCALL R_X86_64_PC32
# define IMAGE_FILE_MACHINE 0x8664
# define RSRC_RELTYPE 3
#elif defined TCC_TARGET_ARM
# define ADDR3264 DWORD
# define PE_IMAGE_REL IMAGE_REL_BASED_HIGHLOW
# define REL_TYPE_DIRECT R_ARM_ABS32
# define R_XXX_THUNKFIX R_ARM_ABS32
# define R_XXX_RELATIVE R_ARM_RELATIVE
# define R_XXX_FUNCCALL R_ARM_PC24
# define R_XXX_FUNCCALL2 R_ARM_ABS32
# define IMAGE_FILE_MACHINE 0x01C0
# define RSRC_RELTYPE 7 /* ??? (not tested) */
#elif defined TCC_TARGET_I386
# define ADDR3264 DWORD
# define PE_IMAGE_REL IMAGE_REL_BASED_HIGHLOW
# define REL_TYPE_DIRECT R_386_32
# define R_XXX_THUNKFIX R_386_32
# define R_XXX_RELATIVE R_386_RELATIVE
# define R_XXX_FUNCCALL R_386_PC32
# define IMAGE_FILE_MACHINE 0x014C
# define RSRC_RELTYPE 7 /* DIR32NB */
#endif
#ifndef IMAGE_NT_SIGNATURE
/* ----------------------------------------------------------- */
/* definitions below are from winnt.h */
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef unsigned int DWORD;
typedef unsigned long long ULONGLONG;
#pragma pack(push, 1)
typedef struct _IMAGE_DOS_HEADER { /* DOS .EXE header */
WORD e_magic; /* Magic number */
WORD e_cblp; /* Bytes on last page of file */
WORD e_cp; /* Pages in file */
WORD e_crlc; /* Relocations */
WORD e_cparhdr; /* Size of header in paragraphs */
WORD e_minalloc; /* Minimum extra paragraphs needed */
WORD e_maxalloc; /* Maximum extra paragraphs needed */
WORD e_ss; /* Initial (relative) SS value */
WORD e_sp; /* Initial SP value */
WORD e_csum; /* Checksum */
WORD e_ip; /* Initial IP value */
WORD e_cs; /* Initial (relative) CS value */
WORD e_lfarlc; /* File address of relocation table */
WORD e_ovno; /* Overlay number */
WORD e_res[4]; /* Reserved words */
WORD e_oemid; /* OEM identifier (for e_oeminfo) */
WORD e_oeminfo; /* OEM information; e_oemid specific */
WORD e_res2[10]; /* Reserved words */
DWORD e_lfanew; /* File address of new exe header */
} IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
#define IMAGE_NT_SIGNATURE 0x00004550 /* PE00 */
#define SIZE_OF_NT_SIGNATURE 4
typedef struct _IMAGE_FILE_HEADER {
WORD Machine;
WORD NumberOfSections;
DWORD TimeDateStamp;
DWORD PointerToSymbolTable;
DWORD NumberOfSymbols;
WORD SizeOfOptionalHeader;
WORD Characteristics;
} IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
#define IMAGE_SIZEOF_FILE_HEADER 20
typedef struct _IMAGE_DATA_DIRECTORY {
DWORD VirtualAddress;
DWORD Size;
} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
typedef struct _IMAGE_OPTIONAL_HEADER {
/* Standard fields. */
WORD Magic;
BYTE MajorLinkerVersion;
BYTE MinorLinkerVersion;
DWORD SizeOfCode;
DWORD SizeOfInitializedData;
DWORD SizeOfUninitializedData;
DWORD AddressOfEntryPoint;
DWORD BaseOfCode;
#ifndef TCC_TARGET_X86_64
DWORD BaseOfData;
#endif
/* NT additional fields. */
ADDR3264 ImageBase;
DWORD SectionAlignment;
DWORD FileAlignment;
WORD MajorOperatingSystemVersion;
WORD MinorOperatingSystemVersion;
WORD MajorImageVersion;
WORD MinorImageVersion;
WORD MajorSubsystemVersion;
WORD MinorSubsystemVersion;
DWORD Win32VersionValue;
DWORD SizeOfImage;
DWORD SizeOfHeaders;
DWORD CheckSum;
WORD Subsystem;
WORD DllCharacteristics;
ADDR3264 SizeOfStackReserve;
ADDR3264 SizeOfStackCommit;
ADDR3264 SizeOfHeapReserve;
ADDR3264 SizeOfHeapCommit;
DWORD LoaderFlags;
DWORD NumberOfRvaAndSizes;
IMAGE_DATA_DIRECTORY DataDirectory[16];
} IMAGE_OPTIONAL_HEADER32, IMAGE_OPTIONAL_HEADER64, IMAGE_OPTIONAL_HEADER;
#define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */
#define IMAGE_DIRECTORY_ENTRY_IMPORT 1 /* Import Directory */
#define IMAGE_DIRECTORY_ENTRY_RESOURCE 2 /* Resource Directory */
#define IMAGE_DIRECTORY_ENTRY_EXCEPTION 3 /* Exception Directory */
#define IMAGE_DIRECTORY_ENTRY_SECURITY 4 /* Security Directory */
#define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 /* Base Relocation Table */
#define IMAGE_DIRECTORY_ENTRY_DEBUG 6 /* Debug Directory */
/* IMAGE_DIRECTORY_ENTRY_COPYRIGHT 7 (X86 usage) */
#define IMAGE_DIRECTORY_ENTRY_ARCHITECTURE 7 /* Architecture Specific Data */
#define IMAGE_DIRECTORY_ENTRY_GLOBALPTR 8 /* RVA of GP */
#define IMAGE_DIRECTORY_ENTRY_TLS 9 /* TLS Directory */
#define IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG 10 /* Load Configuration Directory */
#define IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT 11 /* Bound Import Directory in headers */
#define IMAGE_DIRECTORY_ENTRY_IAT 12 /* Import Address Table */
#define IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT 13 /* Delay Load Import Descriptors */
#define IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR 14 /* COM Runtime descriptor */
/* Section header format. */
#define IMAGE_SIZEOF_SHORT_NAME 8
typedef struct _IMAGE_SECTION_HEADER {
BYTE Name[IMAGE_SIZEOF_SHORT_NAME];
union {
DWORD PhysicalAddress;
DWORD VirtualSize;
} Misc;
DWORD VirtualAddress;
DWORD SizeOfRawData;
DWORD PointerToRawData;
DWORD PointerToRelocations;
DWORD PointerToLinenumbers;
WORD NumberOfRelocations;
WORD NumberOfLinenumbers;
DWORD Characteristics;
} IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
#define IMAGE_SIZEOF_SECTION_HEADER 40
typedef struct _IMAGE_EXPORT_DIRECTORY {
DWORD Characteristics;
DWORD TimeDateStamp;
WORD MajorVersion;
WORD MinorVersion;
DWORD Name;
DWORD Base;
DWORD NumberOfFunctions;
DWORD NumberOfNames;
DWORD AddressOfFunctions;
DWORD AddressOfNames;
DWORD AddressOfNameOrdinals;
} IMAGE_EXPORT_DIRECTORY,*PIMAGE_EXPORT_DIRECTORY;
typedef struct _IMAGE_IMPORT_DESCRIPTOR {
union {
DWORD Characteristics;
DWORD OriginalFirstThunk;
};
DWORD TimeDateStamp;
DWORD ForwarderChain;
DWORD Name;
DWORD FirstThunk;
} IMAGE_IMPORT_DESCRIPTOR;
typedef struct _IMAGE_BASE_RELOCATION {
DWORD VirtualAddress;
DWORD SizeOfBlock;
// WORD TypeOffset[1];
} IMAGE_BASE_RELOCATION;
#define IMAGE_SIZEOF_BASE_RELOCATION 8
#define IMAGE_REL_BASED_ABSOLUTE 0
#define IMAGE_REL_BASED_HIGH 1
#define IMAGE_REL_BASED_LOW 2
#define IMAGE_REL_BASED_HIGHLOW 3
#define IMAGE_REL_BASED_HIGHADJ 4
#define IMAGE_REL_BASED_MIPS_JMPADDR 5
#define IMAGE_REL_BASED_SECTION 6
#define IMAGE_REL_BASED_REL32 7
#define IMAGE_REL_BASED_DIR64 10
#define IMAGE_SCN_CNT_CODE 0x00000020
#define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040
#define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080
#define IMAGE_SCN_MEM_DISCARDABLE 0x02000000
#define IMAGE_SCN_MEM_SHARED 0x10000000
#define IMAGE_SCN_MEM_EXECUTE 0x20000000
#define IMAGE_SCN_MEM_READ 0x40000000
#define IMAGE_SCN_MEM_WRITE 0x80000000
#pragma pack(pop)
/* ----------------------------------------------------------- */
#endif /* ndef IMAGE_NT_SIGNATURE */
/* ----------------------------------------------------------- */
#ifndef IMAGE_REL_BASED_DIR64
# define IMAGE_REL_BASED_DIR64 10
#endif
#pragma pack(push, 1)
struct pe_header
{
IMAGE_DOS_HEADER doshdr;
BYTE dosstub[0x40];
DWORD nt_sig;
IMAGE_FILE_HEADER filehdr;
#ifdef TCC_TARGET_X86_64
IMAGE_OPTIONAL_HEADER64 opthdr;
#else
#ifdef _WIN64
IMAGE_OPTIONAL_HEADER32 opthdr;
#else
IMAGE_OPTIONAL_HEADER opthdr;
#endif
#endif
};
struct pe_reloc_header {
DWORD offset;
DWORD size;
};
struct pe_rsrc_header {
struct _IMAGE_FILE_HEADER filehdr;
struct _IMAGE_SECTION_HEADER sectionhdr;
};
struct pe_rsrc_reloc {
DWORD offset;
DWORD size;
WORD type;
};
#pragma pack(pop)
/* ------------------------------------------------------------- */
/* internal temporary structures */
enum {
sec_text = 0,
sec_rdata ,
sec_data ,
sec_bss ,
sec_idata ,
sec_pdata ,
sec_other ,
sec_rsrc ,
sec_stab ,
sec_stabstr ,
sec_reloc ,
sec_last
};
#if 0
static const DWORD pe_sec_flags[] = {
0x60000020, /* ".text" , */
0xC0000040, /* ".data" , */
0xC0000080, /* ".bss" , */
0x40000040, /* ".idata" , */
0x40000040, /* ".pdata" , */
0xE0000060, /* < other > , */
0x40000040, /* ".rsrc" , */
0x42000802, /* ".stab" , */
0x42000040, /* ".reloc" , */
};
#endif
struct section_info {
int cls;
char name[32];
ADDR3264 sh_addr;
DWORD sh_size;
DWORD pe_flags;
Section *sec;
DWORD data_size;
IMAGE_SECTION_HEADER ish;
};
struct import_symbol {
int sym_index;
int iat_index;
int thk_offset;
};
struct pe_import_info {
int dll_index;
int sym_count;
struct import_symbol **symbols;
};
struct pe_info {
TCCState *s1;
Section *reloc;
Section *thunk;
const char *filename;
int type;
DWORD sizeofheaders;
ADDR3264 imagebase;
const char *start_symbol;
DWORD start_addr;
DWORD imp_offs;
DWORD imp_size;
DWORD iat_offs;
DWORD iat_size;
DWORD exp_offs;
DWORD exp_size;
int subsystem;
DWORD section_align;
DWORD file_align;
struct section_info **sec_info;
int sec_count;
struct pe_import_info **imp_info;
int imp_count;
};
#define PE_NUL 0
#define PE_DLL 1
#define PE_GUI 2
#define PE_EXE 3
#define PE_RUN 4
/* --------------------------------------------*/
static const char *pe_export_name(TCCState *s1, ElfW(Sym) *sym)
{
const char *name = (char*)symtab_section->link->data + sym->st_name;
if (s1->leading_underscore && name[0] == '_' && !(sym->st_other & ST_PE_STDCALL))
return name + 1;
return name;
}
static int pe_find_import(TCCState * s1, ElfW(Sym) *sym)
{
char buffer[200];
const char *s, *p;
int sym_index = 0, n = 0;
int a, err = 0;
do {
s = pe_export_name(s1, sym);
a = 0;
if (n) {
/* second try: */
if (sym->st_other & ST_PE_STDCALL) {
/* try w/0 stdcall deco (windows API convention) */
p = strrchr(s, '@');
if (!p || s[0] != '_')
break;
strcpy(buffer, s+1)[p-s-1] = 0;
} else if (s[0] != '_') { /* try non-ansi function */
buffer[0] = '_', strcpy(buffer + 1, s);
} else if (0 == memcmp(s, "__imp_", 6)) { /* mingw 2.0 */
strcpy(buffer, s + 6), a = 1;
} else if (0 == memcmp(s, "_imp__", 6)) { /* mingw 3.7 */
strcpy(buffer, s + 6), a = 1;
} else {
continue;
}
s = buffer;
}
sym_index = find_elf_sym(s1->dynsymtab_section, s);
// printf("find (%d) %d %s\n", n, sym_index, s);
if (sym_index
&& ELFW(ST_TYPE)(sym->st_info) == STT_OBJECT
&& 0 == (sym->st_other & ST_PE_IMPORT)
&& 0 == a
) err = -1, sym_index = 0;
} while (0 == sym_index && ++n < 2);
return n == 2 ? err : sym_index;
}
/*----------------------------------------------------------------------------*/
static int dynarray_assoc(void **pp, int n, int key)
{
int i;
for (i = 0; i < n; ++i, ++pp)
if (key == **(int **) pp)
return i;
return -1;
}
static DWORD umin(DWORD a, DWORD b)
{
return a < b ? a : b;
}
static DWORD umax(DWORD a, DWORD b)
{
return a < b ? b : a;
}
static DWORD pe_file_align(struct pe_info *pe, DWORD n)
{
return (n + (pe->file_align - 1)) & ~(pe->file_align - 1);
}
static ADDR3264 pe_virtual_align(struct pe_info *pe, ADDR3264 n)
{
return (n + (pe->section_align - 1)) & ~(ADDR3264)(pe->section_align - 1);
}
static void pe_align_section(Section *s, int a)
{
int i = s->data_offset & (a-1);
if (i)
section_ptr_add(s, a - i);
}
static void pe_set_datadir(struct pe_header *hdr, int dir, DWORD addr, DWORD size)
{
hdr->opthdr.DataDirectory[dir].VirtualAddress = addr;
hdr->opthdr.DataDirectory[dir].Size = size;
}
struct pe_file {
FILE *op;
DWORD sum;
unsigned pos;
};
static int pe_fwrite(void *data, int len, struct pe_file *pf)
{
WORD *p = data;
DWORD sum;
int ret, i;
pf->pos += (ret = fwrite(data, 1, len, pf->op));
sum = pf->sum;
for (i = len; i > 0; i -= 2) {
sum += (i >= 2) ? *p++ : *(BYTE*)p;
sum = (sum + (sum >> 16)) & 0xFFFF;
}
pf->sum = sum;
return len == ret ? 0 : -1;
}
static void pe_fpad(struct pe_file *pf, DWORD new_pos)
{
char buf[256];
int n, diff = new_pos - pf->pos;
memset(buf, 0, sizeof buf);
while (diff > 0) {
diff -= n = umin(diff, sizeof buf);
fwrite(buf, n, 1, pf->op);
}
pf->pos = new_pos;
}
/*----------------------------------------------------------------------------*/
static int pe_write(struct pe_info *pe)
{
static const struct pe_header pe_template = {
{
/* IMAGE_DOS_HEADER doshdr */
0x5A4D, /*WORD e_magic; Magic number */
0x0090, /*WORD e_cblp; Bytes on last page of file */
0x0003, /*WORD e_cp; Pages in file */
0x0000, /*WORD e_crlc; Relocations */
0x0004, /*WORD e_cparhdr; Size of header in paragraphs */
0x0000, /*WORD e_minalloc; Minimum extra paragraphs needed */
0xFFFF, /*WORD e_maxalloc; Maximum extra paragraphs needed */
0x0000, /*WORD e_ss; Initial (relative) SS value */
0x00B8, /*WORD e_sp; Initial SP value */
0x0000, /*WORD e_csum; Checksum */
0x0000, /*WORD e_ip; Initial IP value */
0x0000, /*WORD e_cs; Initial (relative) CS value */
0x0040, /*WORD e_lfarlc; File address of relocation table */
0x0000, /*WORD e_ovno; Overlay number */
{0,0,0,0}, /*WORD e_res[4]; Reserved words */
0x0000, /*WORD e_oemid; OEM identifier (for e_oeminfo) */
0x0000, /*WORD e_oeminfo; OEM information; e_oemid specific */
{0,0,0,0,0,0,0,0,0,0}, /*WORD e_res2[10]; Reserved words */
0x00000080 /*DWORD e_lfanew; File address of new exe header */
},{
/* BYTE dosstub[0x40] */
/* 14 code bytes + "This program cannot be run in DOS mode.\r\r\n$" + 6 * 0x00 */
0x0e,0x1f,0xba,0x0e,0x00,0xb4,0x09,0xcd,0x21,0xb8,0x01,0x4c,0xcd,0x21,0x54,0x68,
0x69,0x73,0x20,0x70,0x72,0x6f,0x67,0x72,0x61,0x6d,0x20,0x63,0x61,0x6e,0x6e,0x6f,
0x74,0x20,0x62,0x65,0x20,0x72,0x75,0x6e,0x20,0x69,0x6e,0x20,0x44,0x4f,0x53,0x20,
0x6d,0x6f,0x64,0x65,0x2e,0x0d,0x0d,0x0a,0x24,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
},
0x00004550, /* DWORD nt_sig = IMAGE_NT_SIGNATURE */
{
/* IMAGE_FILE_HEADER filehdr */
IMAGE_FILE_MACHINE, /*WORD Machine; */
0x0003, /*WORD NumberOfSections; */
0x00000000, /*DWORD TimeDateStamp; */
0x00000000, /*DWORD PointerToSymbolTable; */
0x00000000, /*DWORD NumberOfSymbols; */
#if defined(TCC_TARGET_X86_64)
0x00F0, /*WORD SizeOfOptionalHeader; */
0x022F /*WORD Characteristics; */
#define CHARACTERISTICS_DLL 0x222E
#elif defined(TCC_TARGET_I386)
0x00E0, /*WORD SizeOfOptionalHeader; */
0x030F /*WORD Characteristics; */
#define CHARACTERISTICS_DLL 0x230E
#elif defined(TCC_TARGET_ARM)
0x00E0, /*WORD SizeOfOptionalHeader; */
0x010F, /*WORD Characteristics; */
#define CHARACTERISTICS_DLL 0x230F
#endif
},{
/* IMAGE_OPTIONAL_HEADER opthdr */
/* Standard fields. */
#ifdef TCC_TARGET_X86_64
0x020B, /*WORD Magic; */
#else
0x010B, /*WORD Magic; */
#endif
0x06, /*BYTE MajorLinkerVersion; */
0x00, /*BYTE MinorLinkerVersion; */
0x00000000, /*DWORD SizeOfCode; */
0x00000000, /*DWORD SizeOfInitializedData; */
0x00000000, /*DWORD SizeOfUninitializedData; */
0x00000000, /*DWORD AddressOfEntryPoint; */
0x00000000, /*DWORD BaseOfCode; */
#ifndef TCC_TARGET_X86_64
0x00000000, /*DWORD BaseOfData; */
#endif
/* NT additional fields. */
#if defined(TCC_TARGET_ARM)
0x00100000, /*DWORD ImageBase; */
#else
0x00400000, /*DWORD ImageBase; */
#endif
0x00001000, /*DWORD SectionAlignment; */
0x00000200, /*DWORD FileAlignment; */
0x0004, /*WORD MajorOperatingSystemVersion; */
0x0000, /*WORD MinorOperatingSystemVersion; */
0x0000, /*WORD MajorImageVersion; */
0x0000, /*WORD MinorImageVersion; */
0x0004, /*WORD MajorSubsystemVersion; */
0x0000, /*WORD MinorSubsystemVersion; */
0x00000000, /*DWORD Win32VersionValue; */
0x00000000, /*DWORD SizeOfImage; */
0x00000200, /*DWORD SizeOfHeaders; */
0x00000000, /*DWORD CheckSum; */
0x0002, /*WORD Subsystem; */
0x0000, /*WORD DllCharacteristics; */
0x00100000, /*DWORD SizeOfStackReserve; */
0x00001000, /*DWORD SizeOfStackCommit; */
0x00100000, /*DWORD SizeOfHeapReserve; */
0x00001000, /*DWORD SizeOfHeapCommit; */
0x00000000, /*DWORD LoaderFlags; */
0x00000010, /*DWORD NumberOfRvaAndSizes; */
/* IMAGE_DATA_DIRECTORY DataDirectory[16]; */
{{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0},
{0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}, {0,0}}
}};
struct pe_header pe_header = pe_template;
int i;
struct pe_file pf = {0};
DWORD file_offset;
struct section_info *si;
IMAGE_SECTION_HEADER *psh;
TCCState *s1 = pe->s1;
pf.op = fopen(pe->filename, "wb");
if (NULL == pf.op) {
tcc_error_noabort("could not write '%s': %s", pe->filename, strerror(errno));
return -1;
}
pe->sizeofheaders = pe_file_align(pe,
sizeof (struct pe_header)
+ pe->sec_count * sizeof (IMAGE_SECTION_HEADER)
);
file_offset = pe->sizeofheaders;
if (2 == pe->s1->verbose)
printf("-------------------------------"
"\n virt file size section" "\n");
for (i = 0; i < pe->sec_count; ++i) {
DWORD addr, size;
const char *sh_name;
si = pe->sec_info[i];
sh_name = si->name;
addr = si->sh_addr - pe->imagebase;
size = si->sh_size;
psh = &si->ish;
if (2 == pe->s1->verbose)
printf("%6x %6x %6x %s\n",
(unsigned)addr, (unsigned)file_offset, (unsigned)size, sh_name);
switch (si->cls) {
case sec_text:
if (!pe_header.opthdr.BaseOfCode)
pe_header.opthdr.BaseOfCode = addr;
break;
case sec_data:
#ifndef TCC_TARGET_X86_64
if (!pe_header.opthdr.BaseOfData)
pe_header.opthdr.BaseOfData = addr;
#endif
break;
case sec_bss:
break;
case sec_reloc:
pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_BASERELOC, addr, size);
break;
case sec_rsrc:
pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_RESOURCE, addr, size);
break;
case sec_pdata:
pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXCEPTION, addr, size);
break;
}
if (pe->imp_size) {
pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IMPORT,
pe->imp_offs, pe->imp_size);
pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_IAT,
pe->iat_offs, pe->iat_size);
}
if (pe->exp_size) {
pe_set_datadir(&pe_header, IMAGE_DIRECTORY_ENTRY_EXPORT,
pe->exp_offs, pe->exp_size);
}
memcpy(psh->Name, sh_name, umin(strlen(sh_name), sizeof psh->Name));
psh->Characteristics = si->pe_flags;
psh->VirtualAddress = addr;
psh->Misc.VirtualSize = size;
pe_header.opthdr.SizeOfImage =
umax(pe_virtual_align(pe, size + addr), pe_header.opthdr.SizeOfImage);
if (si->data_size) {
psh->PointerToRawData = file_offset;
file_offset = pe_file_align(pe, file_offset + si->data_size);
psh->SizeOfRawData = file_offset - psh->PointerToRawData;
if (si->cls == sec_text)
pe_header.opthdr.SizeOfCode += psh->SizeOfRawData;
else
pe_header.opthdr.SizeOfInitializedData += psh->SizeOfRawData;
}
}
//pe_header.filehdr.TimeDateStamp = time(NULL);
pe_header.filehdr.NumberOfSections = pe->sec_count;
pe_header.opthdr.AddressOfEntryPoint = pe->start_addr;
pe_header.opthdr.SizeOfHeaders = pe->sizeofheaders;
pe_header.opthdr.ImageBase = pe->imagebase;
pe_header.opthdr.Subsystem = pe->subsystem;
if (pe->s1->pe_stack_size)
pe_header.opthdr.SizeOfStackReserve = pe->s1->pe_stack_size;
if (PE_DLL == pe->type)
pe_header.filehdr.Characteristics = CHARACTERISTICS_DLL;
pe_header.filehdr.Characteristics |= pe->s1->pe_characteristics;
pe_fwrite(&pe_header, sizeof pe_header, &pf);
for (i = 0; i < pe->sec_count; ++i)
pe_fwrite(&pe->sec_info[i]->ish, sizeof(IMAGE_SECTION_HEADER), &pf);
file_offset = pe->sizeofheaders;
for (i = 0; i < pe->sec_count; ++i) {
Section *s;
si = pe->sec_info[i];
if (!si->data_size)
continue;
for (s = si->sec; s; s = s->prev) {
pe_fpad(&pf, file_offset);
pe_fwrite(s->data, s->data_offset, &pf);
if (s->prev)
file_offset += s->prev->sh_addr - s->sh_addr;
}
file_offset = si->ish.PointerToRawData + si->ish.SizeOfRawData;
pe_fpad(&pf, file_offset);
}
pf.sum += file_offset;
fseek(pf.op, offsetof(struct pe_header, opthdr.CheckSum), SEEK_SET);
pe_fwrite(&pf.sum, sizeof (DWORD), &pf);
fclose (pf.op);
#ifndef _WIN32
chmod(pe->filename, 0777);
#endif
if (2 == pe->s1->verbose)
printf("-------------------------------\n");
if (pe->s1->verbose)
printf("<- %s (%u bytes)\n", pe->filename, (unsigned)file_offset);
return 0;
}
/*----------------------------------------------------------------------------*/
static struct import_symbol *pe_add_import(struct pe_info *pe, int sym_index)
{
int i;
int dll_index;
struct pe_import_info *p;
struct import_symbol *s;
ElfW(Sym) *isym;
isym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
dll_index = isym->st_size;
i = dynarray_assoc ((void**)pe->imp_info, pe->imp_count, dll_index);
if (-1 != i) {
p = pe->imp_info[i];
goto found_dll;
}
p = tcc_mallocz(sizeof *p);
p->dll_index = dll_index;
dynarray_add(&pe->imp_info, &pe->imp_count, p);
found_dll:
i = dynarray_assoc ((void**)p->symbols, p->sym_count, sym_index);
if (-1 != i)
return p->symbols[i];
s = tcc_mallocz(sizeof *s);
dynarray_add(&p->symbols, &p->sym_count, s);
s->sym_index = sym_index;
return s;
}
void pe_free_imports(struct pe_info *pe)
{
int i;
for (i = 0; i < pe->imp_count; ++i) {
struct pe_import_info *p = pe->imp_info[i];
dynarray_reset(&p->symbols, &p->sym_count);
}
dynarray_reset(&pe->imp_info, &pe->imp_count);
}
/*----------------------------------------------------------------------------*/
static void pe_build_imports(struct pe_info *pe)
{
int thk_ptr, ent_ptr, dll_ptr, sym_cnt, i;
DWORD rva_base = pe->thunk->sh_addr - pe->imagebase;
int ndlls = pe->imp_count;
TCCState *s1 = pe->s1;
for (sym_cnt = i = 0; i < ndlls; ++i)
sym_cnt += pe->imp_info[i]->sym_count;
if (0 == sym_cnt)
return;
pe_align_section(pe->thunk, 16);
pe->imp_size = (ndlls + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR);
pe->iat_size = (sym_cnt + ndlls) * sizeof(ADDR3264);
dll_ptr = pe->thunk->data_offset;
thk_ptr = dll_ptr + pe->imp_size;
ent_ptr = thk_ptr + pe->iat_size;
pe->imp_offs = dll_ptr + rva_base;
pe->iat_offs = thk_ptr + rva_base;
section_ptr_add(pe->thunk, pe->imp_size + 2*pe->iat_size);
for (i = 0; i < pe->imp_count; ++i) {
IMAGE_IMPORT_DESCRIPTOR *hdr;
int k, n, dllindex;
ADDR3264 v;
struct pe_import_info *p = pe->imp_info[i];
const char *name;
DLLReference *dllref;
dllindex = p->dll_index;
if (dllindex)
name = tcc_basename((dllref = pe->s1->loaded_dlls[dllindex-1])->name);
else
name = "", dllref = NULL;
/* put the dll name into the import header */
v = put_elf_str(pe->thunk, name);
hdr = (IMAGE_IMPORT_DESCRIPTOR*)(pe->thunk->data + dll_ptr);
hdr->FirstThunk = thk_ptr + rva_base;
hdr->OriginalFirstThunk = ent_ptr + rva_base;
hdr->Name = v + rva_base;
for (k = 0, n = p->sym_count; k <= n; ++k) {
if (k < n) {
int iat_index = p->symbols[k]->iat_index;
int sym_index = p->symbols[k]->sym_index;
ElfW(Sym) *imp_sym = (ElfW(Sym) *)pe->s1->dynsymtab_section->data + sym_index;
ElfW(Sym) *org_sym = (ElfW(Sym) *)symtab_section->data + iat_index;
const char *name = (char*)pe->s1->dynsymtab_section->link->data + imp_sym->st_name;
int ordinal;
org_sym->st_value = thk_ptr;
org_sym->st_shndx = pe->thunk->sh_num;
if (dllref)
v = 0, ordinal = imp_sym->st_value; /* ordinal from pe_load_def */
else
ordinal = 0, v = imp_sym->st_value; /* address from tcc_add_symbol() */
#ifdef TCC_IS_NATIVE
if (pe->type == PE_RUN) {
if (dllref) {
if ( !dllref->handle )
dllref->handle = LoadLibrary(dllref->name);
v = (ADDR3264)GetProcAddress(dllref->handle, ordinal?(char*)0+ordinal:name);
}
if (!v)
tcc_error_noabort("could not resolve symbol '%s'", name);
} else
#endif
if (ordinal) {
v = ordinal | (ADDR3264)1 << (sizeof(ADDR3264)*8 - 1);
} else {
v = pe->thunk->data_offset + rva_base;
section_ptr_add(pe->thunk, sizeof(WORD)); /* hint, not used */
put_elf_str(pe->thunk, name);
}
} else {
v = 0; /* last entry is zero */
}
*(ADDR3264*)(pe->thunk->data+thk_ptr) =
*(ADDR3264*)(pe->thunk->data+ent_ptr) = v;
thk_ptr += sizeof (ADDR3264);
ent_ptr += sizeof (ADDR3264);
}
dll_ptr += sizeof(IMAGE_IMPORT_DESCRIPTOR);
}
}
/* ------------------------------------------------------------- */
struct pe_sort_sym
{
int index;
const char *name;
};
static int sym_cmp(const void *va, const void *vb)
{
const char *ca = (*(struct pe_sort_sym**)va)->name;
const char *cb = (*(struct pe_sort_sym**)vb)->name;
return strcmp(ca, cb);
}
static void pe_build_exports(struct pe_info *pe)
{
ElfW(Sym) *sym;
int sym_index, sym_end;
DWORD rva_base, base_o, func_o, name_o, ord_o, str_o;
IMAGE_EXPORT_DIRECTORY *hdr;
int sym_count, ord;
struct pe_sort_sym **sorted, *p;
TCCState *s1 = pe->s1;
FILE *op;
char buf[260];
const char *dllname;
const char *name;
rva_base = pe->thunk->sh_addr - pe->imagebase;
sym_count = 0, sorted = NULL, op = NULL;
sym_end = symtab_section->data_offset / sizeof(ElfW(Sym));
for (sym_index = 1; sym_index < sym_end; ++sym_index) {
sym = (ElfW(Sym)*)symtab_section->data + sym_index;
name = pe_export_name(pe->s1, sym);
if (sym->st_other & ST_PE_EXPORT) {
p = tcc_malloc(sizeof *p);
p->index = sym_index;
p->name = name;
dynarray_add(&sorted, &sym_count, p);
}
#if 0
if (sym->st_other & ST_PE_EXPORT)
printf("export: %s\n", name);
if (sym->st_other & ST_PE_STDCALL)
printf("stdcall: %s\n", name);
#endif
}
if (0 == sym_count)
return;
qsort (sorted, sym_count, sizeof *sorted, sym_cmp);
pe_align_section(pe->thunk, 16);
dllname = tcc_basename(pe->filename);
base_o = pe->thunk->data_offset;
func_o = base_o + sizeof(IMAGE_EXPORT_DIRECTORY);
name_o = func_o + sym_count * sizeof (DWORD);
ord_o = name_o + sym_count * sizeof (DWORD);
str_o = ord_o + sym_count * sizeof(WORD);
hdr = section_ptr_add(pe->thunk, str_o - base_o);
hdr->Characteristics = 0;
hdr->Base = 1;
hdr->NumberOfFunctions = sym_count;
hdr->NumberOfNames = sym_count;
hdr->AddressOfFunctions = func_o + rva_base;
hdr->AddressOfNames = name_o + rva_base;
hdr->AddressOfNameOrdinals = ord_o + rva_base;
hdr->Name = str_o + rva_base;
put_elf_str(pe->thunk, dllname);
#if 1
/* automatically write exports to <output-filename>.def */
pstrcpy(buf, sizeof buf, pe->filename);
strcpy(tcc_fileextension(buf), ".def");
op = fopen(buf, "wb");
if (NULL == op) {
tcc_error_noabort("could not create '%s': %s", buf, strerror(errno));
} else {
fprintf(op, "LIBRARY %s\n\nEXPORTS\n", dllname);
if (pe->s1->verbose)
printf("<- %s (%d symbol%s)\n", buf, sym_count, &"s"[sym_count < 2]);
}
#endif
for (ord = 0; ord < sym_count; ++ord)
{
p = sorted[ord], sym_index = p->index, name = p->name;
/* insert actual address later in relocate_sections() */
put_elf_reloc(symtab_section, pe->thunk,
func_o, R_XXX_RELATIVE, sym_index);
*(DWORD*)(pe->thunk->data + name_o)
= pe->thunk->data_offset + rva_base;
*(WORD*)(pe->thunk->data + ord_o)
= ord;
put_elf_str(pe->thunk, name);
func_o += sizeof (DWORD);
name_o += sizeof (DWORD);
ord_o += sizeof (WORD);
if (op)
fprintf(op, "%s\n", name);