blob: 5a72410decfa7e0e8acead1ec59ca2dba8398a05 [file] [log] [blame]
Alexey Samsonovea83baf2013-01-22 14:21:19 +00001//===-- LLVMSymbolize.cpp -------------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Implementation for LLVM symbolization library.
11//
12//===----------------------------------------------------------------------===//
13
Alexey Samsonov57f88372015-10-26 17:56:12 +000014#include "llvm/DebugInfo/Symbolize/Symbolize.h"
15
Alexey Samsonovdd71c5b2013-03-19 15:33:18 +000016#include "llvm/ADT/STLExtras.h"
Alexey Samsonova591ae62013-08-26 18:12:03 +000017#include "llvm/Config/config.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000018#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Zachary Turner20dbd0d2015-04-27 17:19:51 +000019#include "llvm/DebugInfo/PDB/PDB.h"
20#include "llvm/DebugInfo/PDB/PDBContext.h"
Alexey Samsonova5f07682014-02-26 13:10:01 +000021#include "llvm/Object/ELFObjectFile.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000022#include "llvm/Object/MachO.h"
Rafael Espindolad8e96ec2015-06-25 15:06:38 +000023#include "llvm/Object/SymbolSize.h"
Reid Klecknerc25c7942015-08-10 21:47:11 +000024#include "llvm/Support/COFF.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000025#include "llvm/Support/Casting.h"
Alexey Samsonov3e9997f2013-08-14 17:09:30 +000026#include "llvm/Support/Compression.h"
27#include "llvm/Support/DataExtractor.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000028#include "llvm/Support/Errc.h"
Alexey Samsonov5239d582013-06-04 07:57:38 +000029#include "llvm/Support/FileSystem.h"
Alexey Samsonov3e9997f2013-08-14 17:09:30 +000030#include "llvm/Support/MemoryBuffer.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000031#include "llvm/Support/Path.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000032#include <sstream>
Alexey Samsonova591ae62013-08-26 18:12:03 +000033#include <stdlib.h>
Alexey Samsonovea83baf2013-01-22 14:21:19 +000034
Zachary Turnerc007aa42015-05-06 22:26:30 +000035#if defined(_MSC_VER)
36#include <Windows.h>
37#include <DbgHelp.h>
Leny Kholodovbebb27b2015-07-02 14:34:57 +000038#pragma comment(lib, "dbghelp.lib")
Reid Klecknerc25c7942015-08-10 21:47:11 +000039
40// Windows.h conflicts with our COFF header definitions.
41#ifdef IMAGE_FILE_MACHINE_I386
42#undef IMAGE_FILE_MACHINE_I386
43#endif
Zachary Turnerc007aa42015-05-06 22:26:30 +000044#endif
45
Alexey Samsonovea83baf2013-01-22 14:21:19 +000046namespace llvm {
47namespace symbolize {
48
Alexey Samsonov57f88372015-10-26 17:56:12 +000049// FIXME: Move this to llvm-symbolizer tool.
Rafael Espindola4453e42942014-06-13 03:07:50 +000050static bool error(std::error_code ec) {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +000051 if (!ec)
52 return false;
Dmitry Vyukovef8fb722013-02-14 13:06:18 +000053 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
54 return true;
55}
56
Alexey Samsonovdce67342014-05-15 21:24:32 +000057static DILineInfoSpecifier
Alexey Samsonov0fb64512015-10-26 22:34:56 +000058getDILineInfoSpecifier(FunctionNameKind FNKind) {
Alexey Samsonovdce67342014-05-15 21:24:32 +000059 return DILineInfoSpecifier(
Alexey Samsonov0fb64512015-10-26 22:34:56 +000060 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FNKind);
Alexey Samsonovea83baf2013-01-22 14:21:19 +000061}
62
Alexey Samsonov7a952e52015-10-26 19:41:23 +000063ModuleInfo::ModuleInfo(ObjectFile *Obj, std::unique_ptr<DIContext> DICtx)
64 : Module(Obj), DebugInfoContext(std::move(DICtx)) {
Jay Foad52695da2014-11-07 09:08:39 +000065 std::unique_ptr<DataExtractor> OpdExtractor;
66 uint64_t OpdAddress = 0;
67 // Find the .opd (function descriptor) section if any, for big-endian
68 // PowerPC64 ELF.
69 if (Module->getArch() == Triple::ppc64) {
70 for (section_iterator Section : Module->sections()) {
71 StringRef Name;
72 if (!error(Section->getName(Name)) && Name == ".opd") {
73 StringRef Data;
74 if (!error(Section->getContents(Data))) {
75 OpdExtractor.reset(new DataExtractor(Data, Module->isLittleEndian(),
76 Module->getBytesInAddress()));
77 OpdAddress = Section->getAddress();
78 }
79 break;
80 }
81 }
82 }
Rafael Espindolad8e96ec2015-06-25 15:06:38 +000083 std::vector<std::pair<SymbolRef, uint64_t>> Symbols =
84 computeSymbolSizes(*Module);
85 for (auto &P : Symbols)
86 addSymbol(P.first, P.second, OpdExtractor.get(), OpdAddress);
Reid Kleckner02b74362015-10-16 23:43:22 +000087
88 // If this is a COFF object and we didn't find any symbols, try the export
89 // table.
90 if (Symbols.empty()) {
91 if (auto *CoffObj = dyn_cast<COFFObjectFile>(Obj))
92 addCoffExportSymbols(CoffObj);
93 }
94}
95
Reid Kleckner793d9632015-10-16 23:53:12 +000096namespace {
97struct OffsetNamePair {
98 uint32_t Offset;
99 StringRef Name;
100 bool operator<(const OffsetNamePair &R) const {
101 return Offset < R.Offset;
102 }
103};
104}
105
Reid Kleckner02b74362015-10-16 23:43:22 +0000106void ModuleInfo::addCoffExportSymbols(const COFFObjectFile *CoffObj) {
107 // Get all export names and offsets.
Reid Kleckner02b74362015-10-16 23:43:22 +0000108 std::vector<OffsetNamePair> ExportSyms;
109 for (const ExportDirectoryEntryRef &Ref : CoffObj->export_directories()) {
110 StringRef Name;
111 uint32_t Offset;
112 if (error(Ref.getSymbolName(Name)) || error(Ref.getExportRVA(Offset)))
113 return;
114 ExportSyms.push_back(OffsetNamePair{Offset, Name});
115 }
116 if (ExportSyms.empty())
117 return;
118
119 // Sort by ascending offset.
Reid Kleckner793d9632015-10-16 23:53:12 +0000120 array_pod_sort(ExportSyms.begin(), ExportSyms.end());
Reid Kleckner02b74362015-10-16 23:43:22 +0000121
122 // Approximate the symbol sizes by assuming they run to the next symbol.
123 // FIXME: This assumes all exports are functions.
124 uint64_t ImageBase = CoffObj->getImageBase();
125 for (auto I = ExportSyms.begin(), E = ExportSyms.end(); I != E; ++I) {
126 OffsetNamePair &Export = *I;
127 // FIXME: The last export has a one byte size now.
128 uint32_t NextOffset = I != E ? I->Offset : Export.Offset + 1;
129 uint64_t SymbolStart = ImageBase + Export.Offset;
130 uint64_t SymbolSize = NextOffset - Export.Offset;
131 SymbolDesc SD = {SymbolStart, SymbolSize};
132 Functions.insert(std::make_pair(SD, Export.Name));
133 }
Alexey Samsonova5f07682014-02-26 13:10:01 +0000134}
135
Rafael Espindolad8e96ec2015-06-25 15:06:38 +0000136void ModuleInfo::addSymbol(const SymbolRef &Symbol, uint64_t SymbolSize,
137 DataExtractor *OpdExtractor, uint64_t OpdAddress) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +0000138 SymbolRef::Type SymbolType = Symbol.getType();
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000139 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
Alexey Samsonova5f07682014-02-26 13:10:01 +0000140 return;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000141 ErrorOr<uint64_t> SymbolAddressOrErr = Symbol.getAddress();
142 if (error(SymbolAddressOrErr.getError()))
143 return;
144 uint64_t SymbolAddress = *SymbolAddressOrErr;
Jay Foad52695da2014-11-07 09:08:39 +0000145 if (OpdExtractor) {
146 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
147 // function descriptors. The first word of the descriptor is a pointer to
148 // the function's code.
149 // For the purposes of symbolization, pretend the symbol's address is that
150 // of the function's code, not the descriptor.
151 uint64_t OpdOffset = SymbolAddress - OpdAddress;
152 uint32_t OpdOffset32 = OpdOffset;
153 if (OpdOffset == OpdOffset32 &&
154 OpdExtractor->isValidOffsetForAddress(OpdOffset32))
155 SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
156 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000157 ErrorOr<StringRef> SymbolNameOrErr = Symbol.getName();
158 if (error(SymbolNameOrErr.getError()))
Alexey Samsonova5f07682014-02-26 13:10:01 +0000159 return;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000160 StringRef SymbolName = *SymbolNameOrErr;
Alexey Samsonova5f07682014-02-26 13:10:01 +0000161 // Mach-O symbol table names have leading underscore, skip it.
162 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
163 SymbolName = SymbolName.drop_front();
164 // FIXME: If a function has alias, there are two entries in symbol table
165 // with same address size. Make sure we choose the correct one.
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000166 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
Alexey Samsonova5f07682014-02-26 13:10:01 +0000167 SymbolDesc SD = { SymbolAddress, SymbolSize };
168 M.insert(std::make_pair(SD, SymbolName));
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000169}
170
Reid Klecknerc25c7942015-08-10 21:47:11 +0000171// Return true if this is a 32-bit x86 PE COFF module.
172bool ModuleInfo::isWin32Module() const {
173 auto *CoffObject = dyn_cast<COFFObjectFile>(Module);
174 return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386;
175}
176
Reid Klecknere94fef72015-10-09 00:15:01 +0000177uint64_t ModuleInfo::getModulePreferredBase() const {
178 if (auto *CoffObject = dyn_cast<COFFObjectFile>(Module))
Reid Kleckner21427ad2015-10-09 00:15:08 +0000179 return CoffObject->getImageBase();
Reid Klecknere94fef72015-10-09 00:15:01 +0000180 return 0;
181}
182
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000183bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
184 std::string &Name, uint64_t &Addr,
185 uint64_t &Size) const {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000186 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
187 if (SymbolMap.empty())
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000188 return false;
Alexey Samsonov5239d582013-06-04 07:57:38 +0000189 SymbolDesc SD = { Address, Address };
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000190 auto SymbolIterator = SymbolMap.upper_bound(SD);
191 if (SymbolIterator == SymbolMap.begin())
Alexey Samsonov35c987d2013-06-07 15:25:27 +0000192 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000193 --SymbolIterator;
194 if (SymbolIterator->first.Size != 0 &&
195 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000196 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000197 Name = SymbolIterator->second.str();
198 Addr = SymbolIterator->first.Addr;
199 Size = SymbolIterator->first.Size;
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000200 return true;
201}
202
Alexey Samsonov0fb64512015-10-26 22:34:56 +0000203DILineInfo ModuleInfo::symbolizeCode(uint64_t ModuleOffset,
204 FunctionNameKind FNKind,
205 bool UseSymbolTable) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000206 DILineInfo LineInfo;
207 if (DebugInfoContext) {
208 LineInfo = DebugInfoContext->getLineInfoForAddress(
Alexey Samsonov0fb64512015-10-26 22:34:56 +0000209 ModuleOffset, getDILineInfoSpecifier(FNKind));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000210 }
211 // Override function name from symbol table if necessary.
Alexey Samsonov0fb64512015-10-26 22:34:56 +0000212 if (FNKind == FunctionNameKind::LinkageName && UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000213 std::string FunctionName;
214 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000215 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
216 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000217 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000218 }
219 }
220 return LineInfo;
221}
222
Alexey Samsonov0fb64512015-10-26 22:34:56 +0000223DIInliningInfo ModuleInfo::symbolizeInlinedCode(uint64_t ModuleOffset,
224 FunctionNameKind FNKind,
225 bool UseSymbolTable) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000226 DIInliningInfo InlinedContext;
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000227
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000228 if (DebugInfoContext) {
229 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
Alexey Samsonov0fb64512015-10-26 22:34:56 +0000230 ModuleOffset, getDILineInfoSpecifier(FNKind));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000231 }
232 // Make sure there is at least one frame in context.
233 if (InlinedContext.getNumberOfFrames() == 0) {
234 InlinedContext.addFrame(DILineInfo());
235 }
236 // Override the function name in lower frame with name from symbol table.
Alexey Samsonov0fb64512015-10-26 22:34:56 +0000237 if (FNKind == FunctionNameKind::LinkageName && UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000238 DIInliningInfo PatchedInlinedContext;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000239 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000240 DILineInfo LineInfo = InlinedContext.getFrame(i);
241 if (i == n - 1) {
242 std::string FunctionName;
243 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000244 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
245 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000246 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000247 }
248 }
249 PatchedInlinedContext.addFrame(LineInfo);
250 }
251 InlinedContext = PatchedInlinedContext;
252 }
253 return InlinedContext;
254}
255
256bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
257 uint64_t &Start, uint64_t &Size) const {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000258 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
259 Size);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000260}
261
Alexey Samsonovd6cef102013-02-04 15:55:26 +0000262const char LLVMSymbolizer::kBadString[] = "??";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000263
264std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
265 uint64_t ModuleOffset) {
266 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000267 if (!Info)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000268 return printDILineInfo(DILineInfo(), Info);
Reid Klecknere94fef72015-10-09 00:15:01 +0000269
270 // If the user is giving us relative addresses, add the preferred base of the
271 // object to the offset before we do the query. It's what DIContext expects.
272 if (Opts.RelativeAddresses)
273 ModuleOffset += Info->getModulePreferredBase();
274
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000275 if (Opts.PrintInlining) {
Alexey Samsonov0fb64512015-10-26 22:34:56 +0000276 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
277 ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000278 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
279 assert(FramesNum > 0);
280 std::string Result;
281 for (uint32_t i = 0; i < FramesNum; i++) {
282 DILineInfo LineInfo = InlinedContext.getFrame(i);
Reid Klecknerc25c7942015-08-10 21:47:11 +0000283 Result += printDILineInfo(LineInfo, Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000284 }
285 return Result;
286 }
Alexey Samsonov0fb64512015-10-26 22:34:56 +0000287 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions,
288 Opts.UseSymbolTable);
Reid Klecknerc25c7942015-08-10 21:47:11 +0000289 return printDILineInfo(LineInfo, Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000290}
291
292std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
293 uint64_t ModuleOffset) {
294 std::string Name = kBadString;
295 uint64_t Start = 0;
296 uint64_t Size = 0;
297 if (Opts.UseSymbolTable) {
298 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
Reid Klecknere94fef72015-10-09 00:15:01 +0000299 // If the user is giving us relative addresses, add the preferred base of the
300 // object to the offset before we do the query. It's what DIContext expects.
301 if (Opts.RelativeAddresses)
302 ModuleOffset += Info->getModulePreferredBase();
Alexey Samsonov601beb72013-06-28 12:06:25 +0000303 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000304 Name = DemangleName(Name, Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000305 }
306 }
307 std::stringstream ss;
308 ss << Name << "\n" << Start << " " << Size << "\n";
309 return ss.str();
310}
311
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000312void LLVMSymbolizer::flush() {
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000313 Modules.clear();
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000314 ObjectPairForPathArch.clear();
Alexey Samsonovfe3a5d92013-06-28 15:08:29 +0000315 ObjectFileForArch.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000316}
317
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000318// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
319// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
320// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
321// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
322static
323std::string getDarwinDWARFResourceForPath(
324 const std::string &Path, const std::string &Basename) {
325 SmallString<16> ResourceName = StringRef(Path);
326 if (sys::path::extension(Path) != ".dSYM") {
327 ResourceName += ".dSYM";
328 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000329 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
330 sys::path::append(ResourceName, Basename);
331 return ResourceName.str();
332}
333
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000334static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000335 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
336 MemoryBuffer::getFileOrSTDIN(Path);
337 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000338 return false;
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000339 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000340}
341
342static bool findDebugBinary(const std::string &OrigPath,
343 const std::string &DebuglinkName, uint32_t CRCHash,
344 std::string &Result) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000345 std::string OrigRealPath = OrigPath;
346#if defined(HAVE_REALPATH)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000347 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000348 OrigRealPath = RP;
349 free(RP);
350 }
351#endif
352 SmallString<16> OrigDir(OrigRealPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000353 llvm::sys::path::remove_filename(OrigDir);
354 SmallString<16> DebugPath = OrigDir;
355 // Try /path/to/original_binary/debuglink_name
356 llvm::sys::path::append(DebugPath, DebuglinkName);
357 if (checkFileCRC(DebugPath, CRCHash)) {
358 Result = DebugPath.str();
359 return true;
360 }
361 // Try /path/to/original_binary/.debug/debuglink_name
Alexey Samsonova591ae62013-08-26 18:12:03 +0000362 DebugPath = OrigRealPath;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000363 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
364 if (checkFileCRC(DebugPath, CRCHash)) {
365 Result = DebugPath.str();
366 return true;
367 }
368 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
369 DebugPath = "/usr/lib/debug";
370 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
371 DebuglinkName);
372 if (checkFileCRC(DebugPath, CRCHash)) {
373 Result = DebugPath.str();
374 return true;
375 }
376 return false;
377}
378
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000379static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000380 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000381 if (!Obj)
382 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000383 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000384 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000385 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000386 Name = Name.substr(Name.find_first_not_of("._"));
387 if (Name == "gnu_debuglink") {
388 StringRef Data;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000389 Section.getContents(Data);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000390 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
391 uint32_t Offset = 0;
392 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
393 // 4-byte align the offset.
394 Offset = (Offset + 3) & ~0x3;
395 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
396 DebugName = DebugNameStr;
397 CRCHash = DE.getU32(&Offset);
398 return true;
399 }
400 }
401 break;
402 }
403 }
404 return false;
405}
406
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000407static
408bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
409 const MachOObjectFile *Obj) {
410 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
411 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
412 if (dbg_uuid.empty() || bin_uuid.empty())
413 return false;
414 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
415}
416
417ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
418 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
419 // On Darwin we may find DWARF in separate object file in
420 // resource directory.
421 std::vector<std::string> DsymPaths;
422 StringRef Filename = sys::path::filename(ExePath);
423 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
424 for (const auto &Path : Opts.DsymHints) {
425 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
426 }
427 for (const auto &path : DsymPaths) {
428 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
429 std::error_code EC = BinaryOrErr.getError();
430 if (EC != errc::no_such_file_or_directory && !error(EC)) {
431 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
432 ObjectFile *DbgObj =
Lang Hamesf04de6e2014-10-31 21:37:49 +0000433 getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000434 const MachOObjectFile *MachDbgObj =
435 dyn_cast<const MachOObjectFile>(DbgObj);
436 if (!MachDbgObj) continue;
437 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000438 addOwningBinary(std::move(B));
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000439 return DbgObj;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000440 }
441 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000442 }
443 return nullptr;
444}
445
446LLVMSymbolizer::ObjectPair
447LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
448 const std::string &ArchName) {
449 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
450 if (I != ObjectPairForPathArch.end())
451 return I->second;
452 ObjectFile *Obj = nullptr;
453 ObjectFile *DbgObj = nullptr;
454 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
455 if (!error(BinaryOrErr.getError())) {
456 OwningBinary<Binary> &B = BinaryOrErr.get();
Lang Hamesf04de6e2014-10-31 21:37:49 +0000457 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000458 if (!Obj) {
459 ObjectPair Res = std::make_pair(nullptr, nullptr);
460 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
461 return Res;
462 }
463 addOwningBinary(std::move(B));
464 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
465 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000466 // Try to locate the debug binary using .gnu_debuglink section.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000467 if (!DbgObj) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000468 std::string DebuglinkName;
469 uint32_t CRCHash;
470 std::string DebugBinaryPath;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000471 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
Rafael Espindola63da2952014-01-15 19:37:43 +0000472 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
473 BinaryOrErr = createBinary(DebugBinaryPath);
474 if (!error(BinaryOrErr.getError())) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000475 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
Lang Hamesf04de6e2014-10-31 21:37:49 +0000476 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000477 addOwningBinary(std::move(B));
Rafael Espindola63da2952014-01-15 19:37:43 +0000478 }
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000479 }
480 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000481 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000482 if (!DbgObj)
483 DbgObj = Obj;
484 ObjectPair Res = std::make_pair(Obj, DbgObj);
485 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000486 return Res;
487}
488
489ObjectFile *
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000490LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
491 const std::string &ArchName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000492 if (!Bin)
493 return nullptr;
494 ObjectFile *Res = nullptr;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000495 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000496 const auto &I = ObjectFileForArch.find(
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000497 std::make_pair(UB, ArchName));
498 if (I != ObjectFileForArch.end())
499 return I->second;
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000500 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
Frederic Rissebc162a2015-06-22 21:33:24 +0000501 UB->getObjectForArch(ArchName);
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000502 if (ParsedObj) {
503 Res = ParsedObj.get().get();
504 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000505 }
506 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
507 } else if (Bin->isObject()) {
508 Res = cast<ObjectFile>(Bin);
509 }
510 return Res;
511}
512
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000513ModuleInfo *
514LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000515 const auto &I = Modules.find(ModuleName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000516 if (I != Modules.end())
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000517 return I->second.get();
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000518 std::string BinaryName = ModuleName;
519 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000520 size_t ColonPos = ModuleName.find_last_of(':');
521 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000522 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000523 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000524 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000525 BinaryName = ModuleName.substr(0, ColonPos);
526 ArchName = ArchStr;
527 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000528 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000529 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000530
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000531 if (!Objects.first) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000532 // Failed to find valid object file.
Alexey Samsonovff8a80b2015-10-26 21:20:37 +0000533 Modules.insert(
534 std::make_pair(ModuleName, std::unique_ptr<ModuleInfo>(nullptr)));
Craig Toppere6cb63e2014-04-25 04:24:47 +0000535 return nullptr;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000536 }
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000537 std::unique_ptr<DIContext> Context;
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000538 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
539 // If this is a COFF object, assume it contains PDB debug information. If
540 // we don't find any we will fall back to the DWARF case.
541 std::unique_ptr<IPDBSession> Session;
542 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
543 Objects.first->getFileName(), Session);
Zachary Turnerc007aa42015-05-06 22:26:30 +0000544 if (Error == PDB_ErrorCode::Success) {
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000545 Context.reset(new PDBContext(*CoffObject, std::move(Session)));
Zachary Turnerc007aa42015-05-06 22:26:30 +0000546 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000547 }
548 if (!Context)
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000549 Context.reset(new DWARFContextInMemory(*Objects.second));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000550 assert(Context);
Alexey Samsonov1d3f3272015-10-26 20:12:27 +0000551 auto Info = llvm::make_unique<ModuleInfo>(Objects.first, std::move(Context));
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000552 ModuleInfo *Res = Info.get();
Alexey Samsonovff8a80b2015-10-26 21:20:37 +0000553 Modules.insert(std::make_pair(ModuleName, std::move(Info)));
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000554 return Res;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000555}
556
Reid Klecknerc25c7942015-08-10 21:47:11 +0000557std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo,
558 ModuleInfo *ModInfo) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000559 // By default, DILineInfo contains "<invalid>" for function/filename it
560 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
561 static const std::string kDILineInfoBadString = "<invalid>";
562 std::stringstream Result;
Alexey Samsonovcd014722014-05-17 00:07:48 +0000563 if (Opts.PrintFunctions != FunctionNameKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000564 std::string FunctionName = LineInfo.FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000565 if (FunctionName == kDILineInfoBadString)
566 FunctionName = kBadString;
Alexey Samsonov601beb72013-06-28 12:06:25 +0000567 else if (Opts.Demangle)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000568 FunctionName = DemangleName(FunctionName, ModInfo);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000569 Result << FunctionName << "\n";
570 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000571 std::string Filename = LineInfo.FileName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000572 if (Filename == kDILineInfoBadString)
573 Filename = kBadString;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000574 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000575 return Result.str();
576}
577
Reid Klecknerc25c7942015-08-10 21:47:11 +0000578// Undo these various manglings for Win32 extern "C" functions:
579// cdecl - _foo
580// stdcall - _foo@12
581// fastcall - @foo@12
582// vectorcall - foo@@12
583// These are all different linkage names for 'foo'.
584static StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
585 // Remove any '_' or '@' prefix.
586 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
587 if (Front == '_' || Front == '@')
588 SymbolName = SymbolName.drop_front();
589
590 // Remove any '@[0-9]+' suffix.
591 if (Front != '?') {
592 size_t AtPos = SymbolName.rfind('@');
593 if (AtPos != StringRef::npos &&
594 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
595 [](char C) { return C >= '0' && C <= '9'; })) {
596 SymbolName = SymbolName.substr(0, AtPos);
597 }
598 }
599
600 // Remove any ending '@' for vectorcall.
601 if (SymbolName.endswith("@"))
602 SymbolName = SymbolName.drop_back();
603
604 return SymbolName;
605}
606
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000607#if !defined(_MSC_VER)
608// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
609extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
610 size_t *length, int *status);
611#endif
612
Reid Klecknerc25c7942015-08-10 21:47:11 +0000613std::string LLVMSymbolizer::DemangleName(const std::string &Name,
614 ModuleInfo *ModInfo) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000615#if !defined(_MSC_VER)
Ed Masteef6fed72014-01-16 17:25:12 +0000616 // We can spoil names of symbols with C linkage, so use an heuristic
617 // approach to check if the name should be demangled.
Reid Klecknerc25c7942015-08-10 21:47:11 +0000618 if (Name.substr(0, 2) == "_Z") {
619 int status = 0;
620 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
621 if (status != 0)
622 return Name;
623 std::string Result = DemangledName;
624 free(DemangledName);
625 return Result;
626 }
Alexey Samsonov601beb72013-06-28 12:06:25 +0000627#else
Reid Klecknerc25c7942015-08-10 21:47:11 +0000628 if (!Name.empty() && Name.front() == '?') {
629 // Only do MSVC C++ demangling on symbols starting with '?'.
630 char DemangledName[1024] = {0};
631 DWORD result = ::UnDecorateSymbolName(
632 Name.c_str(), DemangledName, 1023,
633 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
634 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
635 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
636 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
637 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
638 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
639 return (result == 0) ? Name : std::string(DemangledName);
640 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000641#endif
Reid Klecknerc25c7942015-08-10 21:47:11 +0000642 if (ModInfo->isWin32Module())
643 return std::string(demanglePE32ExternCFunc(Name));
644 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000645}
646
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000647} // namespace symbolize
648} // namespace llvm