/
mscoffobj.d
2601 lines (2252 loc) · 78.3 KB
/
mscoffobj.d
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
/**
* Compiler implementation of the
* $(LINK2 https://www.dlang.org, D programming language).
*
* Copyright: Copyright (C) 2009-2024 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/backend/mscoffobj.d, backend/mscoffobj.d)
*/
module dmd.backend.mscoffobj;
import core.stdc.ctype;
import core.stdc.stdio;
import core.stdc.stdint;
import core.stdc.stdlib;
import core.stdc.string;
import core.stdc.time;
import dmd.backend.barray;
import dmd.backend.cc;
import dmd.backend.cdef;
import dmd.backend.code;
import dmd.backend.code_x86;
import dmd.backend.cv8;
import dmd.backend.dlist;
import dmd.backend.dvec;
import dmd.backend.el;
import dmd.backend.md5;
import dmd.backend.mem;
import dmd.backend.global;
import dmd.backend.obj;
import dmd.backend.ty;
import dmd.backend.type;
import dmd.backend.mscoff;
import dmd.common.outbuffer;
nothrow:
@safe:
alias _compare_fp_t = extern(C) nothrow int function(const void*, const void*);
extern(C) void qsort(void* base, size_t nmemb, size_t size, _compare_fp_t compar);
extern (C) char* strupr(char*);
private extern (D) __gshared OutBuffer *fobjbuf;
enum DEST_LEN = (IDMAX + IDOHD + 1);
/******************************************
*/
// The object file is built ib several separate pieces
__gshared private
{
// String Table - String table for all other names
OutBuffer *string_table;
// Section Headers
public OutBuffer *ScnhdrBuf; // Buffer to build section table in
// The -1 is because it is 1 based indexing
@trusted
IMAGE_SECTION_HEADER* ScnhdrTab() { return cast(IMAGE_SECTION_HEADER *)ScnhdrBuf.buf - 1; }
int scnhdr_cnt; // Number of sections in table
enum SCNHDR_TAB_INITSIZE = 16; // Initial number of sections in buffer
enum SCNHDR_TAB_INC = 4; // Number of sections to increment buffer by
enum SYM_TAB_INIT = 100; // Initial number of symbol entries in buffer
enum SYM_TAB_INC = 50; // Number of symbols to increment buffer by
// The symbol table
OutBuffer *symbuf;
OutBuffer *syment_buf; // array of struct syment
segidx_t segidx_drectve = UNKNOWN; // contents of ".drectve" section
segidx_t segidx_debugS = UNKNOWN;
segidx_t segidx_xdata = UNKNOWN;
segidx_t segidx_pdata = UNKNOWN;
extern (D) int jumpTableSeg; // segment index for __jump_table
extern (D) OutBuffer *indirectsymbuf2; // indirect symbol table of Symbol*'s
extern (D) int pointersSeg; // segment index for __pointers
OutBuffer *ptrref_buf; // buffer for pointer references
OutBuffer *impref_buf; // buffer for import table references
int floatused;
/* If an MsCoffObj_external_def() happens, set this to the string index,
* to be added last to the symbol table.
* Obviously, there can be only one.
*/
extern (D) IDXSTR extdef;
// Each compiler segment is a section
// Predefined compiler segments CODE,DATA,CDATA,UDATA map to indexes
// into SegData[]
// New compiler segments are added to end.
public:
/******************************
* Returns !=0 if this segment is a code segment.
*/
@trusted
int mscoff_seg_data_isCode(const ref seg_data sd)
{
return (ScnhdrTab[sd.SDshtidx].Characteristics & IMAGE_SCN_CNT_CODE) != 0;
}
private extern (D) segidx_t seg_tlsseg = UNKNOWN;
private extern (D) segidx_t seg_tlsseg_bss = UNKNOWN;
}
/*******************************************************
* Because the mscoff relocations cannot be computed until after
* all the segments are written out, and we need more information
* than the mscoff relocations provide, make our own relocation
* type. Later, translate to mscoff relocation structure.
*/
enum
{
RELaddr = 0, // straight address
RELrel = 1, // relative to location to be fixed up
RELseg = 2, // 2 byte section
RELaddr32 = 3, // 4 byte offset
}
struct Relocation
{ // Relocations are attached to the struct seg_data they refer to
targ_size_t offset; // location in segment to be fixed up
Symbol *funcsym; // function in which offset lies, if any
Symbol *targsym; // if !=null, then location is to be fixed up
// to address of this symbol
uint targseg; // if !=0, then location is to be fixed up
// to address of start of this segment
ubyte rtype; // RELxxxx
short val; // 0, -1, -2, -3, -4, -5
}
/*******************************
* Output a string into a string table
* Input:
* strtab = string table for entry
* str = string to add
*
* Returns offset into the specified string table.
*/
IDXSTR MsCoffObj_addstr(OutBuffer *strtab, const char[] str) @system
{
//printf("MsCoffObj_addstr(strtab = %p str = '%s')\n",strtab,str);
IDXSTR idx = cast(IDXSTR)strtab.length(); // remember starting offset
strtab.writeStringz(str);
//printf("\tidx %d, new size %d\n",idx,strtab.length());
return idx;
}
/**************************
* Output read only data and generate a symbol for it.
*
*/
Symbol * MsCoffObj_sym_cdata(tym_t ty,char *p,int len)
{
//printf("MsCoffObj_sym_cdata(ty = %x, p = %x, len = %d, Offset(CDATA) = %x)\n", ty, p, len, Offset(CDATA));
alignOffset(CDATA, tysize(ty));
Symbol *s = symboldata(Offset(CDATA), ty);
s.Sseg = CDATA;
MsCoffObj_pubdef(CDATA, s, Offset(CDATA));
MsCoffObj_bytes(CDATA, Offset(CDATA), len, p);
s.Sfl = FLdata; //FLextern;
return s;
}
/**************************
* Ouput read only data for data
*
*/
@trusted
int MsCoffObj_data_readonly(char *p, int len, segidx_t *pseg)
{
int oldoff;
oldoff = cast(int)Offset(CDATA);
SegData[CDATA].SDbuf.reserve(len);
SegData[CDATA].SDbuf.writen(p,len);
Offset(CDATA) += len;
*pseg = CDATA;
return oldoff;
}
@trusted
int MsCoffObj_data_readonly(char *p, int len)
{
segidx_t pseg;
return MsCoffObj_data_readonly(p, len, &pseg);
}
/*****************************
* Get segment for readonly string literals.
* The linker will pool strings in this section.
* Params:
* sz = number of bytes per character (1, 2, or 4)
* Returns:
* segment index
*/
int MsCoffObj_string_literal_segment(uint sz)
{
assert(0);
}
/******************************
* Start a .obj file.
* Called before any other obj_xxx routines.
* One source file can generate multiple .obj files.
*/
@system
Obj MsCoffObj_init(OutBuffer *objbuf, const(char)* filename, const(char)* csegname)
{
//printf("MsCoffObj_init()\n");
Obj obj = cast(Obj)mem_calloc(__traits(classInstanceSize, Obj));
cseg = CODE;
fobjbuf = objbuf;
assert(objbuf.length() == 0);
floatused = 0;
segidx_drectve = UNKNOWN;
seg_tlsseg = UNKNOWN;
seg_tlsseg_bss = UNKNOWN;
segidx_pdata = UNKNOWN;
segidx_xdata = UNKNOWN;
segidx_debugS = UNKNOWN;
// Initialize buffers
if (!string_table)
{
string_table = cast(OutBuffer*) calloc(1, OutBuffer.sizeof);
if (!string_table)
err_nomem();
string_table.reserve(2048);
}
string_table.reset();
string_table.write32(4); // first 4 bytes are length of string table
if (symbuf)
{
Symbol **p = cast(Symbol **)symbuf.buf;
const size_t n = symbuf.length() / (Symbol *).sizeof;
for (size_t i = 0; i < n; ++i)
symbol_reset(p[i]);
symbuf.reset();
}
else
{
symbuf = cast(OutBuffer*) calloc(1, OutBuffer.sizeof);
if (!symbuf)
err_nomem();
symbuf.reserve((Symbol *).sizeof * SYM_TAB_INIT);
}
if (!syment_buf)
{
syment_buf = cast(OutBuffer*) calloc(1, OutBuffer.sizeof);
if (!syment_buf)
err_nomem();
syment_buf.reserve(SymbolTable32.sizeof * SYM_TAB_INIT);
}
syment_buf.reset();
extdef = 0;
pointersSeg = 0;
// Initialize segments for CODE, DATA, UDATA and CDATA
if (!ScnhdrBuf)
{
ScnhdrBuf = cast(OutBuffer*) calloc(1, OutBuffer.sizeof);
if (!ScnhdrBuf)
err_nomem();
ScnhdrBuf.reserve(SCNHDR_TAB_INITSIZE * (IMAGE_SECTION_HEADER).sizeof);
}
ScnhdrBuf.reset();
scnhdr_cnt = 0;
/* Define sections. Although the order should not matter, we duplicate
* the same order VC puts out just to avoid trouble.
*/
int alignText = I64 ? IMAGE_SCN_ALIGN_16BYTES : IMAGE_SCN_ALIGN_8BYTES;
int alignData = IMAGE_SCN_ALIGN_16BYTES;
MsCoffObj_addScnhdr(".data$B", IMAGE_SCN_CNT_INITIALIZED_DATA |
alignData |
IMAGE_SCN_MEM_READ |
IMAGE_SCN_MEM_WRITE); // DATA
MsCoffObj_addScnhdr(".text", IMAGE_SCN_CNT_CODE |
alignText |
IMAGE_SCN_MEM_EXECUTE |
IMAGE_SCN_MEM_READ); // CODE
MsCoffObj_addScnhdr(".bss$B", IMAGE_SCN_CNT_UNINITIALIZED_DATA |
alignData |
IMAGE_SCN_MEM_READ |
IMAGE_SCN_MEM_WRITE); // UDATA
MsCoffObj_addScnhdr(".rdata", IMAGE_SCN_CNT_INITIALIZED_DATA |
alignData |
IMAGE_SCN_MEM_READ); // CONST
SegData.reset();
SegData.push();
enum
{
SHI_DATA = 1,
SHI_TEXT = 2,
SHI_UDATA = 3,
SHI_CDATA = 4,
}
MsCoffObj_getsegment2(SHI_TEXT);
assert(SegData[CODE].SDseg == CODE);
MsCoffObj_getsegment2(SHI_DATA);
assert(SegData[DATA].SDseg == DATA);
MsCoffObj_getsegment2(SHI_CDATA);
assert(SegData[CDATA].SDseg == CDATA);
MsCoffObj_getsegment2(SHI_UDATA);
assert(SegData[UDATA].SDseg == UDATA);
if (config.fulltypes)
cv8_initfile(filename);
assert(objbuf.length() == 0);
return obj;
}
/**************************
* Start a module within a .obj file.
* There can be multiple modules within a single .obj file.
*
* Input:
* filename: Name of source file
* csegname: User specified default code segment name
*/
@trusted
void MsCoffObj_initfile(const(char)* filename, const(char)* csegname, const(char)* modname)
{
//dbg_printf("MsCoffObj_initfile(filename = %s, modname = %s)\n",filename,modname);
if (config.fulltypes)
cv8_initmodule(filename, modname);
}
/************************************
* Patch pseg/offset by adding in the vmaddr difference from
* pseg/offset to start of seg.
*/
@trusted
private extern (D)
int32_t *MsCoffObj_patchAddr(int seg, targ_size_t offset)
{
return cast(int32_t *)(fobjbuf.buf + ScnhdrTab[SegData[seg].SDshtidx].PointerToRawData + offset);
}
@trusted
private extern (D)
int32_t *MsCoffObj_patchAddr64(int seg, targ_size_t offset)
{
return cast(int32_t *)(fobjbuf.buf + ScnhdrTab[SegData[seg].SDshtidx].PointerToRawData + offset);
}
private extern (D)
static if (0)
{
@trusted
void patch(seg_data *pseg, targ_size_t offset, int seg, targ_size_t value)
{
//printf("patch(offset = x%04x, seg = %d, value = x%llx)\n", cast(uint)offset, seg, value);
if (I64)
{
int32_t *p = cast(int32_t *)(fobjbuf.buf + ScnhdrTab[pseg.SDshtidx].PointerToRawData + offset);
static if (0)
printf("\taddr1 = x%llx\n\taddr2 = x%llx\n\t*p = x%llx\n\tdelta = x%llx\n",
ScnhdrTab[pseg.SDshtidx].VirtualAddress,
ScnhdrTab[SegData[seg].SDshtidx].VirtualAddress,
*p,
ScnhdrTab[SegData[seg].SDshtidx].VirtualAddress -
(ScnhdrTab[pseg.SDshtidx].VirtualAddress + offset));
*p += ScnhdrTab[SegData[seg].SDshtidx].VirtualAddress -
(ScnhdrTab[pseg.SDshtidx].VirtualAddress - value);
}
else
{
int32_t *p = cast(int32_t *)(fobjbuf.buf + ScnhdrTab[pseg.SDshtidx].PointerToRawData + offset);
static if (0)
printf("\taddr1 = x%x\n\taddr2 = x%x\n\t*p = x%x\n\tdelta = x%x\n",
ScnhdrTab[pseg.SDshtidx].VirtualAddress,
ScnhdrTab[SegData[seg].SDshtidx].VirtualAddress,
*p,
ScnhdrTab[SegData[seg].SDshtidx].VirtualAddress -
(ScnhdrTab[pseg.SDshtidx].VirtualAddress + offset));
*p += ScnhdrTab[SegData[seg].SDshtidx].VirtualAddress -
(ScnhdrTab[pseg.SDshtidx].VirtualAddress - value);
}
}
}
/*********************************
* Build syment[], the array of symbols.
* Store them in syment_buf.
*/
@trusted
private void syment_set_name(SymbolTable32 *sym, const(char)* name)
{
size_t len = strlen(name);
if (len > 8)
{ // Use offset into string table
IDXSTR idx = MsCoffObj_addstr(string_table, name[0 .. len]);
sym.Zeros = 0;
sym.Offset = idx;
}
else
{ memcpy(sym.Name.ptr, name, len);
if (len < 8)
memset(sym.Name.ptr + len, 0, 8 - len);
}
}
@trusted
void write_sym(SymbolTable32* sym, bool bigobj)
{
assert((*sym).sizeof == 20);
if (bigobj)
{
syment_buf.write(sym[0 .. 1]);
}
else
{
// the only difference between SymbolTable32 and SymbolTable
// is that field SectionNumber is long instead of short
uint scoff = cast(uint)(cast(char*)&sym.SectionNumber - cast(char*)sym);
syment_buf.write(sym, scoff + 2);
syment_buf.write(cast(char*)sym + scoff + 4, cast(uint)((*sym).sizeof - scoff - 4));
}
}
@trusted
void build_syment_table(bool bigobj)
{
/* The @comp.id symbol appears to be the version of VC that generated the .obj file.
* Anything we put in there would have no relevance, so we'll not put out this symbol.
*/
uint symsize = bigobj ? SymbolTable32.sizeof : SymbolTable.sizeof;
/* Now goes one symbol per section.
*/
for (segidx_t seg = 1; seg < SegData.length; seg++)
{
seg_data *pseg = SegData[seg];
IMAGE_SECTION_HEADER *psechdr = &ScnhdrTab[pseg.SDshtidx]; // corresponding section
SymbolTable32 sym;
memcpy(sym.Name.ptr, psechdr.Name.ptr, 8);
sym.Value = 0;
sym.SectionNumber = pseg.SDshtidx;
sym.Type = 0;
sym.StorageClass = IMAGE_SYM_CLASS_STATIC;
sym.NumberOfAuxSymbols = 1;
write_sym(&sym, bigobj);
auxent aux = void;
memset(&aux, 0, (aux).sizeof);
// s_size is not set yet
//aux.x_section.length = psechdr.s_size;
if (pseg.SDbuf && pseg.SDbuf.length())
aux.x_section.length = cast(uint)pseg.SDbuf.length();
else
aux.x_section.length = cast(uint)pseg.SDoffset;
if (pseg.SDrel)
aux.x_section.NumberOfRelocations = cast(ushort)(pseg.SDrel.length() / (Relocation).sizeof);
if (psechdr.Characteristics & IMAGE_SCN_LNK_COMDAT)
{
aux.x_section.Selection = cast(ubyte)IMAGE_COMDAT_SELECT_ANY;
if (pseg.SDassocseg)
{ aux.x_section.Selection = cast(ubyte)IMAGE_COMDAT_SELECT_ASSOCIATIVE;
aux.x_section.NumberHighPart = cast(ushort)(pseg.SDassocseg >> 16);
aux.x_section.NumberLowPart = cast(ushort)(pseg.SDassocseg & 0x0000FFFF);
}
}
// memset(&aux.x_section.Zeros, 0, 2);
syment_buf.write(&aux, symsize);
assert((aux).sizeof == 18);
}
/* Add symbols from symbuf[]
*/
int n = cast(int)SegData.length;
size_t dim = symbuf.length() / (Symbol *).sizeof;
for (size_t i = 0; i < dim; i++)
{ Symbol *s = (cast(Symbol **)symbuf.buf)[i];
s.Sxtrnnum = cast(uint)(syment_buf.length() / symsize);
n++;
SymbolTable32 sym;
char[DEST_LEN+1] dest = void;
char *destr = obj_mangle2(s, dest.ptr);
syment_set_name(&sym, destr);
sym.Value = 0;
switch (s.Sclass)
{
case SC.extern_:
sym.SectionNumber = IMAGE_SYM_UNDEFINED;
break;
default:
sym.SectionNumber = SegData[s.Sseg].SDshtidx;
break;
}
sym.Type = tyfunc(s.Stype.Tty) ? 0x20 : 0;
switch (s.Sclass)
{
case SC.static_:
if (s.Sflags & SFLhidden)
goto default;
goto case;
case SC.locstat:
sym.StorageClass = IMAGE_SYM_CLASS_STATIC;
sym.Value = cast(uint)s.Soffset;
break;
default:
sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL;
if (sym.SectionNumber != IMAGE_SYM_UNDEFINED)
sym.Value = cast(uint)s.Soffset;
break;
}
sym.NumberOfAuxSymbols = 0;
write_sym(&sym, bigobj);
}
}
/***************************
* Fixup and terminate object file.
*/
@trusted
void MsCoffObj_termfile()
{
//dbg_printf("MsCoffObj_termfile\n");
if (configv.addlinenumbers)
{
cv8_termmodule();
}
}
/*********************************
* Terminate package.
*/
@trusted
void MsCoffObj_term(const(char)* objfilename)
{
//printf("MsCoffObj_term()\n");
assert(fobjbuf.length() == 0);
objflush_pointerRefs();
outfixlist(); // backpatches
objflush_importTableRefs();
if (configv.addlinenumbers)
{
cv8_termfile(objfilename);
}
// To allow tooling support for most output files
// switch to new object file format (similar to C++ with /bigobj)
// only when exceeding the limit for 16-bit section count according to
// https://msdn.microsoft.com/en-us/library/8578y171%28v=vs.71%29.aspx
bool bigobj = scnhdr_cnt > 65_279;
build_syment_table(bigobj);
/* Write out the object file in the following order:
* Header
* Section Headers
* Symbol table
* String table
* Section data
*/
uint foffset;
// Write out the bytes for the header
BIGOBJ_HEADER header = void;
IMAGE_FILE_HEADER header_old = void;
time_t f_timedat = 0;
time(&f_timedat);
uint symtable_offset;
if (bigobj)
{
header.Sig1 = IMAGE_FILE_MACHINE_UNKNOWN;
header.Sig2 = 0xFFFF;
header.Version = 2;
header.Machine = I64 ? IMAGE_FILE_MACHINE_AMD64 : IMAGE_FILE_MACHINE_I386;
header.NumberOfSections = scnhdr_cnt;
header.TimeDateStamp = cast(uint)f_timedat;
static immutable ubyte[16] uuid =
[ '\xc7', '\xa1', '\xba', '\xd1', '\xee', '\xba', '\xa9', '\x4b',
'\xaf', '\x20', '\xfa', '\xf6', '\x6a', '\xa4', '\xdc', '\xb8' ];
memcpy(header.UUID.ptr, uuid.ptr, 16);
memset(header.unused.ptr, 0, (header.unused).sizeof);
foffset = (header).sizeof; // start after header
foffset += ScnhdrBuf.length(); // section headers
header.PointerToSymbolTable = foffset; // offset to symbol table
symtable_offset = foffset;
header.NumberOfSymbols = cast(uint)(syment_buf.length() / (SymbolTable32).sizeof);
foffset += header.NumberOfSymbols * (SymbolTable32).sizeof; // symbol table
}
else
{
header_old.Machine = I64 ? IMAGE_FILE_MACHINE_AMD64 : IMAGE_FILE_MACHINE_I386;
header_old.NumberOfSections = cast(ushort)scnhdr_cnt;
header_old.TimeDateStamp = cast(uint)f_timedat;
header_old.SizeOfOptionalHeader = 0;
header_old.Characteristics = 0;
foffset = (header_old).sizeof; // start after header
foffset += ScnhdrBuf.length(); // section headers
header_old.PointerToSymbolTable = foffset; // offset to symbol table
symtable_offset = foffset;
header_old.NumberOfSymbols = cast(uint)(syment_buf.length() / (SymbolTable).sizeof);
foffset += header_old.NumberOfSymbols * (SymbolTable).sizeof; // symbol table
}
uint string_table_offset = foffset;
foffset += string_table.length(); // string table
// Compute file offsets of all the section data
for (segidx_t seg = 1; seg < SegData.length; seg++)
{
seg_data *pseg = SegData[seg];
IMAGE_SECTION_HEADER *psechdr = &ScnhdrTab[pseg.SDshtidx]; // corresponding section
int align_ = pseg.SDalignment;
if (align_ > 1)
foffset = (foffset + align_ - 1) & ~(align_ - 1);
if (pseg.SDbuf && pseg.SDbuf.length())
{
psechdr.PointerToRawData = foffset;
//printf("seg = %2d SDshtidx = %2d psechdr = %p s_scnptr = x%x\n", seg, pseg.SDshtidx, psechdr, cast(uint)psechdr.s_scnptr);
psechdr.SizeOfRawData = cast(uint)pseg.SDbuf.length();
foffset += psechdr.SizeOfRawData;
}
else
psechdr.SizeOfRawData = cast(uint)pseg.SDoffset;
}
// Compute file offsets of the relocation data
for (segidx_t seg = 1; seg < SegData.length; seg++)
{
seg_data *pseg = SegData[seg];
IMAGE_SECTION_HEADER *psechdr = &ScnhdrTab[pseg.SDshtidx]; // corresponding section
if (pseg.SDrel)
{
foffset = (foffset + 3) & ~3;
assert(psechdr.PointerToRelocations == 0);
auto nreloc = pseg.SDrel.length() / Relocation.sizeof;
if (nreloc > 0xffff)
{
// https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#coff-relocations-object-only
psechdr.Characteristics |= IMAGE_SCN_LNK_NRELOC_OVFL;
psechdr.PointerToRelocations = foffset;
psechdr.NumberOfRelocations = 0xffff;
foffset += reloc.sizeof;
}
else if (nreloc)
{
psechdr.PointerToRelocations = foffset;
//printf("seg = %d SDshtidx = %d psechdr = %p s_relptr = x%x\n", seg, pseg.SDshtidx, psechdr, cast(uint)psechdr.s_relptr);
psechdr.NumberOfRelocations = cast(ushort)nreloc;
}
foffset += nreloc * reloc.sizeof;
}
}
assert(fobjbuf.length() == 0);
// Write the header
if (bigobj)
{
fobjbuf.write((&header)[0 .. 1]);
foffset = (header).sizeof;
}
else
{
fobjbuf.write((&header_old)[0 .. 1]);
foffset = (header_old).sizeof;
}
// Write the section headers
fobjbuf.write((*ScnhdrBuf)[]);
foffset += ScnhdrBuf.length();
// Write the symbol table
assert(foffset == symtable_offset);
fobjbuf.write((*syment_buf)[]);
foffset += syment_buf.length();
// Write the string table
assert(foffset == string_table_offset);
*cast(uint *)(string_table.buf) = cast(uint)string_table.length();
fobjbuf.write((*string_table)[]);
foffset += string_table.length();
// Write the section data
for (segidx_t seg = 1; seg < SegData.length; seg++)
{
seg_data *pseg = SegData[seg];
IMAGE_SECTION_HEADER *psechdr = &ScnhdrTab[pseg.SDshtidx]; // corresponding section
foffset = elf_align(pseg.SDalignment, foffset);
if (pseg.SDbuf && pseg.SDbuf.length())
{
//printf("seg = %2d SDshtidx = %2d psechdr = %p s_scnptr = x%x, foffset = x%x\n", seg, pseg.SDshtidx, psechdr, cast(uint)psechdr.s_scnptr, cast(uint)foffset);
assert(pseg.SDbuf.length() == psechdr.SizeOfRawData);
assert(foffset == psechdr.PointerToRawData);
fobjbuf.write((*pseg.SDbuf)[]);
foffset += pseg.SDbuf.length();
}
}
// Compute the relocations, write them out
assert((reloc).sizeof == 10);
for (segidx_t seg = 1; seg < SegData.length; seg++)
{
seg_data *pseg = SegData[seg];
IMAGE_SECTION_HEADER *psechdr = &ScnhdrTab[pseg.SDshtidx]; // corresponding section
if (pseg.SDrel)
{
Relocation *r = cast(Relocation *)pseg.SDrel.buf;
size_t sz = pseg.SDrel.length();
bool pdata = (strcmp(cast(const(char)* )psechdr.Name, ".pdata") == 0);
Relocation *rend = cast(Relocation *)(pseg.SDrel.buf + sz);
foffset = elf_align(4, foffset);
debug
if (sz && foffset != psechdr.PointerToRelocations)
printf("seg = %d SDshtidx = %d psechdr = %p s_relptr = x%x, foffset = x%x\n", seg, pseg.SDshtidx, psechdr, cast(uint)psechdr.PointerToRelocations, cast(uint)foffset);
assert(sz == 0 || foffset == psechdr.PointerToRelocations);
if (psechdr.Characteristics & IMAGE_SCN_LNK_NRELOC_OVFL)
{
auto rel = reloc(cast(uint)(sz / Relocation.sizeof) + 1);
fobjbuf.write((&rel)[0 .. 1]);
foffset += rel.sizeof;
}
for (; r != rend; r++)
{ reloc rel;
rel.r_vaddr = 0;
rel.r_symndx = 0;
rel.r_type = 0;
Symbol *s = r.targsym;
const(char)* rs = r.rtype == RELaddr ? "addr" : "rel";
//printf("%d:x%04lx : tseg %d tsym %s REL%s\n", seg, cast(int)r.offset, r.targseg, s ? s.Sident.ptr : "0", rs);
if (s)
{
//printf("Relocation\n");
//symbol_print(s);
if (pseg.isCode())
{
if (I64)
{
rel.r_type = (r.rtype == RELrel)
? IMAGE_REL_AMD64_REL32
: IMAGE_REL_AMD64_REL32;
if (s.Stype.Tty & mTYthread)
rel.r_type = IMAGE_REL_AMD64_SECREL;
if (r.val == -1)
rel.r_type = IMAGE_REL_AMD64_REL32_1;
else if (r.val == -2)
rel.r_type = IMAGE_REL_AMD64_REL32_2;
else if (r.val == -3)
rel.r_type = IMAGE_REL_AMD64_REL32_3;
else if (r.val == -4)
rel.r_type = IMAGE_REL_AMD64_REL32_4;
else if (r.val == -5)
rel.r_type = IMAGE_REL_AMD64_REL32_5;
/+if (s.Sclass == SCextern ||
s.Sclass == SCcomdef ||
s.Sclass == SCcomdat ||
s.Sclass == SCglobal)
{
rel.r_vaddr = cast(uint)r.offset;
rel.r_symndx = s.Sxtrnnum;
}
else+/
{
rel.r_vaddr = cast(uint)r.offset;
rel.r_symndx = s.Sxtrnnum;
}
}
else if (I32)
{
rel.r_type = (r.rtype == RELrel)
? IMAGE_REL_I386_REL32
: IMAGE_REL_I386_DIR32;
if (s.Stype.Tty & mTYthread)
rel.r_type = IMAGE_REL_I386_SECREL;
/+if (s.Sclass == SCextern ||
s.Sclass == SCcomdef ||
s.Sclass == SCcomdat ||
s.Sclass == SCglobal)
{
rel.r_vaddr = cast(uint)r.offset;
rel.r_symndx = s.Sxtrnnum;
}
else+/
{
rel.r_vaddr = cast(uint)r.offset;
rel.r_symndx = s.Sxtrnnum;
}
}
else
assert(false); // not implemented for I16
}
else
{
if (I64)
{
if (pdata)
rel.r_type = IMAGE_REL_AMD64_ADDR32NB;
else
rel.r_type = IMAGE_REL_AMD64_ADDR64;
if (r.rtype == RELseg)
rel.r_type = IMAGE_REL_AMD64_SECTION;
else if (r.rtype == RELaddr32)
rel.r_type = IMAGE_REL_AMD64_SECREL;
}
else if (I32)
{
if (pdata)
rel.r_type = IMAGE_REL_I386_DIR32NB;
else
rel.r_type = IMAGE_REL_I386_DIR32;
if (r.rtype == RELseg)
rel.r_type = IMAGE_REL_I386_SECTION;
else if (r.rtype == RELaddr32)
rel.r_type = IMAGE_REL_I386_SECREL;
}
else
assert(false); // not implemented for I16
rel.r_vaddr = cast(uint)r.offset;
rel.r_symndx = s.Sxtrnnum;
}
}
else if (r.rtype == RELaddr && pseg.isCode())
{
int32_t *p = null;
p = MsCoffObj_patchAddr(seg, r.offset);
rel.r_vaddr = cast(uint)r.offset;
rel.r_symndx = s ? s.Sxtrnnum : 0;
if (I64)
{
rel.r_type = IMAGE_REL_AMD64_REL32;
//srel.r_value = ScnhdrTab[SegData[r.targseg].SDshtidx].s_vaddr + *p;
//printf("SECTDIFF: x%llx + x%llx = x%x\n", ScnhdrTab[SegData[r.targseg].SDshtidx].s_vaddr, *p, srel.r_value);
}
else
{
rel.r_type = IMAGE_REL_I386_SECREL;
//srel.r_value = ScnhdrTab[SegData[r.targseg].SDshtidx].s_vaddr + *p;
//printf("SECTDIFF: x%x + x%x = x%x\n", ScnhdrTab[SegData[r.targseg].SDshtidx].s_vaddr, *p, srel.r_value);
}
}
else
{
assert(0);
}
/* Some programs do generate a lot of symbols.
* Note that MS-Link can get pretty slow with large numbers of symbols.
*/
//assert(rel.r_symndx <= 20000);
assert(rel.r_type <= 0x14);
fobjbuf.write((&rel)[0 .. 1]);
foffset += (rel).sizeof;
}
}
}
}
/*****************************
* Line number support.
*/
/***************************
* Record file and line number at segment and offset.
* Params:
* srcpos = source file position
* seg = segment it corresponds to
* offset = offset within seg
*/
@trusted
void MsCoffObj_linnum(Srcpos srcpos, int seg, targ_size_t offset)
{
if (srcpos.Slinnum == 0 || !srcpos.Sfilename)
return;
cv8_linnum(srcpos, cast(uint)offset);
}
/*******************************
* Set start address
*/
void MsCoffObj_startaddress(Symbol *s)
{
//dbg_printf("MsCoffObj_startaddress(Symbol *%s)\n",s.Sident.ptr);
//obj.startaddress = s;
}
/*******************************
* Output library name.
*/
@trusted
extern (D)
bool MsCoffObj_includelib(scope const char[] name)
{
int seg = MsCoffObj_seg_drectve();
//dbg_printf("MsCoffObj_includelib(name *%s)\n",name);
SegData[seg].SDbuf.write(" /DEFAULTLIB:\"".ptr, 14);
SegData[seg].SDbuf.write(name.ptr, cast(uint)name.length);
SegData[seg].SDbuf.writeByte('"');
return true;
}
/*******************************
* Output linker directive name.
*/
@trusted
bool MsCoffObj_linkerdirective(scope const(char)* directive)
{
int seg = MsCoffObj_seg_drectve();