1 //===-- LLVMSymbolize.cpp -------------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Implementation for LLVM symbolization library. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/DebugInfo/Symbolize/Symbolize.h" 15 16 #include "SymbolizableObjectFile.h" 17 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/Config/config.h" 20 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 21 #include "llvm/DebugInfo/PDB/PDB.h" 22 #include "llvm/DebugInfo/PDB/PDBContext.h" 23 #include "llvm/Object/ELFObjectFile.h" 24 #include "llvm/Object/MachO.h" 25 #include "llvm/Object/MachOUniversal.h" 26 #include "llvm/Support/COFF.h" 27 #include "llvm/Support/Casting.h" 28 #include "llvm/Support/Compression.h" 29 #include "llvm/Support/DataExtractor.h" 30 #include "llvm/Support/Errc.h" 31 #include "llvm/Support/FileSystem.h" 32 #include "llvm/Support/MemoryBuffer.h" 33 #include "llvm/Support/Path.h" 34 #include <algorithm> 35 #include <cassert> 36 #include <cstdlib> 37 #include <cstring> 38 39 #if defined(_MSC_VER) 40 #include <Windows.h> 41 #include <DbgHelp.h> 42 #pragma comment(lib, "dbghelp.lib") 43 44 // Windows.h conflicts with our COFF header definitions. 45 #ifdef IMAGE_FILE_MACHINE_I386 46 #undef IMAGE_FILE_MACHINE_I386 47 #endif 48 #endif 49 50 namespace llvm { 51 namespace symbolize { 52 53 ErrorOr<DILineInfo> LLVMSymbolizer::symbolizeCode(const std::string &ModuleName, 54 uint64_t ModuleOffset) { 55 auto InfoOrErr = getOrCreateModuleInfo(ModuleName); 56 if (auto EC = InfoOrErr.getError()) 57 return EC; 58 SymbolizableModule *Info = InfoOrErr.get(); 59 60 // If the user is giving us relative addresses, add the preferred base of the 61 // object to the offset before we do the query. It's what DIContext expects. 62 if (Opts.RelativeAddresses) 63 ModuleOffset += Info->getModulePreferredBase(); 64 65 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions, 66 Opts.UseSymbolTable); 67 if (Opts.Demangle) 68 LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info); 69 return LineInfo; 70 } 71 72 ErrorOr<DIInliningInfo> 73 LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName, 74 uint64_t ModuleOffset) { 75 auto InfoOrErr = getOrCreateModuleInfo(ModuleName); 76 if (auto EC = InfoOrErr.getError()) 77 return EC; 78 SymbolizableModule *Info = InfoOrErr.get(); 79 80 // If the user is giving us relative addresses, add the preferred base of the 81 // object to the offset before we do the query. It's what DIContext expects. 82 if (Opts.RelativeAddresses) 83 ModuleOffset += Info->getModulePreferredBase(); 84 85 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode( 86 ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable); 87 if (Opts.Demangle) { 88 for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) { 89 auto *Frame = InlinedContext.getMutableFrame(i); 90 Frame->FunctionName = DemangleName(Frame->FunctionName, Info); 91 } 92 } 93 return InlinedContext; 94 } 95 96 ErrorOr<DIGlobal> LLVMSymbolizer::symbolizeData(const std::string &ModuleName, 97 uint64_t ModuleOffset) { 98 auto InfoOrErr = getOrCreateModuleInfo(ModuleName); 99 if (auto EC = InfoOrErr.getError()) 100 return EC; 101 SymbolizableModule *Info = InfoOrErr.get(); 102 103 // If the user is giving us relative addresses, add the preferred base of 104 // the object to the offset before we do the query. It's what DIContext 105 // expects. 106 if (Opts.RelativeAddresses) 107 ModuleOffset += Info->getModulePreferredBase(); 108 109 DIGlobal Global = Info->symbolizeData(ModuleOffset); 110 if (Opts.Demangle) 111 Global.Name = DemangleName(Global.Name, Info); 112 return Global; 113 } 114 115 void LLVMSymbolizer::flush() { 116 ObjectForUBPathAndArch.clear(); 117 BinaryForPath.clear(); 118 ObjectPairForPathArch.clear(); 119 Modules.clear(); 120 } 121 122 namespace { 123 124 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in 125 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo. 126 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in 127 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo. 128 std::string getDarwinDWARFResourceForPath( 129 const std::string &Path, const std::string &Basename) { 130 SmallString<16> ResourceName = StringRef(Path); 131 if (sys::path::extension(Path) != ".dSYM") { 132 ResourceName += ".dSYM"; 133 } 134 sys::path::append(ResourceName, "Contents", "Resources", "DWARF"); 135 sys::path::append(ResourceName, Basename); 136 return ResourceName.str(); 137 } 138 139 bool checkFileCRC(StringRef Path, uint32_t CRCHash) { 140 ErrorOr<std::unique_ptr<MemoryBuffer>> MB = 141 MemoryBuffer::getFileOrSTDIN(Path); 142 if (!MB) 143 return false; 144 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer()); 145 } 146 147 bool findDebugBinary(const std::string &OrigPath, 148 const std::string &DebuglinkName, uint32_t CRCHash, 149 std::string &Result) { 150 std::string OrigRealPath = OrigPath; 151 #if defined(HAVE_REALPATH) 152 if (char *RP = realpath(OrigPath.c_str(), nullptr)) { 153 OrigRealPath = RP; 154 free(RP); 155 } 156 #endif 157 SmallString<16> OrigDir(OrigRealPath); 158 llvm::sys::path::remove_filename(OrigDir); 159 SmallString<16> DebugPath = OrigDir; 160 // Try /path/to/original_binary/debuglink_name 161 llvm::sys::path::append(DebugPath, DebuglinkName); 162 if (checkFileCRC(DebugPath, CRCHash)) { 163 Result = DebugPath.str(); 164 return true; 165 } 166 // Try /path/to/original_binary/.debug/debuglink_name 167 DebugPath = OrigRealPath; 168 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName); 169 if (checkFileCRC(DebugPath, CRCHash)) { 170 Result = DebugPath.str(); 171 return true; 172 } 173 // Try /usr/lib/debug/path/to/original_binary/debuglink_name 174 DebugPath = "/usr/lib/debug"; 175 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir), 176 DebuglinkName); 177 if (checkFileCRC(DebugPath, CRCHash)) { 178 Result = DebugPath.str(); 179 return true; 180 } 181 return false; 182 } 183 184 bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName, 185 uint32_t &CRCHash) { 186 if (!Obj) 187 return false; 188 for (const SectionRef &Section : Obj->sections()) { 189 StringRef Name; 190 Section.getName(Name); 191 Name = Name.substr(Name.find_first_not_of("._")); 192 if (Name == "gnu_debuglink") { 193 StringRef Data; 194 Section.getContents(Data); 195 DataExtractor DE(Data, Obj->isLittleEndian(), 0); 196 uint32_t Offset = 0; 197 if (const char *DebugNameStr = DE.getCStr(&Offset)) { 198 // 4-byte align the offset. 199 Offset = (Offset + 3) & ~0x3; 200 if (DE.isValidOffsetForDataOfSize(Offset, 4)) { 201 DebugName = DebugNameStr; 202 CRCHash = DE.getU32(&Offset); 203 return true; 204 } 205 } 206 break; 207 } 208 } 209 return false; 210 } 211 212 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj, 213 const MachOObjectFile *Obj) { 214 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid(); 215 ArrayRef<uint8_t> bin_uuid = Obj->getUuid(); 216 if (dbg_uuid.empty() || bin_uuid.empty()) 217 return false; 218 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size()); 219 } 220 221 } // end anonymous namespace 222 223 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath, 224 const MachOObjectFile *MachExeObj, const std::string &ArchName) { 225 // On Darwin we may find DWARF in separate object file in 226 // resource directory. 227 std::vector<std::string> DsymPaths; 228 StringRef Filename = sys::path::filename(ExePath); 229 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename)); 230 for (const auto &Path : Opts.DsymHints) { 231 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename)); 232 } 233 for (const auto &Path : DsymPaths) { 234 auto DbgObjOrErr = getOrCreateObject(Path, ArchName); 235 if (!DbgObjOrErr) 236 continue; 237 ObjectFile *DbgObj = DbgObjOrErr.get(); 238 const MachOObjectFile *MachDbgObj = dyn_cast<const MachOObjectFile>(DbgObj); 239 if (!MachDbgObj) 240 continue; 241 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) 242 return DbgObj; 243 } 244 return nullptr; 245 } 246 247 ObjectFile *LLVMSymbolizer::lookUpDebuglinkObject(const std::string &Path, 248 const ObjectFile *Obj, 249 const std::string &ArchName) { 250 std::string DebuglinkName; 251 uint32_t CRCHash; 252 std::string DebugBinaryPath; 253 if (!getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash)) 254 return nullptr; 255 if (!findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) 256 return nullptr; 257 auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName); 258 if (!DbgObjOrErr) 259 return nullptr; 260 return DbgObjOrErr.get(); 261 } 262 263 ErrorOr<LLVMSymbolizer::ObjectPair> 264 LLVMSymbolizer::getOrCreateObjectPair(const std::string &Path, 265 const std::string &ArchName) { 266 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName)); 267 if (I != ObjectPairForPathArch.end()) 268 return I->second; 269 270 auto ObjOrErr = getOrCreateObject(Path, ArchName); 271 if (auto EC = ObjOrErr.getError()) { 272 ObjectPairForPathArch.insert( 273 std::make_pair(std::make_pair(Path, ArchName), EC)); 274 return EC; 275 } 276 277 ObjectFile *Obj = ObjOrErr.get(); 278 assert(Obj != nullptr); 279 ObjectFile *DbgObj = nullptr; 280 281 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj)) 282 DbgObj = lookUpDsymFile(Path, MachObj, ArchName); 283 if (!DbgObj) 284 DbgObj = lookUpDebuglinkObject(Path, Obj, ArchName); 285 if (!DbgObj) 286 DbgObj = Obj; 287 ObjectPair Res = std::make_pair(Obj, DbgObj); 288 ObjectPairForPathArch.insert( 289 std::make_pair(std::make_pair(Path, ArchName), Res)); 290 return Res; 291 } 292 293 ErrorOr<ObjectFile *> 294 LLVMSymbolizer::getOrCreateObject(const std::string &Path, 295 const std::string &ArchName) { 296 const auto &I = BinaryForPath.find(Path); 297 Binary *Bin = nullptr; 298 if (I == BinaryForPath.end()) { 299 Expected<OwningBinary<Binary>> BinOrErr = createBinary(Path); 300 if (!BinOrErr) { 301 auto EC = errorToErrorCode(BinOrErr.takeError()); 302 BinaryForPath.insert(std::make_pair(Path, EC)); 303 return EC; 304 } 305 Bin = BinOrErr->getBinary(); 306 BinaryForPath.insert(std::make_pair(Path, std::move(BinOrErr.get()))); 307 } else if (auto EC = I->second.getError()) { 308 return EC; 309 } else { 310 Bin = I->second->getBinary(); 311 } 312 313 assert(Bin != nullptr); 314 315 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) { 316 const auto &I = ObjectForUBPathAndArch.find(std::make_pair(Path, ArchName)); 317 if (I != ObjectForUBPathAndArch.end()) { 318 if (auto EC = I->second.getError()) 319 return EC; 320 return I->second->get(); 321 } 322 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = 323 UB->getObjectForArch(ArchName); 324 if (auto EC = ObjOrErr.getError()) { 325 ObjectForUBPathAndArch.insert( 326 std::make_pair(std::make_pair(Path, ArchName), EC)); 327 return EC; 328 } 329 ObjectFile *Res = ObjOrErr->get(); 330 ObjectForUBPathAndArch.insert(std::make_pair(std::make_pair(Path, ArchName), 331 std::move(ObjOrErr.get()))); 332 return Res; 333 } 334 if (Bin->isObject()) { 335 return cast<ObjectFile>(Bin); 336 } 337 return object_error::arch_not_found; 338 } 339 340 ErrorOr<SymbolizableModule *> 341 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) { 342 const auto &I = Modules.find(ModuleName); 343 if (I != Modules.end()) { 344 auto &InfoOrErr = I->second; 345 if (auto EC = InfoOrErr.getError()) 346 return EC; 347 return InfoOrErr->get(); 348 } 349 std::string BinaryName = ModuleName; 350 std::string ArchName = Opts.DefaultArch; 351 size_t ColonPos = ModuleName.find_last_of(':'); 352 // Verify that substring after colon form a valid arch name. 353 if (ColonPos != std::string::npos) { 354 std::string ArchStr = ModuleName.substr(ColonPos + 1); 355 if (Triple(ArchStr).getArch() != Triple::UnknownArch) { 356 BinaryName = ModuleName.substr(0, ColonPos); 357 ArchName = ArchStr; 358 } 359 } 360 auto ObjectsOrErr = getOrCreateObjectPair(BinaryName, ArchName); 361 if (auto EC = ObjectsOrErr.getError()) { 362 // Failed to find valid object file. 363 Modules.insert(std::make_pair(ModuleName, EC)); 364 return EC; 365 } 366 ObjectPair Objects = ObjectsOrErr.get(); 367 368 std::unique_ptr<DIContext> Context; 369 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) { 370 // If this is a COFF object, assume it contains PDB debug information. If 371 // we don't find any we will fall back to the DWARF case. 372 std::unique_ptr<IPDBSession> Session; 373 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA, 374 Objects.first->getFileName(), Session); 375 if (Error == PDB_ErrorCode::Success) { 376 Context.reset(new PDBContext(*CoffObject, std::move(Session))); 377 } 378 } 379 if (!Context) 380 Context.reset(new DWARFContextInMemory(*Objects.second)); 381 assert(Context); 382 auto InfoOrErr = 383 SymbolizableObjectFile::create(Objects.first, std::move(Context)); 384 auto InsertResult = 385 Modules.insert(std::make_pair(ModuleName, std::move(InfoOrErr))); 386 assert(InsertResult.second); 387 if (auto EC = InsertResult.first->second.getError()) 388 return EC; 389 return InsertResult.first->second->get(); 390 } 391 392 namespace { 393 394 // Undo these various manglings for Win32 extern "C" functions: 395 // cdecl - _foo 396 // stdcall - _foo@12 397 // fastcall - @foo@12 398 // vectorcall - foo@@12 399 // These are all different linkage names for 'foo'. 400 StringRef demanglePE32ExternCFunc(StringRef SymbolName) { 401 // Remove any '_' or '@' prefix. 402 char Front = SymbolName.empty() ? '\0' : SymbolName[0]; 403 if (Front == '_' || Front == '@') 404 SymbolName = SymbolName.drop_front(); 405 406 // Remove any '@[0-9]+' suffix. 407 if (Front != '?') { 408 size_t AtPos = SymbolName.rfind('@'); 409 if (AtPos != StringRef::npos && 410 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(), 411 [](char C) { return C >= '0' && C <= '9'; })) { 412 SymbolName = SymbolName.substr(0, AtPos); 413 } 414 } 415 416 // Remove any ending '@' for vectorcall. 417 if (SymbolName.endswith("@")) 418 SymbolName = SymbolName.drop_back(); 419 420 return SymbolName; 421 } 422 423 } // end anonymous namespace 424 425 #if !defined(_MSC_VER) 426 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows). 427 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer, 428 size_t *length, int *status); 429 #endif 430 431 std::string LLVMSymbolizer::DemangleName(const std::string &Name, 432 const SymbolizableModule *ModInfo) { 433 #if !defined(_MSC_VER) 434 // We can spoil names of symbols with C linkage, so use an heuristic 435 // approach to check if the name should be demangled. 436 if (Name.substr(0, 2) == "_Z") { 437 int status = 0; 438 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status); 439 if (status != 0) 440 return Name; 441 std::string Result = DemangledName; 442 free(DemangledName); 443 return Result; 444 } 445 #else 446 if (!Name.empty() && Name.front() == '?') { 447 // Only do MSVC C++ demangling on symbols starting with '?'. 448 char DemangledName[1024] = {0}; 449 DWORD result = ::UnDecorateSymbolName( 450 Name.c_str(), DemangledName, 1023, 451 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected 452 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc 453 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications 454 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers 455 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords 456 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types 457 return (result == 0) ? Name : std::string(DemangledName); 458 } 459 #endif 460 if (ModInfo && ModInfo->isWin32Module()) 461 return std::string(demanglePE32ExternCFunc(Name)); 462 return Name; 463 } 464 465 } // namespace symbolize 466 } // namespace llvm 467