github.com/zxy12/go_duplicate_112_new@v0.0.0-20200807091221-747231827200/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  	"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  	dwarfGenerateDebugInfo(ctxt)
   212  	if objabi.Fieldtrack_enabled != 0 {
   213  		fieldtrack(ctxt)
   214  	}
   215  	ctxt.mangleTypeSym()
   216  	ctxt.callgraph()
   217  
   218  	ctxt.doelf()
   219  	if ctxt.HeadType == objabi.Hdarwin {
   220  		ctxt.domacho()
   221  	}
   222  	ctxt.dostkcheck()
   223  	if ctxt.HeadType == objabi.Hwindows {
   224  		ctxt.dope()
   225  		ctxt.windynrelocsyms()
   226  	}
   227  	if ctxt.HeadType == objabi.Haix {
   228  		ctxt.doxcoff()
   229  	}
   230  
   231  	ctxt.addexport()
   232  	thearch.Gentext(ctxt) // trampolines, call stubs, etc.
   233  	ctxt.textbuildid()
   234  	ctxt.textaddress()
   235  	ctxt.pclntab()
   236  	ctxt.findfunctab()
   237  	ctxt.typelink()
   238  	ctxt.symtab()
   239  	ctxt.dodata()
   240  	order := ctxt.address()
   241  	ctxt.reloc()
   242  	dwarfcompress(ctxt)
   243  	ctxt.layout(order)
   244  	thearch.Asmb(ctxt)
   245  	ctxt.undef()
   246  	ctxt.hostlink()
   247  	ctxt.archive()
   248  	if ctxt.Debugvlog != 0 {
   249  		ctxt.Logf("%5.2f cpu time\n", Cputime())
   250  		ctxt.Logf("%d symbols\n", len(ctxt.Syms.Allsym))
   251  		ctxt.Logf("%d liveness data\n", liveness)
   252  	}
   253  
   254  	ctxt.Bso.Flush()
   255  
   256  	errorexit()
   257  }
   258  
   259  type Rpath struct {
   260  	set bool
   261  	val string
   262  }
   263  
   264  func (r *Rpath) Set(val string) error {
   265  	r.set = true
   266  	r.val = val
   267  	return nil
   268  }
   269  
   270  func (r *Rpath) String() string {
   271  	return r.val
   272  }
   273  
   274  func startProfile() {
   275  	if *cpuprofile != "" {
   276  		f, err := os.Create(*cpuprofile)
   277  		if err != nil {
   278  			log.Fatalf("%v", err)
   279  		}
   280  		if err := pprof.StartCPUProfile(f); err != nil {
   281  			log.Fatalf("%v", err)
   282  		}
   283  		AtExit(pprof.StopCPUProfile)
   284  	}
   285  	if *memprofile != "" {
   286  		if *memprofilerate != 0 {
   287  			runtime.MemProfileRate = int(*memprofilerate)
   288  		}
   289  		f, err := os.Create(*memprofile)
   290  		if err != nil {
   291  			log.Fatalf("%v", err)
   292  		}
   293  		AtExit(func() {
   294  			runtime.GC() // profile all outstanding allocations
   295  			if err := pprof.WriteHeapProfile(f); err != nil {
   296  				log.Fatalf("%v", err)
   297  			}
   298  		})
   299  	}
   300  }