llvm-project/lld/ELF/InputSection.cpp

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

1476 lines
56 KiB
C++
Raw Normal View History

//===- InputSection.cpp ---------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "InputSection.h"
#include "Config.h"
#include "EhFrame.h"
#include "InputFiles.h"
#include "LinkerScript.h"
#include "OutputSections.h"
#include "Relocations.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "Thunks.h"
#include "lld/Common/ErrorHandler.h"
#include "lld/Common/Memory.h"
2017-06-09 04:16:21 +08:00
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Compression.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/Threading.h"
#include "llvm/Support/xxhash.h"
#include <algorithm>
Parallelize uncompress() and splitIntoPieces(). Uncompressing section contents and spliting mergeable section contents into smaller chunks are heavy tasks. They scan entire section contents and do CPU-intensive tasks such as uncompressing zlib-compressed data or computing a hash value for each section piece. Luckily, these tasks are independent to each other, so we can do that in parallel_for_each. The number of input sections is large (as opposed to the number of output sections), so there's a large parallelism here. Actually the current design to call uncompress() and splitIntoPieces() in batch was chosen with doing this in mind. Basically what we need to do here is to replace `for` with `parallel_for_each`. It seems this patch improves latency significantly if linked programs contain debug info (which in turn contain lots of mergeable strings.) For example, the latency to link Clang (debug build) improved by 20% on my machine as shown below. Note that ld.gold took 19.2 seconds to do the same thing. Before: 30801.782712 task-clock (msec) # 3.652 CPUs utilized ( +- 2.59% ) 104,084 context-switches # 0.003 M/sec ( +- 1.02% ) 5,063 cpu-migrations # 0.164 K/sec ( +- 13.66% ) 2,528,130 page-faults # 0.082 M/sec ( +- 0.47% ) 85,317,809,130 cycles # 2.770 GHz ( +- 2.62% ) 67,352,463,373 stalled-cycles-frontend # 78.94% frontend cycles idle ( +- 3.06% ) <not supported> stalled-cycles-backend 44,295,945,493 instructions # 0.52 insns per cycle # 1.52 stalled cycles per insn ( +- 0.44% ) 8,572,384,877 branches # 278.308 M/sec ( +- 0.66% ) 141,806,726 branch-misses # 1.65% of all branches ( +- 0.13% ) 8.433424003 seconds time elapsed ( +- 1.20% ) After: 35523.764575 task-clock (msec) # 5.265 CPUs utilized ( +- 2.67% ) 159,107 context-switches # 0.004 M/sec ( +- 0.48% ) 8,123 cpu-migrations # 0.229 K/sec ( +- 23.34% ) 2,372,483 page-faults # 0.067 M/sec ( +- 0.36% ) 98,395,342,152 cycles # 2.770 GHz ( +- 2.62% ) 79,294,670,125 stalled-cycles-frontend # 80.59% frontend cycles idle ( +- 3.03% ) <not supported> stalled-cycles-backend 46,274,151,813 instructions # 0.47 insns per cycle # 1.71 stalled cycles per insn ( +- 0.47% ) 8,987,621,670 branches # 253.003 M/sec ( +- 0.60% ) 148,900,624 branch-misses # 1.66% of all branches ( +- 0.27% ) 6.747548004 seconds time elapsed ( +- 0.40% ) llvm-svn: 287946
2016-11-26 04:05:08 +08:00
#include <mutex>
#include <set>
#include <unordered_set>
#include <vector>
using namespace llvm;
using namespace llvm::ELF;
using namespace llvm::object;
using namespace llvm::support;
using namespace llvm::support::endian;
using namespace llvm::sys;
using namespace lld;
using namespace lld::elf;
std::vector<InputSectionBase *> elf::inputSections;
DenseSet<std::pair<const Symbol *, uint64_t>> elf::ppc64noTocRelax;
// Returns a string to construct an error message.
std::string lld::toString(const InputSectionBase *sec) {
return (toString(sec->file) + ":(" + sec->name + ")").str();
}
template <class ELFT>
static ArrayRef<uint8_t> getSectionContents(ObjFile<ELFT> &file,
const typename ELFT::Shdr &hdr) {
if (hdr.sh_type == SHT_NOBITS)
return makeArrayRef<uint8_t>(nullptr, hdr.sh_size);
return check(file.getObj().getSectionContents(hdr));
}
InputSectionBase::InputSectionBase(InputFile *file, uint64_t flags,
uint32_t type, uint64_t entsize,
uint32_t link, uint32_t info,
uint32_t alignment, ArrayRef<uint8_t> data,
StringRef name, Kind sectionKind)
: SectionBase(sectionKind, name, flags, entsize, alignment, type, info,
link),
file(file), rawData(data) {
// In order to reduce memory allocation, we assume that mergeable
// sections are smaller than 4 GiB, which is not an unreasonable
// assumption as of 2017.
if (sectionKind == SectionBase::Merge && rawData.size() > UINT32_MAX)
error(toString(this) + ": section too large");
numRelocations = 0;
areRelocsRela = false;
// The ELF spec states that a value of 0 means the section has
// no alignment constraints.
uint32_t v = std::max<uint32_t>(alignment, 1);
if (!isPowerOf2_64(v))
fatal(toString(this) + ": sh_addralign is not a power of 2");
this->alignment = v;
// In ELF, each section can be compressed by zlib, and if compressed,
// section name may be mangled by appending "z" (e.g. ".zdebug_info").
// If that's the case, demangle section name so that we can handle a
// section as if it weren't compressed.
if ((flags & SHF_COMPRESSED) || name.startswith(".zdebug")) {
if (!zlib::isAvailable())
error(toString(file) + ": contains a compressed section, " +
"but zlib is not available");
parseCompressedHeader();
}
}
// Drop SHF_GROUP bit unless we are producing a re-linkable object file.
// SHF_GROUP is a marker that a section belongs to some comdat group.
// That flag doesn't make sense in an executable.
static uint64_t getFlags(uint64_t flags) {
flags &= ~(uint64_t)SHF_INFO_LINK;
if (!config->relocatable)
flags &= ~(uint64_t)SHF_GROUP;
return flags;
}
// GNU assembler 2.24 and LLVM 4.0.0's MC (the newest release as of
// March 2017) fail to infer section types for sections starting with
// ".init_array." or ".fini_array.". They set SHT_PROGBITS instead of
// SHF_INIT_ARRAY. As a result, the following assembler directive
// creates ".init_array.100" with SHT_PROGBITS, for example.
//
// .section .init_array.100, "aw"
//
// This function forces SHT_{INIT,FINI}_ARRAY so that we can handle
// incorrect inputs as if they were correct from the beginning.
static uint64_t getType(uint64_t type, StringRef name) {
if (type == SHT_PROGBITS && name.startswith(".init_array."))
return SHT_INIT_ARRAY;
if (type == SHT_PROGBITS && name.startswith(".fini_array."))
return SHT_FINI_ARRAY;
return type;
}
template <class ELFT>
InputSectionBase::InputSectionBase(ObjFile<ELFT> &file,
const typename ELFT::Shdr &hdr,
StringRef name, Kind sectionKind)
: InputSectionBase(&file, getFlags(hdr.sh_flags),
getType(hdr.sh_type, name), hdr.sh_entsize, hdr.sh_link,
hdr.sh_info, hdr.sh_addralign,
getSectionContents(file, hdr), name, sectionKind) {
// We reject object files having insanely large alignments even though
// they are allowed by the spec. I think 4GB is a reasonable limitation.
// We might want to relax this in the future.
if (hdr.sh_addralign > UINT32_MAX)
fatal(toString(&file) + ": section sh_addralign is too large");
}
size_t InputSectionBase::getSize() const {
if (auto *s = dyn_cast<SyntheticSection>(this))
return s->getSize();
if (uncompressedSize >= 0)
return uncompressedSize;
LLD Support for Basic Block Sections This is part of the Propeller framework to do post link code layout optimizations. Please see the RFC here: https://groups.google.com/forum/#!msg/llvm-dev/ef3mKzAdJ7U/1shV64BYBAAJ and the detailed RFC doc here: https://github.com/google/llvm-propeller/blob/plo-dev/Propeller_RFC.pdf This patch adds lld support for basic block sections and performs relaxations after the basic blocks have been reordered. After the linker has reordered the basic block sections according to the desired sequence, it runs a relaxation pass to optimize jump instructions. Currently, the compiler emits the long form of all jump instructions. AMD64 ISA supports variants of jump instructions with one byte offset or a four byte offset. The compiler generates jump instructions with R_X86_64 32-bit PC relative relocations. We would like to use a new relocation type for these jump instructions as it makes it easy and accurate while relaxing these instructions. The relaxation pass does two things: First, it deletes all explicit fall-through direct jump instructions between adjacent basic blocks. This is done by discarding the tail of the basic block section. Second, If there are consecutive jump instructions, it checks if the first conditional jump can be inverted to convert the second into a fall through and delete the second. The jump instructions are relaxed by using jump instruction mods, something like relocations. These are used to modify the opcode of the jump instruction. Jump instruction mods contain three values, instruction offset, jump type and size. While writing this jump instruction out to the final binary, the linker uses the jump instruction mod to determine the opcode and the size of the modified jump instruction. These mods are required because the input object files are memory-mapped without write permissions and directly modifying the object files requires copying these sections. Copying a large number of basic block sections significantly bloats memory. Differential Revision: https://reviews.llvm.org/D68065
2020-04-07 21:48:18 +08:00
return rawData.size() - bytesDropped;
}
void InputSectionBase::uncompress() const {
size_t size = uncompressedSize;
char *uncompressedBuf;
{
static std::mutex mu;
std::lock_guard<std::mutex> lock(mu);
uncompressedBuf = bAlloc.Allocate<char>(size);
}
if (Error e = zlib::uncompress(toStringRef(rawData), uncompressedBuf, size))
fatal(toString(this) +
": uncompress failed: " + llvm::toString(std::move(e)));
rawData = makeArrayRef((uint8_t *)uncompressedBuf, size);
uncompressedSize = -1;
}
uint64_t InputSectionBase::getOffsetInFile() const {
const uint8_t *fileStart = (const uint8_t *)file->mb.getBufferStart();
const uint8_t *secStart = data().begin();
return secStart - fileStart;
}
uint64_t SectionBase::getOffset(uint64_t offset) const {
switch (kind()) {
case Output: {
auto *os = cast<OutputSection>(this);
// For output sections we treat offset -1 as the end of the section.
return offset == uint64_t(-1) ? os->size : offset;
}
case Regular:
case Synthetic:
return cast<InputSection>(this)->getOffset(offset);
case EHFrame:
// The file crtbeginT.o has relocations pointing to the start of an empty
// .eh_frame that is known to be the first in the link. It does that to
// identify the start of the output .eh_frame.
return offset;
case Merge:
const MergeInputSection *ms = cast<MergeInputSection>(this);
if (InputSection *isec = ms->getParent())
return isec->getOffset(ms->getParentOffset(offset));
return ms->getParentOffset(offset);
}
llvm_unreachable("invalid section kind");
}
uint64_t SectionBase::getVA(uint64_t offset) const {
const OutputSection *out = getOutputSection();
return (out ? out->addr : 0) + getOffset(offset);
}
OutputSection *SectionBase::getOutputSection() {
InputSection *sec;
if (auto *isec = dyn_cast<InputSection>(this))
sec = isec;
else if (auto *ms = dyn_cast<MergeInputSection>(this))
sec = ms->getParent();
else if (auto *eh = dyn_cast<EhInputSection>(this))
sec = eh->getParent();
else
return cast<OutputSection>(this);
return sec ? sec->getParent() : nullptr;
}
// When a section is compressed, `rawData` consists with a header followed
// by zlib-compressed data. This function parses a header to initialize
// `uncompressedSize` member and remove the header from `rawData`.
void InputSectionBase::parseCompressedHeader() {
using Chdr64 = typename ELF64LE::Chdr;
using Chdr32 = typename ELF32LE::Chdr;
// Old-style header
if (name.startswith(".zdebug")) {
if (!toStringRef(rawData).startswith("ZLIB")) {
error(toString(this) + ": corrupted compressed section header");
return;
}
rawData = rawData.slice(4);
if (rawData.size() < 8) {
error(toString(this) + ": corrupted compressed section header");
return;
}
uncompressedSize = read64be(rawData.data());
rawData = rawData.slice(8);
// Restore the original section name.
// (e.g. ".zdebug_info" -> ".debug_info")
name = saver.save("." + name.substr(2));
return;
}
assert(flags & SHF_COMPRESSED);
flags &= ~(uint64_t)SHF_COMPRESSED;
// New-style 64-bit header
if (config->is64) {
if (rawData.size() < sizeof(Chdr64)) {
error(toString(this) + ": corrupted compressed section");
return;
}
auto *hdr = reinterpret_cast<const Chdr64 *>(rawData.data());
if (hdr->ch_type != ELFCOMPRESS_ZLIB) {
error(toString(this) + ": unsupported compression type");
return;
}
uncompressedSize = hdr->ch_size;
alignment = std::max<uint32_t>(hdr->ch_addralign, 1);
rawData = rawData.slice(sizeof(*hdr));
return;
}
// New-style 32-bit header
if (rawData.size() < sizeof(Chdr32)) {
error(toString(this) + ": corrupted compressed section");
return;
}
auto *hdr = reinterpret_cast<const Chdr32 *>(rawData.data());
if (hdr->ch_type != ELFCOMPRESS_ZLIB) {
error(toString(this) + ": unsupported compression type");
return;
}
uncompressedSize = hdr->ch_size;
alignment = std::max<uint32_t>(hdr->ch_addralign, 1);
rawData = rawData.slice(sizeof(*hdr));
}
InputSection *InputSectionBase::getLinkOrderDep() const {
assert(flags & SHF_LINK_ORDER);
if (!link)
return nullptr;
return cast<InputSection>(file->getSections()[link]);
}
// Find a function symbol that encloses a given location.
template <class ELFT>
Defined *InputSectionBase::getEnclosingFunction(uint64_t offset) {
for (Symbol *b : file->getSymbols())
if (Defined *d = dyn_cast<Defined>(b))
if (d->section == this && d->type == STT_FUNC && d->value <= offset &&
offset < d->value + d->size)
return d;
return nullptr;
}
// Returns a source location string. Used to construct an error message.
template <class ELFT>
std::string InputSectionBase::getLocation(uint64_t offset) {
std::string secAndOffset = (name + "+0x" + utohexstr(offset)).str();
// We don't have file for synthetic sections.
if (getFile<ELFT>() == nullptr)
return (config->outputFile + ":(" + secAndOffset + ")")
.str();
// First check if we can get desired values from debugging information.
if (Optional<DILineInfo> info = getFile<ELFT>()->getDILineInfo(this, offset))
return info->FileName + ":" + std::to_string(info->Line) + ":(" +
secAndOffset + ")";
// File->sourceFile contains STT_FILE symbol that contains a
// source file name. If it's missing, we use an object file name.
std::string srcFile = std::string(getFile<ELFT>()->sourceFile);
if (srcFile.empty())
srcFile = toString(file);
if (Defined *d = getEnclosingFunction<ELFT>(offset))
return srcFile + ":(function " + toString(*d) + ": " + secAndOffset + ")";
// If there's no symbol, print out the offset in the section.
return (srcFile + ":(" + secAndOffset + ")");
}
// This function is intended to be used for constructing an error message.
// The returned message looks like this:
//
// foo.c:42 (/home/alice/possibly/very/long/path/foo.c:42)
//
// Returns an empty string if there's no way to get line info.
std::string InputSectionBase::getSrcMsg(const Symbol &sym, uint64_t offset) {
return file->getSrcMsg(sym, *this, offset);
}
// Returns a filename string along with an optional section name. This
// function is intended to be used for constructing an error
// message. The returned message looks like this:
//
// path/to/foo.o:(function bar)
//
// or
//
// path/to/foo.o:(function bar) in archive path/to/bar.a
std::string InputSectionBase::getObjMsg(uint64_t off) {
std::string filename = std::string(file->getName());
std::string archive;
if (!file->archiveName.empty())
archive = " in archive " + file->archiveName;
// Find a symbol that encloses a given location.
for (Symbol *b : file->getSymbols())
if (auto *d = dyn_cast<Defined>(b))
if (d->section == this && d->value <= off && off < d->value + d->size)
return filename + ":(" + toString(*d) + ")" + archive;
// If there's no symbol, print out the offset in the section.
return (filename + ":(" + name + "+0x" + utohexstr(off) + ")" + archive)
.str();
}
InputSection InputSection::discarded(nullptr, 0, 0, 0, ArrayRef<uint8_t>(), "");
InputSection::InputSection(InputFile *f, uint64_t flags, uint32_t type,
uint32_t alignment, ArrayRef<uint8_t> data,
StringRef name, Kind k)
: InputSectionBase(f, flags, type,
/*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, alignment, data,
name, k) {}
template <class ELFT>
InputSection::InputSection(ObjFile<ELFT> &f, const typename ELFT::Shdr &header,
StringRef name)
: InputSectionBase(f, header, name, InputSectionBase::Regular) {}
bool InputSection::classof(const SectionBase *s) {
return s->kind() == SectionBase::Regular ||
s->kind() == SectionBase::Synthetic;
}
OutputSection *InputSection::getParent() const {
return cast_or_null<OutputSection>(parent);
}
2017-06-09 11:19:08 +08:00
// Copy SHT_GROUP section contents. Used only for the -r option.
template <class ELFT> void InputSection::copyShtGroup(uint8_t *buf) {
// ELFT::Word is the 32-bit integral type in the target endianness.
using u32 = typename ELFT::Word;
2017-06-09 11:19:08 +08:00
ArrayRef<u32> from = getDataAs<u32>();
auto *to = reinterpret_cast<u32 *>(buf);
// The first entry is not a section number but a flag.
*to++ = from[0];
// Adjust section numbers because section numbers in an input object files are
// different in the output. We also need to handle combined or discarded
// members.
ArrayRef<InputSectionBase *> sections = file->getSections();
std::unordered_set<uint32_t> seen;
for (uint32_t idx : from.slice(1)) {
OutputSection *osec = sections[idx]->getOutputSection();
if (osec && seen.insert(osec->sectionIndex).second)
*to++ = osec->sectionIndex;
}
}
InputSectionBase *InputSection::getRelocatedSection() const {
if (!file || (type != SHT_RELA && type != SHT_REL))
return nullptr;
ArrayRef<InputSectionBase *> sections = file->getSections();
return sections[info];
}
// This is used for -r and --emit-relocs. We can't use memcpy to copy
// relocations because we need to update symbol table offset and section index
// for each relocation. So we copy relocations one by one.
template <class ELFT, class RelTy>
void InputSection::copyRelocations(uint8_t *buf, ArrayRef<RelTy> rels) {
InputSectionBase *sec = getRelocatedSection();
for (const RelTy &rel : rels) {
RelType type = rel.getType(config->isMips64EL);
Reland D61583 [ELF] Error on relocations to STT_SECTION symbols if the sections were discarded This restores r361830 "[ELF] Error on relocations to STT_SECTION symbols if the sections were discarded" and dependent commits (r362218, r362497) which were reverted by r364321, with a fix of a --gdb-index issue. .rela.debug_ranges contains relocations of range list entries: // start address of a range list entry // old: 0; after r361830: 0 00000000000033a0 R_X86_64_64 .text._ZN2v88internal7Isolate7factoryEv + 0 // end address of a range list entry // old: 0xe; after r361830: 0 00000000000033a8 R_X86_64_64 .text._ZN2v88internal7Isolate7factoryEv + e If both start and end addresses of a range list entry resolve to 0, DWARFDebugRangeList::isEndOfListEntry() will return true, then the .debug_range decoding loop will terminate prematurely: while (true) { decode StartAddress decode EndAddress if (Entry.isEndOfListEntry()) // prematurely break; Entries.push_back(Entry); } In lld/ELF/SyntheticSections.cpp, readAddressAreas() will read incomplete address ranges and the resulting .gdb_index will be incomplete. For files that gdb hasn't loaded their debug info, gdb uses .gdb_index to map addresses to CUs. The absent entries make gdb fail to symbolize some addresses. To address this issue, we simply allow relocations to undefined symbols in DWARF.cpp:findAux() and let RelocationResolver resolve them. This patch should fix: [1] http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20190603/659848.html [2] https://bugs.chromium.org/p/chromium/issues/detail?id=978067 llvm-svn: 364391
2019-06-26 16:09:08 +08:00
const ObjFile<ELFT> *file = getFile<ELFT>();
Symbol &sym = file->getRelocTargetSym(rel);
auto *p = reinterpret_cast<typename ELFT::Rela *>(buf);
buf += sizeof(RelTy);
if (RelTy::IsRela)
p->r_addend = getAddend<ELFT>(rel);
// Output section VA is zero for -r, so r_offset is an offset within the
// section, but for --emit-relocs it is a virtual address.
p->r_offset = sec->getVA(rel.r_offset);
p->setSymbolAndType(in.symTab->getSymbolIndex(&sym), type,
config->isMips64EL);
if (sym.type == STT_SECTION) {
// We combine multiple section symbols into only one per
// section. This means we have to update the addend. That is
// trivial for Elf_Rela, but for Elf_Rel we have to write to the
// section data. We do that by adding to the Relocation vector.
// .eh_frame is horribly special and can reference discarded sections. To
// avoid having to parse and recreate .eh_frame, we just replace any
// relocation in it pointing to discarded sections with R_*_NONE, which
Reland D61583 [ELF] Error on relocations to STT_SECTION symbols if the sections were discarded This restores r361830 "[ELF] Error on relocations to STT_SECTION symbols if the sections were discarded" and dependent commits (r362218, r362497) which were reverted by r364321, with a fix of a --gdb-index issue. .rela.debug_ranges contains relocations of range list entries: // start address of a range list entry // old: 0; after r361830: 0 00000000000033a0 R_X86_64_64 .text._ZN2v88internal7Isolate7factoryEv + 0 // end address of a range list entry // old: 0xe; after r361830: 0 00000000000033a8 R_X86_64_64 .text._ZN2v88internal7Isolate7factoryEv + e If both start and end addresses of a range list entry resolve to 0, DWARFDebugRangeList::isEndOfListEntry() will return true, then the .debug_range decoding loop will terminate prematurely: while (true) { decode StartAddress decode EndAddress if (Entry.isEndOfListEntry()) // prematurely break; Entries.push_back(Entry); } In lld/ELF/SyntheticSections.cpp, readAddressAreas() will read incomplete address ranges and the resulting .gdb_index will be incomplete. For files that gdb hasn't loaded their debug info, gdb uses .gdb_index to map addresses to CUs. The absent entries make gdb fail to symbolize some addresses. To address this issue, we simply allow relocations to undefined symbols in DWARF.cpp:findAux() and let RelocationResolver resolve them. This patch should fix: [1] http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20190603/659848.html [2] https://bugs.chromium.org/p/chromium/issues/detail?id=978067 llvm-svn: 364391
2019-06-26 16:09:08 +08:00
// hopefully creates a frame that is ignored at runtime. Also, don't warn
// on .gcc_except_table and debug sections.
//
// See the comment in maybeReportUndefined for PPC32 .got2 and PPC64 .toc
auto *d = dyn_cast<Defined>(&sym);
if (!d) {
if (!isDebugSection(*sec) && sec->name != ".eh_frame" &&
sec->name != ".gcc_except_table" && sec->name != ".got2" &&
sec->name != ".toc") {
Reland D61583 [ELF] Error on relocations to STT_SECTION symbols if the sections were discarded This restores r361830 "[ELF] Error on relocations to STT_SECTION symbols if the sections were discarded" and dependent commits (r362218, r362497) which were reverted by r364321, with a fix of a --gdb-index issue. .rela.debug_ranges contains relocations of range list entries: // start address of a range list entry // old: 0; after r361830: 0 00000000000033a0 R_X86_64_64 .text._ZN2v88internal7Isolate7factoryEv + 0 // end address of a range list entry // old: 0xe; after r361830: 0 00000000000033a8 R_X86_64_64 .text._ZN2v88internal7Isolate7factoryEv + e If both start and end addresses of a range list entry resolve to 0, DWARFDebugRangeList::isEndOfListEntry() will return true, then the .debug_range decoding loop will terminate prematurely: while (true) { decode StartAddress decode EndAddress if (Entry.isEndOfListEntry()) // prematurely break; Entries.push_back(Entry); } In lld/ELF/SyntheticSections.cpp, readAddressAreas() will read incomplete address ranges and the resulting .gdb_index will be incomplete. For files that gdb hasn't loaded their debug info, gdb uses .gdb_index to map addresses to CUs. The absent entries make gdb fail to symbolize some addresses. To address this issue, we simply allow relocations to undefined symbols in DWARF.cpp:findAux() and let RelocationResolver resolve them. This patch should fix: [1] http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20190603/659848.html [2] https://bugs.chromium.org/p/chromium/issues/detail?id=978067 llvm-svn: 364391
2019-06-26 16:09:08 +08:00
uint32_t secIdx = cast<Undefined>(sym).discardedSecIdx;
Elf_Shdr_Impl<ELFT> sec =
CHECK(file->getObj().sections(), file)[secIdx];
warn("relocation refers to a discarded section: " +
CHECK(file->getObj().getSectionName(sec), file) +
Reland D61583 [ELF] Error on relocations to STT_SECTION symbols if the sections were discarded This restores r361830 "[ELF] Error on relocations to STT_SECTION symbols if the sections were discarded" and dependent commits (r362218, r362497) which were reverted by r364321, with a fix of a --gdb-index issue. .rela.debug_ranges contains relocations of range list entries: // start address of a range list entry // old: 0; after r361830: 0 00000000000033a0 R_X86_64_64 .text._ZN2v88internal7Isolate7factoryEv + 0 // end address of a range list entry // old: 0xe; after r361830: 0 00000000000033a8 R_X86_64_64 .text._ZN2v88internal7Isolate7factoryEv + e If both start and end addresses of a range list entry resolve to 0, DWARFDebugRangeList::isEndOfListEntry() will return true, then the .debug_range decoding loop will terminate prematurely: while (true) { decode StartAddress decode EndAddress if (Entry.isEndOfListEntry()) // prematurely break; Entries.push_back(Entry); } In lld/ELF/SyntheticSections.cpp, readAddressAreas() will read incomplete address ranges and the resulting .gdb_index will be incomplete. For files that gdb hasn't loaded their debug info, gdb uses .gdb_index to map addresses to CUs. The absent entries make gdb fail to symbolize some addresses. To address this issue, we simply allow relocations to undefined symbols in DWARF.cpp:findAux() and let RelocationResolver resolve them. This patch should fix: [1] http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20190603/659848.html [2] https://bugs.chromium.org/p/chromium/issues/detail?id=978067 llvm-svn: 364391
2019-06-26 16:09:08 +08:00
"\n>>> referenced by " + getObjMsg(p->r_offset));
}
p->setSymbolAndType(0, 0, false);
continue;
}
SectionBase *section = d->section->repl;
if (!section->isLive()) {
p->setSymbolAndType(0, 0, false);
continue;
}
int64_t addend = getAddend<ELFT>(rel);
const uint8_t *bufLoc = sec->data().begin() + rel.r_offset;
if (!RelTy::IsRela)
addend = target->getImplicitAddend(bufLoc, type);
if (config->emachine == EM_MIPS &&
target->getRelExpr(type, sym, bufLoc) == R_MIPS_GOTREL) {
// Some MIPS relocations depend on "gp" value. By default,
// this value has 0x7ff0 offset from a .got section. But
// relocatable files produced by a compiler or a linker
// might redefine this default value and we must use it
// for a calculation of the relocation result. When we
// generate EXE or DSO it's trivial. Generating a relocatable
// output is more difficult case because the linker does
// not calculate relocations in this mode and loses
// individual "gp" values used by each input object file.
// As a workaround we add the "gp" value to the relocation
// addend and save it back to the file.
addend += sec->getFile<ELFT>()->mipsGp0;
}
if (RelTy::IsRela)
p->r_addend = sym.getVA(addend) - section->getOutputSection()->addr;
else if (config->relocatable && type != target->noneRel)
sec->relocations.push_back({R_ABS, type, rel.r_offset, addend, &sym});
} else if (config->emachine == EM_PPC && type == R_PPC_PLTREL24 &&
p->r_addend >= 0x8000) {
// Similar to R_MIPS_GPREL{16,32}. If the addend of R_PPC_PLTREL24
// indicates that r30 is relative to the input section .got2
// (r_addend>=0x8000), after linking, r30 should be relative to the output
// section .got2 . To compensate for the shift, adjust r_addend by
// ppc32Got2OutSecOff.
p->r_addend += sec->file->ppc32Got2OutSecOff;
}
}
}
// The ARM and AArch64 ABI handle pc-relative relocations to undefined weak
// references specially. The general rule is that the value of the symbol in
// this context is the address of the place P. A further special case is that
// branch relocations to an undefined weak reference resolve to the next
// instruction.
static uint32_t getARMUndefinedRelativeWeakVA(RelType type, uint32_t a,
uint32_t p) {
switch (type) {
// Unresolved branch relocations to weak references resolve to next
// instruction, this will be either 2 or 4 bytes on from P.
case R_ARM_THM_JUMP11:
return p + 2 + a;
case R_ARM_CALL:
case R_ARM_JUMP24:
case R_ARM_PC24:
case R_ARM_PLT32:
case R_ARM_PREL31:
case R_ARM_THM_JUMP19:
case R_ARM_THM_JUMP24:
return p + 4 + a;
case R_ARM_THM_CALL:
// We don't want an interworking BLX to ARM
return p + 5 + a;
// Unresolved non branch pc-relative relocations
// R_ARM_TARGET2 which can be resolved relatively is not present as it never
// targets a weak-reference.
case R_ARM_MOVW_PREL_NC:
case R_ARM_MOVT_PREL:
case R_ARM_REL32:
case R_ARM_THM_ALU_PREL_11_0:
case R_ARM_THM_MOVW_PREL_NC:
case R_ARM_THM_MOVT_PREL:
case R_ARM_THM_PC12:
return p + a;
// p + a is unrepresentable as negative immediates can't be encoded.
case R_ARM_THM_PC8:
return p;
}
llvm_unreachable("ARM pc-relative relocation expected\n");
}
// The comment above getARMUndefinedRelativeWeakVA applies to this function.
2016-11-14 18:14:18 +08:00
static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t type, uint64_t a,
uint64_t p) {
switch (type) {
// Unresolved branch relocations to weak references resolve to next
// instruction, this is 4 bytes on from P.
case R_AARCH64_CALL26:
case R_AARCH64_CONDBR19:
case R_AARCH64_JUMP26:
case R_AARCH64_TSTBR14:
return p + 4 + a;
// Unresolved non branch pc-relative relocations
case R_AARCH64_PREL16:
case R_AARCH64_PREL32:
case R_AARCH64_PREL64:
case R_AARCH64_ADR_PREL_LO21:
case R_AARCH64_LD_PREL_LO19:
case R_AARCH64_PLT32:
return p + a;
}
llvm_unreachable("AArch64 pc-relative relocation expected\n");
}
// ARM SBREL relocations are of the form S + A - B where B is the static base
// The ARM ABI defines base to be "addressing origin of the output segment
// defining the symbol S". We defined the "addressing origin"/static base to be
// the base of the PT_LOAD segment containing the Sym.
// The procedure call standard only defines a Read Write Position Independent
// RWPI variant so in practice we should expect the static base to be the base
// of the RW segment.
static uint64_t getARMStaticBase(const Symbol &sym) {
OutputSection *os = sym.getOutputSection();
if (!os || !os->ptLoad || !os->ptLoad->firstSec)
fatal("SBREL relocation to " + sym.getName() + " without static base");
return os->ptLoad->firstSec->addr;
}
// For R_RISCV_PC_INDIRECT (R_RISCV_PCREL_LO12_{I,S}), the symbol actually
// points the corresponding R_RISCV_PCREL_HI20 relocation, and the target VA
// is calculated using PCREL_HI20's symbol.
//
// This function returns the R_RISCV_PCREL_HI20 relocation from
// R_RISCV_PCREL_LO12's symbol and addend.
static Relocation *getRISCVPCRelHi20(const Symbol *sym, uint64_t addend) {
const Defined *d = cast<Defined>(sym);
if (!d->section) {
error("R_RISCV_PCREL_LO12 relocation points to an absolute symbol: " +
sym->getName());
return nullptr;
}
InputSection *isec = cast<InputSection>(d->section);
if (addend != 0)
warn("Non-zero addend in R_RISCV_PCREL_LO12 relocation to " +
isec->getObjMsg(d->value) + " is ignored");
// Relocations are sorted by offset, so we can use std::equal_range to do
// binary search.
Relocation r;
r.offset = d->value;
auto range =
std::equal_range(isec->relocations.begin(), isec->relocations.end(), r,
[](const Relocation &lhs, const Relocation &rhs) {
return lhs.offset < rhs.offset;
});
for (auto it = range.first; it != range.second; ++it)
if (it->type == R_RISCV_PCREL_HI20 || it->type == R_RISCV_GOT_HI20 ||
it->type == R_RISCV_TLS_GD_HI20 || it->type == R_RISCV_TLS_GOT_HI20)
return &*it;
error("R_RISCV_PCREL_LO12 relocation points to " + isec->getObjMsg(d->value) +
" without an associated R_RISCV_PCREL_HI20 relocation");
return nullptr;
}
[ELF] Refactor per-target TLS layout configuration. NFC. Summary: There are really three different kinds of TLS layouts: * A fixed TLS-to-TP offset. On architectures like PowerPC, MIPS, and RISC-V, the thread pointer points to a fixed offset from the start of the executable's TLS segment. The offset is 0x7000 for PowerPC and MIPS, which allows a signed 16-bit offset to reach 0x1000 of per-thread implementation data and 0xf000 of the application's TLS segment. The size and layout of the TCB isn't relevant to the static linker and might not be known. * A fixed TCB size. This is the format documented as "variant 1" in Ulrich Drepper's TLS spec. The thread pointer points to a 2-word TCB followed by the executable's TLS segment. The first word is always the DTV pointer. Used on ARM. The thread pointer must be aligned to the TLS segment's alignment, possibly creating alignment padding. * Variant 2. This format predates variant 1 and is also documented in Drepper's TLS spec. It allocates the executable's TLS segment before the thread pointer, apparently for backwards-compatibility. It's used on x86 and SPARC. Factor out an lld::elf::getTlsTpOffset() function for use in a follow-up patch for Android. The TcbSize/TlsTpOffset fields are only used in getTlsTpOffset, so replace them with a switch on Config->EMachine. Reviewers: espindola, ruiu, PkmX, jrtc27 Reviewed By: ruiu, PkmX, jrtc27 Subscribers: jyknight, emaste, sdardis, nemanjai, javed.absar, arichardson, kristof.beyls, kbarton, fedor.sergeev, atanasyan, PkmX, jsji, llvm-commits Differential Revision: https://reviews.llvm.org/D53905 llvm-svn: 345775
2018-11-01 04:53:17 +08:00
// A TLS symbol's virtual address is relative to the TLS segment. Add a
// target-specific adjustment to produce a thread-pointer-relative offset.
static int64_t getTlsTpOffset(const Symbol &s) {
// On targets that support TLSDESC, _TLS_MODULE_BASE_@tpoff = 0.
if (&s == ElfSym::tlsModuleBase)
return 0;
[ELF][PPC] Allow PT_LOAD to have overlapping p_offset ranges This change affects the non-linker script case (precisely, when the `SECTIONS` command is not used). It deletes 3 alignments at PT_LOAD boundaries for the default case: the size of a powerpc64 binary can be decreased by at most 192kb. The technique can be ported to other targets. Let me demonstrate the idea with a maxPageSize=65536 example: When assigning the address to the first output section of a new PT_LOAD, if the end p_vaddr of the previous PT_LOAD is 0x10020, we advance to the next multiple of maxPageSize: 0x20000. The new PT_LOAD will thus have p_vaddr=0x20000. Because p_offset and p_vaddr are congruent modulo maxPageSize, p_offset will be 0x20000, leaving a p_offset gap [0x10020, 0x20000) in the output. Alternatively, if we advance to 0x20020, the new PT_LOAD will have p_vaddr=0x20020. We can pick either 0x10020 or 0x20020 for p_offset! Obviously 0x10020 is the choice because it leaves no gap. At runtime, p_vaddr will be rounded down by pagesize (65536 if pagesize=maxPageSize). This PT_LOAD will load additional initial contents from p_offset ranges [0x10000,0x10020), which will also be loaded by the previous PT_LOAD. This is fine if -z noseparate-code is in effect or if we are not transiting between executable and non-executable segments. ld.bfd -z noseparate-code leverages this technique to keep output small. This patch implements the technique in lld, which is mostly effective on targets with large defaultMaxPageSize (AArch64/MIPS/PPC: 65536). The 3 removed alignments can save almost 3*65536 bytes. Two places that rely on p_vaddr%pagesize = 0 have to be updated. 1) We used to round p_memsz(PT_GNU_RELRO) up to commonPageSize (defaults to 4096 on all targets). Now p_vaddr%commonPageSize may be non-zero. The updated formula takes account of that factor. 2) Our TP offsets formulae are only correct if p_vaddr%p_align = 0. Fix them. See the updated comments in InputSection.cpp for details. On targets that we enable the technique (only PPC64 now), we can potentially make `p_vaddr(PT_TLS)%p_align(PT_TLS) != 0` if `sh_addralign(.tdata) < sh_addralign(.tbss)` This exposes many problems in ld.so implementations, especially the offsets of dynamic TLS blocks. Known issues: FreeBSD 13.0-CURRENT rtld-elf (i386/amd64/powerpc/arm64) glibc (HEAD) i386 and x86_64 https://sourceware.org/bugzilla/show_bug.cgi?id=24606 musl<=1.1.22 on TLS Variant I architectures (aarch64/powerpc64/...) So, force p_vaddr%p_align = 0 by rounding dot up to p_align(PT_TLS). The technique will be enabled (with updated tests) for other targets in subsequent patches. Reviewed By: ruiu Differential Revision: https://reviews.llvm.org/D64906 llvm-svn: 369343
2019-08-20 16:34:25 +08:00
// There are 2 TLS layouts. Among targets we support, x86 uses TLS Variant 2
// while most others use Variant 1. At run time TP will be aligned to p_align.
// Variant 1. TP will be followed by an optional gap (which is the size of 2
// pointers on ARM/AArch64, 0 on other targets), followed by alignment
// padding, then the static TLS blocks. The alignment padding is added so that
// (TP + gap + padding) is congruent to p_vaddr modulo p_align.
//
// Variant 2. Static TLS blocks, followed by alignment padding are placed
// before TP. The alignment padding is added so that (TP - padding -
// p_memsz) is congruent to p_vaddr modulo p_align.
PhdrEntry *tls = Out::tlsPhdr;
[ELF] Refactor per-target TLS layout configuration. NFC. Summary: There are really three different kinds of TLS layouts: * A fixed TLS-to-TP offset. On architectures like PowerPC, MIPS, and RISC-V, the thread pointer points to a fixed offset from the start of the executable's TLS segment. The offset is 0x7000 for PowerPC and MIPS, which allows a signed 16-bit offset to reach 0x1000 of per-thread implementation data and 0xf000 of the application's TLS segment. The size and layout of the TCB isn't relevant to the static linker and might not be known. * A fixed TCB size. This is the format documented as "variant 1" in Ulrich Drepper's TLS spec. The thread pointer points to a 2-word TCB followed by the executable's TLS segment. The first word is always the DTV pointer. Used on ARM. The thread pointer must be aligned to the TLS segment's alignment, possibly creating alignment padding. * Variant 2. This format predates variant 1 and is also documented in Drepper's TLS spec. It allocates the executable's TLS segment before the thread pointer, apparently for backwards-compatibility. It's used on x86 and SPARC. Factor out an lld::elf::getTlsTpOffset() function for use in a follow-up patch for Android. The TcbSize/TlsTpOffset fields are only used in getTlsTpOffset, so replace them with a switch on Config->EMachine. Reviewers: espindola, ruiu, PkmX, jrtc27 Reviewed By: ruiu, PkmX, jrtc27 Subscribers: jyknight, emaste, sdardis, nemanjai, javed.absar, arichardson, kristof.beyls, kbarton, fedor.sergeev, atanasyan, PkmX, jsji, llvm-commits Differential Revision: https://reviews.llvm.org/D53905 llvm-svn: 345775
2018-11-01 04:53:17 +08:00
switch (config->emachine) {
[ELF][PPC] Allow PT_LOAD to have overlapping p_offset ranges This change affects the non-linker script case (precisely, when the `SECTIONS` command is not used). It deletes 3 alignments at PT_LOAD boundaries for the default case: the size of a powerpc64 binary can be decreased by at most 192kb. The technique can be ported to other targets. Let me demonstrate the idea with a maxPageSize=65536 example: When assigning the address to the first output section of a new PT_LOAD, if the end p_vaddr of the previous PT_LOAD is 0x10020, we advance to the next multiple of maxPageSize: 0x20000. The new PT_LOAD will thus have p_vaddr=0x20000. Because p_offset and p_vaddr are congruent modulo maxPageSize, p_offset will be 0x20000, leaving a p_offset gap [0x10020, 0x20000) in the output. Alternatively, if we advance to 0x20020, the new PT_LOAD will have p_vaddr=0x20020. We can pick either 0x10020 or 0x20020 for p_offset! Obviously 0x10020 is the choice because it leaves no gap. At runtime, p_vaddr will be rounded down by pagesize (65536 if pagesize=maxPageSize). This PT_LOAD will load additional initial contents from p_offset ranges [0x10000,0x10020), which will also be loaded by the previous PT_LOAD. This is fine if -z noseparate-code is in effect or if we are not transiting between executable and non-executable segments. ld.bfd -z noseparate-code leverages this technique to keep output small. This patch implements the technique in lld, which is mostly effective on targets with large defaultMaxPageSize (AArch64/MIPS/PPC: 65536). The 3 removed alignments can save almost 3*65536 bytes. Two places that rely on p_vaddr%pagesize = 0 have to be updated. 1) We used to round p_memsz(PT_GNU_RELRO) up to commonPageSize (defaults to 4096 on all targets). Now p_vaddr%commonPageSize may be non-zero. The updated formula takes account of that factor. 2) Our TP offsets formulae are only correct if p_vaddr%p_align = 0. Fix them. See the updated comments in InputSection.cpp for details. On targets that we enable the technique (only PPC64 now), we can potentially make `p_vaddr(PT_TLS)%p_align(PT_TLS) != 0` if `sh_addralign(.tdata) < sh_addralign(.tbss)` This exposes many problems in ld.so implementations, especially the offsets of dynamic TLS blocks. Known issues: FreeBSD 13.0-CURRENT rtld-elf (i386/amd64/powerpc/arm64) glibc (HEAD) i386 and x86_64 https://sourceware.org/bugzilla/show_bug.cgi?id=24606 musl<=1.1.22 on TLS Variant I architectures (aarch64/powerpc64/...) So, force p_vaddr%p_align = 0 by rounding dot up to p_align(PT_TLS). The technique will be enabled (with updated tests) for other targets in subsequent patches. Reviewed By: ruiu Differential Revision: https://reviews.llvm.org/D64906 llvm-svn: 369343
2019-08-20 16:34:25 +08:00
// Variant 1.
[ELF] Refactor per-target TLS layout configuration. NFC. Summary: There are really three different kinds of TLS layouts: * A fixed TLS-to-TP offset. On architectures like PowerPC, MIPS, and RISC-V, the thread pointer points to a fixed offset from the start of the executable's TLS segment. The offset is 0x7000 for PowerPC and MIPS, which allows a signed 16-bit offset to reach 0x1000 of per-thread implementation data and 0xf000 of the application's TLS segment. The size and layout of the TCB isn't relevant to the static linker and might not be known. * A fixed TCB size. This is the format documented as "variant 1" in Ulrich Drepper's TLS spec. The thread pointer points to a 2-word TCB followed by the executable's TLS segment. The first word is always the DTV pointer. Used on ARM. The thread pointer must be aligned to the TLS segment's alignment, possibly creating alignment padding. * Variant 2. This format predates variant 1 and is also documented in Drepper's TLS spec. It allocates the executable's TLS segment before the thread pointer, apparently for backwards-compatibility. It's used on x86 and SPARC. Factor out an lld::elf::getTlsTpOffset() function for use in a follow-up patch for Android. The TcbSize/TlsTpOffset fields are only used in getTlsTpOffset, so replace them with a switch on Config->EMachine. Reviewers: espindola, ruiu, PkmX, jrtc27 Reviewed By: ruiu, PkmX, jrtc27 Subscribers: jyknight, emaste, sdardis, nemanjai, javed.absar, arichardson, kristof.beyls, kbarton, fedor.sergeev, atanasyan, PkmX, jsji, llvm-commits Differential Revision: https://reviews.llvm.org/D53905 llvm-svn: 345775
2018-11-01 04:53:17 +08:00
case EM_ARM:
case EM_AARCH64:
[ELF][PPC] Allow PT_LOAD to have overlapping p_offset ranges This change affects the non-linker script case (precisely, when the `SECTIONS` command is not used). It deletes 3 alignments at PT_LOAD boundaries for the default case: the size of a powerpc64 binary can be decreased by at most 192kb. The technique can be ported to other targets. Let me demonstrate the idea with a maxPageSize=65536 example: When assigning the address to the first output section of a new PT_LOAD, if the end p_vaddr of the previous PT_LOAD is 0x10020, we advance to the next multiple of maxPageSize: 0x20000. The new PT_LOAD will thus have p_vaddr=0x20000. Because p_offset and p_vaddr are congruent modulo maxPageSize, p_offset will be 0x20000, leaving a p_offset gap [0x10020, 0x20000) in the output. Alternatively, if we advance to 0x20020, the new PT_LOAD will have p_vaddr=0x20020. We can pick either 0x10020 or 0x20020 for p_offset! Obviously 0x10020 is the choice because it leaves no gap. At runtime, p_vaddr will be rounded down by pagesize (65536 if pagesize=maxPageSize). This PT_LOAD will load additional initial contents from p_offset ranges [0x10000,0x10020), which will also be loaded by the previous PT_LOAD. This is fine if -z noseparate-code is in effect or if we are not transiting between executable and non-executable segments. ld.bfd -z noseparate-code leverages this technique to keep output small. This patch implements the technique in lld, which is mostly effective on targets with large defaultMaxPageSize (AArch64/MIPS/PPC: 65536). The 3 removed alignments can save almost 3*65536 bytes. Two places that rely on p_vaddr%pagesize = 0 have to be updated. 1) We used to round p_memsz(PT_GNU_RELRO) up to commonPageSize (defaults to 4096 on all targets). Now p_vaddr%commonPageSize may be non-zero. The updated formula takes account of that factor. 2) Our TP offsets formulae are only correct if p_vaddr%p_align = 0. Fix them. See the updated comments in InputSection.cpp for details. On targets that we enable the technique (only PPC64 now), we can potentially make `p_vaddr(PT_TLS)%p_align(PT_TLS) != 0` if `sh_addralign(.tdata) < sh_addralign(.tbss)` This exposes many problems in ld.so implementations, especially the offsets of dynamic TLS blocks. Known issues: FreeBSD 13.0-CURRENT rtld-elf (i386/amd64/powerpc/arm64) glibc (HEAD) i386 and x86_64 https://sourceware.org/bugzilla/show_bug.cgi?id=24606 musl<=1.1.22 on TLS Variant I architectures (aarch64/powerpc64/...) So, force p_vaddr%p_align = 0 by rounding dot up to p_align(PT_TLS). The technique will be enabled (with updated tests) for other targets in subsequent patches. Reviewed By: ruiu Differential Revision: https://reviews.llvm.org/D64906 llvm-svn: 369343
2019-08-20 16:34:25 +08:00
return s.getVA(0) + config->wordsize * 2 +
((tls->p_vaddr - config->wordsize * 2) & (tls->p_align - 1));
case EM_MIPS:
case EM_PPC:
[ELF] Refactor per-target TLS layout configuration. NFC. Summary: There are really three different kinds of TLS layouts: * A fixed TLS-to-TP offset. On architectures like PowerPC, MIPS, and RISC-V, the thread pointer points to a fixed offset from the start of the executable's TLS segment. The offset is 0x7000 for PowerPC and MIPS, which allows a signed 16-bit offset to reach 0x1000 of per-thread implementation data and 0xf000 of the application's TLS segment. The size and layout of the TCB isn't relevant to the static linker and might not be known. * A fixed TCB size. This is the format documented as "variant 1" in Ulrich Drepper's TLS spec. The thread pointer points to a 2-word TCB followed by the executable's TLS segment. The first word is always the DTV pointer. Used on ARM. The thread pointer must be aligned to the TLS segment's alignment, possibly creating alignment padding. * Variant 2. This format predates variant 1 and is also documented in Drepper's TLS spec. It allocates the executable's TLS segment before the thread pointer, apparently for backwards-compatibility. It's used on x86 and SPARC. Factor out an lld::elf::getTlsTpOffset() function for use in a follow-up patch for Android. The TcbSize/TlsTpOffset fields are only used in getTlsTpOffset, so replace them with a switch on Config->EMachine. Reviewers: espindola, ruiu, PkmX, jrtc27 Reviewed By: ruiu, PkmX, jrtc27 Subscribers: jyknight, emaste, sdardis, nemanjai, javed.absar, arichardson, kristof.beyls, kbarton, fedor.sergeev, atanasyan, PkmX, jsji, llvm-commits Differential Revision: https://reviews.llvm.org/D53905 llvm-svn: 345775
2018-11-01 04:53:17 +08:00
case EM_PPC64:
[ELF][PPC] Allow PT_LOAD to have overlapping p_offset ranges This change affects the non-linker script case (precisely, when the `SECTIONS` command is not used). It deletes 3 alignments at PT_LOAD boundaries for the default case: the size of a powerpc64 binary can be decreased by at most 192kb. The technique can be ported to other targets. Let me demonstrate the idea with a maxPageSize=65536 example: When assigning the address to the first output section of a new PT_LOAD, if the end p_vaddr of the previous PT_LOAD is 0x10020, we advance to the next multiple of maxPageSize: 0x20000. The new PT_LOAD will thus have p_vaddr=0x20000. Because p_offset and p_vaddr are congruent modulo maxPageSize, p_offset will be 0x20000, leaving a p_offset gap [0x10020, 0x20000) in the output. Alternatively, if we advance to 0x20020, the new PT_LOAD will have p_vaddr=0x20020. We can pick either 0x10020 or 0x20020 for p_offset! Obviously 0x10020 is the choice because it leaves no gap. At runtime, p_vaddr will be rounded down by pagesize (65536 if pagesize=maxPageSize). This PT_LOAD will load additional initial contents from p_offset ranges [0x10000,0x10020), which will also be loaded by the previous PT_LOAD. This is fine if -z noseparate-code is in effect or if we are not transiting between executable and non-executable segments. ld.bfd -z noseparate-code leverages this technique to keep output small. This patch implements the technique in lld, which is mostly effective on targets with large defaultMaxPageSize (AArch64/MIPS/PPC: 65536). The 3 removed alignments can save almost 3*65536 bytes. Two places that rely on p_vaddr%pagesize = 0 have to be updated. 1) We used to round p_memsz(PT_GNU_RELRO) up to commonPageSize (defaults to 4096 on all targets). Now p_vaddr%commonPageSize may be non-zero. The updated formula takes account of that factor. 2) Our TP offsets formulae are only correct if p_vaddr%p_align = 0. Fix them. See the updated comments in InputSection.cpp for details. On targets that we enable the technique (only PPC64 now), we can potentially make `p_vaddr(PT_TLS)%p_align(PT_TLS) != 0` if `sh_addralign(.tdata) < sh_addralign(.tbss)` This exposes many problems in ld.so implementations, especially the offsets of dynamic TLS blocks. Known issues: FreeBSD 13.0-CURRENT rtld-elf (i386/amd64/powerpc/arm64) glibc (HEAD) i386 and x86_64 https://sourceware.org/bugzilla/show_bug.cgi?id=24606 musl<=1.1.22 on TLS Variant I architectures (aarch64/powerpc64/...) So, force p_vaddr%p_align = 0 by rounding dot up to p_align(PT_TLS). The technique will be enabled (with updated tests) for other targets in subsequent patches. Reviewed By: ruiu Differential Revision: https://reviews.llvm.org/D64906 llvm-svn: 369343
2019-08-20 16:34:25 +08:00
// Adjusted Variant 1. TP is placed with a displacement of 0x7000, which is
// to allow a signed 16-bit offset to reach 0x1000 of TCB/thread-library
// data and 0xf000 of the program's TLS segment.
return s.getVA(0) + (tls->p_vaddr & (tls->p_align - 1)) - 0x7000;
case EM_RISCV:
[ELF][PPC] Allow PT_LOAD to have overlapping p_offset ranges This change affects the non-linker script case (precisely, when the `SECTIONS` command is not used). It deletes 3 alignments at PT_LOAD boundaries for the default case: the size of a powerpc64 binary can be decreased by at most 192kb. The technique can be ported to other targets. Let me demonstrate the idea with a maxPageSize=65536 example: When assigning the address to the first output section of a new PT_LOAD, if the end p_vaddr of the previous PT_LOAD is 0x10020, we advance to the next multiple of maxPageSize: 0x20000. The new PT_LOAD will thus have p_vaddr=0x20000. Because p_offset and p_vaddr are congruent modulo maxPageSize, p_offset will be 0x20000, leaving a p_offset gap [0x10020, 0x20000) in the output. Alternatively, if we advance to 0x20020, the new PT_LOAD will have p_vaddr=0x20020. We can pick either 0x10020 or 0x20020 for p_offset! Obviously 0x10020 is the choice because it leaves no gap. At runtime, p_vaddr will be rounded down by pagesize (65536 if pagesize=maxPageSize). This PT_LOAD will load additional initial contents from p_offset ranges [0x10000,0x10020), which will also be loaded by the previous PT_LOAD. This is fine if -z noseparate-code is in effect or if we are not transiting between executable and non-executable segments. ld.bfd -z noseparate-code leverages this technique to keep output small. This patch implements the technique in lld, which is mostly effective on targets with large defaultMaxPageSize (AArch64/MIPS/PPC: 65536). The 3 removed alignments can save almost 3*65536 bytes. Two places that rely on p_vaddr%pagesize = 0 have to be updated. 1) We used to round p_memsz(PT_GNU_RELRO) up to commonPageSize (defaults to 4096 on all targets). Now p_vaddr%commonPageSize may be non-zero. The updated formula takes account of that factor. 2) Our TP offsets formulae are only correct if p_vaddr%p_align = 0. Fix them. See the updated comments in InputSection.cpp for details. On targets that we enable the technique (only PPC64 now), we can potentially make `p_vaddr(PT_TLS)%p_align(PT_TLS) != 0` if `sh_addralign(.tdata) < sh_addralign(.tbss)` This exposes many problems in ld.so implementations, especially the offsets of dynamic TLS blocks. Known issues: FreeBSD 13.0-CURRENT rtld-elf (i386/amd64/powerpc/arm64) glibc (HEAD) i386 and x86_64 https://sourceware.org/bugzilla/show_bug.cgi?id=24606 musl<=1.1.22 on TLS Variant I architectures (aarch64/powerpc64/...) So, force p_vaddr%p_align = 0 by rounding dot up to p_align(PT_TLS). The technique will be enabled (with updated tests) for other targets in subsequent patches. Reviewed By: ruiu Differential Revision: https://reviews.llvm.org/D64906 llvm-svn: 369343
2019-08-20 16:34:25 +08:00
return s.getVA(0) + (tls->p_vaddr & (tls->p_align - 1));
// Variant 2.
case EM_HEXAGON:
case EM_SPARCV9:
[ELF][PPC] Allow PT_LOAD to have overlapping p_offset ranges This change affects the non-linker script case (precisely, when the `SECTIONS` command is not used). It deletes 3 alignments at PT_LOAD boundaries for the default case: the size of a powerpc64 binary can be decreased by at most 192kb. The technique can be ported to other targets. Let me demonstrate the idea with a maxPageSize=65536 example: When assigning the address to the first output section of a new PT_LOAD, if the end p_vaddr of the previous PT_LOAD is 0x10020, we advance to the next multiple of maxPageSize: 0x20000. The new PT_LOAD will thus have p_vaddr=0x20000. Because p_offset and p_vaddr are congruent modulo maxPageSize, p_offset will be 0x20000, leaving a p_offset gap [0x10020, 0x20000) in the output. Alternatively, if we advance to 0x20020, the new PT_LOAD will have p_vaddr=0x20020. We can pick either 0x10020 or 0x20020 for p_offset! Obviously 0x10020 is the choice because it leaves no gap. At runtime, p_vaddr will be rounded down by pagesize (65536 if pagesize=maxPageSize). This PT_LOAD will load additional initial contents from p_offset ranges [0x10000,0x10020), which will also be loaded by the previous PT_LOAD. This is fine if -z noseparate-code is in effect or if we are not transiting between executable and non-executable segments. ld.bfd -z noseparate-code leverages this technique to keep output small. This patch implements the technique in lld, which is mostly effective on targets with large defaultMaxPageSize (AArch64/MIPS/PPC: 65536). The 3 removed alignments can save almost 3*65536 bytes. Two places that rely on p_vaddr%pagesize = 0 have to be updated. 1) We used to round p_memsz(PT_GNU_RELRO) up to commonPageSize (defaults to 4096 on all targets). Now p_vaddr%commonPageSize may be non-zero. The updated formula takes account of that factor. 2) Our TP offsets formulae are only correct if p_vaddr%p_align = 0. Fix them. See the updated comments in InputSection.cpp for details. On targets that we enable the technique (only PPC64 now), we can potentially make `p_vaddr(PT_TLS)%p_align(PT_TLS) != 0` if `sh_addralign(.tdata) < sh_addralign(.tbss)` This exposes many problems in ld.so implementations, especially the offsets of dynamic TLS blocks. Known issues: FreeBSD 13.0-CURRENT rtld-elf (i386/amd64/powerpc/arm64) glibc (HEAD) i386 and x86_64 https://sourceware.org/bugzilla/show_bug.cgi?id=24606 musl<=1.1.22 on TLS Variant I architectures (aarch64/powerpc64/...) So, force p_vaddr%p_align = 0 by rounding dot up to p_align(PT_TLS). The technique will be enabled (with updated tests) for other targets in subsequent patches. Reviewed By: ruiu Differential Revision: https://reviews.llvm.org/D64906 llvm-svn: 369343
2019-08-20 16:34:25 +08:00
case EM_386:
case EM_X86_64:
return s.getVA(0) - tls->p_memsz -
((-tls->p_vaddr - tls->p_memsz) & (tls->p_align - 1));
[ELF] Refactor per-target TLS layout configuration. NFC. Summary: There are really three different kinds of TLS layouts: * A fixed TLS-to-TP offset. On architectures like PowerPC, MIPS, and RISC-V, the thread pointer points to a fixed offset from the start of the executable's TLS segment. The offset is 0x7000 for PowerPC and MIPS, which allows a signed 16-bit offset to reach 0x1000 of per-thread implementation data and 0xf000 of the application's TLS segment. The size and layout of the TCB isn't relevant to the static linker and might not be known. * A fixed TCB size. This is the format documented as "variant 1" in Ulrich Drepper's TLS spec. The thread pointer points to a 2-word TCB followed by the executable's TLS segment. The first word is always the DTV pointer. Used on ARM. The thread pointer must be aligned to the TLS segment's alignment, possibly creating alignment padding. * Variant 2. This format predates variant 1 and is also documented in Drepper's TLS spec. It allocates the executable's TLS segment before the thread pointer, apparently for backwards-compatibility. It's used on x86 and SPARC. Factor out an lld::elf::getTlsTpOffset() function for use in a follow-up patch for Android. The TcbSize/TlsTpOffset fields are only used in getTlsTpOffset, so replace them with a switch on Config->EMachine. Reviewers: espindola, ruiu, PkmX, jrtc27 Reviewed By: ruiu, PkmX, jrtc27 Subscribers: jyknight, emaste, sdardis, nemanjai, javed.absar, arichardson, kristof.beyls, kbarton, fedor.sergeev, atanasyan, PkmX, jsji, llvm-commits Differential Revision: https://reviews.llvm.org/D53905 llvm-svn: 345775
2018-11-01 04:53:17 +08:00
default:
llvm_unreachable("unhandled Config->EMachine");
}
}
LLD Support for Basic Block Sections This is part of the Propeller framework to do post link code layout optimizations. Please see the RFC here: https://groups.google.com/forum/#!msg/llvm-dev/ef3mKzAdJ7U/1shV64BYBAAJ and the detailed RFC doc here: https://github.com/google/llvm-propeller/blob/plo-dev/Propeller_RFC.pdf This patch adds lld support for basic block sections and performs relaxations after the basic blocks have been reordered. After the linker has reordered the basic block sections according to the desired sequence, it runs a relaxation pass to optimize jump instructions. Currently, the compiler emits the long form of all jump instructions. AMD64 ISA supports variants of jump instructions with one byte offset or a four byte offset. The compiler generates jump instructions with R_X86_64 32-bit PC relative relocations. We would like to use a new relocation type for these jump instructions as it makes it easy and accurate while relaxing these instructions. The relaxation pass does two things: First, it deletes all explicit fall-through direct jump instructions between adjacent basic blocks. This is done by discarding the tail of the basic block section. Second, If there are consecutive jump instructions, it checks if the first conditional jump can be inverted to convert the second into a fall through and delete the second. The jump instructions are relaxed by using jump instruction mods, something like relocations. These are used to modify the opcode of the jump instruction. Jump instruction mods contain three values, instruction offset, jump type and size. While writing this jump instruction out to the final binary, the linker uses the jump instruction mod to determine the opcode and the size of the modified jump instruction. These mods are required because the input object files are memory-mapped without write permissions and directly modifying the object files requires copying these sections. Copying a large number of basic block sections significantly bloats memory. Differential Revision: https://reviews.llvm.org/D68065
2020-04-07 21:48:18 +08:00
uint64_t InputSectionBase::getRelocTargetVA(const InputFile *file, RelType type,
int64_t a, uint64_t p,
const Symbol &sym, RelExpr expr) {
switch (expr) {
2017-03-26 12:10:43 +08:00
case R_ABS:
case R_DTPREL:
case R_RELAX_TLS_LD_TO_LE_ABS:
2017-03-26 12:10:43 +08:00
case R_RELAX_GOT_PC_NOPIC:
case R_RISCV_ADD:
return sym.getVA(a);
case R_ADDEND:
return a;
case R_ARM_SBREL:
return sym.getVA(a) - getARMStaticBase(sym);
2017-03-26 12:10:43 +08:00
case R_GOT:
case R_RELAX_TLS_GD_TO_IE_ABS:
return sym.getGotVA() + a;
2017-03-26 12:10:43 +08:00
case R_GOTONLY_PC:
return in.got->getVA() + a - p;
case R_GOTPLTONLY_PC:
return in.gotPlt->getVA() + a - p;
case R_GOTREL:
case R_PPC64_RELAX_TOC:
return sym.getVA(a) - in.got->getVA();
case R_GOTPLTREL:
return sym.getVA(a) - in.gotPlt->getVA();
case R_GOTPLT:
case R_RELAX_TLS_GD_TO_IE_GOTPLT:
return sym.getGotVA() + a - in.gotPlt->getVA();
case R_TLSLD_GOT_OFF:
2017-03-26 12:10:43 +08:00
case R_GOT_OFF:
case R_RELAX_TLS_GD_TO_IE_GOT_OFF:
return sym.getGotOffset() + a;
case R_AARCH64_GOT_PAGE_PC:
case R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC:
return getAArch64Page(sym.getGotVA() + a) - getAArch64Page(p);
case R_AARCH64_GOT_PAGE:
return sym.getGotVA() + a - getAArch64Page(in.got->getVA());
case R_GOT_PC:
2017-03-26 12:10:43 +08:00
case R_RELAX_TLS_GD_TO_IE:
return sym.getGotVA() + a - p;
2017-03-26 12:10:43 +08:00
case R_MIPS_GOTREL:
return sym.getVA(a) - in.mipsGot->getGp(file);
2017-03-26 12:10:43 +08:00
case R_MIPS_GOT_GP:
return in.mipsGot->getGp(file) + a;
2017-03-26 12:10:43 +08:00
case R_MIPS_GOT_GP_PC: {
// R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC type iif the target
// is _gp_disp symbol. In that case we should use the following
// formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at
// ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
// microMIPS variants of these relocations use slightly different
// expressions: AHL + GP - P + 3 for %lo() and AHL + GP - P - 1 for %hi()
// to correctly handle less-significant bit of the microMIPS symbol.
uint64_t v = in.mipsGot->getGp(file) + a - p;
if (type == R_MIPS_LO16 || type == R_MICROMIPS_LO16)
2017-03-26 12:10:43 +08:00
v += 4;
if (type == R_MICROMIPS_LO16 || type == R_MICROMIPS_HI16)
v -= 1;
2017-03-26 12:10:43 +08:00
return v;
}
case R_MIPS_GOT_LOCAL_PAGE:
// If relocation against MIPS local symbol requires GOT entry, this entry
// should be initialized by 'page address'. This address is high 16-bits
// of sum the symbol's value and the addend.
return in.mipsGot->getVA() + in.mipsGot->getPageEntryOffset(file, sym, a) -
in.mipsGot->getGp(file);
case R_MIPS_GOT_OFF:
case R_MIPS_GOT_OFF32:
// In case of MIPS if a GOT relocation has non-zero addend this addend
// should be applied to the GOT entry content not to the GOT entry offset.
// That is why we use separate expression type.
return in.mipsGot->getVA() + in.mipsGot->getSymEntryOffset(file, sym, a) -
in.mipsGot->getGp(file);
case R_MIPS_TLSGD:
return in.mipsGot->getVA() + in.mipsGot->getGlobalDynOffset(file, sym) -
in.mipsGot->getGp(file);
case R_MIPS_TLSLD:
return in.mipsGot->getVA() + in.mipsGot->getTlsIndexOffset(file) -
in.mipsGot->getGp(file);
case R_AARCH64_PAGE_PC: {
uint64_t val = sym.isUndefWeak() ? p + a : sym.getVA(a);
return getAArch64Page(val) - getAArch64Page(p);
}
case R_RISCV_PC_INDIRECT: {
if (const Relocation *hiRel = getRISCVPCRelHi20(&sym, a))
return getRelocTargetVA(file, hiRel->type, hiRel->addend, sym.getVA(),
*hiRel->sym, hiRel->expr);
return 0;
}
case R_PC:
case R_ARM_PCA: {
uint64_t dest;
if (expr == R_ARM_PCA)
// Some PC relative ARM (Thumb) relocations align down the place.
p = p & 0xfffffffc;
if (sym.isUndefWeak()) {
2017-03-26 12:10:43 +08:00
// On ARM and AArch64 a branch to an undefined weak resolves to the
// next instruction, otherwise the place.
if (config->emachine == EM_ARM)
dest = getARMUndefinedRelativeWeakVA(type, a, p);
else if (config->emachine == EM_AARCH64)
dest = getAArch64UndefinedRelativeWeakVA(type, a, p);
[PPC32] Improve the 32-bit PowerPC port Many -static/-no-pie/-shared/-pie applications linked against glibc or musl should work with this patch. This also helps FreeBSD PowerPC64 to migrate their lib32 (PR40888). * Fix default image base and max page size. * Support new-style Secure PLT (see below). Old-style BSS PLT is not implemented, so it is not suitable for FreeBSD rtld now because it doesn't support Secure PLT yet. * Support more initial relocation types: R_PPC_ADDR32, R_PPC_REL16*, R_PPC_LOCAL24PC, R_PPC_PLTREL24, and R_PPC_GOT16. The addend of R_PPC_PLTREL24 is special: it decides the call stub PLT type but it should be ignored for the computation of target symbol VA. * Support GNU ifunc * Support .glink used for lazy PLT resolution in glibc * Add a new thunk type: PPC32PltCallStub that is similar to PPC64PltCallStub. It is used by R_PPC_REL24 and R_PPC_PLTREL24. A PLT stub used in -fPIE/-fPIC usually loads an address relative to .got2+0x8000 (-fpie/-fpic code uses _GLOBAL_OFFSET_TABLE_ relative addresses). Two .got2 sections in two object files have different addresses, thus a PLT stub can't be shared by two object files. To handle this incompatibility, change the parameters of Thunk::isCompatibleWith to `const InputSection &, const Relocation &`. PowerPC psABI specified an old-style .plt (BSS PLT) that is both writable and executable. Linkers don't make separate RW- and RWE segments, which causes all initially writable memory (think .data) executable. This is a big security concern so a new PLT scheme (secure PLT) was developed to address the security issue. TLS will be implemented in D62940. glibc older than ~2012 requires .rela.dyn to include .rela.plt, it can not handle the DT_RELA+DT_RELASZ == DT_JMPREL case correctly. A hack (not included in this patch) in LinkerScript.cpp addOrphanSections() to work around the issue: if (Config->EMachine == EM_PPC) { // Older glibc assumes .rela.dyn includes .rela.plt Add(In.RelaDyn); if (In.RelaPlt->isLive() && !In.RelaPlt->Parent) In.RelaDyn->getParent()->addSection(In.RelaPlt); } Reviewed By: ruiu Differential Revision: https://reviews.llvm.org/D62464 llvm-svn: 362721
2019-06-07 01:03:00 +08:00
else if (config->emachine == EM_PPC)
dest = p;
else
dest = sym.getVA(a);
} else {
dest = sym.getVA(a);
2017-03-26 12:10:43 +08:00
}
return dest - p;
}
2017-03-26 12:10:43 +08:00
case R_PLT:
return sym.getPltVA() + a;
2017-03-26 12:10:43 +08:00
case R_PLT_PC:
case R_PPC64_CALL_PLT:
return sym.getPltVA() + a - p;
[PPC32] Improve the 32-bit PowerPC port Many -static/-no-pie/-shared/-pie applications linked against glibc or musl should work with this patch. This also helps FreeBSD PowerPC64 to migrate their lib32 (PR40888). * Fix default image base and max page size. * Support new-style Secure PLT (see below). Old-style BSS PLT is not implemented, so it is not suitable for FreeBSD rtld now because it doesn't support Secure PLT yet. * Support more initial relocation types: R_PPC_ADDR32, R_PPC_REL16*, R_PPC_LOCAL24PC, R_PPC_PLTREL24, and R_PPC_GOT16. The addend of R_PPC_PLTREL24 is special: it decides the call stub PLT type but it should be ignored for the computation of target symbol VA. * Support GNU ifunc * Support .glink used for lazy PLT resolution in glibc * Add a new thunk type: PPC32PltCallStub that is similar to PPC64PltCallStub. It is used by R_PPC_REL24 and R_PPC_PLTREL24. A PLT stub used in -fPIE/-fPIC usually loads an address relative to .got2+0x8000 (-fpie/-fpic code uses _GLOBAL_OFFSET_TABLE_ relative addresses). Two .got2 sections in two object files have different addresses, thus a PLT stub can't be shared by two object files. To handle this incompatibility, change the parameters of Thunk::isCompatibleWith to `const InputSection &, const Relocation &`. PowerPC psABI specified an old-style .plt (BSS PLT) that is both writable and executable. Linkers don't make separate RW- and RWE segments, which causes all initially writable memory (think .data) executable. This is a big security concern so a new PLT scheme (secure PLT) was developed to address the security issue. TLS will be implemented in D62940. glibc older than ~2012 requires .rela.dyn to include .rela.plt, it can not handle the DT_RELA+DT_RELASZ == DT_JMPREL case correctly. A hack (not included in this patch) in LinkerScript.cpp addOrphanSections() to work around the issue: if (Config->EMachine == EM_PPC) { // Older glibc assumes .rela.dyn includes .rela.plt Add(In.RelaDyn); if (In.RelaPlt->isLive() && !In.RelaPlt->Parent) In.RelaDyn->getParent()->addSection(In.RelaPlt); } Reviewed By: ruiu Differential Revision: https://reviews.llvm.org/D62464 llvm-svn: 362721
2019-06-07 01:03:00 +08:00
case R_PPC32_PLTREL:
// R_PPC_PLTREL24 uses the addend (usually 0 or 0x8000) to indicate r30
// stores _GLOBAL_OFFSET_TABLE_ or .got2+0x8000. The addend is ignored for
// target VA computation.
[PPC32] Improve the 32-bit PowerPC port Many -static/-no-pie/-shared/-pie applications linked against glibc or musl should work with this patch. This also helps FreeBSD PowerPC64 to migrate their lib32 (PR40888). * Fix default image base and max page size. * Support new-style Secure PLT (see below). Old-style BSS PLT is not implemented, so it is not suitable for FreeBSD rtld now because it doesn't support Secure PLT yet. * Support more initial relocation types: R_PPC_ADDR32, R_PPC_REL16*, R_PPC_LOCAL24PC, R_PPC_PLTREL24, and R_PPC_GOT16. The addend of R_PPC_PLTREL24 is special: it decides the call stub PLT type but it should be ignored for the computation of target symbol VA. * Support GNU ifunc * Support .glink used for lazy PLT resolution in glibc * Add a new thunk type: PPC32PltCallStub that is similar to PPC64PltCallStub. It is used by R_PPC_REL24 and R_PPC_PLTREL24. A PLT stub used in -fPIE/-fPIC usually loads an address relative to .got2+0x8000 (-fpie/-fpic code uses _GLOBAL_OFFSET_TABLE_ relative addresses). Two .got2 sections in two object files have different addresses, thus a PLT stub can't be shared by two object files. To handle this incompatibility, change the parameters of Thunk::isCompatibleWith to `const InputSection &, const Relocation &`. PowerPC psABI specified an old-style .plt (BSS PLT) that is both writable and executable. Linkers don't make separate RW- and RWE segments, which causes all initially writable memory (think .data) executable. This is a big security concern so a new PLT scheme (secure PLT) was developed to address the security issue. TLS will be implemented in D62940. glibc older than ~2012 requires .rela.dyn to include .rela.plt, it can not handle the DT_RELA+DT_RELASZ == DT_JMPREL case correctly. A hack (not included in this patch) in LinkerScript.cpp addOrphanSections() to work around the issue: if (Config->EMachine == EM_PPC) { // Older glibc assumes .rela.dyn includes .rela.plt Add(In.RelaDyn); if (In.RelaPlt->isLive() && !In.RelaPlt->Parent) In.RelaDyn->getParent()->addSection(In.RelaPlt); } Reviewed By: ruiu Differential Revision: https://reviews.llvm.org/D62464 llvm-svn: 362721
2019-06-07 01:03:00 +08:00
return sym.getPltVA() - p;
case R_PPC64_CALL: {
uint64_t symVA = sym.getVA(a);
// If we have an undefined weak symbol, we might get here with a symbol
// address of zero. That could overflow, but the code must be unreachable,
// so don't bother doing anything at all.
if (!symVA)
return 0;
// PPC64 V2 ABI describes two entry points to a function. The global entry
// point is used for calls where the caller and callee (may) have different
// TOC base pointers and r2 needs to be modified to hold the TOC base for
// the callee. For local calls the caller and callee share the same
// TOC base and so the TOC pointer initialization code should be skipped by
// branching to the local entry point.
return symVA - p + getPPC64GlobalEntryToLocalEntryOffset(sym.stOther);
}
case R_PPC64_TOCBASE:
2017-03-26 12:10:43 +08:00
return getPPC64TocBase() + a;
case R_RELAX_GOT_PC:
case R_PPC64_RELAX_GOT_PC:
return sym.getVA(a) - p;
2017-03-26 12:10:43 +08:00
case R_RELAX_TLS_GD_TO_LE:
case R_RELAX_TLS_IE_TO_LE:
case R_RELAX_TLS_LD_TO_LE:
case R_TPREL:
// It is not very clear what to return if the symbol is undefined. With
// --noinhibit-exec, even a non-weak undefined reference may reach here.
// Just return A, which matches R_ABS, and the behavior of some dynamic
// loaders.
if (sym.isUndefined() || sym.isLazy())
return a;
return getTlsTpOffset(sym) + a;
2017-03-26 12:10:43 +08:00
case R_RELAX_TLS_GD_TO_LE_NEG:
case R_TPREL_NEG:
if (sym.isUndefined())
return a;
return -getTlsTpOffset(sym) + a;
2017-03-26 12:10:43 +08:00
case R_SIZE:
return sym.getSize() + a;
2017-03-26 12:10:43 +08:00
case R_TLSDESC:
return in.got->getGlobalDynAddr(sym) + a;
case R_TLSDESC_PC:
return in.got->getGlobalDynAddr(sym) + a - p;
case R_AARCH64_TLSDESC_PAGE:
return getAArch64Page(in.got->getGlobalDynAddr(sym) + a) -
2017-03-26 12:10:43 +08:00
getAArch64Page(p);
case R_TLSGD_GOT:
return in.got->getGlobalDynOffset(sym) + a;
case R_TLSGD_GOTPLT:
return in.got->getVA() + in.got->getGlobalDynOffset(sym) + a - in.gotPlt->getVA();
2017-03-26 12:10:43 +08:00
case R_TLSGD_PC:
return in.got->getGlobalDynAddr(sym) + a - p;
case R_TLSLD_GOTPLT:
return in.got->getVA() + in.got->getTlsIndexOff() + a - in.gotPlt->getVA();
case R_TLSLD_GOT:
return in.got->getTlsIndexOff() + a;
2017-03-26 12:10:43 +08:00
case R_TLSLD_PC:
return in.got->getTlsIndexVA() + a - p;
default:
llvm_unreachable("invalid expression");
}
}
// This function applies relocations to sections without SHF_ALLOC bit.
// Such sections are never mapped to memory at runtime. Debug sections are
// an example. Relocations in non-alloc sections are much easier to
// handle than in allocated sections because it will never need complex
2019-10-31 19:54:16 +08:00
// treatment such as GOT or PLT (because at runtime no one refers them).
// So, we handle relocations for non-alloc sections directly in this
// function as a performance optimization.
template <class ELFT, class RelTy>
void InputSection::relocateNonAlloc(uint8_t *buf, ArrayRef<RelTy> rels) {
2017-10-10 12:45:48 +08:00
const unsigned bits = sizeof(typename ELFT::uint) * 8;
[ELF] Resolve relocations in .debug_* referencing (discarded symbols or ICF folded section symbols) to tombstone values See D59553, https://lists.llvm.org/pipermail/llvm-dev/2020-May/141885.html and https://sourceware.org/pipermail/binutils/2020-May/111357.html for extensive discussions on a tombstone value. See http://www.dwarfstd.org/ShowIssue.php?issue=200609.1 (Reserve an address value for "not present") for a DWARF enhancement proposal. We resolve such relocations to a tombstone value to indicate that the address is invalid. This solves several problems (the normal behavior is to resolve the relocation to the addend): * For an empty function in a collected section, a pair of (0,0) can terminate .debug_loc and .debug_ranges (as of binutils 2.34, GNU ld resolves such a relocation to 1 to avoid the .debug_ranges issue) * If DW_AT_high_pc is sufficiently large, the address range can collide with a regular code range of low address (https://bugs.llvm.org/show_bug.cgi?id=41124 ) * If a text section is folded into another by ICF, we may leave entries in multiple CUs claiming ownership of the same range of code, which can confuse consumers. * Debug information associated with COMDAT sections can have problems similar to ICF, but is more complex - thus not addressed by this patch. For pre-DWARF-v5 .debug_loc and .debug_ranges, a pair of 0 can terminate entries (invalidating subsequent ranges). -1 is a reserved value with special meaning (base address selection entry) which can't be used either. Use -2 instead. For all other .debug_*, use UINT32_MAX for 32-bit targets and UINT64_MAX for 64-bit targets. In the code, we intentionally use `uint64_t tombstone = UINT64_MAX` for 32-bit targets as well: this matches SignExtend64 as used in `relocateAlloc`. (Actually UINT32_MAX does not work for R_386_32) Note 0, we only special case `target->symbolicRel` (R_X86_64_64, R_AARCH64_ABS64, R_PPC64_ADDR64), not short-range absolute relocations (e.g. R_X86_64_32). Only forms like DW_FORM_addr need to be special cased. They can hold an arbitrary address (must be 64-bit on a 64-bit target). (In theory, producers can make use of small code model to emit 32-bit relocations. This doesn't seem to be leveraged.) Note 1, we have to ignore the addend, because we don't want to resolve DW_AT_low_pc (which may have a non-zero addend) to -1+addend (wrap around to a low address): __attribute__((section(".text.x"))) void f1() { } __attribute__((section(".text.x"))) void f2() { } // DW_AT_low_pc has a non-zero addend Note 2, if the prevailing copy does not have debugging information while a non-prevailing copy has (partial debug build), we don't do extra work to attach debugging information to the prevailing definition. (clang has a lot of debug info optimizations that are on-by-default that assume the whole program is built with debug info). clang -c -ffunction-sections a.cc # prevailing copy has no debug info clang -c -ffunction-sections -g b.cc Reviewed By: dblaikie, avl, jhenderson Differential Revision: https://reviews.llvm.org/D81784
2020-06-24 02:06:39 +08:00
const bool isDebug = isDebugSection(*this);
const bool isDebugLocOrRanges =
isDebug && (name == ".debug_loc" || name == ".debug_ranges");
[ELF] Don't resolve a relocation in .debug_line referencing an ICF folded symbol to the tombstone value After D81784, we resolve a relocation in .debug_* referencing an ICF folded section symbol to a tombstone value. Doing this for .debug_line has a problem (https://reviews.llvm.org/D81784#2116925 ): .debug_line may describe folded lines as having addresses UINT64_MAX or some wraparound small addresses. ``` int foo(int x) { return x; // line 2 } int bar(int x) { return x; // line 6 } ``` ``` Address Line Column File ISA Discriminator Flags ------------------ ------ ------ ------ --- ------------- ------------- 0x00000000002016c0 1 0 1 0 0 is_stmt 0x00000000002016c7 2 9 1 0 0 is_stmt prologue_end 0x00000000002016ca 2 2 1 0 0 0x00000000002016cc 2 2 1 0 0 end_sequence // UINT64_MAX and wraparound small addresses 0xffffffffffffffff 5 0 1 0 0 is_stmt 0x0000000000000006 6 9 1 0 0 is_stmt prologue_end 0x0000000000000009 6 2 1 0 0 0x000000000000000b 6 2 1 0 0 end_sequence 0x00000000002016d0 9 0 1 0 0 is_stmt 0x00000000002016df 10 6 1 0 0 is_stmt prologue_end 0x00000000002016e6 11 11 1 0 0 is_stmt ... ``` These entries can confuse debuggers: gdb before 2020-07-01 (binutils-gdb a8caed5d7faa639a1e6769eba551d15d8ddd9510 "Recognize -1 as a tombstone value in .debug_line") (can't continue due to a breakpoint in an invalid region of memory): ``` Warning: Cannot insert breakpoint 1. Cannot access memory at address 0x6 ``` lldb (breakpoint has no effect): ``` (lldb) b 6 Breakpoint 1: no locations (pending). WARNING: Unable to resolve breakpoint to any actual locations. ``` This patch special cases .debug_line to not use the tombstone value, restoring the previous behavior: .debug_line will have entries with the same addresses (ICF) but different line numbers. A breakpoint on line 2 or 6 will trigger on both functions. Reviewed By: dblaikie, jhenderson Differential Revision: https://reviews.llvm.org/D82828
2020-07-02 04:37:20 +08:00
const bool isDebugLine = isDebug && name == ".debug_line";
Optional<uint64_t> tombstone;
for (const auto &patAndValue : llvm::reverse(config->deadRelocInNonAlloc))
if (patAndValue.first.match(this->name)) {
tombstone = patAndValue.second;
break;
}
2017-10-10 12:45:48 +08:00
for (const RelTy &rel : rels) {
RelType type = rel.getType(config->isMips64EL);
// GCC 8.0 or earlier have a bug that they emit R_386_GOTPC relocations
// against _GLOBAL_OFFSET_TABLE_ for .debug_info. The bug has been fixed
// in 2017 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82630), but we
// need to keep this bug-compatible code for a while.
if (config->emachine == EM_386 && type == R_386_GOTPC)
continue;
uint64_t offset = rel.r_offset;
uint8_t *bufLoc = buf + offset;
int64_t addend = getAddend<ELFT>(rel);
if (!RelTy::IsRela)
addend += target->getImplicitAddend(bufLoc, type);
Symbol &sym = getFile<ELFT>()->getRelocTargetSym(rel);
RelExpr expr = target->getRelExpr(type, sym, bufLoc);
if (expr == R_NONE)
continue;
LLD Support for Basic Block Sections This is part of the Propeller framework to do post link code layout optimizations. Please see the RFC here: https://groups.google.com/forum/#!msg/llvm-dev/ef3mKzAdJ7U/1shV64BYBAAJ and the detailed RFC doc here: https://github.com/google/llvm-propeller/blob/plo-dev/Propeller_RFC.pdf This patch adds lld support for basic block sections and performs relaxations after the basic blocks have been reordered. After the linker has reordered the basic block sections according to the desired sequence, it runs a relaxation pass to optimize jump instructions. Currently, the compiler emits the long form of all jump instructions. AMD64 ISA supports variants of jump instructions with one byte offset or a four byte offset. The compiler generates jump instructions with R_X86_64 32-bit PC relative relocations. We would like to use a new relocation type for these jump instructions as it makes it easy and accurate while relaxing these instructions. The relaxation pass does two things: First, it deletes all explicit fall-through direct jump instructions between adjacent basic blocks. This is done by discarding the tail of the basic block section. Second, If there are consecutive jump instructions, it checks if the first conditional jump can be inverted to convert the second into a fall through and delete the second. The jump instructions are relaxed by using jump instruction mods, something like relocations. These are used to modify the opcode of the jump instruction. Jump instruction mods contain three values, instruction offset, jump type and size. While writing this jump instruction out to the final binary, the linker uses the jump instruction mod to determine the opcode and the size of the modified jump instruction. These mods are required because the input object files are memory-mapped without write permissions and directly modifying the object files requires copying these sections. Copying a large number of basic block sections significantly bloats memory. Differential Revision: https://reviews.llvm.org/D68065
2020-04-07 21:48:18 +08:00
if (expr == R_SIZE) {
target->relocateNoSym(bufLoc, type,
SignExtend64<bits>(sym.getSize() + addend));
continue;
}
if (expr != R_ABS && expr != R_DTPREL && expr != R_RISCV_ADD) {
std::string msg = getLocation<ELFT>(offset) +
": has non-ABS relocation " + toString(type) +
" against symbol '" + toString(sym) + "'";
if (expr != R_PC && expr != R_ARM_PCA) {
error(msg);
return;
}
// If the control reaches here, we found a PC-relative relocation in a
// non-ALLOC section. Since non-ALLOC section is not loaded into memory
// at runtime, the notion of PC-relative doesn't make sense here. So,
// this is a usage error. However, GNU linkers historically accept such
// relocations without any errors and relocate them as if they were at
// address 0. For bug-compatibilty, we accept them with warnings. We
// know Steel Bank Common Lisp as of 2018 have this bug.
warn(msg);
target->relocateNoSym(
bufLoc, type,
SignExtend64<bits>(sym.getVA(addend - offset - outSecOff)));
continue;
}
if (tombstone ||
(isDebug && (type == target->symbolicRel || expr == R_DTPREL))) {
[ELF] Resolve relocations in .debug_* referencing (discarded symbols or ICF folded section symbols) to tombstone values See D59553, https://lists.llvm.org/pipermail/llvm-dev/2020-May/141885.html and https://sourceware.org/pipermail/binutils/2020-May/111357.html for extensive discussions on a tombstone value. See http://www.dwarfstd.org/ShowIssue.php?issue=200609.1 (Reserve an address value for "not present") for a DWARF enhancement proposal. We resolve such relocations to a tombstone value to indicate that the address is invalid. This solves several problems (the normal behavior is to resolve the relocation to the addend): * For an empty function in a collected section, a pair of (0,0) can terminate .debug_loc and .debug_ranges (as of binutils 2.34, GNU ld resolves such a relocation to 1 to avoid the .debug_ranges issue) * If DW_AT_high_pc is sufficiently large, the address range can collide with a regular code range of low address (https://bugs.llvm.org/show_bug.cgi?id=41124 ) * If a text section is folded into another by ICF, we may leave entries in multiple CUs claiming ownership of the same range of code, which can confuse consumers. * Debug information associated with COMDAT sections can have problems similar to ICF, but is more complex - thus not addressed by this patch. For pre-DWARF-v5 .debug_loc and .debug_ranges, a pair of 0 can terminate entries (invalidating subsequent ranges). -1 is a reserved value with special meaning (base address selection entry) which can't be used either. Use -2 instead. For all other .debug_*, use UINT32_MAX for 32-bit targets and UINT64_MAX for 64-bit targets. In the code, we intentionally use `uint64_t tombstone = UINT64_MAX` for 32-bit targets as well: this matches SignExtend64 as used in `relocateAlloc`. (Actually UINT32_MAX does not work for R_386_32) Note 0, we only special case `target->symbolicRel` (R_X86_64_64, R_AARCH64_ABS64, R_PPC64_ADDR64), not short-range absolute relocations (e.g. R_X86_64_32). Only forms like DW_FORM_addr need to be special cased. They can hold an arbitrary address (must be 64-bit on a 64-bit target). (In theory, producers can make use of small code model to emit 32-bit relocations. This doesn't seem to be leveraged.) Note 1, we have to ignore the addend, because we don't want to resolve DW_AT_low_pc (which may have a non-zero addend) to -1+addend (wrap around to a low address): __attribute__((section(".text.x"))) void f1() { } __attribute__((section(".text.x"))) void f2() { } // DW_AT_low_pc has a non-zero addend Note 2, if the prevailing copy does not have debugging information while a non-prevailing copy has (partial debug build), we don't do extra work to attach debugging information to the prevailing definition. (clang has a lot of debug info optimizations that are on-by-default that assume the whole program is built with debug info). clang -c -ffunction-sections a.cc # prevailing copy has no debug info clang -c -ffunction-sections -g b.cc Reviewed By: dblaikie, avl, jhenderson Differential Revision: https://reviews.llvm.org/D81784
2020-06-24 02:06:39 +08:00
// Resolve relocations in .debug_* referencing (discarded symbols or ICF
// folded section symbols) to a tombstone value. Resolving to addend is
// unsatisfactory because the result address range may collide with a
// valid range of low address, or leave multiple CUs claiming ownership of
// the same range of code, which may confuse consumers.
//
// To address the problems, we use -1 as a tombstone value for most
// .debug_* sections. We have to ignore the addend because we don't want
// to resolve an address attribute (which may have a non-zero addend) to
// -1+addend (wrap around to a low address).
//
[ELF] Resolve R_DTPREL in .debug_* referencing discarded symbols to -1 The location of a TLS variable is encoded as a DW_OP_const4u/DW_OP_const8u followed by a DW_OP_push_tls_address (or DW_OP_GNU_push_tls_address https://sourceware.org/bugzilla/show_bug.cgi?id=11616 ). This change follows up to D81784 and makes relocations types generalized as R_DTPREL (e.g. R_X86_64_DTPOFF{32,64}, R_PPC64_DTPREL64) use -1 as the tombstone value as well. This works for both TLS Variant I and Variant II architectures. * arm: .long tls(tlsldo) # not working currently (R_ARM_TLS_LDO32 is R_ABS) * mips64: .dtpreldword tls+32768 * ppc64: .quad tls@DTPREL+0x8000 * riscv: neither GCC nor clang has implemented DW_AT_location. It is likely .long/.quad tls@dtprel+0x800 * x86-32: .long tls@DTPOFF * x86-64: .long tls@DTPOFF; .quad tls@DTPOFF tls has a non-negative st_value, so such relocations (st_value+addend) never resolve to -1 in a normal (not discarded) case. ``` // clang -fuse-ld=lld -g -ffunction-sections a.c -Wl,--gc-sections // foo and tls will be discarded by --gc-sections. // DW_AT_location [DW_FORM_exprloc] (DW_OP_const8u 0xffffffffffffffff, DW_OP_GNU_push_tls_address) thread_local int tls; int foo() { return ++tls; } int main() {} ``` Also, drop logic added in D26201 intended to address PR30793. It added a test (gc-debuginfo-tls.s) using a non-SHF_ALLOC section and a local symbol, which does not reflect the intended scenario: a relocation in a SHF_ALLOC section referencing a discarded non-local symbol. For such a non .debug_* section, just emit an error. Reviewed By: jhenderson Differential Revision: https://reviews.llvm.org/D82899
2020-07-04 00:50:30 +08:00
// R_DTPREL type relocations represent an offset into the dynamic thread
// vector. The computed value is st_value plus a non-negative offset.
// Negative values are invalid, so -1 can be used as the tombstone value.
//
[ELF] Resolve relocations in .debug_* referencing (discarded symbols or ICF folded section symbols) to tombstone values See D59553, https://lists.llvm.org/pipermail/llvm-dev/2020-May/141885.html and https://sourceware.org/pipermail/binutils/2020-May/111357.html for extensive discussions on a tombstone value. See http://www.dwarfstd.org/ShowIssue.php?issue=200609.1 (Reserve an address value for "not present") for a DWARF enhancement proposal. We resolve such relocations to a tombstone value to indicate that the address is invalid. This solves several problems (the normal behavior is to resolve the relocation to the addend): * For an empty function in a collected section, a pair of (0,0) can terminate .debug_loc and .debug_ranges (as of binutils 2.34, GNU ld resolves such a relocation to 1 to avoid the .debug_ranges issue) * If DW_AT_high_pc is sufficiently large, the address range can collide with a regular code range of low address (https://bugs.llvm.org/show_bug.cgi?id=41124 ) * If a text section is folded into another by ICF, we may leave entries in multiple CUs claiming ownership of the same range of code, which can confuse consumers. * Debug information associated with COMDAT sections can have problems similar to ICF, but is more complex - thus not addressed by this patch. For pre-DWARF-v5 .debug_loc and .debug_ranges, a pair of 0 can terminate entries (invalidating subsequent ranges). -1 is a reserved value with special meaning (base address selection entry) which can't be used either. Use -2 instead. For all other .debug_*, use UINT32_MAX for 32-bit targets and UINT64_MAX for 64-bit targets. In the code, we intentionally use `uint64_t tombstone = UINT64_MAX` for 32-bit targets as well: this matches SignExtend64 as used in `relocateAlloc`. (Actually UINT32_MAX does not work for R_386_32) Note 0, we only special case `target->symbolicRel` (R_X86_64_64, R_AARCH64_ABS64, R_PPC64_ADDR64), not short-range absolute relocations (e.g. R_X86_64_32). Only forms like DW_FORM_addr need to be special cased. They can hold an arbitrary address (must be 64-bit on a 64-bit target). (In theory, producers can make use of small code model to emit 32-bit relocations. This doesn't seem to be leveraged.) Note 1, we have to ignore the addend, because we don't want to resolve DW_AT_low_pc (which may have a non-zero addend) to -1+addend (wrap around to a low address): __attribute__((section(".text.x"))) void f1() { } __attribute__((section(".text.x"))) void f2() { } // DW_AT_low_pc has a non-zero addend Note 2, if the prevailing copy does not have debugging information while a non-prevailing copy has (partial debug build), we don't do extra work to attach debugging information to the prevailing definition. (clang has a lot of debug info optimizations that are on-by-default that assume the whole program is built with debug info). clang -c -ffunction-sections a.cc # prevailing copy has no debug info clang -c -ffunction-sections -g b.cc Reviewed By: dblaikie, avl, jhenderson Differential Revision: https://reviews.llvm.org/D81784
2020-06-24 02:06:39 +08:00
// If the referenced symbol is discarded (made Undefined), or the
// section defining the referenced symbol is garbage collected,
// sym.getOutputSection() is nullptr. `ds->section->repl != ds->section`
[ELF] Don't resolve a relocation in .debug_line referencing an ICF folded symbol to the tombstone value After D81784, we resolve a relocation in .debug_* referencing an ICF folded section symbol to a tombstone value. Doing this for .debug_line has a problem (https://reviews.llvm.org/D81784#2116925 ): .debug_line may describe folded lines as having addresses UINT64_MAX or some wraparound small addresses. ``` int foo(int x) { return x; // line 2 } int bar(int x) { return x; // line 6 } ``` ``` Address Line Column File ISA Discriminator Flags ------------------ ------ ------ ------ --- ------------- ------------- 0x00000000002016c0 1 0 1 0 0 is_stmt 0x00000000002016c7 2 9 1 0 0 is_stmt prologue_end 0x00000000002016ca 2 2 1 0 0 0x00000000002016cc 2 2 1 0 0 end_sequence // UINT64_MAX and wraparound small addresses 0xffffffffffffffff 5 0 1 0 0 is_stmt 0x0000000000000006 6 9 1 0 0 is_stmt prologue_end 0x0000000000000009 6 2 1 0 0 0x000000000000000b 6 2 1 0 0 end_sequence 0x00000000002016d0 9 0 1 0 0 is_stmt 0x00000000002016df 10 6 1 0 0 is_stmt prologue_end 0x00000000002016e6 11 11 1 0 0 is_stmt ... ``` These entries can confuse debuggers: gdb before 2020-07-01 (binutils-gdb a8caed5d7faa639a1e6769eba551d15d8ddd9510 "Recognize -1 as a tombstone value in .debug_line") (can't continue due to a breakpoint in an invalid region of memory): ``` Warning: Cannot insert breakpoint 1. Cannot access memory at address 0x6 ``` lldb (breakpoint has no effect): ``` (lldb) b 6 Breakpoint 1: no locations (pending). WARNING: Unable to resolve breakpoint to any actual locations. ``` This patch special cases .debug_line to not use the tombstone value, restoring the previous behavior: .debug_line will have entries with the same addresses (ICF) but different line numbers. A breakpoint on line 2 or 6 will trigger on both functions. Reviewed By: dblaikie, jhenderson Differential Revision: https://reviews.llvm.org/D82828
2020-07-02 04:37:20 +08:00
// catches the ICF folded case. However, resolving a relocation in
// .debug_line to -1 would stop debugger users from setting breakpoints on
// the folded-in function, so exclude .debug_line.
[ELF] Resolve relocations in .debug_* referencing (discarded symbols or ICF folded section symbols) to tombstone values See D59553, https://lists.llvm.org/pipermail/llvm-dev/2020-May/141885.html and https://sourceware.org/pipermail/binutils/2020-May/111357.html for extensive discussions on a tombstone value. See http://www.dwarfstd.org/ShowIssue.php?issue=200609.1 (Reserve an address value for "not present") for a DWARF enhancement proposal. We resolve such relocations to a tombstone value to indicate that the address is invalid. This solves several problems (the normal behavior is to resolve the relocation to the addend): * For an empty function in a collected section, a pair of (0,0) can terminate .debug_loc and .debug_ranges (as of binutils 2.34, GNU ld resolves such a relocation to 1 to avoid the .debug_ranges issue) * If DW_AT_high_pc is sufficiently large, the address range can collide with a regular code range of low address (https://bugs.llvm.org/show_bug.cgi?id=41124 ) * If a text section is folded into another by ICF, we may leave entries in multiple CUs claiming ownership of the same range of code, which can confuse consumers. * Debug information associated with COMDAT sections can have problems similar to ICF, but is more complex - thus not addressed by this patch. For pre-DWARF-v5 .debug_loc and .debug_ranges, a pair of 0 can terminate entries (invalidating subsequent ranges). -1 is a reserved value with special meaning (base address selection entry) which can't be used either. Use -2 instead. For all other .debug_*, use UINT32_MAX for 32-bit targets and UINT64_MAX for 64-bit targets. In the code, we intentionally use `uint64_t tombstone = UINT64_MAX` for 32-bit targets as well: this matches SignExtend64 as used in `relocateAlloc`. (Actually UINT32_MAX does not work for R_386_32) Note 0, we only special case `target->symbolicRel` (R_X86_64_64, R_AARCH64_ABS64, R_PPC64_ADDR64), not short-range absolute relocations (e.g. R_X86_64_32). Only forms like DW_FORM_addr need to be special cased. They can hold an arbitrary address (must be 64-bit on a 64-bit target). (In theory, producers can make use of small code model to emit 32-bit relocations. This doesn't seem to be leveraged.) Note 1, we have to ignore the addend, because we don't want to resolve DW_AT_low_pc (which may have a non-zero addend) to -1+addend (wrap around to a low address): __attribute__((section(".text.x"))) void f1() { } __attribute__((section(".text.x"))) void f2() { } // DW_AT_low_pc has a non-zero addend Note 2, if the prevailing copy does not have debugging information while a non-prevailing copy has (partial debug build), we don't do extra work to attach debugging information to the prevailing definition. (clang has a lot of debug info optimizations that are on-by-default that assume the whole program is built with debug info). clang -c -ffunction-sections a.cc # prevailing copy has no debug info clang -c -ffunction-sections -g b.cc Reviewed By: dblaikie, avl, jhenderson Differential Revision: https://reviews.llvm.org/D81784
2020-06-24 02:06:39 +08:00
//
// For pre-DWARF-v5 .debug_loc and .debug_ranges, -1 is a reserved value
[ELF] Change tombstone values to (.debug_ranges/.debug_loc) 1 and (other .debug_*) 0 tl;dr See D81784 for the 'tombstone value' concept. This patch changes our behavior to be almost the same as GNU ld (except that we also use 1 for .debug_loc): * .debug_ranges & .debug_loc: 1 (LLD<11: 0+addend; GNU ld uses 1 for .debug_ranges) * .debug_*: 0 (LLD<11: 0+addend; GNU ld uses 0; future LLD: -1) We make the tweaks because: 1) The new tombstone is novel and needs more time to be adopted by consumers before it's the default. 2) The old (gold) strategy had problems with zero-length functions - so rather than going back that, we're going to the GNU ld strategy which doesn't have that problem. 3) One slight tweak to (2) is to apply the .debug_ranges workaround to .debug_loc for the same reasons it applies to debug_ranges - to avoid terminating lists early. ----- http://lists.llvm.org/pipermail/llvm-dev/2020-July/143482.html The tombstone value -1 in .debug_line caused problems to lldb (fixed by D83957; will be included in 11.0.0) and breakpad (fixed by https://crrev.com/c/2321300). It may potentially affects other DWARF consumers. For .debug_ranges & .debug_loc: 1, an argument preferring 1 (GNU ld for .debug_ranges) over -2 is that: ``` {-1, -2} <<< base address selection entry {0, length} <<< address range ``` may create a situation where low_pc is greater than high_pc. So we use 1, the GNU ld behavior for .debug_ranges For other .debug_* sections, there haven't been many reports. One issue is that bloaty (src/dwarf.cc) can incorrectly count address ranges in .debug_ranges . To reduce similar disruption, this patch changes the tombstone values to be similar to GNU ld. This does mean another behavior change to the default trunk behavior. Sorry about it. The default trunk behavior will be similar to release/11.x while we work on a transition plan for LLD users. Reviewed By: dblaikie, echristo Differential Revision: https://reviews.llvm.org/D84825
2020-08-07 03:34:16 +08:00
// (base address selection entry), use 1 (which is used by GNU ld for
// .debug_ranges).
//
// TODO To reduce disruption, we use 0 instead of -1 as the tombstone
// value. Enable -1 in a future release.
[ELF] Resolve relocations in .debug_* referencing (discarded symbols or ICF folded section symbols) to tombstone values See D59553, https://lists.llvm.org/pipermail/llvm-dev/2020-May/141885.html and https://sourceware.org/pipermail/binutils/2020-May/111357.html for extensive discussions on a tombstone value. See http://www.dwarfstd.org/ShowIssue.php?issue=200609.1 (Reserve an address value for "not present") for a DWARF enhancement proposal. We resolve such relocations to a tombstone value to indicate that the address is invalid. This solves several problems (the normal behavior is to resolve the relocation to the addend): * For an empty function in a collected section, a pair of (0,0) can terminate .debug_loc and .debug_ranges (as of binutils 2.34, GNU ld resolves such a relocation to 1 to avoid the .debug_ranges issue) * If DW_AT_high_pc is sufficiently large, the address range can collide with a regular code range of low address (https://bugs.llvm.org/show_bug.cgi?id=41124 ) * If a text section is folded into another by ICF, we may leave entries in multiple CUs claiming ownership of the same range of code, which can confuse consumers. * Debug information associated with COMDAT sections can have problems similar to ICF, but is more complex - thus not addressed by this patch. For pre-DWARF-v5 .debug_loc and .debug_ranges, a pair of 0 can terminate entries (invalidating subsequent ranges). -1 is a reserved value with special meaning (base address selection entry) which can't be used either. Use -2 instead. For all other .debug_*, use UINT32_MAX for 32-bit targets and UINT64_MAX for 64-bit targets. In the code, we intentionally use `uint64_t tombstone = UINT64_MAX` for 32-bit targets as well: this matches SignExtend64 as used in `relocateAlloc`. (Actually UINT32_MAX does not work for R_386_32) Note 0, we only special case `target->symbolicRel` (R_X86_64_64, R_AARCH64_ABS64, R_PPC64_ADDR64), not short-range absolute relocations (e.g. R_X86_64_32). Only forms like DW_FORM_addr need to be special cased. They can hold an arbitrary address (must be 64-bit on a 64-bit target). (In theory, producers can make use of small code model to emit 32-bit relocations. This doesn't seem to be leveraged.) Note 1, we have to ignore the addend, because we don't want to resolve DW_AT_low_pc (which may have a non-zero addend) to -1+addend (wrap around to a low address): __attribute__((section(".text.x"))) void f1() { } __attribute__((section(".text.x"))) void f2() { } // DW_AT_low_pc has a non-zero addend Note 2, if the prevailing copy does not have debugging information while a non-prevailing copy has (partial debug build), we don't do extra work to attach debugging information to the prevailing definition. (clang has a lot of debug info optimizations that are on-by-default that assume the whole program is built with debug info). clang -c -ffunction-sections a.cc # prevailing copy has no debug info clang -c -ffunction-sections -g b.cc Reviewed By: dblaikie, avl, jhenderson Differential Revision: https://reviews.llvm.org/D81784
2020-06-24 02:06:39 +08:00
auto *ds = dyn_cast<Defined>(&sym);
[ELF] Don't resolve a relocation in .debug_line referencing an ICF folded symbol to the tombstone value After D81784, we resolve a relocation in .debug_* referencing an ICF folded section symbol to a tombstone value. Doing this for .debug_line has a problem (https://reviews.llvm.org/D81784#2116925 ): .debug_line may describe folded lines as having addresses UINT64_MAX or some wraparound small addresses. ``` int foo(int x) { return x; // line 2 } int bar(int x) { return x; // line 6 } ``` ``` Address Line Column File ISA Discriminator Flags ------------------ ------ ------ ------ --- ------------- ------------- 0x00000000002016c0 1 0 1 0 0 is_stmt 0x00000000002016c7 2 9 1 0 0 is_stmt prologue_end 0x00000000002016ca 2 2 1 0 0 0x00000000002016cc 2 2 1 0 0 end_sequence // UINT64_MAX and wraparound small addresses 0xffffffffffffffff 5 0 1 0 0 is_stmt 0x0000000000000006 6 9 1 0 0 is_stmt prologue_end 0x0000000000000009 6 2 1 0 0 0x000000000000000b 6 2 1 0 0 end_sequence 0x00000000002016d0 9 0 1 0 0 is_stmt 0x00000000002016df 10 6 1 0 0 is_stmt prologue_end 0x00000000002016e6 11 11 1 0 0 is_stmt ... ``` These entries can confuse debuggers: gdb before 2020-07-01 (binutils-gdb a8caed5d7faa639a1e6769eba551d15d8ddd9510 "Recognize -1 as a tombstone value in .debug_line") (can't continue due to a breakpoint in an invalid region of memory): ``` Warning: Cannot insert breakpoint 1. Cannot access memory at address 0x6 ``` lldb (breakpoint has no effect): ``` (lldb) b 6 Breakpoint 1: no locations (pending). WARNING: Unable to resolve breakpoint to any actual locations. ``` This patch special cases .debug_line to not use the tombstone value, restoring the previous behavior: .debug_line will have entries with the same addresses (ICF) but different line numbers. A breakpoint on line 2 or 6 will trigger on both functions. Reviewed By: dblaikie, jhenderson Differential Revision: https://reviews.llvm.org/D82828
2020-07-02 04:37:20 +08:00
if (!sym.getOutputSection() ||
(ds && ds->section->repl != ds->section && !isDebugLine)) {
// If -z dead-reloc-in-nonalloc= is specified, respect it.
[ELF] Change tombstone values to (.debug_ranges/.debug_loc) 1 and (other .debug_*) 0 tl;dr See D81784 for the 'tombstone value' concept. This patch changes our behavior to be almost the same as GNU ld (except that we also use 1 for .debug_loc): * .debug_ranges & .debug_loc: 1 (LLD<11: 0+addend; GNU ld uses 1 for .debug_ranges) * .debug_*: 0 (LLD<11: 0+addend; GNU ld uses 0; future LLD: -1) We make the tweaks because: 1) The new tombstone is novel and needs more time to be adopted by consumers before it's the default. 2) The old (gold) strategy had problems with zero-length functions - so rather than going back that, we're going to the GNU ld strategy which doesn't have that problem. 3) One slight tweak to (2) is to apply the .debug_ranges workaround to .debug_loc for the same reasons it applies to debug_ranges - to avoid terminating lists early. ----- http://lists.llvm.org/pipermail/llvm-dev/2020-July/143482.html The tombstone value -1 in .debug_line caused problems to lldb (fixed by D83957; will be included in 11.0.0) and breakpad (fixed by https://crrev.com/c/2321300). It may potentially affects other DWARF consumers. For .debug_ranges & .debug_loc: 1, an argument preferring 1 (GNU ld for .debug_ranges) over -2 is that: ``` {-1, -2} <<< base address selection entry {0, length} <<< address range ``` may create a situation where low_pc is greater than high_pc. So we use 1, the GNU ld behavior for .debug_ranges For other .debug_* sections, there haven't been many reports. One issue is that bloaty (src/dwarf.cc) can incorrectly count address ranges in .debug_ranges . To reduce similar disruption, this patch changes the tombstone values to be similar to GNU ld. This does mean another behavior change to the default trunk behavior. Sorry about it. The default trunk behavior will be similar to release/11.x while we work on a transition plan for LLD users. Reviewed By: dblaikie, echristo Differential Revision: https://reviews.llvm.org/D84825
2020-08-07 03:34:16 +08:00
const uint64_t value = tombstone ? SignExtend64<bits>(*tombstone)
: (isDebugLocOrRanges ? 1 : 0);
target->relocateNoSym(bufLoc, type, value);
[ELF] Resolve relocations in .debug_* referencing (discarded symbols or ICF folded section symbols) to tombstone values See D59553, https://lists.llvm.org/pipermail/llvm-dev/2020-May/141885.html and https://sourceware.org/pipermail/binutils/2020-May/111357.html for extensive discussions on a tombstone value. See http://www.dwarfstd.org/ShowIssue.php?issue=200609.1 (Reserve an address value for "not present") for a DWARF enhancement proposal. We resolve such relocations to a tombstone value to indicate that the address is invalid. This solves several problems (the normal behavior is to resolve the relocation to the addend): * For an empty function in a collected section, a pair of (0,0) can terminate .debug_loc and .debug_ranges (as of binutils 2.34, GNU ld resolves such a relocation to 1 to avoid the .debug_ranges issue) * If DW_AT_high_pc is sufficiently large, the address range can collide with a regular code range of low address (https://bugs.llvm.org/show_bug.cgi?id=41124 ) * If a text section is folded into another by ICF, we may leave entries in multiple CUs claiming ownership of the same range of code, which can confuse consumers. * Debug information associated with COMDAT sections can have problems similar to ICF, but is more complex - thus not addressed by this patch. For pre-DWARF-v5 .debug_loc and .debug_ranges, a pair of 0 can terminate entries (invalidating subsequent ranges). -1 is a reserved value with special meaning (base address selection entry) which can't be used either. Use -2 instead. For all other .debug_*, use UINT32_MAX for 32-bit targets and UINT64_MAX for 64-bit targets. In the code, we intentionally use `uint64_t tombstone = UINT64_MAX` for 32-bit targets as well: this matches SignExtend64 as used in `relocateAlloc`. (Actually UINT32_MAX does not work for R_386_32) Note 0, we only special case `target->symbolicRel` (R_X86_64_64, R_AARCH64_ABS64, R_PPC64_ADDR64), not short-range absolute relocations (e.g. R_X86_64_32). Only forms like DW_FORM_addr need to be special cased. They can hold an arbitrary address (must be 64-bit on a 64-bit target). (In theory, producers can make use of small code model to emit 32-bit relocations. This doesn't seem to be leveraged.) Note 1, we have to ignore the addend, because we don't want to resolve DW_AT_low_pc (which may have a non-zero addend) to -1+addend (wrap around to a low address): __attribute__((section(".text.x"))) void f1() { } __attribute__((section(".text.x"))) void f2() { } // DW_AT_low_pc has a non-zero addend Note 2, if the prevailing copy does not have debugging information while a non-prevailing copy has (partial debug build), we don't do extra work to attach debugging information to the prevailing definition. (clang has a lot of debug info optimizations that are on-by-default that assume the whole program is built with debug info). clang -c -ffunction-sections a.cc # prevailing copy has no debug info clang -c -ffunction-sections -g b.cc Reviewed By: dblaikie, avl, jhenderson Differential Revision: https://reviews.llvm.org/D81784
2020-06-24 02:06:39 +08:00
continue;
}
}
target->relocateNoSym(bufLoc, type, SignExtend64<bits>(sym.getVA(addend)));
}
}
// This is used when '-r' is given.
// For REL targets, InputSection::copyRelocations() may store artificial
// relocations aimed to update addends. They are handled in relocateAlloc()
// for allocatable sections, and this function does the same for
// non-allocatable sections, such as sections with debug information.
static void relocateNonAllocForRelocatable(InputSection *sec, uint8_t *buf) {
const unsigned bits = config->is64 ? 64 : 32;
for (const Relocation &rel : sec->relocations) {
// InputSection::copyRelocations() adds only R_ABS relocations.
assert(rel.expr == R_ABS);
uint8_t *bufLoc = buf + rel.offset;
uint64_t targetVA = SignExtend64(rel.sym->getVA(rel.addend), bits);
target->relocate(bufLoc, rel, targetVA);
}
}
template <class ELFT>
void InputSectionBase::relocate(uint8_t *buf, uint8_t *bufEnd) {
if (flags & SHF_EXECINSTR)
adjustSplitStackFunctionPrologues<ELFT>(buf, bufEnd);
if (flags & SHF_ALLOC) {
relocateAlloc(buf, bufEnd);
return;
}
auto *sec = cast<InputSection>(this);
if (config->relocatable)
relocateNonAllocForRelocatable(sec, buf);
else if (sec->areRelocsRela)
sec->relocateNonAlloc<ELFT>(buf, sec->template relas<ELFT>());
else
sec->relocateNonAlloc<ELFT>(buf, sec->template rels<ELFT>());
}
void InputSectionBase::relocateAlloc(uint8_t *buf, uint8_t *bufEnd) {
assert(flags & SHF_ALLOC);
const unsigned bits = config->wordsize * 8;
uint64_t lastPPCRelaxedRelocOff = UINT64_C(-1);
for (const Relocation &rel : relocations) {
LLD Support for Basic Block Sections This is part of the Propeller framework to do post link code layout optimizations. Please see the RFC here: https://groups.google.com/forum/#!msg/llvm-dev/ef3mKzAdJ7U/1shV64BYBAAJ and the detailed RFC doc here: https://github.com/google/llvm-propeller/blob/plo-dev/Propeller_RFC.pdf This patch adds lld support for basic block sections and performs relaxations after the basic blocks have been reordered. After the linker has reordered the basic block sections according to the desired sequence, it runs a relaxation pass to optimize jump instructions. Currently, the compiler emits the long form of all jump instructions. AMD64 ISA supports variants of jump instructions with one byte offset or a four byte offset. The compiler generates jump instructions with R_X86_64 32-bit PC relative relocations. We would like to use a new relocation type for these jump instructions as it makes it easy and accurate while relaxing these instructions. The relaxation pass does two things: First, it deletes all explicit fall-through direct jump instructions between adjacent basic blocks. This is done by discarding the tail of the basic block section. Second, If there are consecutive jump instructions, it checks if the first conditional jump can be inverted to convert the second into a fall through and delete the second. The jump instructions are relaxed by using jump instruction mods, something like relocations. These are used to modify the opcode of the jump instruction. Jump instruction mods contain three values, instruction offset, jump type and size. While writing this jump instruction out to the final binary, the linker uses the jump instruction mod to determine the opcode and the size of the modified jump instruction. These mods are required because the input object files are memory-mapped without write permissions and directly modifying the object files requires copying these sections. Copying a large number of basic block sections significantly bloats memory. Differential Revision: https://reviews.llvm.org/D68065
2020-04-07 21:48:18 +08:00
if (rel.expr == R_NONE)
continue;
uint64_t offset = rel.offset;
uint8_t *bufLoc = buf + offset;
RelType type = rel.type;
uint64_t addrLoc = getOutputSection()->addr + offset;
if (auto *sec = dyn_cast<InputSection>(this))
addrLoc += sec->outSecOff;
RelExpr expr = rel.expr;
uint64_t targetVA = SignExtend64(
getRelocTargetVA(file, type, rel.addend, addrLoc, *rel.sym, expr),
[ELF][MIPS] Multi-GOT implementation Almost all entries inside MIPS GOT are referenced by signed 16-bit index. Zero entry lies approximately in the middle of the GOT. So the total number of GOT entries cannot exceed ~16384 for 32-bit architecture and ~8192 for 64-bit architecture. This limitation makes impossible to link rather large application like for example LLVM+Clang. There are two workaround for this problem. The first one is using the -mxgot compiler's flag. It enables using a 32-bit index to access GOT entries. But each access requires two assembly instructions two load GOT entry index to a register. Another workaround is multi-GOT. This patch implements it. Here is a brief description of multi-GOT for detailed one see the following link https://dmz-portal.mips.com/wiki/MIPS_Multi_GOT. If the sum of local, global and tls entries is less than 64K only single got is enough. Otherwise, multi-got is created. Series of primary and multiple secondary GOTs have the following layout: ``` - Primary GOT Header Local entries Global entries Relocation only entries TLS entries - Secondary GOT Local entries Global entries TLS entries ... ``` All GOT entries required by relocations from a single input file entirely belong to either primary or one of secondary GOTs. To reference GOT entries each GOT has its own _gp value points to the "middle" of the GOT. In the code this value loaded to the register which is used for GOT access. MIPS 32 function's prologue: ``` lui v0,0x0 0: R_MIPS_HI16 _gp_disp addiu v0,v0,0 4: R_MIPS_LO16 _gp_disp ``` MIPS 64 function's prologue: ``` lui at,0x0 14: R_MIPS_GPREL16 main ``` Dynamic linker does not know anything about secondary GOTs and cannot use a regular MIPS mechanism for GOT entries initialization. So we have to use an approach accepted by other architectures and create dynamic relocations R_MIPS_REL32 to initialize global entries (and local in case of PIC code) in secondary GOTs. But ironically MIPS dynamic linker requires GOT entries and correspondingly ordered dynamic symbol table entries to deal with dynamic relocations. To handle this problem relocation-only section in the primary GOT contains entries for all symbols referenced in global parts of secondary GOTs. Although the sum of local and normal global entries of the primary got should be less than 64K, the size of the primary got (including relocation-only entries can be greater than 64K, because parts of the primary got that overflow the 64K limit are used only by the dynamic linker at dynamic link-time and not by 16-bit gp-relative addressing at run-time. The patch affects common LLD code in the following places: - Added new hidden -mips-got-size flag. This flag required to set low maximum size of a single GOT to be able to test the implementation using small test cases. - Added InputFile argument to the getRelocTargetVA function. The same symbol referenced by GOT relocation from different input file might be allocated in different GOT. So result of relocation depends on the file. - Added new ctor to the DynamicReloc class. This constructor records settings of dynamic relocation which used to adjust address of 64kb page lies inside a specific output section. With the patch LLD is able to link all LLVM+Clang+LLD applications and libraries for MIPS 32/64 targets. Differential revision: https://reviews.llvm.org/D31528 llvm-svn: 334390
2018-06-11 15:24:31 +08:00
bits);
2016-05-21 05:14:06 +08:00
switch (expr) {
case R_RELAX_GOT_PC:
case R_RELAX_GOT_PC_NOPIC:
target->relaxGot(bufLoc, rel, targetVA);
break;
case R_PPC64_RELAX_GOT_PC: {
// The R_PPC64_PCREL_OPT relocation must appear immediately after
// R_PPC64_GOT_PCREL34 in the relocations table at the same offset.
// We can only relax R_PPC64_PCREL_OPT if we have also relaxed
// the associated R_PPC64_GOT_PCREL34 since only the latter has an
// associated symbol. So save the offset when relaxing R_PPC64_GOT_PCREL34
// and only relax the other if the saved offset matches.
if (type == R_PPC64_GOT_PCREL34)
lastPPCRelaxedRelocOff = offset;
if (type == R_PPC64_PCREL_OPT && offset != lastPPCRelaxedRelocOff)
break;
target->relaxGot(bufLoc, rel, targetVA);
break;
}
case R_PPC64_RELAX_TOC:
[ELF][PPC64] Suppress toc-indirect to toc-relative relaxation if R_PPC64_TOC16_LO is seen The current implementation assumes that R_PPC64_TOC16_HA is always followed by R_PPC64_TOC16_LO_DS. This can break with R_PPC64_TOC16_LO: // Load the address of the TOC entry, instead of the value stored at that address addis 3, 2, .LC0@tloc@ha # R_PPC64_TOC16_HA addi 3, 3, .LC0@tloc@l # R_PPC64_TOC16_LO blr which is used by boringssl's util/fipstools/delocate/delocate.go https://github.com/google/boringssl/blob/master/crypto/fipsmodule/FIPS.md has some documentation. In short, this tool converts an assembly file to avoid any potential relocations. The distance to an input .toc is not a constant after linking, so it cannot use an `addis;ld` pair. Instead, it jumps to a stub which loads the TOC entry address with `addis;addi`. This patch checks the presence of R_PPC64_TOC16_LO and suppresses toc-indirect to toc-relative relaxation if R_PPC64_TOC16_LO is seen. This approach is conservative and loses some relaxation opportunities but is easy to implement. addis 3, 2, .LC0@toc@ha # no relaxation addi 3, 3, .LC0@toc@l # no relaxation li 9, 0 addis 4, 2, .LC0@toc@ha # can relax but suppressed ld 4, .LC0@toc@l(4) # can relax but suppressed Also note that interleaved R_PPC64_TOC16_HA and R_PPC64_TOC16_LO_DS is possible and this patch accounts for that. addis 3, 2, .LC1@toc@ha # can relax addis 4, 2, .LC2@toc@ha # can relax ld 3, .LC1@toc@l(3) # can relax ld 4, .LC2@toc@l(4) # can relax Reviewed By: #powerpc, sfertile Differential Revision: https://reviews.llvm.org/D78431
2020-04-18 14:08:11 +08:00
// rel.sym refers to the STT_SECTION symbol associated to the .toc input
// section. If an R_PPC64_TOC16_LO (.toc + addend) references the TOC
// entry, there may be R_PPC64_TOC16_HA not paired with
// R_PPC64_TOC16_LO_DS. Don't relax. This loses some relaxation
// opportunities but is safe.
if (ppc64noTocRelax.count({rel.sym, rel.addend}) ||
!tryRelaxPPC64TocIndirection(rel, bufLoc))
target->relocate(bufLoc, rel, targetVA);
break;
2016-05-21 05:14:06 +08:00
case R_RELAX_TLS_IE_TO_LE:
target->relaxTlsIeToLe(bufLoc, rel, targetVA);
2016-05-21 05:14:06 +08:00
break;
case R_RELAX_TLS_LD_TO_LE:
case R_RELAX_TLS_LD_TO_LE_ABS:
target->relaxTlsLdToLe(bufLoc, rel, targetVA);
2016-05-21 05:14:06 +08:00
break;
case R_RELAX_TLS_GD_TO_LE:
case R_RELAX_TLS_GD_TO_LE_NEG:
target->relaxTlsGdToLe(bufLoc, rel, targetVA);
2016-05-21 05:14:06 +08:00
break;
case R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC:
2016-05-21 05:14:06 +08:00
case R_RELAX_TLS_GD_TO_IE:
case R_RELAX_TLS_GD_TO_IE_ABS:
case R_RELAX_TLS_GD_TO_IE_GOT_OFF:
case R_RELAX_TLS_GD_TO_IE_GOTPLT:
target->relaxTlsGdToIe(bufLoc, rel, targetVA);
2016-05-21 05:14:06 +08:00
break;
case R_PPC64_CALL:
// If this is a call to __tls_get_addr, it may be part of a TLS
// sequence that has been relaxed and turned into a nop. In this
// case, we don't want to handle it as a call.
if (read32(bufLoc) == 0x60000000) // nop
break;
// Patch a nop (0x60000000) to a ld.
if (rel.sym->needsTocRestore) {
// gcc/gfortran 5.4, 6.3 and earlier versions do not add nop for
// recursive calls even if the function is preemptible. This is not
// wrong in the common case where the function is not preempted at
// runtime. Just ignore.
if ((bufLoc + 8 > bufEnd || read32(bufLoc + 4) != 0x60000000) &&
rel.sym->file != file) {
// Use substr(6) to remove the "__plt_" prefix.
errorOrWarn(getErrorLocation(bufLoc) + "call to " +
lld::toString(*rel.sym).substr(6) +
" lacks nop, can't restore toc");
break;
}
write32(bufLoc + 4, 0xe8410018); // ld %r2, 24(%r1)
}
target->relocate(bufLoc, rel, targetVA);
break;
2016-05-21 05:14:06 +08:00
default:
target->relocate(bufLoc, rel, targetVA);
2016-05-21 05:14:06 +08:00
break;
}
}
LLD Support for Basic Block Sections This is part of the Propeller framework to do post link code layout optimizations. Please see the RFC here: https://groups.google.com/forum/#!msg/llvm-dev/ef3mKzAdJ7U/1shV64BYBAAJ and the detailed RFC doc here: https://github.com/google/llvm-propeller/blob/plo-dev/Propeller_RFC.pdf This patch adds lld support for basic block sections and performs relaxations after the basic blocks have been reordered. After the linker has reordered the basic block sections according to the desired sequence, it runs a relaxation pass to optimize jump instructions. Currently, the compiler emits the long form of all jump instructions. AMD64 ISA supports variants of jump instructions with one byte offset or a four byte offset. The compiler generates jump instructions with R_X86_64 32-bit PC relative relocations. We would like to use a new relocation type for these jump instructions as it makes it easy and accurate while relaxing these instructions. The relaxation pass does two things: First, it deletes all explicit fall-through direct jump instructions between adjacent basic blocks. This is done by discarding the tail of the basic block section. Second, If there are consecutive jump instructions, it checks if the first conditional jump can be inverted to convert the second into a fall through and delete the second. The jump instructions are relaxed by using jump instruction mods, something like relocations. These are used to modify the opcode of the jump instruction. Jump instruction mods contain three values, instruction offset, jump type and size. While writing this jump instruction out to the final binary, the linker uses the jump instruction mod to determine the opcode and the size of the modified jump instruction. These mods are required because the input object files are memory-mapped without write permissions and directly modifying the object files requires copying these sections. Copying a large number of basic block sections significantly bloats memory. Differential Revision: https://reviews.llvm.org/D68065
2020-04-07 21:48:18 +08:00
// Apply jumpInstrMods. jumpInstrMods are created when the opcode of
// a jmp insn must be modified to shrink the jmp insn or to flip the jmp
// insn. This is primarily used to relax and optimize jumps created with
// basic block sections.
if (isa<InputSection>(this)) {
LLD Support for Basic Block Sections This is part of the Propeller framework to do post link code layout optimizations. Please see the RFC here: https://groups.google.com/forum/#!msg/llvm-dev/ef3mKzAdJ7U/1shV64BYBAAJ and the detailed RFC doc here: https://github.com/google/llvm-propeller/blob/plo-dev/Propeller_RFC.pdf This patch adds lld support for basic block sections and performs relaxations after the basic blocks have been reordered. After the linker has reordered the basic block sections according to the desired sequence, it runs a relaxation pass to optimize jump instructions. Currently, the compiler emits the long form of all jump instructions. AMD64 ISA supports variants of jump instructions with one byte offset or a four byte offset. The compiler generates jump instructions with R_X86_64 32-bit PC relative relocations. We would like to use a new relocation type for these jump instructions as it makes it easy and accurate while relaxing these instructions. The relaxation pass does two things: First, it deletes all explicit fall-through direct jump instructions between adjacent basic blocks. This is done by discarding the tail of the basic block section. Second, If there are consecutive jump instructions, it checks if the first conditional jump can be inverted to convert the second into a fall through and delete the second. The jump instructions are relaxed by using jump instruction mods, something like relocations. These are used to modify the opcode of the jump instruction. Jump instruction mods contain three values, instruction offset, jump type and size. While writing this jump instruction out to the final binary, the linker uses the jump instruction mod to determine the opcode and the size of the modified jump instruction. These mods are required because the input object files are memory-mapped without write permissions and directly modifying the object files requires copying these sections. Copying a large number of basic block sections significantly bloats memory. Differential Revision: https://reviews.llvm.org/D68065
2020-04-07 21:48:18 +08:00
for (const JumpInstrMod &jumpMod : jumpInstrMods) {
uint64_t offset = jumpMod.offset;
LLD Support for Basic Block Sections This is part of the Propeller framework to do post link code layout optimizations. Please see the RFC here: https://groups.google.com/forum/#!msg/llvm-dev/ef3mKzAdJ7U/1shV64BYBAAJ and the detailed RFC doc here: https://github.com/google/llvm-propeller/blob/plo-dev/Propeller_RFC.pdf This patch adds lld support for basic block sections and performs relaxations after the basic blocks have been reordered. After the linker has reordered the basic block sections according to the desired sequence, it runs a relaxation pass to optimize jump instructions. Currently, the compiler emits the long form of all jump instructions. AMD64 ISA supports variants of jump instructions with one byte offset or a four byte offset. The compiler generates jump instructions with R_X86_64 32-bit PC relative relocations. We would like to use a new relocation type for these jump instructions as it makes it easy and accurate while relaxing these instructions. The relaxation pass does two things: First, it deletes all explicit fall-through direct jump instructions between adjacent basic blocks. This is done by discarding the tail of the basic block section. Second, If there are consecutive jump instructions, it checks if the first conditional jump can be inverted to convert the second into a fall through and delete the second. The jump instructions are relaxed by using jump instruction mods, something like relocations. These are used to modify the opcode of the jump instruction. Jump instruction mods contain three values, instruction offset, jump type and size. While writing this jump instruction out to the final binary, the linker uses the jump instruction mod to determine the opcode and the size of the modified jump instruction. These mods are required because the input object files are memory-mapped without write permissions and directly modifying the object files requires copying these sections. Copying a large number of basic block sections significantly bloats memory. Differential Revision: https://reviews.llvm.org/D68065
2020-04-07 21:48:18 +08:00
uint8_t *bufLoc = buf + offset;
target->applyJumpInstrMod(bufLoc, jumpMod.original, jumpMod.size);
}
}
}
// For each function-defining prologue, find any calls to __morestack,
// and replace them with calls to __morestack_non_split.
static void switchMorestackCallsToMorestackNonSplit(
DenseSet<Defined *> &prologues, std::vector<Relocation *> &morestackCalls) {
// If the target adjusted a function's prologue, all calls to
// __morestack inside that function should be switched to
// __morestack_non_split.
Symbol *moreStackNonSplit = symtab->find("__morestack_non_split");
if (!moreStackNonSplit) {
error("Mixing split-stack objects requires a definition of "
"__morestack_non_split");
return;
}
// Sort both collections to compare addresses efficiently.
llvm::sort(morestackCalls, [](const Relocation *l, const Relocation *r) {
return l->offset < r->offset;
});
std::vector<Defined *> functions(prologues.begin(), prologues.end());
llvm::sort(functions, [](const Defined *l, const Defined *r) {
return l->value < r->value;
});
auto it = morestackCalls.begin();
for (Defined *f : functions) {
// Find the first call to __morestack within the function.
while (it != morestackCalls.end() && (*it)->offset < f->value)
++it;
// Adjust all calls inside the function.
while (it != morestackCalls.end() && (*it)->offset < f->value + f->size) {
(*it)->sym = moreStackNonSplit;
++it;
}
}
}
static bool enclosingPrologueAttempted(uint64_t offset,
const DenseSet<Defined *> &prologues) {
for (Defined *f : prologues)
if (f->value <= offset && offset < f->value + f->size)
return true;
return false;
}
// If a function compiled for split stack calls a function not
// compiled for split stack, then the caller needs its prologue
// adjusted to ensure that the called function will have enough stack
// available. Find those functions, and adjust their prologues.
template <class ELFT>
void InputSectionBase::adjustSplitStackFunctionPrologues(uint8_t *buf,
uint8_t *end) {
if (!getFile<ELFT>()->splitStack)
return;
DenseSet<Defined *> prologues;
std::vector<Relocation *> morestackCalls;
for (Relocation &rel : relocations) {
// Local symbols can't possibly be cross-calls, and should have been
// resolved long before this line.
if (rel.sym->isLocal())
continue;
// Ignore calls into the split-stack api.
if (rel.sym->getName().startswith("__morestack")) {
if (rel.sym->getName().equals("__morestack"))
morestackCalls.push_back(&rel);
continue;
}
// A relocation to non-function isn't relevant. Sometimes
// __morestack is not marked as a function, so this check comes
// after the name check.
if (rel.sym->type != STT_FUNC)
continue;
// If the callee's-file was compiled with split stack, nothing to do. In
// this context, a "Defined" symbol is one "defined by the binary currently
// being produced". So an "undefined" symbol might be provided by a shared
// library. It is not possible to tell how such symbols were compiled, so be
// conservative.
if (Defined *d = dyn_cast<Defined>(rel.sym))
if (InputSection *isec = cast_or_null<InputSection>(d->section))
if (!isec || !isec->getFile<ELFT>() || isec->getFile<ELFT>()->splitStack)
continue;
if (enclosingPrologueAttempted(rel.offset, prologues))
continue;
if (Defined *f = getEnclosingFunction<ELFT>(rel.offset)) {
prologues.insert(f);
if (target->adjustPrologueForCrossSplitStack(buf + f->value, end,
f->stOther))
continue;
if (!getFile<ELFT>()->someNoSplitStack)
error(lld::toString(this) + ": " + f->getName() +
" (with -fsplit-stack) calls " + rel.sym->getName() +
" (without -fsplit-stack), but couldn't adjust its prologue");
}
}
if (target->needsMoreStackNonSplit)
switchMorestackCallsToMorestackNonSplit(prologues, morestackCalls);
}
template <class ELFT> void InputSection::writeTo(uint8_t *buf) {
if (type == SHT_NOBITS)
return;
if (auto *s = dyn_cast<SyntheticSection>(this)) {
s->writeTo(buf + outSecOff);
return;
}
// If -r or --emit-relocs is given, then an InputSection
// may be a relocation section.
if (type == SHT_RELA) {
copyRelocations<ELFT>(buf + outSecOff, getDataAs<typename ELFT::Rela>());
return;
}
if (type == SHT_REL) {
copyRelocations<ELFT>(buf + outSecOff, getDataAs<typename ELFT::Rel>());
return;
}
2017-06-09 11:19:08 +08:00
// If -r is given, we may have a SHT_GROUP section.
if (type == SHT_GROUP) {
2017-06-09 11:19:08 +08:00
copyShtGroup<ELFT>(buf + outSecOff);
return;
}
// If this is a compressed section, uncompress section contents directly
// to the buffer.
if (uncompressedSize >= 0) {
size_t size = uncompressedSize;
if (Error e = zlib::uncompress(toStringRef(rawData),
(char *)(buf + outSecOff), size))
fatal(toString(this) +
": uncompress failed: " + llvm::toString(std::move(e)));
uint8_t *bufEnd = buf + outSecOff + size;
relocate<ELFT>(buf + outSecOff, bufEnd);
return;
}
// Copy section contents from source object file to output file
// and then apply relocations.
memcpy(buf + outSecOff, data().data(), data().size());
uint8_t *bufEnd = buf + outSecOff + data().size();
relocate<ELFT>(buf + outSecOff, bufEnd);
}
void InputSection::replace(InputSection *other) {
alignment = std::max(alignment, other->alignment);
// When a section is replaced with another section that was allocated to
// another partition, the replacement section (and its associated sections)
// need to be placed in the main partition so that both partitions will be
// able to access it.
if (partition != other->partition) {
partition = 1;
for (InputSection *isec : dependentSections)
isec->partition = 1;
}
other->repl = repl;
other->markDead();
}
template <class ELFT>
EhInputSection::EhInputSection(ObjFile<ELFT> &f,
const typename ELFT::Shdr &header,
StringRef name)
: InputSectionBase(f, header, name, InputSectionBase::EHFrame) {}
SyntheticSection *EhInputSection::getParent() const {
return cast_or_null<SyntheticSection>(parent);
}
// Returns the index of the first relocation that points to a region between
// Begin and Begin+Size.
template <class IntTy, class RelTy>
static unsigned getReloc(IntTy begin, IntTy size, const ArrayRef<RelTy> &rels,
unsigned &relocI) {
// Start search from RelocI for fast access. That works because the
// relocations are sorted in .eh_frame.
for (unsigned n = rels.size(); relocI < n; ++relocI) {
const RelTy &rel = rels[relocI];
if (rel.r_offset < begin)
continue;
if (rel.r_offset < begin + size)
return relocI;
return -1;
}
return -1;
}
// .eh_frame is a sequence of CIE or FDE records.
// This function splits an input section into records and returns them.
template <class ELFT> void EhInputSection::split() {
if (areRelocsRela)
split<ELFT>(relas<ELFT>());
else
split<ELFT>(rels<ELFT>());
}
template <class ELFT, class RelTy>
void EhInputSection::split(ArrayRef<RelTy> rels) {
unsigned relI = 0;
for (size_t off = 0, end = data().size(); off != end;) {
size_t size = readEhRecordSize(this, off);
pieces.emplace_back(off, this, size, getReloc(off, size, rels, relI));
// The empty record is the end marker.
if (size == 4)
break;
off += size;
}
}
2017-10-22 09:58:30 +08:00
static size_t findNull(StringRef s, size_t entSize) {
// Optimize the common case.
if (entSize == 1)
return s.find(0);
for (unsigned i = 0, n = s.size(); i != n; i += entSize) {
const char *b = s.begin() + i;
if (std::all_of(b, b + entSize, [](char c) { return c == 0; }))
return i;
}
return StringRef::npos;
}
SyntheticSection *MergeInputSection::getParent() const {
return cast_or_null<SyntheticSection>(parent);
}
// Split SHF_STRINGS section. Such section is a sequence of
// null-terminated strings.
void MergeInputSection::splitStrings(ArrayRef<uint8_t> data, size_t entSize) {
size_t off = 0;
bool isAlloc = flags & SHF_ALLOC;
2017-10-22 09:58:30 +08:00
StringRef s = toStringRef(data);
[Coding style change] Rename variables so that they start with a lowercase letter This patch is mechanically generated by clang-llvm-rename tool that I wrote using Clang Refactoring Engine just for creating this patch. You can see the source code of the tool at https://reviews.llvm.org/D64123. There's no manual post-processing; you can generate the same patch by re-running the tool against lld's code base. Here is the main discussion thread to change the LLVM coding style: https://lists.llvm.org/pipermail/llvm-dev/2019-February/130083.html In the discussion thread, I proposed we use lld as a testbed for variable naming scheme change, and this patch does that. I chose to rename variables so that they are in camelCase, just because that is a minimal change to make variables to start with a lowercase letter. Note to downstream patch maintainers: if you are maintaining a downstream lld repo, just rebasing ahead of this commit would cause massive merge conflicts because this patch essentially changes every line in the lld subdirectory. But there's a remedy. clang-llvm-rename tool is a batch tool, so you can rename variables in your downstream repo with the tool. Given that, here is how to rebase your repo to a commit after the mass renaming: 1. rebase to the commit just before the mass variable renaming, 2. apply the tool to your downstream repo to mass-rename variables locally, and 3. rebase again to the head. Most changes made by the tool should be identical for a downstream repo and for the head, so at the step 3, almost all changes should be merged and disappear. I'd expect that there would be some lines that you need to merge by hand, but that shouldn't be too many. Differential Revision: https://reviews.llvm.org/D64121 llvm-svn: 365595
2019-07-10 13:00:37 +08:00
2017-10-22 09:58:30 +08:00
while (!s.empty()) {
size_t end = findNull(s, entSize);
if (end == StringRef::npos)
fatal(toString(this) + ": string is not null terminated");
size_t size = end + entSize;
2017-10-22 09:58:30 +08:00
pieces.emplace_back(off, xxHash64(s.substr(0, size)), !isAlloc);
s = s.substr(size);
off += size;
}
}
// Split non-SHF_STRINGS section. Such section is a sequence of
// fixed size records.
void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> data,
size_t entSize) {
size_t size = data.size();
assert((size % entSize) == 0);
bool isAlloc = flags & SHF_ALLOC;
[Coding style change] Rename variables so that they start with a lowercase letter This patch is mechanically generated by clang-llvm-rename tool that I wrote using Clang Refactoring Engine just for creating this patch. You can see the source code of the tool at https://reviews.llvm.org/D64123. There's no manual post-processing; you can generate the same patch by re-running the tool against lld's code base. Here is the main discussion thread to change the LLVM coding style: https://lists.llvm.org/pipermail/llvm-dev/2019-February/130083.html In the discussion thread, I proposed we use lld as a testbed for variable naming scheme change, and this patch does that. I chose to rename variables so that they are in camelCase, just because that is a minimal change to make variables to start with a lowercase letter. Note to downstream patch maintainers: if you are maintaining a downstream lld repo, just rebasing ahead of this commit would cause massive merge conflicts because this patch essentially changes every line in the lld subdirectory. But there's a remedy. clang-llvm-rename tool is a batch tool, so you can rename variables in your downstream repo with the tool. Given that, here is how to rebase your repo to a commit after the mass renaming: 1. rebase to the commit just before the mass variable renaming, 2. apply the tool to your downstream repo to mass-rename variables locally, and 3. rebase again to the head. Most changes made by the tool should be identical for a downstream repo and for the head, so at the step 3, almost all changes should be merged and disappear. I'd expect that there would be some lines that you need to merge by hand, but that shouldn't be too many. Differential Revision: https://reviews.llvm.org/D64121 llvm-svn: 365595
2019-07-10 13:00:37 +08:00
for (size_t i = 0; i != size; i += entSize)
2018-08-01 02:13:36 +08:00
pieces.emplace_back(i, xxHash64(data.slice(i, entSize)), !isAlloc);
}
template <class ELFT>
MergeInputSection::MergeInputSection(ObjFile<ELFT> &f,
const typename ELFT::Shdr &header,
StringRef name)
: InputSectionBase(f, header, name, InputSectionBase::Merge) {}
MergeInputSection::MergeInputSection(uint64_t flags, uint32_t type,
uint64_t entsize, ArrayRef<uint8_t> data,
StringRef name)
: InputSectionBase(nullptr, flags, type, entsize, /*Link*/ 0, /*Info*/ 0,
/*Alignment*/ entsize, data, name, SectionBase::Merge) {}
Parallelize uncompress() and splitIntoPieces(). Uncompressing section contents and spliting mergeable section contents into smaller chunks are heavy tasks. They scan entire section contents and do CPU-intensive tasks such as uncompressing zlib-compressed data or computing a hash value for each section piece. Luckily, these tasks are independent to each other, so we can do that in parallel_for_each. The number of input sections is large (as opposed to the number of output sections), so there's a large parallelism here. Actually the current design to call uncompress() and splitIntoPieces() in batch was chosen with doing this in mind. Basically what we need to do here is to replace `for` with `parallel_for_each`. It seems this patch improves latency significantly if linked programs contain debug info (which in turn contain lots of mergeable strings.) For example, the latency to link Clang (debug build) improved by 20% on my machine as shown below. Note that ld.gold took 19.2 seconds to do the same thing. Before: 30801.782712 task-clock (msec) # 3.652 CPUs utilized ( +- 2.59% ) 104,084 context-switches # 0.003 M/sec ( +- 1.02% ) 5,063 cpu-migrations # 0.164 K/sec ( +- 13.66% ) 2,528,130 page-faults # 0.082 M/sec ( +- 0.47% ) 85,317,809,130 cycles # 2.770 GHz ( +- 2.62% ) 67,352,463,373 stalled-cycles-frontend # 78.94% frontend cycles idle ( +- 3.06% ) <not supported> stalled-cycles-backend 44,295,945,493 instructions # 0.52 insns per cycle # 1.52 stalled cycles per insn ( +- 0.44% ) 8,572,384,877 branches # 278.308 M/sec ( +- 0.66% ) 141,806,726 branch-misses # 1.65% of all branches ( +- 0.13% ) 8.433424003 seconds time elapsed ( +- 1.20% ) After: 35523.764575 task-clock (msec) # 5.265 CPUs utilized ( +- 2.67% ) 159,107 context-switches # 0.004 M/sec ( +- 0.48% ) 8,123 cpu-migrations # 0.229 K/sec ( +- 23.34% ) 2,372,483 page-faults # 0.067 M/sec ( +- 0.36% ) 98,395,342,152 cycles # 2.770 GHz ( +- 2.62% ) 79,294,670,125 stalled-cycles-frontend # 80.59% frontend cycles idle ( +- 3.03% ) <not supported> stalled-cycles-backend 46,274,151,813 instructions # 0.47 insns per cycle # 1.71 stalled cycles per insn ( +- 0.47% ) 8,987,621,670 branches # 253.003 M/sec ( +- 0.60% ) 148,900,624 branch-misses # 1.66% of all branches ( +- 0.27% ) 6.747548004 seconds time elapsed ( +- 0.40% ) llvm-svn: 287946
2016-11-26 04:05:08 +08:00
// This function is called after we obtain a complete list of input sections
// that need to be linked. This is responsible to split section contents
// into small chunks for further processing.
//
// Note that this function is called from parallelForEach. This must be
Parallelize uncompress() and splitIntoPieces(). Uncompressing section contents and spliting mergeable section contents into smaller chunks are heavy tasks. They scan entire section contents and do CPU-intensive tasks such as uncompressing zlib-compressed data or computing a hash value for each section piece. Luckily, these tasks are independent to each other, so we can do that in parallel_for_each. The number of input sections is large (as opposed to the number of output sections), so there's a large parallelism here. Actually the current design to call uncompress() and splitIntoPieces() in batch was chosen with doing this in mind. Basically what we need to do here is to replace `for` with `parallel_for_each`. It seems this patch improves latency significantly if linked programs contain debug info (which in turn contain lots of mergeable strings.) For example, the latency to link Clang (debug build) improved by 20% on my machine as shown below. Note that ld.gold took 19.2 seconds to do the same thing. Before: 30801.782712 task-clock (msec) # 3.652 CPUs utilized ( +- 2.59% ) 104,084 context-switches # 0.003 M/sec ( +- 1.02% ) 5,063 cpu-migrations # 0.164 K/sec ( +- 13.66% ) 2,528,130 page-faults # 0.082 M/sec ( +- 0.47% ) 85,317,809,130 cycles # 2.770 GHz ( +- 2.62% ) 67,352,463,373 stalled-cycles-frontend # 78.94% frontend cycles idle ( +- 3.06% ) <not supported> stalled-cycles-backend 44,295,945,493 instructions # 0.52 insns per cycle # 1.52 stalled cycles per insn ( +- 0.44% ) 8,572,384,877 branches # 278.308 M/sec ( +- 0.66% ) 141,806,726 branch-misses # 1.65% of all branches ( +- 0.13% ) 8.433424003 seconds time elapsed ( +- 1.20% ) After: 35523.764575 task-clock (msec) # 5.265 CPUs utilized ( +- 2.67% ) 159,107 context-switches # 0.004 M/sec ( +- 0.48% ) 8,123 cpu-migrations # 0.229 K/sec ( +- 23.34% ) 2,372,483 page-faults # 0.067 M/sec ( +- 0.36% ) 98,395,342,152 cycles # 2.770 GHz ( +- 2.62% ) 79,294,670,125 stalled-cycles-frontend # 80.59% frontend cycles idle ( +- 3.03% ) <not supported> stalled-cycles-backend 46,274,151,813 instructions # 0.47 insns per cycle # 1.71 stalled cycles per insn ( +- 0.47% ) 8,987,621,670 branches # 253.003 M/sec ( +- 0.60% ) 148,900,624 branch-misses # 1.66% of all branches ( +- 0.27% ) 6.747548004 seconds time elapsed ( +- 0.40% ) llvm-svn: 287946
2016-11-26 04:05:08 +08:00
// thread-safe (i.e. no memory allocation from the pools).
void MergeInputSection::splitIntoPieces() {
assert(pieces.empty());
2017-10-22 09:58:30 +08:00
if (flags & SHF_STRINGS)
splitStrings(data(), entsize);
else
splitNonStrings(data(), entsize);
}
SectionPiece *MergeInputSection::getSectionPiece(uint64_t offset) {
if (this->data().size() <= offset)
fatal(toString(this) + ": offset is outside the section");
// If Offset is not at beginning of a section piece, it is not in the map.
// In that case we need to do a binary search of the original section piece vector.
auto it = partition_point(
pieces, [=](SectionPiece p) { return p.inputOff <= offset; });
return &it[-1];
}
Avoid doing binary search. MergedInputSection::getOffset is the busiest function in LLD if string merging is enabled and input files have lots of mergeable sections. It is usually the case when creating executable with debug info, so it is pretty common. The reason why it is slow is because it has to do faily complex computations. For non-mergeable sections, section contents are contiguous in output, so in order to compute an output offset, we only have to add the output section's base address to an input offset. But for mergeable strings, section contents are split for merging, so they are not contigous. We've got to do some lookups. We used to do binary search on the list of section pieces. It is slow because I think it's hostile to branch prediction. This patch replaces it with hash table lookup. Seems it's working pretty well. Below is "perf stat -r10" output when linking clang with debug info. In this case this patch speeds up about 4%. Before: 6584.153205 task-clock (msec) # 1.001 CPUs utilized ( +- 0.09% ) 238 context-switches # 0.036 K/sec ( +- 6.59% ) 0 cpu-migrations # 0.000 K/sec ( +- 50.92% ) 1,067,675 page-faults # 0.162 M/sec ( +- 0.15% ) 18,369,931,470 cycles # 2.790 GHz ( +- 0.09% ) 9,640,680,143 stalled-cycles-frontend # 52.48% frontend cycles idle ( +- 0.18% ) <not supported> stalled-cycles-backend 21,206,747,787 instructions # 1.15 insns per cycle # 0.45 stalled cycles per insn ( +- 0.04% ) 3,817,398,032 branches # 579.786 M/sec ( +- 0.04% ) 132,787,249 branch-misses # 3.48% of all branches ( +- 0.02% ) 6.579106511 seconds time elapsed ( +- 0.09% ) After: 6312.317533 task-clock (msec) # 1.001 CPUs utilized ( +- 0.19% ) 221 context-switches # 0.035 K/sec ( +- 4.11% ) 1 cpu-migrations # 0.000 K/sec ( +- 45.21% ) 1,280,775 page-faults # 0.203 M/sec ( +- 0.37% ) 17,611,539,150 cycles # 2.790 GHz ( +- 0.19% ) 10,285,148,569 stalled-cycles-frontend # 58.40% frontend cycles idle ( +- 0.30% ) <not supported> stalled-cycles-backend 18,794,779,900 instructions # 1.07 insns per cycle # 0.55 stalled cycles per insn ( +- 0.03% ) 3,287,450,865 branches # 520.799 M/sec ( +- 0.03% ) 72,259,605 branch-misses # 2.20% of all branches ( +- 0.01% ) 6.307411828 seconds time elapsed ( +- 0.19% ) Differential Revision: http://reviews.llvm.org/D20645 llvm-svn: 270999
2016-05-27 22:39:13 +08:00
// Returns the offset in an output section for a given input offset.
// Because contents of a mergeable section is not contiguous in output,
// it is not just an addition to a base output offset.
uint64_t MergeInputSection::getParentOffset(uint64_t offset) const {
// If Offset is not at beginning of a section piece, it is not in the map.
// In that case we need to search from the original section piece vector.
const SectionPiece &piece =
*(const_cast<MergeInputSection *>(this)->getSectionPiece (offset));
uint64_t addend = offset - piece.inputOff;
2016-05-29 02:40:38 +08:00
return piece.outputOff + addend;
Avoid doing binary search. MergedInputSection::getOffset is the busiest function in LLD if string merging is enabled and input files have lots of mergeable sections. It is usually the case when creating executable with debug info, so it is pretty common. The reason why it is slow is because it has to do faily complex computations. For non-mergeable sections, section contents are contiguous in output, so in order to compute an output offset, we only have to add the output section's base address to an input offset. But for mergeable strings, section contents are split for merging, so they are not contigous. We've got to do some lookups. We used to do binary search on the list of section pieces. It is slow because I think it's hostile to branch prediction. This patch replaces it with hash table lookup. Seems it's working pretty well. Below is "perf stat -r10" output when linking clang with debug info. In this case this patch speeds up about 4%. Before: 6584.153205 task-clock (msec) # 1.001 CPUs utilized ( +- 0.09% ) 238 context-switches # 0.036 K/sec ( +- 6.59% ) 0 cpu-migrations # 0.000 K/sec ( +- 50.92% ) 1,067,675 page-faults # 0.162 M/sec ( +- 0.15% ) 18,369,931,470 cycles # 2.790 GHz ( +- 0.09% ) 9,640,680,143 stalled-cycles-frontend # 52.48% frontend cycles idle ( +- 0.18% ) <not supported> stalled-cycles-backend 21,206,747,787 instructions # 1.15 insns per cycle # 0.45 stalled cycles per insn ( +- 0.04% ) 3,817,398,032 branches # 579.786 M/sec ( +- 0.04% ) 132,787,249 branch-misses # 3.48% of all branches ( +- 0.02% ) 6.579106511 seconds time elapsed ( +- 0.09% ) After: 6312.317533 task-clock (msec) # 1.001 CPUs utilized ( +- 0.19% ) 221 context-switches # 0.035 K/sec ( +- 4.11% ) 1 cpu-migrations # 0.000 K/sec ( +- 45.21% ) 1,280,775 page-faults # 0.203 M/sec ( +- 0.37% ) 17,611,539,150 cycles # 2.790 GHz ( +- 0.19% ) 10,285,148,569 stalled-cycles-frontend # 58.40% frontend cycles idle ( +- 0.30% ) <not supported> stalled-cycles-backend 18,794,779,900 instructions # 1.07 insns per cycle # 0.55 stalled cycles per insn ( +- 0.03% ) 3,287,450,865 branches # 520.799 M/sec ( +- 0.03% ) 72,259,605 branch-misses # 2.20% of all branches ( +- 0.01% ) 6.307411828 seconds time elapsed ( +- 0.19% ) Differential Revision: http://reviews.llvm.org/D20645 llvm-svn: 270999
2016-05-27 22:39:13 +08:00
}
template InputSection::InputSection(ObjFile<ELF32LE> &, const ELF32LE::Shdr &,
StringRef);
template InputSection::InputSection(ObjFile<ELF32BE> &, const ELF32BE::Shdr &,
StringRef);
template InputSection::InputSection(ObjFile<ELF64LE> &, const ELF64LE::Shdr &,
StringRef);
template InputSection::InputSection(ObjFile<ELF64BE> &, const ELF64BE::Shdr &,
StringRef);
template std::string InputSectionBase::getLocation<ELF32LE>(uint64_t);
template std::string InputSectionBase::getLocation<ELF32BE>(uint64_t);
template std::string InputSectionBase::getLocation<ELF64LE>(uint64_t);
template std::string InputSectionBase::getLocation<ELF64BE>(uint64_t);
template void InputSection::writeTo<ELF32LE>(uint8_t *);
template void InputSection::writeTo<ELF32BE>(uint8_t *);
template void InputSection::writeTo<ELF64LE>(uint8_t *);
template void InputSection::writeTo<ELF64BE>(uint8_t *);
2016-02-28 08:25:54 +08:00
template MergeInputSection::MergeInputSection(ObjFile<ELF32LE> &,
const ELF32LE::Shdr &, StringRef);
template MergeInputSection::MergeInputSection(ObjFile<ELF32BE> &,
const ELF32BE::Shdr &, StringRef);
template MergeInputSection::MergeInputSection(ObjFile<ELF64LE> &,
const ELF64LE::Shdr &, StringRef);
template MergeInputSection::MergeInputSection(ObjFile<ELF64BE> &,
const ELF64BE::Shdr &, StringRef);
template EhInputSection::EhInputSection(ObjFile<ELF32LE> &,
const ELF32LE::Shdr &, StringRef);
template EhInputSection::EhInputSection(ObjFile<ELF32BE> &,
const ELF32BE::Shdr &, StringRef);
template EhInputSection::EhInputSection(ObjFile<ELF64LE> &,
const ELF64LE::Shdr &, StringRef);
template EhInputSection::EhInputSection(ObjFile<ELF64BE> &,
const ELF64BE::Shdr &, StringRef);
template void EhInputSection::split<ELF32LE>();
template void EhInputSection::split<ELF32BE>();
template void EhInputSection::split<ELF64LE>();
template void EhInputSection::split<ELF64BE>();