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