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