blob: 996520b84301b78c37a9cea19369c7923185ed18 [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
14#include "LLVMSymbolize.h"
Alexey Samsonovdd71c5b2013-03-19 15:33:18 +000015#include "llvm/ADT/STLExtras.h"
Alexey Samsonova591ae62013-08-26 18:12:03 +000016#include "llvm/Config/config.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000017#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Zachary Turner20dbd0d2015-04-27 17:19:51 +000018#include "llvm/DebugInfo/PDB/PDB.h"
19#include "llvm/DebugInfo/PDB/PDBContext.h"
Alexey Samsonova5f07682014-02-26 13:10:01 +000020#include "llvm/Object/ELFObjectFile.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000021#include "llvm/Object/MachO.h"
Rafael Espindolad8e96ec2015-06-25 15:06:38 +000022#include "llvm/Object/SymbolSize.h"
Reid Klecknerc25c7942015-08-10 21:47:11 +000023#include "llvm/Support/COFF.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000024#include "llvm/Support/Casting.h"
Alexey Samsonov3e9997f2013-08-14 17:09:30 +000025#include "llvm/Support/Compression.h"
26#include "llvm/Support/DataExtractor.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000027#include "llvm/Support/Errc.h"
Alexey Samsonov5239d582013-06-04 07:57:38 +000028#include "llvm/Support/FileSystem.h"
Alexey Samsonov3e9997f2013-08-14 17:09:30 +000029#include "llvm/Support/MemoryBuffer.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000030#include "llvm/Support/Path.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000031#include <sstream>
Alexey Samsonova591ae62013-08-26 18:12:03 +000032#include <stdlib.h>
Alexey Samsonovea83baf2013-01-22 14:21:19 +000033
Zachary Turnerc007aa42015-05-06 22:26:30 +000034#if defined(_MSC_VER)
35#include <Windows.h>
36#include <DbgHelp.h>
Leny Kholodovbebb27b2015-07-02 14:34:57 +000037#pragma comment(lib, "dbghelp.lib")
Reid Klecknerc25c7942015-08-10 21:47:11 +000038
39// Windows.h conflicts with our COFF header definitions.
40#ifdef IMAGE_FILE_MACHINE_I386
41#undef IMAGE_FILE_MACHINE_I386
42#endif
Zachary Turnerc007aa42015-05-06 22:26:30 +000043#endif
44
Alexey Samsonovea83baf2013-01-22 14:21:19 +000045namespace llvm {
46namespace symbolize {
47
Rafael Espindola4453e42942014-06-13 03:07:50 +000048static bool error(std::error_code ec) {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +000049 if (!ec)
50 return false;
Dmitry Vyukovef8fb722013-02-14 13:06:18 +000051 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
52 return true;
53}
54
Alexey Samsonovdce67342014-05-15 21:24:32 +000055static DILineInfoSpecifier
56getDILineInfoSpecifier(const LLVMSymbolizer::Options &Opts) {
57 return DILineInfoSpecifier(
58 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
Alexey Samsonovcd014722014-05-17 00:07:48 +000059 Opts.PrintFunctions);
Alexey Samsonovea83baf2013-01-22 14:21:19 +000060}
61
Dmitry Vyukovef8fb722013-02-14 13:06:18 +000062ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +000063 : Module(Obj), DebugInfoContext(DICtx) {
Jay Foad52695da2014-11-07 09:08:39 +000064 std::unique_ptr<DataExtractor> OpdExtractor;
65 uint64_t OpdAddress = 0;
66 // Find the .opd (function descriptor) section if any, for big-endian
67 // PowerPC64 ELF.
68 if (Module->getArch() == Triple::ppc64) {
69 for (section_iterator Section : Module->sections()) {
70 StringRef Name;
71 if (!error(Section->getName(Name)) && Name == ".opd") {
72 StringRef Data;
73 if (!error(Section->getContents(Data))) {
74 OpdExtractor.reset(new DataExtractor(Data, Module->isLittleEndian(),
75 Module->getBytesInAddress()));
76 OpdAddress = Section->getAddress();
77 }
78 break;
79 }
80 }
81 }
Rafael Espindolad8e96ec2015-06-25 15:06:38 +000082 std::vector<std::pair<SymbolRef, uint64_t>> Symbols =
83 computeSymbolSizes(*Module);
84 for (auto &P : Symbols)
85 addSymbol(P.first, P.second, OpdExtractor.get(), OpdAddress);
Alexey Samsonova5f07682014-02-26 13:10:01 +000086}
87
Rafael Espindolad8e96ec2015-06-25 15:06:38 +000088void ModuleInfo::addSymbol(const SymbolRef &Symbol, uint64_t SymbolSize,
89 DataExtractor *OpdExtractor, uint64_t OpdAddress) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +000090 SymbolRef::Type SymbolType = Symbol.getType();
Alexey Samsonov464d2e42014-03-17 07:28:19 +000091 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
Alexey Samsonova5f07682014-02-26 13:10:01 +000092 return;
Rafael Espindolaed067c42015-07-03 18:19:00 +000093 ErrorOr<uint64_t> SymbolAddressOrErr = Symbol.getAddress();
94 if (error(SymbolAddressOrErr.getError()))
95 return;
96 uint64_t SymbolAddress = *SymbolAddressOrErr;
Jay Foad52695da2014-11-07 09:08:39 +000097 if (OpdExtractor) {
98 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
99 // function descriptors. The first word of the descriptor is a pointer to
100 // the function's code.
101 // For the purposes of symbolization, pretend the symbol's address is that
102 // of the function's code, not the descriptor.
103 uint64_t OpdOffset = SymbolAddress - OpdAddress;
104 uint32_t OpdOffset32 = OpdOffset;
105 if (OpdOffset == OpdOffset32 &&
106 OpdExtractor->isValidOffsetForAddress(OpdOffset32))
107 SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
108 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000109 ErrorOr<StringRef> SymbolNameOrErr = Symbol.getName();
110 if (error(SymbolNameOrErr.getError()))
Alexey Samsonova5f07682014-02-26 13:10:01 +0000111 return;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000112 StringRef SymbolName = *SymbolNameOrErr;
Alexey Samsonova5f07682014-02-26 13:10:01 +0000113 // Mach-O symbol table names have leading underscore, skip it.
114 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
115 SymbolName = SymbolName.drop_front();
116 // FIXME: If a function has alias, there are two entries in symbol table
117 // with same address size. Make sure we choose the correct one.
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000118 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
Alexey Samsonova5f07682014-02-26 13:10:01 +0000119 SymbolDesc SD = { SymbolAddress, SymbolSize };
120 M.insert(std::make_pair(SD, SymbolName));
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000121}
122
Reid Klecknerc25c7942015-08-10 21:47:11 +0000123// Return true if this is a 32-bit x86 PE COFF module.
124bool ModuleInfo::isWin32Module() const {
125 auto *CoffObject = dyn_cast<COFFObjectFile>(Module);
126 return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386;
127}
128
Reid Klecknere94fef72015-10-09 00:15:01 +0000129uint64_t ModuleInfo::getModulePreferredBase() const {
130 if (auto *CoffObject = dyn_cast<COFFObjectFile>(Module))
Reid Kleckner21427ad2015-10-09 00:15:08 +0000131 return CoffObject->getImageBase();
Reid Klecknere94fef72015-10-09 00:15:01 +0000132 return 0;
133}
134
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000135bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
136 std::string &Name, uint64_t &Addr,
137 uint64_t &Size) const {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000138 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
139 if (SymbolMap.empty())
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000140 return false;
Alexey Samsonov5239d582013-06-04 07:57:38 +0000141 SymbolDesc SD = { Address, Address };
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000142 auto SymbolIterator = SymbolMap.upper_bound(SD);
143 if (SymbolIterator == SymbolMap.begin())
Alexey Samsonov35c987d2013-06-07 15:25:27 +0000144 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000145 --SymbolIterator;
146 if (SymbolIterator->first.Size != 0 &&
147 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000148 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000149 Name = SymbolIterator->second.str();
150 Addr = SymbolIterator->first.Addr;
151 Size = SymbolIterator->first.Size;
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000152 return true;
153}
154
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000155DILineInfo ModuleInfo::symbolizeCode(
156 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000157 DILineInfo LineInfo;
158 if (DebugInfoContext) {
159 LineInfo = DebugInfoContext->getLineInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000160 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000161 }
162 // Override function name from symbol table if necessary.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000163 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000164 std::string FunctionName;
165 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000166 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
167 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000168 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000169 }
170 }
171 return LineInfo;
172}
173
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000174DIInliningInfo ModuleInfo::symbolizeInlinedCode(
175 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000176 DIInliningInfo InlinedContext;
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000177
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000178 if (DebugInfoContext) {
179 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000180 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000181 }
182 // Make sure there is at least one frame in context.
183 if (InlinedContext.getNumberOfFrames() == 0) {
184 InlinedContext.addFrame(DILineInfo());
185 }
186 // Override the function name in lower frame with name from symbol table.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000187 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000188 DIInliningInfo PatchedInlinedContext;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000189 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000190 DILineInfo LineInfo = InlinedContext.getFrame(i);
191 if (i == n - 1) {
192 std::string FunctionName;
193 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000194 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
195 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000196 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000197 }
198 }
199 PatchedInlinedContext.addFrame(LineInfo);
200 }
201 InlinedContext = PatchedInlinedContext;
202 }
203 return InlinedContext;
204}
205
206bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
207 uint64_t &Start, uint64_t &Size) const {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000208 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
209 Size);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000210}
211
Alexey Samsonovd6cef102013-02-04 15:55:26 +0000212const char LLVMSymbolizer::kBadString[] = "??";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000213
214std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
215 uint64_t ModuleOffset) {
216 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000217 if (!Info)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000218 return printDILineInfo(DILineInfo(), Info);
Reid Klecknere94fef72015-10-09 00:15:01 +0000219
220 // If the user is giving us relative addresses, add the preferred base of the
221 // object to the offset before we do the query. It's what DIContext expects.
222 if (Opts.RelativeAddresses)
223 ModuleOffset += Info->getModulePreferredBase();
224
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000225 if (Opts.PrintInlining) {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000226 DIInliningInfo InlinedContext =
227 Info->symbolizeInlinedCode(ModuleOffset, Opts);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000228 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
229 assert(FramesNum > 0);
230 std::string Result;
231 for (uint32_t i = 0; i < FramesNum; i++) {
232 DILineInfo LineInfo = InlinedContext.getFrame(i);
Reid Klecknerc25c7942015-08-10 21:47:11 +0000233 Result += printDILineInfo(LineInfo, Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000234 }
235 return Result;
236 }
237 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
Reid Klecknerc25c7942015-08-10 21:47:11 +0000238 return printDILineInfo(LineInfo, Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000239}
240
241std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
242 uint64_t ModuleOffset) {
243 std::string Name = kBadString;
244 uint64_t Start = 0;
245 uint64_t Size = 0;
246 if (Opts.UseSymbolTable) {
247 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
Reid Klecknere94fef72015-10-09 00:15:01 +0000248 // If the user is giving us relative addresses, add the preferred base of the
249 // object to the offset before we do the query. It's what DIContext expects.
250 if (Opts.RelativeAddresses)
251 ModuleOffset += Info->getModulePreferredBase();
Alexey Samsonov601beb72013-06-28 12:06:25 +0000252 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000253 Name = DemangleName(Name, Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000254 }
255 }
256 std::stringstream ss;
257 ss << Name << "\n" << Start << " " << Size << "\n";
258 return ss.str();
259}
260
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000261void LLVMSymbolizer::flush() {
Alexey Samsonovdd71c5b2013-03-19 15:33:18 +0000262 DeleteContainerSeconds(Modules);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000263 ObjectPairForPathArch.clear();
Alexey Samsonovfe3a5d92013-06-28 15:08:29 +0000264 ObjectFileForArch.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000265}
266
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000267// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
268// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
269// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
270// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
271static
272std::string getDarwinDWARFResourceForPath(
273 const std::string &Path, const std::string &Basename) {
274 SmallString<16> ResourceName = StringRef(Path);
275 if (sys::path::extension(Path) != ".dSYM") {
276 ResourceName += ".dSYM";
277 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000278 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
279 sys::path::append(ResourceName, Basename);
280 return ResourceName.str();
281}
282
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000283static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000284 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
285 MemoryBuffer::getFileOrSTDIN(Path);
286 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000287 return false;
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000288 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000289}
290
291static bool findDebugBinary(const std::string &OrigPath,
292 const std::string &DebuglinkName, uint32_t CRCHash,
293 std::string &Result) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000294 std::string OrigRealPath = OrigPath;
295#if defined(HAVE_REALPATH)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000296 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000297 OrigRealPath = RP;
298 free(RP);
299 }
300#endif
301 SmallString<16> OrigDir(OrigRealPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000302 llvm::sys::path::remove_filename(OrigDir);
303 SmallString<16> DebugPath = OrigDir;
304 // Try /path/to/original_binary/debuglink_name
305 llvm::sys::path::append(DebugPath, DebuglinkName);
306 if (checkFileCRC(DebugPath, CRCHash)) {
307 Result = DebugPath.str();
308 return true;
309 }
310 // Try /path/to/original_binary/.debug/debuglink_name
Alexey Samsonova591ae62013-08-26 18:12:03 +0000311 DebugPath = OrigRealPath;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000312 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
313 if (checkFileCRC(DebugPath, CRCHash)) {
314 Result = DebugPath.str();
315 return true;
316 }
317 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
318 DebugPath = "/usr/lib/debug";
319 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
320 DebuglinkName);
321 if (checkFileCRC(DebugPath, CRCHash)) {
322 Result = DebugPath.str();
323 return true;
324 }
325 return false;
326}
327
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000328static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000329 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000330 if (!Obj)
331 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000332 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000333 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000334 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000335 Name = Name.substr(Name.find_first_not_of("._"));
336 if (Name == "gnu_debuglink") {
337 StringRef Data;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000338 Section.getContents(Data);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000339 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
340 uint32_t Offset = 0;
341 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
342 // 4-byte align the offset.
343 Offset = (Offset + 3) & ~0x3;
344 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
345 DebugName = DebugNameStr;
346 CRCHash = DE.getU32(&Offset);
347 return true;
348 }
349 }
350 break;
351 }
352 }
353 return false;
354}
355
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000356static
357bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
358 const MachOObjectFile *Obj) {
359 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
360 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
361 if (dbg_uuid.empty() || bin_uuid.empty())
362 return false;
363 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
364}
365
366ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
367 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
368 // On Darwin we may find DWARF in separate object file in
369 // resource directory.
370 std::vector<std::string> DsymPaths;
371 StringRef Filename = sys::path::filename(ExePath);
372 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
373 for (const auto &Path : Opts.DsymHints) {
374 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
375 }
376 for (const auto &path : DsymPaths) {
377 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
378 std::error_code EC = BinaryOrErr.getError();
379 if (EC != errc::no_such_file_or_directory && !error(EC)) {
380 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
381 ObjectFile *DbgObj =
Lang Hamesf04de6e2014-10-31 21:37:49 +0000382 getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000383 const MachOObjectFile *MachDbgObj =
384 dyn_cast<const MachOObjectFile>(DbgObj);
385 if (!MachDbgObj) continue;
386 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000387 addOwningBinary(std::move(B));
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000388 return DbgObj;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000389 }
390 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000391 }
392 return nullptr;
393}
394
395LLVMSymbolizer::ObjectPair
396LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
397 const std::string &ArchName) {
398 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
399 if (I != ObjectPairForPathArch.end())
400 return I->second;
401 ObjectFile *Obj = nullptr;
402 ObjectFile *DbgObj = nullptr;
403 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
404 if (!error(BinaryOrErr.getError())) {
405 OwningBinary<Binary> &B = BinaryOrErr.get();
Lang Hamesf04de6e2014-10-31 21:37:49 +0000406 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000407 if (!Obj) {
408 ObjectPair Res = std::make_pair(nullptr, nullptr);
409 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
410 return Res;
411 }
412 addOwningBinary(std::move(B));
413 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
414 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000415 // Try to locate the debug binary using .gnu_debuglink section.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000416 if (!DbgObj) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000417 std::string DebuglinkName;
418 uint32_t CRCHash;
419 std::string DebugBinaryPath;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000420 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
Rafael Espindola63da2952014-01-15 19:37:43 +0000421 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
422 BinaryOrErr = createBinary(DebugBinaryPath);
423 if (!error(BinaryOrErr.getError())) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000424 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
Lang Hamesf04de6e2014-10-31 21:37:49 +0000425 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000426 addOwningBinary(std::move(B));
Rafael Espindola63da2952014-01-15 19:37:43 +0000427 }
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000428 }
429 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000430 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000431 if (!DbgObj)
432 DbgObj = Obj;
433 ObjectPair Res = std::make_pair(Obj, DbgObj);
434 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000435 return Res;
436}
437
438ObjectFile *
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000439LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
440 const std::string &ArchName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000441 if (!Bin)
442 return nullptr;
443 ObjectFile *Res = nullptr;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000444 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000445 const auto &I = ObjectFileForArch.find(
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000446 std::make_pair(UB, ArchName));
447 if (I != ObjectFileForArch.end())
448 return I->second;
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000449 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
Frederic Rissebc162a2015-06-22 21:33:24 +0000450 UB->getObjectForArch(ArchName);
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000451 if (ParsedObj) {
452 Res = ParsedObj.get().get();
453 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000454 }
455 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
456 } else if (Bin->isObject()) {
457 Res = cast<ObjectFile>(Bin);
458 }
459 return Res;
460}
461
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000462ModuleInfo *
463LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000464 const auto &I = Modules.find(ModuleName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000465 if (I != Modules.end())
466 return I->second;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000467 std::string BinaryName = ModuleName;
468 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000469 size_t ColonPos = ModuleName.find_last_of(':');
470 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000471 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000472 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000473 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000474 BinaryName = ModuleName.substr(0, ColonPos);
475 ArchName = ArchStr;
476 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000477 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000478 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000479
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000480 if (!Objects.first) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000481 // Failed to find valid object file.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000482 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
483 return nullptr;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000484 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000485 DIContext *Context = nullptr;
486 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
487 // If this is a COFF object, assume it contains PDB debug information. If
488 // we don't find any we will fall back to the DWARF case.
489 std::unique_ptr<IPDBSession> Session;
490 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
491 Objects.first->getFileName(), Session);
Zachary Turnerc007aa42015-05-06 22:26:30 +0000492 if (Error == PDB_ErrorCode::Success) {
Reid Klecknere94fef72015-10-09 00:15:01 +0000493 Context = new PDBContext(*CoffObject, std::move(Session));
Zachary Turnerc007aa42015-05-06 22:26:30 +0000494 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000495 }
496 if (!Context)
497 Context = new DWARFContextInMemory(*Objects.second);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000498 assert(Context);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000499 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000500 Modules.insert(make_pair(ModuleName, Info));
501 return Info;
502}
503
Reid Klecknerc25c7942015-08-10 21:47:11 +0000504std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo,
505 ModuleInfo *ModInfo) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000506 // By default, DILineInfo contains "<invalid>" for function/filename it
507 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
508 static const std::string kDILineInfoBadString = "<invalid>";
509 std::stringstream Result;
Alexey Samsonovcd014722014-05-17 00:07:48 +0000510 if (Opts.PrintFunctions != FunctionNameKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000511 std::string FunctionName = LineInfo.FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000512 if (FunctionName == kDILineInfoBadString)
513 FunctionName = kBadString;
Alexey Samsonov601beb72013-06-28 12:06:25 +0000514 else if (Opts.Demangle)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000515 FunctionName = DemangleName(FunctionName, ModInfo);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000516 Result << FunctionName << "\n";
517 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000518 std::string Filename = LineInfo.FileName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000519 if (Filename == kDILineInfoBadString)
520 Filename = kBadString;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000521 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000522 return Result.str();
523}
524
Reid Klecknerc25c7942015-08-10 21:47:11 +0000525// Undo these various manglings for Win32 extern "C" functions:
526// cdecl - _foo
527// stdcall - _foo@12
528// fastcall - @foo@12
529// vectorcall - foo@@12
530// These are all different linkage names for 'foo'.
531static StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
532 // Remove any '_' or '@' prefix.
533 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
534 if (Front == '_' || Front == '@')
535 SymbolName = SymbolName.drop_front();
536
537 // Remove any '@[0-9]+' suffix.
538 if (Front != '?') {
539 size_t AtPos = SymbolName.rfind('@');
540 if (AtPos != StringRef::npos &&
541 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
542 [](char C) { return C >= '0' && C <= '9'; })) {
543 SymbolName = SymbolName.substr(0, AtPos);
544 }
545 }
546
547 // Remove any ending '@' for vectorcall.
548 if (SymbolName.endswith("@"))
549 SymbolName = SymbolName.drop_back();
550
551 return SymbolName;
552}
553
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000554#if !defined(_MSC_VER)
555// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
556extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
557 size_t *length, int *status);
558#endif
559
Reid Klecknerc25c7942015-08-10 21:47:11 +0000560std::string LLVMSymbolizer::DemangleName(const std::string &Name,
561 ModuleInfo *ModInfo) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000562#if !defined(_MSC_VER)
Ed Masteef6fed72014-01-16 17:25:12 +0000563 // We can spoil names of symbols with C linkage, so use an heuristic
564 // approach to check if the name should be demangled.
Reid Klecknerc25c7942015-08-10 21:47:11 +0000565 if (Name.substr(0, 2) == "_Z") {
566 int status = 0;
567 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
568 if (status != 0)
569 return Name;
570 std::string Result = DemangledName;
571 free(DemangledName);
572 return Result;
573 }
Alexey Samsonov601beb72013-06-28 12:06:25 +0000574#else
Reid Klecknerc25c7942015-08-10 21:47:11 +0000575 if (!Name.empty() && Name.front() == '?') {
576 // Only do MSVC C++ demangling on symbols starting with '?'.
577 char DemangledName[1024] = {0};
578 DWORD result = ::UnDecorateSymbolName(
579 Name.c_str(), DemangledName, 1023,
580 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
581 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
582 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
583 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
584 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
585 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
586 return (result == 0) ? Name : std::string(DemangledName);
587 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000588#endif
Reid Klecknerc25c7942015-08-10 21:47:11 +0000589 if (ModInfo->isWin32Module())
590 return std::string(demanglePE32ExternCFunc(Name));
591 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000592}
593
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000594} // namespace symbolize
595} // namespace llvm