1 //===- tools/dsymutil/MachODebugMapParser.cpp - Parse STABS debug maps ----===// 2 // 3 // The LLVM Linker 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "BinaryHolder.h" 11 #include "DebugMap.h" 12 #include "dsymutil.h" 13 #include "llvm/Object/MachO.h" 14 #include "llvm/Support/Path.h" 15 #include "llvm/Support/raw_ostream.h" 16 17 namespace { 18 using namespace llvm; 19 using namespace llvm::dsymutil; 20 using namespace llvm::object; 21 22 class MachODebugMapParser { 23 public: 24 MachODebugMapParser(StringRef BinaryPath, StringRef PathPrefix = "", 25 bool Verbose = false) 26 : BinaryPath(BinaryPath), PathPrefix(PathPrefix), 27 MainBinaryHolder(Verbose), CurrentObjectHolder(Verbose), 28 CurrentDebugMapObject(nullptr) {} 29 30 /// \brief Parses and returns the DebugMap of the input binary. 31 /// \returns an error in case the provided BinaryPath doesn't exist 32 /// or isn't of a supported type. 33 ErrorOr<std::unique_ptr<DebugMap>> parse(); 34 35 private: 36 std::string BinaryPath; 37 std::string PathPrefix; 38 39 /// Owns the MemoryBuffer for the main binary. 40 BinaryHolder MainBinaryHolder; 41 /// Map of the binary symbol addresses. 42 StringMap<uint64_t> MainBinarySymbolAddresses; 43 StringRef MainBinaryStrings; 44 /// The constructed DebugMap. 45 std::unique_ptr<DebugMap> Result; 46 47 /// Owns the MemoryBuffer for the currently handled object file. 48 BinaryHolder CurrentObjectHolder; 49 /// Map of the currently processed object file symbol addresses. 50 StringMap<uint64_t> CurrentObjectAddresses; 51 /// Element of the debug map corresponfing to the current object file. 52 DebugMapObject *CurrentDebugMapObject; 53 54 /// Holds function info while function scope processing. 55 const char *CurrentFunctionName; 56 uint64_t CurrentFunctionAddress; 57 58 void switchToNewDebugMapObject(StringRef Filename, sys::TimeValue Timestamp); 59 void resetParserState(); 60 uint64_t getMainBinarySymbolAddress(StringRef Name); 61 void loadMainBinarySymbols(); 62 void loadCurrentObjectFileSymbols(); 63 void handleStabSymbolTableEntry(uint32_t StringIndex, uint8_t Type, 64 uint8_t SectionIndex, uint16_t Flags, 65 uint64_t Value); 66 67 template <typename STEType> void handleStabDebugMapEntry(const STEType &STE) { 68 handleStabSymbolTableEntry(STE.n_strx, STE.n_type, STE.n_sect, STE.n_desc, 69 STE.n_value); 70 } 71 }; 72 73 static void Warning(const Twine &Msg) { errs() << "warning: " + Msg + "\n"; } 74 } 75 76 /// Reset the parser state coresponding to the current object 77 /// file. This is to be called after an object file is finished 78 /// processing. 79 void MachODebugMapParser::resetParserState() { 80 CurrentObjectAddresses.clear(); 81 CurrentDebugMapObject = nullptr; 82 } 83 84 /// Create a new DebugMapObject. This function resets the state of the 85 /// parser that was referring to the last object file and sets 86 /// everything up to add symbols to the new one. 87 void MachODebugMapParser::switchToNewDebugMapObject(StringRef Filename, 88 sys::TimeValue Timestamp) { 89 resetParserState(); 90 91 SmallString<80> Path(PathPrefix); 92 sys::path::append(Path, Filename); 93 94 auto MachOOrError = 95 CurrentObjectHolder.GetFileAs<MachOObjectFile>(Path, Timestamp); 96 if (auto Error = MachOOrError.getError()) { 97 Warning(Twine("cannot open debug object \"") + Path.str() + "\": " + 98 Error.message() + "\n"); 99 return; 100 } 101 102 loadCurrentObjectFileSymbols(); 103 CurrentDebugMapObject = &Result->addDebugMapObject(Path, Timestamp); 104 } 105 106 /// This main parsing routine tries to open the main binary and if 107 /// successful iterates over the STAB entries. The real parsing is 108 /// done in handleStabSymbolTableEntry. 109 ErrorOr<std::unique_ptr<DebugMap>> MachODebugMapParser::parse() { 110 auto MainBinOrError = MainBinaryHolder.GetFileAs<MachOObjectFile>(BinaryPath); 111 if (auto Error = MainBinOrError.getError()) 112 return Error; 113 114 const MachOObjectFile &MainBinary = *MainBinOrError; 115 loadMainBinarySymbols(); 116 Result = make_unique<DebugMap>(BinaryHolder::getTriple(MainBinary)); 117 MainBinaryStrings = MainBinary.getStringTableData(); 118 for (const SymbolRef &Symbol : MainBinary.symbols()) { 119 const DataRefImpl &DRI = Symbol.getRawDataRefImpl(); 120 if (MainBinary.is64Bit()) 121 handleStabDebugMapEntry(MainBinary.getSymbol64TableEntry(DRI)); 122 else 123 handleStabDebugMapEntry(MainBinary.getSymbolTableEntry(DRI)); 124 } 125 126 resetParserState(); 127 return std::move(Result); 128 } 129 130 /// Interpret the STAB entries to fill the DebugMap. 131 void MachODebugMapParser::handleStabSymbolTableEntry(uint32_t StringIndex, 132 uint8_t Type, 133 uint8_t SectionIndex, 134 uint16_t Flags, 135 uint64_t Value) { 136 if (!(Type & MachO::N_STAB)) 137 return; 138 139 const char *Name = &MainBinaryStrings.data()[StringIndex]; 140 141 // An N_OSO entry represents the start of a new object file description. 142 if (Type == MachO::N_OSO) { 143 sys::TimeValue Timestamp; 144 Timestamp.fromEpochTime(Value); 145 return switchToNewDebugMapObject(Name, Timestamp); 146 } 147 148 // If the last N_OSO object file wasn't found, 149 // CurrentDebugMapObject will be null. Do not update anything 150 // until we find the next valid N_OSO entry. 151 if (!CurrentDebugMapObject) 152 return; 153 154 uint32_t Size = 0; 155 switch (Type) { 156 case MachO::N_GSYM: 157 // This is a global variable. We need to query the main binary 158 // symbol table to find its address as it might not be in the 159 // debug map (for common symbols). 160 Value = getMainBinarySymbolAddress(Name); 161 break; 162 case MachO::N_FUN: 163 // Functions are scopes in STABS. They have an end marker that 164 // contains the function size. 165 if (Name[0] == '\0') { 166 Size = Value; 167 Value = CurrentFunctionAddress; 168 Name = CurrentFunctionName; 169 break; 170 } else { 171 CurrentFunctionName = Name; 172 CurrentFunctionAddress = Value; 173 return; 174 } 175 case MachO::N_STSYM: 176 break; 177 default: 178 return; 179 } 180 181 auto ObjectSymIt = CurrentObjectAddresses.find(Name); 182 if (ObjectSymIt == CurrentObjectAddresses.end()) 183 return Warning("could not find object file symbol for symbol " + 184 Twine(Name)); 185 if (!CurrentDebugMapObject->addSymbol(Name, ObjectSymIt->getValue(), Value, 186 Size)) 187 return Warning(Twine("failed to insert symbol '") + Name + 188 "' in the debug map."); 189 } 190 191 /// Load the current object file symbols into CurrentObjectAddresses. 192 void MachODebugMapParser::loadCurrentObjectFileSymbols() { 193 CurrentObjectAddresses.clear(); 194 195 for (auto Sym : CurrentObjectHolder.Get().symbols()) { 196 uint64_t Addr = Sym.getValue(); 197 ErrorOr<StringRef> Name = Sym.getName(); 198 if (!Name) 199 continue; 200 CurrentObjectAddresses[*Name] = Addr; 201 } 202 } 203 204 /// Lookup a symbol address in the main binary symbol table. The 205 /// parser only needs to query common symbols, thus not every symbol's 206 /// address is available through this function. 207 uint64_t MachODebugMapParser::getMainBinarySymbolAddress(StringRef Name) { 208 auto Sym = MainBinarySymbolAddresses.find(Name); 209 if (Sym == MainBinarySymbolAddresses.end()) 210 return 0; 211 return Sym->second; 212 } 213 214 /// Load the interesting main binary symbols' addresses into 215 /// MainBinarySymbolAddresses. 216 void MachODebugMapParser::loadMainBinarySymbols() { 217 const MachOObjectFile &MainBinary = MainBinaryHolder.GetAs<MachOObjectFile>(); 218 section_iterator Section = MainBinary.section_end(); 219 for (const auto &Sym : MainBinary.symbols()) { 220 SymbolRef::Type Type = Sym.getType(); 221 // Skip undefined and STAB entries. 222 if ((Type & SymbolRef::ST_Debug) || (Type & SymbolRef::ST_Unknown)) 223 continue; 224 // The only symbols of interest are the global variables. These 225 // are the only ones that need to be queried because the address 226 // of common data won't be described in the debug map. All other 227 // addresses should be fetched for the debug map. 228 if (!(Sym.getFlags() & SymbolRef::SF_Global) || Sym.getSection(Section) || 229 Section == MainBinary.section_end() || Section->isText()) 230 continue; 231 uint64_t Addr = Sym.getValue(); 232 ErrorOr<StringRef> NameOrErr = Sym.getName(); 233 if (!NameOrErr) 234 continue; 235 StringRef Name = *NameOrErr; 236 if (Name.size() == 0 || Name[0] == '\0') 237 continue; 238 MainBinarySymbolAddresses[Name] = Addr; 239 } 240 } 241 242 namespace llvm { 243 namespace dsymutil { 244 llvm::ErrorOr<std::unique_ptr<DebugMap>> parseDebugMap(StringRef InputFile, 245 StringRef PrependPath, 246 bool Verbose, 247 bool InputIsYAML) { 248 if (!InputIsYAML) { 249 MachODebugMapParser Parser(InputFile, PrependPath, Verbose); 250 return Parser.parse(); 251 } else { 252 return DebugMap::parseYAMLDebugMap(InputFile, PrependPath, Verbose); 253 } 254 } 255 } 256 } 257