Sort the #include lines for tools/...
[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 #include <cstdio>
33 #include <cstring>
34 #include <map>
35 #include <string>
36
37 using namespace llvm;
38 using namespace object;
39
40 static cl::opt<bool>
41 UseSymbolTable("use-symbol-table", cl::init(true),
42                cl::desc("Prefer names in symbol table to names "
43                         "in debug info"));
44
45 static cl::opt<bool>
46 PrintFunctions("functions", cl::init(true),
47                cl::desc("Print function names as well as line "
48                         "information for a given address"));
49
50 static cl::opt<bool>
51 PrintInlining("inlining", cl::init(true),
52               cl::desc("Print all inlined frames for a given address"));
53
54 static cl::opt<bool>
55 Demangle("demangle", cl::init(true),
56          cl::desc("Demangle function names"));
57
58 static StringRef ToolInvocationPath;
59
60 static bool error(error_code ec) {
61   if (!ec) return false;
62   errs() << ToolInvocationPath << ": error reading file: "
63          << ec.message() << ".\n";
64   return true;
65 }
66
67 static uint32_t getDILineInfoSpecifierFlags() {
68   uint32_t Flags = llvm::DILineInfoSpecifier::FileLineInfo |
69                    llvm::DILineInfoSpecifier::AbsoluteFilePath;
70   if (PrintFunctions)
71     Flags |= llvm::DILineInfoSpecifier::FunctionName;
72   return Flags;
73 }
74
75 static void patchFunctionNameInDILineInfo(const std::string &NewFunctionName,
76                                           DILineInfo &LineInfo) {
77   std::string FileName = LineInfo.getFileName();
78   LineInfo = DILineInfo(StringRef(FileName), StringRef(NewFunctionName),
79                         LineInfo.getLine(), LineInfo.getColumn());
80 }
81
82 namespace {
83 class ModuleInfo {
84   OwningPtr<ObjectFile> Module;
85   OwningPtr<DIContext> DebugInfoContext;
86  public:
87   ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
88       : Module(Obj), DebugInfoContext(DICtx) {}
89
90   DILineInfo symbolizeCode(uint64_t ModuleOffset) const {
91     DILineInfo LineInfo;
92     if (DebugInfoContext) {
93       LineInfo = DebugInfoContext->getLineInfoForAddress(
94           ModuleOffset, getDILineInfoSpecifierFlags());
95     }
96     // Override function name from symbol table if necessary.
97     if (PrintFunctions && UseSymbolTable) {
98       std::string Function;
99       if (getFunctionNameFromSymbolTable(ModuleOffset, Function)) {
100         patchFunctionNameInDILineInfo(Function, LineInfo);
101       }
102     }
103     return LineInfo;
104   }
105
106   DIInliningInfo symbolizeInlinedCode(uint64_t ModuleOffset) const {
107     DIInliningInfo InlinedContext;
108     if (DebugInfoContext) {
109       InlinedContext = DebugInfoContext->getInliningInfoForAddress(
110           ModuleOffset, getDILineInfoSpecifierFlags());
111     }
112     // Make sure there is at least one frame in context.
113     if (InlinedContext.getNumberOfFrames() == 0) {
114       InlinedContext.addFrame(DILineInfo());
115     }
116     // Override the function name in lower frame with name from symbol table.
117     if (PrintFunctions && UseSymbolTable) {
118       DIInliningInfo PatchedInlinedContext;
119       for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames();
120            i != n; i++) {
121         DILineInfo LineInfo = InlinedContext.getFrame(i);
122         if (i == n - 1) {
123           std::string Function;
124           if (getFunctionNameFromSymbolTable(ModuleOffset, Function)) {
125             patchFunctionNameInDILineInfo(Function, LineInfo);
126           }
127         }
128         PatchedInlinedContext.addFrame(LineInfo);
129       }
130       InlinedContext = PatchedInlinedContext;
131     }
132     return InlinedContext;
133   }
134
135  private:
136   bool getFunctionNameFromSymbolTable(uint64_t Address,
137                                       std::string &FunctionName) const {
138     assert(Module);
139     error_code ec;
140     for (symbol_iterator si = Module->begin_symbols(),
141                          se = Module->end_symbols();
142                          si != se; si.increment(ec)) {
143       if (error(ec)) return false;
144       uint64_t SymbolAddress;
145       uint64_t SymbolSize;
146       SymbolRef::Type SymbolType;
147       if (error(si->getAddress(SymbolAddress)) ||
148           SymbolAddress == UnknownAddressOrSize) continue;
149       if (error(si->getSize(SymbolSize)) ||
150           SymbolSize == UnknownAddressOrSize) continue;
151       if (error(si->getType(SymbolType))) continue;
152       // FIXME: If a function has alias, there are two entries in symbol table
153       // with same address size. Make sure we choose the correct one.
154       if (SymbolAddress <= Address && Address < SymbolAddress + SymbolSize &&
155           SymbolType == SymbolRef::ST_Function) {
156         StringRef Name;
157         if (error(si->getName(Name))) continue;
158         FunctionName = Name.str();
159         return true;
160       }
161     }
162     return false;
163   }
164 };
165
166 typedef std::map<std::string, ModuleInfo*> ModuleMapTy;
167 typedef ModuleMapTy::iterator ModuleMapIter;
168 }  // namespace
169
170 static ModuleMapTy Modules;
171
172 // Returns true if the object endianness is known.
173 static bool getObjectEndianness(const ObjectFile *Obj,
174                                 bool &IsLittleEndian) {
175   // FIXME: Implement this when libLLVMObject allows to do it easily.
176   IsLittleEndian = true;
177   return true;
178 }
179
180 static ObjectFile *getObjectFile(const std::string &Path) {
181   OwningPtr<MemoryBuffer> Buff;
182   MemoryBuffer::getFile(Path, Buff);
183   return ObjectFile::createObjectFile(Buff.take());
184 }
185
186 static std::string getDarwinDWARFResourceForModule(const std::string &Path) {
187   StringRef Basename = sys::path::filename(Path);
188   const std::string &DSymDirectory = Path + ".dSYM";
189   SmallString<16> ResourceName = StringRef(DSymDirectory);
190   sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
191   sys::path::append(ResourceName, Basename);
192   return ResourceName.str();
193 }
194
195 static ModuleInfo *getOrCreateModuleInfo(const std::string &ModuleName) {
196   ModuleMapIter I = Modules.find(ModuleName);
197   if (I != Modules.end())
198     return I->second;
199
200   ObjectFile *Obj = getObjectFile(ModuleName);
201   ObjectFile *DbgObj = Obj;
202   if (Obj == 0) {
203     // Module name doesn't point to a valid object file.
204     Modules.insert(make_pair(ModuleName, (ModuleInfo*)0));
205     return 0;
206   }
207
208   DIContext *Context = 0;
209   bool IsLittleEndian;
210   if (getObjectEndianness(Obj, IsLittleEndian)) {
211     // On Darwin we may find DWARF in separate object file in
212     // resource directory.
213     if (isa<MachOObjectFile>(Obj)) {
214       const std::string &ResourceName = getDarwinDWARFResourceForModule(
215           ModuleName);
216       ObjectFile *ResourceObj = getObjectFile(ResourceName);
217       if (ResourceObj != 0)
218         DbgObj = ResourceObj;
219     }
220     Context = DIContext::getDWARFContext(DbgObj);
221     assert(Context);
222   }
223
224   ModuleInfo *Info = new ModuleInfo(Obj, Context);
225   Modules.insert(make_pair(ModuleName, Info));
226   return Info;
227 }
228
229 #if !defined(_MSC_VER)
230 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
231 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
232                                 size_t *length, int *status);
233 #endif
234
235 static void printDILineInfo(DILineInfo LineInfo) {
236   // By default, DILineInfo contains "<invalid>" for function/filename it
237   // cannot fetch. We replace it to "??" to make our output closer to addr2line.
238   static const std::string kDILineInfoBadString = "<invalid>";
239   static const std::string kSymbolizerBadString = "??";
240   if (PrintFunctions) {
241     std::string FunctionName = LineInfo.getFunctionName();
242     if (FunctionName == kDILineInfoBadString)
243       FunctionName = kSymbolizerBadString;
244 #if !defined(_MSC_VER)
245     if (Demangle) {
246       int status = 0;
247       char *DemangledName = __cxa_demangle(
248           FunctionName.c_str(), 0, 0, &status);
249       if (status == 0) {
250         FunctionName = DemangledName;
251         free(DemangledName);
252       }
253     }
254 #endif
255     outs() << FunctionName << "\n";
256   }
257   std::string Filename = LineInfo.getFileName();
258   if (Filename == kDILineInfoBadString)
259     Filename = kSymbolizerBadString;
260   outs() << Filename <<
261          ":" << LineInfo.getLine() <<
262          ":" << LineInfo.getColumn() <<
263          "\n";
264 }
265
266 static void symbolize(std::string ModuleName, std::string ModuleOffsetStr) {
267   ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
268   uint64_t Offset = 0;
269   if (Info == 0 ||
270       StringRef(ModuleOffsetStr).getAsInteger(0, Offset)) {
271     printDILineInfo(DILineInfo());
272   } else if (PrintInlining) {
273     DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(Offset);
274     uint32_t FramesNum = InlinedContext.getNumberOfFrames();
275     assert(FramesNum > 0);
276     for (uint32_t i = 0; i < FramesNum; i++) {
277       DILineInfo LineInfo = InlinedContext.getFrame(i);
278       printDILineInfo(LineInfo);
279     }
280   } else {
281     DILineInfo LineInfo = Info->symbolizeCode(Offset);
282     printDILineInfo(LineInfo);
283   }
284
285   outs() << "\n";  // Print extra empty line to mark the end of output.
286   outs().flush();
287 }
288
289 static bool parseModuleNameAndOffset(std::string &ModuleName,
290                                      std::string &ModuleOffsetStr) {
291   static const int kMaxInputStringLength = 1024;
292   static const char kDelimiters[] = " \n";
293   char InputString[kMaxInputStringLength];
294   if (!fgets(InputString, sizeof(InputString), stdin))
295     return false;
296   ModuleName = "";
297   ModuleOffsetStr = "";
298   // FIXME: Handle case when filename is given in quotes.
299   if (char *FilePath = strtok(InputString, kDelimiters)) {
300     ModuleName = FilePath;
301     if (char *OffsetStr = strtok((char*)0, kDelimiters))
302       ModuleOffsetStr = OffsetStr;
303   }
304   return true;
305 }
306
307 int main(int argc, char **argv) {
308   // Print stack trace if we signal out.
309   sys::PrintStackTraceOnErrorSignal();
310   PrettyStackTraceProgram X(argc, argv);
311   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
312
313   cl::ParseCommandLineOptions(argc, argv, "llvm symbolizer for compiler-rt\n");
314   ToolInvocationPath = argv[0];
315
316   std::string ModuleName;
317   std::string ModuleOffsetStr;
318   while (parseModuleNameAndOffset(ModuleName, ModuleOffsetStr)) {
319     symbolize(ModuleName, ModuleOffsetStr);
320   }
321   return 0;
322 }