Source file src/cmd/link/internal/loadpe/ldpe.go

     1  // Copyright 2010 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package loadpe implements a PE/COFF file reader.
     6  package loadpe
     7  
     8  import (
     9  	"bytes"
    10  	"cmd/internal/bio"
    11  	"cmd/internal/objabi"
    12  	"cmd/internal/sys"
    13  	"cmd/link/internal/loader"
    14  	"cmd/link/internal/sym"
    15  	"debug/pe"
    16  	"encoding/binary"
    17  	"errors"
    18  	"fmt"
    19  	"io"
    20  	"strings"
    21  )
    22  
    23  const (
    24  	// TODO: the Microsoft doco says IMAGE_SYM_DTYPE_ARRAY is 3 (same with IMAGE_SYM_DTYPE_POINTER and IMAGE_SYM_DTYPE_FUNCTION)
    25  	IMAGE_SYM_UNDEFINED              = 0
    26  	IMAGE_SYM_ABSOLUTE               = -1
    27  	IMAGE_SYM_DEBUG                  = -2
    28  	IMAGE_SYM_TYPE_NULL              = 0
    29  	IMAGE_SYM_TYPE_VOID              = 1
    30  	IMAGE_SYM_TYPE_CHAR              = 2
    31  	IMAGE_SYM_TYPE_SHORT             = 3
    32  	IMAGE_SYM_TYPE_INT               = 4
    33  	IMAGE_SYM_TYPE_LONG              = 5
    34  	IMAGE_SYM_TYPE_FLOAT             = 6
    35  	IMAGE_SYM_TYPE_DOUBLE            = 7
    36  	IMAGE_SYM_TYPE_STRUCT            = 8
    37  	IMAGE_SYM_TYPE_UNION             = 9
    38  	IMAGE_SYM_TYPE_ENUM              = 10
    39  	IMAGE_SYM_TYPE_MOE               = 11
    40  	IMAGE_SYM_TYPE_BYTE              = 12
    41  	IMAGE_SYM_TYPE_WORD              = 13
    42  	IMAGE_SYM_TYPE_UINT              = 14
    43  	IMAGE_SYM_TYPE_DWORD             = 15
    44  	IMAGE_SYM_TYPE_PCODE             = 32768
    45  	IMAGE_SYM_DTYPE_NULL             = 0
    46  	IMAGE_SYM_DTYPE_POINTER          = 0x10
    47  	IMAGE_SYM_DTYPE_FUNCTION         = 0x20
    48  	IMAGE_SYM_DTYPE_ARRAY            = 0x30
    49  	IMAGE_SYM_CLASS_END_OF_FUNCTION  = -1
    50  	IMAGE_SYM_CLASS_NULL             = 0
    51  	IMAGE_SYM_CLASS_AUTOMATIC        = 1
    52  	IMAGE_SYM_CLASS_EXTERNAL         = 2
    53  	IMAGE_SYM_CLASS_STATIC           = 3
    54  	IMAGE_SYM_CLASS_REGISTER         = 4
    55  	IMAGE_SYM_CLASS_EXTERNAL_DEF     = 5
    56  	IMAGE_SYM_CLASS_LABEL            = 6
    57  	IMAGE_SYM_CLASS_UNDEFINED_LABEL  = 7
    58  	IMAGE_SYM_CLASS_MEMBER_OF_STRUCT = 8
    59  	IMAGE_SYM_CLASS_ARGUMENT         = 9
    60  	IMAGE_SYM_CLASS_STRUCT_TAG       = 10
    61  	IMAGE_SYM_CLASS_MEMBER_OF_UNION  = 11
    62  	IMAGE_SYM_CLASS_UNION_TAG        = 12
    63  	IMAGE_SYM_CLASS_TYPE_DEFINITION  = 13
    64  	IMAGE_SYM_CLASS_UNDEFINED_STATIC = 14
    65  	IMAGE_SYM_CLASS_ENUM_TAG         = 15
    66  	IMAGE_SYM_CLASS_MEMBER_OF_ENUM   = 16
    67  	IMAGE_SYM_CLASS_REGISTER_PARAM   = 17
    68  	IMAGE_SYM_CLASS_BIT_FIELD        = 18
    69  	IMAGE_SYM_CLASS_FAR_EXTERNAL     = 68 /* Not in PECOFF v8 spec */
    70  	IMAGE_SYM_CLASS_BLOCK            = 100
    71  	IMAGE_SYM_CLASS_FUNCTION         = 101
    72  	IMAGE_SYM_CLASS_END_OF_STRUCT    = 102
    73  	IMAGE_SYM_CLASS_FILE             = 103
    74  	IMAGE_SYM_CLASS_SECTION          = 104
    75  	IMAGE_SYM_CLASS_WEAK_EXTERNAL    = 105
    76  	IMAGE_SYM_CLASS_CLR_TOKEN        = 107
    77  	IMAGE_REL_I386_ABSOLUTE          = 0x0000
    78  	IMAGE_REL_I386_DIR16             = 0x0001
    79  	IMAGE_REL_I386_REL16             = 0x0002
    80  	IMAGE_REL_I386_DIR32             = 0x0006
    81  	IMAGE_REL_I386_DIR32NB           = 0x0007
    82  	IMAGE_REL_I386_SEG12             = 0x0009
    83  	IMAGE_REL_I386_SECTION           = 0x000A
    84  	IMAGE_REL_I386_SECREL            = 0x000B
    85  	IMAGE_REL_I386_TOKEN             = 0x000C
    86  	IMAGE_REL_I386_SECREL7           = 0x000D
    87  	IMAGE_REL_I386_REL32             = 0x0014
    88  	IMAGE_REL_AMD64_ABSOLUTE         = 0x0000
    89  	IMAGE_REL_AMD64_ADDR64           = 0x0001
    90  	IMAGE_REL_AMD64_ADDR32           = 0x0002
    91  	IMAGE_REL_AMD64_ADDR32NB         = 0x0003
    92  	IMAGE_REL_AMD64_REL32            = 0x0004
    93  	IMAGE_REL_AMD64_REL32_1          = 0x0005
    94  	IMAGE_REL_AMD64_REL32_2          = 0x0006
    95  	IMAGE_REL_AMD64_REL32_3          = 0x0007
    96  	IMAGE_REL_AMD64_REL32_4          = 0x0008
    97  	IMAGE_REL_AMD64_REL32_5          = 0x0009
    98  	IMAGE_REL_AMD64_SECTION          = 0x000A
    99  	IMAGE_REL_AMD64_SECREL           = 0x000B
   100  	IMAGE_REL_AMD64_SECREL7          = 0x000C
   101  	IMAGE_REL_AMD64_TOKEN            = 0x000D
   102  	IMAGE_REL_AMD64_SREL32           = 0x000E
   103  	IMAGE_REL_AMD64_PAIR             = 0x000F
   104  	IMAGE_REL_AMD64_SSPAN32          = 0x0010
   105  	IMAGE_REL_ARM_ABSOLUTE           = 0x0000
   106  	IMAGE_REL_ARM_ADDR32             = 0x0001
   107  	IMAGE_REL_ARM_ADDR32NB           = 0x0002
   108  	IMAGE_REL_ARM_BRANCH24           = 0x0003
   109  	IMAGE_REL_ARM_BRANCH11           = 0x0004
   110  	IMAGE_REL_ARM_SECTION            = 0x000E
   111  	IMAGE_REL_ARM_SECREL             = 0x000F
   112  	IMAGE_REL_ARM_MOV32              = 0x0010
   113  	IMAGE_REL_THUMB_MOV32            = 0x0011
   114  	IMAGE_REL_THUMB_BRANCH20         = 0x0012
   115  	IMAGE_REL_THUMB_BRANCH24         = 0x0014
   116  	IMAGE_REL_THUMB_BLX23            = 0x0015
   117  	IMAGE_REL_ARM_PAIR               = 0x0016
   118  	IMAGE_REL_ARM64_ABSOLUTE         = 0x0000
   119  	IMAGE_REL_ARM64_ADDR32           = 0x0001
   120  	IMAGE_REL_ARM64_ADDR32NB         = 0x0002
   121  	IMAGE_REL_ARM64_BRANCH26         = 0x0003
   122  	IMAGE_REL_ARM64_PAGEBASE_REL21   = 0x0004
   123  	IMAGE_REL_ARM64_REL21            = 0x0005
   124  	IMAGE_REL_ARM64_PAGEOFFSET_12A   = 0x0006
   125  	IMAGE_REL_ARM64_PAGEOFFSET_12L   = 0x0007
   126  	IMAGE_REL_ARM64_SECREL           = 0x0008
   127  	IMAGE_REL_ARM64_SECREL_LOW12A    = 0x0009
   128  	IMAGE_REL_ARM64_SECREL_HIGH12A   = 0x000A
   129  	IMAGE_REL_ARM64_SECREL_LOW12L    = 0x000B
   130  	IMAGE_REL_ARM64_TOKEN            = 0x000C
   131  	IMAGE_REL_ARM64_SECTION          = 0x000D
   132  	IMAGE_REL_ARM64_ADDR64           = 0x000E
   133  	IMAGE_REL_ARM64_BRANCH19         = 0x000F
   134  	IMAGE_REL_ARM64_BRANCH14         = 0x0010
   135  	IMAGE_REL_ARM64_REL32            = 0x0011
   136  )
   137  
   138  // TODO(crawshaw): de-duplicate these symbols with cmd/internal/ld, ideally in debug/pe.
   139  const (
   140  	IMAGE_SCN_CNT_CODE               = 0x00000020
   141  	IMAGE_SCN_CNT_INITIALIZED_DATA   = 0x00000040
   142  	IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080
   143  	IMAGE_SCN_MEM_DISCARDABLE        = 0x02000000
   144  	IMAGE_SCN_MEM_EXECUTE            = 0x20000000
   145  	IMAGE_SCN_MEM_READ               = 0x40000000
   146  	IMAGE_SCN_MEM_WRITE              = 0x80000000
   147  )
   148  
   149  // TODO(brainman): maybe just add ReadAt method to bio.Reader instead of creating peBiobuf
   150  
   151  // peBiobuf makes bio.Reader look like io.ReaderAt.
   152  type peBiobuf bio.Reader
   153  
   154  func (f *peBiobuf) ReadAt(p []byte, off int64) (int, error) {
   155  	ret := ((*bio.Reader)(f)).MustSeek(off, 0)
   156  	if ret < 0 {
   157  		return 0, errors.New("fail to seek")
   158  	}
   159  	n, err := f.Read(p)
   160  	if err != nil {
   161  		return 0, err
   162  	}
   163  	return n, nil
   164  }
   165  
   166  // makeUpdater creates a loader.SymbolBuilder if one hasn't been created previously.
   167  // We use this to lazily make SymbolBuilders as we don't always need a builder, and creating them for all symbols might be an error.
   168  func makeUpdater(l *loader.Loader, bld *loader.SymbolBuilder, s loader.Sym) *loader.SymbolBuilder {
   169  	if bld != nil {
   170  		return bld
   171  	}
   172  	bld = l.MakeSymbolUpdater(s)
   173  	return bld
   174  }
   175  
   176  // Load loads the PE file pn from input.
   177  // Symbols are written into syms, and a slice of the text symbols is returned.
   178  // If an .rsrc section or set of .rsrc$xx sections is found, its symbols are
   179  // returned as rsrc.
   180  func Load(l *loader.Loader, arch *sys.Arch, localSymVersion int, input *bio.Reader, pkg string, length int64, pn string) (textp []loader.Sym, rsrc []loader.Sym, err error) {
   181  	lookup := l.LookupOrCreateCgoExport
   182  	sectsyms := make(map[*pe.Section]loader.Sym)
   183  	sectdata := make(map[*pe.Section][]byte)
   184  
   185  	// Some input files are archives containing multiple of
   186  	// object files, and pe.NewFile seeks to the start of
   187  	// input file and get confused. Create section reader
   188  	// to stop pe.NewFile looking before current position.
   189  	sr := io.NewSectionReader((*peBiobuf)(input), input.Offset(), 1<<63-1)
   190  
   191  	// TODO: replace pe.NewFile with pe.Load (grep for "add Load function" in debug/pe for details)
   192  	f, err := pe.NewFile(sr)
   193  	if err != nil {
   194  		return nil, nil, err
   195  	}
   196  	defer f.Close()
   197  
   198  	// TODO return error if found .cormeta
   199  
   200  	// create symbols for mapped sections
   201  	for _, sect := range f.Sections {
   202  		if sect.Characteristics&IMAGE_SCN_MEM_DISCARDABLE != 0 {
   203  			continue
   204  		}
   205  
   206  		if sect.Characteristics&(IMAGE_SCN_CNT_CODE|IMAGE_SCN_CNT_INITIALIZED_DATA|IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 {
   207  			// This has been seen for .idata sections, which we
   208  			// want to ignore. See issues 5106 and 5273.
   209  			continue
   210  		}
   211  
   212  		name := fmt.Sprintf("%s(%s)", pkg, sect.Name)
   213  		s := lookup(name, localSymVersion)
   214  		bld := l.MakeSymbolUpdater(s)
   215  
   216  		switch sect.Characteristics & (IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE) {
   217  		case IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ: //.rdata
   218  			bld.SetType(sym.SRODATA)
   219  
   220  		case IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE: //.bss
   221  			bld.SetType(sym.SNOPTRBSS)
   222  
   223  		case IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE: //.data
   224  			bld.SetType(sym.SNOPTRDATA)
   225  
   226  		case IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ: //.text
   227  			bld.SetType(sym.STEXT)
   228  
   229  		default:
   230  			return nil, nil, fmt.Errorf("unexpected flags %#06x for PE section %s", sect.Characteristics, sect.Name)
   231  		}
   232  
   233  		if bld.Type() != sym.SNOPTRBSS {
   234  			data, err := sect.Data()
   235  			if err != nil {
   236  				return nil, nil, err
   237  			}
   238  			sectdata[sect] = data
   239  			bld.SetData(data)
   240  		}
   241  		bld.SetSize(int64(sect.Size))
   242  		sectsyms[sect] = s
   243  		if sect.Name == ".rsrc" || strings.HasPrefix(sect.Name, ".rsrc$") {
   244  			rsrc = append(rsrc, s)
   245  		}
   246  	}
   247  
   248  	// load relocations
   249  	for _, rsect := range f.Sections {
   250  		if _, found := sectsyms[rsect]; !found {
   251  			continue
   252  		}
   253  		if rsect.NumberOfRelocations == 0 {
   254  			continue
   255  		}
   256  		if rsect.Characteristics&IMAGE_SCN_MEM_DISCARDABLE != 0 {
   257  			continue
   258  		}
   259  		if rsect.Characteristics&(IMAGE_SCN_CNT_CODE|IMAGE_SCN_CNT_INITIALIZED_DATA|IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 {
   260  			// This has been seen for .idata sections, which we
   261  			// want to ignore. See issues 5106 and 5273.
   262  			continue
   263  		}
   264  
   265  		splitResources := strings.HasPrefix(rsect.Name, ".rsrc$")
   266  		sb := l.MakeSymbolUpdater(sectsyms[rsect])
   267  		for j, r := range rsect.Relocs {
   268  			if int(r.SymbolTableIndex) >= len(f.COFFSymbols) {
   269  				return nil, nil, fmt.Errorf("relocation number %d symbol index idx=%d cannot be large then number of symbols %d", j, r.SymbolTableIndex, len(f.COFFSymbols))
   270  			}
   271  			pesym := &f.COFFSymbols[r.SymbolTableIndex]
   272  			_, gosym, err := readpesym(l, arch, lookup, f, pesym, sectsyms, localSymVersion)
   273  			if err != nil {
   274  				return nil, nil, err
   275  			}
   276  			if gosym == 0 {
   277  				name, err := pesym.FullName(f.StringTable)
   278  				if err != nil {
   279  					name = string(pesym.Name[:])
   280  				}
   281  				return nil, nil, fmt.Errorf("reloc of invalid sym %s idx=%d type=%d", name, r.SymbolTableIndex, pesym.Type)
   282  			}
   283  
   284  			rSym := gosym
   285  			rSize := uint8(4)
   286  			rOff := int32(r.VirtualAddress)
   287  			var rAdd int64
   288  			var rType objabi.RelocType
   289  			switch arch.Family {
   290  			default:
   291  				return nil, nil, fmt.Errorf("%s: unsupported arch %v", pn, arch.Family)
   292  			case sys.I386, sys.AMD64:
   293  				switch r.Type {
   294  				default:
   295  					return nil, nil, fmt.Errorf("%s: %v: unknown relocation type %v", pn, sectsyms[rsect], r.Type)
   296  
   297  				case IMAGE_REL_I386_REL32, IMAGE_REL_AMD64_REL32,
   298  					IMAGE_REL_AMD64_ADDR32, // R_X86_64_PC32
   299  					IMAGE_REL_AMD64_ADDR32NB:
   300  					rType = objabi.R_PCREL
   301  
   302  					rAdd = int64(int32(binary.LittleEndian.Uint32(sectdata[rsect][rOff:])))
   303  
   304  				case IMAGE_REL_I386_DIR32NB, IMAGE_REL_I386_DIR32:
   305  					rType = objabi.R_ADDR
   306  
   307  					// load addend from image
   308  					rAdd = int64(int32(binary.LittleEndian.Uint32(sectdata[rsect][rOff:])))
   309  
   310  				case IMAGE_REL_AMD64_ADDR64: // R_X86_64_64
   311  					rSize = 8
   312  
   313  					rType = objabi.R_ADDR
   314  
   315  					// load addend from image
   316  					rAdd = int64(binary.LittleEndian.Uint64(sectdata[rsect][rOff:]))
   317  				}
   318  
   319  			case sys.ARM:
   320  				switch r.Type {
   321  				default:
   322  					return nil, nil, fmt.Errorf("%s: %v: unknown ARM relocation type %v", pn, sectsyms[rsect], r.Type)
   323  
   324  				case IMAGE_REL_ARM_SECREL:
   325  					rType = objabi.R_PCREL
   326  
   327  					rAdd = int64(int32(binary.LittleEndian.Uint32(sectdata[rsect][rOff:])))
   328  
   329  				case IMAGE_REL_ARM_ADDR32, IMAGE_REL_ARM_ADDR32NB:
   330  					rType = objabi.R_ADDR
   331  
   332  					rAdd = int64(int32(binary.LittleEndian.Uint32(sectdata[rsect][rOff:])))
   333  
   334  				case IMAGE_REL_ARM_BRANCH24:
   335  					rType = objabi.R_CALLARM
   336  
   337  					rAdd = int64(int32(binary.LittleEndian.Uint32(sectdata[rsect][rOff:])))
   338  				}
   339  
   340  			case sys.ARM64:
   341  				switch r.Type {
   342  				default:
   343  					return nil, nil, fmt.Errorf("%s: %v: unknown ARM64 relocation type %v", pn, sectsyms[rsect], r.Type)
   344  
   345  				case IMAGE_REL_ARM64_ADDR32, IMAGE_REL_ARM64_ADDR32NB:
   346  					rType = objabi.R_ADDR
   347  
   348  					rAdd = int64(int32(binary.LittleEndian.Uint32(sectdata[rsect][rOff:])))
   349  				}
   350  			}
   351  
   352  			// ld -r could generate multiple section symbols for the
   353  			// same section but with different values, we have to take
   354  			// that into account, or in the case of split resources,
   355  			// the section and its symbols are split into two sections.
   356  			if issect(pesym) || splitResources {
   357  				rAdd += int64(pesym.Value)
   358  			}
   359  
   360  			rel, _ := sb.AddRel(rType)
   361  			rel.SetOff(rOff)
   362  			rel.SetSiz(rSize)
   363  			rel.SetSym(rSym)
   364  			rel.SetAdd(rAdd)
   365  		}
   366  
   367  		sb.SortRelocs()
   368  	}
   369  
   370  	// enter sub-symbols into symbol table.
   371  	for i, numaux := 0, 0; i < len(f.COFFSymbols); i += numaux + 1 {
   372  		pesym := &f.COFFSymbols[i]
   373  
   374  		numaux = int(pesym.NumberOfAuxSymbols)
   375  
   376  		name, err := pesym.FullName(f.StringTable)
   377  		if err != nil {
   378  			return nil, nil, err
   379  		}
   380  		if name == "" {
   381  			continue
   382  		}
   383  		if issect(pesym) {
   384  			continue
   385  		}
   386  		if int(pesym.SectionNumber) > len(f.Sections) {
   387  			continue
   388  		}
   389  		if pesym.SectionNumber == IMAGE_SYM_DEBUG {
   390  			continue
   391  		}
   392  		if pesym.SectionNumber == IMAGE_SYM_ABSOLUTE && bytes.Equal(pesym.Name[:], []byte("@feat.00")) {
   393  			// Microsoft's linker looks at whether all input objects have an empty
   394  			// section called @feat.00. If all of them do, then it enables SEH;
   395  			// otherwise it doesn't enable that feature. So, since around the Windows
   396  			// XP SP2 era, most tools that make PE objects just tack on that section,
   397  			// so that it won't gimp Microsoft's linker logic. Go doesn't support SEH,
   398  			// so in theory, none of this really matters to us. But actually, if the
   399  			// linker tries to ingest an object with @feat.00 -- which are produced by
   400  			// LLVM's resource compiler, for example -- it chokes because of the
   401  			// IMAGE_SYM_ABSOLUTE section that it doesn't know how to deal with. Since
   402  			// @feat.00 is just a marking anyway, skip IMAGE_SYM_ABSOLUTE sections that
   403  			// are called @feat.00.
   404  			continue
   405  		}
   406  		var sect *pe.Section
   407  		if pesym.SectionNumber > 0 {
   408  			sect = f.Sections[pesym.SectionNumber-1]
   409  			if _, found := sectsyms[sect]; !found {
   410  				continue
   411  			}
   412  		}
   413  
   414  		bld, s, err := readpesym(l, arch, lookup, f, pesym, sectsyms, localSymVersion)
   415  		if err != nil {
   416  			return nil, nil, err
   417  		}
   418  
   419  		if pesym.SectionNumber == 0 { // extern
   420  			if l.SymType(s) == sym.SDYNIMPORT {
   421  				bld = makeUpdater(l, bld, s)
   422  				bld.SetPlt(-2) // flag for dynimport in PE object files.
   423  			}
   424  			if l.SymType(s) == sym.SXREF && pesym.Value > 0 { // global data
   425  				bld = makeUpdater(l, bld, s)
   426  				bld.SetType(sym.SNOPTRDATA)
   427  				bld.SetSize(int64(pesym.Value))
   428  			}
   429  
   430  			continue
   431  		} else if pesym.SectionNumber > 0 && int(pesym.SectionNumber) <= len(f.Sections) {
   432  			sect = f.Sections[pesym.SectionNumber-1]
   433  			if _, found := sectsyms[sect]; !found {
   434  				return nil, nil, fmt.Errorf("%s: %v: missing sect.sym", pn, s)
   435  			}
   436  		} else {
   437  			return nil, nil, fmt.Errorf("%s: %v: sectnum < 0!", pn, s)
   438  		}
   439  
   440  		if sect == nil {
   441  			return nil, nil, nil
   442  		}
   443  
   444  		if l.OuterSym(s) != 0 {
   445  			if l.AttrDuplicateOK(s) {
   446  				continue
   447  			}
   448  			outerName := l.SymName(l.OuterSym(s))
   449  			sectName := l.SymName(sectsyms[sect])
   450  			return nil, nil, fmt.Errorf("%s: duplicate symbol reference: %s in both %s and %s", pn, l.SymName(s), outerName, sectName)
   451  		}
   452  
   453  		bld = makeUpdater(l, bld, s)
   454  		sectsym := sectsyms[sect]
   455  		bld.SetType(l.SymType(sectsym))
   456  		l.AddInteriorSym(sectsym, s)
   457  		bld.SetValue(int64(pesym.Value))
   458  		bld.SetSize(4)
   459  		if l.SymType(sectsym) == sym.STEXT {
   460  			if bld.External() && !bld.DuplicateOK() {
   461  				return nil, nil, fmt.Errorf("%s: duplicate symbol definition", l.SymName(s))
   462  			}
   463  			bld.SetExternal(true)
   464  		}
   465  	}
   466  
   467  	// Sort outer lists by address, adding to textp.
   468  	// This keeps textp in increasing address order.
   469  	for _, sect := range f.Sections {
   470  		s := sectsyms[sect]
   471  		if s == 0 {
   472  			continue
   473  		}
   474  		l.SortSub(s)
   475  		if l.SymType(s) == sym.STEXT {
   476  			for ; s != 0; s = l.SubSym(s) {
   477  				if l.AttrOnList(s) {
   478  					return nil, nil, fmt.Errorf("symbol %s listed multiple times", l.SymName(s))
   479  				}
   480  				l.SetAttrOnList(s, true)
   481  				textp = append(textp, s)
   482  			}
   483  		}
   484  	}
   485  
   486  	return textp, rsrc, nil
   487  }
   488  
   489  func issect(s *pe.COFFSymbol) bool {
   490  	return s.StorageClass == IMAGE_SYM_CLASS_STATIC && s.Type == 0 && s.Name[0] == '.'
   491  }
   492  
   493  func readpesym(l *loader.Loader, arch *sys.Arch, lookup func(string, int) loader.Sym, f *pe.File, pesym *pe.COFFSymbol, sectsyms map[*pe.Section]loader.Sym, localSymVersion int) (*loader.SymbolBuilder, loader.Sym, error) {
   494  	symname, err := pesym.FullName(f.StringTable)
   495  	if err != nil {
   496  		return nil, 0, err
   497  	}
   498  	var name string
   499  	if issect(pesym) {
   500  		name = l.SymName(sectsyms[f.Sections[pesym.SectionNumber-1]])
   501  	} else {
   502  		name = symname
   503  		switch arch.Family {
   504  		case sys.AMD64:
   505  			if name == "__imp___acrt_iob_func" {
   506  				// Do not rename __imp___acrt_iob_func into __acrt_iob_func,
   507  				// because __imp___acrt_iob_func symbol is real
   508  				// (see commit b295099 from git://git.code.sf.net/p/mingw-w64/mingw-w64 for details).
   509  			} else {
   510  				name = strings.TrimPrefix(name, "__imp_") // __imp_Name => Name
   511  			}
   512  		case sys.I386:
   513  			if name == "__imp____acrt_iob_func" {
   514  				// Do not rename __imp____acrt_iob_func into ___acrt_iob_func,
   515  				// because __imp____acrt_iob_func symbol is real
   516  				// (see commit b295099 from git://git.code.sf.net/p/mingw-w64/mingw-w64 for details).
   517  			} else {
   518  				name = strings.TrimPrefix(name, "__imp_") // __imp_Name => Name
   519  			}
   520  			if name[0] == '_' {
   521  				name = name[1:] // _Name => Name
   522  			}
   523  		}
   524  	}
   525  
   526  	// remove last @XXX
   527  	if i := strings.LastIndex(name, "@"); i >= 0 {
   528  		name = name[:i]
   529  	}
   530  
   531  	var s loader.Sym
   532  	var bld *loader.SymbolBuilder
   533  	switch pesym.Type {
   534  	default:
   535  		return nil, 0, fmt.Errorf("%s: invalid symbol type %d", symname, pesym.Type)
   536  
   537  	case IMAGE_SYM_DTYPE_FUNCTION, IMAGE_SYM_DTYPE_NULL:
   538  		switch pesym.StorageClass {
   539  		case IMAGE_SYM_CLASS_EXTERNAL: //global
   540  			s = lookup(name, 0)
   541  
   542  		case IMAGE_SYM_CLASS_NULL, IMAGE_SYM_CLASS_STATIC, IMAGE_SYM_CLASS_LABEL:
   543  			s = lookup(name, localSymVersion)
   544  			bld = makeUpdater(l, bld, s)
   545  			bld.SetDuplicateOK(true)
   546  
   547  		default:
   548  			return nil, 0, fmt.Errorf("%s: invalid symbol binding %d", symname, pesym.StorageClass)
   549  		}
   550  	}
   551  
   552  	if s != 0 && l.SymType(s) == 0 && (pesym.StorageClass != IMAGE_SYM_CLASS_STATIC || pesym.Value != 0) {
   553  		bld = makeUpdater(l, bld, s)
   554  		bld.SetType(sym.SXREF)
   555  	}
   556  	if strings.HasPrefix(symname, "__imp_") {
   557  		bld = makeUpdater(l, bld, s)
   558  		bld.SetGot(-2) // flag for __imp_
   559  	}
   560  
   561  	return bld, s, nil
   562  }
   563  

View as plain text