Black Lives Matter. Support the Equal Justice Initiative.

Source file src/cmd/internal/obj/sym.go

Documentation: cmd/internal/obj

     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 obj
    33  
    34  import (
    35  	"cmd/internal/goobj"
    36  	"cmd/internal/objabi"
    37  	"fmt"
    38  	"log"
    39  	"math"
    40  	"sort"
    41  	"strings"
    42  )
    43  
    44  func Linknew(arch *LinkArch) *Link {
    45  	ctxt := new(Link)
    46  	ctxt.hash = make(map[string]*LSym)
    47  	ctxt.funchash = make(map[string]*LSym)
    48  	ctxt.statichash = make(map[string]*LSym)
    49  	ctxt.Arch = arch
    50  	ctxt.Pathname = objabi.WorkingDir()
    51  
    52  	if err := ctxt.Headtype.Set(objabi.GOOS); err != nil {
    53  		log.Fatalf("unknown goos %s", objabi.GOOS)
    54  	}
    55  
    56  	ctxt.Flag_optimize = true
    57  	return ctxt
    58  }
    59  
    60  // LookupDerived looks up or creates the symbol with name name derived from symbol s.
    61  // The resulting symbol will be static iff s is.
    62  func (ctxt *Link) LookupDerived(s *LSym, name string) *LSym {
    63  	if s.Static() {
    64  		return ctxt.LookupStatic(name)
    65  	}
    66  	return ctxt.Lookup(name)
    67  }
    68  
    69  // LookupStatic looks up the static symbol with name name.
    70  // If it does not exist, it creates it.
    71  func (ctxt *Link) LookupStatic(name string) *LSym {
    72  	s := ctxt.statichash[name]
    73  	if s == nil {
    74  		s = &LSym{Name: name, Attribute: AttrStatic}
    75  		ctxt.statichash[name] = s
    76  	}
    77  	return s
    78  }
    79  
    80  // LookupABI looks up a symbol with the given ABI.
    81  // If it does not exist, it creates it.
    82  func (ctxt *Link) LookupABI(name string, abi ABI) *LSym {
    83  	return ctxt.LookupABIInit(name, abi, nil)
    84  }
    85  
    86  // LookupABI looks up a symbol with the given ABI.
    87  // If it does not exist, it creates it and
    88  // passes it to init for one-time initialization.
    89  func (ctxt *Link) LookupABIInit(name string, abi ABI, init func(s *LSym)) *LSym {
    90  	var hash map[string]*LSym
    91  	switch abi {
    92  	case ABI0:
    93  		hash = ctxt.hash
    94  	case ABIInternal:
    95  		hash = ctxt.funchash
    96  	default:
    97  		panic("unknown ABI")
    98  	}
    99  
   100  	ctxt.hashmu.Lock()
   101  	s := hash[name]
   102  	if s == nil {
   103  		s = &LSym{Name: name}
   104  		s.SetABI(abi)
   105  		hash[name] = s
   106  		if init != nil {
   107  			init(s)
   108  		}
   109  	}
   110  	ctxt.hashmu.Unlock()
   111  	return s
   112  }
   113  
   114  // Lookup looks up the symbol with name name.
   115  // If it does not exist, it creates it.
   116  func (ctxt *Link) Lookup(name string) *LSym {
   117  	return ctxt.LookupInit(name, nil)
   118  }
   119  
   120  // LookupInit looks up the symbol with name name.
   121  // If it does not exist, it creates it and
   122  // passes it to init for one-time initialization.
   123  func (ctxt *Link) LookupInit(name string, init func(s *LSym)) *LSym {
   124  	ctxt.hashmu.Lock()
   125  	s := ctxt.hash[name]
   126  	if s == nil {
   127  		s = &LSym{Name: name}
   128  		ctxt.hash[name] = s
   129  		if init != nil {
   130  			init(s)
   131  		}
   132  	}
   133  	ctxt.hashmu.Unlock()
   134  	return s
   135  }
   136  
   137  func (ctxt *Link) Float32Sym(f float32) *LSym {
   138  	i := math.Float32bits(f)
   139  	name := fmt.Sprintf("$f32.%08x", i)
   140  	return ctxt.LookupInit(name, func(s *LSym) {
   141  		s.Size = 4
   142  		s.WriteFloat32(ctxt, 0, f)
   143  		s.Type = objabi.SRODATA
   144  		s.Set(AttrLocal, true)
   145  		s.Set(AttrContentAddressable, true)
   146  		ctxt.constSyms = append(ctxt.constSyms, s)
   147  	})
   148  }
   149  
   150  func (ctxt *Link) Float64Sym(f float64) *LSym {
   151  	i := math.Float64bits(f)
   152  	name := fmt.Sprintf("$f64.%016x", i)
   153  	return ctxt.LookupInit(name, func(s *LSym) {
   154  		s.Size = 8
   155  		s.WriteFloat64(ctxt, 0, f)
   156  		s.Type = objabi.SRODATA
   157  		s.Set(AttrLocal, true)
   158  		s.Set(AttrContentAddressable, true)
   159  		ctxt.constSyms = append(ctxt.constSyms, s)
   160  	})
   161  }
   162  
   163  func (ctxt *Link) Int64Sym(i int64) *LSym {
   164  	name := fmt.Sprintf("$i64.%016x", uint64(i))
   165  	return ctxt.LookupInit(name, func(s *LSym) {
   166  		s.Size = 8
   167  		s.WriteInt(ctxt, 0, 8, i)
   168  		s.Type = objabi.SRODATA
   169  		s.Set(AttrLocal, true)
   170  		s.Set(AttrContentAddressable, true)
   171  		ctxt.constSyms = append(ctxt.constSyms, s)
   172  	})
   173  }
   174  
   175  // Assign index to symbols.
   176  // asm is set to true if this is called by the assembler (i.e. not the compiler),
   177  // in which case all the symbols are non-package (for now).
   178  func (ctxt *Link) NumberSyms() {
   179  	if ctxt.Headtype == objabi.Haix {
   180  		// Data must be sorted to keep a constant order in TOC symbols.
   181  		// As they are created during Progedit, two symbols can be switched between
   182  		// two different compilations. Therefore, BuildID will be different.
   183  		// TODO: find a better place and optimize to only sort TOC symbols
   184  		sort.Slice(ctxt.Data, func(i, j int) bool {
   185  			return ctxt.Data[i].Name < ctxt.Data[j].Name
   186  		})
   187  	}
   188  
   189  	// Constant symbols are created late in the concurrent phase. Sort them
   190  	// to ensure a deterministic order.
   191  	sort.Slice(ctxt.constSyms, func(i, j int) bool {
   192  		return ctxt.constSyms[i].Name < ctxt.constSyms[j].Name
   193  	})
   194  	ctxt.Data = append(ctxt.Data, ctxt.constSyms...)
   195  	ctxt.constSyms = nil
   196  
   197  	ctxt.pkgIdx = make(map[string]int32)
   198  	ctxt.defs = []*LSym{}
   199  	ctxt.hashed64defs = []*LSym{}
   200  	ctxt.hasheddefs = []*LSym{}
   201  	ctxt.nonpkgdefs = []*LSym{}
   202  
   203  	var idx, hashedidx, hashed64idx, nonpkgidx int32
   204  	ctxt.traverseSyms(traverseDefs, func(s *LSym) {
   205  		// if Pkgpath is unknown, cannot hash symbols with relocations, as it
   206  		// may reference named symbols whose names are not fully expanded.
   207  		if s.ContentAddressable() && (ctxt.Pkgpath != "" || len(s.R) == 0) {
   208  			if s.Size <= 8 && len(s.R) == 0 && !strings.HasPrefix(s.Name, "type.") {
   209  				// We can use short hash only for symbols without relocations.
   210  				// Don't use short hash for type symbols, as they need special handling.
   211  				s.PkgIdx = goobj.PkgIdxHashed64
   212  				s.SymIdx = hashed64idx
   213  				if hashed64idx != int32(len(ctxt.hashed64defs)) {
   214  					panic("bad index")
   215  				}
   216  				ctxt.hashed64defs = append(ctxt.hashed64defs, s)
   217  				hashed64idx++
   218  			} else {
   219  				s.PkgIdx = goobj.PkgIdxHashed
   220  				s.SymIdx = hashedidx
   221  				if hashedidx != int32(len(ctxt.hasheddefs)) {
   222  					panic("bad index")
   223  				}
   224  				ctxt.hasheddefs = append(ctxt.hasheddefs, s)
   225  				hashedidx++
   226  			}
   227  		} else if isNonPkgSym(ctxt, s) {
   228  			s.PkgIdx = goobj.PkgIdxNone
   229  			s.SymIdx = nonpkgidx
   230  			if nonpkgidx != int32(len(ctxt.nonpkgdefs)) {
   231  				panic("bad index")
   232  			}
   233  			ctxt.nonpkgdefs = append(ctxt.nonpkgdefs, s)
   234  			nonpkgidx++
   235  		} else {
   236  			s.PkgIdx = goobj.PkgIdxSelf
   237  			s.SymIdx = idx
   238  			if idx != int32(len(ctxt.defs)) {
   239  				panic("bad index")
   240  			}
   241  			ctxt.defs = append(ctxt.defs, s)
   242  			idx++
   243  		}
   244  		s.Set(AttrIndexed, true)
   245  	})
   246  
   247  	ipkg := int32(1) // 0 is invalid index
   248  	nonpkgdef := nonpkgidx
   249  	ctxt.traverseSyms(traverseRefs|traverseAux, func(rs *LSym) {
   250  		if rs.PkgIdx != goobj.PkgIdxInvalid {
   251  			return
   252  		}
   253  		if !ctxt.Flag_linkshared {
   254  			// Assign special index for builtin symbols.
   255  			// Don't do it when linking against shared libraries, as the runtime
   256  			// may be in a different library.
   257  			if i := goobj.BuiltinIdx(rs.Name, int(rs.ABI())); i != -1 {
   258  				rs.PkgIdx = goobj.PkgIdxBuiltin
   259  				rs.SymIdx = int32(i)
   260  				rs.Set(AttrIndexed, true)
   261  				return
   262  			}
   263  		}
   264  		pkg := rs.Pkg
   265  		if rs.ContentAddressable() {
   266  			// for now, only support content-addressable symbols that are always locally defined.
   267  			panic("hashed refs unsupported for now")
   268  		}
   269  		if pkg == "" || pkg == "\"\"" || pkg == "_" || !rs.Indexed() {
   270  			rs.PkgIdx = goobj.PkgIdxNone
   271  			rs.SymIdx = nonpkgidx
   272  			rs.Set(AttrIndexed, true)
   273  			if nonpkgidx != nonpkgdef+int32(len(ctxt.nonpkgrefs)) {
   274  				panic("bad index")
   275  			}
   276  			ctxt.nonpkgrefs = append(ctxt.nonpkgrefs, rs)
   277  			nonpkgidx++
   278  			return
   279  		}
   280  		if k, ok := ctxt.pkgIdx[pkg]; ok {
   281  			rs.PkgIdx = k
   282  			return
   283  		}
   284  		rs.PkgIdx = ipkg
   285  		ctxt.pkgIdx[pkg] = ipkg
   286  		ipkg++
   287  	})
   288  }
   289  
   290  // Returns whether s is a non-package symbol, which needs to be referenced
   291  // by name instead of by index.
   292  func isNonPkgSym(ctxt *Link, s *LSym) bool {
   293  	if ctxt.IsAsm && !s.Static() {
   294  		// asm symbols are referenced by name only, except static symbols
   295  		// which are file-local and can be referenced by index.
   296  		return true
   297  	}
   298  	if ctxt.Flag_linkshared {
   299  		// The referenced symbol may be in a different shared library so
   300  		// the linker cannot see its index.
   301  		return true
   302  	}
   303  	if s.Pkg == "_" {
   304  		// The frontend uses package "_" to mark symbols that should not
   305  		// be referenced by index, e.g. linkname'd symbols.
   306  		return true
   307  	}
   308  	if s.DuplicateOK() {
   309  		// Dupok symbol needs to be dedup'd by name.
   310  		return true
   311  	}
   312  	return false
   313  }
   314  
   315  // StaticNamePref is the prefix the front end applies to static temporary
   316  // variables. When turned into LSyms, these can be tagged as static so
   317  // as to avoid inserting them into the linker's name lookup tables.
   318  const StaticNamePref = ".stmp_"
   319  
   320  type traverseFlag uint32
   321  
   322  const (
   323  	traverseDefs traverseFlag = 1 << iota
   324  	traverseRefs
   325  	traverseAux
   326  
   327  	traverseAll = traverseDefs | traverseRefs | traverseAux
   328  )
   329  
   330  // Traverse symbols based on flag, call fn for each symbol.
   331  func (ctxt *Link) traverseSyms(flag traverseFlag, fn func(*LSym)) {
   332  	lists := [][]*LSym{ctxt.Text, ctxt.Data, ctxt.ABIAliases}
   333  	for _, list := range lists {
   334  		for _, s := range list {
   335  			if flag&traverseDefs != 0 {
   336  				fn(s)
   337  			}
   338  			if flag&traverseRefs != 0 {
   339  				for _, r := range s.R {
   340  					if r.Sym != nil {
   341  						fn(r.Sym)
   342  					}
   343  				}
   344  			}
   345  			if flag&traverseAux != 0 {
   346  				if s.Gotype != nil {
   347  					fn(s.Gotype)
   348  				}
   349  				if s.Type == objabi.STEXT {
   350  					f := func(parent *LSym, aux *LSym) {
   351  						fn(aux)
   352  					}
   353  					ctxt.traverseFuncAux(flag, s, f)
   354  				}
   355  			}
   356  		}
   357  	}
   358  }
   359  
   360  func (ctxt *Link) traverseFuncAux(flag traverseFlag, fsym *LSym, fn func(parent *LSym, aux *LSym)) {
   361  	fninfo := fsym.Func()
   362  	pc := &fninfo.Pcln
   363  	if flag&traverseAux == 0 {
   364  		// NB: should it become necessary to walk aux sym reloc references
   365  		// without walking the aux syms themselves, this can be changed.
   366  		panic("should not be here")
   367  	}
   368  	for _, d := range pc.Funcdata {
   369  		if d != nil {
   370  			fn(fsym, d)
   371  		}
   372  	}
   373  	files := ctxt.PosTable.FileTable()
   374  	usedFiles := make([]goobj.CUFileIndex, 0, len(pc.UsedFiles))
   375  	for f := range pc.UsedFiles {
   376  		usedFiles = append(usedFiles, f)
   377  	}
   378  	sort.Slice(usedFiles, func(i, j int) bool { return usedFiles[i] < usedFiles[j] })
   379  	for _, f := range usedFiles {
   380  		if filesym := ctxt.Lookup(files[f]); filesym != nil {
   381  			fn(fsym, filesym)
   382  		}
   383  	}
   384  	for _, call := range pc.InlTree.nodes {
   385  		if call.Func != nil {
   386  			fn(fsym, call.Func)
   387  		}
   388  		f, _ := linkgetlineFromPos(ctxt, call.Pos)
   389  		if filesym := ctxt.Lookup(f); filesym != nil {
   390  			fn(fsym, filesym)
   391  		}
   392  	}
   393  
   394  	dwsyms := []*LSym{fninfo.dwarfRangesSym, fninfo.dwarfLocSym, fninfo.dwarfDebugLinesSym, fninfo.dwarfInfoSym}
   395  	for _, dws := range dwsyms {
   396  		if dws == nil || dws.Size == 0 {
   397  			continue
   398  		}
   399  		fn(fsym, dws)
   400  		if flag&traverseRefs != 0 {
   401  			for _, r := range dws.R {
   402  				if r.Sym != nil {
   403  					fn(dws, r.Sym)
   404  				}
   405  			}
   406  		}
   407  	}
   408  }
   409  
   410  // Traverse aux symbols, calling fn for each sym/aux pair.
   411  func (ctxt *Link) traverseAuxSyms(flag traverseFlag, fn func(parent *LSym, aux *LSym)) {
   412  	lists := [][]*LSym{ctxt.Text, ctxt.Data, ctxt.ABIAliases}
   413  	for _, list := range lists {
   414  		for _, s := range list {
   415  			if s.Gotype != nil {
   416  				if flag&traverseDefs != 0 {
   417  					fn(s, s.Gotype)
   418  				}
   419  			}
   420  			if s.Type != objabi.STEXT {
   421  				continue
   422  			}
   423  			ctxt.traverseFuncAux(flag, s, fn)
   424  		}
   425  	}
   426  }
   427  

View as plain text