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/Compression.h"
19 #include "llvm/Support/DataExtractor.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include "llvm/Support/Path.h"
29 static bool error(error_code ec) {
32 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
37 getDILineInfoSpecifierFlags(const LLVMSymbolizer::Options &Opts) {
38 uint32_t Flags = llvm::DILineInfoSpecifier::FileLineInfo |
39 llvm::DILineInfoSpecifier::AbsoluteFilePath;
40 if (Opts.PrintFunctions)
41 Flags |= llvm::DILineInfoSpecifier::FunctionName;
45 static void patchFunctionNameInDILineInfo(const std::string &NewFunctionName,
46 DILineInfo &LineInfo) {
47 std::string FileName = LineInfo.getFileName();
48 LineInfo = DILineInfo(StringRef(FileName), StringRef(NewFunctionName),
49 LineInfo.getLine(), LineInfo.getColumn());
52 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
53 : Module(Obj), DebugInfoContext(DICtx) {
55 for (symbol_iterator si = Module->begin_symbols(), se = Module->end_symbols();
56 si != se; si.increment(ec)) {
59 SymbolRef::Type SymbolType;
60 if (error(si->getType(SymbolType)))
62 if (SymbolType != SymbolRef::ST_Function &&
63 SymbolType != SymbolRef::ST_Data)
65 uint64_t SymbolAddress;
66 if (error(si->getAddress(SymbolAddress)) ||
67 SymbolAddress == UnknownAddressOrSize)
70 // Getting symbol size is linear for Mach-O files, so assume that symbol
71 // occupies the memory range up to the following symbol.
72 if (isa<MachOObjectFile>(Obj))
74 else if (error(si->getSize(SymbolSize)) ||
75 SymbolSize == UnknownAddressOrSize)
78 if (error(si->getName(SymbolName)))
80 // Mach-O symbol table names have leading underscore, skip it.
81 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
82 SymbolName = SymbolName.drop_front();
83 // FIXME: If a function has alias, there are two entries in symbol table
84 // with same address size. Make sure we choose the correct one.
85 SymbolMapTy &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
86 SymbolDesc SD = { SymbolAddress, SymbolSize };
87 M.insert(std::make_pair(SD, SymbolName));
91 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
92 std::string &Name, uint64_t &Addr,
93 uint64_t &Size) const {
94 const SymbolMapTy &M = Type == SymbolRef::ST_Function ? Functions : Objects;
97 SymbolDesc SD = { Address, Address };
98 SymbolMapTy::const_iterator it = M.upper_bound(SD);
102 if (it->first.Size != 0 && it->first.Addr + it->first.Size <= Address)
104 Name = it->second.str();
105 Addr = it->first.Addr;
106 Size = it->first.Size;
110 DILineInfo ModuleInfo::symbolizeCode(
111 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
113 if (DebugInfoContext) {
114 LineInfo = DebugInfoContext->getLineInfoForAddress(
115 ModuleOffset, getDILineInfoSpecifierFlags(Opts));
117 // Override function name from symbol table if necessary.
118 if (Opts.PrintFunctions && Opts.UseSymbolTable) {
119 std::string FunctionName;
120 uint64_t Start, Size;
121 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
122 FunctionName, Start, Size)) {
123 patchFunctionNameInDILineInfo(FunctionName, LineInfo);
129 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
130 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
131 DIInliningInfo InlinedContext;
132 if (DebugInfoContext) {
133 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
134 ModuleOffset, getDILineInfoSpecifierFlags(Opts));
136 // Make sure there is at least one frame in context.
137 if (InlinedContext.getNumberOfFrames() == 0) {
138 InlinedContext.addFrame(DILineInfo());
140 // Override the function name in lower frame with name from symbol table.
141 if (Opts.PrintFunctions && Opts.UseSymbolTable) {
142 DIInliningInfo PatchedInlinedContext;
143 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
144 DILineInfo LineInfo = InlinedContext.getFrame(i);
146 std::string FunctionName;
147 uint64_t Start, Size;
148 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
149 FunctionName, Start, Size)) {
150 patchFunctionNameInDILineInfo(FunctionName, LineInfo);
153 PatchedInlinedContext.addFrame(LineInfo);
155 InlinedContext = PatchedInlinedContext;
157 return InlinedContext;
160 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
161 uint64_t &Start, uint64_t &Size) const {
162 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
166 const char LLVMSymbolizer::kBadString[] = "??";
168 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
169 uint64_t ModuleOffset) {
170 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
172 return printDILineInfo(DILineInfo());
173 if (Opts.PrintInlining) {
174 DIInliningInfo InlinedContext =
175 Info->symbolizeInlinedCode(ModuleOffset, Opts);
176 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
177 assert(FramesNum > 0);
179 for (uint32_t i = 0; i < FramesNum; i++) {
180 DILineInfo LineInfo = InlinedContext.getFrame(i);
181 Result += printDILineInfo(LineInfo);
185 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
186 return printDILineInfo(LineInfo);
189 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
190 uint64_t ModuleOffset) {
191 std::string Name = kBadString;
194 if (Opts.UseSymbolTable) {
195 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
196 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
197 Name = DemangleName(Name);
200 std::stringstream ss;
201 ss << Name << "\n" << Start << " " << Size << "\n";
205 void LLVMSymbolizer::flush() {
206 DeleteContainerSeconds(Modules);
207 DeleteContainerPointers(ParsedBinariesAndObjects);
208 BinaryForPath.clear();
209 ObjectFileForArch.clear();
212 static std::string getDarwinDWARFResourceForPath(const std::string &Path) {
213 StringRef Basename = sys::path::filename(Path);
214 const std::string &DSymDirectory = Path + ".dSYM";
215 SmallString<16> ResourceName = StringRef(DSymDirectory);
216 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
217 sys::path::append(ResourceName, Basename);
218 return ResourceName.str();
221 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
222 OwningPtr<MemoryBuffer> MB;
223 if (MemoryBuffer::getFileOrSTDIN(Path, MB))
225 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB->getBuffer());
228 static bool findDebugBinary(const std::string &OrigPath,
229 const std::string &DebuglinkName, uint32_t CRCHash,
230 std::string &Result) {
231 SmallString<16> OrigDir(OrigPath);
232 llvm::sys::path::remove_filename(OrigDir);
233 SmallString<16> DebugPath = OrigDir;
234 // Try /path/to/original_binary/debuglink_name
235 llvm::sys::path::append(DebugPath, DebuglinkName);
236 if (checkFileCRC(DebugPath, CRCHash)) {
237 Result = DebugPath.str();
240 // Try /path/to/original_binary/.debug/debuglink_name
241 DebugPath = OrigPath;
242 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
243 if (checkFileCRC(DebugPath, CRCHash)) {
244 Result = DebugPath.str();
247 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
248 DebugPath = "/usr/lib/debug";
249 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
251 if (checkFileCRC(DebugPath, CRCHash)) {
252 Result = DebugPath.str();
258 static bool getGNUDebuglinkContents(const Binary *Bin, std::string &DebugName,
260 const ObjectFile *Obj = dyn_cast<ObjectFile>(Bin);
264 for (section_iterator I = Obj->begin_sections(), E = Obj->end_sections();
265 I != E; I.increment(EC)) {
268 Name = Name.substr(Name.find_first_not_of("._"));
269 if (Name == "gnu_debuglink") {
271 I->getContents(Data);
272 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
274 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
275 // 4-byte align the offset.
276 Offset = (Offset + 3) & ~0x3;
277 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
278 DebugName = DebugNameStr;
279 CRCHash = DE.getU32(&Offset);
289 LLVMSymbolizer::BinaryPair
290 LLVMSymbolizer::getOrCreateBinary(const std::string &Path) {
291 BinaryMapTy::iterator I = BinaryForPath.find(Path);
292 if (I != BinaryForPath.end())
296 OwningPtr<Binary> ParsedBinary;
297 OwningPtr<Binary> ParsedDbgBinary;
298 if (!error(createBinary(Path, ParsedBinary))) {
299 // Check if it's a universal binary.
300 Bin = ParsedBinary.take();
301 ParsedBinariesAndObjects.push_back(Bin);
302 if (Bin->isMachO() || Bin->isMachOUniversalBinary()) {
303 // On Darwin we may find DWARF in separate object file in
304 // resource directory.
305 const std::string &ResourcePath =
306 getDarwinDWARFResourceForPath(Path);
307 bool ResourceFileExists = false;
308 if (!sys::fs::exists(ResourcePath, ResourceFileExists) &&
309 ResourceFileExists &&
310 !error(createBinary(ResourcePath, ParsedDbgBinary))) {
311 DbgBin = ParsedDbgBinary.take();
312 ParsedBinariesAndObjects.push_back(DbgBin);
315 // Try to locate the debug binary using .gnu_debuglink section.
317 std::string DebuglinkName;
319 std::string DebugBinaryPath;
320 if (getGNUDebuglinkContents(Bin, DebuglinkName, CRCHash) &&
321 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath) &&
322 !error(createBinary(DebugBinaryPath, ParsedDbgBinary))) {
323 DbgBin = ParsedDbgBinary.take();
324 ParsedBinariesAndObjects.push_back(DbgBin);
330 BinaryPair Res = std::make_pair(Bin, DbgBin);
331 BinaryForPath[Path] = Res;
336 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin, const std::string &ArchName) {
340 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
341 ObjectFileForArchMapTy::iterator I = ObjectFileForArch.find(
342 std::make_pair(UB, ArchName));
343 if (I != ObjectFileForArch.end())
345 OwningPtr<ObjectFile> ParsedObj;
346 if (!UB->getObjectForArch(Triple(ArchName).getArch(), ParsedObj)) {
347 Res = ParsedObj.take();
348 ParsedBinariesAndObjects.push_back(Res);
350 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
351 } else if (Bin->isObject()) {
352 Res = cast<ObjectFile>(Bin);
358 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
359 ModuleMapTy::iterator I = Modules.find(ModuleName);
360 if (I != Modules.end())
362 std::string BinaryName = ModuleName;
363 std::string ArchName = Opts.DefaultArch;
364 size_t ColonPos = ModuleName.find_last_of(':');
365 // Verify that substring after colon form a valid arch name.
366 if (ColonPos != std::string::npos) {
367 std::string ArchStr = ModuleName.substr(ColonPos + 1);
368 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
369 BinaryName = ModuleName.substr(0, ColonPos);
373 BinaryPair Binaries = getOrCreateBinary(BinaryName);
374 ObjectFile *Obj = getObjectFileFromBinary(Binaries.first, ArchName);
375 ObjectFile *DbgObj = getObjectFileFromBinary(Binaries.second, ArchName);
378 // Failed to find valid object file.
379 Modules.insert(make_pair(ModuleName, (ModuleInfo *)0));
382 DIContext *Context = DIContext::getDWARFContext(DbgObj);
384 ModuleInfo *Info = new ModuleInfo(Obj, Context);
385 Modules.insert(make_pair(ModuleName, Info));
389 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
390 // By default, DILineInfo contains "<invalid>" for function/filename it
391 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
392 static const std::string kDILineInfoBadString = "<invalid>";
393 std::stringstream Result;
394 if (Opts.PrintFunctions) {
395 std::string FunctionName = LineInfo.getFunctionName();
396 if (FunctionName == kDILineInfoBadString)
397 FunctionName = kBadString;
398 else if (Opts.Demangle)
399 FunctionName = DemangleName(FunctionName);
400 Result << FunctionName << "\n";
402 std::string Filename = LineInfo.getFileName();
403 if (Filename == kDILineInfoBadString)
404 Filename = kBadString;
405 Result << Filename << ":" << LineInfo.getLine() << ":" << LineInfo.getColumn()
410 #if !defined(_MSC_VER)
411 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
412 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
413 size_t *length, int *status);
416 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
417 #if !defined(_MSC_VER)
419 char *DemangledName = __cxa_demangle(Name.c_str(), 0, 0, &status);
422 std::string Result = DemangledName;
430 } // namespace symbolize