1//===- tools/dsymutil/DebugMap.cpp - Generic debug map representation -----===//
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#include "DebugMap.h"
10#include "BinaryHolder.h"
11#include "llvm/ADT/SmallString.h"
12#include "llvm/ADT/StringMap.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/BinaryFormat/MachO.h"
15#include "llvm/Object/ObjectFile.h"
16#include "llvm/Support/Chrono.h"
17#include "llvm/Support/Error.h"
18#include "llvm/Support/Format.h"
19#include "llvm/Support/MemoryBuffer.h"
20#include "llvm/Support/Path.h"
21#include "llvm/Support/WithColor.h"
22#include "llvm/Support/YAMLTraits.h"
23#include "llvm/Support/raw_ostream.h"
24#include "llvm/TargetParser/Triple.h"
25#include <algorithm>
26#include <cinttypes>
27#include <cstdint>
28#include <memory>
29#include <optional>
30#include <string>
31#include <utility>
32#include <vector>
33
34namespace llvm {
35
36namespace dsymutil {
37
38using namespace llvm::object;
39
40DebugMapObject::DebugMapObject(StringRef ObjectFilename,
41 sys::TimePoint<std::chrono::seconds> Timestamp,
42 uint8_t Type)
43 : DebugMapObjectFilter(ObjectFilename), Timestamp(Timestamp), Type(Type) {}
44
45bool DebugMapObject::addSymbol(StringRef Name,
46 std::optional<uint64_t> ObjectAddress,
47 uint64_t LinkedAddress, uint32_t Size) {
48 if (Symbols.count(Key: Name)) {
49 // Symbol was previously added.
50 return true;
51 }
52
53 auto InsertResult = Symbols.insert(
54 KV: std::make_pair(x&: Name, y: SymbolMapping(ObjectAddress, LinkedAddress, Size)));
55
56 if (ObjectAddress && InsertResult.second)
57 AddressToMapping[*ObjectAddress] = &*InsertResult.first;
58 return InsertResult.second;
59}
60
61void DebugMapObject::setRelocationMap(dsymutil::RelocationMap &RM) {
62 RelocMap.emplace(args&: RM);
63}
64
65void DebugMapObject::setInstallName(StringRef IN) { InstallName.emplace(args&: IN); }
66
67void DebugMapObject::print(raw_ostream &OS) const {
68 OS << getObjectFilename() << ":\n";
69 // Sort the symbols in alphabetical order, like llvm-nm (and to get
70 // deterministic output for testing).
71 using Entry = std::pair<StringRef, SymbolMapping>;
72 std::vector<Entry> Entries;
73 Entries.reserve(n: Symbols.getNumItems());
74 for (const auto &Sym : Symbols)
75 Entries.push_back(x: std::make_pair(x: Sym.getKey(), y: Sym.getValue()));
76 llvm::sort(C&: Entries, Comp: llvm::less_first());
77 for (const auto &Sym : Entries) {
78 if (Sym.second.ObjectAddress)
79 OS << format(Fmt: "\t%016" PRIx64, Vals: uint64_t(*Sym.second.ObjectAddress));
80 else
81 OS << "\t????????????????";
82 OS << format(Fmt: " => %016" PRIx64 "+0x%x\t%s\n",
83 Vals: uint64_t(Sym.second.BinaryAddress), Vals: uint32_t(Sym.second.Size),
84 Vals: Sym.first.data());
85 }
86 OS << '\n';
87}
88
89#ifndef NDEBUG
90void DebugMapObject::dump() const { print(errs()); }
91#endif
92
93DebugMapObject &
94DebugMap::addDebugMapObject(StringRef ObjectFilePath,
95 sys::TimePoint<std::chrono::seconds> Timestamp,
96 uint8_t Type) {
97 getObjects().emplace_back(
98 args: new DebugMapObject(ObjectFilePath, Timestamp, Type));
99 return *getObjects().back();
100}
101
102const DebugMapObject::DebugMapEntry *
103DebugMapObject::lookupSymbol(StringRef SymbolName) const {
104 StringMap<SymbolMapping>::const_iterator Sym = Symbols.find(Key: SymbolName);
105 if (Sym == Symbols.end())
106 return nullptr;
107 return &*Sym;
108}
109
110const DebugMapObject::DebugMapEntry *
111DebugMapObject::lookupObjectAddress(uint64_t Address) const {
112 auto Mapping = AddressToMapping.find(Val: Address);
113 if (Mapping == AddressToMapping.end())
114 return nullptr;
115 return Mapping->getSecond();
116}
117
118void DebugMap::print(raw_ostream &OS) const {
119 yaml::Output yout(OS, /* Ctxt = */ nullptr, /* WrapColumn = */ 0);
120 yout << const_cast<DebugMap &>(*this);
121}
122
123#ifndef NDEBUG
124void DebugMap::dump() const { print(errs()); }
125#endif
126
127DebugMapObjectFilter::DebugMapObjectFilter(StringRef ObjectFilename)
128 : Filename(std::string(ObjectFilename)) {}
129
130namespace {
131
132struct YAMLContext {
133 YAMLContext(BinaryHolder &BinHolder, StringRef PrependPath)
134 : BinHolder(BinHolder), PrependPath(PrependPath) {}
135 BinaryHolder &BinHolder;
136 StringRef PrependPath;
137 Triple BinaryTriple;
138};
139
140} // end anonymous namespace
141
142DebugMap::DebugMap(const Triple &BinaryTriple, StringRef BinaryPath,
143 ArrayRef<uint8_t> BinaryUUID)
144 : BinaryTriple(BinaryTriple), BinaryPath(std::string(BinaryPath)),
145 BinaryUUID(BinaryUUID.begin(), BinaryUUID.end()) {}
146
147ErrorOr<std::vector<std::unique_ptr<DebugMap>>>
148DebugMap::parseYAMLDebugMap(BinaryHolder &BinHolder, StringRef InputFile,
149 StringRef PrependPath, bool Verbose) {
150 auto ErrOrFile = MemoryBuffer::getFileOrSTDIN(Filename: InputFile);
151 if (auto Err = ErrOrFile.getError())
152 return Err;
153
154 YAMLContext Ctxt(BinHolder, PrependPath);
155
156 std::unique_ptr<DebugMap> Res;
157 yaml::Input yin((*ErrOrFile)->getBuffer(), &Ctxt);
158 yin >> Res;
159
160 if (auto EC = yin.error())
161 return EC;
162 std::vector<std::unique_ptr<DebugMap>> Result;
163 Result.push_back(x: std::move(Res));
164 return std::move(Result);
165}
166
167} // end namespace dsymutil
168
169namespace yaml {
170
171// Normalize/Denormalize between YAML and a DebugMapObject.
172struct MappingTraits<dsymutil::DebugMapObject>::YamlDMO {
173 YamlDMO(IO &io) {}
174 YamlDMO(IO &io, dsymutil::DebugMapObject &Obj);
175 dsymutil::DebugMapObject denormalize(IO &IO);
176
177 std::string Filename;
178 int64_t Timestamp = 0;
179 uint8_t Type = MachO::N_OSO;
180 std::vector<dsymutil::DebugMapObject::YAMLSymbolMapping> Entries;
181};
182
183void MappingTraits<std::pair<std::string, SymbolMapping>>::mapping(
184 IO &io, std::pair<std::string, SymbolMapping> &s) {
185 io.mapRequired(Key: "sym", Val&: s.first);
186 io.mapOptional(Key: "objAddr", Val&: s.second.ObjectAddress);
187 io.mapRequired(Key: "binAddr", Val&: s.second.BinaryAddress);
188 io.mapOptional(Key: "size", Val&: s.second.Size);
189}
190
191void MappingTraits<dsymutil::DebugMapObject>::mapping(
192 IO &io, dsymutil::DebugMapObject &DMO) {
193 MappingNormalization<YamlDMO, dsymutil::DebugMapObject> Norm(io, DMO);
194 io.mapRequired(Key: "filename", Val&: Norm->Filename);
195 io.mapOptional(Key: "timestamp", Val&: Norm->Timestamp);
196 io.mapOptional(Key: "type", Val&: Norm->Type);
197 io.mapRequired(Key: "symbols", Val&: Norm->Entries);
198}
199
200void ScalarTraits<Triple>::output(const Triple &val, void *, raw_ostream &out) {
201 out << val.str();
202}
203
204StringRef ScalarTraits<Triple>::input(StringRef scalar, void *, Triple &value) {
205 value = Triple(scalar);
206 return StringRef();
207}
208
209size_t
210SequenceTraits<std::vector<std::unique_ptr<dsymutil::DebugMapObject>>>::size(
211 IO &io, std::vector<std::unique_ptr<dsymutil::DebugMapObject>> &seq) {
212 return seq.size();
213}
214
215dsymutil::DebugMapObject &
216SequenceTraits<std::vector<std::unique_ptr<dsymutil::DebugMapObject>>>::element(
217 IO &, std::vector<std::unique_ptr<dsymutil::DebugMapObject>> &seq,
218 size_t index) {
219 if (index >= seq.size()) {
220 seq.resize(new_size: index + 1);
221 seq[index].reset(p: new dsymutil::DebugMapObject);
222 }
223 return *seq[index];
224}
225
226size_t
227SequenceTraits<std::vector<std::unique_ptr<dsymutil::DebugMapObjectFilter>>>::
228 size(IO &io,
229 std::vector<std::unique_ptr<dsymutil::DebugMapObjectFilter>> &seq) {
230 return seq.size();
231}
232
233dsymutil::DebugMapObjectFilter &
234SequenceTraits<std::vector<std::unique_ptr<dsymutil::DebugMapObjectFilter>>>::
235 element(IO &io,
236 std::vector<std::unique_ptr<dsymutil::DebugMapObjectFilter>> &seq,
237 size_t index) {
238 if (index >= seq.size()) {
239 seq.resize(new_size: index + 1);
240 seq[index].reset(p: new dsymutil::DebugMapObjectFilter);
241 }
242 return *seq[index];
243}
244
245void MappingTraits<dsymutil::DebugMapObjectFilter>::mapping(
246 IO &io, dsymutil::DebugMapObjectFilter &DMOF) {
247 io.mapRequired(Key: "filename", Val&: DMOF.Filename);
248}
249
250void MappingTraits<dsymutil::DebugMapFilter>::mapping(
251 IO &io, dsymutil::DebugMapFilter &DMF) {
252 io.mapRequired(Key: "objects", Val&: DMF.Objects);
253}
254
255void MappingTraits<std::unique_ptr<dsymutil::DebugMapFilter>>::mapping(
256 IO &io, std::unique_ptr<dsymutil::DebugMapFilter> &DMF) {
257 if (!DMF)
258 DMF.reset(p: new DebugMapFilter());
259 io.mapRequired(Key: "objects", Val&: DMF->Objects);
260}
261
262void MappingTraits<dsymutil::DebugMap>::mapping(IO &io,
263 dsymutil::DebugMap &DM) {
264 io.mapRequired(Key: "triple", Val&: DM.BinaryTriple);
265 io.mapOptional(Key: "binary-path", Val&: DM.BinaryPath);
266 if (void *Ctxt = io.getContext())
267 reinterpret_cast<YAMLContext *>(Ctxt)->BinaryTriple = DM.BinaryTriple;
268 io.mapOptional(Key: "objects", Val&: DM.getObjects());
269}
270
271void MappingTraits<std::unique_ptr<dsymutil::DebugMap>>::mapping(
272 IO &io, std::unique_ptr<dsymutil::DebugMap> &DM) {
273 if (!DM)
274 DM.reset(p: new DebugMap());
275 io.mapRequired(Key: "triple", Val&: DM->BinaryTriple);
276 io.mapOptional(Key: "binary-path", Val&: DM->BinaryPath);
277 if (void *Ctxt = io.getContext())
278 reinterpret_cast<YAMLContext *>(Ctxt)->BinaryTriple = DM->BinaryTriple;
279 io.mapOptional(Key: "objects", Val&: DM->getObjects());
280}
281
282MappingTraits<dsymutil::DebugMapObject>::YamlDMO::YamlDMO(
283 IO &io, dsymutil::DebugMapObject &Obj) {
284 Filename = Obj.Filename;
285 Timestamp = sys::toTimeT(TP: Obj.getTimestamp());
286 Type = Obj.getType();
287 Entries.reserve(n: Obj.Symbols.size());
288 for (auto &Entry : Obj.Symbols)
289 Entries.push_back(
290 x: std::make_pair(x: std::string(Entry.getKey()), y&: Entry.getValue()));
291 llvm::sort(C&: Entries, Comp: llvm::less_first());
292}
293
294dsymutil::DebugMapObject
295MappingTraits<dsymutil::DebugMapObject>::YamlDMO::denormalize(IO &IO) {
296 const auto &Ctxt = *reinterpret_cast<YAMLContext *>(IO.getContext());
297 SmallString<80> Path(Ctxt.PrependPath);
298 StringMap<uint64_t> SymbolAddresses;
299
300 sys::path::append(path&: Path, a: Filename);
301
302 auto ObjectEntry = Ctxt.BinHolder.getObjectEntry(Filename: Path);
303 if (!ObjectEntry) {
304 auto Err = ObjectEntry.takeError();
305 WithColor::warning() << "Unable to open " << Path << " "
306 << toString(E: std::move(Err)) << '\n';
307 } else {
308 auto Object = ObjectEntry->getObject(T: Ctxt.BinaryTriple);
309 if (!Object) {
310 auto Err = Object.takeError();
311 WithColor::warning() << "Unable to open " << Path << " "
312 << toString(E: std::move(Err)) << '\n';
313 } else {
314 for (const auto &Sym : Object->symbols()) {
315 Expected<uint64_t> AddressOrErr = Sym.getValue();
316 if (!AddressOrErr) {
317 // TODO: Actually report errors helpfully.
318 consumeError(Err: AddressOrErr.takeError());
319 continue;
320 }
321 Expected<StringRef> Name = Sym.getName();
322 Expected<uint32_t> FlagsOrErr = Sym.getFlags();
323 if (!Name || !FlagsOrErr ||
324 (*FlagsOrErr & (SymbolRef::SF_Absolute | SymbolRef::SF_Common))) {
325 // TODO: Actually report errors helpfully.
326 if (!FlagsOrErr)
327 consumeError(Err: FlagsOrErr.takeError());
328 if (!Name)
329 consumeError(Err: Name.takeError());
330 continue;
331 }
332 SymbolAddresses[*Name] = *AddressOrErr;
333 }
334 }
335 }
336
337 if (Path.ends_with(Suffix: ".dylib")) {
338 // FIXME: find a more resilient way
339 Type = MachO::N_LIB;
340 }
341 dsymutil::DebugMapObject Res(Path, sys::toTimePoint(T: Timestamp), Type);
342
343 for (auto &Entry : Entries) {
344 auto &Mapping = Entry.second;
345 std::optional<uint64_t> ObjAddress;
346 if (Mapping.ObjectAddress)
347 ObjAddress = *Mapping.ObjectAddress;
348 auto AddressIt = SymbolAddresses.find(Key: Entry.first);
349 if (AddressIt != SymbolAddresses.end())
350 ObjAddress = AddressIt->getValue();
351 Res.addSymbol(Name: Entry.first, ObjectAddress: ObjAddress, LinkedAddress: Mapping.BinaryAddress, Size: Mapping.Size);
352 }
353 return Res;
354}
355
356} // end namespace yaml
357} // end namespace llvm
358