Source file src/cmd/link/internal/amd64/asm.go

     1  // Inferno utils/6l/asm.c
     2  // https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/asm.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 amd64
    32  
    33  import (
    34  	"cmd/internal/objabi"
    35  	"cmd/internal/sys"
    36  	"cmd/link/internal/ld"
    37  	"cmd/link/internal/loader"
    38  	"cmd/link/internal/sym"
    39  	"debug/elf"
    40  	"log"
    41  )
    42  
    43  func gentext(ctxt *ld.Link, ldr *loader.Loader) {
    44  	initfunc, addmoduledata := ld.PrepareAddmoduledata(ctxt)
    45  	if initfunc == nil {
    46  		return
    47  	}
    48  
    49  	o := func(op ...uint8) {
    50  		for _, op1 := range op {
    51  			initfunc.AddUint8(op1)
    52  		}
    53  	}
    54  
    55  	// 0000000000000000 <local.dso_init>:
    56  	//    0:	48 8d 3d 00 00 00 00 	lea    0x0(%rip),%rdi        # 7 <local.dso_init+0x7>
    57  	// 			3: R_X86_64_PC32	runtime.firstmoduledata-0x4
    58  	o(0x48, 0x8d, 0x3d)
    59  	initfunc.AddPCRelPlus(ctxt.Arch, ctxt.Moduledata, 0)
    60  	//    7:	e8 00 00 00 00       	callq  c <local.dso_init+0xc>
    61  	// 			8: R_X86_64_PLT32	runtime.addmoduledata-0x4
    62  	o(0xe8)
    63  	initfunc.AddSymRef(ctxt.Arch, addmoduledata, 0, objabi.R_CALL, 4)
    64  	//    c:	c3                   	retq
    65  	o(0xc3)
    66  }
    67  
    68  func adddynrel(target *ld.Target, ldr *loader.Loader, syms *ld.ArchSyms, s loader.Sym, r loader.Reloc, rIdx int) bool {
    69  	targ := r.Sym()
    70  	var targType sym.SymKind
    71  	if targ != 0 {
    72  		targType = ldr.SymType(targ)
    73  	}
    74  
    75  	switch rt := r.Type(); rt {
    76  	default:
    77  		if rt >= objabi.ElfRelocOffset {
    78  			ldr.Errorf(s, "unexpected relocation type %d (%s)", r.Type(), sym.RelocName(target.Arch, r.Type()))
    79  			return false
    80  		}
    81  
    82  		// Handle relocations found in ELF object files.
    83  	case objabi.ElfRelocOffset + objabi.RelocType(elf.R_X86_64_PC32):
    84  		if targType == sym.SDYNIMPORT {
    85  			ldr.Errorf(s, "unexpected R_X86_64_PC32 relocation for dynamic symbol %s", ldr.SymName(targ))
    86  		}
    87  		if targType == 0 || targType == sym.SXREF {
    88  			ldr.Errorf(s, "unknown symbol %s in pcrel", ldr.SymName(targ))
    89  		}
    90  		su := ldr.MakeSymbolUpdater(s)
    91  		su.SetRelocType(rIdx, objabi.R_PCREL)
    92  		su.SetRelocAdd(rIdx, r.Add()+4)
    93  		return true
    94  
    95  	case objabi.ElfRelocOffset + objabi.RelocType(elf.R_X86_64_PC64):
    96  		if targType == sym.SDYNIMPORT {
    97  			ldr.Errorf(s, "unexpected R_X86_64_PC64 relocation for dynamic symbol %s", ldr.SymName(targ))
    98  		}
    99  		if targType == 0 || targType == sym.SXREF {
   100  			ldr.Errorf(s, "unknown symbol %s in pcrel", ldr.SymName(targ))
   101  		}
   102  		su := ldr.MakeSymbolUpdater(s)
   103  		su.SetRelocType(rIdx, objabi.R_PCREL)
   104  		su.SetRelocAdd(rIdx, r.Add()+8)
   105  		return true
   106  
   107  	case objabi.ElfRelocOffset + objabi.RelocType(elf.R_X86_64_PLT32):
   108  		su := ldr.MakeSymbolUpdater(s)
   109  		su.SetRelocType(rIdx, objabi.R_PCREL)
   110  		su.SetRelocAdd(rIdx, r.Add()+4)
   111  		if targType == sym.SDYNIMPORT {
   112  			addpltsym(target, ldr, syms, targ)
   113  			su.SetRelocSym(rIdx, syms.PLT)
   114  			su.SetRelocAdd(rIdx, r.Add()+int64(ldr.SymPlt(targ)))
   115  		}
   116  
   117  		return true
   118  
   119  	case objabi.ElfRelocOffset + objabi.RelocType(elf.R_X86_64_GOTPCREL),
   120  		objabi.ElfRelocOffset + objabi.RelocType(elf.R_X86_64_GOTPCRELX),
   121  		objabi.ElfRelocOffset + objabi.RelocType(elf.R_X86_64_REX_GOTPCRELX):
   122  		su := ldr.MakeSymbolUpdater(s)
   123  		if targType != sym.SDYNIMPORT {
   124  			// have symbol
   125  			sData := ldr.Data(s)
   126  			if r.Off() >= 2 && sData[r.Off()-2] == 0x8b {
   127  				su.MakeWritable()
   128  				// turn MOVQ of GOT entry into LEAQ of symbol itself
   129  				writeableData := su.Data()
   130  				writeableData[r.Off()-2] = 0x8d
   131  				su.SetRelocType(rIdx, objabi.R_PCREL)
   132  				su.SetRelocAdd(rIdx, r.Add()+4)
   133  				return true
   134  			}
   135  		}
   136  
   137  		// fall back to using GOT and hope for the best (CMOV*)
   138  		// TODO: just needs relocation, no need to put in .dynsym
   139  		ld.AddGotSym(target, ldr, syms, targ, uint32(elf.R_X86_64_GLOB_DAT))
   140  
   141  		su.SetRelocType(rIdx, objabi.R_PCREL)
   142  		su.SetRelocSym(rIdx, syms.GOT)
   143  		su.SetRelocAdd(rIdx, r.Add()+4+int64(ldr.SymGot(targ)))
   144  		return true
   145  
   146  	case objabi.ElfRelocOffset + objabi.RelocType(elf.R_X86_64_64):
   147  		if targType == sym.SDYNIMPORT {
   148  			ldr.Errorf(s, "unexpected R_X86_64_64 relocation for dynamic symbol %s", ldr.SymName(targ))
   149  		}
   150  		su := ldr.MakeSymbolUpdater(s)
   151  		su.SetRelocType(rIdx, objabi.R_ADDR)
   152  		if target.IsPIE() && target.IsInternal() {
   153  			// For internal linking PIE, this R_ADDR relocation cannot
   154  			// be resolved statically. We need to generate a dynamic
   155  			// relocation. Let the code below handle it.
   156  			break
   157  		}
   158  		return true
   159  
   160  	// Handle relocations found in Mach-O object files.
   161  	case objabi.MachoRelocOffset + ld.MACHO_X86_64_RELOC_UNSIGNED*2 + 0,
   162  		objabi.MachoRelocOffset + ld.MACHO_X86_64_RELOC_SIGNED*2 + 0,
   163  		objabi.MachoRelocOffset + ld.MACHO_X86_64_RELOC_BRANCH*2 + 0:
   164  		su := ldr.MakeSymbolUpdater(s)
   165  		su.SetRelocType(rIdx, objabi.R_ADDR)
   166  
   167  		if target.IsPIE() && target.IsInternal() {
   168  			// For internal linking PIE, this R_ADDR relocation cannot
   169  			// be resolved statically. We need to generate a dynamic
   170  			// relocation. Let the code below handle it.
   171  			if rt == objabi.MachoRelocOffset+ld.MACHO_X86_64_RELOC_UNSIGNED*2 {
   172  				break
   173  			} else {
   174  				// MACHO_X86_64_RELOC_SIGNED or MACHO_X86_64_RELOC_BRANCH
   175  				// Can this happen? The object is expected to be PIC.
   176  				ldr.Errorf(s, "unsupported relocation for PIE: %v", rt)
   177  			}
   178  		}
   179  		if targType == sym.SDYNIMPORT {
   180  			ldr.Errorf(s, "unexpected reloc for dynamic symbol %s", ldr.SymName(targ))
   181  		}
   182  		return true
   183  
   184  	case objabi.MachoRelocOffset + ld.MACHO_X86_64_RELOC_SUBTRACTOR*2 + 0:
   185  		// X86_64_RELOC_SUBTRACTOR must be followed by X86_64_RELOC_UNSIGNED.
   186  		// The pair of relocations resolves to the difference between two
   187  		// symbol addresses (each relocation specifies a symbol).
   188  		// See Darwin's header file include/mach-o/x86_64/reloc.h.
   189  		// ".quad _foo - _bar" is expressed as
   190  		// r_type=X86_64_RELOC_SUBTRACTOR, r_length=3, r_extern=1, r_pcrel=0, r_symbolnum=_bar
   191  		// r_type=X86_64_RELOC_UNSIGNED, r_length=3, r_extern=1, r_pcrel=0, r_symbolnum=_foo
   192  		//
   193  		// For the cases we care (the race syso), the symbol being subtracted
   194  		// out is always in the current section, so we can just convert it to
   195  		// a PC-relative relocation, with the addend adjusted.
   196  		// If later we need the more general form, we can introduce objabi.R_DIFF
   197  		// that works like this Mach-O relocation.
   198  		su := ldr.MakeSymbolUpdater(s)
   199  		outer, off := ld.FoldSubSymbolOffset(ldr, targ)
   200  		if outer != s {
   201  			ldr.Errorf(s, "unsupported X86_64_RELOC_SUBTRACTOR reloc: target %s, outer %s",
   202  				ldr.SymName(targ), ldr.SymName(outer))
   203  			break
   204  		}
   205  		relocs := su.Relocs()
   206  		if rIdx+1 >= relocs.Count() || relocs.At(rIdx+1).Type() != objabi.MachoRelocOffset+ld.MACHO_X86_64_RELOC_UNSIGNED*2+0 || relocs.At(rIdx+1).Off() != r.Off() {
   207  			ldr.Errorf(s, "unexpected X86_64_RELOC_SUBTRACTOR reloc, must be followed by X86_64_RELOC_UNSIGNED at the same offset: %d %v %d", rIdx, relocs.At(rIdx+1).Type(), relocs.At(rIdx+1).Off())
   208  		}
   209  		// The second relocation has the target symbol we want
   210  		su.SetRelocType(rIdx+1, objabi.R_PCREL)
   211  		su.SetRelocAdd(rIdx+1, r.Add()+int64(r.Off())+int64(r.Siz())-off)
   212  		// Remove the other relocation
   213  		su.SetRelocSiz(rIdx, 0)
   214  		return true
   215  
   216  	case objabi.MachoRelocOffset + ld.MACHO_X86_64_RELOC_BRANCH*2 + 1:
   217  		if targType == sym.SDYNIMPORT {
   218  			addpltsym(target, ldr, syms, targ)
   219  			su := ldr.MakeSymbolUpdater(s)
   220  			su.SetRelocSym(rIdx, syms.PLT)
   221  			su.SetRelocType(rIdx, objabi.R_PCREL)
   222  			su.SetRelocAdd(rIdx, int64(ldr.SymPlt(targ)))
   223  			return true
   224  		}
   225  		fallthrough
   226  
   227  	case objabi.MachoRelocOffset + ld.MACHO_X86_64_RELOC_UNSIGNED*2 + 1,
   228  		objabi.MachoRelocOffset + ld.MACHO_X86_64_RELOC_SIGNED*2 + 1,
   229  		objabi.MachoRelocOffset + ld.MACHO_X86_64_RELOC_SIGNED_1*2 + 1,
   230  		objabi.MachoRelocOffset + ld.MACHO_X86_64_RELOC_SIGNED_2*2 + 1,
   231  		objabi.MachoRelocOffset + ld.MACHO_X86_64_RELOC_SIGNED_4*2 + 1:
   232  		su := ldr.MakeSymbolUpdater(s)
   233  		su.SetRelocType(rIdx, objabi.R_PCREL)
   234  
   235  		if targType == sym.SDYNIMPORT {
   236  			ldr.Errorf(s, "unexpected pc-relative reloc for dynamic symbol %s", ldr.SymName(targ))
   237  		}
   238  		return true
   239  
   240  	case objabi.MachoRelocOffset + ld.MACHO_X86_64_RELOC_GOT_LOAD*2 + 1:
   241  		if targType != sym.SDYNIMPORT {
   242  			// have symbol
   243  			// turn MOVQ of GOT entry into LEAQ of symbol itself
   244  			sdata := ldr.Data(s)
   245  			if r.Off() < 2 || sdata[r.Off()-2] != 0x8b {
   246  				ldr.Errorf(s, "unexpected GOT_LOAD reloc for non-dynamic symbol %s", ldr.SymName(targ))
   247  				return false
   248  			}
   249  
   250  			su := ldr.MakeSymbolUpdater(s)
   251  			su.MakeWritable()
   252  			sdata = su.Data()
   253  			sdata[r.Off()-2] = 0x8d
   254  			su.SetRelocType(rIdx, objabi.R_PCREL)
   255  			return true
   256  		}
   257  		fallthrough
   258  
   259  	case objabi.MachoRelocOffset + ld.MACHO_X86_64_RELOC_GOT*2 + 1:
   260  		if targType != sym.SDYNIMPORT {
   261  			ldr.Errorf(s, "unexpected GOT reloc for non-dynamic symbol %s", ldr.SymName(targ))
   262  		}
   263  		ld.AddGotSym(target, ldr, syms, targ, 0)
   264  		su := ldr.MakeSymbolUpdater(s)
   265  		su.SetRelocType(rIdx, objabi.R_PCREL)
   266  		su.SetRelocSym(rIdx, syms.GOT)
   267  		su.SetRelocAdd(rIdx, r.Add()+int64(ldr.SymGot(targ)))
   268  		return true
   269  	}
   270  
   271  	// Reread the reloc to incorporate any changes in type above.
   272  	relocs := ldr.Relocs(s)
   273  	r = relocs.At(rIdx)
   274  
   275  	switch r.Type() {
   276  	case objabi.R_CALL:
   277  		if targType != sym.SDYNIMPORT {
   278  			// nothing to do, the relocation will be laid out in reloc
   279  			return true
   280  		}
   281  		if target.IsExternal() {
   282  			// External linker will do this relocation.
   283  			return true
   284  		}
   285  		// Internal linking, for both ELF and Mach-O.
   286  		// Build a PLT entry and change the relocation target to that entry.
   287  		addpltsym(target, ldr, syms, targ)
   288  		su := ldr.MakeSymbolUpdater(s)
   289  		su.SetRelocSym(rIdx, syms.PLT)
   290  		su.SetRelocAdd(rIdx, int64(ldr.SymPlt(targ)))
   291  		return true
   292  
   293  	case objabi.R_PCREL:
   294  		if targType == sym.SDYNIMPORT && ldr.SymType(s).IsText() && (target.IsDarwin() || target.IsElf()) {
   295  			// Loading the address of a dynamic symbol. Rewrite to use GOT.
   296  			// turn LEAQ symbol address to MOVQ of GOT entry
   297  			if r.Add() != 0 {
   298  				ldr.Errorf(s, "unexpected nonzero addend for dynamic symbol %s", ldr.SymName(targ))
   299  				return false
   300  			}
   301  			su := ldr.MakeSymbolUpdater(s)
   302  			if r.Off() >= 2 && su.Data()[r.Off()-2] == 0x8d {
   303  				su.MakeWritable()
   304  				su.Data()[r.Off()-2] = 0x8b
   305  				if target.IsInternal() {
   306  					var elfRelocTyp uint32
   307  					if target.IsElf() {
   308  						elfRelocTyp = uint32(elf.R_X86_64_GLOB_DAT)
   309  					}
   310  					ld.AddGotSym(target, ldr, syms, targ, elfRelocTyp)
   311  					su.SetRelocSym(rIdx, syms.GOT)
   312  					su.SetRelocAdd(rIdx, int64(ldr.SymGot(targ)))
   313  				} else {
   314  					su.SetRelocType(rIdx, objabi.R_GOTPCREL)
   315  				}
   316  				return true
   317  			}
   318  			ldr.Errorf(s, "unexpected R_PCREL reloc for dynamic symbol %s: not preceded by LEAQ instruction", ldr.SymName(targ))
   319  		}
   320  
   321  	case objabi.R_ADDR:
   322  		if ldr.SymType(s).IsText() && target.IsElf() {
   323  			su := ldr.MakeSymbolUpdater(s)
   324  			if target.IsSolaris() {
   325  				addpltsym(target, ldr, syms, targ)
   326  				su.SetRelocSym(rIdx, syms.PLT)
   327  				su.SetRelocAdd(rIdx, r.Add()+int64(ldr.SymPlt(targ)))
   328  				return true
   329  			}
   330  			// The code is asking for the address of an external
   331  			// function. We provide it with the address of the
   332  			// correspondent GOT symbol.
   333  			ld.AddGotSym(target, ldr, syms, targ, uint32(elf.R_X86_64_GLOB_DAT))
   334  
   335  			su.SetRelocSym(rIdx, syms.GOT)
   336  			su.SetRelocAdd(rIdx, r.Add()+int64(ldr.SymGot(targ)))
   337  			return true
   338  		}
   339  
   340  		// Process dynamic relocations for the data sections.
   341  		if target.IsPIE() && target.IsInternal() {
   342  			// When internally linking, generate dynamic relocations
   343  			// for all typical R_ADDR relocations. The exception
   344  			// are those R_ADDR that are created as part of generating
   345  			// the dynamic relocations and must be resolved statically.
   346  			//
   347  			// There are three phases relevant to understanding this:
   348  			//
   349  			//	dodata()  // we are here
   350  			//	address() // symbol address assignment
   351  			//	reloc()   // resolution of static R_ADDR relocs
   352  			//
   353  			// At this point symbol addresses have not been
   354  			// assigned yet (as the final size of the .rela section
   355  			// will affect the addresses), and so we cannot write
   356  			// the Elf64_Rela.r_offset now. Instead we delay it
   357  			// until after the 'address' phase of the linker is
   358  			// complete. We do this via Addaddrplus, which creates
   359  			// a new R_ADDR relocation which will be resolved in
   360  			// the 'reloc' phase.
   361  			//
   362  			// These synthetic static R_ADDR relocs must be skipped
   363  			// now, or else we will be caught in an infinite loop
   364  			// of generating synthetic relocs for our synthetic
   365  			// relocs.
   366  			//
   367  			// Furthermore, the rela sections contain dynamic
   368  			// relocations with R_ADDR relocations on
   369  			// Elf64_Rela.r_offset. This field should contain the
   370  			// symbol offset as determined by reloc(), not the
   371  			// final dynamically linked address as a dynamic
   372  			// relocation would provide.
   373  			switch ldr.SymName(s) {
   374  			case ".dynsym", ".rela", ".rela.plt", ".got.plt", ".dynamic":
   375  				return false
   376  			}
   377  		} else {
   378  			// Either internally linking a static executable,
   379  			// in which case we can resolve these relocations
   380  			// statically in the 'reloc' phase, or externally
   381  			// linking, in which case the relocation will be
   382  			// prepared in the 'reloc' phase and passed to the
   383  			// external linker in the 'asmb' phase.
   384  			if t := ldr.SymType(s); !t.IsDATA() && !t.IsNOPTRDATA() && !t.IsRODATA() {
   385  				break
   386  			}
   387  		}
   388  
   389  		if target.IsElf() {
   390  			rela := ldr.MakeSymbolUpdater(syms.Rela)
   391  			rela.AddAddrPlus(target.Arch, s, int64(r.Off()))
   392  			if r.Siz() != 8 {
   393  				ldr.Errorf(s, "unexpected relocation for dynamic symbol %s", ldr.SymName(targ))
   394  			}
   395  
   396  			if targType == sym.SDYNIMPORT {
   397  				ld.Adddynsym(ldr, target, syms, targ)
   398  				rela.AddUint64(target.Arch, elf.R_INFO(uint32(ldr.SymDynid(targ)), uint32(elf.R_X86_64_64)))
   399  				rela.AddUint64(target.Arch, uint64(r.Add()))
   400  				su := ldr.MakeSymbolUpdater(s)
   401  				su.SetRelocType(rIdx, objabi.ElfRelocOffset)
   402  				return true
   403  			}
   404  
   405  			// Generate R_X86_64_RELATIVE relocations for best
   406  			// efficiency in the dynamic linker.
   407  			//
   408  			// As noted above, symbol addresses have not been
   409  			// assigned yet, so we can't generate the final reloc
   410  			// entry yet. We ultimately want:
   411  			//
   412  			// r_offset = s + r.Off
   413  			// r_info = R_X86_64_RELATIVE
   414  			// r_addend = targ + r.Add
   415  			//
   416  			// The dynamic linker will set *offset = base address +
   417  			// addend.
   418  			//
   419  			// AddAddrPlus is used for r_offset and r_addend to
   420  			// generate new R_ADDR relocations that will update
   421  			// these fields in the 'reloc' phase.
   422  			rela.AddUint64(target.Arch, elf.R_INFO(0, uint32(elf.R_X86_64_RELATIVE)))
   423  			rela.AddAddrPlus(target.Arch, targ, r.Add())
   424  			// Not mark r done here. So we still apply it statically,
   425  			// so in the file content we'll also have the right offset
   426  			// to the relocation target. So it can be examined statically
   427  			// (e.g. go version).
   428  			return true
   429  		}
   430  
   431  		if target.IsDarwin() {
   432  			// Mach-O relocations are a royal pain to lay out.
   433  			// They use a compact stateful bytecode representation.
   434  			// Here we record what are needed and encode them later.
   435  			if targType == sym.SDYNIMPORT {
   436  				// Dynamic import: the pointer must be bound by
   437  				// the dynamic linker at load time.
   438  				ld.MachoAddBind(s, int64(r.Off()), targ)
   439  			} else {
   440  				ld.MachoAddRebase(s, int64(r.Off()))
   441  			}
   442  			// Not mark r done here. So we still apply it statically,
   443  			// so in the file content we'll also have the right offset
   444  			// to the relocation target. So it can be examined statically
   445  			// (e.g. go version).
   446  			return true
   447  		}
   448  	case objabi.R_GOTPCREL:
   449  		if target.IsExternal() {
   450  			// External linker will do this relocation.
   451  			return true
   452  		}
   453  		// We only need to handle external linking mode, as R_GOTPCREL can
   454  		// only occur in plugin or shared build modes.
   455  	}
   456  
   457  	return false
   458  }
   459  
   460  func elfreloc1(ctxt *ld.Link, out *ld.OutBuf, ldr *loader.Loader, s loader.Sym, r loader.ExtReloc, ri int, sectoff int64) bool {
   461  	out.Write64(uint64(sectoff))
   462  
   463  	elfsym := ld.ElfSymForReloc(ctxt, r.Xsym)
   464  	siz := r.Size
   465  	switch r.Type {
   466  	default:
   467  		return false
   468  	case objabi.R_ADDR, objabi.R_DWARFSECREF:
   469  		if siz == 4 {
   470  			out.Write64(uint64(elf.R_X86_64_32) | uint64(elfsym)<<32)
   471  		} else if siz == 8 {
   472  			out.Write64(uint64(elf.R_X86_64_64) | uint64(elfsym)<<32)
   473  		} else {
   474  			return false
   475  		}
   476  	case objabi.R_TLS_LE:
   477  		if siz == 4 {
   478  			out.Write64(uint64(elf.R_X86_64_TPOFF32) | uint64(elfsym)<<32)
   479  		} else {
   480  			return false
   481  		}
   482  	case objabi.R_TLS_IE:
   483  		if siz == 4 {
   484  			out.Write64(uint64(elf.R_X86_64_GOTTPOFF) | uint64(elfsym)<<32)
   485  		} else {
   486  			return false
   487  		}
   488  	case objabi.R_CALL:
   489  		if siz == 4 {
   490  			if ldr.SymType(r.Xsym) == sym.SDYNIMPORT {
   491  				out.Write64(uint64(elf.R_X86_64_PLT32) | uint64(elfsym)<<32)
   492  			} else {
   493  				out.Write64(uint64(elf.R_X86_64_PC32) | uint64(elfsym)<<32)
   494  			}
   495  		} else {
   496  			return false
   497  		}
   498  	case objabi.R_PCREL:
   499  		if siz == 4 {
   500  			if ldr.SymType(r.Xsym) == sym.SDYNIMPORT && ldr.SymElfType(r.Xsym) == elf.STT_FUNC {
   501  				out.Write64(uint64(elf.R_X86_64_PLT32) | uint64(elfsym)<<32)
   502  			} else {
   503  				out.Write64(uint64(elf.R_X86_64_PC32) | uint64(elfsym)<<32)
   504  			}
   505  		} else {
   506  			return false
   507  		}
   508  	case objabi.R_GOTPCREL:
   509  		if siz == 4 {
   510  			out.Write64(uint64(elf.R_X86_64_GOTPCREL) | uint64(elfsym)<<32)
   511  		} else {
   512  			return false
   513  		}
   514  	}
   515  
   516  	out.Write64(uint64(r.Xadd))
   517  	return true
   518  }
   519  
   520  func machoreloc1(arch *sys.Arch, out *ld.OutBuf, ldr *loader.Loader, s loader.Sym, r loader.ExtReloc, sectoff int64) bool {
   521  	var v uint32
   522  
   523  	rs := r.Xsym
   524  	rt := r.Type
   525  
   526  	if !ldr.SymType(s).IsDWARF() {
   527  		if ldr.SymDynid(rs) < 0 {
   528  			ldr.Errorf(s, "reloc %d (%s) to non-macho symbol %s type=%d (%s)", rt, sym.RelocName(arch, rt), ldr.SymName(rs), ldr.SymType(rs), ldr.SymType(rs))
   529  			return false
   530  		}
   531  
   532  		v = uint32(ldr.SymDynid(rs))
   533  		v |= 1 << 27 // external relocation
   534  	} else {
   535  		v = uint32(ldr.SymSect(rs).Extnum)
   536  		if v == 0 {
   537  			ldr.Errorf(s, "reloc %d (%s) to symbol %s in non-macho section %s type=%d (%s)", rt, sym.RelocName(arch, rt), ldr.SymName(rs), ldr.SymSect(rs).Name, ldr.SymType(rs), ldr.SymType(rs))
   538  			return false
   539  		}
   540  	}
   541  
   542  	switch rt {
   543  	default:
   544  		return false
   545  
   546  	case objabi.R_ADDR:
   547  		v |= ld.MACHO_X86_64_RELOC_UNSIGNED << 28
   548  
   549  	case objabi.R_CALL:
   550  		v |= 1 << 24 // pc-relative bit
   551  		v |= ld.MACHO_X86_64_RELOC_BRANCH << 28
   552  
   553  		// NOTE: Only works with 'external' relocation. Forced above.
   554  	case objabi.R_PCREL:
   555  		v |= 1 << 24 // pc-relative bit
   556  		v |= ld.MACHO_X86_64_RELOC_SIGNED << 28
   557  	case objabi.R_GOTPCREL:
   558  		v |= 1 << 24 // pc-relative bit
   559  		v |= ld.MACHO_X86_64_RELOC_GOT_LOAD << 28
   560  	}
   561  
   562  	switch r.Size {
   563  	default:
   564  		return false
   565  
   566  	case 1:
   567  		v |= 0 << 25
   568  
   569  	case 2:
   570  		v |= 1 << 25
   571  
   572  	case 4:
   573  		v |= 2 << 25
   574  
   575  	case 8:
   576  		v |= 3 << 25
   577  	}
   578  
   579  	out.Write32(uint32(sectoff))
   580  	out.Write32(v)
   581  	return true
   582  }
   583  
   584  func pereloc1(arch *sys.Arch, out *ld.OutBuf, ldr *loader.Loader, s loader.Sym, r loader.ExtReloc, sectoff int64) bool {
   585  	var v uint32
   586  
   587  	rs := r.Xsym
   588  	rt := r.Type
   589  
   590  	if ldr.SymDynid(rs) < 0 {
   591  		ldr.Errorf(s, "reloc %d (%s) to non-coff symbol %s type=%d (%s)", rt, sym.RelocName(arch, rt), ldr.SymName(rs), ldr.SymType(rs), ldr.SymType(rs))
   592  		return false
   593  	}
   594  
   595  	out.Write32(uint32(sectoff))
   596  	out.Write32(uint32(ldr.SymDynid(rs)))
   597  
   598  	switch rt {
   599  	default:
   600  		return false
   601  
   602  	case objabi.R_ADDROFF, objabi.R_DWARFSECREF:
   603  		v = ld.IMAGE_REL_AMD64_SECREL
   604  
   605  	case objabi.R_ADDR:
   606  		if r.Size == 8 {
   607  			v = ld.IMAGE_REL_AMD64_ADDR64
   608  		} else {
   609  			v = ld.IMAGE_REL_AMD64_ADDR32
   610  		}
   611  
   612  	case objabi.R_PEIMAGEOFF:
   613  		v = ld.IMAGE_REL_AMD64_ADDR32NB
   614  
   615  	case objabi.R_CALL,
   616  		objabi.R_PCREL:
   617  		v = ld.IMAGE_REL_AMD64_REL32
   618  	}
   619  
   620  	out.Write16(uint16(v))
   621  
   622  	return true
   623  }
   624  
   625  func archreloc(*ld.Target, *loader.Loader, *ld.ArchSyms, loader.Reloc, loader.Sym, int64) (int64, int, bool) {
   626  	return -1, 0, false
   627  }
   628  
   629  func archrelocvariant(*ld.Target, *loader.Loader, loader.Reloc, sym.RelocVariant, loader.Sym, int64, []byte) int64 {
   630  	log.Fatalf("unexpected relocation variant")
   631  	return -1
   632  }
   633  
   634  func elfsetupplt(ctxt *ld.Link, ldr *loader.Loader, plt, got *loader.SymbolBuilder, dynamic loader.Sym) {
   635  	if plt.Size() == 0 {
   636  		// pushq got+8(IP)
   637  		plt.AddUint8(0xff)
   638  
   639  		plt.AddUint8(0x35)
   640  		plt.AddPCRelPlus(ctxt.Arch, got.Sym(), 8)
   641  
   642  		// jmpq got+16(IP)
   643  		plt.AddUint8(0xff)
   644  
   645  		plt.AddUint8(0x25)
   646  		plt.AddPCRelPlus(ctxt.Arch, got.Sym(), 16)
   647  
   648  		// nopl 0(AX)
   649  		plt.AddUint32(ctxt.Arch, 0x00401f0f)
   650  
   651  		// assume got->size == 0 too
   652  		got.AddAddrPlus(ctxt.Arch, dynamic, 0)
   653  
   654  		got.AddUint64(ctxt.Arch, 0)
   655  		got.AddUint64(ctxt.Arch, 0)
   656  	}
   657  }
   658  
   659  func addpltsym(target *ld.Target, ldr *loader.Loader, syms *ld.ArchSyms, s loader.Sym) {
   660  	if ldr.SymPlt(s) >= 0 {
   661  		return
   662  	}
   663  
   664  	ld.Adddynsym(ldr, target, syms, s)
   665  
   666  	if target.IsElf() {
   667  		plt := ldr.MakeSymbolUpdater(syms.PLT)
   668  		got := ldr.MakeSymbolUpdater(syms.GOTPLT)
   669  		rela := ldr.MakeSymbolUpdater(syms.RelaPLT)
   670  		if plt.Size() == 0 {
   671  			panic("plt is not set up")
   672  		}
   673  
   674  		// jmpq *got+size(IP)
   675  		plt.AddUint8(0xff)
   676  
   677  		plt.AddUint8(0x25)
   678  		plt.AddPCRelPlus(target.Arch, got.Sym(), got.Size())
   679  
   680  		// add to got: pointer to current pos in plt
   681  		got.AddAddrPlus(target.Arch, plt.Sym(), plt.Size())
   682  
   683  		// pushq $x
   684  		plt.AddUint8(0x68)
   685  
   686  		plt.AddUint32(target.Arch, uint32((got.Size()-24-8)/8))
   687  
   688  		// jmpq .plt
   689  		plt.AddUint8(0xe9)
   690  
   691  		plt.AddUint32(target.Arch, uint32(-(plt.Size() + 4)))
   692  
   693  		// rela
   694  		rela.AddAddrPlus(target.Arch, got.Sym(), got.Size()-8)
   695  
   696  		sDynid := ldr.SymDynid(s)
   697  		rela.AddUint64(target.Arch, elf.R_INFO(uint32(sDynid), uint32(elf.R_X86_64_JMP_SLOT)))
   698  		rela.AddUint64(target.Arch, 0)
   699  
   700  		ldr.SetPlt(s, int32(plt.Size()-16))
   701  	} else if target.IsDarwin() {
   702  		ld.AddGotSym(target, ldr, syms, s, 0)
   703  
   704  		sDynid := ldr.SymDynid(s)
   705  		lep := ldr.MakeSymbolUpdater(syms.LinkEditPLT)
   706  		lep.AddUint32(target.Arch, uint32(sDynid))
   707  
   708  		plt := ldr.MakeSymbolUpdater(syms.PLT)
   709  		ldr.SetPlt(s, int32(plt.Size()))
   710  
   711  		// jmpq *got+size(IP)
   712  		plt.AddUint8(0xff)
   713  		plt.AddUint8(0x25)
   714  		plt.AddPCRelPlus(target.Arch, syms.GOT, int64(ldr.SymGot(s)))
   715  	} else {
   716  		ldr.Errorf(s, "addpltsym: unsupported binary format")
   717  	}
   718  }
   719  
   720  func tlsIEtoLE(P []byte, off, size int) {
   721  	// Transform the PC-relative instruction into a constant load.
   722  	// That is,
   723  	//
   724  	//	MOVQ X(IP), REG  ->  MOVQ $Y, REG
   725  	//
   726  	// To determine the instruction and register, we study the op codes.
   727  	// Consult an AMD64 instruction encoding guide to decipher this.
   728  	if off < 3 {
   729  		log.Fatal("R_X86_64_GOTTPOFF reloc not preceded by MOVQ or ADDQ instruction")
   730  	}
   731  	op := P[off-3 : off]
   732  	reg := op[2] >> 3
   733  
   734  	if op[1] == 0x8b || reg == 4 {
   735  		// MOVQ
   736  		if op[0] == 0x4c {
   737  			op[0] = 0x49
   738  		} else if size == 4 && op[0] == 0x44 {
   739  			op[0] = 0x41
   740  		}
   741  		if op[1] == 0x8b {
   742  			op[1] = 0xc7
   743  		} else {
   744  			op[1] = 0x81 // special case for SP
   745  		}
   746  		op[2] = 0xc0 | reg
   747  	} else {
   748  		// An alternate op is ADDQ. This is handled by GNU gold,
   749  		// but right now is not generated by the Go compiler:
   750  		//	ADDQ X(IP), REG  ->  ADDQ $Y, REG
   751  		// Consider adding support for it here.
   752  		log.Fatalf("expected TLS IE op to be MOVQ, got %v", op)
   753  	}
   754  }
   755  

View as plain text