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 ObjectFile *LLVMSymbolizer::lookUpDebuglinkObject(const std::string &Path,
248 const ObjectFile *Obj,
249 const std::string &ArchName) {
250 std::string DebuglinkName;
252 std::string DebugBinaryPath;
253 if (!getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash))
255 if (!findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath))
257 ErrorOr<OwningBinary<Binary>> DebugBinaryOrErr =
258 createBinary(DebugBinaryPath);
259 if (!DebugBinaryOrErr)
261 OwningBinary<Binary> &DB = DebugBinaryOrErr.get();
262 auto DbgObjOrErr = getObjectFileFromBinary(DB.getBinary(), ArchName);
265 addOwningBinary(std::move(DB));
266 return DbgObjOrErr.get();
269 ErrorOr<LLVMSymbolizer::ObjectPair>
270 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
271 const std::string &ArchName) {
272 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
273 if (I != ObjectPairForPathArch.end())
276 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
277 if (auto EC = BinaryOrErr.getError()) {
278 ObjectPairForPathArch.insert(
279 std::make_pair(std::make_pair(Path, ArchName), EC));
282 OwningBinary<Binary> &B = BinaryOrErr.get();
284 auto ObjOrErr = getObjectFileFromBinary(B.getBinary(), ArchName);
285 if (auto EC = ObjOrErr.getError()) {
286 ObjectPairForPathArch.insert(
287 std::make_pair(std::make_pair(Path, ArchName), EC));
290 addOwningBinary(std::move(B));
292 ObjectFile *Obj = ObjOrErr.get();
293 assert(Obj != nullptr);
294 ObjectFile *DbgObj = nullptr;
296 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
297 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
299 DbgObj = lookUpDebuglinkObject(Path, Obj, ArchName);
302 ObjectPair Res = std::make_pair(Obj, DbgObj);
303 ObjectPairForPathArch.insert(
304 std::make_pair(std::make_pair(Path, ArchName), Res));
308 ErrorOr<ObjectFile *>
309 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
310 const std::string &ArchName) {
311 assert(Bin != nullptr);
312 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
313 const auto &I = ObjectFileForArch.find(
314 std::make_pair(UB, ArchName));
315 if (I != ObjectFileForArch.end())
317 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
318 UB->getObjectForArch(ArchName);
319 if (auto EC = ParsedObj.getError()) {
320 ObjectFileForArch.insert(
321 std::make_pair(std::make_pair(UB, ArchName), EC));
324 ObjectFile *Res = ParsedObj.get().get();
325 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
326 ObjectFileForArch.insert(std::make_pair(std::make_pair(UB, ArchName), Res));
329 if (Bin->isObject()) {
330 return cast<ObjectFile>(Bin);
332 return object_error::arch_not_found;
335 ErrorOr<SymbolizableModule *>
336 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
337 const auto &I = Modules.find(ModuleName);
338 if (I != Modules.end()) {
339 auto &InfoOrErr = I->second;
340 if (auto EC = InfoOrErr.getError())
342 return InfoOrErr->get();
344 std::string BinaryName = ModuleName;
345 std::string ArchName = Opts.DefaultArch;
346 size_t ColonPos = ModuleName.find_last_of(':');
347 // Verify that substring after colon form a valid arch name.
348 if (ColonPos != std::string::npos) {
349 std::string ArchStr = ModuleName.substr(ColonPos + 1);
350 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
351 BinaryName = ModuleName.substr(0, ColonPos);
355 auto ObjectsOrErr = getOrCreateObjects(BinaryName, ArchName);
356 if (auto EC = ObjectsOrErr.getError()) {
357 // Failed to find valid object file.
358 Modules.insert(std::make_pair(ModuleName, EC));
361 ObjectPair Objects = ObjectsOrErr.get();
363 std::unique_ptr<DIContext> Context;
364 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
365 // If this is a COFF object, assume it contains PDB debug information. If
366 // we don't find any we will fall back to the DWARF case.
367 std::unique_ptr<IPDBSession> Session;
368 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
369 Objects.first->getFileName(), Session);
370 if (Error == PDB_ErrorCode::Success) {
371 Context.reset(new PDBContext(*CoffObject, std::move(Session)));
375 Context.reset(new DWARFContextInMemory(*Objects.second));
378 SymbolizableObjectFile::create(Objects.first, std::move(Context));
380 Modules.insert(std::make_pair(ModuleName, std::move(InfoOrErr)));
381 assert(InsertResult.second);
382 if (auto EC = InsertResult.first->second.getError())
384 return InsertResult.first->second->get();
387 // Undo these various manglings for Win32 extern "C" functions:
390 // fastcall - @foo@12
391 // vectorcall - foo@@12
392 // These are all different linkage names for 'foo'.
393 static StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
394 // Remove any '_' or '@' prefix.
395 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
396 if (Front == '_' || Front == '@')
397 SymbolName = SymbolName.drop_front();
399 // Remove any '@[0-9]+' suffix.
401 size_t AtPos = SymbolName.rfind('@');
402 if (AtPos != StringRef::npos &&
403 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
404 [](char C) { return C >= '0' && C <= '9'; })) {
405 SymbolName = SymbolName.substr(0, AtPos);
409 // Remove any ending '@' for vectorcall.
410 if (SymbolName.endswith("@"))
411 SymbolName = SymbolName.drop_back();
416 #if !defined(_MSC_VER)
417 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
418 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
419 size_t *length, int *status);
422 std::string LLVMSymbolizer::DemangleName(const std::string &Name,
423 const SymbolizableModule *ModInfo) {
424 #if !defined(_MSC_VER)
425 // We can spoil names of symbols with C linkage, so use an heuristic
426 // approach to check if the name should be demangled.
427 if (Name.substr(0, 2) == "_Z") {
429 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
432 std::string Result = DemangledName;
437 if (!Name.empty() && Name.front() == '?') {
438 // Only do MSVC C++ demangling on symbols starting with '?'.
439 char DemangledName[1024] = {0};
440 DWORD result = ::UnDecorateSymbolName(
441 Name.c_str(), DemangledName, 1023,
442 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
443 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
444 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
445 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
446 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
447 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
448 return (result == 0) ? Name : std::string(DemangledName);
451 if (ModInfo && ModInfo->isWin32Module())
452 return std::string(demanglePE32ExternCFunc(Name));
456 } // namespace symbolize