blob: 51bb965b8df4b0db7c9d4fa5047608ebf54cb345 [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);
Reid Kleckner02b74362015-10-16 23:43:22 +000086
87 // If this is a COFF object and we didn't find any symbols, try the export
88 // table.
89 if (Symbols.empty()) {
90 if (auto *CoffObj = dyn_cast<COFFObjectFile>(Obj))
91 addCoffExportSymbols(CoffObj);
92 }
93}
94
Reid Kleckner793d9632015-10-16 23:53:12 +000095namespace {
96struct OffsetNamePair {
97 uint32_t Offset;
98 StringRef Name;
99 bool operator<(const OffsetNamePair &R) const {
100 return Offset < R.Offset;
101 }
102};
103}
104
Reid Kleckner02b74362015-10-16 23:43:22 +0000105void ModuleInfo::addCoffExportSymbols(const COFFObjectFile *CoffObj) {
106 // Get all export names and offsets.
Reid Kleckner02b74362015-10-16 23:43:22 +0000107 std::vector<OffsetNamePair> ExportSyms;
108 for (const ExportDirectoryEntryRef &Ref : CoffObj->export_directories()) {
109 StringRef Name;
110 uint32_t Offset;
111 if (error(Ref.getSymbolName(Name)) || error(Ref.getExportRVA(Offset)))
112 return;
113 ExportSyms.push_back(OffsetNamePair{Offset, Name});
114 }
115 if (ExportSyms.empty())
116 return;
117
118 // Sort by ascending offset.
Reid Kleckner793d9632015-10-16 23:53:12 +0000119 array_pod_sort(ExportSyms.begin(), ExportSyms.end());
Reid Kleckner02b74362015-10-16 23:43:22 +0000120
121 // Approximate the symbol sizes by assuming they run to the next symbol.
122 // FIXME: This assumes all exports are functions.
123 uint64_t ImageBase = CoffObj->getImageBase();
124 for (auto I = ExportSyms.begin(), E = ExportSyms.end(); I != E; ++I) {
125 OffsetNamePair &Export = *I;
126 // FIXME: The last export has a one byte size now.
127 uint32_t NextOffset = I != E ? I->Offset : Export.Offset + 1;
128 uint64_t SymbolStart = ImageBase + Export.Offset;
129 uint64_t SymbolSize = NextOffset - Export.Offset;
130 SymbolDesc SD = {SymbolStart, SymbolSize};
131 Functions.insert(std::make_pair(SD, Export.Name));
132 }
Alexey Samsonova5f07682014-02-26 13:10:01 +0000133}
134
Rafael Espindolad8e96ec2015-06-25 15:06:38 +0000135void ModuleInfo::addSymbol(const SymbolRef &Symbol, uint64_t SymbolSize,
136 DataExtractor *OpdExtractor, uint64_t OpdAddress) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +0000137 SymbolRef::Type SymbolType = Symbol.getType();
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000138 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
Alexey Samsonova5f07682014-02-26 13:10:01 +0000139 return;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000140 ErrorOr<uint64_t> SymbolAddressOrErr = Symbol.getAddress();
141 if (error(SymbolAddressOrErr.getError()))
142 return;
143 uint64_t SymbolAddress = *SymbolAddressOrErr;
Jay Foad52695da2014-11-07 09:08:39 +0000144 if (OpdExtractor) {
145 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
146 // function descriptors. The first word of the descriptor is a pointer to
147 // the function's code.
148 // For the purposes of symbolization, pretend the symbol's address is that
149 // of the function's code, not the descriptor.
150 uint64_t OpdOffset = SymbolAddress - OpdAddress;
151 uint32_t OpdOffset32 = OpdOffset;
152 if (OpdOffset == OpdOffset32 &&
153 OpdExtractor->isValidOffsetForAddress(OpdOffset32))
154 SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
155 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000156 ErrorOr<StringRef> SymbolNameOrErr = Symbol.getName();
157 if (error(SymbolNameOrErr.getError()))
Alexey Samsonova5f07682014-02-26 13:10:01 +0000158 return;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000159 StringRef SymbolName = *SymbolNameOrErr;
Alexey Samsonova5f07682014-02-26 13:10:01 +0000160 // Mach-O symbol table names have leading underscore, skip it.
161 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
162 SymbolName = SymbolName.drop_front();
163 // FIXME: If a function has alias, there are two entries in symbol table
164 // with same address size. Make sure we choose the correct one.
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000165 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
Alexey Samsonova5f07682014-02-26 13:10:01 +0000166 SymbolDesc SD = { SymbolAddress, SymbolSize };
167 M.insert(std::make_pair(SD, SymbolName));
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000168}
169
Reid Klecknerc25c7942015-08-10 21:47:11 +0000170// Return true if this is a 32-bit x86 PE COFF module.
171bool ModuleInfo::isWin32Module() const {
172 auto *CoffObject = dyn_cast<COFFObjectFile>(Module);
173 return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386;
174}
175
Reid Klecknere94fef72015-10-09 00:15:01 +0000176uint64_t ModuleInfo::getModulePreferredBase() const {
177 if (auto *CoffObject = dyn_cast<COFFObjectFile>(Module))
Reid Kleckner21427ad2015-10-09 00:15:08 +0000178 return CoffObject->getImageBase();
Reid Klecknere94fef72015-10-09 00:15:01 +0000179 return 0;
180}
181
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000182bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
183 std::string &Name, uint64_t &Addr,
184 uint64_t &Size) const {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000185 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
186 if (SymbolMap.empty())
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000187 return false;
Alexey Samsonov5239d582013-06-04 07:57:38 +0000188 SymbolDesc SD = { Address, Address };
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000189 auto SymbolIterator = SymbolMap.upper_bound(SD);
190 if (SymbolIterator == SymbolMap.begin())
Alexey Samsonov35c987d2013-06-07 15:25:27 +0000191 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000192 --SymbolIterator;
193 if (SymbolIterator->first.Size != 0 &&
194 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000195 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000196 Name = SymbolIterator->second.str();
197 Addr = SymbolIterator->first.Addr;
198 Size = SymbolIterator->first.Size;
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000199 return true;
200}
201
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000202DILineInfo ModuleInfo::symbolizeCode(
203 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000204 DILineInfo LineInfo;
205 if (DebugInfoContext) {
206 LineInfo = DebugInfoContext->getLineInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000207 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000208 }
209 // Override function name from symbol table if necessary.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000210 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000211 std::string FunctionName;
212 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000213 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
214 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000215 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000216 }
217 }
218 return LineInfo;
219}
220
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000221DIInliningInfo ModuleInfo::symbolizeInlinedCode(
222 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000223 DIInliningInfo InlinedContext;
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000224
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000225 if (DebugInfoContext) {
226 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000227 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000228 }
229 // Make sure there is at least one frame in context.
230 if (InlinedContext.getNumberOfFrames() == 0) {
231 InlinedContext.addFrame(DILineInfo());
232 }
233 // Override the function name in lower frame with name from symbol table.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000234 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000235 DIInliningInfo PatchedInlinedContext;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000236 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000237 DILineInfo LineInfo = InlinedContext.getFrame(i);
238 if (i == n - 1) {
239 std::string FunctionName;
240 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000241 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
242 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000243 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000244 }
245 }
246 PatchedInlinedContext.addFrame(LineInfo);
247 }
248 InlinedContext = PatchedInlinedContext;
249 }
250 return InlinedContext;
251}
252
253bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
254 uint64_t &Start, uint64_t &Size) const {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000255 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
256 Size);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000257}
258
Alexey Samsonovd6cef102013-02-04 15:55:26 +0000259const char LLVMSymbolizer::kBadString[] = "??";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000260
261std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
262 uint64_t ModuleOffset) {
263 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000264 if (!Info)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000265 return printDILineInfo(DILineInfo(), Info);
Reid Klecknere94fef72015-10-09 00:15:01 +0000266
267 // If the user is giving us relative addresses, add the preferred base of the
268 // object to the offset before we do the query. It's what DIContext expects.
269 if (Opts.RelativeAddresses)
270 ModuleOffset += Info->getModulePreferredBase();
271
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000272 if (Opts.PrintInlining) {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000273 DIInliningInfo InlinedContext =
274 Info->symbolizeInlinedCode(ModuleOffset, Opts);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000275 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
276 assert(FramesNum > 0);
277 std::string Result;
278 for (uint32_t i = 0; i < FramesNum; i++) {
279 DILineInfo LineInfo = InlinedContext.getFrame(i);
Reid Klecknerc25c7942015-08-10 21:47:11 +0000280 Result += printDILineInfo(LineInfo, Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000281 }
282 return Result;
283 }
284 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
Reid Klecknerc25c7942015-08-10 21:47:11 +0000285 return printDILineInfo(LineInfo, Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000286}
287
288std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
289 uint64_t ModuleOffset) {
290 std::string Name = kBadString;
291 uint64_t Start = 0;
292 uint64_t Size = 0;
293 if (Opts.UseSymbolTable) {
294 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
Reid Klecknere94fef72015-10-09 00:15:01 +0000295 // If the user is giving us relative addresses, add the preferred base of the
296 // object to the offset before we do the query. It's what DIContext expects.
297 if (Opts.RelativeAddresses)
298 ModuleOffset += Info->getModulePreferredBase();
Alexey Samsonov601beb72013-06-28 12:06:25 +0000299 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000300 Name = DemangleName(Name, Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000301 }
302 }
303 std::stringstream ss;
304 ss << Name << "\n" << Start << " " << Size << "\n";
305 return ss.str();
306}
307
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000308void LLVMSymbolizer::flush() {
Alexey Samsonovdd71c5b2013-03-19 15:33:18 +0000309 DeleteContainerSeconds(Modules);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000310 ObjectPairForPathArch.clear();
Alexey Samsonovfe3a5d92013-06-28 15:08:29 +0000311 ObjectFileForArch.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000312}
313
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000314// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
315// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
316// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
317// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
318static
319std::string getDarwinDWARFResourceForPath(
320 const std::string &Path, const std::string &Basename) {
321 SmallString<16> ResourceName = StringRef(Path);
322 if (sys::path::extension(Path) != ".dSYM") {
323 ResourceName += ".dSYM";
324 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000325 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
326 sys::path::append(ResourceName, Basename);
327 return ResourceName.str();
328}
329
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000330static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000331 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
332 MemoryBuffer::getFileOrSTDIN(Path);
333 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000334 return false;
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000335 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000336}
337
338static bool findDebugBinary(const std::string &OrigPath,
339 const std::string &DebuglinkName, uint32_t CRCHash,
340 std::string &Result) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000341 std::string OrigRealPath = OrigPath;
342#if defined(HAVE_REALPATH)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000343 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000344 OrigRealPath = RP;
345 free(RP);
346 }
347#endif
348 SmallString<16> OrigDir(OrigRealPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000349 llvm::sys::path::remove_filename(OrigDir);
350 SmallString<16> DebugPath = OrigDir;
351 // Try /path/to/original_binary/debuglink_name
352 llvm::sys::path::append(DebugPath, DebuglinkName);
353 if (checkFileCRC(DebugPath, CRCHash)) {
354 Result = DebugPath.str();
355 return true;
356 }
357 // Try /path/to/original_binary/.debug/debuglink_name
Alexey Samsonova591ae62013-08-26 18:12:03 +0000358 DebugPath = OrigRealPath;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000359 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
360 if (checkFileCRC(DebugPath, CRCHash)) {
361 Result = DebugPath.str();
362 return true;
363 }
364 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
365 DebugPath = "/usr/lib/debug";
366 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
367 DebuglinkName);
368 if (checkFileCRC(DebugPath, CRCHash)) {
369 Result = DebugPath.str();
370 return true;
371 }
372 return false;
373}
374
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000375static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000376 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000377 if (!Obj)
378 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000379 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000380 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000381 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000382 Name = Name.substr(Name.find_first_not_of("._"));
383 if (Name == "gnu_debuglink") {
384 StringRef Data;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000385 Section.getContents(Data);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000386 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
387 uint32_t Offset = 0;
388 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
389 // 4-byte align the offset.
390 Offset = (Offset + 3) & ~0x3;
391 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
392 DebugName = DebugNameStr;
393 CRCHash = DE.getU32(&Offset);
394 return true;
395 }
396 }
397 break;
398 }
399 }
400 return false;
401}
402
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000403static
404bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
405 const MachOObjectFile *Obj) {
406 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
407 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
408 if (dbg_uuid.empty() || bin_uuid.empty())
409 return false;
410 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
411}
412
413ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
414 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
415 // On Darwin we may find DWARF in separate object file in
416 // resource directory.
417 std::vector<std::string> DsymPaths;
418 StringRef Filename = sys::path::filename(ExePath);
419 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
420 for (const auto &Path : Opts.DsymHints) {
421 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
422 }
423 for (const auto &path : DsymPaths) {
424 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
425 std::error_code EC = BinaryOrErr.getError();
426 if (EC != errc::no_such_file_or_directory && !error(EC)) {
427 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
428 ObjectFile *DbgObj =
Lang Hamesf04de6e2014-10-31 21:37:49 +0000429 getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000430 const MachOObjectFile *MachDbgObj =
431 dyn_cast<const MachOObjectFile>(DbgObj);
432 if (!MachDbgObj) continue;
433 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000434 addOwningBinary(std::move(B));
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000435 return DbgObj;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000436 }
437 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000438 }
439 return nullptr;
440}
441
442LLVMSymbolizer::ObjectPair
443LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
444 const std::string &ArchName) {
445 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
446 if (I != ObjectPairForPathArch.end())
447 return I->second;
448 ObjectFile *Obj = nullptr;
449 ObjectFile *DbgObj = nullptr;
450 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
451 if (!error(BinaryOrErr.getError())) {
452 OwningBinary<Binary> &B = BinaryOrErr.get();
Lang Hamesf04de6e2014-10-31 21:37:49 +0000453 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000454 if (!Obj) {
455 ObjectPair Res = std::make_pair(nullptr, nullptr);
456 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
457 return Res;
458 }
459 addOwningBinary(std::move(B));
460 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
461 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000462 // Try to locate the debug binary using .gnu_debuglink section.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000463 if (!DbgObj) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000464 std::string DebuglinkName;
465 uint32_t CRCHash;
466 std::string DebugBinaryPath;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000467 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
Rafael Espindola63da2952014-01-15 19:37:43 +0000468 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
469 BinaryOrErr = createBinary(DebugBinaryPath);
470 if (!error(BinaryOrErr.getError())) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000471 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
Lang Hamesf04de6e2014-10-31 21:37:49 +0000472 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000473 addOwningBinary(std::move(B));
Rafael Espindola63da2952014-01-15 19:37:43 +0000474 }
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000475 }
476 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000477 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000478 if (!DbgObj)
479 DbgObj = Obj;
480 ObjectPair Res = std::make_pair(Obj, DbgObj);
481 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000482 return Res;
483}
484
485ObjectFile *
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000486LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
487 const std::string &ArchName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000488 if (!Bin)
489 return nullptr;
490 ObjectFile *Res = nullptr;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000491 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000492 const auto &I = ObjectFileForArch.find(
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000493 std::make_pair(UB, ArchName));
494 if (I != ObjectFileForArch.end())
495 return I->second;
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000496 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
Frederic Rissebc162a2015-06-22 21:33:24 +0000497 UB->getObjectForArch(ArchName);
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000498 if (ParsedObj) {
499 Res = ParsedObj.get().get();
500 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000501 }
502 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
503 } else if (Bin->isObject()) {
504 Res = cast<ObjectFile>(Bin);
505 }
506 return Res;
507}
508
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000509ModuleInfo *
510LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000511 const auto &I = Modules.find(ModuleName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000512 if (I != Modules.end())
513 return I->second;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000514 std::string BinaryName = ModuleName;
515 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000516 size_t ColonPos = ModuleName.find_last_of(':');
517 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000518 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000519 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000520 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000521 BinaryName = ModuleName.substr(0, ColonPos);
522 ArchName = ArchStr;
523 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000524 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000525 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000526
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000527 if (!Objects.first) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000528 // Failed to find valid object file.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000529 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
530 return nullptr;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000531 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000532 DIContext *Context = nullptr;
533 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
534 // If this is a COFF object, assume it contains PDB debug information. If
535 // we don't find any we will fall back to the DWARF case.
536 std::unique_ptr<IPDBSession> Session;
537 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
538 Objects.first->getFileName(), Session);
Zachary Turnerc007aa42015-05-06 22:26:30 +0000539 if (Error == PDB_ErrorCode::Success) {
Reid Klecknere94fef72015-10-09 00:15:01 +0000540 Context = new PDBContext(*CoffObject, std::move(Session));
Zachary Turnerc007aa42015-05-06 22:26:30 +0000541 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000542 }
543 if (!Context)
544 Context = new DWARFContextInMemory(*Objects.second);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000545 assert(Context);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000546 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000547 Modules.insert(make_pair(ModuleName, Info));
548 return Info;
549}
550
Reid Klecknerc25c7942015-08-10 21:47:11 +0000551std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo,
552 ModuleInfo *ModInfo) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000553 // By default, DILineInfo contains "<invalid>" for function/filename it
554 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
555 static const std::string kDILineInfoBadString = "<invalid>";
556 std::stringstream Result;
Alexey Samsonovcd014722014-05-17 00:07:48 +0000557 if (Opts.PrintFunctions != FunctionNameKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000558 std::string FunctionName = LineInfo.FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000559 if (FunctionName == kDILineInfoBadString)
560 FunctionName = kBadString;
Alexey Samsonov601beb72013-06-28 12:06:25 +0000561 else if (Opts.Demangle)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000562 FunctionName = DemangleName(FunctionName, ModInfo);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000563 Result << FunctionName << "\n";
564 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000565 std::string Filename = LineInfo.FileName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000566 if (Filename == kDILineInfoBadString)
567 Filename = kBadString;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000568 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000569 return Result.str();
570}
571
Reid Klecknerc25c7942015-08-10 21:47:11 +0000572// Undo these various manglings for Win32 extern "C" functions:
573// cdecl - _foo
574// stdcall - _foo@12
575// fastcall - @foo@12
576// vectorcall - foo@@12
577// These are all different linkage names for 'foo'.
578static StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
579 // Remove any '_' or '@' prefix.
580 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
581 if (Front == '_' || Front == '@')
582 SymbolName = SymbolName.drop_front();
583
584 // Remove any '@[0-9]+' suffix.
585 if (Front != '?') {
586 size_t AtPos = SymbolName.rfind('@');
587 if (AtPos != StringRef::npos &&
588 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
589 [](char C) { return C >= '0' && C <= '9'; })) {
590 SymbolName = SymbolName.substr(0, AtPos);
591 }
592 }
593
594 // Remove any ending '@' for vectorcall.
595 if (SymbolName.endswith("@"))
596 SymbolName = SymbolName.drop_back();
597
598 return SymbolName;
599}
600
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000601#if !defined(_MSC_VER)
602// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
603extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
604 size_t *length, int *status);
605#endif
606
Reid Klecknerc25c7942015-08-10 21:47:11 +0000607std::string LLVMSymbolizer::DemangleName(const std::string &Name,
608 ModuleInfo *ModInfo) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000609#if !defined(_MSC_VER)
Ed Masteef6fed72014-01-16 17:25:12 +0000610 // We can spoil names of symbols with C linkage, so use an heuristic
611 // approach to check if the name should be demangled.
Reid Klecknerc25c7942015-08-10 21:47:11 +0000612 if (Name.substr(0, 2) == "_Z") {
613 int status = 0;
614 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
615 if (status != 0)
616 return Name;
617 std::string Result = DemangledName;
618 free(DemangledName);
619 return Result;
620 }
Alexey Samsonov601beb72013-06-28 12:06:25 +0000621#else
Reid Klecknerc25c7942015-08-10 21:47:11 +0000622 if (!Name.empty() && Name.front() == '?') {
623 // Only do MSVC C++ demangling on symbols starting with '?'.
624 char DemangledName[1024] = {0};
625 DWORD result = ::UnDecorateSymbolName(
626 Name.c_str(), DemangledName, 1023,
627 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
628 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
629 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
630 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
631 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
632 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
633 return (result == 0) ? Name : std::string(DemangledName);
634 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000635#endif
Reid Klecknerc25c7942015-08-10 21:47:11 +0000636 if (ModInfo->isWin32Module())
637 return std::string(demanglePE32ExternCFunc(Name));
638 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000639}
640
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000641} // namespace symbolize
642} // namespace llvm