Don't use __cxa_demangle under MSVC (which doesn't have it)
[oota-llvm.git] / tools / llvm-symbolizer / llvm-symbolizer.cpp
1 //===-- llvm-symbolizer.cpp - Simple addr2line-like symbolizer ------------===//
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 // This utility works much like "addr2line". It is able of transforming
11 // tuples (module name, module offset) to code locations (function name,
12 // file, line number, column number). It is targeted for compiler-rt tools
13 // (especially AddressSanitizer and ThreadSanitizer) that can use it
14 // to symbolize stack traces in their error reports.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/DebugInfo/DIContext.h"
21 #include "llvm/Object/MachO.h"
22 #include "llvm/Object/ObjectFile.h"
23 #include "llvm/Support/Casting.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/PrettyStackTrace.h"
30 #include "llvm/Support/Signals.h"
31 #include "llvm/Support/raw_ostream.h"
32
33 #include <cstdio>
34 #include <cstring>
35 #include <map>
36 #include <string>
37
38 using namespace llvm;
39 using namespace object;
40
41 static cl::opt<bool>
42 UseSymbolTable("use-symbol-table", cl::init(true),
43                cl::desc("Prefer names in symbol table to names "
44                         "in debug info"));
45
46 static cl::opt<bool>
47 PrintFunctions("functions", cl::init(true),
48                cl::desc("Print function names as well as line "
49                         "information for a given address"));
50
51 static cl::opt<bool>
52 PrintInlining("inlining", cl::init(true),
53               cl::desc("Print all inlined frames for a given address"));
54
55 static cl::opt<bool>
56 Demangle("demangle", cl::init(true),
57          cl::desc("Demangle function names"));
58
59 static StringRef ToolInvocationPath;
60
61 static bool error(error_code ec) {
62   if (!ec) return false;
63   errs() << ToolInvocationPath << ": error reading file: "
64          << ec.message() << ".\n";
65   return true;
66 }
67
68 static uint32_t getDILineInfoSpecifierFlags() {
69   uint32_t Flags = llvm::DILineInfoSpecifier::FileLineInfo |
70                    llvm::DILineInfoSpecifier::AbsoluteFilePath;
71   if (PrintFunctions)
72     Flags |= llvm::DILineInfoSpecifier::FunctionName;
73   return Flags;
74 }
75
76 static void patchFunctionNameInDILineInfo(const std::string &NewFunctionName,
77                                           DILineInfo &LineInfo) {
78   std::string FileName = LineInfo.getFileName();
79   LineInfo = DILineInfo(StringRef(FileName), StringRef(NewFunctionName),
80                         LineInfo.getLine(), LineInfo.getColumn());
81 }
82
83 namespace {
84 class ModuleInfo {
85   OwningPtr<ObjectFile> Module;
86   OwningPtr<DIContext> DebugInfoContext;
87  public:
88   ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
89       : Module(Obj), DebugInfoContext(DICtx) {}
90
91   DILineInfo symbolizeCode(uint64_t ModuleOffset) const {
92     DILineInfo LineInfo;
93     if (DebugInfoContext) {
94       LineInfo = DebugInfoContext->getLineInfoForAddress(
95           ModuleOffset, getDILineInfoSpecifierFlags());
96     }
97     // Override function name from symbol table if necessary.
98     if (PrintFunctions && UseSymbolTable) {
99       std::string Function;
100       if (getFunctionNameFromSymbolTable(ModuleOffset, Function)) {
101         patchFunctionNameInDILineInfo(Function, LineInfo);
102       }
103     }
104     return LineInfo;
105   }
106
107   DIInliningInfo symbolizeInlinedCode(uint64_t ModuleOffset) const {
108     DIInliningInfo InlinedContext;
109     if (DebugInfoContext) {
110       InlinedContext = DebugInfoContext->getInliningInfoForAddress(
111           ModuleOffset, getDILineInfoSpecifierFlags());
112     }
113     // Make sure there is at least one frame in context.
114     if (InlinedContext.getNumberOfFrames() == 0) {
115       InlinedContext.addFrame(DILineInfo());
116     }
117     // Override the function name in lower frame with name from symbol table.
118     if (PrintFunctions && UseSymbolTable) {
119       DIInliningInfo PatchedInlinedContext;
120       for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames();
121            i != n; i++) {
122         DILineInfo LineInfo = InlinedContext.getFrame(i);
123         if (i == n - 1) {
124           std::string Function;
125           if (getFunctionNameFromSymbolTable(ModuleOffset, Function)) {
126             patchFunctionNameInDILineInfo(Function, LineInfo);
127           }
128         }
129         PatchedInlinedContext.addFrame(LineInfo);
130       }
131       InlinedContext = PatchedInlinedContext;
132     }
133     return InlinedContext;
134   }
135
136  private:
137   bool getFunctionNameFromSymbolTable(uint64_t Address,
138                                       std::string &FunctionName) const {
139     assert(Module);
140     error_code ec;
141     for (symbol_iterator si = Module->begin_symbols(),
142                          se = Module->end_symbols();
143                          si != se; si.increment(ec)) {
144       if (error(ec)) return false;
145       uint64_t SymbolAddress;
146       uint64_t SymbolSize;
147       SymbolRef::Type SymbolType;
148       if (error(si->getAddress(SymbolAddress)) ||
149           SymbolAddress == UnknownAddressOrSize) continue;
150       if (error(si->getSize(SymbolSize)) ||
151           SymbolSize == UnknownAddressOrSize) continue;
152       if (error(si->getType(SymbolType))) continue;
153       // FIXME: If a function has alias, there are two entries in symbol table
154       // with same address size. Make sure we choose the correct one.
155       if (SymbolAddress <= Address && Address < SymbolAddress + SymbolSize &&
156           SymbolType == SymbolRef::ST_Function) {
157         StringRef Name;
158         if (error(si->getName(Name))) continue;
159         FunctionName = Name.str();
160         return true;
161       }
162     }
163     return false;
164   }
165 };
166
167 typedef std::map<std::string, ModuleInfo*> ModuleMapTy;
168 typedef ModuleMapTy::iterator ModuleMapIter;
169 }  // namespace
170
171 static ModuleMapTy Modules;
172
173 static bool isFullNameOfDwarfSection(const StringRef &FullName,
174                                      const StringRef &ShortName) {
175   static const char kDwarfPrefix[] = "__DWARF,";
176   StringRef Name = FullName;
177   // Skip "__DWARF," prefix.
178   if (Name.startswith(kDwarfPrefix))
179     Name = Name.substr(strlen(kDwarfPrefix));
180   // Skip . and _ prefixes.
181   Name = Name.substr(Name.find_first_not_of("._"));
182   return (Name == ShortName);
183 }
184
185 // Returns true if the object endianness is known.
186 static bool getObjectEndianness(const ObjectFile *Obj,
187                                 bool &IsLittleEndian) {
188   // FIXME: Implement this when libLLVMObject allows to do it easily.
189   IsLittleEndian = true;
190   return true;
191 }
192
193 static void getDebugInfoSections(const ObjectFile *Obj,
194                                  StringRef &DebugInfoSection,
195                                  StringRef &DebugAbbrevSection,
196                                  StringRef &DebugLineSection,
197                                  StringRef &DebugArangesSection, 
198                                  StringRef &DebugStringSection, 
199                                  StringRef &DebugRangesSection) {
200   if (Obj == 0)
201     return;
202   error_code ec;
203   for (section_iterator i = Obj->begin_sections(),
204                         e = Obj->end_sections();
205                         i != e; i.increment(ec)) {
206     if (error(ec)) break;
207     StringRef Name;
208     if (error(i->getName(Name))) continue;
209     StringRef Data;
210     if (error(i->getContents(Data))) continue;
211     if (isFullNameOfDwarfSection(Name, "debug_info"))
212       DebugInfoSection = Data;
213     else if (isFullNameOfDwarfSection(Name, "debug_abbrev"))
214       DebugAbbrevSection = Data;
215     else if (isFullNameOfDwarfSection(Name, "debug_line"))
216       DebugLineSection = Data;
217     // Don't use debug_aranges for now, as address ranges contained
218     // there may not cover all instructions in the module
219     // else if (isFullNameOfDwarfSection(Name, "debug_aranges"))
220     //   DebugArangesSection = Data;
221     else if (isFullNameOfDwarfSection(Name, "debug_str"))
222       DebugStringSection = Data;
223     else if (isFullNameOfDwarfSection(Name, "debug_ranges"))
224       DebugRangesSection = Data;
225   }
226 }
227
228 static ObjectFile *getObjectFile(const std::string &Path) {
229   OwningPtr<MemoryBuffer> Buff;
230   MemoryBuffer::getFile(Path, Buff);
231   return ObjectFile::createObjectFile(Buff.take());
232 }
233
234 static std::string getDarwinDWARFResourceForModule(const std::string &Path) {
235   StringRef Basename = sys::path::filename(Path);
236   const std::string &DSymDirectory = Path + ".dSYM";
237   SmallString<16> ResourceName = StringRef(DSymDirectory);
238   sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
239   sys::path::append(ResourceName, Basename);
240   return ResourceName.str();
241 }
242
243 static ModuleInfo *getOrCreateModuleInfo(const std::string &ModuleName) {
244   ModuleMapIter I = Modules.find(ModuleName);
245   if (I != Modules.end())
246     return I->second;
247
248   ObjectFile *Obj = getObjectFile(ModuleName);
249   if (Obj == 0) {
250     // Module name doesn't point to a valid object file.
251     Modules.insert(make_pair(ModuleName, (ModuleInfo*)0));
252     return 0;
253   }
254
255   DIContext *Context = 0;
256   bool IsLittleEndian;
257   if (getObjectEndianness(Obj, IsLittleEndian)) {
258     StringRef DebugInfo;
259     StringRef DebugAbbrev;
260     StringRef DebugLine;
261     StringRef DebugAranges;
262     StringRef DebugString;
263     StringRef DebugRanges;
264     getDebugInfoSections(Obj, DebugInfo, DebugAbbrev, DebugLine,
265                          DebugAranges, DebugString, DebugRanges);
266     
267     // On Darwin we may find DWARF in separate object file in
268     // resource directory.
269     if (isa<MachOObjectFile>(Obj)) {
270       const std::string &ResourceName = getDarwinDWARFResourceForModule(
271           ModuleName);
272       ObjectFile *ResourceObj = getObjectFile(ResourceName);
273       if (ResourceObj != 0)
274         getDebugInfoSections(ResourceObj, DebugInfo, DebugAbbrev, DebugLine,
275                              DebugAranges, DebugString, DebugRanges);
276     }
277
278     Context = DIContext::getDWARFContext(
279         IsLittleEndian, DebugInfo, DebugAbbrev,
280         DebugAranges, DebugLine, DebugString,
281         DebugRanges);
282     assert(Context);
283   }
284
285   ModuleInfo *Info = new ModuleInfo(Obj, Context);
286   Modules.insert(make_pair(ModuleName, Info));
287   return Info;
288 }
289
290 #if !defined(_MSC_VER)
291 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
292 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
293                                 size_t *length, int *status);
294 #endif
295
296 static void printDILineInfo(DILineInfo LineInfo) {
297   // By default, DILineInfo contains "<invalid>" for function/filename it
298   // cannot fetch. We replace it to "??" to make our output closer to addr2line.
299   static const std::string kDILineInfoBadString = "<invalid>";
300   static const std::string kSymbolizerBadString = "??";
301   if (PrintFunctions) {
302     std::string FunctionName = LineInfo.getFunctionName();
303     if (FunctionName == kDILineInfoBadString)
304       FunctionName = kSymbolizerBadString;
305 #if !defined(_MSC_VER)
306     if (Demangle) {
307       int status = 0;
308       char *DemangledName = __cxa_demangle(
309           FunctionName.c_str(), 0, 0, &status);
310       if (status == 0) {
311         FunctionName = DemangledName;
312         free(DemangledName);
313       }
314     }
315 #endif
316     outs() << FunctionName << "\n";
317   }
318   std::string Filename = LineInfo.getFileName();
319   if (Filename == kDILineInfoBadString)
320     Filename = kSymbolizerBadString;
321   outs() << Filename <<
322          ":" << LineInfo.getLine() <<
323          ":" << LineInfo.getColumn() <<
324          "\n";
325 }
326
327 static void symbolize(std::string ModuleName, std::string ModuleOffsetStr) {
328   ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
329   uint64_t Offset = 0;
330   if (Info == 0 ||
331       StringRef(ModuleOffsetStr).getAsInteger(0, Offset)) {
332     printDILineInfo(DILineInfo());
333   } else if (PrintInlining) {
334     DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(Offset);
335     uint32_t FramesNum = InlinedContext.getNumberOfFrames();
336     assert(FramesNum > 0);
337     for (uint32_t i = 0; i < FramesNum; i++) {
338       DILineInfo LineInfo = InlinedContext.getFrame(i);
339       printDILineInfo(LineInfo);
340     }
341   } else {
342     DILineInfo LineInfo = Info->symbolizeCode(Offset);
343     printDILineInfo(LineInfo);
344   }
345
346   outs() << "\n";  // Print extra empty line to mark the end of output.
347   outs().flush();
348 }
349
350 static bool parseModuleNameAndOffset(std::string &ModuleName,
351                                      std::string &ModuleOffsetStr) {
352   static const int kMaxInputStringLength = 1024;
353   static const char kDelimiters[] = " \n";
354   char InputString[kMaxInputStringLength];
355   if (!fgets(InputString, sizeof(InputString), stdin))
356     return false;
357   ModuleName = "";
358   ModuleOffsetStr = "";
359   // FIXME: Handle case when filename is given in quotes.
360   if (char *FilePath = strtok(InputString, kDelimiters)) {
361     ModuleName = FilePath;
362     if (char *OffsetStr = strtok((char*)0, kDelimiters))
363       ModuleOffsetStr = OffsetStr;
364   }
365   return true;
366 }
367
368 int main(int argc, char **argv) {
369   // Print stack trace if we signal out.
370   sys::PrintStackTraceOnErrorSignal();
371   PrettyStackTraceProgram X(argc, argv);
372   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
373
374   cl::ParseCommandLineOptions(argc, argv, "llvm symbolizer for compiler-rt\n");
375   ToolInvocationPath = argv[0];
376
377   std::string ModuleName;
378   std::string ModuleOffsetStr;
379   while (parseModuleNameAndOffset(ModuleName, ModuleOffsetStr)) {
380     symbolize(ModuleName, ModuleOffsetStr);
381   }
382   return 0;
383 }