[LLVMSymbolize] Factor out the logic for printing structs from DIContext. NFC.
[oota-llvm.git] / lib / DebugInfo / Symbolize / Symbolize.cpp
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/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"
33 #include <stdlib.h>
34
35 #if defined(_MSC_VER)
36 #include <Windows.h>
37 #include <DbgHelp.h>
38 #pragma comment(lib, "dbghelp.lib")
39
40 // Windows.h conflicts with our COFF header definitions.
41 #ifdef IMAGE_FILE_MACHINE_I386
42 #undef IMAGE_FILE_MACHINE_I386
43 #endif
44 #endif
45
46 namespace llvm {
47 namespace symbolize {
48
49 // FIXME: Move this to llvm-symbolizer tool.
50 static bool error(std::error_code ec) {
51   if (!ec)
52     return false;
53   errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
54   return true;
55 }
56
57 DILineInfo LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
58                                          uint64_t ModuleOffset) {
59   SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName);
60   if (!Info)
61     return DILineInfo();
62
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();
67
68   DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions,
69                                             Opts.UseSymbolTable);
70   if (Opts.Demangle)
71     LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
72   return LineInfo;
73 }
74
75 DIInliningInfo
76 LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
77                                      uint64_t ModuleOffset) {
78   SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName);
79   if (!Info)
80     return DIInliningInfo();
81
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();
86
87   DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
88       ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable);
89   if (Opts.Demangle) {
90     for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
91       auto *Frame = InlinedContext.getMutableFrame(i);
92       Frame->FunctionName = DemangleName(Frame->FunctionName, Info);
93     }
94   }
95   return InlinedContext;
96 }
97
98 DIGlobal LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
99                                        uint64_t ModuleOffset) {
100   if (!Opts.UseSymbolTable)
101     return DIGlobal();
102   SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName);
103   if (!Info)
104     return DIGlobal();
105
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
108   // expects.
109   if (Opts.RelativeAddresses)
110     ModuleOffset += Info->getModulePreferredBase();
111
112   DIGlobal Global = Info->symbolizeData(ModuleOffset);
113   if (Opts.Demangle)
114     Global.Name = DemangleName(Global.Name, Info);
115   return Global;
116 }
117
118 void LLVMSymbolizer::flush() {
119   Modules.clear();
120   ObjectPairForPathArch.clear();
121   ObjectFileForArch.clear();
122 }
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 static
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";
134   }
135   sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
136   sys::path::append(ResourceName, Basename);
137   return ResourceName.str();
138 }
139
140 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
141   ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
142       MemoryBuffer::getFileOrSTDIN(Path);
143   if (!MB)
144     return false;
145   return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
146 }
147
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)) {
154     OrigRealPath = RP;
155     free(RP);
156   }
157 #endif
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();
165     return true;
166   }
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();
172     return true;
173   }
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),
177                           DebuglinkName);
178   if (checkFileCRC(DebugPath, CRCHash)) {
179     Result = DebugPath.str();
180     return true;
181   }
182   return false;
183 }
184
185 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
186                                     uint32_t &CRCHash) {
187   if (!Obj)
188     return false;
189   for (const SectionRef &Section : Obj->sections()) {
190     StringRef Name;
191     Section.getName(Name);
192     Name = Name.substr(Name.find_first_not_of("._"));
193     if (Name == "gnu_debuglink") {
194       StringRef Data;
195       Section.getContents(Data);
196       DataExtractor DE(Data, Obj->isLittleEndian(), 0);
197       uint32_t Offset = 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);
204           return true;
205         }
206       }
207       break;
208     }
209   }
210   return false;
211 }
212
213 static
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())
219     return false;
220   return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
221 }
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     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());
238       ObjectFile *DbgObj =
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));
245         return DbgObj; 
246       }
247     }
248   }
249   return nullptr;
250 }
251
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())
257     return I->second;
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);
264     if (!Obj) {
265       ObjectPair Res = std::make_pair(nullptr, nullptr);
266       ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
267       return Res;
268     }
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.
273     if (!DbgObj) {
274       std::string DebuglinkName;
275       uint32_t CRCHash;
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));
284         }
285       }
286     }
287   }
288   if (!DbgObj)
289     DbgObj = Obj;
290   ObjectPair Res = std::make_pair(Obj, DbgObj);
291   ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
292   return Res;
293 }
294
295 ObjectFile *
296 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
297                                         const std::string &ArchName) {
298   if (!Bin)
299     return nullptr;
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())
305       return I->second;
306     ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
307         UB->getObjectForArch(ArchName);
308     if (ParsedObj) {
309       Res = ParsedObj.get().get();
310       ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
311     }
312     ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
313   } else if (Bin->isObject()) {
314     Res = cast<ObjectFile>(Bin);
315   }
316   return Res;
317 }
318
319 SymbolizableModule *
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);
332       ArchName = ArchStr;
333     }
334   }
335   ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
336
337   if (!Objects.first) {
338     // Failed to find valid object file.
339     Modules.insert(std::make_pair(ModuleName, nullptr));
340     return nullptr;
341   }
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)));
351     }
352   }
353   if (!Context)
354     Context.reset(new DWARFContextInMemory(*Objects.second));
355   assert(Context);
356   auto ErrOrInfo =
357       SymbolizableObjectFile::create(Objects.first, std::move(Context));
358   if (error(ErrOrInfo.getError())) {
359     Modules.insert(std::make_pair(ModuleName, nullptr));
360     return nullptr;
361   }
362   SymbolizableModule *Res = ErrOrInfo.get().get();
363   Modules.insert(std::make_pair(ModuleName, std::move(ErrOrInfo.get())));
364   return Res;
365 }
366
367 // Undo these various manglings for Win32 extern "C" functions:
368 // cdecl       - _foo
369 // stdcall     - _foo@12
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();
378
379   // Remove any '@[0-9]+' suffix.
380   if (Front != '?') {
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);
386     }
387   }
388
389   // Remove any ending '@' for vectorcall.
390   if (SymbolName.endswith("@"))
391     SymbolName = SymbolName.drop_back();
392
393   return SymbolName;
394 }
395
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);
400 #endif
401
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") {
408     int status = 0;
409     char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
410     if (status != 0)
411       return Name;
412     std::string Result = DemangledName;
413     free(DemangledName);
414     return Result;
415   }
416 #else
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);
429   }
430 #endif
431   if (ModInfo && ModInfo->isWin32Module())
432     return std::string(demanglePE32ExternCFunc(Name));
433   return Name;
434 }
435
436 } // namespace symbolize
437 } // namespace llvm