Commit Graph

5962 Commits

Author SHA1 Message Date
Fangrui Song c8a1dfc484 [ELF][Hexagon] Improve error message for unknown relocations
Like rLLD354040

Previously, for unknown relocation types, in -no-pie/-pie mode, we got something like:

    foo.o: unrecognized relocation ...

In -shared mode:

    error: can't create dynamic relocation ... against symbol: yyy in readonly segment

Delete the default case from Hexagon::getRelExpr and add the error there. We will get consistent error message like `error: unknown relocation (1024) against symbol foo`

Reviewed By: sidneym

Differential Revision: https://reviews.llvm.org/D66275

llvm-svn: 369260
2019-08-19 14:07:14 +00:00
Sid Manning a0a4c6b722 [lld][Hexagon] Add GOTREL relocations.
Add GOTREL relocation support. (S + A - GOT)

Differential Revision: https://reviews.llvm.org/D66260

llvm-svn: 369258
2019-08-19 13:32:32 +00:00
Fangrui Song a560bbf7a0 [ELF] Replace local variable hasExportDynamic with config->exportDynamic. NFC
llvm-svn: 369187
2019-08-17 10:04:18 +00:00
Fangrui Song d5d79dfd56 [ELF][PPC] Fix getRelExpr for R_PPC64_REL16_HI
Fixes https://github.com/ClangBuiltLinux/linux/issues/640

R_PPC64_REL16_HI was incorrectly computed as an R_ABS relocation.
rLLD368964 made it a linker failure. Change it to use R_PC to fix the
failures.

Add ppc64-reloc-rel.s for these R_PPC64_REL* tests.

llvm-svn: 369184
2019-08-17 06:28:03 +00:00
Fangrui Song 7ca1e0c825 [ELF][Hexagon] Replace R_HEXAGON_GOT with R_GOTPLT
R_GOTPLT is relative to .got.plt since D59594. Since R_HEXAGON_GOT
relocations always have 0 r_addend, they can use R_GOTPLT instead.

Reviewed By: sidneym

Differential Revision: https://reviews.llvm.org/D66274

llvm-svn: 369128
2019-08-16 17:01:56 +00:00
Sid Manning 2d3ebeb813 [lld][Hexagon]Support HEX_32 when building shared objects
Differential Revision: https://reviews.llvm.org/D66105

llvm-svn: 369121
2019-08-16 15:35:02 +00:00
JF Bastien 7a210d65ed Fix lld on GCC 5.1 after the C++14 move
Summary:
libstdc++ in GCC 5.1 has some bugs. The move to C++14 in D66195 triggered one
such bug caused by the new constexpr support in C++14, and the implementation
doing SFINAE wrong with the comparator to std::stable_sort.

Here's a small repro: https://godbolt.org/z/2QC3-n

The fix is to inline the lambdas directly into the llvm::stable_sort call
instead of erasing them through a std::function. The code is more readable as
well.

Reviewers: thakis, ruiu, espindola

Subscribers: emaste, arichardson, MaskRay, jkorous, dexonsmith, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D66306

llvm-svn: 369023
2019-08-15 17:47:19 +00:00
Fangrui Song e54ed4789f [ELF][AArch64] Improve error message for unknown relocations
Like rLLD354040.

Previously, for unrecognized relocation types, in -no-pie/-pie mode, we got something like:

  foo.o: unrecognized relocation ...

In -shared mode:

  error: can't create dynamic relocation ... against symbol: yyy in readonly segment

Delete the default case from AArch64::getRelExpr and add the error there.

Reviewed By: grimar

Differential Revision: https://reviews.llvm.org/D66277

llvm-svn: 368983
2019-08-15 10:02:54 +00:00
Fangrui Song 1542ff5282 [ELF][PPC] Improve error message for unknown relocations
Like rLLD354040.

Previously, for unrecognized relocation types, in -no-pie mode:

  foo.o: unrecognized reloc 256

In -pie/-shared mode:

  error: can't create dynamic relocation R_PPC_xxx against symbol: yyy in readonly segment

llvm-svn: 368964
2019-08-15 05:22:23 +00:00
Jonas Devlieghere 6ba7992031 [LLD] Migrate llvm::make_unique to std::make_unique
Now that we've moved to C++14, we no longer need the llvm::make_unique
implementation from STLExtras.h. This patch is a mechanical replacement
of (hopefully) all the llvm::make_unique instances across the monorepo.

Differential revision: https://reviews.llvm.org/D66259

llvm-svn: 368936
2019-08-14 22:28:17 +00:00
Fangrui Song e220c67b7a [ELF] --gdb-index: fix odd variable name cUs after r365730 and replace lower_bound with partition_point. NFC
llvm-svn: 368845
2019-08-14 12:56:30 +00:00
Fangrui Song f1d538cce5 [ELF] Initialize 2 fields of Symbol in SymbolTable::insert
A new symbol is added to elf::symtab in 3 steps:

1) SymbolTable::insert creates a placeholder.
2) Symbol::mergeProperties
3) Symbol::replace

Fields referenced by steps 2) and 3) should be initialized in
SymbolTable::insert.  `traced` and `referenced` were missed previously.
This did not cause problems because compilers generated code that
initialized them (bit fields) to 0.

Reviewed By: grimar

Differential Revision: https://reviews.llvm.org/D66130

llvm-svn: 368784
2019-08-14 01:52:47 +00:00
Fangrui Song dc06b0bc9a [ELF] Don't special case symbolic relocations with 0 addend to ifunc in writable locations
Currently the following 3 relocation types do not trigger the creation
of a canonical PLT (which changes STT_GNU_IFUNC to STT_FUNC and
redirects all references):

1) GOT-generating (`needsGot`)
2) PLT-generating (`needsPlt`)
3) R_ABS with 0 addend in a writable location. This is used for
  for ifunc function pointers in writable sections such as .data and .toc.

This patch deletes case 3) to simplify the R_*_IRELATIVE generating
logic added in D57371. Other advantages:

* It is guaranteed no more than 1 R_*_IRELATIVE is created for an ifunc.
* PPC64: no need to special case ifunc in toc-indirect to toc-relative relaxation. See D65755

The deleted elf::addIRelativeRelocs demonstrates that one-pass scan
through relocations makes several optimizations difficult. This is
something we can think about in the future.

Reviewed By: peter.smith

Differential Revision: https://reviews.llvm.org/D65995

llvm-svn: 368661
2019-08-13 09:43:40 +00:00
Fangrui Song c6cd62352c [ELF] Simplify handling of exportDynamic and isPreemptible
In Writer::includeInDynSym(), exportDynamic is used by a Defined with
protected or default visibility, to record whether it is required to be
exported into .dynsym. It is set when any of the following conditions
hold:

1) There is an interposable symbol from a DSO (Undefined or SharedSymbol with default visibility)
2) If -shared or --export-dynamic is specified, any symbol in an object file/bitcode sets this property, unless suppressed by canBeOmittedFromSymbolTable().
3) --dynamic-list when producing an executable

4) protected symbol from a DSO preempted by copy relocation/canonical PLT when
  --ignore-{data,function}-address-equality is specified
5) ifunc is exported when -z ifunc-noplt is specified

Bullet points 4) and 5) are irrelevant in this patch.

Bullet 3) does not play well with 1) and 2). When -shared is specified,
exportDynamic of most symbols is true. This makes it incapable to record
--dynamic-list marked symbols. We thus have obscure:

    if (!config->shared)
      b->exportDynamic = true;
    else if (b->includeInDynsym())
      b->isPreemptible = true;

This patch adds another bit `Symbol::inDynamicList` to record
3). We can thus simplify handleDynamicList() by unifying the DSO and
  executable cases. It also allows us to simplify isPreemptible - now
the field is only used in finalizeSections() and later stages.

Reviewed By: peter.smith

Differential Revision: https://reviews.llvm.org/D66091

llvm-svn: 368659
2019-08-13 09:12:52 +00:00
Fangrui Song ab04ad6af7 [ELF] Rename odd variable names "New" after r365730. NFC
New -> newSym or newFlags

Reviewed By: atanasyan

Differential Revision: https://reviews.llvm.org/D66127

llvm-svn: 368651
2019-08-13 06:19:39 +00:00
Fangrui Song 3cafdfddcb [ELF] Remove unnecessary assignment to `isPreemptible` in replaceWithDefined()
After r368535, it is no longer used in the handling of VER_NDX_LOCAL.
Drop it.

llvm-svn: 368550
2019-08-12 10:01:17 +00:00
Fangrui Song cfdd4589f1 [ELF] Remove redundant isDefined() in Symbol::computeBinding() and delete one redundant call site
After r367869, VER_NDX_LOCAL can only be assigned to Defined and
CommonSymbol.  CommonSymbol becomes Defined after replaceCommonSymbols(),
thus `versionId == VER_NDX_LOCAL` will imply `isDefined()`.

In maybeReportUndefined(), computeBinding() is called when the symbol is
unknown to be Undefined. computeBinding() != STB_LOCAL will always be
true.

llvm-svn: 368536
2019-08-11 17:03:00 +00:00
Fangrui Song 635eda8bb0 [ELF] Remove redundant !isPreemptible in Symbol::computeBinding()
!isPreemptible was added in r343668 to fix PR39104: symbols redefined by
replaceWithDefined() might be incorrectly considered STB_LOCAL if a
version script specified `local: *;`.

After r367869 (`config->defaultSymbolVersion` was removed), we will
assign VER_NDX_LOCAL to only regular Defined and CommonSymbol, not
Defined created by replaceWithDefined() (because scanVersionScript() is
called before scanRelocations()). The !isPreemptible is thus redundant
and can be deleted.

llvm-svn: 368535
2019-08-11 16:12:07 +00:00
Fangrui Song 38c5788548 [ELF] Remove unnecessary assignment to `used` in replaceWithDefined
`Symbol::used` is used by Undefined and SharedSymbol to record if a
.symtab entry is needed. It is of no use for Defined.

llvm-svn: 368533
2019-08-11 13:32:46 +00:00
Fangrui Song 179dc276eb [ELF] Expand regions for gaps due to explicit address
If the dot gets moved by an explicit section address, an empty gap between sections could be created. The encompassing region for the section being parsed needs to be expanded to include the gap.

Differential Revision: https://reviews.llvm.org/D65722

Patch by Gabriel Smith!

llvm-svn: 368379
2019-08-09 01:25:49 +00:00
David Blaikie 84b55e61dd DebugInfo: Explicitly handle errors when parsing unit DIEs
This ensures these errors produce a non-zero exit and improves the
context (providing the name of the input object and section being
parsed).

llvm-svn: 368378
2019-08-09 01:14:36 +00:00
Peter Collingbourne 1fa1cd200b ELF: Move sections referred to by __start_/__stop_ symbols into the main partition.
In the case where C identifier sections have SHF_LINK_ORDER they will most
likely be placed in the same partition as the section that they are associated
with. But unless this happens to be the main partition, this will cause them
to be excluded from the range covered by the __start_ and __stop_ symbols,
which may lead to incorrect program behaviour. So we need to move them
all into the main partition so that they will be covered by the __start_
and __stop_ symbols.

We may want to refine this approach later and allow different __start_/__stop_
symbol values for different partitions. This would only make sense for
relocations from SHT_NOTE sections since they are duplicated into each
partition.

Differential Revision: https://reviews.llvm.org/D65909

llvm-svn: 368375
2019-08-09 00:57:54 +00:00
Peter Smith d4695e1d75 [ELF][AArch64] Support for movz, movk tprel relocations
This patch Implements the R_AARCH64_TLSLE_MOVW_TPREL_G*[_NC]. These are
logically the same calculation as the existing TLSLE relocations with
the result written back to mov[nz] and movk instructions. A typical code
sequence is:
movz x0, #:tprel_g2:foo    // bits [47:32] of R_TLS with overflow check
movk x0, #:tprel_g1_nc:foo // bits [31:16] of R_TLS with no overflow check
movk x0, #:tprel_g0_nc:foo // bits [15:0] of R_TLS with no overflow check

This type of code sequence is usually used with a large code model.

Differential Revision: https://reviews.llvm.org/D65882

Fixes: PR42853
llvm-svn: 368293
2019-08-08 13:38:09 +00:00
David Blaikie 8a480d2cbf gdb-index: Wire up str_offsets section to avoid incorrect error message about offsets_base
There's still a need for a deeper fix to the way libDebugInfoDWARF error
messages are propagated up to lld - if lld had exited non-zero on this
error message we would've found the issue sooner.

llvm-svn: 368229
2019-08-07 22:49:14 +00:00
David Blaikie fa2f4395e9 API update for change to LLVM's lib/DebugInfo/DWARF
llvm-svn: 368190
2019-08-07 17:18:18 +00:00
Rui Ueyama cac8df1ab9 Re-submit r367649: Improve raw_ostream so that you can "write" colors using operator<<
The original patch broke buildbots, perhaps because it changed the
default setting whether colors are enabled or not.

llvm-svn: 368131
2019-08-07 08:08:17 +00:00
Fangrui Song c55c0598f9 [ELF][PPC] Don't relax ifunc toc-indirect accesses to toc-relative
Fixes PR42759.

```
// If ifunc is taken address in -fPIC code, it may have a toc entry
.section .toc,"aw",@progbits
  .quad ifunc

// ifunc may be defined as STT_GNU_IFUNC in another object file
.type ifunc, %gnu_indirect_function
```

If ifunc is non-preemptable (e.g. when linking an executable), the toc
entry will be relocated by R_PPC64_IRELATIVE.

R_*_IRELATIVE represents the symbolic value of a
non-preemptable ifunc (not associated with a canonical PLT) in a writable location. It has an unknown value at
link time, so we cannot apply toc-indirect to toc-relative relaxation.

Reviewed By: luporl, sfertile

Differential Revision: https://reviews.llvm.org/D65755

llvm-svn: 368057
2019-08-06 16:57:54 +00:00
Peter Smith 7f320d4bf0 [ELF][ARM] Fix /DISCARD/ of section with .ARM.exidx section
The combineEhSections runs, by design, before processSectionCommands so
that input exception sections like .ARM.exidx and .eh_frame are not assigned
to OutputSections. Unfortunately if /DISCARD/ removes InputSections that
have associated .ARM.exidx sections without discarding the .ARM.exidx
synthetic section then we will end up crashing when trying to sort the
InputSections in ascending address order.

We fix this by filtering out the sections that have been discarded prior
to processing the InputSections in finalizeContents().

fixes pr42890

Differential Revision: https://reviews.llvm.org/D65759

llvm-svn: 368041
2019-08-06 14:13:38 +00:00
Fangrui Song e49c417ed1 [ELF] Make binding (weak or non-weak) logic consistent for Undefined and SharedSymbol
This is a case missed by D64136. If %t1.o has a weak reference on foo,
and %t2.so has a non-weak reference on foo:

```
0. ld.lld %t1.o %t2.so          # ok; STB_WEAK; accepted since D64136
1. ld.lld %t2.so %t1.o          # undefined symbol: foo; STB_GLOBAL
2. gold %t1.o %t2.so            # ok; STB_WEAK
3. gold %t2.so %t1.o            # undefined reference to 'foo'; STB_GLOBAL
4. ld.bfd %t1.o %t2.so          # undefined reference to `foo'; STB_WEAK
5. ld.bfd %t2.so %t1.o          # undefined reference to `foo'; STB_WEAK
```

It can be argued that in both cases, the binding of the undefined foo
should be set to STB_WEAK, because the binding should not be affected by
referenced from shared objects.

--allow-shlib-undefined doesn't suppress errors (3,4,5), but -shared or
--noinhibit-exec allows ld.bfd/gold to produce a binary:

```
3. gold -shared %t2.so %t1.o    # ok; STB_GLOBAL
4. ld.bfd -shared %t2.so %t1.o  # ok; STB_WEAK
5. ld.bfd -shared %t1.o %t1.o   # ok; STB_WEAK
```

If %t2.so has DT_NEEDED entries, ld.bfd will load them (lld/gold don't
have the behavior). If one of the DSO defines foo and it is in the
link-time search path (e.g. DT_NEEDED entry is an absolute path, via
-rpath=, via -rpath-link=, etc),
`ld.bfd %t1.o %t2.so` and `ld.bfd %t1.o %t2.so` will not error.

In this patch, we make Undefined and SharedSymbol share the same binding
computing logic. Case 1 will be allowed:

```
0. ld.lld %t1.o %t2.so          # ok; STB_WEAK; accepted since D64136
1. ld.lld %t2.so %t1.o          # ok; STB_WEAK; changed by this patch
```

In the future, we can explore the option that turns both (0,1) into
errors if --no-allow-shlib-undefined (default when linking an
executable) is in action.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D65584

llvm-svn: 368038
2019-08-06 14:03:45 +00:00
Fangrui Song e28a70daf4 [ELF] Consistently prioritize non-* wildcards overs "*" in version scripts
We prioritize non-* wildcards overs VER_NDX_LOCAL/VER_NDX_GLOBAL "*".
This patch generalizes the rule to "*" of other versions and thus fixes PR40176.
I don't feel strongly about this GNU linkers' behavior but the
generalization simplifies code.

Delete `config->defaultSymbolVersion` which was used to special case
VER_NDX_LOCAL/VER_NDX_GLOBAL "*".

In `SymbolTable::scanVersionScript`, custom versions are handled the same
way as VER_NDX_LOCAL/VER_NDX_GLOBAL. So merge
`config->versionScript{Locals,Globals}` into `config->versionDefinitions`.
Overall this seems to simplify the code.

In `SymbolTable::assign{Exact,Wildcard}Versions`,
`sym->verdefIndex == config->defaultSymbolVersion` is changed to
`verdefIndex == UINT32_C(-1)`.
This allows us to give duplicate assignment diagnostics for
`{ global: foo; };` `V1 { global: foo; };`

In test/linkerscript/version-script.s:
  vs_index of an undefined symbol changes from 0 to 1. This doesn't matter (arguably 1 is better because the binding is STB_GLOBAL) because vs_index of an undefined symbol is ignored.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D65716

llvm-svn: 367869
2019-08-05 14:31:39 +00:00
Fangrui Song d9b948b6eb Rename F_{None,Text,Append} to OF_{None,Text,Append}. NFC
F_{None,Text,Append} are kept for compatibility since r334221.

llvm-svn: 367800
2019-08-05 05:43:48 +00:00
Fangrui Song 25ab1c6471 [ELF] Move R_*_IRELATIVE from .rel[a].plt to .rel[a].dyn unless --pack-dyn-relocs=android[+relr]
An R_*_IRELATIVE represents the address of a STT_GNU_IFUNC symbol
(redirected at runtime) which is non-preemptable and is not associated
with a canonical PLT (associated with a symbol with a section index of
SHN_UNDEF but a non-zero st_value).

.rel[a].plt [DT_JMPREL, DT_JMPREL+DT_JMPRELSZ) contains relocations that
can be lazily resolved. R_*_IRELATIVE are always eagerly resolved, so
conceptually they do not belong to .rela.plt. "iplt" is mostly a misnomer.

glibc powerpc and powerpc64 do not resolve R_*_IRELATIVE if they are in .rela.plt.

    // a.o - synthesized PLT call stub has an R_*_IRELATIVE
    void ifunc(); int main() { ifunc(); }
    // b.o
    static void real() {}
    asm (".type ifunc, %gnu_indirect_function");
    void *ifunc() { return &real; }

The lld-linked executable crashes. ld.bfd places R_*_IRELATIVE in
.rela.dyn and the executable works.

glibc i386, x86_64, and aarch64 have logic
(glibc/sysdeps/*/dl-machine.h:elf_machine_lazy_rel) to eagerly resolve
R_*_IRELATIVE in .rel[a].plt so the lld-linked executable works.

Move R_*_IRELATIVE from .rel[a].plt to .rel[a].dyn to fix the crashes on
glibc powerpc/powerpc64. This also helps simplifying ifunc
implementation in FreeBSD rtld-elf powerpc64.

If --pack-dyn-relocs=android[+relr] is specified, the Android packed
dynamic relocation format is used for .rela.dyn. We cannot name
in.relaIplt ".rela.dyn" because the output section will have mixed
formats. This can be improved in the future.

Reviewed By: pcc

Differential Revision: https://reviews.llvm.org/D65651

llvm-svn: 367745
2019-08-03 02:26:52 +00:00
Rui Ueyama 4d41c332ef Revert r367649: Improve raw_ostream so that you can "write" colors using operator<<
This reverts commit r367649 in an attempt to unbreak Windows bots.

llvm-svn: 367658
2019-08-02 07:22:34 +00:00
Rui Ueyama a52f982f1c Improve raw_ostream so that you can "write" colors using operator<<
1. raw_ostream supports ANSI colors so that you can write messages to
the termina with colors. Previously, in order to change and reset
color, you had to call `changeColor` and `resetColor` functions,
respectively.

So, if you print out "error: " in red, for example, you had to do
something like this:

  OS.changeColor(raw_ostream::RED);
  OS << "error: ";
  OS.resetColor();

With this patch, you can write the same code as follows:

  OS << raw_ostream::RED << "error: " << raw_ostream::RESET;

2. Add a boolean flag to raw_ostream so that you can disable colored
output. If you disable colors, changeColor, operator<<(Color),
resetColor and other color-related functions have no effect.

Most LLVM tools automatically prints out messages using colors, and
you can disable it by passing a flag such as `--disable-colors`.
This new flag makes it easy to write code that works that way.

Differential Revision: https://reviews.llvm.org/D65564

llvm-svn: 367649
2019-08-02 04:48:30 +00:00
Fangrui Song 5391f158c2 [ELF] Add -z separate-code and pad the last page of last PF_X PT_LOAD with traps only if -z separate-code is specified
This patch

1) adds -z separate-code and -z noseparate-code (default).
2) changes the condition that the last page of last PF_X PT_LOAD is
 padded with trap instructions.
 Current condition (after D33630): if there is no `SECTIONS` commands.
 After this change: if -z separate-code is specified.

-z separate-code was introduced to ld.bfd in 2018, to place the text
segment in its own pages. There is no overlap in pages between an
executable segment and a non-executable segment:

1) RX cannot load initial contents from R or RW(or non-SHF_ALLOC).
2) R and RW(or non-SHF_ALLOC) cannot load initial contents from RX.

lld's current status:

- Between R and RX: in `Writer<ELFT>::fixSectionAlignments()`, the start of a
  segment is always aligned to maxPageSize, so the initial contents loaded by R
  and RX do not overlap. I plan to allow overlaps in D64906 if -z noseparate-code
  is in effect.
- Between RX and RW(or non-SHF_ALLOC if RW doesn't exist):
  we currently unconditionally pad the last page to commonPageSize
  (defaults to 4096 on all targets we support).
  This patch will make it effective only if -z separate-code is specified.

-z separate-code is a dubious feature that intends to reduce the number
of ROP gadgets (which is actually ineffective because attackers can find
plenty of gadgets in the text segment, no need to find gadgets in
non-code regions).

With the overlapping PT_LOAD technique D64906, -z noseparate-code
removes two more alignments at segment boundaries than -z separate-code.
This saves at most defaultCommonPageSize*2 bytes, which are significant
on targets with large defaultCommonPageSize (AArch64/MIPS/PPC: 65536).

Issues/feedback on alignment at segment boundaries to help understand
the implication:

* binutils PR24490 (the situation on ld.bfd is worse because they have
  two R-- on both sides of R-E so more alignments.)

* In binutils, the 2018-02-27 commit "ld: Add --enable-separate-code" made -z separate-code the default on Linux.
  d969dea983
  In musl-cross-make, binutils is configured with --disable-separate-code
  to address size regressions caused by -z separate-code. (lld actually has the same
  issue, which I plan to fix in a future patch. The ld.bfd x86 status is
  worse because they default to max-page-size=0x200000).

* https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=237676 people want
  smaller code size. This patch will remove one alignment boundary.

* Stef O'Rear: I'm opposed to any kind of page alignment at the
  text/rodata line (having a partial page of text aliased as rodata and
  vice versa has no demonstrable harm, and I actually care about small
  systems).

So, make -z noseparate-code the default.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D64903

llvm-svn: 367537
2019-08-01 09:58:25 +00:00
Rui Ueyama d524c17029 Return early. NFC.
llvm-svn: 367200
2019-07-29 05:24:51 +00:00
Fangrui Song d6c448244b [ELF] Simplify with dyn_cast_or_null. NFC
llvm-svn: 367126
2019-07-26 16:29:15 +00:00
Fangrui Song 3d51d4ed6d [ELF] Detemplate maybeReportUndefined and copySectionsIntoPartitions
llvm-svn: 367117
2019-07-26 14:57:53 +00:00
Simon Atanasyan 5adbfdda2d [mips] Assign R_TLS type to the R_MIPS_TLS_TPREL_XXX relocations. NFC
That allows to remove duplicated code which subtracts 0x7000 from the
R_MIPS_TLS_TPREL_XXX relocations values in the `MIPS::relocateOne`
function.

llvm-svn: 366888
2019-07-24 11:37:13 +00:00
Nico Weber 9c0716f116 ld.lld: Demangle symbols from archives in diagnostics
This ports r366573 from COFF to ELF.

There are now to toString(Archive::Symbol), one doing MSVC demangling
in COFF and one doing Itanium demangling in ELF, so rename these two
to toCOFFString() and to toELFString() to not get a duplicate symbol.

Nothing ever passes a raw Archive::Symbol to CHECK(), so these not
being part of the normal toString() machinery seems ok.

There are two code paths in the ELF linker that emits this type of
diagnostic:

1. The "normal" one in InputFiles.cpp. This is covered by the tweaked test.

2. An additional one that's only used for libcalls if there's at least
   one bitcode in the link, and if the libcall symbol is lazy, and
   lazily loaded from an archive (i.e. not from a lazy .o file).
   (This code path was added in r339301.) Since all libcall names so far
   are C symbols and never mangled, the change there is not observable
   and hence not covered by tests.

Differential Revision: https://reviews.llvm.org/D65095

llvm-svn: 366836
2019-07-23 19:00:01 +00:00
Petr Hosek ae4c30a4be [ELF] Support explicitly overriding relocation model in LTO
lld currently selects the relocation model automatically depending on
the link flags specified, but in some cases it'd be useful to allow
explicitly overriding the relocation model using a flag.

llvm-svn: 366644
2019-07-20 21:59:47 +00:00
Peter Collingbourne c2ccf4ccba ELF: Add support for remaining R_AARCH64_MOVW* relocations.
Differential Revision: https://reviews.llvm.org/D64685

llvm-svn: 366466
2019-07-18 17:12:50 +00:00
Peter Collingbourne cb2d8e9125 ELF: Allow forward references to linked sections.
It's possible to create IR that uses !associated to refer to a global that
appears later in the module, which can result in these types of forward
references being generated. Unfortunately our assembler does not currently
accept the resulting .s so I needed to use yaml2obj to test this.

Differential Revision: https://reviews.llvm.org/D64880

llvm-svn: 366460
2019-07-18 16:47:29 +00:00
Fangrui Song 782390258b [ELF][PPC] Refactor some ppc64 tests
Merge ppc64-dynamic-relocations.s into ppc64-plt-stub.s
Add ppc64-tls-ie.s: covers ppc64-initial-exec-tls.s and ppc64-tls-ie-le.s
Add ppc64-tls-gd.s: covers ppc64-general-dynamic-tls.s, ppc64-gd-to-ie.s, ppc64-tls-gd-le.s, and ppc64-tls-gd-le-small.s

llvm-svn: 366424
2019-07-18 10:43:07 +00:00
Alex Bradbury 44deaf7e54 [DWARF][RISCV] Add support for RISC-V relocations needed for debug info
When code relaxation is enabled many RISC-V fixups are not resolved but
instead relocations are emitted. This happens even for DWARF debug
sections. Therefore, to properly support the parsing of DWARF debug info
we need to be able to resolve RISC-V relocations. This patch adds:

* Support for RISC-V relocations in RelocationResolver
* DWARF support for two relocations per object file offset
* DWARF changes to support relocations in more DIE fields

The two relocations per offset change is needed because some RISC-V
relocations (used for label differences) come in pairs.

Relocations can also be emitted for DWARF fields where relocations were
not yet evaluated. Adding relocation support for some of these fields is
essencial. On the other hand, LLVM currently emits RISC-V relocations
for fixups that could be safely evaluated, since they can never be
affected by code relaxations. This patch also adds relocation support
for the fields affected by those extraneous relocations (the DWARF unit
entry Length, and the DWARF debug line entry TotalLength and
PrologueLength), for testing purposes.

Differential Revision: https://reviews.llvm.org/D62062
Patch by Luís Marques.

llvm-svn: 366402
2019-07-18 05:22:55 +00:00
Chris Jackson 87886299b4 [lld] Add Visual Studio compatible diagnostics
Summary:
Add a --vs-diagnostics flag that alters the format of diagnostic output
to enable source hyperlinks in Visual Studio.

Differential Revision: https://reviews.llvm.org/D58484

Reviewed by: ruiu

llvm-svn: 366333
2019-07-17 14:54:02 +00:00
Fangrui Song 2be0ebb0d8 [ELF] Delete redundant pageAlign at PT_GNU_RELRO boundaries after D58892
Summary:
After D58892 split the RW PT_LOAD on the PT_GNU_RELRO boundary, the new
layout is:

PT_LOAD(PT_GNU_RELRO(.data.rel.ro .bss.rel.ro)) PT_LOAD(.data. .bss)

The two pageAlign() calls at PT_GNU_RELRO boundaries are redundant due
to the existence of PT_LOAD.

Reviewers: grimar, peter.smith, ruiu, espindola

Reviewed By: ruiu

Subscribers: sfertile, atanasyan, emaste, arichardson, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D64854

llvm-svn: 366307
2019-07-17 09:23:04 +00:00
Fangrui Song 47cfe8f321 [ELF] Fix variable names in comments after VariableName -> variableName change
Also fix some typos.

llvm-svn: 366181
2019-07-16 05:50:45 +00:00
Rui Ueyama 49a3ad21d6 Fix parameter name comments using clang-tidy. NFC.
This patch applies clang-tidy's bugprone-argument-comment tool
to LLVM, clang and lld source trees. Here is how I created this
patch:

$ git clone https://github.com/llvm/llvm-project.git
$ cd llvm-project
$ mkdir build
$ cd build
$ cmake -GNinja -DCMAKE_BUILD_TYPE=Debug \
    -DLLVM_ENABLE_PROJECTS='clang;lld;clang-tools-extra' \
    -DCMAKE_EXPORT_COMPILE_COMMANDS=On -DLLVM_ENABLE_LLD=On \
    -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ ../llvm
$ ninja
$ parallel clang-tidy -checks='-*,bugprone-argument-comment' \
    -config='{CheckOptions: [{key: StrictMode, value: 1}]}' -fix \
    ::: ../llvm/lib/**/*.{cpp,h} ../clang/lib/**/*.{cpp,h} ../lld/**/*.{cpp,h}

llvm-svn: 366177
2019-07-16 04:46:31 +00:00
Jonas Devlieghere ca16d280f7 Re-land "[DebugInfo] Move function from line table to the prologue (NFC)"
In LLDB, when parsing type units, we don't need to parse the whole line
table. Instead, we only need to parse the "support files" from the line
table prologue.

To make that possible, this patch moves the respective functions from
the LineTable into the Prologue. Because I don't think users of the
LineTable should have to know that these files come from the Prologue,

I've left the original methods in place, and made them redirect to the
LineTable.

Differential revision: https://reviews.llvm.org/D64774

llvm-svn: 366164
2019-07-16 01:21:25 +00:00
George Rimar 8d9b9f6bf2 [LLD][ELF] - Minor simplification. NFC.
This removes a call to `object::getSymbol<ELFT>`.
We used this function in a next way: it was given an
array of symbols and index and returned either a symbol
at the index given or a error.

This function was removed in D64631. 
(rL366052, but was reverted because of LLD compilation error
that I didn't know about).

It does not make much sense to keep this function on LLVM side
only for LLD, because having only a list of symbols and the index it
is not able to produce a valueable error message about context anyways.

llvm-svn: 366057
2019-07-15 11:47:54 +00:00
Fangrui Song e1ee3837ac [ELF] Handle non-glob patterns before glob patterns in version scripts & fix a corner case of --dynamic-list
This fixes PR38549, which is silently accepted by ld.bfd.
This seems correct because it makes sense to let non-glob patterns take
precedence over glob patterns.

lld issues an error because
`assignWildcardVersion(ver, VER_NDX_LOCAL);` is processed before `assignExactVersion(ver, v.id, v.name);`.

Move all assignWildcardVersion() calls after assignExactVersion() calls
to fix this.

Also, move handleDynamicList() to the bottom. computeBinding() called by
includeInDynsym() has this cryptic rule:

    if (versionId == VER_NDX_LOCAL && isDefined() && !isPreemptible)
      return STB_LOCAL;

Before the change:

* foo's version is set to VER_NDX_LOCAL due to `local: *`
* handleDynamicList() is called
  - foo.computeBinding() is STB_LOCAL
  - foo.includeInDynsym() is false
  - foo.isPreemptible is not set (wrong)
* foo's version is set to V1

After the change:

* foo's version is set to VER_NDX_LOCAL due to `local: *`
* foo's version is set to V1
* handleDynamicList() is called
  - foo.computeBinding() is STB_GLOBAL
  - foo.includeInDynsym() is true
  - foo.isPreemptible is set (correct)

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D64550

llvm-svn: 365760
2019-07-11 11:16:51 +00:00
Fangrui Song be8275753f [ELF] Warn rather than error when duplicate version assignments occur
In lvm2, libdevmapper.so is linked with a version script with duplicate
version assignments:

    DM_1_02_138 { global: ... dm_bitset_parse_list; ... };
    DM_1_02_129 { global: ... dm_bitset_parse_list; ... };

ld.bfd silently accepts this while gold issues a warning. We currently
error, thus inhibit producing the executable. Change the error to
warning to allow this case, and improve the message.

There are some cases where ld.bfd error
`anonymous version tag cannot be combined with other version tags`
but we just warn. It is probably OK for now.

Reviewed By: grimar, ruiu

Differential Revision: https://reviews.llvm.org/D64549

llvm-svn: 365759
2019-07-11 11:16:44 +00:00
Rui Ueyama bfaf64ae57 Update comments for r365730. NFC.
llvm-svn: 365733
2019-07-11 06:08:54 +00:00
Rui Ueyama 136d27ab4d [Coding style change][lld] Rename variables for non-ELF ports
This patch does the same thing as r365595 to other subdirectories,
which completes the naming style change for the entire lld directory.

With this, the naming style conversion is complete for lld.

Differential Revision: https://reviews.llvm.org/D64473

llvm-svn: 365730
2019-07-11 05:40:30 +00:00
Peter Collingbourne d37edd0c79 ELF: Add support for R_AARCH64_ADR_PREL_PG_HI21_NC relocation.
Differential Revision: https://reviews.llvm.org/D64456

llvm-svn: 365662
2019-07-10 16:42:20 +00:00
George Rimar c44a23f8f4 [LLD][ELF] - Linkerscript: fix FILL() expressions handling.
D64130 introduced a bug described in the following message:
https://reviews.llvm.org/D64130#1571560

The problem can happen with the following script:

SECTIONS {
  .out : {
...
   FILL(0x10101010)
   *(.aaa)
...
}

The current code tries to read (0x10101010) as an expression and
does not break when meets *, what results in a script parsing error.

In this patch, I verify that FILL command's expression always wrapped in ().
And at the same time =<fillexp> expression can be both wrapped or unwrapped.
I checked it matches to bfd/gold.

Differential revision: https://reviews.llvm.org/D64476

llvm-svn: 365635
2019-07-10 14:36:48 +00:00
Rui Ueyama 3837f4273f [Coding style change] Rename variables so that they start with a lowercase letter
This patch is mechanically generated by clang-llvm-rename tool that I wrote
using Clang Refactoring Engine just for creating this patch. You can see the
source code of the tool at https://reviews.llvm.org/D64123. There's no manual
post-processing; you can generate the same patch by re-running the tool against
lld's code base.

Here is the main discussion thread to change the LLVM coding style:
https://lists.llvm.org/pipermail/llvm-dev/2019-February/130083.html
In the discussion thread, I proposed we use lld as a testbed for variable
naming scheme change, and this patch does that.

I chose to rename variables so that they are in camelCase, just because that
is a minimal change to make variables to start with a lowercase letter.

Note to downstream patch maintainers: if you are maintaining a downstream lld
repo, just rebasing ahead of this commit would cause massive merge conflicts
because this patch essentially changes every line in the lld subdirectory. But
there's a remedy.

clang-llvm-rename tool is a batch tool, so you can rename variables in your
downstream repo with the tool. Given that, here is how to rebase your repo to
a commit after the mass renaming:

1. rebase to the commit just before the mass variable renaming,
2. apply the tool to your downstream repo to mass-rename variables locally, and
3. rebase again to the head.

Most changes made by the tool should be identical for a downstream repo and
for the head, so at the step 3, almost all changes should be merged and
disappear. I'd expect that there would be some lines that you need to merge by
hand, but that shouldn't be too many.

Differential Revision: https://reviews.llvm.org/D64121

llvm-svn: 365595
2019-07-10 05:00:37 +00:00
Fangrui Song 50e7f45b28 [ELF] Assert sizeof(SymbolUnion) <= 80
Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D64077

llvm-svn: 365443
2019-07-09 07:12:58 +00:00
Denis Bakhvalov 92fb5f2e47 [LLD] NFC: Fixed GCC warning in ELF/Arch/RISCV.cpp
GCC emits warning on this line:
error: enumeral and non-enumeral type in conditional
expression [-Werror=extra]

Change-Id: I04969cc32e27e310968b88ebaa4e1c4894528d74
llvm-svn: 365434
2019-07-09 03:56:44 +00:00
Nico Weber e3f06b478c Let unaliased Args track which Alias they were created from, and use that in Arg::getAsString() for diagnostics
With this, `clang-cl /source-charset:utf-16 test.cc` now prints `invalid
value 'utf-16' in '/source-charset:utf-16'` instead of `invalid value
'utf-16' in '-finput-charset=utf-16'` before, and several other clang-cl
flags produce much less confusing output as well.

Fixes PR29106.

Since an arg and its alias can have different arg types (joined vs not)
and different values (because of AliasArgs<>), I chose to give the Alias
its own Arg object. For convenience, I just store the alias directly in
the unaliased arg – there aren't many arg objects at runtime, so that
seems ok.

Finally, I changed Arg::getAsString() to use the alias's representation
if it's present – that function was already documented as being the
suitable function for diagnostics, and most callers already used it for
diagnostics.

Implementation-wise, Arg::accept() previously used to parse things as
the unaliased option. The core of that switch is now extracted into a
new function acceptInternal() which parses as the _aliased_ option, and
the previously-intermingled unaliasing is now done as an explicit step
afterwards.

(This also changes one place in lld that didn't use getAsString() for
diagnostics, so that that one place now also prints the flag as the user
wrote it, not as it looks after it went through unaliasing.)

Differential Revision: https://reviews.llvm.org/D64253

llvm-svn: 365413
2019-07-09 00:34:08 +00:00
Nico Weber a780276301 lld, llvm-dlltool, llvm-lib: Use getAsString() instead of getSpelling() for printing unknown args
Since OPT_UNKNOWN args never have any values and consist only of
spelling (and are never aliased), this doesn't make any difference in
practice, but it's more consistent with Arg's guidance to use
getAsString() for diagnostics, and it matches what clang does.

Also tweak two tests to use an unknown option that contains '=' for
additional coverage while here. (The new tests pass fine with the old
code too though.)

llvm-svn: 365200
2019-07-05 12:31:32 +00:00
Nico Weber cf1a11ded2 Make joined instances of JoinedOrSeparate flags point to the unaliased args, like all other arg types do
This fixes an 8-year-old regression. r105763 made it so that aliases
always refer to the unaliased option – but it missed the "joined" branch
of JoinedOrSeparate flags. (r162231 then made the Args classes
non-virtual, and r169344 moved them from clang to llvm.)

Back then, there was no JoinedOrSeparate flag that was an alias, so it
wasn't observable. Now /U in CLCompatOptions is a JoinedOrSeparate alias
in clang, and warn_slash_u_filename incorrectly used the aliased arg id
(using the unaliased one isn't really a regression since that warning
checks if the undefined macro contains slash or backslash and only then
emits the warning – and no valid use will pass "-Ufoo/bar" or similar).

Also, lld has many JoinedOrSeparate aliases, and due to this bug it had
to explicitly call `getUnaliasedOption()` in a bunch of places, even
though that shouldn't be necessary by design. After this fix in Option,
these calls really don't have an effect any more, so remove them.

No intended behavior change.

(I accidentally fixed this bug while working on PR29106 but then
wondered why the warn_slash_u_filename broke. When I figured it out, I
thought it would make sense to land this in a separate commit.)

Differential Revision: https://reviews.llvm.org/D64156

llvm-svn: 365186
2019-07-05 11:45:24 +00:00
George Rimar 0810f16fb9 [LLD][ELF] - Linkerscript: add a support for expressions for section's filling
Imagine the script:

.section: {
...
} = FILL_EXPR
LLD assumes that FILL_EXPR is a number, and does not allow
it to be an expression. Though that is allowed by specification:
https://sourceware.org/binutils/docs-2.32/ld/Output-Section-Fill.html

This patch adds a support for cases when FILL_EXPR is simple math expression.

Fixes https://bugs.llvm.org/show_bug.cgi?id=42482.

Differential revision: https://reviews.llvm.org/D64130

llvm-svn: 365143
2019-07-04 14:17:31 +00:00
Fangrui Song 5c4bbc2746 [ELF] Allow placing non-string SHF_MERGE sections with different alignments into the same MergeSyntheticSection
The difference from D63432/r365015 is that this patch does not place
SHF_STRINGS sections with different alignments into the same
MergeSyntheticSection. Doing that would:

(1) create unnecessary padding and thus waste space.
  Add a test tail-merge-string-align2.s to check no extra padding is created.
(2) make some input sections unaligned when tail merge (-O2) is enabled.
  The alignment of MergeTailAlignment::Builder was out of sync in D63432.
  MOVAPS on such unaligned strings can raise SIGSEGV.

This should fix PR42289: the Linux kernel has a use case that input
files have .rodata.cst32 sections with different alignments. The
expectation (and what ld.bfd and gold do) is that in the -r link, there
is only one .rodata.cst32 (SHF_MERGE sections with different alignments
can be combined), but lld currently creates one for each different
alignment.

The current merging strategy:

1) Group SHF_MERGE sections by (name, sh_flags, sh_entsize and
   sh_addralign). Merging is performed among a group, even if -O0 is specified.
2) Create one output section for each group. This is a special case in
   addInputSec().

This patch changes 1) to:

1) Group SHF_MERGE sections by (name, sh_flags, sh_entsize).
   Merging is performed among a group, even if -O0 is specified.

We will thus create just one .rodata.cst32 . This also improves merging
efficiency when sections with the same name but different alignments are
combined.

Reviewed By: peter.smith

Differential Revision: https://reviews.llvm.org/D64200

llvm-svn: 365139
2019-07-04 13:33:27 +00:00
Fangrui Song f347541fbc [ELF] resolveUndefined: ignore undefined symbols in SharedFile for Undefined and SharedSymbol
If %t1.o has a weak reference on foo, and %t2.so has a non-weak
reference on foo: `ld.lld %t1.o %t2.so -o %t`

We incorrectly set the binding of the undefined foo to STB_GLOBAL.
Fix this by ignoring undefined symbols in a SharedFile for Undefined and
SharedSymbol.

This fixes the binding of pthread_once when the program links against
both librt.so and libpthread.so

```
a.o: STB_WEAK reference to pthread_once
librt.so: STB_GLOBAL reference to pthread_once    # should be ignored
libstdc++.so: STB_WEAK reference to pthread_once  # should be ignored
libgcc_s.so.1: STB_WEAK reference to pthread_once # should be ignored
```

The STB_GLOBAL pthread_once issue (not fixed by D63974) can cause a link error when the result
DSO is used to link another DSO with -z defs if -lpthread is not specified. (libstdc++.so.6 not having a dependency on libpthread.so is a really nasty hack...)

We happened to create a weak undef before D63974 because libgcc_s.so.1
was linked the last and it changed the binding again to weak.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D64136

llvm-svn: 365129
2019-07-04 10:38:04 +00:00
Fangrui Song 4e225deab4 [ELF][RISCV] Error on R_RISCV_PCREL_LO12_[IS] that point to absolute symbols
The referenced symbol is expected to point to an R_RISCV_*_HI20
relocation. An absolute symbol has no associated section, therefore
there cannot be a matching R_RISCV_*_HI20.

This fixes the crash reported by PR42038. For reference, ld.bfd errors:

    (.init+0x4): dangerous relocation: %pcrel_lo missing matching %pcrel_hi

Differential Revision: https://reviews.llvm.org/D63273

llvm-svn: 365049
2019-07-03 15:38:59 +00:00
Fangrui Song b9bc9f67f5 Revert D63432 "[ELF] Allow placing SHF_MERGE sections with different alignments into the same MergeSyntheticSection"
This reverts r365015.

David Zarzycki reported this change broke stage2 and stage3 tests.  The
root cause is still not very clear, but I guess some SHF_MERGE sections
with the same name have different alignments. They were not merged
before but were merged after r365015.

Something that assumes address uniqueness of such mergeable data caused
the bug.

llvm-svn: 365048
2019-07-03 15:26:54 +00:00
Fangrui Song 5cf3cc6246 [ELF][RISCV] Allow R_RISCV_ADD in relocateNonAlloc()
gcc may generate .debug_info/.debug_aranges/.debug_line/etc that are
relocated by R_RISCV_ADD*/R_RISCV_SUB* pairs.
Allow R_RISCV_ADD in non-SHF_ALLOC section to fix link errors like:

    ld.lld: error: print.c:(.debug_frame+0x60): has non-ABS relocation R_RISCV_ADD64 against symbol '.L0 '

Differential Revision: https://reviews.llvm.org/D63259

llvm-svn: 365035
2019-07-03 12:48:04 +00:00
Fangrui Song 347692e2de [ELF] Allow placing SHF_MERGE sections with different alignments into the same MergeSyntheticSection
This should fix PR42289: the Linux kernel has a use case that input
files have .rodata.cst32 sections with different alignments. The
expectation (and what ld.bfd and gold do) is that in the -r link, there
is only one .rodata.cst32 (SHF_MERGE sections with different alignments
can be combined), but lld currently creates one for each different
alignment.

The current merging strategy:

1) Group SHF_MERGE sections by (name, sh_flags, sh_entsize and
   sh_addralign). String merging is performed among a group, even if -O0 is specified.
2) Create one output section for each group. This is a special case in
   addInputSec().

This patch changes 1) to:

1) Group SHF_MERGE sections by (name, sh_flags, sh_entsize).
   String merging is performed among a group, even if -O0 is specified.

We will thus create just one .rodata.cst32 . This also improves merging
efficiency when sections with the same name but different alignments are
combined.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D63432

llvm-svn: 365015
2019-07-03 10:03:49 +00:00
Rui Ueyama 09a0d3d1a2 Avoid identifiers that are different only in case. NFC.
llvm-svn: 365004
2019-07-03 07:08:27 +00:00
Rui Ueyama 11ae59f0ce Avoid identifiers that are different only in case. NFC.
Some variables in lld have the same name as functions ignoring case.
This patch gives them different names, so that my next patch is easier
to read.

llvm-svn: 365003
2019-07-03 06:11:50 +00:00
Sam Clegg 99745896ce [ELF] Error on archive with missing index
This matches the wasm lld and GNU ld behavior.

The ELF linker has special handling for bitcode archives but if that
doesn't kick in we probably want to error out rather than silently
ignore the library.

Differential Revision: https://reviews.llvm.org/D63781

llvm-svn: 364998
2019-07-03 02:29:02 +00:00
Kito Cheng eb9bc38276 [ELF][RISCV] Support RISC-V in getBitcodeMachineKind
Add Triple::riscv64 and Triple::riscv32 to getBitcodeMachineKind for get right
e_machine during LTO.

Reviewed By: ruiu, MaskRay

Differential Revision: https://reviews.llvm.org/D52165

llvm-svn: 364996
2019-07-03 02:13:11 +00:00
Fangrui Song 1c70d136fb [ELF] Only allow the binding of SharedSymbol to change for the first undef ref
Fixes PR42442

t.o has a STB_GLOBAL undef ref to f
t2.so has a STB_WEAK undef ref to f
t1.so defines f

ld.lld t.o t1.so t2.so currently sets the binding of `f` to STB_WEAK.
This is not correct because there exists a STB_GLOBAL undef ref from a
regular object. The problem is that resolveUndefined() doesn't check
if the undef ref is seen for the first time:

    if (isShared() || isLazy() || (isUndefined() && Other.Binding != STB_WEAK))
      Binding = Other.Binding;

The isShared() condition should be `isShared() && !Referenced`
where Referenced is set to true after an undef ref is seen.

In practice, when linking a pthread program with glibc:

    // a.o
    #include <pthread.h>
    pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
    int main() { pthread_mutex_unlock(&mu); }

{clang,gcc} -fuse-ld=lld a.o -lpthread # libpthread.so is linked before libgcc_s.so.1

The weak undef pthread_mutex_unlock in libgcc_s.so.1 makes the result
weak, which diverges from GNU linkers where STB_DEFAULT is used:

    23: 0000000000000000     0 FUNC    WEAK   DEFAULT  UND pthread_mutex_lock

(Note, if -pthread is used instead, libpthread.so will be linked **after**
libgcc_s.so.1 . lld sets the binding to the expected STB_GLOBAL)

Similar linking sequences (ld.lld t.o t1.so t2.so) appear to be used by
Go, which cause a build error https://github.com/golang/go/issues/31912.

Reviewed By: grimar, ruiu

Differential Revision: https://reviews.llvm.org/D63974

llvm-svn: 364913
2019-07-02 11:37:21 +00:00
Fangrui Song ddc57afab9 [ELF][RISCV] Support GD/LD/IE/LE TLS models
RISC-V psABI doesn't specify TLS relaxation. It can be handled the same
way as we handle ARM TLS. RISC-V TLS is even simpler because GD/LD use
the same relocation type.

Reviewed By: jrtc27, ruiu

Differential Revision: https://reviews.llvm.org/D63220

llvm-svn: 364813
2019-07-01 17:12:26 +00:00
Fangrui Song f01fa40a00 [ELF][RISCV] Support PLT, GOT, copy and relative relocations
* Handle initial relocation types: R_RISCV_CALL_PLT and R_RISCV_GOT_HI20.
* Produce dynamic relocation types: R_RISCV_COPY, R_RISCV_RELATIVE, R_RISCV_JUMP_SLOT.
* Define SymbolRel as R_RISCV_{32,64}
* Generate PLT header: it is used by lazy binding PLT in glibc.
* R_RISCV_CALL is changed from R_PC to R_PC_PLT. If the target symbol is preemptable, this will suppress an unnecessary "canonical PLT".
  This behavior is different from ld.bfd but it is agreed the current lld behavior is favored.
  I have received positive responses from the binutils maintainer that the ABI/binutils implementation can be improved, see:
  https://github.com/riscv/riscv-elf-psabi-doc/issues/98
  https://sourceware.org/bugzilla/show_bug.cgi?id=24685

Many -no-pie/-pie/-shared programs linked against musl or glibc should work with this patch.

Reviewed By: jrtc27

Differential Revision: https://reviews.llvm.org/D63076

llvm-svn: 364812
2019-07-01 17:12:18 +00:00
Fangrui Song 78ee2fbf98 Cleanup: llvm::bsearch -> llvm::partition_point after r364719
llvm-svn: 364720
2019-06-30 11:19:56 +00:00
Igor Kudrin fd0ad4b24d [ELF] Do not produce DT_JMPREL and DT_PLTGOT if .rela.plt is empty.
If .rela.plt is mentioned in a linker script, it might be preserved
even if it is empty. In that case, LLD created DT_JMPREL and DT_PLTGOT
dynamic tags. When the tags exist, a dynamic loader writes values into
reserved slots in .got.plt to support lazy symbol resolution.
The problem is that, in fact, the linker has not reserved that space,
and the writing may occur into the memory allocated for something else.

Differential Revision: https://reviews.llvm.org/D63869

llvm-svn: 364639
2019-06-28 10:14:14 +00:00
Fangrui Song ba51fd5664 Reland D61583 [ELF] Error on relocations to STT_SECTION symbols if the sections were discarded
This restores r361830 "[ELF] Error on relocations to STT_SECTION symbols if the sections were discarded"
and dependent commits (r362218, r362497) which were reverted by r364321, with a fix of a --gdb-index issue.

.rela.debug_ranges contains relocations of range list entries:

    // start address of a range list entry
    // old: 0; after r361830: 0
    00000000000033a0 R_X86_64_64 .text._ZN2v88internal7Isolate7factoryEv + 0
    // end address of a range list entry
    // old: 0xe; after r361830: 0
    00000000000033a8 R_X86_64_64 .text._ZN2v88internal7Isolate7factoryEv + e

If both start and end addresses of a range list entry resolve to 0,
DWARFDebugRangeList::isEndOfListEntry() will return true, then the
.debug_range decoding loop will terminate prematurely:

    while (true) {
      decode StartAddress
      decode EndAddress
      if (Entry.isEndOfListEntry()) // prematurely
        break;
      Entries.push_back(Entry);
    }

In lld/ELF/SyntheticSections.cpp, readAddressAreas() will read
incomplete address ranges and the resulting .gdb_index will be
incomplete. For files that gdb hasn't loaded their debug info, gdb uses
.gdb_index to map addresses to CUs. The absent entries make gdb fail to
symbolize some addresses.

To address this issue, we simply allow relocations to undefined symbols
in DWARF.cpp:findAux() and let RelocationResolver resolve them.

This patch should fix:

[1] http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20190603/659848.html
[2] https://bugs.chromium.org/p/chromium/issues/detail?id=978067

llvm-svn: 364391
2019-06-26 08:09:08 +00:00
Hans Wennborg 36c23cad15 Revert r362743 "Revert "Revert "Reland D61583 [ELF] Error on relocations to STT_SECTION symbols if the sections were discarded"""
(In effect, reverting "[ELF] Error on relocations to STT_SECTION symbols if the sections were discarded".)

It caused debug info problems in LibreOffice [1] and Chromium/V8 [2].
Reverting until those can be fixed.

It also reverts r362497 "STT_SECTION symbol should be defined" on .eh_frame, .debug*, .zdebug* and .gcc_except_table"
which was landed as a follow-up to the above.

> With -r or --emit-relocs, we warn `STT_SECTION symbol should be defined`
> on relocations to discarded section symbol. This was added as an error
> in rLLD319404, but was not so effective before D61583 (it turned the
> error to a warning).
>
> Relocations from .eh_frame .debug* .zdebug* .gcc_except_table to
> discarded .text are very common and somewhat expected. Don't warn/error
> on them. As a reference, ld.bfd has a similar logic in
> _bfd_elf_default_action_discarded() to allow these cases.
>
> Delete invalid-undef-section-symbol.test because what it intended to
> check is now covered by the updated comdat-discarded-reloc.s
>
> Delete relocatable-eh-frame.s because we allow relocations from
> .eh_frame as a special case now.

And finally it reverts r362218 "[ELF] Replace a dead test in getSymVA() with assert()"
as that also depended on the main change reverted here.

> Symbols relative to discarded comdat sections are Undefined instead of
> Defined now (after D59649 and D61583). The `== &InputSection::Discarded`
> test becomes dead. I cannot find a test related to this behavior.

 [1] http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20190603/659848.html
 [2] https://bugs.chromium.org/p/chromium/issues/detail?id=978067

llvm-svn: 364321
2019-06-25 14:58:46 +00:00
Rui Ueyama e63ae7fee4 Fix an issue that common symbols are not internalized under some condition.
r360841 introduced CommonSymbol class. An unintended behavioral change
introduced by that change was that common symbols are not internalized
by LTO under some condition. This patch fixes that issue.

The issue occurred under the following condition:

  1. There exists a common symbol
  2. At least one DSO is given to lld or -pie is used

If the above conditions are met, Symbol::includeInDynsym() returned a
wrong value for a common symbol.

Fixes https://bugs.llvm.org/show_bug.cgi?id=41978

Differential Revision: https://reviews.llvm.org/D63752

llvm-svn: 364273
2019-06-25 06:58:07 +00:00
Fangrui Song 2fb6b0f2ba [ELF][PPC][X86] Use [-2**(n-1), 2**n) to check overflows for R_PPC_ADDR16, R_PPC64_ADDR{16,32}, R_X86_64_{8,16}
Similar to R_AARCH64_ABS32, R_PPC64_ADDR32 can represent either a signed
value or unsigned value, thus we should use `[-2**(n-1), 2**n)` instead of
`[-2**(n-1), 2**(n-1))` to check overflows.

The issue manifests as a bogus linker error when linking the powerpc64le Linux kernel.
The new behavior is compatible with ld.bfd's complain_overflow_bitfield.

The upper bound of the error message is not correct. Fix it as well.

The changes to R_PPC_ADDR16, R_PPC64_ADDR16, R_X86_64_8 and R_X86_64_16 are similar.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D63690

llvm-svn: 364164
2019-06-24 05:37:20 +00:00
Nico Weber 2c45043415 lld/elf: Deduplicate undefined symbol diagnostics
Before:

```
ld.lld: error: undefined symbol: f()
>>> referenced by test.cc:3
>>>               /var/folders/c5/8d7sdn1x2mg92mj0rndghhdr0000gn/T/test-9c0808.o:(g())

ld.lld: error: undefined symbol: f()
>>> referenced by test.cc:4
>>>               /var/folders/c5/8d7sdn1x2mg92mj0rndghhdr0000gn/T/test-9c0808.o:(h())

ld.lld: error: undefined symbol: f()
>>> referenced by test.cc:5
>>>               /var/folders/c5/8d7sdn1x2mg92mj0rndghhdr0000gn/T/test-9c0808.o:(j())

ld.lld: error: undefined symbol: k()
>>> referenced by test.cc:5
>>>               /var/folders/c5/8d7sdn1x2mg92mj0rndghhdr0000gn/T/test-9c0808.o:(j())

ld.lld: error: undefined symbol: f()
>>> referenced by test2.cc:2
>>>               /var/folders/c5/8d7sdn1x2mg92mj0rndghhdr0000gn/T/test2-07b391.o:(asdf())
clang: error: linker command failed with exit code 1 (use -v to see invocation)
```

Now:

```
ld.lld: error: undefined symbol: f()
>>> referenced by test.cc:3
>>>               /var/folders/c5/8d7sdn1x2mg92mj0rndghhdr0000gn/T/test-0e07ba.o:(g())
>>> referenced by test.cc:4
>>>               /var/folders/c5/8d7sdn1x2mg92mj0rndghhdr0000gn/T/test-0e07ba.o:(h())
>>> referenced by test.cc:5
>>>               /var/folders/c5/8d7sdn1x2mg92mj0rndghhdr0000gn/T/test-0e07ba.o:(j())
>>> referenced by test2.cc:2
>>>               /var/folders/c5/8d7sdn1x2mg92mj0rndghhdr0000gn/T/test2-6bdb24.o:(asdf())

ld.lld: error: undefined symbol: k()
>>> referenced by test.cc:5
>>>               /var/folders/c5/8d7sdn1x2mg92mj0rndghhdr0000gn/T/test-0e07ba.o:(j())
clang: error: linker command failed with exit code 1 (use -v to see invocation)
```

If there are more than 10 references to an undefined symbol, only the
first 10 are printed.

Fixes PR42260.

Differential Revision: https://reviews.llvm.org/D63344

llvm-svn: 363962
2019-06-20 18:25:57 +00:00
Fangrui Song 249fde8583 [ELF][ARM][AARCH64][MIPS][PPC] Simplify the logic to create R_*_RELATIVE for absolute relocation types in writable sections
Summary:
Our rule to create R_*_RELATIVE for absolute relocation types were
loose. D63121 made it stricter but it failed to create R_*_RELATIVE for
R_ARM_TARGET1 and R_PPC64_TOC. rLLD363236 worked around that by
reinstating the original behavior for ARM and PPC64.

This patch is an attempt to simplify the logic.

Note, in ld.bfd, R_ARM_TARGET2 --target2=abs also creates
R_ARM_RELATIVE. This seems a very uncommon scenario (moreover,
--target2=got-rel is the default), so I do not implement any logic
related to it.

Also, delete R_AARCH64_ABS32 from AArch64::getDynRel. We don't have
working ILP32 support yet. Allowing it would create an incorrect
R_AARCH64_RELATIVE.

For MIPS, the (if SymbolRel, then RelativeRel) code is to keep its
behavior unchanged.

Note, in ppc64-abs64-dyn.s, R_PPC64_TOC gets an incorrect addend because
computeAddend() doesn't compute the correct address. We seem to have the
wrong behavior for a long time. The important thing seems that a dynamic
relocation R_PPC64_TOC should not be created as the dynamic loader will
error R_PPC64_TOC is not supported.

Reviewers: atanasyan, grimar, peter.smith, ruiu, sfertile, espindola

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D63383

llvm-svn: 363928
2019-06-20 14:00:08 +00:00
Fangrui Song ffed2c96d9 [ELF][ARM] Merge handleARMTlsRelocation() into handleTlsRelocation()
ARM and RISC-V do not support TLS relaxations. However, for General
Dynamic and Local Dynamic models, if we are producing an executable and
the symbol is non-preemptable, we know it must be defined and the
R_ARM_TLS_DTPMOD32/R_RISCV_TLS_DTPMOD{32,64} dynamic relocation can be
omitted because it is always 1. This may be necessary for static linking
as DTPMOD may not be expected at load time.

Merge handleARMTlsRelocation() into handleTlsRelocation(). This requires
more logic to R_TLSGD_PC and R_TLSLD_PC. Because we use SymbolicRel to
resolve the relocation at link time, R_ARM_TLS_DTPMOD32 can be deleted
from relocateOne(). It cannot be used as a static relocation type.

As a bonus, the additional logic in R_TLSGD_PC code can be shared by the
TLS support for RISC-V (D63220).

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D63333

llvm-svn: 363927
2019-06-20 13:53:11 +00:00
Francis Visoiu Mistrih 34667519dc [Remarks] Extend -fsave-optimization-record to specify the format
Use -fsave-optimization-record=<format> to specify a different format
than the default, which is YAML.

For now, only YAML is supported.

llvm-svn: 363573
2019-06-17 16:06:00 +00:00
Nico Weber 96a15796fb Remove two unused parameters
llvm-svn: 363419
2019-06-14 16:46:02 +00:00
Fangrui Song e05ca38101 [ELF] Don't emit dynamic relocations with weak undef in writable sections
In processRelocAux(), our handling of 1) link-time constant and 2) weak
undef is the same, so put them together to simplify the logic.

This moves the weak undef code around. The result is that: in a writable
section (or -z notext), we will no longer emit dynamic relocations for
weak undefined symbols.

The new behavior seems to match GNU linkers, and improves consistency
with the case of a readonly section.

The condition `!Config->Shared` was there probably because it is common
for a -shared link not to specify full dependencies. Keep it now but we
may revisit the decision in the future.

gABI says:

> The behavior of weak symbols in areas not specified by this document is
> implementation defined. Weak symbols are intended primarily for use in
> system software. Applications using weak symbols are unreliable since
> changes in the runtime environment might cause the execution to fail.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D63003

llvm-svn: 363399
2019-06-14 14:09:15 +00:00
Rui Ueyama 43f4b037d5 Add --undefined-glob which is an --undefined with wildcard pattern match
This patch adds new command line option `--undefined-glob` to lld.
That option is a variant of `--undefined` but accepts wildcard
patterns so that all symbols that match with a given pattern are
handled as if they were given by `-u`.

`-u foo` is to force resolve symbol foo if foo is not a defined symbol
and there's a static archive that contains a definition of symbol foo.

Now, you can specify a wildcard pattern as an argument for `--undefined-glob`.
So, if you want to include all JNI symbols (which start with "Java_"), you
can do that by passing `--undefined-glob "Java_*"` to the linker, for example.

In this patch, I use the same glob pattern matcher as the version script
processor is using, so it does not only support `*` but also `?` and `[...]`.

Differential Revision: https://reviews.llvm.org/D63244

llvm-svn: 363396
2019-06-14 14:00:59 +00:00
Fangrui Song 5b4285d82d [ELF][RISCV] Create dummy .sdata for __global_pointer$ if .sdata does not exist
If .sdata is absent, linker synthesized __global_pointer$ gets a section index of SHN_ABS.
(ld.bfd has a similar issue: binutils PR24678)

Scrt1.o may use `lla gp, __global_pointer$` to reference the symbol PC
relatively. In -pie/-shared mode, lld complains if a PC relative
relocation references an absolute symbol (SHN_ABS) but ld.bfd doesn't:

    ld.lld: error: relocation R_RISCV_PCREL_HI20 cannot refer to lute symbol: __global_pointer$

Let the reference of __global_pointer$ to force creation of .sdata to
fix the problem. This is similar to _GLOBAL_OFFSET_TABLE_, which forces
creation of .got or .got.plt .

Also, change the visibility from STV_HIDDEN to STV_DEFAULT and don't
define the symbol for -shared. This matches ld.bfd, though I don't
understand why it uses STV_DEFAULT.

Reviewed By: ruiu, jrtc27

Differential Revision: https://reviews.llvm.org/D63132

llvm-svn: 363351
2019-06-14 02:14:53 +00:00
Fangrui Song a78e025558 [ELF] Loosen the condition that changes absolute relocation types to relative relocations for ARM and PPC64
Try fixing build bots after D63121

llvm-svn: 363236
2019-06-13 08:45:22 +00:00
Fangrui Song 4ce0a519c1 [ELF][RISCV] Treat R_RISCV_{ADD,SET,SUB}* as link-time constants
R_RISCV_{ADD,SET,SUB}* are used for local label computation.
Add a new RelExpr member R_RISCV_ADD to represent them.

R_RISCV_ADD is treated as a link-time constant because otherwise
R_RISCV_{ADD,SET,SUB}* are not allowed in -pie/-shared mode.
In glibc Scrt1.o, .rela.eh_frame contains such relocations.
Because .eh_frame is not writable, we get this error:

    ld.lld: error: can't create dynamic relocation R_RISCV_ADD32 against symbol: .L0 in readonly segment; recompil object files with -fPIC or pass '-Wl,-z,notext' to allow text relocations in the output
    >>> defined in ..../riscv64-linux-gnu/lib/Scrt1.o

With D63076 and this patch, I can run -pie/-shared programs linked against glibc.

Note llvm-mc cannot currently produce R_RISCV_SET* so they are not tested.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D63183

llvm-svn: 363128
2019-06-12 07:53:06 +00:00
Fangrui Song 11549e5c46 [ELF][PPC64] Don't report "relocation refers to a discarded section" for .toc
Summary:
clang (as of 2019-06-12) / gcc (as of 8.2.1) PPC64 may emit a .rela.toc
which references an embedded switch table in a discarded .rodata/.text
section. The .toc and the .rela.toc are incorrectly not placed in the
comdat.

Technically a relocation from outside the group is not allowed by the ELF spec:

> A symbol table entry with STB_LOCAL binding that is defined relative
> to one of a group's sections, and that is contained in a symbol table
> section that is not part of the group, must be discarded if the group
> members are discarded. References to this symbol table entry from
> outside the group are not allowed.

Don't report errors to work around the bug.

This should fix the ppc64le-lld-multistage-test bot while linking llvm-tblgen:

    ld.lld: error: relocation refers to a discarded section: .rodata._ZNK4llvm3MVT13getSizeInBitsEv
    >>> defined in utils/TableGen/CMakeFiles/llvm-tblgen.dir/CodeGenRegisters.cpp.o
    >>> referenced by CodeGenRegisters.cpp
    >>> utils/TableGen/CMakeFiles/llvm-tblgen.dir/CodeGenRegisters.cpp.o:(.toc+0x0)

Some other PPC specific sections may have similar problems. We can blacklist more
section names when problems occur.

    // A simple program that reproduces the bug.
    // Note .rela.toc (outside the group) references a section symbol (STB_LOCAL) in a group.
    void puts(const char *);
    struct A {
      void foo(int a) {
        switch (a) {
        case 0: puts("0"); break;
        case 1: puts("1"); puts("1"); break;
        case 2: puts("2"); break;
        case 3: puts("3"); puts("4"); break;
        case 4: puts("4"); break;
        case 5: puts("5"); puts("5"); break;
        case 6: puts("6"); break;
        }
      }
      int a;
    };
    void foo(A x) { x.foo(x.a); }

Reviewers: ruiu, sfertile, espindola

Reviewed By: ruiu

Subscribers: emaste, nemanjai, arichardson, kbarton, jsji, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D63182

llvm-svn: 363126
2019-06-12 07:35:42 +00:00
Fangrui Song 8a529f3cea Revert "Revert r362867: [ELF][PPC] Simplify {read,write}FromHalf16"
This reverts commit r363060 and restores r362867.

r362867 is innocent. The ppc64le-lld-multistage-test bot failure was due to a clang/gcc .toc bug:

    ld.lld: error: relocation refers to a discarded section: .rodata._ZNK4llvm3MVT13getSizeInBitsEv
    >>> defined in utils/TableGen/CMakeFiles/llvm-tblgen.dir/CodeGenRegisters.cpp.o
    >>> referenced by CodeGenRegisters.cpp
    >>>               utils/TableGen/CMakeFiles/llvm-tblgen.dir/CodeGenRegisters.cpp.o:(.toc+0x0)

It will be worked around by D63182.

llvm-svn: 363124
2019-06-12 06:00:39 +00:00
Fangrui Song 47d77365aa [ELF][RISCV] Add R_RISCV_PC_INDIRECT to isRelExpr()
So that R_RISCV_PCREL_LO12_[IS] are considered as link-time constants in
-pie mode, otherwise there are bogus errors:

    ld.lld: error: can't create dynamic relocation R_RISCV_PCREL_LO12_I against symbol: .L0  in readonly segment; recompile object files with -fPIC or pass '-Wl,-z,notext' to allow text relocations in the output

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D63123

llvm-svn: 363064
2019-06-11 13:39:08 +00:00
Rui Ueyama 963d73ff44 Revert r362867: [ELF][PPC] Simplify {read,write}FromHalf16
This reverts commit r362867 since it seems to have broken
ppc64le-lld-multistage-test bot.

llvm-svn: 363060
2019-06-11 13:00:52 +00:00
Fangrui Song 025a815d75 [ELF] Make the rule to create relative relocations in a writable section stricter
The current rule is loose: `!Sym.IsPreemptible || Expr == R_GOT`.

When the symbol is non-preemptable, this allows absolute relocation
types with smaller numbers of bits, e.g. R_X86_64_{8,16,32}. They are
disallowed by ld.bfd and gold, e.g.

    ld.bfd: a.o: relocation R_X86_64_8 against `.text' can not be used when making a shared object; recompile with -fPIC

This patch:

a) Add TargetInfo::SymbolicRel to represent relocation types that resolve to a
symbol value (e.g. R_AARCH_ABS64, R_386_32, R_X86_64_64).

  As a side benefit, we currently (ab)use GotRel (R_*_GLOB_DAT) to resolve
  GOT slots that are link-time constants. Since we now use Target->SymbolRel
  to do the job, we can remove R_*_GLOB_DAT from relocateOne() for all targets.
  R_*_GLOB_DAT cannot be used as static relocation types.
b) Change the condition to `!Sym.IsPreemptible && Type != Target->SymbolicRel || Expr == R_GOT`.

Some tests are caught by the improved error checking (ld.bfd/gold also
issue errors on them). Many misuse .long where .quad should be used
instead.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D63121

llvm-svn: 363059
2019-06-11 12:59:30 +00:00
Peter Collingbourne eaf3f56924 ELF: Don't process the partition end marker during combineEhSections().
Otherwise the getPartition() accessor may return an OOB pointer. Found
using _GLIBCXX_DEBUG.

The error is benign (we never dereference the pointer for the end marker)
so this wasn't caught by e.g. the sanitizer bots.

llvm-svn: 363026
2019-06-11 02:54:30 +00:00
Fangrui Song 44d908d743 [ELF][RISCV] Parse BFD names elf{32,64}-littleriscv
e.g. glibc libc.so on riscv64 uses `OUTPUT_FORMAT(elf64-littleriscv)`.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D63070

llvm-svn: 362922
2019-06-10 08:09:55 +00:00
Martin Storsjo 6ddd7aa4c3 [ELF] [PPC] Fix a typo from SVN r362721
Apparently no test covers this exact codepath, but GCC produced a
warning about it.

llvm-svn: 362883
2019-06-08 18:26:27 +00:00
Fangrui Song 27de3d3950 [ELF][PPC] Simplify {read,write}FromHalf16
I've change the variable names used in PPC64.cpp from "Instr" to "Insn"
because "Insn" is a more common abbreviation for "instruction".

While changing PPC64.cpp relocateOne(), make R_PPC64_ADDR16_LO{_DS}
slightly more efficient by saving a read and a write for the TocOptimize
case.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D63043

llvm-svn: 362867
2019-06-08 05:19:05 +00:00
Peter Collingbourne 0282898586 ELF: Create synthetic sections for loadable partitions.
We create several types of synthetic sections for loadable partitions, including:
- The dynamic symbol table. This allows code outside of the loadable partitions
  to find entry points with dlsym.
- Creating a dynamic symbol table also requires the creation of several other
  synthetic sections for the partition, such as the dynamic table and hash table
  sections.
- The partition's ELF header is represented as a synthetic section in the
  combined output file, and will be used by llvm-objcopy to extract partitions.

Differential Revision: https://reviews.llvm.org/D62350

llvm-svn: 362819
2019-06-07 17:57:58 +00:00
Peter Smith e208208a31 [ELF][AArch64] Support for BTI and PAC
Branch Target Identification (BTI) and Pointer Authentication (PAC) are
architecture features introduced in v8.5a and 8.3a respectively. The new
instructions have been added in the hint space so that binaries take
advantage of support where it exists yet still run on older hardware. The
impact of each feature is:

BTI: For executable pages that have been guarded, all indirect branches
must have a destination that is a BTI instruction of the appropriate type.
For the static linker, this means that PLT entries must have a "BTI c" as
the first instruction in the sequence. BTI is an all or nothing
property for a link unit, any indirect branch not landing on a valid
destination will cause a Branch Target Exception.

PAC: The dynamic loader encodes with PACIA the address of the destination
that the PLT entry will load from the .plt.got, placing the result in a
subset of the top-bits that are not valid virtual addresses. The PLT entry
may authenticate these top-bits using the AUTIA instruction before
branching to the destination. Use of PAC in PLT sequences is a contract
between the dynamic loader and the static linker, it is independent of
whether the relocatable objects use PAC.

BTI and PAC are independent features that can be combined. So we can have
several combinations of PLT:
- Standard with no BTI or PAC
- BTI PLT with "BTI c" as first instruction.
- PAC PLT with "AUTIA1716" before the indirect branch to X17.
- BTIPAC PLT with "BTI c" as first instruction and "AUTIA1716" before the
  first indirect branch to X17.
    
The use of BTI and PAC in relocatable object files are encoded by feature
bits in the .note.gnu.property section in a similar way to Intel CET. There
is one AArch64 specific program property GNU_PROPERTY_AARCH64_FEATURE_1_AND
and two target feature bits defined:
- GNU_PROPERTY_AARCH64_FEATURE_1_BTI
-- All executable sections are compatible with BTI.
- GNU_PROPERTY_AARCH64_FEATURE_1_PAC
-- All executable sections have return address signing enabled.

Due to the properties of FEATURE_1_AND the static linker can tell when all
input relocatable objects have the BTI and PAC feature bits set. The static
linker uses this to enable the appropriate PLT sequence.
Neither -> standard PLT
GNU_PROPERTY_AARCH64_FEATURE_1_BTI -> BTI PLT
GNU_PROPERTY_AARCH64_FEATURE_1_PAC -> PAC PLT
Both properties -> BTIPAC PLT

In addition to the .note.gnu.properties there are two new command line
options:
--force-bti : Act as if all relocatable inputs had
GNU_PROPERTY_AARCH64_FEATURE_1_BTI and warn for every relocatable object
that does not.
--pac-plt : Act as if all relocatable inputs had
GNU_PROPERTY_AARCH64_FEATURE_1_PAC. As PAC is a contract between the loader
and static linker no warning is given if it is not present in an input.

Two processor specific dynamic tags are used to communicate that a non
standard PLT sequence is being used.
DTI_AARCH64_BTI_PLT and DTI_AARCH64_BTI_PAC.

Differential Revision: https://reviews.llvm.org/D62609

llvm-svn: 362793
2019-06-07 13:00:17 +00:00
Fangrui Song 32742d8f36 [ELF] Delete R_PPC64_CALL_PLT from isRelExpr()
It was added by D46654 but is actually never used.
R_PPC64_CALL_PLT (was: R_PPC_CALL_PLT) is a static link-time constant.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D62994

llvm-svn: 362788
2019-06-07 11:09:33 +00:00
Jordan Rupprecht 0629e1252f Revert [ELF] Simplify the condition to create .interp
This reverts r362355 (git commit c78c999a9c)

This causes some internal tests to fail; details provided offthread.

llvm-svn: 362755
2019-06-06 23:23:14 +00:00
Sean Fertile 6a573e3ec3 Revert "Revert "[ELF] Suppress "STT_SECTION symbol should be defined" on .eh_frame, .debug*, .zdebug* and .gcc_except_table""
This reverts commit f49f58527a6d8147524d8d6f2eb1feb70f856292.

llvm-svn: 362744
2019-06-06 20:16:59 +00:00
Sean Fertile 6ba76dd779 Revert "Revert "Reland D61583 [ELF] Error on relocations to STT_SECTION symbols if the sections were discarded""
This reverts commit 729111cf1824159bb4dd331cab8a829eab30313f.

Reverting the previous commit breaks other LLD buildbots.

llvm-svn: 362743
2019-06-06 20:16:53 +00:00
Sean Fertile f1d9b3180e Revert "Reland D61583 [ELF] Error on relocations to STT_SECTION symbols if the sections were discarded"
This reverts commit 5d3b3188f7.

Breaks the PowerPC multi-stage buildbot.

llvm-svn: 362739
2019-06-06 19:34:26 +00:00
Sean Fertile a0a63b2f90 Revert "[ELF] Suppress "STT_SECTION symbol should be defined" on .eh_frame, .debug*, .zdebug* and .gcc_except_table"
This reverts commit dcba4828a9.

This commit builds on  dcba4828a9 which breaks the
multi-staged PowerPC buildbot.

llvm-svn: 362738
2019-06-06 19:34:18 +00:00
Fangrui Song 7ccfdad7ab [PPC32] Support GD/LD/IE/LE TLS models and their relaxations
Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D62940

llvm-svn: 362722
2019-06-06 17:03:10 +00:00
Fangrui Song 82442adfc0 [PPC32] Improve the 32-bit PowerPC port
Many -static/-no-pie/-shared/-pie applications linked against glibc or musl
should work with this patch. This also helps FreeBSD PowerPC64 to migrate
their lib32 (PR40888).

* Fix default image base and max page size.
* Support new-style Secure PLT (see below). Old-style BSS PLT is not
  implemented, so it is not suitable for FreeBSD rtld now because it doesn't
  support Secure PLT yet.
* Support more initial relocation types:
  R_PPC_ADDR32, R_PPC_REL16*, R_PPC_LOCAL24PC, R_PPC_PLTREL24, and R_PPC_GOT16.
  The addend of R_PPC_PLTREL24 is special: it decides the call stub PLT type
  but it should be ignored for the computation of target symbol VA.
* Support GNU ifunc
* Support .glink used for lazy PLT resolution in glibc
* Add a new thunk type: PPC32PltCallStub that is similar to PPC64PltCallStub.
  It is used by R_PPC_REL24 and R_PPC_PLTREL24.

A PLT stub used in -fPIE/-fPIC usually loads an address relative to
.got2+0x8000 (-fpie/-fpic code uses _GLOBAL_OFFSET_TABLE_ relative
addresses).
Two .got2 sections in two object files have different addresses, thus a PLT stub
can't be shared by two object files. To handle this incompatibility,
change the parameters of Thunk::isCompatibleWith to
`const InputSection &, const Relocation &`.

PowerPC psABI specified an old-style .plt (BSS PLT) that is both
writable and executable. Linkers don't make separate RW- and RWE segments,
which causes all initially writable memory (think .data) executable.
This is a big security concern so a new PLT scheme (secure PLT) was developed to
address the security issue.

TLS will be implemented in D62940.

glibc older than ~2012 requires .rela.dyn to include .rela.plt, it can
not handle the DT_RELA+DT_RELASZ == DT_JMPREL case correctly. A hack
(not included in this patch) in LinkerScript.cpp addOrphanSections() to
work around the issue:

    if (Config->EMachine == EM_PPC) {
      // Older glibc assumes .rela.dyn includes .rela.plt
      Add(In.RelaDyn);
      if (In.RelaPlt->isLive() && !In.RelaPlt->Parent)
        In.RelaDyn->getParent()->addSection(In.RelaPlt);
    }

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D62464

llvm-svn: 362721
2019-06-06 17:03:00 +00:00
Sam Clegg 579c8df701 [lld] Explicitly ignore comdat groups when parsing LTO object(s)
Any symbols defined in the LTO object are by definition the ones we
want in the final output so we skip the comdat group checking in those
cases.

This change makes the ELF code more explicit about this and means
that wasm and ELF do this in the same way.

Differential Revision: https://reviews.llvm.org/D62884

llvm-svn: 362625
2019-06-05 17:39:37 +00:00
Peter Smith e12334a0f2 [ELF] Allow reading of more than one FEATURE_1_AND in same object.
Although many relocatable objects will have a single
GNU_PROPERTY_X86_FEATURE_1_AND in the .note.gnu.property section it is
permissible to have more than one, and there are tests in ld.bfd that use
it. The behavior that ld.bfd follows is to set the feature bit for a
relocatable object if any of the GNU_PROPERTY_X86_FEATURE_1_AND
have the feature bit set.

Differential Revision: https://reviews.llvm.org/D62862

llvm-svn: 362591
2019-06-05 09:31:45 +00:00
Rui Ueyama 2057f8366a Read .note.gnu.property sections and emit a merged .note.gnu.property section.
This patch also adds `--require-cet` option for the sake of testing.
The actual feature for IBT-aware PLT is not included in this patch.

This is a part of https://reviews.llvm.org/D59780. Submitting this
first should make it easy to work with a related change
(https://reviews.llvm.org/D62609).

Differential Revision: https://reviews.llvm.org/D62853

llvm-svn: 362579
2019-06-05 03:04:46 +00:00
Fangrui Song dcba4828a9 [ELF] Suppress "STT_SECTION symbol should be defined" on .eh_frame, .debug*, .zdebug* and .gcc_except_table
Summary:
With -r or --emit-relocs, we warn `STT_SECTION symbol should be defined`
on relocations to discarded section symbol. This was added as an error
in rLLD319404, but was not so effective before D61583 (it turned the
error to a warning).

Relocations from .eh_frame .debug* .zdebug* .gcc_except_table to
discarded .text are very common and somewhat expected. Don't warn/error
on them. As a reference, ld.bfd has a similar logic in
_bfd_elf_default_action_discarded() to allow these cases.

Delete invalid-undef-section-symbol.test because what it intended to
check is now covered by the updated comdat-discarded-reloc.s

Delete relocatable-eh-frame.s because we allow relocations from
.eh_frame as a special case now.

Reviewers: grimar, phosek, ruiu, espindola

Reviewed By: ruiu

Subscribers: emaste, arichardson, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D62840

llvm-svn: 362497
2019-06-04 13:41:29 +00:00
Peter Collingbourne 06f3b094e4 ELF: Introduce a separate bit for tracking whether an output section has ever had an input section added to it. NFCI.
We currently (ab)use the Live bit on output sections to track whether
the section has ever had an input section added to it, and then later
use it during orphan placement. This will conflict with one of my upcoming
partition-related changes that will assign all output sections to a partition
(thus marking them as live) so that they can be added to the correct segment
by the code that creates program headers.

Instead of using the Live bit for this purpose, create a new flag and
start using it to track the property explicitly.

Differential Revision: https://reviews.llvm.org/D62348

llvm-svn: 362444
2019-06-03 20:14:25 +00:00
George Rimar 3b20ae6c54 [LLD][ELF] - Remove dead code. NFC.
I believe this line was dead after r362356.

llvm-svn: 362367
2019-06-03 09:23:01 +00:00
Fangrui Song 8522d579b8 [ELF][PPC64] Rename some PPC64 ELFv2 specific RelExpr from R_PPC_* to R_PPC64_*
The following abstract relocation types (RelExpr) are PPC64 ELFv2 ABI specific,
not used by PPC32. So rename them to prevent confusion when the PPC32 port is improved.

* R_PPC_CALL R_PPC_CALL_PLT:
  R_PPC_CALL_PLT represents R_PPC64_REL14 and R_PPC64_REL24.
  If the function is not preemptable, R_PPC_CALL_PLT can be optimized to R_PPC_CALL:
  the formula adjusts the symbol VA from the global entry point to the local entry point.
* R_PPC_TOC: represents R_PPC64_TOC.  We don't have a test. Add one to ppc64-relocs.s
  Rename it to R_PPC64_TOCBASE because `@tocbase` is the assembly form.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D62800

llvm-svn: 362359
2019-06-03 06:21:33 +00:00
Fangrui Song ce1534b405 [ELF][PPC64] Don't apply LD->LE relaxation on R_PPC64_GOT_DTPREL16*
In ELF v2 ABI, R_PPC64_GOT_DTPREL16* are not relaxed.

This family of relocation types are used for variables outside of 2GiB
of the TLS block. 2 instructions cannot materialize a DTPREL offset that
is not 32-bit.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D62737

llvm-svn: 362357
2019-06-03 05:41:31 +00:00
Fangrui Song abb7484c31 [ELF] Don't create an output section named `/DISCARD/` if it is assigned to the special phdr `NONE`
Fixes the remaining issue of PR41673 after D61186: with `/DISCARD/ { ... } :NONE`,
we may create an output section named `/DISCARD/`.

Note, if an input section is named `/DISCARD/`, ld.bfd discards it but
lld keeps it. It is probably not worth copying this behavior as it is unrealistic.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D62768

llvm-svn: 362356
2019-06-03 05:34:25 +00:00
Fangrui Song c78c999a9c [ELF] Simplify the condition to create .interp
(1) {gcc,clang} -fuse-ld=bfd -pie -fPIE -nostdlib a.c => .interp created
(2) {gcc,clang} -fuse-ld=lld -pie -fPIE -nostdlib a.c => .interp not created
(3) {gcc,clang} -fuse-ld=lld -pie -fPIE -nostdlib a.c a.so => .interp created

The inconsistency of (2) is due to the condition `!Config->SharedFiles.empty()`.
To make lld behave more like ld.bfd, we could change the condition to:

    Config->HasDynSymTab && !Config->DynamicLinker.empty() && Script->needsInterpSection();

However, that would bring another inconsistency as can be observed with:

(4) {gcc,clang} -fuse-ld=bfd -no-pie -nostdlib a.c => .interp not created

So instead, use `!Config->DynamicLinker.empty() && Script->needsInterpSection()`,
which is both simple and consistent in these cases.

The inconsistency of (4) likely originated from ld.bfd and gold's choice to have a default --dynamic-linker.
Their condition to create .interp is ANDed with (not -shared).
Since lld doesn't have a default --dynamic-linker,
compiler drivers (gcc/clang) don't pass --dynamic-linker for -shared,
and direct ld users are not supposed to specify --dynamic-linker for -shared,
we do not need the condition !Config->Shared.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D62765

llvm-svn: 362355
2019-06-03 05:25:03 +00:00
Fangrui Song 0a6bababa8 [ELF][MIPS] Delete dead !Sym->isDefined() check in addAbsolute()
llvm-svn: 362314
2019-06-02 02:43:38 +00:00
Fangrui Song e98baf8631 [ELF] Delete GotEntrySize and GotPltEntrySize
GotEntrySize and GotPltEntrySize were added in D22288. Later, with
the introduction of wordsize() (then Config->Wordsize), they become
redundant, because there is no target that sets GotEntrySize or
GotPltEntrySize to a number different from Config->Wordsize.

Reviewed By: grimar, ruiu

Differential Revision: https://reviews.llvm.org/D62727

llvm-svn: 362220
2019-05-31 10:35:45 +00:00
Fangrui Song 3f29cfd915 [ELF] Replace a dead test in getSymVA() with assert()
Symbols relative to discarded comdat sections are Undefined instead of
Defined now (after D59649 and D61583). The `== &InputSection::Discarded`
test becomes dead. I cannot find a test related to this behavior.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D62725

llvm-svn: 362218
2019-05-31 10:12:22 +00:00
Fangrui Song 0317e46a63 [ELF] Delete dead SHT_NOBITS->SHT_PROGBITS code after r358981
After D60131/r358981, we no longer create SHT_NOBITS sections that may
contain ByteCommand (BYTE, SHORT, LONG, QUAD).

llvm-svn: 362108
2019-05-30 15:52:11 +00:00
Fangrui Song bdaa39ea6c [ELF] De-template addUndefined() and addWrappedSymbols(). NFC
llvm-svn: 362099
2019-05-30 14:50:10 +00:00
Fangrui Song 0526c0cd8e [ELF] Implement Local Dynamic style TLSDESC for x86-64
For the Local Dynamic case of TLSDESC, _TLS_MODULE_BASE_ is defined as a
special TLS symbol that makes:

1) Without relaxation: it produces a dynamic TLSDESC relocation that
computes 0. Adding @dtpoff to access a TLS symbol.
2) With LD->LE relaxation: _TLS_MODULE_BASE_@tpoff = 0 (lowest address in
the TLS block). Adding @tpoff to access a TLS symbol.

For 1), this saves dynamic relocations and GOT slots as otherwise
(General Dynamic) we would create an R_X86_64_TLSDESC and reserve two
GOT slots for each symbol.

Add ElfSym::TlsModuleBase and change the signature of getTlsTpOffset()
to special case _TLS_MODULE_BASE_.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D62577

llvm-svn: 362078
2019-05-30 10:00:20 +00:00
Peter Collingbourne 87575f6501 ELF: Don't reuse a thunk in a different loadable partition.
There's no guarantee that the other partition will be loaded, so it
can't be reused.

Differential Revision: https://reviews.llvm.org/D62365

llvm-svn: 361926
2019-05-29 04:06:01 +00:00
Peter Collingbourne ba2816be82 ELF: Add basic partition data structures and behaviours.
This change causes us to read partition specifications from partition
specification sections and split output sections into partitions according
to their reachability from partition entry points.

This is only the first step towards a full implementation of partitions. Later
changes will add additional synthetic sections to each partition so that
they can be loaded independently.

Differential Revision: https://reviews.llvm.org/D60353

llvm-svn: 361925
2019-05-29 03:55:20 +00:00
Fangrui Song 719322411c [ELF] Implement General Dynamic style TLSDESC for x86-64
This handles two initial relocation types R_X86_64_GOTPC32_TLSDESC and
R_X86_64_TLSDESC_CALL, as well as the GD->LE and GD->IE relaxations.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D62513

llvm-svn: 361911
2019-05-29 02:03:56 +00:00
Fangrui Song 5d3b3188f7 Reland D61583 [ELF] Error on relocations to STT_SECTION symbols if the sections were discarded
This is implemented by creating Undefined (instead of Defined) for such
local STT_SECTION symbols. It allows us to catch errors when there are
relocations to such discarded sections (e.g. in PR41693, ld.bfd and gold
error but we don't). Updated comdat-discarded-error.s checks we emit
friendly error message.

For relocatable-eh-frame.s, ld.lld -r a.o a.o will now error
"STT_SECTION symbol should be defined" because the section .eh_frame
refers to is now an Undefined instead of a Defined.
So I have to change `error()` to `warn()` to retain the output.

rLLD361144 inadvertently enabled the error for --gdb-index
(in LLDDwarfObj<ELFT>::findAux()).

Relocations from .debug_info (not in comdat) to .text.* (in comdat) for
DW_AT_low_pc are common. If an .text.* was discarded, rLLD361144 would error,
which was unexpected. (Note, if we don't error as this patch does,
InputSection::relocateNonAlloc() will resolve such relocations).

llvm-svn: 361830
2019-05-28 14:34:28 +00:00
Haojian Wu 241dcb386e Revert [ELF] Error on relocations to STT_SECTION symbols if the sections were discarded
This reverts r361792 (git commit cfca5095df), the
revision causes link errors internally, will share more details with the
author.

llvm-svn: 361806
2019-05-28 11:21:59 +00:00
Fangrui Song 173a68f1fb [ELF] Replace two addSymbol() call sites with Symbol::resolve(). NFC
If we have a handle of the symbol, insert() called by addSymbol() is
redundant. Just call resolve().

llvm-svn: 361802
2019-05-28 10:12:06 +00:00
Fangrui Song cfca5095df [ELF] Error on relocations to STT_SECTION symbols if the sections were discarded
This is implemented by creating Undefined (instead of Defined) for such
local STT_SECTION symbols. It allows us to catch errors when there are
relocations to such discarded sections (e.g. in PR41693, ld.bfd and gold
error but we don't). Updated comdat-discarded-error.s checks we emit
friendly error message.

For relocatable-eh-frame.s, ld.lld -r a.o a.o will now error
"STT_SECTION symbol should be defined" because the section .eh_frame
refers to is now an Undefined instead of a Defined.
So I have to change `error()` to `warn()` to retain the output.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D61583

llvm-svn: 361792
2019-05-28 06:34:52 +00:00
Rui Ueyama d8f8abbd4a Use SymbolTable::insert() to implement --trace.
Differential Revision: https://reviews.llvm.org/D62381

llvm-svn: 361791
2019-05-28 06:33:06 +00:00
Rui Ueyama 92069605bf Merge ELFFileBase::{initSymtab,parseHeader} as ELFFileBase:init. NFC.
This patch simplifies ELFFile instance initialization by merging
two similar functions into a single function and call it from the
ctor.

llvm-svn: 361789
2019-05-28 05:17:21 +00:00
Rui Ueyama 76737f4d19 Remove elf::createSharedFile and move its code to SharedFile's ctor. NFC.
llvm-svn: 361747
2019-05-27 07:26:13 +00:00
Sam Clegg a5ca34e6b3 [WebAssebmly] Add support for --wrap
The code for implementing this features is taken almost verbatim
from the ELF backend.

Fixes: https://bugs.llvm.org/show_bug.cgi?id=41681

Differential Revision: https://reviews.llvm.org/D62380

llvm-svn: 361639
2019-05-24 14:14:25 +00:00
Sam Clegg 7991b68284 [lld] Trace all references with lld --trace-symbol
Previously undefined symbol references were only traced if they were
seen before that definition.

Fixes https://bugs.llvm.org/show_bug.cgi?id=41878

Differential Revision: https://reviews.llvm.org/D61929

llvm-svn: 361636
2019-05-24 13:29:17 +00:00
Fangrui Song 7d4a67852d [ELF] Fix a doc typo. NFC
llvm-svn: 361617
2019-05-24 09:53:25 +00:00
Fangrui Song 7f1ff68a16 [ELF] Deleted unused forward declarations. NFC
llvm-svn: 361614
2019-05-24 09:25:47 +00:00
Peter Collingbourne ca6a8ae0bf ELF: Remove a comparison against In.EhFrame. NFCI.
This won't work once we have multiple .eh_frame sections.

Differential Revision: https://reviews.llvm.org/D62280

llvm-svn: 361556
2019-05-23 21:30:30 +00:00
Rui Ueyama f5d9d23905 Simplify InputFile::fetch().
We don't have to return a value from the function. Instead, we can
directly call parseFile from the functions.

llvm-svn: 361478
2019-05-23 10:15:12 +00:00
Rui Ueyama 821a1ac050 Remove LazyObjFile::AddedToLink.
Instead we can just clear a MemoryBuffer so that we cannot get the
same buffer more than once.

llvm-svn: 361477
2019-05-23 10:08:56 +00:00
Rui Ueyama 7f7d2b2e62 Move code for symbol resolution from SymbolTable.cpp to Symbols.cpp.
My recent commits separated symbol resolution from the symbol table,
so the functions to resolve symbols are now in a somewhat wrong file.
This patch moves it to Symbols.cpp.

The functions are now member functions of the symbol.

This is code move change. I modified function names so that they are
appropriate as member functions, though. No functionality change
intended.

Differential Revision: https://reviews.llvm.org/D62290

llvm-svn: 361474
2019-05-23 09:58:08 +00:00
Rui Ueyama 4254840313 Speed up --start-lib and --end-lib.
--{start,end}-lib give files grouped by the options the archive file
semantics. That is, each object file between them acts as if it were
in an archive file whose sole member is the file.

Therefore, files between --{start,end}-lib are linked to the final
output only if they are needed to resolve some undefined symbols.

Previously, the feature was implemented this way:

 1. We read a symbol table and insert defined symbols to the symbol
    table as lazy symbols.

 2. If an undefind symbol is resolved to a lazy symbol, that lazy
    symbol instantiate ObjFile class for that symbol, which re-insert
    all defined symbols to the symbol table.

So, if an ObjFile is instantiated, defined symbols are inserted to the
symbol table twice. Since inserting long symbol names is not cheap,
there's a room to optimize here.

This patch optimzies it. Now, LazyObjFile remembers symbol handles and
passed them over to a new ObjFile instance, so that the ObjFile
doesn't insert the same strings.

Here is a quick benchmark to link clang. "Original" is the original
lld with unmodified command line options. For "Case 1" and "Case 2", I
extracted all files from archive files and replace .a's in a command
line with .o's wrapped with --{start,end}-lib. I used the original lld
for Case 1" and use this patch for Case 2.

  Original: 5.892
    Case 1: 6.001 (+1.8%)
    Case 2: 5.701 (-3.2%)

So, interestingly, --{start,end}-lib are now faster than the regular
linking scheme with archive files. That's perhaps not too surprising,
though, because for regular archive files, we look up the symbol table
with the same string twice.

Differential Revision: https://reviews.llvm.org/D62188

llvm-svn: 361473
2019-05-23 09:53:30 +00:00
George Rimar 77b4f0abb8 [LLD][ELF] - Improve diagnostic about unrecognized relocations.
This is a minor improvement inspired by https://bugs.llvm.org/show_bug.cgi?id=38303.

A person reported that he observed message complaining about unsupported R_ARM_V4BX:
error: can't create dynamic relocation R_ARM_V4BX against local symbol in readonly segment; recompile object files with -fPIC

But with -z notext he only saw a relocation number, what is not convenient:
error: ../../gfx/cairo/libpixman/src/pixman-arm-neon-asm-bilinear.o:(.text+0x4F0): unrecognized reloc 40

Also, in the error messages we use relocation but not reloc.

With this patch we start to print one of the following messages:
error: file.o: unrecognized relocation Unknown(999)
error: file.o: unrecognized relocation R_X_KNOWN_BY_LLVM_BUT_UNSUPPORTED_BY_LLD_NAME

There is no way to write a test for that I believe.

Differential revision: https://reviews.llvm.org/D62237

llvm-svn: 361472
2019-05-23 09:50:18 +00:00
Rui Ueyama 0baaf45be7 Move SymbolTable::addCombinedLTOObject() to LinkerDriver.
Also renames it LinkerDriver::compileBitcodeFiles.

The function doesn't logically belong to SymbolTable. We added this
function to the symbol table because symbol table used to be a
container of input files. This is no longer the case.

Differential Revision: https://reviews.llvm.org/D62291

llvm-svn: 361469
2019-05-23 09:26:27 +00:00
Rui Ueyama ecf6eb515f Copy symbol length when we replace a symbol.
Symbol's NameSize is computed lazily. Currently, when we replace a symbol,
a cached length value can be discarded. This patch propagates that value.

Differential Revision: https://reviews.llvm.org/D62234

llvm-svn: 361364
2019-05-22 09:19:30 +00:00
Fangrui Song b72b091389 [ELF] Improve error message for relocations to symbols defined in discarded sections
Rather than report "undefined symbol: ", give more informative message
about the object file that defines the discarded section.

In particular, PR41133, if the section is a discarded COMDAT, print the
section group signature and the object file with the prevailing
definition. This is useful to track down some ODR issues.

We need to
* add `uint32_t DiscardedSecIdx` to Undefined for this feature.
* make ComdatGroups public and change its type to DenseMap<CachedHashStringRef, const InputFile *>

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D59649

llvm-svn: 361359
2019-05-22 09:06:42 +00:00
Rui Ueyama 33e74d9f62 Simplify the logic to instantiate Symbols. Should be NFC.
llvm-svn: 361350
2019-05-22 04:56:25 +00:00
Fangrui Song 5ea0d06e81 [ELF] Deleted unused ComdatGroups member variable left by D61854
llvm-svn: 361266
2019-05-21 14:40:38 +00:00
Fangrui Song ecf4c9e13c [ELF] Don't advance position in a memory region when assigning to the Dot
For memory5.test, ld.bfd appears to ignore `. += 0x2000;`, so the test was testing
a wrong behavior. After deleting the code added in rLLD336335, we match ld.bfd and thus fix PR41357.

PR37836 (memory4.test) seems to have been fixed by another change.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D62177

llvm-svn: 361228
2019-05-21 08:21:44 +00:00
Fangrui Song 547e3e930c [ELF] Error on relocations to local undefined symbols
For a reference to a local symbol, ld.bfd and gold error if the symbol
is defined in a discarded section but accept it if the symbol is
undefined. This inconsistent behavior seems unnecessary for us (it
probably makes sense for them as they differentiate local/global
symbols, the error would mean more code).

Catch such errors. Symbol index 0 may be used by marker relocations,
e.g. R_*_NONE R_ARM_V4BX. Don't error on them.

The difference from D61563 (which caused msan failure) is we don't call
Sym.computeBinding() on local symbols - VersionId is uninitialized.

llvm-svn: 361213
2019-05-21 02:38:11 +00:00
Tiancong Wang a5d8d01d6f [ELF][Driver] Fix precedence of symbol ordering file and CGProfile
This patch is a fix for https://bugs.llvm.org/show_bug.cgi?id=41804.
We try to solve the precedence of user-specified symbol ordering file and C3 ordering provided as call graph. It deals with two case:
(1) When both --symbol-ordering-file=<file> and --call-graph-order-file=<file> are present, whichever flag comes later will take precedence.
(2) When only --symbol-ordering-file=<file> is present, it takes precedence over implicit call graph (CGProfile) generated by CGProfilePass enabled in new pass manager.

llvm-svn: 361190
2019-05-20 19:13:34 +00:00
Tiancong Wang af4219adf5 Test commit, add an empty line.
llvm-svn: 361186
2019-05-20 18:46:25 +00:00
Fangrui Song 055906e1e5 [ELF] -z combreloc: sort dynamic relocations by (!is_relative,symbol_index,r_offset)
We currently sort dynamic relocations by (!is_relative,symbol_index).
Add r_offset as the third key. This makes `readelf -r` debugging easier
(relocations to the same symbol are ordered by r_offset).

Refactor the test combreloc.s (renamed from combrelocs.s) to check
R_X86_64_RELATIVE, and delete --expand-relocs.

The difference from the reverted D61477 is that we keep !is_relative as
the first key. In local dynamic TLS model, DTPMOD (e.g.
R_ARM_TLS_DTPMOD32 R_X86_64_DTPMOD and R_PPC{,64}_DTPMOD) may use 0 as
the symbol index.

Reviewed By: grimar

Differential Revision: https://reviews.llvm.org/D62141

llvm-svn: 361164
2019-05-20 15:25:01 +00:00
Dmitri Gribenko 0429fddc9d Revert "[ELF] Error on relocations to local undefined symbols"
This reverts commit r361144.  It causes a use-of-uninitialized-value in
maybeReportUndefined at llvm/tools/lld/ELF/Relocations.cpp:682, as
detected by MemorySanitizer when local-undefined-symbol.s test is run.

llvm-svn: 361162
2019-05-20 15:04:08 +00:00
Dmitri Gribenko a2fbe2bcda Revert "[ELF] -z combreloc: sort dynamic relocations by (symbol_index,r_offset)"
This reverts commit r361125.  This linker change breaks shared libraries
in some subtle way on x86_64.  (Specifically, gold segfaults when
loading the LLVMgold.so plugin linked with lldb with this patch.)

llvm-svn: 361150
2019-05-20 13:05:55 +00:00
Fangrui Song 2109572464 [ELF] Fix getRelocTargetVA formulae of R_TLS and R_NEG_TLS
For R_TLS:
1) Delete Sym.isTls() . The assembler ensures the symbol is STT_TLS.
   If not (the input is broken), we would crash (dereferencing null Out::TlsPhdr).
2) Change Sym.isUndefWeak() to Sym.isUndefined(), otherwise with --noinhibit-exec
   we would still evaluate the symbol and crash.
3) Return A if the symbol is undefined. This is PR40570.
   The case is probably unrealistic but returning A matches R_ABS and the
   behavior of several dynamic loaders.

R_NEG_TLS is obsoleted Sun TLS we don't fully support, but
R_RELAX_TLS_GD_TO_LE_NEG is still used by GD->LE relaxation (subl $var@tpoff,%eax).

They should add the addend. Unfortunately I can't test it as compilers don't seem to generate non-zero implicit addends.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D62098

llvm-svn: 361146
2019-05-20 11:47:31 +00:00
Fangrui Song 7c7425483a [ELF] Error on relocations to local undefined symbols
For a reference to a local symbol, ld.bfd and gold error if the symbol
is defined in a discarded section but accept it if the symbol is
undefined. This inconsistent behavior seems unnecessary for us (it
probably makes sense for them as they differentiate local/global
symbols, the error would mean more code).

Weaken the condition to getSymbol(Config->IsMips64EL) == 0 to catch such
errors. The symbol index can be 0 (e.g. R_*_NONE R_ARM_V4BX) and we shouldn't error on them.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D61563

llvm-svn: 361144
2019-05-20 11:25:55 +00:00
Fangrui Song 9f1a6de631 [ELF] -z combreloc: sort dynamic relocations by (symbol_index,r_offset)
Fixes PR41692.

We currently sort dynamic relocations by (!is_relative,symbol_index).
Change it to (symbol_index,r_offset). We still place relative
relocations first because R_*_RELATIVE are the only dynamic relocations
with 0 symbol index (except on MIPS, which doesn't use DT_REL[A]COUNT
anyway).

This makes `readelf -r` debugging easier (relocations to the same symbol
are ordered by r_offset).

Refactor the test combreloc.s (renamed from combrelocs.s) to check
R_X86_64_RELATIVE, and delete --expand-relocs.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D61477

llvm-svn: 361125
2019-05-20 07:22:55 +00:00
Rui Ueyama faf541e1e1 Make replaceSymbol a member function of Symbol.
This is a mechanical rewrite of replaceSymbol(A, B) to A->replace(B).
I also added a comment to Symbol::replace().

Technically this change is not necessary, but this change makes code a
bit more concise.

Differential Revision: https://reviews.llvm.org/D62117

llvm-svn: 361123
2019-05-20 03:36:33 +00:00
Fangrui Song a6720e7407 [ELF] Copy IsPreemptible in replaceSymbol()
Otherwise, we may set IsPreemptible (e.g. --dynamic-list) then clear it
(in replaceCommonSymbols()).

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D62107

llvm-svn: 361122
2019-05-20 02:07:03 +00:00
Michael Liao 63621832da Suppress false-positive GCC -Wreturn-type warning.
llvm-svn: 361094
2019-05-18 06:35:47 +00:00
Fangrui Song ed2ad77ccb [ARM][AArch64] Revert Android Bionic PT_TLS overaligning hack
This reverts D53906.

D53906 increased p_align of PT_TLS on ARM/AArch64 to 32/64 to make the
static TLS layout compatible with Android Bionic's ELF TLS. However,
this may cause glibc ARM/AArch64 programs to crash (see PR41527).

The faulty PT_TLS in the executable satisfies p_vaddr%p_align != 0. The
remainder is normally 0 but may be non-zero with the hack in place. The
problem is that we increase PT_TLS's p_align after OutputSections'
addresses are fixed (assignAddress()). It is possible that
p_vaddr%old_p_align = 0 while p_vaddr%new_p_align != 0.

For a thread local variable defined in the executable, lld computed TLS
offset (local exec) is different from glibc computed TLS offset from
another module (initial exec/generic dynamic). Note: PR41527 said the
bug affects initial exec but actually generic dynamic is affected as
well.

(glibc is correct in that it compute offsets that satisfy
`offset%p_align == p_vaddr%p_align`, which is a basic ELF requirement.
This hack appears to work on FreeBSD rtld, musl<=1.1.22, and Bionic, but
that is just because they (and lld) incorrectly compute offsets that
satisfy `offset%p_align = 0` instead.)

Android developers are fine to revert this patch, carry this patch in
their tree before figuring out a long-term solution (e.g. a dummy .tdata
with sh_addralign=64 sh_size={0,1} in crtbegin*.o files. The overhead is
now insignificant after D62059).

Reviewed By: rprichard, srhines

Differential Revision: https://reviews.llvm.org/D62055

llvm-svn: 361090
2019-05-18 03:16:00 +00:00
Fangrui Song 898896836d [ELF][X86] Fix R_RELAX_TLS_GD_TO_LE_NEG and R_NEG_TLS after D62059
After D62059, we don't align p_memsz of PT_TLS to p_align. The
getRelocTargetVA formula should align it instead.

It becomes clear that R_NEG_TLS and R_TLS are opposite from each other.

In i386-tls-le-align.s, I put ret after call ___tls_get_addr@plt as
otherwise ld.bfd would reject the relaxation:
TLS transition from R_386_TLS_GD to R_386_TLS_LE_32 against `a' at 0x3 in section `.text' failed

llvm-svn: 361088
2019-05-18 01:58:40 +00:00
Fangrui Song 348731aeed [ELF] Fix TP offset of TLS Variant I after D62059
As Ryan Prichard pointed out, after D62059, the TP offset is incorrect.

Add x86-64-tls-le-align.s to check this.  Better formulae for both
variants should take p_vaddr%p_align into account (offset%p_align =
p_vaddr%p_align is a basic ELF requirement), but I can't find a way to
test the behavior.

llvm-svn: 361084
2019-05-18 00:43:10 +00:00
Fangrui Song f3a3b93f54 [ELF] -r: fix R_*_NONE to section symbols on Elf*_Rel targets
On Elf*_Rel targets, for a relocation to a section symbol, an R_ABS is
added which will be used by relocateOne() to compute the implicit
addend.

Addends of R_*_NONE should be ignored, so don't emit an R_ABS.

This fixes crashes on X86 and ARM because their relocateOne() do not
handle R_*_NONE.

Reviewed By: peter.smith

Differential Revision: https://reviews.llvm.org/D62052

llvm-svn: 361036
2019-05-17 14:11:03 +00:00
Fangrui Song f3dccc64af [ELF] Don't align PT_TLS's p_memsz
The code was added in r252352, probably to address some layout issues.
Actually PT_TLS's p_memsz doesn't need to be aligned on either variant.
ld.bfd doesn't do that.

In case of larger alignment (e.g. 64 for Android Bionic on AArch64, see
D62055), this may make the overhead smaller.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D62059

llvm-svn: 361029
2019-05-17 12:48:53 +00:00
Ben Dunbobbin 1d16515fb4 [ELF] Implement Dependent Libraries Feature
This patch implements a limited form of autolinking primarily designed to allow
either the --dependent-library compiler option, or "comment lib" pragmas (
https://docs.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp?view=vs-2017) in
C/C++ e.g. #pragma comment(lib, "foo"), to cause an ELF linker to automatically
add the specified library to the link when processing the input file generated
by the compiler.

Currently this extension is unique to LLVM and LLD. However, care has been taken
to design this feature so that it could be supported by other ELF linkers.

The design goals were to provide:

- A simple linking model for developers to reason about.
- The ability to to override autolinking from the linker command line.
- Source code compatibility, where possible, with "comment lib" pragmas in other
  environments (MSVC in particular).

Dependent library support is implemented differently for ELF platforms than on
the other platforms. Primarily this difference is that on ELF we pass the
dependent library specifiers directly to the linker without manipulating them.
This is in contrast to other platforms where they are mapped to a specific
linker option by the compiler. This difference is a result of the greater
variety of ELF linkers and the fact that ELF linkers tend to handle libraries in
a more complicated fashion than on other platforms. This forces us to defer
handling the specifiers to the linker.

In order to achieve a level of source code compatibility with other platforms
we have restricted this feature to work with libraries that meet the following
"reasonable" requirements:

1. There are no competing defined symbols in a given set of libraries, or
   if they exist, the program owner doesn't care which is linked to their
   program.
2. There may be circular dependencies between libraries.

The binary representation is a mergeable string section (SHF_MERGE,
SHF_STRINGS), called .deplibs, with custom type SHT_LLVM_DEPENDENT_LIBRARIES
(0x6fff4c04). The compiler forms this section by concatenating the arguments of
the "comment lib" pragmas and --dependent-library options in the order they are
encountered. Partial (-r, -Ur) links are handled by concatenating .deplibs
sections with the normal mergeable string section rules. As an example, #pragma
comment(lib, "foo") would result in:

.section ".deplibs","MS",@llvm_dependent_libraries,1
         .asciz "foo"

For LTO, equivalent information to the contents of a the .deplibs section can be
retrieved by the LLD for bitcode input files.

LLD processes the dependent library specifiers in the following way:

1. Dependent libraries which are found from the specifiers in .deplibs sections
   of relocatable object files are added when the linker decides to include that
   file (which could itself be in a library) in the link. Dependent libraries
   behave as if they were appended to the command line after all other options. As
   a consequence the set of dependent libraries are searched last to resolve
   symbols.
2. It is an error if a file cannot be found for a given specifier.
3. Any command line options in effect at the end of the command line parsing apply
   to the dependent libraries, e.g. --whole-archive.
4. The linker tries to add a library or relocatable object file from each of the
   strings in a .deplibs section by; first, handling the string as if it was
   specified on the command line; second, by looking for the string in each of the
   library search paths in turn; third, by looking for a lib<string>.a or
   lib<string>.so (depending on the current mode of the linker) in each of the
   library search paths.
5. A new command line option --no-dependent-libraries tells LLD to ignore the
   dependent libraries.

Rationale for the above points:

1. Adding the dependent libraries last makes the process simple to understand
   from a developers perspective. All linkers are able to implement this scheme.
2. Error-ing for libraries that are not found seems like better behavior than
   failing the link during symbol resolution.
3. It seems useful for the user to be able to apply command line options which
   will affect all of the dependent libraries. There is a potential problem of
   surprise for developers, who might not realize that these options would apply
   to these "invisible" input files; however, despite the potential for surprise,
   this is easy for developers to reason about and gives developers the control
   that they may require.
4. This algorithm takes into account all of the different ways that ELF linkers
   find input files. The different search methods are tried by the linker in most
   obvious to least obvious order.
5. I considered adding finer grained control over which dependent libraries were
   ignored (e.g. MSVC has /nodefaultlib:<library>); however, I concluded that this
   is not necessary: if finer control is required developers can fall back to using
   the command line directly.

RFC thread: http://lists.llvm.org/pipermail/llvm-dev/2019-March/131004.html.

Differential Revision: https://reviews.llvm.org/D60274

llvm-svn: 360984
2019-05-17 03:44:15 +00:00
Rui Ueyama bbf154cf9c Move symbol resolution code out of SymbolTable class.
This is the last patch of the series of patches to make it possible to
resolve symbols without asking SymbolTable to do so.

The main point of this patch is the introduction of
`elf::resolveSymbol(Symbol *Old, Symbol *New)`. That function resolves
or merges given symbols by examining symbol types and call
replaceSymbol (which memcpy's New to Old) if necessary.

With the new function, we have now separated symbol resolution from
symbol lookup. If you already have a Symbol pointer, you can directly
resolve the symbol without asking SymbolTable to do that.

Now that the nice abstraction become available, I can start working on
performance improvement of the linker. As a starter, I'm thinking of
making --{start,end}-lib faster.

--{start,end}-lib is currently unnecessarily slow because it looks up
the symbol table twice for each symbol.

 - The first hash table lookup/insertion occurs when we instantiate a
   LazyObject file to insert LazyObject symbols.

 - The second hash table lookup/insertion occurs when we create an
   ObjFile from LazyObject file. That overwrites LazyObject symbols
   with Defined symbols.

I think it is not too hard to see how we can now eliminate the second
hash table lookup. We can keep LazyObject symbols in Step 1, and then
call elf::resolveSymbol() to do Step 2.

Differential Revision: https://reviews.llvm.org/D61898

llvm-svn: 360975
2019-05-17 01:55:20 +00:00
Bob Haarman 5ff1eb6418 Revert r358069 "Discard debuginfo for object files empty after GC"
The change broke some scenarios where debug information is still
needed, although MarkLive cannot see it, including the
Chromium/Android build. Reverting to unbreak that build.

llvm-svn: 360955
2019-05-16 23:33:06 +00:00
Igor Kudrin 4669cf2750 [LTO] Improve readability of module IDs
Module IDs can appear in diagnostic messages.
This patch adds some auxiliary symbols to improve their readability.

Differential Revision: https://reviews.llvm.org/D61857

llvm-svn: 360858
2019-05-16 05:23:25 +00:00
Rui Ueyama 54ee6df247 Pemove SymbolTable::addBitcode as it is redundant.
Differential Revision: https://reviews.llvm.org/D61897

llvm-svn: 360846
2019-05-16 03:54:50 +00:00
Rui Ueyama d668873bfe Consistently return `Symbol *` from SymbolTable's add-family functions.
llvm-svn: 360845
2019-05-16 03:54:41 +00:00
Rui Ueyama 943cd00580 De-template parseFile() and SymbolTable's add-family functions.
Differential Revision: https://reviews.llvm.org/D61896

llvm-svn: 360844
2019-05-16 03:45:13 +00:00
Rui Ueyama 5c073a94f9 Introduce CommonSymbol.
Previously, we handled common symbols as a kind of Defined symbol,
but what we were doing for common symbols is pretty different from
regular defined symbols.

Common symbol and defined symbol are probably as different as shared
symbol and defined symbols are different.

This patch introduces CommonSymbol to represent common symbols.
After symbols are resolved, they are converted to Defined symbols
residing in a .bss section.

Differential Revision: https://reviews.llvm.org/D61895

llvm-svn: 360841
2019-05-16 03:29:03 +00:00
Rui Ueyama 7d4761928e Simplify SymbolTable::add{Defined,Undefined,...} functions.
SymbolTable's add-family functions have lots of parameters because
when they have to create a new symbol, they forward given arguments
to Symbol's constructors. Therefore, the functions take at least as
many arguments as their corresponding constructors.

This patch simplifies the add-family functions. Now, the functions
take a symbol instead of arguments to construct a symbol. If there's
no existing symbol, a given symbol is memcpy'ed to the symbol table.
Otherwise, the functions attempt to merge the existing and a given
new symbol.

I also eliminated `CanOmitFromDynSym` parameter, so that the functions
take really one argument.

Symbol classes are trivially constructible, so looks like constructing
them to pass to add-family functions is as cheap as passing a lot of
arguments to the functions. A quick benchmark showed that this patch
seems performance-neutral.

This is a preparation for
http://lists.llvm.org/pipermail/llvm-dev/2019-April/131902.html

Differential Revision: https://reviews.llvm.org/D61855

llvm-svn: 360838
2019-05-16 02:14:00 +00:00
Sam Clegg e7ab59eda9 [ELF] Fix typo in header guard. NFC.
llvm-svn: 360832
2019-05-16 00:45:50 +00:00
Fangrui Song e041d15f5e [LLD][ELF] Add the -z ifunc-noplt option
Patch by Mark Johnston!

Summary:
When the option is configured, ifunc calls do not go through the PLT;
rather, they appear as regular function calls with relocations
referencing the ifunc symbol, and the resolver is invoked when
applying the relocation.  This is intended for use in freestanding
environments where text relocations are permissible and is incompatible
with the -z text option.  The option is motivated by ifunc usage in the
FreeBSD kernel, where ifuncs are used to elide CPU feature flag bit
checks in hot paths.  Instead of replacing the cost of a branch with that
of an indirect function call, the -z ifunc-noplt option is used to ensure
that ifunc calls carry no hidden overhead relative to normal function
calls.

Test Plan:
I added a couple of regression tests and tested the FreeBSD kernel
build using the latest lld sources.

To demonstrate the effects of the change, I used a micro-benchmark
which results in frequent invocations of a FreeBSD kernel ifunc.  The
benchmark was run with and without IBRS enabled, and with and without
-zifunc-noplt configured.  The observed speedup is small and consistent,
and is significantly larger with IBRS enabled:

https://people.freebsd.org/~markj/ifunc-noplt/noibrs.txt
https://people.freebsd.org/~markj/ifunc-noplt/ibrs.txt

Reviewed By: ruiu, MaskRay

Differential Revision: https://reviews.llvm.org/D61613

llvm-svn: 360685
2019-05-14 15:25:21 +00:00
Fangrui Song ed4dbe6326 [ELF] --gdb-index: fix SIGSEGV when a DWARFAddressRange has invalid SectionIndex
See D61891: llvm had a bug that might create invalid (DW_AT_low_pc,DW_AT_high_pc) pairs or range list entries due to missing DW_AT_addr_base.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D61889

llvm-svn: 360679
2019-05-14 14:41:20 +00:00
Rui Ueyama 2dd5283d2a Move SymbolTable::addFile to InputFiles.cpp.
The symbol table used to be a container of vectors of input files,
but that's no longer the case because the vectors are moved out of
SymbolTable and are now global variables.

Therefore, addFile doesn't have to belong to any class. This patch
moves the function out of the class.

This patch is a preparation for my RFC [1].

[1] http://lists.llvm.org/pipermail/llvm-dev/2019-April/131902.html

Differential Revision: https://reviews.llvm.org/D61854

llvm-svn: 360666
2019-05-14 12:03:13 +00:00
Peter Smith 4e21c770ec [ELF] Full support for -n (--nmagic) and -N (--omagic) via common page
The -n (--nmagic) disables page alignment, and acts as a -Bstatic
The -N (--omagic) does what -n does but also marks the executable segment as
writeable. As page alignment is disabled headers are not allocated unless
explicit in the linker script.

To disable page alignment in LLD we choose to set the page sizes to 1 so
that any alignment based on the page size does nothing. To set the
Target->PageSize to 1 we implement -z common-page-size, which has the side
effect of allowing the user to set the value as well.

Setting the page alignments to 1 does mean that any use of
CONSTANT(MAXPAGESIZE) or CONSTANT(COMMONPAGESIZE) in a linker script will
return 1, unlike in ld.bfd. However given that -n and -N disable paging
these probably shouldn't be used in a linker script where -n or -N is in
use.

Differential Revision: https://reviews.llvm.org/D61688

llvm-svn: 360593
2019-05-13 16:01:26 +00:00
Fangrui Song 6cdd68e386 [PPC64] Define getThunkSectionSpacing() based on the range of R_PPC64_REL24
Suggested by Sean Fertile and Peter Smith.

Thunk section spacing decrease the total number of thunks. I measured a
decrease of 1% or less in some large programs, with no perceivable
slowdown in link time. Override getThunkSectionSpacing() to enable it.
0x2000000 is the farthest point R_PPC64_REL24 can reach. I tried several
numbers and found 0x2000000 works the best. Numbers near 0x2000000 work
as well but let's just use the simpler number.

As demonstrated by the updated tests, this essentially changes placement
of most thunks to the end of the output section. We leverage this
property to fix PR40740 reported by Alfredo Dal'Ava Júnior:

The output section .init consists of input sections from several object
files (crti.o crtbegin.o crtend.o crtn.o). Sections other than the last
one do not have a terminator. With this patch, we create the thunk after
the last .init input section and thus fix the issue. This is not
foolproof but works quite well for such sections (with no terminator) in
practice.

Reviewed By: ruiu, sfertile

Differential Revision: https://reviews.llvm.org/D61720

llvm-svn: 360405
2019-05-10 05:51:00 +00:00
Ben Dunbobbin 3edca1ac1a [LLD][NFC] Refactor: BuildID hash size now computed in one place.
Differential Revision: https://reviews.llvm.org/D61078

llvm-svn: 360316
2019-05-09 08:08:09 +00:00
Fangrui Song bd086817f6 [ELF] Initialize Target before it may be dereferenced by findAux when reporting "duplicate symbol" error
for (InputFile *F : Files)
      Symtab->addFile<ELFT>(F); // if there is a duplicate symbol error

    ...

    Target = getTarget();

When parsing .debug_info in the object file (for better diagnostics),
DWARF.cpp findAux may dereference the null pointer Target

    auto *DR = dyn_cast<Defined>(&File->getRelocTargetSym(Rel));
    if (!DR) {
      // Broken debug info may point to a non-defined symbol,
      // some asan object files may also contain R_X86_64_NONE
      RelType Type = Rel.getType(Config->IsMips64EL);
      if (Type != Target->NoneRel) /// Target is null

Move the assignment of Target to an earlier place to fix this.

Reviewed By: ruiu

Differential Revision: https://reviews.llvm.org/D61712

llvm-svn: 360305
2019-05-09 01:45:53 +00:00
Sam Clegg a1282a39ba [WebAssembly] Handle command line options consistently with the ELF backend.
Differential Revision: https://reviews.llvm.org/D61645

llvm-svn: 360266
2019-05-08 16:20:05 +00:00
Simon Atanasyan 3bdb81c26d [mips] Fix ld instruction in PLT entries on MIPS64
Use `ld` and `daddiu` instructions in MIPS64 PLT records. That fixes a
segmentation fault.

Patch by Qiao Pengcheng.

Differential Revision: https://reviews.llvm.org/D61586

llvm-svn: 360187
2019-05-07 20:26:23 +00:00
Nico Weber 54743d5767 Add typo correction for command-line flags to ELF and COFF lld drivers
For lld-link, unknown '/'-style flags are treated as filenames on POSIX
systems, so only '-'-style flags get typo correction for now. This
matches clang-cl.

PR37006.

Differential Revision: https://reviews.llvm.org/D61443

llvm-svn: 360145
2019-05-07 13:48:30 +00:00
Fangrui Song f3994e4dfa [ELF] Reorder BitcodeFiles.empty() to call thinLTOCreateEmptyIndexFiles() in only one place
It makes the --plugin-opt=obj-path= and --plugin-opt=thinlto-index-only=
behavior more consistent - the files will be created in the
BitcodeFiles.empty() case, but I assume whether it behaves this way is
not required by anyone.

LTOObj->run() cannot run with empty BitcodeFiles. There would be an error:

    ld.lld: error: No available targets are compatible with triple ""

Differential Revision: https://reviews.llvm.org/D61635

llvm-svn: 360129
2019-05-07 10:40:26 +00:00
Fangrui Song 912251e82f [PPC64] toc-indirect to toc-relative relaxation
This is based on D54720 by Sean Fertile.

When accessing a global symbol which is not defined in the translation unit,
compilers will generate instructions that load the address from the toc entry.

If the symbol is defined, non-preemptable, and addressable with a 32-bit
signed offset from the toc pointer, the address can be computed
directly. e.g.

    addis 3, 2, .LC0@toc@ha  # R_PPC64_TOC16_HA
    ld    3, .LC0@toc@l(3)   # R_PPC64_TOC16_LO_DS, load the address from a .toc entry
    ld/lwa 3, 0(3)           # load the value from the address

    .section .toc,"aw",@progbits
    .LC0: .tc var[TC],var

can be relaxed to

    addis 3,2,var@toc@ha     # this may be relaxed to a nop,
    addi  3,3,var@toc@l      # then this becomes addi 3,2,var@toc
    ld/lwa 3, 0(3)           # load the value from the address

We can delete the test ppc64-got-indirect.s as its purpose is covered by
newly added ppc64-toc-relax.s and ppc64-toc-relax-constants.s

Reviewed By: ruiu, sfertile

Differential Revision: https://reviews.llvm.org/D60958

llvm-svn: 360112
2019-05-07 04:26:05 +00:00
Fangrui Song d45df09435 [ELF] Place SHT_NOTE sections with the same alignment into one PT_NOTE
Summary:
While the generic ABI requires notes to be 8-byte aligned in ELF64, many
vendor-specific notes (from Linux, NetBSD, Solaris, etc) use 4-byte
alignment.

In a PT_NOTE segment, if 4-byte aligned notes are followed by an 8-byte
aligned note, the possible 4-byte padding may make consumers fail to
parse the 8-byte aligned note. See PR41000 for a recent report about
.note.gnu.property (NT_GNU_PROPERTY_TYPE_0).
(Note, for NT_GNU_PROPERTY_TYPE_0, the consumers should probably migrate
to PT_GNU_PROPERTY, but the alignment issue affects other notes as well.)

To fix the issue, don't mix notes with different alignments in one
PT_NOTE. If compilers emit 4-byte aligned notes before 8-byte aligned
notes, we'll create at most 2 segments.

sh_size%sh_addralign=0 is actually implied by the rule for linking
unrecognized sections (in generic ABI), so we don't have to check that.
Notes that match in name, type and attribute flags are concatenated into
a single output section. The compilers have to ensure
sh_size%sh_addralign=0 to make concatenated notes parsable.

An alternative approach is to create a PT_NOTE for each SHT_NOTE, but
we'll have to incur the sizeof(Elf64_Phdr)=56 overhead every time a new
note section is introduced.

Reviewers: ruiu, jakehehrlich, phosek, jhenderson, pcc, espindola

Subscribers: emaste, arichardson, krytarowski, fedor.sergeev, llvm-commits

Tags: #llvm

Differential Revision: https://reviews.llvm.org/D61296

llvm-svn: 359853
2019-05-03 00:35:49 +00:00
Fangrui Song 0178cff279 [ELF] --plugin-opt=thinlto-index-only: create empty index files even if all bitcode files are lazy
Summary:
The gold plugin behavior (creating empty index files for lazy bitcode
files) was added in D46034, but it missed the case when there is no
non-lazy bitcode files, e.g.

    ld.lld -shared crti.o crtbeginS.o --start-lib bitcode.o --end-lib ...

crti.o crtbeginS.o are not bitcode, but our distributed build system
wants bitcode.o.thinlto.bc to confirm all expected outputs are created
based on all of the modules provided to the linker.

Differential Revision: https://reviews.llvm.org/D61420

llvm-svn: 359788
2019-05-02 14:05:20 +00:00
Ben Dunbobbin 6e32dd6cfd [LLD] Emit dynamic relocations for references to script symbols in -pie links
https://reviews.llvm.org/D55423 caused LLD to stop emitting dynamic relocations for references to script symbols in -pie links.

This patch fixes that regression.

https://reviews.llvm.org/D61298

llvm-svn: 359683
2019-05-01 14:07:31 +00:00
Andrew Ng 24896d304d [LLD][ELF] /DISCARD/ output sections should not be orphans
/DISCARD/ output sections were being treated as orphans. As a result, if
a /DISCARD/ output section has been assigned a PHDR, it could cause
incorrect assignment of sections to segments.

Differential Revision: https://reviews.llvm.org/D61186

llvm-svn: 359565
2019-04-30 14:31:22 +00:00
Andrew Ng 0f4c58f6f4 [LLD][ELF] Fix getRankProximity to "ignore" not live sections
This is a follow up to r358979 which made findOrphanPos only consider
live sections. Unfortunately, this required change to getRankProximity,
used by findOrphanPos, was missed.

Differential Revision: https://reviews.llvm.org/D61197

llvm-svn: 359554
2019-04-30 12:27:06 +00:00
George Rimar dee900ae59 [LLD][ELF] - Do not remove empty sections referenced in LOADADDR/ADDR commands.
This is https://bugs.llvm.org//show_bug.cgi?id=38750.

If script references empty sections in LOADADDR/ADDR commands

.empty  : { *(.empty ) }
.text   : AT(LOADADDR (.empty) + SIZEOF (.empty)) { *(.text) }
then an empty section will be removed and LOADADDR/ADDR will evaluate to null.
It is not that user may expect from using of the generic script, what is a common case.

Differential revision: https://reviews.llvm.org/D54621

llvm-svn: 359279
2019-04-26 06:59:30 +00:00
Fangrui Song 98b70f6705 [ELF] Change std::max<uint64_t> to uint32_t for section alignment
Summary:
We use `uint32_t SectionBase::Alignment` and `uint32_t
PhdrEntry::p_align` despite alignments being 64 bits in ELF64.
Fix the std::max template arguments accordingly.

The currently 160-byte InputSection will become 168 bytes if we make SectionBase::Alignment uint64_t.

Differential Revision: https://reviews.llvm.org/D61171

llvm-svn: 359268
2019-04-26 04:07:58 +00:00