Black Lives Matter. Support the Equal Justice Initiative.

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

Documentation: cmd/link/internal/ld

     1  // Derived from Inferno utils/6l/obj.c and utils/6l/span.c
     2  // https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/obj.c
     3  // https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/span.c
     4  //
     5  //	Copyright © 1994-1999 Lucent Technologies Inc.  All rights reserved.
     6  //	Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
     7  //	Portions Copyright © 1997-1999 Vita Nuova Limited
     8  //	Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
     9  //	Portions Copyright © 2004,2006 Bruce Ellis
    10  //	Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net)
    11  //	Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
    12  //	Portions Copyright © 2009 The Go Authors. All rights reserved.
    13  //
    14  // Permission is hereby granted, free of charge, to any person obtaining a copy
    15  // of this software and associated documentation files (the "Software"), to deal
    16  // in the Software without restriction, including without limitation the rights
    17  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    18  // copies of the Software, and to permit persons to whom the Software is
    19  // furnished to do so, subject to the following conditions:
    20  //
    21  // The above copyright notice and this permission notice shall be included in
    22  // all copies or substantial portions of the Software.
    23  //
    24  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    25  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    26  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
    27  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    28  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    29  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    30  // THE SOFTWARE.
    31  
    32  package ld
    33  
    34  import (
    35  	"cmd/internal/goobj"
    36  	"cmd/link/internal/loader"
    37  	"cmd/link/internal/sym"
    38  	"io/ioutil"
    39  	"log"
    40  	"os"
    41  	"path"
    42  	"path/filepath"
    43  	"strconv"
    44  	"strings"
    45  )
    46  
    47  func (ctxt *Link) readImportCfg(file string) {
    48  	ctxt.PackageFile = make(map[string]string)
    49  	ctxt.PackageShlib = make(map[string]string)
    50  	data, err := ioutil.ReadFile(file)
    51  	if err != nil {
    52  		log.Fatalf("-importcfg: %v", err)
    53  	}
    54  
    55  	for lineNum, line := range strings.Split(string(data), "\n") {
    56  		lineNum++ // 1-based
    57  		line = strings.TrimSpace(line)
    58  		if line == "" {
    59  			continue
    60  		}
    61  		if line == "" || strings.HasPrefix(line, "#") {
    62  			continue
    63  		}
    64  
    65  		var verb, args string
    66  		if i := strings.Index(line, " "); i < 0 {
    67  			verb = line
    68  		} else {
    69  			verb, args = line[:i], strings.TrimSpace(line[i+1:])
    70  		}
    71  		var before, after string
    72  		if i := strings.Index(args, "="); i >= 0 {
    73  			before, after = args[:i], args[i+1:]
    74  		}
    75  		switch verb {
    76  		default:
    77  			log.Fatalf("%s:%d: unknown directive %q", file, lineNum, verb)
    78  		case "packagefile":
    79  			if before == "" || after == "" {
    80  				log.Fatalf(`%s:%d: invalid packagefile: syntax is "packagefile path=filename"`, file, lineNum)
    81  			}
    82  			ctxt.PackageFile[before] = after
    83  		case "packageshlib":
    84  			if before == "" || after == "" {
    85  				log.Fatalf(`%s:%d: invalid packageshlib: syntax is "packageshlib path=filename"`, file, lineNum)
    86  			}
    87  			ctxt.PackageShlib[before] = after
    88  		}
    89  	}
    90  }
    91  
    92  func pkgname(ctxt *Link, lib string) string {
    93  	name := path.Clean(lib)
    94  
    95  	// When using importcfg, we have the final package name.
    96  	if ctxt.PackageFile != nil {
    97  		return name
    98  	}
    99  
   100  	// runtime.a -> runtime, runtime.6 -> runtime
   101  	pkg := name
   102  	if len(pkg) >= 2 && pkg[len(pkg)-2] == '.' {
   103  		pkg = pkg[:len(pkg)-2]
   104  	}
   105  	return pkg
   106  }
   107  
   108  func findlib(ctxt *Link, lib string) (string, bool) {
   109  	name := path.Clean(lib)
   110  
   111  	var pname string
   112  	isshlib := false
   113  
   114  	if ctxt.linkShared && ctxt.PackageShlib[name] != "" {
   115  		pname = ctxt.PackageShlib[name]
   116  		isshlib = true
   117  	} else if ctxt.PackageFile != nil {
   118  		pname = ctxt.PackageFile[name]
   119  		if pname == "" {
   120  			ctxt.Logf("cannot find package %s (using -importcfg)\n", name)
   121  			return "", false
   122  		}
   123  	} else {
   124  		if filepath.IsAbs(name) {
   125  			pname = name
   126  		} else {
   127  			pkg := pkgname(ctxt, lib)
   128  			// Add .a if needed; the new -importcfg modes
   129  			// do not put .a into the package name anymore.
   130  			// This only matters when people try to mix
   131  			// compiles using -importcfg with links not using -importcfg,
   132  			// such as when running quick things like
   133  			// 'go tool compile x.go && go tool link x.o'
   134  			// by hand against a standard library built using -importcfg.
   135  			if !strings.HasSuffix(name, ".a") && !strings.HasSuffix(name, ".o") {
   136  				name += ".a"
   137  			}
   138  			// try dot, -L "libdir", and then goroot.
   139  			for _, dir := range ctxt.Libdir {
   140  				if ctxt.linkShared {
   141  					pname = filepath.Join(dir, pkg+".shlibname")
   142  					if _, err := os.Stat(pname); err == nil {
   143  						isshlib = true
   144  						break
   145  					}
   146  				}
   147  				pname = filepath.Join(dir, name)
   148  				if _, err := os.Stat(pname); err == nil {
   149  					break
   150  				}
   151  			}
   152  		}
   153  		pname = filepath.Clean(pname)
   154  	}
   155  
   156  	return pname, isshlib
   157  }
   158  
   159  func addlib(ctxt *Link, src, obj, lib string, fingerprint goobj.FingerprintType) *sym.Library {
   160  	pkg := pkgname(ctxt, lib)
   161  
   162  	// already loaded?
   163  	if l := ctxt.LibraryByPkg[pkg]; l != nil && !l.Fingerprint.IsZero() {
   164  		// Normally, packages are loaded in dependency order, and if l != nil
   165  		// l is already loaded with the actual fingerprint. In shared build mode,
   166  		// however, packages may be added not in dependency order, and it is
   167  		// possible that l's fingerprint is not yet loaded -- exclude it in
   168  		// checking.
   169  		checkFingerprint(l, l.Fingerprint, src, fingerprint)
   170  		return l
   171  	}
   172  
   173  	pname, isshlib := findlib(ctxt, lib)
   174  
   175  	if ctxt.Debugvlog > 1 {
   176  		ctxt.Logf("addlib: %s %s pulls in %s isshlib %v\n", obj, src, pname, isshlib)
   177  	}
   178  
   179  	if isshlib {
   180  		return addlibpath(ctxt, src, obj, "", pkg, pname, fingerprint)
   181  	}
   182  	return addlibpath(ctxt, src, obj, pname, pkg, "", fingerprint)
   183  }
   184  
   185  /*
   186   * add library to library list, return added library.
   187   *	srcref: src file referring to package
   188   *	objref: object file referring to package
   189   *	file: object file, e.g., /home/rsc/go/pkg/container/vector.a
   190   *	pkg: package import path, e.g. container/vector
   191   *	shlib: path to shared library, or .shlibname file holding path
   192   *	fingerprint: if not 0, expected fingerprint for import from srcref
   193   *	             fingerprint is 0 if the library is not imported (e.g. main)
   194   */
   195  func addlibpath(ctxt *Link, srcref, objref, file, pkg, shlib string, fingerprint goobj.FingerprintType) *sym.Library {
   196  	if l := ctxt.LibraryByPkg[pkg]; l != nil {
   197  		return l
   198  	}
   199  
   200  	if ctxt.Debugvlog > 1 {
   201  		ctxt.Logf("addlibpath: srcref: %s objref: %s file: %s pkg: %s shlib: %s fingerprint: %x\n", srcref, objref, file, pkg, shlib, fingerprint)
   202  	}
   203  
   204  	l := &sym.Library{}
   205  	ctxt.LibraryByPkg[pkg] = l
   206  	ctxt.Library = append(ctxt.Library, l)
   207  	l.Objref = objref
   208  	l.Srcref = srcref
   209  	l.File = file
   210  	l.Pkg = pkg
   211  	l.Fingerprint = fingerprint
   212  	if shlib != "" {
   213  		if strings.HasSuffix(shlib, ".shlibname") {
   214  			data, err := ioutil.ReadFile(shlib)
   215  			if err != nil {
   216  				Errorf(nil, "cannot read %s: %v", shlib, err)
   217  			}
   218  			shlib = strings.TrimSpace(string(data))
   219  		}
   220  		l.Shlib = shlib
   221  	}
   222  	return l
   223  }
   224  
   225  func atolwhex(s string) int64 {
   226  	n, _ := strconv.ParseInt(s, 0, 64)
   227  	return n
   228  }
   229  
   230  // PrepareAddmoduledata returns a symbol builder that target-specific
   231  // code can use to build up the linker-generated go.link.addmoduledata
   232  // function, along with the sym for runtime.addmoduledata itself. If
   233  // this function is not needed (for example in cases where we're
   234  // linking a module that contains the runtime) the returned builder
   235  // will be nil.
   236  func PrepareAddmoduledata(ctxt *Link) (*loader.SymbolBuilder, loader.Sym) {
   237  	if !ctxt.DynlinkingGo() {
   238  		return nil, 0
   239  	}
   240  	amd := ctxt.loader.LookupOrCreateSym("runtime.addmoduledata", 0)
   241  	if ctxt.loader.SymType(amd) == sym.STEXT && ctxt.BuildMode != BuildModePlugin {
   242  		// we're linking a module containing the runtime -> no need for
   243  		// an init function
   244  		return nil, 0
   245  	}
   246  	ctxt.loader.SetAttrReachable(amd, true)
   247  
   248  	// Create a new init func text symbol. Caller will populate this
   249  	// sym with arch-specific content.
   250  	ifs := ctxt.loader.LookupOrCreateSym("go.link.addmoduledata", 0)
   251  	initfunc := ctxt.loader.MakeSymbolUpdater(ifs)
   252  	ctxt.loader.SetAttrReachable(ifs, true)
   253  	ctxt.loader.SetAttrLocal(ifs, true)
   254  	initfunc.SetType(sym.STEXT)
   255  
   256  	// Add the init func and/or addmoduledata to Textp.
   257  	if ctxt.BuildMode == BuildModePlugin {
   258  		ctxt.Textp = append(ctxt.Textp, amd)
   259  	}
   260  	ctxt.Textp = append(ctxt.Textp, initfunc.Sym())
   261  
   262  	// Create an init array entry
   263  	amdi := ctxt.loader.LookupOrCreateSym("go.link.addmoduledatainit", 0)
   264  	initarray_entry := ctxt.loader.MakeSymbolUpdater(amdi)
   265  	ctxt.loader.SetAttrReachable(amdi, true)
   266  	ctxt.loader.SetAttrLocal(amdi, true)
   267  	initarray_entry.SetType(sym.SINITARR)
   268  	initarray_entry.AddAddr(ctxt.Arch, ifs)
   269  
   270  	return initfunc, amd
   271  }
   272  

View as plain text