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 // FIXME: Move this to llvm-symbolizer tool.
50 static bool error(std::error_code ec) {
53 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
57 DILineInfo LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
58 uint64_t ModuleOffset) {
59 SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName);
63 // If the user is giving us relative addresses, add the preferred base of the
64 // object to the offset before we do the query. It's what DIContext expects.
65 if (Opts.RelativeAddresses)
66 ModuleOffset += Info->getModulePreferredBase();
68 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions,
71 LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
76 LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
77 uint64_t ModuleOffset) {
78 SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName);
80 return DIInliningInfo();
82 // If the user is giving us relative addresses, add the preferred base of the
83 // object to the offset before we do the query. It's what DIContext expects.
84 if (Opts.RelativeAddresses)
85 ModuleOffset += Info->getModulePreferredBase();
87 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
88 ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable);
90 for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
91 auto *Frame = InlinedContext.getMutableFrame(i);
92 Frame->FunctionName = DemangleName(Frame->FunctionName, Info);
95 return InlinedContext;
98 DIGlobal LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
99 uint64_t ModuleOffset) {
100 if (!Opts.UseSymbolTable)
102 SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName);
106 // If the user is giving us relative addresses, add the preferred base of
107 // the object to the offset before we do the query. It's what DIContext
109 if (Opts.RelativeAddresses)
110 ModuleOffset += Info->getModulePreferredBase();
112 DIGlobal Global = Info->symbolizeData(ModuleOffset);
114 Global.Name = DemangleName(Global.Name, Info);
118 void LLVMSymbolizer::flush() {
120 ObjectPairForPathArch.clear();
121 ObjectFileForArch.clear();
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.
129 std::string getDarwinDWARFResourceForPath(
130 const std::string &Path, const std::string &Basename) {
131 SmallString<16> ResourceName = StringRef(Path);
132 if (sys::path::extension(Path) != ".dSYM") {
133 ResourceName += ".dSYM";
135 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
136 sys::path::append(ResourceName, Basename);
137 return ResourceName.str();
140 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
141 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
142 MemoryBuffer::getFileOrSTDIN(Path);
145 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
148 static bool findDebugBinary(const std::string &OrigPath,
149 const std::string &DebuglinkName, uint32_t CRCHash,
150 std::string &Result) {
151 std::string OrigRealPath = OrigPath;
152 #if defined(HAVE_REALPATH)
153 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
158 SmallString<16> OrigDir(OrigRealPath);
159 llvm::sys::path::remove_filename(OrigDir);
160 SmallString<16> DebugPath = OrigDir;
161 // Try /path/to/original_binary/debuglink_name
162 llvm::sys::path::append(DebugPath, DebuglinkName);
163 if (checkFileCRC(DebugPath, CRCHash)) {
164 Result = DebugPath.str();
167 // Try /path/to/original_binary/.debug/debuglink_name
168 DebugPath = OrigRealPath;
169 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
170 if (checkFileCRC(DebugPath, CRCHash)) {
171 Result = DebugPath.str();
174 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
175 DebugPath = "/usr/lib/debug";
176 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
178 if (checkFileCRC(DebugPath, CRCHash)) {
179 Result = DebugPath.str();
185 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
189 for (const SectionRef &Section : Obj->sections()) {
191 Section.getName(Name);
192 Name = Name.substr(Name.find_first_not_of("._"));
193 if (Name == "gnu_debuglink") {
195 Section.getContents(Data);
196 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
198 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
199 // 4-byte align the offset.
200 Offset = (Offset + 3) & ~0x3;
201 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
202 DebugName = DebugNameStr;
203 CRCHash = DE.getU32(&Offset);
214 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
215 const MachOObjectFile *Obj) {
216 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
217 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
218 if (dbg_uuid.empty() || bin_uuid.empty())
220 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
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));
233 for (const auto &path : DsymPaths) {
234 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
235 std::error_code EC = BinaryOrErr.getError();
236 if (EC != errc::no_such_file_or_directory && !error(EC)) {
237 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
239 getObjectFileFromBinary(B.getBinary(), ArchName);
240 const MachOObjectFile *MachDbgObj =
241 dyn_cast<const MachOObjectFile>(DbgObj);
242 if (!MachDbgObj) continue;
243 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
244 addOwningBinary(std::move(B));
252 LLVMSymbolizer::ObjectPair
253 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
254 const std::string &ArchName) {
255 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
256 if (I != ObjectPairForPathArch.end())
258 ObjectFile *Obj = nullptr;
259 ObjectFile *DbgObj = nullptr;
260 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
261 if (!error(BinaryOrErr.getError())) {
262 OwningBinary<Binary> &B = BinaryOrErr.get();
263 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
265 ObjectPair Res = std::make_pair(nullptr, nullptr);
266 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
269 addOwningBinary(std::move(B));
270 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
271 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
272 // Try to locate the debug binary using .gnu_debuglink section.
274 std::string DebuglinkName;
276 std::string DebugBinaryPath;
277 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
278 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
279 BinaryOrErr = createBinary(DebugBinaryPath);
280 if (!error(BinaryOrErr.getError())) {
281 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
282 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
283 addOwningBinary(std::move(B));
290 ObjectPair Res = std::make_pair(Obj, DbgObj);
291 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
296 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
297 const std::string &ArchName) {
300 ObjectFile *Res = nullptr;
301 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
302 const auto &I = ObjectFileForArch.find(
303 std::make_pair(UB, ArchName));
304 if (I != ObjectFileForArch.end())
306 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
307 UB->getObjectForArch(ArchName);
309 Res = ParsedObj.get().get();
310 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
312 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
313 } else if (Bin->isObject()) {
314 Res = cast<ObjectFile>(Bin);
320 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
321 const auto &I = Modules.find(ModuleName);
322 if (I != Modules.end())
323 return I->second.get();
324 std::string BinaryName = ModuleName;
325 std::string ArchName = Opts.DefaultArch;
326 size_t ColonPos = ModuleName.find_last_of(':');
327 // Verify that substring after colon form a valid arch name.
328 if (ColonPos != std::string::npos) {
329 std::string ArchStr = ModuleName.substr(ColonPos + 1);
330 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
331 BinaryName = ModuleName.substr(0, ColonPos);
335 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
337 if (!Objects.first) {
338 // Failed to find valid object file.
339 Modules.insert(std::make_pair(ModuleName, nullptr));
342 std::unique_ptr<DIContext> Context;
343 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
344 // If this is a COFF object, assume it contains PDB debug information. If
345 // we don't find any we will fall back to the DWARF case.
346 std::unique_ptr<IPDBSession> Session;
347 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
348 Objects.first->getFileName(), Session);
349 if (Error == PDB_ErrorCode::Success) {
350 Context.reset(new PDBContext(*CoffObject, std::move(Session)));
354 Context.reset(new DWARFContextInMemory(*Objects.second));
357 SymbolizableObjectFile::create(Objects.first, std::move(Context));
358 if (error(ErrOrInfo.getError())) {
359 Modules.insert(std::make_pair(ModuleName, nullptr));
362 SymbolizableModule *Res = ErrOrInfo.get().get();
363 Modules.insert(std::make_pair(ModuleName, std::move(ErrOrInfo.get())));
367 // Undo these various manglings for Win32 extern "C" functions:
370 // fastcall - @foo@12
371 // vectorcall - foo@@12
372 // These are all different linkage names for 'foo'.
373 static StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
374 // Remove any '_' or '@' prefix.
375 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
376 if (Front == '_' || Front == '@')
377 SymbolName = SymbolName.drop_front();
379 // Remove any '@[0-9]+' suffix.
381 size_t AtPos = SymbolName.rfind('@');
382 if (AtPos != StringRef::npos &&
383 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
384 [](char C) { return C >= '0' && C <= '9'; })) {
385 SymbolName = SymbolName.substr(0, AtPos);
389 // Remove any ending '@' for vectorcall.
390 if (SymbolName.endswith("@"))
391 SymbolName = SymbolName.drop_back();
396 #if !defined(_MSC_VER)
397 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
398 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
399 size_t *length, int *status);
402 std::string LLVMSymbolizer::DemangleName(const std::string &Name,
403 const SymbolizableModule *ModInfo) {
404 #if !defined(_MSC_VER)
405 // We can spoil names of symbols with C linkage, so use an heuristic
406 // approach to check if the name should be demangled.
407 if (Name.substr(0, 2) == "_Z") {
409 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
412 std::string Result = DemangledName;
417 if (!Name.empty() && Name.front() == '?') {
418 // Only do MSVC C++ demangling on symbols starting with '?'.
419 char DemangledName[1024] = {0};
420 DWORD result = ::UnDecorateSymbolName(
421 Name.c_str(), DemangledName, 1023,
422 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
423 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
424 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
425 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
426 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
427 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
428 return (result == 0) ? Name : std::string(DemangledName);
431 if (ModInfo && ModInfo->isWin32Module())
432 return std::string(demanglePE32ExternCFunc(Name));
436 } // namespace symbolize