elf.go 62.6 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/obj"
9
	"crypto/sha1"
10
	"encoding/binary"
11
	"fmt"
12
	"path/filepath"
13
	"sort"
14
	"strings"
15 16 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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 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
)

/*
 * Derived from:
 * $FreeBSD: src/sys/sys/elf32.h,v 1.8.14.1 2005/12/30 22:13:58 marcel Exp $
 * $FreeBSD: src/sys/sys/elf64.h,v 1.10.14.1 2005/12/30 22:13:58 marcel Exp $
 * $FreeBSD: src/sys/sys/elf_common.h,v 1.15.8.1 2005/12/30 22:13:58 marcel Exp $
 * $FreeBSD: src/sys/alpha/include/elf.h,v 1.14 2003/09/25 01:10:22 peter Exp $
 * $FreeBSD: src/sys/amd64/include/elf.h,v 1.18 2004/08/03 08:21:48 dfr Exp $
 * $FreeBSD: src/sys/arm/include/elf.h,v 1.5.2.1 2006/06/30 21:42:52 cognet Exp $
 * $FreeBSD: src/sys/i386/include/elf.h,v 1.16 2004/08/02 19:12:17 dfr Exp $
 * $FreeBSD: src/sys/powerpc/include/elf.h,v 1.7 2004/11/02 09:47:01 ssouhlal Exp $
 * $FreeBSD: src/sys/sparc64/include/elf.h,v 1.12 2003/09/25 01:10:26 peter Exp $
 *
 * Copyright (c) 1996-1998 John D. Polstra.  All rights reserved.
 * Copyright (c) 2001 David E. O'Brien
 * Portions Copyright 2009 The Go Authors.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

/*
 * ELF definitions that are independent of architecture or word size.
 */

/*
 * Note header.  The ".note" section contains an array of notes.  Each
 * begins with this header, aligned to a word boundary.  Immediately
 * following the note header is n_namesz bytes of name, padded to the
 * next word boundary.  Then comes n_descsz bytes of descriptor, again
 * padded to a word boundary.  The values of n_namesz and n_descsz do
 * not include the padding.
 */
type Elf_Note struct {
	n_namesz uint32
	n_descsz uint32
	n_type   uint32
}

const (
	EI_MAG0              = 0
	EI_MAG1              = 1
	EI_MAG2              = 2
	EI_MAG3              = 3
	EI_CLASS             = 4
	EI_DATA              = 5
	EI_VERSION           = 6
	EI_OSABI             = 7
	EI_ABIVERSION        = 8
	OLD_EI_BRAND         = 8
	EI_PAD               = 9
	EI_NIDENT            = 16
	ELFMAG0              = 0x7f
	ELFMAG1              = 'E'
	ELFMAG2              = 'L'
	ELFMAG3              = 'F'
	SELFMAG              = 4
	EV_NONE              = 0
	EV_CURRENT           = 1
	ELFCLASSNONE         = 0
	ELFCLASS32           = 1
	ELFCLASS64           = 2
	ELFDATANONE          = 0
	ELFDATA2LSB          = 1
	ELFDATA2MSB          = 2
	ELFOSABI_NONE        = 0
	ELFOSABI_HPUX        = 1
	ELFOSABI_NETBSD      = 2
	ELFOSABI_LINUX       = 3
	ELFOSABI_HURD        = 4
	ELFOSABI_86OPEN      = 5
	ELFOSABI_SOLARIS     = 6
	ELFOSABI_AIX         = 7
	ELFOSABI_IRIX        = 8
	ELFOSABI_FREEBSD     = 9
	ELFOSABI_TRU64       = 10
	ELFOSABI_MODESTO     = 11
	ELFOSABI_OPENBSD     = 12
	ELFOSABI_OPENVMS     = 13
	ELFOSABI_NSK         = 14
	ELFOSABI_ARM         = 97
	ELFOSABI_STANDALONE  = 255
	ELFOSABI_SYSV        = ELFOSABI_NONE
	ELFOSABI_MONTEREY    = ELFOSABI_AIX
	ET_NONE              = 0
	ET_REL               = 1
	ET_EXEC              = 2
	ET_DYN               = 3
	ET_CORE              = 4
	ET_LOOS              = 0xfe00
	ET_HIOS              = 0xfeff
	ET_LOPROC            = 0xff00
	ET_HIPROC            = 0xffff
	EM_NONE              = 0
	EM_M32               = 1
	EM_SPARC             = 2
	EM_386               = 3
	EM_68K               = 4
	EM_88K               = 5
	EM_860               = 7
	EM_MIPS              = 8
	EM_S370              = 9
	EM_MIPS_RS3_LE       = 10
	EM_PARISC            = 15
	EM_VPP500            = 17
	EM_SPARC32PLUS       = 18
	EM_960               = 19
	EM_PPC               = 20
	EM_PPC64             = 21
	EM_S390              = 22
	EM_V800              = 36
	EM_FR20              = 37
	EM_RH32              = 38
	EM_RCE               = 39
	EM_ARM               = 40
	EM_SH                = 42
	EM_SPARCV9           = 43
	EM_TRICORE           = 44
	EM_ARC               = 45
	EM_H8_300            = 46
	EM_H8_300H           = 47
	EM_H8S               = 48
	EM_H8_500            = 49
	EM_IA_64             = 50
	EM_MIPS_X            = 51
	EM_COLDFIRE          = 52
	EM_68HC12            = 53
	EM_MMA               = 54
	EM_PCP               = 55
	EM_NCPU              = 56
	EM_NDR1              = 57
	EM_STARCORE          = 58
	EM_ME16              = 59
	EM_ST100             = 60
	EM_TINYJ             = 61
	EM_X86_64            = 62
171
	EM_AARCH64           = 183
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
	EM_486               = 6
	EM_MIPS_RS4_BE       = 10
	EM_ALPHA_STD         = 41
	EM_ALPHA             = 0x9026
	SHN_UNDEF            = 0
	SHN_LORESERVE        = 0xff00
	SHN_LOPROC           = 0xff00
	SHN_HIPROC           = 0xff1f
	SHN_LOOS             = 0xff20
	SHN_HIOS             = 0xff3f
	SHN_ABS              = 0xfff1
	SHN_COMMON           = 0xfff2
	SHN_XINDEX           = 0xffff
	SHN_HIRESERVE        = 0xffff
	SHT_NULL             = 0
	SHT_PROGBITS         = 1
	SHT_SYMTAB           = 2
	SHT_STRTAB           = 3
	SHT_RELA             = 4
	SHT_HASH             = 5
	SHT_DYNAMIC          = 6
	SHT_NOTE             = 7
	SHT_NOBITS           = 8
	SHT_REL              = 9
	SHT_SHLIB            = 10
	SHT_DYNSYM           = 11
	SHT_INIT_ARRAY       = 14
	SHT_FINI_ARRAY       = 15
	SHT_PREINIT_ARRAY    = 16
	SHT_GROUP            = 17
	SHT_SYMTAB_SHNDX     = 18
	SHT_LOOS             = 0x60000000
	SHT_HIOS             = 0x6fffffff
	SHT_GNU_VERDEF       = 0x6ffffffd
	SHT_GNU_VERNEED      = 0x6ffffffe
	SHT_GNU_VERSYM       = 0x6fffffff
	SHT_LOPROC           = 0x70000000
209
	SHT_ARM_ATTRIBUTES   = 0x70000003
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 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
	SHT_HIPROC           = 0x7fffffff
	SHT_LOUSER           = 0x80000000
	SHT_HIUSER           = 0xffffffff
	SHF_WRITE            = 0x1
	SHF_ALLOC            = 0x2
	SHF_EXECINSTR        = 0x4
	SHF_MERGE            = 0x10
	SHF_STRINGS          = 0x20
	SHF_INFO_LINK        = 0x40
	SHF_LINK_ORDER       = 0x80
	SHF_OS_NONCONFORMING = 0x100
	SHF_GROUP            = 0x200
	SHF_TLS              = 0x400
	SHF_MASKOS           = 0x0ff00000
	SHF_MASKPROC         = 0xf0000000
	PT_NULL              = 0
	PT_LOAD              = 1
	PT_DYNAMIC           = 2
	PT_INTERP            = 3
	PT_NOTE              = 4
	PT_SHLIB             = 5
	PT_PHDR              = 6
	PT_TLS               = 7
	PT_LOOS              = 0x60000000
	PT_HIOS              = 0x6fffffff
	PT_LOPROC            = 0x70000000
	PT_HIPROC            = 0x7fffffff
	PT_GNU_STACK         = 0x6474e551
	PT_PAX_FLAGS         = 0x65041580
	PF_X                 = 0x1
	PF_W                 = 0x2
	PF_R                 = 0x4
	PF_MASKOS            = 0x0ff00000
	PF_MASKPROC          = 0xf0000000
	DT_NULL              = 0
	DT_NEEDED            = 1
	DT_PLTRELSZ          = 2
	DT_PLTGOT            = 3
	DT_HASH              = 4
	DT_STRTAB            = 5
	DT_SYMTAB            = 6
	DT_RELA              = 7
	DT_RELASZ            = 8
	DT_RELAENT           = 9
	DT_STRSZ             = 10
	DT_SYMENT            = 11
	DT_INIT              = 12
	DT_FINI              = 13
	DT_SONAME            = 14
	DT_RPATH             = 15
	DT_SYMBOLIC          = 16
	DT_REL               = 17
	DT_RELSZ             = 18
	DT_RELENT            = 19
	DT_PLTREL            = 20
	DT_DEBUG             = 21
	DT_TEXTREL           = 22
	DT_JMPREL            = 23
	DT_BIND_NOW          = 24
	DT_INIT_ARRAY        = 25
	DT_FINI_ARRAY        = 26
	DT_INIT_ARRAYSZ      = 27
	DT_FINI_ARRAYSZ      = 28
	DT_RUNPATH           = 29
	DT_FLAGS             = 30
	DT_ENCODING          = 32
	DT_PREINIT_ARRAY     = 32
	DT_PREINIT_ARRAYSZ   = 33
	DT_LOOS              = 0x6000000d
	DT_HIOS              = 0x6ffff000
	DT_LOPROC            = 0x70000000
	DT_HIPROC            = 0x7fffffff
	DT_VERNEED           = 0x6ffffffe
	DT_VERNEEDNUM        = 0x6fffffff
	DT_VERSYM            = 0x6ffffff0
	DT_PPC64_GLINK       = DT_LOPROC + 0
	DT_PPC64_OPT         = DT_LOPROC + 3
	DF_ORIGIN            = 0x0001
	DF_SYMBOLIC          = 0x0002
	DF_TEXTREL           = 0x0004
	DF_BIND_NOW          = 0x0008
	DF_STATIC_TLS        = 0x0010
	NT_PRSTATUS          = 1
	NT_FPREGSET          = 2
	NT_PRPSINFO          = 3
	STB_LOCAL            = 0
	STB_GLOBAL           = 1
	STB_WEAK             = 2
	STB_LOOS             = 10
	STB_HIOS             = 12
	STB_LOPROC           = 13
	STB_HIPROC           = 15
	STT_NOTYPE           = 0
	STT_OBJECT           = 1
	STT_FUNC             = 2
	STT_SECTION          = 3
	STT_FILE             = 4
	STT_COMMON           = 5
	STT_TLS              = 6
	STT_LOOS             = 10
	STT_HIOS             = 12
	STT_LOPROC           = 13
	STT_HIPROC           = 15
	STV_DEFAULT          = 0x0
	STV_INTERNAL         = 0x1
	STV_HIDDEN           = 0x2
	STV_PROTECTED        = 0x3
	STN_UNDEF            = 0
)

/* For accessing the fields of r_info. */

/* For constructing r_info from field values. */

/*
 * Relocation types.
 */
const (
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
	R_X86_64_NONE           = 0
	R_X86_64_64             = 1
	R_X86_64_PC32           = 2
	R_X86_64_GOT32          = 3
	R_X86_64_PLT32          = 4
	R_X86_64_COPY           = 5
	R_X86_64_GLOB_DAT       = 6
	R_X86_64_JMP_SLOT       = 7
	R_X86_64_RELATIVE       = 8
	R_X86_64_GOTPCREL       = 9
	R_X86_64_32             = 10
	R_X86_64_32S            = 11
	R_X86_64_16             = 12
	R_X86_64_PC16           = 13
	R_X86_64_8              = 14
	R_X86_64_PC8            = 15
	R_X86_64_DTPMOD64       = 16
	R_X86_64_DTPOFF64       = 17
	R_X86_64_TPOFF64        = 18
	R_X86_64_TLSGD          = 19
	R_X86_64_TLSLD          = 20
	R_X86_64_DTPOFF32       = 21
	R_X86_64_GOTTPOFF       = 22
	R_X86_64_TPOFF32        = 23
	R_X86_64_PC64           = 24
	R_X86_64_GOTOFF64       = 25
	R_X86_64_GOTPC32        = 26
	R_X86_64_GOT64          = 27
	R_X86_64_GOTPCREL64     = 28
	R_X86_64_GOTPC64        = 29
	R_X86_64_GOTPLT64       = 30
	R_X86_64_PLTOFF64       = 31
	R_X86_64_SIZE32         = 32
	R_X86_64_SIZE64         = 33
	R_X86_64_GOTPC32_TLSDEC = 34
	R_X86_64_TLSDESC_CALL   = 35
	R_X86_64_TLSDESC        = 36
	R_X86_64_IRELATIVE      = 37
	R_X86_64_PC32_BND       = 40
	R_X86_64_GOTPCRELX      = 41
	R_X86_64_REX_GOTPCRELX  = 42
369

370 371 372 373 374
	R_AARCH64_ABS64                       = 257
	R_AARCH64_ABS32                       = 258
	R_AARCH64_CALL26                      = 283
	R_AARCH64_ADR_PREL_PG_HI21            = 275
	R_AARCH64_ADD_ABS_LO12_NC             = 277
375 376 377 378
	R_AARCH64_LDST8_ABS_LO12_NC           = 278
	R_AARCH64_LDST16_ABS_LO12_NC          = 284
	R_AARCH64_LDST32_ABS_LO12_NC          = 285
	R_AARCH64_LDST64_ABS_LO12_NC          = 286
379 380 381
	R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21   = 541
	R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC = 542
	R_AARCH64_TLSLE_MOVW_TPREL_G0         = 547
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451

	R_ALPHA_NONE           = 0
	R_ALPHA_REFLONG        = 1
	R_ALPHA_REFQUAD        = 2
	R_ALPHA_GPREL32        = 3
	R_ALPHA_LITERAL        = 4
	R_ALPHA_LITUSE         = 5
	R_ALPHA_GPDISP         = 6
	R_ALPHA_BRADDR         = 7
	R_ALPHA_HINT           = 8
	R_ALPHA_SREL16         = 9
	R_ALPHA_SREL32         = 10
	R_ALPHA_SREL64         = 11
	R_ALPHA_OP_PUSH        = 12
	R_ALPHA_OP_STORE       = 13
	R_ALPHA_OP_PSUB        = 14
	R_ALPHA_OP_PRSHIFT     = 15
	R_ALPHA_GPVALUE        = 16
	R_ALPHA_GPRELHIGH      = 17
	R_ALPHA_GPRELLOW       = 18
	R_ALPHA_IMMED_GP_16    = 19
	R_ALPHA_IMMED_GP_HI32  = 20
	R_ALPHA_IMMED_SCN_HI32 = 21
	R_ALPHA_IMMED_BR_HI32  = 22
	R_ALPHA_IMMED_LO32     = 23
	R_ALPHA_COPY           = 24
	R_ALPHA_GLOB_DAT       = 25
	R_ALPHA_JMP_SLOT       = 26
	R_ALPHA_RELATIVE       = 27

	R_ARM_NONE          = 0
	R_ARM_PC24          = 1
	R_ARM_ABS32         = 2
	R_ARM_REL32         = 3
	R_ARM_PC13          = 4
	R_ARM_ABS16         = 5
	R_ARM_ABS12         = 6
	R_ARM_THM_ABS5      = 7
	R_ARM_ABS8          = 8
	R_ARM_SBREL32       = 9
	R_ARM_THM_PC22      = 10
	R_ARM_THM_PC8       = 11
	R_ARM_AMP_VCALL9    = 12
	R_ARM_SWI24         = 13
	R_ARM_THM_SWI8      = 14
	R_ARM_XPC25         = 15
	R_ARM_THM_XPC22     = 16
	R_ARM_COPY          = 20
	R_ARM_GLOB_DAT      = 21
	R_ARM_JUMP_SLOT     = 22
	R_ARM_RELATIVE      = 23
	R_ARM_GOTOFF        = 24
	R_ARM_GOTPC         = 25
	R_ARM_GOT32         = 26
	R_ARM_PLT32         = 27
	R_ARM_CALL          = 28
	R_ARM_JUMP24        = 29
	R_ARM_V4BX          = 40
	R_ARM_GOT_PREL      = 96
	R_ARM_GNU_VTENTRY   = 100
	R_ARM_GNU_VTINHERIT = 101
	R_ARM_TLS_IE32      = 107
	R_ARM_TLS_LE32      = 108
	R_ARM_RSBREL32      = 250
	R_ARM_THM_RPC22     = 251
	R_ARM_RREL32        = 252
	R_ARM_RABS32        = 253
	R_ARM_RPC24         = 254
	R_ARM_RBASE         = 255

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
	R_386_NONE          = 0
	R_386_32            = 1
	R_386_PC32          = 2
	R_386_GOT32         = 3
	R_386_PLT32         = 4
	R_386_COPY          = 5
	R_386_GLOB_DAT      = 6
	R_386_JMP_SLOT      = 7
	R_386_RELATIVE      = 8
	R_386_GOTOFF        = 9
	R_386_GOTPC         = 10
	R_386_TLS_TPOFF     = 14
	R_386_TLS_IE        = 15
	R_386_TLS_GOTIE     = 16
	R_386_TLS_LE        = 17
	R_386_TLS_GD        = 18
	R_386_TLS_LDM       = 19
	R_386_TLS_GD_32     = 24
	R_386_TLS_GD_PUSH   = 25
	R_386_TLS_GD_CALL   = 26
	R_386_TLS_GD_POP    = 27
	R_386_TLS_LDM_32    = 28
	R_386_TLS_LDM_PUSH  = 29
	R_386_TLS_LDM_CALL  = 30
	R_386_TLS_LDM_POP   = 31
	R_386_TLS_LDO_32    = 32
	R_386_TLS_IE_32     = 33
	R_386_TLS_LE_32     = 34
	R_386_TLS_DTPMOD32  = 35
	R_386_TLS_DTPOFF32  = 36
	R_386_TLS_TPOFF32   = 37
	R_386_TLS_GOTDESC   = 39
	R_386_TLS_DESC_CALL = 40
	R_386_TLS_DESC      = 41
	R_386_IRELATIVE     = 42
	R_386_GOT32X        = 43
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566

	R_PPC_NONE            = 0
	R_PPC_ADDR32          = 1
	R_PPC_ADDR24          = 2
	R_PPC_ADDR16          = 3
	R_PPC_ADDR16_LO       = 4
	R_PPC_ADDR16_HI       = 5
	R_PPC_ADDR16_HA       = 6
	R_PPC_ADDR14          = 7
	R_PPC_ADDR14_BRTAKEN  = 8
	R_PPC_ADDR14_BRNTAKEN = 9
	R_PPC_REL24           = 10
	R_PPC_REL14           = 11
	R_PPC_REL14_BRTAKEN   = 12
	R_PPC_REL14_BRNTAKEN  = 13
	R_PPC_GOT16           = 14
	R_PPC_GOT16_LO        = 15
	R_PPC_GOT16_HI        = 16
	R_PPC_GOT16_HA        = 17
	R_PPC_PLTREL24        = 18
	R_PPC_COPY            = 19
	R_PPC_GLOB_DAT        = 20
	R_PPC_JMP_SLOT        = 21
	R_PPC_RELATIVE        = 22
	R_PPC_LOCAL24PC       = 23
	R_PPC_UADDR32         = 24
	R_PPC_UADDR16         = 25
	R_PPC_REL32           = 26
	R_PPC_PLT32           = 27
	R_PPC_PLTREL32        = 28
	R_PPC_PLT16_LO        = 29
	R_PPC_PLT16_HI        = 30
	R_PPC_PLT16_HA        = 31
	R_PPC_SDAREL16        = 32
	R_PPC_SECTOFF         = 33
	R_PPC_SECTOFF_LO      = 34
	R_PPC_SECTOFF_HI      = 35
	R_PPC_SECTOFF_HA      = 36
	R_PPC_TLS             = 67
	R_PPC_DTPMOD32        = 68
	R_PPC_TPREL16         = 69
	R_PPC_TPREL16_LO      = 70
	R_PPC_TPREL16_HI      = 71
	R_PPC_TPREL16_HA      = 72
	R_PPC_TPREL32         = 73
	R_PPC_DTPREL16        = 74
	R_PPC_DTPREL16_LO     = 75
	R_PPC_DTPREL16_HI     = 76
	R_PPC_DTPREL16_HA     = 77
	R_PPC_DTPREL32        = 78
	R_PPC_GOT_TLSGD16     = 79
	R_PPC_GOT_TLSGD16_LO  = 80
	R_PPC_GOT_TLSGD16_HI  = 81
	R_PPC_GOT_TLSGD16_HA  = 82
	R_PPC_GOT_TLSLD16     = 83
	R_PPC_GOT_TLSLD16_LO  = 84
	R_PPC_GOT_TLSLD16_HI  = 85
	R_PPC_GOT_TLSLD16_HA  = 86
	R_PPC_GOT_TPREL16     = 87
	R_PPC_GOT_TPREL16_LO  = 88
	R_PPC_GOT_TPREL16_HI  = 89
	R_PPC_GOT_TPREL16_HA  = 90
	R_PPC_EMB_NADDR32     = 101
	R_PPC_EMB_NADDR16     = 102
	R_PPC_EMB_NADDR16_LO  = 103
	R_PPC_EMB_NADDR16_HI  = 104
	R_PPC_EMB_NADDR16_HA  = 105
	R_PPC_EMB_SDAI16      = 106
	R_PPC_EMB_SDA2I16     = 107
	R_PPC_EMB_SDA2REL     = 108
	R_PPC_EMB_SDA21       = 109
	R_PPC_EMB_MRKREF      = 110
	R_PPC_EMB_RELSEC16    = 111
	R_PPC_EMB_RELST_LO    = 112
	R_PPC_EMB_RELST_HI    = 113
	R_PPC_EMB_RELST_HA    = 114
	R_PPC_EMB_BIT_FLD     = 115
	R_PPC_EMB_RELSDA      = 116

567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
	R_PPC64_ADDR32       = R_PPC_ADDR32
	R_PPC64_ADDR16_LO    = R_PPC_ADDR16_LO
	R_PPC64_ADDR16_HA    = R_PPC_ADDR16_HA
	R_PPC64_REL24        = R_PPC_REL24
	R_PPC64_JMP_SLOT     = R_PPC_JMP_SLOT
	R_PPC64_TPREL16      = R_PPC_TPREL16
	R_PPC64_ADDR64       = 38
	R_PPC64_TOC16        = 47
	R_PPC64_TOC16_LO     = 48
	R_PPC64_TOC16_HI     = 49
	R_PPC64_TOC16_HA     = 50
	R_PPC64_ADDR16_LO_DS = 57
	R_PPC64_TOC16_DS     = 63
	R_PPC64_TOC16_LO_DS  = 64
	R_PPC64_REL16_LO     = 250
	R_PPC64_REL16_HI     = 251
	R_PPC64_REL16_HA     = 252
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642

	R_SPARC_NONE     = 0
	R_SPARC_8        = 1
	R_SPARC_16       = 2
	R_SPARC_32       = 3
	R_SPARC_DISP8    = 4
	R_SPARC_DISP16   = 5
	R_SPARC_DISP32   = 6
	R_SPARC_WDISP30  = 7
	R_SPARC_WDISP22  = 8
	R_SPARC_HI22     = 9
	R_SPARC_22       = 10
	R_SPARC_13       = 11
	R_SPARC_LO10     = 12
	R_SPARC_GOT10    = 13
	R_SPARC_GOT13    = 14
	R_SPARC_GOT22    = 15
	R_SPARC_PC10     = 16
	R_SPARC_PC22     = 17
	R_SPARC_WPLT30   = 18
	R_SPARC_COPY     = 19
	R_SPARC_GLOB_DAT = 20
	R_SPARC_JMP_SLOT = 21
	R_SPARC_RELATIVE = 22
	R_SPARC_UA32     = 23
	R_SPARC_PLT32    = 24
	R_SPARC_HIPLT22  = 25
	R_SPARC_LOPLT10  = 26
	R_SPARC_PCPLT32  = 27
	R_SPARC_PCPLT22  = 28
	R_SPARC_PCPLT10  = 29
	R_SPARC_10       = 30
	R_SPARC_11       = 31
	R_SPARC_64       = 32
	R_SPARC_OLO10    = 33
	R_SPARC_HH22     = 34
	R_SPARC_HM10     = 35
	R_SPARC_LM22     = 36
	R_SPARC_PC_HH22  = 37
	R_SPARC_PC_HM10  = 38
	R_SPARC_PC_LM22  = 39
	R_SPARC_WDISP16  = 40
	R_SPARC_WDISP19  = 41
	R_SPARC_GLOB_JMP = 42
	R_SPARC_7        = 43
	R_SPARC_5        = 44
	R_SPARC_6        = 45
	R_SPARC_DISP64   = 46
	R_SPARC_PLT64    = 47
	R_SPARC_HIX22    = 48
	R_SPARC_LOX10    = 49
	R_SPARC_H44      = 50
	R_SPARC_M44      = 51
	R_SPARC_L44      = 52
	R_SPARC_REGISTER = 53
	R_SPARC_UA64     = 54
	R_SPARC_UA16     = 55

	ARM_MAGIC_TRAMP_NUMBER = 0x5c000003
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
)

/*
 * Symbol table entries.
 */

/* For accessing the fields of st_info. */

/* For constructing st_info from field values. */

/* For accessing the fields of st_other. */

/*
 * ELF header.
 */
type ElfEhdr struct {
	ident     [EI_NIDENT]uint8
	type_     uint16
	machine   uint16
	version   uint32
	entry     uint64
	phoff     uint64
	shoff     uint64
	flags     uint32
	ehsize    uint16
	phentsize uint16
	phnum     uint16
	shentsize uint16
	shnum     uint16
	shstrndx  uint16
}

/*
 * Section header.
 */
type ElfShdr struct {
	name      uint32
	type_     uint32
	flags     uint64
	addr      uint64
	off       uint64
	size      uint64
	link      uint32
	info      uint32
	addralign uint64
	entsize   uint64
	shnum     int
	secsym    *LSym
}

/*
 * Program header.
 */
type ElfPhdr struct {
	type_  uint32
	flags  uint32
	off    uint64
	vaddr  uint64
	paddr  uint64
	filesz uint64
	memsz  uint64
	align  uint64
}

/* For accessing the fields of r_info. */

/* For constructing r_info from field values. */

/*
 * Symbol table entries.
 */

/* For accessing the fields of st_info. */

/* For constructing st_info from field values. */

/* For accessing the fields of st_other. */

/*
 * Go linker interface
 */
const (
	ELF64HDRSIZE  = 64
	ELF64PHDRSIZE = 56
	ELF64SHDRSIZE = 64
	ELF64RELSIZE  = 16
	ELF64RELASIZE = 24
	ELF64SYMSIZE  = 24
	ELF32HDRSIZE  = 52
	ELF32PHDRSIZE = 32
	ELF32SHDRSIZE = 40
	ELF32SYMSIZE  = 16
	ELF32RELSIZE  = 8
)

/*
 * The interface uses the 64-bit structures always,
 * to avoid code duplication.  The writers know how to
 * marshal a 32-bit representation from the 64-bit structure.
 */

var Elfstrdat []byte

/*
 * Total amount of space to reserve at the start of the file
 * for Header, PHeaders, SHeaders, and interp.
 * May waste some.
 * On FreeBSD, cannot be larger than a page.
 */
const (
753
	ELFRESERVE = 4096
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
)

/*
 * We use the 64-bit data structures on both 32- and 64-bit machines
 * in order to write the code just once.  The 64-bit data structure is
 * written in the 32-bit format on the 32-bit machines.
 */
const (
	NSECT = 48
)

var Iself bool

var Nelfsym int = 1

769
var elf64 bool
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799

var ehdr ElfEhdr

var phdr [NSECT]*ElfPhdr

var shdr [NSECT]*ElfShdr

var interp string

type Elfstring struct {
	s   string
	off int
}

var elfstr [100]Elfstring

var nelfstr int

var buildinfo []byte

/*
 Initialize the global variable that describes the ELF header. It will be updated as
 we write section and prog headers.
*/
func Elfinit() {
	Iself = true

	switch Thearch.Thechar {
	// 64-bit architectures
	case '9':
800
		if Ctxt.Arch.ByteOrder == binary.BigEndian {
801 802 803 804 805 806
			ehdr.flags = 1 /* Version 1 ABI */
		} else {
			ehdr.flags = 2 /* Version 2 ABI */
		}
		fallthrough

807 808 809 810
	case '0', '6', '7':
		if Thearch.Thechar == '0' {
			ehdr.flags = 0x20000000 /* MIPS 3 */
		}
811
		elf64 = true
812 813 814 815 816 817 818

		ehdr.phoff = ELF64HDRSIZE      /* Must be be ELF64HDRSIZE: first PHdr must follow ELF header */
		ehdr.shoff = ELF64HDRSIZE      /* Will move as we add PHeaders */
		ehdr.ehsize = ELF64HDRSIZE     /* Must be ELF64HDRSIZE */
		ehdr.phentsize = ELF64PHDRSIZE /* Must be ELF64PHDRSIZE */
		ehdr.shentsize = ELF64SHDRSIZE /* Must be ELF64SHDRSIZE */

819
	// we use EABI on both linux/arm and freebsd/arm.
820 821
	// 32-bit architectures
	case '5':
822
		// we use EABI on both linux/arm and freebsd/arm.
823
		if HEADTYPE == obj.Hlinux || HEADTYPE == obj.Hfreebsd {
824 825 826 827 828 829 830 831
			// We set a value here that makes no indication of which
			// float ABI the object uses, because this is information
			// used by the dynamic linker to compare executables and
			// shared libraries -- so it only matters for cgo calls, and
			// the information properly comes from the object files
			// produced by the host C compiler. parseArmAttributes in
			// ldelf.go reads that information and updates this field as
			// appropriate.
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 860 861
			ehdr.flags = 0x5000002 // has entry point, Version5 EABI
		}
		fallthrough

	default:
		ehdr.phoff = ELF32HDRSIZE
		/* Must be be ELF32HDRSIZE: first PHdr must follow ELF header */
		ehdr.shoff = ELF32HDRSIZE      /* Will move as we add PHeaders */
		ehdr.ehsize = ELF32HDRSIZE     /* Must be ELF32HDRSIZE */
		ehdr.phentsize = ELF32PHDRSIZE /* Must be ELF32PHDRSIZE */
		ehdr.shentsize = ELF32SHDRSIZE /* Must be ELF32SHDRSIZE */
	}
}

func elf64phdr(e *ElfPhdr) {
	Thearch.Lput(e.type_)
	Thearch.Lput(e.flags)
	Thearch.Vput(e.off)
	Thearch.Vput(e.vaddr)
	Thearch.Vput(e.paddr)
	Thearch.Vput(e.filesz)
	Thearch.Vput(e.memsz)
	Thearch.Vput(e.align)
}

func elf32phdr(e *ElfPhdr) {
	if e.type_ == PT_LOAD {
		// Correct ELF loaders will do this implicitly,
		// but buggy ELF loaders like the one in some
		// versions of QEMU won't.
Russ Cox's avatar
Russ Cox committed
862
		frag := int(e.vaddr & (e.align - 1))
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907

		e.off -= uint64(frag)
		e.vaddr -= uint64(frag)
		e.paddr -= uint64(frag)
		e.filesz += uint64(frag)
		e.memsz += uint64(frag)
	}

	Thearch.Lput(e.type_)
	Thearch.Lput(uint32(e.off))
	Thearch.Lput(uint32(e.vaddr))
	Thearch.Lput(uint32(e.paddr))
	Thearch.Lput(uint32(e.filesz))
	Thearch.Lput(uint32(e.memsz))
	Thearch.Lput(e.flags)
	Thearch.Lput(uint32(e.align))
}

func elf64shdr(e *ElfShdr) {
	Thearch.Lput(e.name)
	Thearch.Lput(e.type_)
	Thearch.Vput(e.flags)
	Thearch.Vput(e.addr)
	Thearch.Vput(e.off)
	Thearch.Vput(e.size)
	Thearch.Lput(e.link)
	Thearch.Lput(e.info)
	Thearch.Vput(e.addralign)
	Thearch.Vput(e.entsize)
}

func elf32shdr(e *ElfShdr) {
	Thearch.Lput(e.name)
	Thearch.Lput(e.type_)
	Thearch.Lput(uint32(e.flags))
	Thearch.Lput(uint32(e.addr))
	Thearch.Lput(uint32(e.off))
	Thearch.Lput(uint32(e.size))
	Thearch.Lput(e.link)
	Thearch.Lput(e.info)
	Thearch.Lput(uint32(e.addralign))
	Thearch.Lput(uint32(e.entsize))
}

func elfwriteshdrs() uint32 {
908
	if elf64 {
Russ Cox's avatar
Russ Cox committed
909
		for i := 0; i < int(ehdr.shnum); i++ {
910 911 912 913 914
			elf64shdr(shdr[i])
		}
		return uint32(ehdr.shnum) * ELF64SHDRSIZE
	}

Russ Cox's avatar
Russ Cox committed
915
	for i := 0; i < int(ehdr.shnum); i++ {
916 917 918 919 920 921 922 923
		elf32shdr(shdr[i])
	}
	return uint32(ehdr.shnum) * ELF32SHDRSIZE
}

func elfsetstring(s string, off int) {
	if nelfstr >= len(elfstr) {
		Diag("too many elf strings")
924
		errorexit()
925 926 927 928 929 930 931 932
	}

	elfstr[nelfstr].s = s
	elfstr[nelfstr].off = off
	nelfstr++
}

func elfwritephdrs() uint32 {
933
	if elf64 {
Russ Cox's avatar
Russ Cox committed
934
		for i := 0; i < int(ehdr.phnum); i++ {
935 936 937 938 939
			elf64phdr(phdr[i])
		}
		return uint32(ehdr.phnum) * ELF64PHDRSIZE
	}

Russ Cox's avatar
Russ Cox committed
940
	for i := 0; i < int(ehdr.phnum); i++ {
941 942 943 944 945 946
		elf32phdr(phdr[i])
	}
	return uint32(ehdr.phnum) * ELF32PHDRSIZE
}

func newElfPhdr() *ElfPhdr {
Russ Cox's avatar
Russ Cox committed
947
	e := new(ElfPhdr)
948 949 950 951 952 953
	if ehdr.phnum >= NSECT {
		Diag("too many phdrs")
	} else {
		phdr[ehdr.phnum] = e
		ehdr.phnum++
	}
954
	if elf64 {
955 956 957 958 959 960 961 962
		ehdr.shoff += ELF64PHDRSIZE
	} else {
		ehdr.shoff += ELF32PHDRSIZE
	}
	return e
}

func newElfShdr(name int64) *ElfShdr {
Russ Cox's avatar
Russ Cox committed
963
	e := new(ElfShdr)
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
	e.name = uint32(name)
	e.shnum = int(ehdr.shnum)
	if ehdr.shnum >= NSECT {
		Diag("too many shdrs")
	} else {
		shdr[ehdr.shnum] = e
		ehdr.shnum++
	}

	return e
}

func getElfEhdr() *ElfEhdr {
	return &ehdr
}

func elf64writehdr() uint32 {
Russ Cox's avatar
Russ Cox committed
981
	for i := 0; i < EI_NIDENT; i++ {
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
		Cput(ehdr.ident[i])
	}
	Thearch.Wput(ehdr.type_)
	Thearch.Wput(ehdr.machine)
	Thearch.Lput(ehdr.version)
	Thearch.Vput(ehdr.entry)
	Thearch.Vput(ehdr.phoff)
	Thearch.Vput(ehdr.shoff)
	Thearch.Lput(ehdr.flags)
	Thearch.Wput(ehdr.ehsize)
	Thearch.Wput(ehdr.phentsize)
	Thearch.Wput(ehdr.phnum)
	Thearch.Wput(ehdr.shentsize)
	Thearch.Wput(ehdr.shnum)
	Thearch.Wput(ehdr.shstrndx)
	return ELF64HDRSIZE
}

func elf32writehdr() uint32 {
Russ Cox's avatar
Russ Cox committed
1001
	for i := 0; i < EI_NIDENT; i++ {
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
		Cput(ehdr.ident[i])
	}
	Thearch.Wput(ehdr.type_)
	Thearch.Wput(ehdr.machine)
	Thearch.Lput(ehdr.version)
	Thearch.Lput(uint32(ehdr.entry))
	Thearch.Lput(uint32(ehdr.phoff))
	Thearch.Lput(uint32(ehdr.shoff))
	Thearch.Lput(ehdr.flags)
	Thearch.Wput(ehdr.ehsize)
	Thearch.Wput(ehdr.phentsize)
	Thearch.Wput(ehdr.phnum)
	Thearch.Wput(ehdr.shentsize)
	Thearch.Wput(ehdr.shnum)
	Thearch.Wput(ehdr.shstrndx)
	return ELF32HDRSIZE
}

func elfwritehdr() uint32 {
1021
	if elf64 {
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
		return elf64writehdr()
	}
	return elf32writehdr()
}

/* Taken directly from the definition document for ELF64 */
func elfhash(name []byte) uint32 {
	var h uint32 = 0
	var g uint32
	for len(name) != 0 {
		h = (h << 4) + uint32(name[0])
		name = name[1:]
		g = h & 0xf0000000
		if g != 0 {
			h ^= g >> 24
		}
		h &= 0x0fffffff
	}

	return h
}

func Elfwritedynent(s *LSym, tag int, val uint64) {
1045
	if elf64 {
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
		Adduint64(Ctxt, s, uint64(tag))
		Adduint64(Ctxt, s, val)
	} else {
		Adduint32(Ctxt, s, uint32(tag))
		Adduint32(Ctxt, s, uint32(val))
	}
}

func elfwritedynentsym(s *LSym, tag int, t *LSym) {
	Elfwritedynentsymplus(s, tag, t, 0)
}

func Elfwritedynentsymplus(s *LSym, tag int, t *LSym, add int64) {
1059
	if elf64 {
1060 1061 1062 1063 1064 1065 1066 1067
		Adduint64(Ctxt, s, uint64(tag))
	} else {
		Adduint32(Ctxt, s, uint32(tag))
	}
	Addaddrplus(Ctxt, s, t, add)
}

func elfwritedynentsymsize(s *LSym, tag int, t *LSym) {
1068
	if elf64 {
1069 1070 1071 1072 1073 1074 1075 1076 1077
		Adduint64(Ctxt, s, uint64(tag))
	} else {
		Adduint32(Ctxt, s, uint32(tag))
	}
	addsize(Ctxt, s, t)
}

func elfinterp(sh *ElfShdr, startva uint64, resoff uint64, p string) int {
	interp = p
Russ Cox's avatar
Russ Cox committed
1078
	n := len(interp) + 1
1079 1080 1081 1082 1083 1084 1085 1086
	sh.addr = startva + resoff - uint64(n)
	sh.off = resoff - uint64(n)
	sh.size = uint64(n)

	return n
}

func elfwriteinterp() int {
Russ Cox's avatar
Russ Cox committed
1087
	sh := elfshname(".interp")
1088
	Cseek(int64(sh.off))
1089
	coutbuf.WriteString(interp)
1090 1091 1092 1093
	Cput(0)
	return int(sh.size)
}

1094
func elfnote(sh *ElfShdr, startva uint64, resoff uint64, sz int, alloc bool) int {
Russ Cox's avatar
Russ Cox committed
1095
	n := 3*4 + uint64(sz) + resoff%4
1096 1097

	sh.type_ = SHT_NOTE
1098 1099 1100
	if alloc {
		sh.flags = SHF_ALLOC
	}
1101 1102 1103 1104 1105 1106 1107 1108 1109
	sh.addralign = 4
	sh.addr = startva + resoff - n
	sh.off = resoff - n
	sh.size = n - resoff%4

	return int(n)
}

func elfwritenotehdr(str string, namesz uint32, descsz uint32, tag uint32) *ElfShdr {
Russ Cox's avatar
Russ Cox committed
1110
	sh := elfshname(str)
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126

	// Write Elf_Note header.
	Cseek(int64(sh.off))

	Thearch.Lput(namesz)
	Thearch.Lput(descsz)
	Thearch.Lput(tag)

	return sh
}

// NetBSD Signature (as per sys/exec_elf.h)
const (
	ELF_NOTE_NETBSD_NAMESZ  = 7
	ELF_NOTE_NETBSD_DESCSZ  = 4
	ELF_NOTE_NETBSD_TAG     = 1
1127
	ELF_NOTE_NETBSD_VERSION = 599000000 /* NetBSD 5.99 */
1128 1129 1130 1131 1132
)

var ELF_NOTE_NETBSD_NAME = []byte("NetBSD\x00")

func elfnetbsdsig(sh *ElfShdr, startva uint64, resoff uint64) int {
Russ Cox's avatar
Russ Cox committed
1133
	n := int(Rnd(ELF_NOTE_NETBSD_NAMESZ, 4) + Rnd(ELF_NOTE_NETBSD_DESCSZ, 4))
1134
	return elfnote(sh, startva, resoff, n, true)
1135 1136 1137 1138
}

func elfwritenetbsdsig() int {
	// Write Elf_Note header.
Russ Cox's avatar
Russ Cox committed
1139
	sh := elfwritenotehdr(".note.netbsd.ident", ELF_NOTE_NETBSD_NAMESZ, ELF_NOTE_NETBSD_DESCSZ, ELF_NOTE_NETBSD_TAG)
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164

	if sh == nil {
		return 0
	}

	// Followed by NetBSD string and version.
	Cwrite(ELF_NOTE_NETBSD_NAME)
	Cput(0)

	Thearch.Lput(ELF_NOTE_NETBSD_VERSION)

	return int(sh.size)
}

// OpenBSD Signature
const (
	ELF_NOTE_OPENBSD_NAMESZ  = 8
	ELF_NOTE_OPENBSD_DESCSZ  = 4
	ELF_NOTE_OPENBSD_TAG     = 1
	ELF_NOTE_OPENBSD_VERSION = 0
)

var ELF_NOTE_OPENBSD_NAME = []byte("OpenBSD\x00")

func elfopenbsdsig(sh *ElfShdr, startva uint64, resoff uint64) int {
Russ Cox's avatar
Russ Cox committed
1165
	n := ELF_NOTE_OPENBSD_NAMESZ + ELF_NOTE_OPENBSD_DESCSZ
1166
	return elfnote(sh, startva, resoff, n, true)
1167 1168 1169 1170
}

func elfwriteopenbsdsig() int {
	// Write Elf_Note header.
Russ Cox's avatar
Russ Cox committed
1171
	sh := elfwritenotehdr(".note.openbsd.ident", ELF_NOTE_OPENBSD_NAMESZ, ELF_NOTE_OPENBSD_DESCSZ, ELF_NOTE_OPENBSD_TAG)
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188

	if sh == nil {
		return 0
	}

	// Followed by OpenBSD string and version.
	Cwrite(ELF_NOTE_OPENBSD_NAME)

	Thearch.Lput(ELF_NOTE_OPENBSD_VERSION)

	return int(sh.size)
}

func addbuildinfo(val string) {
	var j int

	if val[0] != '0' || val[1] != 'x' {
1189
		Exitf("-B argument must start with 0x: %s", val)
1190 1191
	}

Russ Cox's avatar
Russ Cox committed
1192
	ov := val
1193
	val = val[2:]
Russ Cox's avatar
Russ Cox committed
1194 1195
	i := 0
	var b int
1196 1197
	for val != "" {
		if len(val) == 1 {
1198
			Exitf("-B argument must have even number of digits: %s", ov)
1199 1200 1201
		}

		b = 0
1202
		for j = 0; j < 2; j, val = j+1, val[1:] {
1203 1204 1205 1206 1207 1208 1209 1210
			b *= 16
			if val[0] >= '0' && val[0] <= '9' {
				b += int(val[0]) - '0'
			} else if val[0] >= 'a' && val[0] <= 'f' {
				b += int(val[0]) - 'a' + 10
			} else if val[0] >= 'A' && val[0] <= 'F' {
				b += int(val[0]) - 'A' + 10
			} else {
1211
				Exitf("-B argument contains invalid hex digit %c: %s", val[0], ov)
1212 1213 1214 1215 1216
			}
		}

		const maxLen = 32
		if i >= maxLen {
1217
			Exitf("-B option too long (max %d digits): %s", maxLen, ov)
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
		}

		buildinfo = append(buildinfo, uint8(b))
		i++
	}

	buildinfo = buildinfo[:i]
}

// Build info note
const (
	ELF_NOTE_BUILDINFO_NAMESZ = 4
	ELF_NOTE_BUILDINFO_TAG    = 3
)

var ELF_NOTE_BUILDINFO_NAME = []byte("GNU\x00")

func elfbuildinfo(sh *ElfShdr, startva uint64, resoff uint64) int {
Russ Cox's avatar
Russ Cox committed
1236
	n := int(ELF_NOTE_BUILDINFO_NAMESZ + Rnd(int64(len(buildinfo)), 4))
1237
	return elfnote(sh, startva, resoff, n, true)
1238 1239
}

1240 1241 1242 1243 1244
func elfgobuildid(sh *ElfShdr, startva uint64, resoff uint64) int {
	n := len(ELF_NOTE_GO_NAME) + int(Rnd(int64(len(buildid)), 4))
	return elfnote(sh, startva, resoff, n, true)
}

1245
func elfwritebuildinfo() int {
Russ Cox's avatar
Russ Cox committed
1246
	sh := elfwritenotehdr(".note.gnu.build-id", ELF_NOTE_BUILDINFO_NAMESZ, uint32(len(buildinfo)), ELF_NOTE_BUILDINFO_TAG)
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
	if sh == nil {
		return 0
	}

	Cwrite(ELF_NOTE_BUILDINFO_NAME)
	Cwrite(buildinfo)
	var zero = make([]byte, 4)
	Cwrite(zero[:int(Rnd(int64(len(buildinfo)), 4)-int64(len(buildinfo)))])

	return int(sh.size)
}

1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
func elfwritegobuildid() int {
	sh := elfwritenotehdr(".note.go.buildid", uint32(len(ELF_NOTE_GO_NAME)), uint32(len(buildid)), ELF_NOTE_GOBUILDID_TAG)
	if sh == nil {
		return 0
	}

	Cwrite(ELF_NOTE_GO_NAME)
	Cwrite([]byte(buildid))
	var zero = make([]byte, 4)
	Cwrite(zero[:int(Rnd(int64(len(buildid)), 4)-int64(len(buildid)))])

	return int(sh.size)
}

1273
// Go specific notes
1274 1275
const (
	ELF_NOTE_GOPKGLIST_TAG = 1
1276
	ELF_NOTE_GOABIHASH_TAG = 2
1277
	ELF_NOTE_GODEPS_TAG    = 3
1278
	ELF_NOTE_GOBUILDID_TAG = 4
1279 1280
)

1281
var ELF_NOTE_GO_NAME = []byte("Go\x00\x00")
1282

1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
var elfverneed int

type Elfaux struct {
	next *Elfaux
	num  int
	vers string
}

type Elflib struct {
	next *Elflib
	aux  *Elfaux
	file string
}

func addelflib(list **Elflib, file string, vers string) *Elfaux {
	var lib *Elflib

	for lib = *list; lib != nil; lib = lib.next {
		if lib.file == file {
			goto havelib
		}
	}
	lib = new(Elflib)
	lib.next = *list
	lib.file = file
	*list = lib

havelib:
Russ Cox's avatar
Russ Cox committed
1311
	for aux := lib.aux; aux != nil; aux = aux.next {
1312
		if aux.vers == vers {
Russ Cox's avatar
Russ Cox committed
1313
			return aux
1314 1315
		}
	}
Russ Cox's avatar
Russ Cox committed
1316
	aux := new(Elfaux)
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
	aux.next = lib.aux
	aux.vers = vers
	lib.aux = aux

	return aux
}

func elfdynhash() {
	if !Iself {
		return
	}

Russ Cox's avatar
Russ Cox committed
1329 1330
	nsym := Nelfsym
	s := Linklookup(Ctxt, ".hash", 0)
1331
	s.Type = obj.SELFROSECT
1332 1333
	s.Reachable = true

Russ Cox's avatar
Russ Cox committed
1334 1335
	i := nsym
	nbucket := 1
1336 1337 1338 1339 1340
	for i > 0 {
		nbucket++
		i >>= 1
	}

Russ Cox's avatar
Russ Cox committed
1341
	var needlib *Elflib
Russ Cox's avatar
Russ Cox committed
1342 1343 1344
	need := make([]*Elfaux, nsym)
	chain := make([]uint32, nsym)
	buckets := make([]uint32, nbucket)
1345

Russ Cox's avatar
Russ Cox committed
1346 1347 1348 1349
	var b int
	var hc uint32
	var name string
	for sy := Ctxt.Allsym; sy != nil; sy = sy.Allsym {
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
		if sy.Dynid <= 0 {
			continue
		}

		if sy.Dynimpvers != "" {
			need[sy.Dynid] = addelflib(&needlib, sy.Dynimplib, sy.Dynimpvers)
		}

		name = sy.Extname
		hc = elfhash([]byte(name))

		b = int(hc % uint32(nbucket))
		chain[sy.Dynid] = buckets[b]
		buckets[b] = uint32(sy.Dynid)
	}

	Adduint32(Ctxt, s, uint32(nbucket))
	Adduint32(Ctxt, s, uint32(nsym))
Russ Cox's avatar
Russ Cox committed
1368
	for i := 0; i < nbucket; i++ {
1369 1370
		Adduint32(Ctxt, s, buckets[i])
	}
Russ Cox's avatar
Russ Cox committed
1371
	for i := 0; i < nsym; i++ {
1372 1373 1374 1375
		Adduint32(Ctxt, s, chain[i])
	}

	// version symbols
Russ Cox's avatar
Russ Cox committed
1376
	dynstr := Linklookup(Ctxt, ".dynstr", 0)
1377 1378 1379

	s = Linklookup(Ctxt, ".gnu.version_r", 0)
	i = 2
Russ Cox's avatar
Russ Cox committed
1380 1381 1382 1383
	nfile := 0
	var j int
	var x *Elfaux
	for l := needlib; l != nil; l = l.next {
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
		nfile++

		// header
		Adduint16(Ctxt, s, 1) // table version
		j = 0
		for x = l.aux; x != nil; x = x.next {
			j++
		}
		Adduint16(Ctxt, s, uint16(j))                         // aux count
		Adduint32(Ctxt, s, uint32(Addstring(dynstr, l.file))) // file string offset
		Adduint32(Ctxt, s, 16)                                // offset from header to first aux
		if l.next != nil {
			Adduint32(Ctxt, s, 16+uint32(j)*16) // offset from this header to next
		} else {
			Adduint32(Ctxt, s, 0)
		}

		for x = l.aux; x != nil; x = x.next {
			x.num = i
			i++

			// aux struct
			Adduint32(Ctxt, s, elfhash([]byte(x.vers)))           // hash
			Adduint16(Ctxt, s, 0)                                 // flags
			Adduint16(Ctxt, s, uint16(x.num))                     // other - index we refer to this by
			Adduint32(Ctxt, s, uint32(Addstring(dynstr, x.vers))) // version string offset
			if x.next != nil {
				Adduint32(Ctxt, s, 16) // offset from this aux to next
			} else {
				Adduint32(Ctxt, s, 0)
			}
		}
	}

	// version references
	s = Linklookup(Ctxt, ".gnu.version", 0)

Russ Cox's avatar
Russ Cox committed
1421
	for i := 0; i < nsym; i++ {
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
		if i == 0 {
			Adduint16(Ctxt, s, 0) // first entry - no symbol
		} else if need[i] == nil {
			Adduint16(Ctxt, s, 1) // global
		} else {
			Adduint16(Ctxt, s, uint16(need[i].num))
		}
	}

	s = Linklookup(Ctxt, ".dynamic", 0)
	elfverneed = nfile
	if elfverneed != 0 {
		elfwritedynentsym(s, DT_VERNEED, Linklookup(Ctxt, ".gnu.version_r", 0))
		Elfwritedynent(s, DT_VERNEEDNUM, uint64(nfile))
		elfwritedynentsym(s, DT_VERSYM, Linklookup(Ctxt, ".gnu.version", 0))
	}

1439
	switch Thearch.Thechar {
1440
	case '0', '6', '7', '9':
Russ Cox's avatar
Russ Cox committed
1441
		sy := Linklookup(Ctxt, ".rela.plt", 0)
1442 1443 1444 1445 1446
		if sy.Size > 0 {
			Elfwritedynent(s, DT_PLTREL, DT_RELA)
			elfwritedynentsymsize(s, DT_PLTRELSZ, sy)
			elfwritedynentsym(s, DT_JMPREL, sy)
		}
1447
	default:
Russ Cox's avatar
Russ Cox committed
1448
		sy := Linklookup(Ctxt, ".rel.plt", 0)
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
		if sy.Size > 0 {
			Elfwritedynent(s, DT_PLTREL, DT_REL)
			elfwritedynentsymsize(s, DT_PLTRELSZ, sy)
			elfwritedynentsym(s, DT_JMPREL, sy)
		}
	}

	Elfwritedynent(s, DT_NULL, 0)
}

func elfphload(seg *Segment) *ElfPhdr {
Russ Cox's avatar
Russ Cox committed
1460
	ph := newElfPhdr()
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
	ph.type_ = PT_LOAD
	if seg.Rwx&4 != 0 {
		ph.flags |= PF_R
	}
	if seg.Rwx&2 != 0 {
		ph.flags |= PF_W
	}
	if seg.Rwx&1 != 0 {
		ph.flags |= PF_X
	}
	ph.vaddr = seg.Vaddr
	ph.paddr = seg.Vaddr
	ph.memsz = seg.Length
	ph.off = seg.Fileoff
	ph.filesz = seg.Filelen
	ph.align = uint64(INITRND)

	return ph
}

func elfshname(name string) *ElfShdr {
	var off int
	var sh *ElfShdr

Russ Cox's avatar
Russ Cox committed
1485
	for i := 0; i < nelfstr; i++ {
1486 1487
		if name == elfstr[i].s {
			off = elfstr[i].off
Russ Cox's avatar
Russ Cox committed
1488 1489 1490 1491 1492 1493 1494 1495 1496
			for i = 0; i < int(ehdr.shnum); i++ {
				sh = shdr[i]
				if sh.name == uint32(off) {
					return sh
				}
			}

			sh = newElfShdr(int64(off))
			return sh
1497 1498 1499 1500
		}
	}

	Diag("cannot find elf name %s", name)
1501
	errorexit()
1502 1503 1504 1505
	return nil
}

func elfshalloc(sect *Section) *ElfShdr {
Russ Cox's avatar
Russ Cox committed
1506
	sh := elfshname(sect.Name)
1507 1508 1509 1510 1511
	sect.Elfsect = sh
	return sh
}

func elfshbits(sect *Section) *ElfShdr {
Russ Cox's avatar
Russ Cox committed
1512
	sh := elfshalloc(sect)
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
	// If this section has already been set up as a note, we assume type_ and
	// flags are already correct, but the other fields still need filling in.
	if sh.type_ == SHT_NOTE {
		if Linkmode != LinkExternal {
			// TODO(mwhudson): the approach here will work OK when
			// linking internally for notes that we want to be included
			// in a loadable segment (e.g. the abihash note) but not for
			// notes that we do not want to be mapped (e.g. the package
			// list note). The real fix is probably to define new values
			// for LSym.Type corresponding to mapped and unmapped notes
			// and handle them in dodata().
			Diag("sh.type_ == SHT_NOTE in elfshbits when linking internally")
		}
		sh.addralign = uint64(sect.Align)
		sh.size = sect.Length
		sh.off = sect.Seg.Fileoff + sect.Vaddr - sect.Seg.Vaddr
		return sh
	}
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
	if sh.type_ > 0 {
		return sh
	}

	if sect.Vaddr < sect.Seg.Vaddr+sect.Seg.Filelen {
		sh.type_ = SHT_PROGBITS
	} else {
		sh.type_ = SHT_NOBITS
	}
	sh.flags = SHF_ALLOC
	if sect.Rwx&1 != 0 {
		sh.flags |= SHF_EXECINSTR
	}
	if sect.Rwx&2 != 0 {
		sh.flags |= SHF_WRITE
	}
	if sect.Name == ".tbss" {
1548
		sh.flags |= SHF_TLS
1549 1550 1551 1552 1553 1554 1555 1556
		sh.type_ = SHT_NOBITS
	}

	if Linkmode != LinkExternal {
		sh.addr = sect.Vaddr
	}
	sh.addralign = uint64(sect.Align)
	sh.size = sect.Length
1557
	if sect.Name != ".tbss" {
1558 1559
		sh.off = sect.Seg.Fileoff + sect.Vaddr - sect.Seg.Vaddr
	}
1560 1561 1562 1563 1564 1565

	return sh
}

func elfshreloc(sect *Section) *ElfShdr {
	// If main section is SHT_NOBITS, nothing to relocate.
1566
	// Also nothing to relocate in .shstrtab or notes.
1567 1568 1569 1570 1571 1572
	if sect.Vaddr >= sect.Seg.Vaddr+sect.Seg.Filelen {
		return nil
	}
	if sect.Name == ".shstrtab" || sect.Name == ".tbss" {
		return nil
	}
1573 1574 1575
	if sect.Elfsect.type_ == SHT_NOTE {
		return nil
	}
1576

Russ Cox's avatar
Russ Cox committed
1577 1578
	var prefix string
	var typ int
1579
	switch Thearch.Thechar {
1580
	case '0', '6', '7', '9':
1581 1582
		prefix = ".rela"
		typ = SHT_RELA
1583
	default:
1584 1585 1586 1587
		prefix = ".rel"
		typ = SHT_REL
	}

Russ Cox's avatar
Russ Cox committed
1588 1589
	buf := fmt.Sprintf("%s%s", prefix, sect.Name)
	sh := elfshname(buf)
1590 1591 1592 1593 1594 1595
	sh.type_ = uint32(typ)
	sh.entsize = uint64(Thearch.Regsize) * 2
	if typ == SHT_RELA {
		sh.entsize += uint64(Thearch.Regsize)
	}
	sh.link = uint32(elfshname(".symtab").shnum)
1596
	sh.info = uint32(sect.Elfsect.shnum)
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
	sh.off = sect.Reloff
	sh.size = sect.Rellen
	sh.addralign = uint64(Thearch.Regsize)
	return sh
}

func elfrelocsect(sect *Section, first *LSym) {
	// If main section is SHT_NOBITS, nothing to relocate.
	// Also nothing to relocate in .shstrtab.
	if sect.Vaddr >= sect.Seg.Vaddr+sect.Seg.Filelen {
		return
	}
	if sect.Name == ".shstrtab" {
		return
	}

	sect.Reloff = uint64(Cpos())
Russ Cox's avatar
Russ Cox committed
1614
	var sym *LSym
1615 1616 1617 1618 1619 1620 1621 1622 1623
	for sym = first; sym != nil; sym = sym.Next {
		if !sym.Reachable {
			continue
		}
		if uint64(sym.Value) >= sect.Vaddr {
			break
		}
	}

Russ Cox's avatar
Russ Cox committed
1624 1625 1626
	eaddr := int32(sect.Vaddr + sect.Length)
	var r *Reloc
	var ri int
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
	for ; sym != nil; sym = sym.Next {
		if !sym.Reachable {
			continue
		}
		if sym.Value >= int64(eaddr) {
			break
		}
		Ctxt.Cursym = sym

		for ri = 0; ri < len(sym.R); ri++ {
			r = &sym.R[ri]
			if r.Done != 0 {
				continue
			}
			if r.Xsym == nil {
				Diag("missing xsym in relocation")
				continue
			}

1646
			if r.Xsym.ElfsymForReloc() == 0 {
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
				Diag("reloc %d to non-elf symbol %s (outer=%s) %d", r.Type, r.Sym.Name, r.Xsym.Name, r.Sym.Type)
			}
			if Thearch.Elfreloc1(r, int64(uint64(sym.Value+int64(r.Off))-sect.Vaddr)) < 0 {
				Diag("unsupported obj reloc %d/%d to %s", r.Type, r.Siz, r.Sym.Name)
			}
		}
	}

	sect.Rellen = uint64(Cpos()) - sect.Reloff
}

func Elfemitreloc() {
	for Cpos()&7 != 0 {
		Cput(0)
	}

	elfrelocsect(Segtext.Sect, Ctxt.Textp)
Russ Cox's avatar
Russ Cox committed
1664
	for sect := Segtext.Sect.Next; sect != nil; sect = sect.Next {
1665 1666
		elfrelocsect(sect, datap)
	}
Russ Cox's avatar
Russ Cox committed
1667
	for sect := Segrodata.Sect; sect != nil; sect = sect.Next {
1668 1669
		elfrelocsect(sect, datap)
	}
Russ Cox's avatar
Russ Cox committed
1670
	for sect := Segdata.Sect; sect != nil; sect = sect.Next {
1671 1672 1673 1674
		elfrelocsect(sect, datap)
	}
}

1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
func addgonote(sectionName string, tag uint32, desc []byte) {
	s := Linklookup(Ctxt, sectionName, 0)
	s.Reachable = true
	s.Type = obj.SELFROSECT
	// namesz
	Adduint32(Ctxt, s, uint32(len(ELF_NOTE_GO_NAME)))
	// descsz
	Adduint32(Ctxt, s, uint32(len(desc)))
	// tag
	Adduint32(Ctxt, s, tag)
	// name + padding
	s.P = append(s.P, ELF_NOTE_GO_NAME...)
	for len(s.P)%4 != 0 {
		s.P = append(s.P, 0)
	}
	// desc + padding
	s.P = append(s.P, desc...)
	for len(s.P)%4 != 0 {
		s.P = append(s.P, 0)
	}
	s.Size = int64(len(s.P))
}

1698 1699 1700 1701 1702 1703
func doelf() {
	if !Iself {
		return
	}

	/* predefine strings we need for section headers */
Russ Cox's avatar
Russ Cox committed
1704
	shstrtab := Linklookup(Ctxt, ".shstrtab", 0)
1705

1706
	shstrtab.Type = obj.SELFROSECT
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
	shstrtab.Reachable = true

	Addstring(shstrtab, "")
	Addstring(shstrtab, ".text")
	Addstring(shstrtab, ".noptrdata")
	Addstring(shstrtab, ".data")
	Addstring(shstrtab, ".bss")
	Addstring(shstrtab, ".noptrbss")

	// generate .tbss section (except for OpenBSD where it's not supported)
	// for dynamic internal linker or external linking, so that various
	// binutils could correctly calculate PT_TLS size.
1719
	// see https://golang.org/issue/5200.
1720
	if HEADTYPE != obj.Hopenbsd {
1721 1722 1723 1724
		if Debug['d'] == 0 || Linkmode == LinkExternal {
			Addstring(shstrtab, ".tbss")
		}
	}
1725
	if HEADTYPE == obj.Hnetbsd {
1726 1727
		Addstring(shstrtab, ".note.netbsd.ident")
	}
1728
	if HEADTYPE == obj.Hopenbsd {
1729 1730 1731 1732 1733
		Addstring(shstrtab, ".note.openbsd.ident")
	}
	if len(buildinfo) > 0 {
		Addstring(shstrtab, ".note.gnu.build-id")
	}
1734 1735 1736
	if buildid != "" {
		Addstring(shstrtab, ".note.go.buildid")
	}
1737 1738
	Addstring(shstrtab, ".elfdata")
	Addstring(shstrtab, ".rodata")
1739 1740 1741
	// See the comment about data.rel.ro.FOO section names in data.go.
	relro_prefix := ""
	if UseRelro() {
1742
		Addstring(shstrtab, ".data.rel.ro")
1743 1744 1745 1746 1747
		relro_prefix = ".data.rel.ro"
	}
	Addstring(shstrtab, relro_prefix+".typelink")
	Addstring(shstrtab, relro_prefix+".gosymtab")
	Addstring(shstrtab, relro_prefix+".gopclntab")
1748 1749 1750 1751

	if Linkmode == LinkExternal {
		Debug['d'] = 1

1752
		switch Thearch.Thechar {
1753
		case '0', '6', '7', '9':
1754 1755
			Addstring(shstrtab, ".rela.text")
			Addstring(shstrtab, ".rela.rodata")
1756 1757 1758
			Addstring(shstrtab, ".rela"+relro_prefix+".typelink")
			Addstring(shstrtab, ".rela"+relro_prefix+".gosymtab")
			Addstring(shstrtab, ".rela"+relro_prefix+".gopclntab")
1759 1760
			Addstring(shstrtab, ".rela.noptrdata")
			Addstring(shstrtab, ".rela.data")
1761 1762 1763
			if UseRelro() {
				Addstring(shstrtab, ".rela.data.rel.ro")
			}
1764 1765

		default:
1766 1767
			Addstring(shstrtab, ".rel.text")
			Addstring(shstrtab, ".rel.rodata")
1768 1769 1770
			Addstring(shstrtab, ".rel"+relro_prefix+".typelink")
			Addstring(shstrtab, ".rel"+relro_prefix+".gosymtab")
			Addstring(shstrtab, ".rel"+relro_prefix+".gopclntab")
1771 1772
			Addstring(shstrtab, ".rel.noptrdata")
			Addstring(shstrtab, ".rel.data")
1773 1774 1775
			if UseRelro() {
				Addstring(shstrtab, ".rel.data.rel.ro")
			}
1776 1777 1778 1779
		}

		// add a .note.GNU-stack section to mark the stack as non-executable
		Addstring(shstrtab, ".note.GNU-stack")
1780 1781 1782 1783

		if Buildmode == BuildmodeShared {
			Addstring(shstrtab, ".note.go.abihash")
			Addstring(shstrtab, ".note.go.pkg-list")
1784
			Addstring(shstrtab, ".note.go.deps")
1785
		}
1786 1787
	}

1788 1789 1790
	hasinitarr := Linkshared

	/* shared library initializer */
1791 1792
	switch Buildmode {
	case BuildmodeCArchive, BuildmodeCShared, BuildmodeShared:
1793 1794 1795 1796
		hasinitarr = true
	}

	if hasinitarr {
1797
		Addstring(shstrtab, ".init_array")
1798
		switch Thearch.Thechar {
1799
		case '0', '6', '7', '9':
1800
			Addstring(shstrtab, ".rela.init_array")
1801
		default:
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
			Addstring(shstrtab, ".rel.init_array")
		}
	}

	if Debug['s'] == 0 {
		Addstring(shstrtab, ".symtab")
		Addstring(shstrtab, ".strtab")
		dwarfaddshstrings(shstrtab)
	}

	Addstring(shstrtab, ".shstrtab")

1814
	if Debug['d'] == 0 { /* -d suppresses dynamic loader format */
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
		Addstring(shstrtab, ".interp")
		Addstring(shstrtab, ".hash")
		Addstring(shstrtab, ".got")
		if Thearch.Thechar == '9' {
			Addstring(shstrtab, ".glink")
		}
		Addstring(shstrtab, ".got.plt")
		Addstring(shstrtab, ".dynamic")
		Addstring(shstrtab, ".dynsym")
		Addstring(shstrtab, ".dynstr")
1825
		switch Thearch.Thechar {
1826
		case '0', '6', '7', '9':
1827 1828
			Addstring(shstrtab, ".rela")
			Addstring(shstrtab, ".rela.plt")
1829
		default:
1830 1831 1832 1833 1834 1835 1836 1837 1838
			Addstring(shstrtab, ".rel")
			Addstring(shstrtab, ".rel.plt")
		}

		Addstring(shstrtab, ".plt")
		Addstring(shstrtab, ".gnu.version")
		Addstring(shstrtab, ".gnu.version_r")

		/* dynamic symbol table - first entry all zeros */
Russ Cox's avatar
Russ Cox committed
1839
		s := Linklookup(Ctxt, ".dynsym", 0)
1840

1841
		s.Type = obj.SELFROSECT
1842
		s.Reachable = true
1843
		switch Thearch.Thechar {
1844
		case '0', '6', '7', '9':
1845
			s.Size += ELF64SYMSIZE
1846
		default:
1847 1848 1849 1850 1851 1852
			s.Size += ELF32SYMSIZE
		}

		/* dynamic string table */
		s = Linklookup(Ctxt, ".dynstr", 0)

1853
		s.Type = obj.SELFROSECT
1854 1855 1856 1857
		s.Reachable = true
		if s.Size == 0 {
			Addstring(s, "")
		}
Russ Cox's avatar
Russ Cox committed
1858
		dynstr := s
1859 1860

		/* relocation table */
1861
		switch Thearch.Thechar {
1862
		case '0', '6', '7', '9':
1863
			s = Linklookup(Ctxt, ".rela", 0)
1864
		default:
1865 1866 1867
			s = Linklookup(Ctxt, ".rel", 0)
		}
		s.Reachable = true
1868
		s.Type = obj.SELFROSECT
1869 1870 1871 1872 1873

		/* global offset table */
		s = Linklookup(Ctxt, ".got", 0)

		s.Reachable = true
1874
		s.Type = obj.SELFGOT // writable
1875 1876 1877

		/* ppc64 glink resolver */
		if Thearch.Thechar == '9' {
Russ Cox's avatar
Russ Cox committed
1878
			s := Linklookup(Ctxt, ".glink", 0)
1879
			s.Reachable = true
1880
			s.Type = obj.SELFRXSECT
1881 1882 1883 1884 1885 1886
		}

		/* hash */
		s = Linklookup(Ctxt, ".hash", 0)

		s.Reachable = true
1887
		s.Type = obj.SELFROSECT
1888 1889 1890

		s = Linklookup(Ctxt, ".got.plt", 0)
		s.Reachable = true
1891
		s.Type = obj.SELFSECT // writable
1892 1893 1894 1895 1896 1897 1898

		s = Linklookup(Ctxt, ".plt", 0)

		s.Reachable = true
		if Thearch.Thechar == '9' {
			// In the ppc64 ABI, .plt is a data section
			// written by the dynamic linker.
1899
			s.Type = obj.SELFSECT
1900
		} else {
1901
			s.Type = obj.SELFRXSECT
1902 1903 1904 1905
		}

		Thearch.Elfsetupplt()

1906
		switch Thearch.Thechar {
1907
		case '0', '6', '7', '9':
1908
			s = Linklookup(Ctxt, ".rela.plt", 0)
1909
		default:
1910 1911 1912
			s = Linklookup(Ctxt, ".rel.plt", 0)
		}
		s.Reachable = true
1913
		s.Type = obj.SELFROSECT
1914 1915 1916

		s = Linklookup(Ctxt, ".gnu.version", 0)
		s.Reachable = true
1917
		s.Type = obj.SELFROSECT
1918 1919 1920

		s = Linklookup(Ctxt, ".gnu.version_r", 0)
		s.Reachable = true
1921
		s.Type = obj.SELFROSECT
1922 1923 1924 1925 1926

		/* define dynamic elf table */
		s = Linklookup(Ctxt, ".dynamic", 0)

		s.Reachable = true
1927
		s.Type = obj.SELFSECT // writable
1928 1929 1930 1931 1932 1933 1934

		/*
		 * .dynamic table
		 */
		elfwritedynentsym(s, DT_HASH, Linklookup(Ctxt, ".hash", 0))

		elfwritedynentsym(s, DT_SYMTAB, Linklookup(Ctxt, ".dynsym", 0))
1935
		switch Thearch.Thechar {
1936
		case '0', '6', '7', '9':
1937
			Elfwritedynent(s, DT_SYMENT, ELF64SYMSIZE)
1938
		default:
1939 1940 1941 1942
			Elfwritedynent(s, DT_SYMENT, ELF32SYMSIZE)
		}
		elfwritedynentsym(s, DT_STRTAB, Linklookup(Ctxt, ".dynstr", 0))
		elfwritedynentsymsize(s, DT_STRSZ, Linklookup(Ctxt, ".dynstr", 0))
1943
		switch Thearch.Thechar {
1944
		case '0', '6', '7', '9':
1945 1946 1947
			elfwritedynentsym(s, DT_RELA, Linklookup(Ctxt, ".rela", 0))
			elfwritedynentsymsize(s, DT_RELASZ, Linklookup(Ctxt, ".rela", 0))
			Elfwritedynent(s, DT_RELAENT, ELF64RELASIZE)
1948
		default:
1949 1950 1951 1952 1953
			elfwritedynentsym(s, DT_REL, Linklookup(Ctxt, ".rel", 0))
			elfwritedynentsymsize(s, DT_RELSZ, Linklookup(Ctxt, ".rel", 0))
			Elfwritedynent(s, DT_RELENT, ELF32RELSIZE)
		}

1954 1955
		if rpath.val != "" {
			Elfwritedynent(s, DT_RUNPATH, uint64(Addstring(dynstr, rpath.val)))
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
		}

		if Thearch.Thechar == '9' {
			elfwritedynentsym(s, DT_PLTGOT, Linklookup(Ctxt, ".plt", 0))
		} else {
			elfwritedynentsym(s, DT_PLTGOT, Linklookup(Ctxt, ".got.plt", 0))
		}

		if Thearch.Thechar == '9' {
			Elfwritedynent(s, DT_PPC64_OPT, 0)
		}

		// Solaris dynamic linker can't handle an empty .rela.plt if
		// DT_JMPREL is emitted so we have to defer generation of DT_PLTREL,
		// DT_PLTRELSZ, and DT_JMPREL dynamic entries until after we know the
		// size of .rel(a).plt section.
		Elfwritedynent(s, DT_DEBUG, 0)
	}
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991

	if Buildmode == BuildmodeShared {
		// The go.link.abihashbytes symbol will be pointed at the appropriate
		// part of the .note.go.abihash section in data.go:func address().
		s := Linklookup(Ctxt, "go.link.abihashbytes", 0)
		s.Local = true
		s.Type = obj.SRODATA
		s.Special = 1
		s.Reachable = true
		s.Size = int64(sha1.Size)

		sort.Sort(byPkg(Ctxt.Library))
		h := sha1.New()
		for _, l := range Ctxt.Library {
			h.Write(l.hash)
		}
		addgonote(".note.go.abihash", ELF_NOTE_GOABIHASH_TAG, h.Sum([]byte{}))
		addgonote(".note.go.pkg-list", ELF_NOTE_GOPKGLIST_TAG, []byte(pkglistfornote))
1992 1993 1994 1995 1996
		var deplist []string
		for _, shlib := range Ctxt.Shlibs {
			deplist = append(deplist, filepath.Base(shlib.Path))
		}
		addgonote(".note.go.deps", ELF_NOTE_GODEPS_TAG, []byte(strings.Join(deplist, "\n")))
1997
	}
1998 1999 2000 2001

	if Linkmode == LinkExternal && buildid != "" {
		addgonote(".note.go.buildid", ELF_NOTE_GOBUILDID_TAG, []byte(buildid))
	}
2002 2003 2004 2005
}

// Do not write DT_NULL.  elfdynhash will finish it.
func shsym(sh *ElfShdr, s *LSym) {
Russ Cox's avatar
Russ Cox committed
2006
	addr := Symaddr(s)
2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
	if sh.flags&SHF_ALLOC != 0 {
		sh.addr = uint64(addr)
	}
	sh.off = uint64(datoff(addr))
	sh.size = uint64(s.Size)
}

func phsh(ph *ElfPhdr, sh *ElfShdr) {
	ph.vaddr = sh.addr
	ph.paddr = ph.vaddr
	ph.off = sh.off
	ph.filesz = sh.size
	ph.memsz = sh.size
	ph.align = sh.addralign
}

func Asmbelfsetup() {
	/* This null SHdr must appear before all others */
	elfshname("")

Russ Cox's avatar
Russ Cox committed
2027
	for sect := Segtext.Sect; sect != nil; sect = sect.Next {
2028 2029
		elfshalloc(sect)
	}
Russ Cox's avatar
Russ Cox committed
2030
	for sect := Segrodata.Sect; sect != nil; sect = sect.Next {
2031 2032
		elfshalloc(sect)
	}
Russ Cox's avatar
Russ Cox committed
2033
	for sect := Segdata.Sect; sect != nil; sect = sect.Next {
2034 2035 2036 2037 2038
		elfshalloc(sect)
	}
}

func Asmbelf(symo int64) {
Russ Cox's avatar
Russ Cox committed
2039
	eh := getElfEhdr()
2040 2041
	switch Thearch.Thechar {
	default:
2042
		Exitf("unknown architecture in asmbelf: %v", Thearch.Thechar)
2043 2044
	case '0':
		eh.machine = EM_MIPS
2045 2046 2047 2048
	case '5':
		eh.machine = EM_ARM
	case '6':
		eh.machine = EM_X86_64
2049 2050
	case '7':
		eh.machine = EM_AARCH64
2051 2052 2053 2054 2055 2056
	case '8':
		eh.machine = EM_386
	case '9':
		eh.machine = EM_PPC64
	}

2057
	elfreserve := int64(ELFRESERVE)
Russ Cox's avatar
Russ Cox committed
2058
	startva := INITTEXT - int64(HEADR)
2059
	resoff := elfreserve
2060

Russ Cox's avatar
Russ Cox committed
2061
	var pph *ElfPhdr
Russ Cox's avatar
Russ Cox committed
2062
	var pnote *ElfPhdr
2063 2064 2065 2066 2067
	if Linkmode == LinkExternal {
		/* skip program headers */
		eh.phoff = 0

		eh.phentsize = 0
2068 2069 2070

		if Buildmode == BuildmodeShared {
			sh := elfshname(".note.go.pkg-list")
2071 2072 2073 2074
			sh.type_ = SHT_NOTE
			sh = elfshname(".note.go.abihash")
			sh.type_ = SHT_NOTE
			sh.flags = SHF_ALLOC
2075 2076
			sh = elfshname(".note.go.deps")
			sh.type_ = SHT_NOTE
2077
		}
2078 2079 2080 2081 2082 2083 2084

		if buildid != "" {
			sh := elfshname(".note.go.buildid")
			sh.type_ = SHT_NOTE
			sh.flags = SHF_ALLOC
		}

2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102
		goto elfobj
	}

	/* program header info */
	pph = newElfPhdr()

	pph.type_ = PT_PHDR
	pph.flags = PF_R
	pph.off = uint64(eh.ehsize)
	pph.vaddr = uint64(INITTEXT) - uint64(HEADR) + pph.off
	pph.paddr = uint64(INITTEXT) - uint64(HEADR) + pph.off
	pph.align = uint64(INITRND)

	/*
	 * PHDR must be in a loaded segment. Adjust the text
	 * segment boundaries downwards to include it.
	 * Except on NaCl where it must not be loaded.
	 */
2103
	if HEADTYPE != obj.Hnacl {
Russ Cox's avatar
Russ Cox committed
2104
		o := int64(Segtext.Vaddr - pph.vaddr)
2105 2106 2107 2108 2109 2110 2111
		Segtext.Vaddr -= uint64(o)
		Segtext.Length += uint64(o)
		o = int64(Segtext.Fileoff - pph.off)
		Segtext.Fileoff -= uint64(o)
		Segtext.Filelen += uint64(o)
	}

2112
	if Debug['d'] == 0 { /* -d suppresses dynamic loader format */
2113
		/* interpreter */
Russ Cox's avatar
Russ Cox committed
2114
		sh := elfshname(".interp")
2115 2116 2117 2118 2119 2120

		sh.type_ = SHT_PROGBITS
		sh.flags = SHF_ALLOC
		sh.addralign = 1
		if interpreter == "" {
			switch HEADTYPE {
2121
			case obj.Hlinux:
2122 2123
				interpreter = Thearch.Linuxdynld

2124
			case obj.Hfreebsd:
2125 2126
				interpreter = Thearch.Freebsddynld

2127
			case obj.Hnetbsd:
2128 2129
				interpreter = Thearch.Netbsddynld

2130
			case obj.Hopenbsd:
2131 2132
				interpreter = Thearch.Openbsddynld

2133
			case obj.Hdragonfly:
2134 2135
				interpreter = Thearch.Dragonflydynld

2136
			case obj.Hsolaris:
2137 2138 2139 2140 2141 2142
				interpreter = Thearch.Solarisdynld
			}
		}

		resoff -= int64(elfinterp(sh, uint64(startva), uint64(resoff), interpreter))

Russ Cox's avatar
Russ Cox committed
2143
		ph := newElfPhdr()
2144 2145 2146 2147 2148 2149
		ph.type_ = PT_INTERP
		ph.flags = PF_R
		phsh(ph, sh)
	}

	pnote = nil
2150
	if HEADTYPE == obj.Hnetbsd || HEADTYPE == obj.Hopenbsd {
Russ Cox's avatar
Russ Cox committed
2151
		var sh *ElfShdr
2152
		switch HEADTYPE {
2153
		case obj.Hnetbsd:
2154 2155 2156
			sh = elfshname(".note.netbsd.ident")
			resoff -= int64(elfnetbsdsig(sh, uint64(startva), uint64(resoff)))

2157
		case obj.Hopenbsd:
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
			sh = elfshname(".note.openbsd.ident")
			resoff -= int64(elfopenbsdsig(sh, uint64(startva), uint64(resoff)))
		}

		pnote = newElfPhdr()
		pnote.type_ = PT_NOTE
		pnote.flags = PF_R
		phsh(pnote, sh)
	}

	if len(buildinfo) > 0 {
Russ Cox's avatar
Russ Cox committed
2169
		sh := elfshname(".note.gnu.build-id")
2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180
		resoff -= int64(elfbuildinfo(sh, uint64(startva), uint64(resoff)))

		if pnote == nil {
			pnote = newElfPhdr()
			pnote.type_ = PT_NOTE
			pnote.flags = PF_R
		}

		phsh(pnote, sh)
	}

2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
	if buildid != "" {
		sh := elfshname(".note.go.buildid")
		resoff -= int64(elfgobuildid(sh, uint64(startva), uint64(resoff)))

		pnote := newElfPhdr()
		pnote.type_ = PT_NOTE
		pnote.flags = PF_R
		phsh(pnote, sh)
	}

2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
	// Additions to the reserved area must be above this line.

	elfphload(&Segtext)
	if Segrodata.Sect != nil {
		elfphload(&Segrodata)
	}
	elfphload(&Segdata)

	/* Dynamic linking sections */
	if Debug['d'] == 0 {
Russ Cox's avatar
Russ Cox committed
2201
		sh := elfshname(".dynsym")
2202 2203
		sh.type_ = SHT_DYNSYM
		sh.flags = SHF_ALLOC
2204
		if elf64 {
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
			sh.entsize = ELF64SYMSIZE
		} else {
			sh.entsize = ELF32SYMSIZE
		}
		sh.addralign = uint64(Thearch.Regsize)
		sh.link = uint32(elfshname(".dynstr").shnum)

		// sh->info = index of first non-local symbol (number of local symbols)
		shsym(sh, Linklookup(Ctxt, ".dynsym", 0))

		sh = elfshname(".dynstr")
		sh.type_ = SHT_STRTAB
		sh.flags = SHF_ALLOC
		sh.addralign = 1
		shsym(sh, Linklookup(Ctxt, ".dynstr", 0))

		if elfverneed != 0 {
Russ Cox's avatar
Russ Cox committed
2222
			sh := elfshname(".gnu.version")
2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
			sh.type_ = SHT_GNU_VERSYM
			sh.flags = SHF_ALLOC
			sh.addralign = 2
			sh.link = uint32(elfshname(".dynsym").shnum)
			sh.entsize = 2
			shsym(sh, Linklookup(Ctxt, ".gnu.version", 0))

			sh = elfshname(".gnu.version_r")
			sh.type_ = SHT_GNU_VERNEED
			sh.flags = SHF_ALLOC
			sh.addralign = uint64(Thearch.Regsize)
			sh.info = uint32(elfverneed)
			sh.link = uint32(elfshname(".dynstr").shnum)
			shsym(sh, Linklookup(Ctxt, ".gnu.version_r", 0))
		}

		switch eh.machine {
2240
		case EM_X86_64, EM_PPC64, EM_AARCH64:
Russ Cox's avatar
Russ Cox committed
2241
			sh := elfshname(".rela.plt")
2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
			sh.type_ = SHT_RELA
			sh.flags = SHF_ALLOC
			sh.entsize = ELF64RELASIZE
			sh.addralign = uint64(Thearch.Regsize)
			sh.link = uint32(elfshname(".dynsym").shnum)
			sh.info = uint32(elfshname(".plt").shnum)
			shsym(sh, Linklookup(Ctxt, ".rela.plt", 0))

			sh = elfshname(".rela")
			sh.type_ = SHT_RELA
			sh.flags = SHF_ALLOC
			sh.entsize = ELF64RELASIZE
			sh.addralign = 8
			sh.link = uint32(elfshname(".dynsym").shnum)
			shsym(sh, Linklookup(Ctxt, ".rela", 0))

		default:
Russ Cox's avatar
Russ Cox committed
2259
			sh := elfshname(".rel.plt")
2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
			sh.type_ = SHT_REL
			sh.flags = SHF_ALLOC
			sh.entsize = ELF32RELSIZE
			sh.addralign = 4
			sh.link = uint32(elfshname(".dynsym").shnum)
			shsym(sh, Linklookup(Ctxt, ".rel.plt", 0))

			sh = elfshname(".rel")
			sh.type_ = SHT_REL
			sh.flags = SHF_ALLOC
			sh.entsize = ELF32RELSIZE
			sh.addralign = 4
			sh.link = uint32(elfshname(".dynsym").shnum)
			shsym(sh, Linklookup(Ctxt, ".rel", 0))
		}

		if eh.machine == EM_PPC64 {
Russ Cox's avatar
Russ Cox committed
2277
			sh := elfshname(".glink")
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
			sh.type_ = SHT_PROGBITS
			sh.flags = SHF_ALLOC + SHF_EXECINSTR
			sh.addralign = 4
			shsym(sh, Linklookup(Ctxt, ".glink", 0))
		}

		sh = elfshname(".plt")
		sh.type_ = SHT_PROGBITS
		sh.flags = SHF_ALLOC + SHF_EXECINSTR
		if eh.machine == EM_X86_64 {
			sh.entsize = 16
		} else if eh.machine == EM_PPC64 {
			// On ppc64, this is just a table of addresses
			// filled by the dynamic linker
			sh.type_ = SHT_NOBITS

			sh.flags = SHF_ALLOC + SHF_WRITE
			sh.entsize = 8
		} else {
			sh.entsize = 4
		}
		sh.addralign = sh.entsize
		shsym(sh, Linklookup(Ctxt, ".plt", 0))

		// On ppc64, .got comes from the input files, so don't
		// create it here, and .got.plt is not used.
		if eh.machine != EM_PPC64 {
Russ Cox's avatar
Russ Cox committed
2305
			sh := elfshname(".got")
2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
			sh.type_ = SHT_PROGBITS
			sh.flags = SHF_ALLOC + SHF_WRITE
			sh.entsize = uint64(Thearch.Regsize)
			sh.addralign = uint64(Thearch.Regsize)
			shsym(sh, Linklookup(Ctxt, ".got", 0))

			sh = elfshname(".got.plt")
			sh.type_ = SHT_PROGBITS
			sh.flags = SHF_ALLOC + SHF_WRITE
			sh.entsize = uint64(Thearch.Regsize)
			sh.addralign = uint64(Thearch.Regsize)
			shsym(sh, Linklookup(Ctxt, ".got.plt", 0))
		}

		sh = elfshname(".hash")
		sh.type_ = SHT_HASH
		sh.flags = SHF_ALLOC
		sh.entsize = 4
		sh.addralign = uint64(Thearch.Regsize)
		sh.link = uint32(elfshname(".dynsym").shnum)
		shsym(sh, Linklookup(Ctxt, ".hash", 0))

		/* sh and PT_DYNAMIC for .dynamic section */
		sh = elfshname(".dynamic")

		sh.type_ = SHT_DYNAMIC
		sh.flags = SHF_ALLOC + SHF_WRITE
		sh.entsize = 2 * uint64(Thearch.Regsize)
		sh.addralign = uint64(Thearch.Regsize)
		sh.link = uint32(elfshname(".dynstr").shnum)
		shsym(sh, Linklookup(Ctxt, ".dynamic", 0))
Russ Cox's avatar
Russ Cox committed
2337
		ph := newElfPhdr()
2338 2339 2340 2341 2342 2343 2344 2345 2346 2347
		ph.type_ = PT_DYNAMIC
		ph.flags = PF_R + PF_W
		phsh(ph, sh)

		/*
		 * Thread-local storage segment (really just size).
		 */
		// Do not emit PT_TLS for OpenBSD since ld.so(1) does
		// not currently support it. This is handled
		// appropriately in runtime/cgo.
2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361
		if HEADTYPE != obj.Hopenbsd {
			tlssize := uint64(0)
			for sect := Segdata.Sect; sect != nil; sect = sect.Next {
				if sect.Name == ".tbss" {
					tlssize = sect.Length
				}
			}
			if tlssize != 0 {
				ph := newElfPhdr()
				ph.type_ = PT_TLS
				ph.flags = PF_R
				ph.memsz = tlssize
				ph.align = uint64(Thearch.Regsize)
			}
2362 2363 2364
		}
	}

2365
	if HEADTYPE == obj.Hlinux {
Russ Cox's avatar
Russ Cox committed
2366
		ph := newElfPhdr()
2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377
		ph.type_ = PT_GNU_STACK
		ph.flags = PF_W + PF_R
		ph.align = uint64(Thearch.Regsize)

		ph = newElfPhdr()
		ph.type_ = PT_PAX_FLAGS
		ph.flags = 0x2a00 // mprotect, randexec, emutramp disabled
		ph.align = uint64(Thearch.Regsize)
	}

elfobj:
Russ Cox's avatar
Russ Cox committed
2378
	sh := elfshname(".shstrtab")
2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
	sh.type_ = SHT_STRTAB
	sh.addralign = 1
	shsym(sh, Linklookup(Ctxt, ".shstrtab", 0))
	eh.shstrndx = uint16(sh.shnum)

	// put these sections early in the list
	if Debug['s'] == 0 {
		elfshname(".symtab")
		elfshname(".strtab")
	}

Russ Cox's avatar
Russ Cox committed
2390
	for sect := Segtext.Sect; sect != nil; sect = sect.Next {
2391 2392
		elfshbits(sect)
	}
Russ Cox's avatar
Russ Cox committed
2393
	for sect := Segrodata.Sect; sect != nil; sect = sect.Next {
2394 2395
		elfshbits(sect)
	}
Russ Cox's avatar
Russ Cox committed
2396
	for sect := Segdata.Sect; sect != nil; sect = sect.Next {
2397 2398 2399 2400
		elfshbits(sect)
	}

	if Linkmode == LinkExternal {
Russ Cox's avatar
Russ Cox committed
2401
		for sect := Segtext.Sect; sect != nil; sect = sect.Next {
2402 2403
			elfshreloc(sect)
		}
Russ Cox's avatar
Russ Cox committed
2404
		for sect := Segrodata.Sect; sect != nil; sect = sect.Next {
2405 2406
			elfshreloc(sect)
		}
Russ Cox's avatar
Russ Cox committed
2407
		for sect := Segdata.Sect; sect != nil; sect = sect.Next {
2408 2409 2410 2411
			elfshreloc(sect)
		}

		// add a .note.GNU-stack section to mark the stack as non-executable
Russ Cox's avatar
Russ Cox committed
2412
		sh := elfshname(".note.GNU-stack")
2413 2414 2415 2416 2417 2418 2419

		sh.type_ = SHT_PROGBITS
		sh.addralign = 1
		sh.flags = 0
	}

	if Debug['s'] == 0 {
Russ Cox's avatar
Russ Cox committed
2420
		sh := elfshname(".symtab")
2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443
		sh.type_ = SHT_SYMTAB
		sh.off = uint64(symo)
		sh.size = uint64(Symsize)
		sh.addralign = uint64(Thearch.Regsize)
		sh.entsize = 8 + 2*uint64(Thearch.Regsize)
		sh.link = uint32(elfshname(".strtab").shnum)
		sh.info = uint32(elfglobalsymndx)

		sh = elfshname(".strtab")
		sh.type_ = SHT_STRTAB
		sh.off = uint64(symo) + uint64(Symsize)
		sh.size = uint64(len(Elfstrdat))
		sh.addralign = 1

		dwarfaddelfheaders()
	}

	/* Main header */
	eh.ident[EI_MAG0] = '\177'

	eh.ident[EI_MAG1] = 'E'
	eh.ident[EI_MAG2] = 'L'
	eh.ident[EI_MAG3] = 'F'
2444
	if HEADTYPE == obj.Hfreebsd {
2445
		eh.ident[EI_OSABI] = ELFOSABI_FREEBSD
2446
	} else if HEADTYPE == obj.Hnetbsd {
2447
		eh.ident[EI_OSABI] = ELFOSABI_NETBSD
2448
	} else if HEADTYPE == obj.Hopenbsd {
2449
		eh.ident[EI_OSABI] = ELFOSABI_OPENBSD
2450
	} else if HEADTYPE == obj.Hdragonfly {
2451 2452
		eh.ident[EI_OSABI] = ELFOSABI_NONE
	}
2453
	if elf64 {
2454 2455 2456 2457
		eh.ident[EI_CLASS] = ELFCLASS64
	} else {
		eh.ident[EI_CLASS] = ELFCLASS32
	}
2458
	if Ctxt.Arch.ByteOrder == binary.BigEndian {
2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482
		eh.ident[EI_DATA] = ELFDATA2MSB
	} else {
		eh.ident[EI_DATA] = ELFDATA2LSB
	}
	eh.ident[EI_VERSION] = EV_CURRENT

	if Linkmode == LinkExternal {
		eh.type_ = ET_REL
	} else {
		eh.type_ = ET_EXEC
	}

	if Linkmode != LinkExternal {
		eh.entry = uint64(Entryvalue())
	}

	eh.version = EV_CURRENT

	if pph != nil {
		pph.filesz = uint64(eh.phnum) * uint64(eh.phentsize)
		pph.memsz = pph.filesz
	}

	Cseek(0)
Russ Cox's avatar
Russ Cox committed
2483
	a := int64(0)
2484 2485 2486 2487 2488 2489 2490
	a += int64(elfwritehdr())
	a += int64(elfwritephdrs())
	a += int64(elfwriteshdrs())
	if Debug['d'] == 0 {
		a += int64(elfwriteinterp())
	}
	if Linkmode != LinkExternal {
2491
		if HEADTYPE == obj.Hnetbsd {
2492 2493
			a += int64(elfwritenetbsdsig())
		}
2494
		if HEADTYPE == obj.Hopenbsd {
2495 2496 2497 2498 2499
			a += int64(elfwriteopenbsdsig())
		}
		if len(buildinfo) > 0 {
			a += int64(elfwritebuildinfo())
		}
2500 2501 2502
		if buildid != "" {
			a += int64(elfwritegobuildid())
		}
2503 2504
	}

2505 2506
	if a > elfreserve {
		Diag("ELFRESERVE too small: %d > %d", a, elfreserve)
2507 2508 2509
	}
}

2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596
func Elfadddynsym(ctxt *Link, s *LSym) {
	if elf64 {
		s.Dynid = int32(Nelfsym)
		Nelfsym++

		d := Linklookup(ctxt, ".dynsym", 0)

		name := s.Extname
		Adduint32(ctxt, d, uint32(Addstring(Linklookup(ctxt, ".dynstr", 0), name)))

		/* type */
		t := STB_GLOBAL << 4

		if s.Cgoexport != 0 && s.Type&obj.SMASK == obj.STEXT {
			t |= STT_FUNC
		} else {
			t |= STT_OBJECT
		}
		Adduint8(ctxt, d, uint8(t))

		/* reserved */
		Adduint8(ctxt, d, 0)

		/* section where symbol is defined */
		if s.Type == obj.SDYNIMPORT {
			Adduint16(ctxt, d, SHN_UNDEF)
		} else {
			Adduint16(ctxt, d, 1)
		}

		/* value */
		if s.Type == obj.SDYNIMPORT {
			Adduint64(ctxt, d, 0)
		} else {
			Addaddr(ctxt, d, s)
		}

		/* size of object */
		Adduint64(ctxt, d, uint64(s.Size))

		if Thearch.Thechar == '6' && s.Cgoexport&CgoExportDynamic == 0 && s.Dynimplib != "" && !seenlib[s.Dynimplib] {
			Elfwritedynent(Linklookup(ctxt, ".dynamic", 0), DT_NEEDED, uint64(Addstring(Linklookup(ctxt, ".dynstr", 0), s.Dynimplib)))
		}
	} else {
		s.Dynid = int32(Nelfsym)
		Nelfsym++

		d := Linklookup(ctxt, ".dynsym", 0)

		/* name */
		name := s.Extname

		Adduint32(ctxt, d, uint32(Addstring(Linklookup(ctxt, ".dynstr", 0), name)))

		/* value */
		if s.Type == obj.SDYNIMPORT {
			Adduint32(ctxt, d, 0)
		} else {
			Addaddr(ctxt, d, s)
		}

		/* size */
		Adduint32(ctxt, d, 0)

		/* type */
		t := STB_GLOBAL << 4

		// TODO(mwhudson): presumably the behaviour should actually be the same on both arm and 386.
		if Thearch.Thechar == '8' && s.Cgoexport != 0 && s.Type&obj.SMASK == obj.STEXT {
			t |= STT_FUNC
		} else if Thearch.Thechar == '5' && s.Cgoexport&CgoExportDynamic != 0 && s.Type&obj.SMASK == obj.STEXT {
			t |= STT_FUNC
		} else {
			t |= STT_OBJECT
		}
		Adduint8(ctxt, d, uint8(t))
		Adduint8(ctxt, d, 0)

		/* shndx */
		if s.Type == obj.SDYNIMPORT {
			Adduint16(ctxt, d, SHN_UNDEF)
		} else {
			Adduint16(ctxt, d, 1)
		}
	}
}

2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
func ELF32_R_SYM(info uint32) uint32 {
	return info >> 8
}

func ELF32_R_TYPE(info uint32) uint32 {
	return uint32(uint8(info))
}

func ELF32_R_INFO(sym uint32, type_ uint32) uint32 {
	return sym<<8 | type_
}

func ELF32_ST_BIND(info uint8) uint8 {
	return info >> 4
}

func ELF32_ST_TYPE(info uint8) uint8 {
	return info & 0xf
}

func ELF32_ST_INFO(bind uint8, type_ uint8) uint8 {
	return bind<<4 | type_&0xf
}

func ELF32_ST_VISIBILITY(oth uint8) uint8 {
	return oth & 3
}

func ELF64_R_SYM(info uint64) uint32 {
	return uint32(info >> 32)
}

func ELF64_R_TYPE(info uint64) uint32 {
	return uint32(info)
}

func ELF64_R_INFO(sym uint32, type_ uint32) uint64 {
	return uint64(sym)<<32 | uint64(type_)
}

func ELF64_ST_BIND(info uint8) uint8 {
	return info >> 4
}

func ELF64_ST_TYPE(info uint8) uint8 {
	return info & 0xf
}

func ELF64_ST_INFO(bind uint8, type_ uint8) uint8 {
	return bind<<4 | type_&0xf
}

func ELF64_ST_VISIBILITY(oth uint8) uint8 {
	return oth & 3
}