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