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/Config/config.h"
17 #include "llvm/Object/MachO.h"
18 #include "llvm/Support/Casting.h"
19 #include "llvm/Support/Compression.h"
20 #include "llvm/Support/DataExtractor.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/Path.h"
30 static bool error(error_code ec) {
33 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
38 getDILineInfoSpecifierFlags(const LLVMSymbolizer::Options &Opts) {
39 uint32_t Flags = llvm::DILineInfoSpecifier::FileLineInfo |
40 llvm::DILineInfoSpecifier::AbsoluteFilePath;
41 if (Opts.PrintFunctions)
42 Flags |= llvm::DILineInfoSpecifier::FunctionName;
46 static void patchFunctionNameInDILineInfo(const std::string &NewFunctionName,
47 DILineInfo &LineInfo) {
48 std::string FileName = LineInfo.getFileName();
49 LineInfo = DILineInfo(StringRef(FileName), StringRef(NewFunctionName),
50 LineInfo.getLine(), LineInfo.getColumn());
53 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
54 : Module(Obj), DebugInfoContext(DICtx) {
55 for (symbol_iterator si = Module->begin_symbols(), se = Module->end_symbols();
57 SymbolRef::Type SymbolType;
58 if (error(si->getType(SymbolType)))
60 if (SymbolType != SymbolRef::ST_Function &&
61 SymbolType != SymbolRef::ST_Data)
63 uint64_t SymbolAddress;
64 if (error(si->getAddress(SymbolAddress)) ||
65 SymbolAddress == UnknownAddressOrSize)
68 // Getting symbol size is linear for Mach-O files, so assume that symbol
69 // occupies the memory range up to the following symbol.
70 if (isa<MachOObjectFile>(Obj))
72 else if (error(si->getSize(SymbolSize)) ||
73 SymbolSize == UnknownAddressOrSize)
76 if (error(si->getName(SymbolName)))
78 // Mach-O symbol table names have leading underscore, skip it.
79 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
80 SymbolName = SymbolName.drop_front();
81 // FIXME: If a function has alias, there are two entries in symbol table
82 // with same address size. Make sure we choose the correct one.
83 SymbolMapTy &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
84 SymbolDesc SD = { SymbolAddress, SymbolSize };
85 M.insert(std::make_pair(SD, SymbolName));
89 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
90 std::string &Name, uint64_t &Addr,
91 uint64_t &Size) const {
92 const SymbolMapTy &M = Type == SymbolRef::ST_Function ? Functions : Objects;
95 SymbolDesc SD = { Address, Address };
96 SymbolMapTy::const_iterator it = M.upper_bound(SD);
100 if (it->first.Size != 0 && it->first.Addr + it->first.Size <= Address)
102 Name = it->second.str();
103 Addr = it->first.Addr;
104 Size = it->first.Size;
108 DILineInfo ModuleInfo::symbolizeCode(
109 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
111 if (DebugInfoContext) {
112 LineInfo = DebugInfoContext->getLineInfoForAddress(
113 ModuleOffset, getDILineInfoSpecifierFlags(Opts));
115 // Override function name from symbol table if necessary.
116 if (Opts.PrintFunctions && Opts.UseSymbolTable) {
117 std::string FunctionName;
118 uint64_t Start, Size;
119 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
120 FunctionName, Start, Size)) {
121 patchFunctionNameInDILineInfo(FunctionName, LineInfo);
127 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
128 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
129 DIInliningInfo InlinedContext;
130 if (DebugInfoContext) {
131 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
132 ModuleOffset, getDILineInfoSpecifierFlags(Opts));
134 // Make sure there is at least one frame in context.
135 if (InlinedContext.getNumberOfFrames() == 0) {
136 InlinedContext.addFrame(DILineInfo());
138 // Override the function name in lower frame with name from symbol table.
139 if (Opts.PrintFunctions && Opts.UseSymbolTable) {
140 DIInliningInfo PatchedInlinedContext;
141 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
142 DILineInfo LineInfo = InlinedContext.getFrame(i);
144 std::string FunctionName;
145 uint64_t Start, Size;
146 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
147 FunctionName, Start, Size)) {
148 patchFunctionNameInDILineInfo(FunctionName, LineInfo);
151 PatchedInlinedContext.addFrame(LineInfo);
153 InlinedContext = PatchedInlinedContext;
155 return InlinedContext;
158 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
159 uint64_t &Start, uint64_t &Size) const {
160 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
164 const char LLVMSymbolizer::kBadString[] = "??";
166 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
167 uint64_t ModuleOffset) {
168 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
170 return printDILineInfo(DILineInfo());
171 if (Opts.PrintInlining) {
172 DIInliningInfo InlinedContext =
173 Info->symbolizeInlinedCode(ModuleOffset, Opts);
174 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
175 assert(FramesNum > 0);
177 for (uint32_t i = 0; i < FramesNum; i++) {
178 DILineInfo LineInfo = InlinedContext.getFrame(i);
179 Result += printDILineInfo(LineInfo);
183 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
184 return printDILineInfo(LineInfo);
187 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
188 uint64_t ModuleOffset) {
189 std::string Name = kBadString;
192 if (Opts.UseSymbolTable) {
193 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
194 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
195 Name = DemangleName(Name);
198 std::stringstream ss;
199 ss << Name << "\n" << Start << " " << Size << "\n";
203 void LLVMSymbolizer::flush() {
204 DeleteContainerSeconds(Modules);
205 DeleteContainerPointers(ParsedBinariesAndObjects);
206 BinaryForPath.clear();
207 ObjectFileForArch.clear();
210 static std::string getDarwinDWARFResourceForPath(const std::string &Path) {
211 StringRef Basename = sys::path::filename(Path);
212 const std::string &DSymDirectory = Path + ".dSYM";
213 SmallString<16> ResourceName = StringRef(DSymDirectory);
214 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
215 sys::path::append(ResourceName, Basename);
216 return ResourceName.str();
219 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
220 OwningPtr<MemoryBuffer> MB;
221 if (MemoryBuffer::getFileOrSTDIN(Path, MB))
223 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB->getBuffer());
226 static bool findDebugBinary(const std::string &OrigPath,
227 const std::string &DebuglinkName, uint32_t CRCHash,
228 std::string &Result) {
229 std::string OrigRealPath = OrigPath;
230 #if defined(HAVE_REALPATH)
231 if (char *RP = realpath(OrigPath.c_str(), NULL)) {
236 SmallString<16> OrigDir(OrigRealPath);
237 llvm::sys::path::remove_filename(OrigDir);
238 SmallString<16> DebugPath = OrigDir;
239 // Try /path/to/original_binary/debuglink_name
240 llvm::sys::path::append(DebugPath, DebuglinkName);
241 if (checkFileCRC(DebugPath, CRCHash)) {
242 Result = DebugPath.str();
245 // Try /path/to/original_binary/.debug/debuglink_name
246 DebugPath = OrigRealPath;
247 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
248 if (checkFileCRC(DebugPath, CRCHash)) {
249 Result = DebugPath.str();
252 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
253 DebugPath = "/usr/lib/debug";
254 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
256 if (checkFileCRC(DebugPath, CRCHash)) {
257 Result = DebugPath.str();
263 static bool getGNUDebuglinkContents(const Binary *Bin, std::string &DebugName,
265 const ObjectFile *Obj = dyn_cast<ObjectFile>(Bin);
268 for (section_iterator I = Obj->begin_sections(), E = Obj->end_sections();
272 Name = Name.substr(Name.find_first_not_of("._"));
273 if (Name == "gnu_debuglink") {
275 I->getContents(Data);
276 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
278 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
279 // 4-byte align the offset.
280 Offset = (Offset + 3) & ~0x3;
281 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
282 DebugName = DebugNameStr;
283 CRCHash = DE.getU32(&Offset);
293 LLVMSymbolizer::BinaryPair
294 LLVMSymbolizer::getOrCreateBinary(const std::string &Path) {
295 BinaryMapTy::iterator I = BinaryForPath.find(Path);
296 if (I != BinaryForPath.end())
300 ErrorOr<Binary *> BinaryOrErr = createBinary(Path);
301 if (!error(BinaryOrErr.getError())) {
302 OwningPtr<Binary> ParsedBinary(BinaryOrErr.get());
303 // Check if it's a universal binary.
304 Bin = ParsedBinary.take();
305 ParsedBinariesAndObjects.push_back(Bin);
306 if (Bin->isMachO() || Bin->isMachOUniversalBinary()) {
307 // On Darwin we may find DWARF in separate object file in
308 // resource directory.
309 const std::string &ResourcePath =
310 getDarwinDWARFResourceForPath(Path);
311 BinaryOrErr = createBinary(ResourcePath);
312 error_code EC = BinaryOrErr.getError();
313 if (EC != errc::no_such_file_or_directory && !error(EC)) {
314 DbgBin = BinaryOrErr.get();
315 ParsedBinariesAndObjects.push_back(DbgBin);
318 // Try to locate the debug binary using .gnu_debuglink section.
320 std::string DebuglinkName;
322 std::string DebugBinaryPath;
323 if (getGNUDebuglinkContents(Bin, DebuglinkName, CRCHash) &&
324 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
325 BinaryOrErr = createBinary(DebugBinaryPath);
326 if (!error(BinaryOrErr.getError())) {
327 DbgBin = BinaryOrErr.get();
328 ParsedBinariesAndObjects.push_back(DbgBin);
335 BinaryPair Res = std::make_pair(Bin, DbgBin);
336 BinaryForPath[Path] = Res;
341 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin, const std::string &ArchName) {
345 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
346 ObjectFileForArchMapTy::iterator I = ObjectFileForArch.find(
347 std::make_pair(UB, ArchName));
348 if (I != ObjectFileForArch.end())
350 OwningPtr<ObjectFile> ParsedObj;
351 if (!UB->getObjectForArch(Triple(ArchName).getArch(), ParsedObj)) {
352 Res = ParsedObj.take();
353 ParsedBinariesAndObjects.push_back(Res);
355 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
356 } else if (Bin->isObject()) {
357 Res = cast<ObjectFile>(Bin);
363 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
364 ModuleMapTy::iterator I = Modules.find(ModuleName);
365 if (I != Modules.end())
367 std::string BinaryName = ModuleName;
368 std::string ArchName = Opts.DefaultArch;
369 size_t ColonPos = ModuleName.find_last_of(':');
370 // Verify that substring after colon form a valid arch name.
371 if (ColonPos != std::string::npos) {
372 std::string ArchStr = ModuleName.substr(ColonPos + 1);
373 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
374 BinaryName = ModuleName.substr(0, ColonPos);
378 BinaryPair Binaries = getOrCreateBinary(BinaryName);
379 ObjectFile *Obj = getObjectFileFromBinary(Binaries.first, ArchName);
380 ObjectFile *DbgObj = getObjectFileFromBinary(Binaries.second, ArchName);
383 // Failed to find valid object file.
384 Modules.insert(make_pair(ModuleName, (ModuleInfo *)0));
387 DIContext *Context = DIContext::getDWARFContext(DbgObj);
389 ModuleInfo *Info = new ModuleInfo(Obj, Context);
390 Modules.insert(make_pair(ModuleName, Info));
394 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
395 // By default, DILineInfo contains "<invalid>" for function/filename it
396 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
397 static const std::string kDILineInfoBadString = "<invalid>";
398 std::stringstream Result;
399 if (Opts.PrintFunctions) {
400 std::string FunctionName = LineInfo.getFunctionName();
401 if (FunctionName == kDILineInfoBadString)
402 FunctionName = kBadString;
403 else if (Opts.Demangle)
404 FunctionName = DemangleName(FunctionName);
405 Result << FunctionName << "\n";
407 std::string Filename = LineInfo.getFileName();
408 if (Filename == kDILineInfoBadString)
409 Filename = kBadString;
410 Result << Filename << ":" << LineInfo.getLine() << ":" << LineInfo.getColumn()
415 #if !defined(_MSC_VER)
416 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
417 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
418 size_t *length, int *status);
421 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
422 #if !defined(_MSC_VER)
423 // We can spoil names of symbols with C linkage, so use an heuristic
424 // approach to check if the name should be demangled.
425 if (Name.substr(0, 2) != "_Z")
428 char *DemangledName = __cxa_demangle(Name.c_str(), 0, 0, &status);
431 std::string Result = DemangledName;
439 } // namespace symbolize