llvm-symbolizer: use real path when looking for debug binary 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/Object/MachO.h"
18 #include "llvm/Support/Casting.h"
19 #include "llvm/Support/Compression.h"
20 #include "llvm/Support/DataExtractor.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/Path.h"
24
25 #include <sstream>
26 #include <stdlib.h>
27
28 namespace llvm {
29 namespace symbolize {
30
31 static bool error(error_code ec) {
32   if (!ec)
33     return false;
34   errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
35   return true;
36 }
37
38 static uint32_t
39 getDILineInfoSpecifierFlags(const LLVMSymbolizer::Options &Opts) {
40   uint32_t Flags = llvm::DILineInfoSpecifier::FileLineInfo |
41                    llvm::DILineInfoSpecifier::AbsoluteFilePath;
42   if (Opts.PrintFunctions)
43     Flags |= llvm::DILineInfoSpecifier::FunctionName;
44   return Flags;
45 }
46
47 static void patchFunctionNameInDILineInfo(const std::string &NewFunctionName,
48                                           DILineInfo &LineInfo) {
49   std::string FileName = LineInfo.getFileName();
50   LineInfo = DILineInfo(StringRef(FileName), StringRef(NewFunctionName),
51                         LineInfo.getLine(), LineInfo.getColumn());
52 }
53
54 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
55     : Module(Obj), DebugInfoContext(DICtx) {
56   error_code ec;
57   for (symbol_iterator si = Module->begin_symbols(), se = Module->end_symbols();
58        si != se; si.increment(ec)) {
59     if (error(ec))
60       return;
61     SymbolRef::Type SymbolType;
62     if (error(si->getType(SymbolType)))
63       continue;
64     if (SymbolType != SymbolRef::ST_Function &&
65         SymbolType != SymbolRef::ST_Data)
66       continue;
67     uint64_t SymbolAddress;
68     if (error(si->getAddress(SymbolAddress)) ||
69         SymbolAddress == UnknownAddressOrSize)
70       continue;
71     uint64_t SymbolSize;
72     // Getting symbol size is linear for Mach-O files, so assume that symbol
73     // occupies the memory range up to the following symbol.
74     if (isa<MachOObjectFile>(Obj))
75       SymbolSize = 0;
76     else if (error(si->getSize(SymbolSize)) ||
77              SymbolSize == UnknownAddressOrSize)
78       continue;
79     StringRef SymbolName;
80     if (error(si->getName(SymbolName)))
81       continue;
82     // Mach-O symbol table names have leading underscore, skip it.
83     if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
84       SymbolName = SymbolName.drop_front();
85     // FIXME: If a function has alias, there are two entries in symbol table
86     // with same address size. Make sure we choose the correct one.
87     SymbolMapTy &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
88     SymbolDesc SD = { SymbolAddress, SymbolSize };
89     M.insert(std::make_pair(SD, SymbolName));
90   }
91 }
92
93 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
94                                         std::string &Name, uint64_t &Addr,
95                                         uint64_t &Size) const {
96   const SymbolMapTy &M = Type == SymbolRef::ST_Function ? Functions : Objects;
97   if (M.empty())
98     return false;
99   SymbolDesc SD = { Address, Address };
100   SymbolMapTy::const_iterator it = M.upper_bound(SD);
101   if (it == M.begin())
102     return false;
103   --it;
104   if (it->first.Size != 0 && it->first.Addr + it->first.Size <= Address)
105     return false;
106   Name = it->second.str();
107   Addr = it->first.Addr;
108   Size = it->first.Size;
109   return true;
110 }
111
112 DILineInfo ModuleInfo::symbolizeCode(
113     uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
114   DILineInfo LineInfo;
115   if (DebugInfoContext) {
116     LineInfo = DebugInfoContext->getLineInfoForAddress(
117         ModuleOffset, getDILineInfoSpecifierFlags(Opts));
118   }
119   // Override function name from symbol table if necessary.
120   if (Opts.PrintFunctions && Opts.UseSymbolTable) {
121     std::string FunctionName;
122     uint64_t Start, Size;
123     if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
124                                FunctionName, Start, Size)) {
125       patchFunctionNameInDILineInfo(FunctionName, LineInfo);
126     }
127   }
128   return LineInfo;
129 }
130
131 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
132     uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
133   DIInliningInfo InlinedContext;
134   if (DebugInfoContext) {
135     InlinedContext = DebugInfoContext->getInliningInfoForAddress(
136         ModuleOffset, getDILineInfoSpecifierFlags(Opts));
137   }
138   // Make sure there is at least one frame in context.
139   if (InlinedContext.getNumberOfFrames() == 0) {
140     InlinedContext.addFrame(DILineInfo());
141   }
142   // Override the function name in lower frame with name from symbol table.
143   if (Opts.PrintFunctions && Opts.UseSymbolTable) {
144     DIInliningInfo PatchedInlinedContext;
145     for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
146       DILineInfo LineInfo = InlinedContext.getFrame(i);
147       if (i == n - 1) {
148         std::string FunctionName;
149         uint64_t Start, Size;
150         if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
151                                    FunctionName, Start, Size)) {
152           patchFunctionNameInDILineInfo(FunctionName, LineInfo);
153         }
154       }
155       PatchedInlinedContext.addFrame(LineInfo);
156     }
157     InlinedContext = PatchedInlinedContext;
158   }
159   return InlinedContext;
160 }
161
162 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
163                                uint64_t &Start, uint64_t &Size) const {
164   return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
165                                 Size);
166 }
167
168 const char LLVMSymbolizer::kBadString[] = "??";
169
170 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
171                                           uint64_t ModuleOffset) {
172   ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
173   if (Info == 0)
174     return printDILineInfo(DILineInfo());
175   if (Opts.PrintInlining) {
176     DIInliningInfo InlinedContext =
177         Info->symbolizeInlinedCode(ModuleOffset, Opts);
178     uint32_t FramesNum = InlinedContext.getNumberOfFrames();
179     assert(FramesNum > 0);
180     std::string Result;
181     for (uint32_t i = 0; i < FramesNum; i++) {
182       DILineInfo LineInfo = InlinedContext.getFrame(i);
183       Result += printDILineInfo(LineInfo);
184     }
185     return Result;
186   }
187   DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
188   return printDILineInfo(LineInfo);
189 }
190
191 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
192                                           uint64_t ModuleOffset) {
193   std::string Name = kBadString;
194   uint64_t Start = 0;
195   uint64_t Size = 0;
196   if (Opts.UseSymbolTable) {
197     if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
198       if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
199         Name = DemangleName(Name);
200     }
201   }
202   std::stringstream ss;
203   ss << Name << "\n" << Start << " " << Size << "\n";
204   return ss.str();
205 }
206
207 void LLVMSymbolizer::flush() {
208   DeleteContainerSeconds(Modules);
209   DeleteContainerPointers(ParsedBinariesAndObjects);
210   BinaryForPath.clear();
211   ObjectFileForArch.clear();
212 }
213
214 static std::string getDarwinDWARFResourceForPath(const std::string &Path) {
215   StringRef Basename = sys::path::filename(Path);
216   const std::string &DSymDirectory = Path + ".dSYM";
217   SmallString<16> ResourceName = StringRef(DSymDirectory);
218   sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
219   sys::path::append(ResourceName, Basename);
220   return ResourceName.str();
221 }
222
223 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
224   OwningPtr<MemoryBuffer> MB;
225   if (MemoryBuffer::getFileOrSTDIN(Path, MB))
226     return false;
227   return !zlib::isAvailable() || CRCHash == zlib::crc32(MB->getBuffer());
228 }
229
230 static bool findDebugBinary(const std::string &OrigPath,
231                             const std::string &DebuglinkName, uint32_t CRCHash,
232                             std::string &Result) {
233   std::string OrigRealPath = OrigPath;
234 #if defined(HAVE_REALPATH)
235   if (char *RP = realpath(OrigPath.c_str(), NULL)) {
236     OrigRealPath = RP;
237     free(RP);
238   }
239 #endif
240   SmallString<16> OrigDir(OrigRealPath);
241   llvm::sys::path::remove_filename(OrigDir);
242   SmallString<16> DebugPath = OrigDir;
243   // Try /path/to/original_binary/debuglink_name
244   llvm::sys::path::append(DebugPath, DebuglinkName);
245   if (checkFileCRC(DebugPath, CRCHash)) {
246     Result = DebugPath.str();
247     return true;
248   }
249   // Try /path/to/original_binary/.debug/debuglink_name
250   DebugPath = OrigRealPath;
251   llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
252   if (checkFileCRC(DebugPath, CRCHash)) {
253     Result = DebugPath.str();
254     return true;
255   }
256   // Try /usr/lib/debug/path/to/original_binary/debuglink_name
257   DebugPath = "/usr/lib/debug";
258   llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
259                           DebuglinkName);
260   if (checkFileCRC(DebugPath, CRCHash)) {
261     Result = DebugPath.str();
262     return true;
263   }
264   return false;
265 }
266
267 static bool getGNUDebuglinkContents(const Binary *Bin, std::string &DebugName,
268                                     uint32_t &CRCHash) {
269   const ObjectFile *Obj = dyn_cast<ObjectFile>(Bin);
270   if (!Obj)
271     return false;
272   error_code EC;
273   for (section_iterator I = Obj->begin_sections(), E = Obj->end_sections();
274        I != E; I.increment(EC)) {
275     StringRef Name;
276     I->getName(Name);
277     Name = Name.substr(Name.find_first_not_of("._"));
278     if (Name == "gnu_debuglink") {
279       StringRef Data;
280       I->getContents(Data);
281       DataExtractor DE(Data, Obj->isLittleEndian(), 0);
282       uint32_t Offset = 0;
283       if (const char *DebugNameStr = DE.getCStr(&Offset)) {
284         // 4-byte align the offset.
285         Offset = (Offset + 3) & ~0x3;
286         if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
287           DebugName = DebugNameStr;
288           CRCHash = DE.getU32(&Offset);
289           return true;
290         }
291       }
292       break;
293     }
294   }
295   return false;
296 }
297
298 LLVMSymbolizer::BinaryPair
299 LLVMSymbolizer::getOrCreateBinary(const std::string &Path) {
300   BinaryMapTy::iterator I = BinaryForPath.find(Path);
301   if (I != BinaryForPath.end())
302     return I->second;
303   Binary *Bin = 0;
304   Binary *DbgBin = 0;
305   OwningPtr<Binary> ParsedBinary;
306   OwningPtr<Binary> ParsedDbgBinary;
307   if (!error(createBinary(Path, ParsedBinary))) {
308     // Check if it's a universal binary.
309     Bin = ParsedBinary.take();
310     ParsedBinariesAndObjects.push_back(Bin);
311     if (Bin->isMachO() || Bin->isMachOUniversalBinary()) {
312       // On Darwin we may find DWARF in separate object file in
313       // resource directory.
314       const std::string &ResourcePath =
315           getDarwinDWARFResourceForPath(Path);
316       bool ResourceFileExists = false;
317       if (!sys::fs::exists(ResourcePath, ResourceFileExists) &&
318           ResourceFileExists &&
319           !error(createBinary(ResourcePath, ParsedDbgBinary))) {
320         DbgBin = ParsedDbgBinary.take();
321         ParsedBinariesAndObjects.push_back(DbgBin);
322       }
323     }
324     // Try to locate the debug binary using .gnu_debuglink section.
325     if (DbgBin == 0) {
326       std::string DebuglinkName;
327       uint32_t CRCHash;
328       std::string DebugBinaryPath;
329       if (getGNUDebuglinkContents(Bin, DebuglinkName, CRCHash) &&
330           findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath) &&
331           !error(createBinary(DebugBinaryPath, ParsedDbgBinary))) {
332         DbgBin = ParsedDbgBinary.take();
333         ParsedBinariesAndObjects.push_back(DbgBin);
334       }
335     }
336   }
337   if (DbgBin == 0)
338     DbgBin = Bin;
339   BinaryPair Res = std::make_pair(Bin, DbgBin);
340   BinaryForPath[Path] = Res;
341   return Res;
342 }
343
344 ObjectFile *
345 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin, const std::string &ArchName) {
346   if (Bin == 0)
347     return 0;
348   ObjectFile *Res = 0;
349   if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
350     ObjectFileForArchMapTy::iterator I = ObjectFileForArch.find(
351         std::make_pair(UB, ArchName));
352     if (I != ObjectFileForArch.end())
353       return I->second;
354     OwningPtr<ObjectFile> ParsedObj;
355     if (!UB->getObjectForArch(Triple(ArchName).getArch(), ParsedObj)) {
356       Res = ParsedObj.take();
357       ParsedBinariesAndObjects.push_back(Res);
358     }
359     ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
360   } else if (Bin->isObject()) {
361     Res = cast<ObjectFile>(Bin);
362   }
363   return Res;
364 }
365
366 ModuleInfo *
367 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
368   ModuleMapTy::iterator I = Modules.find(ModuleName);
369   if (I != Modules.end())
370     return I->second;
371   std::string BinaryName = ModuleName;
372   std::string ArchName = Opts.DefaultArch;
373   size_t ColonPos = ModuleName.find_last_of(':');
374   // Verify that substring after colon form a valid arch name.
375   if (ColonPos != std::string::npos) {
376     std::string ArchStr = ModuleName.substr(ColonPos + 1);
377     if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
378       BinaryName = ModuleName.substr(0, ColonPos);
379       ArchName = ArchStr;
380     }
381   }
382   BinaryPair Binaries = getOrCreateBinary(BinaryName);
383   ObjectFile *Obj = getObjectFileFromBinary(Binaries.first, ArchName);
384   ObjectFile *DbgObj = getObjectFileFromBinary(Binaries.second, ArchName);
385
386   if (Obj == 0) {
387     // Failed to find valid object file.
388     Modules.insert(make_pair(ModuleName, (ModuleInfo *)0));
389     return 0;
390   }
391   DIContext *Context = DIContext::getDWARFContext(DbgObj);
392   assert(Context);
393   ModuleInfo *Info = new ModuleInfo(Obj, Context);
394   Modules.insert(make_pair(ModuleName, Info));
395   return Info;
396 }
397
398 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
399   // By default, DILineInfo contains "<invalid>" for function/filename it
400   // cannot fetch. We replace it to "??" to make our output closer to addr2line.
401   static const std::string kDILineInfoBadString = "<invalid>";
402   std::stringstream Result;
403   if (Opts.PrintFunctions) {
404     std::string FunctionName = LineInfo.getFunctionName();
405     if (FunctionName == kDILineInfoBadString)
406       FunctionName = kBadString;
407     else if (Opts.Demangle)
408       FunctionName = DemangleName(FunctionName);
409     Result << FunctionName << "\n";
410   }
411   std::string Filename = LineInfo.getFileName();
412   if (Filename == kDILineInfoBadString)
413     Filename = kBadString;
414   Result << Filename << ":" << LineInfo.getLine() << ":" << LineInfo.getColumn()
415          << "\n";
416   return Result.str();
417 }
418
419 #if !defined(_MSC_VER)
420 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
421 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
422                                 size_t *length, int *status);
423 #endif
424
425 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
426 #if !defined(_MSC_VER)
427   int status = 0;
428   char *DemangledName = __cxa_demangle(Name.c_str(), 0, 0, &status);
429   if (status != 0)
430     return Name;
431   std::string Result = DemangledName;
432   free(DemangledName);
433   return Result;
434 #else
435   return Name;
436 #endif
437 }
438
439 } // namespace symbolize
440 } // namespace llvm