b0e17cfd3ffda035e407688686c8c28a32a05da3
[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 ErrorOr<DILineInfo> LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
50                                                   uint64_t ModuleOffset) {
51   auto InfoOrErr = getOrCreateModuleInfo(ModuleName);
52   if (auto EC = InfoOrErr.getError())
53     return EC;
54   SymbolizableModule *Info = InfoOrErr.get();
55
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();
60
61   DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions,
62                                             Opts.UseSymbolTable);
63   if (Opts.Demangle)
64     LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
65   return LineInfo;
66 }
67
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())
73     return EC;
74   SymbolizableModule *Info = InfoOrErr.get();
75
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();
80
81   DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
82       ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable);
83   if (Opts.Demangle) {
84     for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
85       auto *Frame = InlinedContext.getMutableFrame(i);
86       Frame->FunctionName = DemangleName(Frame->FunctionName, Info);
87     }
88   }
89   return InlinedContext;
90 }
91
92 ErrorOr<DIGlobal> LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
93                                                 uint64_t ModuleOffset) {
94   auto InfoOrErr = getOrCreateModuleInfo(ModuleName);
95   if (auto EC = InfoOrErr.getError())
96     return EC;
97   SymbolizableModule *Info = InfoOrErr.get();
98
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
101   // expects.
102   if (Opts.RelativeAddresses)
103     ModuleOffset += Info->getModulePreferredBase();
104
105   DIGlobal Global = Info->symbolizeData(ModuleOffset);
106   if (Opts.Demangle)
107     Global.Name = DemangleName(Global.Name, Info);
108   return Global;
109 }
110
111 void LLVMSymbolizer::flush() {
112   Modules.clear();
113   ObjectPairForPathArch.clear();
114   ObjectFileForArch.clear();
115 }
116
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.
121 static
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";
127   }
128   sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
129   sys::path::append(ResourceName, Basename);
130   return ResourceName.str();
131 }
132
133 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
134   ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
135       MemoryBuffer::getFileOrSTDIN(Path);
136   if (!MB)
137     return false;
138   return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
139 }
140
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)) {
147     OrigRealPath = RP;
148     free(RP);
149   }
150 #endif
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();
158     return true;
159   }
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();
165     return true;
166   }
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),
170                           DebuglinkName);
171   if (checkFileCRC(DebugPath, CRCHash)) {
172     Result = DebugPath.str();
173     return true;
174   }
175   return false;
176 }
177
178 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
179                                     uint32_t &CRCHash) {
180   if (!Obj)
181     return false;
182   for (const SectionRef &Section : Obj->sections()) {
183     StringRef Name;
184     Section.getName(Name);
185     Name = Name.substr(Name.find_first_not_of("._"));
186     if (Name == "gnu_debuglink") {
187       StringRef Data;
188       Section.getContents(Data);
189       DataExtractor DE(Data, Obj->isLittleEndian(), 0);
190       uint32_t Offset = 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);
197           return true;
198         }
199       }
200       break;
201     }
202   }
203   return false;
204 }
205
206 static
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())
212     return false;
213   return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
214 }
215
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));
225   }
226   for (const auto &path : DsymPaths) {
227     ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
228     if (!BinaryOrErr)
229       continue;
230     OwningBinary<Binary> &B = BinaryOrErr.get();
231     auto DbgObjOrErr = getObjectFileFromBinary(B.getBinary(), ArchName);
232     if (!DbgObjOrErr)
233       continue;
234     ObjectFile *DbgObj = DbgObjOrErr.get();
235     const MachOObjectFile *MachDbgObj =
236         dyn_cast<const MachOObjectFile>(DbgObj);
237     if (!MachDbgObj)
238       continue;
239     if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
240       addOwningBinary(std::move(B));
241       return DbgObj;
242     }
243   }
244   return nullptr;
245 }
246
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())
252     return I->second;
253
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));
258     return EC;
259   }
260   OwningBinary<Binary> &B = BinaryOrErr.get();
261
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));
266     return EC;
267   }
268   addOwningBinary(std::move(B));
269
270   ObjectFile *Obj = ObjOrErr.get();
271   assert(Obj != nullptr);
272   ObjectFile *DbgObj = nullptr;
273
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.
277   if (!DbgObj) {
278     std::string DebuglinkName;
279     uint32_t CRCHash;
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);
288         if (DbgObjOrErr) {
289           DbgObj = DbgObjOrErr.get();
290           assert(DbgObj != nullptr);
291           addOwningBinary(std::move(DB));
292         }
293       }
294     }
295   }
296
297   if (!DbgObj)
298     DbgObj = Obj;
299   ObjectPair Res = std::make_pair(Obj, DbgObj);
300   ObjectPairForPathArch.insert(
301       std::make_pair(std::make_pair(Path, ArchName), Res));
302   return Res;
303 }
304
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())
313       return I->second;
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));
319       return EC;
320     }
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));
324     return Res;
325   }
326   if (Bin->isObject()) {
327     return cast<ObjectFile>(Bin);
328   }
329   return object_error::arch_not_found;
330 }
331
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())
338       return EC;
339     return InfoOrErr->get();
340   }
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);
349       ArchName = ArchStr;
350     }
351   }
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));
356     return EC;
357   }
358   ObjectPair Objects = ObjectsOrErr.get();
359
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)));
369     }
370   }
371   if (!Context)
372     Context.reset(new DWARFContextInMemory(*Objects.second));
373   assert(Context);
374   auto InfoOrErr =
375       SymbolizableObjectFile::create(Objects.first, std::move(Context));
376   auto InsertResult =
377       Modules.insert(std::make_pair(ModuleName, std::move(InfoOrErr)));
378   assert(InsertResult.second);
379   if (auto EC = InsertResult.first->second.getError())
380     return EC;
381   return InsertResult.first->second->get();
382 }
383
384 // Undo these various manglings for Win32 extern "C" functions:
385 // cdecl       - _foo
386 // stdcall     - _foo@12
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();
395
396   // Remove any '@[0-9]+' suffix.
397   if (Front != '?') {
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);
403     }
404   }
405
406   // Remove any ending '@' for vectorcall.
407   if (SymbolName.endswith("@"))
408     SymbolName = SymbolName.drop_back();
409
410   return SymbolName;
411 }
412
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);
417 #endif
418
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") {
425     int status = 0;
426     char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
427     if (status != 0)
428       return Name;
429     std::string Result = DemangledName;
430     free(DemangledName);
431     return Result;
432   }
433 #else
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);
446   }
447 #endif
448   if (ModInfo && ModInfo->isWin32Module())
449     return std::string(demanglePE32ExternCFunc(Name));
450   return Name;
451 }
452
453 } // namespace symbolize
454 } // namespace llvm