...
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  	"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  
    98  // Main is the main entry point for the linker code.
    99  func Main(arch *sys.Arch, theArch Arch) {
   100  	Thearch = theArch
   101  	ctxt := linknew(arch)
   102  	ctxt.Bso = bufio.NewWriter(os.Stdout)
   103  
   104  	// For testing behavior of go command when tools crash silently.
   105  	// Undocumented, not in standard flag parser to avoid
   106  	// exposing in usage message.
   107  	for _, arg := range os.Args {
   108  		if arg == "-crash_for_testing" {
   109  			os.Exit(2)
   110  		}
   111  	}
   112  
   113  	final := gorootFinal()
   114  	addstrdata1(ctxt, "runtime/internal/sys.DefaultGoroot="+final)
   115  	addstrdata1(ctxt, "cmd/internal/objabi.defaultGOROOT="+final)
   116  
   117  	// TODO(matloob): define these above and then check flag values here
   118  	if ctxt.Arch.Family == sys.AMD64 && objabi.GOOS == "plan9" {
   119  		flag.BoolVar(&Flag8, "8", false, "use 64-bit addresses in symbol table")
   120  	}
   121  	flagHeadType := flag.String("H", "", "set header `type`")
   122  	flag.BoolVar(&ctxt.linkShared, "linkshared", false, "link against installed Go shared libraries")
   123  	flag.Var(&ctxt.LinkMode, "linkmode", "set link `mode`")
   124  	flag.Var(&ctxt.BuildMode, "buildmode", "set build `mode`")
   125  	objabi.Flagfn1("B", "add an ELF NT_GNU_BUILD_ID `note` when using ELF", addbuildinfo)
   126  	objabi.Flagfn1("L", "add specified `directory` to library path", func(a string) { Lflag(ctxt, a) })
   127  	objabi.AddVersionFlag() // -V
   128  	objabi.Flagfn1("X", "add string value `definition` of the form importpath.name=value", func(s string) { addstrdata1(ctxt, s) })
   129  	objabi.Flagcount("v", "print link trace", &ctxt.Debugvlog)
   130  	objabi.Flagfn1("importcfg", "read import configuration from `file`", ctxt.readImportCfg)
   131  
   132  	objabi.Flagparse(usage)
   133  
   134  	switch *flagHeadType {
   135  	case "":
   136  	case "windowsgui":
   137  		ctxt.HeadType = objabi.Hwindows
   138  		windowsgui = true
   139  	default:
   140  		if err := ctxt.HeadType.Set(*flagHeadType); err != nil {
   141  			Errorf(nil, "%v", err)
   142  			usage()
   143  		}
   144  	}
   145  
   146  	startProfile()
   147  	if ctxt.BuildMode == BuildModeUnset {
   148  		ctxt.BuildMode = BuildModeExe
   149  	}
   150  
   151  	if ctxt.BuildMode != BuildModeShared && flag.NArg() != 1 {
   152  		usage()
   153  	}
   154  
   155  	if *flagOutfile == "" {
   156  		*flagOutfile = "a.out"
   157  		if ctxt.HeadType == objabi.Hwindows {
   158  			*flagOutfile += ".exe"
   159  		}
   160  	}
   161  
   162  	interpreter = *flagInterpreter
   163  
   164  	libinit(ctxt) // creates outfile
   165  
   166  	if ctxt.HeadType == objabi.Hunknown {
   167  		ctxt.HeadType.Set(objabi.GOOS)
   168  	}
   169  
   170  	ctxt.computeTLSOffset()
   171  	Thearch.Archinit(ctxt)
   172  
   173  	if ctxt.linkShared && !ctxt.IsELF {
   174  		Exitf("-linkshared can only be used on elf systems")
   175  	}
   176  
   177  	if ctxt.Debugvlog != 0 {
   178  		ctxt.Logf("HEADER = -H%d -T0x%x -D0x%x -R0x%x\n", ctxt.HeadType, uint64(*FlagTextAddr), uint64(*FlagDataAddr), uint32(*FlagRound))
   179  	}
   180  
   181  	switch ctxt.BuildMode {
   182  	case BuildModeShared:
   183  		for i := 0; i < flag.NArg(); i++ {
   184  			arg := flag.Arg(i)
   185  			parts := strings.SplitN(arg, "=", 2)
   186  			var pkgpath, file string
   187  			if len(parts) == 1 {
   188  				pkgpath, file = "main", arg
   189  			} else {
   190  				pkgpath, file = parts[0], parts[1]
   191  			}
   192  			pkglistfornote = append(pkglistfornote, pkgpath...)
   193  			pkglistfornote = append(pkglistfornote, '\n')
   194  			addlibpath(ctxt, "command line", "command line", file, pkgpath, "")
   195  		}
   196  	case BuildModePlugin:
   197  		addlibpath(ctxt, "command line", "command line", flag.Arg(0), *flagPluginPath, "")
   198  	default:
   199  		addlibpath(ctxt, "command line", "command line", flag.Arg(0), "main", "")
   200  	}
   201  	ctxt.loadlib()
   202  
   203  	ctxt.dostrdata()
   204  	deadcode(ctxt)
   205  	fieldtrack(ctxt)
   206  	ctxt.callgraph()
   207  
   208  	ctxt.doelf()
   209  	if ctxt.HeadType == objabi.Hdarwin {
   210  		ctxt.domacho()
   211  	}
   212  	ctxt.dostkcheck()
   213  	if ctxt.HeadType == objabi.Hwindows {
   214  		ctxt.dope()
   215  	}
   216  	ctxt.addexport()
   217  	Thearch.Gentext(ctxt) // trampolines, call stubs, etc.
   218  	ctxt.textbuildid()
   219  	ctxt.textaddress()
   220  	ctxt.pclntab()
   221  	ctxt.findfunctab()
   222  	ctxt.typelink()
   223  	ctxt.symtab()
   224  	ctxt.dodata()
   225  	ctxt.address()
   226  	ctxt.reloc()
   227  	Thearch.Asmb(ctxt)
   228  	ctxt.undef()
   229  	ctxt.hostlink()
   230  	ctxt.archive()
   231  	if ctxt.Debugvlog != 0 {
   232  		ctxt.Logf("%5.2f cpu time\n", Cputime())
   233  		ctxt.Logf("%d symbols\n", len(ctxt.Syms.Allsym))
   234  		ctxt.Logf("%d liveness data\n", liveness)
   235  	}
   236  
   237  	ctxt.Bso.Flush()
   238  
   239  	errorexit()
   240  }
   241  
   242  type Rpath struct {
   243  	set bool
   244  	val string
   245  }
   246  
   247  func (r *Rpath) Set(val string) error {
   248  	r.set = true
   249  	r.val = val
   250  	return nil
   251  }
   252  
   253  func (r *Rpath) String() string {
   254  	return r.val
   255  }
   256  
   257  func startProfile() {
   258  	if *cpuprofile != "" {
   259  		f, err := os.Create(*cpuprofile)
   260  		if err != nil {
   261  			log.Fatalf("%v", err)
   262  		}
   263  		if err := pprof.StartCPUProfile(f); err != nil {
   264  			log.Fatalf("%v", err)
   265  		}
   266  		AtExit(pprof.StopCPUProfile)
   267  	}
   268  	if *memprofile != "" {
   269  		if *memprofilerate != 0 {
   270  			runtime.MemProfileRate = int(*memprofilerate)
   271  		}
   272  		f, err := os.Create(*memprofile)
   273  		if err != nil {
   274  			log.Fatalf("%v", err)
   275  		}
   276  		AtExit(func() {
   277  			runtime.GC() // profile all outstanding allocations
   278  			if err := pprof.WriteHeapProfile(f); err != nil {
   279  				log.Fatalf("%v", err)
   280  			}
   281  		})
   282  	}
   283  }
   284  

View as plain text