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