Commit Graph

6337 Commits

Author SHA1 Message Date
Nathan Lanza 2f65166056 [lld:elf] Weaken the requirement for a computed binding to be STB_LOCAL
Given the following scenario:

```
// Cat.cpp
struct Animal { virtual void makeNoise() const = 0; };
struct Cat : Animal { void makeNoise() const override; };

extern "C" int puts(char const *);
void Cat::makeNoise() const { puts("Meow"); }
void doThingWithCat(Animal *a) { static_cast<Cat *>(a)->makeNoise(); }

// CatUser.cpp
struct Animal { virtual void makeNoise() const = 0; };
struct Cat : Animal { void makeNoise() const override; };

void doThingWithCat(Animal *a);

void useDoThingWithCat() {
  Cat *d = new Cat;
  doThingWithCat(d);
}

// cat.ver
{
  global: _Z17useDoThingWithCatv;
  local: *;
};

$ clang++ Cat.cpp CatUser.cpp -fpic -flto=thin -fwhole-program-vtables
-shared -O3 -fuse-ld=lld -Wl,--lto-whole-program-visibility
-Wl,--version-script,cat.ver
```

We cannot devirtualize `Cat::makeNoise`. The issue is complex:

Due to `-fsplit-lto-unit` and usage of type metadata, we place the Cat
vtable declaration into module 0 and the Cat vtable definition with type
metadata into module 1, causing duplicate entries (Undefined followed by
Defined) in the `lto::InputFile::symbols()` output.
In `BitcodeFile::parse`, after processing the `Undefined` then the
`Defined`, the final state is `Defined`.
In `BitcodeCompiler::add`, for the first symbol, `computeBinding`
returns `STB_LOCAL`, then we reset it to `Undefined` because it is
prevailing (`versionId` is `preserved`). For the second symbol, because
the state is now `Undefined`, `computeBinding` returns `STB_GLOBAL`,
causing `ExportDynamic` to be true and suppressing devirtualization.

In D77280, the `computeBinding` change used a stricter `isDefined()`
condition to make weak``Lazy` symbol work.
This patch relaxes the condition to weaker `!isLazy()` to keep it
working while making the devirtualization work as well.

Differential Revision: https://reviews.llvm.org/D98686
2021-05-24 23:32:21 -04:00
Harald van Dijk d62413452f
[lld][X86] Restore gotEntrySize.
D62727 removed GotEntrySize and GotPltEntrySize with a comment that they
are always equal to wordsize(), but that is not entirely true: X32 has a
word size of 4, but needs 8-byte GOT entries. This restores gotEntrySize
for both, adjusted for current naming conventions, but defaults it to
config->wordsize to keep things simple for architectures other than
x86_64.

This partially reverts D62727.

Reviewed By: MaskRay

Differential Revision: https://reviews.llvm.org/D102509
2021-05-17 00:13:00 +01:00
Fangrui Song 4adf7a7604 [ELF] Add -Bno-symbolic
This option will be available in GNU ld 2.27 (https://sourceware.org/bugzilla/show_bug.cgi?id=27834).
This option can cancel previously specified -Bsymbolic and
-Bsymbolic-functions.  This is useful for excluding some links when the
default uses -Bsymbolic-functions.

Reviewed By: jhenderson, peter.smith

Differential Revision: https://reviews.llvm.org/D102383
2021-05-14 09:40:32 -07:00
Fangrui Song a8053399cd [ELF][AVR] Add explicit relocation types to getRelExpr 2021-05-12 12:38:27 -07:00
Igor Kudrin 70c23e232e [LLD] Improve reporting unresolved symbols in shared libraries
Currently, when reporting unresolved symbols in shared libraries, if an
undefined symbol is firstly seen in a regular object file that shadows
the reference for the same symbol in a shared object. As a result, the
error for the unresolved symbol in the shared library is not reported.
If referencing sections in regular object files are discarded because of
'--gc-sections', no reports about such symbols are generated, and the
linker finishes successfully, generating an output image that fails on
the run.

The patch fixes the issue by keeping symbols, which should be checked,
for each shared library separately.

Differential Revision: https://reviews.llvm.org/D101996
2021-05-11 12:48:29 +07:00
Stefan Pintilie f0adf3a24c [PowerPC][LLD] Make sure that the correct Thunks are used.
This fixes an issue where mixed TOC / NOTOC calls can call the incorrect
thunks if a previous thunk already exists. The issue appears when a TOC
funciton calls a NOTOC callee and then a different NOTOC function calls the same
NOTOC callee. In this case the linker would sometimes incorrectly call the
same thunk for both cases.

Reviewed By: MaskRay

Differential Revision: https://reviews.llvm.org/D101837
2021-05-06 12:00:04 -05:00
Ben Dunbobbin 5dd9f44c17 [LLD] Improve --strip-all help text
This is a slight improvement to the help text, as I was slightly
surprised when strip-all did more than remove the symbol table.

Currently, we match gold's help text for strip-all and strip-debug.
I think that the GNU documentation for these options is not particularly
clear. However, I have opted to make only a minor change here and keep
the help text similar to gold's as these are mature options that are
well understood.

ld.bfd (https://sourceware.org/binutils/docs/ld/Options.html) has a
similar implication although it defines strip-debug as a subset of
strip-all. However, felt that noting that strip-all implies strip-debug
is better; because, with the ld.bfd approach you have to read both the
--strip-debug and the --strip-all help text to understand the behaviour
of --strip-all (and the --strip-all help text doesn't indicate that he
--strip-debug help text is related).

Differential Revision: https://reviews.llvm.org/D101890
2021-05-06 12:34:06 +01:00
Fangrui Song f9c8ebdc30 [ELF] Don't suggest alternative spelling of an empty name
Fix PR50111

Differential Revision: https://reviews.llvm.org/D101698
2021-05-03 09:04:55 -07:00
Fangrui Song 818b508953 [ELF] Simplify the condition adding .got header
Adopt my suggestion in https://reviews.llvm.org/D91426#2653926 ,
generalizing the ppc64 specific code.

GNU ld and glibc ld.so has a contract about the first few entries of .got .
There are somewhat complex conditions when the header is needed. This patch
switches to a simpler approach: add a header unconditionally if
_GLOBAL_OFFSET_TABLE_ is used or the number of entries is more than just the
header.
2021-04-30 17:19:45 -07:00
Duncan P. N. Exon Smith 518d955f9d Support: Stop using F_{None,Text,Append} compatibility synonyms, NFC
Stop using the compatibility spellings of `OF_{None,Text,Append}`
left behind by 1f67a3cba9. A follow-up
will remove them.

Differential Revision: https://reviews.llvm.org/D101650
2021-04-30 11:00:03 -07:00
Fangrui Song c9b1bd1012 [ELF] Support .rela.eh_frame with unordered r_offset values
GNU ld -r can create .rela.eh_frame with unordered r_offset values.
(With LLD, we can craft such a case by reordering sections in .eh_frame.)
This is currently unsupported and will trigger
`assert(pieces[i].inputOff <= off ...` in `OffsetGetter::get`
(the content is corrupted in a -DLLVM_ENABLE_ASSERTIONS=off build).
This patch supports this case.

Reviewed By: jhenderson

Differential Revision: https://reviews.llvm.org/D101116
2021-04-29 08:51:09 -07:00
Alex Richardson aed66d2787 [ELF] Update URL for MIPS TLS wiki page
The original page no longer works, so use a web.archive.org link instead.

Reviewed By: atanasyan

Differential Revision: https://reviews.llvm.org/D100949
2021-04-28 12:19:19 +01:00
Jessica Clarke 7fefd032cb [ELF][MIPS] Emit dynamic relocations for PIC non-preemptible static TLS
This is the same problem as 127176e59e, but for static TLS rather than
dynamic TLS. Although we know the symbol will be the one in our own TLS
segment, and thus the offset of it within that, we don't know where in
the static TLS block our data will be allocated and thus we must emit a
dynamic relocation for this case.

Reviewed By: MaskRay, atanasyan

Differential Revision: https://reviews.llvm.org/D101381
2021-04-27 19:04:50 +01:00
Jessica Clarke 1d505016ef [ELF][MIPS] Don't emit dynamic relocations for PIE non-preemptible TLS
Whilst not wrong (unless using static PIE where the relocations are
likely not implemented by the runtime), this is inefficient, as the TLS
module indices and offsets are independent of the executable's load
address.

Reviewed By: MaskRay, atanasyan

Differential Revision: https://reviews.llvm.org/D101382
2021-04-27 19:04:50 +01:00
Fangrui Song 9aad886e28 [ELF] Simplify a condition in addGotEntry. NFC 2021-04-23 22:11:14 -07:00
Nico Weber fcf59cc917 fix comment typo to cycle bots 2021-04-23 11:45:49 -04:00
Yang Fan c09277b0d8
[lld][ELF] Fix "enumeral and non-enumeral type in conditional expression" warning (NFC)
GCC warning:
```
/llvm-project/lld/ELF/SyntheticSections.cpp: In member function ‘virtual void lld:🧝:VersionTableSection::writeTo(uint8_t*)’:
/llvm-project/lld/ELF/SyntheticSections.cpp:3128:34: warning: enumeral and non-enumeral type in conditional expression [-Wextra]
 3128 |     write16(buf, s.sym->isLazy() ? VER_NDX_GLOBAL : s.sym->versionId);
      |                  ~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```
2021-04-21 16:01:46 +08:00
Fangrui Song 1c00530b30 [ELF] Don't set versionId on undefined weak lazy symbols
An unfetched lazy symbol (undefined weak) should be considered to have its
original versionId which is VER_NDX_GLOBAL, instead of the lazy symbol's
versionId. (The original versionId cannot be non-VER_NDX_GLOBAL because a
undefined versioned symbol is an error.)

The regression was introduced in D77280 when making version scripts work
with lazy symbols fetched by LTO calls.

Fix PR49915

Differential Revision: https://reviews.llvm.org/D100624
2021-04-20 11:23:10 -07:00
Nico Weber 0871ce3547 fix comment typo to cycle bots 2021-04-19 12:59:20 -04:00
Fangrui Song 7c74ce3c68 [ELF] --wrap: don't clear sym->isUsedInRegularObj if real->isUsedInRegularObj; set wrap's initial binding to sym's
Fix PR49897: if `__real_foo` has the isUsedInRegularObj bit set, we need to
retain `foo` in .symtab, even if `foo` is undefined. The new behavior will match
GNU ld.

Before the patch, we produced an R_X86_64_JUMP_SLOT relocation referencing the
index 0 undefined symbol, which would be erroed by glibc
(see f96ff3c0f8).

While here, fix another bug: if `__wrap_foo` does not exist, its initial binding
should be `foo`'s.
2021-04-17 00:29:51 -07:00
Fangrui Song b2a3d31eed [ELF] Simplify R_386_TLS_GD computation. NFC 2021-04-16 19:08:23 -07:00
Fangrui Song 6d2d3bd0a6 [ELF] Default to -z start-stop-gc with a glibc "__libc_" special case
Change the default to facilitate GC for metadata section usage, so that they
don't need SHF_LINK_ORDER or SHF_GROUP just to drop the unhelpful rule (if they
want to be unconditionally retained, use SHF_GNU_RETAIN
(`__attribute__((retain))`) or linker script `KEEP`).

The dropped SHF_GROUP special case makes the behavior of -z start-stop-gc and -z
nostart-stop-gc closer to GNU ld>=2.37 (https://sourceware.org/PR27451).

However, we default to -z start-stop-gc (which actually matches more closely to
GNU ld before 2015-10 https://sourceware.org/PR19167), which is different from
modern GNU ld (which has the unhelpful rule to work around glibc). As a
compensation, we special case `__libc_` sections as a workaround for glibc<2.34
(https://sourceware.org/PR27492).

Since -z start-stop-gc as the default actually matches the traditional GNU ld
behavior, there isn't much to be aware of. There was a systemd usage which has
been fixed by https://github.com/systemd/systemd/pull/19144
2021-04-16 12:18:46 -07:00
LemonBoy 7a781fb692 [LLD][ELF][AVR] Propagate ELF flags to the linked image
The `e_flags` for a ELF file targeting the AVR ISA contains two fields at the time of writing:
- A 7-bit integer field specifying the ISA revision being targeted
- A 1-bit flag specifying whether the object files being linked are suited for applying the relaxations at link time

The linked ELF file is blessed with the arch revision shared among all the files.
The behaviour in case of mismatch is purposefully different than the one implemented in libbfd: LLD will raise a fatal error while libbfd silently picks a default value of `avr2`.
The relaxation-ready flag is handled as done by libbfd, in order for it to appear in the linked object every source object must be tagged with it.

Reviewed By: MaskRay

Differential Revision: https://reviews.llvm.org/D99754
2021-04-16 10:40:18 +02:00
Nico Weber da0ef5ad5b fix typo to cycle bots 2021-04-14 14:59:18 -04:00
Nico Weber 1e89f08f59 fix typo to cycle bots 2021-04-14 14:52:53 -04:00
Stefan Pintilie 660c4e57b4 [PowerPC] Fix issue where binary uses a .got but is missing a .TOC.
From the PowerPC ELFv2 ABI section 4.2.3. Global Offset Table.
```
The GOT consists of an 8-byte header that contains the TOC base (the first TOC
base when multiple TOCs are present), followed by an array of 8-byte addresses.
```

Due to the introduction of PC Relative code it is now possible to require a GOT
without having a .TOC. symbol in the object that is being linked. Since LLD uses
the .TOC. symbol to determine whether or not a GOT is required the GOT header is
not setup correctly and the 8-byte header is missing.

This patch allows the Power PC GOT setup to happen when an element is added to
the GOT instead of at the very begining. When this header is added a .TOC.
symbol is also added.

Reviewed By: MaskRay

Differential Revision: https://reviews.llvm.org/D91426
2021-04-05 09:13:20 -05:00
Jez Ng 9b6dde8af8 [lld-macho] Parallelize UUID hash computation
This reuses the approach (and some code) from LLD-ELF.

It's a decent win when linking chromium_framework on a Mac Pro (3.2 GHz 16-Core Intel Xeon W):

      N           Min           Max        Median           Avg        Stddev
  x  20          4.58          4.83          4.66        4.6685   0.066591844
  +  20          4.42          4.61           4.5         4.505    0.04751731
  Difference at 95.0% confidence
          -0.1635 +/- 0.0370242
          -3.5022% +/- 0.793064%
          (Student's t, pooled s = 0.0578462)

The output binary is 381MB.

Reviewed By: #lld-macho, oontvoo

Differential Revision: https://reviews.llvm.org/D99279
2021-03-31 15:48:36 -04:00
Nico Weber 221388f451 fix comment typo to cycle bots 2021-03-29 14:50:17 -04:00
Abhina Sreeskantharajan c83cd8feef [NFC] Reordering parameters in getFile and getFileOrSTDIN
In future patches I will be setting the IsText parameter frequently so I will refactor the args to be in the following order. I have removed the FileSize parameter because it is never used.

```
  static ErrorOr<std::unique_ptr<MemoryBuffer>>
  getFile(const Twine &Filename, bool IsText = false,
          bool RequiresNullTerminator = true, bool IsVolatile = false);

  static ErrorOr<std::unique_ptr<MemoryBuffer>>
  getFileOrSTDIN(const Twine &Filename, bool IsText = false,
                 bool RequiresNullTerminator = true);

 static ErrorOr<std::unique_ptr<MB>>
 getFileAux(const Twine &Filename, uint64_t MapSize, uint64_t Offset,
            bool IsText, bool RequiresNullTerminator, bool IsVolatile);

  static ErrorOr<std::unique_ptr<WritableMemoryBuffer>>
  getFile(const Twine &Filename, bool IsVolatile = false);
```

Reviewed By: jhenderson

Differential Revision: https://reviews.llvm.org/D99182
2021-03-25 09:47:49 -04:00
Konstantin Zhuravlyov 4f28303133 AMDGPU/LLD: Add target id and code object v4 support to linker
Differential Revision: https://reviews.llvm.org/D95811
2021-03-24 13:41:10 -04:00
Stefan Pintilie f21704e080 [LLD][PowerPC] Fix bug in PC-Relative initial exec
There is a bug when initial exec is relaxed to local exec.
In the following situation:

InitExec.c
```
extern __thread unsigned TGlobal;
unsigned getConst(unsigned*);
unsigned addVal(unsigned, unsigned*);

unsigned GetAddrT() {
  return addVal(getConst(&TGlobal), &TGlobal);
}
```

Def.c
```
__thread unsigned TGlobal;

unsigned getConst(unsigned* A) {
  return *A + 3;
}

unsigned addVal(unsigned A, unsigned* B) {
  return A + *B;
}
```

The problem is in InitExec.c but Def.c is required if you want to link the example and see the problem.
To compile everything:
```
clang -O3 -mcpu=pwr10 -c InitExec.c
clang -O3 -mcpu=pwr10 -c Def.c
ld.lld InitExec.o Def.o -o IeToLe
```

If you objdump the problem object file:
```
$ llvm-objdump -dr --mcpu=pwr10 InitExec.o
```
you will get the following assembly:
```
0000000000000000 <GetAddrT>:
       0: a6 02 08 7c  	mflr 0
       4: f0 ff c1 fb  	std 30, -16(1)
       8: 10 00 01 f8  	std 0, 16(1)
       c: d1 ff 21 f8  	stdu 1, -48(1)
      10: 00 00 10 04 00 00 60 e4      	pld 3, 0(0), 1
		0000000000000010:  R_PPC64_GOT_TPREL_PCREL34	TGlobal
      18: 14 6a c3 7f  	add 30, 3, 13
		0000000000000019:  R_PPC64_TLS	TGlobal
      1c: 78 f3 c3 7f  	mr	3, 30
      20: 01 00 00 48  	bl 0x20
		0000000000000020:  R_PPC64_REL24_NOTOC	getConst
      24: 78 f3 c4 7f  	mr	4, 30
      28: 30 00 21 38  	addi 1, 1, 48
      2c: 10 00 01 e8  	ld 0, 16(1)
      30: f0 ff c1 eb  	ld 30, -16(1)
      34: a6 03 08 7c  	mtlr 0
      38: 00 00 00 48  	b 0x38
		0000000000000038:  R_PPC64_REL24_NOTOC	addVal
```
The lines of interest are:
```
      10: 00 00 10 04 00 00 60 e4      	pld 3, 0(0), 1
		0000000000000010:  R_PPC64_GOT_TPREL_PCREL34	TGlobal
      18: 14 6a c3 7f  	add 30, 3, 13
		0000000000000019:  R_PPC64_TLS	TGlobal
      1c: 78 f3 c3 7f  	mr	3, 30
```
Which once linked gets turned into:
```
10010210: ff ff 03 06 00 90 6d 38      	paddi 3, 13, -28672, 0
10010218: 00 00 00 60  	nop
1001021c: 78 f3 c3 7f  	mr	3, 30
```
The problem is that register 30 is never set after the optimization.

Therefore it is not correct to relax the above instructions by replacing
the add instruction with a nop.
Instead the add instruction should be replaced with a copy (mr) instruction.
If the add uses the same resgiter as input and as ouput then it is safe to
continue to replace the add with a nop.

Reviewed By: MaskRay

Differential Revision: https://reviews.llvm.org/D95262
2021-03-22 13:15:44 -05:00
Fangrui Song 16c30c3c23 [ELF] Change --shuffle-sections=<seed> to --shuffle-sections=<section-glob>=<seed>
`--shuffle-sections=<seed>` applies to all sections.  The new
`--shuffle-sections=<section-glob>=<seed>` makes shuffling selective.  To the
best of my knowledge, the option is only used as debugging, so just drop the
original form.

`--shuffle-sections '.init_array*=-1'` `--shuffle-sections '.fini_array*=-1'`.
reverses static constructors/destructors of the same priority.
Useful to detect some static initialization order fiasco.

`--shuffle-sections '.data*=-1'`
reverses `.data*` sections. Useful to detect unfunded pointer comparison results
of two unrelated objects.

If certain sections have an intrinsic order, the old form cannot be used.

Differential Revision: https://reviews.llvm.org/D98679
2021-03-18 10:18:19 -07:00
Fangrui Song 423cb321df [ELF] Special case --shuffle-sections=-1 to reverse input sections
If the number of sections changes, which is common for re-links after
incremental updates, the section order may change drastically.

Special case -1 to reverse input sections. This is a stable transform.
The section order is more resilient to incremental updates.  Usually the
code issue (e.g. Static Initialization Order Fiasco, assuming pointer
comparison result of two unrelated objects) is due to the relative order
between two problematic input files A and B.  Checking the regular order
and the reversed order is sufficient.

Differential Revision: https://reviews.llvm.org/D98445
2021-03-17 09:32:44 -07:00
Fangrui Song e4f385d894 [ELF] Support . and $ in symbol names in expressions
GNU ld supports `.` and `$` in symbol names while LLD doesn't support them in
`readPrimary` expressions. Using `.` can result in such an error:

```
https://github.com/ClangBuiltLinux/linux/issues/1318
ld.lld: error: ./arch/powerpc/kernel/vmlinux.lds:255: malformed number: .TOC.
>>>   __toc_ptr = (DEFINED (.TOC.) ? .TOC. : ADDR (.got)) + 0x8000;
```

Allow `.` (ppc64 special symbol `.TOC.`) and `$` (RISC-V special symbol `__global_pointer$`).

Change `diag[3-5].test` to use an invalid character `^`.

Note: GNU ld allows `~` in non-leading positions of a symbol name.  `~`
is not used in practice, conflicts with the unary operator, and can
cause some parsing difficulty, so this patch does not add it.

Differential Revision: https://reviews.llvm.org/D98306
2021-03-11 09:34:36 -08:00
Fangrui Song 74bece8dde [WPD][ELF] Allow whole program devirtualization for version script localized symbols
A `local:` version node in a version script can change the effective symbol binding
to STB_LOCAL. The linker needs to communicate the fact to enable WPD
(otherwise LTO does not know that the `!vcall_visibility` metadata has
effectively changed from VCallVisibilityPublic to VCallVisibilityLinkageUnit).

Reviewed By: tejohnson

Differential Revision: https://reviews.llvm.org/D98220
2021-03-09 22:33:47 -08:00
Albion Fung 36192790d8 [PowerPC][PC Rel] Implement option to omit Power10 instructions from stubs
Implemented the option to omit Power10 instructions from save stubs via the
option --no-power10-stubs or --power10-stubs=no on lld. --power10-stubs= will
override the other option. --power10-stubs=auto also exists to use the default
behaviour (ie allow Power10 instructions in stubs).

Differential Revision: https://reviews.llvm.org/D94627
2021-03-04 13:27:46 -05:00
Peter Smith e35929e026 [LLD][ELF][ARM] Refactor inBranchRange to use addend for PC Bias
In AArch32 ARM, the PC reads two instructions ahead of the currently
executiing instruction. This evaluates to 8 in ARM state and 4 in
Thumb state. Branch instructions on AArch32 compensate for this by
subtracting the PC bias from the addend. For a branch to symbol this
will result in an addend of -8 in ARM state and -4 in Thumb state.

The existing ARM Target::inBranchRange function accounted for this
implict addend within the function meaning that if the addend were
to be taken into account by the caller then it would be double
counted. This complicates the interface for all Targets as callers
wanting to account for addends had to account for the ARM PC-bias.

In certain situations such as:
https://github.com/ClangBuiltLinux/linux/issues/1305
the PC-bias compensation code didn't match up. In particular
normalizeExistingThunk() didn't put the PC-bias back in as Arm
thunks did not store the addend.

The simplest fix for the problem is to add the PC bias in
normalizeExistingThunk when restoring the addend. However I think
it is worth refactoring the Arm inBranchRange implementation so
that fewer calls to getPCBias are needed for other Targets. I
wasn't able to remove getPCBias completely but hopefully the
Relocations.cpp code is simpler now.

In principle a test could be written to replicate the linux kernel
build failure but I wasn't able to reproduce with a small example
that I could build up from scratch.

Fixes https://github.com/ClangBuiltLinux/linux/issues/1305

Differential Revision: https://reviews.llvm.org/D97550
2021-03-02 11:02:33 +00:00
Sam Clegg d49270b087 [lld][ELF] Removing redundant cast. NFC.
Also a couple of minor cleanups in merge-string.s:
- fix inconsistent use of tabs
- use `.p2align` rather than `.align` since `.p2align` works the
  same on all platforms (the meaning of align seems to differ
  between platforms according to `AlignmentIsInBytes`.

I noticed these potential cleanups while porting SHF_STRINGS support to
wasm-ld.

Differential Revision: https://reviews.llvm.org/D97647
2021-02-28 16:53:41 -08:00
Fangrui Song 4bbcd63eea [ELF] Add -z start-stop-gc to let __start_/__stop_ not retain C identifier name sections
For one metadata section usage, each text section references a metadata section.
The metadata sections have a C identifier name to allow the runtime to collect them via `__start_/__stop_` symbols.

Since `__start_`/`__stop_` references are always present from live sections, the
C identifier name sections appear like GC roots, which means they cannot be
discarded by `ld --gc-sections`.

To make such sections GCable, either SHF_LINK_ORDER or a section group is needed.

SHF_LINK_ORDER is not suitable for the references can be inlined into other functions
(See D97430:
Function A (in the section .text.A) references its `__sancov_guard` section.
Function B inlines A (so now .text.B references `__sancov_guard` - this is invalid with the semantics of SHF_LINK_ORDER).

In the linking stage,
if `.text.A` gets discarded, and `__sancov_guard` is retained via the reference from `.text.B`,
the output will be invalid because `__sancov_guard` references the discarded `.text.A`.
LLD errors "sh_link points to discarded section".
)

A section group have size overhead, and is cumbersome when there is just one metadata section.

Add `-z start-stop-gc` to drop the "__start_/__stop_ references retain
non-SHF_LINK_ORDER non-SHF_GROUP C identifier name sections" rule.
We reserve the rights to switch the default in the future.

Reviewed By: phosek, jrtc27

Differential Revision: https://reviews.llvm.org/D96914
2021-02-25 15:46:37 -08:00
Petr Hosek 1a3f3a3fa1 [lld][ELF] __start_/__stop_ refs don't retain C-ident named group sections
The special root semantics for identifier-named sections is meant
specifically for the metadata sections. In the context of group
semantics, where group members are always retained or discarded as a
unit, it's natural not to have this semantics apply to a section in a
group, otherwise we would never discard the group defeating the purpose
of using the group in the first place.

This change modifies the GC behavior so that __start_/__stop_ references
don't retain C identifier named sections in section groups which allows
for these groups to be collected. This matches the behavior of BFD ld.

The only kind of existing case that might break is interdependent
metadata sections that are all in a group together, but that group
doesn't contain any other sections referenced by anything except
implicit inclusion in a `__start_` and/or `__stop_`-referenced
identifier-named section, but such cases should be unlikely.

Differential Revision: https://reviews.llvm.org/D96753
2021-02-20 22:22:05 -08:00
Nico Weber cb4df6eb8d fix comment typos to cycle bots 2021-02-18 14:25:21 -05:00
Nico Weber 279c5dc2f3 fix comment typo to cycle bots 2021-02-17 15:29:39 -05:00
Nico Weber 872efb0b31 fix comment typo to cycle bots 2021-02-17 11:53:42 -05:00
Petr Hosek bfa4235e6e [lld][ELF] Support for zero flag section groups
This change introduces support for zero flag ELF section groups to lld.
lld already supports COMDAT sections, which in ELF are a special type of
ELF section groups. These are generally useful to enable linker GC where
you want a group of sections to always travel together, that is to be
either retained or discarded as a whole, but without the COMDAT
semantics. Other ELF linkers already support zero flag ELF section
groups and this change helps us reach feature parity.

Differential Revision: https://reviews.llvm.org/D96636
2021-02-16 14:33:09 -08:00
Fangrui Song 0557b1bdec [ELF] Resolve defined symbols before undefined symbols
When parsing an object file, LLD interleaves undefined symbol resolution (which
may recursively fetch other lazy objects) with defined symbol resolution.

This may lead to surprising results, e.g. if an object file defines currently
undefined symbols and references another lazy symbol, we may interleave defined
symbols with the lazy fetch, potentially leading to the defined symbols
resolving to different files.

As an example, if both `a.a(a.o)` and `a.a(b.o)` define `foo` (not in COMDAT
group, or in different COMDAT groups) and `__profd_foo` (in COMDAT group
`__profd_foo`).  LLD may resolve `foo` to `a.a(a.o)` and `__profd_foo` to
`b.a(b.o)`, i.e. different files.

```
parse ArchiveFile a.a
  entry fetches a.a(a.o)
  parse ObjectFile a.o
    define entry
    define foo
    reference b
    b fetches a.a(b.o)
    parse ObjectFile b.o
      define prevailing __profd_foo
    define (ignored) non-prevailing __profd_foo
```

Assuming a set of interconnected symbols are defined all or none in several lazy
objects. Arguably making them resolve to the same file is preferable than making
them resolve to different files (some are lazy objects).

The main argument favoring the new behavior is the stability. The relative order
between a defined symbol and an undefined symbol does not change the symbol
resolution behavior.  Only the relative order between two undefined symbols can
affect fetching behaviors.

---

The real world case is reduced from a Fuchsia PGO usage: `a.a(a.o)` has a
constructor within COMDAT group C5 while `a.a(b.o)` has a constructor within
COMDAT group C2. Because they use different group signatures, they are not
de-duplicated. It is not entirely whether Clang behavior is entirely conforming.

LLD selects the PGO counter section (`__profd_*`) from `a.a(b.o)` and the
constructor section from `a.a(a.o)`. The `__profd_*` is a SHF_LINK_ORDER section
linking to its own non-prevailing constructor section, so LLD errors
`sh_link points to discarded section`. This patch fixes the error.

Differential Revision: https://reviews.llvm.org/D95985
2021-02-11 09:41:46 -08:00
Fangrui Song d82679d805 [ELF] Drop Android specific workaround -m aarch64_elf64_le_vec
`extern const bfd_target aarch64_elf64_le_vec;` is a variable in BFD.
It was somehow misused as an emulation by Android.

```
% aarch64-linux-gnu-ld -m aarch64_elf64_le_vec a.o
aarch64-linux-gnu-ld: unrecognised emulation mode: aarch64_elf64_le_vec
Supported emulations: aarch64linux aarch64elf aarch64elf32 aarch64elf32b aarch64elfb armelf armelfb aarch64linuxb aarch64linux32 aarch64linux32b armelfb_linux_eabi armelf_linux_eabi
```

Acked by Stephen Hines, who removed the flag from Android a while back.
2021-02-09 00:43:10 -08:00
Hongtao Yu 5b8db127a3 [ELF] Rewriting the path of sample profile file for --reproduce response.txt
Rewritting the path of the sample profile file in response.txt to be relative to the repro tar.

Reviewed By: MaskRay

Differential Revision: https://reviews.llvm.org/D96193
2021-02-09 00:00:16 -08:00
Fangrui Song eea34aae2e [ELF] Inspect -EL & -EB for OUTPUT_FORMAT(default, big, little)
Choose big if -EB is specified, little if -EL is specified, or default if neither is specified.
The new behavior matches GNU ld.

Fixes: https://github.com/ClangBuiltLinux/linux/issues/1025

Differential Revision: https://reviews.llvm.org/D96214
2021-02-08 10:34:57 -08:00
Fangrui Song 7605a9a009 [ELF] Support aarch64_be
This patch adds

* Big-endian values for `R_AARCH64_{ABS,PREL}{16,32,64}` and `R_AARCH64_PLT32`
* aarch64elfb & aarch64linuxb BFD emulations
* elf64-bigaarch64 output format (bfdname)

Link: https://github.com/ClangBuiltLinux/linux/issues/1288

Differential Revision: https://reviews.llvm.org/D96188
2021-02-08 08:55:29 -08:00
Fangrui Song 6a1235211d [ELF] --gc-sections: collect unused SHF_LINK_ORDER .gcc_except_table
A SHF_LINK_ORDER .gcc_except_table is similar to a .gcc_except_table in
a section group. The associated text section is responsible for retaining it.

LLD still does not support GC of non-group non-SHF_LINK_ORDER .gcc_except_table -
but that is not necessary because we can teach the compiler to set SHF_LINK_ORDER.
2021-02-05 21:35:27 -08:00