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 package ld
33
34 import (
35 "bytes"
36 "cmd/internal/gcprog"
37 "cmd/internal/objabi"
38 "cmd/internal/sys"
39 "cmd/link/internal/loader"
40 "cmd/link/internal/sym"
41 "compress/zlib"
42 "debug/elf"
43 "encoding/binary"
44 "fmt"
45 "log"
46 "os"
47 "sort"
48 "strconv"
49 "strings"
50 "sync"
51 "sync/atomic"
52 )
53
54
55 func isRuntimeDepPkg(pkg string) bool {
56 switch pkg {
57 case "runtime",
58 "sync/atomic",
59 "internal/abi",
60 "internal/bytealg",
61 "internal/cpu":
62 return true
63 }
64 return strings.HasPrefix(pkg, "runtime/internal/") && !strings.HasSuffix(pkg, "_test")
65 }
66
67
68
69
70 func maxSizeTrampolines(ctxt *Link, ldr *loader.Loader, s loader.Sym, isTramp bool) uint64 {
71
72
73 if thearch.Trampoline == nil || isTramp {
74 return 0
75 }
76
77 n := uint64(0)
78 relocs := ldr.Relocs(s)
79 for ri := 0; ri < relocs.Count(); ri++ {
80 r := relocs.At(ri)
81 if r.Type().IsDirectCallOrJump() {
82 n++
83 }
84 }
85
86 if ctxt.IsPPC64() {
87 return n * 16
88 }
89 if ctxt.IsARM64() {
90 return n * 12
91 }
92 panic("unreachable")
93 }
94
95
96
97
98
99 func trampoline(ctxt *Link, s loader.Sym) {
100 if thearch.Trampoline == nil {
101 return
102 }
103
104 ldr := ctxt.loader
105 relocs := ldr.Relocs(s)
106 for ri := 0; ri < relocs.Count(); ri++ {
107 r := relocs.At(ri)
108 rt := r.Type()
109 if !rt.IsDirectCallOrJump() && !isPLTCall(rt) {
110 continue
111 }
112 rs := r.Sym()
113 if !ldr.AttrReachable(rs) || ldr.SymType(rs) == sym.Sxxx {
114 continue
115 }
116
117
118
119
120 if ldr.SymValue(rs) == 0 && !ctxt.Target.IsRISCV64() && ldr.SymType(rs) != sym.SDYNIMPORT && ldr.SymType(rs) != sym.SUNDEFEXT {
121 if ldr.SymPkg(s) != "" && ldr.SymPkg(rs) == ldr.SymPkg(s) {
122
123
124
125 continue
126 }
127 if isRuntimeDepPkg(ldr.SymPkg(s)) && isRuntimeDepPkg(ldr.SymPkg(rs)) {
128 continue
129 }
130 }
131 thearch.Trampoline(ctxt, ldr, ri, rs, s)
132 }
133 }
134
135
136
137 func isPLTCall(rt objabi.RelocType) bool {
138 const pcrel = 1
139 switch rt {
140
141 case objabi.ElfRelocOffset + objabi.RelocType(elf.R_AARCH64_CALL26),
142 objabi.ElfRelocOffset + objabi.RelocType(elf.R_AARCH64_JUMP26),
143 objabi.MachoRelocOffset + MACHO_ARM64_RELOC_BRANCH26*2 + pcrel:
144 return true
145
146
147 case objabi.ElfRelocOffset + objabi.RelocType(elf.R_ARM_CALL),
148 objabi.ElfRelocOffset + objabi.RelocType(elf.R_ARM_PC24),
149 objabi.ElfRelocOffset + objabi.RelocType(elf.R_ARM_JUMP24):
150 return true
151 }
152
153 return false
154 }
155
156
157
158
159 func FoldSubSymbolOffset(ldr *loader.Loader, s loader.Sym) (loader.Sym, int64) {
160 outer := ldr.OuterSym(s)
161 off := int64(0)
162 if outer != 0 {
163 off += ldr.SymValue(s) - ldr.SymValue(outer)
164 s = outer
165 }
166 return s, off
167 }
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185 func (st *relocSymState) relocsym(s loader.Sym, P []byte) {
186 ldr := st.ldr
187 relocs := ldr.Relocs(s)
188 if relocs.Count() == 0 {
189 return
190 }
191 target := st.target
192 syms := st.syms
193 nExtReloc := 0
194 for ri := 0; ri < relocs.Count(); ri++ {
195 r := relocs.At(ri)
196 off := r.Off()
197 siz := int32(r.Siz())
198 rs := r.Sym()
199 rt := r.Type()
200 weak := r.Weak()
201 if off < 0 || off+siz > int32(len(P)) {
202 rname := ""
203 if rs != 0 {
204 rname = ldr.SymName(rs)
205 }
206 st.err.Errorf(s, "invalid relocation %s: %d+%d not in [%d,%d)", rname, off, siz, 0, len(P))
207 continue
208 }
209 if siz == 0 {
210 continue
211 }
212
213 var rst sym.SymKind
214 if rs != 0 {
215 rst = ldr.SymType(rs)
216 }
217
218 if rs != 0 && ((rst == sym.Sxxx && !ldr.AttrVisibilityHidden(rs)) || rst == sym.SXREF) {
219
220
221 if target.IsShared() || target.IsPlugin() {
222 if ldr.SymName(rs) == "main.main" || (!target.IsPlugin() && ldr.SymName(rs) == "main..inittask") {
223 sb := ldr.MakeSymbolUpdater(rs)
224 sb.SetType(sym.SDYNIMPORT)
225 } else if strings.HasPrefix(ldr.SymName(rs), "go.info.") {
226
227
228 continue
229 }
230 } else if target.IsPPC64() && target.IsPIE() && ldr.SymName(rs) == ".TOC." {
231
232 } else {
233 st.err.errorUnresolved(ldr, s, rs)
234 continue
235 }
236 }
237
238 if rt >= objabi.ElfRelocOffset {
239 continue
240 }
241
242
243
244 if !target.IsAIX() && !target.IsDarwin() && !target.IsSolaris() && !target.IsOpenbsd() && rs != 0 && rst == sym.SDYNIMPORT && !target.IsDynlinkingGo() && !ldr.AttrSubSymbol(rs) {
245 if !(target.IsPPC64() && target.IsExternal() && ldr.SymName(rs) == ".TOC.") {
246 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))
247 }
248 }
249 if rs != 0 && rst != sym.STLSBSS && !weak && rt != objabi.R_METHODOFF && !ldr.AttrReachable(rs) {
250 st.err.Errorf(s, "unreachable sym in relocation: %s", ldr.SymName(rs))
251 }
252
253 var rv sym.RelocVariant
254 if target.IsPPC64() || target.IsS390X() {
255 rv = ldr.RelocVariant(s, ri)
256 }
257
258
259 if target.IsS390X() {
260 switch rt {
261 case objabi.R_PCRELDBL:
262 rt = objabi.R_PCREL
263 rv = sym.RV_390_DBL
264 case objabi.R_CALL:
265 rv = sym.RV_390_DBL
266 }
267 }
268
269 var o int64
270 switch rt {
271 default:
272 switch siz {
273 default:
274 st.err.Errorf(s, "bad reloc size %#x for %s", uint32(siz), ldr.SymName(rs))
275 case 1:
276 o = int64(P[off])
277 case 2:
278 o = int64(target.Arch.ByteOrder.Uint16(P[off:]))
279 case 4:
280 o = int64(target.Arch.ByteOrder.Uint32(P[off:]))
281 case 8:
282 o = int64(target.Arch.ByteOrder.Uint64(P[off:]))
283 }
284 out, n, ok := thearch.Archreloc(target, ldr, syms, r, s, o)
285 if target.IsExternal() {
286 nExtReloc += n
287 }
288 if ok {
289 o = out
290 } else {
291 st.err.Errorf(s, "unknown reloc to %v: %d (%s)", ldr.SymName(rs), rt, sym.RelocName(target.Arch, rt))
292 }
293 case objabi.R_TLS_LE:
294 if target.IsExternal() && target.IsElf() {
295 nExtReloc++
296 o = 0
297 if !target.IsAMD64() {
298 o = r.Add()
299 }
300 break
301 }
302
303 if target.IsElf() && target.IsARM() {
304
305
306
307
308
309
310
311 o = 8 + ldr.SymValue(rs)
312 } else if target.IsElf() || target.IsPlan9() || target.IsDarwin() {
313 o = int64(syms.Tlsoffset) + r.Add()
314 } else if target.IsWindows() {
315 o = r.Add()
316 } else {
317 log.Fatalf("unexpected R_TLS_LE relocation for %v", target.HeadType)
318 }
319 case objabi.R_TLS_IE:
320 if target.IsExternal() && target.IsElf() {
321 nExtReloc++
322 o = 0
323 if !target.IsAMD64() {
324 o = r.Add()
325 }
326 if target.Is386() {
327 nExtReloc++
328 }
329 break
330 }
331 if target.IsPIE() && target.IsElf() {
332
333
334 if thearch.TLSIEtoLE == nil {
335 log.Fatalf("internal linking of TLS IE not supported on %v", target.Arch.Family)
336 }
337 thearch.TLSIEtoLE(P, int(off), int(siz))
338 o = int64(syms.Tlsoffset)
339 } else {
340 log.Fatalf("cannot handle R_TLS_IE (sym %s) when linking internally", ldr.SymName(s))
341 }
342 case objabi.R_ADDR:
343 if weak && !ldr.AttrReachable(rs) {
344
345 rs = syms.unreachableMethod
346 }
347 if target.IsExternal() {
348 nExtReloc++
349
350
351 rs := rs
352 rs, off := FoldSubSymbolOffset(ldr, rs)
353 xadd := r.Add() + off
354 rst := ldr.SymType(rs)
355 if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && rst != sym.SUNDEFEXT && ldr.SymSect(rs) == nil {
356 st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
357 }
358
359 o = xadd
360 if target.IsElf() {
361 if target.IsAMD64() {
362 o = 0
363 }
364 } else if target.IsDarwin() {
365 if ldr.SymType(rs) != sym.SHOSTOBJ {
366 o += ldr.SymValue(rs)
367 }
368 } else if target.IsWindows() {
369
370 } else if target.IsAIX() {
371 o = ldr.SymValue(rs) + xadd
372 } else {
373 st.err.Errorf(s, "unhandled pcrel relocation to %s on %v", ldr.SymName(rs), target.HeadType)
374 }
375
376 break
377 }
378
379
380
381
382
383 if target.IsAIX() && rst != sym.SDYNIMPORT {
384
385
386
387
388
389 if ldr.SymSect(s).Seg == &Segdata {
390 Xcoffadddynrel(target, ldr, syms, s, r, ri)
391 }
392 }
393
394 o = ldr.SymValue(rs) + r.Add()
395
396
397
398
399
400
401 if int32(o) < 0 && target.Arch.PtrSize > 4 && siz == 4 {
402 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())
403 errorexit()
404 }
405 case objabi.R_DWARFSECREF:
406 if ldr.SymSect(rs) == nil {
407 st.err.Errorf(s, "missing DWARF section for relocation target %s", ldr.SymName(rs))
408 }
409
410 if target.IsExternal() {
411
412
413
414
415
416 if !target.IsDarwin() {
417 nExtReloc++
418 }
419
420 xadd := r.Add() + ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr)
421
422 o = xadd
423 if target.IsElf() && target.IsAMD64() {
424 o = 0
425 }
426 break
427 }
428 o = ldr.SymValue(rs) + r.Add() - int64(ldr.SymSect(rs).Vaddr)
429 case objabi.R_METHODOFF:
430 if !ldr.AttrReachable(rs) {
431
432
433 o = -1
434 break
435 }
436 fallthrough
437 case objabi.R_ADDROFF:
438 if weak && !ldr.AttrReachable(rs) {
439 continue
440 }
441 if ldr.SymSect(rs) == nil {
442 st.err.Errorf(s, "unreachable sym in relocation: %s", ldr.SymName(rs))
443 continue
444 }
445
446
447
448 if ldr.SymSect(rs).Name == ".text" {
449 o = ldr.SymValue(rs) - int64(Segtext.Sections[0].Vaddr) + r.Add()
450 } else {
451 o = ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr) + r.Add()
452 }
453
454 case objabi.R_ADDRCUOFF:
455
456
457 o = ldr.SymValue(rs) + r.Add() - ldr.SymValue(loader.Sym(ldr.SymUnit(rs).Textp[0]))
458
459
460 case objabi.R_GOTPCREL:
461 if target.IsDynlinkingGo() && target.IsDarwin() && rs != 0 {
462 nExtReloc++
463 o = r.Add()
464 break
465 }
466 if target.Is386() && target.IsExternal() && target.IsELF {
467 nExtReloc++
468 }
469 fallthrough
470 case objabi.R_CALL, objabi.R_PCREL:
471 if target.IsExternal() && rs != 0 && rst == sym.SUNDEFEXT {
472
473 nExtReloc++
474 o = 0
475 break
476 }
477 if target.IsExternal() && rs != 0 && (ldr.SymSect(rs) != ldr.SymSect(s) || rt == objabi.R_GOTPCREL) {
478 nExtReloc++
479
480
481 rs := rs
482 rs, off := FoldSubSymbolOffset(ldr, rs)
483 xadd := r.Add() + off - int64(siz)
484 rst := ldr.SymType(rs)
485 if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && ldr.SymSect(rs) == nil {
486 st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
487 }
488
489 o = xadd
490 if target.IsElf() {
491 if target.IsAMD64() {
492 o = 0
493 }
494 } else if target.IsDarwin() {
495 if rt == objabi.R_CALL {
496 if target.IsExternal() && rst == sym.SDYNIMPORT {
497 if target.IsAMD64() {
498
499 o += int64(siz)
500 }
501 } else {
502 if rst != sym.SHOSTOBJ {
503 o += int64(uint64(ldr.SymValue(rs)) - ldr.SymSect(rs).Vaddr)
504 }
505 o -= int64(off)
506 }
507 } else {
508 o += int64(siz)
509 }
510 } else if target.IsWindows() && target.IsAMD64() {
511
512
513 o += int64(siz)
514 } else {
515 st.err.Errorf(s, "unhandled pcrel relocation to %s on %v", ldr.SymName(rs), target.HeadType)
516 }
517
518 break
519 }
520
521 o = 0
522 if rs != 0 {
523 o = ldr.SymValue(rs)
524 }
525
526 o += r.Add() - (ldr.SymValue(s) + int64(off) + int64(siz))
527 case objabi.R_SIZE:
528 o = ldr.SymSize(rs) + r.Add()
529
530 case objabi.R_XCOFFREF:
531 if !target.IsAIX() {
532 st.err.Errorf(s, "find XCOFF R_REF on non-XCOFF files")
533 }
534 if !target.IsExternal() {
535 st.err.Errorf(s, "find XCOFF R_REF with internal linking")
536 }
537 nExtReloc++
538 continue
539
540 case objabi.R_DWARFFILEREF:
541
542 continue
543
544 case objabi.R_CONST:
545 o = r.Add()
546
547 case objabi.R_GOTOFF:
548 o = ldr.SymValue(rs) + r.Add() - ldr.SymValue(syms.GOT)
549 }
550
551 if target.IsPPC64() || target.IsS390X() {
552 if rv != sym.RV_NONE {
553 o = thearch.Archrelocvariant(target, ldr, r, rv, s, o, P)
554 }
555 }
556
557 switch siz {
558 default:
559 st.err.Errorf(s, "bad reloc size %#x for %s", uint32(siz), ldr.SymName(rs))
560 case 1:
561 P[off] = byte(int8(o))
562 case 2:
563 if o != int64(int16(o)) {
564 st.err.Errorf(s, "relocation address for %s is too big: %#x", ldr.SymName(rs), o)
565 }
566 target.Arch.ByteOrder.PutUint16(P[off:], uint16(o))
567 case 4:
568 if rt == objabi.R_PCREL || rt == objabi.R_CALL {
569 if o != int64(int32(o)) {
570 st.err.Errorf(s, "pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), o)
571 }
572 } else {
573 if o != int64(int32(o)) && o != int64(uint32(o)) {
574 st.err.Errorf(s, "non-pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), uint64(o))
575 }
576 }
577 target.Arch.ByteOrder.PutUint32(P[off:], uint32(o))
578 case 8:
579 target.Arch.ByteOrder.PutUint64(P[off:], uint64(o))
580 }
581 }
582 if target.IsExternal() {
583
584
585 atomic.AddUint32(&ldr.SymSect(s).Relcount, uint32(nExtReloc))
586 }
587 }
588
589
590 func extreloc(ctxt *Link, ldr *loader.Loader, s loader.Sym, r loader.Reloc) (loader.ExtReloc, bool) {
591 var rr loader.ExtReloc
592 target := &ctxt.Target
593 siz := int32(r.Siz())
594 if siz == 0 {
595 return rr, false
596 }
597
598 rt := r.Type()
599 if rt >= objabi.ElfRelocOffset {
600 return rr, false
601 }
602 rr.Type = rt
603 rr.Size = uint8(siz)
604
605
606 if target.IsS390X() {
607 switch rt {
608 case objabi.R_PCRELDBL:
609 rt = objabi.R_PCREL
610 }
611 }
612
613 switch rt {
614 default:
615 return thearch.Extreloc(target, ldr, r, s)
616
617 case objabi.R_TLS_LE, objabi.R_TLS_IE:
618 if target.IsElf() {
619 rs := r.Sym()
620 rr.Xsym = rs
621 if rr.Xsym == 0 {
622 rr.Xsym = ctxt.Tlsg
623 }
624 rr.Xadd = r.Add()
625 break
626 }
627 return rr, false
628
629 case objabi.R_ADDR:
630
631 rs := r.Sym()
632 if r.Weak() && !ldr.AttrReachable(rs) {
633 rs = ctxt.ArchSyms.unreachableMethod
634 }
635 rs, off := FoldSubSymbolOffset(ldr, rs)
636 rr.Xadd = r.Add() + off
637 rr.Xsym = rs
638
639 case objabi.R_DWARFSECREF:
640
641
642
643
644
645 if target.IsDarwin() {
646 return rr, false
647 }
648 rs := r.Sym()
649 rr.Xsym = loader.Sym(ldr.SymSect(rs).Sym)
650 rr.Xadd = r.Add() + ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr)
651
652
653 case objabi.R_GOTPCREL, objabi.R_CALL, objabi.R_PCREL:
654 rs := r.Sym()
655 if rt == objabi.R_GOTPCREL && target.IsDynlinkingGo() && target.IsDarwin() && rs != 0 {
656 rr.Xadd = r.Add()
657 rr.Xadd -= int64(siz)
658 rr.Xsym = rs
659 break
660 }
661 if rs != 0 && ldr.SymType(rs) == sym.SUNDEFEXT {
662
663 rr.Xadd = 0
664 if target.IsElf() {
665 rr.Xadd -= int64(siz)
666 }
667 rr.Xsym = rs
668 break
669 }
670 if rs != 0 && (ldr.SymSect(rs) != ldr.SymSect(s) || rt == objabi.R_GOTPCREL) {
671
672 rs := rs
673 rs, off := FoldSubSymbolOffset(ldr, rs)
674 rr.Xadd = r.Add() + off
675 rr.Xadd -= int64(siz)
676 rr.Xsym = rs
677 break
678 }
679 return rr, false
680
681 case objabi.R_XCOFFREF:
682 return ExtrelocSimple(ldr, r), true
683
684
685 case objabi.R_ADDROFF, objabi.R_METHODOFF, objabi.R_ADDRCUOFF,
686 objabi.R_SIZE, objabi.R_CONST, objabi.R_GOTOFF:
687 return rr, false
688 }
689 return rr, true
690 }
691
692
693
694 func ExtrelocSimple(ldr *loader.Loader, r loader.Reloc) loader.ExtReloc {
695 var rr loader.ExtReloc
696 rs := r.Sym()
697 rr.Xsym = rs
698 rr.Xadd = r.Add()
699 rr.Type = r.Type()
700 rr.Size = r.Siz()
701 return rr
702 }
703
704
705
706 func ExtrelocViaOuterSym(ldr *loader.Loader, r loader.Reloc, s loader.Sym) loader.ExtReloc {
707
708 var rr loader.ExtReloc
709 rs := r.Sym()
710 rs, off := FoldSubSymbolOffset(ldr, rs)
711 rr.Xadd = r.Add() + off
712 rst := ldr.SymType(rs)
713 if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && rst != sym.SUNDEFEXT && ldr.SymSect(rs) == nil {
714 ldr.Errorf(s, "missing section for %s", ldr.SymName(rs))
715 }
716 rr.Xsym = rs
717 rr.Type = r.Type()
718 rr.Size = r.Siz()
719 return rr
720 }
721
722
723
724
725
726
727
728
729 type relocSymState struct {
730 target *Target
731 ldr *loader.Loader
732 err *ErrorReporter
733 syms *ArchSyms
734 }
735
736
737
738
739 func (ctxt *Link) makeRelocSymState() *relocSymState {
740 return &relocSymState{
741 target: &ctxt.Target,
742 ldr: ctxt.loader,
743 err: &ctxt.ErrorReporter,
744 syms: &ctxt.ArchSyms,
745 }
746 }
747
748 func windynrelocsym(ctxt *Link, rel *loader.SymbolBuilder, s loader.Sym) {
749 var su *loader.SymbolBuilder
750 relocs := ctxt.loader.Relocs(s)
751 for ri := 0; ri < relocs.Count(); ri++ {
752 r := relocs.At(ri)
753 if r.IsMarker() {
754 continue
755 }
756 targ := r.Sym()
757 if targ == 0 {
758 continue
759 }
760 if !ctxt.loader.AttrReachable(targ) {
761 if r.Weak() {
762 continue
763 }
764 ctxt.Errorf(s, "dynamic relocation to unreachable symbol %s",
765 ctxt.loader.SymName(targ))
766 }
767
768 tplt := ctxt.loader.SymPlt(targ)
769 tgot := ctxt.loader.SymGot(targ)
770 if tplt == -2 && tgot != -2 {
771 tplt := int32(rel.Size())
772 ctxt.loader.SetPlt(targ, tplt)
773
774 if su == nil {
775 su = ctxt.loader.MakeSymbolUpdater(s)
776 }
777 r.SetSym(rel.Sym())
778 r.SetAdd(int64(tplt))
779
780
781 switch ctxt.Arch.Family {
782 default:
783 ctxt.Errorf(s, "unsupported arch %v", ctxt.Arch.Family)
784 return
785 case sys.I386:
786 rel.AddUint8(0xff)
787 rel.AddUint8(0x25)
788 rel.AddAddrPlus(ctxt.Arch, targ, 0)
789 rel.AddUint8(0x90)
790 rel.AddUint8(0x90)
791 case sys.AMD64:
792 rel.AddUint8(0xff)
793 rel.AddUint8(0x24)
794 rel.AddUint8(0x25)
795 rel.AddAddrPlus4(ctxt.Arch, targ, 0)
796 rel.AddUint8(0x90)
797 }
798 } else if tplt >= 0 {
799 if su == nil {
800 su = ctxt.loader.MakeSymbolUpdater(s)
801 }
802 r.SetSym(rel.Sym())
803 r.SetAdd(int64(tplt))
804 }
805 }
806 }
807
808
809
810 func (ctxt *Link) windynrelocsyms() {
811 if !(ctxt.IsWindows() && iscgo && ctxt.IsInternal()) {
812 return
813 }
814
815 rel := ctxt.loader.CreateSymForUpdate(".rel", 0)
816 rel.SetType(sym.STEXT)
817
818 for _, s := range ctxt.Textp {
819 windynrelocsym(ctxt, rel, s)
820 }
821
822 ctxt.Textp = append(ctxt.Textp, rel.Sym())
823 }
824
825 func dynrelocsym(ctxt *Link, s loader.Sym) {
826 target := &ctxt.Target
827 ldr := ctxt.loader
828 syms := &ctxt.ArchSyms
829 relocs := ldr.Relocs(s)
830 for ri := 0; ri < relocs.Count(); ri++ {
831 r := relocs.At(ri)
832 if r.IsMarker() {
833 continue
834 }
835 rSym := r.Sym()
836 if r.Weak() && !ldr.AttrReachable(rSym) {
837 continue
838 }
839 if ctxt.BuildMode == BuildModePIE && ctxt.LinkMode == LinkInternal {
840
841
842
843 thearch.Adddynrel(target, ldr, syms, s, r, ri)
844 continue
845 }
846
847 if rSym != 0 && ldr.SymType(rSym) == sym.SDYNIMPORT || r.Type() >= objabi.ElfRelocOffset {
848 if rSym != 0 && !ldr.AttrReachable(rSym) {
849 ctxt.Errorf(s, "dynamic relocation to unreachable symbol %s", ldr.SymName(rSym))
850 }
851 if !thearch.Adddynrel(target, ldr, syms, s, r, ri) {
852 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))
853 }
854 }
855 }
856 }
857
858 func (state *dodataState) dynreloc(ctxt *Link) {
859 if ctxt.HeadType == objabi.Hwindows {
860 return
861 }
862
863
864 if *FlagD {
865 return
866 }
867
868 for _, s := range ctxt.Textp {
869 dynrelocsym(ctxt, s)
870 }
871 for _, syms := range state.data {
872 for _, s := range syms {
873 dynrelocsym(ctxt, s)
874 }
875 }
876 if ctxt.IsELF {
877 elfdynhash(ctxt)
878 }
879 }
880
881 func CodeblkPad(ctxt *Link, out *OutBuf, addr int64, size int64, pad []byte) {
882 writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, ctxt.Textp, addr, size, pad)
883 }
884
885 const blockSize = 1 << 20
886
887
888
889
890
891
892 func writeBlocks(ctxt *Link, out *OutBuf, sem chan int, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
893 for i, s := range syms {
894 if ldr.SymValue(s) >= addr && !ldr.AttrSubSymbol(s) {
895 syms = syms[i:]
896 break
897 }
898 }
899
900 var wg sync.WaitGroup
901 max, lastAddr, written := int64(blockSize), addr+size, int64(0)
902 for addr < lastAddr {
903
904 idx := -1
905 for i, s := range syms {
906 if ldr.AttrSubSymbol(s) {
907 continue
908 }
909
910
911
912 end := ldr.SymValue(s) + ldr.SymSize(s)
913 if end > lastAddr {
914 break
915 }
916
917
918 idx = i
919
920
921 if end > addr+max {
922 break
923 }
924 }
925
926
927 if idx < 0 {
928 break
929 }
930
931
932
933
934
935
936 length := int64(0)
937 if idx+1 < len(syms) {
938
939
940
941 next := syms[idx+1]
942 for ldr.AttrSubSymbol(next) {
943 idx++
944 next = syms[idx+1]
945 }
946 length = ldr.SymValue(next) - addr
947 }
948 if length == 0 || length > lastAddr-addr {
949 length = lastAddr - addr
950 }
951
952
953 if o, err := out.View(uint64(out.Offset() + written)); err == nil {
954 sem <- 1
955 wg.Add(1)
956 go func(o *OutBuf, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
957 writeBlock(ctxt, o, ldr, syms, addr, size, pad)
958 wg.Done()
959 <-sem
960 }(o, ldr, syms, addr, length, pad)
961 } else {
962 writeBlock(ctxt, out, ldr, syms, addr, length, pad)
963 }
964
965
966 if idx != -1 {
967 syms = syms[idx+1:]
968 }
969 written += length
970 addr += length
971 }
972 wg.Wait()
973 }
974
975 func writeBlock(ctxt *Link, out *OutBuf, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
976
977 st := ctxt.makeRelocSymState()
978
979
980
981
982
983 eaddr := addr + size
984 for _, s := range syms {
985 if ldr.AttrSubSymbol(s) {
986 continue
987 }
988 val := ldr.SymValue(s)
989 if val >= eaddr {
990 break
991 }
992 if val < addr {
993 ldr.Errorf(s, "phase error: addr=%#x but sym=%#x type=%v sect=%v", addr, val, ldr.SymType(s), ldr.SymSect(s).Name)
994 errorexit()
995 }
996 if addr < val {
997 out.WriteStringPad("", int(val-addr), pad)
998 addr = val
999 }
1000 P := out.WriteSym(ldr, s)
1001 st.relocsym(s, P)
1002 if f, ok := ctxt.generatorSyms[s]; ok {
1003 f(ctxt, s)
1004 }
1005 addr += int64(len(P))
1006 siz := ldr.SymSize(s)
1007 if addr < val+siz {
1008 out.WriteStringPad("", int(val+siz-addr), pad)
1009 addr = val + siz
1010 }
1011 if addr != val+siz {
1012 ldr.Errorf(s, "phase error: addr=%#x value+size=%#x", addr, val+siz)
1013 errorexit()
1014 }
1015 if val+siz >= eaddr {
1016 break
1017 }
1018 }
1019
1020 if addr < eaddr {
1021 out.WriteStringPad("", int(eaddr-addr), pad)
1022 }
1023 }
1024
1025 type writeFn func(*Link, *OutBuf, int64, int64)
1026
1027
1028 func writeParallel(wg *sync.WaitGroup, fn writeFn, ctxt *Link, seek, vaddr, length uint64) {
1029 if out, err := ctxt.Out.View(seek); err != nil {
1030 ctxt.Out.SeekSet(int64(seek))
1031 fn(ctxt, ctxt.Out, int64(vaddr), int64(length))
1032 } else {
1033 wg.Add(1)
1034 go func() {
1035 defer wg.Done()
1036 fn(ctxt, out, int64(vaddr), int64(length))
1037 }()
1038 }
1039 }
1040
1041 func datblk(ctxt *Link, out *OutBuf, addr, size int64) {
1042 writeDatblkToOutBuf(ctxt, out, addr, size)
1043 }
1044
1045
1046 func DatblkBytes(ctxt *Link, addr int64, size int64) []byte {
1047 buf := make([]byte, size)
1048 out := &OutBuf{heap: buf}
1049 writeDatblkToOutBuf(ctxt, out, addr, size)
1050 return buf
1051 }
1052
1053 func writeDatblkToOutBuf(ctxt *Link, out *OutBuf, addr int64, size int64) {
1054 writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, ctxt.datap, addr, size, zeros[:])
1055 }
1056
1057 func dwarfblk(ctxt *Link, out *OutBuf, addr int64, size int64) {
1058
1059
1060
1061
1062
1063
1064 n := 0
1065 for i := range dwarfp {
1066 n += len(dwarfp[i].syms)
1067 }
1068 syms := make([]loader.Sym, 0, n)
1069 for i := range dwarfp {
1070 syms = append(syms, dwarfp[i].syms...)
1071 }
1072 writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, syms, addr, size, zeros[:])
1073 }
1074
1075 var zeros [512]byte
1076
1077 var (
1078 strdata = make(map[string]string)
1079 strnames []string
1080 )
1081
1082 func addstrdata1(ctxt *Link, arg string) {
1083 eq := strings.Index(arg, "=")
1084 dot := strings.LastIndex(arg[:eq+1], ".")
1085 if eq < 0 || dot < 0 {
1086 Exitf("-X flag requires argument of the form importpath.name=value")
1087 }
1088 pkg := arg[:dot]
1089 if ctxt.BuildMode == BuildModePlugin && pkg == "main" {
1090 pkg = *flagPluginPath
1091 }
1092 pkg = objabi.PathToPrefix(pkg)
1093 name := pkg + arg[dot:eq]
1094 value := arg[eq+1:]
1095 if _, ok := strdata[name]; !ok {
1096 strnames = append(strnames, name)
1097 }
1098 strdata[name] = value
1099 }
1100
1101
1102 func addstrdata(arch *sys.Arch, l *loader.Loader, name, value string) {
1103 s := l.Lookup(name, 0)
1104 if s == 0 {
1105 return
1106 }
1107 if goType := l.SymGoType(s); goType == 0 {
1108 return
1109 } else if typeName := l.SymName(goType); typeName != "type.string" {
1110 Errorf(nil, "%s: cannot set with -X: not a var of type string (%s)", name, typeName)
1111 return
1112 }
1113 if !l.AttrReachable(s) {
1114 return
1115 }
1116 bld := l.MakeSymbolUpdater(s)
1117 if bld.Type() == sym.SBSS {
1118 bld.SetType(sym.SDATA)
1119 }
1120
1121 p := fmt.Sprintf("%s.str", name)
1122 sbld := l.CreateSymForUpdate(p, 0)
1123 sbld.Addstring(value)
1124 sbld.SetType(sym.SRODATA)
1125
1126 bld.SetSize(0)
1127 bld.SetData(make([]byte, 0, arch.PtrSize*2))
1128 bld.SetReadOnly(false)
1129 bld.ResetRelocs()
1130 bld.AddAddrPlus(arch, sbld.Sym(), 0)
1131 bld.AddUint(arch, uint64(len(value)))
1132 }
1133
1134 func (ctxt *Link) dostrdata() {
1135 for _, name := range strnames {
1136 addstrdata(ctxt.Arch, ctxt.loader, name, strdata[name])
1137 }
1138 }
1139
1140
1141
1142 func addgostring(ctxt *Link, ldr *loader.Loader, s *loader.SymbolBuilder, symname, str string) {
1143 sdata := ldr.CreateSymForUpdate(symname, 0)
1144 if sdata.Type() != sym.Sxxx {
1145 ctxt.Errorf(s.Sym(), "duplicate symname in addgostring: %s", symname)
1146 }
1147 sdata.SetLocal(true)
1148 sdata.SetType(sym.SRODATA)
1149 sdata.SetSize(int64(len(str)))
1150 sdata.SetData([]byte(str))
1151 s.AddAddr(ctxt.Arch, sdata.Sym())
1152 s.AddUint(ctxt.Arch, uint64(len(str)))
1153 }
1154
1155 func addinitarrdata(ctxt *Link, ldr *loader.Loader, s loader.Sym) {
1156 p := ldr.SymName(s) + ".ptr"
1157 sp := ldr.CreateSymForUpdate(p, 0)
1158 sp.SetType(sym.SINITARR)
1159 sp.SetSize(0)
1160 sp.SetDuplicateOK(true)
1161 sp.AddAddr(ctxt.Arch, s)
1162 }
1163
1164
1165 func symalign(ldr *loader.Loader, s loader.Sym) int32 {
1166 min := int32(thearch.Minalign)
1167 align := ldr.SymAlign(s)
1168 if align >= min {
1169 return align
1170 } else if align != 0 {
1171 return min
1172 }
1173 align = int32(thearch.Maxalign)
1174 ssz := ldr.SymSize(s)
1175 for int64(align) > ssz && align > min {
1176 align >>= 1
1177 }
1178 ldr.SetSymAlign(s, align)
1179 return align
1180 }
1181
1182 func aligndatsize(state *dodataState, datsize int64, s loader.Sym) int64 {
1183 return Rnd(datsize, int64(symalign(state.ctxt.loader, s)))
1184 }
1185
1186 const debugGCProg = false
1187
1188 type GCProg struct {
1189 ctxt *Link
1190 sym *loader.SymbolBuilder
1191 w gcprog.Writer
1192 }
1193
1194 func (p *GCProg) Init(ctxt *Link, name string) {
1195 p.ctxt = ctxt
1196 p.sym = ctxt.loader.CreateSymForUpdate(name, 0)
1197 p.w.Init(p.writeByte())
1198 if debugGCProg {
1199 fmt.Fprintf(os.Stderr, "ld: start GCProg %s\n", name)
1200 p.w.Debug(os.Stderr)
1201 }
1202 }
1203
1204 func (p *GCProg) writeByte() func(x byte) {
1205 return func(x byte) {
1206 p.sym.AddUint8(x)
1207 }
1208 }
1209
1210 func (p *GCProg) End(size int64) {
1211 p.w.ZeroUntil(size / int64(p.ctxt.Arch.PtrSize))
1212 p.w.End()
1213 if debugGCProg {
1214 fmt.Fprintf(os.Stderr, "ld: end GCProg\n")
1215 }
1216 }
1217
1218 func (p *GCProg) AddSym(s loader.Sym) {
1219 ldr := p.ctxt.loader
1220 typ := ldr.SymGoType(s)
1221
1222
1223
1224 if typ == 0 {
1225 switch ldr.SymName(s) {
1226 case "runtime.data", "runtime.edata", "runtime.bss", "runtime.ebss":
1227
1228
1229
1230 return
1231 }
1232 p.ctxt.Errorf(p.sym.Sym(), "missing Go type information for global symbol %s: size %d", ldr.SymName(s), ldr.SymSize(s))
1233 return
1234 }
1235
1236 ptrsize := int64(p.ctxt.Arch.PtrSize)
1237 typData := ldr.Data(typ)
1238 nptr := decodetypePtrdata(p.ctxt.Arch, typData) / ptrsize
1239
1240 if debugGCProg {
1241 fmt.Fprintf(os.Stderr, "gcprog sym: %s at %d (ptr=%d+%d)\n", ldr.SymName(s), ldr.SymValue(s), ldr.SymValue(s)/ptrsize, nptr)
1242 }
1243
1244 sval := ldr.SymValue(s)
1245 if decodetypeUsegcprog(p.ctxt.Arch, typData) == 0 {
1246
1247 mask := decodetypeGcmask(p.ctxt, typ)
1248 for i := int64(0); i < nptr; i++ {
1249 if (mask[i/8]>>uint(i%8))&1 != 0 {
1250 p.w.Ptr(sval/ptrsize + i)
1251 }
1252 }
1253 return
1254 }
1255
1256
1257 prog := decodetypeGcprog(p.ctxt, typ)
1258 p.w.ZeroUntil(sval / ptrsize)
1259 p.w.Append(prog[4:], nptr)
1260 }
1261
1262
1263
1264 const cutoff = 2e9
1265
1266 func (state *dodataState) checkdatsize(symn sym.SymKind) {
1267 if state.datsize > cutoff {
1268 Errorf(nil, "too much data in section %v (over %v bytes)", symn, cutoff)
1269 }
1270 }
1271
1272
1273 func fixZeroSizedSymbols(ctxt *Link) {
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297 if !(ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin) && !(ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal) {
1298 return
1299 }
1300
1301 ldr := ctxt.loader
1302 bss := ldr.CreateSymForUpdate("runtime.bss", 0)
1303 bss.SetSize(8)
1304 ldr.SetAttrSpecial(bss.Sym(), false)
1305
1306 ebss := ldr.CreateSymForUpdate("runtime.ebss", 0)
1307 ldr.SetAttrSpecial(ebss.Sym(), false)
1308
1309 data := ldr.CreateSymForUpdate("runtime.data", 0)
1310 data.SetSize(8)
1311 ldr.SetAttrSpecial(data.Sym(), false)
1312
1313 edata := ldr.CreateSymForUpdate("runtime.edata", 0)
1314 ldr.SetAttrSpecial(edata.Sym(), false)
1315
1316 if ctxt.HeadType == objabi.Haix {
1317
1318 edata.SetType(sym.SXCOFFTOC)
1319 }
1320
1321 types := ldr.CreateSymForUpdate("runtime.types", 0)
1322 types.SetType(sym.STYPE)
1323 types.SetSize(8)
1324 ldr.SetAttrSpecial(types.Sym(), false)
1325
1326 etypes := ldr.CreateSymForUpdate("runtime.etypes", 0)
1327 etypes.SetType(sym.SFUNCTAB)
1328 ldr.SetAttrSpecial(etypes.Sym(), false)
1329
1330 if ctxt.HeadType == objabi.Haix {
1331 rodata := ldr.CreateSymForUpdate("runtime.rodata", 0)
1332 rodata.SetType(sym.SSTRING)
1333 rodata.SetSize(8)
1334 ldr.SetAttrSpecial(rodata.Sym(), false)
1335
1336 erodata := ldr.CreateSymForUpdate("runtime.erodata", 0)
1337 ldr.SetAttrSpecial(erodata.Sym(), false)
1338 }
1339 }
1340
1341
1342 func (state *dodataState) makeRelroForSharedLib(target *Link) {
1343 if !target.UseRelro() {
1344 return
1345 }
1346
1347
1348
1349
1350 ldr := target.loader
1351 for _, symnro := range sym.ReadOnly {
1352 symnrelro := sym.RelROMap[symnro]
1353
1354 ro := []loader.Sym{}
1355 relro := state.data[symnrelro]
1356
1357 for _, s := range state.data[symnro] {
1358 relocs := ldr.Relocs(s)
1359 isRelro := relocs.Count() > 0
1360 switch state.symType(s) {
1361 case sym.STYPE, sym.STYPERELRO, sym.SGOFUNCRELRO:
1362
1363
1364
1365 isRelro = true
1366 case sym.SFUNCTAB:
1367 if ldr.SymName(s) == "runtime.etypes" {
1368
1369
1370 isRelro = true
1371 }
1372 case sym.SGOFUNC:
1373
1374
1375
1376 isRelro = false
1377 }
1378 if isRelro {
1379 state.setSymType(s, symnrelro)
1380 if outer := ldr.OuterSym(s); outer != 0 {
1381 state.setSymType(outer, symnrelro)
1382 }
1383 relro = append(relro, s)
1384 } else {
1385 ro = append(ro, s)
1386 }
1387 }
1388
1389
1390
1391
1392
1393 for _, s := range relro {
1394 if outer := ldr.OuterSym(s); outer != 0 {
1395 st := state.symType(s)
1396 ost := state.symType(outer)
1397 if st != ost {
1398 state.ctxt.Errorf(s, "inconsistent types for symbol and its Outer %s (%v != %v)",
1399 ldr.SymName(outer), st, ost)
1400 }
1401 }
1402 }
1403
1404 state.data[symnro] = ro
1405 state.data[symnrelro] = relro
1406 }
1407 }
1408
1409
1410
1411
1412 type dodataState struct {
1413
1414 ctxt *Link
1415
1416 data [sym.SXREF][]loader.Sym
1417
1418 dataMaxAlign [sym.SXREF]int32
1419
1420 symGroupType []sym.SymKind
1421
1422 datsize int64
1423 }
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437 func (state *dodataState) symType(s loader.Sym) sym.SymKind {
1438 if int(s) < len(state.symGroupType) {
1439 if override := state.symGroupType[s]; override != 0 {
1440 return override
1441 }
1442 }
1443 return state.ctxt.loader.SymType(s)
1444 }
1445
1446
1447 func (state *dodataState) setSymType(s loader.Sym, kind sym.SymKind) {
1448 if s == 0 {
1449 panic("bad")
1450 }
1451 if int(s) < len(state.symGroupType) {
1452 state.symGroupType[s] = kind
1453 } else {
1454 su := state.ctxt.loader.MakeSymbolUpdater(s)
1455 su.SetType(kind)
1456 }
1457 }
1458
1459 func (ctxt *Link) dodata(symGroupType []sym.SymKind) {
1460
1461
1462 fixZeroSizedSymbols(ctxt)
1463
1464
1465 state := dodataState{ctxt: ctxt, symGroupType: symGroupType}
1466 ldr := ctxt.loader
1467 for s := loader.Sym(1); s < loader.Sym(ldr.NSym()); s++ {
1468 if !ldr.AttrReachable(s) || ldr.AttrSpecial(s) || ldr.AttrSubSymbol(s) ||
1469 !ldr.TopLevelSym(s) {
1470 continue
1471 }
1472
1473 st := state.symType(s)
1474
1475 if st <= sym.STEXT || st >= sym.SXREF {
1476 continue
1477 }
1478 state.data[st] = append(state.data[st], s)
1479
1480
1481 if ldr.AttrOnList(s) {
1482 log.Fatalf("symbol %s listed multiple times", ldr.SymName(s))
1483 }
1484 ldr.SetAttrOnList(s, true)
1485 }
1486
1487
1488
1489
1490
1491
1492
1493 if ctxt.HeadType == objabi.Hdarwin {
1494 machosymorder(ctxt)
1495 }
1496 state.dynreloc(ctxt)
1497
1498
1499 state.makeRelroForSharedLib(ctxt)
1500
1501
1502
1503
1504
1505 lastSym := loader.Sym(ldr.NSym() - 1)
1506 ldr.SetSymAlign(lastSym, ldr.SymAlign(lastSym))
1507
1508
1509 var wg sync.WaitGroup
1510 for symn := range state.data {
1511 symn := sym.SymKind(symn)
1512 wg.Add(1)
1513 go func() {
1514 state.data[symn], state.dataMaxAlign[symn] = state.dodataSect(ctxt, symn, state.data[symn])
1515 wg.Done()
1516 }()
1517 }
1518 wg.Wait()
1519
1520 if ctxt.IsELF {
1521
1522
1523 syms := state.data[sym.SELFROSECT]
1524 reli, plti := -1, -1
1525 for i, s := range syms {
1526 switch ldr.SymName(s) {
1527 case ".rel.plt", ".rela.plt":
1528 plti = i
1529 case ".rel", ".rela":
1530 reli = i
1531 }
1532 }
1533 if reli >= 0 && plti >= 0 && plti != reli+1 {
1534 var first, second int
1535 if plti > reli {
1536 first, second = reli, plti
1537 } else {
1538 first, second = plti, reli
1539 }
1540 rel, plt := syms[reli], syms[plti]
1541 copy(syms[first+2:], syms[first+1:second])
1542 syms[first+0] = rel
1543 syms[first+1] = plt
1544
1545
1546
1547
1548
1549 ldr.SetSymAlign(rel, int32(ctxt.Arch.RegSize))
1550 ldr.SetSymAlign(plt, int32(ctxt.Arch.RegSize))
1551 }
1552 state.data[sym.SELFROSECT] = syms
1553 }
1554
1555 if ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal {
1556
1557
1558 ldr.SetSymAlign(ldr.Lookup("runtime.data", 0), state.dataMaxAlign[sym.SDATA])
1559 ldr.SetSymAlign(ldr.Lookup("runtime.bss", 0), state.dataMaxAlign[sym.SBSS])
1560 }
1561
1562
1563
1564 state.allocateDataSections(ctxt)
1565
1566
1567
1568 state.allocateDwarfSections(ctxt)
1569
1570
1571 n := int16(1)
1572
1573 for _, sect := range Segtext.Sections {
1574 sect.Extnum = n
1575 n++
1576 }
1577 for _, sect := range Segrodata.Sections {
1578 sect.Extnum = n
1579 n++
1580 }
1581 for _, sect := range Segrelrodata.Sections {
1582 sect.Extnum = n
1583 n++
1584 }
1585 for _, sect := range Segdata.Sections {
1586 sect.Extnum = n
1587 n++
1588 }
1589 for _, sect := range Segdwarf.Sections {
1590 sect.Extnum = n
1591 n++
1592 }
1593 }
1594
1595
1596
1597
1598
1599 func (state *dodataState) allocateDataSectionForSym(seg *sym.Segment, s loader.Sym, rwx int) *sym.Section {
1600 ldr := state.ctxt.loader
1601 sname := ldr.SymName(s)
1602 sect := addsection(ldr, state.ctxt.Arch, seg, sname, rwx)
1603 sect.Align = symalign(ldr, s)
1604 state.datsize = Rnd(state.datsize, int64(sect.Align))
1605 sect.Vaddr = uint64(state.datsize)
1606 return sect
1607 }
1608
1609
1610
1611
1612
1613
1614 func (state *dodataState) allocateNamedDataSection(seg *sym.Segment, sName string, types []sym.SymKind, rwx int) *sym.Section {
1615 sect := addsection(state.ctxt.loader, state.ctxt.Arch, seg, sName, rwx)
1616 if len(types) == 0 {
1617 sect.Align = 1
1618 } else if len(types) == 1 {
1619 sect.Align = state.dataMaxAlign[types[0]]
1620 } else {
1621 for _, symn := range types {
1622 align := state.dataMaxAlign[symn]
1623 if sect.Align < align {
1624 sect.Align = align
1625 }
1626 }
1627 }
1628 state.datsize = Rnd(state.datsize, int64(sect.Align))
1629 sect.Vaddr = uint64(state.datsize)
1630 return sect
1631 }
1632
1633
1634
1635
1636
1637
1638
1639 func (state *dodataState) assignDsymsToSection(sect *sym.Section, syms []loader.Sym, forceType sym.SymKind, aligner func(state *dodataState, datsize int64, s loader.Sym) int64) {
1640 ldr := state.ctxt.loader
1641 for _, s := range syms {
1642 state.datsize = aligner(state, state.datsize, s)
1643 ldr.SetSymSect(s, sect)
1644 if forceType != sym.Sxxx {
1645 state.setSymType(s, forceType)
1646 }
1647 ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
1648 state.datsize += ldr.SymSize(s)
1649 }
1650 sect.Length = uint64(state.datsize) - sect.Vaddr
1651 }
1652
1653 func (state *dodataState) assignToSection(sect *sym.Section, symn sym.SymKind, forceType sym.SymKind) {
1654 state.assignDsymsToSection(sect, state.data[symn], forceType, aligndatsize)
1655 state.checkdatsize(symn)
1656 }
1657
1658
1659
1660
1661
1662
1663
1664 func (state *dodataState) allocateSingleSymSections(seg *sym.Segment, symn sym.SymKind, forceType sym.SymKind, rwx int) {
1665 ldr := state.ctxt.loader
1666 for _, s := range state.data[symn] {
1667 sect := state.allocateDataSectionForSym(seg, s, rwx)
1668 ldr.SetSymSect(s, sect)
1669 state.setSymType(s, forceType)
1670 ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
1671 state.datsize += ldr.SymSize(s)
1672 sect.Length = uint64(state.datsize) - sect.Vaddr
1673 }
1674 state.checkdatsize(symn)
1675 }
1676
1677
1678
1679
1680
1681
1682
1683
1684 func (state *dodataState) allocateNamedSectionAndAssignSyms(seg *sym.Segment, secName string, symn sym.SymKind, forceType sym.SymKind, rwx int) *sym.Section {
1685
1686 sect := state.allocateNamedDataSection(seg, secName, []sym.SymKind{symn}, rwx)
1687 state.assignDsymsToSection(sect, state.data[symn], forceType, aligndatsize)
1688 return sect
1689 }
1690
1691
1692
1693 func (state *dodataState) allocateDataSections(ctxt *Link) {
1694
1695
1696
1697
1698
1699
1700 writable := []sym.SymKind{
1701 sym.SBUILDINFO,
1702 sym.SELFSECT,
1703 sym.SMACHO,
1704 sym.SMACHOGOT,
1705 sym.SWINDOWS,
1706 }
1707 for _, symn := range writable {
1708 state.allocateSingleSymSections(&Segdata, symn, sym.SDATA, 06)
1709 }
1710 ldr := ctxt.loader
1711
1712
1713 if len(state.data[sym.SELFGOT]) > 0 {
1714 state.allocateNamedSectionAndAssignSyms(&Segdata, ".got", sym.SELFGOT, sym.SDATA, 06)
1715 }
1716
1717
1718 sect := state.allocateNamedSectionAndAssignSyms(&Segdata, ".noptrdata", sym.SNOPTRDATA, sym.SDATA, 06)
1719 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.noptrdata", 0), sect)
1720 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.enoptrdata", 0), sect)
1721
1722 hasinitarr := ctxt.linkShared
1723
1724
1725 switch ctxt.BuildMode {
1726 case BuildModeCArchive, BuildModeCShared, BuildModeShared, BuildModePlugin:
1727 hasinitarr = true
1728 }
1729
1730 if ctxt.HeadType == objabi.Haix {
1731 if len(state.data[sym.SINITARR]) > 0 {
1732 Errorf(nil, "XCOFF format doesn't allow .init_array section")
1733 }
1734 }
1735
1736 if hasinitarr && len(state.data[sym.SINITARR]) > 0 {
1737 state.allocateNamedSectionAndAssignSyms(&Segdata, ".init_array", sym.SINITARR, sym.Sxxx, 06)
1738 }
1739
1740
1741 sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".data", sym.SDATA, sym.SDATA, 06)
1742 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.data", 0), sect)
1743 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.edata", 0), sect)
1744 dataGcEnd := state.datsize - int64(sect.Vaddr)
1745
1746
1747
1748 state.assignToSection(sect, sym.SXCOFFTOC, sym.SDATA)
1749 state.checkdatsize(sym.SDATA)
1750 sect.Length = uint64(state.datsize) - sect.Vaddr
1751
1752
1753 sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".bss", sym.SBSS, sym.Sxxx, 06)
1754 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.bss", 0), sect)
1755 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.ebss", 0), sect)
1756 bssGcEnd := state.datsize - int64(sect.Vaddr)
1757
1758
1759 gcsToEmit := []struct {
1760 symName string
1761 symKind sym.SymKind
1762 gcEnd int64
1763 }{
1764 {"runtime.gcdata", sym.SDATA, dataGcEnd},
1765 {"runtime.gcbss", sym.SBSS, bssGcEnd},
1766 }
1767 for _, g := range gcsToEmit {
1768 var gc GCProg
1769 gc.Init(ctxt, g.symName)
1770 for _, s := range state.data[g.symKind] {
1771 gc.AddSym(s)
1772 }
1773 gc.End(g.gcEnd)
1774 }
1775
1776
1777 sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".noptrbss", sym.SNOPTRBSS, sym.Sxxx, 06)
1778 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.noptrbss", 0), sect)
1779 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.enoptrbss", 0), sect)
1780 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.end", 0), sect)
1781
1782
1783 if len(state.data[sym.SLIBFUZZER_EXTRA_COUNTER]) > 0 {
1784 sect := state.allocateNamedSectionAndAssignSyms(&Segdata, "__libfuzzer_extra_counters", sym.SLIBFUZZER_EXTRA_COUNTER, sym.Sxxx, 06)
1785 ldr.SetSymSect(ldr.LookupOrCreateSym("internal/fuzz._counters", 0), sect)
1786 ldr.SetSymSect(ldr.LookupOrCreateSym("internal/fuzz._ecounters", 0), sect)
1787 }
1788
1789 if len(state.data[sym.STLSBSS]) > 0 {
1790 var sect *sym.Section
1791
1792 if (ctxt.IsELF || ctxt.HeadType == objabi.Haix) && (ctxt.LinkMode == LinkExternal || !*FlagD) {
1793 sect = addsection(ldr, ctxt.Arch, &Segdata, ".tbss", 06)
1794 sect.Align = int32(ctxt.Arch.PtrSize)
1795
1796 sect.Vaddr = 0
1797 }
1798 state.datsize = 0
1799
1800 for _, s := range state.data[sym.STLSBSS] {
1801 state.datsize = aligndatsize(state, state.datsize, s)
1802 if sect != nil {
1803 ldr.SetSymSect(s, sect)
1804 }
1805 ldr.SetSymValue(s, state.datsize)
1806 state.datsize += ldr.SymSize(s)
1807 }
1808 state.checkdatsize(sym.STLSBSS)
1809
1810 if sect != nil {
1811 sect.Length = uint64(state.datsize)
1812 }
1813 }
1814
1815
1824 var segro *sym.Segment
1825 if ctxt.IsELF && ctxt.LinkMode == LinkInternal {
1826 segro = &Segrodata
1827 } else if ctxt.HeadType == objabi.Hwindows {
1828 segro = &Segrodata
1829 } else {
1830 segro = &Segtext
1831 }
1832
1833 state.datsize = 0
1834
1835
1836 if len(state.data[sym.STEXT]) != 0 {
1837 culprit := ldr.SymName(state.data[sym.STEXT][0])
1838 Errorf(nil, "dodata found an sym.STEXT symbol: %s", culprit)
1839 }
1840 state.allocateSingleSymSections(&Segtext, sym.SELFRXSECT, sym.SRODATA, 05)
1841 state.allocateSingleSymSections(&Segtext, sym.SMACHOPLT, sym.SRODATA, 05)
1842
1843
1844 sect = state.allocateNamedDataSection(segro, ".rodata", sym.ReadOnly, 04)
1845 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.rodata", 0), sect)
1846 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.erodata", 0), sect)
1847 if !ctxt.UseRelro() {
1848 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.types", 0), sect)
1849 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.etypes", 0), sect)
1850 }
1851 for _, symn := range sym.ReadOnly {
1852 symnStartValue := state.datsize
1853 state.assignToSection(sect, symn, sym.SRODATA)
1854 setCarrierSize(symn, state.datsize-symnStartValue)
1855 if ctxt.HeadType == objabi.Haix {
1856
1857
1858
1859
1860 xcoffUpdateOuterSize(ctxt, state.datsize-symnStartValue, symn)
1861 }
1862 }
1863
1864
1865 state.allocateSingleSymSections(segro, sym.SELFROSECT, sym.SRODATA, 04)
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877 const relroPerm = 06
1878 const fallbackPerm = 04
1879 relroSecPerm := fallbackPerm
1880 genrelrosecname := func(suffix string) string {
1881 if suffix == "" {
1882 return ".rodata"
1883 }
1884 return suffix
1885 }
1886 seg := segro
1887
1888 if ctxt.UseRelro() {
1889 segrelro := &Segrelrodata
1890 if ctxt.LinkMode == LinkExternal && !ctxt.IsAIX() && !ctxt.IsDarwin() {
1891
1892
1893
1894
1895
1896
1897 segrelro = segro
1898 } else {
1899
1900 state.datsize = 0
1901 }
1902
1903 if !ctxt.IsDarwin() {
1904 genrelrosecname = func(suffix string) string {
1905 return ".data.rel.ro" + suffix
1906 }
1907 }
1908
1909 relroReadOnly := []sym.SymKind{}
1910 for _, symnro := range sym.ReadOnly {
1911 symn := sym.RelROMap[symnro]
1912 relroReadOnly = append(relroReadOnly, symn)
1913 }
1914 seg = segrelro
1915 relroSecPerm = relroPerm
1916
1917
1918 sect = state.allocateNamedDataSection(segrelro, genrelrosecname(""), relroReadOnly, relroSecPerm)
1919
1920 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.types", 0), sect)
1921 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.etypes", 0), sect)
1922
1923 for i, symnro := range sym.ReadOnly {
1924 if i == 0 && symnro == sym.STYPE && ctxt.HeadType != objabi.Haix {
1925
1926
1927
1928
1929 state.datsize++
1930 }
1931
1932 symn := sym.RelROMap[symnro]
1933 symnStartValue := state.datsize
1934
1935 for _, s := range state.data[symn] {
1936 outer := ldr.OuterSym(s)
1937 if s != 0 && ldr.SymSect(outer) != nil && ldr.SymSect(outer) != sect {
1938 ctxt.Errorf(s, "s.Outer (%s) in different section from s, %s != %s", ldr.SymName(outer), ldr.SymSect(outer).Name, sect.Name)
1939 }
1940 }
1941 state.assignToSection(sect, symn, sym.SRODATA)
1942 setCarrierSize(symn, state.datsize-symnStartValue)
1943 if ctxt.HeadType == objabi.Haix {
1944
1945
1946
1947
1948 xcoffUpdateOuterSize(ctxt, state.datsize-symnStartValue, symn)
1949 }
1950 }
1951
1952 sect.Length = uint64(state.datsize) - sect.Vaddr
1953 }
1954
1955
1956 sect = state.allocateNamedDataSection(seg, genrelrosecname(".typelink"), []sym.SymKind{sym.STYPELINK}, relroSecPerm)
1957
1958 typelink := ldr.CreateSymForUpdate("runtime.typelink", 0)
1959 ldr.SetSymSect(typelink.Sym(), sect)
1960 typelink.SetType(sym.SRODATA)
1961 state.datsize += typelink.Size()
1962 state.checkdatsize(sym.STYPELINK)
1963 sect.Length = uint64(state.datsize) - sect.Vaddr
1964
1965
1966 sect = state.allocateNamedDataSection(seg, genrelrosecname(".itablink"), []sym.SymKind{sym.SITABLINK}, relroSecPerm)
1967
1968 itablink := ldr.CreateSymForUpdate("runtime.itablink", 0)
1969 ldr.SetSymSect(itablink.Sym(), sect)
1970 itablink.SetType(sym.SRODATA)
1971 state.datsize += itablink.Size()
1972 state.checkdatsize(sym.SITABLINK)
1973 sect.Length = uint64(state.datsize) - sect.Vaddr
1974
1975
1976 sect = state.allocateNamedSectionAndAssignSyms(seg, genrelrosecname(".gosymtab"), sym.SSYMTAB, sym.SRODATA, relroSecPerm)
1977 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.symtab", 0), sect)
1978 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.esymtab", 0), sect)
1979
1980
1981 sect = state.allocateNamedSectionAndAssignSyms(seg, genrelrosecname(".gopclntab"), sym.SPCLNTAB, sym.SRODATA, relroSecPerm)
1982 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pclntab", 0), sect)
1983 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pcheader", 0), sect)
1984 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.funcnametab", 0), sect)
1985 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.cutab", 0), sect)
1986 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.filetab", 0), sect)
1987 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pctab", 0), sect)
1988 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.functab", 0), sect)
1989 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.epclntab", 0), sect)
1990 setCarrierSize(sym.SPCLNTAB, int64(sect.Length))
1991 if ctxt.HeadType == objabi.Haix {
1992 xcoffUpdateOuterSize(ctxt, int64(sect.Length), sym.SPCLNTAB)
1993 }
1994
1995
1996 if state.datsize != int64(uint32(state.datsize)) {
1997 Errorf(nil, "read-only data segment too large: %d", state.datsize)
1998 }
1999
2000 siz := 0
2001 for symn := sym.SELFRXSECT; symn < sym.SXREF; symn++ {
2002 siz += len(state.data[symn])
2003 }
2004 ctxt.datap = make([]loader.Sym, 0, siz)
2005 for symn := sym.SELFRXSECT; symn < sym.SXREF; symn++ {
2006 ctxt.datap = append(ctxt.datap, state.data[symn]...)
2007 }
2008 }
2009
2010
2011
2012 func (state *dodataState) allocateDwarfSections(ctxt *Link) {
2013
2014 alignOne := func(state *dodataState, datsize int64, s loader.Sym) int64 { return datsize }
2015
2016 ldr := ctxt.loader
2017 for i := 0; i < len(dwarfp); i++ {
2018
2019 s := dwarfp[i].secSym()
2020 sect := state.allocateNamedDataSection(&Segdwarf, ldr.SymName(s), []sym.SymKind{}, 04)
2021 ldr.SetSymSect(s, sect)
2022 sect.Sym = sym.LoaderSym(s)
2023 curType := ldr.SymType(s)
2024 state.setSymType(s, sym.SRODATA)
2025 ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
2026 state.datsize += ldr.SymSize(s)
2027
2028
2029 subSyms := dwarfp[i].subSyms()
2030 state.assignDsymsToSection(sect, subSyms, sym.SRODATA, alignOne)
2031
2032 for j := 0; j < len(subSyms); j++ {
2033 s := subSyms[j]
2034 if ctxt.HeadType == objabi.Haix && curType == sym.SDWARFLOC {
2035
2036
2037 addDwsectCUSize(".debug_loc", ldr.SymPkg(s), uint64(ldr.SymSize(s)))
2038 }
2039 }
2040 sect.Length = uint64(state.datsize) - sect.Vaddr
2041 state.checkdatsize(curType)
2042 }
2043 }
2044
2045 type symNameSize struct {
2046 name string
2047 sz int64
2048 val int64
2049 sym loader.Sym
2050 }
2051
2052 func (state *dodataState) dodataSect(ctxt *Link, symn sym.SymKind, syms []loader.Sym) (result []loader.Sym, maxAlign int32) {
2053 var head, tail loader.Sym
2054 ldr := ctxt.loader
2055 sl := make([]symNameSize, len(syms))
2056 for k, s := range syms {
2057 ss := ldr.SymSize(s)
2058 sl[k] = symNameSize{name: ldr.SymName(s), sz: ss, sym: s}
2059 ds := int64(len(ldr.Data(s)))
2060 switch {
2061 case ss < ds:
2062 ctxt.Errorf(s, "initialize bounds (%d < %d)", ss, ds)
2063 case ss < 0:
2064 ctxt.Errorf(s, "negative size (%d bytes)", ss)
2065 case ss > cutoff:
2066 ctxt.Errorf(s, "symbol too large (%d bytes)", ss)
2067 }
2068
2069
2070
2071
2072 if (ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin) || (ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal) {
2073 switch ldr.SymName(s) {
2074 case "runtime.text", "runtime.bss", "runtime.data", "runtime.types", "runtime.rodata":
2075 head = s
2076 continue
2077 case "runtime.etext", "runtime.ebss", "runtime.edata", "runtime.etypes", "runtime.erodata":
2078 tail = s
2079 continue
2080 }
2081 }
2082 }
2083
2084
2085
2086
2087
2088 checkSize := symn != sym.SELFGOT
2089
2090
2091 if symn != sym.SPCLNTAB {
2092 sort.Slice(sl, func(i, j int) bool {
2093 si, sj := sl[i].sym, sl[j].sym
2094 switch {
2095 case si == head, sj == tail:
2096 return true
2097 case sj == head, si == tail:
2098 return false
2099 }
2100 if checkSize {
2101 isz := sl[i].sz
2102 jsz := sl[j].sz
2103 if isz != jsz {
2104 return isz < jsz
2105 }
2106 }
2107 iname := sl[i].name
2108 jname := sl[j].name
2109 if iname != jname {
2110 return iname < jname
2111 }
2112 return si < sj
2113 })
2114 } else {
2115
2116
2117 for k, s := range syms {
2118 sl[k].val = ldr.SymValue(s)
2119 }
2120 sort.Slice(sl, func(i, j int) bool { return sl[i].val < sl[j].val })
2121 }
2122
2123
2124 syms = syms[:0]
2125 for k := range sl {
2126 s := sl[k].sym
2127 if s != head && s != tail {
2128 align := symalign(ldr, s)
2129 if maxAlign < align {
2130 maxAlign = align
2131 }
2132 }
2133 syms = append(syms, s)
2134 }
2135
2136 return syms, maxAlign
2137 }
2138
2139
2140
2141
2142
2143
2144 func (ctxt *Link) textbuildid() {
2145 if ctxt.IsELF || ctxt.BuildMode == BuildModePlugin || *flagBuildid == "" {
2146 return
2147 }
2148
2149 ldr := ctxt.loader
2150 s := ldr.CreateSymForUpdate("go.buildid", 0)
2151
2152
2153 data := "\xff Go build ID: " + strconv.Quote(*flagBuildid) + "\n \xff"
2154 s.SetType(sym.STEXT)
2155 s.SetData([]byte(data))
2156 s.SetSize(int64(len(data)))
2157
2158 ctxt.Textp = append(ctxt.Textp, 0)
2159 copy(ctxt.Textp[1:], ctxt.Textp)
2160 ctxt.Textp[0] = s.Sym()
2161 }
2162
2163 func (ctxt *Link) buildinfo() {
2164 if ctxt.linkShared || ctxt.BuildMode == BuildModePlugin {
2165
2166
2167
2168
2169 return
2170 }
2171
2172
2173
2174 ldr := ctxt.loader
2175 s := ldr.CreateSymForUpdate(".go.buildinfo", 0)
2176 s.SetType(sym.SBUILDINFO)
2177 s.SetAlign(16)
2178
2179
2180 const prefix = "\xff Go buildinf:"
2181 data := make([]byte, 32)
2182 copy(data, prefix)
2183 data[len(prefix)] = byte(ctxt.Arch.PtrSize)
2184 data[len(prefix)+1] = 0
2185 if ctxt.Arch.ByteOrder == binary.BigEndian {
2186 data[len(prefix)+1] = 1
2187 }
2188 data[len(prefix)+1] |= 2
2189 data = appendString(data, strdata["runtime.buildVersion"])
2190 data = appendString(data, strdata["runtime.modinfo"])
2191
2192 for len(data)%16 != 0 {
2193 data = append(data, 0)
2194 }
2195 s.SetData(data)
2196 s.SetSize(int64(len(data)))
2197 }
2198
2199
2200 func appendString(data []byte, s string) []byte {
2201 var v [binary.MaxVarintLen64]byte
2202 n := binary.PutUvarint(v[:], uint64(len(s)))
2203 data = append(data, v[:n]...)
2204 data = append(data, s...)
2205 return data
2206 }
2207
2208
2209 func (ctxt *Link) textaddress() {
2210 addsection(ctxt.loader, ctxt.Arch, &Segtext, ".text", 05)
2211
2212
2213
2214
2215 sect := Segtext.Sections[0]
2216
2217 sect.Align = int32(Funcalign)
2218
2219 ldr := ctxt.loader
2220
2221 text := ctxt.xdefine("runtime.text", sym.STEXT, 0)
2222 etext := ctxt.xdefine("runtime.etext", sym.STEXT, 0)
2223 ldr.SetSymSect(text, sect)
2224 if ctxt.IsAIX() && ctxt.IsExternal() {
2225
2226
2227
2228 u := ldr.MakeSymbolUpdater(text)
2229 u.SetAlign(sect.Align)
2230 u.SetSize(8)
2231 }
2232
2233 if (ctxt.DynlinkingGo() && ctxt.IsDarwin()) || (ctxt.IsAIX() && ctxt.IsExternal()) {
2234 ldr.SetSymSect(etext, sect)
2235 ctxt.Textp = append(ctxt.Textp, etext, 0)
2236 copy(ctxt.Textp[1:], ctxt.Textp)
2237 ctxt.Textp[0] = text
2238 }
2239
2240 start := uint64(Rnd(*FlagTextAddr, int64(Funcalign)))
2241 va := start
2242 n := 1
2243 sect.Vaddr = va
2244
2245 limit := thearch.TrampLimit
2246 if limit == 0 {
2247 limit = 1 << 63
2248 }
2249 if *FlagDebugTextSize != 0 {
2250 limit = uint64(*FlagDebugTextSize)
2251 }
2252 if *FlagDebugTramp > 1 {
2253 limit = 1
2254 }
2255
2256 if ctxt.IsAIX() && ctxt.IsExternal() {
2257
2258
2259
2260
2261
2262 limit = 1
2263 }
2264
2265
2266
2267 big := false
2268 for _, s := range ctxt.Textp {
2269 sect, n, va = assignAddress(ctxt, sect, n, s, va, false, big)
2270 if va-start >= limit {
2271 big = true
2272 break
2273 }
2274 }
2275
2276
2277
2278 if big {
2279
2280 for _, s := range ctxt.Textp {
2281 if ldr.OuterSym(s) != 0 || s == text {
2282 continue
2283 }
2284 oldv := ldr.SymValue(s)
2285 for sub := s; sub != 0; sub = ldr.SubSym(sub) {
2286 ldr.SetSymValue(sub, ldr.SymValue(sub)-oldv)
2287 }
2288 }
2289 va = start
2290
2291 ntramps := 0
2292 for _, s := range ctxt.Textp {
2293 sect, n, va = assignAddress(ctxt, sect, n, s, va, false, big)
2294
2295 trampoline(ctxt, s)
2296
2297
2298 for ; ntramps < len(ctxt.tramps); ntramps++ {
2299 tramp := ctxt.tramps[ntramps]
2300 if ctxt.IsAIX() && strings.HasPrefix(ldr.SymName(tramp), "runtime.text.") {
2301
2302 continue
2303 }
2304 sect, n, va = assignAddress(ctxt, sect, n, tramp, va, true, big)
2305 }
2306 }
2307
2308
2309 if ntramps != 0 {
2310 newtextp := make([]loader.Sym, 0, len(ctxt.Textp)+ntramps)
2311 i := 0
2312 for _, s := range ctxt.Textp {
2313 for ; i < ntramps && ldr.SymValue(ctxt.tramps[i]) < ldr.SymValue(s); i++ {
2314 newtextp = append(newtextp, ctxt.tramps[i])
2315 }
2316 newtextp = append(newtextp, s)
2317 }
2318 newtextp = append(newtextp, ctxt.tramps[i:ntramps]...)
2319
2320 ctxt.Textp = newtextp
2321 }
2322 }
2323
2324 sect.Length = va - sect.Vaddr
2325 ldr.SetSymSect(etext, sect)
2326 if ldr.SymValue(etext) == 0 {
2327
2328
2329 ldr.SetSymValue(etext, int64(va))
2330 ldr.SetSymValue(text, int64(Segtext.Sections[0].Vaddr))
2331 }
2332 }
2333
2334
2335 func assignAddress(ctxt *Link, sect *sym.Section, n int, s loader.Sym, va uint64, isTramp, big bool) (*sym.Section, int, uint64) {
2336 ldr := ctxt.loader
2337 if thearch.AssignAddress != nil {
2338 return thearch.AssignAddress(ldr, sect, n, s, va, isTramp)
2339 }
2340
2341 ldr.SetSymSect(s, sect)
2342 if ldr.AttrSubSymbol(s) {
2343 return sect, n, va
2344 }
2345
2346 align := ldr.SymAlign(s)
2347 if align == 0 {
2348 align = int32(Funcalign)
2349 }
2350 va = uint64(Rnd(int64(va), int64(align)))
2351 if sect.Align < align {
2352 sect.Align = align
2353 }
2354
2355 funcsize := uint64(MINFUNC)
2356 if ldr.SymSize(s) > MINFUNC {
2357 funcsize = uint64(ldr.SymSize(s))
2358 }
2359
2360
2361
2362
2363
2364 if big && splitTextSections(ctxt) && ldr.OuterSym(s) == 0 {
2365
2366
2367 var textSizelimit uint64 = thearch.TrampLimit
2368 if *FlagDebugTextSize != 0 {
2369 textSizelimit = uint64(*FlagDebugTextSize)
2370 }
2371
2372
2373
2374 if funcsize > textSizelimit {
2375 panic(fmt.Sprintf("error: text size limit %d less than text symbol %s size of %d", textSizelimit, ldr.SymName(s), funcsize))
2376 }
2377
2378 if va-sect.Vaddr+funcsize+maxSizeTrampolines(ctxt, ldr, s, isTramp) > textSizelimit {
2379 sectAlign := int32(thearch.Funcalign)
2380 if ctxt.IsPPC64() {
2381
2382
2383
2384
2385
2386
2387 const ppc64maxFuncalign = 64
2388 sectAlign = ppc64maxFuncalign
2389 va = uint64(Rnd(int64(va), ppc64maxFuncalign))
2390 }
2391
2392
2393 sect.Length = va - sect.Vaddr
2394
2395
2396 sect = addsection(ctxt.loader, ctxt.Arch, &Segtext, ".text", 05)
2397
2398 sect.Vaddr = va
2399 sect.Align = sectAlign
2400 ldr.SetSymSect(s, sect)
2401
2402
2403 ntext := ldr.CreateSymForUpdate(fmt.Sprintf("runtime.text.%d", n), 0)
2404 ntext.SetSect(sect)
2405 if ctxt.IsAIX() {
2406
2407
2408
2409 ntext.SetType(sym.STEXT)
2410 ntext.SetSize(int64(MINFUNC))
2411 ntext.SetOnList(true)
2412 ntext.SetAlign(sectAlign)
2413 ctxt.tramps = append(ctxt.tramps, ntext.Sym())
2414
2415 ntext.SetValue(int64(va))
2416 va += uint64(ntext.Size())
2417
2418 if align := ldr.SymAlign(s); align != 0 {
2419 va = uint64(Rnd(int64(va), int64(align)))
2420 } else {
2421 va = uint64(Rnd(int64(va), int64(Funcalign)))
2422 }
2423 }
2424 n++
2425 }
2426 }
2427
2428 ldr.SetSymValue(s, 0)
2429 for sub := s; sub != 0; sub = ldr.SubSym(sub) {
2430 ldr.SetSymValue(sub, ldr.SymValue(sub)+int64(va))
2431 if ctxt.Debugvlog > 2 {
2432 fmt.Println("assign text address:", ldr.SymName(sub), ldr.SymValue(sub))
2433 }
2434 }
2435
2436 va += funcsize
2437
2438 return sect, n, va
2439 }
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450 func splitTextSections(ctxt *Link) bool {
2451 return (ctxt.IsPPC64() || (ctxt.IsARM64() && ctxt.IsDarwin())) && ctxt.IsExternal()
2452 }
2453
2454
2455
2456
2457
2458 const wasmMinDataAddr = 4096 + 8192
2459
2460
2461
2462 func (ctxt *Link) address() []*sym.Segment {
2463 var order []*sym.Segment
2464
2465 va := uint64(*FlagTextAddr)
2466 order = append(order, &Segtext)
2467 Segtext.Rwx = 05
2468 Segtext.Vaddr = va
2469 for i, s := range Segtext.Sections {
2470 va = uint64(Rnd(int64(va), int64(s.Align)))
2471 s.Vaddr = va
2472 va += s.Length
2473
2474 if ctxt.IsWasm() && i == 0 && va < wasmMinDataAddr {
2475 va = wasmMinDataAddr
2476 }
2477 }
2478
2479 Segtext.Length = va - uint64(*FlagTextAddr)
2480
2481 if len(Segrodata.Sections) > 0 {
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495 va = uint64(Rnd(int64(va), int64(*FlagRound)))
2496
2497 order = append(order, &Segrodata)
2498 Segrodata.Rwx = 04
2499 Segrodata.Vaddr = va
2500 for _, s := range Segrodata.Sections {
2501 va = uint64(Rnd(int64(va), int64(s.Align)))
2502 s.Vaddr = va
2503 va += s.Length
2504 }
2505
2506 Segrodata.Length = va - Segrodata.Vaddr
2507 }
2508 if len(Segrelrodata.Sections) > 0 {
2509
2510
2511 va = uint64(Rnd(int64(va), int64(*FlagRound)))
2512 if ctxt.HeadType == objabi.Haix {
2513
2514 va += uint64(XCOFFDATABASE) - uint64(XCOFFTEXTBASE)
2515 }
2516
2517 order = append(order, &Segrelrodata)
2518 Segrelrodata.Rwx = 06
2519 Segrelrodata.Vaddr = va
2520 for _, s := range Segrelrodata.Sections {
2521 va = uint64(Rnd(int64(va), int64(s.Align)))
2522 s.Vaddr = va
2523 va += s.Length
2524 }
2525
2526 Segrelrodata.Length = va - Segrelrodata.Vaddr
2527 }
2528
2529 va = uint64(Rnd(int64(va), int64(*FlagRound)))
2530 if ctxt.HeadType == objabi.Haix && len(Segrelrodata.Sections) == 0 {
2531
2532
2533
2534 va += uint64(XCOFFDATABASE) - uint64(XCOFFTEXTBASE)
2535 }
2536 order = append(order, &Segdata)
2537 Segdata.Rwx = 06
2538 Segdata.Vaddr = va
2539 var data *sym.Section
2540 var noptr *sym.Section
2541 var bss *sym.Section
2542 var noptrbss *sym.Section
2543 var fuzzCounters *sym.Section
2544 for i, s := range Segdata.Sections {
2545 if (ctxt.IsELF || ctxt.HeadType == objabi.Haix) && s.Name == ".tbss" {
2546 continue
2547 }
2548 vlen := int64(s.Length)
2549 if i+1 < len(Segdata.Sections) && !((ctxt.IsELF || ctxt.HeadType == objabi.Haix) && Segdata.Sections[i+1].Name == ".tbss") {
2550 vlen = int64(Segdata.Sections[i+1].Vaddr - s.Vaddr)
2551 }
2552 s.Vaddr = va
2553 va += uint64(vlen)
2554 Segdata.Length = va - Segdata.Vaddr
2555 switch s.Name {
2556 case ".data":
2557 data = s
2558 case ".noptrdata":
2559 noptr = s
2560 case ".bss":
2561 bss = s
2562 case ".noptrbss":
2563 noptrbss = s
2564 case "__libfuzzer_extra_counters":
2565 fuzzCounters = s
2566 }
2567 }
2568
2569
2570
2571 Segdata.Filelen = bss.Vaddr - Segdata.Vaddr
2572
2573 va = uint64(Rnd(int64(va), int64(*FlagRound)))
2574 order = append(order, &Segdwarf)
2575 Segdwarf.Rwx = 06
2576 Segdwarf.Vaddr = va
2577 for i, s := range Segdwarf.Sections {
2578 vlen := int64(s.Length)
2579 if i+1 < len(Segdwarf.Sections) {
2580 vlen = int64(Segdwarf.Sections[i+1].Vaddr - s.Vaddr)
2581 }
2582 s.Vaddr = va
2583 va += uint64(vlen)
2584 if ctxt.HeadType == objabi.Hwindows {
2585 va = uint64(Rnd(int64(va), PEFILEALIGN))
2586 }
2587 Segdwarf.Length = va - Segdwarf.Vaddr
2588 }
2589
2590 ldr := ctxt.loader
2591 var (
2592 rodata = ldr.SymSect(ldr.LookupOrCreateSym("runtime.rodata", 0))
2593 symtab = ldr.SymSect(ldr.LookupOrCreateSym("runtime.symtab", 0))
2594 pclntab = ldr.SymSect(ldr.LookupOrCreateSym("runtime.pclntab", 0))
2595 types = ldr.SymSect(ldr.LookupOrCreateSym("runtime.types", 0))
2596 )
2597
2598 for _, s := range ctxt.datap {
2599 if sect := ldr.SymSect(s); sect != nil {
2600 ldr.AddToSymValue(s, int64(sect.Vaddr))
2601 }
2602 v := ldr.SymValue(s)
2603 for sub := ldr.SubSym(s); sub != 0; sub = ldr.SubSym(sub) {
2604 ldr.AddToSymValue(sub, v)
2605 }
2606 }
2607
2608 for _, si := range dwarfp {
2609 for _, s := range si.syms {
2610 if sect := ldr.SymSect(s); sect != nil {
2611 ldr.AddToSymValue(s, int64(sect.Vaddr))
2612 }
2613 sub := ldr.SubSym(s)
2614 if sub != 0 {
2615 panic(fmt.Sprintf("unexpected sub-sym for %s %s", ldr.SymName(s), ldr.SymType(s).String()))
2616 }
2617 v := ldr.SymValue(s)
2618 for ; sub != 0; sub = ldr.SubSym(sub) {
2619 ldr.AddToSymValue(s, v)
2620 }
2621 }
2622 }
2623
2624 if ctxt.BuildMode == BuildModeShared {
2625 s := ldr.LookupOrCreateSym("go.link.abihashbytes", 0)
2626 sect := ldr.SymSect(ldr.LookupOrCreateSym(".note.go.abihash", 0))
2627 ldr.SetSymSect(s, sect)
2628 ldr.SetSymValue(s, int64(sect.Vaddr+16))
2629 }
2630
2631
2632
2633 n := 1
2634 for _, sect := range Segtext.Sections[1:] {
2635 if sect.Name != ".text" {
2636 break
2637 }
2638 symname := fmt.Sprintf("runtime.text.%d", n)
2639 if ctxt.HeadType != objabi.Haix || ctxt.LinkMode != LinkExternal {
2640
2641
2642 ctxt.xdefine(symname, sym.STEXT, int64(sect.Vaddr))
2643 }
2644 n++
2645 }
2646
2647 ctxt.xdefine("runtime.rodata", sym.SRODATA, int64(rodata.Vaddr))
2648 ctxt.xdefine("runtime.erodata", sym.SRODATA, int64(rodata.Vaddr+rodata.Length))
2649 ctxt.xdefine("runtime.types", sym.SRODATA, int64(types.Vaddr))
2650 ctxt.xdefine("runtime.etypes", sym.SRODATA, int64(types.Vaddr+types.Length))
2651
2652 s := ldr.Lookup("runtime.gcdata", 0)
2653 ldr.SetAttrLocal(s, true)
2654 ctxt.xdefine("runtime.egcdata", sym.SRODATA, ldr.SymAddr(s)+ldr.SymSize(s))
2655 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.egcdata", 0), ldr.SymSect(s))
2656
2657 s = ldr.LookupOrCreateSym("runtime.gcbss", 0)
2658 ldr.SetAttrLocal(s, true)
2659 ctxt.xdefine("runtime.egcbss", sym.SRODATA, ldr.SymAddr(s)+ldr.SymSize(s))
2660 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.egcbss", 0), ldr.SymSect(s))
2661
2662 ctxt.xdefine("runtime.symtab", sym.SRODATA, int64(symtab.Vaddr))
2663 ctxt.xdefine("runtime.esymtab", sym.SRODATA, int64(symtab.Vaddr+symtab.Length))
2664 ctxt.xdefine("runtime.pclntab", sym.SRODATA, int64(pclntab.Vaddr))
2665 ctxt.defineInternal("runtime.pcheader", sym.SRODATA)
2666 ctxt.defineInternal("runtime.funcnametab", sym.SRODATA)
2667 ctxt.defineInternal("runtime.cutab", sym.SRODATA)
2668 ctxt.defineInternal("runtime.filetab", sym.SRODATA)
2669 ctxt.defineInternal("runtime.pctab", sym.SRODATA)
2670 ctxt.defineInternal("runtime.functab", sym.SRODATA)
2671 ctxt.xdefine("runtime.epclntab", sym.SRODATA, int64(pclntab.Vaddr+pclntab.Length))
2672 ctxt.xdefine("runtime.noptrdata", sym.SNOPTRDATA, int64(noptr.Vaddr))
2673 ctxt.xdefine("runtime.enoptrdata", sym.SNOPTRDATA, int64(noptr.Vaddr+noptr.Length))
2674 ctxt.xdefine("runtime.bss", sym.SBSS, int64(bss.Vaddr))
2675 ctxt.xdefine("runtime.ebss", sym.SBSS, int64(bss.Vaddr+bss.Length))
2676 ctxt.xdefine("runtime.data", sym.SDATA, int64(data.Vaddr))
2677 ctxt.xdefine("runtime.edata", sym.SDATA, int64(data.Vaddr+data.Length))
2678 ctxt.xdefine("runtime.noptrbss", sym.SNOPTRBSS, int64(noptrbss.Vaddr))
2679 ctxt.xdefine("runtime.enoptrbss", sym.SNOPTRBSS, int64(noptrbss.Vaddr+noptrbss.Length))
2680 ctxt.xdefine("runtime.end", sym.SBSS, int64(Segdata.Vaddr+Segdata.Length))
2681
2682 if fuzzCounters != nil {
2683 ctxt.xdefine("internal/fuzz._counters", sym.SLIBFUZZER_EXTRA_COUNTER, int64(fuzzCounters.Vaddr))
2684 ctxt.xdefine("internal/fuzz._ecounters", sym.SLIBFUZZER_EXTRA_COUNTER, int64(fuzzCounters.Vaddr+fuzzCounters.Length))
2685 }
2686
2687 if ctxt.IsSolaris() {
2688
2689
2690
2691 etext := ldr.Lookup("runtime.etext", 0)
2692 edata := ldr.Lookup("runtime.edata", 0)
2693 end := ldr.Lookup("runtime.end", 0)
2694 ldr.SetSymExtname(etext, "runtime.etext")
2695 ldr.SetSymExtname(edata, "runtime.edata")
2696 ldr.SetSymExtname(end, "runtime.end")
2697 ctxt.xdefine("_etext", ldr.SymType(etext), ldr.SymValue(etext))
2698 ctxt.xdefine("_edata", ldr.SymType(edata), ldr.SymValue(edata))
2699 ctxt.xdefine("_end", ldr.SymType(end), ldr.SymValue(end))
2700 ldr.SetSymSect(ldr.Lookup("_etext", 0), ldr.SymSect(etext))
2701 ldr.SetSymSect(ldr.Lookup("_edata", 0), ldr.SymSect(edata))
2702 ldr.SetSymSect(ldr.Lookup("_end", 0), ldr.SymSect(end))
2703 }
2704
2705 if ctxt.IsPPC64() && ctxt.IsElf() {
2706
2707
2708
2709 tocAddr := int64(Segdata.Vaddr) + 0x8000
2710 if gotAddr := ldr.SymValue(ctxt.GOT); gotAddr != 0 {
2711 tocAddr = gotAddr + 0x8000
2712 }
2713 for i, _ := range ctxt.DotTOC {
2714 if i >= sym.SymVerABICount && i < sym.SymVerStatic {
2715 continue
2716 }
2717 if toc := ldr.Lookup(".TOC.", i); toc != 0 {
2718 ldr.SetSymValue(toc, tocAddr)
2719 }
2720 }
2721 }
2722
2723 return order
2724 }
2725
2726
2727
2728 func (ctxt *Link) layout(order []*sym.Segment) uint64 {
2729 var prev *sym.Segment
2730 for _, seg := range order {
2731 if prev == nil {
2732 seg.Fileoff = uint64(HEADR)
2733 } else {
2734 switch ctxt.HeadType {
2735 default:
2736
2737
2738
2739
2740 seg.Fileoff = uint64(Rnd(int64(prev.Fileoff+prev.Filelen), int64(*FlagRound)))
2741 if seg.Vaddr%uint64(*FlagRound) != seg.Fileoff%uint64(*FlagRound) {
2742 Exitf("bad segment rounding (Vaddr=%#x Fileoff=%#x FlagRound=%#x)", seg.Vaddr, seg.Fileoff, *FlagRound)
2743 }
2744 case objabi.Hwindows:
2745 seg.Fileoff = prev.Fileoff + uint64(Rnd(int64(prev.Filelen), PEFILEALIGN))
2746 case objabi.Hplan9:
2747 seg.Fileoff = prev.Fileoff + prev.Filelen
2748 }
2749 }
2750 if seg != &Segdata {
2751
2752
2753 seg.Filelen = seg.Length
2754 }
2755 prev = seg
2756 }
2757 return prev.Fileoff + prev.Filelen
2758 }
2759
2760
2761 func (ctxt *Link) AddTramp(s *loader.SymbolBuilder) {
2762 s.SetType(sym.STEXT)
2763 s.SetReachable(true)
2764 s.SetOnList(true)
2765 ctxt.tramps = append(ctxt.tramps, s.Sym())
2766 if *FlagDebugTramp > 0 && ctxt.Debugvlog > 0 {
2767 ctxt.Logf("trampoline %s inserted\n", s.Name())
2768 }
2769 }
2770
2771
2772
2773 func compressSyms(ctxt *Link, syms []loader.Sym) []byte {
2774 ldr := ctxt.loader
2775 var total int64
2776 for _, sym := range syms {
2777 total += ldr.SymSize(sym)
2778 }
2779
2780 var buf bytes.Buffer
2781 buf.Write([]byte("ZLIB"))
2782 var sizeBytes [8]byte
2783 binary.BigEndian.PutUint64(sizeBytes[:], uint64(total))
2784 buf.Write(sizeBytes[:])
2785
2786 var relocbuf []byte
2787
2788
2789
2790
2791
2792 z, err := zlib.NewWriterLevel(&buf, zlib.BestSpeed)
2793 if err != nil {
2794 log.Fatalf("NewWriterLevel failed: %s", err)
2795 }
2796 st := ctxt.makeRelocSymState()
2797 for _, s := range syms {
2798
2799
2800 P := ldr.Data(s)
2801 relocs := ldr.Relocs(s)
2802 if relocs.Count() != 0 {
2803 relocbuf = append(relocbuf[:0], P...)
2804 P = relocbuf
2805 st.relocsym(s, P)
2806 }
2807 if _, err := z.Write(P); err != nil {
2808 log.Fatalf("compression failed: %s", err)
2809 }
2810 for i := ldr.SymSize(s) - int64(len(P)); i > 0; {
2811 b := zeros[:]
2812 if i < int64(len(b)) {
2813 b = b[:i]
2814 }
2815 n, err := z.Write(b)
2816 if err != nil {
2817 log.Fatalf("compression failed: %s", err)
2818 }
2819 i -= int64(n)
2820 }
2821 }
2822 if err := z.Close(); err != nil {
2823 log.Fatalf("compression failed: %s", err)
2824 }
2825 if int64(buf.Len()) >= total {
2826
2827 return nil
2828 }
2829 return buf.Bytes()
2830 }
2831
View as plain text