Skip to content

Commit a954bb1

Browse files
committed
[ELF] Add --why-extract= to query why archive members/lazy object files are extracted
Similar to D69607 but for archive member extraction unrelated to GC. This patch adds --why-extract=. Prior art: GNU ld -M prints ``` Archive member included to satisfy reference by file (symbol) a.a(a.o) main.o (a) b.a(b.o) (b()) ``` -M is mainly for input section/symbol assignment <-> output section mapping (often huge output) and the information may appear ad-hoc. Apple ld64 ``` __Z1bv forced load of b.a(b.o) _a forced load of a.a(a.o) ``` It doesn't say the reference file. Arm's proprietary linker ``` Selecting member vsnprintf.o(c_wfu.l) to define vsnprintf. ... Loading member vsnprintf.o from c_wfu.l. definition: vsnprintf reference : _printf_a ``` --- --why-extract= gives the user the full data (which is much shorter than GNU ld -Map). It is easy to track a chain of references to one archive member with a one-liner, e.g. ``` % ld.lld main.o a_b.a b_c.a c.a -o /dev/null --why-extract=- | tee stdout reference extracted symbol main.o a_b.a(a_b.o) a a_b.a(a_b.o) b_c.a(b_c.o) b() b_c.a(b_c.o) c.a(c.o) c() % ruby -ane 'BEGIN{p={}}; p[$F[1]]=[$F[0],$F[2]] if $.>1; END{x="c.a(c.o)"; while y=p[x]; puts "#{y[0]} extracts #{x} to resolve #{y[1]}"; x=y[0] end}' stdout b_c.a(b_c.o) extracts c.a(c.o) to resolve c() a_b.a(a_b.o) extracts b_c.a(b_c.o) to resolve b() main.o extracts a_b.a(a_b.o) to resolve a ``` Archive member extraction happens before --gc-sections, so this may not be a live path under --gc-sections, but I think it is a good approximation in practice. * Specifying a file avoids output interleaving with --verbose. * Required `=` prevents accidental overwrite of an input if the user forgets `=`. (Most of compiler drivers' long options accept `=` but not ` `) Differential Revision: https://reviews.llvm.org/D109572
1 parent ecd52a5 commit a954bb1

File tree

11 files changed

+150
-9
lines changed

11 files changed

+150
-9
lines changed

lld/ELF/Config.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@ struct Configuration {
127127
llvm::StringRef sysroot;
128128
llvm::StringRef thinLTOCacheDir;
129129
llvm::StringRef thinLTOIndexOnlyArg;
130+
llvm::StringRef whyExtract;
130131
llvm::StringRef ltoBasicBlockSections;
131132
std::pair<llvm::StringRef, llvm::StringRef> thinLTOObjectSuffixReplace;
132133
std::pair<llvm::StringRef, llvm::StringRef> thinLTOPrefixReplace;

lld/ELF/Driver.cpp

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ bool elf::link(ArrayRef<const char *> args, bool canExitEarly,
9494
objectFiles.clear();
9595
sharedFiles.clear();
9696
backwardReferences.clear();
97+
whyExtract.clear();
9798

9899
tar = nullptr;
99100
memset(&in, 0, sizeof(in));
@@ -1171,6 +1172,7 @@ static void readConfigs(opt::InputArgList &args) {
11711172
config->warnCommon = args.hasFlag(OPT_warn_common, OPT_no_warn_common, false);
11721173
config->warnSymbolOrdering =
11731174
args.hasFlag(OPT_warn_symbol_ordering, OPT_no_warn_symbol_ordering, true);
1175+
config->whyExtract = args.getLastArgValue(OPT_why_extract);
11741176
config->zCombreloc = getZFlag(args, "combreloc", "nocombreloc", true);
11751177
config->zCopyreloc = getZFlag(args, "copyreloc", "nocopyreloc", true);
11761178
config->zForceBti = hasZOption(args, "force-bti");
@@ -1696,13 +1698,16 @@ static void excludeLibs(opt::InputArgList &args) {
16961698
}
16971699

16981700
// Force Sym to be entered in the output.
1699-
static void handleUndefined(Symbol *sym) {
1701+
static void handleUndefined(Symbol *sym, const char *option) {
17001702
// Since a symbol may not be used inside the program, LTO may
17011703
// eliminate it. Mark the symbol as "used" to prevent it.
17021704
sym->isUsedInRegularObj = true;
17031705

1704-
if (sym->isLazy())
1705-
sym->fetch();
1706+
if (!sym->isLazy())
1707+
return;
1708+
sym->fetch();
1709+
if (!config->whyExtract.empty())
1710+
whyExtract.emplace_back(option, sym->file, *sym);
17061711
}
17071712

17081713
// As an extension to GNU linkers, lld supports a variant of `-u`
@@ -1725,7 +1730,7 @@ static void handleUndefinedGlob(StringRef arg) {
17251730
}
17261731

17271732
for (Symbol *sym : syms)
1728-
handleUndefined(sym);
1733+
handleUndefined(sym, "--undefined-glob");
17291734
}
17301735

17311736
static void handleLibcall(StringRef name) {
@@ -2192,6 +2197,9 @@ template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
21922197
e.message());
21932198
if (auto e = tryCreateFile(config->mapFile))
21942199
error("cannot open map file " + config->mapFile + ": " + e.message());
2200+
if (auto e = tryCreateFile(config->whyExtract))
2201+
error("cannot open --why-extract= file " + config->whyExtract + ": " +
2202+
e.message());
21952203
}
21962204
if (errorCount())
21972205
return;
@@ -2246,7 +2254,7 @@ template <class ELFT> void LinkerDriver::link(opt::InputArgList &args) {
22462254

22472255
// If an entry symbol is in a static archive, pull out that file now.
22482256
if (Symbol *sym = symtab->find(config->entry))
2249-
handleUndefined(sym);
2257+
handleUndefined(sym, "--entry");
22502258

22512259
// Handle the `--undefined-glob <pattern>` options.
22522260
for (StringRef pat : args::getStrings(args, OPT_undefined_glob))

lld/ELF/MapFile.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,25 @@ void elf::writeMapFile() {
215215
}
216216
}
217217

218+
void elf::writeWhyExtract() {
219+
if (config->whyExtract.empty())
220+
return;
221+
222+
std::error_code ec;
223+
raw_fd_ostream os(config->whyExtract, ec, sys::fs::OF_None);
224+
if (ec) {
225+
error("cannot open --why-extract= file " + config->whyExtract + ": " +
226+
ec.message());
227+
return;
228+
}
229+
230+
os << "reference\textracted\tsymbol\n";
231+
for (auto &entry : whyExtract) {
232+
os << std::get<0>(entry) << '\t' << toString(std::get<1>(entry)) << '\t'
233+
<< toString(std::get<2>(entry)) << '\n';
234+
}
235+
}
236+
218237
static void print(StringRef a, StringRef b) {
219238
lld::outs() << left_justify(a, 49) << " " << b << "\n";
220239
}

lld/ELF/MapFile.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
namespace lld {
1313
namespace elf {
1414
void writeMapFile();
15+
void writeWhyExtract();
1516
void writeCrossReferenceTable();
1617
void writeArchiveStats();
1718
} // namespace elf

lld/ELF/Options.td

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,8 @@ defm whole_archive: B<"whole-archive",
492492
"Force load of all members in a static library",
493493
"Do not force load of all members in a static library (default)">;
494494

495+
def why_extract: JJ<"why-extract=">, HelpText<"Print to a file about why archive members are extracted">;
496+
495497
defm wrap : Eq<"wrap", "Redirect symbol references to __wrap_symbol and "
496498
"__real_symbol references to symbol">,
497499
MetaVarName<"<symbol>">;

lld/ELF/Symbols.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ Defined *ElfSym::riscvGlobalPointer;
6464
Defined *ElfSym::tlsModuleBase;
6565
DenseMap<const Symbol *, std::pair<const InputFile *, const InputFile *>>
6666
elf::backwardReferences;
67+
SmallVector<std::tuple<std::string, const InputFile *, const Symbol &>, 0>
68+
elf::whyExtract;
6769

6870
static uint64_t getSymVA(const Symbol &sym, int64_t &addend) {
6971
switch (sym.kind()) {
@@ -321,6 +323,11 @@ void elf::printTraceSymbol(const Symbol *sym) {
321323
message(toString(sym->file) + s + sym->getName());
322324
}
323325

326+
static void recordWhyExtract(const InputFile *reference,
327+
const InputFile &extracted, const Symbol &sym) {
328+
whyExtract.emplace_back(toString(reference), &extracted, sym);
329+
}
330+
324331
void elf::maybeWarnUnorderableSymbol(const Symbol *sym) {
325332
if (!config->warnSymbolOrdering)
326333
return;
@@ -533,6 +540,9 @@ void Symbol::resolveUndefined(const Undefined &other) {
533540
file->groupId < other.file->groupId;
534541
fetch();
535542

543+
if (!config->whyExtract.empty())
544+
recordWhyExtract(other.file, *file, *this);
545+
536546
// We don't report backward references to weak symbols as they can be
537547
// overridden later.
538548
//
@@ -742,7 +752,10 @@ template <class LazyT> void Symbol::resolveLazy(const LazyT &other) {
742752
return;
743753
}
744754

755+
const InputFile *oldFile = file;
745756
other.fetch();
757+
if (!config->whyExtract.empty())
758+
recordWhyExtract(oldFile, *file, *this);
746759
}
747760

748761
void Symbol::resolveShared(const SharedSymbol &other) {

lld/ELF/Symbols.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
#include "llvm/ADT/DenseMap.h"
2121
#include "llvm/Object/Archive.h"
2222
#include "llvm/Object/ELF.h"
23+
#include <tuple>
2324

2425
namespace lld {
2526
// Returns a string representation for a symbol for diagnostics.
@@ -582,6 +583,11 @@ extern llvm::DenseMap<const Symbol *,
582583
std::pair<const InputFile *, const InputFile *>>
583584
backwardReferences;
584585

586+
// A tuple of (reference, extractedFile, sym). Used by --why-extract=.
587+
extern SmallVector<std::tuple<std::string, const InputFile *, const Symbol &>,
588+
0>
589+
whyExtract;
590+
585591
} // namespace elf
586592
} // namespace lld
587593

lld/ELF/Writer.cpp

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -622,11 +622,12 @@ template <class ELFT> void Writer<ELFT>::run() {
622622
for (OutputSection *sec : outputSections)
623623
sec->addr = 0;
624624

625-
// Handle --print-map(-M)/--Map, --cref and --print-archive-stats=. Dump them
626-
// before checkSections() because the files may be useful in case
627-
// checkSections() or openFile() fails, for example, due to an erroneous file
628-
// size.
625+
// Handle --print-map(-M)/--Map, --why-extract=, --cref and
626+
// --print-archive-stats=. Dump them before checkSections() because the files
627+
// may be useful in case checkSections() or openFile() fails, for example, due
628+
// to an erroneous file size.
629629
writeMapFile();
630+
writeWhyExtract();
630631
writeCrossReferenceTable();
631632
writeArchiveStats();
632633

lld/docs/ReleaseNotes.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ ELF Improvements
2626

2727
* ``--export-dynamic-symbol-list`` has been added.
2828
(`D107317 <https://reviews.llvm.org/D107317>`_)
29+
* ``--why-extract`` has been added to query why archive members/lazy object files are extracted.
30+
(`D109572 <https://reviews.llvm.org/D109572>`_)
2931
* ``e_entry`` no longer falls back to the address of ``.text`` if the entry symbol does not exist.
3032
Instead, a value of 0 will be written.
3133
(`D110014 <https://reviews.llvm.org/D110014>`_)

lld/docs/ld.lld.1

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -658,6 +658,8 @@ linkers, and may be removed in the future.
658658
Report unresolved symbols as warnings.
659659
.It Fl -whole-archive
660660
Force load of all members in a static library.
661+
.It Fl -why-extract Ns = Ns Ar file
662+
Print to a file about why archive members are extracted.
661663
.It Fl -wrap Ns = Ns Ar symbol
662664
Redirect
663665
.Ar symbol

lld/test/ELF/why-extract.s

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# REQUIRES: x86
2+
3+
# RUN: rm -rf %t && split-file %s %t
4+
# RUN: llvm-mc -filetype=obj -triple=x86_64 %t/main.s -o %t/main.o
5+
# RUN: llvm-mc -filetype=obj -triple=x86_64 %t/a.s -o %t/a.o
6+
# RUN: llvm-mc -filetype=obj -triple=x86_64 %t/a_b.s -o %t/a_b.o
7+
# RUN: llvm-mc -filetype=obj -triple=x86_64 %t/b.s -o %t/b.o
8+
# RUN: llvm-ar rc %t/a.a %t/a.o
9+
# RUN: llvm-ar rc %t/a_b.a %t/a_b.o
10+
# RUN: llvm-ar rc %t/b.a %t/b.o
11+
# RUN: cd %t
12+
13+
## Nothing is extracted from an archive. The file is created with just a header.
14+
# RUN: ld.lld main.o a.o b.a -o /dev/null --why-extract=why1.txt
15+
# RUN: FileCheck %s --input-file=why1.txt --check-prefix=CHECK1 --match-full-lines --strict-whitespace
16+
17+
# CHECK1:reference extracted symbol
18+
# CHECK1-NOT:{{.}}
19+
20+
## Some archive members are extracted.
21+
# RUN: ld.lld main.o a_b.a b.a -o /dev/null --why-extract=why2.txt
22+
# RUN: FileCheck %s --input-file=why2.txt --check-prefix=CHECK2 --match-full-lines --strict-whitespace
23+
24+
# CHECK2:reference extracted symbol
25+
# CHECK2-NEXT:main.o a_b.a(a_b.o) a
26+
# CHECK2-NEXT:a_b.a(a_b.o) b.a(b.o) b()
27+
28+
## Check that backward references are supported.
29+
## - means stdout.
30+
# RUN: ld.lld b.a a_b.a main.o -o /dev/null --why-extract=- | FileCheck %s --check-prefix=CHECK3
31+
32+
# CHECK3:reference extracted symbol
33+
# CHECK3-NEXT:a_b.a(a_b.o) b.a(b.o) b()
34+
# CHECK3-NEXT:main.o a_b.a(a_b.o) a
35+
36+
# RUN: ld.lld main.o a_b.a b.a -o /dev/null --no-demangle --why-extract=- | FileCheck %s --check-prefix=MANGLED
37+
38+
# MANGLED: a_b.a(a_b.o) b.a(b.o) _Z1bv
39+
40+
# RUN: ld.lld main.o a.a b.a -o /dev/null -u _Z1bv --why-extract=- | FileCheck %s --check-prefix=UNDEFINED
41+
42+
## We insert -u symbol before processing other files, so its name is <internal>.
43+
## This is not ideal.
44+
# UNDEFINED: <internal> b.a(b.o) b()
45+
46+
# RUN: ld.lld main.o a.a b.a -o /dev/null --undefined-glob '_Z1b*' --why-extract=- | FileCheck %s --check-prefix=UNDEFINED_GLOB
47+
48+
# UNDEFINED_GLOB: --undefined-glob b.a(b.o) b()
49+
50+
# RUN: ld.lld main.o a.a b.a -o /dev/null -e _Z1bv --why-extract=- | FileCheck %s --check-prefix=ENTRY
51+
52+
# ENTRY: --entry b.a(b.o) b()
53+
54+
# RUN: ld.lld main.o b.a -o /dev/null -T a.lds --why-extract=- | FileCheck %s --check-prefix=SCRIPT
55+
56+
# SCRIPT: <internal> b.a(b.o) b()
57+
58+
# RUN: ld.lld main.o --start-lib a_b.o b.o --end-lib -o /dev/null --why-extract=- | FileCheck %s --check-prefix=LAZY
59+
60+
# LAZY: main.o a_b.o a
61+
# LAZY: a_b.o b.o b()
62+
63+
# RUN: not ld.lld -shared main.o -o /dev/null --why-extract=/ 2>&1 | FileCheck %s --check-prefix=ERR
64+
65+
# ERR: error: cannot open --why-extract= file /: {{.*}}
66+
67+
#--- main.s
68+
.globl _start
69+
_start:
70+
call a
71+
72+
#--- a.s
73+
.globl a
74+
a:
75+
76+
#--- a_b.s
77+
.globl a
78+
a:
79+
call _Z1bv
80+
81+
#--- b.s
82+
.globl _Z1bv
83+
_Z1bv:
84+
85+
#--- a.lds
86+
a = _Z1bv;

0 commit comments

Comments
 (0)