/
pe.go
1299 lines (1124 loc) · 30.6 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/obj"
"cmd/internal/sys"
"encoding/binary"
"fmt"
"os"
"sort"
"strconv"
"strings"
)
type IMAGE_FILE_HEADER struct {
Machine uint16
NumberOfSections uint16
TimeDateStamp uint32
PointerToSymbolTable uint32
NumberOfSymbols uint32
SizeOfOptionalHeader uint16
Characteristics uint16
}
type IMAGE_DATA_DIRECTORY struct {
VirtualAddress uint32
Size uint32
}
type IMAGE_OPTIONAL_HEADER struct {
Magic uint16
MajorLinkerVersion uint8
MinorLinkerVersion uint8
SizeOfCode uint32
SizeOfInitializedData uint32
SizeOfUninitializedData uint32
AddressOfEntryPoint uint32
BaseOfCode uint32
BaseOfData uint32
ImageBase uint32
SectionAlignment uint32
FileAlignment uint32
MajorOperatingSystemVersion uint16
MinorOperatingSystemVersion uint16
MajorImageVersion uint16
MinorImageVersion uint16
MajorSubsystemVersion uint16
MinorSubsystemVersion uint16
Win32VersionValue uint32
SizeOfImage uint32
SizeOfHeaders uint32
CheckSum uint32
Subsystem uint16
DllCharacteristics uint16
SizeOfStackReserve uint32
SizeOfStackCommit uint32
SizeOfHeapReserve uint32
SizeOfHeapCommit uint32
LoaderFlags uint32
NumberOfRvaAndSizes uint32
DataDirectory [16]IMAGE_DATA_DIRECTORY
}
type IMAGE_SECTION_HEADER struct {
Name [8]uint8
VirtualSize uint32
VirtualAddress uint32
SizeOfRawData uint32
PointerToRawData uint32
PointerToRelocations uint32
PointerToLineNumbers uint32
NumberOfRelocations uint16
NumberOfLineNumbers uint16
Characteristics uint32
}
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
// SectionAlignment must be greater than or equal to FileAlignment.
// The default is the page size for the architecture.
PESECTALIGN = 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 = 2 << 8
)
const (
IMAGE_FILE_MACHINE_I386 = 0x14c
IMAGE_FILE_MACHINE_AMD64 = 0x8664
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
)
// X64
type PE64_IMAGE_OPTIONAL_HEADER struct {
Magic uint16
MajorLinkerVersion uint8
MinorLinkerVersion uint8
SizeOfCode uint32
SizeOfInitializedData uint32
SizeOfUninitializedData uint32
AddressOfEntryPoint uint32
BaseOfCode uint32
ImageBase uint64
SectionAlignment uint32
FileAlignment uint32
MajorOperatingSystemVersion uint16
MinorOperatingSystemVersion uint16
MajorImageVersion uint16
MinorImageVersion uint16
MajorSubsystemVersion uint16
MinorSubsystemVersion uint16
Win32VersionValue uint32
SizeOfImage uint32
SizeOfHeaders uint32
CheckSum uint32
Subsystem uint16
DllCharacteristics uint16
SizeOfStackReserve uint64
SizeOfStackCommit uint64
SizeOfHeapReserve uint64
SizeOfHeapCommit uint64
LoaderFlags uint32
NumberOfRvaAndSizes uint32
DataDirectory [16]IMAGE_DATA_DIRECTORY
}
// 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
// http://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,
}
var rsrcsym *LSym
var strtbl []byte
var PESECTHEADR int32
var PEFILEHEADR int32
var pe64 int
var pensect int
var nextsectoff int
var nextfileoff int
var textsect int
var datasect int
var bsssect int
var fh IMAGE_FILE_HEADER
var oh IMAGE_OPTIONAL_HEADER
var oh64 PE64_IMAGE_OPTIONAL_HEADER
var sh [16]IMAGE_SECTION_HEADER
var dd []IMAGE_DATA_DIRECTORY
type Imp struct {
s *LSym
off uint64
next *Imp
argsize int
}
type Dll struct {
name string
nameoff uint64
thunkoff uint64
ms *Imp
next *Dll
}
var dr *Dll
var dexport [1024]*LSym
var nexport int
func addpesection(name string, sectsize int, filesize int) *IMAGE_SECTION_HEADER {
if pensect == 16 {
Diag("too many sections")
errorexit()
}
h := &sh[pensect]
pensect++
copy(h.Name[:], name)
h.VirtualSize = uint32(sectsize)
h.VirtualAddress = uint32(nextsectoff)
nextsectoff = int(Rnd(int64(nextsectoff)+int64(sectsize), PESECTALIGN))
h.PointerToRawData = uint32(nextfileoff)
if filesize > 0 {
h.SizeOfRawData = uint32(Rnd(int64(filesize), PEFILEALIGN))
nextfileoff += int(h.SizeOfRawData)
}
return h
}
func chksectoff(h *IMAGE_SECTION_HEADER, off int64) {
if off != int64(h.PointerToRawData) {
Diag("%s.PointerToRawData = %#x, want %#x", cstring(h.Name[:]), uint64(int64(h.PointerToRawData)), uint64(off))
errorexit()
}
}
func chksectseg(h *IMAGE_SECTION_HEADER, s *Segment) {
if s.Vaddr-PEBASE != uint64(h.VirtualAddress) {
Diag("%s.VirtualAddress = %#x, want %#x", cstring(h.Name[:]), uint64(int64(h.VirtualAddress)), uint64(int64(s.Vaddr-PEBASE)))
errorexit()
}
if s.Fileoff != uint64(h.PointerToRawData) {
Diag("%s.PointerToRawData = %#x, want %#x", cstring(h.Name[:]), uint64(int64(h.PointerToRawData)), uint64(int64(s.Fileoff)))
errorexit()
}
}
func Peinit() {
var l int
switch SysArch.Family {
// 64-bit architectures
case sys.AMD64:
pe64 = 1
l = binary.Size(&oh64)
dd = oh64.DataDirectory[:]
// 32-bit architectures
default:
l = binary.Size(&oh)
dd = oh.DataDirectory[:]
}
PEFILEHEADR = int32(Rnd(int64(len(dosstub)+binary.Size(&fh)+l+binary.Size(&sh)), PEFILEALIGN))
PESECTHEADR = int32(Rnd(int64(PEFILEHEADR), PESECTALIGN))
nextsectoff = int(PESECTHEADR)
nextfileoff = int(PEFILEHEADR)
// some mingw libs depend on this symbol, for example, FindPESectionByName
xdefine("__image_base__", obj.SDATA, PEBASE)
xdefine("_image_base__", obj.SDATA, PEBASE)
}
func pewrite() {
Cseek(0)
if Linkmode != LinkExternal {
Cwrite(dosstub)
strnput("PE", 4)
}
binary.Write(&coutbuf, binary.LittleEndian, &fh)
if pe64 != 0 {
binary.Write(&coutbuf, binary.LittleEndian, &oh64)
} else {
binary.Write(&coutbuf, binary.LittleEndian, &oh)
}
binary.Write(&coutbuf, binary.LittleEndian, sh[:pensect])
}
func strput(s string) {
coutbuf.WriteString(s)
Cput(0)
// string must be padded to even size
if (len(s)+1)%2 != 0 {
Cput(0)
}
}
func initdynimport() *Dll {
var d *Dll
dr = nil
var m *Imp
for _, s := range Ctxt.Allsym {
if !s.Attr.Reachable() || s.Type != obj.SDYNIMPORT {
continue
}
for d = dr; d != nil; d = d.next {
if d.name == s.Dynimplib {
m = new(Imp)
break
}
}
if d == nil {
d = new(Dll)
d.name = s.Dynimplib
d.next = dr
dr = d
m = new(Imp)
}
// Because external link requires properly stdcall decorated name,
// all external symbols in runtime use %n to denote that the number
// of uinptrs this function consumes. Store the argsize and discard
// the %n suffix if any.
m.argsize = -1
if i := strings.IndexByte(s.Extname, '%'); i >= 0 {
var err error
m.argsize, err = strconv.Atoi(s.Extname[i+1:])
if err != nil {
Diag("failed to parse stdcall decoration: %v", err)
}
m.argsize *= SysArch.PtrSize
s.Extname = s.Extname[:i]
}
m.s = s
m.next = d.ms
d.ms = m
}
if Linkmode == LinkExternal {
// Add real symbol name
for d := dr; d != nil; d = d.next {
for m = d.ms; m != nil; m = m.next {
m.s.Type = obj.SDATA
Symgrow(Ctxt, m.s, int64(SysArch.PtrSize))
dynName := m.s.Extname
// only windows/386 requires stdcall decoration
if SysArch.Family == sys.I386 && m.argsize >= 0 {
dynName += fmt.Sprintf("@%d", m.argsize)
}
dynSym := Linklookup(Ctxt, dynName, 0)
dynSym.Attr |= AttrReachable
dynSym.Type = obj.SHOSTOBJ
r := Addrel(m.s)
r.Sym = dynSym
r.Off = 0
r.Siz = uint8(SysArch.PtrSize)
r.Type = obj.R_ADDR
}
}
} else {
dynamic := Linklookup(Ctxt, ".windynamic", 0)
dynamic.Attr |= AttrReachable
dynamic.Type = obj.SWINDOWS
for d := dr; d != nil; d = d.next {
for m = d.ms; m != nil; m = m.next {
m.s.Type = obj.SWINDOWS | obj.SSUB
m.s.Sub = dynamic.Sub
dynamic.Sub = m.s
m.s.Value = dynamic.Size
dynamic.Size += int64(SysArch.PtrSize)
}
dynamic.Size += int64(SysArch.PtrSize)
}
}
return dr
}
// peimporteddlls returns the gcc command line argument to link all imported
// DLLs.
func peimporteddlls() []string {
var dlls []string
for d := dr; d != nil; d = d.next {
dlls = append(dlls, "-l"+strings.TrimSuffix(d.name, ".dll"))
}
return dlls
}
func addimports(datsect *IMAGE_SECTION_HEADER) {
startoff := Cpos()
dynamic := Linklookup(Ctxt, ".windynamic", 0)
// skip import descriptor table (will write it later)
n := uint64(0)
for d := dr; d != nil; d = d.next {
n++
}
Cseek(startoff + int64(binary.Size(&IMAGE_IMPORT_DESCRIPTOR{}))*int64(n+1))
// write dll names
for d := dr; d != nil; d = d.next {
d.nameoff = uint64(Cpos()) - uint64(startoff)
strput(d.name)
}
// write function names
var m *Imp
for d := dr; d != nil; d = d.next {
for m = d.ms; m != nil; m = m.next {
m.off = uint64(nextsectoff) + uint64(Cpos()) - uint64(startoff)
Wputl(0) // hint
strput(m.s.Extname)
}
}
// write OriginalFirstThunks
oftbase := uint64(Cpos()) - uint64(startoff)
n = uint64(Cpos())
for d := dr; d != nil; d = d.next {
d.thunkoff = uint64(Cpos()) - n
for m = d.ms; m != nil; m = m.next {
if pe64 != 0 {
Vputl(m.off)
} else {
Lputl(uint32(m.off))
}
}
if pe64 != 0 {
Vputl(0)
} else {
Lputl(0)
}
}
// add pe section and pad it at the end
n = uint64(Cpos()) - uint64(startoff)
isect := addpesection(".idata", int(n), int(n))
isect.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE
chksectoff(isect, startoff)
strnput("", int(uint64(isect.SizeOfRawData)-n))
endoff := Cpos()
// write FirstThunks (allocated in .data section)
ftbase := uint64(dynamic.Value) - uint64(datsect.VirtualAddress) - PEBASE
Cseek(int64(uint64(datsect.PointerToRawData) + ftbase))
for d := dr; d != nil; d = d.next {
for m = d.ms; m != nil; m = m.next {
if pe64 != 0 {
Vputl(m.off)
} else {
Lputl(uint32(m.off))
}
}
if pe64 != 0 {
Vputl(0)
} else {
Lputl(0)
}
}
// finally write import descriptor table
Cseek(startoff)
for d := dr; d != nil; d = d.next {
Lputl(uint32(uint64(isect.VirtualAddress) + oftbase + d.thunkoff))
Lputl(0)
Lputl(0)
Lputl(uint32(uint64(isect.VirtualAddress) + d.nameoff))
Lputl(uint32(uint64(datsect.VirtualAddress) + ftbase + d.thunkoff))
}
Lputl(0) //end
Lputl(0)
Lputl(0)
Lputl(0)
Lputl(0)
// update data directory
dd[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress = isect.VirtualAddress
dd[IMAGE_DIRECTORY_ENTRY_IMPORT].Size = isect.VirtualSize
dd[IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress = uint32(dynamic.Value - PEBASE)
dd[IMAGE_DIRECTORY_ENTRY_IAT].Size = uint32(dynamic.Size)
Cseek(endoff)
}
type byExtname []*LSym
func (s byExtname) Len() int { return len(s) }
func (s byExtname) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s byExtname) Less(i, j int) bool { return s[i].Extname < s[j].Extname }
func initdynexport() {
nexport = 0
for _, s := range Ctxt.Allsym {
if !s.Attr.Reachable() || !s.Attr.CgoExportDynamic() {
continue
}
if nexport+1 > len(dexport) {
Diag("pe dynexport table is full")
errorexit()
}
dexport[nexport] = s
nexport++
}
sort.Sort(byExtname(dexport[:nexport]))
}
func addexports() {
var e IMAGE_EXPORT_DIRECTORY
size := binary.Size(&e) + 10*nexport + len(outfile) + 1
for i := 0; i < nexport; i++ {
size += len(dexport[i].Extname) + 1
}
if nexport == 0 {
return
}
sect := addpesection(".edata", size, size)
sect.Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ
chksectoff(sect, Cpos())
va := int(sect.VirtualAddress)
dd[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress = uint32(va)
dd[IMAGE_DIRECTORY_ENTRY_EXPORT].Size = sect.VirtualSize
va_name := va + binary.Size(&e) + nexport*4
va_addr := va + binary.Size(&e)
va_na := va + binary.Size(&e) + nexport*8
e.Characteristics = 0
e.MajorVersion = 0
e.MinorVersion = 0
e.NumberOfFunctions = uint32(nexport)
e.NumberOfNames = uint32(nexport)
e.Name = uint32(va+binary.Size(&e)) + uint32(nexport)*10 // Program names.
e.Base = 1
e.AddressOfFunctions = uint32(va_addr)
e.AddressOfNames = uint32(va_name)
e.AddressOfNameOrdinals = uint32(va_na)
// put IMAGE_EXPORT_DIRECTORY
binary.Write(&coutbuf, binary.LittleEndian, &e)
// put EXPORT Address Table
for i := 0; i < nexport; i++ {
Lputl(uint32(dexport[i].Value - PEBASE))
}
// put EXPORT Name Pointer Table
v := int(e.Name + uint32(len(outfile)) + 1)
for i := 0; i < nexport; i++ {
Lputl(uint32(v))
v += len(dexport[i].Extname) + 1
}
// put EXPORT Ordinal Table
for i := 0; i < nexport; i++ {
Wputl(uint16(i))
}
// put Names
strnput(outfile, len(outfile)+1)
for i := 0; i < nexport; i++ {
strnput(dexport[i].Extname, len(dexport[i].Extname)+1)
}
strnput("", int(sect.SizeOfRawData-uint32(size)))
}
// perelocsect relocates symbols from first in section sect, and returns
// the total number of relocations emitted.
func perelocsect(sect *Section, syms []*LSym) 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(Cpos())
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
}
Ctxt.Cursym = sym
for ri := 0; ri < len(sym.R); ri++ {
r := &sym.R[ri]
if r.Done != 0 {
continue
}
if r.Xsym == nil {
Diag("missing xsym in relocation")
continue
}
if r.Xsym.Dynid < 0 {
Diag("reloc %d to non-coff symbol %s (outer=%s) %d", r.Type, r.Sym.Name, r.Xsym.Name, r.Sym.Type)
}
if !Thearch.PEreloc1(r, int64(uint64(sym.Value+int64(r.Off))-PEBASE)) {
Diag("unsupported obj reloc %d/%d to %s", r.Type, r.Siz, r.Sym.Name)
}
relocs++
}
}
sect.Rellen = uint64(Cpos()) - sect.Reloff
return relocs
}
// peemitreloc emits relocation entries for go.o in external linking.
func peemitreloc(text, data, ctors *IMAGE_SECTION_HEADER) {
for Cpos()&7 != 0 {
Cput(0)
}
text.PointerToRelocations = uint32(Cpos())
// first entry: extended relocs
Lputl(0) // placeholder for number of relocation + 1
Lputl(0)
Wputl(0)
n := perelocsect(Segtext.Sect, Ctxt.Textp) + 1
for sect := Segtext.Sect.Next; sect != nil; sect = sect.Next {
n += perelocsect(sect, datap)
}
cpos := Cpos()
Cseek(int64(text.PointerToRelocations))
Lputl(uint32(n))
Cseek(cpos)
if n > 0x10000 {
n = 0x10000
text.Characteristics |= IMAGE_SCN_LNK_NRELOC_OVFL
} else {
text.PointerToRelocations += 10 // skip the extend reloc entry
}
text.NumberOfRelocations = uint16(n - 1)
data.PointerToRelocations = uint32(cpos)
// first entry: extended relocs
Lputl(0) // placeholder for number of relocation + 1
Lputl(0)
Wputl(0)
n = 1
for sect := Segdata.Sect; sect != nil; sect = sect.Next {
n += perelocsect(sect, datap)
}
cpos = Cpos()
Cseek(int64(data.PointerToRelocations))
Lputl(uint32(n))
Cseek(cpos)
if n > 0x10000 {
n = 0x10000
data.Characteristics |= IMAGE_SCN_LNK_NRELOC_OVFL
} else {
data.PointerToRelocations += 10 // skip the extend reloc entry
}
data.NumberOfRelocations = uint16(n - 1)
dottext := Linklookup(Ctxt, ".text", 0)
ctors.NumberOfRelocations = 1
ctors.PointerToRelocations = uint32(Cpos())
sectoff := ctors.VirtualAddress
Lputl(sectoff)
Lputl(uint32(dottext.Dynid))
switch obj.Getgoarch() {
default:
fmt.Fprintf(os.Stderr, "link: unknown architecture for PE: %q\n", obj.Getgoarch())
os.Exit(2)
case "386":
Wputl(IMAGE_REL_I386_DIR32)
case "amd64":
Wputl(IMAGE_REL_AMD64_ADDR64)
}
}
func dope() {
/* relocation table */
rel := Linklookup(Ctxt, ".rel", 0)
rel.Attr |= AttrReachable
rel.Type = obj.SELFROSECT
initdynimport()
initdynexport()
}
func strtbladd(name string) int {
off := len(strtbl) + 4 // offset includes 4-byte length at beginning of table
strtbl = append(strtbl, name...)
strtbl = append(strtbl, 0)
return off
}
/*
* For more than 8 characters section names, name contains a slash (/) that is
* followed by an ASCII representation of a decimal number that is an offset into
* the string table.
* reference: pecoff_v8.docx Page 24.
* <http://www.microsoft.com/whdc/system/platform/firmware/PECOFFdwn.mspx>
*/
func newPEDWARFSection(name string, size int64) *IMAGE_SECTION_HEADER {
if size == 0 {
return nil
}
off := strtbladd(name)
s := fmt.Sprintf("/%d", off)
h := addpesection(s, int(size), int(size))
h.Characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_DISCARDABLE
return h
}
// writePESymTableRecords writes all COFF symbol table records.
// It returns number of records written.
func writePESymTableRecords() int {
var symcnt int
put := func(s *LSym, name string, type_ int, addr int64, size int64, ver int, gotype *LSym) {
if s == nil {
return
}
if s.Sect == nil && type_ != 'U' {
return
}
switch type_ {
default:
return
case 'D', 'B', 'T', 'U':
}
// only windows/386 requires underscore prefix on external symbols
if SysArch.Family == sys.I386 &&
Linkmode == LinkExternal &&
(s.Type != obj.SDYNIMPORT || s.Attr.CgoExport()) &&
s.Name == s.Extname &&
s.Name != "_main" {
s.Name = "_" + s.Name
}
var typ uint16
var sect int
var value int64
// Note: although address of runtime.edata (type SDATA) is at the start of .bss section
// it still belongs to the .data section, not the .bss section.
if uint64(s.Value) >= Segdata.Vaddr+Segdata.Filelen && s.Type != obj.SDATA && Linkmode == LinkExternal {
value = int64(uint64(s.Value) - Segdata.Vaddr - Segdata.Filelen)
sect = bsssect
} else if uint64(s.Value) >= Segdata.Vaddr {
value = int64(uint64(s.Value) - Segdata.Vaddr)
sect = datasect
} else if uint64(s.Value) >= Segtext.Vaddr {
value = int64(uint64(s.Value) - Segtext.Vaddr)
sect = textsect
} else if type_ == 'U' {
typ = IMAGE_SYM_DTYPE_FUNCTION
} else {
Diag("addpesym %#x", addr)
}
// write COFF symbol table record
if len(s.Name) > 8 {
Lputl(0)
Lputl(uint32(strtbladd(s.Name)))
} else {
strnput(s.Name, 8)
}
Lputl(uint32(value))
Wputl(uint16(sect))
if typ != 0 {
Wputl(typ)
} else if Linkmode == LinkExternal {
Wputl(0)
} else {
Wputl(0x0308) // "array of structs"
}
Cput(2) // storage class: external
Cput(0) // no aux entries
s.Dynid = int32(symcnt)
symcnt++
}
if Linkmode == LinkExternal {