pe.go 41.3 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package ld

import (
8
	"cmd/internal/objabi"
9
	"cmd/internal/sys"
10
	"cmd/link/internal/sym"
Alex Brainman's avatar
Alex Brainman committed
11
	"debug/pe"
12 13 14
	"encoding/binary"
	"fmt"
	"sort"
15 16
	"strconv"
	"strings"
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
)

type IMAGE_IMPORT_DESCRIPTOR struct {
	OriginalFirstThunk uint32
	TimeDateStamp      uint32
	ForwarderChain     uint32
	Name               uint32
	FirstThunk         uint32
}

type IMAGE_EXPORT_DIRECTORY struct {
	Characteristics       uint32
	TimeDateStamp         uint32
	MajorVersion          uint16
	MinorVersion          uint16
	Name                  uint32
	Base                  uint32
	NumberOfFunctions     uint32
	NumberOfNames         uint32
	AddressOfFunctions    uint32
	AddressOfNames        uint32
	AddressOfNameOrdinals uint32
}

const (
42
	PEBASE = 0x00400000
43
)
44

45
var (
46 47
	// SectionAlignment must be greater than or equal to FileAlignment.
	// The default is the page size for the architecture.
48
	PESECTALIGN int64 = 0x1000
49 50 51 52

	// FileAlignment should be a power of 2 between 512 and 64 K, inclusive.
	// The default is 512. If the SectionAlignment is less than
	// the architecture's page size, then FileAlignment must match SectionAlignment.
53
	PEFILEALIGN int64 = 2 << 8
54 55 56
)

const (
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
	IMAGE_FILE_MACHINE_I386               = 0x14c
	IMAGE_FILE_MACHINE_AMD64              = 0x8664
	IMAGE_FILE_MACHINE_ARM                = 0x1c0
	IMAGE_FILE_MACHINE_ARMNT              = 0x1c4
	IMAGE_FILE_RELOCS_STRIPPED            = 0x0001
	IMAGE_FILE_EXECUTABLE_IMAGE           = 0x0002
	IMAGE_FILE_LINE_NUMS_STRIPPED         = 0x0004
	IMAGE_FILE_LARGE_ADDRESS_AWARE        = 0x0020
	IMAGE_FILE_32BIT_MACHINE              = 0x0100
	IMAGE_FILE_DEBUG_STRIPPED             = 0x0200
	IMAGE_SCN_CNT_CODE                    = 0x00000020
	IMAGE_SCN_CNT_INITIALIZED_DATA        = 0x00000040
	IMAGE_SCN_CNT_UNINITIALIZED_DATA      = 0x00000080
	IMAGE_SCN_MEM_EXECUTE                 = 0x20000000
	IMAGE_SCN_MEM_READ                    = 0x40000000
	IMAGE_SCN_MEM_WRITE                   = 0x80000000
	IMAGE_SCN_MEM_DISCARDABLE             = 0x2000000
	IMAGE_SCN_LNK_NRELOC_OVFL             = 0x1000000
	IMAGE_SCN_ALIGN_32BYTES               = 0x600000
	IMAGE_DIRECTORY_ENTRY_EXPORT          = 0
	IMAGE_DIRECTORY_ENTRY_IMPORT          = 1
	IMAGE_DIRECTORY_ENTRY_RESOURCE        = 2
	IMAGE_DIRECTORY_ENTRY_EXCEPTION       = 3
	IMAGE_DIRECTORY_ENTRY_SECURITY        = 4
	IMAGE_DIRECTORY_ENTRY_BASERELOC       = 5
	IMAGE_DIRECTORY_ENTRY_DEBUG           = 6
	IMAGE_DIRECTORY_ENTRY_COPYRIGHT       = 7
	IMAGE_DIRECTORY_ENTRY_ARCHITECTURE    = 7
	IMAGE_DIRECTORY_ENTRY_GLOBALPTR       = 8
	IMAGE_DIRECTORY_ENTRY_TLS             = 9
	IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG     = 10
	IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT    = 11
	IMAGE_DIRECTORY_ENTRY_IAT             = 12
	IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT    = 13
	IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR  = 14
	IMAGE_SUBSYSTEM_WINDOWS_GUI           = 2
	IMAGE_SUBSYSTEM_WINDOWS_CUI           = 3
	IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE = 0x0040
	IMAGE_DLLCHARACTERISTICS_NX_COMPAT    = 0x0100
96
)
97 98 99

// TODO(crawshaw): add these constants to debug/pe.
const (
100
	// TODO: the Microsoft doco says IMAGE_SYM_DTYPE_ARRAY is 3 and IMAGE_SYM_DTYPE_FUNCTION is 2
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
	IMAGE_SYM_TYPE_NULL      = 0
	IMAGE_SYM_TYPE_STRUCT    = 8
	IMAGE_SYM_DTYPE_FUNCTION = 0x20
	IMAGE_SYM_DTYPE_ARRAY    = 0x30
	IMAGE_SYM_CLASS_EXTERNAL = 2
	IMAGE_SYM_CLASS_STATIC   = 3

	IMAGE_REL_I386_DIR32  = 0x0006
	IMAGE_REL_I386_SECREL = 0x000B
	IMAGE_REL_I386_REL32  = 0x0014

	IMAGE_REL_AMD64_ADDR64 = 0x0001
	IMAGE_REL_AMD64_ADDR32 = 0x0002
	IMAGE_REL_AMD64_REL32  = 0x0004
	IMAGE_REL_AMD64_SECREL = 0x000B
116 117 118 119 120 121 122 123 124

	IMAGE_REL_ARM_ABSOLUTE = 0x0000
	IMAGE_REL_ARM_ADDR32   = 0x0001
	IMAGE_REL_ARM_ADDR32NB = 0x0002
	IMAGE_REL_ARM_BRANCH24 = 0x0003
	IMAGE_REL_ARM_BRANCH11 = 0x0004
	IMAGE_REL_ARM_SECREL   = 0x000F

	IMAGE_REL_BASED_HIGHLOW = 3
125
)
126 127 128 129 130 131

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// PE (Portable Executable) file writing
132
// https://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267

// DOS stub that prints out
// "This program cannot be run in DOS mode."
var dosstub = []uint8{
	0x4d,
	0x5a,
	0x90,
	0x00,
	0x03,
	0x00,
	0x04,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0xff,
	0xff,
	0x00,
	0x00,
	0x8b,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x40,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x80,
	0x00,
	0x00,
	0x00,
	0x0e,
	0x1f,
	0xba,
	0x0e,
	0x00,
	0xb4,
	0x09,
	0xcd,
	0x21,
	0xb8,
	0x01,
	0x4c,
	0xcd,
	0x21,
	0x54,
	0x68,
	0x69,
	0x73,
	0x20,
	0x70,
	0x72,
	0x6f,
	0x67,
	0x72,
	0x61,
	0x6d,
	0x20,
	0x63,
	0x61,
	0x6e,
	0x6e,
	0x6f,
	0x74,
	0x20,
	0x62,
	0x65,
	0x20,
	0x72,
	0x75,
	0x6e,
	0x20,
	0x69,
	0x6e,
	0x20,
	0x44,
	0x4f,
	0x53,
	0x20,
	0x6d,
	0x6f,
	0x64,
	0x65,
	0x2e,
	0x0d,
	0x0d,
	0x0a,
	0x24,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
	0x00,
}

type Imp struct {
268
	s       *sym.Symbol
269 270 271
	off     uint64
	next    *Imp
	argsize int
272 273 274 275 276 277 278 279 280 281
}

type Dll struct {
	name     string
	nameoff  uint64
	thunkoff uint64
	ms       *Imp
	next     *Dll
}

282
var (
283
	rsrcsym     *sym.Symbol
284 285 286 287
	PESECTHEADR int32
	PEFILEHEADR int32
	pe64        int
	dr          *Dll
288
	dexport     [1024]*sym.Symbol
289 290
	nexport     int
)
291

292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
// peStringTable is a COFF string table.
type peStringTable struct {
	strings    []string
	stringsLen int
}

// size resturns size of string table t.
func (t *peStringTable) size() int {
	// string table starts with 4-byte length at the beginning
	return t.stringsLen + 4
}

// add adds string str to string table t.
func (t *peStringTable) add(str string) int {
	off := t.size()
	t.strings = append(t.strings, str)
	t.stringsLen += len(str) + 1 // each string will have 0 appended to it
	return off
}

// write writes string table t into the output file.
313 314
func (t *peStringTable) write(out *OutBuf) {
	out.Write32(uint32(t.size()))
315
	for _, s := range t.strings {
316 317
		out.WriteString(s)
		out.Write8(0)
318 319 320
	}
}

Alex Brainman's avatar
Alex Brainman committed
321 322
// peSection represents section from COFF section table.
type peSection struct {
323 324 325 326 327 328 329 330 331 332
	name                 string
	shortName            string
	index                int // one-based index into the Section Table
	virtualSize          uint32
	virtualAddress       uint32
	sizeOfRawData        uint32
	pointerToRawData     uint32
	pointerToRelocations uint32
	numberOfRelocations  uint16
	characteristics      uint32
Alex Brainman's avatar
Alex Brainman committed
333 334
}

335 336
// checkOffset verifies COFF section sect offset in the file.
func (sect *peSection) checkOffset(off int64) {
337 338
	if off != int64(sect.pointerToRawData) {
		Errorf(nil, "%s.PointerToRawData = %#x, want %#x", sect.name, uint64(int64(sect.pointerToRawData)), uint64(off))
339 340 341 342
		errorexit()
	}
}

343 344
// checkSegment verifies COFF section sect matches address
// and file offset provided in segment seg.
345
func (sect *peSection) checkSegment(seg *sym.Segment) {
346 347
	if seg.Vaddr-PEBASE != uint64(sect.virtualAddress) {
		Errorf(nil, "%s.VirtualAddress = %#x, want %#x", sect.name, uint64(int64(sect.virtualAddress)), uint64(int64(seg.Vaddr-PEBASE)))
348 349
		errorexit()
	}
350 351
	if seg.Fileoff != uint64(sect.pointerToRawData) {
		Errorf(nil, "%s.PointerToRawData = %#x, want %#x", sect.name, uint64(int64(sect.pointerToRawData)), uint64(int64(seg.Fileoff)))
352 353 354 355
		errorexit()
	}
}

356 357 358
// pad adds zeros to the section sect. It writes as many bytes
// as necessary to make section sect.SizeOfRawData bytes long.
// It assumes that n bytes are already written to the file.
359 360
func (sect *peSection) pad(out *OutBuf, n uint32) {
	out.WriteStringN("", int(sect.sizeOfRawData-n))
361 362
}

Alex Brainman's avatar
Alex Brainman committed
363
// write writes COFF section sect into the output file.
364
func (sect *peSection) write(out *OutBuf, linkmode LinkMode) error {
Alex Brainman's avatar
Alex Brainman committed
365
	h := pe.SectionHeader32{
366 367 368 369 370 371
		VirtualSize:          sect.virtualSize,
		SizeOfRawData:        sect.sizeOfRawData,
		PointerToRawData:     sect.pointerToRawData,
		PointerToRelocations: sect.pointerToRelocations,
		NumberOfRelocations:  sect.numberOfRelocations,
		Characteristics:      sect.characteristics,
Alex Brainman's avatar
Alex Brainman committed
372
	}
373
	if linkmode != LinkExternal {
374
		h.VirtualAddress = sect.virtualAddress
Alex Brainman's avatar
Alex Brainman committed
375 376
	}
	copy(h.Name[:], sect.shortName)
377
	return binary.Write(out, binary.LittleEndian, h)
Alex Brainman's avatar
Alex Brainman committed
378 379
}

380 381 382 383
// emitRelocations emits the relocation entries for the sect.
// The actual relocations are emitted by relocfn.
// This updates the corresponding PE section table entry
// with the relocation offset and count.
384 385
func (sect *peSection) emitRelocations(out *OutBuf, relocfn func() int) {
	sect.pointerToRelocations = uint32(out.Offset())
386
	// first entry: extended relocs
387 388 389
	out.Write32(0) // placeholder for number of relocation + 1
	out.Write32(0)
	out.Write16(0)
390 391 392

	n := relocfn() + 1

393 394 395 396
	cpos := out.Offset()
	out.SeekSet(int64(sect.pointerToRelocations))
	out.Write32(uint32(n))
	out.SeekSet(cpos)
397 398
	if n > 0x10000 {
		n = 0x10000
399
		sect.characteristics |= IMAGE_SCN_LNK_NRELOC_OVFL
400
	} else {
401
		sect.pointerToRelocations += 10 // skip the extend reloc entry
402
	}
403
	sect.numberOfRelocations = uint16(n - 1)
404 405
}

406 407
// peFile is used to build COFF file.
type peFile struct {
408 409 410
	sections       []*peSection
	stringTable    peStringTable
	textSect       *peSection
411
	rdataSect      *peSection
412 413
	dataSect       *peSection
	bssSect        *peSection
414
	ctorsSect      *peSection
415 416
	nextSectOffset uint32
	nextFileOffset uint32
417 418
	symtabOffset   int64 // offset to the start of symbol table
	symbolCount    int   // number of symbol table records written
419
	dataDirectory  [16]pe.DataDirectory
420 421
}

Alex Brainman's avatar
Alex Brainman committed
422 423 424 425 426 427
// addSection adds section to the COFF file f.
func (f *peFile) addSection(name string, sectsize int, filesize int) *peSection {
	sect := &peSection{
		name:             name,
		shortName:        name,
		index:            len(f.sections) + 1,
428 429 430
		virtualSize:      uint32(sectsize),
		virtualAddress:   f.nextSectOffset,
		pointerToRawData: f.nextFileOffset,
Alex Brainman's avatar
Alex Brainman committed
431
	}
432
	f.nextSectOffset = uint32(Rnd(int64(f.nextSectOffset)+int64(sectsize), PESECTALIGN))
Alex Brainman's avatar
Alex Brainman committed
433
	if filesize > 0 {
434 435
		sect.sizeOfRawData = uint32(Rnd(int64(filesize), PEFILEALIGN))
		f.nextFileOffset += sect.sizeOfRawData
Alex Brainman's avatar
Alex Brainman committed
436 437 438 439 440
	}
	f.sections = append(f.sections, sect)
	return sect
}

441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
// addDWARFSection adds DWARF section to the COFF file f.
// This function is similar to addSection, but DWARF section names are
// longer than 8 characters, so they need to be stored in the string table.
func (f *peFile) addDWARFSection(name string, size int) *peSection {
	if size == 0 {
		Exitf("DWARF section %q is empty", name)
	}
	// DWARF section names are longer than 8 characters.
	// PE format requires such names to be stored in string table,
	// and section names replaced with slash (/) followed by
	// correspondent string table index.
	// see http://www.microsoft.com/whdc/system/platform/firmware/PECOFFdwn.mspx
	// for details
	off := f.stringTable.add(name)
	h := f.addSection(name, size, size)
	h.shortName = fmt.Sprintf("/%d", off)
457
	h.characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_DISCARDABLE
458 459 460
	return h
}

461 462 463 464 465 466 467 468 469 470 471
// addDWARF adds DWARF information to the COFF file f.
func (f *peFile) addDWARF() {
	if *FlagS { // disable symbol table
		return
	}
	if *FlagW { // disable dwarf
		return
	}
	for _, sect := range Segdwarf.Sections {
		h := f.addDWARFSection(sect.Name, int(sect.Length))
		fileoff := sect.Vaddr - Segdwarf.Vaddr + Segdwarf.Fileoff
472 473
		if uint64(h.pointerToRawData) != fileoff {
			Exitf("%s.PointerToRawData = %#x, want %#x", sect.Name, h.pointerToRawData, fileoff)
474 475 476 477
		}
	}
}

478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
// addInitArray adds .ctors COFF section to the file f.
func (f *peFile) addInitArray(ctxt *Link) *peSection {
	// The size below was determined by the specification for array relocations,
	// and by observing what GCC writes here. If the initarray section grows to
	// contain more than one constructor entry, the size will need to be 8 * constructor_count.
	// However, the entire Go runtime is initialized from just one function, so it is unlikely
	// that this will need to grow in the future.
	var size int
	switch objabi.GOARCH {
	default:
		Exitf("peFile.addInitArray: unsupported GOARCH=%q\n", objabi.GOARCH)
	case "386":
		size = 4
	case "amd64":
		size = 8
493 494
	case "arm":
		size = 4
495 496
	}
	sect := f.addSection(".ctors", size, size)
497 498
	sect.characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ
	sect.sizeOfRawData = uint32(size)
499 500
	ctxt.Out.SeekSet(int64(sect.pointerToRawData))
	sect.checkOffset(ctxt.Out.Offset())
501 502 503 504

	init_entry := ctxt.Syms.Lookup(*flagEntrySymbol, 0)
	addr := uint64(init_entry.Value) - init_entry.Sect.Vaddr
	switch objabi.GOARCH {
505
	case "386", "arm":
506
		ctxt.Out.Write32(uint32(addr))
507
	case "amd64":
508
		ctxt.Out.Write64(addr)
509 510 511 512
	}
	return sect
}

513
// emitRelocations emits relocation entries for go.o in external linking.
514
func (f *peFile) emitRelocations(ctxt *Link) {
515 516
	for ctxt.Out.Offset()&7 != 0 {
		ctxt.Out.Write8(0)
517 518
	}

519 520
	// relocsect relocates symbols from first in section sect, and returns
	// the total number of relocations emitted.
521
	relocsect := func(sect *sym.Section, syms []*sym.Symbol, base uint64) int {
522 523 524 525 526
		// If main section has no bits, nothing to relocate.
		if sect.Vaddr >= sect.Seg.Vaddr+sect.Seg.Filelen {
			return 0
		}
		relocs := 0
527
		sect.Reloff = uint64(ctxt.Out.Offset())
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
		for i, s := range syms {
			if !s.Attr.Reachable() {
				continue
			}
			if uint64(s.Value) >= sect.Vaddr {
				syms = syms[i:]
				break
			}
		}
		eaddr := int32(sect.Vaddr + sect.Length)
		for _, sym := range syms {
			if !sym.Attr.Reachable() {
				continue
			}
			if sym.Value >= int64(eaddr) {
				break
			}
545
			for ri := range sym.R {
546
				r := &sym.R[ri]
547
				if r.Done {
548 549 550 551 552 553 554 555 556
					continue
				}
				if r.Xsym == nil {
					Errorf(sym, "missing xsym in relocation")
					continue
				}
				if r.Xsym.Dynid < 0 {
					Errorf(sym, "reloc %d to non-coff symbol %s (outer=%s) %d", r.Type, r.Sym.Name, r.Xsym.Name, r.Sym.Type)
				}
557
				if !thearch.PEreloc1(ctxt.Arch, ctxt.Out, sym, r, int64(uint64(sym.Value+int64(r.Off))-base)) {
558 559 560 561 562
					Errorf(sym, "unsupported obj reloc %d/%d to %s", r.Type, r.Siz, r.Sym.Name)
				}
				relocs++
			}
		}
563
		sect.Rellen = uint64(ctxt.Out.Offset()) - sect.Reloff
564 565 566
		return relocs
	}

567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
	sects := []struct {
		peSect *peSection
		seg    *sym.Segment
		syms   []*sym.Symbol
	}{
		{f.textSect, &Segtext, ctxt.Textp},
		{f.rdataSect, &Segrodata, datap},
		{f.dataSect, &Segdata, datap},
	}
	for _, s := range sects {
		s.peSect.emitRelocations(ctxt.Out, func() int {
			var n int
			for _, sect := range s.seg.Sections {
				n += relocsect(sect, s.syms, s.seg.Vaddr)
			}
			return n
		})
	}
585 586 587 588 589

dwarfLoop:
	for _, sect := range Segdwarf.Sections {
		for _, pesect := range f.sections {
			if sect.Name == pesect.name {
590
				pesect.emitRelocations(ctxt.Out, func() int {
591
					return relocsect(sect, dwarfp, sect.Vaddr)
592 593 594 595 596 597 598
				})
				continue dwarfLoop
			}
		}
		Errorf(nil, "emitRelocations: could not find %q section", sect.Name)
	}

599
	f.ctorsSect.emitRelocations(ctxt.Out, func() int {
600
		dottext := ctxt.Syms.Lookup(".text", 0)
601 602
		ctxt.Out.Write32(0)
		ctxt.Out.Write32(uint32(dottext.Dynid))
603 604 605 606
		switch objabi.GOARCH {
		default:
			Errorf(dottext, "unknown architecture for PE: %q\n", objabi.GOARCH)
		case "386":
607
			ctxt.Out.Write16(IMAGE_REL_I386_DIR32)
608
		case "amd64":
609
			ctxt.Out.Write16(IMAGE_REL_AMD64_ADDR64)
610 611
		case "arm":
			ctxt.Out.Write16(IMAGE_REL_ARM_ADDR32)
612 613 614 615 616
		}
		return 1
	})
}

617 618
// writeSymbol appends symbol s to file f symbol table.
// It also sets s.Dynid to written symbol number.
619
func (f *peFile) writeSymbol(out *OutBuf, s *sym.Symbol, value int64, sectidx int, typ uint16, class uint8) {
620
	if len(s.Name) > 8 {
621 622
		out.Write32(0)
		out.Write32(uint32(f.stringTable.add(s.Name)))
623
	} else {
624
		out.WriteStringN(s.Name, 8)
625
	}
626 627 628 629 630
	out.Write32(uint32(value))
	out.Write16(uint16(sectidx))
	out.Write16(typ)
	out.Write8(class)
	out.Write8(0) // no aux entries
631 632 633 634 635 636

	s.Dynid = int32(f.symbolCount)

	f.symbolCount++
}

637 638
// mapToPESection searches peFile f for s symbol's location.
// It returns PE section index, and offset within that section.
639
func (f *peFile) mapToPESection(s *sym.Symbol, linkmode LinkMode) (pesectidx int, offset int64, err error) {
640 641 642 643 644 645
	if s.Sect == nil {
		return 0, 0, fmt.Errorf("could not map %s symbol with no section", s.Name)
	}
	if s.Sect.Seg == &Segtext {
		return f.textSect.index, int64(uint64(s.Value) - Segtext.Vaddr), nil
	}
646 647 648
	if s.Sect.Seg == &Segrodata {
		return f.rdataSect.index, int64(uint64(s.Value) - Segrodata.Vaddr), nil
	}
649
	if s.Sect.Seg != &Segdata {
650
		return 0, 0, fmt.Errorf("could not map %s symbol with non .text or .rdata or .data section", s.Name)
651 652
	}
	v := uint64(s.Value) - Segdata.Vaddr
653
	if linkmode != LinkExternal {
654 655
		return f.dataSect.index, int64(v), nil
	}
656
	if s.Type == sym.SDATA {
657 658
		return f.dataSect.index, int64(v), nil
	}
659
	// Note: although address of runtime.edata (type sym.SDATA) is at the start of .bss section
660 661 662 663 664 665 666
	// it still belongs to the .data section, not the .bss section.
	if v < Segdata.Filelen {
		return f.dataSect.index, int64(v), nil
	}
	return f.bssSect.index, int64(v - Segdata.Filelen), nil
}

667 668 669
// writeSymbols writes all COFF symbol table records.
func (f *peFile) writeSymbols(ctxt *Link) {

670
	put := func(ctxt *Link, s *sym.Symbol, name string, type_ SymbolType, addr int64, gotype *sym.Symbol) {
671 672 673 674 675 676 677 678 679 680 681 682 683
		if s == nil {
			return
		}
		if s.Sect == nil && type_ != UndefinedSym {
			return
		}
		switch type_ {
		default:
			return
		case DataSym, BSSSym, TextSym, UndefinedSym:
		}

		// Only windows/386 requires underscore prefix on external symbols.
684
		if ctxt.Arch.Family == sys.I386 &&
685
			ctxt.LinkMode == LinkExternal &&
686
			(s.Type == sym.SHOSTOBJ || s.Attr.CgoExport()) {
687 688 689 690
			s.Name = "_" + s.Name
		}

		var typ uint16
691
		if ctxt.LinkMode == LinkExternal {
692 693 694 695 696 697
			typ = IMAGE_SYM_TYPE_NULL
		} else {
			// TODO: fix IMAGE_SYM_DTYPE_ARRAY value and use following expression, instead of 0x0308
			typ = IMAGE_SYM_DTYPE_ARRAY<<8 + IMAGE_SYM_TYPE_STRUCT
			typ = 0x0308 // "array of structs"
		}
698
		sect, value, err := f.mapToPESection(s, ctxt.LinkMode)
699 700 701 702 703 704 705 706
		if err != nil {
			if type_ == UndefinedSym {
				typ = IMAGE_SYM_DTYPE_FUNCTION
			} else {
				Errorf(s, "addpesym: %v", err)
			}
		}
		class := IMAGE_SYM_CLASS_EXTERNAL
707
		if s.Version != 0 || s.Attr.VisibilityHidden() || s.Attr.Local() {
708 709
			class = IMAGE_SYM_CLASS_STATIC
		}
710
		f.writeSymbol(ctxt.Out, s, value, sect, typ, uint8(class))
711 712
	}

713
	if ctxt.LinkMode == LinkExternal {
714 715 716 717
		// Include section symbols as external, because
		// .ctors and .debug_* section relocations refer to it.
		for _, pesect := range f.sections {
			sym := ctxt.Syms.Lookup(pesect.name, 0)
718
			f.writeSymbol(ctxt.Out, sym, 0, pesect.index, IMAGE_SYM_TYPE_NULL, IMAGE_SYM_CLASS_STATIC)
719 720 721 722 723 724
		}
	}

	genasmsym(ctxt, put)
}

725 726
// writeSymbolTableAndStringTable writes out symbol and string tables for peFile f.
func (f *peFile) writeSymbolTableAndStringTable(ctxt *Link) {
727
	f.symtabOffset = ctxt.Out.Offset()
728 729

	// write COFF symbol table
730
	if !*FlagS || ctxt.LinkMode == LinkExternal {
731 732 733 734 735 736
		f.writeSymbols(ctxt)
	}

	// update COFF file header and section table
	size := f.stringTable.size() + 18*f.symbolCount
	var h *peSection
737
	if ctxt.LinkMode != LinkExternal {
738 739 740
		// We do not really need .symtab for go.o, and if we have one, ld
		// will also include it in the exe, and that will confuse windows.
		h = f.addSection(".symtab", size, size)
741
		h.characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_DISCARDABLE
742
		h.checkOffset(f.symtabOffset)
743 744 745
	}

	// write COFF string table
746
	f.stringTable.write(ctxt.Out)
747
	if ctxt.LinkMode != LinkExternal {
748
		h.pad(ctxt.Out, uint32(size))
749 750 751
	}
}

752
// writeFileHeader writes COFF file header for peFile f.
753
func (f *peFile) writeFileHeader(arch *sys.Arch, out *OutBuf, linkmode LinkMode) {
754 755
	var fh pe.FileHeader

756
	switch arch.Family {
757
	default:
758
		Exitf("unknown PE architecture: %v", arch.Family)
759 760 761 762
	case sys.AMD64:
		fh.Machine = IMAGE_FILE_MACHINE_AMD64
	case sys.I386:
		fh.Machine = IMAGE_FILE_MACHINE_I386
763 764
	case sys.ARM:
		fh.Machine = IMAGE_FILE_MACHINE_ARMNT
765 766 767 768 769 770 771 772
	}

	fh.NumberOfSections = uint16(len(f.sections))

	// Being able to produce identical output for identical input is
	// much more beneficial than having build timestamp in the header.
	fh.TimeDateStamp = 0

773
	if linkmode == LinkExternal {
774 775
		fh.Characteristics = IMAGE_FILE_LINE_NUMS_STRIPPED
	} else {
776 777 778 779 780 781 782 783
		switch arch.Family {
		default:
			Exitf("write COFF(ext): unknown PE architecture: %v", arch.Family)
		case sys.AMD64, sys.I386:
			fh.Characteristics = IMAGE_FILE_RELOCS_STRIPPED | IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DEBUG_STRIPPED
		case sys.ARM:
			fh.Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DEBUG_STRIPPED
		}
784 785
	}
	if pe64 != 0 {
786
		var oh64 pe.OptionalHeader64
787 788 789
		fh.SizeOfOptionalHeader = uint16(binary.Size(&oh64))
		fh.Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE
	} else {
790
		var oh pe.OptionalHeader32
791 792 793 794 795 796 797
		fh.SizeOfOptionalHeader = uint16(binary.Size(&oh))
		fh.Characteristics |= IMAGE_FILE_32BIT_MACHINE
	}

	fh.PointerToSymbolTable = uint32(f.symtabOffset)
	fh.NumberOfSymbols = uint32(f.symbolCount)

798
	binary.Write(out, binary.LittleEndian, &fh)
799 800
}

801 802 803 804 805 806 807 808 809
// writeOptionalHeader writes COFF optional header for peFile f.
func (f *peFile) writeOptionalHeader(ctxt *Link) {
	var oh pe.OptionalHeader32
	var oh64 pe.OptionalHeader64

	if pe64 != 0 {
		oh64.Magic = 0x20b // PE32+
	} else {
		oh.Magic = 0x10b // PE32
810
		oh.BaseOfData = f.dataSect.virtualAddress
811 812 813 814 815 816 817
	}

	// Fill out both oh64 and oh. We only use one. Oh well.
	oh64.MajorLinkerVersion = 3
	oh.MajorLinkerVersion = 3
	oh64.MinorLinkerVersion = 0
	oh.MinorLinkerVersion = 0
818 819 820 821
	oh64.SizeOfCode = f.textSect.sizeOfRawData
	oh.SizeOfCode = f.textSect.sizeOfRawData
	oh64.SizeOfInitializedData = f.dataSect.sizeOfRawData
	oh.SizeOfInitializedData = f.dataSect.sizeOfRawData
822 823
	oh64.SizeOfUninitializedData = 0
	oh.SizeOfUninitializedData = 0
824
	if ctxt.LinkMode != LinkExternal {
825 826 827
		oh64.AddressOfEntryPoint = uint32(Entryvalue(ctxt) - PEBASE)
		oh.AddressOfEntryPoint = uint32(Entryvalue(ctxt) - PEBASE)
	}
828 829
	oh64.BaseOfCode = f.textSect.virtualAddress
	oh.BaseOfCode = f.textSect.virtualAddress
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
	oh64.ImageBase = PEBASE
	oh.ImageBase = PEBASE
	oh64.SectionAlignment = uint32(PESECTALIGN)
	oh.SectionAlignment = uint32(PESECTALIGN)
	oh64.FileAlignment = uint32(PEFILEALIGN)
	oh.FileAlignment = uint32(PEFILEALIGN)
	oh64.MajorOperatingSystemVersion = 4
	oh.MajorOperatingSystemVersion = 4
	oh64.MinorOperatingSystemVersion = 0
	oh.MinorOperatingSystemVersion = 0
	oh64.MajorImageVersion = 1
	oh.MajorImageVersion = 1
	oh64.MinorImageVersion = 0
	oh.MinorImageVersion = 0
	oh64.MajorSubsystemVersion = 4
	oh.MajorSubsystemVersion = 4
	oh64.MinorSubsystemVersion = 0
	oh.MinorSubsystemVersion = 0
	oh64.SizeOfImage = f.nextSectOffset
	oh.SizeOfImage = f.nextSectOffset
	oh64.SizeOfHeaders = uint32(PEFILEHEADR)
	oh.SizeOfHeaders = uint32(PEFILEHEADR)
	if windowsgui {
		oh64.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_GUI
		oh.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_GUI
	} else {
		oh64.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI
		oh.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI
	}

860 861 862 863 864 865
	switch ctxt.Arch.Family {
	case sys.ARM:
		oh64.DllCharacteristics = IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE | IMAGE_DLLCHARACTERISTICS_NX_COMPAT
		oh.DllCharacteristics = IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE | IMAGE_DLLCHARACTERISTICS_NX_COMPAT
	}

866 867 868 869 870 871 872 873 874 875 876 877 878 879
	// Disable stack growth as we don't want Windows to
	// fiddle with the thread stack limits, which we set
	// ourselves to circumvent the stack checks in the
	// Windows exception dispatcher.
	// Commit size must be strictly less than reserve
	// size otherwise reserve will be rounded up to a
	// larger size, as verified with VMMap.

	// On 64-bit, we always reserve 2MB stacks. "Pure" Go code is
	// okay with much smaller stacks, but the syscall package
	// makes it easy to call into arbitrary C code without cgo,
	// and system calls even in "pure" Go code are actually C
	// calls that may need more stack than we think.
	//
880
	// The default stack reserve size directly affects only the main
881 882 883 884
	// thread, ctrlhandler thread, and profileloop thread. For
	// these, it must be greater than the stack size assumed by
	// externalthreadhandler.
	//
885 886 887 888 889 890 891
	// For other threads, the runtime explicitly asks the kernel
	// to use the default stack size so that all stacks are
	// consistent.
	//
	// At thread start, in minit, the runtime queries the OS for
	// the actual stack bounds so that the stack size doesn't need
	// to be hard-coded into the runtime.
892
	oh64.SizeOfStackReserve = 0x00200000
893 894 895 896 897 898 899 900
	if !iscgo {
		oh64.SizeOfStackCommit = 0x00001000
	} else {
		// TODO(brainman): Maybe remove optional header writing altogether for cgo.
		// For cgo it is the external linker that is building final executable.
		// And it probably does not use any information stored in optional header.
		oh64.SizeOfStackCommit = 0x00200000 - 0x2000 // account for 2 guard pages
	}
901

902
	oh.SizeOfStackReserve = 0x00100000
903 904 905
	if !iscgo {
		oh.SizeOfStackCommit = 0x00001000
	} else {
906
		oh.SizeOfStackCommit = 0x00100000 - 0x2000 // account for 2 guard pages
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
	}

	oh64.SizeOfHeapReserve = 0x00100000
	oh.SizeOfHeapReserve = 0x00100000
	oh64.SizeOfHeapCommit = 0x00001000
	oh.SizeOfHeapCommit = 0x00001000
	oh64.NumberOfRvaAndSizes = 16
	oh.NumberOfRvaAndSizes = 16

	if pe64 != 0 {
		oh64.DataDirectory = f.dataDirectory
	} else {
		oh.DataDirectory = f.dataDirectory
	}

	if pe64 != 0 {
923
		binary.Write(ctxt.Out, binary.LittleEndian, &oh64)
924
	} else {
925
		binary.Write(ctxt.Out, binary.LittleEndian, &oh)
926 927 928
	}
}

929 930
var pefile peFile

931
func Peinit(ctxt *Link) {
932 933
	var l int

934
	switch ctxt.Arch.Family {
935
	// 64-bit architectures
936
	case sys.AMD64:
937
		pe64 = 1
938
		var oh64 pe.OptionalHeader64
939 940
		l = binary.Size(&oh64)

941
	// 32-bit architectures
942
	default:
943
		var oh pe.OptionalHeader32
944 945 946 947
		l = binary.Size(&oh)

	}

948
	if ctxt.LinkMode == LinkExternal {
949 950 951 952 953
		// .rdata section will contain "masks" and "shifts" symbols, and they
		// need to be aligned to 16-bytes. So make all sections aligned
		// to 32-byte and mark them all IMAGE_SCN_ALIGN_32BYTES so external
		// linker will honour that requirement.
		PESECTALIGN = 32
954 955 956
		PEFILEALIGN = 0
	}

957
	var sh [16]pe.SectionHeader32
958
	var fh pe.FileHeader
959
	PEFILEHEADR = int32(Rnd(int64(len(dosstub)+binary.Size(&fh)+l+binary.Size(&sh)), PEFILEALIGN))
960
	if ctxt.LinkMode != LinkExternal {
961 962 963 964
		PESECTHEADR = int32(Rnd(int64(PEFILEHEADR), PESECTALIGN))
	} else {
		PESECTHEADR = 0
	}
965 966
	pefile.nextSectOffset = uint32(PESECTHEADR)
	pefile.nextFileOffset = uint32(PEFILEHEADR)
967

968
	if ctxt.LinkMode == LinkInternal {
969
		// some mingw libs depend on this symbol, for example, FindPESectionByName
970 971
		ctxt.xdefine("__image_base__", sym.SDATA, PEBASE)
		ctxt.xdefine("_image_base__", sym.SDATA, PEBASE)
972
	}
973 974 975 976 977 978 979 980 981 982 983 984 985 986

	HEADR = PEFILEHEADR
	if *FlagTextAddr == -1 {
		*FlagTextAddr = PEBASE + int64(PESECTHEADR)
	}
	if *FlagDataAddr == -1 {
		*FlagDataAddr = 0
	}
	if *FlagRound == -1 {
		*FlagRound = int(PESECTALIGN)
	}
	if *FlagDataAddr != 0 && *FlagRound != 0 {
		fmt.Printf("warning: -D0x%x is ignored because of -R0x%x\n", uint64(*FlagDataAddr), uint32(*FlagRound))
	}
987 988
}

989
func pewrite(ctxt *Link) {
990
	ctxt.Out.SeekSet(0)
991
	if ctxt.LinkMode != LinkExternal {
992 993
		ctxt.Out.Write(dosstub)
		ctxt.Out.WriteStringN("PE", 4)
994
	}
995

996
	pefile.writeFileHeader(ctxt.Arch, ctxt.Out, ctxt.LinkMode)
997

998 999
	pefile.writeOptionalHeader(ctxt)

1000
	for _, sect := range pefile.sections {
1001
		sect.write(ctxt.Out, ctxt.LinkMode)
1002
	}
1003 1004
}

1005 1006 1007
func strput(out *OutBuf, s string) {
	out.WriteString(s)
	out.Write8(0)
1008 1009
	// string must be padded to even size
	if (len(s)+1)%2 != 0 {
1010
		out.Write8(0)
1011 1012 1013
	}
}

1014
func initdynimport(ctxt *Link) *Dll {
1015 1016 1017
	var d *Dll

	dr = nil
Russ Cox's avatar
Russ Cox committed
1018
	var m *Imp
1019
	for _, s := range ctxt.Syms.Allsym {
1020
		if !s.Attr.Reachable() || s.Type != sym.SDYNIMPORT {
1021 1022 1023
			continue
		}
		for d = dr; d != nil; d = d.next {
1024
			if d.name == s.Dynimplib() {
1025 1026 1027 1028 1029 1030 1031
				m = new(Imp)
				break
			}
		}

		if d == nil {
			d = new(Dll)
1032
			d.name = s.Dynimplib()
1033 1034 1035 1036 1037
			d.next = dr
			dr = d
			m = new(Imp)
		}

1038 1039 1040 1041 1042
		// Because external link requires properly stdcall decorated name,
		// all external symbols in runtime use %n to denote that the number
		// of uinptrs this function consumes. Store the argsize and discard
		// the %n suffix if any.
		m.argsize = -1
1043 1044
		extName := s.Extname()
		if i := strings.IndexByte(extName, '%'); i >= 0 {
1045
			var err error
1046
			m.argsize, err = strconv.Atoi(extName[i+1:])
1047
			if err != nil {
1048
				Errorf(s, "failed to parse stdcall decoration: %v", err)
1049
			}
1050
			m.argsize *= ctxt.Arch.PtrSize
1051
			s.SetExtname(extName[:i])
1052 1053
		}

1054 1055 1056 1057 1058
		m.s = s
		m.next = d.ms
		d.ms = m
	}

1059
	if ctxt.LinkMode == LinkExternal {
1060 1061 1062
		// Add real symbol name
		for d := dr; d != nil; d = d.next {
			for m = d.ms; m != nil; m = m.next {
1063
				m.s.Type = sym.SDATA
1064
				m.s.Grow(int64(ctxt.Arch.PtrSize))
1065
				dynName := m.s.Extname()
1066
				// only windows/386 requires stdcall decoration
1067
				if ctxt.Arch.Family == sys.I386 && m.argsize >= 0 {
1068 1069
					dynName += fmt.Sprintf("@%d", m.argsize)
				}
1070
				dynSym := ctxt.Syms.Lookup(dynName, 0)
1071 1072
				dynSym.Attr |= sym.AttrReachable
				dynSym.Type = sym.SHOSTOBJ
1073
				r := m.s.AddRel()
1074 1075
				r.Sym = dynSym
				r.Off = 0
1076
				r.Siz = uint8(ctxt.Arch.PtrSize)
1077
				r.Type = objabi.R_ADDR
1078
			}
1079
		}
1080
	} else {
1081
		dynamic := ctxt.Syms.Lookup(".windynamic", 0)
1082 1083
		dynamic.Attr |= sym.AttrReachable
		dynamic.Type = sym.SWINDOWS
1084 1085
		for d := dr; d != nil; d = d.next {
			for m = d.ms; m != nil; m = m.next {
1086 1087
				m.s.Type = sym.SWINDOWS
				m.s.Attr |= sym.AttrSubSymbol
1088 1089 1090
				m.s.Sub = dynamic.Sub
				dynamic.Sub = m.s
				m.s.Value = dynamic.Size
1091
				dynamic.Size += int64(ctxt.Arch.PtrSize)
1092
			}
1093

1094
			dynamic.Size += int64(ctxt.Arch.PtrSize)
1095
		}
1096 1097 1098 1099 1100
	}

	return dr
}

1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
// peimporteddlls returns the gcc command line argument to link all imported
// DLLs.
func peimporteddlls() []string {
	var dlls []string

	for d := dr; d != nil; d = d.next {
		dlls = append(dlls, "-l"+strings.TrimSuffix(d.name, ".dll"))
	}

	return dlls
}

1113
func addimports(ctxt *Link, datsect *peSection) {
1114
	startoff := ctxt.Out.Offset()
1115
	dynamic := ctxt.Syms.Lookup(".windynamic", 0)
1116 1117

	// skip import descriptor table (will write it later)
Russ Cox's avatar
Russ Cox committed
1118
	n := uint64(0)
1119

Russ Cox's avatar
Russ Cox committed
1120
	for d := dr; d != nil; d = d.next {
1121 1122
		n++
	}
1123
	ctxt.Out.SeekSet(startoff + int64(binary.Size(&IMAGE_IMPORT_DESCRIPTOR{}))*int64(n+1))
1124 1125

	// write dll names
Russ Cox's avatar
Russ Cox committed
1126
	for d := dr; d != nil; d = d.next {
1127 1128
		d.nameoff = uint64(ctxt.Out.Offset()) - uint64(startoff)
		strput(ctxt.Out, d.name)
1129 1130 1131
	}

	// write function names
Russ Cox's avatar
Russ Cox committed
1132
	for d := dr; d != nil; d = d.next {
1133
		for m := d.ms; m != nil; m = m.next {
1134 1135
			m.off = uint64(pefile.nextSectOffset) + uint64(ctxt.Out.Offset()) - uint64(startoff)
			ctxt.Out.Write16(0) // hint
1136
			strput(ctxt.Out, m.s.Extname())
1137 1138 1139 1140
		}
	}

	// write OriginalFirstThunks
1141
	oftbase := uint64(ctxt.Out.Offset()) - uint64(startoff)
1142

1143
	n = uint64(ctxt.Out.Offset())
Russ Cox's avatar
Russ Cox committed
1144
	for d := dr; d != nil; d = d.next {
1145
		d.thunkoff = uint64(ctxt.Out.Offset()) - n
1146
		for m := d.ms; m != nil; m = m.next {
1147
			if pe64 != 0 {
1148
				ctxt.Out.Write64(m.off)
1149
			} else {
1150
				ctxt.Out.Write32(uint32(m.off))
1151 1152 1153 1154
			}
		}

		if pe64 != 0 {
1155
			ctxt.Out.Write64(0)
1156
		} else {
1157
			ctxt.Out.Write32(0)
1158 1159 1160 1161
		}
	}

	// add pe section and pad it at the end
1162
	n = uint64(ctxt.Out.Offset()) - uint64(startoff)
1163

1164
	isect := pefile.addSection(".idata", int(n), int(n))
1165
	isect.characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE
1166
	isect.checkOffset(startoff)
1167 1168
	isect.pad(ctxt.Out, uint32(n))
	endoff := ctxt.Out.Offset()
1169 1170

	// write FirstThunks (allocated in .data section)
1171
	ftbase := uint64(dynamic.Value) - uint64(datsect.virtualAddress) - PEBASE
1172

1173
	ctxt.Out.SeekSet(int64(uint64(datsect.pointerToRawData) + ftbase))
Russ Cox's avatar
Russ Cox committed
1174
	for d := dr; d != nil; d = d.next {
1175
		for m := d.ms; m != nil; m = m.next {
1176
			if pe64 != 0 {
1177
				ctxt.Out.Write64(m.off)
1178
			} else {
1179
				ctxt.Out.Write32(uint32(m.off))
1180 1181 1182 1183
			}
		}

		if pe64 != 0 {
1184
			ctxt.Out.Write64(0)
1185
		} else {
1186
			ctxt.Out.Write32(0)
1187 1188 1189 1190
		}
	}

	// finally write import descriptor table
1191 1192
	out := ctxt.Out
	out.SeekSet(startoff)
1193

Russ Cox's avatar
Russ Cox committed
1194
	for d := dr; d != nil; d = d.next {
1195 1196 1197 1198 1199
		out.Write32(uint32(uint64(isect.virtualAddress) + oftbase + d.thunkoff))
		out.Write32(0)
		out.Write32(0)
		out.Write32(uint32(uint64(isect.virtualAddress) + d.nameoff))
		out.Write32(uint32(uint64(datsect.virtualAddress) + ftbase + d.thunkoff))
1200 1201
	}

1202 1203 1204 1205 1206
	out.Write32(0) //end
	out.Write32(0)
	out.Write32(0)
	out.Write32(0)
	out.Write32(0)
1207 1208

	// update data directory
1209 1210
	pefile.dataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress = isect.virtualAddress
	pefile.dataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size = isect.virtualSize
1211 1212
	pefile.dataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress = uint32(dynamic.Value - PEBASE)
	pefile.dataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].Size = uint32(dynamic.Size)
1213

1214
	out.SeekSet(endoff)
1215 1216
}

1217
type byExtname []*sym.Symbol
1218

1219 1220
func (s byExtname) Len() int           { return len(s) }
func (s byExtname) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
1221
func (s byExtname) Less(i, j int) bool { return s[i].Extname() < s[j].Extname() }
1222

1223
func initdynexport(ctxt *Link) {
1224
	nexport = 0
1225
	for _, s := range ctxt.Syms.Allsym {
1226
		if !s.Attr.Reachable() || !s.Attr.CgoExportDynamic() {
1227 1228 1229
			continue
		}
		if nexport+1 > len(dexport) {
1230
			Errorf(s, "pe dynexport table is full")
1231
			errorexit()
1232 1233 1234 1235 1236 1237
		}

		dexport[nexport] = s
		nexport++
	}

1238
	sort.Sort(byExtname(dexport[:nexport]))
1239 1240
}

1241
func addexports(ctxt *Link) {
1242
	var e IMAGE_EXPORT_DIRECTORY
Russ Cox's avatar
Russ Cox committed
1243

1244
	size := binary.Size(&e) + 10*nexport + len(*flagOutfile) + 1
Russ Cox's avatar
Russ Cox committed
1245
	for i := 0; i < nexport; i++ {
1246
		size += len(dexport[i].Extname()) + 1
1247 1248 1249 1250 1251 1252
	}

	if nexport == 0 {
		return
	}

1253
	sect := pefile.addSection(".edata", size, size)
1254
	sect.characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ
1255
	sect.checkOffset(ctxt.Out.Offset())
1256
	va := int(sect.virtualAddress)
1257
	pefile.dataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress = uint32(va)
1258
	pefile.dataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size = sect.virtualSize
1259

1260 1261 1262
	vaName := va + binary.Size(&e) + nexport*4
	vaAddr := va + binary.Size(&e)
	vaNa := va + binary.Size(&e) + nexport*8
1263 1264 1265 1266 1267 1268 1269 1270

	e.Characteristics = 0
	e.MajorVersion = 0
	e.MinorVersion = 0
	e.NumberOfFunctions = uint32(nexport)
	e.NumberOfNames = uint32(nexport)
	e.Name = uint32(va+binary.Size(&e)) + uint32(nexport)*10 // Program names.
	e.Base = 1
1271 1272 1273
	e.AddressOfFunctions = uint32(vaAddr)
	e.AddressOfNames = uint32(vaName)
	e.AddressOfNameOrdinals = uint32(vaNa)
1274

1275 1276
	out := ctxt.Out

1277
	// put IMAGE_EXPORT_DIRECTORY
1278
	binary.Write(out, binary.LittleEndian, &e)
1279 1280

	// put EXPORT Address Table
Russ Cox's avatar
Russ Cox committed
1281
	for i := 0; i < nexport; i++ {
1282
		out.Write32(uint32(dexport[i].Value - PEBASE))
1283 1284 1285
	}

	// put EXPORT Name Pointer Table
1286
	v := int(e.Name + uint32(len(*flagOutfile)) + 1)
1287

Russ Cox's avatar
Russ Cox committed
1288
	for i := 0; i < nexport; i++ {
1289
		out.Write32(uint32(v))
1290
		v += len(dexport[i].Extname()) + 1
1291 1292 1293
	}

	// put EXPORT Ordinal Table
Russ Cox's avatar
Russ Cox committed
1294
	for i := 0; i < nexport; i++ {
1295
		out.Write16(uint16(i))
1296 1297 1298
	}

	// put Names
1299
	out.WriteStringN(*flagOutfile, len(*flagOutfile)+1)
1300

Russ Cox's avatar
Russ Cox committed
1301
	for i := 0; i < nexport; i++ {
1302
		out.WriteStringN(dexport[i].Extname(), len(dexport[i].Extname())+1)
1303
	}
1304
	sect.pad(out, uint32(size))
1305 1306
}

1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
// peBaseRelocEntry represents a single relocation entry.
type peBaseRelocEntry struct {
	typeOff uint16
	rel     *sym.Reloc
	sym     *sym.Symbol // For debug
}

// peBaseRelocBlock represents a Base Relocation Block. A block
// is a collection of relocation entries in a page, where each
// entry describes a single relocation.
// The block page RVA (Relative Virtual Address) is the index
// into peBaseRelocTable.blocks.
type peBaseRelocBlock struct {
	entries []peBaseRelocEntry
}

// pePages is a type used to store the list of pages for which there
// are base relocation blocks. This is defined as a type so that
// it can be sorted.
type pePages []uint32

func (p pePages) Len() int           { return len(p) }
func (p pePages) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p pePages) Less(i, j int) bool { return p[i] < p[j] }

// A PE base relocation table is a list of blocks, where each block
// contains relocation information for a single page. The blocks
// must be emitted in order of page virtual address.
// See https://docs.microsoft.com/en-us/windows/desktop/debug/pe-format#the-reloc-section-image-only
type peBaseRelocTable struct {
	blocks map[uint32]peBaseRelocBlock

	// pePages is a list of keys into blocks map.
	// It is stored separately for ease of sorting.
	pages pePages
}

func (rt *peBaseRelocTable) init(ctxt *Link) {
	rt.blocks = make(map[uint32]peBaseRelocBlock)
}

func (rt *peBaseRelocTable) addentry(ctxt *Link, s *sym.Symbol, r *sym.Reloc) {
	// pageSize is the size in bytes of a page
	// described by a base relocation block.
	const pageSize = 0x1000
	const pageMask = pageSize - 1

	addr := s.Value + int64(r.Off) - int64(PEBASE)
	page := uint32(addr &^ pageMask)
	off := uint32(addr & pageMask)

	b, ok := rt.blocks[page]
	if !ok {
		rt.pages = append(rt.pages, page)
	}

	e := peBaseRelocEntry{
		typeOff: uint16(off & 0xFFF),
		rel:     r,
		sym:     s,
	}

	// Set entry type
	switch r.Siz {
	default:
		Exitf("unsupported relocation size %d\n", r.Siz)
	case 4:
		e.typeOff |= uint16(IMAGE_REL_BASED_HIGHLOW << 12)
	}

	b.entries = append(b.entries, e)
	rt.blocks[page] = b
}

func (rt *peBaseRelocTable) write(ctxt *Link) {
	out := ctxt.Out

	// sort the pages array
	sort.Sort(rt.pages)

	for _, p := range rt.pages {
		b := rt.blocks[p]
		const sizeOfPEbaseRelocBlock = 8 // 2 * sizeof(uint32)
		blockSize := uint32(sizeOfPEbaseRelocBlock + len(b.entries)*2)
		out.Write32(p)
		out.Write32(blockSize)

		for _, e := range b.entries {
			out.Write16(e.typeOff)
		}
	}
}

func addPEBaseRelocSym(ctxt *Link, s *sym.Symbol, rt *peBaseRelocTable) {
	for ri := 0; ri < len(s.R); ri++ {
		r := &s.R[ri]

		if r.Sym == nil {
			continue
		}
		if !r.Sym.Attr.Reachable() {
			continue
		}
		if r.Type >= 256 {
			continue
		}
		if r.Siz == 0 { // informational relocation
			continue
		}
		if r.Type == objabi.R_DWARFFILEREF {
			continue
		}

		switch r.Type {
		default:
		case objabi.R_ADDR:
			rt.addentry(ctxt, s, r)
		}
	}
}

func addPEBaseReloc(ctxt *Link) {
	// We only generate base relocation table for ARM (and ... ARM64), x86, and AMD64 are marked as legacy
	// archs and can use fixed base with no base relocation information
	switch ctxt.Arch.Family {
	default:
		return
	case sys.ARM:
	}

	var rt peBaseRelocTable
	rt.init(ctxt)

	// Get relocation information
	for _, s := range ctxt.Textp {
		addPEBaseRelocSym(ctxt, s, &rt)
	}
	for _, s := range datap {
		addPEBaseRelocSym(ctxt, s, &rt)
	}

	// Write relocation information
	startoff := ctxt.Out.Offset()
	rt.write(ctxt)
	size := ctxt.Out.Offset() - startoff

	// Add a PE section and pad it at the end
	rsect := pefile.addSection(".reloc", int(size), int(size))
	rsect.characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_DISCARDABLE
	rsect.checkOffset(startoff)
	rsect.pad(ctxt.Out, uint32(size))

	pefile.dataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress = rsect.virtualAddress
	pefile.dataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size = rsect.virtualSize
}

1463 1464 1465
func (ctxt *Link) dope() {
	initdynimport(ctxt)
	initdynexport(ctxt)
1466 1467
}

1468
func setpersrc(ctxt *Link, sym *sym.Symbol) {
1469
	if rsrcsym != nil {
1470
		Errorf(sym, "too many .rsrc sections")
1471 1472 1473 1474 1475
	}

	rsrcsym = sym
}

1476
func addpersrc(ctxt *Link) {
1477 1478 1479 1480
	if rsrcsym == nil {
		return
	}

1481
	h := pefile.addSection(".rsrc", int(rsrcsym.Size), int(rsrcsym.Size))
1482
	h.characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_CNT_INITIALIZED_DATA
1483
	h.checkOffset(ctxt.Out.Offset())
1484 1485

	// relocation
1486 1487 1488 1489
	for ri := range rsrcsym.R {
		r := &rsrcsym.R[ri]
		p := rsrcsym.P[r.Off:]
		val := uint32(int64(h.virtualAddress) + r.Add)
1490 1491 1492 1493 1494 1495 1496 1497 1498

		// 32-bit little-endian
		p[0] = byte(val)

		p[1] = byte(val >> 8)
		p[2] = byte(val >> 16)
		p[3] = byte(val >> 24)
	}

1499 1500
	ctxt.Out.Write(rsrcsym.P)
	h.pad(ctxt.Out, uint32(rsrcsym.Size))
1501 1502

	// update data directory
1503
	pefile.dataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = h.virtualAddress
1504

1505
	pefile.dataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = h.virtualSize
1506 1507
}

1508
func Asmbpe(ctxt *Link) {
1509
	switch ctxt.Arch.Family {
1510
	default:
1511
		Exitf("unknown PE architecture: %v", ctxt.Arch.Family)
1512
	case sys.AMD64, sys.I386, sys.ARM:
1513 1514
	}

1515
	t := pefile.addSection(".text", int(Segtext.Length), int(Segtext.Length))
1516
	t.characteristics = IMAGE_SCN_CNT_CODE | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ
1517
	if ctxt.LinkMode == LinkExternal {
1518 1519
		// some data symbols (e.g. masks) end up in the .text section, and they normally
		// expect larger alignment requirement than the default text section alignment.
1520
		t.characteristics |= IMAGE_SCN_ALIGN_32BYTES
1521
	}
1522
	t.checkSegment(&Segtext)
1523
	pefile.textSect = t
1524

1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
	ro := pefile.addSection(".rdata", int(Segrodata.Length), int(Segrodata.Length))
	ro.characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ
	if ctxt.LinkMode == LinkExternal {
		// some data symbols (e.g. masks) end up in the .rdata section, and they normally
		// expect larger alignment requirement than the default text section alignment.
		ro.characteristics |= IMAGE_SCN_ALIGN_32BYTES
	}
	ro.checkSegment(&Segrodata)
	pefile.rdataSect = ro

1535
	var d *peSection
1536
	if ctxt.LinkMode != LinkExternal {
1537
		d = pefile.addSection(".data", int(Segdata.Length), int(Segdata.Filelen))
1538
		d.characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE
1539
		d.checkSegment(&Segdata)
1540
		pefile.dataSect = d
1541
	} else {
1542
		d = pefile.addSection(".data", int(Segdata.Filelen), int(Segdata.Filelen))
1543
		d.characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_ALIGN_32BYTES
1544
		d.checkSegment(&Segdata)
1545
		pefile.dataSect = d
1546

1547
		b := pefile.addSection(".bss", int(Segdata.Length-Segdata.Filelen), 0)
1548 1549
		b.characteristics = IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_ALIGN_32BYTES
		b.pointerToRawData = 0
1550
		pefile.bssSect = b
1551
	}
1552

1553
	pefile.addDWARF()
1554

1555
	if ctxt.LinkMode == LinkExternal {
1556
		pefile.ctorsSect = pefile.addInitArray(ctxt)
1557 1558
	}

1559
	ctxt.Out.SeekSet(int64(pefile.nextFileOffset))
1560
	if ctxt.LinkMode != LinkExternal {
1561 1562
		addimports(ctxt, d)
		addexports(ctxt)
1563
		addPEBaseReloc(ctxt)
1564
	}
1565
	pefile.writeSymbolTableAndStringTable(ctxt)
1566
	addpersrc(ctxt)
1567
	if ctxt.LinkMode == LinkExternal {
1568
		pefile.emitRelocations(ctxt)
1569
	}
1570

1571
	pewrite(ctxt)
1572
}