1 //===-- LLVMSymbolize.cpp -------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implementation for LLVM symbolization library.
12 //===----------------------------------------------------------------------===//
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"
26 static bool error(error_code ec) {
29 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
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;
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());
49 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
50 : Module(Obj), DebugInfoContext(DICtx) {
52 for (symbol_iterator si = Module->begin_symbols(), se = Module->end_symbols();
53 si != se; si.increment(ec)) {
56 SymbolRef::Type SymbolType;
57 if (error(si->getType(SymbolType)))
59 if (SymbolType != SymbolRef::ST_Function &&
60 SymbolType != SymbolRef::ST_Data)
62 uint64_t SymbolAddress;
63 if (error(si->getAddress(SymbolAddress)) ||
64 SymbolAddress == UnknownAddressOrSize)
67 // Getting symbol size is linear for Mach-O files, so avoid it.
68 if (isa<MachOObjectFile>(Obj))
70 else if (error(si->getSize(SymbolSize)) ||
71 SymbolSize == UnknownAddressOrSize)
74 if (error(si->getName(SymbolName)))
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));
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;
90 SymbolDesc SD = { Address, Address };
91 SymbolMapTy::const_iterator it = M.upper_bound(SD);
93 // Assume that symbols with zero size are large enough.
94 if (it->first.Addr < it->first.AddrEnd &&
95 it->first.AddrEnd <= Address)
97 Name = it->second.str();
98 Addr = it->first.Addr;
99 Size = it->first.AddrEnd - it->first.Addr;
103 DILineInfo ModuleInfo::symbolizeCode(
104 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
106 if (DebugInfoContext) {
107 LineInfo = DebugInfoContext->getLineInfoForAddress(
108 ModuleOffset, getDILineInfoSpecifierFlags(Opts));
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);
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));
129 // Make sure there is at least one frame in context.
130 if (InlinedContext.getNumberOfFrames() == 0) {
131 InlinedContext.addFrame(DILineInfo());
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);
139 std::string FunctionName;
140 uint64_t Start, Size;
141 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
142 FunctionName, Start, Size)) {
143 patchFunctionNameInDILineInfo(FunctionName, LineInfo);
146 PatchedInlinedContext.addFrame(LineInfo);
148 InlinedContext = PatchedInlinedContext;
150 return InlinedContext;
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,
159 const char LLVMSymbolizer::kBadString[] = "??";
161 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
162 uint64_t ModuleOffset) {
163 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
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);
172 for (uint32_t i = 0; i < FramesNum; i++) {
173 DILineInfo LineInfo = InlinedContext.getFrame(i);
174 Result += printDILineInfo(LineInfo);
178 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
179 return printDILineInfo(LineInfo);
182 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
183 uint64_t ModuleOffset) {
184 std::string Name = kBadString;
187 if (Opts.UseSymbolTable) {
188 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
189 if (Info->symbolizeData(ModuleOffset, Name, Start, Size))
193 std::stringstream ss;
194 ss << Name << "\n" << Start << " " << Size << "\n";
198 void LLVMSymbolizer::flush() {
199 DeleteContainerSeconds(Modules);
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;
209 static ObjectFile *getObjectFile(const std::string &Path) {
210 OwningPtr<MemoryBuffer> Buff;
211 if (error(MemoryBuffer::getFile(Path, Buff)))
213 return ObjectFile::createObjectFile(Buff.take());
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();
226 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
227 ModuleMapTy::iterator I = Modules.find(ModuleName);
228 if (I != Modules.end())
231 ObjectFile *Obj = getObjectFile(ModuleName);
233 // Module name doesn't point to a valid object file.
234 Modules.insert(make_pair(ModuleName, (ModuleInfo *)0));
238 DIContext *Context = 0;
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;
254 Context = DIContext::getDWARFContext(DbgObj);
258 ModuleInfo *Info = new ModuleInfo(Obj, Context);
259 Modules.insert(make_pair(ModuleName, Info));
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";
275 std::string Filename = LineInfo.getFileName();
276 if (Filename == kDILineInfoBadString)
277 Filename = kBadString;
278 Result << Filename << ":" << LineInfo.getLine() << ":" << LineInfo.getColumn()
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);
289 void LLVMSymbolizer::DemangleName(std::string &Name) const {
290 #if !defined(_MSC_VER)
294 char *DemangledName = __cxa_demangle(Name.c_str(), 0, 0, &status);
297 Name = DemangledName;
302 } // namespace symbolize