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