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/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/Support/COFF.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/Compression.h"
28 #include "llvm/Support/DataExtractor.h"
29 #include "llvm/Support/Errc.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Path.h"
38 #pragma comment(lib, "dbghelp.lib")
40 // Windows.h conflicts with our COFF header definitions.
41 #ifdef IMAGE_FILE_MACHINE_I386
42 #undef IMAGE_FILE_MACHINE_I386
49 ErrorOr<DILineInfo> LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
50 uint64_t ModuleOffset) {
51 auto InfoOrErr = getOrCreateModuleInfo(ModuleName);
52 if (auto EC = InfoOrErr.getError())
54 SymbolizableModule *Info = InfoOrErr.get();
56 // If the user is giving us relative addresses, add the preferred base of the
57 // object to the offset before we do the query. It's what DIContext expects.
58 if (Opts.RelativeAddresses)
59 ModuleOffset += Info->getModulePreferredBase();
61 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions,
64 LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
68 ErrorOr<DIInliningInfo>
69 LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
70 uint64_t ModuleOffset) {
71 auto InfoOrErr = getOrCreateModuleInfo(ModuleName);
72 if (auto EC = InfoOrErr.getError())
74 SymbolizableModule *Info = InfoOrErr.get();
76 // If the user is giving us relative addresses, add the preferred base of the
77 // object to the offset before we do the query. It's what DIContext expects.
78 if (Opts.RelativeAddresses)
79 ModuleOffset += Info->getModulePreferredBase();
81 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
82 ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable);
84 for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
85 auto *Frame = InlinedContext.getMutableFrame(i);
86 Frame->FunctionName = DemangleName(Frame->FunctionName, Info);
89 return InlinedContext;
92 ErrorOr<DIGlobal> LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
93 uint64_t ModuleOffset) {
94 auto InfoOrErr = getOrCreateModuleInfo(ModuleName);
95 if (auto EC = InfoOrErr.getError())
97 SymbolizableModule *Info = InfoOrErr.get();
99 // If the user is giving us relative addresses, add the preferred base of
100 // the object to the offset before we do the query. It's what DIContext
102 if (Opts.RelativeAddresses)
103 ModuleOffset += Info->getModulePreferredBase();
105 DIGlobal Global = Info->symbolizeData(ModuleOffset);
107 Global.Name = DemangleName(Global.Name, Info);
111 void LLVMSymbolizer::flush() {
113 ObjectPairForPathArch.clear();
114 ObjectFileForArch.clear();
117 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
118 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
119 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
120 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
122 std::string getDarwinDWARFResourceForPath(
123 const std::string &Path, const std::string &Basename) {
124 SmallString<16> ResourceName = StringRef(Path);
125 if (sys::path::extension(Path) != ".dSYM") {
126 ResourceName += ".dSYM";
128 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
129 sys::path::append(ResourceName, Basename);
130 return ResourceName.str();
133 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
134 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
135 MemoryBuffer::getFileOrSTDIN(Path);
138 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
141 static bool findDebugBinary(const std::string &OrigPath,
142 const std::string &DebuglinkName, uint32_t CRCHash,
143 std::string &Result) {
144 std::string OrigRealPath = OrigPath;
145 #if defined(HAVE_REALPATH)
146 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
151 SmallString<16> OrigDir(OrigRealPath);
152 llvm::sys::path::remove_filename(OrigDir);
153 SmallString<16> DebugPath = OrigDir;
154 // Try /path/to/original_binary/debuglink_name
155 llvm::sys::path::append(DebugPath, DebuglinkName);
156 if (checkFileCRC(DebugPath, CRCHash)) {
157 Result = DebugPath.str();
160 // Try /path/to/original_binary/.debug/debuglink_name
161 DebugPath = OrigRealPath;
162 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
163 if (checkFileCRC(DebugPath, CRCHash)) {
164 Result = DebugPath.str();
167 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
168 DebugPath = "/usr/lib/debug";
169 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
171 if (checkFileCRC(DebugPath, CRCHash)) {
172 Result = DebugPath.str();
178 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
182 for (const SectionRef &Section : Obj->sections()) {
184 Section.getName(Name);
185 Name = Name.substr(Name.find_first_not_of("._"));
186 if (Name == "gnu_debuglink") {
188 Section.getContents(Data);
189 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
191 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
192 // 4-byte align the offset.
193 Offset = (Offset + 3) & ~0x3;
194 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
195 DebugName = DebugNameStr;
196 CRCHash = DE.getU32(&Offset);
207 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
208 const MachOObjectFile *Obj) {
209 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
210 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
211 if (dbg_uuid.empty() || bin_uuid.empty())
213 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
216 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
217 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
218 // On Darwin we may find DWARF in separate object file in
219 // resource directory.
220 std::vector<std::string> DsymPaths;
221 StringRef Filename = sys::path::filename(ExePath);
222 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
223 for (const auto &Path : Opts.DsymHints) {
224 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
226 for (const auto &path : DsymPaths) {
227 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
230 OwningBinary<Binary> &B = BinaryOrErr.get();
231 auto DbgObjOrErr = getObjectFileFromBinary(B.getBinary(), ArchName);
234 ObjectFile *DbgObj = DbgObjOrErr.get();
235 const MachOObjectFile *MachDbgObj =
236 dyn_cast<const MachOObjectFile>(DbgObj);
239 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
240 addOwningBinary(std::move(B));
247 ErrorOr<LLVMSymbolizer::ObjectPair>
248 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
249 const std::string &ArchName) {
250 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
251 if (I != ObjectPairForPathArch.end())
254 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
255 if (auto EC = BinaryOrErr.getError()) {
256 ObjectPairForPathArch.insert(
257 std::make_pair(std::make_pair(Path, ArchName), EC));
260 OwningBinary<Binary> &B = BinaryOrErr.get();
262 auto ObjOrErr = getObjectFileFromBinary(B.getBinary(), ArchName);
263 if (auto EC = ObjOrErr.getError()) {
264 ObjectPairForPathArch.insert(
265 std::make_pair(std::make_pair(Path, ArchName), EC));
268 addOwningBinary(std::move(B));
270 ObjectFile *Obj = ObjOrErr.get();
271 assert(Obj != nullptr);
272 ObjectFile *DbgObj = nullptr;
274 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
275 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
276 // Try to locate the debug binary using .gnu_debuglink section.
278 std::string DebuglinkName;
280 std::string DebugBinaryPath;
281 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
282 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
283 ErrorOr<OwningBinary<Binary>> DebugBinaryOrErr =
284 createBinary(DebugBinaryPath);
285 if (DebugBinaryOrErr) {
286 OwningBinary<Binary> &DB = DebugBinaryOrErr.get();
287 auto DbgObjOrErr = getObjectFileFromBinary(DB.getBinary(), ArchName);
289 DbgObj = DbgObjOrErr.get();
290 assert(DbgObj != nullptr);
291 addOwningBinary(std::move(DB));
299 ObjectPair Res = std::make_pair(Obj, DbgObj);
300 ObjectPairForPathArch.insert(
301 std::make_pair(std::make_pair(Path, ArchName), Res));
305 ErrorOr<ObjectFile *>
306 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
307 const std::string &ArchName) {
308 assert(Bin != nullptr);
309 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
310 const auto &I = ObjectFileForArch.find(
311 std::make_pair(UB, ArchName));
312 if (I != ObjectFileForArch.end())
314 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
315 UB->getObjectForArch(ArchName);
316 if (auto EC = ParsedObj.getError()) {
317 ObjectFileForArch.insert(
318 std::make_pair(std::make_pair(UB, ArchName), EC));
321 ObjectFile *Res = ParsedObj.get().get();
322 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
323 ObjectFileForArch.insert(std::make_pair(std::make_pair(UB, ArchName), Res));
326 if (Bin->isObject()) {
327 return cast<ObjectFile>(Bin);
329 return object_error::arch_not_found;
332 ErrorOr<SymbolizableModule *>
333 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
334 const auto &I = Modules.find(ModuleName);
335 if (I != Modules.end()) {
336 auto &InfoOrErr = I->second;
337 if (auto EC = InfoOrErr.getError())
339 return InfoOrErr->get();
341 std::string BinaryName = ModuleName;
342 std::string ArchName = Opts.DefaultArch;
343 size_t ColonPos = ModuleName.find_last_of(':');
344 // Verify that substring after colon form a valid arch name.
345 if (ColonPos != std::string::npos) {
346 std::string ArchStr = ModuleName.substr(ColonPos + 1);
347 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
348 BinaryName = ModuleName.substr(0, ColonPos);
352 auto ObjectsOrErr = getOrCreateObjects(BinaryName, ArchName);
353 if (auto EC = ObjectsOrErr.getError()) {
354 // Failed to find valid object file.
355 Modules.insert(std::make_pair(ModuleName, EC));
358 ObjectPair Objects = ObjectsOrErr.get();
360 std::unique_ptr<DIContext> Context;
361 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
362 // If this is a COFF object, assume it contains PDB debug information. If
363 // we don't find any we will fall back to the DWARF case.
364 std::unique_ptr<IPDBSession> Session;
365 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
366 Objects.first->getFileName(), Session);
367 if (Error == PDB_ErrorCode::Success) {
368 Context.reset(new PDBContext(*CoffObject, std::move(Session)));
372 Context.reset(new DWARFContextInMemory(*Objects.second));
375 SymbolizableObjectFile::create(Objects.first, std::move(Context));
377 Modules.insert(std::make_pair(ModuleName, std::move(InfoOrErr)));
378 assert(InsertResult.second);
379 if (auto EC = InsertResult.first->second.getError())
381 return InsertResult.first->second->get();
384 // Undo these various manglings for Win32 extern "C" functions:
387 // fastcall - @foo@12
388 // vectorcall - foo@@12
389 // These are all different linkage names for 'foo'.
390 static StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
391 // Remove any '_' or '@' prefix.
392 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
393 if (Front == '_' || Front == '@')
394 SymbolName = SymbolName.drop_front();
396 // Remove any '@[0-9]+' suffix.
398 size_t AtPos = SymbolName.rfind('@');
399 if (AtPos != StringRef::npos &&
400 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
401 [](char C) { return C >= '0' && C <= '9'; })) {
402 SymbolName = SymbolName.substr(0, AtPos);
406 // Remove any ending '@' for vectorcall.
407 if (SymbolName.endswith("@"))
408 SymbolName = SymbolName.drop_back();
413 #if !defined(_MSC_VER)
414 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
415 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
416 size_t *length, int *status);
419 std::string LLVMSymbolizer::DemangleName(const std::string &Name,
420 const SymbolizableModule *ModInfo) {
421 #if !defined(_MSC_VER)
422 // We can spoil names of symbols with C linkage, so use an heuristic
423 // approach to check if the name should be demangled.
424 if (Name.substr(0, 2) == "_Z") {
426 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
429 std::string Result = DemangledName;
434 if (!Name.empty() && Name.front() == '?') {
435 // Only do MSVC C++ demangling on symbols starting with '?'.
436 char DemangledName[1024] = {0};
437 DWORD result = ::UnDecorateSymbolName(
438 Name.c_str(), DemangledName, 1023,
439 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
440 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
441 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
442 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
443 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
444 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
445 return (result == 0) ? Name : std::string(DemangledName);
448 if (ModInfo && ModInfo->isWin32Module())
449 return std::string(demanglePE32ExternCFunc(Name));
453 } // namespace symbolize