]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/link/internal/ld/data.go
8534a55111666b3cfe4d499fa8e0af18b7efc255
[gostls13.git] / src / cmd / link / internal / ld / data.go
1 // Derived from Inferno utils/6l/obj.c and utils/6l/span.c
2 // https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/obj.c
3 // https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/span.c
4 //
5 //      Copyright © 1994-1999 Lucent Technologies Inc.  All rights reserved.
6 //      Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
7 //      Portions Copyright © 1997-1999 Vita Nuova Limited
8 //      Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
9 //      Portions Copyright © 2004,2006 Bruce Ellis
10 //      Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net)
11 //      Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
12 //      Portions Copyright © 2009 The Go Authors. All rights reserved.
13 //
14 // Permission is hereby granted, free of charge, to any person obtaining a copy
15 // of this software and associated documentation files (the "Software"), to deal
16 // in the Software without restriction, including without limitation the rights
17 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18 // copies of the Software, and to permit persons to whom the Software is
19 // furnished to do so, subject to the following conditions:
20 //
21 // The above copyright notice and this permission notice shall be included in
22 // all copies or substantial portions of the Software.
23 //
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
27 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30 // THE SOFTWARE.
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/loadpe"
41         "cmd/link/internal/sym"
42         "compress/zlib"
43         "debug/elf"
44         "encoding/binary"
45         "fmt"
46         "log"
47         "os"
48         "sort"
49         "strconv"
50         "strings"
51         "sync"
52         "sync/atomic"
53 )
54
55 // isRuntimeDepPkg reports whether pkg is the runtime package or its dependency.
56 func isRuntimeDepPkg(pkg string) bool {
57         switch pkg {
58         case "runtime",
59                 "sync/atomic",      // runtime may call to sync/atomic, due to go:linkname
60                 "internal/abi",     // used by reflectcall (and maybe more)
61                 "internal/bytealg", // for IndexByte
62                 "internal/cpu":     // for cpu features
63                 return true
64         }
65         return strings.HasPrefix(pkg, "runtime/internal/") && !strings.HasSuffix(pkg, "_test")
66 }
67
68 // Estimate the max size needed to hold any new trampolines created for this function. This
69 // is used to determine when the section can be split if it becomes too large, to ensure that
70 // the trampolines are in the same section as the function that uses them.
71 func maxSizeTrampolines(ctxt *Link, ldr *loader.Loader, s loader.Sym, isTramp bool) uint64 {
72         // If thearch.Trampoline is nil, then trampoline support is not available on this arch.
73         // A trampoline does not need any dependent trampolines.
74         if thearch.Trampoline == nil || isTramp {
75                 return 0
76         }
77
78         n := uint64(0)
79         relocs := ldr.Relocs(s)
80         for ri := 0; ri < relocs.Count(); ri++ {
81                 r := relocs.At(ri)
82                 if r.Type().IsDirectCallOrJump() {
83                         n++
84                 }
85         }
86
87         switch {
88         case ctxt.IsARM():
89                 return n * 20 // Trampolines in ARM range from 3 to 5 instructions.
90         case ctxt.IsARM64():
91                 return n * 12 // Trampolines in ARM64 are 3 instructions.
92         case ctxt.IsPPC64():
93                 return n * 16 // Trampolines in PPC64 are 4 instructions.
94         case ctxt.IsRISCV64():
95                 return n * 8 // Trampolines in RISCV64 are 2 instructions.
96         }
97         panic("unreachable")
98 }
99
100 // Detect too-far jumps in function s, and add trampolines if necessary.
101 // ARM, PPC64, PPC64LE and RISCV64 support trampoline insertion for internal
102 // and external linking. On PPC64 and PPC64LE the text sections might be split
103 // but will still insert trampolines where necessary.
104 func trampoline(ctxt *Link, s loader.Sym) {
105         if thearch.Trampoline == nil {
106                 return // no need or no support of trampolines on this arch
107         }
108
109         ldr := ctxt.loader
110         relocs := ldr.Relocs(s)
111         for ri := 0; ri < relocs.Count(); ri++ {
112                 r := relocs.At(ri)
113                 rt := r.Type()
114                 if !rt.IsDirectCallOrJump() && !isPLTCall(rt) {
115                         continue
116                 }
117                 rs := r.Sym()
118                 if !ldr.AttrReachable(rs) || ldr.SymType(rs) == sym.Sxxx {
119                         continue // something is wrong. skip it here and we'll emit a better error later
120                 }
121
122                 if ldr.SymValue(rs) == 0 && ldr.SymType(rs) != sym.SDYNIMPORT && ldr.SymType(rs) != sym.SUNDEFEXT {
123                         // Symbols in the same package are laid out together.
124                         // Except that if SymPkg(s) == "", it is a host object symbol
125                         // which may call an external symbol via PLT.
126                         if ldr.SymPkg(s) != "" && ldr.SymPkg(rs) == ldr.SymPkg(s) {
127                                 // RISC-V is only able to reach +/-1MiB via a JAL instruction.
128                                 // We need to generate a trampoline when an address is
129                                 // currently unknown.
130                                 if !ctxt.Target.IsRISCV64() {
131                                         continue
132                                 }
133                         }
134                         // Runtime packages are laid out together.
135                         if isRuntimeDepPkg(ldr.SymPkg(s)) && isRuntimeDepPkg(ldr.SymPkg(rs)) {
136                                 continue
137                         }
138                 }
139                 thearch.Trampoline(ctxt, ldr, ri, rs, s)
140         }
141 }
142
143 // whether rt is a (host object) relocation that will be turned into
144 // a call to PLT.
145 func isPLTCall(rt objabi.RelocType) bool {
146         const pcrel = 1
147         switch rt {
148         // ARM64
149         case objabi.ElfRelocOffset + objabi.RelocType(elf.R_AARCH64_CALL26),
150                 objabi.ElfRelocOffset + objabi.RelocType(elf.R_AARCH64_JUMP26),
151                 objabi.MachoRelocOffset + MACHO_ARM64_RELOC_BRANCH26*2 + pcrel:
152                 return true
153
154         // ARM
155         case objabi.ElfRelocOffset + objabi.RelocType(elf.R_ARM_CALL),
156                 objabi.ElfRelocOffset + objabi.RelocType(elf.R_ARM_PC24),
157                 objabi.ElfRelocOffset + objabi.RelocType(elf.R_ARM_JUMP24):
158                 return true
159         }
160         // TODO: other architectures.
161         return false
162 }
163
164 // FoldSubSymbolOffset computes the offset of symbol s to its top-level outer
165 // symbol. Returns the top-level symbol and the offset.
166 // This is used in generating external relocations.
167 func FoldSubSymbolOffset(ldr *loader.Loader, s loader.Sym) (loader.Sym, int64) {
168         outer := ldr.OuterSym(s)
169         off := int64(0)
170         if outer != 0 {
171                 off += ldr.SymValue(s) - ldr.SymValue(outer)
172                 s = outer
173         }
174         return s, off
175 }
176
177 // relocsym resolve relocations in "s", updating the symbol's content
178 // in "P".
179 // The main loop walks through the list of relocations attached to "s"
180 // and resolves them where applicable. Relocations are often
181 // architecture-specific, requiring calls into the 'archreloc' and/or
182 // 'archrelocvariant' functions for the architecture. When external
183 // linking is in effect, it may not be  possible to completely resolve
184 // the address/offset for a symbol, in which case the goal is to lay
185 // the groundwork for turning a given relocation into an external reloc
186 // (to be applied by the external linker). For more on how relocations
187 // work in general, see
188 //
189 //      "Linkers and Loaders", by John R. Levine (Morgan Kaufmann, 1999), ch. 7
190 //
191 // This is a performance-critical function for the linker; be careful
192 // to avoid introducing unnecessary allocations in the main loop.
193 func (st *relocSymState) relocsym(s loader.Sym, P []byte) {
194         ldr := st.ldr
195         relocs := ldr.Relocs(s)
196         if relocs.Count() == 0 {
197                 return
198         }
199         target := st.target
200         syms := st.syms
201         nExtReloc := 0 // number of external relocations
202         for ri := 0; ri < relocs.Count(); ri++ {
203                 r := relocs.At(ri)
204                 off := r.Off()
205                 siz := int32(r.Siz())
206                 rs := r.Sym()
207                 rt := r.Type()
208                 weak := r.Weak()
209                 if off < 0 || off+siz > int32(len(P)) {
210                         rname := ""
211                         if rs != 0 {
212                                 rname = ldr.SymName(rs)
213                         }
214                         st.err.Errorf(s, "invalid relocation %s: %d+%d not in [%d,%d)", rname, off, siz, 0, len(P))
215                         continue
216                 }
217                 if siz == 0 { // informational relocation - no work to do
218                         continue
219                 }
220
221                 var rst sym.SymKind
222                 if rs != 0 {
223                         rst = ldr.SymType(rs)
224                 }
225
226                 if rs != 0 && (rst == sym.Sxxx || rst == sym.SXREF) {
227                         // When putting the runtime but not main into a shared library
228                         // these symbols are undefined and that's OK.
229                         if target.IsShared() || target.IsPlugin() {
230                                 if ldr.SymName(rs) == "main.main" || (!target.IsPlugin() && ldr.SymName(rs) == "main..inittask") {
231                                         sb := ldr.MakeSymbolUpdater(rs)
232                                         sb.SetType(sym.SDYNIMPORT)
233                                 } else if strings.HasPrefix(ldr.SymName(rs), "go:info.") {
234                                         // Skip go.info symbols. They are only needed to communicate
235                                         // DWARF info between the compiler and linker.
236                                         continue
237                                 }
238                         } else if target.IsPPC64() && ldr.SymName(rs) == ".TOC." {
239                                 // TOC symbol doesn't have a type but we do assign a value
240                                 // (see the address pass) and we can resolve it.
241                                 // TODO: give it a type.
242                         } else {
243                                 st.err.errorUnresolved(ldr, s, rs)
244                                 continue
245                         }
246                 }
247
248                 if rt >= objabi.ElfRelocOffset {
249                         continue
250                 }
251
252                 // We need to be able to reference dynimport symbols when linking against
253                 // shared libraries, and AIX, Darwin, OpenBSD and Solaris always need it.
254                 if !target.IsAIX() && !target.IsDarwin() && !target.IsSolaris() && !target.IsOpenbsd() && rs != 0 && rst == sym.SDYNIMPORT && !target.IsDynlinkingGo() && !ldr.AttrSubSymbol(rs) {
255                         if !(target.IsPPC64() && target.IsExternal() && ldr.SymName(rs) == ".TOC.") {
256                                 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))
257                         }
258                 }
259                 if rs != 0 && rst != sym.STLSBSS && !weak && rt != objabi.R_METHODOFF && !ldr.AttrReachable(rs) {
260                         st.err.Errorf(s, "unreachable sym in relocation: %s", ldr.SymName(rs))
261                 }
262
263                 var rv sym.RelocVariant
264                 if target.IsPPC64() || target.IsS390X() {
265                         rv = ldr.RelocVariant(s, ri)
266                 }
267
268                 // TODO(mundaym): remove this special case - see issue 14218.
269                 if target.IsS390X() {
270                         switch rt {
271                         case objabi.R_PCRELDBL:
272                                 rt = objabi.R_PCREL
273                                 rv = sym.RV_390_DBL
274                         case objabi.R_CALL:
275                                 rv = sym.RV_390_DBL
276                         }
277                 }
278
279                 var o int64
280                 switch rt {
281                 default:
282                         switch siz {
283                         default:
284                                 st.err.Errorf(s, "bad reloc size %#x for %s", uint32(siz), ldr.SymName(rs))
285                         case 1:
286                                 o = int64(P[off])
287                         case 2:
288                                 o = int64(target.Arch.ByteOrder.Uint16(P[off:]))
289                         case 4:
290                                 o = int64(target.Arch.ByteOrder.Uint32(P[off:]))
291                         case 8:
292                                 o = int64(target.Arch.ByteOrder.Uint64(P[off:]))
293                         }
294                         out, n, ok := thearch.Archreloc(target, ldr, syms, r, s, o)
295                         if target.IsExternal() {
296                                 nExtReloc += n
297                         }
298                         if ok {
299                                 o = out
300                         } else {
301                                 st.err.Errorf(s, "unknown reloc to %v: %d (%s)", ldr.SymName(rs), rt, sym.RelocName(target.Arch, rt))
302                         }
303                 case objabi.R_TLS_LE:
304                         if target.IsExternal() && target.IsElf() {
305                                 nExtReloc++
306                                 o = 0
307                                 if !target.IsAMD64() {
308                                         o = r.Add()
309                                 }
310                                 break
311                         }
312
313                         if target.IsElf() && target.IsARM() {
314                                 // On ELF ARM, the thread pointer is 8 bytes before
315                                 // the start of the thread-local data block, so add 8
316                                 // to the actual TLS offset (r->sym->value).
317                                 // This 8 seems to be a fundamental constant of
318                                 // ELF on ARM (or maybe Glibc on ARM); it is not
319                                 // related to the fact that our own TLS storage happens
320                                 // to take up 8 bytes.
321                                 o = 8 + ldr.SymValue(rs)
322                         } else if target.IsElf() || target.IsPlan9() || target.IsDarwin() {
323                                 o = int64(syms.Tlsoffset) + r.Add()
324                         } else if target.IsWindows() {
325                                 o = r.Add()
326                         } else {
327                                 log.Fatalf("unexpected R_TLS_LE relocation for %v", target.HeadType)
328                         }
329                 case objabi.R_TLS_IE:
330                         if target.IsExternal() && target.IsElf() {
331                                 nExtReloc++
332                                 o = 0
333                                 if !target.IsAMD64() {
334                                         o = r.Add()
335                                 }
336                                 if target.Is386() {
337                                         nExtReloc++ // need two ELF relocations on 386, see ../x86/asm.go:elfreloc1
338                                 }
339                                 break
340                         }
341                         if target.IsPIE() && target.IsElf() {
342                                 // We are linking the final executable, so we
343                                 // can optimize any TLS IE relocation to LE.
344                                 if thearch.TLSIEtoLE == nil {
345                                         log.Fatalf("internal linking of TLS IE not supported on %v", target.Arch.Family)
346                                 }
347                                 thearch.TLSIEtoLE(P, int(off), int(siz))
348                                 o = int64(syms.Tlsoffset)
349                         } else {
350                                 log.Fatalf("cannot handle R_TLS_IE (sym %s) when linking internally", ldr.SymName(s))
351                         }
352                 case objabi.R_ADDR, objabi.R_PEIMAGEOFF:
353                         if weak && !ldr.AttrReachable(rs) {
354                                 // Redirect it to runtime.unreachableMethod, which will throw if called.
355                                 rs = syms.unreachableMethod
356                         }
357                         if target.IsExternal() {
358                                 nExtReloc++
359
360                                 // set up addend for eventual relocation via outer symbol.
361                                 rs := rs
362                                 rs, off := FoldSubSymbolOffset(ldr, rs)
363                                 xadd := r.Add() + off
364                                 rst := ldr.SymType(rs)
365                                 if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && rst != sym.SUNDEFEXT && ldr.SymSect(rs) == nil {
366                                         st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
367                                 }
368
369                                 o = xadd
370                                 if target.IsElf() {
371                                         if target.IsAMD64() {
372                                                 o = 0
373                                         }
374                                 } else if target.IsDarwin() {
375                                         if ldr.SymType(s).IsDWARF() {
376                                                 // We generally use symbol-targeted relocations.
377                                                 // DWARF tools seem to only handle section-targeted relocations,
378                                                 // so generate section-targeted relocations in DWARF sections.
379                                                 // See also machoreloc1.
380                                                 o += ldr.SymValue(rs)
381                                         }
382                                 } else if target.IsWindows() {
383                                         // nothing to do
384                                 } else if target.IsAIX() {
385                                         o = ldr.SymValue(rs) + xadd
386                                 } else {
387                                         st.err.Errorf(s, "unhandled pcrel relocation to %s on %v", ldr.SymName(rs), target.HeadType)
388                                 }
389
390                                 break
391                         }
392
393                         // On AIX, a second relocation must be done by the loader,
394                         // as section addresses can change once loaded.
395                         // The "default" symbol address is still needed by the loader so
396                         // the current relocation can't be skipped.
397                         if target.IsAIX() && rst != sym.SDYNIMPORT {
398                                 // It's not possible to make a loader relocation in a
399                                 // symbol which is not inside .data section.
400                                 // FIXME: It should be forbidden to have R_ADDR from a
401                                 // symbol which isn't in .data. However, as .text has the
402                                 // same address once loaded, this is possible.
403                                 if ldr.SymSect(s).Seg == &Segdata {
404                                         Xcoffadddynrel(target, ldr, syms, s, r, ri)
405                                 }
406                         }
407
408                         o = ldr.SymValue(rs) + r.Add()
409                         if rt == objabi.R_PEIMAGEOFF {
410                                 // The R_PEIMAGEOFF offset is a RVA, so subtract
411                                 // the base address for the executable.
412                                 o -= PEBASE
413                         }
414
415                         // On amd64, 4-byte offsets will be sign-extended, so it is impossible to
416                         // access more than 2GB of static data; fail at link time is better than
417                         // fail at runtime. See https://golang.org/issue/7980.
418                         // Instead of special casing only amd64, we treat this as an error on all
419                         // 64-bit architectures so as to be future-proof.
420                         if int32(o) < 0 && target.Arch.PtrSize > 4 && siz == 4 {
421                                 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())
422                                 errorexit()
423                         }
424                 case objabi.R_DWARFSECREF:
425                         if ldr.SymSect(rs) == nil {
426                                 st.err.Errorf(s, "missing DWARF section for relocation target %s", ldr.SymName(rs))
427                         }
428
429                         if target.IsExternal() {
430                                 // On most platforms, the external linker needs to adjust DWARF references
431                                 // as it combines DWARF sections. However, on Darwin, dsymutil does the
432                                 // DWARF linking, and it understands how to follow section offsets.
433                                 // Leaving in the relocation records confuses it (see
434                                 // https://golang.org/issue/22068) so drop them for Darwin.
435                                 if !target.IsDarwin() {
436                                         nExtReloc++
437                                 }
438
439                                 xadd := r.Add() + ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr)
440
441                                 o = xadd
442                                 if target.IsElf() && target.IsAMD64() {
443                                         o = 0
444                                 }
445                                 break
446                         }
447                         o = ldr.SymValue(rs) + r.Add() - int64(ldr.SymSect(rs).Vaddr)
448                 case objabi.R_METHODOFF:
449                         if !ldr.AttrReachable(rs) {
450                                 // Set it to a sentinel value. The runtime knows this is not pointing to
451                                 // anything valid.
452                                 o = -1
453                                 break
454                         }
455                         fallthrough
456                 case objabi.R_ADDROFF:
457                         if weak && !ldr.AttrReachable(rs) {
458                                 continue
459                         }
460                         sect := ldr.SymSect(rs)
461                         if sect == nil {
462                                 if rst == sym.SDYNIMPORT {
463                                         st.err.Errorf(s, "cannot target DYNIMPORT sym in section-relative reloc: %s", ldr.SymName(rs))
464                                 } else if rst == sym.SUNDEFEXT {
465                                         st.err.Errorf(s, "undefined symbol in relocation: %s", ldr.SymName(rs))
466                                 } else {
467                                         st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
468                                 }
469                                 continue
470                         }
471
472                         // The method offset tables using this relocation expect the offset to be relative
473                         // to the start of the first text section, even if there are multiple.
474                         if sect.Name == ".text" {
475                                 o = ldr.SymValue(rs) - int64(Segtext.Sections[0].Vaddr) + r.Add()
476                         } else {
477                                 o = ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr) + r.Add()
478                         }
479
480                 case objabi.R_ADDRCUOFF:
481                         // debug_range and debug_loc elements use this relocation type to get an
482                         // offset from the start of the compile unit.
483                         o = ldr.SymValue(rs) + r.Add() - ldr.SymValue(loader.Sym(ldr.SymUnit(rs).Textp[0]))
484
485                 // r.Sym() can be 0 when CALL $(constant) is transformed from absolute PC to relative PC call.
486                 case objabi.R_GOTPCREL:
487                         if target.IsDynlinkingGo() && target.IsDarwin() && rs != 0 {
488                                 nExtReloc++
489                                 o = r.Add()
490                                 break
491                         }
492                         if target.Is386() && target.IsExternal() && target.IsELF {
493                                 nExtReloc++ // need two ELF relocations on 386, see ../x86/asm.go:elfreloc1
494                         }
495                         fallthrough
496                 case objabi.R_CALL, objabi.R_PCREL:
497                         if target.IsExternal() && rs != 0 && rst == sym.SUNDEFEXT {
498                                 // pass through to the external linker.
499                                 nExtReloc++
500                                 o = 0
501                                 break
502                         }
503                         if target.IsExternal() && rs != 0 && (ldr.SymSect(rs) != ldr.SymSect(s) || rt == objabi.R_GOTPCREL) {
504                                 nExtReloc++
505
506                                 // set up addend for eventual relocation via outer symbol.
507                                 rs := rs
508                                 rs, off := FoldSubSymbolOffset(ldr, rs)
509                                 xadd := r.Add() + off - int64(siz) // relative to address after the relocated chunk
510                                 rst := ldr.SymType(rs)
511                                 if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && ldr.SymSect(rs) == nil {
512                                         st.err.Errorf(s, "missing section for relocation target %s", ldr.SymName(rs))
513                                 }
514
515                                 o = xadd
516                                 if target.IsElf() {
517                                         if target.IsAMD64() {
518                                                 o = 0
519                                         }
520                                 } else if target.IsDarwin() {
521                                         if rt == objabi.R_CALL {
522                                                 if target.IsExternal() && rst == sym.SDYNIMPORT {
523                                                         if target.IsAMD64() {
524                                                                 // AMD64 dynamic relocations are relative to the end of the relocation.
525                                                                 o += int64(siz)
526                                                         }
527                                                 } else {
528                                                         if rst != sym.SHOSTOBJ {
529                                                                 o += int64(uint64(ldr.SymValue(rs)) - ldr.SymSect(rs).Vaddr)
530                                                         }
531                                                         o -= int64(off) // relative to section offset, not symbol
532                                                 }
533                                         } else {
534                                                 o += int64(siz)
535                                         }
536                                 } else if target.IsWindows() && target.IsAMD64() { // only amd64 needs PCREL
537                                         // PE/COFF's PC32 relocation uses the address after the relocated
538                                         // bytes as the base. Compensate by skewing the addend.
539                                         o += int64(siz)
540                                 } else {
541                                         st.err.Errorf(s, "unhandled pcrel relocation to %s on %v", ldr.SymName(rs), target.HeadType)
542                                 }
543
544                                 break
545                         }
546
547                         o = 0
548                         if rs != 0 {
549                                 o = ldr.SymValue(rs)
550                         }
551
552                         o += r.Add() - (ldr.SymValue(s) + int64(off) + int64(siz))
553                 case objabi.R_SIZE:
554                         o = ldr.SymSize(rs) + r.Add()
555
556                 case objabi.R_XCOFFREF:
557                         if !target.IsAIX() {
558                                 st.err.Errorf(s, "find XCOFF R_REF on non-XCOFF files")
559                         }
560                         if !target.IsExternal() {
561                                 st.err.Errorf(s, "find XCOFF R_REF with internal linking")
562                         }
563                         nExtReloc++
564                         continue
565
566                 case objabi.R_DWARFFILEREF:
567                         // We don't renumber files in dwarf.go:writelines anymore.
568                         continue
569
570                 case objabi.R_CONST:
571                         o = r.Add()
572
573                 case objabi.R_GOTOFF:
574                         o = ldr.SymValue(rs) + r.Add() - ldr.SymValue(syms.GOT)
575                 }
576
577                 if target.IsPPC64() || target.IsS390X() {
578                         if rv != sym.RV_NONE {
579                                 o = thearch.Archrelocvariant(target, ldr, r, rv, s, o, P)
580                         }
581                 }
582
583                 switch siz {
584                 default:
585                         st.err.Errorf(s, "bad reloc size %#x for %s", uint32(siz), ldr.SymName(rs))
586                 case 1:
587                         P[off] = byte(int8(o))
588                 case 2:
589                         if (rt == objabi.R_PCREL || rt == objabi.R_CALL) && o != int64(int16(o)) {
590                                 st.err.Errorf(s, "pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), o)
591                         } else if o != int64(int16(o)) && o != int64(uint16(o)) {
592                                 st.err.Errorf(s, "non-pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), uint64(o))
593                         }
594                         target.Arch.ByteOrder.PutUint16(P[off:], uint16(o))
595                 case 4:
596                         if (rt == objabi.R_PCREL || rt == objabi.R_CALL) && o != int64(int32(o)) {
597                                 st.err.Errorf(s, "pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), o)
598                         } else if o != int64(int32(o)) && o != int64(uint32(o)) {
599                                 st.err.Errorf(s, "non-pc-relative relocation address for %s is too big: %#x", ldr.SymName(rs), uint64(o))
600                         }
601                         target.Arch.ByteOrder.PutUint32(P[off:], uint32(o))
602                 case 8:
603                         target.Arch.ByteOrder.PutUint64(P[off:], uint64(o))
604                 }
605         }
606         if target.IsExternal() {
607                 // We'll stream out the external relocations in asmb2 (e.g. elfrelocsect)
608                 // and we only need the count here.
609                 atomic.AddUint32(&ldr.SymSect(s).Relcount, uint32(nExtReloc))
610         }
611 }
612
613 // Convert a Go relocation to an external relocation.
614 func extreloc(ctxt *Link, ldr *loader.Loader, s loader.Sym, r loader.Reloc) (loader.ExtReloc, bool) {
615         var rr loader.ExtReloc
616         target := &ctxt.Target
617         siz := int32(r.Siz())
618         if siz == 0 { // informational relocation - no work to do
619                 return rr, false
620         }
621
622         rt := r.Type()
623         if rt >= objabi.ElfRelocOffset {
624                 return rr, false
625         }
626         rr.Type = rt
627         rr.Size = uint8(siz)
628
629         // TODO(mundaym): remove this special case - see issue 14218.
630         if target.IsS390X() {
631                 switch rt {
632                 case objabi.R_PCRELDBL:
633                         rt = objabi.R_PCREL
634                 }
635         }
636
637         switch rt {
638         default:
639                 return thearch.Extreloc(target, ldr, r, s)
640
641         case objabi.R_TLS_LE, objabi.R_TLS_IE:
642                 if target.IsElf() {
643                         rs := r.Sym()
644                         rr.Xsym = rs
645                         if rr.Xsym == 0 {
646                                 rr.Xsym = ctxt.Tlsg
647                         }
648                         rr.Xadd = r.Add()
649                         break
650                 }
651                 return rr, false
652
653         case objabi.R_ADDR, objabi.R_PEIMAGEOFF:
654                 // set up addend for eventual relocation via outer symbol.
655                 rs := r.Sym()
656                 if r.Weak() && !ldr.AttrReachable(rs) {
657                         rs = ctxt.ArchSyms.unreachableMethod
658                 }
659                 rs, off := FoldSubSymbolOffset(ldr, rs)
660                 rr.Xadd = r.Add() + off
661                 rr.Xsym = rs
662
663         case objabi.R_DWARFSECREF:
664                 // On most platforms, the external linker needs to adjust DWARF references
665                 // as it combines DWARF sections. However, on Darwin, dsymutil does the
666                 // DWARF linking, and it understands how to follow section offsets.
667                 // Leaving in the relocation records confuses it (see
668                 // https://golang.org/issue/22068) so drop them for Darwin.
669                 if target.IsDarwin() {
670                         return rr, false
671                 }
672                 rs := r.Sym()
673                 rr.Xsym = loader.Sym(ldr.SymSect(rs).Sym)
674                 rr.Xadd = r.Add() + ldr.SymValue(rs) - int64(ldr.SymSect(rs).Vaddr)
675
676         // r.Sym() can be 0 when CALL $(constant) is transformed from absolute PC to relative PC call.
677         case objabi.R_GOTPCREL, objabi.R_CALL, objabi.R_PCREL:
678                 rs := r.Sym()
679                 if rt == objabi.R_GOTPCREL && target.IsDynlinkingGo() && target.IsDarwin() && rs != 0 {
680                         rr.Xadd = r.Add()
681                         rr.Xadd -= int64(siz) // relative to address after the relocated chunk
682                         rr.Xsym = rs
683                         break
684                 }
685                 if rs != 0 && ldr.SymType(rs) == sym.SUNDEFEXT {
686                         // pass through to the external linker.
687                         rr.Xadd = 0
688                         if target.IsElf() {
689                                 rr.Xadd -= int64(siz)
690                         }
691                         rr.Xsym = rs
692                         break
693                 }
694                 if rs != 0 && (ldr.SymSect(rs) != ldr.SymSect(s) || rt == objabi.R_GOTPCREL) {
695                         // set up addend for eventual relocation via outer symbol.
696                         rs := rs
697                         rs, off := FoldSubSymbolOffset(ldr, rs)
698                         rr.Xadd = r.Add() + off
699                         rr.Xadd -= int64(siz) // relative to address after the relocated chunk
700                         rr.Xsym = rs
701                         break
702                 }
703                 return rr, false
704
705         case objabi.R_XCOFFREF:
706                 return ExtrelocSimple(ldr, r), true
707
708         // These reloc types don't need external relocations.
709         case objabi.R_ADDROFF, objabi.R_METHODOFF, objabi.R_ADDRCUOFF,
710                 objabi.R_SIZE, objabi.R_CONST, objabi.R_GOTOFF:
711                 return rr, false
712         }
713         return rr, true
714 }
715
716 // ExtrelocSimple creates a simple external relocation from r, with the same
717 // symbol and addend.
718 func ExtrelocSimple(ldr *loader.Loader, r loader.Reloc) loader.ExtReloc {
719         var rr loader.ExtReloc
720         rs := r.Sym()
721         rr.Xsym = rs
722         rr.Xadd = r.Add()
723         rr.Type = r.Type()
724         rr.Size = r.Siz()
725         return rr
726 }
727
728 // ExtrelocViaOuterSym creates an external relocation from r targeting the
729 // outer symbol and folding the subsymbol's offset into the addend.
730 func ExtrelocViaOuterSym(ldr *loader.Loader, r loader.Reloc, s loader.Sym) loader.ExtReloc {
731         // set up addend for eventual relocation via outer symbol.
732         var rr loader.ExtReloc
733         rs := r.Sym()
734         rs, off := FoldSubSymbolOffset(ldr, rs)
735         rr.Xadd = r.Add() + off
736         rst := ldr.SymType(rs)
737         if rst != sym.SHOSTOBJ && rst != sym.SDYNIMPORT && rst != sym.SUNDEFEXT && ldr.SymSect(rs) == nil {
738                 ldr.Errorf(s, "missing section for %s", ldr.SymName(rs))
739         }
740         rr.Xsym = rs
741         rr.Type = r.Type()
742         rr.Size = r.Siz()
743         return rr
744 }
745
746 // relocSymState hold state information needed when making a series of
747 // successive calls to relocsym(). The items here are invariant
748 // (meaning that they are set up once initially and then don't change
749 // during the execution of relocsym), with the exception of a slice
750 // used to facilitate batch allocation of external relocations. Calls
751 // to relocsym happen in parallel; the assumption is that each
752 // parallel thread will have its own state object.
753 type relocSymState struct {
754         target *Target
755         ldr    *loader.Loader
756         err    *ErrorReporter
757         syms   *ArchSyms
758 }
759
760 // makeRelocSymState creates a relocSymState container object to
761 // pass to relocsym(). If relocsym() calls happen in parallel,
762 // each parallel thread should have its own state object.
763 func (ctxt *Link) makeRelocSymState() *relocSymState {
764         return &relocSymState{
765                 target: &ctxt.Target,
766                 ldr:    ctxt.loader,
767                 err:    &ctxt.ErrorReporter,
768                 syms:   &ctxt.ArchSyms,
769         }
770 }
771
772 // windynrelocsym examines a text symbol 's' and looks for relocations
773 // from it that correspond to references to symbols defined in DLLs,
774 // then fixes up those relocations as needed. A reference to a symbol
775 // XYZ from some DLL will fall into one of two categories: an indirect
776 // ref via "__imp_XYZ", or a direct ref to "XYZ". Here's an example of
777 // an indirect ref (this is an excerpt from objdump -ldr):
778 //
779 //           1c1: 48 89 c6                      movq    %rax, %rsi
780 //           1c4: ff 15 00 00 00 00             callq   *(%rip)
781 //                      00000000000001c6:  IMAGE_REL_AMD64_REL32        __imp__errno
782 //
783 // In the assembly above, the code loads up the value of __imp_errno
784 // and then does an indirect call to that value.
785 //
786 // Here is what a direct reference might look like:
787 //
788 //           137: e9 20 06 00 00                jmp     0x75c <pow+0x75c>
789 //           13c: e8 00 00 00 00                callq   0x141 <pow+0x141>
790 //                      000000000000013d:  IMAGE_REL_AMD64_REL32        _errno
791 //
792 // The assembly below dispenses with the import symbol and just makes
793 // a direct call to _errno.
794 //
795 // The code below handles indirect refs by redirecting the target of
796 // the relocation from "__imp_XYZ" to "XYZ" (since the latter symbol
797 // is what the Windows loader is expected to resolve). For direct refs
798 // the call is redirected to a stub, where the stub first loads the
799 // symbol and then direct an indirect call to that value.
800 //
801 // Note that for a given symbol (as above) it is perfectly legal to
802 // have both direct and indirect references.
803 func windynrelocsym(ctxt *Link, rel *loader.SymbolBuilder, s loader.Sym) error {
804         var su *loader.SymbolBuilder
805         relocs := ctxt.loader.Relocs(s)
806         for ri := 0; ri < relocs.Count(); ri++ {
807                 r := relocs.At(ri)
808                 if r.IsMarker() {
809                         continue // skip marker relocations
810                 }
811                 targ := r.Sym()
812                 if targ == 0 {
813                         continue
814                 }
815                 if !ctxt.loader.AttrReachable(targ) {
816                         if r.Weak() {
817                                 continue
818                         }
819                         return fmt.Errorf("dynamic relocation to unreachable symbol %s",
820                                 ctxt.loader.SymName(targ))
821                 }
822                 tgot := ctxt.loader.SymGot(targ)
823                 if tgot == loadpe.RedirectToDynImportGotToken {
824
825                         // Consistency check: name should be __imp_X
826                         sname := ctxt.loader.SymName(targ)
827                         if !strings.HasPrefix(sname, "__imp_") {
828                                 return fmt.Errorf("internal error in windynrelocsym: redirect GOT token applied to non-import symbol %s", sname)
829                         }
830
831                         // Locate underlying symbol (which originally had type
832                         // SDYNIMPORT but has since been retyped to SWINDOWS).
833                         ds, err := loadpe.LookupBaseFromImport(targ, ctxt.loader, ctxt.Arch)
834                         if err != nil {
835                                 return err
836                         }
837                         dstyp := ctxt.loader.SymType(ds)
838                         if dstyp != sym.SWINDOWS {
839                                 return fmt.Errorf("internal error in windynrelocsym: underlying sym for %q has wrong type %s", sname, dstyp.String())
840                         }
841
842                         // Redirect relocation to the dynimport.
843                         r.SetSym(ds)
844                         continue
845                 }
846
847                 tplt := ctxt.loader.SymPlt(targ)
848                 if tplt == loadpe.CreateImportStubPltToken {
849
850                         // Consistency check: don't want to see both PLT and GOT tokens.
851                         if tgot != -1 {
852                                 return fmt.Errorf("internal error in windynrelocsym: invalid GOT setting %d for reloc to %s", tgot, ctxt.loader.SymName(targ))
853                         }
854
855                         // make dynimport JMP table for PE object files.
856                         tplt := int32(rel.Size())
857                         ctxt.loader.SetPlt(targ, tplt)
858
859                         if su == nil {
860                                 su = ctxt.loader.MakeSymbolUpdater(s)
861                         }
862                         r.SetSym(rel.Sym())
863                         r.SetAdd(int64(tplt))
864
865                         // jmp *addr
866                         switch ctxt.Arch.Family {
867                         default:
868                                 return fmt.Errorf("internal error in windynrelocsym: unsupported arch %v", ctxt.Arch.Family)
869                         case sys.I386:
870                                 rel.AddUint8(0xff)
871                                 rel.AddUint8(0x25)
872                                 rel.AddAddrPlus(ctxt.Arch, targ, 0)
873                                 rel.AddUint8(0x90)
874                                 rel.AddUint8(0x90)
875                         case sys.AMD64:
876                                 rel.AddUint8(0xff)
877                                 rel.AddUint8(0x24)
878                                 rel.AddUint8(0x25)
879                                 rel.AddAddrPlus4(ctxt.Arch, targ, 0)
880                                 rel.AddUint8(0x90)
881                         }
882                 } else if tplt >= 0 {
883                         if su == nil {
884                                 su = ctxt.loader.MakeSymbolUpdater(s)
885                         }
886                         r.SetSym(rel.Sym())
887                         r.SetAdd(int64(tplt))
888                 }
889         }
890         return nil
891 }
892
893 // windynrelocsyms generates jump table to C library functions that will be
894 // added later. windynrelocsyms writes the table into .rel symbol.
895 func (ctxt *Link) windynrelocsyms() {
896         if !(ctxt.IsWindows() && iscgo && ctxt.IsInternal()) {
897                 return
898         }
899
900         rel := ctxt.loader.CreateSymForUpdate(".rel", 0)
901         rel.SetType(sym.STEXT)
902
903         for _, s := range ctxt.Textp {
904                 if err := windynrelocsym(ctxt, rel, s); err != nil {
905                         ctxt.Errorf(s, "%v", err)
906                 }
907         }
908
909         ctxt.Textp = append(ctxt.Textp, rel.Sym())
910 }
911
912 func dynrelocsym(ctxt *Link, s loader.Sym) {
913         target := &ctxt.Target
914         ldr := ctxt.loader
915         syms := &ctxt.ArchSyms
916         relocs := ldr.Relocs(s)
917         for ri := 0; ri < relocs.Count(); ri++ {
918                 r := relocs.At(ri)
919                 if r.IsMarker() {
920                         continue // skip marker relocations
921                 }
922                 rSym := r.Sym()
923                 if r.Weak() && !ldr.AttrReachable(rSym) {
924                         continue
925                 }
926                 if ctxt.BuildMode == BuildModePIE && ctxt.LinkMode == LinkInternal {
927                         // It's expected that some relocations will be done
928                         // later by relocsym (R_TLS_LE, R_ADDROFF), so
929                         // don't worry if Adddynrel returns false.
930                         thearch.Adddynrel(target, ldr, syms, s, r, ri)
931                         continue
932                 }
933
934                 if rSym != 0 && ldr.SymType(rSym) == sym.SDYNIMPORT || r.Type() >= objabi.ElfRelocOffset {
935                         if rSym != 0 && !ldr.AttrReachable(rSym) {
936                                 ctxt.Errorf(s, "dynamic relocation to unreachable symbol %s", ldr.SymName(rSym))
937                         }
938                         if !thearch.Adddynrel(target, ldr, syms, s, r, ri) {
939                                 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))
940                         }
941                 }
942         }
943 }
944
945 func (state *dodataState) dynreloc(ctxt *Link) {
946         if ctxt.HeadType == objabi.Hwindows {
947                 return
948         }
949         // -d suppresses dynamic loader format, so we may as well not
950         // compute these sections or mark their symbols as reachable.
951         if *FlagD {
952                 return
953         }
954
955         for _, s := range ctxt.Textp {
956                 dynrelocsym(ctxt, s)
957         }
958         for _, syms := range state.data {
959                 for _, s := range syms {
960                         dynrelocsym(ctxt, s)
961                 }
962         }
963         if ctxt.IsELF {
964                 elfdynhash(ctxt)
965         }
966 }
967
968 func CodeblkPad(ctxt *Link, out *OutBuf, addr int64, size int64, pad []byte) {
969         writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, ctxt.Textp, addr, size, pad)
970 }
971
972 const blockSize = 1 << 20 // 1MB chunks written at a time.
973
974 // writeBlocks writes a specified chunk of symbols to the output buffer. It
975 // breaks the write up into ≥blockSize chunks to write them out, and schedules
976 // as many goroutines as necessary to accomplish this task. This call then
977 // blocks, waiting on the writes to complete. Note that we use the sem parameter
978 // to limit the number of concurrent writes taking place.
979 func writeBlocks(ctxt *Link, out *OutBuf, sem chan int, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
980         for i, s := range syms {
981                 if ldr.SymValue(s) >= addr && !ldr.AttrSubSymbol(s) {
982                         syms = syms[i:]
983                         break
984                 }
985         }
986
987         var wg sync.WaitGroup
988         max, lastAddr, written := int64(blockSize), addr+size, int64(0)
989         for addr < lastAddr {
990                 // Find the last symbol we'd write.
991                 idx := -1
992                 for i, s := range syms {
993                         if ldr.AttrSubSymbol(s) {
994                                 continue
995                         }
996
997                         // If the next symbol's size would put us out of bounds on the total length,
998                         // stop looking.
999                         end := ldr.SymValue(s) + ldr.SymSize(s)
1000                         if end > lastAddr {
1001                                 break
1002                         }
1003
1004                         // We're gonna write this symbol.
1005                         idx = i
1006
1007                         // If we cross over the max size, we've got enough symbols.
1008                         if end > addr+max {
1009                                 break
1010                         }
1011                 }
1012
1013                 // If we didn't find any symbols to write, we're done here.
1014                 if idx < 0 {
1015                         break
1016                 }
1017
1018                 // Compute the length to write, including padding.
1019                 // We need to write to the end address (lastAddr), or the next symbol's
1020                 // start address, whichever comes first. If there is no more symbols,
1021                 // just write to lastAddr. This ensures we don't leave holes between the
1022                 // blocks or at the end.
1023                 length := int64(0)
1024                 if idx+1 < len(syms) {
1025                         // Find the next top-level symbol.
1026                         // Skip over sub symbols so we won't split a container symbol
1027                         // into two blocks.
1028                         next := syms[idx+1]
1029                         for ldr.AttrSubSymbol(next) {
1030                                 idx++
1031                                 next = syms[idx+1]
1032                         }
1033                         length = ldr.SymValue(next) - addr
1034                 }
1035                 if length == 0 || length > lastAddr-addr {
1036                         length = lastAddr - addr
1037                 }
1038
1039                 // Start the block output operator.
1040                 if o, err := out.View(uint64(out.Offset() + written)); err == nil {
1041                         sem <- 1
1042                         wg.Add(1)
1043                         go func(o *OutBuf, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
1044                                 writeBlock(ctxt, o, ldr, syms, addr, size, pad)
1045                                 wg.Done()
1046                                 <-sem
1047                         }(o, ldr, syms, addr, length, pad)
1048                 } else { // output not mmaped, don't parallelize.
1049                         writeBlock(ctxt, out, ldr, syms, addr, length, pad)
1050                 }
1051
1052                 // Prepare for the next loop.
1053                 if idx != -1 {
1054                         syms = syms[idx+1:]
1055                 }
1056                 written += length
1057                 addr += length
1058         }
1059         wg.Wait()
1060 }
1061
1062 func writeBlock(ctxt *Link, out *OutBuf, ldr *loader.Loader, syms []loader.Sym, addr, size int64, pad []byte) {
1063
1064         st := ctxt.makeRelocSymState()
1065
1066         // This doesn't distinguish the memory size from the file
1067         // size, and it lays out the file based on Symbol.Value, which
1068         // is the virtual address. DWARF compression changes file sizes,
1069         // so dwarfcompress will fix this up later if necessary.
1070         eaddr := addr + size
1071         for _, s := range syms {
1072                 if ldr.AttrSubSymbol(s) {
1073                         continue
1074                 }
1075                 val := ldr.SymValue(s)
1076                 if val >= eaddr {
1077                         break
1078                 }
1079                 if val < addr {
1080                         ldr.Errorf(s, "phase error: addr=%#x but val=%#x sym=%s type=%v sect=%v sect.addr=%#x", addr, val, ldr.SymName(s), ldr.SymType(s), ldr.SymSect(s).Name, ldr.SymSect(s).Vaddr)
1081                         errorexit()
1082                 }
1083                 if addr < val {
1084                         out.WriteStringPad("", int(val-addr), pad)
1085                         addr = val
1086                 }
1087                 P := out.WriteSym(ldr, s)
1088                 st.relocsym(s, P)
1089                 if ldr.IsGeneratedSym(s) {
1090                         f := ctxt.generatorSyms[s]
1091                         f(ctxt, s)
1092                 }
1093                 addr += int64(len(P))
1094                 siz := ldr.SymSize(s)
1095                 if addr < val+siz {
1096                         out.WriteStringPad("", int(val+siz-addr), pad)
1097                         addr = val + siz
1098                 }
1099                 if addr != val+siz {
1100                         ldr.Errorf(s, "phase error: addr=%#x value+size=%#x", addr, val+siz)
1101                         errorexit()
1102                 }
1103                 if val+siz >= eaddr {
1104                         break
1105                 }
1106         }
1107
1108         if addr < eaddr {
1109                 out.WriteStringPad("", int(eaddr-addr), pad)
1110         }
1111 }
1112
1113 type writeFn func(*Link, *OutBuf, int64, int64)
1114
1115 // writeParallel handles scheduling parallel execution of data write functions.
1116 func writeParallel(wg *sync.WaitGroup, fn writeFn, ctxt *Link, seek, vaddr, length uint64) {
1117         if out, err := ctxt.Out.View(seek); err != nil {
1118                 ctxt.Out.SeekSet(int64(seek))
1119                 fn(ctxt, ctxt.Out, int64(vaddr), int64(length))
1120         } else {
1121                 wg.Add(1)
1122                 go func() {
1123                         defer wg.Done()
1124                         fn(ctxt, out, int64(vaddr), int64(length))
1125                 }()
1126         }
1127 }
1128
1129 func datblk(ctxt *Link, out *OutBuf, addr, size int64) {
1130         writeDatblkToOutBuf(ctxt, out, addr, size)
1131 }
1132
1133 // Used only on Wasm for now.
1134 func DatblkBytes(ctxt *Link, addr int64, size int64) []byte {
1135         buf := make([]byte, size)
1136         out := &OutBuf{heap: buf}
1137         writeDatblkToOutBuf(ctxt, out, addr, size)
1138         return buf
1139 }
1140
1141 func writeDatblkToOutBuf(ctxt *Link, out *OutBuf, addr int64, size int64) {
1142         writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, ctxt.datap, addr, size, zeros[:])
1143 }
1144
1145 func dwarfblk(ctxt *Link, out *OutBuf, addr int64, size int64) {
1146         // Concatenate the section symbol lists into a single list to pass
1147         // to writeBlocks.
1148         //
1149         // NB: ideally we would do a separate writeBlocks call for each
1150         // section, but this would run the risk of undoing any file offset
1151         // adjustments made during layout.
1152         n := 0
1153         for i := range dwarfp {
1154                 n += len(dwarfp[i].syms)
1155         }
1156         syms := make([]loader.Sym, 0, n)
1157         for i := range dwarfp {
1158                 syms = append(syms, dwarfp[i].syms...)
1159         }
1160         writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, syms, addr, size, zeros[:])
1161 }
1162
1163 func pdatablk(ctxt *Link, out *OutBuf, addr int64, size int64) {
1164         writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, []loader.Sym{sehp.pdata}, addr, size, zeros[:])
1165 }
1166
1167 func xdatablk(ctxt *Link, out *OutBuf, addr int64, size int64) {
1168         writeBlocks(ctxt, out, ctxt.outSem, ctxt.loader, []loader.Sym{sehp.xdata}, addr, size, zeros[:])
1169 }
1170
1171 var covCounterDataStartOff, covCounterDataLen uint64
1172
1173 var zeros [512]byte
1174
1175 var (
1176         strdata  = make(map[string]string)
1177         strnames []string
1178 )
1179
1180 func addstrdata1(ctxt *Link, arg string) {
1181         eq := strings.Index(arg, "=")
1182         dot := strings.LastIndex(arg[:eq+1], ".")
1183         if eq < 0 || dot < 0 {
1184                 Exitf("-X flag requires argument of the form importpath.name=value")
1185         }
1186         pkg := arg[:dot]
1187         if ctxt.BuildMode == BuildModePlugin && pkg == "main" {
1188                 pkg = *flagPluginPath
1189         }
1190         pkg = objabi.PathToPrefix(pkg)
1191         name := pkg + arg[dot:eq]
1192         value := arg[eq+1:]
1193         if _, ok := strdata[name]; !ok {
1194                 strnames = append(strnames, name)
1195         }
1196         strdata[name] = value
1197 }
1198
1199 // addstrdata sets the initial value of the string variable name to value.
1200 func addstrdata(arch *sys.Arch, l *loader.Loader, name, value string) {
1201         s := l.Lookup(name, 0)
1202         if s == 0 {
1203                 return
1204         }
1205         if goType := l.SymGoType(s); goType == 0 {
1206                 return
1207         } else if typeName := l.SymName(goType); typeName != "type:string" {
1208                 Errorf(nil, "%s: cannot set with -X: not a var of type string (%s)", name, typeName)
1209                 return
1210         }
1211         if !l.AttrReachable(s) {
1212                 return // don't bother setting unreachable variable
1213         }
1214         bld := l.MakeSymbolUpdater(s)
1215         if bld.Type() == sym.SBSS {
1216                 bld.SetType(sym.SDATA)
1217         }
1218
1219         p := fmt.Sprintf("%s.str", name)
1220         sbld := l.CreateSymForUpdate(p, 0)
1221         sbld.Addstring(value)
1222         sbld.SetType(sym.SRODATA)
1223
1224         // Don't reset the variable's size. String variable usually has size of
1225         // 2*PtrSize, but in ASAN build it can be larger due to red zone.
1226         // (See issue 56175.)
1227         bld.SetData(make([]byte, arch.PtrSize*2))
1228         bld.SetReadOnly(false)
1229         bld.ResetRelocs()
1230         bld.SetAddrPlus(arch, 0, sbld.Sym(), 0)
1231         bld.SetUint(arch, int64(arch.PtrSize), uint64(len(value)))
1232 }
1233
1234 func (ctxt *Link) dostrdata() {
1235         for _, name := range strnames {
1236                 addstrdata(ctxt.Arch, ctxt.loader, name, strdata[name])
1237         }
1238 }
1239
1240 // addgostring adds str, as a Go string value, to s. symname is the name of the
1241 // symbol used to define the string data and must be unique per linked object.
1242 func addgostring(ctxt *Link, ldr *loader.Loader, s *loader.SymbolBuilder, symname, str string) {
1243         sdata := ldr.CreateSymForUpdate(symname, 0)
1244         if sdata.Type() != sym.Sxxx {
1245                 ctxt.Errorf(s.Sym(), "duplicate symname in addgostring: %s", symname)
1246         }
1247         sdata.SetLocal(true)
1248         sdata.SetType(sym.SRODATA)
1249         sdata.SetSize(int64(len(str)))
1250         sdata.SetData([]byte(str))
1251         s.AddAddr(ctxt.Arch, sdata.Sym())
1252         s.AddUint(ctxt.Arch, uint64(len(str)))
1253 }
1254
1255 func addinitarrdata(ctxt *Link, ldr *loader.Loader, s loader.Sym) {
1256         p := ldr.SymName(s) + ".ptr"
1257         sp := ldr.CreateSymForUpdate(p, 0)
1258         sp.SetType(sym.SINITARR)
1259         sp.SetSize(0)
1260         sp.SetDuplicateOK(true)
1261         sp.AddAddr(ctxt.Arch, s)
1262 }
1263
1264 // symalign returns the required alignment for the given symbol s.
1265 func symalign(ldr *loader.Loader, s loader.Sym) int32 {
1266         min := int32(thearch.Minalign)
1267         align := ldr.SymAlign(s)
1268         if align >= min {
1269                 return align
1270         } else if align != 0 {
1271                 return min
1272         }
1273         align = int32(thearch.Maxalign)
1274         ssz := ldr.SymSize(s)
1275         for int64(align) > ssz && align > min {
1276                 align >>= 1
1277         }
1278         ldr.SetSymAlign(s, align)
1279         return align
1280 }
1281
1282 func aligndatsize(state *dodataState, datsize int64, s loader.Sym) int64 {
1283         return Rnd(datsize, int64(symalign(state.ctxt.loader, s)))
1284 }
1285
1286 const debugGCProg = false
1287
1288 type GCProg struct {
1289         ctxt *Link
1290         sym  *loader.SymbolBuilder
1291         w    gcprog.Writer
1292 }
1293
1294 func (p *GCProg) Init(ctxt *Link, name string) {
1295         p.ctxt = ctxt
1296         p.sym = ctxt.loader.CreateSymForUpdate(name, 0)
1297         p.w.Init(p.writeByte())
1298         if debugGCProg {
1299                 fmt.Fprintf(os.Stderr, "ld: start GCProg %s\n", name)
1300                 p.w.Debug(os.Stderr)
1301         }
1302 }
1303
1304 func (p *GCProg) writeByte() func(x byte) {
1305         return func(x byte) {
1306                 p.sym.AddUint8(x)
1307         }
1308 }
1309
1310 func (p *GCProg) End(size int64) {
1311         p.w.ZeroUntil(size / int64(p.ctxt.Arch.PtrSize))
1312         p.w.End()
1313         if debugGCProg {
1314                 fmt.Fprintf(os.Stderr, "ld: end GCProg\n")
1315         }
1316 }
1317
1318 func (p *GCProg) AddSym(s loader.Sym) {
1319         ldr := p.ctxt.loader
1320         typ := ldr.SymGoType(s)
1321
1322         // Things without pointers should be in sym.SNOPTRDATA or sym.SNOPTRBSS;
1323         // everything we see should have pointers and should therefore have a type.
1324         if typ == 0 {
1325                 switch ldr.SymName(s) {
1326                 case "runtime.data", "runtime.edata", "runtime.bss", "runtime.ebss":
1327                         // Ignore special symbols that are sometimes laid out
1328                         // as real symbols. See comment about dyld on darwin in
1329                         // the address function.
1330                         return
1331                 }
1332                 p.ctxt.Errorf(p.sym.Sym(), "missing Go type information for global symbol %s: size %d", ldr.SymName(s), ldr.SymSize(s))
1333                 return
1334         }
1335
1336         ptrsize := int64(p.ctxt.Arch.PtrSize)
1337         typData := ldr.Data(typ)
1338         nptr := decodetypePtrdata(p.ctxt.Arch, typData) / ptrsize
1339
1340         if debugGCProg {
1341                 fmt.Fprintf(os.Stderr, "gcprog sym: %s at %d (ptr=%d+%d)\n", ldr.SymName(s), ldr.SymValue(s), ldr.SymValue(s)/ptrsize, nptr)
1342         }
1343
1344         sval := ldr.SymValue(s)
1345         if decodetypeUsegcprog(p.ctxt.Arch, typData) == 0 {
1346                 // Copy pointers from mask into program.
1347                 mask := decodetypeGcmask(p.ctxt, typ)
1348                 for i := int64(0); i < nptr; i++ {
1349                         if (mask[i/8]>>uint(i%8))&1 != 0 {
1350                                 p.w.Ptr(sval/ptrsize + i)
1351                         }
1352                 }
1353                 return
1354         }
1355
1356         // Copy program.
1357         prog := decodetypeGcprog(p.ctxt, typ)
1358         p.w.ZeroUntil(sval / ptrsize)
1359         p.w.Append(prog[4:], nptr)
1360 }
1361
1362 // cutoff is the maximum data section size permitted by the linker
1363 // (see issue #9862).
1364 const cutoff = 2e9 // 2 GB (or so; looks better in errors than 2^31)
1365
1366 // check accumulated size of data sections
1367 func (state *dodataState) checkdatsize(symn sym.SymKind) {
1368         if state.datsize > cutoff {
1369                 Errorf(nil, "too much data, last section %v (%d, over %v bytes)", symn, state.datsize, cutoff)
1370         }
1371 }
1372
1373 func checkSectSize(sect *sym.Section) {
1374         // TODO: consider using 4 GB size limit for DWARF sections, and
1375         // make sure we generate unsigned offset in relocations and check
1376         // for overflow.
1377         if sect.Length > cutoff {
1378                 Errorf(nil, "too much data in section %s (%d, over %v bytes)", sect.Name, sect.Length, cutoff)
1379         }
1380 }
1381
1382 // fixZeroSizedSymbols gives a few special symbols with zero size some space.
1383 func fixZeroSizedSymbols(ctxt *Link) {
1384         // The values in moduledata are filled out by relocations
1385         // pointing to the addresses of these special symbols.
1386         // Typically these symbols have no size and are not laid
1387         // out with their matching section.
1388         //
1389         // However on darwin, dyld will find the special symbol
1390         // in the first loaded module, even though it is local.
1391         //
1392         // (An hypothesis, formed without looking in the dyld sources:
1393         // these special symbols have no size, so their address
1394         // matches a real symbol. The dynamic linker assumes we
1395         // want the normal symbol with the same address and finds
1396         // it in the other module.)
1397         //
1398         // To work around this we lay out the symbls whose
1399         // addresses are vital for multi-module programs to work
1400         // as normal symbols, and give them a little size.
1401         //
1402         // On AIX, as all DATA sections are merged together, ld might not put
1403         // these symbols at the beginning of their respective section if there
1404         // aren't real symbols, their alignment might not match the
1405         // first symbol alignment. Therefore, there are explicitly put at the
1406         // beginning of their section with the same alignment.
1407         if !(ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin) && !(ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal) {
1408                 return
1409         }
1410
1411         ldr := ctxt.loader
1412         bss := ldr.CreateSymForUpdate("runtime.bss", 0)
1413         bss.SetSize(8)
1414         ldr.SetAttrSpecial(bss.Sym(), false)
1415
1416         ebss := ldr.CreateSymForUpdate("runtime.ebss", 0)
1417         ldr.SetAttrSpecial(ebss.Sym(), false)
1418
1419         data := ldr.CreateSymForUpdate("runtime.data", 0)
1420         data.SetSize(8)
1421         ldr.SetAttrSpecial(data.Sym(), false)
1422
1423         edata := ldr.CreateSymForUpdate("runtime.edata", 0)
1424         ldr.SetAttrSpecial(edata.Sym(), false)
1425
1426         if ctxt.HeadType == objabi.Haix {
1427                 // XCOFFTOC symbols are part of .data section.
1428                 edata.SetType(sym.SXCOFFTOC)
1429         }
1430
1431         noptrbss := ldr.CreateSymForUpdate("runtime.noptrbss", 0)
1432         noptrbss.SetSize(8)
1433         ldr.SetAttrSpecial(noptrbss.Sym(), false)
1434
1435         enoptrbss := ldr.CreateSymForUpdate("runtime.enoptrbss", 0)
1436         ldr.SetAttrSpecial(enoptrbss.Sym(), false)
1437
1438         noptrdata := ldr.CreateSymForUpdate("runtime.noptrdata", 0)
1439         noptrdata.SetSize(8)
1440         ldr.SetAttrSpecial(noptrdata.Sym(), false)
1441
1442         enoptrdata := ldr.CreateSymForUpdate("runtime.enoptrdata", 0)
1443         ldr.SetAttrSpecial(enoptrdata.Sym(), false)
1444
1445         types := ldr.CreateSymForUpdate("runtime.types", 0)
1446         types.SetType(sym.STYPE)
1447         types.SetSize(8)
1448         ldr.SetAttrSpecial(types.Sym(), false)
1449
1450         etypes := ldr.CreateSymForUpdate("runtime.etypes", 0)
1451         etypes.SetType(sym.SFUNCTAB)
1452         ldr.SetAttrSpecial(etypes.Sym(), false)
1453
1454         if ctxt.HeadType == objabi.Haix {
1455                 rodata := ldr.CreateSymForUpdate("runtime.rodata", 0)
1456                 rodata.SetType(sym.SSTRING)
1457                 rodata.SetSize(8)
1458                 ldr.SetAttrSpecial(rodata.Sym(), false)
1459
1460                 erodata := ldr.CreateSymForUpdate("runtime.erodata", 0)
1461                 ldr.SetAttrSpecial(erodata.Sym(), false)
1462         }
1463 }
1464
1465 // makeRelroForSharedLib creates a section of readonly data if necessary.
1466 func (state *dodataState) makeRelroForSharedLib(target *Link) {
1467         if !target.UseRelro() {
1468                 return
1469         }
1470
1471         // "read only" data with relocations needs to go in its own section
1472         // when building a shared library. We do this by boosting objects of
1473         // type SXXX with relocations to type SXXXRELRO.
1474         ldr := target.loader
1475         for _, symnro := range sym.ReadOnly {
1476                 symnrelro := sym.RelROMap[symnro]
1477
1478                 ro := []loader.Sym{}
1479                 relro := state.data[symnrelro]
1480
1481                 for _, s := range state.data[symnro] {
1482                         relocs := ldr.Relocs(s)
1483                         isRelro := relocs.Count() > 0
1484                         switch state.symType(s) {
1485                         case sym.STYPE, sym.STYPERELRO, sym.SGOFUNCRELRO:
1486                                 // Symbols are not sorted yet, so it is possible
1487                                 // that an Outer symbol has been changed to a
1488                                 // relro Type before it reaches here.
1489                                 isRelro = true
1490                         case sym.SFUNCTAB:
1491                                 if ldr.SymName(s) == "runtime.etypes" {
1492                                         // runtime.etypes must be at the end of
1493                                         // the relro data.
1494                                         isRelro = true
1495                                 }
1496                         case sym.SGOFUNC:
1497                                 // The only SGOFUNC symbols that contain relocations are .stkobj,
1498                                 // and their relocations are of type objabi.R_ADDROFF,
1499                                 // which always get resolved during linking.
1500                                 isRelro = false
1501                         }
1502                         if isRelro {
1503                                 state.setSymType(s, symnrelro)
1504                                 if outer := ldr.OuterSym(s); outer != 0 {
1505                                         state.setSymType(outer, symnrelro)
1506                                 }
1507                                 relro = append(relro, s)
1508                         } else {
1509                                 ro = append(ro, s)
1510                         }
1511                 }
1512
1513                 // Check that we haven't made two symbols with the same .Outer into
1514                 // different types (because references two symbols with non-nil Outer
1515                 // become references to the outer symbol + offset it's vital that the
1516                 // symbol and the outer end up in the same section).
1517                 for _, s := range relro {
1518                         if outer := ldr.OuterSym(s); outer != 0 {
1519                                 st := state.symType(s)
1520                                 ost := state.symType(outer)
1521                                 if st != ost {
1522                                         state.ctxt.Errorf(s, "inconsistent types for symbol and its Outer %s (%v != %v)",
1523                                                 ldr.SymName(outer), st, ost)
1524                                 }
1525                         }
1526                 }
1527
1528                 state.data[symnro] = ro
1529                 state.data[symnrelro] = relro
1530         }
1531 }
1532
1533 // dodataState holds bits of state information needed by dodata() and the
1534 // various helpers it calls. The lifetime of these items should not extend
1535 // past the end of dodata().
1536 type dodataState struct {
1537         // Link context
1538         ctxt *Link
1539         // Data symbols bucketed by type.
1540         data [sym.SXREF][]loader.Sym
1541         // Max alignment for each flavor of data symbol.
1542         dataMaxAlign [sym.SXREF]int32
1543         // Overridden sym type
1544         symGroupType []sym.SymKind
1545         // Current data size so far.
1546         datsize int64
1547 }
1548
1549 // A note on symType/setSymType below:
1550 //
1551 // In the legacy linker, the types of symbols (notably data symbols) are
1552 // changed during the symtab() phase so as to insure that similar symbols
1553 // are bucketed together, then their types are changed back again during
1554 // dodata. Symbol to section assignment also plays tricks along these lines
1555 // in the case where a relro segment is needed.
1556 //
1557 // The value returned from setType() below reflects the effects of
1558 // any overrides made by symtab and/or dodata.
1559
1560 // symType returns the (possibly overridden) type of 's'.
1561 func (state *dodataState) symType(s loader.Sym) sym.SymKind {
1562         if int(s) < len(state.symGroupType) {
1563                 if override := state.symGroupType[s]; override != 0 {
1564                         return override
1565                 }
1566         }
1567         return state.ctxt.loader.SymType(s)
1568 }
1569
1570 // setSymType sets a new override type for 's'.
1571 func (state *dodataState) setSymType(s loader.Sym, kind sym.SymKind) {
1572         if s == 0 {
1573                 panic("bad")
1574         }
1575         if int(s) < len(state.symGroupType) {
1576                 state.symGroupType[s] = kind
1577         } else {
1578                 su := state.ctxt.loader.MakeSymbolUpdater(s)
1579                 su.SetType(kind)
1580         }
1581 }
1582
1583 func (ctxt *Link) dodata(symGroupType []sym.SymKind) {
1584
1585         // Give zeros sized symbols space if necessary.
1586         fixZeroSizedSymbols(ctxt)
1587
1588         // Collect data symbols by type into data.
1589         state := dodataState{ctxt: ctxt, symGroupType: symGroupType}
1590         ldr := ctxt.loader
1591         for s := loader.Sym(1); s < loader.Sym(ldr.NSym()); s++ {
1592                 if !ldr.AttrReachable(s) || ldr.AttrSpecial(s) || ldr.AttrSubSymbol(s) ||
1593                         !ldr.TopLevelSym(s) {
1594                         continue
1595                 }
1596
1597                 st := state.symType(s)
1598
1599                 if st <= sym.STEXT || st >= sym.SXREF {
1600                         continue
1601                 }
1602                 state.data[st] = append(state.data[st], s)
1603
1604                 // Similarly with checking the onlist attr.
1605                 if ldr.AttrOnList(s) {
1606                         log.Fatalf("symbol %s listed multiple times", ldr.SymName(s))
1607                 }
1608                 ldr.SetAttrOnList(s, true)
1609         }
1610
1611         // Now that we have the data symbols, but before we start
1612         // to assign addresses, record all the necessary
1613         // dynamic relocations. These will grow the relocation
1614         // symbol, which is itself data.
1615         //
1616         // On darwin, we need the symbol table numbers for dynreloc.
1617         if ctxt.HeadType == objabi.Hdarwin {
1618                 machosymorder(ctxt)
1619         }
1620         state.dynreloc(ctxt)
1621
1622         // Move any RO data with relocations to a separate section.
1623         state.makeRelroForSharedLib(ctxt)
1624
1625         // Set alignment for the symbol with the largest known index,
1626         // so as to trigger allocation of the loader's internal
1627         // alignment array. This will avoid data races in the parallel
1628         // section below.
1629         lastSym := loader.Sym(ldr.NSym() - 1)
1630         ldr.SetSymAlign(lastSym, ldr.SymAlign(lastSym))
1631
1632         // Sort symbols.
1633         var wg sync.WaitGroup
1634         for symn := range state.data {
1635                 symn := sym.SymKind(symn)
1636                 wg.Add(1)
1637                 go func() {
1638                         state.data[symn], state.dataMaxAlign[symn] = state.dodataSect(ctxt, symn, state.data[symn])
1639                         wg.Done()
1640                 }()
1641         }
1642         wg.Wait()
1643
1644         if ctxt.IsELF {
1645                 // Make .rela and .rela.plt contiguous, the ELF ABI requires this
1646                 // and Solaris actually cares.
1647                 syms := state.data[sym.SELFROSECT]
1648                 reli, plti := -1, -1
1649                 for i, s := range syms {
1650                         switch ldr.SymName(s) {
1651                         case ".rel.plt", ".rela.plt":
1652                                 plti = i
1653                         case ".rel", ".rela":
1654                                 reli = i
1655                         }
1656                 }
1657                 if reli >= 0 && plti >= 0 && plti != reli+1 {
1658                         var first, second int
1659                         if plti > reli {
1660                                 first, second = reli, plti
1661                         } else {
1662                                 first, second = plti, reli
1663                         }
1664                         rel, plt := syms[reli], syms[plti]
1665                         copy(syms[first+2:], syms[first+1:second])
1666                         syms[first+0] = rel
1667                         syms[first+1] = plt
1668
1669                         // Make sure alignment doesn't introduce a gap.
1670                         // Setting the alignment explicitly prevents
1671                         // symalign from basing it on the size and
1672                         // getting it wrong.
1673                         ldr.SetSymAlign(rel, int32(ctxt.Arch.RegSize))
1674                         ldr.SetSymAlign(plt, int32(ctxt.Arch.RegSize))
1675                 }
1676                 state.data[sym.SELFROSECT] = syms
1677         }
1678
1679         if ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal {
1680                 // These symbols must have the same alignment as their section.
1681                 // Otherwise, ld might change the layout of Go sections.
1682                 ldr.SetSymAlign(ldr.Lookup("runtime.data", 0), state.dataMaxAlign[sym.SDATA])
1683                 ldr.SetSymAlign(ldr.Lookup("runtime.bss", 0), state.dataMaxAlign[sym.SBSS])
1684         }
1685
1686         // Create *sym.Section objects and assign symbols to sections for
1687         // data/rodata (and related) symbols.
1688         state.allocateDataSections(ctxt)
1689
1690         state.allocateSEHSections(ctxt)
1691
1692         // Create *sym.Section objects and assign symbols to sections for
1693         // DWARF symbols.
1694         state.allocateDwarfSections(ctxt)
1695
1696         /* number the sections */
1697         n := int16(1)
1698
1699         for _, sect := range Segtext.Sections {
1700                 sect.Extnum = n
1701                 n++
1702         }
1703         for _, sect := range Segrodata.Sections {
1704                 sect.Extnum = n
1705                 n++
1706         }
1707         for _, sect := range Segrelrodata.Sections {
1708                 sect.Extnum = n
1709                 n++
1710         }
1711         for _, sect := range Segdata.Sections {
1712                 sect.Extnum = n
1713                 n++
1714         }
1715         for _, sect := range Segdwarf.Sections {
1716                 sect.Extnum = n
1717                 n++
1718         }
1719         for _, sect := range Segpdata.Sections {
1720                 sect.Extnum = n
1721                 n++
1722         }
1723         for _, sect := range Segxdata.Sections {
1724                 sect.Extnum = n
1725                 n++
1726         }
1727 }
1728
1729 // allocateDataSectionForSym creates a new sym.Section into which a
1730 // single symbol will be placed. Here "seg" is the segment into which
1731 // the section will go, "s" is the symbol to be placed into the new
1732 // section, and "rwx" contains permissions for the section.
1733 func (state *dodataState) allocateDataSectionForSym(seg *sym.Segment, s loader.Sym, rwx int) *sym.Section {
1734         ldr := state.ctxt.loader
1735         sname := ldr.SymName(s)
1736         if strings.HasPrefix(sname, "go:") {
1737                 sname = ".go." + sname[len("go:"):]
1738         }
1739         sect := addsection(ldr, state.ctxt.Arch, seg, sname, rwx)
1740         sect.Align = symalign(ldr, s)
1741         state.datsize = Rnd(state.datsize, int64(sect.Align))
1742         sect.Vaddr = uint64(state.datsize)
1743         return sect
1744 }
1745
1746 // allocateNamedDataSection creates a new sym.Section for a category
1747 // of data symbols. Here "seg" is the segment into which the section
1748 // will go, "sName" is the name to give to the section, "types" is a
1749 // range of symbol types to be put into the section, and "rwx"
1750 // contains permissions for the section.
1751 func (state *dodataState) allocateNamedDataSection(seg *sym.Segment, sName string, types []sym.SymKind, rwx int) *sym.Section {
1752         sect := addsection(state.ctxt.loader, state.ctxt.Arch, seg, sName, rwx)
1753         if len(types) == 0 {
1754                 sect.Align = 1
1755         } else if len(types) == 1 {
1756                 sect.Align = state.dataMaxAlign[types[0]]
1757         } else {
1758                 for _, symn := range types {
1759                         align := state.dataMaxAlign[symn]
1760                         if sect.Align < align {
1761                                 sect.Align = align
1762                         }
1763                 }
1764         }
1765         state.datsize = Rnd(state.datsize, int64(sect.Align))
1766         sect.Vaddr = uint64(state.datsize)
1767         return sect
1768 }
1769
1770 // assignDsymsToSection assigns a collection of data symbols to a
1771 // newly created section. "sect" is the section into which to place
1772 // the symbols, "syms" holds the list of symbols to assign,
1773 // "forceType" (if non-zero) contains a new sym type to apply to each
1774 // sym during the assignment, and "aligner" is a hook to call to
1775 // handle alignment during the assignment process.
1776 func (state *dodataState) assignDsymsToSection(sect *sym.Section, syms []loader.Sym, forceType sym.SymKind, aligner func(state *dodataState, datsize int64, s loader.Sym) int64) {
1777         ldr := state.ctxt.loader
1778         for _, s := range syms {
1779                 state.datsize = aligner(state, state.datsize, s)
1780                 ldr.SetSymSect(s, sect)
1781                 if forceType != sym.Sxxx {
1782                         state.setSymType(s, forceType)
1783                 }
1784                 ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
1785                 state.datsize += ldr.SymSize(s)
1786         }
1787         sect.Length = uint64(state.datsize) - sect.Vaddr
1788 }
1789
1790 func (state *dodataState) assignToSection(sect *sym.Section, symn sym.SymKind, forceType sym.SymKind) {
1791         state.assignDsymsToSection(sect, state.data[symn], forceType, aligndatsize)
1792         state.checkdatsize(symn)
1793 }
1794
1795 // allocateSingleSymSections walks through the bucketed data symbols
1796 // with type 'symn', creates a new section for each sym, and assigns
1797 // the sym to a newly created section. Section name is set from the
1798 // symbol name. "Seg" is the segment into which to place the new
1799 // section, "forceType" is the new sym.SymKind to assign to the symbol
1800 // within the section, and "rwx" holds section permissions.
1801 func (state *dodataState) allocateSingleSymSections(seg *sym.Segment, symn sym.SymKind, forceType sym.SymKind, rwx int) {
1802         ldr := state.ctxt.loader
1803         for _, s := range state.data[symn] {
1804                 sect := state.allocateDataSectionForSym(seg, s, rwx)
1805                 ldr.SetSymSect(s, sect)
1806                 state.setSymType(s, forceType)
1807                 ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
1808                 state.datsize += ldr.SymSize(s)
1809                 sect.Length = uint64(state.datsize) - sect.Vaddr
1810         }
1811         state.checkdatsize(symn)
1812 }
1813
1814 // allocateNamedSectionAndAssignSyms creates a new section with the
1815 // specified name, then walks through the bucketed data symbols with
1816 // type 'symn' and assigns each of them to this new section. "Seg" is
1817 // the segment into which to place the new section, "secName" is the
1818 // name to give to the new section, "forceType" (if non-zero) contains
1819 // a new sym type to apply to each sym during the assignment, and
1820 // "rwx" holds section permissions.
1821 func (state *dodataState) allocateNamedSectionAndAssignSyms(seg *sym.Segment, secName string, symn sym.SymKind, forceType sym.SymKind, rwx int) *sym.Section {
1822
1823         sect := state.allocateNamedDataSection(seg, secName, []sym.SymKind{symn}, rwx)
1824         state.assignDsymsToSection(sect, state.data[symn], forceType, aligndatsize)
1825         return sect
1826 }
1827
1828 // allocateDataSections allocates sym.Section objects for data/rodata
1829 // (and related) symbols, and then assigns symbols to those sections.
1830 func (state *dodataState) allocateDataSections(ctxt *Link) {
1831         // Allocate sections.
1832         // Data is processed before segtext, because we need
1833         // to see all symbols in the .data and .bss sections in order
1834         // to generate garbage collection information.
1835
1836         // Writable data sections that do not need any specialized handling.
1837         writable := []sym.SymKind{
1838                 sym.SBUILDINFO,
1839                 sym.SELFSECT,
1840                 sym.SMACHO,
1841                 sym.SMACHOGOT,
1842                 sym.SWINDOWS,
1843         }
1844         for _, symn := range writable {
1845                 state.allocateSingleSymSections(&Segdata, symn, sym.SDATA, 06)
1846         }
1847         ldr := ctxt.loader
1848
1849         // .got
1850         if len(state.data[sym.SELFGOT]) > 0 {
1851                 state.allocateNamedSectionAndAssignSyms(&Segdata, ".got", sym.SELFGOT, sym.SDATA, 06)
1852         }
1853
1854         /* pointer-free data */
1855         sect := state.allocateNamedSectionAndAssignSyms(&Segdata, ".noptrdata", sym.SNOPTRDATA, sym.SDATA, 06)
1856         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.noptrdata", 0), sect)
1857         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.enoptrdata", 0), sect)
1858
1859         hasinitarr := ctxt.linkShared
1860
1861         /* shared library initializer */
1862         switch ctxt.BuildMode {
1863         case BuildModeCArchive, BuildModeCShared, BuildModeShared, BuildModePlugin:
1864                 hasinitarr = true
1865         }
1866
1867         if ctxt.HeadType == objabi.Haix {
1868                 if len(state.data[sym.SINITARR]) > 0 {
1869                         Errorf(nil, "XCOFF format doesn't allow .init_array section")
1870                 }
1871         }
1872
1873         if hasinitarr && len(state.data[sym.SINITARR]) > 0 {
1874                 state.allocateNamedSectionAndAssignSyms(&Segdata, ".init_array", sym.SINITARR, sym.Sxxx, 06)
1875         }
1876
1877         /* data */
1878         sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".data", sym.SDATA, sym.SDATA, 06)
1879         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.data", 0), sect)
1880         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.edata", 0), sect)
1881         dataGcEnd := state.datsize - int64(sect.Vaddr)
1882
1883         // On AIX, TOC entries must be the last of .data
1884         // These aren't part of gc as they won't change during the runtime.
1885         state.assignToSection(sect, sym.SXCOFFTOC, sym.SDATA)
1886         state.checkdatsize(sym.SDATA)
1887         sect.Length = uint64(state.datsize) - sect.Vaddr
1888
1889         /* bss */
1890         sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".bss", sym.SBSS, sym.Sxxx, 06)
1891         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.bss", 0), sect)
1892         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.ebss", 0), sect)
1893         bssGcEnd := state.datsize - int64(sect.Vaddr)
1894
1895         // Emit gcdata for bss symbols now that symbol values have been assigned.
1896         gcsToEmit := []struct {
1897                 symName string
1898                 symKind sym.SymKind
1899                 gcEnd   int64
1900         }{
1901                 {"runtime.gcdata", sym.SDATA, dataGcEnd},
1902                 {"runtime.gcbss", sym.SBSS, bssGcEnd},
1903         }
1904         for _, g := range gcsToEmit {
1905                 var gc GCProg
1906                 gc.Init(ctxt, g.symName)
1907                 for _, s := range state.data[g.symKind] {
1908                         gc.AddSym(s)
1909                 }
1910                 gc.End(g.gcEnd)
1911         }
1912
1913         /* pointer-free bss */
1914         sect = state.allocateNamedSectionAndAssignSyms(&Segdata, ".noptrbss", sym.SNOPTRBSS, sym.Sxxx, 06)
1915         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.noptrbss", 0), sect)
1916         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.enoptrbss", 0), sect)
1917         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.end", 0), sect)
1918
1919         // Code coverage counters are assigned to the .noptrbss section.
1920         // We assign them in a separate pass so that they stay aggregated
1921         // together in a single blob (coverage runtime depends on this).
1922         covCounterDataStartOff = sect.Length
1923         state.assignToSection(sect, sym.SCOVERAGE_COUNTER, sym.SNOPTRBSS)
1924         covCounterDataLen = sect.Length - covCounterDataStartOff
1925         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.covctrs", 0), sect)
1926         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.ecovctrs", 0), sect)
1927
1928         // Coverage instrumentation counters for libfuzzer.
1929         if len(state.data[sym.SLIBFUZZER_8BIT_COUNTER]) > 0 {
1930                 sect := state.allocateNamedSectionAndAssignSyms(&Segdata, ".go.fuzzcntrs", sym.SLIBFUZZER_8BIT_COUNTER, sym.Sxxx, 06)
1931                 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.__start___sancov_cntrs", 0), sect)
1932                 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.__stop___sancov_cntrs", 0), sect)
1933                 ldr.SetSymSect(ldr.LookupOrCreateSym("internal/fuzz._counters", 0), sect)
1934                 ldr.SetSymSect(ldr.LookupOrCreateSym("internal/fuzz._ecounters", 0), sect)
1935         }
1936
1937         if len(state.data[sym.STLSBSS]) > 0 {
1938                 var sect *sym.Section
1939                 // FIXME: not clear why it is sometimes necessary to suppress .tbss section creation.
1940                 if (ctxt.IsELF || ctxt.HeadType == objabi.Haix) && (ctxt.LinkMode == LinkExternal || !*FlagD) {
1941                         sect = addsection(ldr, ctxt.Arch, &Segdata, ".tbss", 06)
1942                         sect.Align = int32(ctxt.Arch.PtrSize)
1943                         // FIXME: why does this need to be set to zero?
1944                         sect.Vaddr = 0
1945                 }
1946                 state.datsize = 0
1947
1948                 for _, s := range state.data[sym.STLSBSS] {
1949                         state.datsize = aligndatsize(state, state.datsize, s)
1950                         if sect != nil {
1951                                 ldr.SetSymSect(s, sect)
1952                         }
1953                         ldr.SetSymValue(s, state.datsize)
1954                         state.datsize += ldr.SymSize(s)
1955                 }
1956                 state.checkdatsize(sym.STLSBSS)
1957
1958                 if sect != nil {
1959                         sect.Length = uint64(state.datsize)
1960                 }
1961         }
1962
1963         /*
1964          * We finished data, begin read-only data.
1965          * Not all systems support a separate read-only non-executable data section.
1966          * ELF and Windows PE systems do.
1967          * OS X and Plan 9 do not.
1968          * And if we're using external linking mode, the point is moot,
1969          * since it's not our decision; that code expects the sections in
1970          * segtext.
1971          */
1972         var segro *sym.Segment
1973         if ctxt.IsELF && ctxt.LinkMode == LinkInternal {
1974                 segro = &Segrodata
1975         } else if ctxt.HeadType == objabi.Hwindows {
1976                 segro = &Segrodata
1977         } else {
1978                 segro = &Segtext
1979         }
1980
1981         state.datsize = 0
1982
1983         /* read-only executable ELF, Mach-O sections */
1984         if len(state.data[sym.STEXT]) != 0 {
1985                 culprit := ldr.SymName(state.data[sym.STEXT][0])
1986                 Errorf(nil, "dodata found an sym.STEXT symbol: %s", culprit)
1987         }
1988         state.allocateSingleSymSections(&Segtext, sym.SELFRXSECT, sym.SRODATA, 05)
1989         state.allocateSingleSymSections(&Segtext, sym.SMACHOPLT, sym.SRODATA, 05)
1990
1991         /* read-only data */
1992         sect = state.allocateNamedDataSection(segro, ".rodata", sym.ReadOnly, 04)
1993         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.rodata", 0), sect)
1994         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.erodata", 0), sect)
1995         if !ctxt.UseRelro() {
1996                 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.types", 0), sect)
1997                 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.etypes", 0), sect)
1998         }
1999         for _, symn := range sym.ReadOnly {
2000                 symnStartValue := state.datsize
2001                 if len(state.data[symn]) != 0 {
2002                         symnStartValue = aligndatsize(state, symnStartValue, state.data[symn][0])
2003                 }
2004                 state.assignToSection(sect, symn, sym.SRODATA)
2005                 setCarrierSize(symn, state.datsize-symnStartValue)
2006                 if ctxt.HeadType == objabi.Haix {
2007                         // Read-only symbols might be wrapped inside their outer
2008                         // symbol.
2009                         // XCOFF symbol table needs to know the size of
2010                         // these outer symbols.
2011                         xcoffUpdateOuterSize(ctxt, state.datsize-symnStartValue, symn)
2012                 }
2013         }
2014
2015         /* read-only ELF, Mach-O sections */
2016         state.allocateSingleSymSections(segro, sym.SELFROSECT, sym.SRODATA, 04)
2017
2018         // There is some data that are conceptually read-only but are written to by
2019         // relocations. On GNU systems, we can arrange for the dynamic linker to
2020         // mprotect sections after relocations are applied by giving them write
2021         // permissions in the object file and calling them ".data.rel.ro.FOO". We
2022         // divide the .rodata section between actual .rodata and .data.rel.ro.rodata,
2023         // but for the other sections that this applies to, we just write a read-only
2024         // .FOO section or a read-write .data.rel.ro.FOO section depending on the
2025         // situation.
2026         // TODO(mwhudson): It would make sense to do this more widely, but it makes
2027         // the system linker segfault on darwin.
2028         const relroPerm = 06
2029         const fallbackPerm = 04
2030         relroSecPerm := fallbackPerm
2031         genrelrosecname := func(suffix string) string {
2032                 if suffix == "" {
2033                         return ".rodata"
2034                 }
2035                 return suffix
2036         }
2037         seg := segro
2038
2039         if ctxt.UseRelro() {
2040                 segrelro := &Segrelrodata
2041                 if ctxt.LinkMode == LinkExternal && !ctxt.IsAIX() && !ctxt.IsDarwin() {
2042                         // Using a separate segment with an external
2043                         // linker results in some programs moving
2044                         // their data sections unexpectedly, which
2045                         // corrupts the moduledata. So we use the
2046                         // rodata segment and let the external linker
2047                         // sort out a rel.ro segment.
2048                         segrelro = segro
2049                 } else {
2050                         // Reset datsize for new segment.
2051                         state.datsize = 0
2052                 }
2053
2054                 if !ctxt.IsDarwin() { // We don't need the special names on darwin.
2055                         genrelrosecname = func(suffix string) string {
2056                                 return ".data.rel.ro" + suffix
2057                         }
2058                 }
2059
2060                 relroReadOnly := []sym.SymKind{}
2061                 for _, symnro := range sym.ReadOnly {
2062                         symn := sym.RelROMap[symnro]
2063                         relroReadOnly = append(relroReadOnly, symn)
2064                 }
2065                 seg = segrelro
2066                 relroSecPerm = relroPerm
2067
2068                 /* data only written by relocations */
2069                 sect = state.allocateNamedDataSection(segrelro, genrelrosecname(""), relroReadOnly, relroSecPerm)
2070
2071                 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.types", 0), sect)
2072                 ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.etypes", 0), sect)
2073
2074                 for i, symnro := range sym.ReadOnly {
2075                         if i == 0 && symnro == sym.STYPE && ctxt.HeadType != objabi.Haix {
2076                                 // Skip forward so that no type
2077                                 // reference uses a zero offset.
2078                                 // This is unlikely but possible in small
2079                                 // programs with no other read-only data.
2080                                 state.datsize++
2081                         }
2082
2083                         symn := sym.RelROMap[symnro]
2084                         symnStartValue := state.datsize
2085                         if len(state.data[symn]) != 0 {
2086                                 symnStartValue = aligndatsize(state, symnStartValue, state.data[symn][0])
2087                         }
2088
2089                         for _, s := range state.data[symn] {
2090                                 outer := ldr.OuterSym(s)
2091                                 if s != 0 && ldr.SymSect(outer) != nil && ldr.SymSect(outer) != sect {
2092                                         ctxt.Errorf(s, "s.Outer (%s) in different section from s, %s != %s", ldr.SymName(outer), ldr.SymSect(outer).Name, sect.Name)
2093                                 }
2094                         }
2095                         state.assignToSection(sect, symn, sym.SRODATA)
2096                         setCarrierSize(symn, state.datsize-symnStartValue)
2097                         if ctxt.HeadType == objabi.Haix {
2098                                 // Read-only symbols might be wrapped inside their outer
2099                                 // symbol.
2100                                 // XCOFF symbol table needs to know the size of
2101                                 // these outer symbols.
2102                                 xcoffUpdateOuterSize(ctxt, state.datsize-symnStartValue, symn)
2103                         }
2104                 }
2105
2106                 sect.Length = uint64(state.datsize) - sect.Vaddr
2107         }
2108
2109         /* typelink */
2110         sect = state.allocateNamedDataSection(seg, genrelrosecname(".typelink"), []sym.SymKind{sym.STYPELINK}, relroSecPerm)
2111
2112         typelink := ldr.CreateSymForUpdate("runtime.typelink", 0)
2113         ldr.SetSymSect(typelink.Sym(), sect)
2114         typelink.SetType(sym.SRODATA)
2115         state.datsize += typelink.Size()
2116         state.checkdatsize(sym.STYPELINK)
2117         sect.Length = uint64(state.datsize) - sect.Vaddr
2118
2119         /* itablink */
2120         sect = state.allocateNamedDataSection(seg, genrelrosecname(".itablink"), []sym.SymKind{sym.SITABLINK}, relroSecPerm)
2121
2122         itablink := ldr.CreateSymForUpdate("runtime.itablink", 0)
2123         ldr.SetSymSect(itablink.Sym(), sect)
2124         itablink.SetType(sym.SRODATA)
2125         state.datsize += itablink.Size()
2126         state.checkdatsize(sym.SITABLINK)
2127         sect.Length = uint64(state.datsize) - sect.Vaddr
2128
2129         /* gosymtab */
2130         sect = state.allocateNamedSectionAndAssignSyms(seg, genrelrosecname(".gosymtab"), sym.SSYMTAB, sym.SRODATA, relroSecPerm)
2131         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.symtab", 0), sect)
2132         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.esymtab", 0), sect)
2133
2134         /* gopclntab */
2135         sect = state.allocateNamedSectionAndAssignSyms(seg, genrelrosecname(".gopclntab"), sym.SPCLNTAB, sym.SRODATA, relroSecPerm)
2136         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pclntab", 0), sect)
2137         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pcheader", 0), sect)
2138         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.funcnametab", 0), sect)
2139         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.cutab", 0), sect)
2140         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.filetab", 0), sect)
2141         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.pctab", 0), sect)
2142         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.functab", 0), sect)
2143         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.epclntab", 0), sect)
2144         setCarrierSize(sym.SPCLNTAB, int64(sect.Length))
2145         if ctxt.HeadType == objabi.Haix {
2146                 xcoffUpdateOuterSize(ctxt, int64(sect.Length), sym.SPCLNTAB)
2147         }
2148
2149         // 6g uses 4-byte relocation offsets, so the entire segment must fit in 32 bits.
2150         if state.datsize != int64(uint32(state.datsize)) {
2151                 Errorf(nil, "read-only data segment too large: %d", state.datsize)
2152         }
2153
2154         siz := 0
2155         for symn := sym.SELFRXSECT; symn < sym.SXREF; symn++ {
2156                 siz += len(state.data[symn])
2157         }
2158         ctxt.datap = make([]loader.Sym, 0, siz)
2159         for symn := sym.SELFRXSECT; symn < sym.SXREF; symn++ {
2160                 ctxt.datap = append(ctxt.datap, state.data[symn]...)
2161         }
2162 }
2163
2164 // allocateDwarfSections allocates sym.Section objects for DWARF
2165 // symbols, and assigns symbols to sections.
2166 func (state *dodataState) allocateDwarfSections(ctxt *Link) {
2167
2168         alignOne := func(state *dodataState, datsize int64, s loader.Sym) int64 { return datsize }
2169
2170         ldr := ctxt.loader
2171         for i := 0; i < len(dwarfp); i++ {
2172                 // First the section symbol.
2173                 s := dwarfp[i].secSym()
2174                 sect := state.allocateNamedDataSection(&Segdwarf, ldr.SymName(s), []sym.SymKind{}, 04)
2175                 ldr.SetSymSect(s, sect)
2176                 sect.Sym = sym.LoaderSym(s)
2177                 curType := ldr.SymType(s)
2178                 state.setSymType(s, sym.SRODATA)
2179                 ldr.SetSymValue(s, int64(uint64(state.datsize)-sect.Vaddr))
2180                 state.datsize += ldr.SymSize(s)
2181
2182                 // Then any sub-symbols for the section symbol.
2183                 subSyms := dwarfp[i].subSyms()
2184                 state.assignDsymsToSection(sect, subSyms, sym.SRODATA, alignOne)
2185
2186                 for j := 0; j < len(subSyms); j++ {
2187                         s := subSyms[j]
2188                         if ctxt.HeadType == objabi.Haix && curType == sym.SDWARFLOC {
2189                                 // Update the size of .debug_loc for this symbol's
2190                                 // package.
2191                                 addDwsectCUSize(".debug_loc", ldr.SymPkg(s), uint64(ldr.SymSize(s)))
2192                         }
2193                 }
2194                 sect.Length = uint64(state.datsize) - sect.Vaddr
2195                 checkSectSize(sect)
2196         }
2197 }
2198
2199 // allocateSEHSections allocate a sym.Section object for SEH
2200 // symbols, and assigns symbols to sections.
2201 func (state *dodataState) allocateSEHSections(ctxt *Link) {
2202         if sehp.pdata > 0 {
2203                 sect := state.allocateDataSectionForSym(&Segpdata, sehp.pdata, 04)
2204                 state.assignDsymsToSection(sect, []loader.Sym{sehp.pdata}, sym.SRODATA, aligndatsize)
2205                 state.checkdatsize(sym.SSEHSECT)
2206         }
2207         if sehp.xdata > 0 {
2208                 sect := state.allocateNamedDataSection(&Segxdata, ".xdata", []sym.SymKind{}, 04)
2209                 state.assignDsymsToSection(sect, []loader.Sym{sehp.xdata}, sym.SRODATA, aligndatsize)
2210                 state.checkdatsize(sym.SSEHSECT)
2211         }
2212 }
2213
2214 type symNameSize struct {
2215         name string
2216         sz   int64
2217         val  int64
2218         sym  loader.Sym
2219 }
2220
2221 func (state *dodataState) dodataSect(ctxt *Link, symn sym.SymKind, syms []loader.Sym) (result []loader.Sym, maxAlign int32) {
2222         var head, tail, zerobase loader.Sym
2223         ldr := ctxt.loader
2224         sl := make([]symNameSize, len(syms))
2225
2226         // For ppc64, we want to interleave the .got and .toc sections
2227         // from input files. Both are type sym.SELFGOT, so in that case
2228         // we skip size comparison and do the name comparison instead
2229         // (conveniently, .got sorts before .toc).
2230         checkSize := symn != sym.SELFGOT
2231
2232         for k, s := range syms {
2233                 ss := ldr.SymSize(s)
2234                 sl[k] = symNameSize{sz: ss, sym: s}
2235                 if !checkSize {
2236                         sl[k].name = ldr.SymName(s)
2237                 }
2238                 ds := int64(len(ldr.Data(s)))
2239                 switch {
2240                 case ss < ds:
2241                         ctxt.Errorf(s, "initialize bounds (%d < %d)", ss, ds)
2242                 case ss < 0:
2243                         ctxt.Errorf(s, "negative size (%d bytes)", ss)
2244                 case ss > cutoff:
2245                         ctxt.Errorf(s, "symbol too large (%d bytes)", ss)
2246                 }
2247
2248                 // If the usually-special section-marker symbols are being laid
2249                 // out as regular symbols, put them either at the beginning or
2250                 // end of their section.
2251                 if (ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin) || (ctxt.HeadType == objabi.Haix && ctxt.LinkMode == LinkExternal) {
2252                         switch ldr.SymName(s) {
2253                         case "runtime.text", "runtime.bss", "runtime.data", "runtime.types", "runtime.rodata",
2254                                 "runtime.noptrdata", "runtime.noptrbss":
2255                                 head = s
2256                                 continue
2257                         case "runtime.etext", "runtime.ebss", "runtime.edata", "runtime.etypes", "runtime.erodata",
2258                                 "runtime.enoptrdata", "runtime.enoptrbss":
2259                                 tail = s
2260                                 continue
2261                         }
2262                 }
2263         }
2264         zerobase = ldr.Lookup("runtime.zerobase", 0)
2265
2266         // Perform the sort.
2267         if symn != sym.SPCLNTAB {
2268                 sort.Slice(sl, func(i, j int) bool {
2269                         si, sj := sl[i].sym, sl[j].sym
2270                         isz, jsz := sl[i].sz, sl[j].sz
2271                         switch {
2272                         case si == head, sj == tail:
2273                                 return true
2274                         case sj == head, si == tail:
2275                                 return false
2276                         // put zerobase right after all the zero-sized symbols,
2277                         // so zero-sized symbols have the same address as zerobase.
2278                         case si == zerobase:
2279                                 return jsz != 0 // zerobase < nonzero-sized
2280                         case sj == zerobase:
2281                                 return isz == 0 // 0-sized < zerobase
2282                         }
2283                         if checkSize {
2284                                 if isz != jsz {
2285                                         return isz < jsz
2286                                 }
2287                         } else {
2288                                 iname := sl[i].name
2289                                 jname := sl[j].name
2290                                 if iname != jname {
2291                                         return iname < jname
2292                                 }
2293                         }
2294                         return si < sj
2295                 })
2296         } else {
2297                 // PCLNTAB was built internally, and already has the proper order.
2298         }
2299
2300         // Set alignment, construct result
2301         syms = syms[:0]
2302         for k := range sl {
2303                 s := sl[k].sym
2304                 if s != head && s != tail {
2305                         align := symalign(ldr, s)
2306                         if maxAlign < align {
2307                                 maxAlign = align
2308                         }
2309                 }
2310                 syms = append(syms, s)
2311         }
2312
2313         return syms, maxAlign
2314 }
2315
2316 // Add buildid to beginning of text segment, on non-ELF systems.
2317 // Non-ELF binary formats are not always flexible enough to
2318 // give us a place to put the Go build ID. On those systems, we put it
2319 // at the very beginning of the text segment.
2320 // This “header” is read by cmd/go.
2321 func (ctxt *Link) textbuildid() {
2322         if ctxt.IsELF || *flagBuildid == "" {
2323                 return
2324         }
2325
2326         ldr := ctxt.loader
2327         s := ldr.CreateSymForUpdate("go:buildid", 0)
2328         // The \xff is invalid UTF-8, meant to make it less likely
2329         // to find one of these accidentally.
2330         data := "\xff Go build ID: " + strconv.Quote(*flagBuildid) + "\n \xff"
2331         s.SetType(sym.STEXT)
2332         s.SetData([]byte(data))
2333         s.SetSize(int64(len(data)))
2334
2335         ctxt.Textp = append(ctxt.Textp, 0)
2336         copy(ctxt.Textp[1:], ctxt.Textp)
2337         ctxt.Textp[0] = s.Sym()
2338 }
2339
2340 func (ctxt *Link) buildinfo() {
2341         // Write the buildinfo symbol, which go version looks for.
2342         // The code reading this data is in package debug/buildinfo.
2343         ldr := ctxt.loader
2344         s := ldr.CreateSymForUpdate("go:buildinfo", 0)
2345         s.SetType(sym.SBUILDINFO)
2346         s.SetAlign(16)
2347         // The \xff is invalid UTF-8, meant to make it less likely
2348         // to find one of these accidentally.
2349         const prefix = "\xff Go buildinf:" // 14 bytes, plus 2 data bytes filled in below
2350         data := make([]byte, 32)
2351         copy(data, prefix)
2352         data[len(prefix)] = byte(ctxt.Arch.PtrSize)
2353         data[len(prefix)+1] = 0
2354         if ctxt.Arch.ByteOrder == binary.BigEndian {
2355                 data[len(prefix)+1] = 1
2356         }
2357         data[len(prefix)+1] |= 2 // signals new pointer-free format
2358         data = appendString(data, strdata["runtime.buildVersion"])
2359         data = appendString(data, strdata["runtime.modinfo"])
2360         // MacOS linker gets very upset if the size os not a multiple of alignment.
2361         for len(data)%16 != 0 {
2362                 data = append(data, 0)
2363         }
2364         s.SetData(data)
2365         s.SetSize(int64(len(data)))
2366
2367         // Add reference to go:buildinfo from the rodata section,
2368         // so that external linking with -Wl,--gc-sections does not
2369         // delete the build info.
2370         sr := ldr.CreateSymForUpdate("go:buildinfo.ref", 0)
2371         sr.SetType(sym.SRODATA)
2372         sr.SetAlign(int32(ctxt.Arch.PtrSize))
2373         sr.AddAddr(ctxt.Arch, s.Sym())
2374 }
2375
2376 // appendString appends s to data, prefixed by its varint-encoded length.
2377 func appendString(data []byte, s string) []byte {
2378         var v [binary.MaxVarintLen64]byte
2379         n := binary.PutUvarint(v[:], uint64(len(s)))
2380         data = append(data, v[:n]...)
2381         data = append(data, s...)
2382         return data
2383 }
2384
2385 // assign addresses to text
2386 func (ctxt *Link) textaddress() {
2387         addsection(ctxt.loader, ctxt.Arch, &Segtext, ".text", 05)
2388
2389         // Assign PCs in text segment.
2390         // Could parallelize, by assigning to text
2391         // and then letting threads copy down, but probably not worth it.
2392         sect := Segtext.Sections[0]
2393
2394         sect.Align = int32(Funcalign)
2395
2396         ldr := ctxt.loader
2397
2398         text := ctxt.xdefine("runtime.text", sym.STEXT, 0)
2399         etext := ctxt.xdefine("runtime.etext", sym.STEXT, 0)
2400         ldr.SetSymSect(text, sect)
2401         if ctxt.IsAIX() && ctxt.IsExternal() {
2402                 // Setting runtime.text has a real symbol prevents ld to
2403                 // change its base address resulting in wrong offsets for
2404                 // reflect methods.
2405                 u := ldr.MakeSymbolUpdater(text)
2406                 u.SetAlign(sect.Align)
2407                 u.SetSize(8)
2408         }
2409
2410         if (ctxt.DynlinkingGo() && ctxt.IsDarwin()) || (ctxt.IsAIX() && ctxt.IsExternal()) {
2411                 ldr.SetSymSect(etext, sect)
2412                 ctxt.Textp = append(ctxt.Textp, etext, 0)
2413                 copy(ctxt.Textp[1:], ctxt.Textp)
2414                 ctxt.Textp[0] = text
2415         }
2416
2417         start := uint64(Rnd(*FlagTextAddr, int64(Funcalign)))
2418         va := start
2419         n := 1
2420         sect.Vaddr = va
2421
2422         limit := thearch.TrampLimit
2423         if limit == 0 {
2424                 limit = 1 << 63 // unlimited
2425         }
2426         if *FlagDebugTextSize != 0 {
2427                 limit = uint64(*FlagDebugTextSize)
2428         }
2429         if *FlagDebugTramp > 1 {
2430                 limit = 1 // debug mode, force generating trampolines for everything
2431         }
2432
2433         if ctxt.IsAIX() && ctxt.IsExternal() {
2434                 // On AIX, normally we won't generate direct calls to external symbols,
2435                 // except in one test, cmd/go/testdata/script/link_syso_issue33139.txt.
2436                 // That test doesn't make much sense, and I'm not sure it ever works.
2437                 // Just generate trampoline for now (which will turn a direct call to
2438                 // an indirect call, which at least builds).
2439                 limit = 1
2440         }
2441
2442         // First pass: assign addresses assuming the program is small and will
2443         // not require trampoline generation.
2444         big := false
2445         for _, s := range ctxt.Textp {
2446                 sect, n, va = assignAddress(ctxt, sect, n, s, va, false, big)
2447                 if va-start >= limit {
2448                         big = true
2449                         break
2450                 }
2451         }
2452
2453         // Second pass: only if it is too big, insert trampolines for too-far
2454         // jumps and targets with unknown addresses.
2455         if big {
2456                 // reset addresses
2457                 for _, s := range ctxt.Textp {
2458                         if s != text {
2459                                 resetAddress(ctxt, s)
2460                         }
2461                 }
2462                 va = start
2463
2464                 ntramps := 0
2465                 var curPkg string
2466                 for i, s := range ctxt.Textp {
2467                         // When we find the first symbol in a package, perform a
2468                         // single iteration that assigns temporary addresses to all
2469                         // of the text in the same package, using the maximum possible
2470                         // number of trampolines. This allows for better decisions to
2471                         // be made regarding reachability and the need for trampolines.
2472                         if symPkg := ldr.SymPkg(s); symPkg != "" && curPkg != symPkg {
2473                                 curPkg = symPkg
2474                                 vaTmp := va
2475                                 for j := i; j < len(ctxt.Textp); j++ {
2476                                         curSym := ctxt.Textp[j]
2477                                         if symPkg := ldr.SymPkg(curSym); symPkg == "" || curPkg != symPkg {
2478                                                 break
2479                                         }
2480                                         // We do not pass big to assignAddress here, as this
2481                                         // can result in side effects such as section splitting.
2482                                         sect, n, vaTmp = assignAddress(ctxt, sect, n, curSym, vaTmp, false, false)
2483                                         vaTmp += maxSizeTrampolines(ctxt, ldr, curSym, false)
2484                                 }
2485                         }
2486
2487                         // Reset address for current symbol.
2488                         if s != text {
2489                                 resetAddress(ctxt, s)
2490                         }
2491
2492                         // Assign actual address for current symbol.
2493                         sect, n, va = assignAddress(ctxt, sect, n, s, va, false, big)
2494
2495                         // Resolve jumps, adding trampolines if they are needed.
2496                         trampoline(ctxt, s)
2497
2498                         // lay down trampolines after each function
2499                         for ; ntramps < len(ctxt.tramps); ntramps++ {
2500                                 tramp := ctxt.tramps[ntramps]
2501                                 if ctxt.IsAIX() && strings.HasPrefix(ldr.SymName(tramp), "runtime.text.") {
2502                                         // Already set in assignAddress
2503                                         continue
2504                                 }
2505                                 sect, n, va = assignAddress(ctxt, sect, n, tramp, va, true, big)
2506                         }
2507                 }
2508
2509                 // merge tramps into Textp, keeping Textp in address order
2510                 if ntramps != 0 {
2511                         newtextp := make([]loader.Sym, 0, len(ctxt.Textp)+ntramps)
2512                         i := 0
2513                         for _, s := range ctxt.Textp {
2514                                 for ; i < ntramps && ldr.SymValue(ctxt.tramps[i]) < ldr.SymValue(s); i++ {
2515                                         newtextp = append(newtextp, ctxt.tramps[i])
2516                                 }
2517                                 newtextp = append(newtextp, s)
2518                         }
2519                         newtextp = append(newtextp, ctxt.tramps[i:ntramps]...)
2520
2521                         ctxt.Textp = newtextp
2522                 }
2523         }
2524
2525         // Add MinLC size after etext, so it won't collide with the next symbol
2526         // (which may confuse some symbolizer).
2527         sect.Length = va - sect.Vaddr + uint64(ctxt.Arch.MinLC)
2528         ldr.SetSymSect(etext, sect)
2529         if ldr.SymValue(etext) == 0 {
2530                 // Set the address of the start/end symbols, if not already
2531                 // (i.e. not darwin+dynlink or AIX+external, see above).
2532                 ldr.SetSymValue(etext, int64(va))
2533                 ldr.SetSymValue(text, int64(Segtext.Sections[0].Vaddr))
2534         }
2535 }
2536
2537 // assigns address for a text symbol, returns (possibly new) section, its number, and the address.
2538 func assignAddress(ctxt *Link, sect *sym.Section, n int, s loader.Sym, va uint64, isTramp, big bool) (*sym.Section, int, uint64) {
2539         ldr := ctxt.loader
2540         if thearch.AssignAddress != nil {
2541                 return thearch.AssignAddress(ldr, sect, n, s, va, isTramp)
2542         }
2543
2544         ldr.SetSymSect(s, sect)
2545         if ldr.AttrSubSymbol(s) {
2546                 return sect, n, va
2547         }
2548
2549         align := ldr.SymAlign(s)
2550         if align == 0 {
2551                 align = int32(Funcalign)
2552         }
2553         va = uint64(Rnd(int64(va), int64(align)))
2554         if sect.Align < align {
2555                 sect.Align = align
2556         }
2557
2558         funcsize := uint64(MINFUNC) // spacing required for findfunctab
2559         if ldr.SymSize(s) > MINFUNC {
2560                 funcsize = uint64(ldr.SymSize(s))
2561         }
2562
2563         // If we need to split text sections, and this function doesn't fit in the current
2564         // section, then create a new one.
2565         //
2566         // Only break at outermost syms.
2567         if big && splitTextSections(ctxt) && ldr.OuterSym(s) == 0 {
2568                 // For debugging purposes, allow text size limit to be cranked down,
2569                 // so as to stress test the code that handles multiple text sections.
2570                 var textSizelimit uint64 = thearch.TrampLimit
2571                 if *FlagDebugTextSize != 0 {
2572                         textSizelimit = uint64(*FlagDebugTextSize)
2573                 }
2574
2575                 // Sanity check: make sure the limit is larger than any
2576                 // individual text symbol.
2577                 if funcsize > textSizelimit {
2578                         panic(fmt.Sprintf("error: text size limit %d less than text symbol %s size of %d", textSizelimit, ldr.SymName(s), funcsize))
2579                 }
2580
2581                 if va-sect.Vaddr+funcsize+maxSizeTrampolines(ctxt, ldr, s, isTramp) > textSizelimit {
2582                         sectAlign := int32(thearch.Funcalign)
2583                         if ctxt.IsPPC64() {
2584                                 // Align the next text section to the worst case function alignment likely
2585                                 // to be encountered when processing function symbols. The start address
2586                                 // is rounded against the final alignment of the text section later on in
2587                                 // (*Link).address. This may happen due to usage of PCALIGN directives
2588                                 // larger than Funcalign, or usage of ISA 3.1 prefixed instructions
2589                                 // (see ISA 3.1 Book I 1.9).
2590                                 const ppc64maxFuncalign = 64
2591                                 sectAlign = ppc64maxFuncalign
2592                                 va = uint64(Rnd(int64(va), ppc64maxFuncalign))
2593                         }
2594
2595                         // Set the length for the previous text section
2596                         sect.Length = va - sect.Vaddr
2597
2598                         // Create new section, set the starting Vaddr
2599                         sect = addsection(ctxt.loader, ctxt.Arch, &Segtext, ".text", 05)
2600
2601                         sect.Vaddr = va
2602                         sect.Align = sectAlign
2603                         ldr.SetSymSect(s, sect)
2604
2605                         // Create a symbol for the start of the secondary text sections
2606                         ntext := ldr.CreateSymForUpdate(fmt.Sprintf("runtime.text.%d", n), 0)
2607                         ntext.SetSect(sect)
2608                         if ctxt.IsAIX() {
2609                                 // runtime.text.X must be a real symbol on AIX.
2610                                 // Assign its address directly in order to be the
2611                                 // first symbol of this new section.
2612                                 ntext.SetType(sym.STEXT)
2613                                 ntext.SetSize(int64(MINFUNC))
2614                                 ntext.SetOnList(true)
2615                                 ntext.SetAlign(sectAlign)
2616                                 ctxt.tramps = append(ctxt.tramps, ntext.Sym())
2617
2618                                 ntext.SetValue(int64(va))
2619                                 va += uint64(ntext.Size())
2620
2621                                 if align := ldr.SymAlign(s); align != 0 {
2622                                         va = uint64(Rnd(int64(va), int64(align)))
2623                                 } else {
2624                                         va = uint64(Rnd(int64(va), int64(Funcalign)))
2625                                 }
2626                         }
2627                         n++
2628                 }
2629         }
2630
2631         ldr.SetSymValue(s, 0)
2632         for sub := s; sub != 0; sub = ldr.SubSym(sub) {
2633                 ldr.SetSymValue(sub, ldr.SymValue(sub)+int64(va))
2634                 if ctxt.Debugvlog > 2 {
2635                         fmt.Println("assign text address:", ldr.SymName(sub), ldr.SymValue(sub))
2636                 }
2637         }
2638
2639         va += funcsize
2640
2641         return sect, n, va
2642 }
2643
2644 func resetAddress(ctxt *Link, s loader.Sym) {
2645         ldr := ctxt.loader
2646         if ldr.OuterSym(s) != 0 {
2647                 return
2648         }
2649         oldv := ldr.SymValue(s)
2650         for sub := s; sub != 0; sub = ldr.SubSym(sub) {
2651                 ldr.SetSymValue(sub, ldr.SymValue(sub)-oldv)
2652         }
2653 }
2654
2655 // Return whether we may need to split text sections.
2656 //
2657 // On PPC64x, when external linking, a text section should not be
2658 // larger than 2^25 bytes due to the size of call target offset field
2659 // in the 'bl' instruction. Splitting into smaller text sections
2660 // smaller than this limit allows the system linker to modify the long
2661 // calls appropriately. The limit allows for the space needed for
2662 // tables inserted by the linker.
2663 //
2664 // The same applies to Darwin/ARM64, with 2^27 byte threshold.
2665 //
2666 // Similarly for ARM, we split sections (at 2^25 bytes) to avoid
2667 // inconsistencies between the Go linker's reachability calculations
2668 // (e.g. will direct call from X to Y need a trampoline) and similar
2669 // machinery in the external linker; see #58425 for more on the
2670 // history here.
2671 func splitTextSections(ctxt *Link) bool {
2672         return (ctxt.IsARM() || ctxt.IsPPC64() || (ctxt.IsARM64() && ctxt.IsDarwin())) && ctxt.IsExternal()
2673 }
2674
2675 // On Wasm, we reserve 4096 bytes for zero page, then 8192 bytes for wasm_exec.js
2676 // to store command line args and environment variables.
2677 // Data sections starts from at least address 12288.
2678 // Keep in sync with wasm_exec.js.
2679 const wasmMinDataAddr = 4096 + 8192
2680
2681 // address assigns virtual addresses to all segments and sections and
2682 // returns all segments in file order.
2683 func (ctxt *Link) address() []*sym.Segment {
2684         var order []*sym.Segment // Layout order
2685
2686         va := uint64(*FlagTextAddr)
2687         order = append(order, &Segtext)
2688         Segtext.Rwx = 05
2689         Segtext.Vaddr = va
2690         for i, s := range Segtext.Sections {
2691                 va = uint64(Rnd(int64(va), int64(s.Align)))
2692                 s.Vaddr = va
2693                 va += s.Length
2694
2695                 if ctxt.IsWasm() && i == 0 && va < wasmMinDataAddr {
2696                         va = wasmMinDataAddr
2697                 }
2698         }
2699
2700         Segtext.Length = va - uint64(*FlagTextAddr)
2701
2702         if len(Segrodata.Sections) > 0 {
2703                 // align to page boundary so as not to mix
2704                 // rodata and executable text.
2705                 //
2706                 // Note: gold or GNU ld will reduce the size of the executable
2707                 // file by arranging for the relro segment to end at a page
2708                 // boundary, and overlap the end of the text segment with the
2709                 // start of the relro segment in the file.  The PT_LOAD segments
2710                 // will be such that the last page of the text segment will be
2711                 // mapped twice, once r-x and once starting out rw- and, after
2712                 // relocation processing, changed to r--.
2713                 //
2714                 // Ideally the last page of the text segment would not be
2715                 // writable even for this short period.
2716                 va = uint64(Rnd(int64(va), *FlagRound))
2717
2718                 order = append(order, &Segrodata)
2719                 Segrodata.Rwx = 04
2720                 Segrodata.Vaddr = va
2721                 for _, s := range Segrodata.Sections {
2722                         va = uint64(Rnd(int64(va), int64(s.Align)))
2723                         s.Vaddr = va
2724                         va += s.Length
2725                 }
2726
2727                 Segrodata.Length = va - Segrodata.Vaddr
2728         }
2729         if len(Segrelrodata.Sections) > 0 {
2730                 // align to page boundary so as not to mix
2731                 // rodata, rel-ro data, and executable text.
2732                 va = uint64(Rnd(int64(va), *FlagRound))
2733                 if ctxt.HeadType == objabi.Haix {
2734                         // Relro data are inside data segment on AIX.
2735                         va += uint64(XCOFFDATABASE) - uint64(XCOFFTEXTBASE)
2736                 }
2737
2738                 order = append(order, &Segrelrodata)
2739                 Segrelrodata.Rwx = 06
2740                 Segrelrodata.Vaddr = va
2741                 for _, s := range Segrelrodata.Sections {
2742                         va = uint64(Rnd(int64(va), int64(s.Align)))
2743                         s.Vaddr = va
2744                         va += s.Length
2745                 }
2746
2747                 Segrelrodata.Length = va - Segrelrodata.Vaddr
2748         }
2749
2750         va = uint64(Rnd(int64(va), *FlagRound))
2751         if ctxt.HeadType == objabi.Haix && len(Segrelrodata.Sections) == 0 {
2752                 // Data sections are moved to an unreachable segment
2753                 // to ensure that they are position-independent.
2754                 // Already done if relro sections exist.
2755                 va += uint64(XCOFFDATABASE) - uint64(XCOFFTEXTBASE)
2756         }
2757         order = append(order, &Segdata)
2758         Segdata.Rwx = 06
2759         Segdata.Vaddr = va
2760         var data *sym.Section
2761         var noptr *sym.Section
2762         var bss *sym.Section
2763         var noptrbss *sym.Section
2764         var fuzzCounters *sym.Section
2765         for i, s := range Segdata.Sections {
2766                 if (ctxt.IsELF || ctxt.HeadType == objabi.Haix) && s.Name == ".tbss" {
2767                         continue
2768                 }
2769                 vlen := int64(s.Length)
2770                 if i+1 < len(Segdata.Sections) && !((ctxt.IsELF || ctxt.HeadType == objabi.Haix) && Segdata.Sections[i+1].Name == ".tbss") {
2771                         vlen = int64(Segdata.Sections[i+1].Vaddr - s.Vaddr)
2772                 }
2773                 s.Vaddr = va
2774                 va += uint64(vlen)
2775                 Segdata.Length = va - Segdata.Vaddr
2776                 switch s.Name {
2777                 case ".data":
2778                         data = s
2779                 case ".noptrdata":
2780                         noptr = s
2781                 case ".bss":
2782                         bss = s
2783                 case ".noptrbss":
2784                         noptrbss = s
2785                 case ".go.fuzzcntrs":
2786                         fuzzCounters = s
2787                 }
2788         }
2789
2790         // Assign Segdata's Filelen omitting the BSS. We do this here
2791         // simply because right now we know where the BSS starts.
2792         Segdata.Filelen = bss.Vaddr - Segdata.Vaddr
2793
2794         if len(Segpdata.Sections) > 0 {
2795                 va = uint64(Rnd(int64(va), *FlagRound))
2796                 order = append(order, &Segpdata)
2797                 Segpdata.Rwx = 04
2798                 Segpdata.Vaddr = va
2799                 // Segpdata.Sections is intended to contain just one section.
2800                 // Loop through the slice anyway for consistency.
2801                 for _, s := range Segpdata.Sections {
2802                         va = uint64(Rnd(int64(va), int64(s.Align)))
2803                         s.Vaddr = va
2804                         va += s.Length
2805                 }
2806                 Segpdata.Length = va - Segpdata.Vaddr
2807         }
2808
2809         if len(Segxdata.Sections) > 0 {
2810                 va = uint64(Rnd(int64(va), *FlagRound))
2811                 order = append(order, &Segxdata)
2812                 Segxdata.Rwx = 04
2813                 Segxdata.Vaddr = va
2814                 // Segxdata.Sections is intended to contain just one section.
2815                 // Loop through the slice anyway for consistency.
2816                 for _, s := range Segxdata.Sections {
2817                         va = uint64(Rnd(int64(va), int64(s.Align)))
2818                         s.Vaddr = va
2819                         va += s.Length
2820                 }
2821                 Segxdata.Length = va - Segxdata.Vaddr
2822         }
2823
2824         va = uint64(Rnd(int64(va), *FlagRound))
2825         order = append(order, &Segdwarf)
2826         Segdwarf.Rwx = 06
2827         Segdwarf.Vaddr = va
2828         for i, s := range Segdwarf.Sections {
2829                 vlen := int64(s.Length)
2830                 if i+1 < len(Segdwarf.Sections) {
2831                         vlen = int64(Segdwarf.Sections[i+1].Vaddr - s.Vaddr)
2832                 }
2833                 s.Vaddr = va
2834                 va += uint64(vlen)
2835                 if ctxt.HeadType == objabi.Hwindows {
2836                         va = uint64(Rnd(int64(va), PEFILEALIGN))
2837                 }
2838                 Segdwarf.Length = va - Segdwarf.Vaddr
2839         }
2840
2841         ldr := ctxt.loader
2842         var (
2843                 rodata  = ldr.SymSect(ldr.LookupOrCreateSym("runtime.rodata", 0))
2844                 symtab  = ldr.SymSect(ldr.LookupOrCreateSym("runtime.symtab", 0))
2845                 pclntab = ldr.SymSect(ldr.LookupOrCreateSym("runtime.pclntab", 0))
2846                 types   = ldr.SymSect(ldr.LookupOrCreateSym("runtime.types", 0))
2847         )
2848
2849         for _, s := range ctxt.datap {
2850                 if sect := ldr.SymSect(s); sect != nil {
2851                         ldr.AddToSymValue(s, int64(sect.Vaddr))
2852                 }
2853                 v := ldr.SymValue(s)
2854                 for sub := ldr.SubSym(s); sub != 0; sub = ldr.SubSym(sub) {
2855                         ldr.AddToSymValue(sub, v)
2856                 }
2857         }
2858
2859         for _, si := range dwarfp {
2860                 for _, s := range si.syms {
2861                         if sect := ldr.SymSect(s); sect != nil {
2862                                 ldr.AddToSymValue(s, int64(sect.Vaddr))
2863                         }
2864                         sub := ldr.SubSym(s)
2865                         if sub != 0 {
2866                                 panic(fmt.Sprintf("unexpected sub-sym for %s %s", ldr.SymName(s), ldr.SymType(s).String()))
2867                         }
2868                         v := ldr.SymValue(s)
2869                         for ; sub != 0; sub = ldr.SubSym(sub) {
2870                                 ldr.AddToSymValue(s, v)
2871                         }
2872                 }
2873         }
2874
2875         for _, s := range []loader.Sym{sehp.pdata, sehp.xdata} {
2876                 if sect := ldr.SymSect(s); sect != nil {
2877                         ldr.AddToSymValue(s, int64(sect.Vaddr))
2878                 }
2879         }
2880
2881         if ctxt.BuildMode == BuildModeShared {
2882                 s := ldr.LookupOrCreateSym("go:link.abihashbytes", 0)
2883                 sect := ldr.SymSect(ldr.LookupOrCreateSym(".note.go.abihash", 0))
2884                 ldr.SetSymSect(s, sect)
2885                 ldr.SetSymValue(s, int64(sect.Vaddr+16))
2886         }
2887
2888         // If there are multiple text sections, create runtime.text.n for
2889         // their section Vaddr, using n for index
2890         n := 1
2891         for _, sect := range Segtext.Sections[1:] {
2892                 if sect.Name != ".text" {
2893                         break
2894                 }
2895                 symname := fmt.Sprintf("runtime.text.%d", n)
2896                 if ctxt.HeadType != objabi.Haix || ctxt.LinkMode != LinkExternal {
2897                         // Addresses are already set on AIX with external linker
2898                         // because these symbols are part of their sections.
2899                         ctxt.xdefine(symname, sym.STEXT, int64(sect.Vaddr))
2900                 }
2901                 n++
2902         }
2903
2904         ctxt.xdefine("runtime.rodata", sym.SRODATA, int64(rodata.Vaddr))
2905         ctxt.xdefine("runtime.erodata", sym.SRODATA, int64(rodata.Vaddr+rodata.Length))
2906         ctxt.xdefine("runtime.types", sym.SRODATA, int64(types.Vaddr))
2907         ctxt.xdefine("runtime.etypes", sym.SRODATA, int64(types.Vaddr+types.Length))
2908
2909         s := ldr.Lookup("runtime.gcdata", 0)
2910         ldr.SetAttrLocal(s, true)
2911         ctxt.xdefine("runtime.egcdata", sym.SRODATA, ldr.SymAddr(s)+ldr.SymSize(s))
2912         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.egcdata", 0), ldr.SymSect(s))
2913
2914         s = ldr.LookupOrCreateSym("runtime.gcbss", 0)
2915         ldr.SetAttrLocal(s, true)
2916         ctxt.xdefine("runtime.egcbss", sym.SRODATA, ldr.SymAddr(s)+ldr.SymSize(s))
2917         ldr.SetSymSect(ldr.LookupOrCreateSym("runtime.egcbss", 0), ldr.SymSect(s))
2918
2919         ctxt.xdefine("runtime.symtab", sym.SRODATA, int64(symtab.Vaddr))
2920         ctxt.xdefine("runtime.esymtab", sym.SRODATA, int64(symtab.Vaddr+symtab.Length))
2921         ctxt.xdefine("runtime.pclntab", sym.SRODATA, int64(pclntab.Vaddr))
2922         ctxt.defineInternal("runtime.pcheader", sym.SRODATA)
2923         ctxt.defineInternal("runtime.funcnametab", sym.SRODATA)
2924         ctxt.defineInternal("runtime.cutab", sym.SRODATA)
2925         ctxt.defineInternal("runtime.filetab", sym.SRODATA)
2926         ctxt.defineInternal("runtime.pctab", sym.SRODATA)
2927         ctxt.defineInternal("runtime.functab", sym.SRODATA)
2928         ctxt.xdefine("runtime.epclntab", sym.SRODATA, int64(pclntab.Vaddr+pclntab.Length))
2929         ctxt.xdefine("runtime.noptrdata", sym.SNOPTRDATA, int64(noptr.Vaddr))
2930         ctxt.xdefine("runtime.enoptrdata", sym.SNOPTRDATA, int64(noptr.Vaddr+noptr.Length))
2931         ctxt.xdefine("runtime.bss", sym.SBSS, int64(bss.Vaddr))
2932         ctxt.xdefine("runtime.ebss", sym.SBSS, int64(bss.Vaddr+bss.Length))
2933         ctxt.xdefine("runtime.data", sym.SDATA, int64(data.Vaddr))
2934         ctxt.xdefine("runtime.edata", sym.SDATA, int64(data.Vaddr+data.Length))
2935         ctxt.xdefine("runtime.noptrbss", sym.SNOPTRBSS, int64(noptrbss.Vaddr))
2936         ctxt.xdefine("runtime.enoptrbss", sym.SNOPTRBSS, int64(noptrbss.Vaddr+noptrbss.Length))
2937         ctxt.xdefine("runtime.covctrs", sym.SCOVERAGE_COUNTER, int64(noptrbss.Vaddr+covCounterDataStartOff))
2938         ctxt.xdefine("runtime.ecovctrs", sym.SCOVERAGE_COUNTER, int64(noptrbss.Vaddr+covCounterDataStartOff+covCounterDataLen))
2939         ctxt.xdefine("runtime.end", sym.SBSS, int64(Segdata.Vaddr+Segdata.Length))
2940
2941         if fuzzCounters != nil {
2942                 ctxt.xdefine("runtime.__start___sancov_cntrs", sym.SLIBFUZZER_8BIT_COUNTER, int64(fuzzCounters.Vaddr))
2943                 ctxt.xdefine("runtime.__stop___sancov_cntrs", sym.SLIBFUZZER_8BIT_COUNTER, int64(fuzzCounters.Vaddr+fuzzCounters.Length))
2944                 ctxt.xdefine("internal/fuzz._counters", sym.SLIBFUZZER_8BIT_COUNTER, int64(fuzzCounters.Vaddr))
2945                 ctxt.xdefine("internal/fuzz._ecounters", sym.SLIBFUZZER_8BIT_COUNTER, int64(fuzzCounters.Vaddr+fuzzCounters.Length))
2946         }
2947
2948         if ctxt.IsSolaris() {
2949                 // On Solaris, in the runtime it sets the external names of the
2950                 // end symbols. Unset them and define separate symbols, so we
2951                 // keep both.
2952                 etext := ldr.Lookup("runtime.etext", 0)
2953                 edata := ldr.Lookup("runtime.edata", 0)
2954                 end := ldr.Lookup("runtime.end", 0)
2955                 ldr.SetSymExtname(etext, "runtime.etext")
2956                 ldr.SetSymExtname(edata, "runtime.edata")
2957                 ldr.SetSymExtname(end, "runtime.end")
2958                 ctxt.xdefine("_etext", ldr.SymType(etext), ldr.SymValue(etext))
2959                 ctxt.xdefine("_edata", ldr.SymType(edata), ldr.SymValue(edata))
2960                 ctxt.xdefine("_end", ldr.SymType(end), ldr.SymValue(end))
2961                 ldr.SetSymSect(ldr.Lookup("_etext", 0), ldr.SymSect(etext))
2962                 ldr.SetSymSect(ldr.Lookup("_edata", 0), ldr.SymSect(edata))
2963                 ldr.SetSymSect(ldr.Lookup("_end", 0), ldr.SymSect(end))
2964         }
2965
2966         if ctxt.IsPPC64() && ctxt.IsElf() {
2967                 // Resolve .TOC. symbols for all objects. Only one TOC region is supported. If a
2968                 // GOT section is present, compute it as suggested by the ELFv2 ABI. Otherwise,
2969                 // choose a similar offset from the start of the data segment.
2970                 tocAddr := int64(Segdata.Vaddr) + 0x8000
2971                 if gotAddr := ldr.SymValue(ctxt.GOT); gotAddr != 0 {
2972                         tocAddr = gotAddr + 0x8000
2973                 }
2974                 for i := range ctxt.DotTOC {
2975                         if i >= sym.SymVerABICount && i < sym.SymVerStatic { // these versions are not used currently
2976                                 continue
2977                         }
2978                         if toc := ldr.Lookup(".TOC.", i); toc != 0 {
2979                                 ldr.SetSymValue(toc, tocAddr)
2980                         }
2981                 }
2982         }
2983
2984         return order
2985 }
2986
2987 // layout assigns file offsets and lengths to the segments in order.
2988 // Returns the file size containing all the segments.
2989 func (ctxt *Link) layout(order []*sym.Segment) uint64 {
2990         var prev *sym.Segment
2991         for _, seg := range order {
2992                 if prev == nil {
2993                         seg.Fileoff = uint64(HEADR)
2994                 } else {
2995                         switch ctxt.HeadType {
2996                         default:
2997                                 // Assuming the previous segment was
2998                                 // aligned, the following rounding
2999                                 // should ensure that this segment's
3000                                 // VA ≡ Fileoff mod FlagRound.
3001                                 seg.Fileoff = uint64(Rnd(int64(prev.Fileoff+prev.Filelen), *FlagRound))
3002                                 if seg.Vaddr%uint64(*FlagRound) != seg.Fileoff%uint64(*FlagRound) {
3003                                         Exitf("bad segment rounding (Vaddr=%#x Fileoff=%#x FlagRound=%#x)", seg.Vaddr, seg.Fileoff, *FlagRound)
3004                                 }
3005                         case objabi.Hwindows:
3006                                 seg.Fileoff = prev.Fileoff + uint64(Rnd(int64(prev.Filelen), PEFILEALIGN))
3007                         case objabi.Hplan9:
3008                                 seg.Fileoff = prev.Fileoff + prev.Filelen
3009                         }
3010                 }
3011                 if seg != &Segdata {
3012                         // Link.address already set Segdata.Filelen to
3013                         // account for BSS.
3014                         seg.Filelen = seg.Length
3015                 }
3016                 prev = seg
3017         }
3018         return prev.Fileoff + prev.Filelen
3019 }
3020
3021 // add a trampoline with symbol s (to be laid down after the current function)
3022 func (ctxt *Link) AddTramp(s *loader.SymbolBuilder) {
3023         s.SetType(sym.STEXT)
3024         s.SetReachable(true)
3025         s.SetOnList(true)
3026         ctxt.tramps = append(ctxt.tramps, s.Sym())
3027         if *FlagDebugTramp > 0 && ctxt.Debugvlog > 0 {
3028                 ctxt.Logf("trampoline %s inserted\n", s.Name())
3029         }
3030 }
3031
3032 // compressSyms compresses syms and returns the contents of the
3033 // compressed section. If the section would get larger, it returns nil.
3034 func compressSyms(ctxt *Link, syms []loader.Sym) []byte {
3035         ldr := ctxt.loader
3036         var total int64
3037         for _, sym := range syms {
3038                 total += ldr.SymSize(sym)
3039         }
3040
3041         var buf bytes.Buffer
3042         if ctxt.IsELF {
3043                 switch ctxt.Arch.PtrSize {
3044                 case 8:
3045                         binary.Write(&buf, ctxt.Arch.ByteOrder, elf.Chdr64{
3046                                 Type:      uint32(elf.COMPRESS_ZLIB),
3047                                 Size:      uint64(total),
3048                                 Addralign: uint64(ctxt.Arch.Alignment),
3049                         })
3050                 case 4:
3051                         binary.Write(&buf, ctxt.Arch.ByteOrder, elf.Chdr32{
3052                                 Type:      uint32(elf.COMPRESS_ZLIB),
3053                                 Size:      uint32(total),
3054                                 Addralign: uint32(ctxt.Arch.Alignment),
3055                         })
3056                 default:
3057                         log.Fatalf("can't compress header size:%d", ctxt.Arch.PtrSize)
3058                 }
3059         } else {
3060                 buf.Write([]byte("ZLIB"))
3061                 var sizeBytes [8]byte
3062                 binary.BigEndian.PutUint64(sizeBytes[:], uint64(total))
3063                 buf.Write(sizeBytes[:])
3064         }
3065
3066         var relocbuf []byte // temporary buffer for applying relocations
3067
3068         // Using zlib.BestSpeed achieves very nearly the same
3069         // compression levels of zlib.DefaultCompression, but takes
3070         // substantially less time. This is important because DWARF
3071         // compression can be a significant fraction of link time.
3072         z, err := zlib.NewWriterLevel(&buf, zlib.BestSpeed)
3073         if err != nil {
3074                 log.Fatalf("NewWriterLevel failed: %s", err)
3075         }
3076         st := ctxt.makeRelocSymState()
3077         for _, s := range syms {
3078                 // Symbol data may be read-only. Apply relocations in a
3079                 // temporary buffer, and immediately write it out.
3080                 P := ldr.Data(s)
3081                 relocs := ldr.Relocs(s)
3082                 if relocs.Count() != 0 {
3083                         relocbuf = append(relocbuf[:0], P...)
3084                         P = relocbuf
3085                         st.relocsym(s, P)
3086                 }
3087                 if _, err := z.Write(P); err != nil {
3088                         log.Fatalf("compression failed: %s", err)
3089                 }
3090                 for i := ldr.SymSize(s) - int64(len(P)); i > 0; {
3091                         b := zeros[:]
3092                         if i < int64(len(b)) {
3093                                 b = b[:i]
3094                         }
3095                         n, err := z.Write(b)
3096                         if err != nil {
3097                                 log.Fatalf("compression failed: %s", err)
3098                         }
3099                         i -= int64(n)
3100                 }
3101         }
3102         if err := z.Close(); err != nil {
3103                 log.Fatalf("compression failed: %s", err)
3104         }
3105         if int64(buf.Len()) >= total {
3106                 // Compression didn't save any space.
3107                 return nil
3108         }
3109         return buf.Bytes()
3110 }