1 // Inferno utils/6l/obj.c
2 // https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/obj.c
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.
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:
20 // The above copyright notice and this permission notice shall be included in
21 // all copies or substantial portions of the Software.
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
38 "cmd/link/internal/benchmark"
50 windowsgui bool // writes a "GUI binary" instead of a "console binary"
51 ownTmpDir bool // set to true if tmp dir created by linker (e.g. no -tmpdir)
55 flag.Var(&rpath, "r", "set the ELF dynamic linker search `path` to dir1:dir2:...")
58 // Flags used by the linker. The exported flags are used by the architecture-specific packages.
60 flagBuildid = flag.String("buildid", "", "record `id` as Go toolchain build id")
62 flagOutfile = flag.String("o", "", "write output to `file`")
63 flagPluginPath = flag.String("pluginpath", "", "full path name for plugin")
65 flagInstallSuffix = flag.String("installsuffix", "", "set package directory `suffix`")
66 flagDumpDep = flag.Bool("dumpdep", false, "dump symbol dependency graph")
67 flagRace = flag.Bool("race", false, "enable race detector")
68 flagMsan = flag.Bool("msan", false, "enable MSan interface")
69 flagAslr = flag.Bool("aslr", true, "enable ASLR for buildmode=c-shared on windows")
71 flagFieldTrack = flag.String("k", "", "set field tracking `symbol`")
72 flagLibGCC = flag.String("libgcc", "", "compiler support lib for internal linking; use \"none\" to disable")
73 flagTmpdir = flag.String("tmpdir", "", "use `directory` for temporary files")
75 flagExtld = flag.String("extld", "", "use `linker` when linking in external mode")
76 flagExtldflags = flag.String("extldflags", "", "pass `flags` to external linker")
77 flagExtar = flag.String("extar", "", "archive program for buildmode=c-archive")
79 flagA = flag.Bool("a", false, "no-op (deprecated)")
80 FlagC = flag.Bool("c", false, "dump call graph")
81 FlagD = flag.Bool("d", false, "disable dynamic executable")
82 flagF = flag.Bool("f", false, "ignore version mismatch")
83 flagG = flag.Bool("g", false, "disable go package data checks")
84 flagH = flag.Bool("h", false, "halt on error")
85 flagN = flag.Bool("n", false, "dump symbol table")
86 FlagS = flag.Bool("s", false, "disable symbol table")
87 FlagW = flag.Bool("w", false, "disable DWARF generation")
88 flag8 bool // use 64-bit addresses in symbol table
89 flagInterpreter = flag.String("I", "", "use `linker` as ELF dynamic linker")
90 FlagDebugTramp = flag.Int("debugtramp", 0, "debug trampolines")
91 FlagDebugTextSize = flag.Int("debugppc64textsize", 0, "debug PPC64 text section max")
92 FlagStrictDups = flag.Int("strictdups", 0, "sanity check duplicate symbol contents during object file reading (1=warn 2=err).")
93 FlagRound = flag.Int("R", -1, "set address rounding `quantum`")
94 FlagTextAddr = flag.Int64("T", -1, "set text segment `address`")
95 flagEntrySymbol = flag.String("E", "", "set `entry` symbol name")
96 cpuprofile = flag.String("cpuprofile", "", "write cpu profile to `file`")
97 memprofile = flag.String("memprofile", "", "write memory profile to `file`")
98 memprofilerate = flag.Int64("memprofilerate", 0, "set runtime.MemProfileRate to `rate`")
99 benchmarkFlag = flag.String("benchmark", "", "set to 'mem' or 'cpu' to enable phase benchmarking")
100 benchmarkFileFlag = flag.String("benchmarkprofile", "", "emit phase profiles to `base`_phase.{cpu,mem}prof")
103 // Main is the main entry point for the linker code.
104 func Main(arch *sys.Arch, theArch Arch) {
106 ctxt := linknew(arch)
107 ctxt.Bso = bufio.NewWriter(os.Stdout)
109 // For testing behavior of go command when tools crash silently.
110 // Undocumented, not in standard flag parser to avoid
111 // exposing in usage message.
112 for _, arg := range os.Args {
113 if arg == "-crash_for_testing" {
118 final := gorootFinal()
119 addstrdata1(ctxt, "runtime.defaultGOROOT="+final)
120 addstrdata1(ctxt, "cmd/internal/objabi.defaultGOROOT="+final)
122 buildVersion := buildcfg.Version
123 if goexperiment := buildcfg.GOEXPERIMENT(); goexperiment != "" {
124 buildVersion += " X:" + goexperiment
126 addstrdata1(ctxt, "runtime.buildVersion="+buildVersion)
128 // TODO(matloob): define these above and then check flag values here
129 if ctxt.Arch.Family == sys.AMD64 && buildcfg.GOOS == "plan9" {
130 flag.BoolVar(&flag8, "8", false, "use 64-bit addresses in symbol table")
132 flagHeadType := flag.String("H", "", "set header `type`")
133 flag.BoolVar(&ctxt.linkShared, "linkshared", false, "link against installed Go shared libraries")
134 flag.Var(&ctxt.LinkMode, "linkmode", "set link `mode`")
135 flag.Var(&ctxt.BuildMode, "buildmode", "set build `mode`")
136 flag.BoolVar(&ctxt.compressDWARF, "compressdwarf", true, "compress DWARF if possible")
137 objabi.Flagfn1("B", "add an ELF NT_GNU_BUILD_ID `note` when using ELF", addbuildinfo)
138 objabi.Flagfn1("L", "add specified `directory` to library path", func(a string) { Lflag(ctxt, a) })
139 objabi.AddVersionFlag() // -V
140 objabi.Flagfn1("X", "add string value `definition` of the form importpath.name=value", func(s string) { addstrdata1(ctxt, s) })
141 objabi.Flagcount("v", "print link trace", &ctxt.Debugvlog)
142 objabi.Flagfn1("importcfg", "read import configuration from `file`", ctxt.readImportCfg)
144 objabi.Flagparse(usage)
146 if ctxt.Debugvlog > 0 {
147 // dump symbol info on crash
148 defer func() { ctxt.loader.Dump() }()
151 switch *flagHeadType {
154 ctxt.HeadType = objabi.Hwindows
157 if err := ctxt.HeadType.Set(*flagHeadType); err != nil {
158 Errorf(nil, "%v", err)
162 if ctxt.HeadType == objabi.Hunknown {
163 ctxt.HeadType.Set(buildcfg.GOOS)
166 if !*flagAslr && ctxt.BuildMode != BuildModeCShared {
167 Errorf(nil, "-aslr=false is only allowed for -buildmode=c-shared")
171 checkStrictDups = *FlagStrictDups
174 if ctxt.BuildMode == BuildModeUnset {
175 ctxt.BuildMode.Set("exe")
178 if ctxt.BuildMode != BuildModeShared && flag.NArg() != 1 {
182 if *flagOutfile == "" {
183 *flagOutfile = "a.out"
184 if ctxt.HeadType == objabi.Hwindows {
185 *flagOutfile += ".exe"
189 interpreter = *flagInterpreter
191 if *flagBuildid == "" && ctxt.Target.IsOpenbsd() {
192 // TODO(jsing): Remove once direct syscalls are no longer in use.
193 // OpenBSD 6.7 onwards will not permit direct syscalls from a
194 // dynamically linked binary unless it identifies the binary
195 // contains a .note.go.buildid ELF note. See issue #36435.
196 *flagBuildid = "go-openbsd"
199 // enable benchmarking
200 var bench *benchmark.Metrics
201 if len(*benchmarkFlag) != 0 {
202 if *benchmarkFlag == "mem" {
203 bench = benchmark.New(benchmark.GC, *benchmarkFileFlag)
204 } else if *benchmarkFlag == "cpu" {
205 bench = benchmark.New(benchmark.NoGC, *benchmarkFileFlag)
207 Errorf(nil, "unknown benchmark flag: %q", *benchmarkFlag)
212 bench.Start("libinit")
213 libinit(ctxt) // creates outfile
214 bench.Start("computeTLSOffset")
215 ctxt.computeTLSOffset()
216 bench.Start("Archinit")
217 thearch.Archinit(ctxt)
219 if ctxt.linkShared && !ctxt.IsELF {
220 Exitf("-linkshared can only be used on elf systems")
223 if ctxt.Debugvlog != 0 {
224 ctxt.Logf("HEADER = -H%d -T0x%x -R0x%x\n", ctxt.HeadType, uint64(*FlagTextAddr), uint32(*FlagRound))
227 zerofp := goobj.FingerprintType{}
228 switch ctxt.BuildMode {
229 case BuildModeShared:
230 for i := 0; i < flag.NArg(); i++ {
232 parts := strings.SplitN(arg, "=", 2)
233 var pkgpath, file string
235 pkgpath, file = "main", arg
237 pkgpath, file = parts[0], parts[1]
239 pkglistfornote = append(pkglistfornote, pkgpath...)
240 pkglistfornote = append(pkglistfornote, '\n')
241 addlibpath(ctxt, "command line", "command line", file, pkgpath, "", zerofp)
243 case BuildModePlugin:
244 addlibpath(ctxt, "command line", "command line", flag.Arg(0), *flagPluginPath, "", zerofp)
246 addlibpath(ctxt, "command line", "command line", flag.Arg(0), "main", "", zerofp)
248 bench.Start("loadlib")
251 bench.Start("deadcode")
254 bench.Start("linksetup")
257 bench.Start("dostrdata")
259 if buildcfg.Experiment.FieldTrack {
260 bench.Start("fieldtrack")
261 fieldtrack(ctxt.Arch, ctxt.loader)
264 bench.Start("dwarfGenerateDebugInfo")
265 dwarfGenerateDebugInfo(ctxt)
267 bench.Start("callgraph")
270 bench.Start("dostkcheck")
273 bench.Start("mangleTypeSym")
281 bench.Start("domacho")
284 if ctxt.IsWindows() {
287 bench.Start("windynrelocsyms")
288 ctxt.windynrelocsyms()
291 bench.Start("doxcoff")
295 bench.Start("textbuildid")
297 bench.Start("addexport")
300 bench.Start("Gentext")
301 thearch.Gentext(ctxt, ctxt.loader) // trampolines, call stubs, etc.
303 bench.Start("textaddress")
305 bench.Start("typelink")
307 bench.Start("buildinfo")
309 bench.Start("pclntab")
310 containers := ctxt.findContainerSyms()
311 pclnState := ctxt.pclntab(containers)
312 bench.Start("findfunctab")
313 ctxt.findfunctab(pclnState, containers)
314 bench.Start("dwarfGenerateDebugSyms")
315 dwarfGenerateDebugSyms(ctxt)
316 bench.Start("symtab")
317 symGroupType := ctxt.symtab(pclnState)
318 bench.Start("dodata")
319 ctxt.dodata(symGroupType)
320 bench.Start("address")
321 order := ctxt.address()
322 bench.Start("dwarfcompress")
324 bench.Start("layout")
325 filesize := ctxt.layout(order)
327 // Write out the output file.
328 // It is split into two parts (Asmb and Asmb2). The first
329 // part writes most of the content (sections and segments),
330 // for which we have computed the size and offset, in a
331 // mmap'd region. The second part writes more content, for
332 // which we don't know the size.
333 if ctxt.Arch.Family != sys.Wasm {
334 // Don't mmap if we're building for Wasm. Wasm file
335 // layout is very different so filesize is meaningless.
336 if err := ctxt.Out.Mmap(filesize); err != nil {
340 // asmb will redirect symbols to the output file mmap, and relocations
341 // will be applied directly there.
347 // Generate additional symbols for the native symbol table just prior
348 // to code generation.
349 bench.Start("GenSymsLate")
350 if thearch.GenSymsLate != nil {
351 thearch.GenSymsLate(ctxt, ctxt.loader)
357 bench.Start("Munmap")
358 ctxt.Out.Close() // Close handles Munmapping if necessary.
360 bench.Start("hostlink")
362 if ctxt.Debugvlog != 0 {
363 ctxt.Logf("%s", ctxt.loader.Stat())
364 ctxt.Logf("%d liveness data\n", liveness)
368 bench.Start("archive")
370 bench.Report(os.Stdout)
380 func (r *Rpath) Set(val string) error {
386 func (r *Rpath) String() string {
390 func startProfile() {
391 if *cpuprofile != "" {
392 f, err := os.Create(*cpuprofile)
394 log.Fatalf("%v", err)
396 if err := pprof.StartCPUProfile(f); err != nil {
397 log.Fatalf("%v", err)
399 AtExit(pprof.StopCPUProfile)
401 if *memprofile != "" {
402 if *memprofilerate != 0 {
403 runtime.MemProfileRate = int(*memprofilerate)
405 f, err := os.Create(*memprofile)
407 log.Fatalf("%v", err)
410 // Profile all outstanding allocations.
412 // compilebench parses the memory profile to extract memstats,
413 // which are only written in the legacy pprof format.
414 // See golang.org/issue/18641 and runtime/pprof/pprof.go:writeHeap.
415 const writeLegacyFormat = 1
416 if err := pprof.Lookup("heap").WriteTo(f, writeLegacyFormat); err != nil {
417 log.Fatalf("%v", err)