]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/link/internal/ld/lib.go
[dev.boringcrypto] all: merge master into dev.boringcrypto
[gostls13.git] / src / cmd / link / internal / ld / lib.go
1 // Inferno utils/8l/asm.c
2 // https://bitbucket.org/inferno-os/inferno-os/src/default/utils/8l/asm.c
3 //
4 //      Copyright © 1994-1999 Lucent Technologies Inc.  All rights reserved.
5 //      Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
6 //      Portions Copyright © 1997-1999 Vita Nuova Limited
7 //      Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
8 //      Portions Copyright © 2004,2006 Bruce Ellis
9 //      Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net)
10 //      Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
11 //      Portions Copyright © 2009 The Go Authors. All rights reserved.
12 //
13 // Permission is hereby granted, free of charge, to any person obtaining a copy
14 // of this software and associated documentation files (the "Software"), to deal
15 // in the Software without restriction, including without limitation the rights
16 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 // copies of the Software, and to permit persons to whom the Software is
18 // furnished to do so, subject to the following conditions:
19 //
20 // The above copyright notice and this permission notice shall be included in
21 // all copies or substantial portions of the Software.
22 //
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
26 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
29 // THE SOFTWARE.
30
31 package ld
32
33 import (
34         "bufio"
35         "bytes"
36         "cmd/internal/bio"
37         "cmd/internal/objabi"
38         "cmd/internal/sys"
39         "cmd/link/internal/loadelf"
40         "cmd/link/internal/loadmacho"
41         "cmd/link/internal/loadpe"
42         "cmd/link/internal/loadxcoff"
43         "cmd/link/internal/objfile"
44         "cmd/link/internal/sym"
45         "crypto/sha1"
46         "debug/elf"
47         "encoding/base64"
48         "encoding/binary"
49         "encoding/hex"
50         "fmt"
51         "io"
52         "io/ioutil"
53         "log"
54         "os"
55         "os/exec"
56         "path/filepath"
57         "runtime"
58         "strings"
59         "sync"
60 )
61
62 // Data layout and relocation.
63
64 // Derived from Inferno utils/6l/l.h
65 // https://bitbucket.org/inferno-os/inferno-os/src/default/utils/6l/l.h
66 //
67 //      Copyright © 1994-1999 Lucent Technologies Inc.  All rights reserved.
68 //      Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
69 //      Portions Copyright © 1997-1999 Vita Nuova Limited
70 //      Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
71 //      Portions Copyright © 2004,2006 Bruce Ellis
72 //      Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net)
73 //      Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
74 //      Portions Copyright © 2009 The Go Authors. All rights reserved.
75 //
76 // Permission is hereby granted, free of charge, to any person obtaining a copy
77 // of this software and associated documentation files (the "Software"), to deal
78 // in the Software without restriction, including without limitation the rights
79 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
80 // copies of the Software, and to permit persons to whom the Software is
81 // furnished to do so, subject to the following conditions:
82 //
83 // The above copyright notice and this permission notice shall be included in
84 // all copies or substantial portions of the Software.
85 //
86 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
87 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
88 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
89 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
90 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
91 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
92 // THE SOFTWARE.
93
94 type Arch struct {
95         Funcalign      int
96         Maxalign       int
97         Minalign       int
98         Dwarfregsp     int
99         Dwarfreglr     int
100         Linuxdynld     string
101         Freebsddynld   string
102         Netbsddynld    string
103         Openbsddynld   string
104         Dragonflydynld string
105         Solarisdynld   string
106         Adddynrel      func(*Link, *sym.Symbol, *sym.Reloc) bool
107         Archinit       func(*Link)
108         // Archreloc is an arch-specific hook that assists in
109         // relocation processing (invoked by 'relocsym'); it handles
110         // target-specific relocation tasks. Here "rel" is the current
111         // relocation being examined, "sym" is the symbol containing the
112         // chunk of data to which the relocation applies, and "off" is the
113         // contents of the to-be-relocated data item (from sym.P). Return
114         // value is the appropriately relocated value (to be written back
115         // to the same spot in sym.P) and a boolean indicating
116         // success/failure (a failing value indicates a fatal error).
117         Archreloc func(link *Link, rel *sym.Reloc, sym *sym.Symbol,
118                 offset int64) (relocatedOffset int64, success bool)
119         // Archrelocvariant is a second arch-specific hook used for
120         // relocation processing; it handles relocations where r.Type is
121         // insufficient to describe the relocation (r.Variant !=
122         // sym.RV_NONE). Here "rel" is the relocation being applied, "sym"
123         // is the symbol containing the chunk of data to which the
124         // relocation applies, and "off" is the contents of the
125         // to-be-relocated data item (from sym.P). Return is an updated
126         // offset value.
127         Archrelocvariant func(link *Link, rel *sym.Reloc, sym *sym.Symbol,
128                 offset int64) (relocatedOffset int64)
129         Trampoline  func(*Link, *sym.Reloc, *sym.Symbol)
130         Asmb        func(*Link)
131         Elfreloc1   func(*Link, *sym.Reloc, int64) bool
132         Elfsetupplt func(*Link)
133         Gentext     func(*Link)
134         Machoreloc1 func(*sys.Arch, *OutBuf, *sym.Symbol, *sym.Reloc, int64) bool
135         PEreloc1    func(*sys.Arch, *OutBuf, *sym.Symbol, *sym.Reloc, int64) bool
136
137         // TLSIEtoLE converts a TLS Initial Executable relocation to
138         // a TLS Local Executable relocation.
139         //
140         // This is possible when a TLS IE relocation refers to a local
141         // symbol in an executable, which is typical when internally
142         // linking PIE binaries.
143         TLSIEtoLE func(s *sym.Symbol, off, size int)
144
145         // optional override for assignAddress
146         AssignAddress func(ctxt *Link, sect *sym.Section, n int, s *sym.Symbol, va uint64, isTramp bool) (*sym.Section, int, uint64)
147 }
148
149 var (
150         thearch Arch
151         Lcsize  int32
152         rpath   Rpath
153         Spsize  int32
154         Symsize int32
155 )
156
157 const (
158         MINFUNC = 16 // minimum size for a function
159 )
160
161 // DynlinkingGo returns whether we are producing Go code that can live
162 // in separate shared libraries linked together at runtime.
163 func (ctxt *Link) DynlinkingGo() bool {
164         if !ctxt.Loaded {
165                 panic("DynlinkingGo called before all symbols loaded")
166         }
167         return ctxt.BuildMode == BuildModeShared || ctxt.linkShared || ctxt.BuildMode == BuildModePlugin || ctxt.CanUsePlugins()
168 }
169
170 // CanUsePlugins returns whether a plugins can be used
171 func (ctxt *Link) CanUsePlugins() bool {
172         return ctxt.Syms.ROLookup("plugin.Open", 0) != nil
173 }
174
175 // UseRelro returns whether to make use of "read only relocations" aka
176 // relro.
177 func (ctxt *Link) UseRelro() bool {
178         switch ctxt.BuildMode {
179         case BuildModeCArchive, BuildModeCShared, BuildModeShared, BuildModePIE, BuildModePlugin:
180                 return ctxt.IsELF
181         default:
182                 return ctxt.linkShared
183         }
184 }
185
186 var (
187         dynexp          []*sym.Symbol
188         dynlib          []string
189         ldflag          []string
190         havedynamic     int
191         Funcalign       int
192         iscgo           bool
193         elfglobalsymndx int
194         interpreter     string
195
196         debug_s bool // backup old value of debug['s']
197         HEADR   int32
198
199         nerrors  int
200         liveness int64
201 )
202
203 var (
204         Segtext      sym.Segment
205         Segrodata    sym.Segment
206         Segrelrodata sym.Segment
207         Segdata      sym.Segment
208         Segdwarf     sym.Segment
209 )
210
211 const pkgdef = "__.PKGDEF"
212
213 var (
214         // Set if we see an object compiled by the host compiler that is not
215         // from a package that is known to support internal linking mode.
216         externalobj = false
217         theline     string
218 )
219
220 func Lflag(ctxt *Link, arg string) {
221         ctxt.Libdir = append(ctxt.Libdir, arg)
222 }
223
224 /*
225  * Unix doesn't like it when we write to a running (or, sometimes,
226  * recently run) binary, so remove the output file before writing it.
227  * On Windows 7, remove() can force a subsequent create() to fail.
228  * S_ISREG() does not exist on Plan 9.
229  */
230 func mayberemoveoutfile() {
231         if fi, err := os.Lstat(*flagOutfile); err == nil && !fi.Mode().IsRegular() {
232                 return
233         }
234         os.Remove(*flagOutfile)
235 }
236
237 func libinit(ctxt *Link) {
238         Funcalign = thearch.Funcalign
239
240         // add goroot to the end of the libdir list.
241         suffix := ""
242
243         suffixsep := ""
244         if *flagInstallSuffix != "" {
245                 suffixsep = "_"
246                 suffix = *flagInstallSuffix
247         } else if *flagRace {
248                 suffixsep = "_"
249                 suffix = "race"
250         } else if *flagMsan {
251                 suffixsep = "_"
252                 suffix = "msan"
253         }
254
255         Lflag(ctxt, filepath.Join(objabi.GOROOT, "pkg", fmt.Sprintf("%s_%s%s%s", objabi.GOOS, objabi.GOARCH, suffixsep, suffix)))
256
257         mayberemoveoutfile()
258         f, err := os.OpenFile(*flagOutfile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0775)
259         if err != nil {
260                 Exitf("cannot create %s: %v", *flagOutfile, err)
261         }
262
263         ctxt.Out.w = bufio.NewWriter(f)
264         ctxt.Out.f = f
265
266         if *flagEntrySymbol == "" {
267                 switch ctxt.BuildMode {
268                 case BuildModeCShared, BuildModeCArchive:
269                         *flagEntrySymbol = fmt.Sprintf("_rt0_%s_%s_lib", objabi.GOARCH, objabi.GOOS)
270                 case BuildModeExe, BuildModePIE:
271                         *flagEntrySymbol = fmt.Sprintf("_rt0_%s_%s", objabi.GOARCH, objabi.GOOS)
272                 case BuildModeShared, BuildModePlugin:
273                         // No *flagEntrySymbol for -buildmode=shared and plugin
274                 default:
275                         Errorf(nil, "unknown *flagEntrySymbol for buildmode %v", ctxt.BuildMode)
276                 }
277         }
278 }
279
280 func errorexit() {
281         if nerrors != 0 {
282                 Exit(2)
283         }
284         Exit(0)
285 }
286
287 func loadinternal(ctxt *Link, name string) *sym.Library {
288         if ctxt.linkShared && ctxt.PackageShlib != nil {
289                 if shlib := ctxt.PackageShlib[name]; shlib != "" {
290                         return addlibpath(ctxt, "internal", "internal", "", name, shlib)
291                 }
292         }
293         if ctxt.PackageFile != nil {
294                 if pname := ctxt.PackageFile[name]; pname != "" {
295                         return addlibpath(ctxt, "internal", "internal", pname, name, "")
296                 }
297                 ctxt.Logf("loadinternal: cannot find %s\n", name)
298                 return nil
299         }
300
301         for _, libdir := range ctxt.Libdir {
302                 if ctxt.linkShared {
303                         shlibname := filepath.Join(libdir, name+".shlibname")
304                         if ctxt.Debugvlog != 0 {
305                                 ctxt.Logf("searching for %s.a in %s\n", name, shlibname)
306                         }
307                         if _, err := os.Stat(shlibname); err == nil {
308                                 return addlibpath(ctxt, "internal", "internal", "", name, shlibname)
309                         }
310                 }
311                 pname := filepath.Join(libdir, name+".a")
312                 if ctxt.Debugvlog != 0 {
313                         ctxt.Logf("searching for %s.a in %s\n", name, pname)
314                 }
315                 if _, err := os.Stat(pname); err == nil {
316                         return addlibpath(ctxt, "internal", "internal", pname, name, "")
317                 }
318         }
319
320         ctxt.Logf("warning: unable to find %s.a\n", name)
321         return nil
322 }
323
324 // findLibPathCmd uses cmd command to find gcc library libname.
325 // It returns library full path if found, or "none" if not found.
326 func (ctxt *Link) findLibPathCmd(cmd, libname string) string {
327         if *flagExtld == "" {
328                 *flagExtld = "gcc"
329         }
330         args := hostlinkArchArgs(ctxt.Arch)
331         args = append(args, cmd)
332         if ctxt.Debugvlog != 0 {
333                 ctxt.Logf("%s %v\n", *flagExtld, args)
334         }
335         out, err := exec.Command(*flagExtld, args...).Output()
336         if err != nil {
337                 if ctxt.Debugvlog != 0 {
338                         ctxt.Logf("not using a %s file because compiler failed\n%v\n%s\n", libname, err, out)
339                 }
340                 return "none"
341         }
342         return strings.TrimSpace(string(out))
343 }
344
345 // findLibPath searches for library libname.
346 // It returns library full path if found, or "none" if not found.
347 func (ctxt *Link) findLibPath(libname string) string {
348         return ctxt.findLibPathCmd("--print-file-name="+libname, libname)
349 }
350
351 func (ctxt *Link) loadlib() {
352         switch ctxt.BuildMode {
353         case BuildModeCShared, BuildModePlugin:
354                 s := ctxt.Syms.Lookup("runtime.islibrary", 0)
355                 s.Attr |= sym.AttrDuplicateOK
356                 s.AddUint8(1)
357         case BuildModeCArchive:
358                 s := ctxt.Syms.Lookup("runtime.isarchive", 0)
359                 s.Attr |= sym.AttrDuplicateOK
360                 s.AddUint8(1)
361         }
362
363         loadinternal(ctxt, "runtime")
364         if ctxt.Arch.Family == sys.ARM {
365                 loadinternal(ctxt, "math")
366         }
367         if *flagRace {
368                 loadinternal(ctxt, "runtime/race")
369         }
370         if *flagMsan {
371                 loadinternal(ctxt, "runtime/msan")
372         }
373
374         // ctxt.Library grows during the loop, so not a range loop.
375         for i := 0; i < len(ctxt.Library); i++ {
376                 lib := ctxt.Library[i]
377                 if lib.Shlib == "" {
378                         if ctxt.Debugvlog > 1 {
379                                 ctxt.Logf("%5.2f autolib: %s (from %s)\n", Cputime(), lib.File, lib.Objref)
380                         }
381                         loadobjfile(ctxt, lib)
382                 }
383         }
384
385         for _, lib := range ctxt.Library {
386                 if lib.Shlib != "" {
387                         if ctxt.Debugvlog > 1 {
388                                 ctxt.Logf("%5.2f autolib: %s (from %s)\n", Cputime(), lib.Shlib, lib.Objref)
389                         }
390                         ldshlibsyms(ctxt, lib.Shlib)
391                 }
392         }
393
394         iscgo = ctxt.Syms.ROLookup("x_cgo_init", 0) != nil
395
396         // We now have enough information to determine the link mode.
397         determineLinkMode(ctxt)
398
399         // Recalculate pe parameters now that we have ctxt.LinkMode set.
400         if ctxt.HeadType == objabi.Hwindows {
401                 Peinit(ctxt)
402         }
403
404         if ctxt.HeadType == objabi.Hdarwin && ctxt.LinkMode == LinkExternal {
405                 *FlagTextAddr = 0
406         }
407
408         if ctxt.LinkMode == LinkExternal && ctxt.Arch.Family == sys.PPC64 {
409                 toc := ctxt.Syms.Lookup(".TOC.", 0)
410                 toc.Type = sym.SDYNIMPORT
411         }
412
413         if ctxt.LinkMode == LinkExternal && !iscgo && ctxt.LibraryByPkg["runtime/cgo"] == nil && !(objabi.GOOS == "darwin" && (ctxt.Arch.Family == sys.AMD64 || ctxt.Arch.Family == sys.I386)) {
414                 // This indicates a user requested -linkmode=external.
415                 // The startup code uses an import of runtime/cgo to decide
416                 // whether to initialize the TLS.  So give it one. This could
417                 // be handled differently but it's an unusual case.
418                 if lib := loadinternal(ctxt, "runtime/cgo"); lib != nil {
419                         if lib.Shlib != "" {
420                                 ldshlibsyms(ctxt, lib.Shlib)
421                         } else {
422                                 if ctxt.BuildMode == BuildModeShared || ctxt.linkShared {
423                                         Exitf("cannot implicitly include runtime/cgo in a shared library")
424                                 }
425                                 loadobjfile(ctxt, lib)
426                         }
427                 }
428         }
429
430         if ctxt.LinkMode == LinkInternal {
431                 // Drop all the cgo_import_static declarations.
432                 // Turns out we won't be needing them.
433                 for _, s := range ctxt.Syms.Allsym {
434                         if s.Type == sym.SHOSTOBJ {
435                                 // If a symbol was marked both
436                                 // cgo_import_static and cgo_import_dynamic,
437                                 // then we want to make it cgo_import_dynamic
438                                 // now.
439                                 if s.Extname() != "" && s.Dynimplib() != "" && !s.Attr.CgoExport() {
440                                         s.Type = sym.SDYNIMPORT
441                                 } else {
442                                         s.Type = 0
443                                 }
444                         }
445                 }
446         }
447
448         tlsg := ctxt.Syms.Lookup("runtime.tlsg", 0)
449
450         // runtime.tlsg is used for external linking on platforms that do not define
451         // a variable to hold g in assembly (currently only intel).
452         if tlsg.Type == 0 {
453                 tlsg.Type = sym.STLSBSS
454                 tlsg.Size = int64(ctxt.Arch.PtrSize)
455         } else if tlsg.Type != sym.SDYNIMPORT {
456                 Errorf(nil, "runtime declared tlsg variable %v", tlsg.Type)
457         }
458         tlsg.Attr |= sym.AttrReachable
459         ctxt.Tlsg = tlsg
460
461         var moduledata *sym.Symbol
462         if ctxt.BuildMode == BuildModePlugin {
463                 moduledata = ctxt.Syms.Lookup("local.pluginmoduledata", 0)
464                 moduledata.Attr |= sym.AttrLocal
465         } else {
466                 moduledata = ctxt.Syms.Lookup("runtime.firstmoduledata", 0)
467         }
468         if moduledata.Type != 0 && moduledata.Type != sym.SDYNIMPORT {
469                 // If the module (toolchain-speak for "executable or shared
470                 // library") we are linking contains the runtime package, it
471                 // will define the runtime.firstmoduledata symbol and we
472                 // truncate it back to 0 bytes so we can define its entire
473                 // contents in symtab.go:symtab().
474                 moduledata.Size = 0
475
476                 // In addition, on ARM, the runtime depends on the linker
477                 // recording the value of GOARM.
478                 if ctxt.Arch.Family == sys.ARM {
479                         s := ctxt.Syms.Lookup("runtime.goarm", 0)
480                         s.Type = sym.SDATA
481                         s.Size = 0
482                         s.AddUint8(uint8(objabi.GOARM))
483                 }
484
485                 if objabi.Framepointer_enabled(objabi.GOOS, objabi.GOARCH) {
486                         s := ctxt.Syms.Lookup("runtime.framepointer_enabled", 0)
487                         s.Type = sym.SDATA
488                         s.Size = 0
489                         s.AddUint8(1)
490                 }
491         } else {
492                 // If OTOH the module does not contain the runtime package,
493                 // create a local symbol for the moduledata.
494                 moduledata = ctxt.Syms.Lookup("local.moduledata", 0)
495                 moduledata.Attr |= sym.AttrLocal
496         }
497         // In all cases way we mark the moduledata as noptrdata to hide it from
498         // the GC.
499         moduledata.Type = sym.SNOPTRDATA
500         moduledata.Attr |= sym.AttrReachable
501         ctxt.Moduledata = moduledata
502
503         // Now that we know the link mode, trim the dynexp list.
504         x := sym.AttrCgoExportDynamic
505
506         if ctxt.LinkMode == LinkExternal {
507                 x = sym.AttrCgoExportStatic
508         }
509         w := 0
510         for i := range dynexp {
511                 if dynexp[i].Attr&x != 0 {
512                         dynexp[w] = dynexp[i]
513                         w++
514                 }
515         }
516         dynexp = dynexp[:w]
517
518         // In internal link mode, read the host object files.
519         if ctxt.LinkMode == LinkInternal {
520                 hostobjs(ctxt)
521
522                 // If we have any undefined symbols in external
523                 // objects, try to read them from the libgcc file.
524                 any := false
525                 for _, s := range ctxt.Syms.Allsym {
526                         for i := range s.R {
527                                 r := &s.R[i] // Copying sym.Reloc has measurable impact on performance
528                                 if r.Sym != nil && r.Sym.Type == sym.SXREF && r.Sym.Name != ".got" {
529                                         any = true
530                                         break
531                                 }
532                         }
533                 }
534                 if any {
535                         if *flagLibGCC == "" {
536                                 *flagLibGCC = ctxt.findLibPathCmd("--print-libgcc-file-name", "libgcc")
537                         }
538                         if *flagLibGCC != "none" {
539                                 hostArchive(ctxt, *flagLibGCC)
540                         }
541                         if ctxt.HeadType == objabi.Hwindows {
542                                 if p := ctxt.findLibPath("libmingwex.a"); p != "none" {
543                                         hostArchive(ctxt, p)
544                                 }
545                                 if p := ctxt.findLibPath("libmingw32.a"); p != "none" {
546                                         hostArchive(ctxt, p)
547                                 }
548                                 // TODO: maybe do something similar to peimporteddlls to collect all lib names
549                                 // and try link them all to final exe just like libmingwex.a and libmingw32.a:
550                                 /*
551                                         for:
552                                         #cgo windows LDFLAGS: -lmsvcrt -lm
553                                         import:
554                                         libmsvcrt.a libm.a
555                                 */
556                         }
557                 }
558         } else {
559                 hostlinksetup(ctxt)
560         }
561
562         // We've loaded all the code now.
563         ctxt.Loaded = true
564
565         // If there are no dynamic libraries needed, gcc disables dynamic linking.
566         // Because of this, glibc's dynamic ELF loader occasionally (like in version 2.13)
567         // assumes that a dynamic binary always refers to at least one dynamic library.
568         // Rather than be a source of test cases for glibc, disable dynamic linking
569         // the same way that gcc would.
570         //
571         // Exception: on OS X, programs such as Shark only work with dynamic
572         // binaries, so leave it enabled on OS X (Mach-O) binaries.
573         // Also leave it enabled on Solaris which doesn't support
574         // statically linked binaries.
575         if ctxt.BuildMode == BuildModeExe {
576                 if havedynamic == 0 && ctxt.HeadType != objabi.Hdarwin && ctxt.HeadType != objabi.Hsolaris {
577                         *FlagD = true
578                 }
579         }
580
581         // If package versioning is required, generate a hash of the
582         // packages used in the link.
583         if ctxt.BuildMode == BuildModeShared || ctxt.BuildMode == BuildModePlugin || ctxt.CanUsePlugins() {
584                 for _, lib := range ctxt.Library {
585                         if lib.Shlib == "" {
586                                 genhash(ctxt, lib)
587                         }
588                 }
589         }
590
591         if ctxt.Arch == sys.Arch386 {
592                 if (ctxt.BuildMode == BuildModeCArchive && ctxt.IsELF) || (ctxt.BuildMode == BuildModeCShared && ctxt.HeadType != objabi.Hwindows) || ctxt.BuildMode == BuildModePIE || ctxt.DynlinkingGo() {
593                         got := ctxt.Syms.Lookup("_GLOBAL_OFFSET_TABLE_", 0)
594                         got.Type = sym.SDYNIMPORT
595                         got.Attr |= sym.AttrReachable
596                 }
597         }
598
599         importcycles()
600
601         // put symbols into Textp
602         // do it in postorder so that packages are laid down in dependency order
603         // internal first, then everything else
604         ctxt.Library = postorder(ctxt.Library)
605         for _, doInternal := range [2]bool{true, false} {
606                 for _, lib := range ctxt.Library {
607                         if isRuntimeDepPkg(lib.Pkg) != doInternal {
608                                 continue
609                         }
610                         ctxt.Textp = append(ctxt.Textp, lib.Textp...)
611                         for _, s := range lib.DupTextSyms {
612                                 if !s.Attr.OnList() {
613                                         ctxt.Textp = append(ctxt.Textp, s)
614                                         s.Attr |= sym.AttrOnList
615                                         // dupok symbols may be defined in multiple packages. its
616                                         // associated package is chosen sort of arbitrarily (the
617                                         // first containing package that the linker loads). canonicalize
618                                         // it here to the package with which it will be laid down
619                                         // in text.
620                                         s.File = objabi.PathToPrefix(lib.Pkg)
621                                 }
622                         }
623                 }
624         }
625
626         if len(ctxt.Shlibs) > 0 {
627                 // We might have overwritten some functions above (this tends to happen for the
628                 // autogenerated type equality/hashing functions) and we don't want to generated
629                 // pcln table entries for these any more so remove them from Textp.
630                 textp := make([]*sym.Symbol, 0, len(ctxt.Textp))
631                 for _, s := range ctxt.Textp {
632                         if s.Type != sym.SDYNIMPORT {
633                                 textp = append(textp, s)
634                         }
635                 }
636                 ctxt.Textp = textp
637         }
638 }
639
640 // mangleTypeSym shortens the names of symbols that represent Go types
641 // if they are visible in the symbol table.
642 //
643 // As the names of these symbols are derived from the string of
644 // the type, they can run to many kilobytes long. So we shorten
645 // them using a SHA-1 when the name appears in the final binary.
646 // This also removes characters that upset external linkers.
647 //
648 // These are the symbols that begin with the prefix 'type.' and
649 // contain run-time type information used by the runtime and reflect
650 // packages. All Go binaries contain these symbols, but only
651 // those programs loaded dynamically in multiple parts need these
652 // symbols to have entries in the symbol table.
653 func (ctxt *Link) mangleTypeSym() {
654         if ctxt.BuildMode != BuildModeShared && !ctxt.linkShared && ctxt.BuildMode != BuildModePlugin && ctxt.Syms.ROLookup("plugin.Open", 0) == nil {
655                 return
656         }
657
658         for _, s := range ctxt.Syms.Allsym {
659                 newName := typeSymbolMangle(s.Name)
660                 if newName != s.Name {
661                         ctxt.Syms.Rename(s.Name, newName, int(s.Version), ctxt.Reachparent)
662                 }
663         }
664 }
665
666 // typeSymbolMangle mangles the given symbol name into something shorter.
667 //
668 // Keep the type.. prefix, which parts of the linker (like the
669 // DWARF generator) know means the symbol is not decodable.
670 // Leave type.runtime. symbols alone, because other parts of
671 // the linker manipulates them.
672 func typeSymbolMangle(name string) string {
673         if !strings.HasPrefix(name, "type.") {
674                 return name
675         }
676         if strings.HasPrefix(name, "type.runtime.") {
677                 return name
678         }
679         if len(name) <= 14 && !strings.Contains(name, "@") { // Issue 19529
680                 return name
681         }
682         hash := sha1.Sum([]byte(name))
683         prefix := "type."
684         if name[5] == '.' {
685                 prefix = "type.."
686         }
687         return prefix + base64.StdEncoding.EncodeToString(hash[:6])
688 }
689
690 /*
691  * look for the next file in an archive.
692  * adapted from libmach.
693  */
694 func nextar(bp *bio.Reader, off int64, a *ArHdr) int64 {
695         if off&1 != 0 {
696                 off++
697         }
698         bp.Seek(off, 0)
699         var buf [SAR_HDR]byte
700         if n, err := io.ReadFull(bp, buf[:]); err != nil {
701                 if n == 0 && err != io.EOF {
702                         return -1
703                 }
704                 return 0
705         }
706
707         a.name = artrim(buf[0:16])
708         a.date = artrim(buf[16:28])
709         a.uid = artrim(buf[28:34])
710         a.gid = artrim(buf[34:40])
711         a.mode = artrim(buf[40:48])
712         a.size = artrim(buf[48:58])
713         a.fmag = artrim(buf[58:60])
714
715         arsize := atolwhex(a.size)
716         if arsize&1 != 0 {
717                 arsize++
718         }
719         return arsize + SAR_HDR
720 }
721
722 func genhash(ctxt *Link, lib *sym.Library) {
723         f, err := bio.Open(lib.File)
724         if err != nil {
725                 Errorf(nil, "cannot open file %s for hash generation: %v", lib.File, err)
726                 return
727         }
728         defer f.Close()
729
730         var magbuf [len(ARMAG)]byte
731         if _, err := io.ReadFull(f, magbuf[:]); err != nil {
732                 Exitf("file %s too short", lib.File)
733         }
734
735         if string(magbuf[:]) != ARMAG {
736                 Exitf("%s is not an archive file", lib.File)
737         }
738
739         var arhdr ArHdr
740         l := nextar(f, f.Offset(), &arhdr)
741         if l <= 0 {
742                 Errorf(nil, "%s: short read on archive file symbol header", lib.File)
743                 return
744         }
745         if arhdr.name != pkgdef {
746                 Errorf(nil, "%s: missing package data entry", lib.File)
747                 return
748         }
749
750         h := sha1.New()
751
752         // To compute the hash of a package, we hash the first line of
753         // __.PKGDEF (which contains the toolchain version and any
754         // GOEXPERIMENT flags) and the export data (which is between
755         // the first two occurrences of "\n$$").
756
757         pkgDefBytes := make([]byte, atolwhex(arhdr.size))
758         _, err = io.ReadFull(f, pkgDefBytes)
759         if err != nil {
760                 Errorf(nil, "%s: error reading package data: %v", lib.File, err)
761                 return
762         }
763         firstEOL := bytes.IndexByte(pkgDefBytes, '\n')
764         if firstEOL < 0 {
765                 Errorf(nil, "cannot parse package data of %s for hash generation, no newline found", lib.File)
766                 return
767         }
768         firstDoubleDollar := bytes.Index(pkgDefBytes, []byte("\n$$"))
769         if firstDoubleDollar < 0 {
770                 Errorf(nil, "cannot parse package data of %s for hash generation, no \\n$$ found", lib.File)
771                 return
772         }
773         secondDoubleDollar := bytes.Index(pkgDefBytes[firstDoubleDollar+1:], []byte("\n$$"))
774         if secondDoubleDollar < 0 {
775                 Errorf(nil, "cannot parse package data of %s for hash generation, only one \\n$$ found", lib.File)
776                 return
777         }
778         h.Write(pkgDefBytes[0:firstEOL])
779         h.Write(pkgDefBytes[firstDoubleDollar : firstDoubleDollar+secondDoubleDollar])
780         lib.Hash = hex.EncodeToString(h.Sum(nil))
781 }
782
783 func loadobjfile(ctxt *Link, lib *sym.Library) {
784         pkg := objabi.PathToPrefix(lib.Pkg)
785
786         if ctxt.Debugvlog > 1 {
787                 ctxt.Logf("%5.2f ldobj: %s (%s)\n", Cputime(), lib.File, pkg)
788         }
789         f, err := bio.Open(lib.File)
790         if err != nil {
791                 Exitf("cannot open file %s: %v", lib.File, err)
792         }
793         defer f.Close()
794         defer func() {
795                 if pkg == "main" && !lib.Main {
796                         Exitf("%s: not package main", lib.File)
797                 }
798
799                 // Ideally, we'd check that *all* object files within
800                 // the archive were marked safe, but here we settle
801                 // for *any*.
802                 //
803                 // Historically, cmd/link only checked the __.PKGDEF
804                 // file, which in turn came from the first object
805                 // file, typically produced by cmd/compile. The
806                 // remaining object files are normally produced by
807                 // cmd/asm, which doesn't support marking files as
808                 // safe anyway. So at least in practice, this matches
809                 // how safe mode has always worked.
810                 if *flagU && !lib.Safe {
811                         Exitf("%s: load of unsafe package %s", lib.File, pkg)
812                 }
813         }()
814
815         for i := 0; i < len(ARMAG); i++ {
816                 if c, err := f.ReadByte(); err == nil && c == ARMAG[i] {
817                         continue
818                 }
819
820                 /* load it as a regular file */
821                 l := f.Seek(0, 2)
822                 f.Seek(0, 0)
823                 ldobj(ctxt, f, lib, l, lib.File, lib.File)
824                 return
825         }
826
827         /*
828          * load all the object files from the archive now.
829          * this gives us sequential file access and keeps us
830          * from needing to come back later to pick up more
831          * objects.  it breaks the usual C archive model, but
832          * this is Go, not C.  the common case in Go is that
833          * we need to load all the objects, and then we throw away
834          * the individual symbols that are unused.
835          *
836          * loading every object will also make it possible to
837          * load foreign objects not referenced by __.PKGDEF.
838          */
839         var arhdr ArHdr
840         off := f.Offset()
841         for {
842                 l := nextar(f, off, &arhdr)
843                 if l == 0 {
844                         break
845                 }
846                 if l < 0 {
847                         Exitf("%s: malformed archive", lib.File)
848                 }
849                 off += l
850
851                 // __.PKGDEF isn't a real Go object file, and it's
852                 // absent in -linkobj builds anyway. Skipping it
853                 // ensures consistency between -linkobj and normal
854                 // build modes.
855                 if arhdr.name == pkgdef {
856                         continue
857                 }
858
859                 // Skip other special (non-object-file) sections that
860                 // build tools may have added. Such sections must have
861                 // short names so that the suffix is not truncated.
862                 if len(arhdr.name) < 16 && !strings.HasSuffix(arhdr.name, ".o") {
863                         continue
864                 }
865
866                 pname := fmt.Sprintf("%s(%s)", lib.File, arhdr.name)
867                 l = atolwhex(arhdr.size)
868                 ldobj(ctxt, f, lib, l, pname, lib.File)
869         }
870 }
871
872 type Hostobj struct {
873         ld     func(*Link, *bio.Reader, string, int64, string)
874         pkg    string
875         pn     string
876         file   string
877         off    int64
878         length int64
879 }
880
881 var hostobj []Hostobj
882
883 // These packages can use internal linking mode.
884 // Others trigger external mode.
885 var internalpkg = []string{
886         "crypto/internal/boring",
887         "crypto/x509",
888         "net",
889         "os/user",
890         "runtime/cgo",
891         "runtime/race",
892         "runtime/msan",
893 }
894
895 func ldhostobj(ld func(*Link, *bio.Reader, string, int64, string), headType objabi.HeadType, f *bio.Reader, pkg string, length int64, pn string, file string) *Hostobj {
896         isinternal := false
897         for _, intpkg := range internalpkg {
898                 if pkg == intpkg {
899                         isinternal = true
900                         break
901                 }
902         }
903
904         // DragonFly declares errno with __thread, which results in a symbol
905         // type of R_386_TLS_GD or R_X86_64_TLSGD. The Go linker does not
906         // currently know how to handle TLS relocations, hence we have to
907         // force external linking for any libraries that link in code that
908         // uses errno. This can be removed if the Go linker ever supports
909         // these relocation types.
910         if headType == objabi.Hdragonfly {
911                 if pkg == "net" || pkg == "os/user" {
912                         isinternal = false
913                 }
914         }
915
916         if !isinternal {
917                 externalobj = true
918         }
919
920         hostobj = append(hostobj, Hostobj{})
921         h := &hostobj[len(hostobj)-1]
922         h.ld = ld
923         h.pkg = pkg
924         h.pn = pn
925         h.file = file
926         h.off = f.Offset()
927         h.length = length
928         return h
929 }
930
931 func hostobjs(ctxt *Link) {
932         var h *Hostobj
933
934         for i := 0; i < len(hostobj); i++ {
935                 h = &hostobj[i]
936                 f, err := bio.Open(h.file)
937                 if err != nil {
938                         Exitf("cannot reopen %s: %v", h.pn, err)
939                 }
940
941                 f.Seek(h.off, 0)
942                 h.ld(ctxt, f, h.pkg, h.length, h.pn)
943                 f.Close()
944         }
945 }
946
947 func hostlinksetup(ctxt *Link) {
948         if ctxt.LinkMode != LinkExternal {
949                 return
950         }
951
952         // For external link, record that we need to tell the external linker -s,
953         // and turn off -s internally: the external linker needs the symbol
954         // information for its final link.
955         debug_s = *FlagS
956         *FlagS = false
957
958         // create temporary directory and arrange cleanup
959         if *flagTmpdir == "" {
960                 dir, err := ioutil.TempDir("", "go-link-")
961                 if err != nil {
962                         log.Fatal(err)
963                 }
964                 *flagTmpdir = dir
965                 AtExit(func() {
966                         ctxt.Out.f.Close()
967                         os.RemoveAll(*flagTmpdir)
968                 })
969         }
970
971         // change our output to temporary object file
972         ctxt.Out.f.Close()
973         mayberemoveoutfile()
974
975         p := filepath.Join(*flagTmpdir, "go.o")
976         var err error
977         f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0775)
978         if err != nil {
979                 Exitf("cannot create %s: %v", p, err)
980         }
981
982         ctxt.Out.w = bufio.NewWriter(f)
983         ctxt.Out.f = f
984         ctxt.Out.off = 0
985 }
986
987 // hostobjCopy creates a copy of the object files in hostobj in a
988 // temporary directory.
989 func hostobjCopy() (paths []string) {
990         var wg sync.WaitGroup
991         sema := make(chan struct{}, runtime.NumCPU()) // limit open file descriptors
992         for i, h := range hostobj {
993                 h := h
994                 dst := filepath.Join(*flagTmpdir, fmt.Sprintf("%06d.o", i))
995                 paths = append(paths, dst)
996
997                 wg.Add(1)
998                 go func() {
999                         sema <- struct{}{}
1000                         defer func() {
1001                                 <-sema
1002                                 wg.Done()
1003                         }()
1004                         f, err := os.Open(h.file)
1005                         if err != nil {
1006                                 Exitf("cannot reopen %s: %v", h.pn, err)
1007                         }
1008                         if _, err := f.Seek(h.off, 0); err != nil {
1009                                 Exitf("cannot seek %s: %v", h.pn, err)
1010                         }
1011
1012                         w, err := os.Create(dst)
1013                         if err != nil {
1014                                 Exitf("cannot create %s: %v", dst, err)
1015                         }
1016                         if _, err := io.CopyN(w, f, h.length); err != nil {
1017                                 Exitf("cannot write %s: %v", dst, err)
1018                         }
1019                         if err := w.Close(); err != nil {
1020                                 Exitf("cannot close %s: %v", dst, err)
1021                         }
1022                 }()
1023         }
1024         wg.Wait()
1025         return paths
1026 }
1027
1028 // writeGDBLinkerScript creates gcc linker script file in temp
1029 // directory. writeGDBLinkerScript returns created file path.
1030 // The script is used to work around gcc bug
1031 // (see https://golang.org/issue/20183 for details).
1032 func writeGDBLinkerScript() string {
1033         name := "fix_debug_gdb_scripts.ld"
1034         path := filepath.Join(*flagTmpdir, name)
1035         src := `SECTIONS
1036 {
1037   .debug_gdb_scripts BLOCK(__section_alignment__) (NOLOAD) :
1038   {
1039     *(.debug_gdb_scripts)
1040   }
1041 }
1042 INSERT AFTER .debug_types;
1043 `
1044         err := ioutil.WriteFile(path, []byte(src), 0666)
1045         if err != nil {
1046                 Errorf(nil, "WriteFile %s failed: %v", name, err)
1047         }
1048         return path
1049 }
1050
1051 // archive builds a .a archive from the hostobj object files.
1052 func (ctxt *Link) archive() {
1053         if ctxt.BuildMode != BuildModeCArchive {
1054                 return
1055         }
1056
1057         if *flagExtar == "" {
1058                 *flagExtar = "ar"
1059         }
1060
1061         mayberemoveoutfile()
1062
1063         // Force the buffer to flush here so that external
1064         // tools will see a complete file.
1065         ctxt.Out.Flush()
1066         if err := ctxt.Out.f.Close(); err != nil {
1067                 Exitf("close: %v", err)
1068         }
1069         ctxt.Out.f = nil
1070
1071         argv := []string{*flagExtar, "-q", "-c", "-s", *flagOutfile}
1072         argv = append(argv, filepath.Join(*flagTmpdir, "go.o"))
1073         argv = append(argv, hostobjCopy()...)
1074
1075         if ctxt.Debugvlog != 0 {
1076                 ctxt.Logf("archive: %s\n", strings.Join(argv, " "))
1077         }
1078
1079         if out, err := exec.Command(argv[0], argv[1:]...).CombinedOutput(); err != nil {
1080                 Exitf("running %s failed: %v\n%s", argv[0], err, out)
1081         }
1082 }
1083
1084 func (ctxt *Link) hostlink() {
1085         if ctxt.LinkMode != LinkExternal || nerrors > 0 {
1086                 return
1087         }
1088         if ctxt.BuildMode == BuildModeCArchive {
1089                 return
1090         }
1091
1092         if *flagExtld == "" {
1093                 *flagExtld = "gcc"
1094         }
1095
1096         var argv []string
1097         argv = append(argv, *flagExtld)
1098         argv = append(argv, hostlinkArchArgs(ctxt.Arch)...)
1099
1100         if *FlagS || debug_s {
1101                 if ctxt.HeadType == objabi.Hdarwin {
1102                         // Recent versions of macOS print
1103                         //      ld: warning: option -s is obsolete and being ignored
1104                         // so do not pass any arguments.
1105                 } else {
1106                         argv = append(argv, "-s")
1107                 }
1108         }
1109
1110         switch ctxt.HeadType {
1111         case objabi.Hdarwin:
1112                 argv = append(argv, "-Wl,-headerpad,1144")
1113                 if ctxt.DynlinkingGo() {
1114                         argv = append(argv, "-Wl,-flat_namespace")
1115                 }
1116                 if ctxt.BuildMode == BuildModeExe && !ctxt.Arch.InFamily(sys.ARM64) {
1117                         argv = append(argv, "-Wl,-no_pie")
1118                 }
1119         case objabi.Hopenbsd:
1120                 argv = append(argv, "-Wl,-nopie")
1121         case objabi.Hwindows:
1122                 if windowsgui {
1123                         argv = append(argv, "-mwindows")
1124                 } else {
1125                         argv = append(argv, "-mconsole")
1126                 }
1127         }
1128
1129         switch ctxt.BuildMode {
1130         case BuildModeExe:
1131                 if ctxt.HeadType == objabi.Hdarwin {
1132                         if ctxt.Arch.Family == sys.ARM64 {
1133                                 // __PAGEZERO segment size determined empirically.
1134                                 // XCode 9.0.1 successfully uploads an iOS app with this value.
1135                                 argv = append(argv, "-Wl,-pagezero_size,100000000")
1136                         } else {
1137                                 argv = append(argv, "-Wl,-pagezero_size,4000000")
1138                         }
1139                 }
1140         case BuildModePIE:
1141                 // ELF.
1142                 if ctxt.HeadType != objabi.Hdarwin {
1143                         if ctxt.UseRelro() {
1144                                 argv = append(argv, "-Wl,-z,relro")
1145                         }
1146                         argv = append(argv, "-pie")
1147                 }
1148         case BuildModeCShared:
1149                 if ctxt.HeadType == objabi.Hdarwin {
1150                         argv = append(argv, "-dynamiclib")
1151                         if ctxt.Arch.Family != sys.AMD64 {
1152                                 argv = append(argv, "-Wl,-read_only_relocs,suppress")
1153                         }
1154                 } else {
1155                         // ELF.
1156                         argv = append(argv, "-Wl,-Bsymbolic")
1157                         if ctxt.UseRelro() {
1158                                 argv = append(argv, "-Wl,-z,relro")
1159                         }
1160                         argv = append(argv, "-shared")
1161                         if ctxt.HeadType != objabi.Hwindows {
1162                                 // Pass -z nodelete to mark the shared library as
1163                                 // non-closeable: a dlclose will do nothing.
1164                                 argv = append(argv, "-Wl,-z,nodelete")
1165                         }
1166                 }
1167         case BuildModeShared:
1168                 if ctxt.UseRelro() {
1169                         argv = append(argv, "-Wl,-z,relro")
1170                 }
1171                 argv = append(argv, "-shared")
1172         case BuildModePlugin:
1173                 if ctxt.HeadType == objabi.Hdarwin {
1174                         argv = append(argv, "-dynamiclib")
1175                 } else {
1176                         if ctxt.UseRelro() {
1177                                 argv = append(argv, "-Wl,-z,relro")
1178                         }
1179                         argv = append(argv, "-shared")
1180                 }
1181         }
1182
1183         if ctxt.IsELF && ctxt.DynlinkingGo() {
1184                 // We force all symbol resolution to be done at program startup
1185                 // because lazy PLT resolution can use large amounts of stack at
1186                 // times we cannot allow it to do so.
1187                 argv = append(argv, "-Wl,-znow")
1188
1189                 // Do not let the host linker generate COPY relocations. These
1190                 // can move symbols out of sections that rely on stable offsets
1191                 // from the beginning of the section (like sym.STYPE).
1192                 argv = append(argv, "-Wl,-znocopyreloc")
1193
1194                 if ctxt.Arch.InFamily(sys.ARM, sys.ARM64) {
1195                         // On ARM, the GNU linker will generate COPY relocations
1196                         // even with -znocopyreloc set.
1197                         // https://sourceware.org/bugzilla/show_bug.cgi?id=19962
1198                         //
1199                         // On ARM64, the GNU linker will fail instead of
1200                         // generating COPY relocations.
1201                         //
1202                         // In both cases, switch to gold.
1203                         argv = append(argv, "-fuse-ld=gold")
1204
1205                         // If gold is not installed, gcc will silently switch
1206                         // back to ld.bfd. So we parse the version information
1207                         // and provide a useful error if gold is missing.
1208                         cmd := exec.Command(*flagExtld, "-fuse-ld=gold", "-Wl,--version")
1209                         if out, err := cmd.CombinedOutput(); err == nil {
1210                                 if !bytes.Contains(out, []byte("GNU gold")) {
1211                                         log.Fatalf("ARM external linker must be gold (issue #15696), but is not: %s", out)
1212                                 }
1213                         }
1214                 }
1215         }
1216
1217         if ctxt.IsELF && len(buildinfo) > 0 {
1218                 argv = append(argv, fmt.Sprintf("-Wl,--build-id=0x%x", buildinfo))
1219         }
1220
1221         // On Windows, given -o foo, GCC will append ".exe" to produce
1222         // "foo.exe".  We have decided that we want to honor the -o
1223         // option. To make this work, we append a '.' so that GCC
1224         // will decide that the file already has an extension. We
1225         // only want to do this when producing a Windows output file
1226         // on a Windows host.
1227         outopt := *flagOutfile
1228         if objabi.GOOS == "windows" && runtime.GOOS == "windows" && filepath.Ext(outopt) == "" {
1229                 outopt += "."
1230         }
1231         argv = append(argv, "-o")
1232         argv = append(argv, outopt)
1233
1234         if rpath.val != "" {
1235                 argv = append(argv, fmt.Sprintf("-Wl,-rpath,%s", rpath.val))
1236         }
1237
1238         // Force global symbols to be exported for dlopen, etc.
1239         if ctxt.IsELF {
1240                 argv = append(argv, "-rdynamic")
1241         }
1242
1243         if strings.Contains(argv[0], "clang") {
1244                 argv = append(argv, "-Qunused-arguments")
1245         }
1246
1247         const compressDWARF = "-Wl,--compress-debug-sections=zlib-gnu"
1248         if ctxt.compressDWARF && linkerFlagSupported(argv[0], compressDWARF) {
1249                 argv = append(argv, compressDWARF)
1250         }
1251
1252         argv = append(argv, filepath.Join(*flagTmpdir, "go.o"))
1253         argv = append(argv, hostobjCopy()...)
1254
1255         if ctxt.linkShared {
1256                 seenDirs := make(map[string]bool)
1257                 seenLibs := make(map[string]bool)
1258                 addshlib := func(path string) {
1259                         dir, base := filepath.Split(path)
1260                         if !seenDirs[dir] {
1261                                 argv = append(argv, "-L"+dir)
1262                                 if !rpath.set {
1263                                         argv = append(argv, "-Wl,-rpath="+dir)
1264                                 }
1265                                 seenDirs[dir] = true
1266                         }
1267                         base = strings.TrimSuffix(base, ".so")
1268                         base = strings.TrimPrefix(base, "lib")
1269                         if !seenLibs[base] {
1270                                 argv = append(argv, "-l"+base)
1271                                 seenLibs[base] = true
1272                         }
1273                 }
1274                 for _, shlib := range ctxt.Shlibs {
1275                         addshlib(shlib.Path)
1276                         for _, dep := range shlib.Deps {
1277                                 if dep == "" {
1278                                         continue
1279                                 }
1280                                 libpath := findshlib(ctxt, dep)
1281                                 if libpath != "" {
1282                                         addshlib(libpath)
1283                                 }
1284                         }
1285                 }
1286         }
1287
1288         // clang, unlike GCC, passes -rdynamic to the linker
1289         // even when linking with -static, causing a linker
1290         // error when using GNU ld. So take out -rdynamic if
1291         // we added it. We do it in this order, rather than
1292         // only adding -rdynamic later, so that -*extldflags
1293         // can override -rdynamic without using -static.
1294         checkStatic := func(arg string) {
1295                 if ctxt.IsELF && arg == "-static" {
1296                         for i := range argv {
1297                                 if argv[i] == "-rdynamic" {
1298                                         argv[i] = "-static"
1299                                 }
1300                         }
1301                 }
1302         }
1303
1304         for _, p := range ldflag {
1305                 argv = append(argv, p)
1306                 checkStatic(p)
1307         }
1308
1309         // When building a program with the default -buildmode=exe the
1310         // gc compiler generates code requires DT_TEXTREL in a
1311         // position independent executable (PIE). On systems where the
1312         // toolchain creates PIEs by default, and where DT_TEXTREL
1313         // does not work, the resulting programs will not run. See
1314         // issue #17847. To avoid this problem pass -no-pie to the
1315         // toolchain if it is supported.
1316         if ctxt.BuildMode == BuildModeExe && !ctxt.linkShared {
1317                 // GCC uses -no-pie, clang uses -nopie.
1318                 for _, nopie := range []string{"-no-pie", "-nopie"} {
1319                         if linkerFlagSupported(argv[0], nopie) {
1320                                 argv = append(argv, nopie)
1321                                 break
1322                         }
1323                 }
1324         }
1325
1326         for _, p := range strings.Fields(*flagExtldflags) {
1327                 argv = append(argv, p)
1328                 checkStatic(p)
1329         }
1330         if ctxt.HeadType == objabi.Hwindows {
1331                 // use gcc linker script to work around gcc bug
1332                 // (see https://golang.org/issue/20183 for details).
1333                 p := writeGDBLinkerScript()
1334                 argv = append(argv, "-Wl,-T,"+p)
1335                 // libmingw32 and libmingwex have some inter-dependencies,
1336                 // so must use linker groups.
1337                 argv = append(argv, "-Wl,--start-group", "-lmingwex", "-lmingw32", "-Wl,--end-group")
1338                 argv = append(argv, peimporteddlls()...)
1339         }
1340
1341         if ctxt.Debugvlog != 0 {
1342                 ctxt.Logf("%5.2f host link:", Cputime())
1343                 for _, v := range argv {
1344                         ctxt.Logf(" %q", v)
1345                 }
1346                 ctxt.Logf("\n")
1347         }
1348
1349         out, err := exec.Command(argv[0], argv[1:]...).CombinedOutput()
1350         if err != nil {
1351                 Exitf("running %s failed: %v\n%s", argv[0], err, out)
1352         }
1353
1354         // Filter out useless linker warnings caused by bugs outside Go.
1355         // See also cmd/go/internal/work/exec.go's gccld method.
1356         var save [][]byte
1357         for _, line := range bytes.SplitAfter(out, []byte("\n")) {
1358                 // golang.org/issue/26073 - Apple Xcode bug
1359                 if bytes.Contains(line, []byte("ld: warning: text-based stub file")) {
1360                         continue
1361                 }
1362                 save = append(save, line)
1363         }
1364         out = bytes.Join(save, nil)
1365
1366         if len(out) > 0 {
1367                 // always print external output even if the command is successful, so that we don't
1368                 // swallow linker warnings (see https://golang.org/issue/17935).
1369                 ctxt.Logf("%s", out)
1370         }
1371
1372         if !*FlagS && !*FlagW && !debug_s && ctxt.HeadType == objabi.Hdarwin {
1373                 dsym := filepath.Join(*flagTmpdir, "go.dwarf")
1374                 if out, err := exec.Command("dsymutil", "-f", *flagOutfile, "-o", dsym).CombinedOutput(); err != nil {
1375                         Exitf("%s: running dsymutil failed: %v\n%s", os.Args[0], err, out)
1376                 }
1377                 // Skip combining if `dsymutil` didn't generate a file. See #11994.
1378                 if _, err := os.Stat(dsym); os.IsNotExist(err) {
1379                         return
1380                 }
1381                 // For os.Rename to work reliably, must be in same directory as outfile.
1382                 combinedOutput := *flagOutfile + "~"
1383                 isIOS, err := machoCombineDwarf(ctxt, *flagOutfile, dsym, combinedOutput)
1384                 if err != nil {
1385                         Exitf("%s: combining dwarf failed: %v", os.Args[0], err)
1386                 }
1387                 if !isIOS {
1388                         os.Remove(*flagOutfile)
1389                         if err := os.Rename(combinedOutput, *flagOutfile); err != nil {
1390                                 Exitf("%s: %v", os.Args[0], err)
1391                         }
1392                 }
1393         }
1394 }
1395
1396 var createTrivialCOnce sync.Once
1397
1398 func linkerFlagSupported(linker, flag string) bool {
1399         createTrivialCOnce.Do(func() {
1400                 src := filepath.Join(*flagTmpdir, "trivial.c")
1401                 if err := ioutil.WriteFile(src, []byte("int main() { return 0; }"), 0666); err != nil {
1402                         Errorf(nil, "WriteFile trivial.c failed: %v", err)
1403                 }
1404         })
1405
1406         flagsWithNextArgSkip := []string{
1407                 "-F",
1408                 "-l",
1409                 "-L",
1410                 "-framework",
1411                 "-Wl,-framework",
1412                 "-Wl,-rpath",
1413                 "-Wl,-undefined",
1414         }
1415         flagsWithNextArgKeep := []string{
1416                 "-arch",
1417                 "-isysroot",
1418                 "--sysroot",
1419                 "-target",
1420         }
1421         prefixesToKeep := []string{
1422                 "-f",
1423                 "-m",
1424                 "-p",
1425                 "-Wl,",
1426                 "-arch",
1427                 "-isysroot",
1428                 "--sysroot",
1429                 "-target",
1430         }
1431
1432         var flags []string
1433         keep := false
1434         skip := false
1435         extldflags := strings.Fields(*flagExtldflags)
1436         for _, f := range append(extldflags, ldflag...) {
1437                 if keep {
1438                         flags = append(flags, f)
1439                         keep = false
1440                 } else if skip {
1441                         skip = false
1442                 } else if f == "" || f[0] != '-' {
1443                 } else if contains(flagsWithNextArgSkip, f) {
1444                         skip = true
1445                 } else if contains(flagsWithNextArgKeep, f) {
1446                         flags = append(flags, f)
1447                         keep = true
1448                 } else {
1449                         for _, p := range prefixesToKeep {
1450                                 if strings.HasPrefix(f, p) {
1451                                         flags = append(flags, f)
1452                                         break
1453                                 }
1454                         }
1455                 }
1456         }
1457
1458         flags = append(flags, flag, "trivial.c")
1459
1460         cmd := exec.Command(linker, flags...)
1461         cmd.Dir = *flagTmpdir
1462         cmd.Env = append([]string{"LC_ALL=C"}, os.Environ()...)
1463         out, err := cmd.CombinedOutput()
1464         // GCC says "unrecognized command line option ‘-no-pie’"
1465         // clang says "unknown argument: '-no-pie'"
1466         return err == nil && !bytes.Contains(out, []byte("unrecognized")) && !bytes.Contains(out, []byte("unknown"))
1467 }
1468
1469 // hostlinkArchArgs returns arguments to pass to the external linker
1470 // based on the architecture.
1471 func hostlinkArchArgs(arch *sys.Arch) []string {
1472         switch arch.Family {
1473         case sys.I386:
1474                 return []string{"-m32"}
1475         case sys.AMD64, sys.PPC64, sys.S390X:
1476                 return []string{"-m64"}
1477         case sys.ARM:
1478                 return []string{"-marm"}
1479         case sys.ARM64:
1480                 // nothing needed
1481         case sys.MIPS64:
1482                 return []string{"-mabi=64"}
1483         case sys.MIPS:
1484                 return []string{"-mabi=32"}
1485         }
1486         return nil
1487 }
1488
1489 // ldobj loads an input object. If it is a host object (an object
1490 // compiled by a non-Go compiler) it returns the Hostobj pointer. If
1491 // it is a Go object, it returns nil.
1492 func ldobj(ctxt *Link, f *bio.Reader, lib *sym.Library, length int64, pn string, file string) *Hostobj {
1493         pkg := objabi.PathToPrefix(lib.Pkg)
1494
1495         eof := f.Offset() + length
1496         start := f.Offset()
1497         c1 := bgetc(f)
1498         c2 := bgetc(f)
1499         c3 := bgetc(f)
1500         c4 := bgetc(f)
1501         f.Seek(start, 0)
1502
1503         magic := uint32(c1)<<24 | uint32(c2)<<16 | uint32(c3)<<8 | uint32(c4)
1504         if magic == 0x7f454c46 { // \x7F E L F
1505                 ldelf := func(ctxt *Link, f *bio.Reader, pkg string, length int64, pn string) {
1506                         textp, flags, err := loadelf.Load(ctxt.Arch, ctxt.Syms, f, pkg, length, pn, ehdr.flags)
1507                         if err != nil {
1508                                 Errorf(nil, "%v", err)
1509                                 return
1510                         }
1511                         ehdr.flags = flags
1512                         ctxt.Textp = append(ctxt.Textp, textp...)
1513                 }
1514                 return ldhostobj(ldelf, ctxt.HeadType, f, pkg, length, pn, file)
1515         }
1516
1517         if magic&^1 == 0xfeedface || magic&^0x01000000 == 0xcefaedfe {
1518                 ldmacho := func(ctxt *Link, f *bio.Reader, pkg string, length int64, pn string) {
1519                         textp, err := loadmacho.Load(ctxt.Arch, ctxt.Syms, f, pkg, length, pn)
1520                         if err != nil {
1521                                 Errorf(nil, "%v", err)
1522                                 return
1523                         }
1524                         ctxt.Textp = append(ctxt.Textp, textp...)
1525                 }
1526                 return ldhostobj(ldmacho, ctxt.HeadType, f, pkg, length, pn, file)
1527         }
1528
1529         if c1 == 0x4c && c2 == 0x01 || c1 == 0x64 && c2 == 0x86 {
1530                 ldpe := func(ctxt *Link, f *bio.Reader, pkg string, length int64, pn string) {
1531                         textp, rsrc, err := loadpe.Load(ctxt.Arch, ctxt.Syms, f, pkg, length, pn)
1532                         if err != nil {
1533                                 Errorf(nil, "%v", err)
1534                                 return
1535                         }
1536                         if rsrc != nil {
1537                                 setpersrc(ctxt, rsrc)
1538                         }
1539                         ctxt.Textp = append(ctxt.Textp, textp...)
1540                 }
1541                 return ldhostobj(ldpe, ctxt.HeadType, f, pkg, length, pn, file)
1542         }
1543
1544         if c1 == 0x01 && (c2 == 0xD7 || c2 == 0xF7) {
1545                 ldxcoff := func(ctxt *Link, f *bio.Reader, pkg string, length int64, pn string) {
1546                         textp, err := loadxcoff.Load(ctxt.Arch, ctxt.Syms, f, pkg, length, pn)
1547                         if err != nil {
1548                                 Errorf(nil, "%v", err)
1549                                 return
1550                         }
1551                         ctxt.Textp = append(ctxt.Textp, textp...)
1552                 }
1553                 return ldhostobj(ldxcoff, ctxt.HeadType, f, pkg, length, pn, file)
1554         }
1555
1556         /* check the header */
1557         line, err := f.ReadString('\n')
1558         if err != nil {
1559                 Errorf(nil, "truncated object file: %s: %v", pn, err)
1560                 return nil
1561         }
1562
1563         if !strings.HasPrefix(line, "go object ") {
1564                 if strings.HasSuffix(pn, ".go") {
1565                         Exitf("%s: uncompiled .go source file", pn)
1566                         return nil
1567                 }
1568
1569                 if line == ctxt.Arch.Name {
1570                         // old header format: just $GOOS
1571                         Errorf(nil, "%s: stale object file", pn)
1572                         return nil
1573                 }
1574
1575                 Errorf(nil, "%s: not an object file", pn)
1576                 return nil
1577         }
1578
1579         // First, check that the basic GOOS, GOARCH, and Version match.
1580         t := fmt.Sprintf("%s %s %s ", objabi.GOOS, objabi.GOARCH, objabi.Version)
1581
1582         line = strings.TrimRight(line, "\n")
1583         if !strings.HasPrefix(line[10:]+" ", t) && !*flagF {
1584                 Errorf(nil, "%s: object is [%s] expected [%s]", pn, line[10:], t)
1585                 return nil
1586         }
1587
1588         // Second, check that longer lines match each other exactly,
1589         // so that the Go compiler and write additional information
1590         // that must be the same from run to run.
1591         if len(line) >= len(t)+10 {
1592                 if theline == "" {
1593                         theline = line[10:]
1594                 } else if theline != line[10:] {
1595                         Errorf(nil, "%s: object is [%s] expected [%s]", pn, line[10:], theline)
1596                         return nil
1597                 }
1598         }
1599
1600         // Skip over exports and other info -- ends with \n!\n.
1601         //
1602         // Note: It's possible for "\n!\n" to appear within the binary
1603         // package export data format. To avoid truncating the package
1604         // definition prematurely (issue 21703), we keep track of
1605         // how many "$$" delimiters we've seen.
1606
1607         import0 := f.Offset()
1608
1609         c1 = '\n' // the last line ended in \n
1610         c2 = bgetc(f)
1611         c3 = bgetc(f)
1612         markers := 0
1613         for {
1614                 if c1 == '\n' {
1615                         if markers%2 == 0 && c2 == '!' && c3 == '\n' {
1616                                 break
1617                         }
1618                         if c2 == '$' && c3 == '$' {
1619                                 markers++
1620                         }
1621                 }
1622
1623                 c1 = c2
1624                 c2 = c3
1625                 c3 = bgetc(f)
1626                 if c3 == -1 {
1627                         Errorf(nil, "truncated object file: %s", pn)
1628                         return nil
1629                 }
1630         }
1631
1632         import1 := f.Offset()
1633
1634         f.Seek(import0, 0)
1635         ldpkg(ctxt, f, lib, import1-import0-2, pn) // -2 for !\n
1636         f.Seek(import1, 0)
1637
1638         objfile.Load(ctxt.Arch, ctxt.Syms, f, lib, eof-f.Offset(), pn)
1639         addImports(ctxt, lib, pn)
1640         return nil
1641 }
1642
1643 func readelfsymboldata(ctxt *Link, f *elf.File, sym *elf.Symbol) []byte {
1644         data := make([]byte, sym.Size)
1645         sect := f.Sections[sym.Section]
1646         if sect.Type != elf.SHT_PROGBITS && sect.Type != elf.SHT_NOTE {
1647                 Errorf(nil, "reading %s from non-data section", sym.Name)
1648         }
1649         n, err := sect.ReadAt(data, int64(sym.Value-sect.Addr))
1650         if uint64(n) != sym.Size {
1651                 Errorf(nil, "reading contents of %s: %v", sym.Name, err)
1652         }
1653         return data
1654 }
1655
1656 func readwithpad(r io.Reader, sz int32) ([]byte, error) {
1657         data := make([]byte, Rnd(int64(sz), 4))
1658         _, err := io.ReadFull(r, data)
1659         if err != nil {
1660                 return nil, err
1661         }
1662         data = data[:sz]
1663         return data, nil
1664 }
1665
1666 func readnote(f *elf.File, name []byte, typ int32) ([]byte, error) {
1667         for _, sect := range f.Sections {
1668                 if sect.Type != elf.SHT_NOTE {
1669                         continue
1670                 }
1671                 r := sect.Open()
1672                 for {
1673                         var namesize, descsize, noteType int32
1674                         err := binary.Read(r, f.ByteOrder, &namesize)
1675                         if err != nil {
1676                                 if err == io.EOF {
1677                                         break
1678                                 }
1679                                 return nil, fmt.Errorf("read namesize failed: %v", err)
1680                         }
1681                         err = binary.Read(r, f.ByteOrder, &descsize)
1682                         if err != nil {
1683                                 return nil, fmt.Errorf("read descsize failed: %v", err)
1684                         }
1685                         err = binary.Read(r, f.ByteOrder, &noteType)
1686                         if err != nil {
1687                                 return nil, fmt.Errorf("read type failed: %v", err)
1688                         }
1689                         noteName, err := readwithpad(r, namesize)
1690                         if err != nil {
1691                                 return nil, fmt.Errorf("read name failed: %v", err)
1692                         }
1693                         desc, err := readwithpad(r, descsize)
1694                         if err != nil {
1695                                 return nil, fmt.Errorf("read desc failed: %v", err)
1696                         }
1697                         if string(name) == string(noteName) && typ == noteType {
1698                                 return desc, nil
1699                         }
1700                 }
1701         }
1702         return nil, nil
1703 }
1704
1705 func findshlib(ctxt *Link, shlib string) string {
1706         if filepath.IsAbs(shlib) {
1707                 return shlib
1708         }
1709         for _, libdir := range ctxt.Libdir {
1710                 libpath := filepath.Join(libdir, shlib)
1711                 if _, err := os.Stat(libpath); err == nil {
1712                         return libpath
1713                 }
1714         }
1715         Errorf(nil, "cannot find shared library: %s", shlib)
1716         return ""
1717 }
1718
1719 func ldshlibsyms(ctxt *Link, shlib string) {
1720         var libpath string
1721         if filepath.IsAbs(shlib) {
1722                 libpath = shlib
1723                 shlib = filepath.Base(shlib)
1724         } else {
1725                 libpath = findshlib(ctxt, shlib)
1726                 if libpath == "" {
1727                         return
1728                 }
1729         }
1730         for _, processedlib := range ctxt.Shlibs {
1731                 if processedlib.Path == libpath {
1732                         return
1733                 }
1734         }
1735         if ctxt.Debugvlog > 1 {
1736                 ctxt.Logf("%5.2f ldshlibsyms: found library with name %s at %s\n", Cputime(), shlib, libpath)
1737         }
1738
1739         f, err := elf.Open(libpath)
1740         if err != nil {
1741                 Errorf(nil, "cannot open shared library: %s", libpath)
1742                 return
1743         }
1744         defer f.Close()
1745
1746         hash, err := readnote(f, ELF_NOTE_GO_NAME, ELF_NOTE_GOABIHASH_TAG)
1747         if err != nil {
1748                 Errorf(nil, "cannot read ABI hash from shared library %s: %v", libpath, err)
1749                 return
1750         }
1751
1752         depsbytes, err := readnote(f, ELF_NOTE_GO_NAME, ELF_NOTE_GODEPS_TAG)
1753         if err != nil {
1754                 Errorf(nil, "cannot read dep list from shared library %s: %v", libpath, err)
1755                 return
1756         }
1757         var deps []string
1758         for _, dep := range strings.Split(string(depsbytes), "\n") {
1759                 if dep == "" {
1760                         continue
1761                 }
1762                 if !filepath.IsAbs(dep) {
1763                         // If the dep can be interpreted as a path relative to the shlib
1764                         // in which it was found, do that. Otherwise, we will leave it
1765                         // to be resolved by libdir lookup.
1766                         abs := filepath.Join(filepath.Dir(libpath), dep)
1767                         if _, err := os.Stat(abs); err == nil {
1768                                 dep = abs
1769                         }
1770                 }
1771                 deps = append(deps, dep)
1772         }
1773
1774         syms, err := f.DynamicSymbols()
1775         if err != nil {
1776                 Errorf(nil, "cannot read symbols from shared library: %s", libpath)
1777                 return
1778         }
1779         gcdataLocations := make(map[uint64]*sym.Symbol)
1780         for _, elfsym := range syms {
1781                 if elf.ST_TYPE(elfsym.Info) == elf.STT_NOTYPE || elf.ST_TYPE(elfsym.Info) == elf.STT_SECTION {
1782                         continue
1783                 }
1784                 lsym := ctxt.Syms.Lookup(elfsym.Name, 0)
1785                 // Because loadlib above loads all .a files before loading any shared
1786                 // libraries, any non-dynimport symbols we find that duplicate symbols
1787                 // already loaded should be ignored (the symbols from the .a files
1788                 // "win").
1789                 if lsym.Type != 0 && lsym.Type != sym.SDYNIMPORT {
1790                         continue
1791                 }
1792                 lsym.Type = sym.SDYNIMPORT
1793                 lsym.SetElfType(elf.ST_TYPE(elfsym.Info))
1794                 lsym.Size = int64(elfsym.Size)
1795                 if elfsym.Section != elf.SHN_UNDEF {
1796                         // Set .File for the library that actually defines the symbol.
1797                         lsym.File = libpath
1798                         // The decodetype_* functions in decodetype.go need access to
1799                         // the type data.
1800                         if strings.HasPrefix(lsym.Name, "type.") && !strings.HasPrefix(lsym.Name, "type..") {
1801                                 lsym.P = readelfsymboldata(ctxt, f, &elfsym)
1802                                 gcdataLocations[elfsym.Value+2*uint64(ctxt.Arch.PtrSize)+8+1*uint64(ctxt.Arch.PtrSize)] = lsym
1803                         }
1804                 }
1805         }
1806         gcdataAddresses := make(map[*sym.Symbol]uint64)
1807         if ctxt.Arch.Family == sys.ARM64 {
1808                 for _, sect := range f.Sections {
1809                         if sect.Type == elf.SHT_RELA {
1810                                 var rela elf.Rela64
1811                                 rdr := sect.Open()
1812                                 for {
1813                                         err := binary.Read(rdr, f.ByteOrder, &rela)
1814                                         if err == io.EOF {
1815                                                 break
1816                                         } else if err != nil {
1817                                                 Errorf(nil, "reading relocation failed %v", err)
1818                                                 return
1819                                         }
1820                                         t := elf.R_AARCH64(rela.Info & 0xffff)
1821                                         if t != elf.R_AARCH64_RELATIVE {
1822                                                 continue
1823                                         }
1824                                         if lsym, ok := gcdataLocations[rela.Off]; ok {
1825                                                 gcdataAddresses[lsym] = uint64(rela.Addend)
1826                                         }
1827                                 }
1828                         }
1829                 }
1830         }
1831
1832         ctxt.Shlibs = append(ctxt.Shlibs, Shlib{Path: libpath, Hash: hash, Deps: deps, File: f, gcdataAddresses: gcdataAddresses})
1833 }
1834
1835 func addsection(arch *sys.Arch, seg *sym.Segment, name string, rwx int) *sym.Section {
1836         sect := new(sym.Section)
1837         sect.Rwx = uint8(rwx)
1838         sect.Name = name
1839         sect.Seg = seg
1840         sect.Align = int32(arch.PtrSize) // everything is at least pointer-aligned
1841         seg.Sections = append(seg.Sections, sect)
1842         return sect
1843 }
1844
1845 type chain struct {
1846         sym   *sym.Symbol
1847         up    *chain
1848         limit int // limit on entry to sym
1849 }
1850
1851 var morestack *sym.Symbol
1852
1853 // TODO: Record enough information in new object files to
1854 // allow stack checks here.
1855
1856 func haslinkregister(ctxt *Link) bool {
1857         return ctxt.FixedFrameSize() != 0
1858 }
1859
1860 func callsize(ctxt *Link) int {
1861         if haslinkregister(ctxt) {
1862                 return 0
1863         }
1864         return ctxt.Arch.RegSize
1865 }
1866
1867 func (ctxt *Link) dostkcheck() {
1868         var ch chain
1869
1870         morestack = ctxt.Syms.Lookup("runtime.morestack", 0)
1871
1872         // Every splitting function ensures that there are at least StackLimit
1873         // bytes available below SP when the splitting prologue finishes.
1874         // If the splitting function calls F, then F begins execution with
1875         // at least StackLimit - callsize() bytes available.
1876         // Check that every function behaves correctly with this amount
1877         // of stack, following direct calls in order to piece together chains
1878         // of non-splitting functions.
1879         ch.up = nil
1880
1881         ch.limit = objabi.StackLimit - callsize(ctxt)
1882         if objabi.GOARCH == "arm64" {
1883                 // need extra 8 bytes below SP to save FP
1884                 ch.limit -= 8
1885         }
1886
1887         // Check every function, but do the nosplit functions in a first pass,
1888         // to make the printed failure chains as short as possible.
1889         for _, s := range ctxt.Textp {
1890                 // runtime.racesymbolizethunk is called from gcc-compiled C
1891                 // code running on the operating system thread stack.
1892                 // It uses more than the usual amount of stack but that's okay.
1893                 if s.Name == "runtime.racesymbolizethunk" {
1894                         continue
1895                 }
1896
1897                 if s.Attr.NoSplit() {
1898                         ch.sym = s
1899                         stkcheck(ctxt, &ch, 0)
1900                 }
1901         }
1902
1903         for _, s := range ctxt.Textp {
1904                 if !s.Attr.NoSplit() {
1905                         ch.sym = s
1906                         stkcheck(ctxt, &ch, 0)
1907                 }
1908         }
1909 }
1910
1911 func stkcheck(ctxt *Link, up *chain, depth int) int {
1912         limit := up.limit
1913         s := up.sym
1914
1915         // Don't duplicate work: only need to consider each
1916         // function at top of safe zone once.
1917         top := limit == objabi.StackLimit-callsize(ctxt)
1918         if top {
1919                 if s.Attr.StackCheck() {
1920                         return 0
1921                 }
1922                 s.Attr |= sym.AttrStackCheck
1923         }
1924
1925         if depth > 100 {
1926                 Errorf(s, "nosplit stack check too deep")
1927                 stkbroke(ctxt, up, 0)
1928                 return -1
1929         }
1930
1931         if s.Attr.External() || s.FuncInfo == nil {
1932                 // external function.
1933                 // should never be called directly.
1934                 // onlyctxt.Diagnose the direct caller.
1935                 // TODO(mwhudson): actually think about this.
1936                 // TODO(khr): disabled for now. Calls to external functions can only happen on the g0 stack.
1937                 // See the trampolines in src/runtime/sys_darwin_$ARCH.go.
1938                 if depth == 1 && s.Type != sym.SXREF && !ctxt.DynlinkingGo() &&
1939                         ctxt.BuildMode != BuildModeCArchive && ctxt.BuildMode != BuildModePIE && ctxt.BuildMode != BuildModeCShared && ctxt.BuildMode != BuildModePlugin {
1940                         //Errorf(s, "call to external function")
1941                 }
1942                 return -1
1943         }
1944
1945         if limit < 0 {
1946                 stkbroke(ctxt, up, limit)
1947                 return -1
1948         }
1949
1950         // morestack looks like it calls functions,
1951         // but it switches the stack pointer first.
1952         if s == morestack {
1953                 return 0
1954         }
1955
1956         var ch chain
1957         ch.up = up
1958
1959         if !s.Attr.NoSplit() {
1960                 // Ensure we have enough stack to call morestack.
1961                 ch.limit = limit - callsize(ctxt)
1962                 ch.sym = morestack
1963                 if stkcheck(ctxt, &ch, depth+1) < 0 {
1964                         return -1
1965                 }
1966                 if !top {
1967                         return 0
1968                 }
1969                 // Raise limit to allow frame.
1970                 locals := int32(0)
1971                 if s.FuncInfo != nil {
1972                         locals = s.FuncInfo.Locals
1973                 }
1974                 limit = int(objabi.StackLimit+locals) + int(ctxt.FixedFrameSize())
1975         }
1976
1977         // Walk through sp adjustments in function, consuming relocs.
1978         ri := 0
1979
1980         endr := len(s.R)
1981         var ch1 chain
1982         var pcsp Pciter
1983         var r *sym.Reloc
1984         for pciterinit(ctxt, &pcsp, &s.FuncInfo.Pcsp); pcsp.done == 0; pciternext(&pcsp) {
1985                 // pcsp.value is in effect for [pcsp.pc, pcsp.nextpc).
1986
1987                 // Check stack size in effect for this span.
1988                 if int32(limit)-pcsp.value < 0 {
1989                         stkbroke(ctxt, up, int(int32(limit)-pcsp.value))
1990                         return -1
1991                 }
1992
1993                 // Process calls in this span.
1994                 for ; ri < endr && uint32(s.R[ri].Off) < pcsp.nextpc; ri++ {
1995                         r = &s.R[ri]
1996                         switch r.Type {
1997                         // Direct call.
1998                         case objabi.R_CALL, objabi.R_CALLARM, objabi.R_CALLARM64, objabi.R_CALLPOWER, objabi.R_CALLMIPS:
1999                                 ch.limit = int(int32(limit) - pcsp.value - int32(callsize(ctxt)))
2000                                 ch.sym = r.Sym
2001                                 if stkcheck(ctxt, &ch, depth+1) < 0 {
2002                                         return -1
2003                                 }
2004
2005                         // Indirect call. Assume it is a call to a splitting function,
2006                         // so we have to make sure it can call morestack.
2007                         // Arrange the data structures to report both calls, so that
2008                         // if there is an error, stkprint shows all the steps involved.
2009                         case objabi.R_CALLIND:
2010                                 ch.limit = int(int32(limit) - pcsp.value - int32(callsize(ctxt)))
2011
2012                                 ch.sym = nil
2013                                 ch1.limit = ch.limit - callsize(ctxt) // for morestack in called prologue
2014                                 ch1.up = &ch
2015                                 ch1.sym = morestack
2016                                 if stkcheck(ctxt, &ch1, depth+2) < 0 {
2017                                         return -1
2018                                 }
2019                         }
2020                 }
2021         }
2022
2023         return 0
2024 }
2025
2026 func stkbroke(ctxt *Link, ch *chain, limit int) {
2027         Errorf(ch.sym, "nosplit stack overflow")
2028         stkprint(ctxt, ch, limit)
2029 }
2030
2031 func stkprint(ctxt *Link, ch *chain, limit int) {
2032         var name string
2033
2034         if ch.sym != nil {
2035                 name = ch.sym.Name
2036                 if ch.sym.Attr.NoSplit() {
2037                         name += " (nosplit)"
2038                 }
2039         } else {
2040                 name = "function pointer"
2041         }
2042
2043         if ch.up == nil {
2044                 // top of chain.  ch->sym != nil.
2045                 if ch.sym.Attr.NoSplit() {
2046                         fmt.Printf("\t%d\tassumed on entry to %s\n", ch.limit, name)
2047                 } else {
2048                         fmt.Printf("\t%d\tguaranteed after split check in %s\n", ch.limit, name)
2049                 }
2050         } else {
2051                 stkprint(ctxt, ch.up, ch.limit+callsize(ctxt))
2052                 if !haslinkregister(ctxt) {
2053                         fmt.Printf("\t%d\ton entry to %s\n", ch.limit, name)
2054                 }
2055         }
2056
2057         if ch.limit != limit {
2058                 fmt.Printf("\t%d\tafter %s uses %d\n", limit, name, ch.limit-limit)
2059         }
2060 }
2061
2062 func usage() {
2063         fmt.Fprintf(os.Stderr, "usage: link [options] main.o\n")
2064         objabi.Flagprint(os.Stderr)
2065         Exit(2)
2066 }
2067
2068 type SymbolType int8
2069
2070 const (
2071         // see also https://9p.io/magic/man2html/1/nm
2072         TextSym      SymbolType = 'T'
2073         DataSym      SymbolType = 'D'
2074         BSSSym       SymbolType = 'B'
2075         UndefinedSym SymbolType = 'U'
2076         TLSSym       SymbolType = 't'
2077         FrameSym     SymbolType = 'm'
2078         ParamSym     SymbolType = 'p'
2079         AutoSym      SymbolType = 'a'
2080
2081         // Deleted auto (not a real sym, just placeholder for type)
2082         DeletedAutoSym = 'x'
2083 )
2084
2085 func genasmsym(ctxt *Link, put func(*Link, *sym.Symbol, string, SymbolType, int64, *sym.Symbol)) {
2086         // These symbols won't show up in the first loop below because we
2087         // skip sym.STEXT symbols. Normal sym.STEXT symbols are emitted by walking textp.
2088         s := ctxt.Syms.Lookup("runtime.text", 0)
2089         if s.Type == sym.STEXT {
2090                 // We've already included this symbol in ctxt.Textp
2091                 // if ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin.
2092                 // See data.go:/textaddress
2093                 if !(ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin) {
2094                         put(ctxt, s, s.Name, TextSym, s.Value, nil)
2095                 }
2096         }
2097
2098         n := 0
2099
2100         // Generate base addresses for all text sections if there are multiple
2101         for _, sect := range Segtext.Sections {
2102                 if n == 0 {
2103                         n++
2104                         continue
2105                 }
2106                 if sect.Name != ".text" {
2107                         break
2108                 }
2109                 s = ctxt.Syms.ROLookup(fmt.Sprintf("runtime.text.%d", n), 0)
2110                 if s == nil {
2111                         break
2112                 }
2113                 if s.Type == sym.STEXT {
2114                         put(ctxt, s, s.Name, TextSym, s.Value, nil)
2115                 }
2116                 n++
2117         }
2118
2119         s = ctxt.Syms.Lookup("runtime.etext", 0)
2120         if s.Type == sym.STEXT {
2121                 // We've already included this symbol in ctxt.Textp
2122                 // if ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin.
2123                 // See data.go:/textaddress
2124                 if !(ctxt.DynlinkingGo() && ctxt.HeadType == objabi.Hdarwin) {
2125                         put(ctxt, s, s.Name, TextSym, s.Value, nil)
2126                 }
2127         }
2128
2129         for _, s := range ctxt.Syms.Allsym {
2130                 if s.Attr.NotInSymbolTable() {
2131                         continue
2132                 }
2133                 if (s.Name == "" || s.Name[0] == '.') && s.Version == 0 && s.Name != ".rathole" && s.Name != ".TOC." {
2134                         continue
2135                 }
2136                 switch s.Type {
2137                 case sym.SCONST,
2138                         sym.SRODATA,
2139                         sym.SSYMTAB,
2140                         sym.SPCLNTAB,
2141                         sym.SINITARR,
2142                         sym.SDATA,
2143                         sym.SNOPTRDATA,
2144                         sym.SELFROSECT,
2145                         sym.SMACHOGOT,
2146                         sym.STYPE,
2147                         sym.SSTRING,
2148                         sym.SGOSTRING,
2149                         sym.SGOFUNC,
2150                         sym.SGCBITS,
2151                         sym.STYPERELRO,
2152                         sym.SSTRINGRELRO,
2153                         sym.SGOSTRINGRELRO,
2154                         sym.SGOFUNCRELRO,
2155                         sym.SGCBITSRELRO,
2156                         sym.SRODATARELRO,
2157                         sym.STYPELINK,
2158                         sym.SITABLINK,
2159                         sym.SWINDOWS:
2160                         if !s.Attr.Reachable() {
2161                                 continue
2162                         }
2163                         put(ctxt, s, s.Name, DataSym, Symaddr(s), s.Gotype)
2164
2165                 case sym.SBSS, sym.SNOPTRBSS:
2166                         if !s.Attr.Reachable() {
2167                                 continue
2168                         }
2169                         if len(s.P) > 0 {
2170                                 Errorf(s, "should not be bss (size=%d type=%v special=%v)", len(s.P), s.Type, s.Attr.Special())
2171                         }
2172                         put(ctxt, s, s.Name, BSSSym, Symaddr(s), s.Gotype)
2173
2174                 case sym.SHOSTOBJ:
2175                         if ctxt.HeadType == objabi.Hwindows || ctxt.IsELF {
2176                                 put(ctxt, s, s.Name, UndefinedSym, s.Value, nil)
2177                         }
2178
2179                 case sym.SDYNIMPORT:
2180                         if !s.Attr.Reachable() {
2181                                 continue
2182                         }
2183                         put(ctxt, s, s.Extname(), UndefinedSym, 0, nil)
2184
2185                 case sym.STLSBSS:
2186                         if ctxt.LinkMode == LinkExternal {
2187                                 put(ctxt, s, s.Name, TLSSym, Symaddr(s), s.Gotype)
2188                         }
2189                 }
2190         }
2191
2192         var off int32
2193         for _, s := range ctxt.Textp {
2194                 put(ctxt, s, s.Name, TextSym, s.Value, s.Gotype)
2195
2196                 locals := int32(0)
2197                 if s.FuncInfo != nil {
2198                         locals = s.FuncInfo.Locals
2199                 }
2200                 // NOTE(ality): acid can't produce a stack trace without .frame symbols
2201                 put(ctxt, nil, ".frame", FrameSym, int64(locals)+int64(ctxt.Arch.PtrSize), nil)
2202
2203                 if s.FuncInfo == nil {
2204                         continue
2205                 }
2206                 for _, a := range s.FuncInfo.Autom {
2207                         if a.Name == objabi.A_DELETED_AUTO {
2208                                 put(ctxt, nil, "", DeletedAutoSym, 0, a.Gotype)
2209                                 continue
2210                         }
2211
2212                         // Emit a or p according to actual offset, even if label is wrong.
2213                         // This avoids negative offsets, which cannot be encoded.
2214                         if a.Name != objabi.A_AUTO && a.Name != objabi.A_PARAM {
2215                                 continue
2216                         }
2217
2218                         // compute offset relative to FP
2219                         if a.Name == objabi.A_PARAM {
2220                                 off = a.Aoffset
2221                         } else {
2222                                 off = a.Aoffset - int32(ctxt.Arch.PtrSize)
2223                         }
2224
2225                         // FP
2226                         if off >= 0 {
2227                                 put(ctxt, nil, a.Asym.Name, ParamSym, int64(off), a.Gotype)
2228                                 continue
2229                         }
2230
2231                         // SP
2232                         if off <= int32(-ctxt.Arch.PtrSize) {
2233                                 put(ctxt, nil, a.Asym.Name, AutoSym, -(int64(off) + int64(ctxt.Arch.PtrSize)), a.Gotype)
2234                                 continue
2235                         }
2236                         // Otherwise, off is addressing the saved program counter.
2237                         // Something underhanded is going on. Say nothing.
2238                 }
2239         }
2240
2241         if ctxt.Debugvlog != 0 || *flagN {
2242                 ctxt.Logf("%5.2f symsize = %d\n", Cputime(), uint32(Symsize))
2243         }
2244 }
2245
2246 func Symaddr(s *sym.Symbol) int64 {
2247         if !s.Attr.Reachable() {
2248                 Errorf(s, "unreachable symbol in symaddr")
2249         }
2250         return s.Value
2251 }
2252
2253 func (ctxt *Link) xdefine(p string, t sym.SymKind, v int64) {
2254         s := ctxt.Syms.Lookup(p, 0)
2255         s.Type = t
2256         s.Value = v
2257         s.Attr |= sym.AttrReachable
2258         s.Attr |= sym.AttrSpecial
2259         s.Attr |= sym.AttrLocal
2260 }
2261
2262 func datoff(s *sym.Symbol, addr int64) int64 {
2263         if uint64(addr) >= Segdata.Vaddr {
2264                 return int64(uint64(addr) - Segdata.Vaddr + Segdata.Fileoff)
2265         }
2266         if uint64(addr) >= Segtext.Vaddr {
2267                 return int64(uint64(addr) - Segtext.Vaddr + Segtext.Fileoff)
2268         }
2269         Errorf(s, "invalid datoff %#x", addr)
2270         return 0
2271 }
2272
2273 func Entryvalue(ctxt *Link) int64 {
2274         a := *flagEntrySymbol
2275         if a[0] >= '0' && a[0] <= '9' {
2276                 return atolwhex(a)
2277         }
2278         s := ctxt.Syms.Lookup(a, 0)
2279         if s.Type == 0 {
2280                 return *FlagTextAddr
2281         }
2282         if ctxt.HeadType != objabi.Haix && s.Type != sym.STEXT {
2283                 Errorf(s, "entry not text")
2284         }
2285         return s.Value
2286 }
2287
2288 func undefsym(ctxt *Link, s *sym.Symbol) {
2289         var r *sym.Reloc
2290
2291         for i := 0; i < len(s.R); i++ {
2292                 r = &s.R[i]
2293                 if r.Sym == nil { // happens for some external ARM relocs
2294                         continue
2295                 }
2296                 // TODO(mwhudson): the test of VisibilityHidden here probably doesn't make
2297                 // sense and should be removed when someone has thought about it properly.
2298                 if (r.Sym.Type == sym.Sxxx || r.Sym.Type == sym.SXREF) && !r.Sym.Attr.VisibilityHidden() {
2299                         Errorf(s, "undefined: %q", r.Sym.Name)
2300                 }
2301                 if !r.Sym.Attr.Reachable() && r.Type != objabi.R_WEAKADDROFF {
2302                         Errorf(s, "relocation target %q", r.Sym.Name)
2303                 }
2304         }
2305 }
2306
2307 func (ctxt *Link) undef() {
2308         // undefsym performs checks (almost) identical to checks
2309         // that report undefined relocations in relocsym.
2310         // Both undefsym and relocsym can report same symbol as undefined,
2311         // which results in error message duplication (see #10978).
2312         //
2313         // The undef is run after Arch.Asmb and could detect some
2314         // programming errors there, but if object being linked is already
2315         // failed with errors, it is better to avoid duplicated errors.
2316         if nerrors > 0 {
2317                 return
2318         }
2319
2320         for _, s := range ctxt.Textp {
2321                 undefsym(ctxt, s)
2322         }
2323         for _, s := range datap {
2324                 undefsym(ctxt, s)
2325         }
2326         if nerrors > 0 {
2327                 errorexit()
2328         }
2329 }
2330
2331 func (ctxt *Link) callgraph() {
2332         if !*FlagC {
2333                 return
2334         }
2335
2336         var i int
2337         var r *sym.Reloc
2338         for _, s := range ctxt.Textp {
2339                 for i = 0; i < len(s.R); i++ {
2340                         r = &s.R[i]
2341                         if r.Sym == nil {
2342                                 continue
2343                         }
2344                         if (r.Type == objabi.R_CALL || r.Type == objabi.R_CALLARM || r.Type == objabi.R_CALLPOWER || r.Type == objabi.R_CALLMIPS) && r.Sym.Type == sym.STEXT {
2345                                 ctxt.Logf("%s calls %s\n", s.Name, r.Sym.Name)
2346                         }
2347                 }
2348         }
2349 }
2350
2351 func Rnd(v int64, r int64) int64 {
2352         if r <= 0 {
2353                 return v
2354         }
2355         v += r - 1
2356         c := v % r
2357         if c < 0 {
2358                 c += r
2359         }
2360         v -= c
2361         return v
2362 }
2363
2364 func bgetc(r *bio.Reader) int {
2365         c, err := r.ReadByte()
2366         if err != nil {
2367                 if err != io.EOF {
2368                         log.Fatalf("reading input: %v", err)
2369                 }
2370                 return -1
2371         }
2372         return int(c)
2373 }
2374
2375 type markKind uint8 // for postorder traversal
2376 const (
2377         _ markKind = iota
2378         visiting
2379         visited
2380 )
2381
2382 func postorder(libs []*sym.Library) []*sym.Library {
2383         order := make([]*sym.Library, 0, len(libs)) // hold the result
2384         mark := make(map[*sym.Library]markKind, len(libs))
2385         for _, lib := range libs {
2386                 dfs(lib, mark, &order)
2387         }
2388         return order
2389 }
2390
2391 func dfs(lib *sym.Library, mark map[*sym.Library]markKind, order *[]*sym.Library) {
2392         if mark[lib] == visited {
2393                 return
2394         }
2395         if mark[lib] == visiting {
2396                 panic("found import cycle while visiting " + lib.Pkg)
2397         }
2398         mark[lib] = visiting
2399         for _, i := range lib.Imports {
2400                 dfs(i, mark, order)
2401         }
2402         mark[lib] = visited
2403         *order = append(*order, lib)
2404 }