github.com/epfl-dcsl/gotee@v0.0.0-20200909122901-014b35f5e5e9/src/cmd/link/internal/ld/main.go (about)

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