llvm-symbolizer: factor out bits of the tool into separate LLVMSymbolize.{h,cpp}...
[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/Object/MachO.h"
16 #include "llvm/Support/Casting.h"
17 #include "llvm/Support/Path.h"
18
19 #include <sstream>
20
21 namespace llvm {
22 namespace symbolize {
23
24 static uint32_t getDILineInfoSpecifierFlags(
25     const LLVMSymbolizer::Options &Opts) {
26   uint32_t Flags = llvm::DILineInfoSpecifier::FileLineInfo |
27                    llvm::DILineInfoSpecifier::AbsoluteFilePath;
28   if (Opts.PrintFunctions)
29     Flags |= llvm::DILineInfoSpecifier::FunctionName;
30   return Flags;
31 }
32
33 static void patchFunctionNameInDILineInfo(const std::string &NewFunctionName,
34                                           DILineInfo &LineInfo) {
35   std::string FileName = LineInfo.getFileName();
36   LineInfo = DILineInfo(StringRef(FileName), StringRef(NewFunctionName),
37                         LineInfo.getLine(), LineInfo.getColumn());
38 }
39
40 DILineInfo ModuleInfo::symbolizeCode(uint64_t ModuleOffset,
41     const LLVMSymbolizer::Options& Opts) const {
42   DILineInfo LineInfo;
43   if (DebugInfoContext) {
44     LineInfo = DebugInfoContext->getLineInfoForAddress(
45         ModuleOffset, getDILineInfoSpecifierFlags(Opts));
46   }
47   // Override function name from symbol table if necessary.
48   if (Opts.PrintFunctions && Opts.UseSymbolTable) {
49     std::string FunctionName;
50     uint64_t Start, Size;
51     if (getNameFromSymbolTable(SymbolRef::ST_Function,
52                                ModuleOffset, FunctionName, Start, Size)) {
53       patchFunctionNameInDILineInfo(FunctionName, LineInfo);
54     }
55   }
56   return LineInfo;
57 }
58
59 DIInliningInfo ModuleInfo::symbolizeInlinedCode(uint64_t ModuleOffset,
60     const LLVMSymbolizer::Options& Opts) const {
61   DIInliningInfo InlinedContext;
62   if (DebugInfoContext) {
63     InlinedContext = DebugInfoContext->getInliningInfoForAddress(
64         ModuleOffset, getDILineInfoSpecifierFlags(Opts));
65   }
66   // Make sure there is at least one frame in context.
67   if (InlinedContext.getNumberOfFrames() == 0) {
68     InlinedContext.addFrame(DILineInfo());
69   }
70   // Override the function name in lower frame with name from symbol table.
71   if (Opts.PrintFunctions && Opts.UseSymbolTable) {
72     DIInliningInfo PatchedInlinedContext;
73     for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames();
74          i < n; i++) {
75       DILineInfo LineInfo = InlinedContext.getFrame(i);
76       if (i == n - 1) {
77         std::string FunctionName;
78         uint64_t Start, Size;
79         if (getNameFromSymbolTable(SymbolRef::ST_Function,
80                                    ModuleOffset, FunctionName, Start, Size)) {
81           patchFunctionNameInDILineInfo(FunctionName, LineInfo);
82         }
83       }
84       PatchedInlinedContext.addFrame(LineInfo);
85     }
86     InlinedContext = PatchedInlinedContext;
87   }
88   return InlinedContext;
89 }
90
91 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
92                                uint64_t &Start, uint64_t &Size) const {
93   return getNameFromSymbolTable(SymbolRef::ST_Data,
94                                 ModuleOffset, Name, Start, Size);
95 }
96
97 static bool error(error_code ec) {
98   if (!ec) return false;
99   errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
100   return true;
101 }
102
103 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
104                                         std::string &Name, uint64_t &Addr,
105                                         uint64_t &Size) const {
106   assert(Module);
107   error_code ec;
108   for (symbol_iterator si = Module->begin_symbols(),
109                        se = Module->end_symbols();
110                        si != se; si.increment(ec)) {
111     if (error(ec)) return false;
112     uint64_t SymbolAddress;
113     uint64_t SymbolSize;
114     SymbolRef::Type SymbolType;
115     if (error(si->getAddress(SymbolAddress)) ||
116         SymbolAddress == UnknownAddressOrSize) continue;
117     if (error(si->getSize(SymbolSize)) ||
118         SymbolSize == UnknownAddressOrSize) continue;
119     if (error(si->getType(SymbolType))) continue;
120     // FIXME: If a function has alias, there are two entries in symbol table
121     // with same address size. Make sure we choose the correct one.
122     if (SymbolAddress <= Address && Address < SymbolAddress + SymbolSize &&
123         SymbolType == Type) {
124       StringRef SymbolName;
125       if (error(si->getName(SymbolName))) continue;
126       Name = SymbolName.str();
127       Addr = SymbolAddress;
128       Size = SymbolSize;
129       return true;
130     }
131   }
132   return false;
133 }
134
135 const std::string LLVMSymbolizer::kBadString = "??";
136
137 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
138                                           uint64_t ModuleOffset) {
139   ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
140   if (Info == 0)
141     return printDILineInfo(DILineInfo());
142   if (Opts.PrintInlining) {
143     DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
144         ModuleOffset, Opts);
145     uint32_t FramesNum = InlinedContext.getNumberOfFrames();
146     assert(FramesNum > 0);
147     std::string Result;
148     for (uint32_t i = 0; i < FramesNum; i++) {
149       DILineInfo LineInfo = InlinedContext.getFrame(i);
150       Result += printDILineInfo(LineInfo);
151     }
152     return Result;
153   }
154   DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
155   return printDILineInfo(LineInfo);
156 }
157
158 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
159                                           uint64_t ModuleOffset) {
160   std::string Name = kBadString;
161   uint64_t Start = 0;
162   uint64_t Size = 0;
163   if (Opts.UseSymbolTable) {
164     if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
165       if (Info->symbolizeData(ModuleOffset, Name, Start, Size))
166         DemangleName(Name);
167     }
168   }
169   std::stringstream ss;
170   ss << Name << "\n" << Start << " " << Size << "\n";
171   return ss.str();
172 }
173
174 // Returns true if the object endianness is known.
175 static bool getObjectEndianness(const ObjectFile *Obj,
176                                 bool &IsLittleEndian) {
177   // FIXME: Implement this when libLLVMObject allows to do it easily.
178   IsLittleEndian = true;
179   return true;
180 }
181
182 static ObjectFile *getObjectFile(const std::string &Path) {
183   OwningPtr<MemoryBuffer> Buff;
184   MemoryBuffer::getFile(Path, Buff);
185   return ObjectFile::createObjectFile(Buff.take());
186 }
187
188 static std::string getDarwinDWARFResourceForModule(const std::string &Path) {
189   StringRef Basename = sys::path::filename(Path);
190   const std::string &DSymDirectory = Path + ".dSYM";
191   SmallString<16> ResourceName = StringRef(DSymDirectory);
192   sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
193   sys::path::append(ResourceName, Basename);
194   return ResourceName.str();
195 }
196
197 ModuleInfo *LLVMSymbolizer::getOrCreateModuleInfo(
198     const std::string &ModuleName) {
199   ModuleMapTy::iterator I = Modules.find(ModuleName);
200   if (I != Modules.end())
201     return I->second;
202
203   ObjectFile *Obj = getObjectFile(ModuleName);
204   ObjectFile *DbgObj = Obj;
205   if (Obj == 0) {
206     // Module name doesn't point to a valid object file.
207     Modules.insert(make_pair(ModuleName, (ModuleInfo*)0));
208     return 0;
209   }
210
211   DIContext *Context = 0;
212   bool IsLittleEndian;
213   if (getObjectEndianness(Obj, IsLittleEndian)) {
214     // On Darwin we may find DWARF in separate object file in
215     // resource directory.
216     if (isa<MachOObjectFile>(Obj)) {
217       const std::string &ResourceName = getDarwinDWARFResourceForModule(
218           ModuleName);
219       ObjectFile *ResourceObj = getObjectFile(ResourceName);
220       if (ResourceObj != 0)
221         DbgObj = ResourceObj;
222     }
223     Context = DIContext::getDWARFContext(DbgObj);
224     assert(Context);
225   }
226
227   ModuleInfo *Info = new ModuleInfo(Obj, Context);
228   Modules.insert(make_pair(ModuleName, Info));
229   return Info;
230 }
231
232 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
233   // By default, DILineInfo contains "<invalid>" for function/filename it
234   // cannot fetch. We replace it to "??" to make our output closer to addr2line.
235   static const std::string kDILineInfoBadString = "<invalid>";
236   std::stringstream Result;
237   if (Opts.PrintFunctions) {
238     std::string FunctionName = LineInfo.getFunctionName();
239     if (FunctionName == kDILineInfoBadString)
240       FunctionName = kBadString;
241     DemangleName(FunctionName);
242     Result << FunctionName << "\n";
243   }
244   std::string Filename = LineInfo.getFileName();
245   if (Filename == kDILineInfoBadString)
246     Filename = kBadString;
247   Result << Filename << ":" << LineInfo.getLine()
248                      << ":" << LineInfo.getColumn() << "\n";
249   return Result.str();
250 }
251
252 #if !defined(_MSC_VER)
253 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
254 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
255                                 size_t *length, int *status);
256 #endif
257
258 void LLVMSymbolizer::DemangleName(std::string &Name) const {
259 #if !defined(_MSC_VER)
260   if (!Opts.Demangle)
261     return;
262   int status = 0;
263   char *DemangledName = __cxa_demangle(Name.c_str(), 0, 0, &status);
264   if (status != 0)
265     return;
266   Name = DemangledName;
267   free(DemangledName);
268 #endif
269 }
270
271 }  // namespace symbolize
272 }  // namespace llvm