1 //===-- LLVMSymbolize.cpp -------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implementation for LLVM symbolization library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/DebugInfo/Symbolize/Symbolize.h"
16 #include "SymbolizableObjectFile.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/BinaryFormat/COFF.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
22 #include "llvm/DebugInfo/PDB/PDB.h"
23 #include "llvm/DebugInfo/PDB/PDBContext.h"
24 #include "llvm/Object/COFF.h"
25 #include "llvm/Object/ELFObjectFile.h"
26 #include "llvm/Object/MachO.h"
27 #include "llvm/Object/MachOUniversal.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/Compression.h"
30 #include "llvm/Support/DataExtractor.h"
31 #include "llvm/Support/Errc.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Path.h"
43 // This must be included after windows.h.
45 #pragma comment(lib, "dbghelp.lib")
47 // Windows.h conflicts with our COFF header definitions.
48 #ifdef IMAGE_FILE_MACHINE_I386
49 #undef IMAGE_FILE_MACHINE_I386
56 Expected<DILineInfo> LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
57 uint64_t ModuleOffset) {
58 SymbolizableModule *Info;
59 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
60 Info = InfoOrErr.get();
62 return InfoOrErr.takeError();
64 // A null module means an error has already been reported. Return an empty
69 // If the user is giving us relative addresses, add the preferred base of the
70 // object to the offset before we do the query. It's what DIContext expects.
71 if (Opts.RelativeAddresses)
72 ModuleOffset += Info->getModulePreferredBase();
74 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions,
77 LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
81 Expected<DIInliningInfo>
82 LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
83 uint64_t ModuleOffset) {
84 SymbolizableModule *Info;
85 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
86 Info = InfoOrErr.get();
88 return InfoOrErr.takeError();
90 // A null module means an error has already been reported. Return an empty
93 return DIInliningInfo();
95 // If the user is giving us relative addresses, add the preferred base of the
96 // object to the offset before we do the query. It's what DIContext expects.
97 if (Opts.RelativeAddresses)
98 ModuleOffset += Info->getModulePreferredBase();
100 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
101 ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable);
103 for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
104 auto *Frame = InlinedContext.getMutableFrame(i);
105 Frame->FunctionName = DemangleName(Frame->FunctionName, Info);
108 return InlinedContext;
111 Expected<DIGlobal> LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
112 uint64_t ModuleOffset) {
113 SymbolizableModule *Info;
114 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
115 Info = InfoOrErr.get();
117 return InfoOrErr.takeError();
119 // A null module means an error has already been reported. Return an empty
124 // If the user is giving us relative addresses, add the preferred base of
125 // the object to the offset before we do the query. It's what DIContext
127 if (Opts.RelativeAddresses)
128 ModuleOffset += Info->getModulePreferredBase();
130 DIGlobal Global = Info->symbolizeData(ModuleOffset);
132 Global.Name = DemangleName(Global.Name, Info);
136 void LLVMSymbolizer::flush() {
137 ObjectForUBPathAndArch.clear();
138 BinaryForPath.clear();
139 ObjectPairForPathArch.clear();
145 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
146 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
147 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
148 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
149 std::string getDarwinDWARFResourceForPath(
150 const std::string &Path, const std::string &Basename) {
151 SmallString<16> ResourceName = StringRef(Path);
152 if (sys::path::extension(Path) != ".dSYM") {
153 ResourceName += ".dSYM";
155 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
156 sys::path::append(ResourceName, Basename);
157 return ResourceName.str();
160 bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
161 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
162 MemoryBuffer::getFileOrSTDIN(Path);
165 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
168 bool findDebugBinary(const std::string &OrigPath,
169 const std::string &DebuglinkName, uint32_t CRCHash,
170 std::string &Result) {
171 std::string OrigRealPath = OrigPath;
172 #if defined(HAVE_REALPATH)
173 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
178 SmallString<16> OrigDir(OrigRealPath);
179 llvm::sys::path::remove_filename(OrigDir);
180 SmallString<16> DebugPath = OrigDir;
181 // Try /path/to/original_binary/debuglink_name
182 llvm::sys::path::append(DebugPath, DebuglinkName);
183 if (checkFileCRC(DebugPath, CRCHash)) {
184 Result = DebugPath.str();
187 // Try /path/to/original_binary/.debug/debuglink_name
188 DebugPath = OrigRealPath;
189 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
190 if (checkFileCRC(DebugPath, CRCHash)) {
191 Result = DebugPath.str();
194 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
195 DebugPath = "/usr/lib/debug";
196 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
198 if (checkFileCRC(DebugPath, CRCHash)) {
199 Result = DebugPath.str();
205 bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
209 for (const SectionRef &Section : Obj->sections()) {
211 Section.getName(Name);
212 Name = Name.substr(Name.find_first_not_of("._"));
213 if (Name == "gnu_debuglink") {
215 Section.getContents(Data);
216 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
218 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
219 // 4-byte align the offset.
220 Offset = (Offset + 3) & ~0x3;
221 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
222 DebugName = DebugNameStr;
223 CRCHash = DE.getU32(&Offset);
233 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
234 const MachOObjectFile *Obj) {
235 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
236 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
237 if (dbg_uuid.empty() || bin_uuid.empty())
239 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
242 } // end anonymous namespace
244 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
245 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
246 // On Darwin we may find DWARF in separate object file in
247 // resource directory.
248 std::vector<std::string> DsymPaths;
249 StringRef Filename = sys::path::filename(ExePath);
250 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
251 for (const auto &Path : Opts.DsymHints) {
252 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
254 for (const auto &Path : DsymPaths) {
255 auto DbgObjOrErr = getOrCreateObject(Path, ArchName);
257 // Ignore errors, the file might not exist.
258 consumeError(DbgObjOrErr.takeError());
261 ObjectFile *DbgObj = DbgObjOrErr.get();
264 const MachOObjectFile *MachDbgObj = dyn_cast<const MachOObjectFile>(DbgObj);
267 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj))
273 ObjectFile *LLVMSymbolizer::lookUpDebuglinkObject(const std::string &Path,
274 const ObjectFile *Obj,
275 const std::string &ArchName) {
276 std::string DebuglinkName;
278 std::string DebugBinaryPath;
279 if (!getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash))
281 if (!findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath))
283 auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName);
285 // Ignore errors, the file might not exist.
286 consumeError(DbgObjOrErr.takeError());
289 return DbgObjOrErr.get();
292 Expected<LLVMSymbolizer::ObjectPair>
293 LLVMSymbolizer::getOrCreateObjectPair(const std::string &Path,
294 const std::string &ArchName) {
295 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
296 if (I != ObjectPairForPathArch.end()) {
300 auto ObjOrErr = getOrCreateObject(Path, ArchName);
302 ObjectPairForPathArch.insert(std::make_pair(std::make_pair(Path, ArchName),
303 ObjectPair(nullptr, nullptr)));
304 return ObjOrErr.takeError();
307 ObjectFile *Obj = ObjOrErr.get();
308 assert(Obj != nullptr);
309 ObjectFile *DbgObj = nullptr;
311 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
312 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
314 DbgObj = lookUpDebuglinkObject(Path, Obj, ArchName);
317 ObjectPair Res = std::make_pair(Obj, DbgObj);
318 ObjectPairForPathArch.insert(
319 std::make_pair(std::make_pair(Path, ArchName), Res));
323 Expected<ObjectFile *>
324 LLVMSymbolizer::getOrCreateObject(const std::string &Path,
325 const std::string &ArchName) {
326 const auto &I = BinaryForPath.find(Path);
327 Binary *Bin = nullptr;
328 if (I == BinaryForPath.end()) {
329 Expected<OwningBinary<Binary>> BinOrErr = createBinary(Path);
331 BinaryForPath.insert(std::make_pair(Path, OwningBinary<Binary>()));
332 return BinOrErr.takeError();
334 Bin = BinOrErr->getBinary();
335 BinaryForPath.insert(std::make_pair(Path, std::move(BinOrErr.get())));
337 Bin = I->second.getBinary();
341 return static_cast<ObjectFile *>(nullptr);
343 if (MachOUniversalBinary *UB = dyn_cast_or_null<MachOUniversalBinary>(Bin)) {
344 const auto &I = ObjectForUBPathAndArch.find(std::make_pair(Path, ArchName));
345 if (I != ObjectForUBPathAndArch.end()) {
346 return I->second.get();
348 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
349 UB->getObjectForArch(ArchName);
351 ObjectForUBPathAndArch.insert(std::make_pair(
352 std::make_pair(Path, ArchName), std::unique_ptr<ObjectFile>()));
353 return ObjOrErr.takeError();
355 ObjectFile *Res = ObjOrErr->get();
356 ObjectForUBPathAndArch.insert(std::make_pair(std::make_pair(Path, ArchName),
357 std::move(ObjOrErr.get())));
360 if (Bin->isObject()) {
361 return cast<ObjectFile>(Bin);
363 return errorCodeToError(object_error::arch_not_found);
366 Expected<SymbolizableModule *>
367 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
368 const auto &I = Modules.find(ModuleName);
369 if (I != Modules.end()) {
370 return I->second.get();
372 std::string BinaryName = ModuleName;
373 std::string ArchName = Opts.DefaultArch;
374 size_t ColonPos = ModuleName.find_last_of(':');
375 // Verify that substring after colon form a valid arch name.
376 if (ColonPos != std::string::npos) {
377 std::string ArchStr = ModuleName.substr(ColonPos + 1);
378 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
379 BinaryName = ModuleName.substr(0, ColonPos);
383 auto ObjectsOrErr = getOrCreateObjectPair(BinaryName, ArchName);
385 // Failed to find valid object file.
387 std::make_pair(ModuleName, std::unique_ptr<SymbolizableModule>()));
388 return ObjectsOrErr.takeError();
390 ObjectPair Objects = ObjectsOrErr.get();
392 std::unique_ptr<DIContext> Context;
393 // If this is a COFF object containing PDB info, use a PDBContext to
394 // symbolize. Otherwise, use DWARF.
395 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
396 const codeview::DebugInfo *DebugInfo;
397 StringRef PDBFileName;
398 auto EC = CoffObject->getDebugPDBInfo(DebugInfo, PDBFileName);
399 if (!EC && DebugInfo != nullptr && !PDBFileName.empty()) {
401 std::unique_ptr<IPDBSession> Session;
402 if (auto Err = loadDataForEXE(PDB_ReaderType::DIA,
403 Objects.first->getFileName(), Session)) {
405 std::make_pair(ModuleName, std::unique_ptr<SymbolizableModule>()));
406 return std::move(Err);
408 Context.reset(new PDBContext(*CoffObject, std::move(Session)));
412 Context.reset(new DWARFContextInMemory(*Objects.second));
415 SymbolizableObjectFile::create(Objects.first, std::move(Context));
416 std::unique_ptr<SymbolizableModule> SymMod;
418 SymMod = std::move(InfoOrErr.get());
420 Modules.insert(std::make_pair(ModuleName, std::move(SymMod)));
421 assert(InsertResult.second);
422 if (auto EC = InfoOrErr.getError())
423 return errorCodeToError(EC);
424 return InsertResult.first->second.get();
429 // Undo these various manglings for Win32 extern "C" functions:
432 // fastcall - @foo@12
433 // vectorcall - foo@@12
434 // These are all different linkage names for 'foo'.
435 StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
436 // Remove any '_' or '@' prefix.
437 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
438 if (Front == '_' || Front == '@')
439 SymbolName = SymbolName.drop_front();
441 // Remove any '@[0-9]+' suffix.
443 size_t AtPos = SymbolName.rfind('@');
444 if (AtPos != StringRef::npos &&
445 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
446 [](char C) { return C >= '0' && C <= '9'; })) {
447 SymbolName = SymbolName.substr(0, AtPos);
451 // Remove any ending '@' for vectorcall.
452 if (SymbolName.endswith("@"))
453 SymbolName = SymbolName.drop_back();
458 } // end anonymous namespace
460 #if !defined(_MSC_VER)
461 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
462 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
463 size_t *length, int *status);
467 LLVMSymbolizer::DemangleName(const std::string &Name,
468 const SymbolizableModule *DbiModuleDescriptor) {
469 #if !defined(_MSC_VER)
470 // We can spoil names of symbols with C linkage, so use an heuristic
471 // approach to check if the name should be demangled.
472 if (Name.substr(0, 2) == "_Z") {
474 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
477 std::string Result = DemangledName;
482 if (!Name.empty() && Name.front() == '?') {
483 // Only do MSVC C++ demangling on symbols starting with '?'.
484 char DemangledName[1024] = {0};
485 DWORD result = ::UnDecorateSymbolName(
486 Name.c_str(), DemangledName, 1023,
487 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
488 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
489 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
490 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
491 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
492 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
493 return (result == 0) ? Name : std::string(DemangledName);
496 if (DbiModuleDescriptor && DbiModuleDescriptor->isWin32Module())
497 return std::string(demanglePE32ExternCFunc(Name));
501 } // namespace symbolize