blob: ae164b07b96daa95329952e6f10a1456e257b2ef [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
95void ModuleInfo::addCoffExportSymbols(const COFFObjectFile *CoffObj) {
96 // Get all export names and offsets.
97 struct OffsetNamePair {
98 uint32_t Offset;
99 StringRef Name;
100 };
101 std::vector<OffsetNamePair> ExportSyms;
102 for (const ExportDirectoryEntryRef &Ref : CoffObj->export_directories()) {
103 StringRef Name;
104 uint32_t Offset;
105 if (error(Ref.getSymbolName(Name)) || error(Ref.getExportRVA(Offset)))
106 return;
107 ExportSyms.push_back(OffsetNamePair{Offset, Name});
108 }
109 if (ExportSyms.empty())
110 return;
111
112 // Sort by ascending offset.
113 array_pod_sort(ExportSyms.begin(), ExportSyms.end(),
114 [](const OffsetNamePair *L, const OffsetNamePair *R) -> int {
115 return L->Offset - R->Offset;
116 });
117
118 // Approximate the symbol sizes by assuming they run to the next symbol.
119 // FIXME: This assumes all exports are functions.
120 uint64_t ImageBase = CoffObj->getImageBase();
121 for (auto I = ExportSyms.begin(), E = ExportSyms.end(); I != E; ++I) {
122 OffsetNamePair &Export = *I;
123 // FIXME: The last export has a one byte size now.
124 uint32_t NextOffset = I != E ? I->Offset : Export.Offset + 1;
125 uint64_t SymbolStart = ImageBase + Export.Offset;
126 uint64_t SymbolSize = NextOffset - Export.Offset;
127 SymbolDesc SD = {SymbolStart, SymbolSize};
128 Functions.insert(std::make_pair(SD, Export.Name));
129 }
Alexey Samsonova5f07682014-02-26 13:10:01 +0000130}
131
Rafael Espindolad8e96ec2015-06-25 15:06:38 +0000132void ModuleInfo::addSymbol(const SymbolRef &Symbol, uint64_t SymbolSize,
133 DataExtractor *OpdExtractor, uint64_t OpdAddress) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +0000134 SymbolRef::Type SymbolType = Symbol.getType();
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000135 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
Alexey Samsonova5f07682014-02-26 13:10:01 +0000136 return;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000137 ErrorOr<uint64_t> SymbolAddressOrErr = Symbol.getAddress();
138 if (error(SymbolAddressOrErr.getError()))
139 return;
140 uint64_t SymbolAddress = *SymbolAddressOrErr;
Jay Foad52695da2014-11-07 09:08:39 +0000141 if (OpdExtractor) {
142 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
143 // function descriptors. The first word of the descriptor is a pointer to
144 // the function's code.
145 // For the purposes of symbolization, pretend the symbol's address is that
146 // of the function's code, not the descriptor.
147 uint64_t OpdOffset = SymbolAddress - OpdAddress;
148 uint32_t OpdOffset32 = OpdOffset;
149 if (OpdOffset == OpdOffset32 &&
150 OpdExtractor->isValidOffsetForAddress(OpdOffset32))
151 SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
152 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000153 ErrorOr<StringRef> SymbolNameOrErr = Symbol.getName();
154 if (error(SymbolNameOrErr.getError()))
Alexey Samsonova5f07682014-02-26 13:10:01 +0000155 return;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000156 StringRef SymbolName = *SymbolNameOrErr;
Alexey Samsonova5f07682014-02-26 13:10:01 +0000157 // Mach-O symbol table names have leading underscore, skip it.
158 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
159 SymbolName = SymbolName.drop_front();
160 // FIXME: If a function has alias, there are two entries in symbol table
161 // with same address size. Make sure we choose the correct one.
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000162 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
Alexey Samsonova5f07682014-02-26 13:10:01 +0000163 SymbolDesc SD = { SymbolAddress, SymbolSize };
164 M.insert(std::make_pair(SD, SymbolName));
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000165}
166
Reid Klecknerc25c7942015-08-10 21:47:11 +0000167// Return true if this is a 32-bit x86 PE COFF module.
168bool ModuleInfo::isWin32Module() const {
169 auto *CoffObject = dyn_cast<COFFObjectFile>(Module);
170 return CoffObject && CoffObject->getMachine() == COFF::IMAGE_FILE_MACHINE_I386;
171}
172
Reid Klecknere94fef72015-10-09 00:15:01 +0000173uint64_t ModuleInfo::getModulePreferredBase() const {
174 if (auto *CoffObject = dyn_cast<COFFObjectFile>(Module))
Reid Kleckner21427ad2015-10-09 00:15:08 +0000175 return CoffObject->getImageBase();
Reid Klecknere94fef72015-10-09 00:15:01 +0000176 return 0;
177}
178
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000179bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
180 std::string &Name, uint64_t &Addr,
181 uint64_t &Size) const {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000182 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
183 if (SymbolMap.empty())
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000184 return false;
Alexey Samsonov5239d582013-06-04 07:57:38 +0000185 SymbolDesc SD = { Address, Address };
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000186 auto SymbolIterator = SymbolMap.upper_bound(SD);
187 if (SymbolIterator == SymbolMap.begin())
Alexey Samsonov35c987d2013-06-07 15:25:27 +0000188 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000189 --SymbolIterator;
190 if (SymbolIterator->first.Size != 0 &&
191 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000192 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000193 Name = SymbolIterator->second.str();
194 Addr = SymbolIterator->first.Addr;
195 Size = SymbolIterator->first.Size;
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000196 return true;
197}
198
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000199DILineInfo ModuleInfo::symbolizeCode(
200 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000201 DILineInfo LineInfo;
202 if (DebugInfoContext) {
203 LineInfo = DebugInfoContext->getLineInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000204 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000205 }
206 // Override function name from symbol table if necessary.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000207 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000208 std::string FunctionName;
209 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000210 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
211 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000212 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000213 }
214 }
215 return LineInfo;
216}
217
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000218DIInliningInfo ModuleInfo::symbolizeInlinedCode(
219 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000220 DIInliningInfo InlinedContext;
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000221
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000222 if (DebugInfoContext) {
223 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000224 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000225 }
226 // Make sure there is at least one frame in context.
227 if (InlinedContext.getNumberOfFrames() == 0) {
228 InlinedContext.addFrame(DILineInfo());
229 }
230 // Override the function name in lower frame with name from symbol table.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000231 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000232 DIInliningInfo PatchedInlinedContext;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000233 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000234 DILineInfo LineInfo = InlinedContext.getFrame(i);
235 if (i == n - 1) {
236 std::string FunctionName;
237 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000238 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
239 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000240 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000241 }
242 }
243 PatchedInlinedContext.addFrame(LineInfo);
244 }
245 InlinedContext = PatchedInlinedContext;
246 }
247 return InlinedContext;
248}
249
250bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
251 uint64_t &Start, uint64_t &Size) const {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000252 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
253 Size);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000254}
255
Alexey Samsonovd6cef102013-02-04 15:55:26 +0000256const char LLVMSymbolizer::kBadString[] = "??";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000257
258std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
259 uint64_t ModuleOffset) {
260 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000261 if (!Info)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000262 return printDILineInfo(DILineInfo(), Info);
Reid Klecknere94fef72015-10-09 00:15:01 +0000263
264 // If the user is giving us relative addresses, add the preferred base of the
265 // object to the offset before we do the query. It's what DIContext expects.
266 if (Opts.RelativeAddresses)
267 ModuleOffset += Info->getModulePreferredBase();
268
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000269 if (Opts.PrintInlining) {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000270 DIInliningInfo InlinedContext =
271 Info->symbolizeInlinedCode(ModuleOffset, Opts);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000272 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
273 assert(FramesNum > 0);
274 std::string Result;
275 for (uint32_t i = 0; i < FramesNum; i++) {
276 DILineInfo LineInfo = InlinedContext.getFrame(i);
Reid Klecknerc25c7942015-08-10 21:47:11 +0000277 Result += printDILineInfo(LineInfo, Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000278 }
279 return Result;
280 }
281 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
Reid Klecknerc25c7942015-08-10 21:47:11 +0000282 return printDILineInfo(LineInfo, Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000283}
284
285std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
286 uint64_t ModuleOffset) {
287 std::string Name = kBadString;
288 uint64_t Start = 0;
289 uint64_t Size = 0;
290 if (Opts.UseSymbolTable) {
291 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
Reid Klecknere94fef72015-10-09 00:15:01 +0000292 // If the user is giving us relative addresses, add the preferred base of the
293 // object to the offset before we do the query. It's what DIContext expects.
294 if (Opts.RelativeAddresses)
295 ModuleOffset += Info->getModulePreferredBase();
Alexey Samsonov601beb72013-06-28 12:06:25 +0000296 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000297 Name = DemangleName(Name, Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000298 }
299 }
300 std::stringstream ss;
301 ss << Name << "\n" << Start << " " << Size << "\n";
302 return ss.str();
303}
304
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000305void LLVMSymbolizer::flush() {
Alexey Samsonovdd71c5b2013-03-19 15:33:18 +0000306 DeleteContainerSeconds(Modules);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000307 ObjectPairForPathArch.clear();
Alexey Samsonovfe3a5d92013-06-28 15:08:29 +0000308 ObjectFileForArch.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000309}
310
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000311// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
312// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
313// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
314// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
315static
316std::string getDarwinDWARFResourceForPath(
317 const std::string &Path, const std::string &Basename) {
318 SmallString<16> ResourceName = StringRef(Path);
319 if (sys::path::extension(Path) != ".dSYM") {
320 ResourceName += ".dSYM";
321 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000322 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
323 sys::path::append(ResourceName, Basename);
324 return ResourceName.str();
325}
326
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000327static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000328 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
329 MemoryBuffer::getFileOrSTDIN(Path);
330 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000331 return false;
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000332 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000333}
334
335static bool findDebugBinary(const std::string &OrigPath,
336 const std::string &DebuglinkName, uint32_t CRCHash,
337 std::string &Result) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000338 std::string OrigRealPath = OrigPath;
339#if defined(HAVE_REALPATH)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000340 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000341 OrigRealPath = RP;
342 free(RP);
343 }
344#endif
345 SmallString<16> OrigDir(OrigRealPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000346 llvm::sys::path::remove_filename(OrigDir);
347 SmallString<16> DebugPath = OrigDir;
348 // Try /path/to/original_binary/debuglink_name
349 llvm::sys::path::append(DebugPath, DebuglinkName);
350 if (checkFileCRC(DebugPath, CRCHash)) {
351 Result = DebugPath.str();
352 return true;
353 }
354 // Try /path/to/original_binary/.debug/debuglink_name
Alexey Samsonova591ae62013-08-26 18:12:03 +0000355 DebugPath = OrigRealPath;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000356 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
357 if (checkFileCRC(DebugPath, CRCHash)) {
358 Result = DebugPath.str();
359 return true;
360 }
361 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
362 DebugPath = "/usr/lib/debug";
363 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
364 DebuglinkName);
365 if (checkFileCRC(DebugPath, CRCHash)) {
366 Result = DebugPath.str();
367 return true;
368 }
369 return false;
370}
371
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000372static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000373 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000374 if (!Obj)
375 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000376 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000377 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000378 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000379 Name = Name.substr(Name.find_first_not_of("._"));
380 if (Name == "gnu_debuglink") {
381 StringRef Data;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000382 Section.getContents(Data);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000383 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
384 uint32_t Offset = 0;
385 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
386 // 4-byte align the offset.
387 Offset = (Offset + 3) & ~0x3;
388 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
389 DebugName = DebugNameStr;
390 CRCHash = DE.getU32(&Offset);
391 return true;
392 }
393 }
394 break;
395 }
396 }
397 return false;
398}
399
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000400static
401bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
402 const MachOObjectFile *Obj) {
403 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
404 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
405 if (dbg_uuid.empty() || bin_uuid.empty())
406 return false;
407 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
408}
409
410ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
411 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
412 // On Darwin we may find DWARF in separate object file in
413 // resource directory.
414 std::vector<std::string> DsymPaths;
415 StringRef Filename = sys::path::filename(ExePath);
416 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
417 for (const auto &Path : Opts.DsymHints) {
418 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
419 }
420 for (const auto &path : DsymPaths) {
421 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
422 std::error_code EC = BinaryOrErr.getError();
423 if (EC != errc::no_such_file_or_directory && !error(EC)) {
424 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
425 ObjectFile *DbgObj =
Lang Hamesf04de6e2014-10-31 21:37:49 +0000426 getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000427 const MachOObjectFile *MachDbgObj =
428 dyn_cast<const MachOObjectFile>(DbgObj);
429 if (!MachDbgObj) continue;
430 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000431 addOwningBinary(std::move(B));
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000432 return DbgObj;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000433 }
434 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000435 }
436 return nullptr;
437}
438
439LLVMSymbolizer::ObjectPair
440LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
441 const std::string &ArchName) {
442 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
443 if (I != ObjectPairForPathArch.end())
444 return I->second;
445 ObjectFile *Obj = nullptr;
446 ObjectFile *DbgObj = nullptr;
447 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
448 if (!error(BinaryOrErr.getError())) {
449 OwningBinary<Binary> &B = BinaryOrErr.get();
Lang Hamesf04de6e2014-10-31 21:37:49 +0000450 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000451 if (!Obj) {
452 ObjectPair Res = std::make_pair(nullptr, nullptr);
453 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
454 return Res;
455 }
456 addOwningBinary(std::move(B));
457 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
458 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000459 // Try to locate the debug binary using .gnu_debuglink section.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000460 if (!DbgObj) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000461 std::string DebuglinkName;
462 uint32_t CRCHash;
463 std::string DebugBinaryPath;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000464 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
Rafael Espindola63da2952014-01-15 19:37:43 +0000465 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
466 BinaryOrErr = createBinary(DebugBinaryPath);
467 if (!error(BinaryOrErr.getError())) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000468 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
Lang Hamesf04de6e2014-10-31 21:37:49 +0000469 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000470 addOwningBinary(std::move(B));
Rafael Espindola63da2952014-01-15 19:37:43 +0000471 }
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000472 }
473 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000474 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000475 if (!DbgObj)
476 DbgObj = Obj;
477 ObjectPair Res = std::make_pair(Obj, DbgObj);
478 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000479 return Res;
480}
481
482ObjectFile *
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000483LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
484 const std::string &ArchName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000485 if (!Bin)
486 return nullptr;
487 ObjectFile *Res = nullptr;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000488 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000489 const auto &I = ObjectFileForArch.find(
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000490 std::make_pair(UB, ArchName));
491 if (I != ObjectFileForArch.end())
492 return I->second;
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000493 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
Frederic Rissebc162a2015-06-22 21:33:24 +0000494 UB->getObjectForArch(ArchName);
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000495 if (ParsedObj) {
496 Res = ParsedObj.get().get();
497 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000498 }
499 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
500 } else if (Bin->isObject()) {
501 Res = cast<ObjectFile>(Bin);
502 }
503 return Res;
504}
505
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000506ModuleInfo *
507LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000508 const auto &I = Modules.find(ModuleName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000509 if (I != Modules.end())
510 return I->second;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000511 std::string BinaryName = ModuleName;
512 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000513 size_t ColonPos = ModuleName.find_last_of(':');
514 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000515 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000516 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000517 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000518 BinaryName = ModuleName.substr(0, ColonPos);
519 ArchName = ArchStr;
520 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000521 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000522 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000523
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000524 if (!Objects.first) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000525 // Failed to find valid object file.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000526 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
527 return nullptr;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000528 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000529 DIContext *Context = nullptr;
530 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
531 // If this is a COFF object, assume it contains PDB debug information. If
532 // we don't find any we will fall back to the DWARF case.
533 std::unique_ptr<IPDBSession> Session;
534 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
535 Objects.first->getFileName(), Session);
Zachary Turnerc007aa42015-05-06 22:26:30 +0000536 if (Error == PDB_ErrorCode::Success) {
Reid Klecknere94fef72015-10-09 00:15:01 +0000537 Context = new PDBContext(*CoffObject, std::move(Session));
Zachary Turnerc007aa42015-05-06 22:26:30 +0000538 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000539 }
540 if (!Context)
541 Context = new DWARFContextInMemory(*Objects.second);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000542 assert(Context);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000543 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000544 Modules.insert(make_pair(ModuleName, Info));
545 return Info;
546}
547
Reid Klecknerc25c7942015-08-10 21:47:11 +0000548std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo,
549 ModuleInfo *ModInfo) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000550 // By default, DILineInfo contains "<invalid>" for function/filename it
551 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
552 static const std::string kDILineInfoBadString = "<invalid>";
553 std::stringstream Result;
Alexey Samsonovcd014722014-05-17 00:07:48 +0000554 if (Opts.PrintFunctions != FunctionNameKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000555 std::string FunctionName = LineInfo.FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000556 if (FunctionName == kDILineInfoBadString)
557 FunctionName = kBadString;
Alexey Samsonov601beb72013-06-28 12:06:25 +0000558 else if (Opts.Demangle)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000559 FunctionName = DemangleName(FunctionName, ModInfo);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000560 Result << FunctionName << "\n";
561 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000562 std::string Filename = LineInfo.FileName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000563 if (Filename == kDILineInfoBadString)
564 Filename = kBadString;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000565 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000566 return Result.str();
567}
568
Reid Klecknerc25c7942015-08-10 21:47:11 +0000569// Undo these various manglings for Win32 extern "C" functions:
570// cdecl - _foo
571// stdcall - _foo@12
572// fastcall - @foo@12
573// vectorcall - foo@@12
574// These are all different linkage names for 'foo'.
575static StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
576 // Remove any '_' or '@' prefix.
577 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
578 if (Front == '_' || Front == '@')
579 SymbolName = SymbolName.drop_front();
580
581 // Remove any '@[0-9]+' suffix.
582 if (Front != '?') {
583 size_t AtPos = SymbolName.rfind('@');
584 if (AtPos != StringRef::npos &&
585 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
586 [](char C) { return C >= '0' && C <= '9'; })) {
587 SymbolName = SymbolName.substr(0, AtPos);
588 }
589 }
590
591 // Remove any ending '@' for vectorcall.
592 if (SymbolName.endswith("@"))
593 SymbolName = SymbolName.drop_back();
594
595 return SymbolName;
596}
597
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000598#if !defined(_MSC_VER)
599// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
600extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
601 size_t *length, int *status);
602#endif
603
Reid Klecknerc25c7942015-08-10 21:47:11 +0000604std::string LLVMSymbolizer::DemangleName(const std::string &Name,
605 ModuleInfo *ModInfo) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000606#if !defined(_MSC_VER)
Ed Masteef6fed72014-01-16 17:25:12 +0000607 // We can spoil names of symbols with C linkage, so use an heuristic
608 // approach to check if the name should be demangled.
Reid Klecknerc25c7942015-08-10 21:47:11 +0000609 if (Name.substr(0, 2) == "_Z") {
610 int status = 0;
611 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
612 if (status != 0)
613 return Name;
614 std::string Result = DemangledName;
615 free(DemangledName);
616 return Result;
617 }
Alexey Samsonov601beb72013-06-28 12:06:25 +0000618#else
Reid Klecknerc25c7942015-08-10 21:47:11 +0000619 if (!Name.empty() && Name.front() == '?') {
620 // Only do MSVC C++ demangling on symbols starting with '?'.
621 char DemangledName[1024] = {0};
622 DWORD result = ::UnDecorateSymbolName(
623 Name.c_str(), DemangledName, 1023,
624 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
625 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
626 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
627 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
628 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
629 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
630 return (result == 0) ? Name : std::string(DemangledName);
631 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000632#endif
Reid Klecknerc25c7942015-08-10 21:47:11 +0000633 if (ModInfo->isWin32Module())
634 return std::string(demanglePE32ExternCFunc(Name));
635 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000636}
637
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000638} // namespace symbolize
639} // namespace llvm