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/ELFObjectFile.h"
18 #include "llvm/Object/MachO.h"
19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/Compression.h"
21 #include "llvm/Support/DataExtractor.h"
22 #include "llvm/Support/Errc.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/Path.h"
32 static bool error(std::error_code ec) {
35 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
39 static DILineInfoSpecifier
40 getDILineInfoSpecifier(const LLVMSymbolizer::Options &Opts) {
41 return DILineInfoSpecifier(
42 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
46 ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
47 : Module(Obj), DebugInfoContext(DICtx) {
48 for (const SymbolRef &Symbol : Module->symbols()) {
51 bool NoSymbolTable = (Module->symbol_begin() == Module->symbol_end());
52 if (NoSymbolTable && Module->isELF()) {
53 // Fallback to dynamic symbol table, if regular symbol table is stripped.
54 std::pair<symbol_iterator, symbol_iterator> IDyn =
55 getELFDynamicSymbolIterators(Module);
56 for (symbol_iterator si = IDyn.first, se = IDyn.second; si != se; ++si) {
62 void ModuleInfo::addSymbol(const SymbolRef &Symbol) {
63 SymbolRef::Type SymbolType;
64 if (error(Symbol.getType(SymbolType)))
66 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
68 uint64_t SymbolAddress;
69 if (error(Symbol.getAddress(SymbolAddress)) ||
70 SymbolAddress == UnknownAddressOrSize)
73 // Getting symbol size is linear for Mach-O files, so assume that symbol
74 // occupies the memory range up to the following symbol.
75 if (isa<MachOObjectFile>(Module))
77 else if (error(Symbol.getSize(SymbolSize)) ||
78 SymbolSize == UnknownAddressOrSize)
81 if (error(Symbol.getName(SymbolName)))
83 // Mach-O symbol table names have leading underscore, skip it.
84 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
85 SymbolName = SymbolName.drop_front();
86 // FIXME: If a function has alias, there are two entries in symbol table
87 // with same address size. Make sure we choose the correct one.
88 SymbolMapTy &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
89 SymbolDesc SD = { SymbolAddress, SymbolSize };
90 M.insert(std::make_pair(SD, SymbolName));
93 bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
94 std::string &Name, uint64_t &Addr,
95 uint64_t &Size) const {
96 const SymbolMapTy &M = Type == SymbolRef::ST_Function ? Functions : Objects;
99 SymbolDesc SD = { Address, Address };
100 SymbolMapTy::const_iterator it = M.upper_bound(SD);
104 if (it->first.Size != 0 && it->first.Addr + it->first.Size <= Address)
106 Name = it->second.str();
107 Addr = it->first.Addr;
108 Size = it->first.Size;
112 DILineInfo ModuleInfo::symbolizeCode(
113 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
115 if (DebugInfoContext) {
116 LineInfo = DebugInfoContext->getLineInfoForAddress(
117 ModuleOffset, getDILineInfoSpecifier(Opts));
119 // Override function name from symbol table if necessary.
120 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
121 std::string FunctionName;
122 uint64_t Start, Size;
123 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
124 FunctionName, Start, Size)) {
125 LineInfo.FunctionName = FunctionName;
131 DIInliningInfo ModuleInfo::symbolizeInlinedCode(
132 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
133 DIInliningInfo InlinedContext;
134 if (DebugInfoContext) {
135 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
136 ModuleOffset, getDILineInfoSpecifier(Opts));
138 // Make sure there is at least one frame in context.
139 if (InlinedContext.getNumberOfFrames() == 0) {
140 InlinedContext.addFrame(DILineInfo());
142 // Override the function name in lower frame with name from symbol table.
143 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
144 DIInliningInfo PatchedInlinedContext;
145 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
146 DILineInfo LineInfo = InlinedContext.getFrame(i);
148 std::string FunctionName;
149 uint64_t Start, Size;
150 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
151 FunctionName, Start, Size)) {
152 LineInfo.FunctionName = FunctionName;
155 PatchedInlinedContext.addFrame(LineInfo);
157 InlinedContext = PatchedInlinedContext;
159 return InlinedContext;
162 bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
163 uint64_t &Start, uint64_t &Size) const {
164 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
168 const char LLVMSymbolizer::kBadString[] = "??";
170 std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
171 uint64_t ModuleOffset) {
172 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
174 return printDILineInfo(DILineInfo());
175 if (Opts.PrintInlining) {
176 DIInliningInfo InlinedContext =
177 Info->symbolizeInlinedCode(ModuleOffset, Opts);
178 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
179 assert(FramesNum > 0);
181 for (uint32_t i = 0; i < FramesNum; i++) {
182 DILineInfo LineInfo = InlinedContext.getFrame(i);
183 Result += printDILineInfo(LineInfo);
187 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
188 return printDILineInfo(LineInfo);
191 std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
192 uint64_t ModuleOffset) {
193 std::string Name = kBadString;
196 if (Opts.UseSymbolTable) {
197 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
198 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
199 Name = DemangleName(Name);
202 std::stringstream ss;
203 ss << Name << "\n" << Start << " " << Size << "\n";
207 void LLVMSymbolizer::flush() {
208 DeleteContainerSeconds(Modules);
209 BinaryForPath.clear();
210 ObjectFileForArch.clear();
213 static std::string getDarwinDWARFResourceForPath(const std::string &Path) {
214 StringRef Basename = sys::path::filename(Path);
215 const std::string &DSymDirectory = Path + ".dSYM";
216 SmallString<16> ResourceName = StringRef(DSymDirectory);
217 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
218 sys::path::append(ResourceName, Basename);
219 return ResourceName.str();
222 static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
223 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
224 MemoryBuffer::getFileOrSTDIN(Path);
227 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
230 static bool findDebugBinary(const std::string &OrigPath,
231 const std::string &DebuglinkName, uint32_t CRCHash,
232 std::string &Result) {
233 std::string OrigRealPath = OrigPath;
234 #if defined(HAVE_REALPATH)
235 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
240 SmallString<16> OrigDir(OrigRealPath);
241 llvm::sys::path::remove_filename(OrigDir);
242 SmallString<16> DebugPath = OrigDir;
243 // Try /path/to/original_binary/debuglink_name
244 llvm::sys::path::append(DebugPath, DebuglinkName);
245 if (checkFileCRC(DebugPath, CRCHash)) {
246 Result = DebugPath.str();
249 // Try /path/to/original_binary/.debug/debuglink_name
250 DebugPath = OrigRealPath;
251 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
252 if (checkFileCRC(DebugPath, CRCHash)) {
253 Result = DebugPath.str();
256 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
257 DebugPath = "/usr/lib/debug";
258 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
260 if (checkFileCRC(DebugPath, CRCHash)) {
261 Result = DebugPath.str();
267 static bool getGNUDebuglinkContents(const Binary *Bin, std::string &DebugName,
269 const ObjectFile *Obj = dyn_cast<ObjectFile>(Bin);
272 for (const SectionRef &Section : Obj->sections()) {
274 Section.getName(Name);
275 Name = Name.substr(Name.find_first_not_of("._"));
276 if (Name == "gnu_debuglink") {
278 Section.getContents(Data);
279 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
281 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
282 // 4-byte align the offset.
283 Offset = (Offset + 3) & ~0x3;
284 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
285 DebugName = DebugNameStr;
286 CRCHash = DE.getU32(&Offset);
296 LLVMSymbolizer::BinaryPair
297 LLVMSymbolizer::getOrCreateBinary(const std::string &Path) {
298 BinaryMapTy::iterator I = BinaryForPath.find(Path);
299 if (I != BinaryForPath.end())
301 Binary *Bin = nullptr;
302 Binary *DbgBin = nullptr;
303 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
304 if (!error(BinaryOrErr.getError())) {
305 OwningBinary<Binary> &ParsedBinary = BinaryOrErr.get();
306 // Check if it's a universal binary.
307 Bin = ParsedBinary.getBinary().get();
308 addOwningBinary(std::move(ParsedBinary));
309 if (Bin->isMachO() || Bin->isMachOUniversalBinary()) {
310 // On Darwin we may find DWARF in separate object file in
311 // resource directory.
312 const std::string &ResourcePath =
313 getDarwinDWARFResourceForPath(Path);
314 BinaryOrErr = createBinary(ResourcePath);
315 std::error_code EC = BinaryOrErr.getError();
316 if (EC != errc::no_such_file_or_directory && !error(EC)) {
317 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
318 DbgBin = B.getBinary().get();
319 addOwningBinary(std::move(B));
322 // Try to locate the debug binary using .gnu_debuglink section.
324 std::string DebuglinkName;
326 std::string DebugBinaryPath;
327 if (getGNUDebuglinkContents(Bin, DebuglinkName, CRCHash) &&
328 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
329 BinaryOrErr = createBinary(DebugBinaryPath);
330 if (!error(BinaryOrErr.getError())) {
331 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
332 DbgBin = B.getBinary().get();
333 addOwningBinary(std::move(B));
340 BinaryPair Res = std::make_pair(Bin, DbgBin);
341 BinaryForPath[Path] = Res;
346 LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin, const std::string &ArchName) {
349 ObjectFile *Res = nullptr;
350 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
351 ObjectFileForArchMapTy::iterator I = ObjectFileForArch.find(
352 std::make_pair(UB, ArchName));
353 if (I != ObjectFileForArch.end())
355 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
356 UB->getObjectForArch(Triple(ArchName).getArch());
358 Res = ParsedObj.get().get();
359 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
361 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
362 } else if (Bin->isObject()) {
363 Res = cast<ObjectFile>(Bin);
369 LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
370 ModuleMapTy::iterator I = Modules.find(ModuleName);
371 if (I != Modules.end())
373 std::string BinaryName = ModuleName;
374 std::string ArchName = Opts.DefaultArch;
375 size_t ColonPos = ModuleName.find_last_of(':');
376 // Verify that substring after colon form a valid arch name.
377 if (ColonPos != std::string::npos) {
378 std::string ArchStr = ModuleName.substr(ColonPos + 1);
379 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
380 BinaryName = ModuleName.substr(0, ColonPos);
384 BinaryPair Binaries = getOrCreateBinary(BinaryName);
385 ObjectFile *Obj = getObjectFileFromBinary(Binaries.first, ArchName);
386 ObjectFile *DbgObj = getObjectFileFromBinary(Binaries.second, ArchName);
389 // Failed to find valid object file.
390 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
393 DIContext *Context = DIContext::getDWARFContext(*DbgObj);
395 ModuleInfo *Info = new ModuleInfo(Obj, Context);
396 Modules.insert(make_pair(ModuleName, Info));
400 std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
401 // By default, DILineInfo contains "<invalid>" for function/filename it
402 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
403 static const std::string kDILineInfoBadString = "<invalid>";
404 std::stringstream Result;
405 if (Opts.PrintFunctions != FunctionNameKind::None) {
406 std::string FunctionName = LineInfo.FunctionName;
407 if (FunctionName == kDILineInfoBadString)
408 FunctionName = kBadString;
409 else if (Opts.Demangle)
410 FunctionName = DemangleName(FunctionName);
411 Result << FunctionName << "\n";
413 std::string Filename = LineInfo.FileName;
414 if (Filename == kDILineInfoBadString)
415 Filename = kBadString;
416 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
420 #if !defined(_MSC_VER)
421 // Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
422 extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
423 size_t *length, int *status);
426 std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
427 #if !defined(_MSC_VER)
428 // We can spoil names of symbols with C linkage, so use an heuristic
429 // approach to check if the name should be demangled.
430 if (Name.substr(0, 2) != "_Z")
433 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
436 std::string Result = DemangledName;
444 } // namespace symbolize