2020-04-02 11:54:05 -07:00
|
|
|
//===- InputFiles.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
|
|
|
|
|
//
|
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
//
|
|
|
|
|
// This file contains functions to parse Mach-O object files. In this comment,
|
|
|
|
|
// we describe the Mach-O file structure and how we parse it.
|
|
|
|
|
//
|
|
|
|
|
// Mach-O is not very different from ELF or COFF. The notion of symbols,
|
|
|
|
|
// sections and relocations exists in Mach-O as it does in ELF and COFF.
|
|
|
|
|
//
|
|
|
|
|
// Perhaps the notion that is new to those who know ELF/COFF is "subsections".
|
|
|
|
|
// In ELF/COFF, sections are an atomic unit of data copied from input files to
|
|
|
|
|
// output files. When we merge or garbage-collect sections, we treat each
|
|
|
|
|
// section as an atomic unit. In Mach-O, that's not the case. Sections can
|
|
|
|
|
// consist of multiple subsections, and subsections are a unit of merging and
|
|
|
|
|
// garbage-collecting. Therefore, Mach-O's subsections are more similar to
|
|
|
|
|
// ELF/COFF's sections than Mach-O's sections are.
|
|
|
|
|
//
|
|
|
|
|
// A section can have multiple symbols. A symbol that does not have the
|
|
|
|
|
// N_ALT_ENTRY attribute indicates a beginning of a subsection. Therefore, by
|
|
|
|
|
// definition, a symbol is always present at the beginning of each subsection. A
|
|
|
|
|
// symbol with N_ALT_ENTRY attribute does not start a new subsection and can
|
|
|
|
|
// point to a middle of a subsection.
|
|
|
|
|
//
|
|
|
|
|
// The notion of subsections also affects how relocations are represented in
|
|
|
|
|
// Mach-O. All references within a section need to be explicitly represented as
|
|
|
|
|
// relocations if they refer to different subsections, because we obviously need
|
|
|
|
|
// to fix up addresses if subsections are laid out in an output file differently
|
|
|
|
|
// than they were in object files. To represent that, Mach-O relocations can
|
|
|
|
|
// refer to an unnamed location via its address. Scattered relocations (those
|
|
|
|
|
// with the R_SCATTERED bit set) always refer to unnamed locations.
|
|
|
|
|
// Non-scattered relocations refer to an unnamed location if r_extern is not set
|
|
|
|
|
// and r_symbolnum is zero.
|
|
|
|
|
//
|
|
|
|
|
// Without the above differences, I think you can use your knowledge about ELF
|
|
|
|
|
// and COFF for Mach-O.
|
|
|
|
|
//
|
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
|
|
#include "InputFiles.h"
|
2020-04-23 20:16:49 -07:00
|
|
|
#include "Config.h"
|
2020-11-18 12:31:47 -05:00
|
|
|
#include "Driver.h"
|
[lld-macho] Emit STABS symbols for debugging, and drop debug sections
Debug sections contain a large amount of data. In order not to bloat the size
of the final binary, we remove them and instead emit STABS symbols for
`dsymutil` and the debugger to locate their contents in the object files.
With this diff, `dsymutil` is able to locate the debug info. However, we need
a few more features before `lldb` is able to work well with our binaries --
e.g. having `LC_DYSYMTAB` accurately reflect the number of local symbols,
emitting `LC_UUID`, and more. Those will be handled in follow-up diffs.
Note also that the STABS we emit differ slightly from what ld64 does. First, we
emit the path to the source file as one `N_SO` symbol instead of two. (`ld64`
emits one `N_SO` for the dirname and one of the basename.) Second, we do not
emit `N_BNSYM` and `N_ENSYM` STABS to mark the start and end of functions,
because the `N_FUN` STABS already serve that purpose. @clayborg recommended
these changes based on his knowledge of what the debugging tools look for.
Additionally, this current implementation doesn't accurately reflect the size
of function symbols. It uses the size of their containing sectioins as a proxy,
but that is only accurate if `.subsections_with_symbols` is set, and if there
isn't an `N_ALT_ENTRY` in that particular subsection. I think we have two
options to solve this:
1. We can split up subsections by symbol even if `.subsections_with_symbols`
is not set, but include constraints to ensure those subsections retain
their order in the final output. This is `ld64`'s approach.
2. We could just add a `size` field to our `Symbol` class. This seems simpler,
and I'm more inclined toward it, but I'm not sure if there are use cases
that it doesn't handle well. As such I'm punting on the decision for now.
Reviewed By: clayborg
Differential Revision: https://reviews.llvm.org/D89257
2020-12-01 14:45:01 -08:00
|
|
|
#include "Dwarf.h"
|
2022-06-12 21:56:45 -04:00
|
|
|
#include "EhFrame.h"
|
[lld-macho] Use export trie instead of symtab when linking against dylibs
Summary:
This allows us to link against stripped dylibs. Moreover, it's simply
more correct: The symbol table includes symbols that the dylib uses but
doesn't export.
This temporarily regresses our ability to do lazy symbol binding because
dyld_stub_binder isn't in libSystem's export trie. Rather, it is in one
of the sub-libraries libSystem re-exports. (This doesn't affect our
tests since we are mocking out dyld_stub_binder there.) A follow-up diff
will address this by adding support for sub-libraries.
Depends on D79114.
Reviewers: ruiu, pcc, MaskRay, smeenai, alexshap, gkm, Ktwu, christylee
Subscribers: mgorny, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D79226
2020-04-22 20:00:57 -07:00
|
|
|
#include "ExportTrie.h"
|
2020-04-02 11:54:05 -07:00
|
|
|
#include "InputSection.h"
|
2020-08-18 14:37:04 -07:00
|
|
|
#include "ObjC.h"
|
2020-05-01 16:29:06 -07:00
|
|
|
#include "OutputSection.h"
|
2020-08-18 14:37:04 -07:00
|
|
|
#include "OutputSegment.h"
|
2020-04-02 11:54:05 -07:00
|
|
|
#include "SymbolTable.h"
|
|
|
|
|
#include "Symbols.h"
|
[lld-macho] Implement cstring deduplication
Our implementation draws heavily from LLD-ELF's, which in turn delegates
its string deduplication to llvm-mc's StringTableBuilder. The messiness of
this diff is largely due to the fact that we've previously assumed that
all InputSections get concatenated together to form the output. This is
no longer true with CStringInputSections, which split their contents into
StringPieces. StringPieces are much more lightweight than InputSections,
which is important as we create a lot of them. They may also overlap in
the output, which makes it possible for strings to be tail-merged. In
fact, the initial version of this diff implemented tail merging, but
I've dropped it for reasons I'll explain later.
**Alignment Issues**
Mergeable cstring literals are found under the `__TEXT,__cstring`
section. In contrast to ELF, which puts strings that need different
alignments into different sections, clang's Mach-O backend puts them all
in one section. Strings that need to be aligned have the `.p2align`
directive emitted before them, which simply translates into zero padding
in the object file.
I *think* ld64 extracts the desired per-string alignment from this data
by preserving each string's offset from the last section-aligned
address. I'm not entirely certain since it doesn't seem consistent about
doing this; but perhaps this can be chalked up to cases where ld64 has
to deduplicate strings with different offset/alignment combos -- it
seems to pick one of their alignments to preserve. This doesn't seem
correct in general; we can in fact can induce ld64 to produce a crashing
binary just by linking in an additional object file that only contains
cstrings and no code. See PR50563 for details.
Moreover, this scheme seems rather inefficient: since unaligned and
aligned strings are all put in the same section, which has a single
alignment value, it doesn't seem possible to tell whether a given string
doesn't have any alignment requirements. Preserving offset+alignments
for strings that don't need it is wasteful.
In practice, the crashes seen so far seem to stem from x86_64 SIMD
operations on cstrings. X86_64 requires SIMD accesses to be
16-byte-aligned. So for now, I'm thinking of just aligning all strings
to 16 bytes on x86_64. This is indeed wasteful, but implementation-wise
it's simpler than preserving per-string alignment+offsets. It also
avoids the aforementioned crash after deduplication of
differently-aligned strings. Finally, the overhead is not huge: using
16-byte alignment (vs no alignment) is only a 0.5% size overhead when
linking chromium_framework.
With these alignment requirements, it doesn't make sense to attempt tail
merging -- most strings will not be eligible since their overlaps aren't
likely to start at a 16-byte boundary. Tail-merging (with alignment) for
chromium_framework only improves size by 0.3%.
It's worth noting that LLD-ELF only does tail merging at `-O2`. By
default (at `-O1`), it just deduplicates w/o tail merging. @thakis has
also mentioned that they saw it regress compressed size in some cases
and therefore turned it off. `ld64` does not seem to do tail merging at
all.
**Performance Numbers**
CString deduplication reduces chromium_framework from 250MB to 242MB, or
about a 3.2% reduction.
Numbers for linking chromium_framework on my 3.2 GHz 16-Core Intel Xeon W:
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.99 4.14 4.015 4.0365 0.0492336
Difference at 95.0% confidence
0.0865 +/- 0.027245
2.18987% +/- 0.689746%
(Student's t, pooled s = 0.0425673)
As expected, cstring merging incurs some non-trivial overhead.
When passing `--no-literal-merge`, it seems that performance is the
same, i.e. the refactoring in this diff didn't cost us.
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.89 4.02 3.935 3.9435 0.043197831
No difference proven at 95.0% confidence
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D102964
2021-06-07 23:47:12 -04:00
|
|
|
#include "SyntheticSections.h"
|
2020-04-02 11:54:05 -07:00
|
|
|
#include "Target.h"
|
|
|
|
|
|
2022-01-20 14:53:18 -05:00
|
|
|
#include "lld/Common/CommonLinkerContext.h"
|
[lld-macho] Emit STABS symbols for debugging, and drop debug sections
Debug sections contain a large amount of data. In order not to bloat the size
of the final binary, we remove them and instead emit STABS symbols for
`dsymutil` and the debugger to locate their contents in the object files.
With this diff, `dsymutil` is able to locate the debug info. However, we need
a few more features before `lldb` is able to work well with our binaries --
e.g. having `LC_DYSYMTAB` accurately reflect the number of local symbols,
emitting `LC_UUID`, and more. Those will be handled in follow-up diffs.
Note also that the STABS we emit differ slightly from what ld64 does. First, we
emit the path to the source file as one `N_SO` symbol instead of two. (`ld64`
emits one `N_SO` for the dirname and one of the basename.) Second, we do not
emit `N_BNSYM` and `N_ENSYM` STABS to mark the start and end of functions,
because the `N_FUN` STABS already serve that purpose. @clayborg recommended
these changes based on his knowledge of what the debugging tools look for.
Additionally, this current implementation doesn't accurately reflect the size
of function symbols. It uses the size of their containing sectioins as a proxy,
but that is only accurate if `.subsections_with_symbols` is set, and if there
isn't an `N_ALT_ENTRY` in that particular subsection. I think we have two
options to solve this:
1. We can split up subsections by symbol even if `.subsections_with_symbols`
is not set, but include constraints to ensure those subsections retain
their order in the final output. This is `ld64`'s approach.
2. We could just add a `size` field to our `Symbol` class. This seems simpler,
and I'm more inclined toward it, but I'm not sure if there are use cases
that it doesn't handle well. As such I'm punting on the decision for now.
Reviewed By: clayborg
Differential Revision: https://reviews.llvm.org/D89257
2020-12-01 14:45:01 -08:00
|
|
|
#include "lld/Common/DWARF.h"
|
2020-11-28 22:38:27 -05:00
|
|
|
#include "lld/Common/Reproduce.h"
|
2020-08-13 13:48:47 -07:00
|
|
|
#include "llvm/ADT/iterator.h"
|
2020-04-02 11:54:05 -07:00
|
|
|
#include "llvm/BinaryFormat/MachO.h"
|
2020-10-26 19:18:29 -07:00
|
|
|
#include "llvm/LTO/LTO.h"
|
2022-01-12 10:47:04 -05:00
|
|
|
#include "llvm/Support/BinaryStreamReader.h"
|
2020-04-02 11:54:05 -07:00
|
|
|
#include "llvm/Support/Endian.h"
|
|
|
|
|
#include "llvm/Support/MemoryBuffer.h"
|
2020-04-23 20:16:49 -07:00
|
|
|
#include "llvm/Support/Path.h"
|
2020-11-28 22:38:27 -05:00
|
|
|
#include "llvm/Support/TarWriter.h"
|
2022-01-12 10:47:04 -05:00
|
|
|
#include "llvm/Support/TimeProfiler.h"
|
2021-04-05 09:59:50 -07:00
|
|
|
#include "llvm/TextAPI/Architecture.h"
|
|
|
|
|
#include "llvm/TextAPI/InterfaceFile.h"
|
2020-04-02 11:54:05 -07:00
|
|
|
|
2022-11-26 21:02:09 -08:00
|
|
|
#include <optional>
|
2021-11-16 19:57:24 -05:00
|
|
|
#include <type_traits>
|
|
|
|
|
|
2020-04-02 11:54:05 -07:00
|
|
|
using namespace llvm;
|
|
|
|
|
using namespace llvm::MachO;
|
|
|
|
|
using namespace llvm::support::endian;
|
2020-04-23 20:16:49 -07:00
|
|
|
using namespace llvm::sys;
|
2020-04-02 11:54:05 -07:00
|
|
|
using namespace lld;
|
|
|
|
|
using namespace lld::macho;
|
|
|
|
|
|
2020-12-01 19:00:48 -05:00
|
|
|
// Returns "<internal>", "foo.a(bar.o)", or "baz.o".
|
|
|
|
|
std::string lld::toString(const InputFile *f) {
|
|
|
|
|
if (!f)
|
|
|
|
|
return "<internal>";
|
2021-03-04 14:36:49 -05:00
|
|
|
|
|
|
|
|
// Multiple dylibs can be defined in one .tbd file.
|
2023-04-05 01:48:34 -04:00
|
|
|
if (const auto *dylibFile = dyn_cast<DylibFile>(f))
|
2023-06-05 14:36:19 -07:00
|
|
|
if (f->getName().ends_with(".tbd"))
|
2021-06-06 18:25:28 -04:00
|
|
|
return (f->getName() + "(" + dylibFile->installName + ")").str();
|
2021-03-04 14:36:49 -05:00
|
|
|
|
2020-12-01 19:00:48 -05:00
|
|
|
if (f->archiveName.empty())
|
|
|
|
|
return std::string(f->getName());
|
2021-04-13 10:40:22 -04:00
|
|
|
return (f->archiveName + "(" + path::filename(f->getName()) + ")").str();
|
2020-12-01 19:00:48 -05:00
|
|
|
}
|
|
|
|
|
|
2022-04-07 14:28:44 -04:00
|
|
|
std::string lld::toString(const Section &sec) {
|
|
|
|
|
return (toString(sec.file) + ":(" + sec.name + ")").str();
|
|
|
|
|
}
|
|
|
|
|
|
2020-12-14 17:59:22 -05:00
|
|
|
SetVector<InputFile *> macho::inputFiles;
|
2020-11-28 22:38:27 -05:00
|
|
|
std::unique_ptr<TarWriter> macho::tar;
|
2020-12-01 14:45:12 -08:00
|
|
|
int InputFile::idCount = 0;
|
2020-04-02 11:54:05 -07:00
|
|
|
|
2021-04-21 05:41:14 -07:00
|
|
|
static VersionTuple decodeVersion(uint32_t version) {
|
|
|
|
|
unsigned major = version >> 16;
|
|
|
|
|
unsigned minor = (version >> 8) & 0xffu;
|
|
|
|
|
unsigned subMinor = version & 0xffu;
|
|
|
|
|
return VersionTuple(major, minor, subMinor);
|
|
|
|
|
}
|
|
|
|
|
|
2021-05-06 11:18:19 -04:00
|
|
|
static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) {
|
2021-04-21 05:41:14 -07:00
|
|
|
if (!isa<ObjFile>(input) && !isa<DylibFile>(input))
|
2021-05-06 11:18:19 -04:00
|
|
|
return {};
|
2021-04-21 05:41:14 -07:00
|
|
|
|
2021-05-03 18:31:23 -04:00
|
|
|
const char *hdr = input->mb.getBufferStart();
|
2021-04-21 08:18:20 -07:00
|
|
|
|
2022-04-20 12:36:16 -04:00
|
|
|
// "Zippered" object files can have multiple LC_BUILD_VERSION load commands.
|
2021-05-06 11:18:19 -04:00
|
|
|
std::vector<PlatformInfo> platformInfos;
|
|
|
|
|
for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) {
|
|
|
|
|
PlatformInfo info;
|
2022-01-12 14:01:59 -08:00
|
|
|
info.target.Platform = static_cast<PlatformType>(cmd->platform);
|
2023-03-03 12:08:33 -08:00
|
|
|
info.target.MinDeployment = decodeVersion(cmd->minos);
|
2021-05-06 11:18:19 -04:00
|
|
|
platformInfos.emplace_back(std::move(info));
|
2021-04-21 08:18:20 -07:00
|
|
|
}
|
2021-05-06 11:18:19 -04:00
|
|
|
for (auto *cmd : findCommands<version_min_command>(
|
|
|
|
|
hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS,
|
|
|
|
|
LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) {
|
|
|
|
|
PlatformInfo info;
|
2021-04-21 08:18:20 -07:00
|
|
|
switch (cmd->cmd) {
|
|
|
|
|
case LC_VERSION_MIN_MACOSX:
|
2022-01-12 14:01:59 -08:00
|
|
|
info.target.Platform = PLATFORM_MACOS;
|
2021-04-21 08:18:20 -07:00
|
|
|
break;
|
|
|
|
|
case LC_VERSION_MIN_IPHONEOS:
|
2022-01-12 14:01:59 -08:00
|
|
|
info.target.Platform = PLATFORM_IOS;
|
2021-04-21 08:18:20 -07:00
|
|
|
break;
|
|
|
|
|
case LC_VERSION_MIN_TVOS:
|
2022-01-12 14:01:59 -08:00
|
|
|
info.target.Platform = PLATFORM_TVOS;
|
2021-04-21 08:18:20 -07:00
|
|
|
break;
|
|
|
|
|
case LC_VERSION_MIN_WATCHOS:
|
2022-01-12 14:01:59 -08:00
|
|
|
info.target.Platform = PLATFORM_WATCHOS;
|
2021-04-21 08:18:20 -07:00
|
|
|
break;
|
|
|
|
|
}
|
2023-03-03 12:08:33 -08:00
|
|
|
info.target.MinDeployment = decodeVersion(cmd->version);
|
2021-05-06 11:18:19 -04:00
|
|
|
platformInfos.emplace_back(std::move(info));
|
2021-04-21 05:41:14 -07:00
|
|
|
}
|
|
|
|
|
|
2021-05-06 11:18:19 -04:00
|
|
|
return platformInfos;
|
2021-04-21 05:41:14 -07:00
|
|
|
}
|
|
|
|
|
|
2021-05-03 18:31:23 -04:00
|
|
|
static bool checkCompatibility(const InputFile *input) {
|
2021-05-06 11:18:19 -04:00
|
|
|
std::vector<PlatformInfo> platformInfos = getPlatformInfos(input);
|
|
|
|
|
if (platformInfos.empty())
|
2021-04-21 05:41:14 -07:00
|
|
|
return true;
|
2021-05-04 16:23:21 -04:00
|
|
|
|
2021-05-06 11:18:19 -04:00
|
|
|
auto it = find_if(platformInfos, [&](const PlatformInfo &info) {
|
|
|
|
|
return removeSimulator(info.target.Platform) ==
|
|
|
|
|
removeSimulator(config->platform());
|
|
|
|
|
});
|
|
|
|
|
if (it == platformInfos.end()) {
|
|
|
|
|
std::string platformNames;
|
|
|
|
|
raw_string_ostream os(platformNames);
|
|
|
|
|
interleave(
|
|
|
|
|
platformInfos, os,
|
|
|
|
|
[&](const PlatformInfo &info) {
|
|
|
|
|
os << getPlatformName(info.target.Platform);
|
|
|
|
|
},
|
|
|
|
|
"/");
|
|
|
|
|
error(toString(input) + " has platform " + platformNames +
|
2021-04-21 05:41:14 -07:00
|
|
|
Twine(", which is different from target platform ") +
|
2021-04-21 15:43:38 -04:00
|
|
|
getPlatformName(config->platform()));
|
2021-04-21 05:41:14 -07:00
|
|
|
return false;
|
|
|
|
|
}
|
2021-05-06 11:18:19 -04:00
|
|
|
|
2023-03-03 12:08:33 -08:00
|
|
|
if (it->target.MinDeployment > config->platformInfo.target.MinDeployment)
|
|
|
|
|
warn(toString(input) + " has version " +
|
|
|
|
|
it->target.MinDeployment.getAsString() +
|
2021-06-16 11:06:14 -04:00
|
|
|
", which is newer than target minimum of " +
|
2023-03-03 12:08:33 -08:00
|
|
|
config->platformInfo.target.MinDeployment.getAsString());
|
2021-05-06 11:18:19 -04:00
|
|
|
|
2021-06-16 11:06:14 -04:00
|
|
|
return true;
|
2021-04-21 05:41:14 -07:00
|
|
|
}
|
|
|
|
|
|
2023-07-27 13:56:23 -04:00
|
|
|
template <class Header>
|
|
|
|
|
static bool compatWithTargetArch(const InputFile *file, const Header *hdr) {
|
|
|
|
|
uint32_t cpuType;
|
|
|
|
|
std::tie(cpuType, std::ignore) = getCPUTypeFromArchitecture(config->arch());
|
|
|
|
|
|
|
|
|
|
if (hdr->cputype != cpuType) {
|
|
|
|
|
Architecture arch =
|
|
|
|
|
getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
|
|
|
|
|
auto msg = config->errorForArchMismatch
|
|
|
|
|
? static_cast<void (*)(const Twine &)>(error)
|
|
|
|
|
: warn;
|
|
|
|
|
|
|
|
|
|
msg(toString(file) + " has architecture " + getArchitectureName(arch) +
|
|
|
|
|
" which is incompatible with target architecture " +
|
|
|
|
|
getArchitectureName(config->arch()));
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return checkCompatibility(file);
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-03 21:42:04 -07:00
|
|
|
// This cache mostly exists to store system libraries (and .tbds) as they're
|
|
|
|
|
// loaded, rather than the input archives, which are already cached at a higher
|
|
|
|
|
// level, and other files like the filelist that are only read once.
|
|
|
|
|
// Theoretically this caching could be more efficient by hoisting it, but that
|
|
|
|
|
// would require altering many callers to track the state.
|
2021-11-04 09:42:57 -07:00
|
|
|
DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads;
|
2020-04-02 11:54:05 -07:00
|
|
|
// Open a given file path and return it as a memory-mapped file.
|
2022-11-27 16:54:07 -08:00
|
|
|
std::optional<MemoryBufferRef> macho::readFile(StringRef path) {
|
2021-11-03 21:42:04 -07:00
|
|
|
CachedHashStringRef key(path);
|
2021-11-04 09:42:57 -07:00
|
|
|
auto entry = cachedReads.find(key);
|
|
|
|
|
if (entry != cachedReads.end())
|
2021-11-03 21:42:04 -07:00
|
|
|
return entry->second;
|
|
|
|
|
|
2021-03-09 20:15:29 -08:00
|
|
|
ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path);
|
|
|
|
|
if (std::error_code ec = mbOrErr.getError()) {
|
2020-04-02 11:54:05 -07:00
|
|
|
error("cannot open " + path + ": " + ec.message());
|
2022-12-02 23:12:36 -08:00
|
|
|
return std::nullopt;
|
2020-04-02 11:54:05 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
|
|
|
|
|
MemoryBufferRef mbref = mb->getMemBufferRef();
|
|
|
|
|
make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
|
2020-04-21 13:37:57 -07:00
|
|
|
|
|
|
|
|
// If this is a regular non-fat file, return it.
|
|
|
|
|
const char *buf = mbref.getBufferStart();
|
2021-03-11 13:28:08 -05:00
|
|
|
const auto *hdr = reinterpret_cast<const fat_header *>(buf);
|
2021-03-02 01:20:22 -08:00
|
|
|
if (mbref.getBufferSize() < sizeof(uint32_t) ||
|
2021-03-11 13:28:08 -05:00
|
|
|
read32be(&hdr->magic) != FAT_MAGIC) {
|
2020-11-28 22:38:27 -05:00
|
|
|
if (tar)
|
|
|
|
|
tar->append(relativeToRoot(path), mbref.getBuffer());
|
2021-11-04 09:42:57 -07:00
|
|
|
return cachedReads[key] = mbref;
|
2020-11-28 22:38:27 -05:00
|
|
|
}
|
2020-04-21 13:37:57 -07:00
|
|
|
|
2022-01-20 14:53:18 -05:00
|
|
|
llvm::BumpPtrAllocator &bAlloc = lld::bAlloc();
|
|
|
|
|
|
2021-05-25 14:57:58 -04:00
|
|
|
// Object files and archive files may be fat files, which contain multiple
|
|
|
|
|
// real files for different CPU ISAs. Here, we search for a file that matches
|
|
|
|
|
// with the current link target and returns it as a MemoryBufferRef.
|
2021-03-11 13:28:08 -05:00
|
|
|
const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr));
|
2023-01-13 14:17:07 -08:00
|
|
|
auto getArchName = [](uint32_t cpuType, uint32_t cpuSubtype) {
|
|
|
|
|
return getArchitectureName(getArchitectureFromCpuType(cpuType, cpuSubtype));
|
|
|
|
|
};
|
2020-04-29 15:42:36 -07:00
|
|
|
|
2023-01-13 14:17:07 -08:00
|
|
|
std::vector<StringRef> archs;
|
2020-04-29 15:42:36 -07:00
|
|
|
for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
|
|
|
|
|
if (reinterpret_cast<const char *>(arch + i + 1) >
|
|
|
|
|
buf + mbref.getBufferSize()) {
|
|
|
|
|
error(path + ": fat_arch struct extends beyond end of file");
|
2022-12-02 23:12:36 -08:00
|
|
|
return std::nullopt;
|
2020-04-29 15:42:36 -07:00
|
|
|
}
|
|
|
|
|
|
2022-12-17 22:53:44 -05:00
|
|
|
uint32_t cpuType = read32be(&arch[i].cputype);
|
|
|
|
|
uint32_t cpuSubtype =
|
|
|
|
|
read32be(&arch[i].cpusubtype) & ~MachO::CPU_SUBTYPE_MASK;
|
|
|
|
|
|
|
|
|
|
// FIXME: LD64 has a more complex fallback logic here.
|
|
|
|
|
// Consider implementing that as well?
|
|
|
|
|
if (cpuType != static_cast<uint32_t>(target->cpuType) ||
|
2023-01-13 14:17:07 -08:00
|
|
|
cpuSubtype != target->cpuSubtype) {
|
|
|
|
|
archs.emplace_back(getArchName(cpuType, cpuSubtype));
|
2020-04-29 15:42:36 -07:00
|
|
|
continue;
|
2023-01-13 14:17:07 -08:00
|
|
|
}
|
2020-04-29 15:42:36 -07:00
|
|
|
|
|
|
|
|
uint32_t offset = read32be(&arch[i].offset);
|
|
|
|
|
uint32_t size = read32be(&arch[i].size);
|
|
|
|
|
if (offset + size > mbref.getBufferSize())
|
|
|
|
|
error(path + ": slice extends beyond end of file");
|
2020-11-28 22:38:27 -05:00
|
|
|
if (tar)
|
|
|
|
|
tar->append(relativeToRoot(path), mbref.getBuffer());
|
2021-11-04 09:42:57 -07:00
|
|
|
return cachedReads[key] = MemoryBufferRef(StringRef(buf + offset, size),
|
|
|
|
|
path.copy(bAlloc));
|
2020-04-29 15:42:36 -07:00
|
|
|
}
|
|
|
|
|
|
2023-01-13 14:17:07 -08:00
|
|
|
auto targetArchName = getArchName(target->cpuType, target->cpuSubtype);
|
|
|
|
|
warn(path + ": ignoring file because it is universal (" + join(archs, ",") +
|
|
|
|
|
") but does not contain the " + targetArchName + " architecture");
|
2022-12-02 23:12:36 -08:00
|
|
|
return std::nullopt;
|
2020-04-02 11:54:05 -07:00
|
|
|
}
|
|
|
|
|
|
2021-03-11 13:28:08 -05:00
|
|
|
InputFile::InputFile(Kind kind, const InterfaceFile &interface)
|
2022-01-20 14:53:18 -05:00
|
|
|
: id(idCount++), fileKind(kind), name(saver().save(interface.getPath())) {}
|
2021-03-11 13:28:08 -05:00
|
|
|
|
2021-07-07 13:47:26 -04:00
|
|
|
// Some sections comprise of fixed-size records, so instead of splitting them at
|
|
|
|
|
// symbol boundaries, we split them based on size. Records are distinct from
|
|
|
|
|
// literals in that they may contain references to other sections, instead of
|
|
|
|
|
// being leaf nodes in the InputSection graph.
|
|
|
|
|
//
|
|
|
|
|
// Note that "record" is a term I came up with. In contrast, "literal" is a term
|
|
|
|
|
// used by the Mach-O format.
|
2022-11-26 21:02:09 -08:00
|
|
|
static std::optional<size_t> getRecordSize(StringRef segname, StringRef name) {
|
2022-03-08 08:25:59 -05:00
|
|
|
if (name == section_names::compactUnwind) {
|
2022-05-24 07:59:18 +07:00
|
|
|
if (segname == segment_names::ld)
|
|
|
|
|
return target->wordSize == 8 ? 32 : 20;
|
[lld-macho] Associate compact unwind entries with function symbols
Compact unwind entries (CUEs) contain pointers to their respective
function symbols. However, during the link process, it's far more useful
to have pointers from the function symbol to the CUE than vice versa.
This diff adds that pointer in the form of `Defined::compactUnwind`.
In particular, when doing dead-stripping, we want to mark CUEs live when
their function symbol is live; and when doing ICF, we want to dedup
sections iff the symbols in that section have identical CUEs. In both
cases, we want to be able to locate the symbols within a given section,
as well as locate the CUEs belonging to those symbols. So this diff also
adds `InputSection::symbols`.
The ultimate goal of this refactor is to have ICF support dedup'ing
functions with unwind info, but that will be handled in subsequent
diffs. This diff focuses on simplifying `-dead_strip` --
`findFunctionsWithUnwindInfo` is no longer necessary, and
`Defined::isLive()` is now a lot simpler. Moreover, UnwindInfoSection no
longer has to check for dead CUEs -- we simply avoid adding them in the
first place.
Additionally, we now support stripping of dead LSDAs, which follows
quite naturally since `markLive()` can now reach them via the CUEs.
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D109944
2021-10-26 16:04:04 -04:00
|
|
|
}
|
2022-12-21 15:48:28 -08:00
|
|
|
if (!config->dedupStrings)
|
2022-03-08 08:25:59 -05:00
|
|
|
return {};
|
|
|
|
|
|
|
|
|
|
if (name == section_names::cfString && segname == segment_names::data)
|
|
|
|
|
return target->wordSize == 8 ? 32 : 16;
|
2022-07-19 17:03:34 -07:00
|
|
|
|
|
|
|
|
if (config->icfLevel == ICFLevel::none)
|
|
|
|
|
return {};
|
|
|
|
|
|
2022-03-08 08:25:59 -05:00
|
|
|
if (name == section_names::objcClassRefs && segname == segment_names::data)
|
|
|
|
|
return target->wordSize;
|
2022-09-13 11:15:15 -04:00
|
|
|
|
|
|
|
|
if (name == section_names::objcSelrefs && segname == segment_names::data)
|
|
|
|
|
return target->wordSize;
|
2021-07-07 13:47:26 -04:00
|
|
|
return {};
|
|
|
|
|
}
|
|
|
|
|
|
2022-02-15 21:13:41 -05:00
|
|
|
static Error parseCallGraph(ArrayRef<uint8_t> data,
|
|
|
|
|
std::vector<CallGraphEntry> &callGraph) {
|
|
|
|
|
TimeTraceScope timeScope("Parsing call graph section");
|
2023-10-12 21:21:44 -07:00
|
|
|
BinaryStreamReader reader(data, llvm::endianness::little);
|
2022-02-15 21:13:41 -05:00
|
|
|
while (!reader.empty()) {
|
|
|
|
|
uint32_t fromIndex, toIndex;
|
|
|
|
|
uint64_t count;
|
|
|
|
|
if (Error err = reader.readInteger(fromIndex))
|
|
|
|
|
return err;
|
|
|
|
|
if (Error err = reader.readInteger(toIndex))
|
|
|
|
|
return err;
|
|
|
|
|
if (Error err = reader.readInteger(count))
|
|
|
|
|
return err;
|
|
|
|
|
callGraph.emplace_back(fromIndex, toIndex, count);
|
|
|
|
|
}
|
|
|
|
|
return Error::success();
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-04 20:55:31 -07:00
|
|
|
// Parse the sequence of sections within a single LC_SEGMENT(_64).
|
|
|
|
|
// Split each section into subsections.
|
|
|
|
|
template <class SectionHeader>
|
|
|
|
|
void ObjFile::parseSections(ArrayRef<SectionHeader> sectionHeaders) {
|
|
|
|
|
sections.reserve(sectionHeaders.size());
|
2020-04-02 11:54:05 -07:00
|
|
|
auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
|
|
|
|
|
|
2021-11-04 20:55:31 -07:00
|
|
|
for (const SectionHeader &sec : sectionHeaders) {
|
2021-06-11 19:49:53 -04:00
|
|
|
StringRef name =
|
|
|
|
|
StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
|
|
|
|
|
StringRef segname =
|
|
|
|
|
StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
|
[lld-macho][nfc] Eliminate InputSection::Shared
Earlier in LLD's evolution, I tried to create the illusion that
subsections were indistinguishable from "top-level" sections. Thus, even
though the subsections shared many common field values, I hid those
common values away in a private Shared struct (see D105305). More
recently, however, @gkm added a public `Section` struct in D113241 that
served as an explicit way to store values that are common to an entire
set of subsections (aka InputSections). Now that we have another "common
value" struct, `Shared` has been rendered redundant. All its fields can
be moved into `Section` instead, and the pointer to `Shared` can be replaced
with a pointer to `Section`.
This `Section` pointer also has the advantage of letting us inspect other
subsections easily, simplifying the implementation of {D118798}.
P.S. I do think that having both `Section` and `InputSection` makes for
a slightly confusing naming scheme. I considered renaming `InputSection`
to `Subsection`, but that would break the symmetry with `OutputSection`.
It would also make us deviate from LLD-ELF's naming scheme.
This change is perf-neutral on my 3.2 GHz 16-Core Intel Xeon W machine:
base diff difference (95% CI)
sys_time 1.258 ± 0.031 1.248 ± 0.023 [ -1.6% .. +0.1%]
user_time 3.659 ± 0.047 3.658 ± 0.041 [ -0.5% .. +0.4%]
wall_time 4.640 ± 0.085 4.625 ± 0.063 [ -1.0% .. +0.3%]
samples 49 61
There's also no stat sig change in RSS (as measured by `time -l`):
base diff difference (95% CI)
time 998038627.097 ± 13567305.958 1003327715.556 ± 15210451.236 [ -0.2% .. +1.2%]
samples 31 36
Reviewed By: #lld-macho, oontvoo
Differential Revision: https://reviews.llvm.org/D118797
2022-02-03 19:53:29 -05:00
|
|
|
sections.push_back(make<Section>(this, segname, name, sec.flags, sec.addr));
|
2021-06-13 23:20:30 -04:00
|
|
|
if (sec.align >= 32) {
|
2021-06-11 19:49:53 -04:00
|
|
|
error("alignment " + std::to_string(sec.align) + " of section " + name +
|
|
|
|
|
" is too large");
|
2021-06-13 23:20:30 -04:00
|
|
|
continue;
|
|
|
|
|
}
|
2022-04-07 14:28:44 -04:00
|
|
|
Section §ion = *sections.back();
|
2021-06-11 19:49:53 -04:00
|
|
|
uint32_t align = 1 << sec.align;
|
2022-04-07 00:00:41 -04:00
|
|
|
ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr
|
|
|
|
|
: buf + sec.offset,
|
|
|
|
|
static_cast<size_t>(sec.size)};
|
2021-06-11 19:49:53 -04:00
|
|
|
|
2022-12-21 16:02:38 -08:00
|
|
|
auto splitRecords = [&](size_t recordSize) -> void {
|
2021-10-26 15:14:25 -04:00
|
|
|
if (data.empty())
|
2021-07-07 13:47:26 -04:00
|
|
|
return;
|
2022-04-07 14:28:44 -04:00
|
|
|
Subsections &subsections = section.subsections;
|
2021-11-04 20:55:31 -07:00
|
|
|
subsections.reserve(data.size() / recordSize);
|
[lld-macho][nfc] Eliminate InputSection::Shared
Earlier in LLD's evolution, I tried to create the illusion that
subsections were indistinguishable from "top-level" sections. Thus, even
though the subsections shared many common field values, I hid those
common values away in a private Shared struct (see D105305). More
recently, however, @gkm added a public `Section` struct in D113241 that
served as an explicit way to store values that are common to an entire
set of subsections (aka InputSections). Now that we have another "common
value" struct, `Shared` has been rendered redundant. All its fields can
be moved into `Section` instead, and the pointer to `Shared` can be replaced
with a pointer to `Section`.
This `Section` pointer also has the advantage of letting us inspect other
subsections easily, simplifying the implementation of {D118798}.
P.S. I do think that having both `Section` and `InputSection` makes for
a slightly confusing naming scheme. I considered renaming `InputSection`
to `Subsection`, but that would break the symmetry with `OutputSection`.
It would also make us deviate from LLD-ELF's naming scheme.
This change is perf-neutral on my 3.2 GHz 16-Core Intel Xeon W machine:
base diff difference (95% CI)
sys_time 1.258 ± 0.031 1.248 ± 0.023 [ -1.6% .. +0.1%]
user_time 3.659 ± 0.047 3.658 ± 0.041 [ -0.5% .. +0.4%]
wall_time 4.640 ± 0.085 4.625 ± 0.063 [ -1.0% .. +0.3%]
samples 49 61
There's also no stat sig change in RSS (as measured by `time -l`):
base diff difference (95% CI)
time 998038627.097 ± 13567305.958 1003327715.556 ± 15210451.236 [ -0.2% .. +1.2%]
samples 31 36
Reviewed By: #lld-macho, oontvoo
Differential Revision: https://reviews.llvm.org/D118797
2022-02-03 19:53:29 -05:00
|
|
|
for (uint64_t off = 0; off < data.size(); off += recordSize) {
|
|
|
|
|
auto *isec = make<ConcatInputSection>(
|
2022-12-21 16:02:38 -08:00
|
|
|
section, data.slice(off, std::min(data.size(), recordSize)), align);
|
[lld-macho][nfc] Eliminate InputSection::Shared
Earlier in LLD's evolution, I tried to create the illusion that
subsections were indistinguishable from "top-level" sections. Thus, even
though the subsections shared many common field values, I hid those
common values away in a private Shared struct (see D105305). More
recently, however, @gkm added a public `Section` struct in D113241 that
served as an explicit way to store values that are common to an entire
set of subsections (aka InputSections). Now that we have another "common
value" struct, `Shared` has been rendered redundant. All its fields can
be moved into `Section` instead, and the pointer to `Shared` can be replaced
with a pointer to `Section`.
This `Section` pointer also has the advantage of letting us inspect other
subsections easily, simplifying the implementation of {D118798}.
P.S. I do think that having both `Section` and `InputSection` makes for
a slightly confusing naming scheme. I considered renaming `InputSection`
to `Subsection`, but that would break the symmetry with `OutputSection`.
It would also make us deviate from LLD-ELF's naming scheme.
This change is perf-neutral on my 3.2 GHz 16-Core Intel Xeon W machine:
base diff difference (95% CI)
sys_time 1.258 ± 0.031 1.248 ± 0.023 [ -1.6% .. +0.1%]
user_time 3.659 ± 0.047 3.658 ± 0.041 [ -0.5% .. +0.4%]
wall_time 4.640 ± 0.085 4.625 ± 0.063 [ -1.0% .. +0.3%]
samples 49 61
There's also no stat sig change in RSS (as measured by `time -l`):
base diff difference (95% CI)
time 998038627.097 ± 13567305.958 1003327715.556 ± 15210451.236 [ -0.2% .. +1.2%]
samples 31 36
Reviewed By: #lld-macho, oontvoo
Differential Revision: https://reviews.llvm.org/D118797
2022-02-03 19:53:29 -05:00
|
|
|
subsections.push_back({off, isec});
|
2021-07-07 13:47:26 -04:00
|
|
|
}
|
2022-06-12 21:56:45 -04:00
|
|
|
section.doneSplitting = true;
|
2021-07-07 13:47:26 -04:00
|
|
|
};
|
|
|
|
|
|
2022-12-21 15:48:28 -08:00
|
|
|
if (sectionType(sec.flags) == S_CSTRING_LITERALS) {
|
2023-01-05 14:14:11 -05:00
|
|
|
if (sec.nreloc)
|
|
|
|
|
fatal(toString(this) + ": " + sec.segname + "," + sec.sectname +
|
|
|
|
|
" contains relocations, which is unsupported");
|
|
|
|
|
bool dedupLiterals =
|
|
|
|
|
name == section_names::objcMethname || config->dedupStrings;
|
|
|
|
|
InputSection *isec =
|
|
|
|
|
make<CStringInputSection>(section, data, align, dedupLiterals);
|
2022-12-21 15:48:28 -08:00
|
|
|
// FIXME: parallelize this?
|
|
|
|
|
cast<CStringInputSection>(isec)->splitIntoPieces();
|
|
|
|
|
section.subsections.push_back({0, isec});
|
|
|
|
|
} else if (isWordLiteralSection(sec.flags)) {
|
|
|
|
|
if (sec.nreloc)
|
2023-01-05 14:14:11 -05:00
|
|
|
fatal(toString(this) + ": " + sec.segname + "," + sec.sectname +
|
|
|
|
|
" contains relocations, which is unsupported");
|
2022-12-21 15:48:28 -08:00
|
|
|
InputSection *isec = make<WordLiteralInputSection>(section, data, align);
|
2022-04-07 14:28:44 -04:00
|
|
|
section.subsections.push_back({0, isec});
|
2021-07-07 13:47:26 -04:00
|
|
|
} else if (auto recordSize = getRecordSize(segname, name)) {
|
|
|
|
|
splitRecords(*recordSize);
|
[lld-macho] Enable EH frame relocation / pruning
This just removes the code that gates the logic. The main issue here is
perf impact: without {D122258}, LLD takes a significant perf hit because
it now has to do a lot more work in the input parsing phase. But with
that change to eliminate unnecessary EH frames from input object files,
the perf overhead here is minimal. Concretely, here are the numbers for
some builds as measured on my 16-core Mac Pro:
**chromium_framework**
This is without the use of `-femit-dwarf-unwind=no-compact-unwind`:
base diff difference (95% CI)
sys_time 1.826 ± 0.019 1.962 ± 0.034 [ +6.5% .. +8.4%]
user_time 9.306 ± 0.054 9.926 ± 0.082 [ +6.2% .. +7.1%]
wall_time 8.225 ± 0.068 8.947 ± 0.128 [ +8.0% .. +9.6%]
samples 15 22
With that flag enabled, the regression mostly disappears, as hoped:
base diff difference (95% CI)
sys_time 1.839 ± 0.062 1.866 ± 0.068 [ -0.9% .. +3.8%]
user_time 9.452 ± 0.068 9.490 ± 0.067 [ -0.1% .. +0.9%]
wall_time 8.383 ± 0.127 8.452 ± 0.114 [ -0.1% .. +1.8%]
samples 17 21
**Unnamed internal app**
Without `-femit-dwarf-unwind`, this is the perf hit:
base diff difference (95% CI)
sys_time 1.372 ± 0.029 1.317 ± 0.024 [ -4.6% .. -3.5%]
user_time 2.835 ± 0.028 2.980 ± 0.027 [ +4.8% .. +5.4%]
wall_time 3.205 ± 0.079 3.383 ± 0.066 [ +4.9% .. +6.2%]
samples 102 83
With `-femit-dwarf-unwind`, the perf hit almost disappears:
base diff difference (95% CI)
sys_time 1.274 ± 0.026 1.270 ± 0.025 [ -0.9% .. +0.3%]
user_time 2.812 ± 0.023 2.822 ± 0.035 [ +0.1% .. +0.7%]
wall_time 3.166 ± 0.047 3.174 ± 0.059 [ -0.2% .. +0.7%]
samples 95 97
Just for fun, I measured the impact of `-femit-dwarf-unwind` on ld64
(`base` has the extra DWARF unwind info in the input object files,
`diff` doesn't):
base diff difference (95% CI)
sys_time 1.128 ± 0.010 1.124 ± 0.023 [ -1.3% .. +0.6%]
user_time 7.176 ± 0.030 7.106 ± 0.094 [ -1.5% .. -0.4%]
wall_time 7.874 ± 0.041 7.795 ± 0.121 [ -1.7% .. -0.3%]
samples 16 25
And for LLD:
base diff difference (95% CI)
sys_time 1.315 ± 0.019 1.280 ± 0.019 [ -3.2% .. -2.0%]
user_time 2.980 ± 0.022 2.822 ± 0.016 [ -5.5% .. -5.0%]
wall_time 3.369 ± 0.038 3.175 ± 0.033 [ -6.2% .. -5.3%]
samples 47 47
So parsing the extra EH frames is a lot more expensive for us than for
ld64. But given that we are quite a lot faster than ld64 to begin with,
I guess this isn't entirely unexpected...
Reviewed By: #lld-macho, oontvoo
Differential Revision: https://reviews.llvm.org/D129540
2022-07-13 21:13:45 -04:00
|
|
|
} else if (name == section_names::ehFrame &&
|
2022-06-12 21:56:45 -04:00
|
|
|
segname == segment_names::text) {
|
|
|
|
|
splitEhFrames(data, *sections.back());
|
2021-08-16 15:19:43 -07:00
|
|
|
} else if (segname == segment_names::llvm) {
|
2022-02-15 21:13:41 -05:00
|
|
|
if (config->callGraphProfileSort && name == section_names::cgProfile)
|
|
|
|
|
checkError(parseCallGraph(data, callGraph));
|
2021-08-16 15:19:43 -07:00
|
|
|
// ld64 does not appear to emit contents from sections within the __LLVM
|
|
|
|
|
// segment. Symbols within those sections point to bitcode metadata
|
|
|
|
|
// instead of actual symbols. Global symbols within those sections could
|
2022-02-02 17:08:35 -05:00
|
|
|
// have the same name without causing duplicate symbol errors. To avoid
|
|
|
|
|
// spurious duplicate symbol errors, we do not parse these sections.
|
2021-08-16 15:19:43 -07:00
|
|
|
// TODO: Evaluate whether the bitcode metadata is needed.
|
2022-07-23 12:11:46 -04:00
|
|
|
} else if (name == section_names::objCImageInfo &&
|
|
|
|
|
segname == segment_names::data) {
|
|
|
|
|
objCImageInfo = data;
|
2020-12-08 17:47:19 -08:00
|
|
|
} else {
|
2022-05-03 21:00:41 -04:00
|
|
|
if (name == section_names::addrSig)
|
|
|
|
|
addrSigSection = sections.back();
|
|
|
|
|
|
[lld-macho][nfc] Eliminate InputSection::Shared
Earlier in LLD's evolution, I tried to create the illusion that
subsections were indistinguishable from "top-level" sections. Thus, even
though the subsections shared many common field values, I hid those
common values away in a private Shared struct (see D105305). More
recently, however, @gkm added a public `Section` struct in D113241 that
served as an explicit way to store values that are common to an entire
set of subsections (aka InputSections). Now that we have another "common
value" struct, `Shared` has been rendered redundant. All its fields can
be moved into `Section` instead, and the pointer to `Shared` can be replaced
with a pointer to `Section`.
This `Section` pointer also has the advantage of letting us inspect other
subsections easily, simplifying the implementation of {D118798}.
P.S. I do think that having both `Section` and `InputSection` makes for
a slightly confusing naming scheme. I considered renaming `InputSection`
to `Subsection`, but that would break the symmetry with `OutputSection`.
It would also make us deviate from LLD-ELF's naming scheme.
This change is perf-neutral on my 3.2 GHz 16-Core Intel Xeon W machine:
base diff difference (95% CI)
sys_time 1.258 ± 0.031 1.248 ± 0.023 [ -1.6% .. +0.1%]
user_time 3.659 ± 0.047 3.658 ± 0.041 [ -0.5% .. +0.4%]
wall_time 4.640 ± 0.085 4.625 ± 0.063 [ -1.0% .. +0.3%]
samples 49 61
There's also no stat sig change in RSS (as measured by `time -l`):
base diff difference (95% CI)
time 998038627.097 ± 13567305.958 1003327715.556 ± 15210451.236 [ -0.2% .. +1.2%]
samples 31 36
Reviewed By: #lld-macho, oontvoo
Differential Revision: https://reviews.llvm.org/D118797
2022-02-03 19:53:29 -05:00
|
|
|
auto *isec = make<ConcatInputSection>(section, data, align);
|
2021-08-11 22:08:56 -07:00
|
|
|
if (isDebugSection(isec->getFlags()) &&
|
|
|
|
|
isec->getSegName() == segment_names::dwarf) {
|
[lld-macho] Implement cstring deduplication
Our implementation draws heavily from LLD-ELF's, which in turn delegates
its string deduplication to llvm-mc's StringTableBuilder. The messiness of
this diff is largely due to the fact that we've previously assumed that
all InputSections get concatenated together to form the output. This is
no longer true with CStringInputSections, which split their contents into
StringPieces. StringPieces are much more lightweight than InputSections,
which is important as we create a lot of them. They may also overlap in
the output, which makes it possible for strings to be tail-merged. In
fact, the initial version of this diff implemented tail merging, but
I've dropped it for reasons I'll explain later.
**Alignment Issues**
Mergeable cstring literals are found under the `__TEXT,__cstring`
section. In contrast to ELF, which puts strings that need different
alignments into different sections, clang's Mach-O backend puts them all
in one section. Strings that need to be aligned have the `.p2align`
directive emitted before them, which simply translates into zero padding
in the object file.
I *think* ld64 extracts the desired per-string alignment from this data
by preserving each string's offset from the last section-aligned
address. I'm not entirely certain since it doesn't seem consistent about
doing this; but perhaps this can be chalked up to cases where ld64 has
to deduplicate strings with different offset/alignment combos -- it
seems to pick one of their alignments to preserve. This doesn't seem
correct in general; we can in fact can induce ld64 to produce a crashing
binary just by linking in an additional object file that only contains
cstrings and no code. See PR50563 for details.
Moreover, this scheme seems rather inefficient: since unaligned and
aligned strings are all put in the same section, which has a single
alignment value, it doesn't seem possible to tell whether a given string
doesn't have any alignment requirements. Preserving offset+alignments
for strings that don't need it is wasteful.
In practice, the crashes seen so far seem to stem from x86_64 SIMD
operations on cstrings. X86_64 requires SIMD accesses to be
16-byte-aligned. So for now, I'm thinking of just aligning all strings
to 16 bytes on x86_64. This is indeed wasteful, but implementation-wise
it's simpler than preserving per-string alignment+offsets. It also
avoids the aforementioned crash after deduplication of
differently-aligned strings. Finally, the overhead is not huge: using
16-byte alignment (vs no alignment) is only a 0.5% size overhead when
linking chromium_framework.
With these alignment requirements, it doesn't make sense to attempt tail
merging -- most strings will not be eligible since their overlaps aren't
likely to start at a 16-byte boundary. Tail-merging (with alignment) for
chromium_framework only improves size by 0.3%.
It's worth noting that LLD-ELF only does tail merging at `-O2`. By
default (at `-O1`), it just deduplicates w/o tail merging. @thakis has
also mentioned that they saw it regress compressed size in some cases
and therefore turned it off. `ld64` does not seem to do tail merging at
all.
**Performance Numbers**
CString deduplication reduces chromium_framework from 250MB to 242MB, or
about a 3.2% reduction.
Numbers for linking chromium_framework on my 3.2 GHz 16-Core Intel Xeon W:
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.99 4.14 4.015 4.0365 0.0492336
Difference at 95.0% confidence
0.0865 +/- 0.027245
2.18987% +/- 0.689746%
(Student's t, pooled s = 0.0425673)
As expected, cstring merging incurs some non-trivial overhead.
When passing `--no-literal-merge`, it seems that performance is the
same, i.e. the refactoring in this diff didn't cost us.
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.89 4.02 3.935 3.9435 0.043197831
No difference proven at 95.0% confidence
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D102964
2021-06-07 23:47:12 -04:00
|
|
|
// Instead of emitting DWARF sections, we emit STABS symbols to the
|
|
|
|
|
// object files that contain them. We filter them out early to avoid
|
2022-02-02 17:08:35 -05:00
|
|
|
// parsing their relocations unnecessarily.
|
[lld-macho] Implement cstring deduplication
Our implementation draws heavily from LLD-ELF's, which in turn delegates
its string deduplication to llvm-mc's StringTableBuilder. The messiness of
this diff is largely due to the fact that we've previously assumed that
all InputSections get concatenated together to form the output. This is
no longer true with CStringInputSections, which split their contents into
StringPieces. StringPieces are much more lightweight than InputSections,
which is important as we create a lot of them. They may also overlap in
the output, which makes it possible for strings to be tail-merged. In
fact, the initial version of this diff implemented tail merging, but
I've dropped it for reasons I'll explain later.
**Alignment Issues**
Mergeable cstring literals are found under the `__TEXT,__cstring`
section. In contrast to ELF, which puts strings that need different
alignments into different sections, clang's Mach-O backend puts them all
in one section. Strings that need to be aligned have the `.p2align`
directive emitted before them, which simply translates into zero padding
in the object file.
I *think* ld64 extracts the desired per-string alignment from this data
by preserving each string's offset from the last section-aligned
address. I'm not entirely certain since it doesn't seem consistent about
doing this; but perhaps this can be chalked up to cases where ld64 has
to deduplicate strings with different offset/alignment combos -- it
seems to pick one of their alignments to preserve. This doesn't seem
correct in general; we can in fact can induce ld64 to produce a crashing
binary just by linking in an additional object file that only contains
cstrings and no code. See PR50563 for details.
Moreover, this scheme seems rather inefficient: since unaligned and
aligned strings are all put in the same section, which has a single
alignment value, it doesn't seem possible to tell whether a given string
doesn't have any alignment requirements. Preserving offset+alignments
for strings that don't need it is wasteful.
In practice, the crashes seen so far seem to stem from x86_64 SIMD
operations on cstrings. X86_64 requires SIMD accesses to be
16-byte-aligned. So for now, I'm thinking of just aligning all strings
to 16 bytes on x86_64. This is indeed wasteful, but implementation-wise
it's simpler than preserving per-string alignment+offsets. It also
avoids the aforementioned crash after deduplication of
differently-aligned strings. Finally, the overhead is not huge: using
16-byte alignment (vs no alignment) is only a 0.5% size overhead when
linking chromium_framework.
With these alignment requirements, it doesn't make sense to attempt tail
merging -- most strings will not be eligible since their overlaps aren't
likely to start at a 16-byte boundary. Tail-merging (with alignment) for
chromium_framework only improves size by 0.3%.
It's worth noting that LLD-ELF only does tail merging at `-O2`. By
default (at `-O1`), it just deduplicates w/o tail merging. @thakis has
also mentioned that they saw it regress compressed size in some cases
and therefore turned it off. `ld64` does not seem to do tail merging at
all.
**Performance Numbers**
CString deduplication reduces chromium_framework from 250MB to 242MB, or
about a 3.2% reduction.
Numbers for linking chromium_framework on my 3.2 GHz 16-Core Intel Xeon W:
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.99 4.14 4.015 4.0365 0.0492336
Difference at 95.0% confidence
0.0865 +/- 0.027245
2.18987% +/- 0.689746%
(Student's t, pooled s = 0.0425673)
As expected, cstring merging incurs some non-trivial overhead.
When passing `--no-literal-merge`, it seems that performance is the
same, i.e. the refactoring in this diff didn't cost us.
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.89 4.02 3.935 3.9435 0.043197831
No difference proven at 95.0% confidence
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D102964
2021-06-07 23:47:12 -04:00
|
|
|
debugSections.push_back(isec);
|
2021-08-11 22:08:56 -07:00
|
|
|
} else {
|
2022-04-07 14:28:44 -04:00
|
|
|
section.subsections.push_back({0, isec});
|
[lld-macho] Implement cstring deduplication
Our implementation draws heavily from LLD-ELF's, which in turn delegates
its string deduplication to llvm-mc's StringTableBuilder. The messiness of
this diff is largely due to the fact that we've previously assumed that
all InputSections get concatenated together to form the output. This is
no longer true with CStringInputSections, which split their contents into
StringPieces. StringPieces are much more lightweight than InputSections,
which is important as we create a lot of them. They may also overlap in
the output, which makes it possible for strings to be tail-merged. In
fact, the initial version of this diff implemented tail merging, but
I've dropped it for reasons I'll explain later.
**Alignment Issues**
Mergeable cstring literals are found under the `__TEXT,__cstring`
section. In contrast to ELF, which puts strings that need different
alignments into different sections, clang's Mach-O backend puts them all
in one section. Strings that need to be aligned have the `.p2align`
directive emitted before them, which simply translates into zero padding
in the object file.
I *think* ld64 extracts the desired per-string alignment from this data
by preserving each string's offset from the last section-aligned
address. I'm not entirely certain since it doesn't seem consistent about
doing this; but perhaps this can be chalked up to cases where ld64 has
to deduplicate strings with different offset/alignment combos -- it
seems to pick one of their alignments to preserve. This doesn't seem
correct in general; we can in fact can induce ld64 to produce a crashing
binary just by linking in an additional object file that only contains
cstrings and no code. See PR50563 for details.
Moreover, this scheme seems rather inefficient: since unaligned and
aligned strings are all put in the same section, which has a single
alignment value, it doesn't seem possible to tell whether a given string
doesn't have any alignment requirements. Preserving offset+alignments
for strings that don't need it is wasteful.
In practice, the crashes seen so far seem to stem from x86_64 SIMD
operations on cstrings. X86_64 requires SIMD accesses to be
16-byte-aligned. So for now, I'm thinking of just aligning all strings
to 16 bytes on x86_64. This is indeed wasteful, but implementation-wise
it's simpler than preserving per-string alignment+offsets. It also
avoids the aforementioned crash after deduplication of
differently-aligned strings. Finally, the overhead is not huge: using
16-byte alignment (vs no alignment) is only a 0.5% size overhead when
linking chromium_framework.
With these alignment requirements, it doesn't make sense to attempt tail
merging -- most strings will not be eligible since their overlaps aren't
likely to start at a 16-byte boundary. Tail-merging (with alignment) for
chromium_framework only improves size by 0.3%.
It's worth noting that LLD-ELF only does tail merging at `-O2`. By
default (at `-O1`), it just deduplicates w/o tail merging. @thakis has
also mentioned that they saw it regress compressed size in some cases
and therefore turned it off. `ld64` does not seem to do tail merging at
all.
**Performance Numbers**
CString deduplication reduces chromium_framework from 250MB to 242MB, or
about a 3.2% reduction.
Numbers for linking chromium_framework on my 3.2 GHz 16-Core Intel Xeon W:
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.99 4.14 4.015 4.0365 0.0492336
Difference at 95.0% confidence
0.0865 +/- 0.027245
2.18987% +/- 0.689746%
(Student's t, pooled s = 0.0425673)
As expected, cstring merging incurs some non-trivial overhead.
When passing `--no-literal-merge`, it seems that performance is the
same, i.e. the refactoring in this diff didn't cost us.
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.89 4.02 3.935 3.9435 0.043197831
No difference proven at 95.0% confidence
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D102964
2021-06-07 23:47:12 -04:00
|
|
|
}
|
2020-12-08 17:47:19 -08:00
|
|
|
}
|
2020-04-02 11:54:05 -07:00
|
|
|
}
|
[lld-macho][re-land] Support .subsections_via_symbols
Summary:
This diff restores and builds upon @pcc and @ruiu's initial work on
subsections.
The .subsections_via_symbols directive indicates we can split each
section along symbol boundaries, unless those symbols have been marked
with `.alt_entry`.
We exercise this functionality in our tests by using order files that
rearrange those symbols.
Depends on D79668.
Reviewers: ruiu, pcc, MaskRay, smeenai, alexshap, gkm, Ktwu, christylee
Reviewed By: smeenai
Subscribers: thakis, llvm-commits, pcc, ruiu
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D79926
2020-05-19 08:46:07 -07:00
|
|
|
}
|
2020-04-02 11:54:05 -07:00
|
|
|
|
2022-06-12 21:56:45 -04:00
|
|
|
void ObjFile::splitEhFrames(ArrayRef<uint8_t> data, Section &ehFrameSection) {
|
2022-07-31 20:16:08 -04:00
|
|
|
EhReader reader(this, data, /*dataOff=*/0);
|
2022-06-12 21:56:45 -04:00
|
|
|
size_t off = 0;
|
|
|
|
|
while (off < reader.size()) {
|
|
|
|
|
uint64_t frameOff = off;
|
|
|
|
|
uint64_t length = reader.readLength(&off);
|
|
|
|
|
if (length == 0)
|
|
|
|
|
break;
|
|
|
|
|
uint64_t fullLength = length + (off - frameOff);
|
|
|
|
|
off += length;
|
|
|
|
|
// We hard-code an alignment of 1 here because we don't actually want our
|
|
|
|
|
// EH frames to be aligned to the section alignment. EH frame decoders don't
|
|
|
|
|
// expect this alignment. Moreover, each EH frame must start where the
|
|
|
|
|
// previous one ends, and where it ends is indicated by the length field.
|
|
|
|
|
// Unless we update the length field (troublesome), we should keep the
|
|
|
|
|
// alignment to 1.
|
|
|
|
|
// Note that we still want to preserve the alignment of the overall section,
|
|
|
|
|
// just not of the individual EH frames.
|
|
|
|
|
ehFrameSection.subsections.push_back(
|
|
|
|
|
{frameOff, make<ConcatInputSection>(ehFrameSection,
|
|
|
|
|
data.slice(frameOff, fullLength),
|
|
|
|
|
/*align=*/1)});
|
|
|
|
|
}
|
|
|
|
|
ehFrameSection.doneSplitting = true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
template <class T>
|
|
|
|
|
static Section *findContainingSection(const std::vector<Section *> §ions,
|
|
|
|
|
T *offset) {
|
2022-08-20 23:00:39 -07:00
|
|
|
static_assert(std::is_same<uint64_t, T>::value ||
|
|
|
|
|
std::is_same<uint32_t, T>::value,
|
2022-06-12 21:56:45 -04:00
|
|
|
"unexpected type for offset");
|
|
|
|
|
auto it = std::prev(llvm::upper_bound(
|
|
|
|
|
sections, *offset,
|
|
|
|
|
[](uint64_t value, const Section *sec) { return value < sec->addr; }));
|
|
|
|
|
*offset -= (*it)->addr;
|
|
|
|
|
return *it;
|
|
|
|
|
}
|
|
|
|
|
|
[lld-macho][re-land] Support .subsections_via_symbols
Summary:
This diff restores and builds upon @pcc and @ruiu's initial work on
subsections.
The .subsections_via_symbols directive indicates we can split each
section along symbol boundaries, unless those symbols have been marked
with `.alt_entry`.
We exercise this functionality in our tests by using order files that
rearrange those symbols.
Depends on D79668.
Reviewers: ruiu, pcc, MaskRay, smeenai, alexshap, gkm, Ktwu, christylee
Reviewed By: smeenai
Subscribers: thakis, llvm-commits, pcc, ruiu
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D79926
2020-05-19 08:46:07 -07:00
|
|
|
// Find the subsection corresponding to the greatest section offset that is <=
|
|
|
|
|
// that of the given offset.
|
|
|
|
|
//
|
|
|
|
|
// offset: an offset relative to the start of the original InputSection (before
|
|
|
|
|
// any subsection splitting has occurred). It will be updated to represent the
|
|
|
|
|
// same location as an offset relative to the start of the containing
|
|
|
|
|
// subsection.
|
2021-11-12 16:07:07 -08:00
|
|
|
template <class T>
|
2022-03-16 18:05:32 -04:00
|
|
|
static InputSection *findContainingSubsection(const Section §ion,
|
2021-11-12 16:07:07 -08:00
|
|
|
T *offset) {
|
2022-08-20 23:00:39 -07:00
|
|
|
static_assert(std::is_same<uint64_t, T>::value ||
|
|
|
|
|
std::is_same<uint32_t, T>::value,
|
2021-11-16 19:57:24 -05:00
|
|
|
"unexpected type for offset");
|
2021-03-31 15:23:19 -07:00
|
|
|
auto it = std::prev(llvm::upper_bound(
|
2022-03-16 18:05:32 -04:00
|
|
|
section.subsections, *offset,
|
2021-11-04 20:55:31 -07:00
|
|
|
[](uint64_t value, Subsection subsec) { return value < subsec.offset; }));
|
2021-03-31 15:23:19 -07:00
|
|
|
*offset -= it->offset;
|
|
|
|
|
return it->isec;
|
2020-04-02 11:54:05 -07:00
|
|
|
}
|
|
|
|
|
|
2022-04-07 09:05:33 -04:00
|
|
|
// Find a symbol at offset `off` within `isec`.
|
|
|
|
|
static Defined *findSymbolAtOffset(const ConcatInputSection *isec,
|
|
|
|
|
uint64_t off) {
|
|
|
|
|
auto it = llvm::lower_bound(isec->symbols, off, [](Defined *d, uint64_t off) {
|
|
|
|
|
return d->value < off;
|
|
|
|
|
});
|
|
|
|
|
// The offset should point at the exact address of a symbol (with no addend.)
|
|
|
|
|
if (it == isec->symbols.end() || (*it)->value != off) {
|
|
|
|
|
assert(isec->wasCoalesced);
|
|
|
|
|
return nullptr;
|
|
|
|
|
}
|
|
|
|
|
return *it;
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-04 20:55:31 -07:00
|
|
|
template <class SectionHeader>
|
|
|
|
|
static bool validateRelocationInfo(InputFile *file, const SectionHeader &sec,
|
2021-01-19 07:44:42 -08:00
|
|
|
relocation_info rel) {
|
2021-03-11 13:28:09 -05:00
|
|
|
const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
|
2021-01-19 07:44:42 -08:00
|
|
|
bool valid = true;
|
2021-02-23 21:41:52 -05:00
|
|
|
auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
|
2021-01-19 07:44:42 -08:00
|
|
|
valid = false;
|
|
|
|
|
return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
|
|
|
|
|
std::to_string(rel.r_address) + " of " + sec.segname + "," +
|
2021-02-23 21:41:52 -05:00
|
|
|
sec.sectname + " in " + toString(file))
|
2021-01-19 07:44:42 -08:00
|
|
|
.str();
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
|
|
|
|
|
error(message("must be extern"));
|
|
|
|
|
if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
|
|
|
|
|
error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
|
|
|
|
|
"be PC-relative"));
|
|
|
|
|
if (isThreadLocalVariables(sec.flags) &&
|
2021-02-23 21:41:54 -05:00
|
|
|
!relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
|
2021-01-19 07:44:42 -08:00
|
|
|
error(message("not allowed in thread-local section, must be UNSIGNED"));
|
2025-10-27 11:55:05 -04:00
|
|
|
if (!relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
|
|
|
|
|
error(message("has invalid width of " + std::to_string(1 << rel.r_length) +
|
2021-01-19 07:44:42 -08:00
|
|
|
" bytes"));
|
|
|
|
|
}
|
|
|
|
|
return valid;
|
|
|
|
|
}
|
|
|
|
|
|
2021-11-04 20:55:31 -07:00
|
|
|
template <class SectionHeader>
|
|
|
|
|
void ObjFile::parseRelocations(ArrayRef<SectionHeader> sectionHeaders,
|
2022-05-24 07:59:18 +07:00
|
|
|
const SectionHeader &sec, Section §ion) {
|
2020-04-02 11:54:05 -07:00
|
|
|
auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
|
2020-10-14 09:49:54 -07:00
|
|
|
ArrayRef<relocation_info> relInfos(
|
|
|
|
|
reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
|
2020-04-02 11:54:05 -07:00
|
|
|
|
2022-03-16 18:05:32 -04:00
|
|
|
Subsections &subsections = section.subsections;
|
2021-11-04 20:55:31 -07:00
|
|
|
auto subsecIt = subsections.rbegin();
|
2020-10-14 09:49:54 -07:00
|
|
|
for (size_t i = 0; i < relInfos.size(); i++) {
|
|
|
|
|
// Paired relocations serve as Mach-O's method for attaching a
|
|
|
|
|
// supplemental datum to a primary relocation record. ELF does not
|
|
|
|
|
// need them because the *_RELOC_RELA records contain the extra
|
|
|
|
|
// addend field, vs. *_RELOC_REL which omit the addend.
|
|
|
|
|
//
|
|
|
|
|
// The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
|
|
|
|
|
// and the paired *_RELOC_UNSIGNED record holds the minuend. The
|
2021-01-19 07:44:42 -08:00
|
|
|
// datum for each is a symbolic address. The result is the offset
|
|
|
|
|
// between two addresses.
|
2020-10-14 09:49:54 -07:00
|
|
|
//
|
|
|
|
|
// The ARM64_RELOC_ADDEND record holds the addend, and the paired
|
|
|
|
|
// ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
|
|
|
|
|
// base symbolic address.
|
|
|
|
|
//
|
2022-11-08 17:28:04 -08:00
|
|
|
// Note: X86 does not use *_RELOC_ADDEND because it can embed an addend into
|
|
|
|
|
// the instruction stream. On X86, a relocatable address field always
|
|
|
|
|
// occupies an entire contiguous sequence of byte(s), so there is no need to
|
|
|
|
|
// merge opcode bits with address bits. Therefore, it's easy and convenient
|
|
|
|
|
// to store addends in the instruction-stream bytes that would otherwise
|
|
|
|
|
// contain zeroes. By contrast, RISC ISAs such as ARM64 mix opcode bits with
|
|
|
|
|
// address bits so that bitwise arithmetic is necessary to extract and
|
|
|
|
|
// insert them. Storing addends in the instruction stream is possible, but
|
|
|
|
|
// inconvenient and more costly at link time.
|
[lld-macho][re-land] Support .subsections_via_symbols
Summary:
This diff restores and builds upon @pcc and @ruiu's initial work on
subsections.
The .subsections_via_symbols directive indicates we can split each
section along symbol boundaries, unless those symbols have been marked
with `.alt_entry`.
We exercise this functionality in our tests by using order files that
rearrange those symbols.
Depends on D79668.
Reviewers: ruiu, pcc, MaskRay, smeenai, alexshap, gkm, Ktwu, christylee
Reviewed By: smeenai
Subscribers: thakis, llvm-commits, pcc, ruiu
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D79926
2020-05-19 08:46:07 -07:00
|
|
|
|
2021-01-19 07:44:42 -08:00
|
|
|
relocation_info relInfo = relInfos[i];
|
2021-11-15 11:46:59 -07:00
|
|
|
bool isSubtrahend =
|
|
|
|
|
target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND);
|
|
|
|
|
int64_t pairedAddend = 0;
|
2021-01-19 07:44:42 -08:00
|
|
|
if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
|
|
|
|
|
pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
|
|
|
|
|
relInfo = relInfos[++i];
|
|
|
|
|
}
|
2020-10-14 09:49:54 -07:00
|
|
|
assert(i < relInfos.size());
|
2021-02-23 21:41:52 -05:00
|
|
|
if (!validateRelocationInfo(this, sec, relInfo))
|
2021-01-19 07:44:42 -08:00
|
|
|
continue;
|
2020-10-14 09:49:54 -07:00
|
|
|
if (relInfo.r_address & R_SCATTERED)
|
|
|
|
|
fatal("TODO: Scattered relocations not supported");
|
[lld-macho][re-land] Support .subsections_via_symbols
Summary:
This diff restores and builds upon @pcc and @ruiu's initial work on
subsections.
The .subsections_via_symbols directive indicates we can split each
section along symbol boundaries, unless those symbols have been marked
with `.alt_entry`.
We exercise this functionality in our tests by using order files that
rearrange those symbols.
Depends on D79668.
Reviewers: ruiu, pcc, MaskRay, smeenai, alexshap, gkm, Ktwu, christylee
Reviewed By: smeenai
Subscribers: thakis, llvm-commits, pcc, ruiu
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D79926
2020-05-19 08:46:07 -07:00
|
|
|
|
2021-04-02 18:46:18 -04:00
|
|
|
int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo);
|
2021-02-27 12:30:19 -05:00
|
|
|
assert(!(embeddedAddend && pairedAddend));
|
2021-03-12 17:26:11 -05:00
|
|
|
int64_t totalAddend = pairedAddend + embeddedAddend;
|
2020-04-02 11:54:05 -07:00
|
|
|
Reloc r;
|
2020-09-12 20:45:00 -07:00
|
|
|
r.type = relInfo.r_type;
|
|
|
|
|
r.pcrel = relInfo.r_pcrel;
|
|
|
|
|
r.length = relInfo.r_length;
|
2020-10-14 09:49:54 -07:00
|
|
|
r.offset = relInfo.r_address;
|
2020-09-12 20:45:00 -07:00
|
|
|
if (relInfo.r_extern) {
|
|
|
|
|
r.referent = symbols[relInfo.r_symbolnum];
|
2021-04-20 16:58:06 -04:00
|
|
|
r.addend = isSubtrahend ? 0 : totalAddend;
|
2020-04-02 11:54:05 -07:00
|
|
|
} else {
|
2021-04-20 16:58:06 -04:00
|
|
|
assert(!isSubtrahend);
|
2021-11-04 20:55:31 -07:00
|
|
|
const SectionHeader &referentSecHead =
|
|
|
|
|
sectionHeaders[relInfo.r_symbolnum - 1];
|
2021-03-31 15:23:19 -07:00
|
|
|
uint64_t referentOffset;
|
2020-09-12 20:45:00 -07:00
|
|
|
if (relInfo.r_pcrel) {
|
2020-06-13 19:56:04 -07:00
|
|
|
// The implicit addend for pcrel section relocations is the pcrel offset
|
|
|
|
|
// in terms of the addresses in the input file. Here we adjust it so
|
2020-09-12 20:45:00 -07:00
|
|
|
// that it describes the offset from the start of the referent section.
|
2021-03-11 13:28:11 -05:00
|
|
|
// FIXME This logic was written around x86_64 behavior -- ARM64 doesn't
|
|
|
|
|
// have pcrel section relocations. We may want to factor this out into
|
|
|
|
|
// the arch-specific .cpp file.
|
2021-03-01 12:30:08 -05:00
|
|
|
assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
|
2021-11-04 20:55:31 -07:00
|
|
|
referentOffset = sec.addr + relInfo.r_address + 4 + totalAddend -
|
|
|
|
|
referentSecHead.addr;
|
2020-06-13 19:56:04 -07:00
|
|
|
} else {
|
|
|
|
|
// The addend for a non-pcrel relocation is its absolute address.
|
2021-11-04 20:55:31 -07:00
|
|
|
referentOffset = totalAddend - referentSecHead.addr;
|
2020-06-13 19:56:04 -07:00
|
|
|
}
|
2022-03-16 18:05:32 -04:00
|
|
|
r.referent = findContainingSubsection(*sections[relInfo.r_symbolnum - 1],
|
|
|
|
|
&referentOffset);
|
2020-09-12 20:45:00 -07:00
|
|
|
r.addend = referentOffset;
|
2020-04-02 11:54:05 -07:00
|
|
|
}
|
[lld-macho][re-land] Support .subsections_via_symbols
Summary:
This diff restores and builds upon @pcc and @ruiu's initial work on
subsections.
The .subsections_via_symbols directive indicates we can split each
section along symbol boundaries, unless those symbols have been marked
with `.alt_entry`.
We exercise this functionality in our tests by using order files that
rearrange those symbols.
Depends on D79668.
Reviewers: ruiu, pcc, MaskRay, smeenai, alexshap, gkm, Ktwu, christylee
Reviewed By: smeenai
Subscribers: thakis, llvm-commits, pcc, ruiu
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D79926
2020-05-19 08:46:07 -07:00
|
|
|
|
2021-07-05 01:13:30 -04:00
|
|
|
// Find the subsection that this relocation belongs to.
|
|
|
|
|
// Though not required by the Mach-O format, clang and gcc seem to emit
|
|
|
|
|
// relocations in order, so let's take advantage of it. However, ld64 emits
|
|
|
|
|
// unsorted relocations (in `-r` mode), so we have a fallback for that
|
|
|
|
|
// uncommon case.
|
|
|
|
|
InputSection *subsec;
|
2021-11-04 20:55:31 -07:00
|
|
|
while (subsecIt != subsections.rend() && subsecIt->offset > r.offset)
|
2021-07-05 01:13:30 -04:00
|
|
|
++subsecIt;
|
2021-11-04 20:55:31 -07:00
|
|
|
if (subsecIt == subsections.rend() ||
|
2021-07-05 01:13:30 -04:00
|
|
|
subsecIt->offset + subsecIt->isec->getSize() <= r.offset) {
|
2022-03-16 18:05:32 -04:00
|
|
|
subsec = findContainingSubsection(section, &r.offset);
|
2021-07-05 01:13:30 -04:00
|
|
|
// Now that we know the relocs are unsorted, avoid trying the 'fast path'
|
|
|
|
|
// for the other relocations.
|
2021-11-04 20:55:31 -07:00
|
|
|
subsecIt = subsections.rend();
|
2021-07-05 01:13:30 -04:00
|
|
|
} else {
|
|
|
|
|
subsec = subsecIt->isec;
|
|
|
|
|
r.offset -= subsecIt->offset;
|
|
|
|
|
}
|
[lld-macho][re-land] Support .subsections_via_symbols
Summary:
This diff restores and builds upon @pcc and @ruiu's initial work on
subsections.
The .subsections_via_symbols directive indicates we can split each
section along symbol boundaries, unless those symbols have been marked
with `.alt_entry`.
We exercise this functionality in our tests by using order files that
rearrange those symbols.
Depends on D79668.
Reviewers: ruiu, pcc, MaskRay, smeenai, alexshap, gkm, Ktwu, christylee
Reviewed By: smeenai
Subscribers: thakis, llvm-commits, pcc, ruiu
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D79926
2020-05-19 08:46:07 -07:00
|
|
|
subsec->relocs.push_back(r);
|
2021-03-11 13:28:13 -05:00
|
|
|
|
2021-04-20 16:58:06 -04:00
|
|
|
if (isSubtrahend) {
|
|
|
|
|
relocation_info minuendInfo = relInfos[++i];
|
2021-03-11 13:28:13 -05:00
|
|
|
// SUBTRACTOR relocations should always be followed by an UNSIGNED one
|
2021-04-20 16:58:06 -04:00
|
|
|
// attached to the same address.
|
|
|
|
|
assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) &&
|
|
|
|
|
relInfo.r_address == minuendInfo.r_address);
|
2021-03-11 13:28:13 -05:00
|
|
|
Reloc p;
|
2021-04-20 16:58:06 -04:00
|
|
|
p.type = minuendInfo.r_type;
|
|
|
|
|
if (minuendInfo.r_extern) {
|
|
|
|
|
p.referent = symbols[minuendInfo.r_symbolnum];
|
|
|
|
|
p.addend = totalAddend;
|
|
|
|
|
} else {
|
|
|
|
|
uint64_t referentOffset =
|
|
|
|
|
totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr;
|
2022-03-16 18:05:32 -04:00
|
|
|
p.referent = findContainingSubsection(
|
|
|
|
|
*sections[minuendInfo.r_symbolnum - 1], &referentOffset);
|
2021-04-20 16:58:06 -04:00
|
|
|
p.addend = referentOffset;
|
|
|
|
|
}
|
2021-03-11 13:28:13 -05:00
|
|
|
subsec->relocs.push_back(p);
|
|
|
|
|
}
|
[lld-macho][re-land] Support .subsections_via_symbols
Summary:
This diff restores and builds upon @pcc and @ruiu's initial work on
subsections.
The .subsections_via_symbols directive indicates we can split each
section along symbol boundaries, unless those symbols have been marked
with `.alt_entry`.
We exercise this functionality in our tests by using order files that
rearrange those symbols.
Depends on D79668.
Reviewers: ruiu, pcc, MaskRay, smeenai, alexshap, gkm, Ktwu, christylee
Reviewed By: smeenai
Subscribers: thakis, llvm-commits, pcc, ruiu
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D79926
2020-05-19 08:46:07 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-04-02 18:46:18 -04:00
|
|
|
template <class NList>
|
|
|
|
|
static macho::Symbol *createDefined(const NList &sym, StringRef name,
|
|
|
|
|
InputSection *isec, uint64_t value,
|
2022-07-25 11:45:55 +02:00
|
|
|
uint64_t size, bool forceHidden) {
|
[lld/mac] Implement support for private extern symbols
Private extern symbols are used for things scoped to the linkage unit.
They cause duplicate symbol errors (so they're in the symbol table,
unlike TU-scoped truly local symbols), but they don't make it into the
export trie. They are created e.g. by compiling with
-fvisibility=hidden.
If two weak symbols have differing privateness, the combined symbol is
non-private external. (Example: inline functions and some TUs that
include the header defining it were built with
-fvisibility-inlines-hidden and some weren't).
A weak private external symbol implicitly has its "weak" dropped and
behaves like a regular strong private external symbol: Weak is an export
trie concept, and private symbols are not in the export trie.
If a weak and a strong symbol have different privateness, the strong
symbol wins.
If two common symbols have differing privateness, the larger symbol
wins. If they have the same size, the privateness of the symbol seen
later during the link wins (!) -- this is a bit lame, but it matches
ld64 and this behavior takes 2 lines less to implement than the less
surprising "result is non-private external), so match ld64.
(Example: `int a` in two .c files, both built with -fcommon,
one built with -fvisibility=hidden and one without.)
This also makes `__dyld_private` a true TU-local symbol, matching ld64.
To make this work, make the `const char*` StringRefZ ctor to correctly
set `size` (without this, writing the string table crashed when calling
getName() on the __dyld_private symbol).
Mention in CommonSymbol's comment that common symbols are now disabled
by default in clang.
Mention in -keep_private_externs's HelpText that the flag only has an
effect with `-r` (which we don't implement yet -- so this patch here
doesn't regress any behavior around -r + -keep_private_externs)). ld64
doesn't explicitly document it, but the commit text of
http://reviews.llvm.org/rL216146 does, and ld64's
OutputFile::buildSymbolTable() checks `_options.outputKind() ==
Options::kObjectFile` before calling `_options.keepPrivateExterns()`
(the only reference to that function).
Fixes PR48536.
Differential Revision: https://reviews.llvm.org/D93609
2020-12-17 13:30:18 -05:00
|
|
|
// Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
|
[lld/mac] Implement support for .weak_def_can_be_hidden
I first had a more invasive patch for this (D101069), but while trying
to get that polished for review I realized that lld's current symbol
merging semantics mean that only a very small code change is needed.
So this goes with the smaller patch for now.
This has no effect on projects that build with -fvisibility=hidden
(e.g. chromium), since these see .private_extern symbols instead.
It does have an effect on projects that build with -fvisibility-inlines-hidden
(e.g. llvm) in -O2 builds, where LLVM's GlobalOpt pass will promote most inline
functions from .weak_definition to .weak_def_can_be_hidden.
Before this patch:
% ls -l out/gn/bin/clang out/gn/lib/libclang.dylib
-rwxr-xr-x 1 thakis staff 113059936 Apr 22 11:51 out/gn/bin/clang
-rwxr-xr-x 1 thakis staff 86370064 Apr 22 11:51 out/gn/lib/libclang.dylib
% out/gn/bin/llvm-objdump --macho --weak-bind out/gn/bin/clang | wc -l
8291
% out/gn/bin/llvm-objdump --macho --weak-bind out/gn/lib/libclang.dylib | wc -l
5698
With this patch:
% ls -l out/gn/bin/clang out/gn/lib/libclang.dylib
-rwxr-xr-x 1 thakis staff 111721096 Apr 22 11:55 out/gn/bin/clang
-rwxr-xr-x 1 thakis staff 85291208 Apr 22 11:55 out/gn/lib/libclang.dylib
thakis@MBP llvm-project % out/gn/bin/llvm-objdump --macho --weak-bind out/gn/bin/clang | wc -l
725
thakis@MBP llvm-project % out/gn/bin/llvm-objdump --macho --weak-bind out/gn/lib/libclang.dylib | wc -l
542
Linking clang becomes a tiny bit faster with this patch:
x 100 0.67263818 0.77847815 0.69430709 0.69877208 0.017715892
+ 100 0.67209601 0.73323393 0.68600798 0.68917346 0.012824377
Difference at 95.0% confidence
-0.00959861 +/- 0.00428661
-1.37364% +/- 0.613449%
(Student's t, pooled s = 0.0154648)
This only happens if lld with the patch and lld without the patch are both
linked with an lld with the patch or both linked with an lld without the patch
(...or with ld64). I accidentally linked the lld with the patch with an lld
without the patch and the other way round at first. In that setup, no
difference is found. That makese sense, since having fewer weak imports will
make the linked output a bit faster too. So not only does this make linking
binaries such as clang a bit faster (since fewer exports need to be written to
the export trie by lld), the linked output binary binary is also a bit faster
(since dyld needs to process fewer dynamic imports).
This also happens to fix the one `check-clang` failure when using lld as host
linker, but mostly for silly reasons: See crbug.com/1183336, mostly comment 26.
The real bug here is that c-index-test links all of LLVM both statically and
dynamically, which is an ODR violation. Things just happen to work with this
patch.
So after this patch, check-clang, check-lld, check-llvm all pass with lld as
host linker :)
Differential Revision: https://reviews.llvm.org/D101080
2021-04-22 11:28:35 -04:00
|
|
|
// N_EXT: Global symbols. These go in the symbol table during the link,
|
|
|
|
|
// and also in the export table of the output so that the dynamic
|
|
|
|
|
// linker sees them.
|
|
|
|
|
// N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the
|
|
|
|
|
// symbol table during the link so that duplicates are
|
|
|
|
|
// either reported (for non-weak symbols) or merged
|
|
|
|
|
// (for weak symbols), but they do not go in the export
|
|
|
|
|
// table of the output.
|
2021-06-18 16:35:46 -04:00
|
|
|
// N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits
|
|
|
|
|
// object files) may produce them. LLD does not yet support -r.
|
|
|
|
|
// These are translation-unit scoped, identical to the `0` case.
|
[lld/mac] Implement support for .weak_def_can_be_hidden
I first had a more invasive patch for this (D101069), but while trying
to get that polished for review I realized that lld's current symbol
merging semantics mean that only a very small code change is needed.
So this goes with the smaller patch for now.
This has no effect on projects that build with -fvisibility=hidden
(e.g. chromium), since these see .private_extern symbols instead.
It does have an effect on projects that build with -fvisibility-inlines-hidden
(e.g. llvm) in -O2 builds, where LLVM's GlobalOpt pass will promote most inline
functions from .weak_definition to .weak_def_can_be_hidden.
Before this patch:
% ls -l out/gn/bin/clang out/gn/lib/libclang.dylib
-rwxr-xr-x 1 thakis staff 113059936 Apr 22 11:51 out/gn/bin/clang
-rwxr-xr-x 1 thakis staff 86370064 Apr 22 11:51 out/gn/lib/libclang.dylib
% out/gn/bin/llvm-objdump --macho --weak-bind out/gn/bin/clang | wc -l
8291
% out/gn/bin/llvm-objdump --macho --weak-bind out/gn/lib/libclang.dylib | wc -l
5698
With this patch:
% ls -l out/gn/bin/clang out/gn/lib/libclang.dylib
-rwxr-xr-x 1 thakis staff 111721096 Apr 22 11:55 out/gn/bin/clang
-rwxr-xr-x 1 thakis staff 85291208 Apr 22 11:55 out/gn/lib/libclang.dylib
thakis@MBP llvm-project % out/gn/bin/llvm-objdump --macho --weak-bind out/gn/bin/clang | wc -l
725
thakis@MBP llvm-project % out/gn/bin/llvm-objdump --macho --weak-bind out/gn/lib/libclang.dylib | wc -l
542
Linking clang becomes a tiny bit faster with this patch:
x 100 0.67263818 0.77847815 0.69430709 0.69877208 0.017715892
+ 100 0.67209601 0.73323393 0.68600798 0.68917346 0.012824377
Difference at 95.0% confidence
-0.00959861 +/- 0.00428661
-1.37364% +/- 0.613449%
(Student's t, pooled s = 0.0154648)
This only happens if lld with the patch and lld without the patch are both
linked with an lld with the patch or both linked with an lld without the patch
(...or with ld64). I accidentally linked the lld with the patch with an lld
without the patch and the other way round at first. In that setup, no
difference is found. That makese sense, since having fewer weak imports will
make the linked output a bit faster too. So not only does this make linking
binaries such as clang a bit faster (since fewer exports need to be written to
the export trie by lld), the linked output binary binary is also a bit faster
(since dyld needs to process fewer dynamic imports).
This also happens to fix the one `check-clang` failure when using lld as host
linker, but mostly for silly reasons: See crbug.com/1183336, mostly comment 26.
The real bug here is that c-index-test links all of LLVM both statically and
dynamically, which is an ODR violation. Things just happen to work with this
patch.
So after this patch, check-clang, check-lld, check-llvm all pass with lld as
host linker :)
Differential Revision: https://reviews.llvm.org/D101080
2021-04-22 11:28:35 -04:00
|
|
|
// 0: Translation-unit scoped. These are not in the symbol table during
|
|
|
|
|
// link, and not in the export table of the output either.
|
|
|
|
|
bool isWeakDefCanBeHidden =
|
|
|
|
|
(sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF);
|
[lld/mac] Implement support for private extern symbols
Private extern symbols are used for things scoped to the linkage unit.
They cause duplicate symbol errors (so they're in the symbol table,
unlike TU-scoped truly local symbols), but they don't make it into the
export trie. They are created e.g. by compiling with
-fvisibility=hidden.
If two weak symbols have differing privateness, the combined symbol is
non-private external. (Example: inline functions and some TUs that
include the header defining it were built with
-fvisibility-inlines-hidden and some weren't).
A weak private external symbol implicitly has its "weak" dropped and
behaves like a regular strong private external symbol: Weak is an export
trie concept, and private symbols are not in the export trie.
If a weak and a strong symbol have different privateness, the strong
symbol wins.
If two common symbols have differing privateness, the larger symbol
wins. If they have the same size, the privateness of the symbol seen
later during the link wins (!) -- this is a bit lame, but it matches
ld64 and this behavior takes 2 lines less to implement than the less
surprising "result is non-private external), so match ld64.
(Example: `int a` in two .c files, both built with -fcommon,
one built with -fvisibility=hidden and one without.)
This also makes `__dyld_private` a true TU-local symbol, matching ld64.
To make this work, make the `const char*` StringRefZ ctor to correctly
set `size` (without this, writing the string table crashed when calling
getName() on the __dyld_private symbol).
Mention in CommonSymbol's comment that common symbols are now disabled
by default in clang.
Mention in -keep_private_externs's HelpText that the flag only has an
effect with `-r` (which we don't implement yet -- so this patch here
doesn't regress any behavior around -r + -keep_private_externs)). ld64
doesn't explicitly document it, but the commit text of
http://reviews.llvm.org/rL216146 does, and ld64's
OutputFile::buildSymbolTable() checks `_options.outputKind() ==
Options::kObjectFile` before calling `_options.keepPrivateExterns()`
(the only reference to that function).
Fixes PR48536.
Differential Revision: https://reviews.llvm.org/D93609
2020-12-17 13:30:18 -05:00
|
|
|
|
2023-05-15 02:00:29 -07:00
|
|
|
assert(!(sym.n_desc & N_ARM_THUMB_DEF) && "ARM32 arch is not supported");
|
|
|
|
|
|
2021-06-18 16:35:46 -04:00
|
|
|
if (sym.n_type & N_EXT) {
|
2022-07-25 11:45:55 +02:00
|
|
|
// -load_hidden makes us treat global symbols as linkage unit scoped.
|
|
|
|
|
// Duplicates are reported but the symbol does not go in the export trie.
|
|
|
|
|
bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
|
|
|
|
|
|
[lld/mac] Implement support for .weak_def_can_be_hidden
I first had a more invasive patch for this (D101069), but while trying
to get that polished for review I realized that lld's current symbol
merging semantics mean that only a very small code change is needed.
So this goes with the smaller patch for now.
This has no effect on projects that build with -fvisibility=hidden
(e.g. chromium), since these see .private_extern symbols instead.
It does have an effect on projects that build with -fvisibility-inlines-hidden
(e.g. llvm) in -O2 builds, where LLVM's GlobalOpt pass will promote most inline
functions from .weak_definition to .weak_def_can_be_hidden.
Before this patch:
% ls -l out/gn/bin/clang out/gn/lib/libclang.dylib
-rwxr-xr-x 1 thakis staff 113059936 Apr 22 11:51 out/gn/bin/clang
-rwxr-xr-x 1 thakis staff 86370064 Apr 22 11:51 out/gn/lib/libclang.dylib
% out/gn/bin/llvm-objdump --macho --weak-bind out/gn/bin/clang | wc -l
8291
% out/gn/bin/llvm-objdump --macho --weak-bind out/gn/lib/libclang.dylib | wc -l
5698
With this patch:
% ls -l out/gn/bin/clang out/gn/lib/libclang.dylib
-rwxr-xr-x 1 thakis staff 111721096 Apr 22 11:55 out/gn/bin/clang
-rwxr-xr-x 1 thakis staff 85291208 Apr 22 11:55 out/gn/lib/libclang.dylib
thakis@MBP llvm-project % out/gn/bin/llvm-objdump --macho --weak-bind out/gn/bin/clang | wc -l
725
thakis@MBP llvm-project % out/gn/bin/llvm-objdump --macho --weak-bind out/gn/lib/libclang.dylib | wc -l
542
Linking clang becomes a tiny bit faster with this patch:
x 100 0.67263818 0.77847815 0.69430709 0.69877208 0.017715892
+ 100 0.67209601 0.73323393 0.68600798 0.68917346 0.012824377
Difference at 95.0% confidence
-0.00959861 +/- 0.00428661
-1.37364% +/- 0.613449%
(Student's t, pooled s = 0.0154648)
This only happens if lld with the patch and lld without the patch are both
linked with an lld with the patch or both linked with an lld without the patch
(...or with ld64). I accidentally linked the lld with the patch with an lld
without the patch and the other way round at first. In that setup, no
difference is found. That makese sense, since having fewer weak imports will
make the linked output a bit faster too. So not only does this make linking
binaries such as clang a bit faster (since fewer exports need to be written to
the export trie by lld), the linked output binary binary is also a bit faster
(since dyld needs to process fewer dynamic imports).
This also happens to fix the one `check-clang` failure when using lld as host
linker, but mostly for silly reasons: See crbug.com/1183336, mostly comment 26.
The real bug here is that c-index-test links all of LLVM both statically and
dynamically, which is an ODR violation. Things just happen to work with this
patch.
So after this patch, check-clang, check-lld, check-llvm all pass with lld as
host linker :)
Differential Revision: https://reviews.llvm.org/D101080
2021-04-22 11:28:35 -04:00
|
|
|
// lld's behavior for merging symbols is slightly different from ld64:
|
|
|
|
|
// ld64 picks the winning symbol based on several criteria (see
|
|
|
|
|
// pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld
|
|
|
|
|
// just merges metadata and keeps the contents of the first symbol
|
|
|
|
|
// with that name (see SymbolTable::addDefined). For:
|
|
|
|
|
// * inline function F in a TU built with -fvisibility-inlines-hidden
|
|
|
|
|
// * and inline function F in another TU built without that flag
|
|
|
|
|
// ld64 will pick the one from the file built without
|
|
|
|
|
// -fvisibility-inlines-hidden.
|
|
|
|
|
// lld will instead pick the one listed first on the link command line and
|
|
|
|
|
// give it visibility as if the function was built without
|
|
|
|
|
// -fvisibility-inlines-hidden.
|
|
|
|
|
// If both functions have the same contents, this will have the same
|
|
|
|
|
// behavior. If not, it won't, but the input had an ODR violation in
|
|
|
|
|
// that case.
|
|
|
|
|
//
|
|
|
|
|
// Similarly, merging a symbol
|
|
|
|
|
// that's isPrivateExtern and not isWeakDefCanBeHidden with one
|
|
|
|
|
// that's not isPrivateExtern but isWeakDefCanBeHidden technically
|
|
|
|
|
// should produce one
|
|
|
|
|
// that's not isPrivateExtern but isWeakDefCanBeHidden. That matters
|
|
|
|
|
// with ld64's semantics, because it means the non-private-extern
|
|
|
|
|
// definition will continue to take priority if more private extern
|
|
|
|
|
// definitions are encountered. With lld's semantics there's no observable
|
2021-11-08 19:50:34 -05:00
|
|
|
// difference between a symbol that's isWeakDefCanBeHidden(autohide) or one
|
|
|
|
|
// that's privateExtern -- neither makes it into the dynamic symbol table,
|
|
|
|
|
// unless the autohide symbol is explicitly exported.
|
|
|
|
|
// But if a symbol is both privateExtern and autohide then it can't
|
|
|
|
|
// be exported.
|
|
|
|
|
// So we nullify the autohide flag when privateExtern is present
|
|
|
|
|
// and promote the symbol to privateExtern when it is not already.
|
|
|
|
|
if (isWeakDefCanBeHidden && isPrivateExtern)
|
|
|
|
|
isWeakDefCanBeHidden = false;
|
|
|
|
|
else if (isWeakDefCanBeHidden)
|
[lld/mac] Implement support for .weak_def_can_be_hidden
I first had a more invasive patch for this (D101069), but while trying
to get that polished for review I realized that lld's current symbol
merging semantics mean that only a very small code change is needed.
So this goes with the smaller patch for now.
This has no effect on projects that build with -fvisibility=hidden
(e.g. chromium), since these see .private_extern symbols instead.
It does have an effect on projects that build with -fvisibility-inlines-hidden
(e.g. llvm) in -O2 builds, where LLVM's GlobalOpt pass will promote most inline
functions from .weak_definition to .weak_def_can_be_hidden.
Before this patch:
% ls -l out/gn/bin/clang out/gn/lib/libclang.dylib
-rwxr-xr-x 1 thakis staff 113059936 Apr 22 11:51 out/gn/bin/clang
-rwxr-xr-x 1 thakis staff 86370064 Apr 22 11:51 out/gn/lib/libclang.dylib
% out/gn/bin/llvm-objdump --macho --weak-bind out/gn/bin/clang | wc -l
8291
% out/gn/bin/llvm-objdump --macho --weak-bind out/gn/lib/libclang.dylib | wc -l
5698
With this patch:
% ls -l out/gn/bin/clang out/gn/lib/libclang.dylib
-rwxr-xr-x 1 thakis staff 111721096 Apr 22 11:55 out/gn/bin/clang
-rwxr-xr-x 1 thakis staff 85291208 Apr 22 11:55 out/gn/lib/libclang.dylib
thakis@MBP llvm-project % out/gn/bin/llvm-objdump --macho --weak-bind out/gn/bin/clang | wc -l
725
thakis@MBP llvm-project % out/gn/bin/llvm-objdump --macho --weak-bind out/gn/lib/libclang.dylib | wc -l
542
Linking clang becomes a tiny bit faster with this patch:
x 100 0.67263818 0.77847815 0.69430709 0.69877208 0.017715892
+ 100 0.67209601 0.73323393 0.68600798 0.68917346 0.012824377
Difference at 95.0% confidence
-0.00959861 +/- 0.00428661
-1.37364% +/- 0.613449%
(Student's t, pooled s = 0.0154648)
This only happens if lld with the patch and lld without the patch are both
linked with an lld with the patch or both linked with an lld without the patch
(...or with ld64). I accidentally linked the lld with the patch with an lld
without the patch and the other way round at first. In that setup, no
difference is found. That makese sense, since having fewer weak imports will
make the linked output a bit faster too. So not only does this make linking
binaries such as clang a bit faster (since fewer exports need to be written to
the export trie by lld), the linked output binary binary is also a bit faster
(since dyld needs to process fewer dynamic imports).
This also happens to fix the one `check-clang` failure when using lld as host
linker, but mostly for silly reasons: See crbug.com/1183336, mostly comment 26.
The real bug here is that c-index-test links all of LLVM both statically and
dynamically, which is an ODR violation. Things just happen to work with this
patch.
So after this patch, check-clang, check-lld, check-llvm all pass with lld as
host linker :)
Differential Revision: https://reviews.llvm.org/D101080
2021-04-22 11:28:35 -04:00
|
|
|
isPrivateExtern = true;
|
[lld/mac] Implement -dead_strip
Also adds support for live_support sections, no_dead_strip sections,
.no_dead_strip symbols.
Chromium Framework 345MB unstripped -> 250MB stripped
(vs 290MB unstripped -> 236M stripped with ld64).
Doing dead stripping is a bit faster than not, because so much less
data needs to be processed:
% ministat lld_*
x lld_nostrip.txt
+ lld_strip.txt
N Min Max Median Avg Stddev
x 10 3.929414 4.07692 4.0269079 4.0089678 0.044214794
+ 10 3.8129408 3.9025559 3.8670411 3.8642573 0.024779651
Difference at 95.0% confidence
-0.144711 +/- 0.0336749
-3.60967% +/- 0.839989%
(Student's t, pooled s = 0.0358398)
This interacts with many parts of the linker. I tried to add test coverage
for all added `isLive()` checks, so that some test will fail if any of them
is removed. I checked that the test expectations for the most part match
ld64's behavior (except for live-support-iterations.s, see the comment
in the test). Interacts with:
- debug info
- export tries
- import opcodes
- flags like -exported_symbol(s_list)
- -U / dynamic_lookup
- mod_init_funcs, mod_term_funcs
- weak symbol handling
- unwind info
- stubs
- map files
- -sectcreate
- undefined, dylib, common, defined (both absolute and normal) symbols
It's possible it interacts with more features I didn't think of,
of course.
I also did some manual testing:
- check-llvm check-clang check-lld work with lld with this patch
as host linker and -dead_strip enabled
- Chromium still starts
- Chromium's base_unittests still pass, including unwind tests
Implemenation-wise, this is InputSection-based, so it'll work for
object files with .subsections_via_symbols (which includes all
object files generated by clang). I first based this on the COFF
implementation, but later realized that things are more similar to ELF.
I think it'd be good to refactor MarkLive.cpp to look more like the ELF
part at some point, but I'd like to get a working state checked in first.
Mechanical parts:
- Rename canOmitFromOutput to wasCoalesced (no behavior change)
since it really is for weak coalesced symbols
- Add noDeadStrip to Defined, corresponding to N_NO_DEAD_STRIP
(`.no_dead_strip` in asm)
Fixes PR49276.
Differential Revision: https://reviews.llvm.org/D103324
2021-05-07 17:10:05 -04:00
|
|
|
return symtab->addDefined(
|
2021-07-01 20:33:55 -04:00
|
|
|
name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
|
2023-05-15 02:00:29 -07:00
|
|
|
isPrivateExtern, sym.n_desc & REFERENCED_DYNAMICALLY,
|
|
|
|
|
sym.n_desc & N_NO_DEAD_STRIP, isWeakDefCanBeHidden);
|
[lld/mac] Implement support for private extern symbols
Private extern symbols are used for things scoped to the linkage unit.
They cause duplicate symbol errors (so they're in the symbol table,
unlike TU-scoped truly local symbols), but they don't make it into the
export trie. They are created e.g. by compiling with
-fvisibility=hidden.
If two weak symbols have differing privateness, the combined symbol is
non-private external. (Example: inline functions and some TUs that
include the header defining it were built with
-fvisibility-inlines-hidden and some weren't).
A weak private external symbol implicitly has its "weak" dropped and
behaves like a regular strong private external symbol: Weak is an export
trie concept, and private symbols are not in the export trie.
If a weak and a strong symbol have different privateness, the strong
symbol wins.
If two common symbols have differing privateness, the larger symbol
wins. If they have the same size, the privateness of the symbol seen
later during the link wins (!) -- this is a bit lame, but it matches
ld64 and this behavior takes 2 lines less to implement than the less
surprising "result is non-private external), so match ld64.
(Example: `int a` in two .c files, both built with -fcommon,
one built with -fvisibility=hidden and one without.)
This also makes `__dyld_private` a true TU-local symbol, matching ld64.
To make this work, make the `const char*` StringRefZ ctor to correctly
set `size` (without this, writing the string table crashed when calling
getName() on the __dyld_private symbol).
Mention in CommonSymbol's comment that common symbols are now disabled
by default in clang.
Mention in -keep_private_externs's HelpText that the flag only has an
effect with `-r` (which we don't implement yet -- so this patch here
doesn't regress any behavior around -r + -keep_private_externs)). ld64
doesn't explicitly document it, but the commit text of
http://reviews.llvm.org/rL216146 does, and ld64's
OutputFile::buildSymbolTable() checks `_options.outputKind() ==
Options::kObjectFile` before calling `_options.keepPrivateExterns()`
(the only reference to that function).
Fixes PR48536.
Differential Revision: https://reviews.llvm.org/D93609
2020-12-17 13:30:18 -05:00
|
|
|
}
|
2022-12-21 17:44:45 -05:00
|
|
|
bool includeInSymtab = !isPrivateLabel(name) && !isEhFrameSection(isec);
|
2021-05-23 20:35:55 -07:00
|
|
|
return make<Defined>(
|
2021-07-01 20:33:55 -04:00
|
|
|
name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
|
2022-04-11 15:45:25 -04:00
|
|
|
/*isExternal=*/false, /*isPrivateExtern=*/false, includeInSymtab,
|
2023-05-15 02:00:29 -07:00
|
|
|
sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP);
|
2020-09-18 08:40:46 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Absolute symbols are defined symbols that do not have an associated
|
|
|
|
|
// InputSection. They cannot be weak.
|
2021-04-02 18:46:18 -04:00
|
|
|
template <class NList>
|
|
|
|
|
static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
|
2022-07-25 11:45:55 +02:00
|
|
|
StringRef name, bool forceHidden) {
|
2023-05-15 02:00:29 -07:00
|
|
|
assert(!(sym.n_desc & N_ARM_THUMB_DEF) && "ARM32 arch is not supported");
|
|
|
|
|
|
2021-06-18 16:35:46 -04:00
|
|
|
if (sym.n_type & N_EXT) {
|
2022-07-25 11:45:55 +02:00
|
|
|
bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
|
2023-05-15 02:00:29 -07:00
|
|
|
return symtab->addDefined(name, file, nullptr, sym.n_value, /*size=*/0,
|
|
|
|
|
/*isWeakDef=*/false, isPrivateExtern,
|
|
|
|
|
/*isReferencedDynamically=*/false,
|
|
|
|
|
sym.n_desc & N_NO_DEAD_STRIP,
|
|
|
|
|
/*isWeakDefCanBeHidden=*/false);
|
[lld/mac] Implement support for private extern symbols
Private extern symbols are used for things scoped to the linkage unit.
They cause duplicate symbol errors (so they're in the symbol table,
unlike TU-scoped truly local symbols), but they don't make it into the
export trie. They are created e.g. by compiling with
-fvisibility=hidden.
If two weak symbols have differing privateness, the combined symbol is
non-private external. (Example: inline functions and some TUs that
include the header defining it were built with
-fvisibility-inlines-hidden and some weren't).
A weak private external symbol implicitly has its "weak" dropped and
behaves like a regular strong private external symbol: Weak is an export
trie concept, and private symbols are not in the export trie.
If a weak and a strong symbol have different privateness, the strong
symbol wins.
If two common symbols have differing privateness, the larger symbol
wins. If they have the same size, the privateness of the symbol seen
later during the link wins (!) -- this is a bit lame, but it matches
ld64 and this behavior takes 2 lines less to implement than the less
surprising "result is non-private external), so match ld64.
(Example: `int a` in two .c files, both built with -fcommon,
one built with -fvisibility=hidden and one without.)
This also makes `__dyld_private` a true TU-local symbol, matching ld64.
To make this work, make the `const char*` StringRefZ ctor to correctly
set `size` (without this, writing the string table crashed when calling
getName() on the __dyld_private symbol).
Mention in CommonSymbol's comment that common symbols are now disabled
by default in clang.
Mention in -keep_private_externs's HelpText that the flag only has an
effect with `-r` (which we don't implement yet -- so this patch here
doesn't regress any behavior around -r + -keep_private_externs)). ld64
doesn't explicitly document it, but the commit text of
http://reviews.llvm.org/rL216146 does, and ld64's
OutputFile::buildSymbolTable() checks `_options.outputKind() ==
Options::kObjectFile` before calling `_options.keepPrivateExterns()`
(the only reference to that function).
Fixes PR48536.
Differential Revision: https://reviews.llvm.org/D93609
2020-12-17 13:30:18 -05:00
|
|
|
}
|
2021-04-01 17:48:09 -07:00
|
|
|
return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
|
|
|
|
|
/*isWeakDef=*/false,
|
2021-04-30 16:17:26 -04:00
|
|
|
/*isExternal=*/false, /*isPrivateExtern=*/false,
|
2023-05-15 02:00:29 -07:00
|
|
|
/*includeInSymtab=*/true,
|
[lld/mac] Implement -dead_strip
Also adds support for live_support sections, no_dead_strip sections,
.no_dead_strip symbols.
Chromium Framework 345MB unstripped -> 250MB stripped
(vs 290MB unstripped -> 236M stripped with ld64).
Doing dead stripping is a bit faster than not, because so much less
data needs to be processed:
% ministat lld_*
x lld_nostrip.txt
+ lld_strip.txt
N Min Max Median Avg Stddev
x 10 3.929414 4.07692 4.0269079 4.0089678 0.044214794
+ 10 3.8129408 3.9025559 3.8670411 3.8642573 0.024779651
Difference at 95.0% confidence
-0.144711 +/- 0.0336749
-3.60967% +/- 0.839989%
(Student's t, pooled s = 0.0358398)
This interacts with many parts of the linker. I tried to add test coverage
for all added `isLive()` checks, so that some test will fail if any of them
is removed. I checked that the test expectations for the most part match
ld64's behavior (except for live-support-iterations.s, see the comment
in the test). Interacts with:
- debug info
- export tries
- import opcodes
- flags like -exported_symbol(s_list)
- -U / dynamic_lookup
- mod_init_funcs, mod_term_funcs
- weak symbol handling
- unwind info
- stubs
- map files
- -sectcreate
- undefined, dylib, common, defined (both absolute and normal) symbols
It's possible it interacts with more features I didn't think of,
of course.
I also did some manual testing:
- check-llvm check-clang check-lld work with lld with this patch
as host linker and -dead_strip enabled
- Chromium still starts
- Chromium's base_unittests still pass, including unwind tests
Implemenation-wise, this is InputSection-based, so it'll work for
object files with .subsections_via_symbols (which includes all
object files generated by clang). I first based this on the COFF
implementation, but later realized that things are more similar to ELF.
I think it'd be good to refactor MarkLive.cpp to look more like the ELF
part at some point, but I'd like to get a working state checked in first.
Mechanical parts:
- Rename canOmitFromOutput to wasCoalesced (no behavior change)
since it really is for weak coalesced symbols
- Add noDeadStrip to Defined, corresponding to N_NO_DEAD_STRIP
(`.no_dead_strip` in asm)
Fixes PR49276.
Differential Revision: https://reviews.llvm.org/D103324
2021-05-07 17:10:05 -04:00
|
|
|
/*isReferencedDynamically=*/false,
|
|
|
|
|
sym.n_desc & N_NO_DEAD_STRIP);
|
2020-09-18 08:40:46 -07:00
|
|
|
}
|
|
|
|
|
|
2021-04-02 18:46:18 -04:00
|
|
|
template <class NList>
|
|
|
|
|
macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,
|
2022-09-15 22:55:41 -04:00
|
|
|
const char *strtab) {
|
|
|
|
|
StringRef name = StringRef(strtab + sym.n_strx);
|
2020-09-18 08:40:46 -07:00
|
|
|
uint8_t type = sym.n_type & N_TYPE;
|
2022-07-25 11:45:55 +02:00
|
|
|
bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
|
2020-09-18 08:40:46 -07:00
|
|
|
switch (type) {
|
|
|
|
|
case N_UNDF:
|
|
|
|
|
return sym.n_value == 0
|
2021-02-03 13:31:40 -05:00
|
|
|
? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
|
2020-09-18 08:40:46 -07:00
|
|
|
: symtab->addCommon(name, this, sym.n_value,
|
[lld/mac] Implement support for private extern symbols
Private extern symbols are used for things scoped to the linkage unit.
They cause duplicate symbol errors (so they're in the symbol table,
unlike TU-scoped truly local symbols), but they don't make it into the
export trie. They are created e.g. by compiling with
-fvisibility=hidden.
If two weak symbols have differing privateness, the combined symbol is
non-private external. (Example: inline functions and some TUs that
include the header defining it were built with
-fvisibility-inlines-hidden and some weren't).
A weak private external symbol implicitly has its "weak" dropped and
behaves like a regular strong private external symbol: Weak is an export
trie concept, and private symbols are not in the export trie.
If a weak and a strong symbol have different privateness, the strong
symbol wins.
If two common symbols have differing privateness, the larger symbol
wins. If they have the same size, the privateness of the symbol seen
later during the link wins (!) -- this is a bit lame, but it matches
ld64 and this behavior takes 2 lines less to implement than the less
surprising "result is non-private external), so match ld64.
(Example: `int a` in two .c files, both built with -fcommon,
one built with -fvisibility=hidden and one without.)
This also makes `__dyld_private` a true TU-local symbol, matching ld64.
To make this work, make the `const char*` StringRefZ ctor to correctly
set `size` (without this, writing the string table crashed when calling
getName() on the __dyld_private symbol).
Mention in CommonSymbol's comment that common symbols are now disabled
by default in clang.
Mention in -keep_private_externs's HelpText that the flag only has an
effect with `-r` (which we don't implement yet -- so this patch here
doesn't regress any behavior around -r + -keep_private_externs)). ld64
doesn't explicitly document it, but the commit text of
http://reviews.llvm.org/rL216146 does, and ld64's
OutputFile::buildSymbolTable() checks `_options.outputKind() ==
Options::kObjectFile` before calling `_options.keepPrivateExterns()`
(the only reference to that function).
Fixes PR48536.
Differential Revision: https://reviews.llvm.org/D93609
2020-12-17 13:30:18 -05:00
|
|
|
1 << GET_COMM_ALIGN(sym.n_desc),
|
2022-07-25 11:45:55 +02:00
|
|
|
isPrivateExtern);
|
2020-09-18 08:40:46 -07:00
|
|
|
case N_ABS:
|
2022-07-25 11:45:55 +02:00
|
|
|
return createAbsolute(sym, this, name, forceHidden);
|
2022-09-15 22:55:41 -04:00
|
|
|
case N_INDR: {
|
|
|
|
|
// Not much point in making local aliases -- relocs in the current file can
|
|
|
|
|
// just refer to the actual symbol itself. ld64 ignores these symbols too.
|
|
|
|
|
if (!(sym.n_type & N_EXT))
|
|
|
|
|
return nullptr;
|
|
|
|
|
StringRef aliasedName = StringRef(strtab + sym.n_value);
|
|
|
|
|
// isPrivateExtern is the only symbol flag that has an impact on the final
|
|
|
|
|
// aliased symbol.
|
2023-04-05 01:48:34 -04:00
|
|
|
auto *alias = make<AliasSymbol>(this, name, aliasedName, isPrivateExtern);
|
2022-09-15 22:55:41 -04:00
|
|
|
aliases.push_back(alias);
|
|
|
|
|
return alias;
|
|
|
|
|
}
|
2020-09-18 08:40:46 -07:00
|
|
|
case N_PBUD:
|
2022-09-15 22:55:41 -04:00
|
|
|
error("TODO: support symbols of type N_PBUD");
|
2020-09-18 08:40:46 -07:00
|
|
|
return nullptr;
|
|
|
|
|
case N_SECT:
|
|
|
|
|
llvm_unreachable(
|
|
|
|
|
"N_SECT symbols should not be passed to parseNonSectionSymbol");
|
|
|
|
|
default:
|
|
|
|
|
llvm_unreachable("invalid symbol type");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-10-26 15:14:25 -04:00
|
|
|
template <class NList> static bool isUndef(const NList &sym) {
|
2021-07-19 14:38:15 -04:00
|
|
|
return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0;
|
|
|
|
|
}
|
|
|
|
|
|
2021-04-02 18:46:18 -04:00
|
|
|
template <class LP>
|
|
|
|
|
void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
|
|
|
|
|
ArrayRef<typename LP::nlist> nList,
|
2020-12-01 19:57:37 -08:00
|
|
|
const char *strtab, bool subsectionsViaSymbols) {
|
2021-04-02 18:46:18 -04:00
|
|
|
using NList = typename LP::nlist;
|
|
|
|
|
|
2021-04-06 15:09:14 -04:00
|
|
|
// Groups indices of the symbols by the sections that contain them.
|
2021-11-04 20:55:31 -07:00
|
|
|
std::vector<std::vector<uint32_t>> symbolsBySection(sections.size());
|
2021-03-31 15:23:19 -07:00
|
|
|
symbols.resize(nList.size());
|
2021-07-19 14:38:15 -04:00
|
|
|
SmallVector<unsigned, 32> undefineds;
|
2021-04-06 15:09:14 -04:00
|
|
|
for (uint32_t i = 0; i < nList.size(); ++i) {
|
2021-04-02 18:46:18 -04:00
|
|
|
const NList &sym = nList[i];
|
2021-06-30 12:50:24 -04:00
|
|
|
|
|
|
|
|
// Ignore debug symbols for now.
|
|
|
|
|
// FIXME: may need special handling.
|
|
|
|
|
if (sym.n_type & N_STAB)
|
|
|
|
|
continue;
|
|
|
|
|
|
2021-04-06 15:09:14 -04:00
|
|
|
if ((sym.n_type & N_TYPE) == N_SECT) {
|
2025-11-11 14:27:03 -08:00
|
|
|
if (sym.n_sect == 0) {
|
|
|
|
|
fatal("section symbol " + StringRef(strtab + sym.n_strx) + " in " +
|
|
|
|
|
toString(this) + " has an invalid section index [0]");
|
|
|
|
|
}
|
|
|
|
|
if (sym.n_sect > sections.size()) {
|
|
|
|
|
fatal("section symbol " + StringRef(strtab + sym.n_strx) + " in " +
|
|
|
|
|
toString(this) + " has an invalid section index [" +
|
|
|
|
|
Twine(static_cast<unsigned>(sym.n_sect)) +
|
|
|
|
|
"] greater than the total number of sections [" +
|
|
|
|
|
Twine(sections.size()) + "]");
|
|
|
|
|
}
|
[lld-macho][nfc] Eliminate InputSection::Shared
Earlier in LLD's evolution, I tried to create the illusion that
subsections were indistinguishable from "top-level" sections. Thus, even
though the subsections shared many common field values, I hid those
common values away in a private Shared struct (see D105305). More
recently, however, @gkm added a public `Section` struct in D113241 that
served as an explicit way to store values that are common to an entire
set of subsections (aka InputSections). Now that we have another "common
value" struct, `Shared` has been rendered redundant. All its fields can
be moved into `Section` instead, and the pointer to `Shared` can be replaced
with a pointer to `Section`.
This `Section` pointer also has the advantage of letting us inspect other
subsections easily, simplifying the implementation of {D118798}.
P.S. I do think that having both `Section` and `InputSection` makes for
a slightly confusing naming scheme. I considered renaming `InputSection`
to `Subsection`, but that would break the symmetry with `OutputSection`.
It would also make us deviate from LLD-ELF's naming scheme.
This change is perf-neutral on my 3.2 GHz 16-Core Intel Xeon W machine:
base diff difference (95% CI)
sys_time 1.258 ± 0.031 1.248 ± 0.023 [ -1.6% .. +0.1%]
user_time 3.659 ± 0.047 3.658 ± 0.041 [ -0.5% .. +0.4%]
wall_time 4.640 ± 0.085 4.625 ± 0.063 [ -1.0% .. +0.3%]
samples 49 61
There's also no stat sig change in RSS (as measured by `time -l`):
base diff difference (95% CI)
time 998038627.097 ± 13567305.958 1003327715.556 ± 15210451.236 [ -0.2% .. +1.2%]
samples 31 36
Reviewed By: #lld-macho, oontvoo
Differential Revision: https://reviews.llvm.org/D118797
2022-02-03 19:53:29 -05:00
|
|
|
Subsections &subsections = sections[sym.n_sect - 1]->subsections;
|
2021-04-06 15:09:14 -04:00
|
|
|
// parseSections() may have chosen not to parse this section.
|
2021-11-04 20:55:31 -07:00
|
|
|
if (subsections.empty())
|
2021-04-06 15:09:14 -04:00
|
|
|
continue;
|
|
|
|
|
symbolsBySection[sym.n_sect - 1].push_back(i);
|
2021-07-19 14:38:15 -04:00
|
|
|
} else if (isUndef(sym)) {
|
|
|
|
|
undefineds.push_back(i);
|
2021-04-06 15:09:14 -04:00
|
|
|
} else {
|
2022-09-15 22:55:41 -04:00
|
|
|
symbols[i] = parseNonSectionSymbol(sym, strtab);
|
[lld-macho][re-land] Support .subsections_via_symbols
Summary:
This diff restores and builds upon @pcc and @ruiu's initial work on
subsections.
The .subsections_via_symbols directive indicates we can split each
section along symbol boundaries, unless those symbols have been marked
with `.alt_entry`.
We exercise this functionality in our tests by using order files that
rearrange those symbols.
Depends on D79668.
Reviewers: ruiu, pcc, MaskRay, smeenai, alexshap, gkm, Ktwu, christylee
Reviewed By: smeenai
Subscribers: thakis, llvm-commits, pcc, ruiu
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D79926
2020-05-19 08:46:07 -07:00
|
|
|
}
|
2021-04-06 15:09:14 -04:00
|
|
|
}
|
[lld-macho][re-land] Support .subsections_via_symbols
Summary:
This diff restores and builds upon @pcc and @ruiu's initial work on
subsections.
The .subsections_via_symbols directive indicates we can split each
section along symbol boundaries, unless those symbols have been marked
with `.alt_entry`.
We exercise this functionality in our tests by using order files that
rearrange those symbols.
Depends on D79668.
Reviewers: ruiu, pcc, MaskRay, smeenai, alexshap, gkm, Ktwu, christylee
Reviewed By: smeenai
Subscribers: thakis, llvm-commits, pcc, ruiu
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D79926
2020-05-19 08:46:07 -07:00
|
|
|
|
2021-11-04 20:55:31 -07:00
|
|
|
for (size_t i = 0; i < sections.size(); ++i) {
|
[lld-macho][nfc] Eliminate InputSection::Shared
Earlier in LLD's evolution, I tried to create the illusion that
subsections were indistinguishable from "top-level" sections. Thus, even
though the subsections shared many common field values, I hid those
common values away in a private Shared struct (see D105305). More
recently, however, @gkm added a public `Section` struct in D113241 that
served as an explicit way to store values that are common to an entire
set of subsections (aka InputSections). Now that we have another "common
value" struct, `Shared` has been rendered redundant. All its fields can
be moved into `Section` instead, and the pointer to `Shared` can be replaced
with a pointer to `Section`.
This `Section` pointer also has the advantage of letting us inspect other
subsections easily, simplifying the implementation of {D118798}.
P.S. I do think that having both `Section` and `InputSection` makes for
a slightly confusing naming scheme. I considered renaming `InputSection`
to `Subsection`, but that would break the symmetry with `OutputSection`.
It would also make us deviate from LLD-ELF's naming scheme.
This change is perf-neutral on my 3.2 GHz 16-Core Intel Xeon W machine:
base diff difference (95% CI)
sys_time 1.258 ± 0.031 1.248 ± 0.023 [ -1.6% .. +0.1%]
user_time 3.659 ± 0.047 3.658 ± 0.041 [ -0.5% .. +0.4%]
wall_time 4.640 ± 0.085 4.625 ± 0.063 [ -1.0% .. +0.3%]
samples 49 61
There's also no stat sig change in RSS (as measured by `time -l`):
base diff difference (95% CI)
time 998038627.097 ± 13567305.958 1003327715.556 ± 15210451.236 [ -0.2% .. +1.2%]
samples 31 36
Reviewed By: #lld-macho, oontvoo
Differential Revision: https://reviews.llvm.org/D118797
2022-02-03 19:53:29 -05:00
|
|
|
Subsections &subsections = sections[i]->subsections;
|
2021-11-04 20:55:31 -07:00
|
|
|
if (subsections.empty())
|
2021-03-05 17:22:57 -05:00
|
|
|
continue;
|
2021-04-06 15:09:14 -04:00
|
|
|
std::vector<uint32_t> &symbolIndices = symbolsBySection[i];
|
|
|
|
|
uint64_t sectionAddr = sectionHeaders[i].addr;
|
2021-05-09 18:35:16 -04:00
|
|
|
uint32_t sectionAlign = 1u << sectionHeaders[i].align;
|
2021-04-06 15:09:14 -04:00
|
|
|
|
2022-06-12 21:56:45 -04:00
|
|
|
// Some sections have already been split into subsections during
|
2021-07-01 20:33:44 -04:00
|
|
|
// parseSections(), so we simply need to match Symbols to the corresponding
|
|
|
|
|
// subsection here.
|
2022-06-12 21:56:45 -04:00
|
|
|
if (sections[i]->doneSplitting) {
|
2021-07-01 20:33:44 -04:00
|
|
|
for (size_t j = 0; j < symbolIndices.size(); ++j) {
|
2022-10-13 10:36:08 -04:00
|
|
|
const uint32_t symIndex = symbolIndices[j];
|
2021-07-01 20:33:44 -04:00
|
|
|
const NList &sym = nList[symIndex];
|
|
|
|
|
StringRef name = strtab + sym.n_strx;
|
|
|
|
|
uint64_t symbolOffset = sym.n_value - sectionAddr;
|
2021-11-04 20:55:31 -07:00
|
|
|
InputSection *isec =
|
2022-03-16 18:05:32 -04:00
|
|
|
findContainingSubsection(*sections[i], &symbolOffset);
|
2021-07-01 20:33:44 -04:00
|
|
|
if (symbolOffset != 0) {
|
2022-04-07 14:28:44 -04:00
|
|
|
error(toString(*sections[i]) + ": symbol " + name +
|
2021-07-01 20:33:44 -04:00
|
|
|
" at misaligned offset");
|
|
|
|
|
continue;
|
|
|
|
|
}
|
2022-07-25 11:45:55 +02:00
|
|
|
symbols[symIndex] =
|
|
|
|
|
createDefined(sym, name, isec, 0, isec->getSize(), forceHidden);
|
2021-07-01 20:33:44 -04:00
|
|
|
}
|
|
|
|
|
continue;
|
|
|
|
|
}
|
2022-06-12 21:56:45 -04:00
|
|
|
sections[i]->doneSplitting = true;
|
2021-07-01 20:33:44 -04:00
|
|
|
|
2022-12-21 17:44:45 -05:00
|
|
|
auto getSymName = [strtab](const NList& sym) -> StringRef {
|
|
|
|
|
return StringRef(strtab + sym.n_strx);
|
|
|
|
|
};
|
|
|
|
|
|
2021-07-01 20:33:44 -04:00
|
|
|
// Calculate symbol sizes and create subsections by splitting the sections
|
|
|
|
|
// along symbol boundaries.
|
2021-11-04 20:55:31 -07:00
|
|
|
// We populate subsections by repeatedly splitting the last (highest
|
|
|
|
|
// address) subsection.
|
2021-07-01 20:33:44 -04:00
|
|
|
llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {
|
2023-03-10 22:28:36 -05:00
|
|
|
// Put extern weak symbols after other symbols at the same address so
|
|
|
|
|
// that weak symbol coalescing works correctly. See
|
|
|
|
|
// SymbolTable::addDefined() for details.
|
|
|
|
|
if (nList[lhs].n_value == nList[rhs].n_value &&
|
|
|
|
|
nList[lhs].n_type & N_EXT && nList[rhs].n_type & N_EXT)
|
|
|
|
|
return !(nList[lhs].n_desc & N_WEAK_DEF) && (nList[rhs].n_desc & N_WEAK_DEF);
|
2021-07-01 20:33:44 -04:00
|
|
|
return nList[lhs].n_value < nList[rhs].n_value;
|
|
|
|
|
});
|
2021-04-06 15:09:14 -04:00
|
|
|
for (size_t j = 0; j < symbolIndices.size(); ++j) {
|
2022-10-13 10:36:08 -04:00
|
|
|
const uint32_t symIndex = symbolIndices[j];
|
2021-04-06 15:09:14 -04:00
|
|
|
const NList &sym = nList[symIndex];
|
2022-12-21 17:44:45 -05:00
|
|
|
StringRef name = getSymName(sym);
|
2021-11-15 11:46:59 -07:00
|
|
|
Subsection &subsec = subsections.back();
|
2021-11-04 20:55:31 -07:00
|
|
|
InputSection *isec = subsec.isec;
|
2021-04-06 15:09:14 -04:00
|
|
|
|
2021-11-04 20:55:31 -07:00
|
|
|
uint64_t subsecAddr = sectionAddr + subsec.offset;
|
2021-06-18 15:19:38 +00:00
|
|
|
size_t symbolOffset = sym.n_value - subsecAddr;
|
2021-04-06 15:09:14 -04:00
|
|
|
uint64_t symbolSize =
|
|
|
|
|
j + 1 < symbolIndices.size()
|
|
|
|
|
? nList[symbolIndices[j + 1]].n_value - sym.n_value
|
|
|
|
|
: isec->data.size() - symbolOffset;
|
[lld-macho] Implement cstring deduplication
Our implementation draws heavily from LLD-ELF's, which in turn delegates
its string deduplication to llvm-mc's StringTableBuilder. The messiness of
this diff is largely due to the fact that we've previously assumed that
all InputSections get concatenated together to form the output. This is
no longer true with CStringInputSections, which split their contents into
StringPieces. StringPieces are much more lightweight than InputSections,
which is important as we create a lot of them. They may also overlap in
the output, which makes it possible for strings to be tail-merged. In
fact, the initial version of this diff implemented tail merging, but
I've dropped it for reasons I'll explain later.
**Alignment Issues**
Mergeable cstring literals are found under the `__TEXT,__cstring`
section. In contrast to ELF, which puts strings that need different
alignments into different sections, clang's Mach-O backend puts them all
in one section. Strings that need to be aligned have the `.p2align`
directive emitted before them, which simply translates into zero padding
in the object file.
I *think* ld64 extracts the desired per-string alignment from this data
by preserving each string's offset from the last section-aligned
address. I'm not entirely certain since it doesn't seem consistent about
doing this; but perhaps this can be chalked up to cases where ld64 has
to deduplicate strings with different offset/alignment combos -- it
seems to pick one of their alignments to preserve. This doesn't seem
correct in general; we can in fact can induce ld64 to produce a crashing
binary just by linking in an additional object file that only contains
cstrings and no code. See PR50563 for details.
Moreover, this scheme seems rather inefficient: since unaligned and
aligned strings are all put in the same section, which has a single
alignment value, it doesn't seem possible to tell whether a given string
doesn't have any alignment requirements. Preserving offset+alignments
for strings that don't need it is wasteful.
In practice, the crashes seen so far seem to stem from x86_64 SIMD
operations on cstrings. X86_64 requires SIMD accesses to be
16-byte-aligned. So for now, I'm thinking of just aligning all strings
to 16 bytes on x86_64. This is indeed wasteful, but implementation-wise
it's simpler than preserving per-string alignment+offsets. It also
avoids the aforementioned crash after deduplication of
differently-aligned strings. Finally, the overhead is not huge: using
16-byte alignment (vs no alignment) is only a 0.5% size overhead when
linking chromium_framework.
With these alignment requirements, it doesn't make sense to attempt tail
merging -- most strings will not be eligible since their overlaps aren't
likely to start at a 16-byte boundary. Tail-merging (with alignment) for
chromium_framework only improves size by 0.3%.
It's worth noting that LLD-ELF only does tail merging at `-O2`. By
default (at `-O1`), it just deduplicates w/o tail merging. @thakis has
also mentioned that they saw it regress compressed size in some cases
and therefore turned it off. `ld64` does not seem to do tail merging at
all.
**Performance Numbers**
CString deduplication reduces chromium_framework from 250MB to 242MB, or
about a 3.2% reduction.
Numbers for linking chromium_framework on my 3.2 GHz 16-Core Intel Xeon W:
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.99 4.14 4.015 4.0365 0.0492336
Difference at 95.0% confidence
0.0865 +/- 0.027245
2.18987% +/- 0.689746%
(Student's t, pooled s = 0.0425673)
As expected, cstring merging incurs some non-trivial overhead.
When passing `--no-literal-merge`, it seems that performance is the
same, i.e. the refactoring in this diff didn't cost us.
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.89 4.02 3.935 3.9435 0.043197831
No difference proven at 95.0% confidence
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D102964
2021-06-07 23:47:12 -04:00
|
|
|
// There are 4 cases where we do not need to create a new subsection:
|
2021-04-06 15:09:14 -04:00
|
|
|
// 1. If the input file does not use subsections-via-symbols.
|
|
|
|
|
// 2. Multiple symbols at the same address only induce one subsection.
|
[lld/mac] Write every weak symbol only once in the output
Before this, if an inline function was defined in several input files,
lld would write each copy of the inline function the output. With this
patch, it only writes one copy.
Reduces the size of Chromium Framework from 378MB to 345MB (compared
to 290MB linked with ld64, which also does dead-stripping, which we
don't do yet), and makes linking it faster:
N Min Max Median Avg Stddev
x 10 3.9957051 4.3496981 4.1411121 4.156837 0.10092097
+ 10 3.908154 4.169318 3.9712729 3.9846753 0.075773012
Difference at 95.0% confidence
-0.172162 +/- 0.083847
-4.14165% +/- 2.01709%
(Student's t, pooled s = 0.0892373)
Implementation-wise, when merging two weak symbols, this sets a
"canOmitFromOutput" on the InputSection belonging to the weak symbol not put in
the symbol table. We then don't write InputSections that have this set, as long
as they are not referenced from other symbols. (This happens e.g. for object
files that don't set .subsections_via_symbols or that use .alt_entry.)
Some restrictions:
- not yet done for bitcode inputs
- no "comdat" handling (`kindNoneGroupSubordinate*` in ld64) --
Frame Descriptor Entries (FDEs), Language Specific Data Areas (LSDAs)
(that is, catch block unwind information) and Personality Routines
associated with weak functions still not stripped. This is wasteful,
but harmless.
- However, this does strip weaks from __unwind_info (which is needed for
correctness and not just for size)
- This nopes out on InputSections that are referenced form more than
one symbol (eg from .alt_entry) for now
Things that work based on symbols Just Work:
- map files (change in MapFile.cpp is no-op and not needed; I just
found it a bit more explicit)
- exports
Things that work with inputSections need to explicitly check if
an inputSection is written (e.g. unwind info).
This patch is useful in itself, but it's also likely also a useful foundation
for dead_strip.
I used to have a "canoncialRepresentative" pointer on InputSection instead of
just the bool, which would be handy for ICF too. But I ended up not needing it
for this patch, so I removed that again for now.
Differential Revision: https://reviews.llvm.org/D102076
2021-05-06 14:47:57 -04:00
|
|
|
// (The symbolOffset == 0 check covers both this case as well as
|
|
|
|
|
// the first loop iteration.)
|
2021-04-06 15:09:14 -04:00
|
|
|
// 3. Alternative entry points do not induce new subsections.
|
[lld-macho] Implement cstring deduplication
Our implementation draws heavily from LLD-ELF's, which in turn delegates
its string deduplication to llvm-mc's StringTableBuilder. The messiness of
this diff is largely due to the fact that we've previously assumed that
all InputSections get concatenated together to form the output. This is
no longer true with CStringInputSections, which split their contents into
StringPieces. StringPieces are much more lightweight than InputSections,
which is important as we create a lot of them. They may also overlap in
the output, which makes it possible for strings to be tail-merged. In
fact, the initial version of this diff implemented tail merging, but
I've dropped it for reasons I'll explain later.
**Alignment Issues**
Mergeable cstring literals are found under the `__TEXT,__cstring`
section. In contrast to ELF, which puts strings that need different
alignments into different sections, clang's Mach-O backend puts them all
in one section. Strings that need to be aligned have the `.p2align`
directive emitted before them, which simply translates into zero padding
in the object file.
I *think* ld64 extracts the desired per-string alignment from this data
by preserving each string's offset from the last section-aligned
address. I'm not entirely certain since it doesn't seem consistent about
doing this; but perhaps this can be chalked up to cases where ld64 has
to deduplicate strings with different offset/alignment combos -- it
seems to pick one of their alignments to preserve. This doesn't seem
correct in general; we can in fact can induce ld64 to produce a crashing
binary just by linking in an additional object file that only contains
cstrings and no code. See PR50563 for details.
Moreover, this scheme seems rather inefficient: since unaligned and
aligned strings are all put in the same section, which has a single
alignment value, it doesn't seem possible to tell whether a given string
doesn't have any alignment requirements. Preserving offset+alignments
for strings that don't need it is wasteful.
In practice, the crashes seen so far seem to stem from x86_64 SIMD
operations on cstrings. X86_64 requires SIMD accesses to be
16-byte-aligned. So for now, I'm thinking of just aligning all strings
to 16 bytes on x86_64. This is indeed wasteful, but implementation-wise
it's simpler than preserving per-string alignment+offsets. It also
avoids the aforementioned crash after deduplication of
differently-aligned strings. Finally, the overhead is not huge: using
16-byte alignment (vs no alignment) is only a 0.5% size overhead when
linking chromium_framework.
With these alignment requirements, it doesn't make sense to attempt tail
merging -- most strings will not be eligible since their overlaps aren't
likely to start at a 16-byte boundary. Tail-merging (with alignment) for
chromium_framework only improves size by 0.3%.
It's worth noting that LLD-ELF only does tail merging at `-O2`. By
default (at `-O1`), it just deduplicates w/o tail merging. @thakis has
also mentioned that they saw it regress compressed size in some cases
and therefore turned it off. `ld64` does not seem to do tail merging at
all.
**Performance Numbers**
CString deduplication reduces chromium_framework from 250MB to 242MB, or
about a 3.2% reduction.
Numbers for linking chromium_framework on my 3.2 GHz 16-Core Intel Xeon W:
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.99 4.14 4.015 4.0365 0.0492336
Difference at 95.0% confidence
0.0865 +/- 0.027245
2.18987% +/- 0.689746%
(Student's t, pooled s = 0.0425673)
As expected, cstring merging incurs some non-trivial overhead.
When passing `--no-literal-merge`, it seems that performance is the
same, i.e. the refactoring in this diff didn't cost us.
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.89 4.02 3.935 3.9435 0.043197831
No difference proven at 95.0% confidence
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D102964
2021-06-07 23:47:12 -04:00
|
|
|
// 4. If we have a literal section (e.g. __cstring and __literal4).
|
2021-04-06 15:09:14 -04:00
|
|
|
if (!subsectionsViaSymbols || symbolOffset == 0 ||
|
[lld-macho] Implement cstring deduplication
Our implementation draws heavily from LLD-ELF's, which in turn delegates
its string deduplication to llvm-mc's StringTableBuilder. The messiness of
this diff is largely due to the fact that we've previously assumed that
all InputSections get concatenated together to form the output. This is
no longer true with CStringInputSections, which split their contents into
StringPieces. StringPieces are much more lightweight than InputSections,
which is important as we create a lot of them. They may also overlap in
the output, which makes it possible for strings to be tail-merged. In
fact, the initial version of this diff implemented tail merging, but
I've dropped it for reasons I'll explain later.
**Alignment Issues**
Mergeable cstring literals are found under the `__TEXT,__cstring`
section. In contrast to ELF, which puts strings that need different
alignments into different sections, clang's Mach-O backend puts them all
in one section. Strings that need to be aligned have the `.p2align`
directive emitted before them, which simply translates into zero padding
in the object file.
I *think* ld64 extracts the desired per-string alignment from this data
by preserving each string's offset from the last section-aligned
address. I'm not entirely certain since it doesn't seem consistent about
doing this; but perhaps this can be chalked up to cases where ld64 has
to deduplicate strings with different offset/alignment combos -- it
seems to pick one of their alignments to preserve. This doesn't seem
correct in general; we can in fact can induce ld64 to produce a crashing
binary just by linking in an additional object file that only contains
cstrings and no code. See PR50563 for details.
Moreover, this scheme seems rather inefficient: since unaligned and
aligned strings are all put in the same section, which has a single
alignment value, it doesn't seem possible to tell whether a given string
doesn't have any alignment requirements. Preserving offset+alignments
for strings that don't need it is wasteful.
In practice, the crashes seen so far seem to stem from x86_64 SIMD
operations on cstrings. X86_64 requires SIMD accesses to be
16-byte-aligned. So for now, I'm thinking of just aligning all strings
to 16 bytes on x86_64. This is indeed wasteful, but implementation-wise
it's simpler than preserving per-string alignment+offsets. It also
avoids the aforementioned crash after deduplication of
differently-aligned strings. Finally, the overhead is not huge: using
16-byte alignment (vs no alignment) is only a 0.5% size overhead when
linking chromium_framework.
With these alignment requirements, it doesn't make sense to attempt tail
merging -- most strings will not be eligible since their overlaps aren't
likely to start at a 16-byte boundary. Tail-merging (with alignment) for
chromium_framework only improves size by 0.3%.
It's worth noting that LLD-ELF only does tail merging at `-O2`. By
default (at `-O1`), it just deduplicates w/o tail merging. @thakis has
also mentioned that they saw it regress compressed size in some cases
and therefore turned it off. `ld64` does not seem to do tail merging at
all.
**Performance Numbers**
CString deduplication reduces chromium_framework from 250MB to 242MB, or
about a 3.2% reduction.
Numbers for linking chromium_framework on my 3.2 GHz 16-Core Intel Xeon W:
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.99 4.14 4.015 4.0365 0.0492336
Difference at 95.0% confidence
0.0865 +/- 0.027245
2.18987% +/- 0.689746%
(Student's t, pooled s = 0.0425673)
As expected, cstring merging incurs some non-trivial overhead.
When passing `--no-literal-merge`, it seems that performance is the
same, i.e. the refactoring in this diff didn't cost us.
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.89 4.02 3.935 3.9435 0.043197831
No difference proven at 95.0% confidence
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D102964
2021-06-07 23:47:12 -04:00
|
|
|
sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) {
|
2022-10-18 17:21:39 -04:00
|
|
|
isec->hasAltEntry = symbolOffset != 0;
|
2023-03-10 22:28:36 -05:00
|
|
|
symbols[symIndex] = createDefined(sym, name, isec, symbolOffset,
|
|
|
|
|
symbolSize, forceHidden);
|
2021-04-06 15:09:14 -04:00
|
|
|
continue;
|
|
|
|
|
}
|
[lld-macho] Implement cstring deduplication
Our implementation draws heavily from LLD-ELF's, which in turn delegates
its string deduplication to llvm-mc's StringTableBuilder. The messiness of
this diff is largely due to the fact that we've previously assumed that
all InputSections get concatenated together to form the output. This is
no longer true with CStringInputSections, which split their contents into
StringPieces. StringPieces are much more lightweight than InputSections,
which is important as we create a lot of them. They may also overlap in
the output, which makes it possible for strings to be tail-merged. In
fact, the initial version of this diff implemented tail merging, but
I've dropped it for reasons I'll explain later.
**Alignment Issues**
Mergeable cstring literals are found under the `__TEXT,__cstring`
section. In contrast to ELF, which puts strings that need different
alignments into different sections, clang's Mach-O backend puts them all
in one section. Strings that need to be aligned have the `.p2align`
directive emitted before them, which simply translates into zero padding
in the object file.
I *think* ld64 extracts the desired per-string alignment from this data
by preserving each string's offset from the last section-aligned
address. I'm not entirely certain since it doesn't seem consistent about
doing this; but perhaps this can be chalked up to cases where ld64 has
to deduplicate strings with different offset/alignment combos -- it
seems to pick one of their alignments to preserve. This doesn't seem
correct in general; we can in fact can induce ld64 to produce a crashing
binary just by linking in an additional object file that only contains
cstrings and no code. See PR50563 for details.
Moreover, this scheme seems rather inefficient: since unaligned and
aligned strings are all put in the same section, which has a single
alignment value, it doesn't seem possible to tell whether a given string
doesn't have any alignment requirements. Preserving offset+alignments
for strings that don't need it is wasteful.
In practice, the crashes seen so far seem to stem from x86_64 SIMD
operations on cstrings. X86_64 requires SIMD accesses to be
16-byte-aligned. So for now, I'm thinking of just aligning all strings
to 16 bytes on x86_64. This is indeed wasteful, but implementation-wise
it's simpler than preserving per-string alignment+offsets. It also
avoids the aforementioned crash after deduplication of
differently-aligned strings. Finally, the overhead is not huge: using
16-byte alignment (vs no alignment) is only a 0.5% size overhead when
linking chromium_framework.
With these alignment requirements, it doesn't make sense to attempt tail
merging -- most strings will not be eligible since their overlaps aren't
likely to start at a 16-byte boundary. Tail-merging (with alignment) for
chromium_framework only improves size by 0.3%.
It's worth noting that LLD-ELF only does tail merging at `-O2`. By
default (at `-O1`), it just deduplicates w/o tail merging. @thakis has
also mentioned that they saw it regress compressed size in some cases
and therefore turned it off. `ld64` does not seem to do tail merging at
all.
**Performance Numbers**
CString deduplication reduces chromium_framework from 250MB to 242MB, or
about a 3.2% reduction.
Numbers for linking chromium_framework on my 3.2 GHz 16-Core Intel Xeon W:
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.99 4.14 4.015 4.0365 0.0492336
Difference at 95.0% confidence
0.0865 +/- 0.027245
2.18987% +/- 0.689746%
(Student's t, pooled s = 0.0425673)
As expected, cstring merging incurs some non-trivial overhead.
When passing `--no-literal-merge`, it seems that performance is the
same, i.e. the refactoring in this diff didn't cost us.
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.89 4.02 3.935 3.9435 0.043197831
No difference proven at 95.0% confidence
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D102964
2021-06-07 23:47:12 -04:00
|
|
|
auto *concatIsec = cast<ConcatInputSection>(isec);
|
[lld-macho][re-land] Support .subsections_via_symbols
Summary:
This diff restores and builds upon @pcc and @ruiu's initial work on
subsections.
The .subsections_via_symbols directive indicates we can split each
section along symbol boundaries, unless those symbols have been marked
with `.alt_entry`.
We exercise this functionality in our tests by using order files that
rearrange those symbols.
Depends on D79668.
Reviewers: ruiu, pcc, MaskRay, smeenai, alexshap, gkm, Ktwu, christylee
Reviewed By: smeenai
Subscribers: thakis, llvm-commits, pcc, ruiu
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D79926
2020-05-19 08:46:07 -07:00
|
|
|
|
[lld-macho] Implement cstring deduplication
Our implementation draws heavily from LLD-ELF's, which in turn delegates
its string deduplication to llvm-mc's StringTableBuilder. The messiness of
this diff is largely due to the fact that we've previously assumed that
all InputSections get concatenated together to form the output. This is
no longer true with CStringInputSections, which split their contents into
StringPieces. StringPieces are much more lightweight than InputSections,
which is important as we create a lot of them. They may also overlap in
the output, which makes it possible for strings to be tail-merged. In
fact, the initial version of this diff implemented tail merging, but
I've dropped it for reasons I'll explain later.
**Alignment Issues**
Mergeable cstring literals are found under the `__TEXT,__cstring`
section. In contrast to ELF, which puts strings that need different
alignments into different sections, clang's Mach-O backend puts them all
in one section. Strings that need to be aligned have the `.p2align`
directive emitted before them, which simply translates into zero padding
in the object file.
I *think* ld64 extracts the desired per-string alignment from this data
by preserving each string's offset from the last section-aligned
address. I'm not entirely certain since it doesn't seem consistent about
doing this; but perhaps this can be chalked up to cases where ld64 has
to deduplicate strings with different offset/alignment combos -- it
seems to pick one of their alignments to preserve. This doesn't seem
correct in general; we can in fact can induce ld64 to produce a crashing
binary just by linking in an additional object file that only contains
cstrings and no code. See PR50563 for details.
Moreover, this scheme seems rather inefficient: since unaligned and
aligned strings are all put in the same section, which has a single
alignment value, it doesn't seem possible to tell whether a given string
doesn't have any alignment requirements. Preserving offset+alignments
for strings that don't need it is wasteful.
In practice, the crashes seen so far seem to stem from x86_64 SIMD
operations on cstrings. X86_64 requires SIMD accesses to be
16-byte-aligned. So for now, I'm thinking of just aligning all strings
to 16 bytes on x86_64. This is indeed wasteful, but implementation-wise
it's simpler than preserving per-string alignment+offsets. It also
avoids the aforementioned crash after deduplication of
differently-aligned strings. Finally, the overhead is not huge: using
16-byte alignment (vs no alignment) is only a 0.5% size overhead when
linking chromium_framework.
With these alignment requirements, it doesn't make sense to attempt tail
merging -- most strings will not be eligible since their overlaps aren't
likely to start at a 16-byte boundary. Tail-merging (with alignment) for
chromium_framework only improves size by 0.3%.
It's worth noting that LLD-ELF only does tail merging at `-O2`. By
default (at `-O1`), it just deduplicates w/o tail merging. @thakis has
also mentioned that they saw it regress compressed size in some cases
and therefore turned it off. `ld64` does not seem to do tail merging at
all.
**Performance Numbers**
CString deduplication reduces chromium_framework from 250MB to 242MB, or
about a 3.2% reduction.
Numbers for linking chromium_framework on my 3.2 GHz 16-Core Intel Xeon W:
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.99 4.14 4.015 4.0365 0.0492336
Difference at 95.0% confidence
0.0865 +/- 0.027245
2.18987% +/- 0.689746%
(Student's t, pooled s = 0.0425673)
As expected, cstring merging incurs some non-trivial overhead.
When passing `--no-literal-merge`, it seems that performance is the
same, i.e. the refactoring in this diff didn't cost us.
N Min Max Median Avg Stddev
x 20 3.91 4.03 3.935 3.95 0.034641016
+ 20 3.89 4.02 3.935 3.9435 0.043197831
No difference proven at 95.0% confidence
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D102964
2021-06-07 23:47:12 -04:00
|
|
|
auto *nextIsec = make<ConcatInputSection>(*concatIsec);
|
[lld/mac] Implement -dead_strip
Also adds support for live_support sections, no_dead_strip sections,
.no_dead_strip symbols.
Chromium Framework 345MB unstripped -> 250MB stripped
(vs 290MB unstripped -> 236M stripped with ld64).
Doing dead stripping is a bit faster than not, because so much less
data needs to be processed:
% ministat lld_*
x lld_nostrip.txt
+ lld_strip.txt
N Min Max Median Avg Stddev
x 10 3.929414 4.07692 4.0269079 4.0089678 0.044214794
+ 10 3.8129408 3.9025559 3.8670411 3.8642573 0.024779651
Difference at 95.0% confidence
-0.144711 +/- 0.0336749
-3.60967% +/- 0.839989%
(Student's t, pooled s = 0.0358398)
This interacts with many parts of the linker. I tried to add test coverage
for all added `isLive()` checks, so that some test will fail if any of them
is removed. I checked that the test expectations for the most part match
ld64's behavior (except for live-support-iterations.s, see the comment
in the test). Interacts with:
- debug info
- export tries
- import opcodes
- flags like -exported_symbol(s_list)
- -U / dynamic_lookup
- mod_init_funcs, mod_term_funcs
- weak symbol handling
- unwind info
- stubs
- map files
- -sectcreate
- undefined, dylib, common, defined (both absolute and normal) symbols
It's possible it interacts with more features I didn't think of,
of course.
I also did some manual testing:
- check-llvm check-clang check-lld work with lld with this patch
as host linker and -dead_strip enabled
- Chromium still starts
- Chromium's base_unittests still pass, including unwind tests
Implemenation-wise, this is InputSection-based, so it'll work for
object files with .subsections_via_symbols (which includes all
object files generated by clang). I first based this on the COFF
implementation, but later realized that things are more similar to ELF.
I think it'd be good to refactor MarkLive.cpp to look more like the ELF
part at some point, but I'd like to get a working state checked in first.
Mechanical parts:
- Rename canOmitFromOutput to wasCoalesced (no behavior change)
since it really is for weak coalesced symbols
- Add noDeadStrip to Defined, corresponding to N_NO_DEAD_STRIP
(`.no_dead_strip` in asm)
Fixes PR49276.
Differential Revision: https://reviews.llvm.org/D103324
2021-05-07 17:10:05 -04:00
|
|
|
nextIsec->wasCoalesced = false;
|
2021-07-01 20:33:55 -04:00
|
|
|
if (isZeroFill(isec->getFlags())) {
|
2021-05-19 09:58:17 -07:00
|
|
|
// Zero-fill sections have NULL data.data() non-zero data.size()
|
|
|
|
|
nextIsec->data = {nullptr, isec->data.size() - symbolOffset};
|
|
|
|
|
isec->data = {nullptr, symbolOffset};
|
|
|
|
|
} else {
|
|
|
|
|
nextIsec->data = isec->data.slice(symbolOffset);
|
|
|
|
|
isec->data = isec->data.slice(0, symbolOffset);
|
|
|
|
|
}
|
[lld-macho][re-land] Support .subsections_via_symbols
Summary:
This diff restores and builds upon @pcc and @ruiu's initial work on
subsections.
The .subsections_via_symbols directive indicates we can split each
section along symbol boundaries, unless those symbols have been marked
with `.alt_entry`.
We exercise this functionality in our tests by using order files that
rearrange those symbols.
Depends on D79668.
Reviewers: ruiu, pcc, MaskRay, smeenai, alexshap, gkm, Ktwu, christylee
Reviewed By: smeenai
Subscribers: thakis, llvm-commits, pcc, ruiu
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D79926
2020-05-19 08:46:07 -07:00
|
|
|
|
2021-04-06 17:52:30 -04:00
|
|
|
// By construction, the symbol will be at offset zero in the new
|
|
|
|
|
// subsection.
|
2022-07-25 11:45:55 +02:00
|
|
|
symbols[symIndex] = createDefined(sym, name, nextIsec, /*value=*/0,
|
|
|
|
|
symbolSize, forceHidden);
|
2021-04-06 15:09:14 -04:00
|
|
|
// TODO: ld64 appears to preserve the original alignment as well as each
|
|
|
|
|
// subsection's offset from the last aligned address. We should consider
|
|
|
|
|
// emulating that behavior.
|
2021-05-09 18:35:16 -04:00
|
|
|
nextIsec->align = MinAlign(sectionAlign, sym.n_value);
|
2021-11-04 20:55:31 -07:00
|
|
|
subsections.push_back({sym.n_value - sectionAddr, nextIsec});
|
2021-04-06 15:09:14 -04:00
|
|
|
}
|
|
|
|
|
}
|
2021-07-19 14:38:15 -04:00
|
|
|
|
|
|
|
|
// Undefined symbols can trigger recursive fetch from Archives due to
|
|
|
|
|
// LazySymbols. Process defined symbols first so that the relative order
|
|
|
|
|
// between a defined symbol and an undefined symbol does not change the
|
|
|
|
|
// symbol resolution behavior. In addition, a set of interconnected symbols
|
|
|
|
|
// will all be resolved to the same file, instead of being resolved to
|
|
|
|
|
// different files.
|
2022-09-15 22:55:41 -04:00
|
|
|
for (unsigned i : undefineds)
|
|
|
|
|
symbols[i] = parseNonSectionSymbol(nList[i], strtab);
|
2020-04-02 11:54:05 -07:00
|
|
|
}
|
|
|
|
|
|
2020-08-10 18:47:13 -07:00
|
|
|
OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
|
|
|
|
|
StringRef sectName)
|
|
|
|
|
: InputFile(OpaqueKind, mb) {
|
|
|
|
|
const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
|
2021-07-01 20:33:55 -04:00
|
|
|
ArrayRef<uint8_t> data = {buf, mb.getBufferSize()};
|
[lld-macho][nfc] Eliminate InputSection::Shared
Earlier in LLD's evolution, I tried to create the illusion that
subsections were indistinguishable from "top-level" sections. Thus, even
though the subsections shared many common field values, I hid those
common values away in a private Shared struct (see D105305). More
recently, however, @gkm added a public `Section` struct in D113241 that
served as an explicit way to store values that are common to an entire
set of subsections (aka InputSections). Now that we have another "common
value" struct, `Shared` has been rendered redundant. All its fields can
be moved into `Section` instead, and the pointer to `Shared` can be replaced
with a pointer to `Section`.
This `Section` pointer also has the advantage of letting us inspect other
subsections easily, simplifying the implementation of {D118798}.
P.S. I do think that having both `Section` and `InputSection` makes for
a slightly confusing naming scheme. I considered renaming `InputSection`
to `Subsection`, but that would break the symmetry with `OutputSection`.
It would also make us deviate from LLD-ELF's naming scheme.
This change is perf-neutral on my 3.2 GHz 16-Core Intel Xeon W machine:
base diff difference (95% CI)
sys_time 1.258 ± 0.031 1.248 ± 0.023 [ -1.6% .. +0.1%]
user_time 3.659 ± 0.047 3.658 ± 0.041 [ -0.5% .. +0.4%]
wall_time 4.640 ± 0.085 4.625 ± 0.063 [ -1.0% .. +0.3%]
samples 49 61
There's also no stat sig change in RSS (as measured by `time -l`):
base diff difference (95% CI)
time 998038627.097 ± 13567305.958 1003327715.556 ± 15210451.236 [ -0.2% .. +1.2%]
samples 31 36
Reviewed By: #lld-macho, oontvoo
Differential Revision: https://reviews.llvm.org/D118797
2022-02-03 19:53:29 -05:00
|
|
|
sections.push_back(make<Section>(/*file=*/this, segName.take_front(16),
|
|
|
|
|
sectName.take_front(16),
|
|
|
|
|
/*flags=*/0, /*addr=*/0));
|
|
|
|
|
Section §ion = *sections.back();
|
|
|
|
|
ConcatInputSection *isec = make<ConcatInputSection>(section, data);
|
[lld/mac] Implement -dead_strip
Also adds support for live_support sections, no_dead_strip sections,
.no_dead_strip symbols.
Chromium Framework 345MB unstripped -> 250MB stripped
(vs 290MB unstripped -> 236M stripped with ld64).
Doing dead stripping is a bit faster than not, because so much less
data needs to be processed:
% ministat lld_*
x lld_nostrip.txt
+ lld_strip.txt
N Min Max Median Avg Stddev
x 10 3.929414 4.07692 4.0269079 4.0089678 0.044214794
+ 10 3.8129408 3.9025559 3.8670411 3.8642573 0.024779651
Difference at 95.0% confidence
-0.144711 +/- 0.0336749
-3.60967% +/- 0.839989%
(Student's t, pooled s = 0.0358398)
This interacts with many parts of the linker. I tried to add test coverage
for all added `isLive()` checks, so that some test will fail if any of them
is removed. I checked that the test expectations for the most part match
ld64's behavior (except for live-support-iterations.s, see the comment
in the test). Interacts with:
- debug info
- export tries
- import opcodes
- flags like -exported_symbol(s_list)
- -U / dynamic_lookup
- mod_init_funcs, mod_term_funcs
- weak symbol handling
- unwind info
- stubs
- map files
- -sectcreate
- undefined, dylib, common, defined (both absolute and normal) symbols
It's possible it interacts with more features I didn't think of,
of course.
I also did some manual testing:
- check-llvm check-clang check-lld work with lld with this patch
as host linker and -dead_strip enabled
- Chromium still starts
- Chromium's base_unittests still pass, including unwind tests
Implemenation-wise, this is InputSection-based, so it'll work for
object files with .subsections_via_symbols (which includes all
object files generated by clang). I first based this on the COFF
implementation, but later realized that things are more similar to ELF.
I think it'd be good to refactor MarkLive.cpp to look more like the ELF
part at some point, but I'd like to get a working state checked in first.
Mechanical parts:
- Rename canOmitFromOutput to wasCoalesced (no behavior change)
since it really is for weak coalesced symbols
- Add noDeadStrip to Defined, corresponding to N_NO_DEAD_STRIP
(`.no_dead_strip` in asm)
Fixes PR49276.
Differential Revision: https://reviews.llvm.org/D103324
2021-05-07 17:10:05 -04:00
|
|
|
isec->live = true;
|
[lld-macho][nfc] Eliminate InputSection::Shared
Earlier in LLD's evolution, I tried to create the illusion that
subsections were indistinguishable from "top-level" sections. Thus, even
though the subsections shared many common field values, I hid those
common values away in a private Shared struct (see D105305). More
recently, however, @gkm added a public `Section` struct in D113241 that
served as an explicit way to store values that are common to an entire
set of subsections (aka InputSections). Now that we have another "common
value" struct, `Shared` has been rendered redundant. All its fields can
be moved into `Section` instead, and the pointer to `Shared` can be replaced
with a pointer to `Section`.
This `Section` pointer also has the advantage of letting us inspect other
subsections easily, simplifying the implementation of {D118798}.
P.S. I do think that having both `Section` and `InputSection` makes for
a slightly confusing naming scheme. I considered renaming `InputSection`
to `Subsection`, but that would break the symmetry with `OutputSection`.
It would also make us deviate from LLD-ELF's naming scheme.
This change is perf-neutral on my 3.2 GHz 16-Core Intel Xeon W machine:
base diff difference (95% CI)
sys_time 1.258 ± 0.031 1.248 ± 0.023 [ -1.6% .. +0.1%]
user_time 3.659 ± 0.047 3.658 ± 0.041 [ -0.5% .. +0.4%]
wall_time 4.640 ± 0.085 4.625 ± 0.063 [ -1.0% .. +0.3%]
samples 49 61
There's also no stat sig change in RSS (as measured by `time -l`):
base diff difference (95% CI)
time 998038627.097 ± 13567305.958 1003327715.556 ± 15210451.236 [ -0.2% .. +1.2%]
samples 31 36
Reviewed By: #lld-macho, oontvoo
Differential Revision: https://reviews.llvm.org/D118797
2022-02-03 19:53:29 -05:00
|
|
|
section.subsections.push_back({0, isec});
|
2020-08-10 18:47:13 -07:00
|
|
|
}
|
|
|
|
|
|
2023-08-13 13:38:49 -07:00
|
|
|
template <class LP>
|
|
|
|
|
void ObjFile::parseLinkerOptions(SmallVectorImpl<StringRef> &LCLinkerOptions) {
|
|
|
|
|
using Header = typename LP::mach_header;
|
|
|
|
|
auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
|
|
|
|
|
|
|
|
|
|
for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) {
|
|
|
|
|
StringRef data{reinterpret_cast<const char *>(cmd + 1),
|
|
|
|
|
cmd->cmdsize - sizeof(linker_option_command)};
|
|
|
|
|
parseLCLinkerOption(LCLinkerOptions, this, cmd->count, data);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
SmallVector<StringRef> macho::unprocessedLCLinkerOptions;
|
2022-01-19 10:14:49 -08:00
|
|
|
ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,
|
2023-08-22 12:02:52 -07:00
|
|
|
bool lazy, bool forceHidden, bool compatArch,
|
|
|
|
|
bool builtFromBitcode)
|
|
|
|
|
: InputFile(ObjKind, mb, lazy), modTime(modTime), forceHidden(forceHidden),
|
|
|
|
|
builtFromBitcode(builtFromBitcode) {
|
2020-12-01 19:00:48 -05:00
|
|
|
this->archiveName = std::string(archiveName);
|
2023-07-27 13:56:23 -04:00
|
|
|
this->compatArch = compatArch;
|
2022-01-19 10:14:49 -08:00
|
|
|
if (lazy) {
|
|
|
|
|
if (target->wordSize == 8)
|
|
|
|
|
parseLazy<LP64>();
|
|
|
|
|
else
|
|
|
|
|
parseLazy<ILP32>();
|
|
|
|
|
} else {
|
|
|
|
|
if (target->wordSize == 8)
|
|
|
|
|
parse<LP64>();
|
|
|
|
|
else
|
|
|
|
|
parse<ILP32>();
|
|
|
|
|
}
|
2021-04-02 18:46:18 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
template <class LP> void ObjFile::parse() {
|
|
|
|
|
using Header = typename LP::mach_header;
|
|
|
|
|
using SegmentCommand = typename LP::segment_command;
|
2021-11-04 20:55:31 -07:00
|
|
|
using SectionHeader = typename LP::section;
|
2021-04-02 18:46:18 -04:00
|
|
|
using NList = typename LP::nlist;
|
2020-12-01 19:00:48 -05:00
|
|
|
|
2020-04-02 11:54:05 -07:00
|
|
|
auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
|
2021-04-02 18:46:18 -04:00
|
|
|
auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
|
2020-04-02 11:54:05 -07:00
|
|
|
|
2023-07-27 13:56:23 -04:00
|
|
|
// If we've already checked the arch, then don't need to check again.
|
|
|
|
|
if (!compatArch)
|
2021-02-23 21:42:00 -05:00
|
|
|
return;
|
2023-07-27 13:56:23 -04:00
|
|
|
if (!(compatArch = compatWithTargetArch(this, hdr)))
|
2021-04-21 05:41:14 -07:00
|
|
|
return;
|
2021-02-23 21:42:00 -05:00
|
|
|
|
2023-08-13 13:38:49 -07:00
|
|
|
// We will resolve LC linker options once all native objects are loaded after
|
|
|
|
|
// LTO is finished.
|
|
|
|
|
SmallVector<StringRef, 4> LCLinkerOptions;
|
|
|
|
|
parseLinkerOptions<LP>(LCLinkerOptions);
|
|
|
|
|
unprocessedLCLinkerOptions.append(LCLinkerOptions);
|
2020-12-03 16:40:04 -05:00
|
|
|
|
2021-11-04 20:55:31 -07:00
|
|
|
ArrayRef<SectionHeader> sectionHeaders;
|
2021-04-02 18:46:18 -04:00
|
|
|
if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {
|
|
|
|
|
auto *c = reinterpret_cast<const SegmentCommand *>(cmd);
|
2021-11-04 20:55:31 -07:00
|
|
|
sectionHeaders = ArrayRef<SectionHeader>{
|
|
|
|
|
reinterpret_cast<const SectionHeader *>(c + 1), c->nsects};
|
[lld-macho][re-land] Support .subsections_via_symbols
Summary:
This diff restores and builds upon @pcc and @ruiu's initial work on
subsections.
The .subsections_via_symbols directive indicates we can split each
section along symbol boundaries, unless those symbols have been marked
with `.alt_entry`.
We exercise this functionality in our tests by using order files that
rearrange those symbols.
Depends on D79668.
Reviewers: ruiu, pcc, MaskRay, smeenai, alexshap, gkm, Ktwu, christylee
Reviewed By: smeenai
Subscribers: thakis, llvm-commits, pcc, ruiu
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D79926
2020-05-19 08:46:07 -07:00
|
|
|
parseSections(sectionHeaders);
|
2020-04-02 11:54:05 -07:00
|
|
|
}
|
|
|
|
|
|
2020-04-21 13:37:57 -07:00
|
|
|
// TODO: Error on missing LC_SYMTAB?
|
2020-04-02 11:54:05 -07:00
|
|
|
if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
|
|
|
|
|
auto *c = reinterpret_cast<const symtab_command *>(cmd);
|
2021-04-02 18:46:18 -04:00
|
|
|
ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
|
|
|
|
|
c->nsyms);
|
[lld-macho][re-land] Support .subsections_via_symbols
Summary:
This diff restores and builds upon @pcc and @ruiu's initial work on
subsections.
The .subsections_via_symbols directive indicates we can split each
section along symbol boundaries, unless those symbols have been marked
with `.alt_entry`.
We exercise this functionality in our tests by using order files that
rearrange those symbols.
Depends on D79668.
Reviewers: ruiu, pcc, MaskRay, smeenai, alexshap, gkm, Ktwu, christylee
Reviewed By: smeenai
Subscribers: thakis, llvm-commits, pcc, ruiu
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D79926
2020-05-19 08:46:07 -07:00
|
|
|
const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
|
|
|
|
|
bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
|
2021-04-02 18:46:18 -04:00
|
|
|
parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);
|
2020-04-02 11:54:05 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// The relocations may refer to the symbols, so we parse them after we have
|
[lld-macho][re-land] Support .subsections_via_symbols
Summary:
This diff restores and builds upon @pcc and @ruiu's initial work on
subsections.
The .subsections_via_symbols directive indicates we can split each
section along symbol boundaries, unless those symbols have been marked
with `.alt_entry`.
We exercise this functionality in our tests by using order files that
rearrange those symbols.
Depends on D79668.
Reviewers: ruiu, pcc, MaskRay, smeenai, alexshap, gkm, Ktwu, christylee
Reviewed By: smeenai
Subscribers: thakis, llvm-commits, pcc, ruiu
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D79926
2020-05-19 08:46:07 -07:00
|
|
|
// parsed all the symbols.
|
2021-11-04 20:55:31 -07:00
|
|
|
for (size_t i = 0, n = sections.size(); i < n; ++i)
|
[lld-macho][nfc] Eliminate InputSection::Shared
Earlier in LLD's evolution, I tried to create the illusion that
subsections were indistinguishable from "top-level" sections. Thus, even
though the subsections shared many common field values, I hid those
common values away in a private Shared struct (see D105305). More
recently, however, @gkm added a public `Section` struct in D113241 that
served as an explicit way to store values that are common to an entire
set of subsections (aka InputSections). Now that we have another "common
value" struct, `Shared` has been rendered redundant. All its fields can
be moved into `Section` instead, and the pointer to `Shared` can be replaced
with a pointer to `Section`.
This `Section` pointer also has the advantage of letting us inspect other
subsections easily, simplifying the implementation of {D118798}.
P.S. I do think that having both `Section` and `InputSection` makes for
a slightly confusing naming scheme. I considered renaming `InputSection`
to `Subsection`, but that would break the symmetry with `OutputSection`.
It would also make us deviate from LLD-ELF's naming scheme.
This change is perf-neutral on my 3.2 GHz 16-Core Intel Xeon W machine:
base diff difference (95% CI)
sys_time 1.258 ± 0.031 1.248 ± 0.023 [ -1.6% .. +0.1%]
user_time 3.659 ± 0.047 3.658 ± 0.041 [ -0.5% .. +0.4%]
wall_time 4.640 ± 0.085 4.625 ± 0.063 [ -1.0% .. +0.3%]
samples 49 61
There's also no stat sig change in RSS (as measured by `time -l`):
base diff difference (95% CI)
time 998038627.097 ± 13567305.958 1003327715.556 ± 15210451.236 [ -0.2% .. +1.2%]
samples 31 36
Reviewed By: #lld-macho, oontvoo
Differential Revision: https://reviews.llvm.org/D118797
2022-02-03 19:53:29 -05:00
|
|
|
if (!sections[i]->subsections.empty())
|
2022-03-16 18:05:32 -04:00
|
|
|
parseRelocations(sectionHeaders, sectionHeaders[i], *sections[i]);
|
[lld-macho] Emit STABS symbols for debugging, and drop debug sections
Debug sections contain a large amount of data. In order not to bloat the size
of the final binary, we remove them and instead emit STABS symbols for
`dsymutil` and the debugger to locate their contents in the object files.
With this diff, `dsymutil` is able to locate the debug info. However, we need
a few more features before `lldb` is able to work well with our binaries --
e.g. having `LC_DYSYMTAB` accurately reflect the number of local symbols,
emitting `LC_UUID`, and more. Those will be handled in follow-up diffs.
Note also that the STABS we emit differ slightly from what ld64 does. First, we
emit the path to the source file as one `N_SO` symbol instead of two. (`ld64`
emits one `N_SO` for the dirname and one of the basename.) Second, we do not
emit `N_BNSYM` and `N_ENSYM` STABS to mark the start and end of functions,
because the `N_FUN` STABS already serve that purpose. @clayborg recommended
these changes based on his knowledge of what the debugging tools look for.
Additionally, this current implementation doesn't accurately reflect the size
of function symbols. It uses the size of their containing sectioins as a proxy,
but that is only accurate if `.subsections_with_symbols` is set, and if there
isn't an `N_ALT_ENTRY` in that particular subsection. I think we have two
options to solve this:
1. We can split up subsections by symbol even if `.subsections_with_symbols`
is not set, but include constraints to ensure those subsections retain
their order in the final output. This is `ld64`'s approach.
2. We could just add a `size` field to our `Symbol` class. This seems simpler,
and I'm more inclined toward it, but I'm not sure if there are use cases
that it doesn't handle well. As such I'm punting on the decision for now.
Reviewed By: clayborg
Differential Revision: https://reviews.llvm.org/D89257
2020-12-01 14:45:01 -08:00
|
|
|
|
|
|
|
|
parseDebugInfo();
|
2022-04-22 15:34:50 -04:00
|
|
|
|
|
|
|
|
Section *ehFrameSection = nullptr;
|
|
|
|
|
Section *compactUnwindSection = nullptr;
|
|
|
|
|
for (Section *sec : sections) {
|
|
|
|
|
Section **s = StringSwitch<Section **>(sec->name)
|
|
|
|
|
.Case(section_names::compactUnwind, &compactUnwindSection)
|
|
|
|
|
.Case(section_names::ehFrame, &ehFrameSection)
|
|
|
|
|
.Default(nullptr);
|
|
|
|
|
if (s)
|
|
|
|
|
*s = sec;
|
|
|
|
|
}
|
2021-11-15 11:46:59 -07:00
|
|
|
if (compactUnwindSection)
|
2022-04-22 15:34:50 -04:00
|
|
|
registerCompactUnwind(*compactUnwindSection);
|
[lld-macho] Enable EH frame relocation / pruning
This just removes the code that gates the logic. The main issue here is
perf impact: without {D122258}, LLD takes a significant perf hit because
it now has to do a lot more work in the input parsing phase. But with
that change to eliminate unnecessary EH frames from input object files,
the perf overhead here is minimal. Concretely, here are the numbers for
some builds as measured on my 16-core Mac Pro:
**chromium_framework**
This is without the use of `-femit-dwarf-unwind=no-compact-unwind`:
base diff difference (95% CI)
sys_time 1.826 ± 0.019 1.962 ± 0.034 [ +6.5% .. +8.4%]
user_time 9.306 ± 0.054 9.926 ± 0.082 [ +6.2% .. +7.1%]
wall_time 8.225 ± 0.068 8.947 ± 0.128 [ +8.0% .. +9.6%]
samples 15 22
With that flag enabled, the regression mostly disappears, as hoped:
base diff difference (95% CI)
sys_time 1.839 ± 0.062 1.866 ± 0.068 [ -0.9% .. +3.8%]
user_time 9.452 ± 0.068 9.490 ± 0.067 [ -0.1% .. +0.9%]
wall_time 8.383 ± 0.127 8.452 ± 0.114 [ -0.1% .. +1.8%]
samples 17 21
**Unnamed internal app**
Without `-femit-dwarf-unwind`, this is the perf hit:
base diff difference (95% CI)
sys_time 1.372 ± 0.029 1.317 ± 0.024 [ -4.6% .. -3.5%]
user_time 2.835 ± 0.028 2.980 ± 0.027 [ +4.8% .. +5.4%]
wall_time 3.205 ± 0.079 3.383 ± 0.066 [ +4.9% .. +6.2%]
samples 102 83
With `-femit-dwarf-unwind`, the perf hit almost disappears:
base diff difference (95% CI)
sys_time 1.274 ± 0.026 1.270 ± 0.025 [ -0.9% .. +0.3%]
user_time 2.812 ± 0.023 2.822 ± 0.035 [ +0.1% .. +0.7%]
wall_time 3.166 ± 0.047 3.174 ± 0.059 [ -0.2% .. +0.7%]
samples 95 97
Just for fun, I measured the impact of `-femit-dwarf-unwind` on ld64
(`base` has the extra DWARF unwind info in the input object files,
`diff` doesn't):
base diff difference (95% CI)
sys_time 1.128 ± 0.010 1.124 ± 0.023 [ -1.3% .. +0.6%]
user_time 7.176 ± 0.030 7.106 ± 0.094 [ -1.5% .. -0.4%]
wall_time 7.874 ± 0.041 7.795 ± 0.121 [ -1.7% .. -0.3%]
samples 16 25
And for LLD:
base diff difference (95% CI)
sys_time 1.315 ± 0.019 1.280 ± 0.019 [ -3.2% .. -2.0%]
user_time 2.980 ± 0.022 2.822 ± 0.016 [ -5.5% .. -5.0%]
wall_time 3.369 ± 0.038 3.175 ± 0.033 [ -6.2% .. -5.3%]
samples 47 47
So parsing the extra EH frames is a lot more expensive for us than for
ld64. But given that we are quite a lot faster than ld64 to begin with,
I guess this isn't entirely unexpected...
Reviewed By: #lld-macho, oontvoo
Differential Revision: https://reviews.llvm.org/D129540
2022-07-13 21:13:45 -04:00
|
|
|
if (ehFrameSection)
|
2022-06-12 21:56:45 -04:00
|
|
|
registerEhFrames(*ehFrameSection);
|
[lld-macho] Emit STABS symbols for debugging, and drop debug sections
Debug sections contain a large amount of data. In order not to bloat the size
of the final binary, we remove them and instead emit STABS symbols for
`dsymutil` and the debugger to locate their contents in the object files.
With this diff, `dsymutil` is able to locate the debug info. However, we need
a few more features before `lldb` is able to work well with our binaries --
e.g. having `LC_DYSYMTAB` accurately reflect the number of local symbols,
emitting `LC_UUID`, and more. Those will be handled in follow-up diffs.
Note also that the STABS we emit differ slightly from what ld64 does. First, we
emit the path to the source file as one `N_SO` symbol instead of two. (`ld64`
emits one `N_SO` for the dirname and one of the basename.) Second, we do not
emit `N_BNSYM` and `N_ENSYM` STABS to mark the start and end of functions,
because the `N_FUN` STABS already serve that purpose. @clayborg recommended
these changes based on his knowledge of what the debugging tools look for.
Additionally, this current implementation doesn't accurately reflect the size
of function symbols. It uses the size of their containing sectioins as a proxy,
but that is only accurate if `.subsections_with_symbols` is set, and if there
isn't an `N_ALT_ENTRY` in that particular subsection. I think we have two
options to solve this:
1. We can split up subsections by symbol even if `.subsections_with_symbols`
is not set, but include constraints to ensure those subsections retain
their order in the final output. This is `ld64`'s approach.
2. We could just add a `size` field to our `Symbol` class. This seems simpler,
and I'm more inclined toward it, but I'm not sure if there are use cases
that it doesn't handle well. As such I'm punting on the decision for now.
Reviewed By: clayborg
Differential Revision: https://reviews.llvm.org/D89257
2020-12-01 14:45:01 -08:00
|
|
|
}
|
|
|
|
|
|
2022-01-19 10:14:49 -08:00
|
|
|
template <class LP> void ObjFile::parseLazy() {
|
|
|
|
|
using Header = typename LP::mach_header;
|
|
|
|
|
using NList = typename LP::nlist;
|
|
|
|
|
|
|
|
|
|
auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
|
|
|
|
|
auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
|
2023-07-27 13:56:23 -04:00
|
|
|
|
|
|
|
|
if (!compatArch)
|
|
|
|
|
return;
|
|
|
|
|
if (!(compatArch = compatWithTargetArch(this, hdr)))
|
|
|
|
|
return;
|
|
|
|
|
|
2022-01-19 10:14:49 -08:00
|
|
|
const load_command *cmd = findCommand(hdr, LC_SYMTAB);
|
|
|
|
|
if (!cmd)
|
|
|
|
|
return;
|
|
|
|
|
auto *c = reinterpret_cast<const symtab_command *>(cmd);
|
|
|
|
|
ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
|
|
|
|
|
c->nsyms);
|
|
|
|
|
const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
|
|
|
|
|
symbols.resize(nList.size());
|
2022-10-22 10:41:10 -04:00
|
|
|
for (const auto &[i, sym] : llvm::enumerate(nList)) {
|
2022-01-19 10:14:49 -08:00
|
|
|
if ((sym.n_type & N_EXT) && !isUndef(sym)) {
|
|
|
|
|
// TODO: Bound checking
|
|
|
|
|
StringRef name = strtab + sym.n_strx;
|
2022-10-22 10:41:10 -04:00
|
|
|
symbols[i] = symtab->addLazyObject(name, *this);
|
2022-01-19 10:14:49 -08:00
|
|
|
if (!lazy)
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
[lld-macho] Emit STABS symbols for debugging, and drop debug sections
Debug sections contain a large amount of data. In order not to bloat the size
of the final binary, we remove them and instead emit STABS symbols for
`dsymutil` and the debugger to locate their contents in the object files.
With this diff, `dsymutil` is able to locate the debug info. However, we need
a few more features before `lldb` is able to work well with our binaries --
e.g. having `LC_DYSYMTAB` accurately reflect the number of local symbols,
emitting `LC_UUID`, and more. Those will be handled in follow-up diffs.
Note also that the STABS we emit differ slightly from what ld64 does. First, we
emit the path to the source file as one `N_SO` symbol instead of two. (`ld64`
emits one `N_SO` for the dirname and one of the basename.) Second, we do not
emit `N_BNSYM` and `N_ENSYM` STABS to mark the start and end of functions,
because the `N_FUN` STABS already serve that purpose. @clayborg recommended
these changes based on his knowledge of what the debugging tools look for.
Additionally, this current implementation doesn't accurately reflect the size
of function symbols. It uses the size of their containing sectioins as a proxy,
but that is only accurate if `.subsections_with_symbols` is set, and if there
isn't an `N_ALT_ENTRY` in that particular subsection. I think we have two
options to solve this:
1. We can split up subsections by symbol even if `.subsections_with_symbols`
is not set, but include constraints to ensure those subsections retain
their order in the final output. This is `ld64`'s approach.
2. We could just add a `size` field to our `Symbol` class. This seems simpler,
and I'm more inclined toward it, but I'm not sure if there are use cases
that it doesn't handle well. As such I'm punting on the decision for now.
Reviewed By: clayborg
Differential Revision: https://reviews.llvm.org/D89257
2020-12-01 14:45:01 -08:00
|
|
|
void ObjFile::parseDebugInfo() {
|
|
|
|
|
std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
|
|
|
|
|
if (!dObj)
|
|
|
|
|
return;
|
|
|
|
|
|
2022-06-21 16:40:27 -04:00
|
|
|
// We do not re-use the context from getDwarf() here as that function
|
|
|
|
|
// constructs an expensive DWARFCache object.
|
[lld-macho] Emit STABS symbols for debugging, and drop debug sections
Debug sections contain a large amount of data. In order not to bloat the size
of the final binary, we remove them and instead emit STABS symbols for
`dsymutil` and the debugger to locate their contents in the object files.
With this diff, `dsymutil` is able to locate the debug info. However, we need
a few more features before `lldb` is able to work well with our binaries --
e.g. having `LC_DYSYMTAB` accurately reflect the number of local symbols,
emitting `LC_UUID`, and more. Those will be handled in follow-up diffs.
Note also that the STABS we emit differ slightly from what ld64 does. First, we
emit the path to the source file as one `N_SO` symbol instead of two. (`ld64`
emits one `N_SO` for the dirname and one of the basename.) Second, we do not
emit `N_BNSYM` and `N_ENSYM` STABS to mark the start and end of functions,
because the `N_FUN` STABS already serve that purpose. @clayborg recommended
these changes based on his knowledge of what the debugging tools look for.
Additionally, this current implementation doesn't accurately reflect the size
of function symbols. It uses the size of their containing sectioins as a proxy,
but that is only accurate if `.subsections_with_symbols` is set, and if there
isn't an `N_ALT_ENTRY` in that particular subsection. I think we have two
options to solve this:
1. We can split up subsections by symbol even if `.subsections_with_symbols`
is not set, but include constraints to ensure those subsections retain
their order in the final output. This is `ld64`'s approach.
2. We could just add a `size` field to our `Symbol` class. This seems simpler,
and I'm more inclined toward it, but I'm not sure if there are use cases
that it doesn't handle well. As such I'm punting on the decision for now.
Reviewed By: clayborg
Differential Revision: https://reviews.llvm.org/D89257
2020-12-01 14:45:01 -08:00
|
|
|
auto *ctx = make<DWARFContext>(
|
|
|
|
|
std::move(dObj), "",
|
2020-12-01 19:00:48 -05:00
|
|
|
[&](Error err) {
|
|
|
|
|
warn(toString(this) + ": " + toString(std::move(err)));
|
|
|
|
|
},
|
[lld-macho] Emit STABS symbols for debugging, and drop debug sections
Debug sections contain a large amount of data. In order not to bloat the size
of the final binary, we remove them and instead emit STABS symbols for
`dsymutil` and the debugger to locate their contents in the object files.
With this diff, `dsymutil` is able to locate the debug info. However, we need
a few more features before `lldb` is able to work well with our binaries --
e.g. having `LC_DYSYMTAB` accurately reflect the number of local symbols,
emitting `LC_UUID`, and more. Those will be handled in follow-up diffs.
Note also that the STABS we emit differ slightly from what ld64 does. First, we
emit the path to the source file as one `N_SO` symbol instead of two. (`ld64`
emits one `N_SO` for the dirname and one of the basename.) Second, we do not
emit `N_BNSYM` and `N_ENSYM` STABS to mark the start and end of functions,
because the `N_FUN` STABS already serve that purpose. @clayborg recommended
these changes based on his knowledge of what the debugging tools look for.
Additionally, this current implementation doesn't accurately reflect the size
of function symbols. It uses the size of their containing sectioins as a proxy,
but that is only accurate if `.subsections_with_symbols` is set, and if there
isn't an `N_ALT_ENTRY` in that particular subsection. I think we have two
options to solve this:
1. We can split up subsections by symbol even if `.subsections_with_symbols`
is not set, but include constraints to ensure those subsections retain
their order in the final output. This is `ld64`'s approach.
2. We could just add a `size` field to our `Symbol` class. This seems simpler,
and I'm more inclined toward it, but I'm not sure if there are use cases
that it doesn't handle well. As such I'm punting on the decision for now.
Reviewed By: clayborg
Differential Revision: https://reviews.llvm.org/D89257
2020-12-01 14:45:01 -08:00
|
|
|
[&](Error warning) {
|
2020-12-01 19:00:48 -05:00
|
|
|
warn(toString(this) + ": " + toString(std::move(warning)));
|
[lld-macho] Emit STABS symbols for debugging, and drop debug sections
Debug sections contain a large amount of data. In order not to bloat the size
of the final binary, we remove them and instead emit STABS symbols for
`dsymutil` and the debugger to locate their contents in the object files.
With this diff, `dsymutil` is able to locate the debug info. However, we need
a few more features before `lldb` is able to work well with our binaries --
e.g. having `LC_DYSYMTAB` accurately reflect the number of local symbols,
emitting `LC_UUID`, and more. Those will be handled in follow-up diffs.
Note also that the STABS we emit differ slightly from what ld64 does. First, we
emit the path to the source file as one `N_SO` symbol instead of two. (`ld64`
emits one `N_SO` for the dirname and one of the basename.) Second, we do not
emit `N_BNSYM` and `N_ENSYM` STABS to mark the start and end of functions,
because the `N_FUN` STABS already serve that purpose. @clayborg recommended
these changes based on his knowledge of what the debugging tools look for.
Additionally, this current implementation doesn't accurately reflect the size
of function symbols. It uses the size of their containing sectioins as a proxy,
but that is only accurate if `.subsections_with_symbols` is set, and if there
isn't an `N_ALT_ENTRY` in that particular subsection. I think we have two
options to solve this:
1. We can split up subsections by symbol even if `.subsections_with_symbols`
is not set, but include constraints to ensure those subsections retain
their order in the final output. This is `ld64`'s approach.
2. We could just add a `size` field to our `Symbol` class. This seems simpler,
and I'm more inclined toward it, but I'm not sure if there are use cases
that it doesn't handle well. As such I'm punting on the decision for now.
Reviewed By: clayborg
Differential Revision: https://reviews.llvm.org/D89257
2020-12-01 14:45:01 -08:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// TODO: Since object files can contain a lot of DWARF info, we should verify
|
|
|
|
|
// that we are parsing just the info we need
|
|
|
|
|
const DWARFContext::compile_unit_range &units = ctx->compile_units();
|
2021-03-05 17:22:56 -05:00
|
|
|
// FIXME: There can be more than one compile unit per object file. See
|
|
|
|
|
// PR48637.
|
[lld-macho] Emit STABS symbols for debugging, and drop debug sections
Debug sections contain a large amount of data. In order not to bloat the size
of the final binary, we remove them and instead emit STABS symbols for
`dsymutil` and the debugger to locate their contents in the object files.
With this diff, `dsymutil` is able to locate the debug info. However, we need
a few more features before `lldb` is able to work well with our binaries --
e.g. having `LC_DYSYMTAB` accurately reflect the number of local symbols,
emitting `LC_UUID`, and more. Those will be handled in follow-up diffs.
Note also that the STABS we emit differ slightly from what ld64 does. First, we
emit the path to the source file as one `N_SO` symbol instead of two. (`ld64`
emits one `N_SO` for the dirname and one of the basename.) Second, we do not
emit `N_BNSYM` and `N_ENSYM` STABS to mark the start and end of functions,
because the `N_FUN` STABS already serve that purpose. @clayborg recommended
these changes based on his knowledge of what the debugging tools look for.
Additionally, this current implementation doesn't accurately reflect the size
of function symbols. It uses the size of their containing sectioins as a proxy,
but that is only accurate if `.subsections_with_symbols` is set, and if there
isn't an `N_ALT_ENTRY` in that particular subsection. I think we have two
options to solve this:
1. We can split up subsections by symbol even if `.subsections_with_symbols`
is not set, but include constraints to ensure those subsections retain
their order in the final output. This is `ld64`'s approach.
2. We could just add a `size` field to our `Symbol` class. This seems simpler,
and I'm more inclined toward it, but I'm not sure if there are use cases
that it doesn't handle well. As such I'm punting on the decision for now.
Reviewed By: clayborg
Differential Revision: https://reviews.llvm.org/D89257
2020-12-01 14:45:01 -08:00
|
|
|
auto it = units.begin();
|
2022-06-21 15:47:45 -04:00
|
|
|
compileUnit = it != units.end() ? it->get() : nullptr;
|
2020-04-02 11:54:05 -07:00
|
|
|
}
|
|
|
|
|
|
2021-12-11 01:01:14 -05:00
|
|
|
ArrayRef<data_in_code_entry> ObjFile::getDataInCode() const {
|
2021-06-14 19:21:43 -07:00
|
|
|
const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
|
|
|
|
|
const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE);
|
|
|
|
|
if (!cmd)
|
2021-12-11 01:01:14 -05:00
|
|
|
return {};
|
2021-06-14 19:21:43 -07:00
|
|
|
const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd);
|
2021-12-11 01:01:14 -05:00
|
|
|
return {reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff),
|
|
|
|
|
c->datasize / sizeof(data_in_code_entry)};
|
2021-06-14 19:21:43 -07:00
|
|
|
}
|
|
|
|
|
|
2022-09-05 19:03:15 +02:00
|
|
|
ArrayRef<uint8_t> ObjFile::getOptimizationHints() const {
|
|
|
|
|
const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
|
|
|
|
|
if (auto *cmd =
|
|
|
|
|
findCommand<linkedit_data_command>(buf, LC_LINKER_OPTIMIZATION_HINT))
|
|
|
|
|
return {buf + cmd->dataoff, cmd->datasize};
|
|
|
|
|
return {};
|
|
|
|
|
}
|
|
|
|
|
|
[lld-macho] Associate compact unwind entries with function symbols
Compact unwind entries (CUEs) contain pointers to their respective
function symbols. However, during the link process, it's far more useful
to have pointers from the function symbol to the CUE than vice versa.
This diff adds that pointer in the form of `Defined::compactUnwind`.
In particular, when doing dead-stripping, we want to mark CUEs live when
their function symbol is live; and when doing ICF, we want to dedup
sections iff the symbols in that section have identical CUEs. In both
cases, we want to be able to locate the symbols within a given section,
as well as locate the CUEs belonging to those symbols. So this diff also
adds `InputSection::symbols`.
The ultimate goal of this refactor is to have ICF support dedup'ing
functions with unwind info, but that will be handled in subsequent
diffs. This diff focuses on simplifying `-dead_strip` --
`findFunctionsWithUnwindInfo` is no longer necessary, and
`Defined::isLive()` is now a lot simpler. Moreover, UnwindInfoSection no
longer has to check for dead CUEs -- we simply avoid adding them in the
first place.
Additionally, we now support stripping of dead LSDAs, which follows
quite naturally since `markLive()` can now reach them via the CUEs.
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D109944
2021-10-26 16:04:04 -04:00
|
|
|
// Create pointers from symbols to their associated compact unwind entries.
|
2022-04-22 15:34:50 -04:00
|
|
|
void ObjFile::registerCompactUnwind(Section &compactUnwindSection) {
|
|
|
|
|
for (const Subsection &subsection : compactUnwindSection.subsections) {
|
2021-11-04 20:55:31 -07:00
|
|
|
ConcatInputSection *isec = cast<ConcatInputSection>(subsection.isec);
|
2022-07-19 13:18:54 -04:00
|
|
|
// Hack!! Each compact unwind entry (CUE) has its UNSIGNED relocations embed
|
|
|
|
|
// their addends in its data. Thus if ICF operated naively and compared the
|
|
|
|
|
// entire contents of each CUE, entries with identical unwind info but e.g.
|
|
|
|
|
// belonging to different functions would never be considered equivalent. To
|
|
|
|
|
// work around this problem, we remove some parts of the data containing the
|
|
|
|
|
// embedded addends. In particular, we remove the function address and LSDA
|
|
|
|
|
// pointers. Since these locations are at the start and end of the entry,
|
|
|
|
|
// we can do this using a simple, efficient slice rather than performing a
|
|
|
|
|
// copy. We are not losing any information here because the embedded
|
|
|
|
|
// addends have already been parsed in the corresponding Reloc structs.
|
|
|
|
|
//
|
|
|
|
|
// Removing these pointers would not be safe if they were pointers to
|
|
|
|
|
// absolute symbols. In that case, there would be no corresponding
|
|
|
|
|
// relocation. However, (AFAIK) MC cannot emit references to absolute
|
|
|
|
|
// symbols for either the function address or the LSDA. However, it *can* do
|
|
|
|
|
// so for the personality pointer, so we are not slicing that field away.
|
|
|
|
|
//
|
|
|
|
|
// Note that we do not adjust the offsets of the corresponding relocations;
|
|
|
|
|
// instead, we rely on `relocateCompactUnwind()` to correctly handle these
|
|
|
|
|
// truncated input sections.
|
|
|
|
|
isec->data = isec->data.slice(target->wordSize, 8 + target->wordSize);
|
2022-06-12 21:56:45 -04:00
|
|
|
uint32_t encoding = read32le(isec->data.data() + sizeof(uint32_t));
|
|
|
|
|
// llvm-mc omits CU entries for functions that need DWARF encoding, but
|
|
|
|
|
// `ld -r` doesn't. We can ignore them because we will re-synthesize these
|
|
|
|
|
// CU entries from the DWARF info during the output phase.
|
2022-10-06 09:08:00 -04:00
|
|
|
if ((encoding & static_cast<uint32_t>(UNWIND_MODE_MASK)) ==
|
|
|
|
|
target->modeDwarfEncoding)
|
2022-06-12 21:56:45 -04:00
|
|
|
continue;
|
2021-11-12 16:01:25 -05:00
|
|
|
|
[lld-macho] Associate compact unwind entries with function symbols
Compact unwind entries (CUEs) contain pointers to their respective
function symbols. However, during the link process, it's far more useful
to have pointers from the function symbol to the CUE than vice versa.
This diff adds that pointer in the form of `Defined::compactUnwind`.
In particular, when doing dead-stripping, we want to mark CUEs live when
their function symbol is live; and when doing ICF, we want to dedup
sections iff the symbols in that section have identical CUEs. In both
cases, we want to be able to locate the symbols within a given section,
as well as locate the CUEs belonging to those symbols. So this diff also
adds `InputSection::symbols`.
The ultimate goal of this refactor is to have ICF support dedup'ing
functions with unwind info, but that will be handled in subsequent
diffs. This diff focuses on simplifying `-dead_strip` --
`findFunctionsWithUnwindInfo` is no longer necessary, and
`Defined::isLive()` is now a lot simpler. Moreover, UnwindInfoSection no
longer has to check for dead CUEs -- we simply avoid adding them in the
first place.
Additionally, we now support stripping of dead LSDAs, which follows
quite naturally since `markLive()` can now reach them via the CUEs.
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D109944
2021-10-26 16:04:04 -04:00
|
|
|
ConcatInputSection *referentIsec;
|
2021-11-12 16:01:25 -05:00
|
|
|
for (auto it = isec->relocs.begin(); it != isec->relocs.end();) {
|
|
|
|
|
Reloc &r = *it;
|
2021-11-15 11:46:59 -07:00
|
|
|
// CUE::functionAddress is at offset 0. Skip personality & LSDA relocs.
|
2021-11-12 16:01:25 -05:00
|
|
|
if (r.offset != 0) {
|
|
|
|
|
++it;
|
[lld-macho] Associate compact unwind entries with function symbols
Compact unwind entries (CUEs) contain pointers to their respective
function symbols. However, during the link process, it's far more useful
to have pointers from the function symbol to the CUE than vice versa.
This diff adds that pointer in the form of `Defined::compactUnwind`.
In particular, when doing dead-stripping, we want to mark CUEs live when
their function symbol is live; and when doing ICF, we want to dedup
sections iff the symbols in that section have identical CUEs. In both
cases, we want to be able to locate the symbols within a given section,
as well as locate the CUEs belonging to those symbols. So this diff also
adds `InputSection::symbols`.
The ultimate goal of this refactor is to have ICF support dedup'ing
functions with unwind info, but that will be handled in subsequent
diffs. This diff focuses on simplifying `-dead_strip` --
`findFunctionsWithUnwindInfo` is no longer necessary, and
`Defined::isLive()` is now a lot simpler. Moreover, UnwindInfoSection no
longer has to check for dead CUEs -- we simply avoid adding them in the
first place.
Additionally, we now support stripping of dead LSDAs, which follows
quite naturally since `markLive()` can now reach them via the CUEs.
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D109944
2021-10-26 16:04:04 -04:00
|
|
|
continue;
|
2021-11-12 16:01:25 -05:00
|
|
|
}
|
[lld-macho] Associate compact unwind entries with function symbols
Compact unwind entries (CUEs) contain pointers to their respective
function symbols. However, during the link process, it's far more useful
to have pointers from the function symbol to the CUE than vice versa.
This diff adds that pointer in the form of `Defined::compactUnwind`.
In particular, when doing dead-stripping, we want to mark CUEs live when
their function symbol is live; and when doing ICF, we want to dedup
sections iff the symbols in that section have identical CUEs. In both
cases, we want to be able to locate the symbols within a given section,
as well as locate the CUEs belonging to those symbols. So this diff also
adds `InputSection::symbols`.
The ultimate goal of this refactor is to have ICF support dedup'ing
functions with unwind info, but that will be handled in subsequent
diffs. This diff focuses on simplifying `-dead_strip` --
`findFunctionsWithUnwindInfo` is no longer necessary, and
`Defined::isLive()` is now a lot simpler. Moreover, UnwindInfoSection no
longer has to check for dead CUEs -- we simply avoid adding them in the
first place.
Additionally, we now support stripping of dead LSDAs, which follows
quite naturally since `markLive()` can now reach them via the CUEs.
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D109944
2021-10-26 16:04:04 -04:00
|
|
|
uint64_t add = r.addend;
|
|
|
|
|
if (auto *sym = cast_or_null<Defined>(r.referent.dyn_cast<Symbol *>())) {
|
2021-11-12 15:00:51 -05:00
|
|
|
// Check whether the symbol defined in this file is the prevailing one.
|
|
|
|
|
// Skip if it is e.g. a weak def that didn't prevail.
|
2021-11-12 16:01:25 -05:00
|
|
|
if (sym->getFile() != this) {
|
|
|
|
|
++it;
|
2021-11-12 15:00:51 -05:00
|
|
|
continue;
|
2021-11-12 16:01:25 -05:00
|
|
|
}
|
[lld-macho] Associate compact unwind entries with function symbols
Compact unwind entries (CUEs) contain pointers to their respective
function symbols. However, during the link process, it's far more useful
to have pointers from the function symbol to the CUE than vice versa.
This diff adds that pointer in the form of `Defined::compactUnwind`.
In particular, when doing dead-stripping, we want to mark CUEs live when
their function symbol is live; and when doing ICF, we want to dedup
sections iff the symbols in that section have identical CUEs. In both
cases, we want to be able to locate the symbols within a given section,
as well as locate the CUEs belonging to those symbols. So this diff also
adds `InputSection::symbols`.
The ultimate goal of this refactor is to have ICF support dedup'ing
functions with unwind info, but that will be handled in subsequent
diffs. This diff focuses on simplifying `-dead_strip` --
`findFunctionsWithUnwindInfo` is no longer necessary, and
`Defined::isLive()` is now a lot simpler. Moreover, UnwindInfoSection no
longer has to check for dead CUEs -- we simply avoid adding them in the
first place.
Additionally, we now support stripping of dead LSDAs, which follows
quite naturally since `markLive()` can now reach them via the CUEs.
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D109944
2021-10-26 16:04:04 -04:00
|
|
|
add += sym->value;
|
2024-04-18 11:42:22 -07:00
|
|
|
referentIsec = cast<ConcatInputSection>(sym->isec());
|
[lld-macho] Associate compact unwind entries with function symbols
Compact unwind entries (CUEs) contain pointers to their respective
function symbols. However, during the link process, it's far more useful
to have pointers from the function symbol to the CUE than vice versa.
This diff adds that pointer in the form of `Defined::compactUnwind`.
In particular, when doing dead-stripping, we want to mark CUEs live when
their function symbol is live; and when doing ICF, we want to dedup
sections iff the symbols in that section have identical CUEs. In both
cases, we want to be able to locate the symbols within a given section,
as well as locate the CUEs belonging to those symbols. So this diff also
adds `InputSection::symbols`.
The ultimate goal of this refactor is to have ICF support dedup'ing
functions with unwind info, but that will be handled in subsequent
diffs. This diff focuses on simplifying `-dead_strip` --
`findFunctionsWithUnwindInfo` is no longer necessary, and
`Defined::isLive()` is now a lot simpler. Moreover, UnwindInfoSection no
longer has to check for dead CUEs -- we simply avoid adding them in the
first place.
Additionally, we now support stripping of dead LSDAs, which follows
quite naturally since `markLive()` can now reach them via the CUEs.
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D109944
2021-10-26 16:04:04 -04:00
|
|
|
} else {
|
|
|
|
|
referentIsec =
|
|
|
|
|
cast<ConcatInputSection>(r.referent.dyn_cast<InputSection *>());
|
|
|
|
|
}
|
2022-04-08 22:33:00 -04:00
|
|
|
// Unwind info lives in __DATA, and finalization of __TEXT will occur
|
|
|
|
|
// before finalization of __DATA. Moreover, the finalization of unwind
|
|
|
|
|
// info depends on the exact addresses that it references. So it is safe
|
|
|
|
|
// for compact unwind to reference addresses in __TEXT, but not addresses
|
|
|
|
|
// in any other segment.
|
2021-10-26 18:40:20 -04:00
|
|
|
if (referentIsec->getSegName() != segment_names::text)
|
2022-02-07 21:06:02 -05:00
|
|
|
error(isec->getLocation(r.offset) + " references section " +
|
|
|
|
|
referentIsec->getName() + " which is not in segment __TEXT");
|
[lld-macho] Associate compact unwind entries with function symbols
Compact unwind entries (CUEs) contain pointers to their respective
function symbols. However, during the link process, it's far more useful
to have pointers from the function symbol to the CUE than vice versa.
This diff adds that pointer in the form of `Defined::compactUnwind`.
In particular, when doing dead-stripping, we want to mark CUEs live when
their function symbol is live; and when doing ICF, we want to dedup
sections iff the symbols in that section have identical CUEs. In both
cases, we want to be able to locate the symbols within a given section,
as well as locate the CUEs belonging to those symbols. So this diff also
adds `InputSection::symbols`.
The ultimate goal of this refactor is to have ICF support dedup'ing
functions with unwind info, but that will be handled in subsequent
diffs. This diff focuses on simplifying `-dead_strip` --
`findFunctionsWithUnwindInfo` is no longer necessary, and
`Defined::isLive()` is now a lot simpler. Moreover, UnwindInfoSection no
longer has to check for dead CUEs -- we simply avoid adding them in the
first place.
Additionally, we now support stripping of dead LSDAs, which follows
quite naturally since `markLive()` can now reach them via the CUEs.
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D109944
2021-10-26 16:04:04 -04:00
|
|
|
// The functionAddress relocations are typically section relocations.
|
|
|
|
|
// However, unwind info operates on a per-symbol basis, so we search for
|
|
|
|
|
// the function symbol here.
|
2022-04-07 09:05:33 -04:00
|
|
|
Defined *d = findSymbolAtOffset(referentIsec, add);
|
|
|
|
|
if (!d) {
|
2021-11-12 16:01:25 -05:00
|
|
|
++it;
|
[lld-macho] Associate compact unwind entries with function symbols
Compact unwind entries (CUEs) contain pointers to their respective
function symbols. However, during the link process, it's far more useful
to have pointers from the function symbol to the CUE than vice versa.
This diff adds that pointer in the form of `Defined::compactUnwind`.
In particular, when doing dead-stripping, we want to mark CUEs live when
their function symbol is live; and when doing ICF, we want to dedup
sections iff the symbols in that section have identical CUEs. In both
cases, we want to be able to locate the symbols within a given section,
as well as locate the CUEs belonging to those symbols. So this diff also
adds `InputSection::symbols`.
The ultimate goal of this refactor is to have ICF support dedup'ing
functions with unwind info, but that will be handled in subsequent
diffs. This diff focuses on simplifying `-dead_strip` --
`findFunctionsWithUnwindInfo` is no longer necessary, and
`Defined::isLive()` is now a lot simpler. Moreover, UnwindInfoSection no
longer has to check for dead CUEs -- we simply avoid adding them in the
first place.
Additionally, we now support stripping of dead LSDAs, which follows
quite naturally since `markLive()` can now reach them via the CUEs.
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D109944
2021-10-26 16:04:04 -04:00
|
|
|
continue;
|
|
|
|
|
}
|
2024-04-18 11:42:22 -07:00
|
|
|
d->originalUnwindEntry = isec;
|
2022-07-15 23:38:48 -04:00
|
|
|
// Now that the symbol points to the unwind entry, we can remove the reloc
|
|
|
|
|
// that points from the unwind entry back to the symbol.
|
|
|
|
|
//
|
|
|
|
|
// First, the symbol keeps the unwind entry alive (and not vice versa), so
|
|
|
|
|
// this keeps dead-stripping simple.
|
|
|
|
|
//
|
|
|
|
|
// Moreover, it reduces the work that ICF needs to do to figure out if
|
|
|
|
|
// functions with unwind info are foldable.
|
|
|
|
|
//
|
|
|
|
|
// However, this does make it possible for ICF to fold CUEs that point to
|
|
|
|
|
// distinct functions (if the CUEs are otherwise identical).
|
|
|
|
|
// UnwindInfoSection takes care of this by re-duplicating the CUEs so that
|
|
|
|
|
// each one can hold a distinct functionAddress value.
|
|
|
|
|
//
|
|
|
|
|
// Given that clang emits relocations in reverse order of address, this
|
|
|
|
|
// relocation should be at the end of the vector for most of our input
|
|
|
|
|
// object files, so this erase() is typically an O(1) operation.
|
2021-11-12 16:01:25 -05:00
|
|
|
it = isec->relocs.erase(it);
|
[lld-macho] Associate compact unwind entries with function symbols
Compact unwind entries (CUEs) contain pointers to their respective
function symbols. However, during the link process, it's far more useful
to have pointers from the function symbol to the CUE than vice versa.
This diff adds that pointer in the form of `Defined::compactUnwind`.
In particular, when doing dead-stripping, we want to mark CUEs live when
their function symbol is live; and when doing ICF, we want to dedup
sections iff the symbols in that section have identical CUEs. In both
cases, we want to be able to locate the symbols within a given section,
as well as locate the CUEs belonging to those symbols. So this diff also
adds `InputSection::symbols`.
The ultimate goal of this refactor is to have ICF support dedup'ing
functions with unwind info, but that will be handled in subsequent
diffs. This diff focuses on simplifying `-dead_strip` --
`findFunctionsWithUnwindInfo` is no longer necessary, and
`Defined::isLive()` is now a lot simpler. Moreover, UnwindInfoSection no
longer has to check for dead CUEs -- we simply avoid adding them in the
first place.
Additionally, we now support stripping of dead LSDAs, which follows
quite naturally since `markLive()` can now reach them via the CUEs.
Reviewed By: #lld-macho, gkm
Differential Revision: https://reviews.llvm.org/D109944
2021-10-26 16:04:04 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-06-12 21:56:45 -04:00
|
|
|
struct CIE {
|
|
|
|
|
macho::Symbol *personalitySymbol = nullptr;
|
|
|
|
|
bool fdesHaveAug = false;
|
2022-07-31 20:16:08 -04:00
|
|
|
uint8_t lsdaPtrSize = 0; // 0 => no LSDA
|
|
|
|
|
uint8_t funcPtrSize = 0;
|
2022-06-12 21:56:45 -04:00
|
|
|
};
|
|
|
|
|
|
2022-07-31 20:16:08 -04:00
|
|
|
static uint8_t pointerEncodingToSize(uint8_t enc) {
|
|
|
|
|
switch (enc & 0xf) {
|
|
|
|
|
case dwarf::DW_EH_PE_absptr:
|
|
|
|
|
return target->wordSize;
|
|
|
|
|
case dwarf::DW_EH_PE_sdata4:
|
|
|
|
|
return 4;
|
|
|
|
|
case dwarf::DW_EH_PE_sdata8:
|
|
|
|
|
// ld64 doesn't actually support sdata8, but this seems simple enough...
|
|
|
|
|
return 8;
|
|
|
|
|
default:
|
|
|
|
|
return 0;
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2022-06-12 21:56:45 -04:00
|
|
|
static CIE parseCIE(const InputSection *isec, const EhReader &reader,
|
|
|
|
|
size_t off) {
|
|
|
|
|
// Handling the full generality of possible DWARF encodings would be a major
|
|
|
|
|
// pain. We instead take advantage of our knowledge of how llvm-mc encodes
|
|
|
|
|
// DWARF and handle just that.
|
|
|
|
|
constexpr uint8_t expectedPersonalityEnc =
|
|
|
|
|
dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_sdata4;
|
|
|
|
|
|
|
|
|
|
CIE cie;
|
|
|
|
|
uint8_t version = reader.readByte(&off);
|
|
|
|
|
if (version != 1 && version != 3)
|
|
|
|
|
fatal("Expected CIE version of 1 or 3, got " + Twine(version));
|
|
|
|
|
StringRef aug = reader.readString(&off);
|
|
|
|
|
reader.skipLeb128(&off); // skip code alignment
|
|
|
|
|
reader.skipLeb128(&off); // skip data alignment
|
|
|
|
|
reader.skipLeb128(&off); // skip return address register
|
|
|
|
|
reader.skipLeb128(&off); // skip aug data length
|
|
|
|
|
uint64_t personalityAddrOff = 0;
|
|
|
|
|
for (char c : aug) {
|
|
|
|
|
switch (c) {
|
|
|
|
|
case 'z':
|
|
|
|
|
cie.fdesHaveAug = true;
|
|
|
|
|
break;
|
|
|
|
|
case 'P': {
|
|
|
|
|
uint8_t personalityEnc = reader.readByte(&off);
|
|
|
|
|
if (personalityEnc != expectedPersonalityEnc)
|
|
|
|
|
reader.failOn(off, "unexpected personality encoding 0x" +
|
|
|
|
|
Twine::utohexstr(personalityEnc));
|
|
|
|
|
personalityAddrOff = off;
|
|
|
|
|
off += 4;
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
case 'L': {
|
|
|
|
|
uint8_t lsdaEnc = reader.readByte(&off);
|
2022-07-31 20:16:08 -04:00
|
|
|
cie.lsdaPtrSize = pointerEncodingToSize(lsdaEnc);
|
|
|
|
|
if (cie.lsdaPtrSize == 0)
|
2022-06-12 21:56:45 -04:00
|
|
|
reader.failOn(off, "unexpected LSDA encoding 0x" +
|
|
|
|
|
Twine::utohexstr(lsdaEnc));
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
case 'R': {
|
|
|
|
|
uint8_t pointerEnc = reader.readByte(&off);
|
2022-07-31 20:16:08 -04:00
|
|
|
cie.funcPtrSize = pointerEncodingToSize(pointerEnc);
|
|
|
|
|
if (cie.funcPtrSize == 0 || !(pointerEnc & dwarf::DW_EH_PE_pcrel))
|
2022-06-12 21:56:45 -04:00
|
|
|
reader.failOn(off, "unexpected pointer encoding 0x" +
|
|
|
|
|
Twine::utohexstr(pointerEnc));
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
default:
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if (personalityAddrOff != 0) {
|
2023-02-16 16:18:46 -05:00
|
|
|
const auto *personalityReloc = isec->getRelocAt(personalityAddrOff);
|
|
|
|
|
if (!personalityReloc)
|
2022-06-12 21:56:45 -04:00
|
|
|
reader.failOn(off, "Failed to locate relocation for personality symbol");
|
2024-12-14 20:07:08 -08:00
|
|
|
cie.personalitySymbol = cast<macho::Symbol *>(personalityReloc->referent);
|
2022-06-12 21:56:45 -04:00
|
|
|
}
|
|
|
|
|
return cie;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// EH frame target addresses may be encoded as pcrel offsets. However, instead
|
|
|
|
|
// of using an actual pcrel reloc, ld64 emits subtractor relocations instead.
|
|
|
|
|
// This function recovers the target address from the subtractors, essentially
|
|
|
|
|
// performing the inverse operation of EhRelocator.
|
|
|
|
|
//
|
|
|
|
|
// Concretely, we expect our relocations to write the value of `PC -
|
|
|
|
|
// target_addr` to `PC`. `PC` itself is denoted by a minuend relocation that
|
2022-06-13 07:32:49 -04:00
|
|
|
// points to a symbol plus an addend.
|
|
|
|
|
//
|
|
|
|
|
// It is important that the minuend relocation point to a symbol within the
|
|
|
|
|
// same section as the fixup value, since sections may get moved around.
|
|
|
|
|
//
|
|
|
|
|
// For example, for arm64, llvm-mc emits relocations for the target function
|
|
|
|
|
// address like so:
|
|
|
|
|
//
|
|
|
|
|
// ltmp:
|
|
|
|
|
// <CIE start>
|
|
|
|
|
// ...
|
|
|
|
|
// <CIE end>
|
|
|
|
|
// ... multiple FDEs ...
|
|
|
|
|
// <FDE start>
|
|
|
|
|
// <target function address - (ltmp + pcrel offset)>
|
|
|
|
|
// ...
|
|
|
|
|
//
|
|
|
|
|
// If any of the FDEs in `multiple FDEs` get dead-stripped, then `FDE start`
|
|
|
|
|
// will move to an earlier address, and `ltmp + pcrel offset` will no longer
|
|
|
|
|
// reflect an accurate pcrel value. To avoid this problem, we "canonicalize"
|
|
|
|
|
// our relocation by adding an `EH_Frame` symbol at `FDE start`, and updating
|
|
|
|
|
// the reloc to be `target function address - (EH_Frame + new pcrel offset)`.
|
2022-06-12 21:56:45 -04:00
|
|
|
//
|
|
|
|
|
// If `Invert` is set, then we instead expect `target_addr - PC` to be written
|
|
|
|
|
// to `PC`.
|
|
|
|
|
template <bool Invert = false>
|
|
|
|
|
Defined *
|
2022-06-13 07:32:49 -04:00
|
|
|
targetSymFromCanonicalSubtractor(const InputSection *isec,
|
|
|
|
|
std::vector<macho::Reloc>::iterator relocIt) {
|
|
|
|
|
macho::Reloc &subtrahend = *relocIt;
|
|
|
|
|
macho::Reloc &minuend = *std::next(relocIt);
|
2022-06-12 21:56:45 -04:00
|
|
|
assert(target->hasAttr(subtrahend.type, RelocAttrBits::SUBTRAHEND));
|
|
|
|
|
assert(target->hasAttr(minuend.type, RelocAttrBits::UNSIGNED));
|
|
|
|
|
// Note: pcSym may *not* be exactly at the PC; there's usually a non-zero
|
|
|
|
|
// addend.
|
2024-12-14 20:07:08 -08:00
|
|
|
auto *pcSym = cast<Defined>(cast<macho::Symbol *>(subtrahend.referent));
|
2022-06-12 21:56:45 -04:00
|
|
|
Defined *target =
|
|
|
|
|
cast_or_null<Defined>(minuend.referent.dyn_cast<macho::Symbol *>());
|
|
|
|
|
if (!pcSym) {
|
|
|
|
|
auto *targetIsec =
|
2024-12-14 20:07:08 -08:00
|
|
|
cast<ConcatInputSection>(cast<InputSection *>(minuend.referent));
|
2022-06-12 21:56:45 -04:00
|
|
|
target = findSymbolAtOffset(targetIsec, minuend.addend);
|
|
|
|
|
}
|
|
|
|
|
if (Invert)
|
|
|
|
|
std::swap(pcSym, target);
|
2024-04-18 11:42:22 -07:00
|
|
|
if (pcSym->isec() == isec) {
|
2022-06-13 07:32:49 -04:00
|
|
|
if (pcSym->value - (Invert ? -1 : 1) * minuend.addend != subtrahend.offset)
|
|
|
|
|
fatal("invalid FDE relocation in __eh_frame");
|
|
|
|
|
} else {
|
|
|
|
|
// Ensure the pcReloc points to a symbol within the current EH frame.
|
|
|
|
|
// HACK: we should really verify that the original relocation's semantics
|
|
|
|
|
// are preserved. In particular, we should have
|
|
|
|
|
// `oldSym->value + oldOffset == newSym + newOffset`. However, we don't
|
|
|
|
|
// have an easy way to access the offsets from this point in the code; some
|
|
|
|
|
// refactoring is needed for that.
|
|
|
|
|
macho::Reloc &pcReloc = Invert ? minuend : subtrahend;
|
|
|
|
|
pcReloc.referent = isec->symbols[0];
|
|
|
|
|
assert(isec->symbols[0]->value == 0);
|
|
|
|
|
minuend.addend = pcReloc.offset * (Invert ? 1LL : -1LL);
|
|
|
|
|
}
|
2022-06-12 21:56:45 -04:00
|
|
|
return target;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Defined *findSymbolAtAddress(const std::vector<Section *> §ions,
|
|
|
|
|
uint64_t addr) {
|
|
|
|
|
Section *sec = findContainingSection(sections, &addr);
|
|
|
|
|
auto *isec = cast<ConcatInputSection>(findContainingSubsection(*sec, &addr));
|
|
|
|
|
return findSymbolAtOffset(isec, addr);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// For symbols that don't have compact unwind info, associate them with the more
|
|
|
|
|
// general-purpose (and verbose) DWARF unwind info found in __eh_frame.
|
|
|
|
|
//
|
|
|
|
|
// This requires us to parse the contents of __eh_frame. See EhFrame.h for a
|
|
|
|
|
// description of its format.
|
|
|
|
|
//
|
|
|
|
|
// While parsing, we also look for what MC calls "abs-ified" relocations -- they
|
|
|
|
|
// are relocations which are implicitly encoded as offsets in the section data.
|
|
|
|
|
// We convert them into explicit Reloc structs so that the EH frames can be
|
|
|
|
|
// handled just like a regular ConcatInputSection later in our output phase.
|
|
|
|
|
//
|
|
|
|
|
// We also need to handle the case where our input object file has explicit
|
|
|
|
|
// relocations. This is the case when e.g. it's the output of `ld -r`. We only
|
|
|
|
|
// look for the "abs-ified" relocation if an explicit relocation is absent.
|
|
|
|
|
void ObjFile::registerEhFrames(Section &ehFrameSection) {
|
|
|
|
|
DenseMap<const InputSection *, CIE> cieMap;
|
|
|
|
|
for (const Subsection &subsec : ehFrameSection.subsections) {
|
|
|
|
|
auto *isec = cast<ConcatInputSection>(subsec.isec);
|
|
|
|
|
uint64_t isecOff = subsec.offset;
|
|
|
|
|
|
|
|
|
|
// Subtractor relocs require the subtrahend to be a symbol reloc. Ensure
|
|
|
|
|
// that all EH frames have an associated symbol so that we can generate
|
|
|
|
|
// subtractor relocs that reference them.
|
|
|
|
|
if (isec->symbols.size() == 0)
|
2022-12-01 01:21:04 -05:00
|
|
|
make<Defined>("EH_Frame", isec->getFile(), isec, /*value=*/0,
|
|
|
|
|
isec->getSize(), /*isWeakDef=*/false, /*isExternal=*/false,
|
|
|
|
|
/*isPrivateExtern=*/false, /*includeInSymtab=*/false,
|
2023-05-15 02:00:29 -07:00
|
|
|
/*isReferencedDynamically=*/false,
|
2022-12-01 01:21:04 -05:00
|
|
|
/*noDeadStrip=*/false);
|
2022-06-12 21:56:45 -04:00
|
|
|
else if (isec->symbols[0]->value != 0)
|
|
|
|
|
fatal("found symbol at unexpected offset in __eh_frame");
|
|
|
|
|
|
2022-07-31 20:16:08 -04:00
|
|
|
EhReader reader(this, isec->data, subsec.offset);
|
2022-06-12 21:56:45 -04:00
|
|
|
size_t dataOff = 0; // Offset from the start of the EH frame.
|
|
|
|
|
reader.skipValidLength(&dataOff); // readLength() already validated this.
|
|
|
|
|
// cieOffOff is the offset from the start of the EH frame to the cieOff
|
|
|
|
|
// value, which is itself an offset from the current PC to a CIE.
|
|
|
|
|
const size_t cieOffOff = dataOff;
|
|
|
|
|
|
|
|
|
|
EhRelocator ehRelocator(isec);
|
|
|
|
|
auto cieOffRelocIt = llvm::find_if(
|
|
|
|
|
isec->relocs, [=](const Reloc &r) { return r.offset == cieOffOff; });
|
|
|
|
|
InputSection *cieIsec = nullptr;
|
|
|
|
|
if (cieOffRelocIt != isec->relocs.end()) {
|
|
|
|
|
// We already have an explicit relocation for the CIE offset.
|
|
|
|
|
cieIsec =
|
2022-06-13 07:32:49 -04:00
|
|
|
targetSymFromCanonicalSubtractor</*Invert=*/true>(isec, cieOffRelocIt)
|
2024-04-18 11:42:22 -07:00
|
|
|
->isec();
|
2022-06-12 21:56:45 -04:00
|
|
|
dataOff += sizeof(uint32_t);
|
|
|
|
|
} else {
|
|
|
|
|
// If we haven't found a relocation, then the CIE offset is most likely
|
|
|
|
|
// embedded in the section data (AKA an "abs-ified" reloc.). Parse that
|
|
|
|
|
// and generate a Reloc struct.
|
|
|
|
|
uint32_t cieMinuend = reader.readU32(&dataOff);
|
2022-08-22 21:58:46 +03:00
|
|
|
if (cieMinuend == 0) {
|
2022-06-12 21:56:45 -04:00
|
|
|
cieIsec = isec;
|
2022-08-22 21:58:46 +03:00
|
|
|
} else {
|
2022-06-12 21:56:45 -04:00
|
|
|
uint32_t cieOff = isecOff + dataOff - cieMinuend;
|
|
|
|
|
cieIsec = findContainingSubsection(ehFrameSection, &cieOff);
|
|
|
|
|
if (cieIsec == nullptr)
|
|
|
|
|
fatal("failed to find CIE");
|
|
|
|
|
}
|
|
|
|
|
if (cieIsec != isec)
|
|
|
|
|
ehRelocator.makeNegativePcRel(cieOffOff, cieIsec->symbols[0],
|
|
|
|
|
/*length=*/2);
|
|
|
|
|
}
|
|
|
|
|
if (cieIsec == isec) {
|
|
|
|
|
cieMap[cieIsec] = parseCIE(isec, reader, dataOff);
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
2022-07-31 20:16:08 -04:00
|
|
|
assert(cieMap.count(cieIsec));
|
|
|
|
|
const CIE &cie = cieMap[cieIsec];
|
2022-06-12 21:56:45 -04:00
|
|
|
// Offset of the function address within the EH frame.
|
|
|
|
|
const size_t funcAddrOff = dataOff;
|
2022-07-31 20:16:08 -04:00
|
|
|
uint64_t funcAddr = reader.readPointer(&dataOff, cie.funcPtrSize) +
|
|
|
|
|
ehFrameSection.addr + isecOff + funcAddrOff;
|
|
|
|
|
uint32_t funcLength = reader.readPointer(&dataOff, cie.funcPtrSize);
|
2022-06-12 21:56:45 -04:00
|
|
|
size_t lsdaAddrOff = 0; // Offset of the LSDA address within the EH frame.
|
2022-11-26 21:02:09 -08:00
|
|
|
std::optional<uint64_t> lsdaAddrOpt;
|
2022-06-12 21:56:45 -04:00
|
|
|
if (cie.fdesHaveAug) {
|
|
|
|
|
reader.skipLeb128(&dataOff);
|
|
|
|
|
lsdaAddrOff = dataOff;
|
2022-07-31 20:16:08 -04:00
|
|
|
if (cie.lsdaPtrSize != 0) {
|
|
|
|
|
uint64_t lsdaOff = reader.readPointer(&dataOff, cie.lsdaPtrSize);
|
2022-06-12 21:56:45 -04:00
|
|
|
if (lsdaOff != 0) // FIXME possible to test this?
|
|
|
|
|
lsdaAddrOpt = ehFrameSection.addr + isecOff + lsdaAddrOff + lsdaOff;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
auto funcAddrRelocIt = isec->relocs.end();
|
|
|
|
|
auto lsdaAddrRelocIt = isec->relocs.end();
|
|
|
|
|
for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) {
|
|
|
|
|
if (it->offset == funcAddrOff)
|
|
|
|
|
funcAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc
|
|
|
|
|
else if (lsdaAddrOpt && it->offset == lsdaAddrOff)
|
|
|
|
|
lsdaAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Defined *funcSym;
|
|
|
|
|
if (funcAddrRelocIt != isec->relocs.end()) {
|
2022-06-13 07:32:49 -04:00
|
|
|
funcSym = targetSymFromCanonicalSubtractor(isec, funcAddrRelocIt);
|
2022-07-21 09:44:01 -04:00
|
|
|
// Canonicalize the symbol. If there are multiple symbols at the same
|
|
|
|
|
// address, we want both `registerEhFrame` and `registerCompactUnwind`
|
|
|
|
|
// to register the unwind entry under same symbol.
|
|
|
|
|
// This is not particularly efficient, but we should run into this case
|
|
|
|
|
// infrequently (only when handling the output of `ld -r`).
|
2024-04-18 11:42:22 -07:00
|
|
|
if (funcSym->isec())
|
|
|
|
|
funcSym = findSymbolAtOffset(cast<ConcatInputSection>(funcSym->isec()),
|
2022-07-23 11:47:44 -04:00
|
|
|
funcSym->value);
|
2022-06-12 21:56:45 -04:00
|
|
|
} else {
|
|
|
|
|
funcSym = findSymbolAtAddress(sections, funcAddr);
|
|
|
|
|
ehRelocator.makePcRel(funcAddrOff, funcSym, target->p2WordSize);
|
|
|
|
|
}
|
|
|
|
|
// The symbol has been coalesced, or already has a compact unwind entry.
|
2024-04-18 11:42:22 -07:00
|
|
|
if (!funcSym || funcSym->getFile() != this || funcSym->unwindEntry()) {
|
2022-06-12 21:56:45 -04:00
|
|
|
// We must prune unused FDEs for correctness, so we cannot rely on
|
|
|
|
|
// -dead_strip being enabled.
|
|
|
|
|
isec->live = false;
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
InputSection *lsdaIsec = nullptr;
|
|
|
|
|
if (lsdaAddrRelocIt != isec->relocs.end()) {
|
2024-04-18 11:42:22 -07:00
|
|
|
lsdaIsec =
|
|
|
|
|
targetSymFromCanonicalSubtractor(isec, lsdaAddrRelocIt)->isec();
|
2022-06-12 21:56:45 -04:00
|
|
|
} else if (lsdaAddrOpt) {
|
|
|
|
|
uint64_t lsdaAddr = *lsdaAddrOpt;
|
|
|
|
|
Section *sec = findContainingSection(sections, &lsdaAddr);
|
|
|
|
|
lsdaIsec =
|
|
|
|
|
cast<ConcatInputSection>(findContainingSubsection(*sec, &lsdaAddr));
|
|
|
|
|
ehRelocator.makePcRel(lsdaAddrOff, lsdaIsec, target->p2WordSize);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fdes[isec] = {funcLength, cie.personalitySymbol, lsdaIsec};
|
2024-04-18 11:42:22 -07:00
|
|
|
funcSym->originalUnwindEntry = isec;
|
2022-06-12 21:56:45 -04:00
|
|
|
ehRelocator.commit();
|
|
|
|
|
}
|
2022-08-22 22:55:41 +03:00
|
|
|
|
|
|
|
|
// __eh_frame is marked as S_ATTR_LIVE_SUPPORT in input files, because FDEs
|
|
|
|
|
// are normally required to be kept alive if they reference a live symbol.
|
|
|
|
|
// However, we've explicitly created a dependency from a symbol to its FDE, so
|
|
|
|
|
// dead-stripping will just work as usual, and S_ATTR_LIVE_SUPPORT will only
|
|
|
|
|
// serve to incorrectly prevent us from dead-stripping duplicate FDEs for a
|
|
|
|
|
// live symbol (e.g. if there were multiple weak copies). Remove this flag to
|
|
|
|
|
// let dead-stripping proceed correctly.
|
|
|
|
|
ehFrameSection.flags &= ~S_ATTR_LIVE_SUPPORT;
|
2022-06-12 21:56:45 -04:00
|
|
|
}
|
|
|
|
|
|
2022-06-21 16:40:27 -04:00
|
|
|
std::string ObjFile::sourceFile() const {
|
2023-11-08 15:55:22 -08:00
|
|
|
const char *unitName = compileUnit->getUnitDIE().getShortName();
|
|
|
|
|
// DWARF allows DW_AT_name to be absolute, in which case nothing should be
|
|
|
|
|
// prepended. As for the styles, debug info can contain paths from any OS, not
|
|
|
|
|
// necessarily an OS we're currently running on. Moreover different
|
|
|
|
|
// compilation units can be compiled on different operating systems and linked
|
|
|
|
|
// together later.
|
|
|
|
|
if (sys::path::is_absolute(unitName, llvm::sys::path::Style::posix) ||
|
|
|
|
|
sys::path::is_absolute(unitName, llvm::sys::path::Style::windows))
|
|
|
|
|
return unitName;
|
2022-06-21 16:40:27 -04:00
|
|
|
SmallString<261> dir(compileUnit->getCompilationDir());
|
|
|
|
|
StringRef sep = sys::path::get_separator();
|
|
|
|
|
// We don't use `path::append` here because we want an empty `dir` to result
|
|
|
|
|
// in an absolute path. `append` would give us a relative path for that case.
|
2023-12-09 14:28:45 -08:00
|
|
|
if (!dir.ends_with(sep))
|
2022-06-21 16:40:27 -04:00
|
|
|
dir += sep;
|
2023-11-08 15:55:22 -08:00
|
|
|
return (dir + unitName).str();
|
2022-06-21 16:40:27 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
lld::DWARFCache *ObjFile::getDwarf() {
|
|
|
|
|
llvm::call_once(initDwarf, [this]() {
|
|
|
|
|
auto dwObj = DwarfObject::create(this);
|
|
|
|
|
if (!dwObj)
|
|
|
|
|
return;
|
|
|
|
|
dwarfCache = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>(
|
|
|
|
|
std::move(dwObj), "",
|
|
|
|
|
[&](Error err) { warn(getName() + ": " + toString(std::move(err))); },
|
|
|
|
|
[&](Error warning) {
|
|
|
|
|
warn(getName() + ": " + toString(std::move(warning)));
|
|
|
|
|
}));
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return dwarfCache.get();
|
|
|
|
|
}
|
2020-08-13 13:48:47 -07:00
|
|
|
// The path can point to either a dylib or a .tbd file.
|
2021-06-01 16:09:41 -04:00
|
|
|
static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) {
|
2022-11-27 16:54:07 -08:00
|
|
|
std::optional<MemoryBufferRef> mbref = readFile(path);
|
2020-08-13 13:48:47 -07:00
|
|
|
if (!mbref) {
|
|
|
|
|
error("could not read dylib file at " + path);
|
2021-06-01 16:09:41 -04:00
|
|
|
return nullptr;
|
2020-08-13 13:48:47 -07:00
|
|
|
}
|
2020-12-09 22:29:28 -08:00
|
|
|
return loadDylib(*mbref, umbrella);
|
2020-08-13 13:48:47 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
|
|
|
|
|
// the first document storing child pointers to the rest of them. When we are
|
[lld-macho] Change loadReexport to handle the case where a TAPI re-exports to reference documents nested within other TBD.
Currently, it was delibrately impleneted to not handle this case, but as it has turnt out, we need this feature.
The concrete use case is
`System/Library/Frameworks/Cocoa.framework/Versions/A/Cocoa` reexports
/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit , which then rexports
/System/Library/PrivateFrameworks/UIFoundation.framework/Versions/A/UIFoundation
The current implemention uses a global currentTopLevelTapi, which is not reset until it finishes loading the whole tree.
This is a problem because if the top-level is set to Cocoa, then when we get to UIFoundation, it will try to find UIFoundation in the current top level, which is Cocoa and will not find it.
The right thing should be:
- When loading a library from a TBD file, re-exports need to be looked up in the auxiliary documents within the same TBD.
- When loading from an actual dylib, no additional TBD documents need to be examined.
- In no case does a re-export mentioned in one TBD file need to be looked up in a document in an auxiliary document from a different TBD file
Differential Revision: https://reviews.llvm.org/D97438
2021-02-24 23:47:22 -05:00
|
|
|
// processing a given TBD file, we store that top-level document in
|
|
|
|
|
// currentTopLevelTapi. When processing re-exports, we search its children for
|
|
|
|
|
// potentially matching documents in the same TBD file. Note that the children
|
|
|
|
|
// themselves don't point to further documents, i.e. this is a two-level tree.
|
2020-08-13 13:48:47 -07:00
|
|
|
//
|
|
|
|
|
// Re-exports can either refer to on-disk files, or to documents within .tbd
|
|
|
|
|
// files.
|
2021-06-06 18:12:27 -04:00
|
|
|
static DylibFile *findDylib(StringRef path, DylibFile *umbrella,
|
|
|
|
|
const InterfaceFile *currentTopLevelTapi) {
|
2021-07-26 20:39:24 -04:00
|
|
|
// Search order:
|
|
|
|
|
// 1. Install name basename in -F / -L directories.
|
|
|
|
|
{
|
2025-05-02 09:15:53 -07:00
|
|
|
// Framework names can be in multiple formats:
|
|
|
|
|
// - Foo.framework/Foo
|
|
|
|
|
// - Foo.framework/Versions/A/Foo
|
2021-07-26 20:39:24 -04:00
|
|
|
StringRef stem = path::stem(path);
|
2025-05-02 09:15:53 -07:00
|
|
|
SmallString<128> frameworkName("/");
|
|
|
|
|
frameworkName += stem;
|
|
|
|
|
frameworkName += ".framework/";
|
|
|
|
|
size_t i = path.rfind(frameworkName);
|
|
|
|
|
if (i != StringRef::npos) {
|
|
|
|
|
StringRef frameworkPath = path.substr(i + 1);
|
2021-07-26 20:39:24 -04:00
|
|
|
for (StringRef dir : config->frameworkSearchPaths) {
|
|
|
|
|
SmallString<128> candidate = dir;
|
2025-05-02 09:15:53 -07:00
|
|
|
path::append(candidate, frameworkPath);
|
2022-11-27 16:54:07 -08:00
|
|
|
if (std::optional<StringRef> dylibPath =
|
|
|
|
|
resolveDylibPath(candidate.str()))
|
2021-07-26 20:39:24 -04:00
|
|
|
return loadDylib(*dylibPath, umbrella);
|
|
|
|
|
}
|
2022-11-27 16:54:07 -08:00
|
|
|
} else if (std::optional<StringRef> dylibPath = findPathCombination(
|
2023-05-22 13:28:42 -07:00
|
|
|
stem, config->librarySearchPaths, {".tbd", ".dylib", ".so"}))
|
2021-07-26 20:39:24 -04:00
|
|
|
return loadDylib(*dylibPath, umbrella);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 2. As absolute path.
|
2020-08-13 13:48:47 -07:00
|
|
|
if (path::is_absolute(path, path::Style::posix))
|
|
|
|
|
for (StringRef root : config->systemLibraryRoots)
|
2022-11-27 16:54:07 -08:00
|
|
|
if (std::optional<StringRef> dylibPath =
|
|
|
|
|
resolveDylibPath((root + path).str()))
|
2020-08-13 13:48:47 -07:00
|
|
|
return loadDylib(*dylibPath, umbrella);
|
|
|
|
|
|
2021-07-26 20:39:24 -04:00
|
|
|
// 3. As relative path.
|
|
|
|
|
|
2021-06-06 21:52:23 -04:00
|
|
|
// TODO: Handle -dylib_file
|
|
|
|
|
|
2021-07-26 20:39:24 -04:00
|
|
|
// Replace @executable_path, @loader_path, @rpath prefixes in install name.
|
2021-06-06 16:57:19 -04:00
|
|
|
SmallString<128> newPath;
|
|
|
|
|
if (config->outputType == MH_EXECUTE &&
|
|
|
|
|
path.consume_front("@executable_path/")) {
|
|
|
|
|
// ld64 allows overriding this with the undocumented flag -executable_path.
|
|
|
|
|
// lld doesn't currently implement that flag.
|
2021-07-05 19:46:09 -04:00
|
|
|
// FIXME: Consider using finalOutput instead of outputFile.
|
2021-06-09 16:09:44 -04:00
|
|
|
path::append(newPath, path::parent_path(config->outputFile), path);
|
2021-06-06 16:57:19 -04:00
|
|
|
path = newPath;
|
2021-06-06 18:12:27 -04:00
|
|
|
} else if (path.consume_front("@loader_path/")) {
|
2021-06-09 16:09:44 -04:00
|
|
|
fs::real_path(umbrella->getName(), newPath);
|
|
|
|
|
path::remove_filename(newPath);
|
|
|
|
|
path::append(newPath, path);
|
2021-06-06 18:12:27 -04:00
|
|
|
path = newPath;
|
2023-06-05 14:36:19 -07:00
|
|
|
} else if (path.starts_with("@rpath/")) {
|
2021-06-06 21:52:23 -04:00
|
|
|
for (StringRef rpath : umbrella->rpaths) {
|
|
|
|
|
newPath.clear();
|
2021-06-09 16:09:44 -04:00
|
|
|
if (rpath.consume_front("@loader_path/")) {
|
|
|
|
|
fs::real_path(umbrella->getName(), newPath);
|
|
|
|
|
path::remove_filename(newPath);
|
|
|
|
|
}
|
2021-06-06 21:52:23 -04:00
|
|
|
path::append(newPath, rpath, path.drop_front(strlen("@rpath/")));
|
2022-11-27 16:54:07 -08:00
|
|
|
if (std::optional<StringRef> dylibPath = resolveDylibPath(newPath.str()))
|
2021-06-06 21:52:23 -04:00
|
|
|
return loadDylib(*dylibPath, umbrella);
|
|
|
|
|
}
|
2025-04-28 13:16:07 -04:00
|
|
|
// If not found in umbrella, try the rpaths specified via -rpath too.
|
|
|
|
|
for (StringRef rpath : config->runtimePaths) {
|
|
|
|
|
newPath.clear();
|
|
|
|
|
if (rpath.consume_front("@loader_path/")) {
|
|
|
|
|
fs::real_path(umbrella->getName(), newPath);
|
|
|
|
|
path::remove_filename(newPath);
|
|
|
|
|
}
|
|
|
|
|
path::append(newPath, rpath, path.drop_front(strlen("@rpath/")));
|
|
|
|
|
if (std::optional<StringRef> dylibPath = resolveDylibPath(newPath.str()))
|
|
|
|
|
return loadDylib(*dylibPath, umbrella);
|
|
|
|
|
}
|
2021-06-06 16:57:19 -04:00
|
|
|
}
|
2020-08-13 13:48:47 -07:00
|
|
|
|
2021-07-26 20:39:24 -04:00
|
|
|
// FIXME: Should this be further up?
|
2020-09-23 20:09:49 -07:00
|
|
|
if (currentTopLevelTapi) {
|
2020-08-13 13:48:47 -07:00
|
|
|
for (InterfaceFile &child :
|
|
|
|
|
make_pointee_range(currentTopLevelTapi->documents())) {
|
2021-03-04 14:36:46 -05:00
|
|
|
assert(child.documents().empty());
|
2021-06-02 21:53:44 -04:00
|
|
|
if (path == child.getInstallName()) {
|
2023-04-05 01:48:34 -04:00
|
|
|
auto *file = make<DylibFile>(child, umbrella, /*isBundleLoader=*/false,
|
|
|
|
|
/*explicitlyLinked=*/false);
|
2021-06-02 21:53:44 -04:00
|
|
|
file->parseReexports(child);
|
|
|
|
|
return file;
|
|
|
|
|
}
|
2020-08-13 13:48:47 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-11-27 16:54:07 -08:00
|
|
|
if (std::optional<StringRef> dylibPath = resolveDylibPath(path))
|
2020-08-13 13:48:47 -07:00
|
|
|
return loadDylib(*dylibPath, umbrella);
|
|
|
|
|
|
2021-06-01 16:09:41 -04:00
|
|
|
return nullptr;
|
2020-08-13 13:48:47 -07:00
|
|
|
}
|
|
|
|
|
|
2020-12-09 15:08:05 -08:00
|
|
|
// If a re-exported dylib is public (lives in /usr/lib or
|
|
|
|
|
// /System/Library/Frameworks), then it is considered implicitly linked: we
|
|
|
|
|
// should bind to its symbols directly instead of via the re-exporting umbrella
|
|
|
|
|
// library.
|
|
|
|
|
static bool isImplicitlyLinked(StringRef path) {
|
|
|
|
|
if (!config->implicitDylibs)
|
|
|
|
|
return false;
|
|
|
|
|
|
2020-12-15 00:49:03 -05:00
|
|
|
if (path::parent_path(path) == "/usr/lib")
|
|
|
|
|
return true;
|
|
|
|
|
|
|
|
|
|
// Match /System/Library/Frameworks/$FOO.framework/**/$FOO
|
|
|
|
|
if (path.consume_front("/System/Library/Frameworks/")) {
|
|
|
|
|
StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
|
|
|
|
|
return path::filename(path) == frameworkName;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return false;
|
2020-12-09 15:08:05 -08:00
|
|
|
}
|
|
|
|
|
|
2022-12-23 19:44:56 -05:00
|
|
|
void DylibFile::loadReexport(StringRef path, DylibFile *umbrella,
|
2021-06-06 18:12:27 -04:00
|
|
|
const InterfaceFile *currentTopLevelTapi) {
|
2021-06-01 16:09:41 -04:00
|
|
|
DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi);
|
2025-04-28 13:16:07 -04:00
|
|
|
if (!reexport) {
|
|
|
|
|
// If not found in umbrella, retry since some rpaths might have been
|
|
|
|
|
// defined in "this" dylib (which contains the LC_REEXPORT_DYLIB cmd) and
|
|
|
|
|
// not in the umbrella.
|
|
|
|
|
DylibFile *reexport2 = findDylib(path, this, currentTopLevelTapi);
|
|
|
|
|
if (!reexport2) {
|
|
|
|
|
error(toString(this) + ": unable to locate re-export with install name " +
|
|
|
|
|
path);
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-12-09 15:08:05 -08:00
|
|
|
}
|
|
|
|
|
|
2021-02-22 13:03:02 -05:00
|
|
|
DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
|
2022-04-22 11:55:50 -04:00
|
|
|
bool isBundleLoader, bool explicitlyLinked)
|
2021-02-22 13:03:02 -05:00
|
|
|
: InputFile(DylibKind, mb), refState(RefState::Unreferenced),
|
2022-04-22 11:55:50 -04:00
|
|
|
explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {
|
2021-02-22 13:03:02 -05:00
|
|
|
assert(!isBundleLoader || !umbrella);
|
2020-04-23 20:16:49 -07:00
|
|
|
if (umbrella == nullptr)
|
|
|
|
|
umbrella = this;
|
2021-06-02 21:53:44 -04:00
|
|
|
this->umbrella = umbrella;
|
2020-04-23 20:16:49 -07:00
|
|
|
|
2021-05-03 18:31:23 -04:00
|
|
|
auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
|
2020-04-21 13:37:57 -07:00
|
|
|
|
2021-06-06 18:25:28 -04:00
|
|
|
// Initialize installName.
|
2020-04-21 13:37:57 -07:00
|
|
|
if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
|
|
|
|
|
auto *c = reinterpret_cast<const dylib_command *>(cmd);
|
2020-12-15 15:25:15 -05:00
|
|
|
currentVersion = read32le(&c->dylib.current_version);
|
|
|
|
|
compatibilityVersion = read32le(&c->dylib.compatibility_version);
|
2021-06-06 18:25:28 -04:00
|
|
|
installName =
|
|
|
|
|
reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
|
2021-02-22 13:03:02 -05:00
|
|
|
} else if (!isBundleLoader) {
|
|
|
|
|
// macho_executable and macho_bundle don't have LC_ID_DYLIB,
|
|
|
|
|
// so it's OK.
|
2022-12-23 19:44:56 -05:00
|
|
|
error(toString(this) + ": dylib missing LC_ID_DYLIB load command");
|
2020-04-21 13:37:57 -07:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2021-06-02 09:35:06 -04:00
|
|
|
if (config->printEachFile)
|
|
|
|
|
message(toString(this));
|
2021-06-07 11:00:34 -04:00
|
|
|
inputFiles.insert(this);
|
2021-06-02 09:35:06 -04:00
|
|
|
|
2021-05-31 22:12:35 -04:00
|
|
|
deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB;
|
|
|
|
|
|
2021-05-03 18:31:23 -04:00
|
|
|
if (!checkCompatibility(this))
|
2021-04-21 05:41:14 -07:00
|
|
|
return;
|
2021-03-04 16:58:21 -05:00
|
|
|
|
2021-07-12 10:26:54 -04:00
|
|
|
checkAppExtensionSafety(hdr->flags & MH_APP_EXTENSION_SAFE);
|
|
|
|
|
|
2021-06-06 21:52:23 -04:00
|
|
|
for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) {
|
|
|
|
|
StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path};
|
|
|
|
|
rpaths.push_back(rpath);
|
|
|
|
|
}
|
|
|
|
|
|
2020-04-21 13:37:57 -07:00
|
|
|
// Initialize symbols.
|
2024-07-08 09:26:16 -07:00
|
|
|
bool canBeImplicitlyLinked = findCommand(hdr, LC_SUB_CLIENT) == nullptr;
|
|
|
|
|
exportingFile = (canBeImplicitlyLinked && isImplicitlyLinked(installName))
|
|
|
|
|
? this
|
|
|
|
|
: this->umbrella;
|
2021-12-14 21:07:06 -05:00
|
|
|
|
2024-11-21 09:02:17 +08:00
|
|
|
if (!canBeImplicitlyLinked) {
|
|
|
|
|
for (auto *cmd : findCommands<sub_client_command>(hdr, LC_SUB_CLIENT)) {
|
|
|
|
|
StringRef allowableClient{reinterpret_cast<const char *>(cmd) +
|
|
|
|
|
cmd->client};
|
|
|
|
|
allowableClients.push_back(allowableClient);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-07-10 00:05:13 +02:00
|
|
|
const auto *dyldInfo = findCommand<dyld_info_command>(hdr, LC_DYLD_INFO_ONLY);
|
|
|
|
|
const auto *exportsTrie =
|
|
|
|
|
findCommand<linkedit_data_command>(hdr, LC_DYLD_EXPORTS_TRIE);
|
|
|
|
|
if (dyldInfo && exportsTrie) {
|
|
|
|
|
// It's unclear what should happen in this case. Maybe we should only error
|
|
|
|
|
// out if the two load commands refer to different data?
|
2022-12-23 19:44:56 -05:00
|
|
|
error(toString(this) +
|
|
|
|
|
": dylib has both LC_DYLD_INFO_ONLY and LC_DYLD_EXPORTS_TRIE");
|
2022-07-10 00:05:13 +02:00
|
|
|
return;
|
2023-04-05 01:48:34 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (dyldInfo) {
|
2022-07-10 00:05:13 +02:00
|
|
|
parseExportedSymbols(dyldInfo->export_off, dyldInfo->export_size);
|
|
|
|
|
} else if (exportsTrie) {
|
|
|
|
|
parseExportedSymbols(exportsTrie->dataoff, exportsTrie->datasize);
|
|
|
|
|
} else {
|
|
|
|
|
error("No LC_DYLD_INFO_ONLY or LC_DYLD_EXPORTS_TRIE found in " +
|
|
|
|
|
toString(this));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void DylibFile::parseExportedSymbols(uint32_t offset, uint32_t size) {
|
|
|
|
|
struct TrieEntry {
|
|
|
|
|
StringRef name;
|
|
|
|
|
uint64_t flags;
|
|
|
|
|
};
|
2021-12-14 21:07:06 -05:00
|
|
|
|
2022-07-10 00:05:13 +02:00
|
|
|
auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
|
|
|
|
|
std::vector<TrieEntry> entries;
|
|
|
|
|
// Find all the $ld$* symbols to process first.
|
2025-08-29 17:08:35 -07:00
|
|
|
parseTrie(toString(this), buf + offset, size,
|
|
|
|
|
[&](const Twine &name, uint64_t flags) {
|
|
|
|
|
StringRef savedName = saver().save(name);
|
|
|
|
|
if (handleLDSymbol(savedName))
|
|
|
|
|
return;
|
|
|
|
|
entries.push_back({savedName, flags});
|
|
|
|
|
});
|
2021-12-14 21:07:06 -05:00
|
|
|
|
2022-07-10 00:05:13 +02:00
|
|
|
// Process the "normal" symbols.
|
|
|
|
|
for (TrieEntry &entry : entries) {
|
|
|
|
|
if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(entry.name)))
|
|
|
|
|
continue;
|
2021-12-14 21:07:06 -05:00
|
|
|
|
2022-07-10 00:05:13 +02:00
|
|
|
bool isWeakDef = entry.flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
|
|
|
|
|
bool isTlv = entry.flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
|
|
|
|
|
|
|
|
|
|
symbols.push_back(
|
|
|
|
|
symtab->addDylib(entry.name, exportingFile, isWeakDef, isTlv));
|
2020-04-23 20:16:49 -07:00
|
|
|
}
|
2021-05-31 14:59:48 -04:00
|
|
|
}
|
2020-04-23 20:16:49 -07:00
|
|
|
|
2021-06-02 21:53:44 -04:00
|
|
|
void DylibFile::parseLoadCommands(MemoryBufferRef mb) {
|
2021-05-31 14:59:48 -04:00
|
|
|
auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
|
|
|
|
|
const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) +
|
|
|
|
|
target->headerSize;
|
2020-04-23 20:16:49 -07:00
|
|
|
for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
|
|
|
|
|
auto *cmd = reinterpret_cast<const load_command *>(p);
|
|
|
|
|
p += cmd->cmdsize;
|
|
|
|
|
|
2021-03-01 15:25:10 -05:00
|
|
|
if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
|
|
|
|
|
cmd->cmd == LC_REEXPORT_DYLIB) {
|
|
|
|
|
const auto *c = reinterpret_cast<const dylib_command *>(cmd);
|
|
|
|
|
StringRef reexportPath =
|
|
|
|
|
reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
|
2021-03-04 14:36:44 -05:00
|
|
|
loadReexport(reexportPath, exportingFile, nullptr);
|
2021-03-01 15:25:10 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
|
|
|
|
|
// LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
|
|
|
|
|
// MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
|
|
|
|
|
if (config->namespaceKind == NamespaceKind::flat &&
|
|
|
|
|
cmd->cmd == LC_LOAD_DYLIB) {
|
|
|
|
|
const auto *c = reinterpret_cast<const dylib_command *>(cmd);
|
|
|
|
|
StringRef dylibPath =
|
|
|
|
|
reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
|
2021-06-01 16:09:41 -04:00
|
|
|
DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr);
|
2021-03-01 15:25:10 -05:00
|
|
|
if (!dylib)
|
|
|
|
|
error(Twine("unable to locate library '") + dylibPath +
|
|
|
|
|
"' loaded from '" + toString(this) + "' for -flat_namespace");
|
|
|
|
|
}
|
2020-04-21 13:37:57 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-04-22 11:55:50 -04:00
|
|
|
// Some versions of Xcode ship with .tbd files that don't have the right
|
2021-05-31 14:59:48 -04:00
|
|
|
// platform settings.
|
2022-04-24 21:10:55 -04:00
|
|
|
constexpr std::array<StringRef, 3> skipPlatformChecks{
|
2021-05-31 14:59:48 -04:00
|
|
|
"/usr/lib/system/libsystem_kernel.dylib",
|
|
|
|
|
"/usr/lib/system/libsystem_platform.dylib",
|
2022-04-24 21:10:55 -04:00
|
|
|
"/usr/lib/system/libsystem_pthread.dylib"};
|
2021-05-31 14:59:48 -04:00
|
|
|
|
2022-04-22 11:55:50 -04:00
|
|
|
static bool skipPlatformCheckForCatalyst(const InterfaceFile &interface,
|
|
|
|
|
bool explicitlyLinked) {
|
|
|
|
|
// Catalyst outputs can link against implicitly linked macOS-only libraries.
|
|
|
|
|
if (config->platform() != PLATFORM_MACCATALYST || explicitlyLinked)
|
|
|
|
|
return false;
|
|
|
|
|
return is_contained(interface.targets(),
|
|
|
|
|
MachO::Target(config->arch(), PLATFORM_MACOS));
|
|
|
|
|
}
|
|
|
|
|
|
2022-07-27 23:31:21 -07:00
|
|
|
static bool isArchABICompatible(ArchitectureSet archSet,
|
|
|
|
|
Architecture targetArch) {
|
|
|
|
|
uint32_t cpuType;
|
|
|
|
|
uint32_t targetCpuType;
|
|
|
|
|
std::tie(targetCpuType, std::ignore) = getCPUTypeFromArchitecture(targetArch);
|
|
|
|
|
|
|
|
|
|
return llvm::any_of(archSet, [&](const auto &p) {
|
|
|
|
|
std::tie(cpuType, std::ignore) = getCPUTypeFromArchitecture(p);
|
|
|
|
|
return cpuType == targetCpuType;
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static bool isTargetPlatformArchCompatible(
|
|
|
|
|
InterfaceFile::const_target_range interfaceTargets, Target target) {
|
|
|
|
|
if (is_contained(interfaceTargets, target))
|
|
|
|
|
return true;
|
|
|
|
|
|
|
|
|
|
if (config->forceExactCpuSubtypeMatch)
|
|
|
|
|
return false;
|
|
|
|
|
|
|
|
|
|
ArchitectureSet archSet;
|
|
|
|
|
for (const auto &p : interfaceTargets)
|
|
|
|
|
if (p.Platform == target.Platform)
|
|
|
|
|
archSet.set(p.Arch);
|
|
|
|
|
if (archSet.empty())
|
|
|
|
|
return false;
|
|
|
|
|
|
|
|
|
|
return isArchABICompatible(archSet, target.Arch);
|
|
|
|
|
}
|
|
|
|
|
|
2021-02-22 13:03:02 -05:00
|
|
|
DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
|
2022-04-22 11:55:50 -04:00
|
|
|
bool isBundleLoader, bool explicitlyLinked)
|
2021-02-22 13:03:02 -05:00
|
|
|
: InputFile(DylibKind, interface), refState(RefState::Unreferenced),
|
2022-04-22 11:55:50 -04:00
|
|
|
explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {
|
2021-02-22 13:03:02 -05:00
|
|
|
// FIXME: Add test for the missing TBD code path.
|
|
|
|
|
|
2020-06-05 11:18:33 -07:00
|
|
|
if (umbrella == nullptr)
|
|
|
|
|
umbrella = this;
|
2021-06-02 21:53:44 -04:00
|
|
|
this->umbrella = umbrella;
|
2020-06-05 11:18:33 -07:00
|
|
|
|
2022-01-20 14:53:18 -05:00
|
|
|
installName = saver().save(interface.getInstallName());
|
2021-03-04 14:36:49 -05:00
|
|
|
compatibilityVersion = interface.getCompatibilityVersion().rawValue();
|
|
|
|
|
currentVersion = interface.getCurrentVersion().rawValue();
|
2025-04-10 07:34:20 -07:00
|
|
|
for (const auto &rpath : interface.rpaths())
|
|
|
|
|
if (rpath.first == config->platformInfo.target)
|
|
|
|
|
rpaths.push_back(saver().save(rpath.second));
|
2021-03-04 14:36:49 -05:00
|
|
|
|
2021-06-02 09:35:06 -04:00
|
|
|
if (config->printEachFile)
|
|
|
|
|
message(toString(this));
|
2021-06-07 11:00:34 -04:00
|
|
|
inputFiles.insert(this);
|
2021-06-02 09:35:06 -04:00
|
|
|
|
2021-06-06 18:25:28 -04:00
|
|
|
if (!is_contained(skipPlatformChecks, installName) &&
|
2022-07-27 23:31:21 -07:00
|
|
|
!isTargetPlatformArchCompatible(interface.targets(),
|
|
|
|
|
config->platformInfo.target) &&
|
2022-04-22 11:55:50 -04:00
|
|
|
!skipPlatformCheckForCatalyst(interface, explicitlyLinked)) {
|
2021-02-23 21:42:00 -05:00
|
|
|
error(toString(this) + " is incompatible with " +
|
2021-04-21 05:41:14 -07:00
|
|
|
std::string(config->platformInfo.target));
|
2021-02-23 21:42:00 -05:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2021-07-12 10:26:54 -04:00
|
|
|
checkAppExtensionSafety(interface.isApplicationExtensionSafe());
|
|
|
|
|
|
2024-07-08 09:26:16 -07:00
|
|
|
bool canBeImplicitlyLinked = interface.allowableClients().size() == 0;
|
|
|
|
|
exportingFile = (canBeImplicitlyLinked && isImplicitlyLinked(installName))
|
|
|
|
|
? this
|
|
|
|
|
: umbrella;
|
2024-11-21 09:02:17 +08:00
|
|
|
|
|
|
|
|
if (!canBeImplicitlyLinked)
|
|
|
|
|
for (const auto &allowableClient : interface.allowableClients())
|
|
|
|
|
allowableClients.push_back(
|
|
|
|
|
*make<std::string>(allowableClient.getInstallName().data()));
|
|
|
|
|
|
2022-08-16 23:09:46 +02:00
|
|
|
auto addSymbol = [&](const llvm::MachO::Symbol &symbol,
|
|
|
|
|
const Twine &name) -> void {
|
2022-01-20 14:53:18 -05:00
|
|
|
StringRef savedName = saver().save(name);
|
2021-12-14 21:07:06 -05:00
|
|
|
if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(savedName)))
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
symbols.push_back(symtab->addDylib(savedName, exportingFile,
|
2022-08-16 23:09:46 +02:00
|
|
|
symbol.isWeakDefined(),
|
|
|
|
|
symbol.isThreadLocalValue()));
|
2020-08-12 19:50:10 -07:00
|
|
|
};
|
2021-12-14 21:07:06 -05:00
|
|
|
|
|
|
|
|
std::vector<const llvm::MachO::Symbol *> normalSymbols;
|
|
|
|
|
normalSymbols.reserve(interface.symbolsCount());
|
2021-03-09 20:15:29 -08:00
|
|
|
for (const auto *symbol : interface.symbols()) {
|
2022-07-27 23:31:21 -07:00
|
|
|
if (!isArchABICompatible(symbol->getArchitectures(), config->arch()))
|
2020-08-12 19:50:10 -07:00
|
|
|
continue;
|
2021-06-05 12:51:36 -07:00
|
|
|
if (handleLDSymbol(symbol->getName()))
|
2021-06-04 23:31:40 -07:00
|
|
|
continue;
|
|
|
|
|
|
2021-12-14 21:07:06 -05:00
|
|
|
switch (symbol->getKind()) {
|
2024-01-26 16:12:50 -08:00
|
|
|
case EncodeKind::GlobalSymbol:
|
|
|
|
|
case EncodeKind::ObjectiveCClass:
|
|
|
|
|
case EncodeKind::ObjectiveCClassEHType:
|
|
|
|
|
case EncodeKind::ObjectiveCInstanceVariable:
|
2021-12-14 21:07:06 -05:00
|
|
|
normalSymbols.push_back(symbol);
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-06-28 16:36:29 -07:00
|
|
|
// interface.symbols() order is non-deterministic.
|
|
|
|
|
llvm::sort(normalSymbols,
|
|
|
|
|
[](auto *l, auto *r) { return l->getName() < r->getName(); });
|
2021-12-14 21:07:06 -05:00
|
|
|
|
|
|
|
|
// TODO(compnerd) filter out symbols based on the target platform
|
|
|
|
|
for (const auto *symbol : normalSymbols) {
|
2020-08-12 19:50:10 -07:00
|
|
|
switch (symbol->getKind()) {
|
2024-01-26 16:12:50 -08:00
|
|
|
case EncodeKind::GlobalSymbol:
|
2022-08-16 23:09:46 +02:00
|
|
|
addSymbol(*symbol, symbol->getName());
|
2020-08-12 19:50:10 -07:00
|
|
|
break;
|
2024-01-26 16:12:50 -08:00
|
|
|
case EncodeKind::ObjectiveCClass:
|
2020-08-12 19:50:10 -07:00
|
|
|
// XXX ld64 only creates these symbols when -ObjC is passed in. We may
|
|
|
|
|
// want to emulate that.
|
2024-03-01 14:12:56 -08:00
|
|
|
addSymbol(*symbol, objc::symbol_names::klass + symbol->getName());
|
|
|
|
|
addSymbol(*symbol, objc::symbol_names::metaclass + symbol->getName());
|
2020-08-12 19:50:10 -07:00
|
|
|
break;
|
2024-01-26 16:12:50 -08:00
|
|
|
case EncodeKind::ObjectiveCClassEHType:
|
2024-03-01 14:12:56 -08:00
|
|
|
addSymbol(*symbol, objc::symbol_names::ehtype + symbol->getName());
|
2020-08-12 19:50:10 -07:00
|
|
|
break;
|
2024-01-26 16:12:50 -08:00
|
|
|
case EncodeKind::ObjectiveCInstanceVariable:
|
2024-03-01 14:12:56 -08:00
|
|
|
addSymbol(*symbol, objc::symbol_names::ivar + symbol->getName());
|
2020-08-12 19:50:10 -07:00
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
2021-05-31 14:59:48 -04:00
|
|
|
}
|
2020-08-13 13:48:47 -07:00
|
|
|
|
2022-06-09 12:13:31 -04:00
|
|
|
DylibFile::DylibFile(DylibFile *umbrella)
|
|
|
|
|
: InputFile(DylibKind, MemoryBufferRef{}), refState(RefState::Unreferenced),
|
|
|
|
|
explicitlyLinked(false), isBundleLoader(false) {
|
|
|
|
|
if (umbrella == nullptr)
|
|
|
|
|
umbrella = this;
|
|
|
|
|
this->umbrella = umbrella;
|
|
|
|
|
}
|
|
|
|
|
|
2021-06-02 21:53:44 -04:00
|
|
|
void DylibFile::parseReexports(const InterfaceFile &interface) {
|
[lld-macho] Change loadReexport to handle the case where a TAPI re-exports to reference documents nested within other TBD.
Currently, it was delibrately impleneted to not handle this case, but as it has turnt out, we need this feature.
The concrete use case is
`System/Library/Frameworks/Cocoa.framework/Versions/A/Cocoa` reexports
/System/Library/Frameworks/AppKit.framework/Versions/C/AppKit , which then rexports
/System/Library/PrivateFrameworks/UIFoundation.framework/Versions/A/UIFoundation
The current implemention uses a global currentTopLevelTapi, which is not reset until it finishes loading the whole tree.
This is a problem because if the top-level is set to Cocoa, then when we get to UIFoundation, it will try to find UIFoundation in the current top level, which is Cocoa and will not find it.
The right thing should be:
- When loading a library from a TBD file, re-exports need to be looked up in the auxiliary documents within the same TBD.
- When loading from an actual dylib, no additional TBD documents need to be examined.
- In no case does a re-export mentioned in one TBD file need to be looked up in a document in an auxiliary document from a different TBD file
Differential Revision: https://reviews.llvm.org/D97438
2021-02-24 23:47:22 -05:00
|
|
|
const InterfaceFile *topLevel =
|
|
|
|
|
interface.getParent() == nullptr ? &interface : interface.getParent();
|
2021-10-26 15:14:25 -04:00
|
|
|
for (const InterfaceFileRef &intfRef : interface.reexportedLibraries()) {
|
2021-03-09 20:15:29 -08:00
|
|
|
InterfaceFile::const_target_range targets = intfRef.targets();
|
2021-04-20 19:54:41 -04:00
|
|
|
if (is_contained(skipPlatformChecks, intfRef.getInstallName()) ||
|
2022-07-27 23:31:21 -07:00
|
|
|
isTargetPlatformArchCompatible(targets, config->platformInfo.target))
|
2021-03-04 14:36:47 -05:00
|
|
|
loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
|
|
|
|
|
}
|
2020-06-05 11:18:33 -07:00
|
|
|
}
|
|
|
|
|
|
2022-06-09 12:13:31 -04:00
|
|
|
bool DylibFile::isExplicitlyLinked() const {
|
|
|
|
|
if (!explicitlyLinked)
|
|
|
|
|
return false;
|
|
|
|
|
|
|
|
|
|
// If this dylib was explicitly linked, but at least one of the symbols
|
|
|
|
|
// of the synthetic dylibs it created via $ld$previous symbols is
|
|
|
|
|
// referenced, then that synthetic dylib fulfils the explicit linkedness
|
|
|
|
|
// and we can deadstrip this dylib if it's unreferenced.
|
|
|
|
|
for (const auto *dylib : extraDylibs)
|
|
|
|
|
if (dylib->isReferenced())
|
|
|
|
|
return false;
|
|
|
|
|
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
DylibFile *DylibFile::getSyntheticDylib(StringRef installName,
|
|
|
|
|
uint32_t currentVersion,
|
|
|
|
|
uint32_t compatVersion) {
|
|
|
|
|
for (DylibFile *dylib : extraDylibs)
|
|
|
|
|
if (dylib->installName == installName) {
|
|
|
|
|
// FIXME: Check what to do if different $ld$previous symbols
|
|
|
|
|
// request the same dylib, but with different versions.
|
|
|
|
|
return dylib;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
auto *dylib = make<DylibFile>(umbrella == this ? nullptr : umbrella);
|
|
|
|
|
dylib->installName = saver().save(installName);
|
|
|
|
|
dylib->currentVersion = currentVersion;
|
|
|
|
|
dylib->compatibilityVersion = compatVersion;
|
|
|
|
|
extraDylibs.push_back(dylib);
|
|
|
|
|
return dylib;
|
|
|
|
|
}
|
|
|
|
|
|
2021-06-04 23:31:40 -07:00
|
|
|
// $ld$ symbols modify the properties/behavior of the library (e.g. its install
|
|
|
|
|
// name, compatibility version or hide/add symbols) for specific target
|
|
|
|
|
// versions.
|
2021-06-05 12:51:36 -07:00
|
|
|
bool DylibFile::handleLDSymbol(StringRef originalName) {
|
2023-06-05 14:36:19 -07:00
|
|
|
if (!originalName.starts_with("$ld$"))
|
2021-06-04 23:31:40 -07:00
|
|
|
return false;
|
|
|
|
|
|
|
|
|
|
StringRef action;
|
|
|
|
|
StringRef name;
|
2021-06-06 16:11:25 -04:00
|
|
|
std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$');
|
2021-06-05 12:51:36 -07:00
|
|
|
if (action == "previous")
|
|
|
|
|
handleLDPreviousSymbol(name, originalName);
|
|
|
|
|
else if (action == "install_name")
|
|
|
|
|
handleLDInstallNameSymbol(name, originalName);
|
2021-12-14 21:07:06 -05:00
|
|
|
else if (action == "hide")
|
|
|
|
|
handleLDHideSymbol(name, originalName);
|
2021-06-05 12:51:36 -07:00
|
|
|
return true;
|
|
|
|
|
}
|
2021-06-04 23:31:40 -07:00
|
|
|
|
2021-06-05 12:51:36 -07:00
|
|
|
void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) {
|
|
|
|
|
// originalName: $ld$ previous $ <installname> $ <compatversion> $
|
|
|
|
|
// <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $
|
2021-06-04 23:31:40 -07:00
|
|
|
StringRef installName;
|
|
|
|
|
StringRef compatVersion;
|
|
|
|
|
StringRef platformStr;
|
|
|
|
|
StringRef startVersion;
|
|
|
|
|
StringRef endVersion;
|
|
|
|
|
StringRef symbolName;
|
|
|
|
|
StringRef rest;
|
|
|
|
|
|
|
|
|
|
std::tie(installName, name) = name.split('$');
|
|
|
|
|
std::tie(compatVersion, name) = name.split('$');
|
|
|
|
|
std::tie(platformStr, name) = name.split('$');
|
|
|
|
|
std::tie(startVersion, name) = name.split('$');
|
2021-06-06 16:11:25 -04:00
|
|
|
std::tie(endVersion, name) = name.split('$');
|
2022-06-09 12:13:31 -04:00
|
|
|
std::tie(symbolName, rest) = name.rsplit('$');
|
|
|
|
|
|
|
|
|
|
// FIXME: Does this do the right thing for zippered files?
|
2021-06-04 23:31:40 -07:00
|
|
|
unsigned platform;
|
|
|
|
|
if (platformStr.getAsInteger(10, platform) ||
|
|
|
|
|
platform != static_cast<unsigned>(config->platform()))
|
2021-06-05 12:51:36 -07:00
|
|
|
return;
|
2021-06-04 23:31:40 -07:00
|
|
|
|
|
|
|
|
VersionTuple start;
|
|
|
|
|
if (start.tryParse(startVersion)) {
|
2022-12-23 19:44:56 -05:00
|
|
|
warn(toString(this) + ": failed to parse start version, symbol '" +
|
|
|
|
|
originalName + "' ignored");
|
2021-06-05 12:51:36 -07:00
|
|
|
return;
|
2021-06-04 23:31:40 -07:00
|
|
|
}
|
|
|
|
|
VersionTuple end;
|
|
|
|
|
if (end.tryParse(endVersion)) {
|
2022-12-23 19:44:56 -05:00
|
|
|
warn(toString(this) + ": failed to parse end version, symbol '" +
|
|
|
|
|
originalName + "' ignored");
|
2021-06-05 12:51:36 -07:00
|
|
|
return;
|
2021-06-04 23:31:40 -07:00
|
|
|
}
|
2023-03-03 12:08:33 -08:00
|
|
|
if (config->platformInfo.target.MinDeployment < start ||
|
|
|
|
|
config->platformInfo.target.MinDeployment >= end)
|
2021-06-05 12:51:36 -07:00
|
|
|
return;
|
2021-06-04 23:31:40 -07:00
|
|
|
|
2022-06-09 12:13:31 -04:00
|
|
|
// Initialized to compatibilityVersion for the symbolName branch below.
|
|
|
|
|
uint32_t newCompatibilityVersion = compatibilityVersion;
|
|
|
|
|
uint32_t newCurrentVersionForSymbol = currentVersion;
|
2021-06-04 23:31:40 -07:00
|
|
|
if (!compatVersion.empty()) {
|
|
|
|
|
VersionTuple cVersion;
|
|
|
|
|
if (cVersion.tryParse(compatVersion)) {
|
2022-12-23 19:44:56 -05:00
|
|
|
warn(toString(this) +
|
|
|
|
|
": failed to parse compatibility version, symbol '" + originalName +
|
2021-06-04 23:31:40 -07:00
|
|
|
"' ignored");
|
2021-06-05 12:51:36 -07:00
|
|
|
return;
|
2021-06-04 23:31:40 -07:00
|
|
|
}
|
2022-06-09 12:13:31 -04:00
|
|
|
newCompatibilityVersion = encodeVersion(cVersion);
|
|
|
|
|
newCurrentVersionForSymbol = newCompatibilityVersion;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!symbolName.empty()) {
|
|
|
|
|
// A $ld$previous$ symbol with symbol name adds a symbol with that name to
|
|
|
|
|
// a dylib with given name and version.
|
|
|
|
|
auto *dylib = getSyntheticDylib(installName, newCurrentVersionForSymbol,
|
|
|
|
|
newCompatibilityVersion);
|
|
|
|
|
|
2022-07-29 12:55:04 -04:00
|
|
|
// The tbd file usually contains the $ld$previous symbol for an old version,
|
|
|
|
|
// and then the symbol itself later, for newer deployment targets, like so:
|
|
|
|
|
// symbols: [
|
|
|
|
|
// '$ld$previous$/Another$$1$3.0$14.0$_zzz$',
|
|
|
|
|
// _zzz,
|
|
|
|
|
// ]
|
|
|
|
|
// Since the symbols are sorted, adding them to the symtab in the given
|
|
|
|
|
// order means the $ld$previous version of _zzz will prevail, as desired.
|
2022-06-09 12:13:31 -04:00
|
|
|
dylib->symbols.push_back(symtab->addDylib(
|
|
|
|
|
saver().save(symbolName), dylib, /*isWeakDef=*/false, /*isTlv=*/false));
|
|
|
|
|
return;
|
2021-06-04 23:31:40 -07:00
|
|
|
}
|
2022-06-09 12:13:31 -04:00
|
|
|
|
|
|
|
|
// A $ld$previous$ symbol without symbol name modifies the dylib it's in.
|
|
|
|
|
this->installName = saver().save(installName);
|
|
|
|
|
this->compatibilityVersion = newCompatibilityVersion;
|
2021-06-05 12:51:36 -07:00
|
|
|
}
|
2021-06-04 23:31:40 -07:00
|
|
|
|
2021-06-05 12:51:36 -07:00
|
|
|
void DylibFile::handleLDInstallNameSymbol(StringRef name,
|
|
|
|
|
StringRef originalName) {
|
|
|
|
|
// originalName: $ld$ install_name $ os<version> $ install_name
|
|
|
|
|
StringRef condition, installName;
|
|
|
|
|
std::tie(condition, installName) = name.split('$');
|
|
|
|
|
VersionTuple version;
|
2021-06-06 16:11:25 -04:00
|
|
|
if (!condition.consume_front("os") || version.tryParse(condition))
|
2022-12-23 19:44:56 -05:00
|
|
|
warn(toString(this) + ": failed to parse os version, symbol '" +
|
|
|
|
|
originalName + "' ignored");
|
2023-03-03 12:08:33 -08:00
|
|
|
else if (version == config->platformInfo.target.MinDeployment)
|
2022-01-20 14:53:18 -05:00
|
|
|
this->installName = saver().save(installName);
|
2021-06-04 23:31:40 -07:00
|
|
|
}
|
|
|
|
|
|
2021-12-14 21:07:06 -05:00
|
|
|
void DylibFile::handleLDHideSymbol(StringRef name, StringRef originalName) {
|
|
|
|
|
StringRef symbolName;
|
|
|
|
|
bool shouldHide = true;
|
2023-06-05 14:36:19 -07:00
|
|
|
if (name.starts_with("os")) {
|
2021-12-14 21:07:06 -05:00
|
|
|
// If it's hidden based on versions.
|
|
|
|
|
name = name.drop_front(2);
|
|
|
|
|
StringRef minVersion;
|
|
|
|
|
std::tie(minVersion, symbolName) = name.split('$');
|
|
|
|
|
VersionTuple versionTup;
|
|
|
|
|
if (versionTup.tryParse(minVersion)) {
|
2022-12-23 19:44:56 -05:00
|
|
|
warn(toString(this) + ": failed to parse hidden version, symbol `" + originalName +
|
2021-12-14 21:07:06 -05:00
|
|
|
"` ignored.");
|
|
|
|
|
return;
|
|
|
|
|
}
|
2023-03-03 12:08:33 -08:00
|
|
|
shouldHide = versionTup == config->platformInfo.target.MinDeployment;
|
2021-12-14 21:07:06 -05:00
|
|
|
} else {
|
|
|
|
|
symbolName = name;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (shouldHide)
|
|
|
|
|
exportingFile->hiddenSymbols.insert(CachedHashStringRef(symbolName));
|
|
|
|
|
}
|
|
|
|
|
|
2021-07-12 10:26:54 -04:00
|
|
|
void DylibFile::checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const {
|
|
|
|
|
if (config->applicationExtension && !dylibIsAppExtensionSafe)
|
|
|
|
|
warn("using '-application_extension' with unsafe dylib: " + toString(this));
|
|
|
|
|
}
|
|
|
|
|
|
2022-07-25 11:45:55 +02:00
|
|
|
ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f, bool forceHidden)
|
|
|
|
|
: InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)),
|
|
|
|
|
forceHidden(forceHidden) {}
|
2021-08-26 11:49:47 -04:00
|
|
|
|
|
|
|
|
void ArchiveFile::addLazySymbols() {
|
2023-08-07 13:41:46 -04:00
|
|
|
// Avoid calling getMemoryBufferRef() on zero-symbol archive
|
|
|
|
|
// since that crashes.
|
2025-04-10 14:33:56 -04:00
|
|
|
if (file->isEmpty() ||
|
|
|
|
|
(file->hasSymbolTable() && file->getNumberOfSymbols() == 0))
|
2023-08-07 13:41:46 -04:00
|
|
|
return;
|
2023-07-27 13:56:23 -04:00
|
|
|
|
2025-04-10 14:33:56 -04:00
|
|
|
if (!file->hasSymbolTable()) {
|
|
|
|
|
// No index, treat each child as a lazy object file.
|
|
|
|
|
Error e = Error::success();
|
|
|
|
|
for (const object::Archive::Child &c : file->children(e)) {
|
|
|
|
|
// Check `seen` but don't insert so a future eager load can still happen.
|
|
|
|
|
if (seen.contains(c.getChildOffset()))
|
|
|
|
|
continue;
|
|
|
|
|
if (!seenLazy.insert(c.getChildOffset()).second)
|
|
|
|
|
continue;
|
|
|
|
|
auto file = childToObjectFile(c, /*lazy=*/true);
|
|
|
|
|
if (!file)
|
|
|
|
|
error(toString(this) +
|
|
|
|
|
": couldn't process child: " + toString(file.takeError()));
|
|
|
|
|
inputFiles.insert(*file);
|
|
|
|
|
}
|
|
|
|
|
if (e)
|
|
|
|
|
error(toString(this) +
|
|
|
|
|
": Archive::children failed: " + toString(std::move(e)));
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2023-08-07 13:41:46 -04:00
|
|
|
Error err = Error::success();
|
|
|
|
|
auto child = file->child_begin(err);
|
2023-07-27 13:56:23 -04:00
|
|
|
// Ignore the I/O error here - will be reported later.
|
2023-08-07 13:41:46 -04:00
|
|
|
if (!err) {
|
|
|
|
|
Expected<MemoryBufferRef> mbOrErr = child->getMemoryBufferRef();
|
|
|
|
|
if (!mbOrErr) {
|
|
|
|
|
llvm::consumeError(mbOrErr.takeError());
|
|
|
|
|
} else {
|
|
|
|
|
if (identify_magic(mbOrErr->getBuffer()) == file_magic::macho_object) {
|
|
|
|
|
if (target->wordSize == 8)
|
|
|
|
|
compatArch = compatWithTargetArch(
|
|
|
|
|
this, reinterpret_cast<const LP64::mach_header *>(
|
|
|
|
|
mbOrErr->getBufferStart()));
|
|
|
|
|
else
|
|
|
|
|
compatArch = compatWithTargetArch(
|
|
|
|
|
this, reinterpret_cast<const ILP32::mach_header *>(
|
|
|
|
|
mbOrErr->getBufferStart()));
|
|
|
|
|
if (!compatArch)
|
|
|
|
|
return;
|
|
|
|
|
}
|
2023-07-27 13:56:23 -04:00
|
|
|
}
|
|
|
|
|
}
|
2023-08-07 13:41:46 -04:00
|
|
|
|
2020-05-14 12:43:51 -07:00
|
|
|
for (const object::Archive::Symbol &sym : file->symbols())
|
2022-01-11 16:49:06 -08:00
|
|
|
symtab->addLazyArchive(sym.getName(), this, sym);
|
2020-05-14 12:43:51 -07:00
|
|
|
}
|
|
|
|
|
|
2022-07-25 11:45:55 +02:00
|
|
|
static Expected<InputFile *>
|
|
|
|
|
loadArchiveMember(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,
|
2025-04-10 14:33:56 -04:00
|
|
|
uint64_t offsetInArchive, bool forceHidden, bool compatArch,
|
|
|
|
|
bool lazy) {
|
2021-08-26 11:49:47 -04:00
|
|
|
if (config->zeroModTime)
|
|
|
|
|
modTime = 0;
|
|
|
|
|
|
|
|
|
|
switch (identify_magic(mb.getBuffer())) {
|
|
|
|
|
case file_magic::macho_object:
|
2025-04-10 14:33:56 -04:00
|
|
|
return make<ObjFile>(mb, modTime, archiveName, lazy, forceHidden,
|
2023-07-27 13:56:23 -04:00
|
|
|
compatArch);
|
2021-08-26 11:49:47 -04:00
|
|
|
case file_magic::bitcode:
|
2025-04-10 14:33:56 -04:00
|
|
|
return make<BitcodeFile>(mb, archiveName, offsetInArchive, lazy,
|
2023-07-27 13:56:23 -04:00
|
|
|
forceHidden, compatArch);
|
2021-08-26 11:49:47 -04:00
|
|
|
default:
|
|
|
|
|
return createStringError(inconvertibleErrorCode(),
|
|
|
|
|
mb.getBufferIdentifier() +
|
|
|
|
|
" has unhandled file type");
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-05-14 12:43:51 -07:00
|
|
|
|
2021-08-26 11:49:47 -04:00
|
|
|
Error ArchiveFile::fetch(const object::Archive::Child &c, StringRef reason) {
|
2020-05-14 12:43:51 -07:00
|
|
|
if (!seen.insert(c.getChildOffset()).second)
|
2021-08-26 11:49:47 -04:00
|
|
|
return Error::success();
|
2025-04-10 14:33:56 -04:00
|
|
|
auto file = childToObjectFile(c, /*lazy=*/false);
|
2021-08-26 11:49:47 -04:00
|
|
|
if (!file)
|
|
|
|
|
return file.takeError();
|
|
|
|
|
|
|
|
|
|
inputFiles.insert(*file);
|
|
|
|
|
printArchiveMemberLoad(reason, *file);
|
|
|
|
|
return Error::success();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
|
|
|
|
|
object::Archive::Child c =
|
|
|
|
|
CHECK(sym.getMember(), toString(this) +
|
|
|
|
|
": could not get the member defining symbol " +
|
|
|
|
|
toMachOString(sym));
|
2020-12-01 14:45:11 -08:00
|
|
|
|
2021-04-30 09:30:46 -04:00
|
|
|
// `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile>
|
2020-12-02 18:59:00 -05:00
|
|
|
// and become invalid after that call. Copy it to the stack so we can refer
|
|
|
|
|
// to it later.
|
2021-04-30 09:30:46 -04:00
|
|
|
const object::Archive::Symbol symCopy = sym;
|
2020-12-02 18:59:00 -05:00
|
|
|
|
2021-08-26 11:49:47 -04:00
|
|
|
// ld64 doesn't demangle sym here even with -demangle.
|
|
|
|
|
// Match that: intentionally don't call toMachOString().
|
|
|
|
|
if (Error e = fetch(c, symCopy.getName()))
|
|
|
|
|
error(toString(this) + ": could not get the member defining symbol " +
|
|
|
|
|
toMachOString(symCopy) + ": " + toString(std::move(e)));
|
2020-05-14 12:43:51 -07:00
|
|
|
}
|
|
|
|
|
|
2025-04-10 14:33:56 -04:00
|
|
|
Expected<InputFile *>
|
|
|
|
|
ArchiveFile::childToObjectFile(const llvm::object::Archive::Child &c,
|
|
|
|
|
bool lazy) {
|
|
|
|
|
Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();
|
|
|
|
|
if (!mb)
|
|
|
|
|
return mb.takeError();
|
|
|
|
|
|
|
|
|
|
Expected<TimePoint<std::chrono::seconds>> modTime = c.getLastModified();
|
|
|
|
|
if (!modTime)
|
|
|
|
|
return modTime.takeError();
|
|
|
|
|
|
|
|
|
|
return loadArchiveMember(*mb, toTimeT(*modTime), getName(),
|
|
|
|
|
c.getChildOffset(), forceHidden, compatArch, lazy);
|
|
|
|
|
}
|
|
|
|
|
|
[lld-macho] Basic support for linkage and visibility attributes in LTO
When parsing bitcode, convert LTO Symbols to LLD Symbols in order to perform
resolution. The "winning" symbol will then be marked as Prevailing at LTO
compilation time. This is similar to what the other LLD ports do.
This change allows us to handle `linkonce` symbols correctly, and to deal with
duplicate bitcode symbols gracefully. Previously, both scenarios would result in
an assertion failure inside the LTO code, complaining that multiple Prevailing
definitions are not allowed.
While at it, I also added basic logic around visibility. We don't do anything
useful with it yet, but we do check that its value is valid. LLD-ELF appears to
use it only to set FinalDefinitionInLinkageUnit for LTO, which I think is just a
performance optimization.
From my local experimentation, the linker itself doesn't seem to do anything
differently when encountering linkonce / linkonce_odr / weak / weak_odr. So I've
only written a test for one of them. LLD-ELF has more, but they seem to mostly
be testing the intermediate bitcode output of their LTO backend...? I'm far from
an expert here though, so I might very well be missing things.
Reviewed By: #lld-macho, MaskRay, smeenai
Differential Revision: https://reviews.llvm.org/D94342
2021-02-25 13:27:40 -05:00
|
|
|
static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
|
|
|
|
|
BitcodeFile &file) {
|
2022-01-20 14:53:18 -05:00
|
|
|
StringRef name = saver().save(objSym.getName());
|
[lld-macho] Basic support for linkage and visibility attributes in LTO
When parsing bitcode, convert LTO Symbols to LLD Symbols in order to perform
resolution. The "winning" symbol will then be marked as Prevailing at LTO
compilation time. This is similar to what the other LLD ports do.
This change allows us to handle `linkonce` symbols correctly, and to deal with
duplicate bitcode symbols gracefully. Previously, both scenarios would result in
an assertion failure inside the LTO code, complaining that multiple Prevailing
definitions are not allowed.
While at it, I also added basic logic around visibility. We don't do anything
useful with it yet, but we do check that its value is valid. LLD-ELF appears to
use it only to set FinalDefinitionInLinkageUnit for LTO, which I think is just a
performance optimization.
From my local experimentation, the linker itself doesn't seem to do anything
differently when encountering linkonce / linkonce_odr / weak / weak_odr. So I've
only written a test for one of them. LLD-ELF has more, but they seem to mostly
be testing the intermediate bitcode output of their LTO backend...? I'm far from
an expert here though, so I might very well be missing things.
Reviewed By: #lld-macho, MaskRay, smeenai
Differential Revision: https://reviews.llvm.org/D94342
2021-02-25 13:27:40 -05:00
|
|
|
|
|
|
|
|
if (objSym.isUndefined())
|
2021-12-17 12:35:52 -05:00
|
|
|
return symtab->addUndefined(name, &file, /*isWeakRef=*/objSym.isWeak());
|
[lld-macho] Basic support for linkage and visibility attributes in LTO
When parsing bitcode, convert LTO Symbols to LLD Symbols in order to perform
resolution. The "winning" symbol will then be marked as Prevailing at LTO
compilation time. This is similar to what the other LLD ports do.
This change allows us to handle `linkonce` symbols correctly, and to deal with
duplicate bitcode symbols gracefully. Previously, both scenarios would result in
an assertion failure inside the LTO code, complaining that multiple Prevailing
definitions are not allowed.
While at it, I also added basic logic around visibility. We don't do anything
useful with it yet, but we do check that its value is valid. LLD-ELF appears to
use it only to set FinalDefinitionInLinkageUnit for LTO, which I think is just a
performance optimization.
From my local experimentation, the linker itself doesn't seem to do anything
differently when encountering linkonce / linkonce_odr / weak / weak_odr. So I've
only written a test for one of them. LLD-ELF has more, but they seem to mostly
be testing the intermediate bitcode output of their LTO backend...? I'm far from
an expert here though, so I might very well be missing things.
Reviewed By: #lld-macho, MaskRay, smeenai
Differential Revision: https://reviews.llvm.org/D94342
2021-02-25 13:27:40 -05:00
|
|
|
|
|
|
|
|
// TODO: Write a test demonstrating why computing isPrivateExtern before
|
|
|
|
|
// LTO compilation is important.
|
|
|
|
|
bool isPrivateExtern = false;
|
|
|
|
|
switch (objSym.getVisibility()) {
|
|
|
|
|
case GlobalValue::HiddenVisibility:
|
|
|
|
|
isPrivateExtern = true;
|
|
|
|
|
break;
|
|
|
|
|
case GlobalValue::ProtectedVisibility:
|
|
|
|
|
error(name + " has protected visibility, which is not supported by Mach-O");
|
|
|
|
|
break;
|
|
|
|
|
case GlobalValue::DefaultVisibility:
|
|
|
|
|
break;
|
|
|
|
|
}
|
2022-07-25 11:45:55 +02:00
|
|
|
isPrivateExtern = isPrivateExtern || objSym.canBeOmittedFromSymbolTable() ||
|
|
|
|
|
file.forceHidden;
|
[lld-macho] Basic support for linkage and visibility attributes in LTO
When parsing bitcode, convert LTO Symbols to LLD Symbols in order to perform
resolution. The "winning" symbol will then be marked as Prevailing at LTO
compilation time. This is similar to what the other LLD ports do.
This change allows us to handle `linkonce` symbols correctly, and to deal with
duplicate bitcode symbols gracefully. Previously, both scenarios would result in
an assertion failure inside the LTO code, complaining that multiple Prevailing
definitions are not allowed.
While at it, I also added basic logic around visibility. We don't do anything
useful with it yet, but we do check that its value is valid. LLD-ELF appears to
use it only to set FinalDefinitionInLinkageUnit for LTO, which I think is just a
performance optimization.
From my local experimentation, the linker itself doesn't seem to do anything
differently when encountering linkonce / linkonce_odr / weak / weak_odr. So I've
only written a test for one of them. LLD-ELF has more, but they seem to mostly
be testing the intermediate bitcode output of their LTO backend...? I'm far from
an expert here though, so I might very well be missing things.
Reviewed By: #lld-macho, MaskRay, smeenai
Differential Revision: https://reviews.llvm.org/D94342
2021-02-25 13:27:40 -05:00
|
|
|
|
2021-07-29 11:06:40 -04:00
|
|
|
if (objSym.isCommon())
|
|
|
|
|
return symtab->addCommon(name, &file, objSym.getCommonSize(),
|
|
|
|
|
objSym.getCommonAlignment(), isPrivateExtern);
|
|
|
|
|
|
[lld-macho] Basic support for linkage and visibility attributes in LTO
When parsing bitcode, convert LTO Symbols to LLD Symbols in order to perform
resolution. The "winning" symbol will then be marked as Prevailing at LTO
compilation time. This is similar to what the other LLD ports do.
This change allows us to handle `linkonce` symbols correctly, and to deal with
duplicate bitcode symbols gracefully. Previously, both scenarios would result in
an assertion failure inside the LTO code, complaining that multiple Prevailing
definitions are not allowed.
While at it, I also added basic logic around visibility. We don't do anything
useful with it yet, but we do check that its value is valid. LLD-ELF appears to
use it only to set FinalDefinitionInLinkageUnit for LTO, which I think is just a
performance optimization.
From my local experimentation, the linker itself doesn't seem to do anything
differently when encountering linkonce / linkonce_odr / weak / weak_odr. So I've
only written a test for one of them. LLD-ELF has more, but they seem to mostly
be testing the intermediate bitcode output of their LTO backend...? I'm far from
an expert here though, so I might very well be missing things.
Reviewed By: #lld-macho, MaskRay, smeenai
Differential Revision: https://reviews.llvm.org/D94342
2021-02-25 13:27:40 -05:00
|
|
|
return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
|
2021-04-30 16:17:26 -04:00
|
|
|
/*size=*/0, objSym.isWeak(), isPrivateExtern,
|
[lld/mac] Implement -dead_strip
Also adds support for live_support sections, no_dead_strip sections,
.no_dead_strip symbols.
Chromium Framework 345MB unstripped -> 250MB stripped
(vs 290MB unstripped -> 236M stripped with ld64).
Doing dead stripping is a bit faster than not, because so much less
data needs to be processed:
% ministat lld_*
x lld_nostrip.txt
+ lld_strip.txt
N Min Max Median Avg Stddev
x 10 3.929414 4.07692 4.0269079 4.0089678 0.044214794
+ 10 3.8129408 3.9025559 3.8670411 3.8642573 0.024779651
Difference at 95.0% confidence
-0.144711 +/- 0.0336749
-3.60967% +/- 0.839989%
(Student's t, pooled s = 0.0358398)
This interacts with many parts of the linker. I tried to add test coverage
for all added `isLive()` checks, so that some test will fail if any of them
is removed. I checked that the test expectations for the most part match
ld64's behavior (except for live-support-iterations.s, see the comment
in the test). Interacts with:
- debug info
- export tries
- import opcodes
- flags like -exported_symbol(s_list)
- -U / dynamic_lookup
- mod_init_funcs, mod_term_funcs
- weak symbol handling
- unwind info
- stubs
- map files
- -sectcreate
- undefined, dylib, common, defined (both absolute and normal) symbols
It's possible it interacts with more features I didn't think of,
of course.
I also did some manual testing:
- check-llvm check-clang check-lld work with lld with this patch
as host linker and -dead_strip enabled
- Chromium still starts
- Chromium's base_unittests still pass, including unwind tests
Implemenation-wise, this is InputSection-based, so it'll work for
object files with .subsections_via_symbols (which includes all
object files generated by clang). I first based this on the COFF
implementation, but later realized that things are more similar to ELF.
I think it'd be good to refactor MarkLive.cpp to look more like the ELF
part at some point, but I'd like to get a working state checked in first.
Mechanical parts:
- Rename canOmitFromOutput to wasCoalesced (no behavior change)
since it really is for weak coalesced symbols
- Add noDeadStrip to Defined, corresponding to N_NO_DEAD_STRIP
(`.no_dead_strip` in asm)
Fixes PR49276.
Differential Revision: https://reviews.llvm.org/D103324
2021-05-07 17:10:05 -04:00
|
|
|
/*isReferencedDynamically=*/false,
|
2021-11-08 19:50:34 -05:00
|
|
|
/*noDeadStrip=*/false,
|
|
|
|
|
/*isWeakDefCanBeHidden=*/false);
|
[lld-macho] Basic support for linkage and visibility attributes in LTO
When parsing bitcode, convert LTO Symbols to LLD Symbols in order to perform
resolution. The "winning" symbol will then be marked as Prevailing at LTO
compilation time. This is similar to what the other LLD ports do.
This change allows us to handle `linkonce` symbols correctly, and to deal with
duplicate bitcode symbols gracefully. Previously, both scenarios would result in
an assertion failure inside the LTO code, complaining that multiple Prevailing
definitions are not allowed.
While at it, I also added basic logic around visibility. We don't do anything
useful with it yet, but we do check that its value is valid. LLD-ELF appears to
use it only to set FinalDefinitionInLinkageUnit for LTO, which I think is just a
performance optimization.
From my local experimentation, the linker itself doesn't seem to do anything
differently when encountering linkonce / linkonce_odr / weak / weak_odr. So I've
only written a test for one of them. LLD-ELF has more, but they seem to mostly
be testing the intermediate bitcode output of their LTO backend...? I'm far from
an expert here though, so I might very well be missing things.
Reviewed By: #lld-macho, MaskRay, smeenai
Differential Revision: https://reviews.llvm.org/D94342
2021-02-25 13:27:40 -05:00
|
|
|
}
|
|
|
|
|
|
2021-07-22 22:47:22 -04:00
|
|
|
BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
|
2023-07-27 13:56:23 -04:00
|
|
|
uint64_t offsetInArchive, bool lazy, bool forceHidden,
|
|
|
|
|
bool compatArch)
|
2022-07-25 11:45:55 +02:00
|
|
|
: InputFile(BitcodeKind, mb, lazy), forceHidden(forceHidden) {
|
2021-12-07 19:11:06 -05:00
|
|
|
this->archiveName = std::string(archiveName);
|
2023-07-27 13:56:23 -04:00
|
|
|
this->compatArch = compatArch;
|
2021-07-22 22:47:22 -04:00
|
|
|
std::string path = mb.getBufferIdentifier().str();
|
2022-11-20 11:59:16 -05:00
|
|
|
if (config->thinLTOIndexOnly)
|
|
|
|
|
path = replaceThinLTOSuffix(mb.getBufferIdentifier());
|
|
|
|
|
|
2023-07-27 13:56:23 -04:00
|
|
|
// If the parent archive already determines that the arch is not compat with
|
|
|
|
|
// target, then just return.
|
|
|
|
|
if (!compatArch)
|
|
|
|
|
return;
|
|
|
|
|
|
2021-07-22 22:47:22 -04:00
|
|
|
// ThinLTO assumes that all MemoryBufferRefs given to it have a unique
|
|
|
|
|
// name. If two members with the same name are provided, this causes a
|
|
|
|
|
// collision and ThinLTO can't proceed.
|
|
|
|
|
// So, we append the archive name to disambiguate two members with the same
|
|
|
|
|
// name from multiple different archives, and offset within the archive to
|
|
|
|
|
// disambiguate two members of the same name from a single archive.
|
2022-01-20 14:53:18 -05:00
|
|
|
MemoryBufferRef mbref(mb.getBuffer(),
|
|
|
|
|
saver().save(archiveName.empty()
|
|
|
|
|
? path
|
2023-04-20 17:23:36 -04:00
|
|
|
: archiveName + "(" +
|
|
|
|
|
sys::path::filename(path) + ")" +
|
2022-01-20 14:53:18 -05:00
|
|
|
utostr(offsetInArchive)));
|
2020-10-26 19:18:29 -07:00
|
|
|
obj = check(lto::InputFile::create(mbref));
|
2022-01-19 10:14:49 -08:00
|
|
|
if (lazy)
|
|
|
|
|
parseLazy();
|
|
|
|
|
else
|
|
|
|
|
parse();
|
|
|
|
|
}
|
[lld-macho] Basic support for linkage and visibility attributes in LTO
When parsing bitcode, convert LTO Symbols to LLD Symbols in order to perform
resolution. The "winning" symbol will then be marked as Prevailing at LTO
compilation time. This is similar to what the other LLD ports do.
This change allows us to handle `linkonce` symbols correctly, and to deal with
duplicate bitcode symbols gracefully. Previously, both scenarios would result in
an assertion failure inside the LTO code, complaining that multiple Prevailing
definitions are not allowed.
While at it, I also added basic logic around visibility. We don't do anything
useful with it yet, but we do check that its value is valid. LLD-ELF appears to
use it only to set FinalDefinitionInLinkageUnit for LTO, which I think is just a
performance optimization.
From my local experimentation, the linker itself doesn't seem to do anything
differently when encountering linkonce / linkonce_odr / weak / weak_odr. So I've
only written a test for one of them. LLD-ELF has more, but they seem to mostly
be testing the intermediate bitcode output of their LTO backend...? I'm far from
an expert here though, so I might very well be missing things.
Reviewed By: #lld-macho, MaskRay, smeenai
Differential Revision: https://reviews.llvm.org/D94342
2021-02-25 13:27:40 -05:00
|
|
|
|
2022-01-19 10:14:49 -08:00
|
|
|
void BitcodeFile::parse() {
|
[lld-macho] Basic support for linkage and visibility attributes in LTO
When parsing bitcode, convert LTO Symbols to LLD Symbols in order to perform
resolution. The "winning" symbol will then be marked as Prevailing at LTO
compilation time. This is similar to what the other LLD ports do.
This change allows us to handle `linkonce` symbols correctly, and to deal with
duplicate bitcode symbols gracefully. Previously, both scenarios would result in
an assertion failure inside the LTO code, complaining that multiple Prevailing
definitions are not allowed.
While at it, I also added basic logic around visibility. We don't do anything
useful with it yet, but we do check that its value is valid. LLD-ELF appears to
use it only to set FinalDefinitionInLinkageUnit for LTO, which I think is just a
performance optimization.
From my local experimentation, the linker itself doesn't seem to do anything
differently when encountering linkonce / linkonce_odr / weak / weak_odr. So I've
only written a test for one of them. LLD-ELF has more, but they seem to mostly
be testing the intermediate bitcode output of their LTO backend...? I'm far from
an expert here though, so I might very well be missing things.
Reviewed By: #lld-macho, MaskRay, smeenai
Differential Revision: https://reviews.llvm.org/D94342
2021-02-25 13:27:40 -05:00
|
|
|
// Convert LTO Symbols to LLD Symbols in order to perform resolution. The
|
|
|
|
|
// "winning" symbol will then be marked as Prevailing at LTO compilation
|
|
|
|
|
// time.
|
2023-09-26 15:31:51 -04:00
|
|
|
symbols.resize(obj->symbols().size());
|
|
|
|
|
|
|
|
|
|
// Process defined symbols first. See the comment at the end of
|
|
|
|
|
// ObjFile<>::parseSymbols.
|
|
|
|
|
for (auto it : llvm::enumerate(obj->symbols()))
|
|
|
|
|
if (!it.value().isUndefined())
|
|
|
|
|
symbols[it.index()] = createBitcodeSymbol(it.value(), *this);
|
|
|
|
|
for (auto it : llvm::enumerate(obj->symbols()))
|
|
|
|
|
if (it.value().isUndefined())
|
|
|
|
|
symbols[it.index()] = createBitcodeSymbol(it.value(), *this);
|
2020-10-26 19:18:29 -07:00
|
|
|
}
|
2021-04-02 18:46:18 -04:00
|
|
|
|
2022-01-19 10:14:49 -08:00
|
|
|
void BitcodeFile::parseLazy() {
|
|
|
|
|
symbols.resize(obj->symbols().size());
|
2022-10-22 10:41:10 -04:00
|
|
|
for (const auto &[i, objSym] : llvm::enumerate(obj->symbols())) {
|
2022-01-19 10:14:49 -08:00
|
|
|
if (!objSym.isUndefined()) {
|
2022-10-22 10:41:10 -04:00
|
|
|
symbols[i] = symtab->addLazyObject(saver().save(objSym.getName()), *this);
|
2022-01-19 10:14:49 -08:00
|
|
|
if (!lazy)
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-11-20 11:59:16 -05:00
|
|
|
std::string macho::replaceThinLTOSuffix(StringRef path) {
|
|
|
|
|
auto [suffix, repl] = config->thinLTOObjectSuffixReplace;
|
|
|
|
|
if (path.consume_back(suffix))
|
|
|
|
|
return (path + repl).str();
|
|
|
|
|
return std::string(path);
|
|
|
|
|
}
|
|
|
|
|
|
2022-01-19 10:14:49 -08:00
|
|
|
void macho::extract(InputFile &file, StringRef reason) {
|
2022-12-02 09:29:18 -05:00
|
|
|
if (!file.lazy)
|
|
|
|
|
return;
|
2022-01-19 10:14:49 -08:00
|
|
|
file.lazy = false;
|
2022-12-02 09:29:18 -05:00
|
|
|
|
|
|
|
|
printArchiveMemberLoad(reason, &file);
|
2022-01-19 10:14:49 -08:00
|
|
|
if (auto *bitcode = dyn_cast<BitcodeFile>(&file)) {
|
|
|
|
|
bitcode->parse();
|
|
|
|
|
} else {
|
|
|
|
|
auto &f = cast<ObjFile>(file);
|
|
|
|
|
if (target->wordSize == 8)
|
|
|
|
|
f.parse<LP64>();
|
|
|
|
|
else
|
|
|
|
|
f.parse<ILP32>();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-04-02 18:46:18 -04:00
|
|
|
template void ObjFile::parse<LP64>();
|