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 assume that symbol
68 // occupies the memory range up to the following symbol.
69 if (isa<MachOObjectFile>(Obj))
71 else if (error(si->getSize(SymbolSize)) ||
72 SymbolSize == UnknownAddressOrSize)
75 if (error(si->getName(SymbolName)))
77 // FIXME: If a function has alias, there are two entries in symbol table
78 // with same address size. Make sure we choose the correct one.
79 SymbolMapTy &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
80 SymbolDesc SD = { SymbolAddress, SymbolSize };
81 M.insert(std::make_pair(SD, SymbolName));
85 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
86 std::string &Name, uint64_t &Addr,
87 uint64_t &Size) const {
88 const SymbolMapTy &M = Type == SymbolRef::ST_Function ? Functions : Objects;
91 SymbolDesc SD = { Address, Address };
92 SymbolMapTy::const_iterator it = M.upper_bound(SD);
96 if (it->first.Size != 0 && it->first.Addr + it->first.Size <= Address)
98 Name = it->second.str();
99 Addr = it->first.Addr;
100 Size = it->first.Size;
104 DILineInfo ModuleInfo::symbolizeCode(
105 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
107 if (DebugInfoContext) {
108 LineInfo = DebugInfoContext->getLineInfoForAddress(
109 ModuleOffset, getDILineInfoSpecifierFlags(Opts));
111 // Override function name from symbol table if necessary.
112 if (Opts.PrintFunctions && Opts.UseSymbolTable) {
113 std::string FunctionName;
114 uint64_t Start, Size;
115 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
116 FunctionName, Start, Size)) {
117 patchFunctionNameInDILineInfo(FunctionName, LineInfo);
123 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
124 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
125 DIInliningInfo InlinedContext;
126 if (DebugInfoContext) {
127 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
128 ModuleOffset, getDILineInfoSpecifierFlags(Opts));
130 // Make sure there is at least one frame in context.
131 if (InlinedContext.getNumberOfFrames() == 0) {
132 InlinedContext.addFrame(DILineInfo());
134 // Override the function name in lower frame with name from symbol table.
135 if (Opts.PrintFunctions && Opts.UseSymbolTable) {
136 DIInliningInfo PatchedInlinedContext;
137 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
138 DILineInfo LineInfo = InlinedContext.getFrame(i);
140 std::string FunctionName;
141 uint64_t Start, Size;
142 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
143 FunctionName, Start, Size)) {
144 patchFunctionNameInDILineInfo(FunctionName, LineInfo);
147 PatchedInlinedContext.addFrame(LineInfo);
149 InlinedContext = PatchedInlinedContext;
151 return InlinedContext;
154 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
155 uint64_t &Start, uint64_t &Size) const {
156 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
160 const char LLVMSymbolizer::kBadString[] = "??";
162 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
163 uint64_t ModuleOffset) {
164 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
166 return printDILineInfo(DILineInfo());
167 if (Opts.PrintInlining) {
168 DIInliningInfo InlinedContext =
169 Info->symbolizeInlinedCode(ModuleOffset, Opts);
170 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
171 assert(FramesNum > 0);
173 for (uint32_t i = 0; i < FramesNum; i++) {
174 DILineInfo LineInfo = InlinedContext.getFrame(i);
175 Result += printDILineInfo(LineInfo);
179 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
180 return printDILineInfo(LineInfo);
183 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
184 uint64_t ModuleOffset) {
185 std::string Name = kBadString;
188 if (Opts.UseSymbolTable) {
189 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
190 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
191 Name = DemangleName(Name);
194 std::stringstream ss;
195 ss << Name << "\n" << Start << " " << Size << "\n";
199 void LLVMSymbolizer::flush() {
200 DeleteContainerSeconds(Modules);
201 DeleteContainerPointers(ParsedBinariesAndObjects);
204 static std::string getDarwinDWARFResourceForPath(const std::string &Path) {
205 StringRef Basename = sys::path::filename(Path);
206 const std::string &DSymDirectory = Path + ".dSYM";
207 SmallString<16> ResourceName = StringRef(DSymDirectory);
208 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
209 sys::path::append(ResourceName, Basename);
210 return ResourceName.str();
213 LLVMSymbolizer::BinaryPair
214 LLVMSymbolizer::getOrCreateBinary(const std::string &Path) {
215 BinaryMapTy::iterator I = BinaryForPath.find(Path);
216 if (I != BinaryForPath.end())
220 OwningPtr<Binary> ParsedBinary;
221 OwningPtr<Binary> ParsedDbgBinary;
222 if (!error(createBinary(Path, ParsedBinary))) {
223 // Check if it's a universal binary.
224 Bin = ParsedBinary.take();
225 ParsedBinariesAndObjects.push_back(Bin);
226 if (Bin->isMachO() || Bin->isMachOUniversalBinary()) {
227 // On Darwin we may find DWARF in separate object file in
228 // resource directory.
229 const std::string &ResourcePath =
230 getDarwinDWARFResourceForPath(Path);
231 bool ResourceFileExists = false;
232 if (!sys::fs::exists(ResourcePath, ResourceFileExists) &&
233 ResourceFileExists &&
234 !error(createBinary(ResourcePath, ParsedDbgBinary))) {
235 DbgBin = ParsedDbgBinary.take();
236 ParsedBinariesAndObjects.push_back(DbgBin);
242 BinaryPair Res = std::make_pair(Bin, DbgBin);
243 BinaryForPath[Path] = Res;
248 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin, const std::string &ArchName) {
252 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
253 ObjectFileForArchMapTy::iterator I = ObjectFileForArch.find(
254 std::make_pair(UB, ArchName));
255 if (I != ObjectFileForArch.end())
257 OwningPtr<ObjectFile> ParsedObj;
258 if (!UB->getObjectForArch(Triple(ArchName).getArch(), ParsedObj)) {
259 Res = ParsedObj.take();
260 ParsedBinariesAndObjects.push_back(Res);
262 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
263 } else if (Bin->isObject()) {
264 Res = cast<ObjectFile>(Bin);
270 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
271 ModuleMapTy::iterator I = Modules.find(ModuleName);
272 if (I != Modules.end())
274 std::string BinaryName = ModuleName;
275 std::string ArchName = Opts.DefaultArch;
276 size_t ColonPos = ModuleName.find(':');
277 if (ColonPos != std::string::npos) {
278 BinaryName = ModuleName.substr(0, ColonPos);
279 ArchName = ModuleName.substr(ColonPos + 1);
281 BinaryPair Binaries = getOrCreateBinary(BinaryName);
282 ObjectFile *Obj = getObjectFileFromBinary(Binaries.first, ArchName);
283 ObjectFile *DbgObj = getObjectFileFromBinary(Binaries.second, ArchName);
286 // Failed to find valid object file.
287 Modules.insert(make_pair(ModuleName, (ModuleInfo *)0));
290 DIContext *Context = DIContext::getDWARFContext(DbgObj);
292 ModuleInfo *Info = new ModuleInfo(Obj, Context);
293 Modules.insert(make_pair(ModuleName, Info));
297 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
298 // By default, DILineInfo contains "<invalid>" for function/filename it
299 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
300 static const std::string kDILineInfoBadString = "<invalid>";
301 std::stringstream Result;
302 if (Opts.PrintFunctions) {
303 std::string FunctionName = LineInfo.getFunctionName();
304 if (FunctionName == kDILineInfoBadString)
305 FunctionName = kBadString;
306 else if (Opts.Demangle)
307 FunctionName = DemangleName(FunctionName);
308 Result << FunctionName << "\n";
310 std::string Filename = LineInfo.getFileName();
311 if (Filename == kDILineInfoBadString)
312 Filename = kBadString;
313 Result << Filename << ":" << LineInfo.getLine() << ":" << LineInfo.getColumn()
318 #if !defined(_MSC_VER)
319 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
320 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
321 size_t *length, int *status);
324 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
325 #if !defined(_MSC_VER)
327 char *DemangledName = __cxa_demangle(Name.c_str(), 0, 0, &status);
330 std::string Result = DemangledName;
338 } // namespace symbolize