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