OSDN Git Service

[DWARF parser] Turn DILineInfo into a struct.
[android-x86/external-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/ELFObjectFile.h"
18 #include "llvm/Object/MachO.h"
19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/Compression.h"
21 #include "llvm/Support/DataExtractor.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/Path.h"
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 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
48     : Module(Obj), DebugInfoContext(DICtx) {
49   for (const SymbolRef &Symbol : Module->symbols()) {
50     addSymbol(Symbol);
51   }
52   bool NoSymbolTable = (Module->symbol_begin() == Module->symbol_end());
53   if (NoSymbolTable && Module->isELF()) {
54     // Fallback to dynamic symbol table, if regular symbol table is stripped.
55     std::pair<symbol_iterator, symbol_iterator> IDyn =
56         getELFDynamicSymbolIterators(Module);
57     for (symbol_iterator si = IDyn.first, se = IDyn.second; si != se; ++si) {
58       addSymbol(*si);
59     }
60   }
61 }
62
63 void ModuleInfo::addSymbol(const SymbolRef &Symbol) {
64   SymbolRef::Type SymbolType;
65   if (error(Symbol.getType(SymbolType)))
66     return;
67   if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
68     return;
69   uint64_t SymbolAddress;
70   if (error(Symbol.getAddress(SymbolAddress)) ||
71       SymbolAddress == UnknownAddressOrSize)
72     return;
73   uint64_t SymbolSize;
74   // Getting symbol size is linear for Mach-O files, so assume that symbol
75   // occupies the memory range up to the following symbol.
76   if (isa<MachOObjectFile>(Module))
77     SymbolSize = 0;
78   else if (error(Symbol.getSize(SymbolSize)) ||
79            SymbolSize == UnknownAddressOrSize)
80     return;
81   StringRef SymbolName;
82   if (error(Symbol.getName(SymbolName)))
83     return;
84   // Mach-O symbol table names have leading underscore, skip it.
85   if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
86     SymbolName = SymbolName.drop_front();
87   // FIXME: If a function has alias, there are two entries in symbol table
88   // with same address size. Make sure we choose the correct one.
89   SymbolMapTy &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
90   SymbolDesc SD = { SymbolAddress, SymbolSize };
91   M.insert(std::make_pair(SD, SymbolName));
92 }
93
94 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
95                                         std::string &Name, uint64_t &Addr,
96                                         uint64_t &Size) const {
97   const SymbolMapTy &M = Type == SymbolRef::ST_Function ? Functions : Objects;
98   if (M.empty())
99     return false;
100   SymbolDesc SD = { Address, Address };
101   SymbolMapTy::const_iterator it = M.upper_bound(SD);
102   if (it == M.begin())
103     return false;
104   --it;
105   if (it->first.Size != 0 && it->first.Addr + it->first.Size <= Address)
106     return false;
107   Name = it->second.str();
108   Addr = it->first.Addr;
109   Size = it->first.Size;
110   return true;
111 }
112
113 DILineInfo ModuleInfo::symbolizeCode(
114     uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
115   DILineInfo LineInfo;
116   if (DebugInfoContext) {
117     LineInfo = DebugInfoContext->getLineInfoForAddress(
118         ModuleOffset, getDILineInfoSpecifierFlags(Opts));
119   }
120   // Override function name from symbol table if necessary.
121   if (Opts.PrintFunctions && Opts.UseSymbolTable) {
122     std::string FunctionName;
123     uint64_t Start, Size;
124     if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
125                                FunctionName, Start, Size)) {
126       LineInfo.FunctionName = FunctionName;
127     }
128   }
129   return LineInfo;
130 }
131
132 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
133     uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
134   DIInliningInfo InlinedContext;
135   if (DebugInfoContext) {
136     InlinedContext = DebugInfoContext->getInliningInfoForAddress(
137         ModuleOffset, getDILineInfoSpecifierFlags(Opts));
138   }
139   // Make sure there is at least one frame in context.
140   if (InlinedContext.getNumberOfFrames() == 0) {
141     InlinedContext.addFrame(DILineInfo());
142   }
143   // Override the function name in lower frame with name from symbol table.
144   if (Opts.PrintFunctions && Opts.UseSymbolTable) {
145     DIInliningInfo PatchedInlinedContext;
146     for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
147       DILineInfo LineInfo = InlinedContext.getFrame(i);
148       if (i == n - 1) {
149         std::string FunctionName;
150         uint64_t Start, Size;
151         if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
152                                    FunctionName, Start, Size)) {
153           LineInfo.FunctionName = FunctionName;
154         }
155       }
156       PatchedInlinedContext.addFrame(LineInfo);
157     }
158     InlinedContext = PatchedInlinedContext;
159   }
160   return InlinedContext;
161 }
162
163 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
164                                uint64_t &Start, uint64_t &Size) const {
165   return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
166                                 Size);
167 }
168
169 const char LLVMSymbolizer::kBadString[] = "??";
170
171 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
172                                           uint64_t ModuleOffset) {
173   ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
174   if (Info == 0)
175     return printDILineInfo(DILineInfo());
176   if (Opts.PrintInlining) {
177     DIInliningInfo InlinedContext =
178         Info->symbolizeInlinedCode(ModuleOffset, Opts);
179     uint32_t FramesNum = InlinedContext.getNumberOfFrames();
180     assert(FramesNum > 0);
181     std::string Result;
182     for (uint32_t i = 0; i < FramesNum; i++) {
183       DILineInfo LineInfo = InlinedContext.getFrame(i);
184       Result += printDILineInfo(LineInfo);
185     }
186     return Result;
187   }
188   DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
189   return printDILineInfo(LineInfo);
190 }
191
192 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
193                                           uint64_t ModuleOffset) {
194   std::string Name = kBadString;
195   uint64_t Start = 0;
196   uint64_t Size = 0;
197   if (Opts.UseSymbolTable) {
198     if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
199       if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
200         Name = DemangleName(Name);
201     }
202   }
203   std::stringstream ss;
204   ss << Name << "\n" << Start << " " << Size << "\n";
205   return ss.str();
206 }
207
208 void LLVMSymbolizer::flush() {
209   DeleteContainerSeconds(Modules);
210   DeleteContainerPointers(ParsedBinariesAndObjects);
211   BinaryForPath.clear();
212   ObjectFileForArch.clear();
213 }
214
215 static std::string getDarwinDWARFResourceForPath(const std::string &Path) {
216   StringRef Basename = sys::path::filename(Path);
217   const std::string &DSymDirectory = Path + ".dSYM";
218   SmallString<16> ResourceName = StringRef(DSymDirectory);
219   sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
220   sys::path::append(ResourceName, Basename);
221   return ResourceName.str();
222 }
223
224 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
225   std::unique_ptr<MemoryBuffer> MB;
226   if (MemoryBuffer::getFileOrSTDIN(Path, MB))
227     return false;
228   return !zlib::isAvailable() || CRCHash == zlib::crc32(MB->getBuffer());
229 }
230
231 static bool findDebugBinary(const std::string &OrigPath,
232                             const std::string &DebuglinkName, uint32_t CRCHash,
233                             std::string &Result) {
234   std::string OrigRealPath = OrigPath;
235 #if defined(HAVE_REALPATH)
236   if (char *RP = realpath(OrigPath.c_str(), NULL)) {
237     OrigRealPath = RP;
238     free(RP);
239   }
240 #endif
241   SmallString<16> OrigDir(OrigRealPath);
242   llvm::sys::path::remove_filename(OrigDir);
243   SmallString<16> DebugPath = OrigDir;
244   // Try /path/to/original_binary/debuglink_name
245   llvm::sys::path::append(DebugPath, DebuglinkName);
246   if (checkFileCRC(DebugPath, CRCHash)) {
247     Result = DebugPath.str();
248     return true;
249   }
250   // Try /path/to/original_binary/.debug/debuglink_name
251   DebugPath = OrigRealPath;
252   llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
253   if (checkFileCRC(DebugPath, CRCHash)) {
254     Result = DebugPath.str();
255     return true;
256   }
257   // Try /usr/lib/debug/path/to/original_binary/debuglink_name
258   DebugPath = "/usr/lib/debug";
259   llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
260                           DebuglinkName);
261   if (checkFileCRC(DebugPath, CRCHash)) {
262     Result = DebugPath.str();
263     return true;
264   }
265   return false;
266 }
267
268 static bool getGNUDebuglinkContents(const Binary *Bin, std::string &DebugName,
269                                     uint32_t &CRCHash) {
270   const ObjectFile *Obj = dyn_cast<ObjectFile>(Bin);
271   if (!Obj)
272     return false;
273   for (const SectionRef &Section : Obj->sections()) {
274     StringRef Name;
275     Section.getName(Name);
276     Name = Name.substr(Name.find_first_not_of("._"));
277     if (Name == "gnu_debuglink") {
278       StringRef Data;
279       Section.getContents(Data);
280       DataExtractor DE(Data, Obj->isLittleEndian(), 0);
281       uint32_t Offset = 0;
282       if (const char *DebugNameStr = DE.getCStr(&Offset)) {
283         // 4-byte align the offset.
284         Offset = (Offset + 3) & ~0x3;
285         if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
286           DebugName = DebugNameStr;
287           CRCHash = DE.getU32(&Offset);
288           return true;
289         }
290       }
291       break;
292     }
293   }
294   return false;
295 }
296
297 LLVMSymbolizer::BinaryPair
298 LLVMSymbolizer::getOrCreateBinary(const std::string &Path) {
299   BinaryMapTy::iterator I = BinaryForPath.find(Path);
300   if (I != BinaryForPath.end())
301     return I->second;
302   Binary *Bin = 0;
303   Binary *DbgBin = 0;
304   ErrorOr<Binary *> BinaryOrErr = createBinary(Path);
305   if (!error(BinaryOrErr.getError())) {
306     std::unique_ptr<Binary> ParsedBinary(BinaryOrErr.get());
307     // Check if it's a universal binary.
308     Bin = ParsedBinary.release();
309     ParsedBinariesAndObjects.push_back(Bin);
310     if (Bin->isMachO() || Bin->isMachOUniversalBinary()) {
311       // On Darwin we may find DWARF in separate object file in
312       // resource directory.
313       const std::string &ResourcePath =
314           getDarwinDWARFResourceForPath(Path);
315       BinaryOrErr = createBinary(ResourcePath);
316       error_code EC = BinaryOrErr.getError();
317       if (EC != errc::no_such_file_or_directory && !error(EC)) {
318         DbgBin = BinaryOrErr.get();
319         ParsedBinariesAndObjects.push_back(DbgBin);
320       }
321     }
322     // Try to locate the debug binary using .gnu_debuglink section.
323     if (DbgBin == 0) {
324       std::string DebuglinkName;
325       uint32_t CRCHash;
326       std::string DebugBinaryPath;
327       if (getGNUDebuglinkContents(Bin, DebuglinkName, CRCHash) &&
328           findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
329         BinaryOrErr = createBinary(DebugBinaryPath);
330         if (!error(BinaryOrErr.getError())) {
331           DbgBin = BinaryOrErr.get();
332           ParsedBinariesAndObjects.push_back(DbgBin);
333         }
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     std::unique_ptr<ObjectFile> ParsedObj;
355     if (!UB->getObjectForArch(Triple(ArchName).getArch(), ParsedObj)) {
356       Res = ParsedObj.release();
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.FunctionName;
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.FileName;
412   if (Filename == kDILineInfoBadString)
413     Filename = kBadString;
414   Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
415   return Result.str();
416 }
417
418 #if !defined(_MSC_VER)
419 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
420 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
421                                 size_t *length, int *status);
422 #endif
423
424 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
425 #if !defined(_MSC_VER)
426   // We can spoil names of symbols with C linkage, so use an heuristic
427   // approach to check if the name should be demangled.
428   if (Name.substr(0, 2) != "_Z")
429     return Name;
430   int status = 0;
431   char *DemangledName = __cxa_demangle(Name.c_str(), 0, 0, &status);
432   if (status != 0)
433     return Name;
434   std::string Result = DemangledName;
435   free(DemangledName);
436   return Result;
437 #else
438   return Name;
439 #endif
440 }
441
442 } // namespace symbolize
443 } // namespace llvm