Move DIContext.h to common DebugInfo location.
[oota-llvm.git] / tools / llvm-symbolizer / LLVMSymbolize.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 "LLVMSymbolize.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/Config/config.h"
17 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
18 #include "llvm/Object/ELFObjectFile.h"
19 #include "llvm/Object/MachO.h"
20 #include "llvm/Support/Casting.h"
21 #include "llvm/Support/Compression.h"
22 #include "llvm/Support/DataExtractor.h"
23 #include "llvm/Support/Errc.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/Path.h"
27 #include <sstream>
28 #include <stdlib.h>
29
30 namespace llvm {
31 namespace symbolize {
32
33 static bool error(std::error_code ec) {
34   if (!ec)
35     return false;
36   errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
37   return true;
38 }
39
40 static DILineInfoSpecifier
41 getDILineInfoSpecifier(const LLVMSymbolizer::Options &Opts) {
42   return DILineInfoSpecifier(
43       DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
44       Opts.PrintFunctions);
45 }
46
47 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
48     : Module(Obj), DebugInfoContext(DICtx) {
49   std::unique_ptr<DataExtractor> OpdExtractor;
50   uint64_t OpdAddress = 0;
51   // Find the .opd (function descriptor) section if any, for big-endian
52   // PowerPC64 ELF.
53   if (Module->getArch() == Triple::ppc64) {
54     for (section_iterator Section : Module->sections()) {
55       StringRef Name;
56       if (!error(Section->getName(Name)) && Name == ".opd") {
57         StringRef Data;
58         if (!error(Section->getContents(Data))) {
59           OpdExtractor.reset(new DataExtractor(Data, Module->isLittleEndian(),
60                                                Module->getBytesInAddress()));
61           OpdAddress = Section->getAddress();
62         }
63         break;
64       }
65     }
66   }
67   for (const SymbolRef &Symbol : Module->symbols()) {
68     addSymbol(Symbol, OpdExtractor.get(), OpdAddress);
69   }
70   bool NoSymbolTable = (Module->symbol_begin() == Module->symbol_end());
71   if (NoSymbolTable && Module->isELF()) {
72     // Fallback to dynamic symbol table, if regular symbol table is stripped.
73     std::pair<symbol_iterator, symbol_iterator> IDyn =
74         getELFDynamicSymbolIterators(Module);
75     for (symbol_iterator si = IDyn.first, se = IDyn.second; si != se; ++si) {
76       addSymbol(*si, OpdExtractor.get(), OpdAddress);
77     }
78   }
79 }
80
81 void ModuleInfo::addSymbol(const SymbolRef &Symbol, DataExtractor *OpdExtractor,
82                            uint64_t OpdAddress) {
83   SymbolRef::Type SymbolType;
84   if (error(Symbol.getType(SymbolType)))
85     return;
86   if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
87     return;
88   uint64_t SymbolAddress;
89   if (error(Symbol.getAddress(SymbolAddress)) ||
90       SymbolAddress == UnknownAddressOrSize)
91     return;
92   if (OpdExtractor) {
93     // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
94     // function descriptors. The first word of the descriptor is a pointer to
95     // the function's code.
96     // For the purposes of symbolization, pretend the symbol's address is that
97     // of the function's code, not the descriptor.
98     uint64_t OpdOffset = SymbolAddress - OpdAddress;
99     uint32_t OpdOffset32 = OpdOffset;
100     if (OpdOffset == OpdOffset32 && 
101         OpdExtractor->isValidOffsetForAddress(OpdOffset32))
102       SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
103   }
104   uint64_t SymbolSize;
105   // Getting symbol size is linear for Mach-O files, so assume that symbol
106   // occupies the memory range up to the following symbol.
107   if (isa<MachOObjectFile>(Module))
108     SymbolSize = 0;
109   else if (error(Symbol.getSize(SymbolSize)) ||
110            SymbolSize == UnknownAddressOrSize)
111     return;
112   StringRef SymbolName;
113   if (error(Symbol.getName(SymbolName)))
114     return;
115   // Mach-O symbol table names have leading underscore, skip it.
116   if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
117     SymbolName = SymbolName.drop_front();
118   // FIXME: If a function has alias, there are two entries in symbol table
119   // with same address size. Make sure we choose the correct one.
120   auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
121   SymbolDesc SD = { SymbolAddress, SymbolSize };
122   M.insert(std::make_pair(SD, SymbolName));
123 }
124
125 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
126                                         std::string &Name, uint64_t &Addr,
127                                         uint64_t &Size) const {
128   const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
129   if (SymbolMap.empty())
130     return false;
131   SymbolDesc SD = { Address, Address };
132   auto SymbolIterator = SymbolMap.upper_bound(SD);
133   if (SymbolIterator == SymbolMap.begin())
134     return false;
135   --SymbolIterator;
136   if (SymbolIterator->first.Size != 0 &&
137       SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
138     return false;
139   Name = SymbolIterator->second.str();
140   Addr = SymbolIterator->first.Addr;
141   Size = SymbolIterator->first.Size;
142   return true;
143 }
144
145 DILineInfo ModuleInfo::symbolizeCode(
146     uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
147   DILineInfo LineInfo;
148   if (DebugInfoContext) {
149     LineInfo = DebugInfoContext->getLineInfoForAddress(
150         ModuleOffset, getDILineInfoSpecifier(Opts));
151   }
152   // Override function name from symbol table if necessary.
153   if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
154     std::string FunctionName;
155     uint64_t Start, Size;
156     if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
157                                FunctionName, Start, Size)) {
158       LineInfo.FunctionName = FunctionName;
159     }
160   }
161   return LineInfo;
162 }
163
164 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
165     uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
166   DIInliningInfo InlinedContext;
167   if (DebugInfoContext) {
168     InlinedContext = DebugInfoContext->getInliningInfoForAddress(
169         ModuleOffset, getDILineInfoSpecifier(Opts));
170   }
171   // Make sure there is at least one frame in context.
172   if (InlinedContext.getNumberOfFrames() == 0) {
173     InlinedContext.addFrame(DILineInfo());
174   }
175   // Override the function name in lower frame with name from symbol table.
176   if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
177     DIInliningInfo PatchedInlinedContext;
178     for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
179       DILineInfo LineInfo = InlinedContext.getFrame(i);
180       if (i == n - 1) {
181         std::string FunctionName;
182         uint64_t Start, Size;
183         if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
184                                    FunctionName, Start, Size)) {
185           LineInfo.FunctionName = FunctionName;
186         }
187       }
188       PatchedInlinedContext.addFrame(LineInfo);
189     }
190     InlinedContext = PatchedInlinedContext;
191   }
192   return InlinedContext;
193 }
194
195 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
196                                uint64_t &Start, uint64_t &Size) const {
197   return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
198                                 Size);
199 }
200
201 const char LLVMSymbolizer::kBadString[] = "??";
202
203 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
204                                           uint64_t ModuleOffset) {
205   ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
206   if (!Info)
207     return printDILineInfo(DILineInfo());
208   if (Opts.PrintInlining) {
209     DIInliningInfo InlinedContext =
210         Info->symbolizeInlinedCode(ModuleOffset, Opts);
211     uint32_t FramesNum = InlinedContext.getNumberOfFrames();
212     assert(FramesNum > 0);
213     std::string Result;
214     for (uint32_t i = 0; i < FramesNum; i++) {
215       DILineInfo LineInfo = InlinedContext.getFrame(i);
216       Result += printDILineInfo(LineInfo);
217     }
218     return Result;
219   }
220   DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
221   return printDILineInfo(LineInfo);
222 }
223
224 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
225                                           uint64_t ModuleOffset) {
226   std::string Name = kBadString;
227   uint64_t Start = 0;
228   uint64_t Size = 0;
229   if (Opts.UseSymbolTable) {
230     if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
231       if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
232         Name = DemangleName(Name);
233     }
234   }
235   std::stringstream ss;
236   ss << Name << "\n" << Start << " " << Size << "\n";
237   return ss.str();
238 }
239
240 void LLVMSymbolizer::flush() {
241   DeleteContainerSeconds(Modules);
242   ObjectPairForPathArch.clear();
243   ObjectFileForArch.clear();
244 }
245
246 // For Path="/path/to/foo" and Basename="foo" assume that debug info is in
247 // /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
248 // For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
249 // /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
250 static
251 std::string getDarwinDWARFResourceForPath(
252     const std::string &Path, const std::string &Basename) {
253   SmallString<16> ResourceName = StringRef(Path);
254   if (sys::path::extension(Path) != ".dSYM") {
255     ResourceName += ".dSYM";
256   }
257   sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
258   sys::path::append(ResourceName, Basename);
259   return ResourceName.str();
260 }
261
262 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
263   ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
264       MemoryBuffer::getFileOrSTDIN(Path);
265   if (!MB)
266     return false;
267   return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
268 }
269
270 static bool findDebugBinary(const std::string &OrigPath,
271                             const std::string &DebuglinkName, uint32_t CRCHash,
272                             std::string &Result) {
273   std::string OrigRealPath = OrigPath;
274 #if defined(HAVE_REALPATH)
275   if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
276     OrigRealPath = RP;
277     free(RP);
278   }
279 #endif
280   SmallString<16> OrigDir(OrigRealPath);
281   llvm::sys::path::remove_filename(OrigDir);
282   SmallString<16> DebugPath = OrigDir;
283   // Try /path/to/original_binary/debuglink_name
284   llvm::sys::path::append(DebugPath, DebuglinkName);
285   if (checkFileCRC(DebugPath, CRCHash)) {
286     Result = DebugPath.str();
287     return true;
288   }
289   // Try /path/to/original_binary/.debug/debuglink_name
290   DebugPath = OrigRealPath;
291   llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
292   if (checkFileCRC(DebugPath, CRCHash)) {
293     Result = DebugPath.str();
294     return true;
295   }
296   // Try /usr/lib/debug/path/to/original_binary/debuglink_name
297   DebugPath = "/usr/lib/debug";
298   llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
299                           DebuglinkName);
300   if (checkFileCRC(DebugPath, CRCHash)) {
301     Result = DebugPath.str();
302     return true;
303   }
304   return false;
305 }
306
307 static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
308                                     uint32_t &CRCHash) {
309   if (!Obj)
310     return false;
311   for (const SectionRef &Section : Obj->sections()) {
312     StringRef Name;
313     Section.getName(Name);
314     Name = Name.substr(Name.find_first_not_of("._"));
315     if (Name == "gnu_debuglink") {
316       StringRef Data;
317       Section.getContents(Data);
318       DataExtractor DE(Data, Obj->isLittleEndian(), 0);
319       uint32_t Offset = 0;
320       if (const char *DebugNameStr = DE.getCStr(&Offset)) {
321         // 4-byte align the offset.
322         Offset = (Offset + 3) & ~0x3;
323         if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
324           DebugName = DebugNameStr;
325           CRCHash = DE.getU32(&Offset);
326           return true;
327         }
328       }
329       break;
330     }
331   }
332   return false;
333 }
334
335 static
336 bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
337                              const MachOObjectFile *Obj) {
338   ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
339   ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
340   if (dbg_uuid.empty() || bin_uuid.empty())
341     return false;
342   return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
343 }
344
345 ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
346     const MachOObjectFile *MachExeObj, const std::string &ArchName) {
347   // On Darwin we may find DWARF in separate object file in
348   // resource directory.
349   std::vector<std::string> DsymPaths;
350   StringRef Filename = sys::path::filename(ExePath);
351   DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
352   for (const auto &Path : Opts.DsymHints) {
353     DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
354   }
355   for (const auto &path : DsymPaths) {
356     ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
357     std::error_code EC = BinaryOrErr.getError();
358     if (EC != errc::no_such_file_or_directory && !error(EC)) {
359       OwningBinary<Binary> B = std::move(BinaryOrErr.get());
360       ObjectFile *DbgObj =
361           getObjectFileFromBinary(B.getBinary(), ArchName);
362       const MachOObjectFile *MachDbgObj =
363           dyn_cast<const MachOObjectFile>(DbgObj);
364       if (!MachDbgObj) continue;
365       if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
366         addOwningBinary(std::move(B));
367         return DbgObj; 
368       }
369     }
370   }
371   return nullptr;
372 }
373
374 LLVMSymbolizer::ObjectPair
375 LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
376                                    const std::string &ArchName) {
377   const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
378   if (I != ObjectPairForPathArch.end())
379     return I->second;
380   ObjectFile *Obj = nullptr;
381   ObjectFile *DbgObj = nullptr;
382   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
383   if (!error(BinaryOrErr.getError())) {
384     OwningBinary<Binary> &B = BinaryOrErr.get();
385     Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
386     if (!Obj) {
387       ObjectPair Res = std::make_pair(nullptr, nullptr);
388       ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
389       return Res;
390     }
391     addOwningBinary(std::move(B));
392     if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
393       DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
394     // Try to locate the debug binary using .gnu_debuglink section.
395     if (!DbgObj) {
396       std::string DebuglinkName;
397       uint32_t CRCHash;
398       std::string DebugBinaryPath;
399       if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
400           findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
401         BinaryOrErr = createBinary(DebugBinaryPath);
402         if (!error(BinaryOrErr.getError())) {
403           OwningBinary<Binary> B = std::move(BinaryOrErr.get());
404           DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
405           addOwningBinary(std::move(B));
406         }
407       }
408     }
409   }
410   if (!DbgObj)
411     DbgObj = Obj;
412   ObjectPair Res = std::make_pair(Obj, DbgObj);
413   ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
414   return Res;
415 }
416
417 ObjectFile *
418 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
419                                         const std::string &ArchName) {
420   if (!Bin)
421     return nullptr;
422   ObjectFile *Res = nullptr;
423   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
424     const auto &I = ObjectFileForArch.find(
425         std::make_pair(UB, ArchName));
426     if (I != ObjectFileForArch.end())
427       return I->second;
428     ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
429         UB->getObjectForArch(Triple(ArchName).getArch());
430     if (ParsedObj) {
431       Res = ParsedObj.get().get();
432       ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
433     }
434     ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
435   } else if (Bin->isObject()) {
436     Res = cast<ObjectFile>(Bin);
437   }
438   return Res;
439 }
440
441 ModuleInfo *
442 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
443   const auto &I = Modules.find(ModuleName);
444   if (I != Modules.end())
445     return I->second;
446   std::string BinaryName = ModuleName;
447   std::string ArchName = Opts.DefaultArch;
448   size_t ColonPos = ModuleName.find_last_of(':');
449   // Verify that substring after colon form a valid arch name.
450   if (ColonPos != std::string::npos) {
451     std::string ArchStr = ModuleName.substr(ColonPos + 1);
452     if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
453       BinaryName = ModuleName.substr(0, ColonPos);
454       ArchName = ArchStr;
455     }
456   }
457   ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
458
459   if (!Objects.first) {
460     // Failed to find valid object file.
461     Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
462     return nullptr;
463   }
464   DIContext *Context = new DWARFContextInMemory(*Objects.second);
465   assert(Context);
466   ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
467   Modules.insert(make_pair(ModuleName, Info));
468   return Info;
469 }
470
471 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
472   // By default, DILineInfo contains "<invalid>" for function/filename it
473   // cannot fetch. We replace it to "??" to make our output closer to addr2line.
474   static const std::string kDILineInfoBadString = "<invalid>";
475   std::stringstream Result;
476   if (Opts.PrintFunctions != FunctionNameKind::None) {
477     std::string FunctionName = LineInfo.FunctionName;
478     if (FunctionName == kDILineInfoBadString)
479       FunctionName = kBadString;
480     else if (Opts.Demangle)
481       FunctionName = DemangleName(FunctionName);
482     Result << FunctionName << "\n";
483   }
484   std::string Filename = LineInfo.FileName;
485   if (Filename == kDILineInfoBadString)
486     Filename = kBadString;
487   Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
488   return Result.str();
489 }
490
491 #if !defined(_MSC_VER)
492 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
493 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
494                                 size_t *length, int *status);
495 #endif
496
497 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
498 #if !defined(_MSC_VER)
499   // We can spoil names of symbols with C linkage, so use an heuristic
500   // approach to check if the name should be demangled.
501   if (Name.substr(0, 2) != "_Z")
502     return Name;
503   int status = 0;
504   char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
505   if (status != 0)
506     return Name;
507   std::string Result = DemangledName;
508   free(DemangledName);
509   return Result;
510 #else
511   return Name;
512 #endif
513 }
514
515 } // namespace symbolize
516 } // namespace llvm