blob: ba2f9a18e6837d91e8cc1f3b6bd0fac2f525640e [file] [log] [blame]
Inna Palantff3f07a2019-07-11 16:15:26 -07001//===- tools/dsymutil/MachODebugMapParser.cpp - Parse STABS debug maps ----===//
2//
Chih-Hung Hsieh08600532019-12-19 15:55:38 -08003// 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
Inna Palantff3f07a2019-07-11 16:15:26 -07006//
7//===----------------------------------------------------------------------===//
8
9#include "BinaryHolder.h"
10#include "DebugMap.h"
11#include "MachOUtils.h"
12#include "llvm/ADT/Optional.h"
13#include "llvm/Object/MachO.h"
14#include "llvm/Support/Path.h"
15#include "llvm/Support/WithColor.h"
16#include "llvm/Support/raw_ostream.h"
Jeff Vander Stoep247d86b2020-08-11 14:27:44 +020017#include <vector>
Inna Palantff3f07a2019-07-11 16:15:26 -070018
19namespace {
20using namespace llvm;
21using namespace llvm::dsymutil;
22using namespace llvm::object;
23
24class MachODebugMapParser {
25public:
Thiébaud Weksteene40e7362020-10-28 15:03:00 +010026 MachODebugMapParser(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
27 StringRef BinaryPath, ArrayRef<std::string> Archs,
Inna Palantff3f07a2019-07-11 16:15:26 -070028 StringRef PathPrefix = "",
29 bool PaperTrailWarnings = false, bool Verbose = false)
Thiébaud Weksteene40e7362020-10-28 15:03:00 +010030 : BinaryPath(std::string(BinaryPath)), Archs(Archs.begin(), Archs.end()),
31 PathPrefix(std::string(PathPrefix)),
32 PaperTrailWarnings(PaperTrailWarnings), BinHolder(VFS, Verbose),
33 CurrentDebugMapObject(nullptr) {}
Inna Palantff3f07a2019-07-11 16:15:26 -070034
35 /// Parses and returns the DebugMaps of the input binary. The binary contains
36 /// multiple maps in case it is a universal binary.
37 /// \returns an error in case the provided BinaryPath doesn't exist
38 /// or isn't of a supported type.
39 ErrorOr<std::vector<std::unique_ptr<DebugMap>>> parse();
40
41 /// Walk the symbol table and dump it.
42 bool dumpStab();
43
44private:
45 std::string BinaryPath;
46 SmallVector<StringRef, 1> Archs;
47 std::string PathPrefix;
48 bool PaperTrailWarnings;
49
50 /// Owns the MemoryBuffer for the main binary.
51 BinaryHolder BinHolder;
52 /// Map of the binary symbol addresses.
53 StringMap<uint64_t> MainBinarySymbolAddresses;
54 StringRef MainBinaryStrings;
55 /// The constructed DebugMap.
56 std::unique_ptr<DebugMap> Result;
Jeff Vander Stoep247d86b2020-08-11 14:27:44 +020057 /// List of common symbols that need to be added to the debug map.
58 std::vector<std::string> CommonSymbols;
Inna Palantff3f07a2019-07-11 16:15:26 -070059
60 /// Map of the currently processed object file symbol addresses.
61 StringMap<Optional<uint64_t>> CurrentObjectAddresses;
62 /// Element of the debug map corresponding to the current object file.
63 DebugMapObject *CurrentDebugMapObject;
64
65 /// Holds function info while function scope processing.
66 const char *CurrentFunctionName;
67 uint64_t CurrentFunctionAddress;
68
69 std::unique_ptr<DebugMap> parseOneBinary(const MachOObjectFile &MainBinary,
70 StringRef BinaryPath);
71
72 void
73 switchToNewDebugMapObject(StringRef Filename,
74 sys::TimePoint<std::chrono::seconds> Timestamp);
75 void resetParserState();
76 uint64_t getMainBinarySymbolAddress(StringRef Name);
77 std::vector<StringRef> getMainBinarySymbolNames(uint64_t Value);
78 void loadMainBinarySymbols(const MachOObjectFile &MainBinary);
79 void loadCurrentObjectFileSymbols(const object::MachOObjectFile &Obj);
80 void handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type,
81 uint8_t SectionIndex, uint16_t Flags,
82 uint64_t Value);
83
84 template <typename STEType> void handleStabDebugMapEntry(const STEType &STE) {
85 handleStabSymbolTableEntry(STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc,
86 STE.n_value);
87 }
88
Jeff Vander Stoep247d86b2020-08-11 14:27:44 +020089 void addCommonSymbols();
90
Inna Palantff3f07a2019-07-11 16:15:26 -070091 /// Dump the symbol table output header.
92 void dumpSymTabHeader(raw_ostream &OS, StringRef Arch);
93
94 /// Dump the contents of nlist entries.
95 void dumpSymTabEntry(raw_ostream &OS, uint64_t Index, uint32_t StringIndex,
96 uint8_t Type, uint8_t SectionIndex, uint16_t Flags,
97 uint64_t Value);
98
99 template <typename STEType>
100 void dumpSymTabEntry(raw_ostream &OS, uint64_t Index, const STEType &STE) {
101 dumpSymTabEntry(OS, Index, STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc,
102 STE.n_value);
103 }
104 void dumpOneBinaryStab(const MachOObjectFile &MainBinary,
105 StringRef BinaryPath);
106
107 void Warning(const Twine &Msg, StringRef File = StringRef()) {
108 WithColor::warning() << "("
109 << MachOUtils::getArchName(
110 Result->getTriple().getArchName())
111 << ") " << File << " " << Msg << "\n";
112
113 if (PaperTrailWarnings) {
114 if (!File.empty())
115 Result->addDebugMapObject(File, sys::TimePoint<std::chrono::seconds>());
116 if (Result->end() != Result->begin())
117 (*--Result->end())->addWarning(Msg.str());
118 }
119 }
120};
121
122} // anonymous namespace
123
124/// Reset the parser state corresponding to the current object
125/// file. This is to be called after an object file is finished
126/// processing.
127void MachODebugMapParser::resetParserState() {
Jeff Vander Stoep247d86b2020-08-11 14:27:44 +0200128 CommonSymbols.clear();
Inna Palantff3f07a2019-07-11 16:15:26 -0700129 CurrentObjectAddresses.clear();
130 CurrentDebugMapObject = nullptr;
131}
132
Jeff Vander Stoep247d86b2020-08-11 14:27:44 +0200133/// Commons symbols won't show up in the symbol map but might need to be
134/// relocated. We can add them to the symbol table ourselves by combining the
135/// information in the object file (the symbol name) and the main binary (the
136/// address).
137void MachODebugMapParser::addCommonSymbols() {
138 for (auto &CommonSymbol : CommonSymbols) {
139 uint64_t CommonAddr = getMainBinarySymbolAddress(CommonSymbol);
140 if (CommonAddr == 0) {
141 // The main binary doesn't have an address for the given symbol.
142 continue;
143 }
144 if (!CurrentDebugMapObject->addSymbol(CommonSymbol, None /*ObjectAddress*/,
145 CommonAddr, 0 /*size*/)) {
146 // The symbol is already present.
147 continue;
148 }
149 }
150}
151
Inna Palantff3f07a2019-07-11 16:15:26 -0700152/// Create a new DebugMapObject. This function resets the state of the
153/// parser that was referring to the last object file and sets
154/// everything up to add symbols to the new one.
155void MachODebugMapParser::switchToNewDebugMapObject(
156 StringRef Filename, sys::TimePoint<std::chrono::seconds> Timestamp) {
Jeff Vander Stoep247d86b2020-08-11 14:27:44 +0200157 addCommonSymbols();
Inna Palantff3f07a2019-07-11 16:15:26 -0700158 resetParserState();
159
160 SmallString<80> Path(PathPrefix);
161 sys::path::append(Path, Filename);
162
163 auto ObjectEntry = BinHolder.getObjectEntry(Path, Timestamp);
164 if (!ObjectEntry) {
165 auto Err = ObjectEntry.takeError();
166 Warning("unable to open object file: " + toString(std::move(Err)),
167 Path.str());
168 return;
169 }
170
171 auto Object = ObjectEntry->getObjectAs<MachOObjectFile>(Result->getTriple());
172 if (!Object) {
173 auto Err = Object.takeError();
174 Warning("unable to open object file: " + toString(std::move(Err)),
175 Path.str());
176 return;
177 }
178
179 CurrentDebugMapObject =
180 &Result->addDebugMapObject(Path, Timestamp, MachO::N_OSO);
181 loadCurrentObjectFileSymbols(*Object);
182}
183
184static std::string getArchName(const object::MachOObjectFile &Obj) {
185 Triple T = Obj.getArchTriple();
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100186 return std::string(T.getArchName());
Inna Palantff3f07a2019-07-11 16:15:26 -0700187}
188
189std::unique_ptr<DebugMap>
190MachODebugMapParser::parseOneBinary(const MachOObjectFile &MainBinary,
191 StringRef BinaryPath) {
192 loadMainBinarySymbols(MainBinary);
193 ArrayRef<uint8_t> UUID = MainBinary.getUuid();
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100194 Result =
195 std::make_unique<DebugMap>(MainBinary.getArchTriple(), BinaryPath, UUID);
Inna Palantff3f07a2019-07-11 16:15:26 -0700196 MainBinaryStrings = MainBinary.getStringTableData();
197 for (const SymbolRef &Symbol : MainBinary.symbols()) {
198 const DataRefImpl &DRI = Symbol.getRawDataRefImpl();
199 if (MainBinary.is64Bit())
200 handleStabDebugMapEntry(MainBinary.getSymbol64TableEntry(DRI));
201 else
202 handleStabDebugMapEntry(MainBinary.getSymbolTableEntry(DRI));
203 }
204
205 resetParserState();
206 return std::move(Result);
207}
208
209// Table that maps Darwin's Mach-O stab constants to strings to allow printing.
210// llvm-nm has very similar code, the strings used here are however slightly
211// different and part of the interface of dsymutil (some project's build-systems
212// parse the ouptut of dsymutil -s), thus they shouldn't be changed.
213struct DarwinStabName {
214 uint8_t NType;
215 const char *Name;
216};
217
218static const struct DarwinStabName DarwinStabNames[] = {
219 {MachO::N_GSYM, "N_GSYM"}, {MachO::N_FNAME, "N_FNAME"},
220 {MachO::N_FUN, "N_FUN"}, {MachO::N_STSYM, "N_STSYM"},
221 {MachO::N_LCSYM, "N_LCSYM"}, {MachO::N_BNSYM, "N_BNSYM"},
222 {MachO::N_PC, "N_PC"}, {MachO::N_AST, "N_AST"},
223 {MachO::N_OPT, "N_OPT"}, {MachO::N_RSYM, "N_RSYM"},
224 {MachO::N_SLINE, "N_SLINE"}, {MachO::N_ENSYM, "N_ENSYM"},
225 {MachO::N_SSYM, "N_SSYM"}, {MachO::N_SO, "N_SO"},
226 {MachO::N_OSO, "N_OSO"}, {MachO::N_LSYM, "N_LSYM"},
227 {MachO::N_BINCL, "N_BINCL"}, {MachO::N_SOL, "N_SOL"},
228 {MachO::N_PARAMS, "N_PARAM"}, {MachO::N_VERSION, "N_VERS"},
229 {MachO::N_OLEVEL, "N_OLEV"}, {MachO::N_PSYM, "N_PSYM"},
230 {MachO::N_EINCL, "N_EINCL"}, {MachO::N_ENTRY, "N_ENTRY"},
231 {MachO::N_LBRAC, "N_LBRAC"}, {MachO::N_EXCL, "N_EXCL"},
232 {MachO::N_RBRAC, "N_RBRAC"}, {MachO::N_BCOMM, "N_BCOMM"},
233 {MachO::N_ECOMM, "N_ECOMM"}, {MachO::N_ECOML, "N_ECOML"},
234 {MachO::N_LENG, "N_LENG"}, {0, nullptr}};
235
236static const char *getDarwinStabString(uint8_t NType) {
237 for (unsigned i = 0; DarwinStabNames[i].Name; i++) {
238 if (DarwinStabNames[i].NType == NType)
239 return DarwinStabNames[i].Name;
240 }
241 return nullptr;
242}
243
244void MachODebugMapParser::dumpSymTabHeader(raw_ostream &OS, StringRef Arch) {
245 OS << "-----------------------------------"
246 "-----------------------------------\n";
247 OS << "Symbol table for: '" << BinaryPath << "' (" << Arch.data() << ")\n";
248 OS << "-----------------------------------"
249 "-----------------------------------\n";
250 OS << "Index n_strx n_type n_sect n_desc n_value\n";
251 OS << "======== -------- ------------------ ------ ------ ----------------\n";
252}
253
254void MachODebugMapParser::dumpSymTabEntry(raw_ostream &OS, uint64_t Index,
255 uint32_t StringIndex, uint8_t Type,
256 uint8_t SectionIndex, uint16_t Flags,
257 uint64_t Value) {
258 // Index
259 OS << '[' << format_decimal(Index, 6)
260 << "] "
261 // n_strx
262 << format_hex_no_prefix(StringIndex, 8)
263 << ' '
264 // n_type...
265 << format_hex_no_prefix(Type, 2) << " (";
266
267 if (Type & MachO::N_STAB)
268 OS << left_justify(getDarwinStabString(Type), 13);
269 else {
270 if (Type & MachO::N_PEXT)
271 OS << "PEXT ";
272 else
273 OS << " ";
274 switch (Type & MachO::N_TYPE) {
275 case MachO::N_UNDF: // 0x0 undefined, n_sect == NO_SECT
276 OS << "UNDF";
277 break;
278 case MachO::N_ABS: // 0x2 absolute, n_sect == NO_SECT
279 OS << "ABS ";
280 break;
281 case MachO::N_SECT: // 0xe defined in section number n_sect
282 OS << "SECT";
283 break;
284 case MachO::N_PBUD: // 0xc prebound undefined (defined in a dylib)
285 OS << "PBUD";
286 break;
287 case MachO::N_INDR: // 0xa indirect
288 OS << "INDR";
289 break;
290 default:
291 OS << format_hex_no_prefix(Type, 2) << " ";
292 break;
293 }
294 if (Type & MachO::N_EXT)
295 OS << " EXT";
296 else
297 OS << " ";
298 }
299
300 OS << ") "
301 // n_sect
302 << format_hex_no_prefix(SectionIndex, 2)
303 << " "
304 // n_desc
305 << format_hex_no_prefix(Flags, 4)
306 << " "
307 // n_value
308 << format_hex_no_prefix(Value, 16);
309
310 const char *Name = &MainBinaryStrings.data()[StringIndex];
311 if (Name && Name[0])
312 OS << " '" << Name << "'";
313
314 OS << "\n";
315}
316
317void MachODebugMapParser::dumpOneBinaryStab(const MachOObjectFile &MainBinary,
318 StringRef BinaryPath) {
319 loadMainBinarySymbols(MainBinary);
320 MainBinaryStrings = MainBinary.getStringTableData();
321 raw_ostream &OS(llvm::outs());
322
323 dumpSymTabHeader(OS, getArchName(MainBinary));
324 uint64_t Idx = 0;
325 for (const SymbolRef &Symbol : MainBinary.symbols()) {
326 const DataRefImpl &DRI = Symbol.getRawDataRefImpl();
327 if (MainBinary.is64Bit())
328 dumpSymTabEntry(OS, Idx, MainBinary.getSymbol64TableEntry(DRI));
329 else
330 dumpSymTabEntry(OS, Idx, MainBinary.getSymbolTableEntry(DRI));
331 Idx++;
332 }
333
334 OS << "\n\n";
335 resetParserState();
336}
337
338static bool shouldLinkArch(SmallVectorImpl<StringRef> &Archs, StringRef Arch) {
339 if (Archs.empty() || is_contained(Archs, "all") || is_contained(Archs, "*"))
340 return true;
341
342 if (Arch.startswith("arm") && Arch != "arm64" && is_contained(Archs, "arm"))
343 return true;
344
345 SmallString<16> ArchName = Arch;
346 if (Arch.startswith("thumb"))
347 ArchName = ("arm" + Arch.substr(5)).str();
348
349 return is_contained(Archs, ArchName);
350}
351
352bool MachODebugMapParser::dumpStab() {
353 auto ObjectEntry = BinHolder.getObjectEntry(BinaryPath);
354 if (!ObjectEntry) {
355 auto Err = ObjectEntry.takeError();
356 WithColor::error() << "cannot load '" << BinaryPath
357 << "': " << toString(std::move(Err)) << '\n';
358 return false;
359 }
360
361 auto Objects = ObjectEntry->getObjectsAs<MachOObjectFile>();
362 if (!Objects) {
363 auto Err = Objects.takeError();
364 WithColor::error() << "cannot get '" << BinaryPath
365 << "' as MachO file: " << toString(std::move(Err))
366 << "\n";
367 return false;
368 }
369
370 for (const auto *Object : *Objects)
371 if (shouldLinkArch(Archs, Object->getArchTriple().getArchName()))
372 dumpOneBinaryStab(*Object, BinaryPath);
373
374 return true;
375}
376
377/// This main parsing routine tries to open the main binary and if
378/// successful iterates over the STAB entries. The real parsing is
379/// done in handleStabSymbolTableEntry.
380ErrorOr<std::vector<std::unique_ptr<DebugMap>>> MachODebugMapParser::parse() {
381 auto ObjectEntry = BinHolder.getObjectEntry(BinaryPath);
382 if (!ObjectEntry) {
383 return errorToErrorCode(ObjectEntry.takeError());
384 }
385
386 auto Objects = ObjectEntry->getObjectsAs<MachOObjectFile>();
387 if (!Objects) {
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100388 return errorToErrorCode(Objects.takeError());
Inna Palantff3f07a2019-07-11 16:15:26 -0700389 }
390
391 std::vector<std::unique_ptr<DebugMap>> Results;
392 for (const auto *Object : *Objects)
393 if (shouldLinkArch(Archs, Object->getArchTriple().getArchName()))
394 Results.push_back(parseOneBinary(*Object, BinaryPath));
395
396 return std::move(Results);
397}
398
399/// Interpret the STAB entries to fill the DebugMap.
400void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex,
401 uint8_t Type,
402 uint8_t SectionIndex,
403 uint16_t Flags,
404 uint64_t Value) {
405 if (!(Type & MachO::N_STAB))
406 return;
407
408 const char *Name = &MainBinaryStrings.data()[StringIndex];
409
410 // An N_OSO entry represents the start of a new object file description.
411 if (Type == MachO::N_OSO)
412 return switchToNewDebugMapObject(Name, sys::toTimePoint(Value));
413
414 if (Type == MachO::N_AST) {
415 SmallString<80> Path(PathPrefix);
416 sys::path::append(Path, Name);
417 Result->addDebugMapObject(Path, sys::toTimePoint(Value), Type);
418 return;
419 }
420
421 // If the last N_OSO object file wasn't found, CurrentDebugMapObject will be
422 // null. Do not update anything until we find the next valid N_OSO entry.
423 if (!CurrentDebugMapObject)
424 return;
425
426 uint32_t Size = 0;
427 switch (Type) {
428 case MachO::N_GSYM:
429 // This is a global variable. We need to query the main binary
430 // symbol table to find its address as it might not be in the
431 // debug map (for common symbols).
432 Value = getMainBinarySymbolAddress(Name);
433 break;
434 case MachO::N_FUN:
435 // Functions are scopes in STABS. They have an end marker that
436 // contains the function size.
437 if (Name[0] == '\0') {
438 Size = Value;
439 Value = CurrentFunctionAddress;
440 Name = CurrentFunctionName;
441 break;
442 } else {
443 CurrentFunctionName = Name;
444 CurrentFunctionAddress = Value;
445 return;
446 }
447 case MachO::N_STSYM:
448 break;
449 default:
450 return;
451 }
452
453 auto ObjectSymIt = CurrentObjectAddresses.find(Name);
454
455 // If the name of a (non-static) symbol is not in the current object, we
456 // check all its aliases from the main binary.
457 if (ObjectSymIt == CurrentObjectAddresses.end() && Type != MachO::N_STSYM) {
458 for (const auto &Alias : getMainBinarySymbolNames(Value)) {
459 ObjectSymIt = CurrentObjectAddresses.find(Alias);
460 if (ObjectSymIt != CurrentObjectAddresses.end())
461 break;
462 }
463 }
464
Chris Wailesbcf972c2021-10-21 11:03:28 -0700465 // ThinLTO adds a unique suffix to exported private symbols.
466 if (ObjectSymIt == CurrentObjectAddresses.end()) {
467 for (auto Iter = CurrentObjectAddresses.begin();
468 Iter != CurrentObjectAddresses.end(); ++Iter) {
469 llvm::StringRef SymbolName = Iter->getKey();
470 auto Pos = SymbolName.rfind(".llvm.");
471 if (Pos != llvm::StringRef::npos && SymbolName.substr(0, Pos) == Name) {
472 ObjectSymIt = Iter;
473 break;
474 }
475 }
476 }
477
Inna Palantff3f07a2019-07-11 16:15:26 -0700478 if (ObjectSymIt == CurrentObjectAddresses.end()) {
479 Warning("could not find object file symbol for symbol " + Twine(Name));
480 return;
481 }
482
483 if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value,
484 Size)) {
485 Warning(Twine("failed to insert symbol '") + Name + "' in the debug map.");
486 return;
487 }
488}
489
490/// Load the current object file symbols into CurrentObjectAddresses.
491void MachODebugMapParser::loadCurrentObjectFileSymbols(
492 const object::MachOObjectFile &Obj) {
493 CurrentObjectAddresses.clear();
494
495 for (auto Sym : Obj.symbols()) {
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100496 uint64_t Addr = cantFail(Sym.getValue());
Inna Palantff3f07a2019-07-11 16:15:26 -0700497 Expected<StringRef> Name = Sym.getName();
498 if (!Name) {
499 // TODO: Actually report errors helpfully.
500 consumeError(Name.takeError());
501 continue;
502 }
503 // The value of some categories of symbols isn't meaningful. For
504 // example common symbols store their size in the value field, not
505 // their address. Absolute symbols have a fixed address that can
506 // conflict with standard symbols. These symbols (especially the
507 // common ones), might still be referenced by relocations. These
508 // relocations will use the symbol itself, and won't need an
509 // object file address. The object file address field is optional
510 // in the DebugMap, leave it unassigned for these symbols.
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100511 uint32_t Flags = cantFail(Sym.getFlags());
Jeff Vander Stoep247d86b2020-08-11 14:27:44 +0200512 if (Flags & SymbolRef::SF_Absolute) {
Inna Palantff3f07a2019-07-11 16:15:26 -0700513 CurrentObjectAddresses[*Name] = None;
Jeff Vander Stoep247d86b2020-08-11 14:27:44 +0200514 } else if (Flags & SymbolRef::SF_Common) {
515 CurrentObjectAddresses[*Name] = None;
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100516 CommonSymbols.push_back(std::string(*Name));
Jeff Vander Stoep247d86b2020-08-11 14:27:44 +0200517 } else {
Inna Palantff3f07a2019-07-11 16:15:26 -0700518 CurrentObjectAddresses[*Name] = Addr;
Jeff Vander Stoep247d86b2020-08-11 14:27:44 +0200519 }
Inna Palantff3f07a2019-07-11 16:15:26 -0700520 }
521}
522
523/// Lookup a symbol address in the main binary symbol table. The
524/// parser only needs to query common symbols, thus not every symbol's
525/// address is available through this function.
526uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) {
527 auto Sym = MainBinarySymbolAddresses.find(Name);
528 if (Sym == MainBinarySymbolAddresses.end())
529 return 0;
530 return Sym->second;
531}
532
533/// Get all symbol names in the main binary for the given value.
534std::vector<StringRef>
535MachODebugMapParser::getMainBinarySymbolNames(uint64_t Value) {
536 std::vector<StringRef> Names;
537 for (const auto &Entry : MainBinarySymbolAddresses) {
538 if (Entry.second == Value)
539 Names.push_back(Entry.first());
540 }
541 return Names;
542}
543
544/// Load the interesting main binary symbols' addresses into
545/// MainBinarySymbolAddresses.
546void MachODebugMapParser::loadMainBinarySymbols(
547 const MachOObjectFile &MainBinary) {
548 section_iterator Section = MainBinary.section_end();
549 MainBinarySymbolAddresses.clear();
550 for (const auto &Sym : MainBinary.symbols()) {
551 Expected<SymbolRef::Type> TypeOrErr = Sym.getType();
552 if (!TypeOrErr) {
553 // TODO: Actually report errors helpfully.
554 consumeError(TypeOrErr.takeError());
555 continue;
556 }
557 SymbolRef::Type Type = *TypeOrErr;
558 // Skip undefined and STAB entries.
559 if ((Type == SymbolRef::ST_Debug) || (Type == SymbolRef::ST_Unknown))
560 continue;
561 // In theory, the only symbols of interest are the global variables. These
562 // are the only ones that need to be queried because the address of common
563 // data won't be described in the debug map. All other addresses should be
564 // fetched for the debug map. In reality, by playing with 'ld -r' and
565 // export lists, you can get symbols described as N_GSYM in the debug map,
566 // but associated with a local symbol. Gather all the symbols, but prefer
567 // the global ones.
568 uint8_t SymType =
569 MainBinary.getSymbolTableEntry(Sym.getRawDataRefImpl()).n_type;
570 bool Extern = SymType & (MachO::N_EXT | MachO::N_PEXT);
571 Expected<section_iterator> SectionOrErr = Sym.getSection();
572 if (!SectionOrErr) {
573 // TODO: Actually report errors helpfully.
574 consumeError(SectionOrErr.takeError());
575 continue;
576 }
577 Section = *SectionOrErr;
Chris Wailese3116c42021-07-13 14:40:48 -0700578 if ((Section == MainBinary.section_end() || Section->isText()) && !Extern)
Inna Palantff3f07a2019-07-11 16:15:26 -0700579 continue;
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100580 uint64_t Addr = cantFail(Sym.getValue());
Inna Palantff3f07a2019-07-11 16:15:26 -0700581 Expected<StringRef> NameOrErr = Sym.getName();
582 if (!NameOrErr) {
583 // TODO: Actually report errors helpfully.
584 consumeError(NameOrErr.takeError());
585 continue;
586 }
587 StringRef Name = *NameOrErr;
588 if (Name.size() == 0 || Name[0] == '\0')
589 continue;
590 // Override only if the new key is global.
591 if (Extern)
592 MainBinarySymbolAddresses[Name] = Addr;
593 else
594 MainBinarySymbolAddresses.try_emplace(Name, Addr);
595 }
596}
597
598namespace llvm {
599namespace dsymutil {
600llvm::ErrorOr<std::vector<std::unique_ptr<DebugMap>>>
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100601parseDebugMap(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
602 StringRef InputFile, ArrayRef<std::string> Archs,
Inna Palantff3f07a2019-07-11 16:15:26 -0700603 StringRef PrependPath, bool PaperTrailWarnings, bool Verbose,
604 bool InputIsYAML) {
605 if (InputIsYAML)
606 return DebugMap::parseYAMLDebugMap(InputFile, PrependPath, Verbose);
607
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100608 MachODebugMapParser Parser(VFS, InputFile, Archs, PrependPath,
609 PaperTrailWarnings, Verbose);
Inna Palantff3f07a2019-07-11 16:15:26 -0700610 return Parser.parse();
611}
612
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100613bool dumpStab(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS,
614 StringRef InputFile, ArrayRef<std::string> Archs,
Inna Palantff3f07a2019-07-11 16:15:26 -0700615 StringRef PrependPath) {
Thiébaud Weksteene40e7362020-10-28 15:03:00 +0100616 MachODebugMapParser Parser(VFS, InputFile, Archs, PrependPath, false);
Inna Palantff3f07a2019-07-11 16:15:26 -0700617 return Parser.dumpStab();
618}
619} // namespace dsymutil
620} // namespace llvm