-
Notifications
You must be signed in to change notification settings - Fork 17.8k
/
Copy pathpe.go
1566 lines (1385 loc) · 41.2 KB
/
pe.go
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
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ld
import (
"cmd/internal/objabi"
"cmd/internal/sys"
"cmd/link/internal/sym"
"debug/pe"
"encoding/binary"
"fmt"
"sort"
"strconv"
"strings"
)
type IMAGE_IMPORT_DESCRIPTOR struct {
OriginalFirstThunk uint32
TimeDateStamp uint32
ForwarderChain uint32
Name uint32
FirstThunk uint32
}
type IMAGE_EXPORT_DIRECTORY struct {
Characteristics uint32
TimeDateStamp uint32
MajorVersion uint16
MinorVersion uint16
Name uint32
Base uint32
NumberOfFunctions uint32
NumberOfNames uint32
AddressOfFunctions uint32
AddressOfNames uint32
AddressOfNameOrdinals uint32
}
const (
PEBASE = 0x00400000
)
var (
// SectionAlignment must be greater than or equal to FileAlignment.
// The default is the page size for the architecture.
PESECTALIGN int64 = 0x1000
// FileAlignment should be a power of 2 between 512 and 64 K, inclusive.
// The default is 512. If the SectionAlignment is less than
// the architecture's page size, then FileAlignment must match SectionAlignment.
PEFILEALIGN int64 = 2 << 8
)
const (
IMAGE_FILE_MACHINE_I386 = 0x14c
IMAGE_FILE_MACHINE_AMD64 = 0x8664
IMAGE_FILE_MACHINE_ARM = 0x1c0
IMAGE_FILE_MACHINE_ARMNT = 0x1c4
IMAGE_FILE_RELOCS_STRIPPED = 0x0001
IMAGE_FILE_EXECUTABLE_IMAGE = 0x0002
IMAGE_FILE_LINE_NUMS_STRIPPED = 0x0004
IMAGE_FILE_LARGE_ADDRESS_AWARE = 0x0020
IMAGE_FILE_32BIT_MACHINE = 0x0100
IMAGE_FILE_DEBUG_STRIPPED = 0x0200
IMAGE_SCN_CNT_CODE = 0x00000020
IMAGE_SCN_CNT_INITIALIZED_DATA = 0x00000040
IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080
IMAGE_SCN_MEM_EXECUTE = 0x20000000
IMAGE_SCN_MEM_READ = 0x40000000
IMAGE_SCN_MEM_WRITE = 0x80000000
IMAGE_SCN_MEM_DISCARDABLE = 0x2000000
IMAGE_SCN_LNK_NRELOC_OVFL = 0x1000000
IMAGE_SCN_ALIGN_32BYTES = 0x600000
IMAGE_DIRECTORY_ENTRY_EXPORT = 0
IMAGE_DIRECTORY_ENTRY_IMPORT = 1
IMAGE_DIRECTORY_ENTRY_RESOURCE = 2
IMAGE_DIRECTORY_ENTRY_EXCEPTION = 3
IMAGE_DIRECTORY_ENTRY_SECURITY = 4
IMAGE_DIRECTORY_ENTRY_BASERELOC = 5
IMAGE_DIRECTORY_ENTRY_DEBUG = 6
IMAGE_DIRECTORY_ENTRY_COPYRIGHT = 7
IMAGE_DIRECTORY_ENTRY_ARCHITECTURE = 7
IMAGE_DIRECTORY_ENTRY_GLOBALPTR = 8
IMAGE_DIRECTORY_ENTRY_TLS = 9
IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG = 10
IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT = 11
IMAGE_DIRECTORY_ENTRY_IAT = 12
IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT = 13
IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR = 14
IMAGE_SUBSYSTEM_WINDOWS_GUI = 2
IMAGE_SUBSYSTEM_WINDOWS_CUI = 3
IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE = 0x0040
IMAGE_DLLCHARACTERISTICS_NX_COMPAT = 0x0100
)
// TODO(crawshaw): add these constants to debug/pe.
const (
// TODO: the Microsoft doco says IMAGE_SYM_DTYPE_ARRAY is 3 and IMAGE_SYM_DTYPE_FUNCTION is 2
IMAGE_SYM_TYPE_NULL = 0
IMAGE_SYM_TYPE_STRUCT = 8
IMAGE_SYM_DTYPE_FUNCTION = 0x20
IMAGE_SYM_DTYPE_ARRAY = 0x30
IMAGE_SYM_CLASS_EXTERNAL = 2
IMAGE_SYM_CLASS_STATIC = 3
IMAGE_REL_I386_DIR32 = 0x0006
IMAGE_REL_I386_SECREL = 0x000B
IMAGE_REL_I386_REL32 = 0x0014
IMAGE_REL_AMD64_ADDR64 = 0x0001
IMAGE_REL_AMD64_ADDR32 = 0x0002
IMAGE_REL_AMD64_REL32 = 0x0004
IMAGE_REL_AMD64_SECREL = 0x000B
IMAGE_REL_ARM_ABSOLUTE = 0x0000
IMAGE_REL_ARM_ADDR32 = 0x0001
IMAGE_REL_ARM_ADDR32NB = 0x0002
IMAGE_REL_ARM_BRANCH24 = 0x0003
IMAGE_REL_ARM_BRANCH11 = 0x0004
IMAGE_REL_ARM_SECREL = 0x000F
IMAGE_REL_BASED_HIGHLOW = 3
)
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// PE (Portable Executable) file writing
// https://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
// DOS stub that prints out
// "This program cannot be run in DOS mode."
var dosstub = []uint8{
0x4d,
0x5a,
0x90,
0x00,
0x03,
0x00,
0x04,
0x00,
0x00,
0x00,
0x00,
0x00,
0xff,
0xff,
0x00,
0x00,
0x8b,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x40,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x80,
0x00,
0x00,
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,
}
type Imp struct {
s *sym.Symbol
off uint64
next *Imp
argsize int
}
type Dll struct {
name string
nameoff uint64
thunkoff uint64
ms *Imp
next *Dll
}
var (
rsrcsym *sym.Symbol
PESECTHEADR int32
PEFILEHEADR int32
pe64 int
dr *Dll
dexport [1024]*sym.Symbol
nexport int
)
// peStringTable is a COFF string table.
type peStringTable struct {
strings []string
stringsLen int
}
// size resturns size of string table t.
func (t *peStringTable) size() int {
// string table starts with 4-byte length at the beginning
return t.stringsLen + 4
}
// add adds string str to string table t.
func (t *peStringTable) add(str string) int {
off := t.size()
t.strings = append(t.strings, str)
t.stringsLen += len(str) + 1 // each string will have 0 appended to it
return off
}
// write writes string table t into the output file.
func (t *peStringTable) write(out *OutBuf) {
out.Write32(uint32(t.size()))
for _, s := range t.strings {
out.WriteString(s)
out.Write8(0)
}
}
// peSection represents section from COFF section table.
type peSection struct {
name string
shortName string
index int // one-based index into the Section Table
virtualSize uint32
virtualAddress uint32
sizeOfRawData uint32
pointerToRawData uint32
pointerToRelocations uint32
numberOfRelocations uint16
characteristics uint32
}
// checkOffset verifies COFF section sect offset in the file.
func (sect *peSection) checkOffset(off int64) {
if off != int64(sect.pointerToRawData) {
Errorf(nil, "%s.PointerToRawData = %#x, want %#x", sect.name, uint64(int64(sect.pointerToRawData)), uint64(off))
errorexit()
}
}
// checkSegment verifies COFF section sect matches address
// and file offset provided in segment seg.
func (sect *peSection) checkSegment(seg *sym.Segment) {
if seg.Vaddr-PEBASE != uint64(sect.virtualAddress) {
Errorf(nil, "%s.VirtualAddress = %#x, want %#x", sect.name, uint64(int64(sect.virtualAddress)), uint64(int64(seg.Vaddr-PEBASE)))
errorexit()
}
if seg.Fileoff != uint64(sect.pointerToRawData) {
Errorf(nil, "%s.PointerToRawData = %#x, want %#x", sect.name, uint64(int64(sect.pointerToRawData)), uint64(int64(seg.Fileoff)))
errorexit()
}
}
// pad adds zeros to the section sect. It writes as many bytes
// as necessary to make section sect.SizeOfRawData bytes long.
// It assumes that n bytes are already written to the file.
func (sect *peSection) pad(out *OutBuf, n uint32) {
out.WriteStringN("", int(sect.sizeOfRawData-n))
}
// write writes COFF section sect into the output file.
func (sect *peSection) write(out *OutBuf, linkmode LinkMode) error {
h := pe.SectionHeader32{
VirtualSize: sect.virtualSize,
SizeOfRawData: sect.sizeOfRawData,
PointerToRawData: sect.pointerToRawData,
PointerToRelocations: sect.pointerToRelocations,
NumberOfRelocations: sect.numberOfRelocations,
Characteristics: sect.characteristics,
}
if linkmode != LinkExternal {
h.VirtualAddress = sect.virtualAddress
}
copy(h.Name[:], sect.shortName)
return binary.Write(out, binary.LittleEndian, h)
}
// emitRelocations emits the relocation entries for the sect.
// The actual relocations are emitted by relocfn.
// This updates the corresponding PE section table entry
// with the relocation offset and count.
func (sect *peSection) emitRelocations(out *OutBuf, relocfn func() int) {
sect.pointerToRelocations = uint32(out.Offset())
// first entry: extended relocs
out.Write32(0) // placeholder for number of relocation + 1
out.Write32(0)
out.Write16(0)
n := relocfn() + 1
cpos := out.Offset()
out.SeekSet(int64(sect.pointerToRelocations))
out.Write32(uint32(n))
out.SeekSet(cpos)
if n > 0x10000 {
n = 0x10000
sect.characteristics |= IMAGE_SCN_LNK_NRELOC_OVFL
} else {
sect.pointerToRelocations += 10 // skip the extend reloc entry
}
sect.numberOfRelocations = uint16(n - 1)
}
// peFile is used to build COFF file.
type peFile struct {
sections []*peSection
stringTable peStringTable
textSect *peSection
rdataSect *peSection
dataSect *peSection
bssSect *peSection
ctorsSect *peSection
nextSectOffset uint32
nextFileOffset uint32
symtabOffset int64 // offset to the start of symbol table
symbolCount int // number of symbol table records written
dataDirectory [16]pe.DataDirectory
}
// addSection adds section to the COFF file f.
func (f *peFile) addSection(name string, sectsize int, filesize int) *peSection {
sect := &peSection{
name: name,
shortName: name,
index: len(f.sections) + 1,
virtualSize: uint32(sectsize),
virtualAddress: f.nextSectOffset,
pointerToRawData: f.nextFileOffset,
}
f.nextSectOffset = uint32(Rnd(int64(f.nextSectOffset)+int64(sectsize), PESECTALIGN))
if filesize > 0 {
sect.sizeOfRawData = uint32(Rnd(int64(filesize), PEFILEALIGN))
f.nextFileOffset += sect.sizeOfRawData
}
f.sections = append(f.sections, sect)
return sect
}
// addDWARFSection adds DWARF section to the COFF file f.
// This function is similar to addSection, but DWARF section names are
// longer than 8 characters, so they need to be stored in the string table.
func (f *peFile) addDWARFSection(name string, size int) *peSection {
if size == 0 {
Exitf("DWARF section %q is empty", name)
}
// DWARF section names are longer than 8 characters.
// PE format requires such names to be stored in string table,
// and section names replaced with slash (/) followed by
// correspondent string table index.
// see http://www.microsoft.com/whdc/system/platform/firmware/PECOFFdwn.mspx
// for details
off := f.stringTable.add(name)
h := f.addSection(name, size, size)
h.shortName = fmt.Sprintf("/%d", off)
h.characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_DISCARDABLE
return h
}
// addDWARF adds DWARF information to the COFF file f.
func (f *peFile) addDWARF() {
if *FlagS { // disable symbol table
return
}
if *FlagW { // disable dwarf
return
}
for _, sect := range Segdwarf.Sections {
h := f.addDWARFSection(sect.Name, int(sect.Length))
fileoff := sect.Vaddr - Segdwarf.Vaddr + Segdwarf.Fileoff
if uint64(h.pointerToRawData) != fileoff {
Exitf("%s.PointerToRawData = %#x, want %#x", sect.Name, h.pointerToRawData, fileoff)
}
}
}
// addInitArray adds .ctors COFF section to the file f.
func (f *peFile) addInitArray(ctxt *Link) *peSection {
// The size below was determined by the specification for array relocations,
// and by observing what GCC writes here. If the initarray section grows to
// contain more than one constructor entry, the size will need to be 8 * constructor_count.
// However, the entire Go runtime is initialized from just one function, so it is unlikely
// that this will need to grow in the future.
var size int
switch objabi.GOARCH {
default:
Exitf("peFile.addInitArray: unsupported GOARCH=%q\n", objabi.GOARCH)
case "386":
size = 4
case "amd64":
size = 8
case "arm":
size = 4
}
sect := f.addSection(".ctors", size, size)
sect.characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ
sect.sizeOfRawData = uint32(size)
ctxt.Out.SeekSet(int64(sect.pointerToRawData))
sect.checkOffset(ctxt.Out.Offset())
init_entry := ctxt.Syms.Lookup(*flagEntrySymbol, 0)
addr := uint64(init_entry.Value) - init_entry.Sect.Vaddr
switch objabi.GOARCH {
case "386", "arm":
ctxt.Out.Write32(uint32(addr))
case "amd64":
ctxt.Out.Write64(addr)
}
return sect
}
// emitRelocations emits relocation entries for go.o in external linking.
func (f *peFile) emitRelocations(ctxt *Link) {
for ctxt.Out.Offset()&7 != 0 {
ctxt.Out.Write8(0)
}
// relocsect relocates symbols from first in section sect, and returns
// the total number of relocations emitted.
relocsect := func(sect *sym.Section, syms []*sym.Symbol, base uint64) int {
// If main section has no bits, nothing to relocate.
if sect.Vaddr >= sect.Seg.Vaddr+sect.Seg.Filelen {
return 0
}
relocs := 0
sect.Reloff = uint64(ctxt.Out.Offset())
for i, s := range syms {
if !s.Attr.Reachable() {
continue
}
if uint64(s.Value) >= sect.Vaddr {
syms = syms[i:]
break
}
}
eaddr := int32(sect.Vaddr + sect.Length)
for _, sym := range syms {
if !sym.Attr.Reachable() {
continue
}
if sym.Value >= int64(eaddr) {
break
}
for ri := range sym.R {
r := &sym.R[ri]
if r.Done {
continue
}
if r.Xsym == nil {
Errorf(sym, "missing xsym in relocation")
continue
}
if r.Xsym.Dynid < 0 {
Errorf(sym, "reloc %d to non-coff symbol %s (outer=%s) %d", r.Type, r.Sym.Name, r.Xsym.Name, r.Sym.Type)
}
if !thearch.PEreloc1(ctxt.Arch, ctxt.Out, sym, r, int64(uint64(sym.Value+int64(r.Off))-base)) {
Errorf(sym, "unsupported obj reloc %d/%d to %s", r.Type, r.Siz, r.Sym.Name)
}
relocs++
}
}
sect.Rellen = uint64(ctxt.Out.Offset()) - sect.Reloff
return relocs
}
sects := []struct {
peSect *peSection
seg *sym.Segment
syms []*sym.Symbol
}{
{f.textSect, &Segtext, ctxt.Textp},
{f.rdataSect, &Segrodata, datap},
{f.dataSect, &Segdata, datap},
}
for _, s := range sects {
s.peSect.emitRelocations(ctxt.Out, func() int {
var n int
for _, sect := range s.seg.Sections {
n += relocsect(sect, s.syms, s.seg.Vaddr)
}
return n
})
}
dwarfLoop:
for _, sect := range Segdwarf.Sections {
for _, pesect := range f.sections {
if sect.Name == pesect.name {
pesect.emitRelocations(ctxt.Out, func() int {
return relocsect(sect, dwarfp, sect.Vaddr)
})
continue dwarfLoop
}
}
Errorf(nil, "emitRelocations: could not find %q section", sect.Name)
}
f.ctorsSect.emitRelocations(ctxt.Out, func() int {
dottext := ctxt.Syms.Lookup(".text", 0)
ctxt.Out.Write32(0)
ctxt.Out.Write32(uint32(dottext.Dynid))
switch objabi.GOARCH {
default:
Errorf(dottext, "unknown architecture for PE: %q\n", objabi.GOARCH)
case "386":
ctxt.Out.Write16(IMAGE_REL_I386_DIR32)
case "amd64":
ctxt.Out.Write16(IMAGE_REL_AMD64_ADDR64)
case "arm":
ctxt.Out.Write16(IMAGE_REL_ARM_ADDR32)
}
return 1
})
}
// writeSymbol appends symbol s to file f symbol table.
// It also sets s.Dynid to written symbol number.
func (f *peFile) writeSymbol(out *OutBuf, s *sym.Symbol, value int64, sectidx int, typ uint16, class uint8) {
if len(s.Name) > 8 {
out.Write32(0)
out.Write32(uint32(f.stringTable.add(s.Name)))
} else {
out.WriteStringN(s.Name, 8)
}
out.Write32(uint32(value))
out.Write16(uint16(sectidx))
out.Write16(typ)
out.Write8(class)
out.Write8(0) // no aux entries
s.Dynid = int32(f.symbolCount)
f.symbolCount++
}
// mapToPESection searches peFile f for s symbol's location.
// It returns PE section index, and offset within that section.
func (f *peFile) mapToPESection(s *sym.Symbol, linkmode LinkMode) (pesectidx int, offset int64, err error) {
if s.Sect == nil {
return 0, 0, fmt.Errorf("could not map %s symbol with no section", s.Name)
}
if s.Sect.Seg == &Segtext {
return f.textSect.index, int64(uint64(s.Value) - Segtext.Vaddr), nil
}
if s.Sect.Seg == &Segrodata {
return f.rdataSect.index, int64(uint64(s.Value) - Segrodata.Vaddr), nil
}
if s.Sect.Seg != &Segdata {
return 0, 0, fmt.Errorf("could not map %s symbol with non .text or .rdata or .data section", s.Name)
}
v := uint64(s.Value) - Segdata.Vaddr
if linkmode != LinkExternal {
return f.dataSect.index, int64(v), nil
}
if s.Type == sym.SDATA {
return f.dataSect.index, int64(v), nil
}
// Note: although address of runtime.edata (type sym.SDATA) is at the start of .bss section
// it still belongs to the .data section, not the .bss section.
if v < Segdata.Filelen {
return f.dataSect.index, int64(v), nil
}
return f.bssSect.index, int64(v - Segdata.Filelen), nil
}
// writeSymbols writes all COFF symbol table records.
func (f *peFile) writeSymbols(ctxt *Link) {
put := func(ctxt *Link, s *sym.Symbol, name string, type_ SymbolType, addr int64, gotype *sym.Symbol) {
if s == nil {
return
}
if s.Sect == nil && type_ != UndefinedSym {
return
}
switch type_ {
default:
return
case DataSym, BSSSym, TextSym, UndefinedSym:
}
// Only windows/386 requires underscore prefix on external symbols.
if ctxt.Arch.Family == sys.I386 &&
ctxt.LinkMode == LinkExternal &&
(s.Type == sym.SHOSTOBJ || s.Attr.CgoExport()) {
s.Name = "_" + s.Name
}
var typ uint16
if ctxt.LinkMode == LinkExternal {
typ = IMAGE_SYM_TYPE_NULL
} else {
// TODO: fix IMAGE_SYM_DTYPE_ARRAY value and use following expression, instead of 0x0308
typ = IMAGE_SYM_DTYPE_ARRAY<<8 + IMAGE_SYM_TYPE_STRUCT
typ = 0x0308 // "array of structs"
}
sect, value, err := f.mapToPESection(s, ctxt.LinkMode)
if err != nil {
if type_ == UndefinedSym {
typ = IMAGE_SYM_DTYPE_FUNCTION
} else {
Errorf(s, "addpesym: %v", err)
}
}
class := IMAGE_SYM_CLASS_EXTERNAL
if s.IsFileLocal() || s.Attr.VisibilityHidden() || s.Attr.Local() {
class = IMAGE_SYM_CLASS_STATIC
}
f.writeSymbol(ctxt.Out, s, value, sect, typ, uint8(class))
}
if ctxt.LinkMode == LinkExternal {
// Include section symbols as external, because
// .ctors and .debug_* section relocations refer to it.
for _, pesect := range f.sections {
sym := ctxt.Syms.Lookup(pesect.name, 0)
f.writeSymbol(ctxt.Out, sym, 0, pesect.index, IMAGE_SYM_TYPE_NULL, IMAGE_SYM_CLASS_STATIC)
}
}
genasmsym(ctxt, put)
}
// writeSymbolTableAndStringTable writes out symbol and string tables for peFile f.
func (f *peFile) writeSymbolTableAndStringTable(ctxt *Link) {
f.symtabOffset = ctxt.Out.Offset()
// write COFF symbol table
if !*FlagS || ctxt.LinkMode == LinkExternal {
f.writeSymbols(ctxt)
}
// update COFF file header and section table
size := f.stringTable.size() + 18*f.symbolCount
var h *peSection
if ctxt.LinkMode != LinkExternal {
// We do not really need .symtab for go.o, and if we have one, ld
// will also include it in the exe, and that will confuse windows.
h = f.addSection(".symtab", size, size)
h.characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_DISCARDABLE
h.checkOffset(f.symtabOffset)
}
// write COFF string table
f.stringTable.write(ctxt.Out)
if ctxt.LinkMode != LinkExternal {
h.pad(ctxt.Out, uint32(size))
}
}
// writeFileHeader writes COFF file header for peFile f.
func (f *peFile) writeFileHeader(arch *sys.Arch, out *OutBuf, linkmode LinkMode) {
var fh pe.FileHeader
switch arch.Family {
default:
Exitf("unknown PE architecture: %v", arch.Family)
case sys.AMD64:
fh.Machine = IMAGE_FILE_MACHINE_AMD64
case sys.I386:
fh.Machine = IMAGE_FILE_MACHINE_I386
case sys.ARM:
fh.Machine = IMAGE_FILE_MACHINE_ARMNT
}
fh.NumberOfSections = uint16(len(f.sections))
// Being able to produce identical output for identical input is
// much more beneficial than having build timestamp in the header.
fh.TimeDateStamp = 0
if linkmode == LinkExternal {
fh.Characteristics = IMAGE_FILE_LINE_NUMS_STRIPPED
} else {
switch arch.Family {
default:
Exitf("write COFF(ext): unknown PE architecture: %v", arch.Family)
case sys.AMD64, sys.I386:
fh.Characteristics = IMAGE_FILE_RELOCS_STRIPPED | IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DEBUG_STRIPPED
case sys.ARM:
fh.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DEBUG_STRIPPED
}
}
if pe64 != 0 {
var oh64 pe.OptionalHeader64
fh.SizeOfOptionalHeader = uint16(binary.Size(&oh64))
fh.Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE
} else {
var oh pe.OptionalHeader32
fh.SizeOfOptionalHeader = uint16(binary.Size(&oh))
fh.Characteristics |= IMAGE_FILE_32BIT_MACHINE
}
fh.PointerToSymbolTable = uint32(f.symtabOffset)
fh.NumberOfSymbols = uint32(f.symbolCount)
binary.Write(out, binary.LittleEndian, &fh)
}
// writeOptionalHeader writes COFF optional header for peFile f.
func (f *peFile) writeOptionalHeader(ctxt *Link) {
var oh pe.OptionalHeader32
var oh64 pe.OptionalHeader64
if pe64 != 0 {
oh64.Magic = 0x20b // PE32+
} else {
oh.Magic = 0x10b // PE32
oh.BaseOfData = f.dataSect.virtualAddress
}
// Fill out both oh64 and oh. We only use one. Oh well.
oh64.MajorLinkerVersion = 3
oh.MajorLinkerVersion = 3
oh64.MinorLinkerVersion = 0
oh.MinorLinkerVersion = 0
oh64.SizeOfCode = f.textSect.sizeOfRawData
oh.SizeOfCode = f.textSect.sizeOfRawData
oh64.SizeOfInitializedData = f.dataSect.sizeOfRawData
oh.SizeOfInitializedData = f.dataSect.sizeOfRawData
oh64.SizeOfUninitializedData = 0
oh.SizeOfUninitializedData = 0
if ctxt.LinkMode != LinkExternal {
oh64.AddressOfEntryPoint = uint32(Entryvalue(ctxt) - PEBASE)
oh.AddressOfEntryPoint = uint32(Entryvalue(ctxt) - PEBASE)
}
oh64.BaseOfCode = f.textSect.virtualAddress
oh.BaseOfCode = f.textSect.virtualAddress
oh64.ImageBase = PEBASE
oh.ImageBase = PEBASE
oh64.SectionAlignment = uint32(PESECTALIGN)
oh.SectionAlignment = uint32(PESECTALIGN)
oh64.FileAlignment = uint32(PEFILEALIGN)
oh.FileAlignment = uint32(PEFILEALIGN)
oh64.MajorOperatingSystemVersion = 4
oh.MajorOperatingSystemVersion = 4
oh64.MinorOperatingSystemVersion = 0
oh.MinorOperatingSystemVersion = 0
oh64.MajorImageVersion = 1
oh.MajorImageVersion = 1
oh64.MinorImageVersion = 0
oh.MinorImageVersion = 0
oh64.MajorSubsystemVersion = 4
oh.MajorSubsystemVersion = 4
oh64.MinorSubsystemVersion = 0
oh.MinorSubsystemVersion = 0
oh64.SizeOfImage = f.nextSectOffset
oh.SizeOfImage = f.nextSectOffset
oh64.SizeOfHeaders = uint32(PEFILEHEADR)
oh.SizeOfHeaders = uint32(PEFILEHEADR)
if windowsgui {
oh64.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_GUI
oh.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_GUI
} else {
oh64.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI
oh.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI
}
switch ctxt.Arch.Family {
case sys.ARM:
oh64.DllCharacteristics = IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE | IMAGE_DLLCHARACTERISTICS_NX_COMPAT
oh.DllCharacteristics = IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE | IMAGE_DLLCHARACTERISTICS_NX_COMPAT
}
// Disable stack growth as we don't want Windows to
// fiddle with the thread stack limits, which we set
// ourselves to circumvent the stack checks in the
// Windows exception dispatcher.
// Commit size must be strictly less than reserve
// size otherwise reserve will be rounded up to a
// larger size, as verified with VMMap.
// On 64-bit, we always reserve 2MB stacks. "Pure" Go code is
// okay with much smaller stacks, but the syscall package
// makes it easy to call into arbitrary C code without cgo,
// and system calls even in "pure" Go code are actually C
// calls that may need more stack than we think.
//
// The default stack reserve size directly affects only the main
// thread, ctrlhandler thread, and profileloop thread. For
// these, it must be greater than the stack size assumed by
// externalthreadhandler.
//
// For other threads, the runtime explicitly asks the kernel
// to use the default stack size so that all stacks are
// consistent.
//
// At thread start, in minit, the runtime queries the OS for
// the actual stack bounds so that the stack size doesn't need
// to be hard-coded into the runtime.
oh64.SizeOfStackReserve = 0x00200000
if !iscgo {
oh64.SizeOfStackCommit = 0x00001000
} else {
// TODO(brainman): Maybe remove optional header writing altogether for cgo.
// For cgo it is the external linker that is building final executable.
// And it probably does not use any information stored in optional header.
oh64.SizeOfStackCommit = 0x00200000 - 0x2000 // account for 2 guard pages
}
oh.SizeOfStackReserve = 0x00100000
if !iscgo {
oh.SizeOfStackCommit = 0x00001000
} else {
oh.SizeOfStackCommit = 0x00100000 - 0x2000 // account for 2 guard pages
}
oh64.SizeOfHeapReserve = 0x00100000
oh.SizeOfHeapReserve = 0x00100000
oh64.SizeOfHeapCommit = 0x00001000
oh.SizeOfHeapCommit = 0x00001000
oh64.NumberOfRvaAndSizes = 16
oh.NumberOfRvaAndSizes = 16
if pe64 != 0 {
oh64.DataDirectory = f.dataDirectory
} else {
oh.DataDirectory = f.dataDirectory
}
if pe64 != 0 {
binary.Write(ctxt.Out, binary.LittleEndian, &oh64)
} else {
binary.Write(ctxt.Out, binary.LittleEndian, &oh)
}
}
var pefile peFile
func Peinit(ctxt *Link) {
var l int
switch ctxt.Arch.Family {
// 64-bit architectures
case sys.AMD64:
pe64 = 1
var oh64 pe.OptionalHeader64
l = binary.Size(&oh64)
// 32-bit architectures
default:
var oh pe.OptionalHeader32
l = binary.Size(&oh)
}
if ctxt.LinkMode == LinkExternal {
// .rdata section will contain "masks" and "shifts" symbols, and they
// need to be aligned to 16-bytes. So make all sections aligned
// to 32-byte and mark them all IMAGE_SCN_ALIGN_32BYTES so external
// linker will honour that requirement.
PESECTALIGN = 32
PEFILEALIGN = 0
}
var sh [16]pe.SectionHeader32
var fh pe.FileHeader
PEFILEHEADR = int32(Rnd(int64(len(dosstub)+binary.Size(&fh)+l+binary.Size(&sh)), PEFILEALIGN))
if ctxt.LinkMode != LinkExternal {
PESECTHEADR = int32(Rnd(int64(PEFILEHEADR), PESECTALIGN))
} else {
PESECTHEADR = 0
}
pefile.nextSectOffset = uint32(PESECTHEADR)
pefile.nextFileOffset = uint32(PEFILEHEADR)
if ctxt.LinkMode == LinkInternal {
// some mingw libs depend on this symbol, for example, FindPESectionByName
ctxt.xdefine("__image_base__", sym.SDATA, PEBASE)
ctxt.xdefine("_image_base__", sym.SDATA, PEBASE)
}
HEADR = PEFILEHEADR
if *FlagTextAddr == -1 {
*FlagTextAddr = PEBASE + int64(PESECTHEADR)
}
if *FlagRound == -1 {
*FlagRound = int(PESECTALIGN)
}
}
func pewrite(ctxt *Link) {
ctxt.Out.SeekSet(0)
if ctxt.LinkMode != LinkExternal {
ctxt.Out.Write(dosstub)
ctxt.Out.WriteStringN("PE", 4)
}
pefile.writeFileHeader(ctxt.Arch, ctxt.Out, ctxt.LinkMode)
pefile.writeOptionalHeader(ctxt)
for _, sect := range pefile.sections {
sect.write(ctxt.Out, ctxt.LinkMode)
}
}
func strput(out *OutBuf, s string) {
out.WriteString(s)