-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.go
3117 lines (2810 loc) · 99.7 KB
/
data.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
// Derived from Inferno utils/6l/obj.c and utils/6l/span.c
// https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/obj.c
// https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/span.c
//
// Copyright © 1994-1999 Lucent Technologies Inc. All rights reserved.
// Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
// Portions Copyright © 1997-1999 Vita Nuova Limited
// Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
// Portions Copyright © 2004,2006 Bruce Ellis
// Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net)
// Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
// Portions Copyright © 2009 The Go Authors. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package ld
import (
"bytes"
"compress/zlib"
"debug/elf"
"encoding/binary"
"fmt"
"log"
"os"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"github.com/go-asm/go/cmd/gcprog"
"github.com/go-asm/go/cmd/link/loader"
"github.com/go-asm/go/cmd/link/loadpe"
"github.com/go-asm/go/cmd/link/sym"
"github.com/go-asm/go/cmd/objabi"
"github.com/go-asm/go/cmd/sys"
)
// isRuntimeDepPkg reports whether pkg is the runtime package or its dependency.
func isRuntimeDepPkg(pkg string) bool {
switch pkg {
case "runtime",
"sync/atomic", // runtime may call to sync/atomic, due to go:linkname
"github.com/go-asm/go/abi", // used by reflectcall (and maybe more)
"github.com/go-asm/go/bytealg", // for IndexByte
"github.com/go-asm/go/chacha8rand", // for rand
"github.com/go-asm/go/cpu": // for cpu features
return true
}
return strings.HasPrefix(pkg, "runtime/github.com/go-asm/go/") && !strings.HasSuffix(pkg, "_test")
}
// Estimate the max size needed to hold any new trampolines created for this function. This
// is used to determine when the section can be split if it becomes too large, to ensure that
// the trampolines are in the same section as the function that uses them.
func maxSizeTrampolines(ctxt *Link, ldr *loader.Loader, s loader.Sym, isTramp bool) uint64 {
// If thearch.Trampoline is nil, then trampoline support is not available on this arch.
// A trampoline does not need any dependent trampolines.
if thearch.Trampoline == nil || isTramp {
return 0
}
n := uint64(0)
relocs := ldr.Relocs(s)
for ri := 0; ri < relocs.Count(); ri++ {
r := relocs.At(ri)
if r.Type().IsDirectCallOrJump() {
n++
}
}
switch {
case ctxt.IsARM():
return n * 20 // Trampolines in ARM range from 3 to 5 instructions.
case ctxt.IsARM64():
return n * 12 // Trampolines in ARM64 are 3 instructions.
case ctxt.IsPPC64():
return n * 16 // Trampolines in PPC64 are 4 instructions.
case ctxt.IsRISCV64():
return n * 8 // Trampolines in RISCV64 are 2 instructions.
}
panic("unreachable")
}
// Detect too-far jumps in function s, and add trampolines if necessary.
// ARM, PPC64, PPC64LE and RISCV64 support trampoline insertion for internal
// and external linking. On PPC64 and PPC64LE the text sections might be split
// but will still insert trampolines where necessary.
func trampoline(ctxt *Link, s loader.Sym) {
if thearch.Trampoline == nil {
return // no need or no support of trampolines on this arch
}
ldr := ctxt.loader
relocs := ldr.Relocs(s)
for ri := 0; ri < relocs.Count(); ri++ {
r := relocs.At(ri)
rt := r.Type()
if !rt.IsDirectCallOrJump() && !isPLTCall(rt) {
continue
}
rs := r.Sym()
if !ldr.AttrReachable(rs) || ldr.SymType(rs) == sym.Sxxx {
continue // something is wrong. skip it here and we'll emit a better error later
}
if ldr.SymValue(rs) == 0 && ldr.SymType(rs) != sym.SDYNIMPORT && ldr.SymType(rs) != sym.SUNDEFEXT {
// Symbols in the same package are laid out together.
// Except that if SymPkg(s) == "", it is a host object symbol
// which may call an external symbol via PLT.
if ldr.SymPkg(s) != "" && ldr.SymPkg(rs) == ldr.SymPkg(s) {
// RISC-V is only able to reach +/-1MiB via a JAL instruction.
// We need to generate a trampoline when an address is
// currently unknown.
if !ctxt.Target.IsRISCV64() {
continue
}
}
// Runtime packages are laid out together.
if isRuntimeDepPkg(ldr.SymPkg(s)) && isRuntimeDepPkg(ldr.SymPkg(rs)) {
continue
}
}
thearch.Trampoline(ctxt, ldr, ri, rs, s)
}
}
// whether rt is a (host object) relocation that will be turned into
// a call to PLT.
func isPLTCall(rt objabi.RelocType) bool {
const pcrel = 1
switch rt {
// ARM64
case objabi.ElfRelocOffset + objabi.RelocType(elf.R_AARCH64_CALL26),
objabi.ElfRelocOffset + objabi.RelocType(elf.R_AARCH64_JUMP26),
objabi.MachoRelocOffset + MACHO_ARM64_RELOC_BRANCH26*2 + pcrel:
return true
// ARM
case objabi.ElfRelocOffset + objabi.RelocType(elf.R_ARM_CALL),
objabi.ElfRelocOffset + objabi.RelocType(elf.R_ARM_PC24),
objabi.ElfRelocOffset + objabi.RelocType(elf.R_ARM_JUMP24):
return true
}
// TODO: other architectures.
return false
}
// FoldSubSymbolOffset computes the offset of symbol s to its top-level outer
// symbol. Returns the top-level symbol and the offset.
// This is used in generating external relocations.
func FoldSubSymbolOffset(ldr *loader.Loader, s loader.Sym) (loader.Sym, int64) {
outer := ldr.OuterSym(s)
off := int64(0)
if outer != 0 {
off += ldr.SymValue(s) - ldr.SymValue(outer)
s = outer
}
return s, off
}
// relocsym resolve relocations in "s", updating the symbol's content
// in "P".
// The main loop walks through the list of relocations attached to "s"
// and resolves them where applicable. Relocations are often
// architecture-specific, requiring calls into the 'archreloc' and/or
// 'archrelocvariant' functions for the architecture. When external
// linking is in effect, it may not be possible to completely resolve
// the address/offset for a symbol, in which case the goal is to lay
// the groundwork for turning a given relocation into an external reloc
// (to be applied by the external linker). For more on how relocations
// work in general, see
//
// "Linkers and Loaders", by John R. Levine (Morgan Kaufmann, 1999), ch. 7
//
// This is a performance-critical function for the linker; be careful
// to avoid introducing unnecessary allocations in the main loop.
func (st *relocSymState) relocsym(s loader.Sym, P []byte) {
ldr := st.ldr
relocs := ldr.Relocs(s)
if relocs.Count() == 0 {
return
}
target := st.target
syms := st.syms
nExtReloc := 0 // number of external relocations
for ri := 0; ri < relocs.Count(); ri++ {
r := relocs.At(ri)
off := r.Off()
siz := int32(r.Siz())
rs := r.Sym()
rt := r.Type()
weak := r.Weak()
if off < 0 || off+siz > int32(len(P)) {
rname := ""
if rs != 0 {
rname = ldr.SymName(rs)
}
st.err.Errorf(s, "invalid relocation %s: %d+%d not in [%d,%d)", rname, off, siz, 0, len(P))
continue
}
if siz == 0 { // informational relocation - no work to do
continue
}
var rst sym.SymKind
if rs != 0 {
rst = ldr.SymType(rs)
}
if rs != 0 && (rst == sym.Sxxx || rst == sym.SXREF) {
// When putting the runtime but not main into a shared library
// these symbols are undefined and that's OK.
if target.IsShared() || target.IsPlugin() {
if ldr.SymName(rs) == "main.main" || (!target.IsPlugin() && ldr.SymName(rs) == "main..inittask") {
sb := ldr.MakeSymbolUpdater(rs)
sb.SetType(sym.SDYNIMPORT)
} else if strings.HasPrefix(ldr.SymName(rs), "go:info.") {
// Skip go.info symbols. They are only needed to communicate
// DWARF info between the compiler and linker.
continue
}
} else if target.IsPPC64() && ldr.SymName(rs) == ".TOC." {
// TOC symbol doesn't have a type but we do assign a value
// (see the address pass) and we can resolve it.
// TODO: give it a type.
} else {
st.err.errorUnresolved(ldr, s, rs)
continue
}
}
if rt >= objabi.ElfRelocOffset {
continue
}
// We need to be able to reference dynimport symbols when linking against
// shared libraries, and AIX, Darwin, OpenBSD and Solaris always need it.
if !target.IsAIX() && !target.IsDarwin() && !target.IsSolaris() && !target.IsOpenbsd() && rs != 0 && rst == sym.SDYNIMPORT && !target.IsDynlinkingGo() && !ldr.AttrSubSymbol(rs) {
if !(target.IsPPC64() && target.IsExternal() && ldr.SymName(rs) == ".TOC.") {
st.err.Errorf(s, "unhandled relocation for %s (type %d (%s) rtype %d (%s))", ldr.SymName(rs), rst, rst, rt, sym.RelocName(target.Arch, rt))
}
}
if rs != 0 && rst != sym.STLSBSS && !weak && rt != objabi.R_METHODOFF && !ldr.AttrReachable(rs) {
st.err.Errorf(s, "unreachable sym in relocation: %s", ldr.SymName(rs))
}
var rv sym.RelocVariant
if target.IsPPC64() || target.IsS390X() {
rv = ldr.RelocVariant(s, ri)
}
// TODO(mundaym): remove this special case - see issue 14218.
if target.IsS390X() {
switch rt {
case objabi.R_PCRELDBL:
rt = objabi.R_PCREL
rv = sym.RV_390_DBL
case objabi.R_CALL:
rv = sym.RV_390_DBL
}
}
var o int64
switch rt {
default:
switch siz {
default:
st.err.Errorf(s, "bad reloc size %#x for %s", uint32(siz), ldr.SymName(rs))
case 1:
o = int64(P[off])
case 2:
o = int64(target.Arch.ByteOrder.Uint16(P[off:]))
case 4:
o = int64(target.Arch.ByteOrder.Uint32(P[off:]))
case 8:
o = int64(target.Arch.ByteOrder.Uint64(P[off:]))
}
out, n, ok := thearch.Archreloc(target, ldr, syms, r, s, o)
if target.IsExternal() {
nExtReloc += n
}
if ok {
o = out
} else {
st.err.Errorf(s, "unknown reloc to %v: %d (%s)", ldr.SymName(rs), rt, sym.RelocName(target.Arch, rt))
}
case objabi.R_TLS_LE:
if target.IsExternal() && target.IsElf() {
nExtReloc++
o = 0
if !target.IsAMD64() {
o = r.Add()
}
break
}
if target.IsElf() && target.IsARM() {
// On ELF ARM, the thread pointer is 8 bytes before
// the start of the thread-local data block, so add 8
// to the actual TLS offset (r->sym->value).
// This 8 seems to be a fundamental constant of
// ELF on ARM (or maybe Glibc on ARM); it is not
// related to the fact that our own TLS storage happens
// to take up 8 bytes.
o = 8 + ldr.SymValue(rs)
} else if target.IsElf() || target.IsPlan9() || target.IsDarwin() {
o = int64(syms.Tlsoffset) + r.Add()
} else if target.IsWindows() {
o = r.Add()
} else {
log.Fatalf("unexpected R_TLS_LE relocation for %v", target.HeadType)
}
case objabi.R_TLS_IE:
if target.IsExternal() && target.IsElf() {
nExtReloc++
o = 0
if !target.IsAMD64() {
o = r.Add()
}
if target.Is386() {
nExtReloc++ // need two ELF relocations on 386, see ../x86/asm.go:elfreloc1
}
break
}
if target.IsPIE() && target.IsElf() {
// We are linking the final executable, so we
// can optimize any TLS IE relocation to LE.
if thearch.TLSIEtoLE == nil {
log.Fatalf("internal linking of TLS IE not supported on %v", target.Arch.Family)
}
thearch.TLSIEtoLE(P, int(off), int(siz))
o = int64(syms.Tlsoffset)
} else {
log.Fatalf("cannot handle R_TLS_IE (sym %s) when linking internally", ldr.SymName(s))
}
case objabi.R_ADDR, objabi.R_PEIMAGEOFF:
if weak && !ldr.AttrReachable(rs) {
// Redirect it to runtime.unreachableMethod, which will throw if called.
rs = syms.unreachableMethod
}
if target.IsExternal() {
nExtReloc++
// set up addend for eventual relocation via outer symbol.
rs := rs
rs, off := FoldSubSymbolOffset(ldr, rs)
xadd := r.Add() + off
rst := ldr.SymType(rs)
if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && rst != sym.SUNDEFEXT && ldr.SymSect(rs) == nil {
st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
}
o = xadd
if target.IsElf() {
if target.IsAMD64() {
o = 0
}
} else if target.IsDarwin() {
if ldr.SymType(s).IsDWARF() {
// We generally use symbol-targeted relocations.
// DWARF tools seem to only handle section-targeted relocations,
// so generate section-targeted relocations in DWARF sections.
// See also machoreloc1.
o += ldr.SymValue(rs)
}
} else if target.IsWindows() {
// nothing to do
} else if target.IsAIX() {
o = ldr.SymValue(rs) + xadd
} else {
st.err.Errorf(s, "unhandled pcrel relocation to %s on %v", ldr.SymName(rs), target.HeadType)
}
break
}
// On AIX, a second relocation must be done by the loader,
// as section addresses can change once loaded.
// The "default" symbol address is still needed by the loader so
// the current relocation can't be skipped.
if target.IsAIX() && rst != sym.SDYNIMPORT {
// It's not possible to make a loader relocation in a
// symbol which is not inside .data section.
// FIXME: It should be forbidden to have R_ADDR from a
// symbol which isn't in .data. However, as .text has the
// same address once loaded, this is possible.
if ldr.SymSect(s).Seg == &Segdata {
Xcoffadddynrel(target, ldr, syms, s, r, ri)
}
}
o = ldr.SymValue(rs) + r.Add()
if rt == objabi.R_PEIMAGEOFF {
// The R_PEIMAGEOFF offset is a RVA, so subtract
// the base address for the executable.
o -= PEBASE
}
// On amd64, 4-byte offsets will be sign-extended, so it is impossible to
// access more than 2GB of static data; fail at link time is better than
// fail at runtime. See https://golang.org/issue/7980.
// Instead of special casing only amd64, we treat this as an error on all
// 64-bit architectures so as to be future-proof.
if int32(o) < 0 && target.Arch.PtrSize > 4 && siz == 4 {
st.err.Errorf(s, "non-pc-relative relocation address for %s is too big: %#x (%#x + %#x)", ldr.SymName(rs), uint64(o), ldr.SymValue(rs), r.Add())
errorexit()
}
case objabi.R_DWARFSECREF:
if ldr.SymSect(rs) == nil {
st.err.Errorf(s, "missing DWARF section for relocation target %s", ldr.SymName(rs))
}
if target.IsExternal() {
// On most platforms, the external linker needs to adjust DWARF references
// as it combines DWARF sections. However, on Darwin, dsymutil does the
// DWARF linking, and it understands how to follow section offsets.
// Leaving in the relocation records confuses it (see
// https://golang.org/issue/22068) so drop them for Darwin.
if !target.IsDarwin() {
nExtReloc++
}
xadd := r.Add() + ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr)
o = xadd
if target.IsElf() && target.IsAMD64() {
o = 0
}
break
}
o = ldr.SymValue(rs) + r.Add() - int64(ldr.SymSect(rs).Vaddr)
case objabi.R_METHODOFF:
if !ldr.AttrReachable(rs) {
// Set it to a sentinel value. The runtime knows this is not pointing to
// anything valid.
o = -1
break
}
fallthrough
case objabi.R_ADDROFF:
if weak && !ldr.AttrReachable(rs) {
continue
}
sect := ldr.SymSect(rs)
if sect == nil {
if rst == sym.SDYNIMPORT {
st.err.Errorf(s, "cannot target DYNIMPORT sym in section-relative reloc: %s", ldr.SymName(rs))
} else if rst == sym.SUNDEFEXT {
st.err.Errorf(s, "undefined symbol in relocation: %s", ldr.SymName(rs))
} else {
st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
}
continue
}
// The method offset tables using this relocation expect the offset to be relative
// to the start of the first text section, even if there are multiple.
if sect.Name == ".text" {
o = ldr.SymValue(rs) - int64(Segtext.Sections[0].Vaddr) + r.Add()
} else {
o = ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr) + r.Add()
}
case objabi.R_ADDRCUOFF:
// debug_range and debug_loc elements use this relocation type to get an
// offset from the start of the compile unit.
o = ldr.SymValue(rs) + r.Add() - ldr.SymValue(loader.Sym(ldr.SymUnit(rs).Textp[0]))
// r.Sym() can be 0 when CALL $(constant) is transformed from absolute PC to relative PC call.
case objabi.R_GOTPCREL:
if target.IsDynlinkingGo() && target.IsDarwin() && rs != 0 {
nExtReloc++
o = r.Add()
break
}
if target.Is386() && target.IsExternal() && target.IsELF {
nExtReloc++ // need two ELF relocations on 386, see ../x86/asm.go:elfreloc1
}
fallthrough
case objabi.R_CALL, objabi.R_PCREL:
if target.IsExternal() && rs != 0 && rst == sym.SUNDEFEXT {
// pass through to the external linker.
nExtReloc++
o = 0
break
}
if target.IsExternal() && rs != 0 && (ldr.SymSect(rs) != ldr.SymSect(s) || rt == objabi.R_GOTPCREL) {
nExtReloc++
// set up addend for eventual relocation via outer symbol.
rs := rs
rs, off := FoldSubSymbolOffset(ldr, rs)
xadd := r.Add() + off - int64(siz) // relative to address after the relocated chunk
rst := ldr.SymType(rs)
if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && ldr.SymSect(rs) == nil {
st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
}
o = xadd
if target.IsElf() {
if target.IsAMD64() {
o = 0
}
} else if target.IsDarwin() {
if rt == objabi.R_CALL {
if target.IsExternal() && rst == sym.SDYNIMPORT {
if target.IsAMD64() {
// AMD64 dynamic relocations are relative to the end of the relocation.
o += int64(siz)
}
} else {
if rst != sym.SHOSTOBJ {
o += int64(uint64(ldr.SymValue(rs)) - ldr.SymSect(rs).Vaddr)
}
o -= int64(off) // relative to section offset, not symbol
}
} else {
o += int64(siz)
}
} else if target.IsWindows() && target.IsAMD64() { // only amd64 needs PCREL
// PE/COFF's PC32 relocation uses the address after the relocated
// bytes as the base. Compensate by skewing the addend.
o += int64(siz)
} else {
st.err.Errorf(s, "unhandled pcrel relocation to %s on %v", ldr.SymName(rs), target.HeadType)
}
break
}
o = 0
if rs != 0 {
o = ldr.SymValue(rs)
}
o += r.Add() - (ldr.SymValue(s) + int64(off) + int64(siz))
case objabi.R_SIZE:
o = ldr.SymSize(rs) + r.Add()
case objabi.R_XCOFFREF:
if !target.IsAIX() {
st.err.Errorf(s, "find XCOFF R_REF on non-XCOFF files")
}
if !target.IsExternal() {
st.err.Errorf(s, "find XCOFF R_REF with internal linking")
}
nExtReloc++
continue
case objabi.R_DWARFFILEREF:
// We don't renumber files in dwarf.go:writelines anymore.
continue
case objabi.R_CONST:
o = r.Add()
case objabi.R_GOTOFF:
o = ldr.SymValue(rs) + r.Add() - ldr.SymValue(syms.GOT)
}
if target.IsPPC64() || target.IsS390X() {
if rv != sym.RV_NONE {
o = thearch.Archrelocvariant(target, ldr, r, rv, s, o, P)
}
}
switch siz {
default:
st.err.Errorf(s, "bad reloc size %#x for %s", uint32(siz), ldr.SymName(rs))
case 1:
P[off] = byte(int8(o))
case 2:
if (rt == objabi.R_PCREL || rt == objabi.R_CALL) && o != int64(int16(o)) {
st.err.Errorf(s, "pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), o)
} else if o != int64(int16(o)) && o != int64(uint16(o)) {
st.err.Errorf(s, "non-pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), uint64(o))
}
target.Arch.ByteOrder.PutUint16(P[off:], uint16(o))
case 4:
if (rt == objabi.R_PCREL || rt == objabi.R_CALL) && o != int64(int32(o)) {
st.err.Errorf(s, "pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), o)
} else if o != int64(int32(o)) && o != int64(uint32(o)) {
st.err.Errorf(s, "non-pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), uint64(o))
}
target.Arch.ByteOrder.PutUint32(P[off:], uint32(o))
case 8:
target.Arch.ByteOrder.PutUint64(P[off:], uint64(o))
}
}
if target.IsExternal() {
// We'll stream out the external relocations in asmb2 (e.g. elfrelocsect)
// and we only need the count here.
atomic.AddUint32(&ldr.SymSect(s).Relcount, uint32(nExtReloc))
}
}
// Convert a Go relocation to an external relocation.
func extreloc(ctxt *Link, ldr *loader.Loader, s loader.Sym, r loader.Reloc) (loader.ExtReloc, bool) {
var rr loader.ExtReloc
target := &ctxt.Target
siz := int32(r.Siz())
if siz == 0 { // informational relocation - no work to do
return rr, false
}
rt := r.Type()
if rt >= objabi.ElfRelocOffset {
return rr, false
}
rr.Type = rt
rr.Size = uint8(siz)
// TODO(mundaym): remove this special case - see issue 14218.
if target.IsS390X() {
switch rt {
case objabi.R_PCRELDBL:
rt = objabi.R_PCREL
}
}
switch rt {
default:
return thearch.Extreloc(target, ldr, r, s)
case objabi.R_TLS_LE, objabi.R_TLS_IE:
if target.IsElf() {
rs := r.Sym()
rr.Xsym = rs
if rr.Xsym == 0 {
rr.Xsym = ctxt.Tlsg
}
rr.Xadd = r.Add()
break
}
return rr, false
case objabi.R_ADDR, objabi.R_PEIMAGEOFF:
// set up addend for eventual relocation via outer symbol.
rs := r.Sym()
if r.Weak() && !ldr.AttrReachable(rs) {
rs = ctxt.ArchSyms.unreachableMethod
}
rs, off := FoldSubSymbolOffset(ldr, rs)
rr.Xadd = r.Add() + off
rr.Xsym = rs
case objabi.R_DWARFSECREF:
// On most platforms, the external linker needs to adjust DWARF references
// as it combines DWARF sections. However, on Darwin, dsymutil does the
// DWARF linking, and it understands how to follow section offsets.
// Leaving in the relocation records confuses it (see
// https://golang.org/issue/22068) so drop them for Darwin.
if target.IsDarwin() {
return rr, false
}
rs := r.Sym()
rr.Xsym = loader.Sym(ldr.SymSect(rs).Sym)
rr.Xadd = r.Add() + ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr)
// r.Sym() can be 0 when CALL $(constant) is transformed from absolute PC to relative PC call.
case objabi.R_GOTPCREL, objabi.R_CALL, objabi.R_PCREL:
rs := r.Sym()
if rt == objabi.R_GOTPCREL && target.IsDynlinkingGo() && target.IsDarwin() && rs != 0 {
rr.Xadd = r.Add()
rr.Xadd -= int64(siz) // relative to address after the relocated chunk
rr.Xsym = rs
break
}
if rs != 0 && ldr.SymType(rs) == sym.SUNDEFEXT {
// pass through to the external linker.
rr.Xadd = 0
if target.IsElf() {
rr.Xadd -= int64(siz)
}
rr.Xsym = rs
break
}
if rs != 0 && (ldr.SymSect(rs) != ldr.SymSect(s) || rt == objabi.R_GOTPCREL) {
// set up addend for eventual relocation via outer symbol.
rs := rs
rs, off := FoldSubSymbolOffset(ldr, rs)
rr.Xadd = r.Add() + off
rr.Xadd -= int64(siz) // relative to address after the relocated chunk
rr.Xsym = rs
break
}
return rr, false
case objabi.R_XCOFFREF:
return ExtrelocSimple(ldr, r), true
// These reloc types don't need external relocations.
case objabi.R_ADDROFF, objabi.R_METHODOFF, objabi.R_ADDRCUOFF,
objabi.R_SIZE, objabi.R_CONST, objabi.R_GOTOFF:
return rr, false
}
return rr, true
}
// ExtrelocSimple creates a simple external relocation from r, with the same
// symbol and addend.
func ExtrelocSimple(ldr *loader.Loader, r loader.Reloc) loader.ExtReloc {
var rr loader.ExtReloc
rs := r.Sym()
rr.Xsym = rs
rr.Xadd = r.Add()
rr.Type = r.Type()
rr.Size = r.Siz()
return rr
}
// ExtrelocViaOuterSym creates an external relocation from r targeting the
// outer symbol and folding the subsymbol's offset into the addend.
func ExtrelocViaOuterSym(ldr *loader.Loader, r loader.Reloc, s loader.Sym) loader.ExtReloc {
// set up addend for eventual relocation via outer symbol.
var rr loader.ExtReloc
rs := r.Sym()
rs, off := FoldSubSymbolOffset(ldr, rs)
rr.Xadd = r.Add() + off
rst := ldr.SymType(rs)
if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && rst != sym.SUNDEFEXT && ldr.SymSect(rs) == nil {
ldr.Errorf(s, "missing section for %s", ldr.SymName(rs))
}
rr.Xsym = rs
rr.Type = r.Type()
rr.Size = r.Siz()
return rr
}
// relocSymState hold state information needed when making a series of
// successive calls to relocsym(). The items here are invariant
// (meaning that they are set up once initially and then don't change
// during the execution of relocsym), with the exception of a slice
// used to facilitate batch allocation of external relocations. Calls
// to relocsym happen in parallel; the assumption is that each
// parallel thread will have its own state object.
type relocSymState struct {
target *Target
ldr *loader.Loader
err *ErrorReporter
syms *ArchSyms
}
// makeRelocSymState creates a relocSymState container object to
// pass to relocsym(). If relocsym() calls happen in parallel,
// each parallel thread should have its own state object.
func (ctxt *Link) makeRelocSymState() *relocSymState {
return &relocSymState{
target: &ctxt.Target,
ldr: ctxt.loader,
err: &ctxt.ErrorReporter,
syms: &ctxt.ArchSyms,
}
}
// windynrelocsym examines a text symbol 's' and looks for relocations
// from it that correspond to references to symbols defined in DLLs,
// then fixes up those relocations as needed. A reference to a symbol
// XYZ from some DLL will fall into one of two categories: an indirect
// ref via "__imp_XYZ", or a direct ref to "XYZ". Here's an example of
// an indirect ref (this is an excerpt from objdump -ldr):
//
// 1c1: 48 89 c6 movq %rax, %rsi
// 1c4: ff 15 00 00 00 00 callq *(%rip)
// 00000000000001c6: IMAGE_REL_AMD64_REL32 __imp__errno
//
// In the assembly above, the code loads up the value of __imp_errno
// and then does an indirect call to that value.
//
// Here is what a direct reference might look like:
//
// 137: e9 20 06 00 00 jmp 0x75c <pow+0x75c>
// 13c: e8 00 00 00 00 callq 0x141 <pow+0x141>
// 000000000000013d: IMAGE_REL_AMD64_REL32 _errno
//
// The assembly below dispenses with the import symbol and just makes
// a direct call to _errno.
//
// The code below handles indirect refs by redirecting the target of
// the relocation from "__imp_XYZ" to "XYZ" (since the latter symbol
// is what the Windows loader is expected to resolve). For direct refs
// the call is redirected to a stub, where the stub first loads the
// symbol and then direct an indirect call to that value.
//
// Note that for a given symbol (as above) it is perfectly legal to
// have both direct and indirect references.
func windynrelocsym(ctxt *Link, rel *loader.SymbolBuilder, s loader.Sym) error {
var su *loader.SymbolBuilder
relocs := ctxt.loader.Relocs(s)
for ri := 0; ri < relocs.Count(); ri++ {
r := relocs.At(ri)
if r.IsMarker() {
continue // skip marker relocations
}
targ := r.Sym()
if targ == 0 {
continue
}
if !ctxt.loader.AttrReachable(targ) {
if r.Weak() {
continue
}
return fmt.Errorf("dynamic relocation to unreachable symbol %s",
ctxt.loader.SymName(targ))
}
tgot := ctxt.loader.SymGot(targ)
if tgot == loadpe.RedirectToDynImportGotToken {
// Consistency check: name should be __imp_X
sname := ctxt.loader.SymName(targ)
if !strings.HasPrefix(sname, "__imp_") {
return fmt.Errorf("internal error in windynrelocsym: redirect GOT token applied to non-import symbol %s", sname)
}
// Locate underlying symbol (which originally had type
// SDYNIMPORT but has since been retyped to SWINDOWS).
ds, err := loadpe.LookupBaseFromImport(targ, ctxt.loader, ctxt.Arch)
if err != nil {
return err
}
dstyp := ctxt.loader.SymType(ds)
if dstyp != sym.SWINDOWS {
return fmt.Errorf("internal error in windynrelocsym: underlying sym for %q has wrong type %s", sname, dstyp.String())
}
// Redirect relocation to the dynimport.
r.SetSym(ds)
continue
}
tplt := ctxt.loader.SymPlt(targ)
if tplt == loadpe.CreateImportStubPltToken {
// Consistency check: don't want to see both PLT and GOT tokens.
if tgot != -1 {
return fmt.Errorf("internal error in windynrelocsym: invalid GOT setting %d for reloc to %s", tgot, ctxt.loader.SymName(targ))
}
// make dynimport JMP table for PE object files.
tplt := int32(rel.Size())
ctxt.loader.SetPlt(targ, tplt)
if su == nil {
su = ctxt.loader.MakeSymbolUpdater(s)
}
r.SetSym(rel.Sym())
r.SetAdd(int64(tplt))
// jmp *addr
switch ctxt.Arch.Family {
default:
return fmt.Errorf("internal error in windynrelocsym: unsupported arch %v", ctxt.Arch.Family)
case sys.I386:
rel.AddUint8(0xff)
rel.AddUint8(0x25)
rel.AddAddrPlus(ctxt.Arch, targ, 0)
rel.AddUint8(0x90)
rel.AddUint8(0x90)
case sys.AMD64:
rel.AddUint8(0xff)
rel.AddUint8(0x24)
rel.AddUint8(0x25)
rel.AddAddrPlus4(ctxt.Arch, targ, 0)
rel.AddUint8(0x90)
}
} else if tplt >= 0 {
if su == nil {
su = ctxt.loader.MakeSymbolUpdater(s)
}
r.SetSym(rel.Sym())
r.SetAdd(int64(tplt))
}
}
return nil
}
// windynrelocsyms generates jump table to C library functions that will be
// added later. windynrelocsyms writes the table into .rel symbol.
func (ctxt *Link) windynrelocsyms() {
if !(ctxt.IsWindows() && iscgo && ctxt.IsInternal()) {
return
}
rel := ctxt.loader.CreateSymForUpdate(".rel", 0)
rel.SetType(sym.STEXT)
for _, s := range ctxt.Textp {
if err := windynrelocsym(ctxt, rel, s); err != nil {
ctxt.Errorf(s, "%v", err)
}
}
ctxt.Textp = append(ctxt.Textp, rel.Sym())
}
func dynrelocsym(ctxt *Link, s loader.Sym) {
target := &ctxt.Target
ldr := ctxt.loader
syms := &ctxt.ArchSyms
relocs := ldr.Relocs(s)
for ri := 0; ri < relocs.Count(); ri++ {
r := relocs.At(ri)
if r.IsMarker() {
continue // skip marker relocations
}
rSym := r.Sym()
if r.Weak() && !ldr.AttrReachable(rSym) {
continue
}
if ctxt.BuildMode == BuildModePIE && ctxt.LinkMode == LinkInternal {
// It's expected that some relocations will be done
// later by relocsym (R_TLS_LE, R_ADDROFF), so
// don't worry if Adddynrel returns false.
thearch.Adddynrel(target, ldr, syms, s, r, ri)
continue
}
if rSym != 0 && ldr.SymType(rSym) == sym.SDYNIMPORT || r.Type() >= objabi.ElfRelocOffset {
if rSym != 0 && !ldr.AttrReachable(rSym) {
ctxt.Errorf(s, "dynamic relocation to unreachable symbol %s", ldr.SymName(rSym))
}
if !thearch.Adddynrel(target, ldr, syms, s, r, ri) {
ctxt.Errorf(s, "unsupported dynamic relocation for symbol %s (type=%d (%s) stype=%d (%s))", ldr.SymName(rSym), r.Type(), sym.RelocName(ctxt.Arch, r.Type()), ldr.SymType(rSym), ldr.SymType(rSym))
}
}
}
}
func (state *dodataState) dynreloc(ctxt *Link) {
if ctxt.HeadType == objabi.Hwindows {
return
}
// -d suppresses dynamic loader format, so we may as well not
// compute these sections or mark their symbols as reachable.
if *FlagD {
return
}
for _, s := range ctxt.Textp {
dynrelocsym(ctxt, s)
}
for _, syms := range state.data {
for _, s := range syms {
dynrelocsym(ctxt, s)
}
}
if ctxt.IsELF {
elfdynhash(ctxt)
}
}
func CodeblkPad(ctxt *Link, out *OutBuf, addr int64, size int64, pad []byte) {
writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, ctxt.Textp, addr, size, pad)
}
const blockSize = 1 << 20 // 1MB chunks written at a time.
// writeBlocks writes a specified chunk of symbols to the output buffer. It
// breaks the write up into ≥blockSize chunks to write them out, and schedules
// as many goroutines as necessary to accomplish this task. This call then
// blocks, waiting on the writes to complete. Note that we use the sem parameter
// to limit the number of concurrent writes taking place.
func writeBlocks(ctxt *Link, out *OutBuf, sem chan int, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
for i, s := range syms {
if ldr.SymValue(s) >= addr && !ldr.AttrSubSymbol(s) {
syms = syms[i:]
break
}
}
var wg sync.WaitGroup
max, lastAddr, written := int64(blockSize), addr+size, int64(0)
for addr < lastAddr {
// Find the last symbol we'd write.
idx := -1
for i, s := range syms {
if ldr.AttrSubSymbol(s) {
continue
}
// If the next symbol's size would put us out of bounds on the total length,
// stop looking.