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