[sancov] IWYU fix: add proper header inclusion.
[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 ObjectFile *LLVMSymbolizer::lookUpDebuglinkObject(const std::string &Path,
248                                                   const ObjectFile *Obj,
249                                                   const std::string &ArchName) {
250   std::string DebuglinkName;
251   uint32_t CRCHash;
252   std::string DebugBinaryPath;
253   if (!getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash))
254     return nullptr;
255   if (!findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath))
256     return nullptr;
257   ErrorOr<OwningBinary<Binary>> DebugBinaryOrErr =
258       createBinary(DebugBinaryPath);
259   if (!DebugBinaryOrErr)
260     return nullptr;
261   OwningBinary<Binary> &DB = DebugBinaryOrErr.get();
262   auto DbgObjOrErr = getObjectFileFromBinary(DB.getBinary(), ArchName);
263   if (!DbgObjOrErr)
264     return nullptr;
265   addOwningBinary(std::move(DB));
266   return DbgObjOrErr.get();
267 }
268
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())
274     return I->second;
275
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));
280     return EC;
281   }
282   OwningBinary<Binary> &B = BinaryOrErr.get();
283
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));
288     return EC;
289   }
290   addOwningBinary(std::move(B));
291
292   ObjectFile *Obj = ObjOrErr.get();
293   assert(Obj != nullptr);
294   ObjectFile *DbgObj = nullptr;
295
296   if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
297     DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
298   if (!DbgObj)
299     DbgObj = lookUpDebuglinkObject(Path, Obj, ArchName);
300   if (!DbgObj)
301     DbgObj = Obj;
302   ObjectPair Res = std::make_pair(Obj, DbgObj);
303   ObjectPairForPathArch.insert(
304       std::make_pair(std::make_pair(Path, ArchName), Res));
305   return Res;
306 }
307
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())
316       return I->second;
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));
322       return EC;
323     }
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));
327     return Res;
328   }
329   if (Bin->isObject()) {
330     return cast<ObjectFile>(Bin);
331   }
332   return object_error::arch_not_found;
333 }
334
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())
341       return EC;
342     return InfoOrErr->get();
343   }
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);
352       ArchName = ArchStr;
353     }
354   }
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));
359     return EC;
360   }
361   ObjectPair Objects = ObjectsOrErr.get();
362
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)));
372     }
373   }
374   if (!Context)
375     Context.reset(new DWARFContextInMemory(*Objects.second));
376   assert(Context);
377   auto InfoOrErr =
378       SymbolizableObjectFile::create(Objects.first, std::move(Context));
379   auto InsertResult =
380       Modules.insert(std::make_pair(ModuleName, std::move(InfoOrErr)));
381   assert(InsertResult.second);
382   if (auto EC = InsertResult.first->second.getError())
383     return EC;
384   return InsertResult.first->second->get();
385 }
386
387 // Undo these various manglings for Win32 extern "C" functions:
388 // cdecl       - _foo
389 // stdcall     - _foo@12
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();
398
399   // Remove any '@[0-9]+' suffix.
400   if (Front != '?') {
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);
406     }
407   }
408
409   // Remove any ending '@' for vectorcall.
410   if (SymbolName.endswith("@"))
411     SymbolName = SymbolName.drop_back();
412
413   return SymbolName;
414 }
415
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);
420 #endif
421
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") {
428     int status = 0;
429     char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
430     if (status != 0)
431       return Name;
432     std::string Result = DemangledName;
433     free(DemangledName);
434     return Result;
435   }
436 #else
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);
449   }
450 #endif
451   if (ModInfo && ModInfo->isWin32Module())
452     return std::string(demanglePE32ExternCFunc(Name));
453   return Name;
454 }
455
456 } // namespace symbolize
457 } // namespace llvm