1//===- MapFile.cpp --------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the -Map option. It shows lists in order and
10// hierarchically the output sections, input sections, input files and
11// symbol:
12//
13// Address Size Align Out In Symbol
14// 00201000 00000015 4 .text
15// 00201000 0000000e 4 test.o:(.text)
16// 0020100e 00000000 0 local
17// 00201005 00000000 0 f(int)
18//
19//===----------------------------------------------------------------------===//
20
21#include "MapFile.h"
22#include "InputFiles.h"
23#include "LinkerScript.h"
24#include "OutputSections.h"
25#include "Symbols.h"
26#include "SyntheticSections.h"
27#include "llvm/ADT/MapVector.h"
28#include "llvm/ADT/SetVector.h"
29#include "llvm/ADT/SmallPtrSet.h"
30#include "llvm/Support/Parallel.h"
31#include "llvm/Support/TimeProfiler.h"
32#include "llvm/Support/raw_ostream.h"
33
34using namespace llvm;
35using namespace llvm::object;
36using namespace lld;
37using namespace lld::elf;
38
39using SymbolMapTy = DenseMap<const SectionBase *,
40 SmallVector<std::pair<Defined *, uint64_t>, 0>>;
41
42static constexpr char indent8[] = " "; // 8 spaces
43static constexpr char indent16[] = " "; // 16 spaces
44
45// Print out the first three columns of a line.
46static void writeHeader(Ctx &ctx, raw_ostream &os, uint64_t vma, uint64_t lma,
47 uint64_t size, uint64_t align) {
48 if (ctx.arg.is64)
49 os << format(Fmt: "%16llx %16llx %8llx %5lld ", Vals: vma, Vals: lma, Vals: size, Vals: align);
50 else
51 os << format(Fmt: "%8llx %8llx %8llx %5lld ", Vals: vma, Vals: lma, Vals: size, Vals: align);
52}
53
54// Returns a list of all symbols that we want to print out.
55static std::vector<Defined *> getSymbols(Ctx &ctx) {
56 std::vector<Defined *> v;
57 for (ELFFileBase *file : ctx.objectFiles)
58 for (Symbol *b : file->getSymbols())
59 if (auto *dr = dyn_cast<Defined>(Val: b))
60 if (!dr->isSection() && dr->section && dr->section->isLive() &&
61 (dr->file == file || dr->hasFlag(bit: NEEDS_COPY) ||
62 (isa<SyntheticSection>(Val: dr->section) &&
63 cast<SyntheticSection>(Val: dr->section)->bss)))
64 v.push_back(x: dr);
65 return v;
66}
67
68// Returns a map from sections to their symbols.
69static SymbolMapTy getSectionSyms(Ctx &ctx, ArrayRef<Defined *> syms) {
70 SymbolMapTy ret;
71 for (Defined *dr : syms)
72 ret[dr->section].emplace_back(Args&: dr, Args: dr->getVA(ctx));
73
74 // Sort symbols by address. We want to print out symbols in the
75 // order in the output file rather than the order they appeared
76 // in the input files.
77 SmallPtrSet<Defined *, 4> set;
78 for (auto &it : ret) {
79 // Deduplicate symbols which need a canonical PLT entry/copy relocation.
80 set.clear();
81 llvm::erase_if(C&: it.second, P: [&](std::pair<Defined *, uint64_t> a) {
82 return !set.insert(Ptr: a.first).second;
83 });
84
85 llvm::stable_sort(Range&: it.second, C: llvm::less_second());
86 }
87 return ret;
88}
89
90// Construct a map from symbols to their stringified representations.
91// Demangling symbols (which is what toStr(ctx, ) does) is slow, so
92// we do that in batch using parallel-for.
93static DenseMap<Symbol *, std::string>
94getSymbolStrings(Ctx &ctx, ArrayRef<Defined *> syms) {
95 auto strs = std::make_unique<std::string[]>(num: syms.size());
96 parallelFor(Begin: 0, End: syms.size(), Fn: [&](size_t i) {
97 raw_string_ostream os(strs[i]);
98 OutputSection *osec = syms[i]->getOutputSection();
99 uint64_t vma = syms[i]->getVA(ctx);
100 uint64_t lma = osec ? osec->getLMA() + vma - osec->getVA(offset: 0) : 0;
101 writeHeader(ctx, os, vma, lma, size: syms[i]->getSize(), align: 1);
102 os << indent16 << toStr(ctx, *syms[i]);
103 });
104
105 DenseMap<Symbol *, std::string> ret;
106 for (size_t i = 0, e = syms.size(); i < e; ++i)
107 ret[syms[i]] = std::move(strs[i]);
108 return ret;
109}
110
111// Print .eh_frame contents. Since the section consists of EhSectionPieces,
112// we need a specialized printer for that section.
113//
114// .eh_frame tend to contain a lot of section pieces that are contiguous
115// both in input file and output file. Such pieces are squashed before
116// being displayed to make output compact.
117static void printEhFrame(Ctx &ctx, raw_ostream &os, const EhFrameSection *sec) {
118 struct Piece {
119 const EhInputSection *sec;
120 uint64_t inputOff, outputOff, size;
121 };
122 SmallVector<Piece, 0> pieces;
123 auto add = [&](const EhInputSection *s, const EhSectionPiece &p) {
124 if (p.outputOff == -1)
125 return;
126 // If P is adjacent to Last, squash the two.
127 if (!pieces.empty()) {
128 Piece &last = pieces.back();
129 if (last.sec == s && last.inputOff + last.size == p.inputOff &&
130 last.outputOff + last.size == uint64_t(p.outputOff)) {
131 last.size += p.size;
132 return;
133 }
134 }
135 pieces.push_back(Elt: {.sec: s, .inputOff: p.inputOff, .outputOff: uint64_t(p.outputOff), .size: p.size});
136 };
137
138 // Gather section pieces in output order.
139 for (const EhInputSection *s : sec->sections)
140 for (const EhSectionPiece &cie : s->cies)
141 add(s, cie);
142 for (const EhInputSection *s : sec->sections)
143 for (const EhSectionPiece &fde : s->fdes)
144 add(s, fde);
145
146 // Print out section pieces.
147 const OutputSection *osec = sec->getOutputSection();
148 for (const Piece &p : pieces) {
149 writeHeader(ctx, os, vma: osec->addr + p.outputOff, lma: osec->getLMA() + p.outputOff,
150 size: p.size, align: 1);
151 os << indent8 << toStr(ctx, f: p.sec->file) << ":(" << p.sec->name << "+0x"
152 << Twine::utohexstr(Val: p.inputOff) + ")\n";
153 }
154}
155
156static void writeMapFile(Ctx &ctx, raw_fd_ostream &os) {
157 // Collect symbol info that we want to print out.
158 std::vector<Defined *> syms = getSymbols(ctx);
159 SymbolMapTy sectionSyms = getSectionSyms(ctx, syms);
160 DenseMap<Symbol *, std::string> symStr = getSymbolStrings(ctx, syms);
161
162 // Print out the header line.
163 int w = ctx.arg.is64 ? 16 : 8;
164 os << right_justify(Str: "VMA", Width: w) << ' ' << right_justify(Str: "LMA", Width: w)
165 << " Size Align Out In Symbol\n";
166
167 OutputSection *osec = nullptr;
168 for (SectionCommand *cmd : ctx.script->sectionCommands) {
169 if (auto *assign = dyn_cast<SymbolAssignment>(Val: cmd)) {
170 if (assign->provide && !assign->sym)
171 continue;
172 uint64_t lma = osec ? osec->getLMA() + assign->addr - osec->getVA(offset: 0) : 0;
173 writeHeader(ctx, os, vma: assign->addr, lma, size: assign->size, align: 1);
174 os << assign->commandString << '\n';
175 continue;
176 }
177 if (isa<SectionClassDesc>(Val: cmd))
178 continue;
179
180 osec = &cast<OutputDesc>(Val: cmd)->osec;
181 writeHeader(ctx, os, vma: osec->addr, lma: osec->getLMA(), size: osec->size,
182 align: osec->addralign);
183 os << osec->name << '\n';
184
185 // Dump symbols for each input section.
186 for (SectionCommand *subCmd : osec->commands) {
187 if (auto *isd = dyn_cast<InputSectionDescription>(Val: subCmd)) {
188 for (InputSection *isec : isd->sections) {
189 if (auto *ehSec = dyn_cast<EhFrameSection>(Val: isec)) {
190 printEhFrame(ctx, os, sec: ehSec);
191 continue;
192 }
193
194 writeHeader(ctx, os, vma: isec->getVA(), lma: osec->getLMA() + isec->outSecOff,
195 size: isec->getSize(), align: isec->addralign);
196 os << indent8 << toStr(ctx, isec) << '\n';
197 for (Symbol *sym : llvm::make_first_range(c&: sectionSyms[isec]))
198 os << symStr[sym] << '\n';
199 }
200 continue;
201 }
202
203 if (auto *data = dyn_cast<ByteCommand>(Val: subCmd)) {
204 writeHeader(ctx, os, vma: osec->addr + data->offset,
205 lma: osec->getLMA() + data->offset, size: data->size, align: 1);
206 os << indent8 << data->commandString << '\n';
207 continue;
208 }
209
210 if (auto *assign = dyn_cast<SymbolAssignment>(Val: subCmd)) {
211 if (assign->provide && !assign->sym)
212 continue;
213 writeHeader(ctx, os, vma: assign->addr,
214 lma: osec->getLMA() + assign->addr - osec->getVA(offset: 0),
215 size: assign->size, align: 1);
216 os << indent8 << assign->commandString << '\n';
217 continue;
218 }
219 }
220 }
221}
222
223// Output a cross reference table to stdout. This is for --cref.
224//
225// For each global symbol, we print out a file that defines the symbol
226// followed by files that uses that symbol. Here is an example.
227//
228// strlen /lib/x86_64-linux-gnu/libc.so.6
229// tools/lld/tools/lld/CMakeFiles/lld.dir/lld.cpp.o
230// lib/libLLVMSupport.a(PrettyStackTrace.cpp.o)
231//
232// In this case, strlen is defined by libc.so.6 and used by other two
233// files.
234static void writeCref(Ctx &ctx, raw_fd_ostream &os) {
235 // Collect symbols and files.
236 MapVector<Symbol *, SetVector<InputFile *>> map;
237 for (ELFFileBase *file : ctx.objectFiles) {
238 for (Symbol *sym : file->getSymbols()) {
239 if (isa<SharedSymbol>(Val: sym))
240 map[sym].insert(X: file);
241 if (auto *d = dyn_cast<Defined>(Val: sym))
242 if (!d->isLocal())
243 map[d].insert(X: file);
244 }
245 }
246
247 auto print = [&](StringRef a, StringRef b) {
248 os << left_justify(Str: a, Width: 49) << ' ' << b << '\n';
249 };
250
251 // Print a blank line and a header. The format matches GNU ld.
252 os << "\nCross Reference Table\n\n";
253 print("Symbol", "File");
254
255 // Print out a table.
256 for (auto kv : map) {
257 Symbol *sym = kv.first;
258 SetVector<InputFile *> &files = kv.second;
259
260 print(toStr(ctx, *sym), toStr(ctx, f: sym->file));
261 for (InputFile *file : files)
262 if (file != sym->file)
263 print("", toStr(ctx, f: file));
264 }
265}
266
267void elf::writeMapAndCref(Ctx &ctx) {
268 if (ctx.arg.mapFile.empty() && !ctx.arg.cref)
269 return;
270
271 llvm::TimeTraceScope timeScope("Write map file");
272
273 // Open a map file for writing.
274 std::error_code ec;
275 StringRef mapFile = ctx.arg.mapFile.empty() ? "-" : ctx.arg.mapFile;
276 raw_fd_ostream os = ctx.openAuxiliaryFile(mapFile, ec);
277 if (ec) {
278 ErrAlways(ctx) << "cannot open " << mapFile << ": " << ec.message();
279 return;
280 }
281
282 if (!ctx.arg.mapFile.empty())
283 writeMapFile(ctx, os);
284 if (ctx.arg.cref)
285 writeCref(ctx, os);
286}
287