forked from pkujhd/goloader
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathld.go
1335 lines (1250 loc) · 46.7 KB
/
ld.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
package goloader
import (
"bytes"
"cmd/objfile/objabi"
"cmd/objfile/sys"
"encoding/binary"
"errors"
"fmt"
"os"
"reflect"
"runtime"
"sort"
"strings"
"sync"
"unsafe"
"github.com/eh-steve/goloader/obj"
"github.com/eh-steve/goloader/objabi/reloctype"
"github.com/eh-steve/goloader/objabi/symkind"
"github.com/eh-steve/goloader/stackobject"
)
// ourself defined struct
// code segment
type segment struct {
codeByte []byte
dataByte []byte
codeBase int
dataBase int
sumDataLen int
dataLen int
noptrdataLen int
bssLen int
noptrbssLen int
codeLen int
maxCodeLength int
maxDataLength int
codeOff int
dataOff int
}
type Linker struct {
code []byte
data []byte
noptrdata []byte
bss []byte
noptrbss []byte
cuFiles []obj.CompilationUnitFiles
symMap map[string]*obj.Sym
objsymbolMap map[string]*obj.ObjSymbol
namemap map[string]int
fileNameMap map[string]int
cutab []uint32
filetab []byte
funcnametab []byte
functab []byte
pctab []byte
_func []*_func
initFuncs []string
symNameOrder []string
Arch *sys.Arch
options LinkerOptions
heapStringMap map[string]*string
appliedADRPRelocs map[*byte][]byte
appliedPCRelRelocs map[*byte][]byte
pkgNamesWithUnresolved map[string]struct{}
pkgNamesToForceRebuild map[string]struct{}
reachableTypes map[string]struct{}
reachableSymbols map[string]struct{}
pkgs []*obj.Pkg
pkgsByName map[string]*obj.Pkg
}
type CodeModule struct {
segment
SymbolsByPkg map[string]map[string]interface{}
Syms map[string]uintptr
module *moduledata
gcdata []byte
gcbss []byte
patchedTypeMethodsIfn map[*_type]map[int]struct{}
patchedTypeMethodsTfn map[*_type]map[int]struct{}
patchedTypeMethodsMtyp map[*_type]map[int]typeOff
deduplicatedTypes map[string]uintptr
heapStrings map[string]*string
}
var (
modules = make(map[*CodeModule]bool)
modulesLock sync.Mutex
)
// initialize Linker
func initLinker(opts []LinkerOptFunc) (*Linker, error) {
linker := &Linker{
// Pad these tabs out so offsets don't start at 0, which is often used in runtime as a special value for "missing"
// e.g. runtime/traceback.go and runtime/symtab.go both contain checks like:
// if f.pcsp == 0 ...
// and
// if f.nameoff == 0
funcnametab: make([]byte, PtrSize),
pctab: make([]byte, PtrSize),
symMap: make(map[string]*obj.Sym),
objsymbolMap: make(map[string]*obj.ObjSymbol),
namemap: make(map[string]int),
fileNameMap: make(map[string]int),
heapStringMap: make(map[string]*string),
appliedADRPRelocs: make(map[*byte][]byte),
appliedPCRelRelocs: make(map[*byte][]byte),
pkgNamesWithUnresolved: make(map[string]struct{}),
pkgNamesToForceRebuild: make(map[string]struct{}),
reachableTypes: make(map[string]struct{}),
reachableSymbols: make(map[string]struct{}),
}
if os.Getenv("GOLOADER_FORCE_TEST_RELOCATION_EPILOGUES") == "1" {
opts = append(opts, WithForceTestRelocationEpilogues())
}
linker.Opts(opts...)
head := make([]byte, unsafe.Sizeof(pcHeader{}))
copy(head, obj.ModuleHeadx86)
linker.functab = append(linker.functab, head...)
linker.functab[len(obj.ModuleHeadx86)-1] = PtrSize
return linker, nil
}
func (linker *Linker) Autolib() []string {
// Sort dependent packages into autolib order via depth first recursion
if len(linker.pkgs) == 0 {
return nil
}
seen := map[string]struct{}{}
var autolibsByPkg = map[string][]string{}
for _, pkg := range linker.pkgs {
autolibsByPkg[pkg.PkgPath] = pkg.AutoLib
}
// The last package is the main package, so start there
mainPkg := linker.pkgs[len(linker.pkgs)-1]
var autolibs []string
recurseAutolibs(autolibsByPkg, mainPkg.PkgPath, &autolibs, seen)
return autolibs
}
func recurseAutolibs(autolibsByPkg map[string][]string, targetPkg string, autolibs *[]string, seen map[string]struct{}) {
if _, ok := seen[targetPkg]; ok {
return
}
seen[targetPkg] = struct{}{}
for _, imported := range autolibsByPkg[targetPkg] {
recurseAutolibs(autolibsByPkg, imported, autolibs, seen)
newLibs := autolibsByPkg[imported]
for _, newLib := range newLibs {
if _, ok := seen[newLib]; !ok {
*autolibs = append(*autolibs, newLib)
}
}
}
*autolibs = append(*autolibs, targetPkg)
}
func (linker *Linker) Opts(linkerOpts ...LinkerOptFunc) {
for _, opt := range linkerOpts {
opt(&linker.options)
}
}
func (linker *Linker) addSymbols(symbolNames []string, globalSymPtr map[string]uintptr) error {
// static_tmp is 0, golang compile not allocate memory.
linker.noptrdata = append(linker.noptrdata, make([]byte, IntSize)...)
for _, cuFileSet := range linker.cuFiles {
for _, fileName := range cuFileSet.Files {
if offset, ok := linker.fileNameMap[fileName]; !ok {
linker.cutab = append(linker.cutab, (uint32)(len(linker.filetab)))
linker.fileNameMap[fileName] = len(linker.filetab)
fileName = expandGoroot(strings.TrimPrefix(fileName, FileSymPrefix))
linker.filetab = append(linker.filetab, []byte(fileName)...)
linker.filetab = append(linker.filetab, ZeroByte)
} else {
linker.cutab = append(linker.cutab, uint32(offset))
}
}
}
for _, objSymName := range symbolNames {
if _, ok := linker.symMap[objSymName]; ok {
continue
}
if !linker.isSymbolReachable(objSymName) {
continue
}
objSym := linker.objsymbolMap[objSymName]
if objSym == nil {
// Might have been added as an ABI wrapper without the actual implementation
objSym = linker.objsymbolMap[objSymName+obj.ABI0Suffix]
if objSym != nil {
panic("missing a symbol " + objSymName + " but found its ABI0 wrapper")
} else {
objSym = linker.objsymbolMap[objSymName+obj.ABIInternalSuffix]
if objSym != nil {
panic("missing a symbol " + objSymName + " but found its ABIInternal wrapper")
}
}
}
if objSym.Kind == symkind.STEXT && objSym.DupOK == false {
_, err := linker.addSymbol(objSym.Name, globalSymPtr)
if err != nil {
return err
}
} else if objSym.Kind == symkind.STEXT && objSym.DupOK {
// This might be an asm func ABIWRAPPER. Check if one of its relocs points to itself
// (the abi0 version of itself, without the .abiinternal suffix)
isAsmWrapper := false
if objSym.Func != nil && objSym.Func.FuncID == uint8(obj.FuncIDWrapper) {
for _, reloc := range objSym.Reloc {
if reloc.Sym.Name+obj.ABIInternalSuffix == objSym.Name {
// Relocation pointing at itself (the ABI0 ASM version)
isAsmWrapper = true
}
}
}
if isAsmWrapper {
// This wrapper's symbol has a suffix of .abiinternal to distinguish it from the abi0 ASM func
_, err := linker.addSymbol(objSym.Name, globalSymPtr)
if err != nil {
return err
}
}
}
switch objSym.Kind {
case symkind.SNOPTRDATA, symkind.SRODATA, symkind.SDATA, symkind.SBSS, symkind.SNOPTRBSS:
_, err := linker.addSymbol(objSym.Name, globalSymPtr)
if err != nil {
return err
}
}
}
for _, sym := range linker.symMap {
offset := 0
switch sym.Kind {
case symkind.SNOPTRDATA, symkind.SRODATA:
if strings.HasPrefix(sym.Name, TypeStringPrefix) {
// nothing todo
} else {
offset += len(linker.data)
}
case symkind.SBSS:
offset += len(linker.data) + len(linker.noptrdata)
case symkind.SNOPTRBSS:
offset += len(linker.data) + len(linker.noptrdata) + len(linker.bss)
}
sym.Offset += offset
if offset != 0 {
for index := range sym.Reloc {
sym.Reloc[index].Offset += offset
if sym.Reloc[index].EpilogueOffset > 0 {
sym.Reloc[index].EpilogueOffset += offset
}
}
}
}
linker.symNameOrder = symbolNames
return nil
}
func (linker *Linker) SymbolOrder() []string {
return linker.symNameOrder
}
func (linker *Linker) addSymbol(name string, globalSymPtr map[string]uintptr) (symbol *obj.Sym, err error) {
if symbol, ok := linker.symMap[name]; ok {
return symbol, nil
}
objsym := linker.objsymbolMap[name]
symbol = &obj.Sym{Name: objsym.Name, Kind: objsym.Kind, Pkg: objsym.Pkg}
linker.symMap[symbol.Name] = symbol
switch symbol.Kind {
case symkind.STEXT:
symbol.Offset = len(linker.code)
linker.code = append(linker.code, objsym.Data...)
bytearrayAlignNops(linker.Arch, &linker.code, PtrSize)
for i, reloc := range objsym.Reloc {
// Pessimistically pad the function text with extra bytes for any relocations which might add extra
// instructions at the end in the case of a 32 bit overflow. These epilogue PCs need to be added to
// the PCData, PCLine, PCFile, PCSP etc in case of pre-emption or stack unwinding while the PC is running these hacked instructions.
// We find the relevant PCValues for the offset of the reloc, and reuse the values for the reloc's epilogue
if linker.options.NoRelocationEpilogues && !strings.HasPrefix(reloc.Sym.Name, TypeStringPrefix) {
continue
}
switch reloc.Type {
case reloctype.R_ADDRARM64:
objsym.Reloc[i].EpilogueOffset = len(linker.code) - symbol.Offset
objsym.Reloc[i].EpilogueSize = maxExtraInstructionBytesADRP
linker.code = append(linker.code, createArchNops(linker.Arch, maxExtraInstructionBytesADRP)...)
case reloctype.R_ARM64_PCREL_LDST8, reloctype.R_ARM64_PCREL_LDST16, reloctype.R_ARM64_PCREL_LDST32, reloctype.R_ARM64_PCREL_LDST64:
objsym.Reloc[i].EpilogueOffset = len(linker.code) - symbol.Offset
objsym.Reloc[i].EpilogueSize = maxExtraInstructionBytesADRPLDST
linker.code = append(linker.code, createArchNops(linker.Arch, maxExtraInstructionBytesADRPLDST)...)
case reloctype.R_CALLARM64, reloctype.R_CALLARM64 | reloctype.R_WEAK:
objsym.Reloc[i].EpilogueOffset = alignof(len(linker.code)-symbol.Offset, PtrSize)
objsym.Reloc[i].EpilogueSize = maxExtraInstructionBytesCALLARM64
alignment := alignof(len(linker.code)-symbol.Offset, PtrSize) - (len(linker.code) - symbol.Offset)
linker.code = append(linker.code, createArchNops(linker.Arch, maxExtraInstructionBytesCALLARM64+alignment)...)
case reloctype.R_PCREL:
objsym.Reloc[i].EpilogueOffset = len(linker.code) - symbol.Offset
var epilogueSize int
offset := reloc.Offset
if reloc.Offset == 1 {
// This might happen if a CGo E9 JMP is right at the beginning of a function, so we want to avoid slicing before the start of the text
offset += 1
}
instructionBytes := objsym.Data[offset-2 : reloc.Offset+reloc.Size]
opcode := instructionBytes[0]
switch opcode {
case x86amd64LEAcode:
epilogueSize = maxExtraInstructionBytesPCRELxLEAQ
case x86amd64MOVcode:
epilogueSize = maxExtraInstructionBytesPCRELxMOVNear
case x86amd64CMPLcode:
epilogueSize = maxExtraInstructionBytesPCRELxCMPLNear
case x86amd64JMPcode:
epilogueSize = maxExtraInstructionBytesPCRELxJMP
case x86amd64CALL2code: // CGo FF 15 PCREL call
if instructionBytes[1] == 0x15 {
epilogueSize = maxExtraInstructionBytesPCRELxCALL2
break
}
fallthrough // Might be FF XX E8/E9 ...
default:
switch instructionBytes[1] {
case x86amd64CALLcode:
opcode = x86amd64CALLcode
epilogueSize = maxExtraInstructionBytesCALLNear
case x86amd64JMPcode:
epilogueSize = maxExtraInstructionBytesPCRELxJMP
}
}
returnOffset := (reloc.Offset + reloc.Size) - (objsym.Reloc[i].EpilogueOffset + epilogueSize) - len(x86amd64JMPShortCode) // assumes short jump, adjusts if not
shortJmp := returnOffset < 0 && returnOffset > -0x80
switch opcode {
case x86amd64MOVcode:
if shortJmp {
epilogueSize = maxExtraInstructionBytesPCRELxMOVShort
}
case x86amd64CMPLcode:
if shortJmp {
epilogueSize = maxExtraInstructionBytesPCRELxCMPLShort
}
case x86amd64CALLcode:
if shortJmp {
epilogueSize = maxExtraInstructionBytesCALLShort
}
}
objsym.Reloc[i].EpilogueSize = epilogueSize
linker.code = append(linker.code, createArchNops(linker.Arch, epilogueSize)...)
case reloctype.R_GOTPCREL, reloctype.R_TLS_IE:
objsym.Reloc[i].EpilogueOffset = len(linker.code) - symbol.Offset
objsym.Reloc[i].EpilogueSize = maxExtraInstructionBytesGOTPCREL
linker.code = append(linker.code, createArchNops(linker.Arch, objsym.Reloc[i].EpilogueSize)...)
case reloctype.R_ARM64_GOTPCREL, reloctype.R_ARM64_TLS_IE:
objsym.Reloc[i].EpilogueOffset = alignof(len(linker.code)-symbol.Offset, PtrSize)
objsym.Reloc[i].EpilogueSize = maxExtraInstructionBytesARM64GOTPCREL
// need to be able to pad to align to multiple of 8
alignment := alignof(len(linker.code)-symbol.Offset, PtrSize) - (len(linker.code) - symbol.Offset)
linker.code = append(linker.code, createArchNops(linker.Arch, objsym.Reloc[i].EpilogueSize+alignment)...)
case reloctype.R_CALL, reloctype.R_CALL | reloctype.R_WEAK:
epilogueSize := maxExtraInstructionBytesCALLNear
returnOffset := (reloc.Offset + reloc.Size) - (objsym.Reloc[i].EpilogueOffset + epilogueSize) - len(x86amd64JMPShortCode) // assumes short jump, adjusts if not
shortJmp := returnOffset < 0 && returnOffset > -0x80
objsym.Reloc[i].EpilogueOffset = len(linker.code) - symbol.Offset
if shortJmp {
epilogueSize = maxExtraInstructionBytesCALLShort
}
objsym.Reloc[i].EpilogueSize = epilogueSize
linker.code = append(linker.code, createArchNops(linker.Arch, epilogueSize)...)
}
bytearrayAlignNops(linker.Arch, &linker.code, PtrSize)
}
symbol.Func = &obj.Func{}
if err := linker.readFuncData(linker.objsymbolMap[name], symbol.Offset); err != nil {
return nil, err
}
case symkind.SDATA:
symbol.Offset = len(linker.data)
linker.data = append(linker.data, objsym.Data...)
bytearrayAlign(&linker.data, PtrSize)
case symkind.SNOPTRDATA, symkind.SRODATA:
// because golang string assignment is pointer assignment, so store go.string constants
// in a separate segment and not unload when module unload.
if strings.HasPrefix(symbol.Name, TypeStringPrefix) {
data := make([]byte, len(objsym.Data))
copy(data, objsym.Data)
stringVal := string(data)
linker.heapStringMap[symbol.Name] = &stringVal
} else {
symbol.Offset = len(linker.noptrdata)
linker.noptrdata = append(linker.noptrdata, objsym.Data...)
bytearrayAlign(&linker.noptrdata, PtrSize)
}
case symkind.SBSS:
symbol.Offset = len(linker.bss)
linker.bss = append(linker.bss, objsym.Data...)
bytearrayAlign(&linker.bss, PtrSize)
case symkind.SNOPTRBSS:
symbol.Offset = len(linker.noptrbss)
linker.noptrbss = append(linker.noptrbss, objsym.Data...)
bytearrayAlign(&linker.noptrbss, PtrSize)
case symkind.STLSBSS:
// Nothing to do, since runtime.tls_g should be resolved from the host binary
default:
return nil, fmt.Errorf("invalid symbol:%s kind:%d", symbol.Name, symbol.Kind)
}
if symbol.Kind == symkind.STEXT {
symbol.Size = len(linker.code) - symbol.Offset // includes epilogue
} else {
symbol.Size = int(objsym.Size)
}
for _, loc := range objsym.Reloc {
reloc := loc
reloc.Offset = reloc.Offset + symbol.Offset
reloc.EpilogueOffset = reloc.EpilogueOffset + symbol.Offset
if _, ok := linker.objsymbolMap[reloc.Sym.Name]; ok {
reloc.Sym, err = linker.addSymbol(reloc.Sym.Name, globalSymPtr)
if err != nil {
return nil, err
}
if len(linker.objsymbolMap[reloc.Sym.Name].Data) == 0 && reloc.Size > 0 {
// static_tmp is 0, golang compile not allocate memory.
// goloader add IntSize bytes on linker.noptrdata[0]
if reloc.Size <= IntSize {
reloc.Sym.Offset = 0
} else {
return nil, fmt.Errorf("Symbol: %s size: %d > IntSize: %d\n", reloc.Sym.Name, reloc.Size, IntSize)
}
}
} else {
if reloc.Type == reloctype.R_TLS_LE || reloc.Type == reloctype.R_TLS_IE {
reloc.Sym.Name = TLSNAME
reloc.Sym.Offset = loc.Offset
}
if reloc.Type == reloctype.R_CALLIND {
reloc.Sym.Offset = 0
}
_, exist := linker.symMap[reloc.Sym.Name]
if strings.HasPrefix(reloc.Sym.Name, TypeImportPathPrefix) {
if exist {
reloc.Sym = linker.symMap[reloc.Sym.Name]
} else {
path := strings.Trim(strings.TrimPrefix(reloc.Sym.Name, TypeImportPathPrefix), ".")
reloc.Sym.Kind = symkind.SNOPTRDATA
reloc.Sym.Offset = len(linker.noptrdata)
// name memory layout
// name { tagLen(byte), len(uint16), str*}
nameLen := []byte{0, 0, 0}
binary.PutUvarint(nameLen[1:], uint64(len(path)))
linker.noptrdata = append(linker.noptrdata, nameLen...)
linker.noptrdata = append(linker.noptrdata, path...)
linker.noptrdata = append(linker.noptrdata, ZeroByte)
bytearrayAlign(&linker.noptrdata, PtrSize)
}
}
if ispreprocesssymbol(reloc.Sym.Name) {
bytes := make([]byte, UInt64Size)
if err := preprocesssymbol(linker.Arch.ByteOrder, reloc.Sym.Name, bytes); err != nil {
return nil, err
} else {
if exist {
reloc.Sym = linker.symMap[reloc.Sym.Name]
} else {
reloc.Sym.Kind = symkind.SNOPTRDATA
reloc.Sym.Offset = len(linker.noptrdata)
linker.noptrdata = append(linker.noptrdata, bytes...)
bytearrayAlign(&linker.noptrdata, PtrSize)
}
}
}
if !exist {
// golang1.8, some function generates more than one (MOVQ (TLS), CX)
// so when same name symbol in linker.symMap, do not update it
if reloc.Sym.Name != "" {
linker.symMap[reloc.Sym.Name] = reloc.Sym
}
}
}
symbol.Reloc = append(symbol.Reloc, reloc)
}
if objsym.Type != EmptyString {
if _, ok := linker.symMap[objsym.Type]; !ok {
if _, ok := linker.objsymbolMap[objsym.Type]; !ok {
linker.symMap[objsym.Type] = &obj.Sym{Name: objsym.Type, Offset: InvalidOffset, Pkg: objsym.Pkg}
}
}
}
return symbol, nil
}
func (linker *Linker) readFuncData(symbol *obj.ObjSymbol, codeLen int) (err error) {
nameOff := len(linker.funcnametab)
if offset, ok := linker.namemap[symbol.Name]; !ok {
linker.namemap[symbol.Name] = len(linker.funcnametab)
linker.funcnametab = append(linker.funcnametab, []byte(symbol.Name)...)
linker.funcnametab = append(linker.funcnametab, ZeroByte)
} else {
nameOff = offset
}
for _, reloc := range symbol.Reloc {
if reloc.EpilogueOffset > 0 {
if len(symbol.Func.PCSP) > 0 {
linker.patchPCValuesForReloc(&symbol.Func.PCSP, reloc.Offset, reloc.EpilogueOffset, reloc.EpilogueSize)
}
if len(symbol.Func.PCFile) > 0 {
linker.patchPCValuesForReloc(&symbol.Func.PCFile, reloc.Offset, reloc.EpilogueOffset, reloc.EpilogueSize)
}
if len(symbol.Func.PCLine) > 0 {
linker.patchPCValuesForReloc(&symbol.Func.PCLine, reloc.Offset, reloc.EpilogueOffset, reloc.EpilogueSize)
}
for i, pcdata := range symbol.Func.PCData {
if len(pcdata) > 0 {
linker.patchPCValuesForReloc(&symbol.Func.PCData[i], reloc.Offset, reloc.EpilogueOffset, reloc.EpilogueSize)
}
}
}
}
pcspOff := len(linker.pctab)
linker.pctab = append(linker.pctab, symbol.Func.PCSP...)
pcfileOff := len(linker.pctab)
linker.pctab = append(linker.pctab, symbol.Func.PCFile...)
pclnOff := len(linker.pctab)
linker.pctab = append(linker.pctab, symbol.Func.PCLine...)
_func := initfunc(symbol, nameOff, pcspOff, pcfileOff, pclnOff, symbol.Func.CUOffset)
linker._func = append(linker._func, &_func)
Func := linker.symMap[symbol.Name].Func
for _, pcdata := range symbol.Func.PCData {
if len(pcdata) == 0 {
Func.PCData = append(Func.PCData, 0)
} else {
Func.PCData = append(Func.PCData, uint32(len(linker.pctab)))
linker.pctab = append(linker.pctab, pcdata...)
}
}
for _, name := range symbol.Func.FuncData {
if name == EmptyString {
Func.FuncData = append(Func.FuncData, (uintptr)(0))
} else {
if _, ok := linker.symMap[name]; !ok {
if _, ok := linker.objsymbolMap[name]; ok {
if _, err = linker.addSymbol(name, nil); err != nil {
return err
}
} else {
return errors.New("unknown gcobj:" + name)
}
}
if sym, ok := linker.symMap[name]; ok {
Func.FuncData = append(Func.FuncData, (uintptr)(sym.Offset))
} else {
Func.FuncData = append(Func.FuncData, (uintptr)(0))
}
}
}
if err = linker.addInlineTree(&_func, symbol); err != nil {
return err
}
grow(&linker.pctab, alignof(len(linker.pctab), PtrSize))
return
}
func (linker *Linker) addSymbolMap(symPtr map[string]uintptr, codeModule *CodeModule) (symbolMap map[string]uintptr, err error) {
symbolMap = make(map[string]uintptr)
segment := &codeModule.segment
for name, sym := range linker.symMap {
if !linker.isSymbolReachable(name) {
continue
}
if sym.Offset == InvalidOffset {
if ptr, ok := symPtr[sym.Name]; ok {
symbolMap[name] = ptr
// Mark the symbol as a duplicate
symbolMap[FirstModulePrefix+name] = ptr
} else {
symbolMap[name] = InvalidHandleValue
return nil, fmt.Errorf("unresolved external symbol: %s", sym.Name)
}
} else if sym.Name == TLSNAME {
// nothing todo
} else if sym.Kind == symkind.STEXT {
symbolMap[name] = uintptr(linker.symMap[name].Offset + segment.codeBase)
codeModule.Syms[sym.Name] = symbolMap[name]
if _, ok := symPtr[name]; ok {
// Mark the symbol as a duplicate, and store the original entrypoint
symbolMap[FirstModulePrefix+name] = symPtr[name]
}
} else if strings.HasPrefix(sym.Name, ItabPrefix) {
if ptr, ok := symPtr[sym.Name]; ok {
symbolMap[name] = ptr
symbolMap[FirstModulePrefix+name] = ptr
}
} else {
if _, ok := symPtr[name]; !ok {
if strings.HasPrefix(name, TypeStringPrefix) {
strPtr := linker.heapStringMap[name]
if strPtr == nil {
return nil, fmt.Errorf("impossible! got a nil string for symbol %s", name)
}
if len(*strPtr) == 0 {
// Any address will do, the length is 0, so it should never be read
symbolMap[name] = uintptr(unsafe.Pointer(linker))
} else {
x := (*reflect.StringHeader)(unsafe.Pointer(strPtr))
symbolMap[name] = x.Data
}
} else {
symbolMap[name] = uintptr(linker.symMap[name].Offset + segment.dataBase)
if strings.HasSuffix(sym.Name, "·f") {
codeModule.Syms[sym.Name] = symbolMap[name]
}
if strings.HasPrefix(name, TypePrefix) {
if variant, ok := symbolIsVariant(name); ok && symPtr[variant] != 0 {
symbolMap[FirstModulePrefix+name] = symPtr[variant]
}
}
}
} else {
if strings.HasPrefix(name, MainPkgPrefix) || strings.HasPrefix(name, TypePrefix) {
symbolMap[name] = uintptr(linker.symMap[name].Offset + segment.dataBase)
// Record the presence of a duplicate symbol by adding a prefix
symbolMap[FirstModulePrefix+name] = symPtr[name]
} else {
shouldSkipDedup := false
for _, pkgPath := range linker.options.SkipTypeDeduplicationForPackages {
if strings.HasPrefix(name, pkgPath) {
shouldSkipDedup = true
}
}
if shouldSkipDedup {
// Use the new version of the symbol
symbolMap[name] = uintptr(linker.symMap[name].Offset + segment.dataBase)
} else {
symbolMap[name] = symPtr[name]
// Mark the symbol as a duplicate
symbolMap[FirstModulePrefix+name] = symPtr[name]
}
}
}
}
}
if tlsG, ok := symPtr[TLSNAME]; ok {
symbolMap[TLSNAME] = tlsG
}
codeModule.heapStrings = linker.heapStringMap
return symbolMap, err
}
func (linker *Linker) addFuncTab(module *moduledata, _func *_func, symbolMap map[string]uintptr) (err error) {
funcname := gostringnocopy(&linker.funcnametab[_func.nameoff])
setfuncentry(_func, symbolMap[funcname], module.text)
Func := linker.symMap[funcname].Func
if err = stackobject.AddStackObject(funcname, linker.symMap, symbolMap, module.noptrdata); err != nil {
return err
}
if err = linker.addDeferReturn(_func); err != nil {
return err
}
append2Slice(&module.pclntable, uintptr(unsafe.Pointer(_func)), _FuncSize)
if _func.npcdata > 0 {
append2Slice(&module.pclntable, uintptr(unsafe.Pointer(&(Func.PCData[0]))), Uint32Size*int(_func.npcdata))
}
if _func.nfuncdata > 0 {
addfuncdata(module, Func, _func)
}
return err
}
func readPCData(p []byte, startPC uintptr) (pcs []uintptr, vals []int32) {
pc := startPC
val := int32(-1)
if len(p) == 0 {
return nil, nil
}
for {
var ok bool
p, ok = step(p, &pc, &val, pc == startPC)
if !ok {
break
}
pcs = append(pcs, pc)
vals = append(vals, val)
if len(p) == 0 {
break
}
}
return
}
func formatPCData(p []byte, startPC uintptr) string {
pcs, vals := readPCData(p, startPC)
var result string
if len(pcs) == 0 {
return "()"
}
prevPC := startPC
for i := range pcs {
result += fmt.Sprintf("(%d-%d => %d), ", prevPC, pcs[i], vals[i])
prevPC = startPC + pcs[i]
}
return result
}
func pcValue(p []byte, targetOffset uintptr) (int32, uintptr) {
startPC := uintptr(0)
pc := uintptr(0)
val := int32(-1)
if len(p) == 0 {
return -1, 1<<64 - 1
}
prevpc := pc
for {
var ok bool
p, ok = step(p, &pc, &val, pc == startPC)
if !ok {
break
}
if len(p) == 0 {
break
}
if targetOffset < pc {
return val, prevpc
}
prevpc = pc
}
return -1, 1<<64 - 1
}
func (linker *Linker) patchPCValuesForReloc(pcvalues *[]byte, relocOffet int, epilogueOffset int, epilogueSize int) {
// Use the pcvalue at the offset of the reloc for the entire of that reloc's epilogue.
// This ensures that if the code is pre-empted or the stack unwound while we're inside the epilogue, the runtime behaves correctly
var pcQuantum uintptr = 1
if linker.Arch.Family == sys.ARM64 {
pcQuantum = 4
}
p := *pcvalues
if len(p) == 0 {
panic("trying to patch a zero sized pcvalue table. This shouldn't be possible...")
}
valAtRelocSite, startPC := pcValue(p, uintptr(relocOffet))
if startPC == 1<<64-1 && valAtRelocSite == -1 {
panic(fmt.Sprintf("couldn't interpret pcvalue data when trying to patch it... relocOffset: %d, pcdata: %v\n %s", relocOffet, p, formatPCData(p, 0)))
}
if p[len(p)-1] != 0 {
panic(fmt.Sprintf("got a pcvalue table with an unexpected ending (%d)...\n%s ", p[len(p)-1], formatPCData(p, 0)))
}
p = p[:len(p)-1] // Remove the terminating 0
// Table is (value, PC), (value, PC), (value, PC)... etc
// Each value is delta encoded (signed) relative to the last, and each PC is delta encoded (unsigned)
pcs, vals := readPCData(p, 0)
lastValue := vals[len(vals)-1]
lastPC := pcs[len(pcs)-1]
if lastValue == valAtRelocSite {
// Extend the lastPC delta to absorb our epilogue, keep the value the same
var pcDelta uintptr
if len(pcs) > 1 {
pcDelta = (lastPC - pcs[len(pcs)-2]) / pcQuantum
} else {
pcDelta = lastPC / pcQuantum
}
buf := make([]byte, 10)
n := binary.PutUvarint(buf, uint64(pcDelta))
buf = buf[:n]
index := bytes.LastIndex(p, buf)
if index == -1 {
panic(fmt.Sprintf("could not find varint PC delta of %d (%v)", pcDelta, buf))
}
p = p[:index]
if len(pcs) > 1 {
pcDelta = (uintptr(epilogueOffset+epilogueSize) - pcs[len(pcs)-2]) / pcQuantum
} else {
pcDelta = (uintptr(epilogueOffset + epilogueSize)) / pcQuantum
}
buf = make([]byte, 10)
n = binary.PutUvarint(buf, uint64(pcDelta))
p = append(p, buf[:n]...)
} else {
// Append a new (value, PC) pair
pcDelta := (epilogueOffset + epilogueSize - int(lastPC)) / int(pcQuantum)
if pcDelta < 0 {
panic(fmt.Sprintf("somehow the epilogue is not at the end?? lastPC %d, epilogue offset %d", lastPC, epilogueOffset))
}
valDelta := valAtRelocSite - lastValue
buf := make([]byte, 10)
n := binary.PutVarint(buf, int64(valDelta))
p = append(p, buf[:n]...)
n = binary.PutUvarint(buf, uint64(pcDelta))
p = append(p, buf[:n]...)
}
// Re-add the terminating 0 we stripped off
p = append(p, 0)
*pcvalues = p
}
func (linker *Linker) buildModule(codeModule *CodeModule, symbolMap map[string]uintptr) (err error) {
segment := &codeModule.segment
module := codeModule.module
module.pclntable = append(module.pclntable, linker.functab...)
module.minpc = uintptr(segment.codeBase)
module.maxpc = uintptr(segment.codeBase + segment.codeOff)
module.text = uintptr(segment.codeBase)
module.etext = module.maxpc
module.data = uintptr(segment.dataBase)
module.edata = uintptr(segment.dataBase) + uintptr(segment.dataLen)
module.noptrdata = module.edata
module.enoptrdata = module.noptrdata + uintptr(segment.noptrdataLen)
module.bss = module.enoptrdata
module.ebss = module.bss + uintptr(segment.bssLen)
module.noptrbss = module.ebss
module.enoptrbss = module.noptrbss + uintptr(segment.noptrbssLen)
module.end = module.enoptrbss
module.types = module.data
module.etypes = module.enoptrbss
module.ftab = append(module.ftab, initfunctab(module.minpc, uintptr(len(module.pclntable)), module.text))
for index, _func := range linker._func {
funcname := gostringnocopy(&linker.funcnametab[_func.nameoff])
module.ftab = append(module.ftab, initfunctab(symbolMap[funcname], uintptr(len(module.pclntable)), module.text))
if err = linker.addFuncTab(module, linker._func[index], symbolMap); err != nil {
return err
}
}
module.ftab = append(module.ftab, initfunctab(module.maxpc, uintptr(len(module.pclntable)), module.text))
// see:^src/cmd/link/internal/ld/pcln.go findfunctab
funcbucket := []findfuncbucket{}
for k := 0; k < len(linker._func); k++ {
lEntry := int(getfuncentry(linker._func[k], module.text) - module.text)
lb := lEntry / pcbucketsize
li := lEntry % pcbucketsize / (pcbucketsize / nsub)
entry := int(module.maxpc - module.text)
if k < len(linker._func)-1 {
entry = int(getfuncentry(linker._func[k+1], module.text) - module.text)
}
b := entry / pcbucketsize
i := entry % pcbucketsize / (pcbucketsize / nsub)
for m := b - len(funcbucket); m >= 0; m-- {
funcbucket = append(funcbucket, findfuncbucket{idx: uint32(k)})
}
if lb < b {
i = nsub - 1
}
for n := li + 1; n <= i; n++ {
if funcbucket[lb].subbuckets[n] == 0 {
funcbucket[lb].subbuckets[n] = byte(k - int(funcbucket[lb].idx))
}
}
}
length := len(funcbucket) * FindFuncBucketSize
append2Slice(&module.pclntable, uintptr(unsafe.Pointer(&funcbucket[0])), length)
module.findfunctab = (uintptr)(unsafe.Pointer(&module.pclntable[len(module.pclntable)-length]))
if err = linker.addgcdata(codeModule, symbolMap); err != nil {
return err
}
for name, addr := range symbolMap {
if strings.HasPrefix(name, TypePrefix) &&
!strings.HasPrefix(name, TypeDoubleDotPrefix) &&
addr >= module.types && addr < module.etypes {
module.typelinks = append(module.typelinks, int32(addr-module.types))
module.typemap[typeOff(addr-module.types)] = (*_type)(unsafe.Pointer(addr))
}
}
initmodule(codeModule.module, linker)
modulesLock.Lock()
addModule(codeModule)
modulesLock.Unlock()
additabs(codeModule.module)
moduledataverify1(codeModule.module)
modulesinit()
typelinksinit() // Deduplicate typelinks across all modules
return err
}
func (linker *Linker) deduplicateTypeDescriptors(codeModule *CodeModule, symbolMap map[string]uintptr) (err error) {
// Having called addModule and runtime.modulesinit(), we can now safely use typesEqual()
// (which depended on the module being in the linked list for safe name resolution of types).
// This means we can now deduplicate type descriptors in the actual code
// by relocating their addresses to the equivalent *_type in the main module
// We need to deduplicate type symbols with the main module according to type hash, since type assertion
// uses *_type pointer equality and many overlapping or builtin types may be included twice
// We have to do this after adding the module to the linked list since deduplication
// depends on symbol resolution across all modules
typehash := make(map[uint32][]*_type, len(firstmoduledata.typelinks))
buildModuleTypeHash(activeModules()[0], typehash)
patchedTypeMethodsIfn := make(map[*_type]map[int]struct{})
patchedTypeMethodsTfn := make(map[*_type]map[int]struct{})
patchedTypeMethodsMtyp := make(map[*_type]map[int]typeOff)
segment := &codeModule.segment
byteorder := linker.Arch.ByteOrder
dedupedTypes := map[string]uintptr{}
for _, symbol := range linker.symMap {
if linker.options.DumpTextBeforeAndAfterRelocs && linker.options.RelocationDebugWriter != nil && symbol.Kind == symkind.STEXT && symbol.Offset >= 0 {
_, _ = fmt.Fprintf(linker.options.RelocationDebugWriter, "BEFORE DEDUPE (%x - %x) %142s: %x\n", codeModule.codeBase+symbol.Offset, codeModule.codeBase+symbol.Offset+symbol.Size, symbol.Name, codeModule.codeByte[symbol.Offset:symbol.Offset+symbol.Size])
}
relocLoop:
for _, loc := range symbol.Reloc {
addr := symbolMap[loc.Sym.Name]
sym := loc.Sym
relocByte := segment.dataByte
addrBase := segment.dataBase
if symbol.Kind == symkind.STEXT {
addrBase = segment.codeBase
relocByte = segment.codeByte
}
if addr != InvalidHandleValue && sym.Kind == symkind.SRODATA &&
strings.HasPrefix(sym.Name, TypePrefix) &&
!strings.HasPrefix(sym.Name, TypeDoubleDotPrefix) && sym.Offset != -1 {
// if this is pointing to a type descriptor at an offset inside this binary, we should deduplicate it against
// already known types from other modules to allow fast type assertion using *_type pointer equality
t := (*_type)(unsafe.Pointer(addr))
prevT := (*_type)(unsafe.Pointer(addr))
for _, candidate := range typehash[t.hash] {
seen := map[_typePair]struct{}{}
if typesEqual(t, candidate, seen) {
t = candidate
break
}
}
// Only relocate code if the type is a duplicate
if t != prevT {
_, isVariant := symbolIsVariant(loc.Sym.Name)
if uintptr(unsafe.Pointer(t)) != symbolMap[FirstModulePrefix+loc.Sym.Name] && !isVariant {
// This shouldn't be possible and indicates a registration bug
panic(fmt.Sprintf("found another firstmodule type that wasn't registered by goloader. Symbol name: %s, type name: %s. This shouldn't be possible and indicates a bug in firstmodule type registration\n", loc.Sym.Name, t.nameOff(t.str).name()))
}
// Store this for later so we know which types were deduplicated
dedupedTypes[loc.Sym.Name] = uintptr(unsafe.Pointer(t))
for _, pkgPathToSkip := range linker.options.SkipTypeDeduplicationForPackages {
if t.PkgPath() == pkgPathToSkip {
continue relocLoop
}
}
u := t.uncommon()
prevU := prevT.uncommon()
err2 := codeModule.patchTypeMethodOffsets(t, u, prevU, patchedTypeMethodsIfn, patchedTypeMethodsTfn, patchedTypeMethodsMtyp)
if err2 != nil {
return err2
}
addr = uintptr(unsafe.Pointer(t))
if linker.options.RelocationDebugWriter != nil && loc.Offset != InvalidOffset {
var weakness string
if loc.Type&reloctype.R_WEAK > 0 {
weakness = "WEAK|"
}
relocType := weakness + objabi.RelocType(loc.Type&^reloctype.R_WEAK).String()
_, _ = fmt.Fprintf(linker.options.RelocationDebugWriter, "DEDUPLICATING %10s %10s %18s Base: 0x%x Pos: 0x%08x, Addr: 0x%016x AddrFromBase: %12d %s to %s\n",
objabi.SymKind(symbol.Kind), objabi.SymKind(sym.Kind), relocType, addrBase, uintptr(unsafe.Pointer(&relocByte[loc.Offset])),
addr, int(addr)-addrBase, symbol.Name, sym.Name)
}
switch loc.Type {
case reloctype.R_GOTPCREL:
linker.relocateGOTPCREL(addr, loc, relocByte)
case reloctype.R_PCREL:
err2 := linker.relocatePCREL(addr, loc, &codeModule.segment, relocByte, addrBase)