...
Run Format

Source file src/cmd/link/internal/ld/main.go

Documentation: cmd/link/internal/ld

     1  // Inferno utils/6l/obj.c
     2  // https://bitbucket.org/inferno-os/inferno-os/src/default/utils/6l/obj.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  	"cmd/internal/objabi"
    36  	"cmd/internal/sys"
    37  	"cmd/link/internal/sym"
    38  	"flag"
    39  	"log"
    40  	"os"
    41  	"runtime"
    42  	"runtime/pprof"
    43  	"strings"
    44  )
    45  
    46  var (
    47  	pkglistfornote []byte
    48  	windowsgui     bool // writes a "GUI binary" instead of a "console binary"
    49  )
    50  
    51  func init() {
    52  	flag.Var(&rpath, "r", "set the ELF dynamic linker search `path` to dir1:dir2:...")
    53  }
    54  
    55  // Flags used by the linker. The exported flags are used by the architecture-specific packages.
    56  var (
    57  	flagBuildid = flag.String("buildid", "", "record `id` as Go toolchain build id")
    58  
    59  	flagOutfile    = flag.String("o", "", "write output to `file`")
    60  	flagPluginPath = flag.String("pluginpath", "", "full path name for plugin")
    61  
    62  	flagInstallSuffix = flag.String("installsuffix", "", "set package directory `suffix`")
    63  	flagDumpDep       = flag.Bool("dumpdep", false, "dump symbol dependency graph")
    64  	flagRace          = flag.Bool("race", false, "enable race detector")
    65  	flagMsan          = flag.Bool("msan", false, "enable MSan interface")
    66  
    67  	flagFieldTrack = flag.String("k", "", "set field tracking `symbol`")
    68  	flagLibGCC     = flag.String("libgcc", "", "compiler support lib for internal linking; use \"none\" to disable")
    69  	flagTmpdir     = flag.String("tmpdir", "", "use `directory` for temporary files")
    70  
    71  	flagExtld      = flag.String("extld", "", "use `linker` when linking in external mode")
    72  	flagExtldflags = flag.String("extldflags", "", "pass `flags` to external linker")
    73  	flagExtar      = flag.String("extar", "", "archive program for buildmode=c-archive")
    74  
    75  	flagA           = flag.Bool("a", false, "disassemble output")
    76  	FlagC           = flag.Bool("c", false, "dump call graph")
    77  	FlagD           = flag.Bool("d", false, "disable dynamic executable")
    78  	flagF           = flag.Bool("f", false, "ignore version mismatch")
    79  	flagG           = flag.Bool("g", false, "disable go package data checks")
    80  	flagH           = flag.Bool("h", false, "halt on error")
    81  	flagN           = flag.Bool("n", false, "dump symbol table")
    82  	FlagS           = flag.Bool("s", false, "disable symbol table")
    83  	flagU           = flag.Bool("u", false, "reject unsafe packages")
    84  	FlagW           = flag.Bool("w", false, "disable DWARF generation")
    85  	Flag8           bool // use 64-bit addresses in symbol table
    86  	flagInterpreter = flag.String("I", "", "use `linker` as ELF dynamic linker")
    87  	FlagDebugTramp  = flag.Int("debugtramp", 0, "debug trampolines")
    88  
    89  	FlagRound       = flag.Int("R", -1, "set address rounding `quantum`")
    90  	FlagTextAddr    = flag.Int64("T", -1, "set text segment `address`")
    91  	FlagDataAddr    = flag.Int64("D", -1, "set data segment `address`")
    92  	flagEntrySymbol = flag.String("E", "", "set `entry` symbol name")
    93  
    94  	cpuprofile     = flag.String("cpuprofile", "", "write cpu profile to `file`")
    95  	memprofile     = flag.String("memprofile", "", "write memory profile to `file`")
    96  	memprofilerate = flag.Int64("memprofilerate", 0, "set runtime.MemProfileRate to `rate`")
    97  )
    98  
    99  // Main is the main entry point for the linker code.
   100  func Main(arch *sys.Arch, theArch Arch) {
   101  	thearch = theArch
   102  	ctxt := linknew(arch)
   103  	ctxt.Bso = bufio.NewWriter(os.Stdout)
   104  
   105  	// For testing behavior of go command when tools crash silently.
   106  	// Undocumented, not in standard flag parser to avoid
   107  	// exposing in usage message.
   108  	for _, arg := range os.Args {
   109  		if arg == "-crash_for_testing" {
   110  			os.Exit(2)
   111  		}
   112  	}
   113  
   114  	final := gorootFinal()
   115  	addstrdata1(ctxt, "runtime/internal/sys.DefaultGoroot="+final)
   116  	addstrdata1(ctxt, "cmd/internal/objabi.defaultGOROOT="+final)
   117  
   118  	// TODO(matloob): define these above and then check flag values here
   119  	if ctxt.Arch.Family == sys.AMD64 && objabi.GOOS == "plan9" {
   120  		flag.BoolVar(&Flag8, "8", false, "use 64-bit addresses in symbol table")
   121  	}
   122  	flagHeadType := flag.String("H", "", "set header `type`")
   123  	flag.BoolVar(&ctxt.linkShared, "linkshared", false, "link against installed Go shared libraries")
   124  	flag.Var(&ctxt.LinkMode, "linkmode", "set link `mode`")
   125  	flag.Var(&ctxt.BuildMode, "buildmode", "set build `mode`")
   126  	flag.BoolVar(&ctxt.compressDWARF, "compressdwarf", true, "compress DWARF if possible")
   127  	objabi.Flagfn1("B", "add an ELF NT_GNU_BUILD_ID `note` when using ELF", addbuildinfo)
   128  	objabi.Flagfn1("L", "add specified `directory` to library path", func(a string) { Lflag(ctxt, a) })
   129  	objabi.AddVersionFlag() // -V
   130  	objabi.Flagfn1("X", "add string value `definition` of the form importpath.name=value", func(s string) { addstrdata1(ctxt, s) })
   131  	objabi.Flagcount("v", "print link trace", &ctxt.Debugvlog)
   132  	objabi.Flagfn1("importcfg", "read import configuration from `file`", ctxt.readImportCfg)
   133  
   134  	objabi.Flagparse(usage)
   135  
   136  	switch *flagHeadType {
   137  	case "":
   138  	case "windowsgui":
   139  		ctxt.HeadType = objabi.Hwindows
   140  		windowsgui = true
   141  	default:
   142  		if err := ctxt.HeadType.Set(*flagHeadType); err != nil {
   143  			Errorf(nil, "%v", err)
   144  			usage()
   145  		}
   146  	}
   147  
   148  	if objabi.Fieldtrack_enabled != 0 {
   149  		ctxt.Reachparent = make(map[*sym.Symbol]*sym.Symbol)
   150  	}
   151  
   152  	startProfile()
   153  	if ctxt.BuildMode == BuildModeUnset {
   154  		ctxt.BuildMode = BuildModeExe
   155  	}
   156  
   157  	if ctxt.BuildMode != BuildModeShared && flag.NArg() != 1 {
   158  		usage()
   159  	}
   160  
   161  	if *flagOutfile == "" {
   162  		*flagOutfile = "a.out"
   163  		if ctxt.HeadType == objabi.Hwindows {
   164  			*flagOutfile += ".exe"
   165  		}
   166  	}
   167  
   168  	interpreter = *flagInterpreter
   169  
   170  	libinit(ctxt) // creates outfile
   171  
   172  	if ctxt.HeadType == objabi.Hunknown {
   173  		ctxt.HeadType.Set(objabi.GOOS)
   174  	}
   175  
   176  	ctxt.computeTLSOffset()
   177  	thearch.Archinit(ctxt)
   178  
   179  	if ctxt.linkShared && !ctxt.IsELF {
   180  		Exitf("-linkshared can only be used on elf systems")
   181  	}
   182  
   183  	if ctxt.Debugvlog != 0 {
   184  		ctxt.Logf("HEADER = -H%d -T0x%x -D0x%x -R0x%x\n", ctxt.HeadType, uint64(*FlagTextAddr), uint64(*FlagDataAddr), uint32(*FlagRound))
   185  	}
   186  
   187  	switch ctxt.BuildMode {
   188  	case BuildModeShared:
   189  		for i := 0; i < flag.NArg(); i++ {
   190  			arg := flag.Arg(i)
   191  			parts := strings.SplitN(arg, "=", 2)
   192  			var pkgpath, file string
   193  			if len(parts) == 1 {
   194  				pkgpath, file = "main", arg
   195  			} else {
   196  				pkgpath, file = parts[0], parts[1]
   197  			}
   198  			pkglistfornote = append(pkglistfornote, pkgpath...)
   199  			pkglistfornote = append(pkglistfornote, '\n')
   200  			addlibpath(ctxt, "command line", "command line", file, pkgpath, "")
   201  		}
   202  	case BuildModePlugin:
   203  		addlibpath(ctxt, "command line", "command line", flag.Arg(0), *flagPluginPath, "")
   204  	default:
   205  		addlibpath(ctxt, "command line", "command line", flag.Arg(0), "main", "")
   206  	}
   207  	ctxt.loadlib()
   208  
   209  	ctxt.dostrdata()
   210  	deadcode(ctxt)
   211  	if objabi.Fieldtrack_enabled != 0 {
   212  		fieldtrack(ctxt)
   213  	}
   214  	ctxt.callgraph()
   215  
   216  	ctxt.doelf()
   217  	if ctxt.HeadType == objabi.Hdarwin {
   218  		ctxt.domacho()
   219  	}
   220  	ctxt.dostkcheck()
   221  	if ctxt.HeadType == objabi.Hwindows {
   222  		ctxt.dope()
   223  	}
   224  	ctxt.addexport()
   225  	thearch.Gentext(ctxt) // trampolines, call stubs, etc.
   226  	ctxt.textbuildid()
   227  	ctxt.textaddress()
   228  	ctxt.pclntab()
   229  	ctxt.findfunctab()
   230  	ctxt.typelink()
   231  	ctxt.symtab()
   232  	ctxt.dodata()
   233  	order := ctxt.address()
   234  	ctxt.reloc()
   235  	dwarfcompress(ctxt)
   236  	ctxt.layout(order)
   237  	thearch.Asmb(ctxt)
   238  	ctxt.undef()
   239  	ctxt.hostlink()
   240  	ctxt.archive()
   241  	if ctxt.Debugvlog != 0 {
   242  		ctxt.Logf("%5.2f cpu time\n", Cputime())
   243  		ctxt.Logf("%d symbols\n", len(ctxt.Syms.Allsym))
   244  		ctxt.Logf("%d liveness data\n", liveness)
   245  	}
   246  
   247  	ctxt.Bso.Flush()
   248  
   249  	errorexit()
   250  }
   251  
   252  type Rpath struct {
   253  	set bool
   254  	val string
   255  }
   256  
   257  func (r *Rpath) Set(val string) error {
   258  	r.set = true
   259  	r.val = val
   260  	return nil
   261  }
   262  
   263  func (r *Rpath) String() string {
   264  	return r.val
   265  }
   266  
   267  func startProfile() {
   268  	if *cpuprofile != "" {
   269  		f, err := os.Create(*cpuprofile)
   270  		if err != nil {
   271  			log.Fatalf("%v", err)
   272  		}
   273  		if err := pprof.StartCPUProfile(f); err != nil {
   274  			log.Fatalf("%v", err)
   275  		}
   276  		AtExit(pprof.StopCPUProfile)
   277  	}
   278  	if *memprofile != "" {
   279  		if *memprofilerate != 0 {
   280  			runtime.MemProfileRate = int(*memprofilerate)
   281  		}
   282  		f, err := os.Create(*memprofile)
   283  		if err != nil {
   284  			log.Fatalf("%v", err)
   285  		}
   286  		AtExit(func() {
   287  			runtime.GC() // profile all outstanding allocations
   288  			if err := pprof.WriteHeapProfile(f); err != nil {
   289  				log.Fatalf("%v", err)
   290  			}
   291  		})
   292  	}
   293  }
   294  

View as plain text