1 //===- tools/dsymutil/MachODebugMapParser.cpp - Parse STABS debug maps ----===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "BinaryHolder.h"
13 #include "llvm/Object/MachO.h"
14 #include "llvm/Support/Path.h"
15 #include "llvm/Support/raw_ostream.h"
19 using namespace llvm::dsymutil;
20 using namespace llvm::object;
22 class MachODebugMapParser {
24 MachODebugMapParser(StringRef BinaryPath, ArrayRef<std::string> Archs,
25 StringRef PathPrefix = "", bool Verbose = false)
26 : BinaryPath(BinaryPath), Archs(Archs.begin(), Archs.end()),
27 PathPrefix(PathPrefix), MainBinaryHolder(Verbose),
28 CurrentObjectHolder(Verbose), CurrentDebugMapObject(nullptr) {}
30 /// \brief Parses and returns the DebugMaps of the input binary.
31 /// The binary contains multiple maps in case it is a universal
33 /// \returns an error in case the provided BinaryPath doesn't exist
34 /// or isn't of a supported type.
35 ErrorOr<std::vector<std::unique_ptr<DebugMap>>> parse();
38 std::string BinaryPath;
39 SmallVector<StringRef, 1> Archs;
40 std::string PathPrefix;
42 /// Owns the MemoryBuffer for the main binary.
43 BinaryHolder MainBinaryHolder;
44 /// Map of the binary symbol addresses.
45 StringMap<uint64_t> MainBinarySymbolAddresses;
46 StringRef MainBinaryStrings;
47 /// The constructed DebugMap.
48 std::unique_ptr<DebugMap> Result;
50 /// Owns the MemoryBuffer for the currently handled object file.
51 BinaryHolder CurrentObjectHolder;
52 /// Map of the currently processed object file symbol addresses.
53 StringMap<uint64_t> CurrentObjectAddresses;
54 /// Element of the debug map corresponfing to the current object file.
55 DebugMapObject *CurrentDebugMapObject;
57 /// Holds function info while function scope processing.
58 const char *CurrentFunctionName;
59 uint64_t CurrentFunctionAddress;
61 std::unique_ptr<DebugMap> parseOneBinary(const MachOObjectFile &MainBinary,
62 StringRef BinaryPath);
64 void switchToNewDebugMapObject(StringRef Filename, sys::TimeValue Timestamp);
65 void resetParserState();
66 uint64_t getMainBinarySymbolAddress(StringRef Name);
67 void loadMainBinarySymbols(const MachOObjectFile &MainBinary);
68 void loadCurrentObjectFileSymbols(const object::MachOObjectFile &Obj);
69 void handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type,
70 uint8_t SectionIndex, uint16_t Flags,
73 template <typename STEType> void handleStabDebugMapEntry(const STEType &STE) {
74 handleStabSymbolTableEntry(STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc,
79 static void Warning(const Twine &Msg) { errs() << "warning: " + Msg + "\n"; }
82 /// Reset the parser state coresponding to the current object
83 /// file. This is to be called after an object file is finished
85 void MachODebugMapParser::resetParserState() {
86 CurrentObjectAddresses.clear();
87 CurrentDebugMapObject = nullptr;
90 /// Create a new DebugMapObject. This function resets the state of the
91 /// parser that was referring to the last object file and sets
92 /// everything up to add symbols to the new one.
93 void MachODebugMapParser::switchToNewDebugMapObject(StringRef Filename,
94 sys::TimeValue Timestamp) {
97 SmallString<80> Path(PathPrefix);
98 sys::path::append(Path, Filename);
101 CurrentObjectHolder.GetFilesAs<MachOObjectFile>(Path, Timestamp);
102 if (auto Error = MachOOrError.getError()) {
103 Warning(Twine("cannot open debug object \"") + Path.str() + "\": " +
104 Error.message() + "\n");
109 CurrentObjectHolder.GetAs<MachOObjectFile>(Result->getTriple());
110 if (auto Err = ErrOrAchObj.getError()) {
111 return Warning(Twine("cannot open debug object \"") + Path.str() + "\": " +
112 Err.message() + "\n");
115 CurrentDebugMapObject = &Result->addDebugMapObject(Path, Timestamp);
116 loadCurrentObjectFileSymbols(*ErrOrAchObj);
119 std::unique_ptr<DebugMap>
120 MachODebugMapParser::parseOneBinary(const MachOObjectFile &MainBinary,
121 StringRef BinaryPath) {
122 loadMainBinarySymbols(MainBinary);
124 make_unique<DebugMap>(BinaryHolder::getTriple(MainBinary), BinaryPath);
125 MainBinaryStrings = MainBinary.getStringTableData();
126 for (const SymbolRef &Symbol : MainBinary.symbols()) {
127 const DataRefImpl &DRI = Symbol.getRawDataRefImpl();
128 if (MainBinary.is64Bit())
129 handleStabDebugMapEntry(MainBinary.getSymbol64TableEntry(DRI));
131 handleStabDebugMapEntry(MainBinary.getSymbolTableEntry(DRI));
135 return std::move(Result);
138 static bool shouldLinkArch(SmallVectorImpl<StringRef> &Archs, StringRef Arch) {
140 std::find(Archs.begin(), Archs.end(), "all") != Archs.end() ||
141 std::find(Archs.begin(), Archs.end(), "*") != Archs.end())
144 if (Arch.startswith("arm") && Arch != "arm64" &&
145 std::find(Archs.begin(), Archs.end(), "arm") != Archs.end())
148 return std::find(Archs.begin(), Archs.end(), Arch) != Archs.end();
151 /// This main parsing routine tries to open the main binary and if
152 /// successful iterates over the STAB entries. The real parsing is
153 /// done in handleStabSymbolTableEntry.
154 ErrorOr<std::vector<std::unique_ptr<DebugMap>>> MachODebugMapParser::parse() {
155 auto MainBinOrError =
156 MainBinaryHolder.GetFilesAs<MachOObjectFile>(BinaryPath);
157 if (auto Error = MainBinOrError.getError())
160 std::vector<std::unique_ptr<DebugMap>> Results;
162 for (const auto *Binary : *MainBinOrError)
163 if (shouldLinkArch(Archs, Binary->getArch(nullptr, &T).getArchName()))
164 Results.push_back(parseOneBinary(*Binary, BinaryPath));
166 return std::move(Results);
169 /// Interpret the STAB entries to fill the DebugMap.
170 void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex,
172 uint8_t SectionIndex,
175 if (!(Type & MachO::N_STAB))
178 const char *Name = &MainBinaryStrings.data()[StringIndex];
180 // An N_OSO entry represents the start of a new object file description.
181 if (Type == MachO::N_OSO) {
182 sys::TimeValue Timestamp;
183 Timestamp.fromEpochTime(Value);
184 return switchToNewDebugMapObject(Name, Timestamp);
187 // If the last N_OSO object file wasn't found,
188 // CurrentDebugMapObject will be null. Do not update anything
189 // until we find the next valid N_OSO entry.
190 if (!CurrentDebugMapObject)
196 // This is a global variable. We need to query the main binary
197 // symbol table to find its address as it might not be in the
198 // debug map (for common symbols).
199 Value = getMainBinarySymbolAddress(Name);
202 // Functions are scopes in STABS. They have an end marker that
203 // contains the function size.
204 if (Name[0] == '\0') {
206 Value = CurrentFunctionAddress;
207 Name = CurrentFunctionName;
210 CurrentFunctionName = Name;
211 CurrentFunctionAddress = Value;
220 auto ObjectSymIt = CurrentObjectAddresses.find(Name);
221 if (ObjectSymIt == CurrentObjectAddresses.end())
222 return Warning("could not find object file symbol for symbol " +
224 if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value,
226 return Warning(Twine("failed to insert symbol '") + Name +
227 "' in the debug map.");
230 /// Load the current object file symbols into CurrentObjectAddresses.
231 void MachODebugMapParser::loadCurrentObjectFileSymbols(
232 const object::MachOObjectFile &Obj) {
233 CurrentObjectAddresses.clear();
235 for (auto Sym : Obj.symbols()) {
236 uint64_t Addr = Sym.getValue();
237 ErrorOr<StringRef> Name = Sym.getName();
240 CurrentObjectAddresses[*Name] = Addr;
244 /// Lookup a symbol address in the main binary symbol table. The
245 /// parser only needs to query common symbols, thus not every symbol's
246 /// address is available through this function.
247 uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) {
248 auto Sym = MainBinarySymbolAddresses.find(Name);
249 if (Sym == MainBinarySymbolAddresses.end())
254 /// Load the interesting main binary symbols' addresses into
255 /// MainBinarySymbolAddresses.
256 void MachODebugMapParser::loadMainBinarySymbols(
257 const MachOObjectFile &MainBinary) {
258 section_iterator Section = MainBinary.section_end();
259 MainBinarySymbolAddresses.clear();
260 for (const auto &Sym : MainBinary.symbols()) {
261 SymbolRef::Type Type = Sym.getType();
262 // Skip undefined and STAB entries.
263 if ((Type & SymbolRef::ST_Debug) || (Type & SymbolRef::ST_Unknown))
265 // The only symbols of interest are the global variables. These
266 // are the only ones that need to be queried because the address
267 // of common data won't be described in the debug map. All other
268 // addresses should be fetched for the debug map.
269 if (!(Sym.getFlags() & SymbolRef::SF_Global))
271 ErrorOr<section_iterator> SectionOrErr = Sym.getSection();
274 Section = *SectionOrErr;
275 if (Section == MainBinary.section_end() || Section->isText())
277 uint64_t Addr = Sym.getValue();
278 ErrorOr<StringRef> NameOrErr = Sym.getName();
281 StringRef Name = *NameOrErr;
282 if (Name.size() == 0 || Name[0] == '\0')
284 MainBinarySymbolAddresses[Name] = Addr;
290 llvm::ErrorOr<std::vector<std::unique_ptr<DebugMap>>>
291 parseDebugMap(StringRef InputFile, ArrayRef<std::string> Archs,
292 StringRef PrependPath, bool Verbose, bool InputIsYAML) {
294 MachODebugMapParser Parser(InputFile, Archs, PrependPath, Verbose);
295 return Parser.parse();
297 return DebugMap::parseYAMLDebugMap(InputFile, PrependPath, Verbose);