After D66007/r369262, if the control flow reaches `if (sym.isUndefined())`, we know:
* The relocation is not a link-time constant => symbol is preemptable => Undefined or SharedSymbol
* Not an undef weak.
* -no-pie.
* The symbol type is neither STT_OBJECT nor STT_FUNC.
ld.lld --export-dynamic --unresolved-symbols=ignore-all %t.o can satisfy
these conditions. Delete the isUndefined() test so that we error
`symbol '...' has no type`, because we don't know the type to make the
decision to create copy relocation/canonical PLT.
llvm-svn: 369271
In processRelocAux(), we handle errors before copy relocation/canonical PLT.
This makes error checking a bit complex because we have to check for
conditions that will be allowed by copy relocation/canonical PLT.
Instead, move copy relocation/canonical PLT before error checking. This
simplifies the previous clumsy error checking code
`config->shared || (config->pie && expr == R_ABS && type != target->symbolicRel)`
to the simple `config->isPic`. Some diagnostics can be reported in
different ways. The code motion changes diagnostics for some contrived
test cases:
* copy-rel-pie-error.s -> copy-rel-pie2.s:
It was rejected before but accepted now. ld.bfd also accepts the case.
* copy-errors.s: "cannot preempt symbol" changes to "symbol 'bar' has no type"
* got32{,x}-i386.s: the suggestion changes from "-fPIC or -Wl,-z,notext" to "-fPIE"
* x86-64-dyn-rel-error5.s: one diagnostic changes for -pie case
Reviewed By: peter.smith
Differential Revision: https://reviews.llvm.org/D66007
llvm-svn: 369262
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
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
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
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
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
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
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
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
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
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
!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
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
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
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
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
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
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
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
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
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
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 ℜ }
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
GCC emits warning on this line:
error: enumeral and non-enumeral type in conditional
expression [-Werror=extra]
Change-Id: I04969cc32e27e310968b88ebaa4e1c4894528d74
llvm-svn: 365434
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
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
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
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
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
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
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
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
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
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
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
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
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
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
* 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/98https://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
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
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
(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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
(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
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
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
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
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
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
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
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
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
This patch simplifies ELFFile instance initialization by merging
two similar functions into a single function and call it from the
ctor.
llvm-svn: 361789
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
--{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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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.txthttps://people.freebsd.org/~markj/ifunc-noplt/ibrs.txt
Reviewed By: ruiu, MaskRay
Differential Revision: https://reviews.llvm.org/D61613
llvm-svn: 360685
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
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
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
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
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
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
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
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
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
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
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
/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
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
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
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
Summary:
We don't take localentry offset into account, and thus may fail to
create a long branch when the gap is just a few bytes smaller than 2^25.
relocation R_PPC64_REL24 out of range: 33554432 is not in [-33554432, 33554431]
relocation R_PPC64_REL24 out of range: 33554436 is not in [-33554432, 33554431]
Fix that by adding the offset to the symbol VA.
Differential Revision: https://reviews.llvm.org/D61058
llvm-svn: 359094
This fixes an issue where a symbol only section at the start of a
PT_LOAD segment, causes incorrect alignment of the file offset for the
start of the segment which results in the output of an invalid ELF.
SHT_PROGBITS was the default output section type in the past.
Differential Revision: https://reviews.llvm.org/D60131
llvm-svn: 358981
This patch changes the behaviour of findOrphanPos to only consider live
sections when placing orphan sections. This used to be how it behaved in
the past.
Differential Revision: https://reviews.llvm.org/D60273
llvm-svn: 358979
Make some small adjustment while touching the code: make parameters
const, use less_first(), etc.
Differential Revision: https://reviews.llvm.org/D60989
llvm-svn: 358943
Summary:
Fixes PR35242. A simplified reproduce:
thread_local int i; int f() { return i; }
% {g++,clang++} -fPIC -shared -ftls-model=local-dynamic -fuse-ld=lld a.cc
ld.lld: error: can't create dynamic relocation R_X86_64_DTPOFF32 against symbol: i in readonly segment; recompile object files with -fPIC or pass '-Wl,-z,notext' to allow text relocations in the output
In isStaticLinkTimeConstant(), Syn.IsPreemptible is true, so it is not
seen as a constant. The error is then issued in processRelocAux().
A symbol of the local-dynamic TLS model cannot be preempted but it can
preempt symbols of the global-dynamic TLS model in other DSOs.
So it makes some sense that the variable is not static.
This patch fixes the linking error by changing getRelExpr() on
R_386_TLS_LDO_32 and R_X86_64_DTPOFF{32,64} from R_ABS to R_DTPREL.
R_PPC64_DTPREL_* and R_MIPS_TLS_DTPREL_* need similar fixes, but they are not handled in this patch.
As a bonus, we use `if (Expr == R_ABS && !Config->Shared)` to find
ld-to-le opportunities. R_ABS is overloaded here for such STT_TLS symbols.
A dedicated R_DTPREL is clearer.
Differential Revision: https://reviews.llvm.org/D60945
llvm-svn: 358870
Summary:
This relocation type is used by R_386_TLS_GD. Its formula is the same as
R_GOTPLT (e.g R_X86_64_GOT{32,64} R_386_TLS_GOTIE). Rename it to be clearer.
Differential Revision: https://reviews.llvm.org/D60941
llvm-svn: 358868
This is https://bugs.llvm.org//show_bug.cgi?id=39857.
I added the comment with much more details to the bug page,
the short version is below.
The following script and code demonstrates the issue:
aliasto__text = __text;
SECTIONS {
.text 0x1000 : { __text = . ; *(.text) }
}
...
call aliasto__text
LLD fails with "cannot refer to absolute symbol: aliasto__text" error.
It happens because at the moment of scanning the relocations
we do not yet assign the correct/final/any section value for the symbol aliasto__text.
I made a change to Relocations.cpp to fix that.
Also, I had to remove the symbol-location.s test case completely, because now it does not
trigger any error. Since now all linker scripts symbols are resolved to constants, no
errors can be triggered at all it seems. I checked that it is consistent with the behavior
of bfd and gold (they do not trigger errors for the case from symbol-location.s), so it should
be OK. I.e. at least it is probably not the best possible, but natural behavior we obtained.
Differential revision: https://reviews.llvm.org/D55423
llvm-svn: 358652
Summary:
If the output section contains only symbol assignments, we copy flags
from the previous sections. Don't set SHF_ALLOC if NonAlloc is true.
We also have to change the type from SHT_NOBITS to SHT_PROGBITS.
In ld.bfd, bfd_elf_get_default_section_type maps non-alloctable sections to SHT_PROGBITS.
Non-alloctable SHT_NOBITS sections do not make sense.
Fixes PR38626
Differential Revision: https://reviews.llvm.org/D59986
llvm-svn: 358650
This generalizes code and also fixes the broken behavior shown in
one of our test cases for some targets, like x86-64.
The issue occurs when the forward declarations are used in the script.
One of the samples is:
SECTIONS {
foo = ADDR(.text) - ABSOLUTE(ADDR(.text));
};
In that case, we have a broken output when output target does
not use thunks. That happens because thunks creating code
(called from maybeAddThunks)
calls Script->assignAddresses() at least one more time,
what fixups the values. As a result final symbols values can
be different on AArch64 and x86, for example.
In this patch, I generalize and rename maybeAddThunks to
finalizeAddressDependentContent and now it is used and called
by all targets.
Differential revision: https://reviews.llvm.org/D55550
llvm-svn: 358646
Summary:
We access Live and OutputOff (which may share the same memory location)
concurrently in 2 parallelForEachN loops. Separating them avoids subtle
data races like D41884/PR35788. This patch places Live and Hash
together.
2 reasons this is appealing:
1) Hash is immutable. Live is almost read-only - only written once in MarkLive.cpp where
Hash is not accessed
2) we already discard low bits of Hash to decide ShardID. It doesn't
matter much if we make 32-bit Hash to 31-bit.
For a huge internal clang -O3 executable (1.6GiB),
`Strings` in StringTableBuilder::finalizeStringTable contains at most 310253 elements.
The expected number of pair-wise collisions 2^(-31) * C(310253,2) ~= 22.41 is too small to have a negative impact on performance.
Actually, my benchmark shows there is actually a minor performance improvement.
Differential Revision: https://reviews.llvm.org/D60765
llvm-svn: 358645
Patch by Gabriel Smith.
The address for a section would be evaluated before the region was
switched to. Because of this, the position within the region would not
be updated. After the region is swapped to the dot would be set to the
out of date position within the region, undoing the section address
evaluation.
To fix this, the region is swapped to before the section's address is
evaluated. As part of the fallout of this, expandMemoryRegions needed
to be gated in setDot on the condition that the evaluated address is
less than the dot. This is for the case where sections are not listed
from lowest address to highest address.
Finally, a test for the case where sections are listed "out of order"
was added.
Differential Revision: https://reviews.llvm.org/D60744
llvm-svn: 358638
With partitions, each partition should have the same build id. This means
that the build id needs to be only computed once, otherwise we will end up
with different build ids in each partition as a result of the file contents
changing. This change moves the computation of the build id into Writer so
that it only happens once.
Differential Revision: https://reviews.llvm.org/D60342
llvm-svn: 358536
The typo was introduced to llvm MC in rL204769 (fixed in rL358247) and then to lld.
Also, for relocatable-many-sections.s, the size of .symtab changed at some point and the formula needs update.
llvm-svn: 358248
Patch by Robert O'Callahan.
Rust projects tend to link in all object files from all dependent
libraries and rely on --gc-sections to strip unused code and data.
Unfortunately --gc-sections doesn't currently strip any debuginfo
associated with GC'ed sections, so lld links in the full debuginfo from
all dependencies even if almost all that code has been discarded. See
https://github.com/rust-lang/rust/issues/56068 for some details.
Properly stripping debuginfo for discarded sections would be difficult,
but a simple approach that helps significantly is to mark debuginfo
sections as live only if their associated object file has at least one
live code/data section. This patch does that. In a (contrived but not
totally artificial) Rust testcase linked above, it reduces the final
binary size from 46MB to 5.1MB.
Differential Revision: https://reviews.llvm.org/D54747
llvm-svn: 358069
The code previously specified a 32-bit range for R_RISCV_HI20 and
R_RISCV_LO12_[IS], however this is incorrect as the maximum offset on
RV64 that can be formed from the immediate of lui and the displacement
of an I-type or S-type instruction is -0x80000800 to 0x7ffff7ff. There
is also the same issue with a c.lui and LO12 pair, whose actual
addressable range should be -0x20800 to 0x1f7ff.
The tests will be included in the next patch that converts all RISC-V
tests to use llvm-mc instead of yaml2obj, as assembler support has
matured enough to write tests in them.
Differential Revision: https://reviews.llvm.org/D60414
llvm-svn: 357995
For partitions I intend to use the same set of version indexes in
each partition for simplicity. Since each partition will need its own
VersionNeedSection this will require moving the verneed tracking out of
VersionNeedSection. The way I've done this is to move most of the tracking
into SharedFile. What will eventually become the per-partition tracking
still lives in VersionNeedSection.
As a bonus the code gets a little simpler and more consistent with how we
handle verdef.
Differential Revision: https://reviews.llvm.org/D60307
llvm-svn: 357926
Previously, we drop symbols starting with .L from the symbol table, so
if there is a relocation that refers a .L symbol, it ended up
referencing a null -- which happened to be interpreted as an absolute
symbol.
This patch copies all symbols including local ones if -emit-reloc is
given.
Fixes https://bugs.llvm.org/show_bug.cgi?id=41385
Differential Revision: https://reviews.llvm.org/D60306
llvm-svn: 357885
And rename the function to combineEhSections(). This makes the processing
of .ARM.exidx even more similar to .eh_frame and means that we can avoid an
additional loop over InputSections.
Differential Revision: https://reviews.llvm.org/D60026
llvm-svn: 357417
Summary:
Some synthetic sections can be empty while still being needed, thus they
can't be removed by removeUnusedSyntheticSections(). Rename this member
function to more appropriate isNeeded() with the opposite meaning.
No functional change intended.
Reviewers: ruiu, espindola
Reviewed By: ruiu
Subscribers: jhenderson, grimar, emaste, arichardson, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D59982
llvm-svn: 357377
This change itself doesn't mean anything, but it helps D59780 because
in patch, we don't know whether we need to create a CET-aware PLT or
not until we read all input files.
llvm-svn: 357194
Recommit r356666 with fixes for buildbot failure, as well as handling for
--emit-relocs, which we decide not to emit any relocation sections as the
table is already position independent and an offline tool can deduce the
relocations.
Instead of creating extra Synthetic .ARM.exidx sections to account for
gaps in the table, create a single .ARM.exidx SyntheticSection that can
derive the contents of the gaps from a sorted list of the executable
InputSections. This has the benefit of moving the ARM specific code for
SyntheticSections in SHF_LINK_ORDER processing and the table merging code
into the ARM specific SyntheticSection. This also makes it easier to create
EXIDX_CANTUNWIND table entries for executable InputSections that don't
have an associated .ARM.exidx section.
Fixes pr40277
Differential Revision: https://reviews.llvm.org/D59216
llvm-svn: 357160
Patch by Tiancong Wang.
In D36351, Call-Chain Clustering (C3) heuristic is implemented with
option --call-graph-ordering-file <file>.
This patch adds a flag --print-symbol-order=<file> to LLD, and when
specified, it prints out the symbols ordered by the heuristics to the
file. The symbols printout is helpful to those who want to understand
the heuristics and want to reproduce the ordering with
--symbol-ordering-file in later pass.
Differential Revision: https://reviews.llvm.org/D59311
llvm-svn: 357133
Summary:
This should address remaining issues discussed in PR36555.
Currently R_GOT*_FROM_END are exclusively used by x86 and x86_64 to
express relocations types relative to the GOT base. We have
_GLOBAL_OFFSET_TABLE_ (GOT base) = start(.got.plt) but end(.got) !=
start(.got.plt)
This can have problems when _GLOBAL_OFFSET_TABLE_ is used as a symbol, e.g.
glibc dl_machine_dynamic assumes _GLOBAL_OFFSET_TABLE_ is start(.got.plt),
which is not true.
extern const ElfW(Addr) _GLOBAL_OFFSET_TABLE_[] attribute_hidden;
return _GLOBAL_OFFSET_TABLE_[0]; // R_X86_64_GOTPC32
In this patch, we
* Change all GOT*_FROM_END to GOTPLT* to fix the problem.
* Add HasGotPltOffRel to denote whether .got.plt should be kept even if
the section is empty.
* Simplify GotSection::empty and GotPltSection::empty by setting
HasGotOffRel and HasGotPltOffRel according to GlobalOffsetTable early.
The change of R_386_GOTPC makes X86::writePltHeader simpler as we don't
have to compute the offset start(.got.plt) - Ebx (it is constant 0).
We still diverge from ld.bfd (at least in most cases) and gold in that
.got.plt and .got are not adjacent, but the advantage doing that is
unclear.
Reviewers: ruiu, sivachandra, espindola
Subscribers: emaste, mehdi_amini, arichardson, dexonsmith, jdoerfert, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D59594
llvm-svn: 356968
lld's mark-sweep garbage collector was written in the visitor pattern.
There are functions that traverses a given graph, and the functions calls
callback functions to dispatch according to node type.
The code was originaly pretty simple, and lambdas worked pretty
well. However, as we add more features to the garbage collector, that became
more like a callback hell. We now have a callback function that wraps
another callback function, for example. It is not easy to follow the flow of
the control.
This patch rewrites it as a regular class. What was once a lambda is now a
regular class member function. I think this change fixes the readability
issue.
No functionality change intended.
Differential Revision: https://reviews.llvm.org/D59800
llvm-svn: 356966
Previously, `Entries` contains pairs of symbols and their indices.
The indices are always 0, x, 2x, 3x, ..., where x is the size of
relocation entry. We didn't have to store that values because we can
compute them when we consume them.
llvm-svn: 356812
There is a reproducible buildbot failure (segfault) on the 2 stage
clang-cmake-armv8-lld bot. Reverting while I investigate.
Differential Revision: https://reviews.llvm.org/D59216
llvm-svn: 356684
Instead of creating extra Synthetic .ARM.exidx sections to account for
gaps in the table, create a single .ARM.exidx SyntheticSection that can
derive the contents of the gaps from a sorted list of the executable
InputSections. This has the benefit of moving the ARM specific code for
SyntheticSections in SHF_LINK_ORDER processing and the table merging code
into the ARM specific SyntheticSection. This also makes it easier to create
EXIDX_CANTUNWIND table entries for executable InputSections that don't
have an associated .ARM.exidx section.
Fixes pr40277
Differential Revision: https://reviews.llvm.org/D59216
llvm-svn: 356666
Summary:
This implements Rui Ueyama's idea in PR39044.
I've checked that ld.bfd and gold do not have the power-of-2 requirement
and do not require sh_entsize to be a multiple of sh_align.
Now on the updated test merge-entsize.s, all the 3 linkers happily
create .rodata that is not 3-byte aligned.
This has a use case in Linux arch/x86/crypto/sha512-avx2-asm.S
It uses sh_entsize of 640, which is not a power of 2.
See https://github.com/ClangBuiltLinux/linux/issues/417
Reviewers: ruiu, espindola
Reviewed By: ruiu
Subscribers: nickdesaulniers, E5ten, emaste, arichardson, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D59478
llvm-svn: 356428
Summary:
Based on Peter Collingbourne's suggestion in D56828.
Before D56828: PT_LOAD(.data PT_GNU_RELRO(.data.rel.ro .bss.rel.ro) .bss)
Old: PT_LOAD(PT_GNU_RELRO(.data.rel.ro .bss.rel.ro) .data .bss)
New: PT_LOAD(PT_GNU_RELRO(.data.rel.ro .bss.rel.ro)) PT_LOAD(.data. .bss)
The new layout reflects the runtime memory mappings.
By having two PT_LOAD segments, we can utilize the NOBITS part of the
first PT_LOAD and save bytes for .bss.rel.ro.
.bss.rel.ro is currently small and only used by copy relocations of
symbols in read-only segments, but it can be used for other purposes in
the future, e.g. if a relro section's statically relocated data is all
zeros, we can move it to .bss.rel.ro.
Reviewers: espindola, ruiu, pcc
Reviewed By: ruiu
Subscribers: nemanjai, jvesely, nhaehnle, javed.absar, kbarton, emaste, arichardson, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D58892
llvm-svn: 356226
We allow an archive file without symbol table as a linker input as a
workaround for a very common error in LTO build. But that logic worked
even for an archive file containing non-bitcode files, which is not
expected. This patch limits that workaround to one that contains only
bitcode files.
Differential Revision: https://reviews.llvm.org/D59373
llvm-svn: 356186
Old: PT_LOAD(.data | PT_GNU_RELRO(.data.rel.ro .bss.rel.ro) | .bss)
New: PT_LOAD(PT_GNU_RELRO(.data.rel.ro .bss.rel.ro) | .data .bss)
The placement of | indicates page alignment caused by PT_GNU_RELRO. The
new layout has simpler rules and saves space for many cases.
Old size: roundup(.data) + roundup(.data.rel.ro)
New size: roundup(.data.rel.ro + .bss.rel.ro) + .data
Other advantages:
* At runtime the 3 memory mappings decrease to 2.
* start(PT_TLS) = start(PT_GNU_RELRO) = start(RW PT_LOAD). This
simplifies binary manipulation tools.
GNU strip before 2.31 discards PT_GNU_RELRO if its
address is not equal to the start of its associated PT_LOAD.
This has been fixed by https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;h=f2731e0c374e5323ce4cdae2bcc7b7fe22da1a6f
But with this change, we will be compatible with GNU strip before 2.31
* Before, .got.plt (non-relro by default) was placed before .got (relro
by default), which made it impossible to have _GLOBAL_OFFSET_TABLE_
(start of .got.plt on x86-64) equal to the end of .got (R_GOT*_FROM_END)
(https://bugs.llvm.org/show_bug.cgi?id=36555). With the new ordering, we
can improve on this regard if we'd like to.
Reviewers: ruiu, espindola, pcc
Subscribers: emaste, arichardson, llvm-commits, joerg, jdoerfert
Differential Revision: https://reviews.llvm.org/D56828
llvm-svn: 356117
Currently we have -Rpass for filtering the remarks that are displayed as
diagnostics, but when using -fsave-optimization-record, there is no way
to filter the remarks while generating them.
This adds support for filtering remarks by passes using a regex.
Ex: `clang -fsave-optimization-record -foptimization-record-passes=inline`
will only emit the remarks coming from the pass `inline`.
This adds:
* `-fsave-optimization-record` to the driver
* `-opt-record-passes` to cc1
* `-lto-pass-remarks-filter` to the LTOCodeGenerator
* `--opt-remarks-passes` to lld
* `-pass-remarks-filter` to llc, opt, llvm-lto, llvm-lto2
* `-opt-remarks-passes` to gold-plugin
Differential Revision: https://reviews.llvm.org/D59268
Original llvm-svn: 355964
llvm-svn: 355984
This does not appear to be necessary because StringTableSection does not
need to be finalized, which also means that we can remove the call to
finalizeSynthetic on .dynstr.
Differential Revision: https://reviews.llvm.org/D59240
llvm-svn: 355977
This shaves another word off SectionBase and makes it possible to clone a
section using the implicit copy constructor.
This basically reverts r311056, which removed the mutex in order to
make the code easier to understand. On balance I think it's probably more
straightforward to have a mutex here than to have an unusual copy constructor
in SectionBase.
Differential Revision: https://reviews.llvm.org/D59269
llvm-svn: 355966
Currently we have -Rpass for filtering the remarks that are displayed as
diagnostics, but when using -fsave-optimization-record, there is no way
to filter the remarks while generating them.
This adds support for filtering remarks by passes using a regex.
Ex: `clang -fsave-optimization-record -foptimization-record-passes=inline`
will only emit the remarks coming from the pass `inline`.
This adds:
* `-fsave-optimization-record` to the driver
* `-opt-record-passes` to cc1
* `-lto-pass-remarks-filter` to the LTOCodeGenerator
* `--opt-remarks-passes` to lld
* `-pass-remarks-filter` to llc, opt, llvm-lto, llvm-lto2
* `-opt-remarks-passes` to gold-plugin
Differential Revision: https://reviews.llvm.org/D59268
llvm-svn: 355964
We don't need to take a slice of SectionCommands in addOrphanSections()
because it is not modified until the end of the function.
Differential Revision: https://reviews.llvm.org/D59239
llvm-svn: 355954
This matches the ELF does. Update the comment in ELF/Symbols.h and
duplicate it in wasm/Symbols.h
This a followup on rL355580 and rL355577.
Differential Revision: https://reviews.llvm.org/D59075
llvm-svn: 355737
- The Assigned bit was previously taking a word on its own. Move
it into the bit fields in SectionBase.
- NumRelocations and AreRelocsRela were previously also taking up
a word despite only using half of it. Move them into the alignment gap
after SectionBase's fields.
Differential Revision: https://reviews.llvm.org/D59044
llvm-svn: 355622
We're going to need a separate VersionNeedSection for each partition, and
the partition data structure won't be templated.
With this the VersionTableSection class no longer needs ELFT, so detemplate it.
Differential Revision: https://reviews.llvm.org/D58808
llvm-svn: 355478
This lets us detect file size overflows when creating a 64-bit binary on
a 32-bit machine.
Differential Revision: https://reviews.llvm.org/D58840
llvm-svn: 355218
r355153 introduced a build failure on a build bot that uses clang natively
on an armv7-a machine. This a temporary fix to use size_t rather than
uint64_t.
llvm-svn: 355195
This lets us remove the special case from Writer::writeSections(), and also
fixes a bug where .eh_frame_hdr isn't necessarily written in the correct
order if a linker script moves .eh_frame and .eh_frame_hdr into the same
output section.
Differential Revision: https://reviews.llvm.org/D58795
llvm-svn: 355153
That patch is the fix for https://bugs.llvm.org/show_bug.cgi?id=40703
"wrong line number info for obj file compiled with -ffunction-sections"
bug. The problem happened with only .o files. If object file contains
several .text sections then line number information showed incorrectly.
The reason for this is that DwarfLineTable could not detect section which
corresponds to specified address(because address is the local to the
section). And as the result it could not select proper sequence in the
line table. The fix is to pass SectionIndex with the address. So that it
would be possible to differentiate addresses from various sections. With
this fix llvm-objdump shows correct line numbers for disassembled code.
Differential review: https://reviews.llvm.org/D58194
llvm-svn: 354972
This patch removes the precompiled binary from inputs,
replacing it with a YAML. And teaches LLD to report a
section name in case of such error.
Differential revision: https://reviews.llvm.org/D58670
llvm-svn: 354959
Summary:
The gold linker allowed you to output the ELF files after LTO was run. It did
it by using the 'obj-path' option. This replicates that behavior.
Reviewers: espindola, ruiu, MaskRay, pcc
Reviewed By: MaskRay, pcc
Subscribers: grimar, emaste, inglorion, arichardson, steven_wu, dexonsmith, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D56046
llvm-svn: 354917
The linux kernel uses an old flag -p/-no-pipeline-knowledge that is
accepted by bfd and gold but ignored by modern versions of them. The
original option is very old and is pre-ABI, it sometimes comes up in
code-bases that had support for pre ABI toolchains. The Linux kernel uses
it in 3 places in the ARM specific section.
Differential Revision: https://reviews.llvm.org/D58540
llvm-svn: 354769
RelocationBaseSection is not used in -r links, so Config->Relocatable will
always be false.
Differential Revision: https://reviews.llvm.org/D58489
llvm-svn: 354607
Three MIPS-specific sections `.reginfo`, `.MIPS.options`, and `.MIPS.abiflags`
are used by loader to read their contents and setup environment for running
a program. Loader looks up these data in the corresponding segments:
`PT_MIPS_REGINFO`, `PT_MIPS_OPTIONS`, and `PT_MIPS_ABIFLAGS` respectively.
This patch put these sections to separate segments like we do already
for ARM `SHT_ARM_EXIDX` section.
Differential Revision: http://reviews.llvm.org/D58381
llvm-svn: 354468
MIPS R6 code uses the `R_MIPS_PC26_S2` relocation for calls which might
cross boundaries of non-PIC-to-PIC code. We need to create a LA25 thunks
for that case.
llvm-svn: 354312
The patch solves two tasks:
1. MIPS ABI allows to mix regular and microMIPS code and perform
cross-mode jumps. Linker needs to detect such cases and replace
jump/branch instructions by their cross-mode equivalents.
2. Other tools like dunamic linkers need to recognize cases when dynamic
table entries, e_entry field of an ELF header etc point to microMIPS
symbol. Linker should provide such information.
The first task is implemented in the `MIPS<ELFT>::relocateOne()` method.
New routine `fixupCrossModeJump` detects ISA mode change, checks and
replaces an instruction.
The main problem is how to recognize that relocation target is microMIPS
symbol. For absolute and section symbols compiler or assembler set the
less-significant bit of the symbol's value or sum of the symbol's value
and addend. And this bit signals to linker about microMIPS code. For
global symbols compiler cannot do the same trick because other tools like,
for example, disassembler wants to know an actual position of the symbol.
So compiler sets STO_MIPS_MICROMIPS flag in the `st_other` field.
In `MIPS<ELFT>::relocateOne()` method we have a symbol's value only and
cannot access any symbol's attributes. To pass type of the symbol
(regular/microMIPS) to that routine as well as other places where we
write a symbol value as-is (.dynamic section, `Elf_Ehdr::e_entry` field
etc) we set when necessary a less-significant bit in the `getSymVA`
function.
Differential revision: https://reviews.llvm.org/D40147
llvm-svn: 354311
On PowerPC64, it is necessary to keep the LocalEntry bits in st_other,
especially when -r is used. Otherwise, when the resulting object is used
in a posterior linking, LocalEntry info will be unavailable and
functions may be called through the wrong entrypoint.
Patch by Leandro Lupori.
Differential Revision: https://reviews.llvm.org/D56782
llvm-svn: 354184
Summary:
So this patch just make sure that the thread is at least stated
before we return from main.
If we just detach then the thread may be actually be stated just after
the process returned from main and it's calling atexit handers. Then the thread may try to create own function static variable and it will
add new at exit handlers confusing libc.
GLIBC before 2.27 had race in that case which corrupted atexit handlers
list. Support for this use-case for other implementation is also unclear,
so we can try just avoid that.
PR40162
Reviewers: ruiu, espindola
Subscribers: emaste, arichardson, jfb, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D58246
llvm-svn: 354078