2020-04-03 02:54:05 +08: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-24 11:16:49 +08:00
|
|
|
#include "Config.h"
|
2020-11-19 01:31:47 +08: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-02 06:45:01 +08:00
|
|
|
#include "Dwarf.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-23 11:00:57 +08:00
|
|
|
#include "ExportTrie.h"
|
2020-04-03 02:54:05 +08:00
|
|
|
#include "InputSection.h"
|
2020-05-22 06:26:35 +08:00
|
|
|
#include "MachOStructs.h"
|
2020-08-19 05:37:04 +08:00
|
|
|
#include "ObjC.h"
|
2020-05-02 07:29:06 +08:00
|
|
|
#include "OutputSection.h"
|
2020-08-19 05:37:04 +08:00
|
|
|
#include "OutputSegment.h"
|
2020-04-03 02:54:05 +08:00
|
|
|
#include "SymbolTable.h"
|
|
|
|
#include "Symbols.h"
|
|
|
|
#include "Target.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-02 06:45:01 +08:00
|
|
|
#include "lld/Common/DWARF.h"
|
2020-04-03 02:54:05 +08:00
|
|
|
#include "lld/Common/ErrorHandler.h"
|
|
|
|
#include "lld/Common/Memory.h"
|
2020-11-29 11:38:27 +08:00
|
|
|
#include "lld/Common/Reproduce.h"
|
2020-08-14 04:48:47 +08:00
|
|
|
#include "llvm/ADT/iterator.h"
|
2020-04-03 02:54:05 +08:00
|
|
|
#include "llvm/BinaryFormat/MachO.h"
|
2020-10-27 10:18:29 +08:00
|
|
|
#include "llvm/LTO/LTO.h"
|
2020-04-03 02:54:05 +08:00
|
|
|
#include "llvm/Support/Endian.h"
|
|
|
|
#include "llvm/Support/MemoryBuffer.h"
|
2020-04-24 11:16:49 +08:00
|
|
|
#include "llvm/Support/Path.h"
|
2020-11-29 11:38:27 +08:00
|
|
|
#include "llvm/Support/TarWriter.h"
|
2021-04-06 00:59:50 +08:00
|
|
|
#include "llvm/TextAPI/Architecture.h"
|
|
|
|
#include "llvm/TextAPI/InterfaceFile.h"
|
2020-04-03 02:54:05 +08:00
|
|
|
|
|
|
|
using namespace llvm;
|
|
|
|
using namespace llvm::MachO;
|
|
|
|
using namespace llvm::support::endian;
|
2020-04-24 11:16:49 +08:00
|
|
|
using namespace llvm::sys;
|
2020-04-03 02:54:05 +08:00
|
|
|
using namespace lld;
|
|
|
|
using namespace lld::macho;
|
|
|
|
|
2020-12-02 08:00:48 +08:00
|
|
|
// Returns "<internal>", "foo.a(bar.o)", or "baz.o".
|
|
|
|
std::string lld::toString(const InputFile *f) {
|
|
|
|
if (!f)
|
|
|
|
return "<internal>";
|
2021-03-05 03:36:49 +08:00
|
|
|
|
|
|
|
// Multiple dylibs can be defined in one .tbd file.
|
|
|
|
if (auto dylibFile = dyn_cast<DylibFile>(f))
|
|
|
|
if (f->getName().endswith(".tbd"))
|
|
|
|
return (f->getName() + "(" + dylibFile->dylibName + ")").str();
|
|
|
|
|
2020-12-02 08:00:48 +08:00
|
|
|
if (f->archiveName.empty())
|
|
|
|
return std::string(f->getName());
|
2021-04-13 22:40:22 +08:00
|
|
|
return (f->archiveName + "(" + path::filename(f->getName()) + ")").str();
|
2020-12-02 08:00:48 +08:00
|
|
|
}
|
|
|
|
|
2020-12-15 06:59:22 +08:00
|
|
|
SetVector<InputFile *> macho::inputFiles;
|
2020-11-29 11:38:27 +08:00
|
|
|
std::unique_ptr<TarWriter> macho::tar;
|
2020-12-02 06:45:12 +08:00
|
|
|
int InputFile::idCount = 0;
|
2020-04-03 02:54:05 +08:00
|
|
|
|
2021-04-21 20:41:14 +08: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 23:18:19 +08:00
|
|
|
static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) {
|
2021-04-21 20:41:14 +08:00
|
|
|
if (!isa<ObjFile>(input) && !isa<DylibFile>(input))
|
2021-05-06 23:18:19 +08:00
|
|
|
return {};
|
2021-04-21 20:41:14 +08:00
|
|
|
|
2021-05-04 06:31:23 +08:00
|
|
|
const char *hdr = input->mb.getBufferStart();
|
2021-04-21 23:18:20 +08:00
|
|
|
|
2021-05-06 23:18:19 +08:00
|
|
|
std::vector<PlatformInfo> platformInfos;
|
|
|
|
for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) {
|
|
|
|
PlatformInfo info;
|
|
|
|
info.target.Platform = static_cast<PlatformKind>(cmd->platform);
|
|
|
|
info.minimum = decodeVersion(cmd->minos);
|
|
|
|
platformInfos.emplace_back(std::move(info));
|
2021-04-21 23:18:20 +08:00
|
|
|
}
|
2021-05-06 23:18:19 +08: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 23:18:20 +08:00
|
|
|
switch (cmd->cmd) {
|
|
|
|
case LC_VERSION_MIN_MACOSX:
|
2021-05-06 23:18:19 +08:00
|
|
|
info.target.Platform = PlatformKind::macOS;
|
2021-04-21 23:18:20 +08:00
|
|
|
break;
|
|
|
|
case LC_VERSION_MIN_IPHONEOS:
|
2021-05-06 23:18:19 +08:00
|
|
|
info.target.Platform = PlatformKind::iOS;
|
2021-04-21 23:18:20 +08:00
|
|
|
break;
|
|
|
|
case LC_VERSION_MIN_TVOS:
|
2021-05-06 23:18:19 +08:00
|
|
|
info.target.Platform = PlatformKind::tvOS;
|
2021-04-21 23:18:20 +08:00
|
|
|
break;
|
|
|
|
case LC_VERSION_MIN_WATCHOS:
|
2021-05-06 23:18:19 +08:00
|
|
|
info.target.Platform = PlatformKind::watchOS;
|
2021-04-21 23:18:20 +08:00
|
|
|
break;
|
|
|
|
}
|
2021-05-06 23:18:19 +08:00
|
|
|
info.minimum = decodeVersion(cmd->version);
|
|
|
|
platformInfos.emplace_back(std::move(info));
|
2021-04-21 20:41:14 +08:00
|
|
|
}
|
|
|
|
|
2021-05-06 23:18:19 +08:00
|
|
|
return platformInfos;
|
2021-04-21 20:41:14 +08:00
|
|
|
}
|
|
|
|
|
2021-05-05 04:23:21 +08:00
|
|
|
static PlatformKind removeSimulator(PlatformKind platform) {
|
|
|
|
// Mapping of platform to simulator and vice-versa.
|
|
|
|
static const std::map<PlatformKind, PlatformKind> platformMap = {
|
|
|
|
{PlatformKind::iOSSimulator, PlatformKind::iOS},
|
|
|
|
{PlatformKind::tvOSSimulator, PlatformKind::tvOS},
|
|
|
|
{PlatformKind::watchOSSimulator, PlatformKind::watchOS}};
|
|
|
|
|
|
|
|
auto iter = platformMap.find(platform);
|
|
|
|
if (iter == platformMap.end())
|
|
|
|
return platform;
|
|
|
|
return iter->second;
|
|
|
|
}
|
|
|
|
|
2021-05-04 06:31:23 +08:00
|
|
|
static bool checkCompatibility(const InputFile *input) {
|
2021-05-06 23:18:19 +08:00
|
|
|
std::vector<PlatformInfo> platformInfos = getPlatformInfos(input);
|
|
|
|
if (platformInfos.empty())
|
2021-04-21 20:41:14 +08:00
|
|
|
return true;
|
2021-05-05 04:23:21 +08:00
|
|
|
|
2021-05-06 23:18:19 +08: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 20:41:14 +08:00
|
|
|
Twine(", which is different from target platform ") +
|
2021-04-22 03:43:38 +08:00
|
|
|
getPlatformName(config->platform()));
|
2021-04-21 20:41:14 +08:00
|
|
|
return false;
|
|
|
|
}
|
2021-05-06 23:18:19 +08:00
|
|
|
|
|
|
|
if (it->minimum <= config->platformInfo.minimum)
|
2021-04-21 20:41:14 +08:00
|
|
|
return true;
|
2021-05-06 23:18:19 +08:00
|
|
|
|
|
|
|
error(toString(input) + " has version " + it->minimum.getAsString() +
|
2021-04-23 07:08:04 +08:00
|
|
|
", which is newer than target minimum of " +
|
2021-04-21 20:41:14 +08:00
|
|
|
config->platformInfo.minimum.getAsString());
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2020-04-03 02:54:05 +08:00
|
|
|
// Open a given file path and return it as a memory-mapped file.
|
2021-03-02 17:20:22 +08:00
|
|
|
Optional<MemoryBufferRef> macho::readFile(StringRef path) {
|
2020-04-03 02:54:05 +08:00
|
|
|
// Open a file.
|
2021-03-10 12:15:29 +08:00
|
|
|
ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path);
|
|
|
|
if (std::error_code ec = mbOrErr.getError()) {
|
2020-04-03 02:54:05 +08:00
|
|
|
error("cannot open " + path + ": " + ec.message());
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
|
|
|
|
MemoryBufferRef mbref = mb->getMemBufferRef();
|
|
|
|
make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
|
2020-04-22 04:37:57 +08:00
|
|
|
|
|
|
|
// If this is a regular non-fat file, return it.
|
|
|
|
const char *buf = mbref.getBufferStart();
|
2021-03-12 02:28:08 +08:00
|
|
|
const auto *hdr = reinterpret_cast<const fat_header *>(buf);
|
2021-03-02 17:20:22 +08:00
|
|
|
if (mbref.getBufferSize() < sizeof(uint32_t) ||
|
2021-03-12 02:28:08 +08:00
|
|
|
read32be(&hdr->magic) != FAT_MAGIC) {
|
2020-11-29 11:38:27 +08:00
|
|
|
if (tar)
|
|
|
|
tar->append(relativeToRoot(path), mbref.getBuffer());
|
2020-04-22 04:37:57 +08:00
|
|
|
return mbref;
|
2020-11-29 11:38:27 +08:00
|
|
|
}
|
2020-04-22 04:37:57 +08:00
|
|
|
|
2020-04-30 06:42:36 +08:00
|
|
|
// Object files and archive files may be fat files, which contains
|
|
|
|
// 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-12 02:28:08 +08:00
|
|
|
const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr));
|
2020-04-30 06:42:36 +08: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");
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (read32be(&arch[i].cputype) != target->cpuType ||
|
|
|
|
read32be(&arch[i].cpusubtype) != target->cpuSubtype)
|
|
|
|
continue;
|
|
|
|
|
|
|
|
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-29 11:38:27 +08:00
|
|
|
if (tar)
|
|
|
|
tar->append(relativeToRoot(path), mbref.getBuffer());
|
2020-04-30 06:42:36 +08:00
|
|
|
return MemoryBufferRef(StringRef(buf + offset, size), path.copy(bAlloc));
|
|
|
|
}
|
|
|
|
|
|
|
|
error("unable to find matching architecture in " + path);
|
2020-04-22 04:37:57 +08:00
|
|
|
return None;
|
2020-04-03 02:54:05 +08:00
|
|
|
}
|
|
|
|
|
2021-03-12 02:28:08 +08:00
|
|
|
InputFile::InputFile(Kind kind, const InterfaceFile &interface)
|
|
|
|
: id(idCount++), fileKind(kind), name(saver.save(interface.getPath())) {}
|
|
|
|
|
2021-04-03 06:46:18 +08:00
|
|
|
template <class Section>
|
|
|
|
void ObjFile::parseSections(ArrayRef<Section> sections) {
|
[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 23:46:07 +08:00
|
|
|
subsections.reserve(sections.size());
|
2020-04-03 02:54:05 +08:00
|
|
|
auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
|
|
|
|
|
2021-04-03 06:46:18 +08:00
|
|
|
for (const Section &sec : sections) {
|
2020-04-03 02:54:05 +08:00
|
|
|
InputSection *isec = make<InputSection>();
|
|
|
|
isec->file = this;
|
2020-08-19 05:37:04 +08:00
|
|
|
isec->name =
|
|
|
|
StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
|
|
|
|
isec->segname =
|
|
|
|
StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
|
[lld-macho] Ensure __bss sections we output have file offset of zero
Summary:
llvm-mc emits `__bss` sections with an offset of zero, but we weren't expecting
that in our input, so we were copying non-zero data from the start of the file and
putting it in `__bss`, with obviously undesirable runtime results. (It appears that
the kernel will copy those nonzero bytes as long as the offset is nonzero, regardless
of whether S_ZERO_FILL is set.)
I debated on whether to make a special ZeroFillSection -- separate from a
regular InputSection -- but it seemed like too much work for now. But I'm happy
to refactor if anyone feels strongly about having it as a separate class.
Depends on D80857.
Reviewers: ruiu, pcc, MaskRay, smeenai, alexshap, gkm, Ktwu, christylee
Reviewed By: smeenai
Subscribers: llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D80859
2020-06-14 11:00:36 +08:00
|
|
|
isec->data = {isZeroFill(sec.flags) ? nullptr : buf + sec.offset,
|
|
|
|
static_cast<size_t>(sec.size)};
|
2020-04-03 02:54:05 +08:00
|
|
|
if (sec.align >= 32)
|
|
|
|
error("alignment " + std::to_string(sec.align) + " of section " +
|
|
|
|
isec->name + " is too large");
|
|
|
|
else
|
|
|
|
isec->align = 1 << sec.align;
|
|
|
|
isec->flags = sec.flags;
|
2020-12-09 09:47:19 +08:00
|
|
|
|
|
|
|
if (!(isDebugSection(isec->flags) &&
|
|
|
|
isec->segname == segment_names::dwarf)) {
|
|
|
|
subsections.push_back({{0, isec}});
|
|
|
|
} else {
|
|
|
|
// Instead of emitting DWARF sections, we emit STABS symbols to the
|
|
|
|
// object files that contain them. We filter them out early to avoid
|
|
|
|
// parsing their relocations unnecessarily. But we must still push an
|
|
|
|
// empty map to ensure the indices line up for the remaining sections.
|
|
|
|
subsections.push_back({});
|
|
|
|
debugSections.push_back(isec);
|
|
|
|
}
|
2020-04-03 02:54:05 +08: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 23:46:07 +08:00
|
|
|
}
|
2020-04-03 02:54:05 +08: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 23:46:07 +08: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-04-07 01:58:37 +08:00
|
|
|
static InputSection *findContainingSubsection(SubsectionMap &map,
|
2021-04-01 06:23:19 +08:00
|
|
|
uint64_t *offset) {
|
|
|
|
auto it = std::prev(llvm::upper_bound(
|
2021-04-07 03:09:14 +08:00
|
|
|
map, *offset, [](uint64_t value, SubsectionEntry subsecEntry) {
|
|
|
|
return value < subsecEntry.offset;
|
2021-04-01 06:23:19 +08:00
|
|
|
}));
|
|
|
|
*offset -= it->offset;
|
|
|
|
return it->isec;
|
2020-04-03 02:54:05 +08:00
|
|
|
}
|
|
|
|
|
2021-04-03 06:46:18 +08:00
|
|
|
template <class Section>
|
|
|
|
static bool validateRelocationInfo(InputFile *file, const Section &sec,
|
2021-01-19 23:44:42 +08:00
|
|
|
relocation_info rel) {
|
2021-03-12 02:28:09 +08:00
|
|
|
const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
|
2021-01-19 23:44:42 +08:00
|
|
|
bool valid = true;
|
2021-02-24 10:41:52 +08:00
|
|
|
auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
|
2021-01-19 23:44:42 +08:00
|
|
|
valid = false;
|
|
|
|
return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
|
|
|
|
std::to_string(rel.r_address) + " of " + sec.segname + "," +
|
2021-02-24 10:41:52 +08:00
|
|
|
sec.sectname + " in " + toString(file))
|
2021-01-19 23: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-24 10:41:54 +08:00
|
|
|
!relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
|
2021-01-19 23:44:42 +08:00
|
|
|
error(message("not allowed in thread-local section, must be UNSIGNED"));
|
|
|
|
if (rel.r_length < 2 || rel.r_length > 3 ||
|
|
|
|
!relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
|
2020-09-27 04:00:22 +08:00
|
|
|
static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
|
2021-01-19 23:44:42 +08:00
|
|
|
error(message("has width " + std::to_string(1 << rel.r_length) +
|
|
|
|
" bytes, but must be " +
|
|
|
|
widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
|
|
|
|
" bytes"));
|
|
|
|
}
|
|
|
|
return valid;
|
|
|
|
}
|
|
|
|
|
2021-04-03 06:46:18 +08:00
|
|
|
template <class Section>
|
|
|
|
void ObjFile::parseRelocations(ArrayRef<Section> sectionHeaders,
|
2021-04-07 01:58:37 +08:00
|
|
|
const Section &sec, SubsectionMap &subsecMap) {
|
2020-04-03 02:54:05 +08:00
|
|
|
auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
|
2020-10-15 00:49:54 +08:00
|
|
|
ArrayRef<relocation_info> relInfos(
|
|
|
|
reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
|
2020-04-03 02:54:05 +08:00
|
|
|
|
2020-10-15 00:49:54 +08: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 23:44:42 +08:00
|
|
|
// datum for each is a symbolic address. The result is the offset
|
|
|
|
// between two addresses.
|
2020-10-15 00:49:54 +08: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.
|
|
|
|
//
|
|
|
|
// 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 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 23:46:07 +08:00
|
|
|
|
2021-03-13 06:26:11 +08:00
|
|
|
int64_t pairedAddend = 0;
|
2021-01-19 23:44:42 +08:00
|
|
|
relocation_info relInfo = relInfos[i];
|
|
|
|
if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
|
|
|
|
pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
|
|
|
|
relInfo = relInfos[++i];
|
|
|
|
}
|
2020-10-15 00:49:54 +08:00
|
|
|
assert(i < relInfos.size());
|
2021-02-24 10:41:52 +08:00
|
|
|
if (!validateRelocationInfo(this, sec, relInfo))
|
2021-01-19 23:44:42 +08:00
|
|
|
continue;
|
2020-10-15 00:49:54 +08: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 23:46:07 +08:00
|
|
|
|
2021-04-21 04:58:06 +08:00
|
|
|
bool isSubtrahend =
|
|
|
|
target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND);
|
2021-04-03 06:46:18 +08:00
|
|
|
int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo);
|
2021-02-28 01:30:19 +08:00
|
|
|
assert(!(embeddedAddend && pairedAddend));
|
2021-03-13 06:26:11 +08:00
|
|
|
int64_t totalAddend = pairedAddend + embeddedAddend;
|
2020-04-03 02:54:05 +08:00
|
|
|
Reloc r;
|
2020-09-13 11:45:00 +08:00
|
|
|
r.type = relInfo.r_type;
|
|
|
|
r.pcrel = relInfo.r_pcrel;
|
|
|
|
r.length = relInfo.r_length;
|
2020-10-15 00:49:54 +08:00
|
|
|
r.offset = relInfo.r_address;
|
2020-09-13 11:45:00 +08:00
|
|
|
if (relInfo.r_extern) {
|
|
|
|
r.referent = symbols[relInfo.r_symbolnum];
|
2021-04-21 04:58:06 +08:00
|
|
|
r.addend = isSubtrahend ? 0 : totalAddend;
|
2020-04-03 02:54:05 +08:00
|
|
|
} else {
|
2021-04-21 04:58:06 +08:00
|
|
|
assert(!isSubtrahend);
|
2021-04-03 06:46:18 +08:00
|
|
|
const Section &referentSec = sectionHeaders[relInfo.r_symbolnum - 1];
|
2021-04-01 06:23:19 +08:00
|
|
|
uint64_t referentOffset;
|
2020-09-13 11:45:00 +08:00
|
|
|
if (relInfo.r_pcrel) {
|
2020-06-14 10:56:04 +08: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-13 11:45:00 +08:00
|
|
|
// that it describes the offset from the start of the referent section.
|
2021-03-12 02:28:11 +08: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-02 01:30:08 +08:00
|
|
|
assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
|
2020-09-13 11:45:00 +08:00
|
|
|
referentOffset =
|
2021-01-19 23:44:42 +08:00
|
|
|
sec.addr + relInfo.r_address + 4 + totalAddend - referentSec.addr;
|
2020-06-14 10:56:04 +08:00
|
|
|
} else {
|
|
|
|
// The addend for a non-pcrel relocation is its absolute address.
|
2021-01-19 23:44:42 +08:00
|
|
|
referentOffset = totalAddend - referentSec.addr;
|
2020-06-14 10:56:04 +08:00
|
|
|
}
|
2021-04-21 04:58:06 +08:00
|
|
|
SubsectionMap &referentSubsecMap = subsections[relInfo.r_symbolnum - 1];
|
2020-09-13 11:45:00 +08:00
|
|
|
r.referent = findContainingSubsection(referentSubsecMap, &referentOffset);
|
|
|
|
r.addend = referentOffset;
|
2020-04-03 02:54:05 +08: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 23:46:07 +08:00
|
|
|
|
2020-05-16 04:42:28 +08:00
|
|
|
InputSection *subsec = findContainingSubsection(subsecMap, &r.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 23:46:07 +08:00
|
|
|
subsec->relocs.push_back(r);
|
2021-03-12 02:28:13 +08:00
|
|
|
|
2021-04-21 04:58:06 +08:00
|
|
|
if (isSubtrahend) {
|
|
|
|
relocation_info minuendInfo = relInfos[++i];
|
2021-03-12 02:28:13 +08:00
|
|
|
// SUBTRACTOR relocations should always be followed by an UNSIGNED one
|
2021-04-21 04:58:06 +08:00
|
|
|
// attached to the same address.
|
|
|
|
assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) &&
|
|
|
|
relInfo.r_address == minuendInfo.r_address);
|
2021-03-12 02:28:13 +08:00
|
|
|
Reloc p;
|
2021-04-21 04:58:06 +08: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;
|
|
|
|
SubsectionMap &referentSubsecMap =
|
|
|
|
subsections[minuendInfo.r_symbolnum - 1];
|
|
|
|
p.referent =
|
|
|
|
findContainingSubsection(referentSubsecMap, &referentOffset);
|
|
|
|
p.addend = referentOffset;
|
|
|
|
}
|
2021-03-12 02:28:13 +08: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 23:46:07 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-03 06:46:18 +08:00
|
|
|
template <class NList>
|
|
|
|
static macho::Symbol *createDefined(const NList &sym, StringRef name,
|
|
|
|
InputSection *isec, uint64_t value,
|
|
|
|
uint64_t size) {
|
[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-18 02:30:18 +08: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 23:28:35 +08: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.
|
[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-18 02:30:18 +08:00
|
|
|
// N_PEXT: Does not occur in input files in practice,
|
|
|
|
// a private extern must be external.
|
[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 23:28:35 +08: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-18 02:30:18 +08:00
|
|
|
|
|
|
|
if (sym.n_type & (N_EXT | N_PEXT)) {
|
|
|
|
assert((sym.n_type & N_EXT) && "invalid input");
|
[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 23:28:35 +08:00
|
|
|
bool isPrivateExtern = sym.n_type & N_PEXT;
|
|
|
|
|
|
|
|
// 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
|
|
|
|
// difference between a symbol that's isWeakDefCanBeHidden or one that's
|
|
|
|
// privateExtern -- neither makes it into the dynamic symbol table. So just
|
|
|
|
// promote isWeakDefCanBeHidden to isPrivateExtern here.
|
|
|
|
if (isWeakDefCanBeHidden)
|
|
|
|
isPrivateExtern = true;
|
|
|
|
|
2021-04-02 08:48:09 +08:00
|
|
|
return symtab->addDefined(name, isec->file, isec, value, size,
|
2021-05-01 04:17:26 +08:00
|
|
|
sym.n_desc & N_WEAK_DEF, isPrivateExtern,
|
|
|
|
sym.n_desc & N_ARM_THUMB_DEF);
|
[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-18 02:30:18 +08:00
|
|
|
}
|
[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 23:28:35 +08:00
|
|
|
|
|
|
|
assert(!isWeakDefCanBeHidden &&
|
|
|
|
"weak_def_can_be_hidden on already-hidden symbol?");
|
2021-04-02 08:48:09 +08:00
|
|
|
return make<Defined>(name, isec->file, isec, value, size,
|
|
|
|
sym.n_desc & N_WEAK_DEF,
|
2021-05-01 04:17:26 +08:00
|
|
|
/*isExternal=*/false, /*isPrivateExtern=*/false,
|
|
|
|
sym.n_desc & N_ARM_THUMB_DEF);
|
2020-09-18 23:40:46 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Absolute symbols are defined symbols that do not have an associated
|
|
|
|
// InputSection. They cannot be weak.
|
2021-04-03 06:46:18 +08:00
|
|
|
template <class NList>
|
|
|
|
static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
|
|
|
|
StringRef name) {
|
[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-18 02:30:18 +08:00
|
|
|
if (sym.n_type & (N_EXT | N_PEXT)) {
|
|
|
|
assert((sym.n_type & N_EXT) && "invalid input");
|
2021-04-02 08:48:09 +08:00
|
|
|
return symtab->addDefined(name, file, nullptr, sym.n_value, /*size=*/0,
|
2021-05-01 04:17:26 +08:00
|
|
|
/*isWeakDef=*/false, sym.n_type & N_PEXT,
|
|
|
|
sym.n_desc & N_ARM_THUMB_DEF);
|
[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-18 02:30:18 +08:00
|
|
|
}
|
2021-04-02 08:48:09 +08:00
|
|
|
return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
|
|
|
|
/*isWeakDef=*/false,
|
2021-05-01 04:17:26 +08:00
|
|
|
/*isExternal=*/false, /*isPrivateExtern=*/false,
|
|
|
|
sym.n_desc & N_ARM_THUMB_DEF);
|
2020-09-18 23:40:46 +08:00
|
|
|
}
|
|
|
|
|
2021-04-03 06:46:18 +08:00
|
|
|
template <class NList>
|
|
|
|
macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,
|
2020-12-02 11:57:37 +08:00
|
|
|
StringRef name) {
|
2020-09-18 23:40:46 +08:00
|
|
|
uint8_t type = sym.n_type & N_TYPE;
|
|
|
|
switch (type) {
|
|
|
|
case N_UNDF:
|
|
|
|
return sym.n_value == 0
|
2021-02-04 02:31:40 +08:00
|
|
|
? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
|
2020-09-18 23:40:46 +08: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-18 02:30:18 +08:00
|
|
|
1 << GET_COMM_ALIGN(sym.n_desc),
|
|
|
|
sym.n_type & N_PEXT);
|
2020-09-18 23:40:46 +08:00
|
|
|
case N_ABS:
|
2021-02-04 02:31:40 +08:00
|
|
|
return createAbsolute(sym, this, name);
|
2020-09-18 23:40:46 +08:00
|
|
|
case N_PBUD:
|
|
|
|
case N_INDR:
|
|
|
|
error("TODO: support symbols of type " + std::to_string(type));
|
|
|
|
return nullptr;
|
|
|
|
case N_SECT:
|
|
|
|
llvm_unreachable(
|
|
|
|
"N_SECT symbols should not be passed to parseNonSectionSymbol");
|
|
|
|
default:
|
|
|
|
llvm_unreachable("invalid symbol type");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-03 06:46:18 +08:00
|
|
|
template <class LP>
|
|
|
|
void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
|
|
|
|
ArrayRef<typename LP::nlist> nList,
|
2020-12-02 11:57:37 +08:00
|
|
|
const char *strtab, bool subsectionsViaSymbols) {
|
2021-04-03 06:46:18 +08:00
|
|
|
using NList = typename LP::nlist;
|
|
|
|
|
2021-04-07 03:09:14 +08:00
|
|
|
// Groups indices of the symbols by the sections that contain them.
|
|
|
|
std::vector<std::vector<uint32_t>> symbolsBySection(subsections.size());
|
2021-04-01 06:23:19 +08:00
|
|
|
symbols.resize(nList.size());
|
2021-04-07 03:09:14 +08:00
|
|
|
for (uint32_t i = 0; i < nList.size(); ++i) {
|
2021-04-03 06:46:18 +08:00
|
|
|
const NList &sym = nList[i];
|
2020-09-18 23:40:46 +08:00
|
|
|
StringRef name = strtab + sym.n_strx;
|
2021-04-07 03:09:14 +08:00
|
|
|
if ((sym.n_type & N_TYPE) == N_SECT) {
|
|
|
|
SubsectionMap &subsecMap = subsections[sym.n_sect - 1];
|
|
|
|
// parseSections() may have chosen not to parse this section.
|
|
|
|
if (subsecMap.empty())
|
|
|
|
continue;
|
|
|
|
symbolsBySection[sym.n_sect - 1].push_back(i);
|
|
|
|
} else {
|
2020-09-18 23:40:46 +08:00
|
|
|
symbols[i] = parseNonSectionSymbol(sym, name);
|
[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 23:46:07 +08:00
|
|
|
}
|
2021-04-07 03:09:14 +08: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 23:46:07 +08:00
|
|
|
|
2021-04-07 03:09:14 +08:00
|
|
|
// Calculate symbol sizes and create subsections by splitting the sections
|
|
|
|
// along symbol boundaries.
|
|
|
|
for (size_t i = 0; i < subsections.size(); ++i) {
|
|
|
|
SubsectionMap &subsecMap = subsections[i];
|
2021-03-06 06:22:57 +08:00
|
|
|
if (subsecMap.empty())
|
|
|
|
continue;
|
|
|
|
|
2021-04-07 03:09:14 +08:00
|
|
|
std::vector<uint32_t> &symbolIndices = symbolsBySection[i];
|
|
|
|
llvm::sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {
|
|
|
|
return nList[lhs].n_value < nList[rhs].n_value;
|
|
|
|
});
|
|
|
|
uint64_t sectionAddr = sectionHeaders[i].addr;
|
|
|
|
|
|
|
|
// We populate subsecMap by repeatedly splitting the last (highest address)
|
|
|
|
// subsection.
|
|
|
|
SubsectionEntry subsecEntry = subsecMap.back();
|
|
|
|
for (size_t j = 0; j < symbolIndices.size(); ++j) {
|
|
|
|
uint32_t symIndex = symbolIndices[j];
|
|
|
|
const NList &sym = nList[symIndex];
|
|
|
|
StringRef name = strtab + sym.n_strx;
|
|
|
|
InputSection *isec = subsecEntry.isec;
|
|
|
|
|
|
|
|
uint64_t subsecAddr = sectionAddr + subsecEntry.offset;
|
|
|
|
uint64_t symbolOffset = sym.n_value - subsecAddr;
|
|
|
|
uint64_t symbolSize =
|
|
|
|
j + 1 < symbolIndices.size()
|
|
|
|
? nList[symbolIndices[j + 1]].n_value - sym.n_value
|
|
|
|
: isec->data.size() - symbolOffset;
|
|
|
|
// There are 3 cases where we do not need to create a new subsection:
|
|
|
|
// 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-07 02:47:57 +08:00
|
|
|
// (The symbolOffset == 0 check covers both this case as well as
|
|
|
|
// the first loop iteration.)
|
2021-04-07 03:09:14 +08:00
|
|
|
// 3. Alternative entry points do not induce new subsections.
|
|
|
|
if (!subsectionsViaSymbols || symbolOffset == 0 ||
|
|
|
|
sym.n_desc & N_ALT_ENTRY) {
|
|
|
|
symbols[symIndex] =
|
|
|
|
createDefined(sym, name, isec, symbolOffset, symbolSize);
|
|
|
|
continue;
|
|
|
|
}
|
[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 23:46:07 +08:00
|
|
|
|
2021-04-07 03:09:14 +08:00
|
|
|
auto *nextIsec = make<InputSection>(*isec);
|
|
|
|
nextIsec->data = isec->data.slice(symbolOffset);
|
[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-07 02:47:57 +08:00
|
|
|
nextIsec->numRefs = 0;
|
|
|
|
nextIsec->canOmitFromOutput = false;
|
2021-04-07 03:09:14 +08:00
|
|
|
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 23:46:07 +08:00
|
|
|
|
2021-04-07 05:52:30 +08:00
|
|
|
// By construction, the symbol will be at offset zero in the new
|
|
|
|
// subsection.
|
2021-04-07 03:09:14 +08:00
|
|
|
symbols[symIndex] =
|
|
|
|
createDefined(sym, name, nextIsec, /*value=*/0, symbolSize);
|
|
|
|
// 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.
|
|
|
|
nextIsec->align = MinAlign(isec->align, sym.n_value);
|
|
|
|
subsecMap.push_back({sym.n_value - sectionAddr, nextIsec});
|
|
|
|
subsecEntry = subsecMap.back();
|
|
|
|
}
|
|
|
|
}
|
2020-04-03 02:54:05 +08:00
|
|
|
}
|
|
|
|
|
2020-08-11 09:47:13 +08:00
|
|
|
OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
|
|
|
|
StringRef sectName)
|
|
|
|
: InputFile(OpaqueKind, mb) {
|
|
|
|
InputSection *isec = make<InputSection>();
|
|
|
|
isec->file = this;
|
|
|
|
isec->name = sectName.take_front(16);
|
|
|
|
isec->segname = segName.take_front(16);
|
|
|
|
const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
|
|
|
|
isec->data = {buf, mb.getBufferSize()};
|
|
|
|
subsections.push_back({{0, isec}});
|
|
|
|
}
|
|
|
|
|
2020-12-02 08:00:48 +08:00
|
|
|
ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName)
|
2020-12-02 06:45:11 +08:00
|
|
|
: InputFile(ObjKind, mb), modTime(modTime) {
|
2020-12-02 08:00:48 +08:00
|
|
|
this->archiveName = std::string(archiveName);
|
2021-04-03 06:46:18 +08:00
|
|
|
if (target->wordSize == 8)
|
|
|
|
parse<LP64>();
|
|
|
|
else
|
|
|
|
parse<ILP32>();
|
|
|
|
}
|
|
|
|
|
|
|
|
template <class LP> void ObjFile::parse() {
|
|
|
|
using Header = typename LP::mach_header;
|
|
|
|
using SegmentCommand = typename LP::segment_command;
|
|
|
|
using Section = typename LP::section;
|
|
|
|
using NList = typename LP::nlist;
|
2020-12-02 08:00:48 +08:00
|
|
|
|
2020-04-03 02:54:05 +08:00
|
|
|
auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
|
2021-04-03 06:46:18 +08:00
|
|
|
auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
|
2020-04-03 02:54:05 +08:00
|
|
|
|
2021-03-12 02:28:08 +08:00
|
|
|
Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
|
2021-04-22 03:43:38 +08:00
|
|
|
if (arch != config->arch()) {
|
2021-02-24 10:42:00 +08:00
|
|
|
error(toString(this) + " has architecture " + getArchitectureName(arch) +
|
|
|
|
" which is incompatible with target architecture " +
|
2021-04-22 03:43:38 +08:00
|
|
|
getArchitectureName(config->arch()));
|
2021-02-24 10:42:00 +08:00
|
|
|
return;
|
|
|
|
}
|
2021-03-05 05:58:21 +08:00
|
|
|
|
2021-05-04 06:31:23 +08:00
|
|
|
if (!checkCompatibility(this))
|
2021-04-21 20:41:14 +08:00
|
|
|
return;
|
2021-02-24 10:42:00 +08:00
|
|
|
|
2020-12-04 05:40:04 +08:00
|
|
|
if (const load_command *cmd = findCommand(hdr, LC_LINKER_OPTION)) {
|
|
|
|
auto *c = reinterpret_cast<const linker_option_command *>(cmd);
|
|
|
|
StringRef data{reinterpret_cast<const char *>(c + 1),
|
|
|
|
c->cmdsize - sizeof(linker_option_command)};
|
|
|
|
parseLCLinkerOption(this, c->count, data);
|
|
|
|
}
|
|
|
|
|
2021-04-03 06:46:18 +08:00
|
|
|
ArrayRef<Section> sectionHeaders;
|
|
|
|
if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {
|
|
|
|
auto *c = reinterpret_cast<const SegmentCommand *>(cmd);
|
|
|
|
sectionHeaders =
|
|
|
|
ArrayRef<Section>{reinterpret_cast<const Section *>(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 23:46:07 +08:00
|
|
|
parseSections(sectionHeaders);
|
2020-04-03 02:54:05 +08:00
|
|
|
}
|
|
|
|
|
2020-04-22 04:37:57 +08:00
|
|
|
// TODO: Error on missing LC_SYMTAB?
|
2020-04-03 02:54:05 +08:00
|
|
|
if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
|
|
|
|
auto *c = reinterpret_cast<const symtab_command *>(cmd);
|
2021-04-03 06:46:18 +08: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 23:46:07 +08:00
|
|
|
const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
|
|
|
|
bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
|
2021-04-03 06:46:18 +08:00
|
|
|
parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);
|
2020-04-03 02:54:05 +08: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 23:46:07 +08:00
|
|
|
// parsed all the symbols.
|
|
|
|
for (size_t i = 0, n = subsections.size(); i < n; ++i)
|
2020-12-09 09:47:19 +08:00
|
|
|
if (!subsections[i].empty())
|
2021-04-03 06:46:18 +08:00
|
|
|
parseRelocations(sectionHeaders, sectionHeaders[i], subsections[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-02 06:45:01 +08:00
|
|
|
|
|
|
|
parseDebugInfo();
|
|
|
|
}
|
|
|
|
|
|
|
|
void ObjFile::parseDebugInfo() {
|
|
|
|
std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
|
|
|
|
if (!dObj)
|
|
|
|
return;
|
|
|
|
|
|
|
|
auto *ctx = make<DWARFContext>(
|
|
|
|
std::move(dObj), "",
|
2020-12-02 08:00:48 +08: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-02 06:45:01 +08:00
|
|
|
[&](Error warning) {
|
2020-12-02 08:00:48 +08: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-02 06: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-06 06:22:56 +08: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-02 06:45:01 +08:00
|
|
|
auto it = units.begin();
|
|
|
|
compileUnit = it->get();
|
2020-04-03 02:54:05 +08:00
|
|
|
}
|
|
|
|
|
2020-08-14 04:48:47 +08:00
|
|
|
// The path can point to either a dylib or a .tbd file.
|
|
|
|
static Optional<DylibFile *> loadDylib(StringRef path, DylibFile *umbrella) {
|
2021-03-02 17:20:22 +08:00
|
|
|
Optional<MemoryBufferRef> mbref = readFile(path);
|
2020-08-14 04:48:47 +08:00
|
|
|
if (!mbref) {
|
|
|
|
error("could not read dylib file at " + path);
|
|
|
|
return {};
|
|
|
|
}
|
2020-12-10 14:29:28 +08:00
|
|
|
return loadDylib(*mbref, umbrella);
|
2020-08-14 04:48:47 +08: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-25 12:47:22 +08: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-14 04:48:47 +08:00
|
|
|
//
|
|
|
|
// Re-exports can either refer to on-disk files, or to documents within .tbd
|
|
|
|
// files.
|
[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-25 12:47:22 +08:00
|
|
|
static Optional<DylibFile *>
|
|
|
|
findDylib(StringRef path, DylibFile *umbrella,
|
|
|
|
const InterfaceFile *currentTopLevelTapi) {
|
2020-08-14 04:48:47 +08:00
|
|
|
if (path::is_absolute(path, path::Style::posix))
|
|
|
|
for (StringRef root : config->systemLibraryRoots)
|
|
|
|
if (Optional<std::string> dylibPath =
|
|
|
|
resolveDylibPath((root + path).str()))
|
|
|
|
return loadDylib(*dylibPath, umbrella);
|
|
|
|
|
2021-03-02 04:25:10 +08:00
|
|
|
// TODO: Expand @loader_path, @executable_path, @rpath etc, handle -dylib_path
|
2020-08-14 04:48:47 +08:00
|
|
|
|
2020-09-24 11:09:49 +08:00
|
|
|
if (currentTopLevelTapi) {
|
2020-08-14 04:48:47 +08:00
|
|
|
for (InterfaceFile &child :
|
|
|
|
make_pointee_range(currentTopLevelTapi->documents())) {
|
2021-03-05 03:36:46 +08:00
|
|
|
assert(child.documents().empty());
|
2020-08-14 04:48:47 +08:00
|
|
|
if (path == child.getInstallName())
|
|
|
|
return make<DylibFile>(child, umbrella);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Optional<std::string> dylibPath = resolveDylibPath(path))
|
|
|
|
return loadDylib(*dylibPath, umbrella);
|
|
|
|
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
|
2020-12-10 07: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 13:49:03 +08: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-10 07:08:05 +08:00
|
|
|
}
|
|
|
|
|
[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-25 12:47:22 +08:00
|
|
|
void loadReexport(StringRef path, DylibFile *umbrella,
|
|
|
|
const InterfaceFile *currentTopLevelTapi) {
|
|
|
|
Optional<DylibFile *> reexport =
|
|
|
|
findDylib(path, umbrella, currentTopLevelTapi);
|
2021-03-02 04:25:10 +08:00
|
|
|
if (!reexport)
|
|
|
|
error("unable to locate re-export with install name " + path);
|
|
|
|
else if (isImplicitlyLinked(path))
|
2020-12-15 06:59:22 +08:00
|
|
|
inputFiles.insert(*reexport);
|
2020-12-10 07:08:05 +08:00
|
|
|
}
|
|
|
|
|
2021-02-23 02:03:02 +08:00
|
|
|
DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
|
|
|
|
bool isBundleLoader)
|
|
|
|
: InputFile(DylibKind, mb), refState(RefState::Unreferenced),
|
|
|
|
isBundleLoader(isBundleLoader) {
|
|
|
|
assert(!isBundleLoader || !umbrella);
|
2020-04-24 11:16:49 +08:00
|
|
|
if (umbrella == nullptr)
|
|
|
|
umbrella = this;
|
|
|
|
|
2020-04-22 04:37:57 +08:00
|
|
|
auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
|
2021-05-04 06:31:23 +08:00
|
|
|
auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
|
2020-04-22 04:37:57 +08:00
|
|
|
|
|
|
|
// Initialize dylibName.
|
|
|
|
if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
|
|
|
|
auto *c = reinterpret_cast<const dylib_command *>(cmd);
|
2020-12-16 04:25:15 +08:00
|
|
|
currentVersion = read32le(&c->dylib.current_version);
|
|
|
|
compatibilityVersion = read32le(&c->dylib.compatibility_version);
|
2020-04-22 04:37:57 +08:00
|
|
|
dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
|
2021-02-23 02:03:02 +08:00
|
|
|
} else if (!isBundleLoader) {
|
|
|
|
// macho_executable and macho_bundle don't have LC_ID_DYLIB,
|
|
|
|
// so it's OK.
|
2020-12-02 08:00:48 +08:00
|
|
|
error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
|
2020-04-22 04:37:57 +08:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-05-04 06:31:23 +08:00
|
|
|
if (!checkCompatibility(this))
|
2021-04-21 20:41:14 +08:00
|
|
|
return;
|
2021-03-05 05:58:21 +08:00
|
|
|
|
2020-04-22 04:37:57 +08:00
|
|
|
// Initialize symbols.
|
2020-12-10 07:08:05 +08:00
|
|
|
DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
|
[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-23 11:00:57 +08:00
|
|
|
if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
|
|
|
|
auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
|
|
|
|
parseTrie(buf + c->export_off, c->export_size,
|
|
|
|
[&](const Twine &name, uint64_t flags) {
|
2020-07-25 06:55:25 +08:00
|
|
|
bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
|
2020-08-13 10:50:09 +08:00
|
|
|
bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
|
2020-12-10 07:08:05 +08:00
|
|
|
symbols.push_back(symtab->addDylib(
|
|
|
|
saver.save(name), exportingFile, isWeakDef, isTlv));
|
[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-23 11:00:57 +08:00
|
|
|
});
|
|
|
|
} else {
|
2020-12-02 08:00:48 +08:00
|
|
|
error("LC_DYLD_INFO_ONLY not found in " + toString(this));
|
2020-04-24 11:16:49 +08:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-05-04 06:31:23 +08:00
|
|
|
const uint8_t *p =
|
|
|
|
reinterpret_cast<const uint8_t *>(hdr) + target->headerSize;
|
2020-04-24 11:16:49 +08: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-02 04:25:10 +08: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-05 03:36:44 +08:00
|
|
|
loadReexport(reexportPath, exportingFile, nullptr);
|
2021-03-02 04:25:10 +08: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);
|
[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-25 12:47:22 +08:00
|
|
|
Optional<DylibFile *> dylib = findDylib(dylibPath, umbrella, nullptr);
|
2021-03-02 04:25:10 +08:00
|
|
|
if (!dylib)
|
|
|
|
error(Twine("unable to locate library '") + dylibPath +
|
|
|
|
"' loaded from '" + toString(this) + "' for -flat_namespace");
|
|
|
|
}
|
2020-04-22 04:37:57 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-23 02:03:02 +08:00
|
|
|
DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
|
|
|
|
bool isBundleLoader)
|
|
|
|
: InputFile(DylibKind, interface), refState(RefState::Unreferenced),
|
|
|
|
isBundleLoader(isBundleLoader) {
|
|
|
|
// FIXME: Add test for the missing TBD code path.
|
|
|
|
|
2020-06-06 02:18:33 +08:00
|
|
|
if (umbrella == nullptr)
|
|
|
|
umbrella = this;
|
|
|
|
|
2021-03-05 03:36:49 +08:00
|
|
|
dylibName = saver.save(interface.getInstallName());
|
|
|
|
compatibilityVersion = interface.getCompatibilityVersion().rawValue();
|
|
|
|
currentVersion = interface.getCurrentVersion().rawValue();
|
|
|
|
|
2021-04-21 07:54:41 +08:00
|
|
|
// Some versions of XCode ship with .tbd files that don't have the right
|
|
|
|
// platform settings.
|
|
|
|
static constexpr std::array<StringRef, 3> skipPlatformChecks{
|
|
|
|
"/usr/lib/system/libsystem_kernel.dylib",
|
|
|
|
"/usr/lib/system/libsystem_platform.dylib",
|
|
|
|
"/usr/lib/system/libsystem_pthread.dylib"};
|
|
|
|
|
|
|
|
if (!is_contained(skipPlatformChecks, dylibName) &&
|
2021-04-21 20:41:14 +08:00
|
|
|
!is_contained(interface.targets(), config->platformInfo.target)) {
|
2021-02-24 10:42:00 +08:00
|
|
|
error(toString(this) + " is incompatible with " +
|
2021-04-21 20:41:14 +08:00
|
|
|
std::string(config->platformInfo.target));
|
2021-02-24 10:42:00 +08:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-12-10 07:08:05 +08:00
|
|
|
DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella;
|
2020-08-13 10:50:10 +08:00
|
|
|
auto addSymbol = [&](const Twine &name) -> void {
|
2020-12-10 07:08:05 +08:00
|
|
|
symbols.push_back(symtab->addDylib(saver.save(name), exportingFile,
|
2020-08-13 10:50:10 +08:00
|
|
|
/*isWeakDef=*/false,
|
|
|
|
/*isTlv=*/false));
|
|
|
|
};
|
2020-06-06 02:18:33 +08:00
|
|
|
// TODO(compnerd) filter out symbols based on the target platform
|
2020-08-13 10:50:09 +08:00
|
|
|
// TODO: handle weak defs, thread locals
|
2021-03-10 12:15:29 +08:00
|
|
|
for (const auto *symbol : interface.symbols()) {
|
2021-04-22 03:43:38 +08:00
|
|
|
if (!symbol->getArchitectures().has(config->arch()))
|
2020-08-13 10:50:10 +08:00
|
|
|
continue;
|
|
|
|
|
|
|
|
switch (symbol->getKind()) {
|
|
|
|
case SymbolKind::GlobalSymbol:
|
|
|
|
addSymbol(symbol->getName());
|
|
|
|
break;
|
|
|
|
case SymbolKind::ObjectiveCClass:
|
|
|
|
// XXX ld64 only creates these symbols when -ObjC is passed in. We may
|
|
|
|
// want to emulate that.
|
2020-08-19 05:37:04 +08:00
|
|
|
addSymbol(objc::klass + symbol->getName());
|
|
|
|
addSymbol(objc::metaclass + symbol->getName());
|
2020-08-13 10:50:10 +08:00
|
|
|
break;
|
|
|
|
case SymbolKind::ObjectiveCClassEHType:
|
2020-08-19 05:37:04 +08:00
|
|
|
addSymbol(objc::ehtype + symbol->getName());
|
2020-08-13 10:50:10 +08:00
|
|
|
break;
|
|
|
|
case SymbolKind::ObjectiveCInstanceVariable:
|
2020-08-19 05:37:04 +08:00
|
|
|
addSymbol(objc::ivar + symbol->getName());
|
2020-08-13 10:50:10 +08:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
2020-08-14 04:48:47 +08:00
|
|
|
|
[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-25 12:47:22 +08:00
|
|
|
const InterfaceFile *topLevel =
|
|
|
|
interface.getParent() == nullptr ? &interface : interface.getParent();
|
2020-08-14 04:48:47 +08:00
|
|
|
|
2021-03-05 03:36:47 +08:00
|
|
|
for (InterfaceFileRef intfRef : interface.reexportedLibraries()) {
|
2021-03-10 12:15:29 +08:00
|
|
|
InterfaceFile::const_target_range targets = intfRef.targets();
|
2021-04-21 07:54:41 +08:00
|
|
|
if (is_contained(skipPlatformChecks, intfRef.getInstallName()) ||
|
2021-04-21 20:41:14 +08:00
|
|
|
is_contained(targets, config->platformInfo.target))
|
2021-03-05 03:36:47 +08:00
|
|
|
loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
|
|
|
|
}
|
2020-06-06 02:18:33 +08:00
|
|
|
}
|
|
|
|
|
2021-01-10 00:58:19 +08:00
|
|
|
ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
|
2020-05-15 03:43:51 +08:00
|
|
|
: InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {
|
|
|
|
for (const object::Archive::Symbol &sym : file->symbols())
|
|
|
|
symtab->addLazy(sym.getName(), this, sym);
|
|
|
|
}
|
|
|
|
|
|
|
|
void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
|
|
|
|
object::Archive::Child c =
|
|
|
|
CHECK(sym.getMember(), toString(this) +
|
|
|
|
": could not get the member for symbol " +
|
2020-11-20 23:14:57 +08:00
|
|
|
toMachOString(sym));
|
2020-05-15 03:43:51 +08:00
|
|
|
|
|
|
|
if (!seen.insert(c.getChildOffset()).second)
|
|
|
|
return;
|
|
|
|
|
|
|
|
MemoryBufferRef mb =
|
|
|
|
CHECK(c.getMemoryBufferRef(),
|
|
|
|
toString(this) +
|
|
|
|
": could not get the buffer for the member defining symbol " +
|
2020-11-20 23:14:57 +08:00
|
|
|
toMachOString(sym));
|
2020-12-02 06:45:11 +08:00
|
|
|
|
2020-12-02 12:31:57 +08:00
|
|
|
if (tar && c.getParent()->isThin())
|
|
|
|
tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer());
|
|
|
|
|
2020-12-02 06:45:11 +08:00
|
|
|
uint32_t modTime = toTimeT(
|
|
|
|
CHECK(c.getLastModified(), toString(this) +
|
|
|
|
": could not get the modification time "
|
|
|
|
"for the member defining symbol " +
|
2020-11-20 23:14:57 +08:00
|
|
|
toMachOString(sym)));
|
2020-12-02 06:45:11 +08:00
|
|
|
|
2021-04-30 21:30:46 +08:00
|
|
|
// `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile>
|
2020-12-03 07:59:00 +08:00
|
|
|
// and become invalid after that call. Copy it to the stack so we can refer
|
|
|
|
// to it later.
|
2021-04-30 21:30:46 +08:00
|
|
|
const object::Archive::Symbol symCopy = sym;
|
2020-12-03 07:59:00 +08:00
|
|
|
|
2021-02-04 02:31:42 +08:00
|
|
|
if (Optional<InputFile *> file =
|
|
|
|
loadArchiveMember(mb, modTime, getName(), /*objCOnly=*/false)) {
|
|
|
|
inputFiles.insert(*file);
|
2021-04-30 21:30:46 +08:00
|
|
|
// ld64 doesn't demangle sym here even with -demangle.
|
|
|
|
// Match that: intentionally don't call toMachOString().
|
|
|
|
printArchiveMemberLoad(symCopy.getName(), *file);
|
2020-12-03 06:12:51 +08:00
|
|
|
}
|
2020-05-15 03:43:51 +08:00
|
|
|
}
|
|
|
|
|
[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-26 02:27:40 +08:00
|
|
|
static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
|
|
|
|
BitcodeFile &file) {
|
|
|
|
StringRef name = saver.save(objSym.getName());
|
|
|
|
|
|
|
|
// TODO: support weak references
|
|
|
|
if (objSym.isUndefined())
|
|
|
|
return symtab->addUndefined(name, &file, /*isWeakRef=*/false);
|
|
|
|
|
|
|
|
assert(!objSym.isCommon() && "TODO: support common symbols in LTO");
|
|
|
|
|
|
|
|
// 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;
|
|
|
|
}
|
|
|
|
|
|
|
|
return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
|
2021-05-01 04:17:26 +08:00
|
|
|
/*size=*/0, objSym.isWeak(), isPrivateExtern,
|
|
|
|
/*isThumb=*/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-26 02:27:40 +08:00
|
|
|
}
|
|
|
|
|
2020-10-27 10:18:29 +08:00
|
|
|
BitcodeFile::BitcodeFile(MemoryBufferRef mbref)
|
|
|
|
: InputFile(BitcodeKind, mbref) {
|
|
|
|
obj = check(lto::InputFile::create(mbref));
|
[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-26 02:27:40 +08: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.
|
|
|
|
for (const lto::InputFile::Symbol &objSym : obj->symbols())
|
|
|
|
symbols.push_back(createBitcodeSymbol(objSym, *this));
|
2020-10-27 10:18:29 +08:00
|
|
|
}
|
2021-04-03 06:46:18 +08:00
|
|
|
|
|
|
|
template void ObjFile::parse<LP64>();
|