blob: 497207ed4caae6769bbe30f8f2b914b248a86c9d [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
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000129bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
130 std::string &Name, uint64_t &Addr,
131 uint64_t &Size) const {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000132 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
133 if (SymbolMap.empty())
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000134 return false;
Alexey Samsonov5239d582013-06-04 07:57:38 +0000135 SymbolDesc SD = { Address, Address };
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000136 auto SymbolIterator = SymbolMap.upper_bound(SD);
137 if (SymbolIterator == SymbolMap.begin())
Alexey Samsonov35c987d2013-06-07 15:25:27 +0000138 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000139 --SymbolIterator;
140 if (SymbolIterator->first.Size != 0 &&
141 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000142 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000143 Name = SymbolIterator->second.str();
144 Addr = SymbolIterator->first.Addr;
145 Size = SymbolIterator->first.Size;
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000146 return true;
147}
148
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000149DILineInfo ModuleInfo::symbolizeCode(
150 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000151 DILineInfo LineInfo;
152 if (DebugInfoContext) {
153 LineInfo = DebugInfoContext->getLineInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000154 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000155 }
156 // Override function name from symbol table if necessary.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000157 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000158 std::string FunctionName;
159 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000160 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
161 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000162 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000163 }
164 }
165 return LineInfo;
166}
167
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000168DIInliningInfo ModuleInfo::symbolizeInlinedCode(
169 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000170 DIInliningInfo InlinedContext;
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000171
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000172 if (DebugInfoContext) {
173 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000174 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000175 }
176 // Make sure there is at least one frame in context.
177 if (InlinedContext.getNumberOfFrames() == 0) {
178 InlinedContext.addFrame(DILineInfo());
179 }
180 // Override the function name in lower frame with name from symbol table.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000181 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000182 DIInliningInfo PatchedInlinedContext;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000183 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000184 DILineInfo LineInfo = InlinedContext.getFrame(i);
185 if (i == n - 1) {
186 std::string FunctionName;
187 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000188 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
189 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000190 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000191 }
192 }
193 PatchedInlinedContext.addFrame(LineInfo);
194 }
195 InlinedContext = PatchedInlinedContext;
196 }
197 return InlinedContext;
198}
199
200bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
201 uint64_t &Start, uint64_t &Size) const {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000202 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
203 Size);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000204}
205
Alexey Samsonovd6cef102013-02-04 15:55:26 +0000206const char LLVMSymbolizer::kBadString[] = "??";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000207
208std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
209 uint64_t ModuleOffset) {
210 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000211 if (!Info)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000212 return printDILineInfo(DILineInfo(), Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000213 if (Opts.PrintInlining) {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000214 DIInliningInfo InlinedContext =
215 Info->symbolizeInlinedCode(ModuleOffset, Opts);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000216 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
217 assert(FramesNum > 0);
218 std::string Result;
219 for (uint32_t i = 0; i < FramesNum; i++) {
220 DILineInfo LineInfo = InlinedContext.getFrame(i);
Reid Klecknerc25c7942015-08-10 21:47:11 +0000221 Result += printDILineInfo(LineInfo, Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000222 }
223 return Result;
224 }
225 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
Reid Klecknerc25c7942015-08-10 21:47:11 +0000226 return printDILineInfo(LineInfo, Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000227}
228
229std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
230 uint64_t ModuleOffset) {
231 std::string Name = kBadString;
232 uint64_t Start = 0;
233 uint64_t Size = 0;
234 if (Opts.UseSymbolTable) {
235 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
Alexey Samsonov601beb72013-06-28 12:06:25 +0000236 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000237 Name = DemangleName(Name, Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000238 }
239 }
240 std::stringstream ss;
241 ss << Name << "\n" << Start << " " << Size << "\n";
242 return ss.str();
243}
244
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000245void LLVMSymbolizer::flush() {
Alexey Samsonovdd71c5b2013-03-19 15:33:18 +0000246 DeleteContainerSeconds(Modules);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000247 ObjectPairForPathArch.clear();
Alexey Samsonovfe3a5d92013-06-28 15:08:29 +0000248 ObjectFileForArch.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000249}
250
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000251// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
252// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
253// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
254// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
255static
256std::string getDarwinDWARFResourceForPath(
257 const std::string &Path, const std::string &Basename) {
258 SmallString<16> ResourceName = StringRef(Path);
259 if (sys::path::extension(Path) != ".dSYM") {
260 ResourceName += ".dSYM";
261 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000262 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
263 sys::path::append(ResourceName, Basename);
264 return ResourceName.str();
265}
266
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000267static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000268 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
269 MemoryBuffer::getFileOrSTDIN(Path);
270 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000271 return false;
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000272 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000273}
274
275static bool findDebugBinary(const std::string &OrigPath,
276 const std::string &DebuglinkName, uint32_t CRCHash,
277 std::string &Result) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000278 std::string OrigRealPath = OrigPath;
279#if defined(HAVE_REALPATH)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000280 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000281 OrigRealPath = RP;
282 free(RP);
283 }
284#endif
285 SmallString<16> OrigDir(OrigRealPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000286 llvm::sys::path::remove_filename(OrigDir);
287 SmallString<16> DebugPath = OrigDir;
288 // Try /path/to/original_binary/debuglink_name
289 llvm::sys::path::append(DebugPath, DebuglinkName);
290 if (checkFileCRC(DebugPath, CRCHash)) {
291 Result = DebugPath.str();
292 return true;
293 }
294 // Try /path/to/original_binary/.debug/debuglink_name
Alexey Samsonova591ae62013-08-26 18:12:03 +0000295 DebugPath = OrigRealPath;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000296 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
297 if (checkFileCRC(DebugPath, CRCHash)) {
298 Result = DebugPath.str();
299 return true;
300 }
301 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
302 DebugPath = "/usr/lib/debug";
303 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
304 DebuglinkName);
305 if (checkFileCRC(DebugPath, CRCHash)) {
306 Result = DebugPath.str();
307 return true;
308 }
309 return false;
310}
311
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000312static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000313 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000314 if (!Obj)
315 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000316 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000317 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000318 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000319 Name = Name.substr(Name.find_first_not_of("._"));
320 if (Name == "gnu_debuglink") {
321 StringRef Data;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000322 Section.getContents(Data);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000323 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
324 uint32_t Offset = 0;
325 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
326 // 4-byte align the offset.
327 Offset = (Offset + 3) & ~0x3;
328 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
329 DebugName = DebugNameStr;
330 CRCHash = DE.getU32(&Offset);
331 return true;
332 }
333 }
334 break;
335 }
336 }
337 return false;
338}
339
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000340static
341bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
342 const MachOObjectFile *Obj) {
343 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
344 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
345 if (dbg_uuid.empty() || bin_uuid.empty())
346 return false;
347 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
348}
349
350ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
351 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
352 // On Darwin we may find DWARF in separate object file in
353 // resource directory.
354 std::vector<std::string> DsymPaths;
355 StringRef Filename = sys::path::filename(ExePath);
356 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
357 for (const auto &Path : Opts.DsymHints) {
358 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
359 }
360 for (const auto &path : DsymPaths) {
361 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
362 std::error_code EC = BinaryOrErr.getError();
363 if (EC != errc::no_such_file_or_directory && !error(EC)) {
364 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
365 ObjectFile *DbgObj =
Lang Hamesf04de6e2014-10-31 21:37:49 +0000366 getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000367 const MachOObjectFile *MachDbgObj =
368 dyn_cast<const MachOObjectFile>(DbgObj);
369 if (!MachDbgObj) continue;
370 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000371 addOwningBinary(std::move(B));
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000372 return DbgObj;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000373 }
374 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000375 }
376 return nullptr;
377}
378
379LLVMSymbolizer::ObjectPair
380LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
381 const std::string &ArchName) {
382 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
383 if (I != ObjectPairForPathArch.end())
384 return I->second;
385 ObjectFile *Obj = nullptr;
386 ObjectFile *DbgObj = nullptr;
387 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
388 if (!error(BinaryOrErr.getError())) {
389 OwningBinary<Binary> &B = BinaryOrErr.get();
Lang Hamesf04de6e2014-10-31 21:37:49 +0000390 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000391 if (!Obj) {
392 ObjectPair Res = std::make_pair(nullptr, nullptr);
393 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
394 return Res;
395 }
396 addOwningBinary(std::move(B));
397 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
398 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000399 // Try to locate the debug binary using .gnu_debuglink section.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000400 if (!DbgObj) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000401 std::string DebuglinkName;
402 uint32_t CRCHash;
403 std::string DebugBinaryPath;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000404 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
Rafael Espindola63da2952014-01-15 19:37:43 +0000405 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
406 BinaryOrErr = createBinary(DebugBinaryPath);
407 if (!error(BinaryOrErr.getError())) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000408 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
Lang Hamesf04de6e2014-10-31 21:37:49 +0000409 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000410 addOwningBinary(std::move(B));
Rafael Espindola63da2952014-01-15 19:37:43 +0000411 }
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000412 }
413 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000414 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000415 if (!DbgObj)
416 DbgObj = Obj;
417 ObjectPair Res = std::make_pair(Obj, DbgObj);
418 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000419 return Res;
420}
421
422ObjectFile *
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000423LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
424 const std::string &ArchName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000425 if (!Bin)
426 return nullptr;
427 ObjectFile *Res = nullptr;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000428 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000429 const auto &I = ObjectFileForArch.find(
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000430 std::make_pair(UB, ArchName));
431 if (I != ObjectFileForArch.end())
432 return I->second;
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000433 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
Frederic Rissebc162a2015-06-22 21:33:24 +0000434 UB->getObjectForArch(ArchName);
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000435 if (ParsedObj) {
436 Res = ParsedObj.get().get();
437 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000438 }
439 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
440 } else if (Bin->isObject()) {
441 Res = cast<ObjectFile>(Bin);
442 }
443 return Res;
444}
445
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000446ModuleInfo *
447LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000448 const auto &I = Modules.find(ModuleName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000449 if (I != Modules.end())
450 return I->second;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000451 std::string BinaryName = ModuleName;
452 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000453 size_t ColonPos = ModuleName.find_last_of(':');
454 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000455 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000456 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000457 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000458 BinaryName = ModuleName.substr(0, ColonPos);
459 ArchName = ArchStr;
460 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000461 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000462 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000463
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000464 if (!Objects.first) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000465 // Failed to find valid object file.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000466 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
467 return nullptr;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000468 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000469 DIContext *Context = nullptr;
470 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
471 // If this is a COFF object, assume it contains PDB debug information. If
472 // we don't find any we will fall back to the DWARF case.
473 std::unique_ptr<IPDBSession> Session;
474 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
475 Objects.first->getFileName(), Session);
Zachary Turnerc007aa42015-05-06 22:26:30 +0000476 if (Error == PDB_ErrorCode::Success) {
477 Context = new PDBContext(*CoffObject, std::move(Session),
478 Opts.RelativeAddresses);
479 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000480 }
481 if (!Context)
482 Context = new DWARFContextInMemory(*Objects.second);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000483 assert(Context);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000484 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000485 Modules.insert(make_pair(ModuleName, Info));
486 return Info;
487}
488
Reid Klecknerc25c7942015-08-10 21:47:11 +0000489std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo,
490 ModuleInfo *ModInfo) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000491 // By default, DILineInfo contains "<invalid>" for function/filename it
492 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
493 static const std::string kDILineInfoBadString = "<invalid>";
494 std::stringstream Result;
Alexey Samsonovcd014722014-05-17 00:07:48 +0000495 if (Opts.PrintFunctions != FunctionNameKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000496 std::string FunctionName = LineInfo.FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000497 if (FunctionName == kDILineInfoBadString)
498 FunctionName = kBadString;
Alexey Samsonov601beb72013-06-28 12:06:25 +0000499 else if (Opts.Demangle)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000500 FunctionName = DemangleName(FunctionName, ModInfo);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000501 Result << FunctionName << "\n";
502 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000503 std::string Filename = LineInfo.FileName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000504 if (Filename == kDILineInfoBadString)
505 Filename = kBadString;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000506 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000507 return Result.str();
508}
509
Reid Klecknerc25c7942015-08-10 21:47:11 +0000510// Undo these various manglings for Win32 extern "C" functions:
511// cdecl - _foo
512// stdcall - _foo@12
513// fastcall - @foo@12
514// vectorcall - foo@@12
515// These are all different linkage names for 'foo'.
516static StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
517 // Remove any '_' or '@' prefix.
518 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
519 if (Front == '_' || Front == '@')
520 SymbolName = SymbolName.drop_front();
521
522 // Remove any '@[0-9]+' suffix.
523 if (Front != '?') {
524 size_t AtPos = SymbolName.rfind('@');
525 if (AtPos != StringRef::npos &&
526 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
527 [](char C) { return C >= '0' && C <= '9'; })) {
528 SymbolName = SymbolName.substr(0, AtPos);
529 }
530 }
531
532 // Remove any ending '@' for vectorcall.
533 if (SymbolName.endswith("@"))
534 SymbolName = SymbolName.drop_back();
535
536 return SymbolName;
537}
538
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000539#if !defined(_MSC_VER)
540// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
541extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
542 size_t *length, int *status);
543#endif
544
Reid Klecknerc25c7942015-08-10 21:47:11 +0000545std::string LLVMSymbolizer::DemangleName(const std::string &Name,
546 ModuleInfo *ModInfo) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000547#if !defined(_MSC_VER)
Ed Masteef6fed72014-01-16 17:25:12 +0000548 // We can spoil names of symbols with C linkage, so use an heuristic
549 // approach to check if the name should be demangled.
Reid Klecknerc25c7942015-08-10 21:47:11 +0000550 if (Name.substr(0, 2) == "_Z") {
551 int status = 0;
552 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
553 if (status != 0)
554 return Name;
555 std::string Result = DemangledName;
556 free(DemangledName);
557 return Result;
558 }
Alexey Samsonov601beb72013-06-28 12:06:25 +0000559#else
Reid Klecknerc25c7942015-08-10 21:47:11 +0000560 if (!Name.empty() && Name.front() == '?') {
561 // Only do MSVC C++ demangling on symbols starting with '?'.
562 char DemangledName[1024] = {0};
563 DWORD result = ::UnDecorateSymbolName(
564 Name.c_str(), DemangledName, 1023,
565 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
566 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
567 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
568 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
569 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
570 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
571 return (result == 0) ? Name : std::string(DemangledName);
572 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000573#endif
Reid Klecknerc25c7942015-08-10 21:47:11 +0000574 if (ModInfo->isWin32Module())
575 return std::string(demanglePE32ExternCFunc(Name));
576 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000577}
578
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000579} // namespace symbolize
580} // namespace llvm