blob: afb7cc81c824cfd0abe51a9ed18dae16b75a8392 [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"
22#include "llvm/Support/Casting.h"
Alexey Samsonov3e9997f2013-08-14 17:09:30 +000023#include "llvm/Support/Compression.h"
24#include "llvm/Support/DataExtractor.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000025#include "llvm/Support/Errc.h"
Alexey Samsonov5239d582013-06-04 07:57:38 +000026#include "llvm/Support/FileSystem.h"
Alexey Samsonov3e9997f2013-08-14 17:09:30 +000027#include "llvm/Support/MemoryBuffer.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000028#include "llvm/Support/Path.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000029#include <sstream>
Alexey Samsonova591ae62013-08-26 18:12:03 +000030#include <stdlib.h>
Alexey Samsonovea83baf2013-01-22 14:21:19 +000031
Zachary Turnerc007aa42015-05-06 22:26:30 +000032#if defined(_MSC_VER)
33#include <Windows.h>
34#include <DbgHelp.h>
35#endif
36
Alexey Samsonovea83baf2013-01-22 14:21:19 +000037namespace llvm {
38namespace symbolize {
39
Rafael Espindola4453e42942014-06-13 03:07:50 +000040static bool error(std::error_code ec) {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +000041 if (!ec)
42 return false;
Dmitry Vyukovef8fb722013-02-14 13:06:18 +000043 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
44 return true;
45}
46
Alexey Samsonovdce67342014-05-15 21:24:32 +000047static DILineInfoSpecifier
48getDILineInfoSpecifier(const LLVMSymbolizer::Options &Opts) {
49 return DILineInfoSpecifier(
50 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
Alexey Samsonovcd014722014-05-17 00:07:48 +000051 Opts.PrintFunctions);
Alexey Samsonovea83baf2013-01-22 14:21:19 +000052}
53
Dmitry Vyukovef8fb722013-02-14 13:06:18 +000054ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +000055 : Module(Obj), DebugInfoContext(DICtx) {
Jay Foad52695da2014-11-07 09:08:39 +000056 std::unique_ptr<DataExtractor> OpdExtractor;
57 uint64_t OpdAddress = 0;
58 // Find the .opd (function descriptor) section if any, for big-endian
59 // PowerPC64 ELF.
60 if (Module->getArch() == Triple::ppc64) {
61 for (section_iterator Section : Module->sections()) {
62 StringRef Name;
63 if (!error(Section->getName(Name)) && Name == ".opd") {
64 StringRef Data;
65 if (!error(Section->getContents(Data))) {
66 OpdExtractor.reset(new DataExtractor(Data, Module->isLittleEndian(),
67 Module->getBytesInAddress()));
68 OpdAddress = Section->getAddress();
69 }
70 break;
71 }
72 }
73 }
Alexey Samsonov464d2e42014-03-17 07:28:19 +000074 for (const SymbolRef &Symbol : Module->symbols()) {
Jay Foad52695da2014-11-07 09:08:39 +000075 addSymbol(Symbol, OpdExtractor.get(), OpdAddress);
Dmitry Vyukovef8fb722013-02-14 13:06:18 +000076 }
Alexey Samsonova5f07682014-02-26 13:10:01 +000077 bool NoSymbolTable = (Module->symbol_begin() == Module->symbol_end());
78 if (NoSymbolTable && Module->isELF()) {
79 // Fallback to dynamic symbol table, if regular symbol table is stripped.
80 std::pair<symbol_iterator, symbol_iterator> IDyn =
81 getELFDynamicSymbolIterators(Module);
82 for (symbol_iterator si = IDyn.first, se = IDyn.second; si != se; ++si) {
Jay Foad52695da2014-11-07 09:08:39 +000083 addSymbol(*si, OpdExtractor.get(), OpdAddress);
Alexey Samsonova5f07682014-02-26 13:10:01 +000084 }
85 }
86}
87
Jay Foad52695da2014-11-07 09:08:39 +000088void ModuleInfo::addSymbol(const SymbolRef &Symbol, DataExtractor *OpdExtractor,
89 uint64_t OpdAddress) {
Alexey Samsonova5f07682014-02-26 13:10:01 +000090 SymbolRef::Type SymbolType;
Alexey Samsonov464d2e42014-03-17 07:28:19 +000091 if (error(Symbol.getType(SymbolType)))
Alexey Samsonova5f07682014-02-26 13:10:01 +000092 return;
Alexey Samsonov464d2e42014-03-17 07:28:19 +000093 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
Alexey Samsonova5f07682014-02-26 13:10:01 +000094 return;
95 uint64_t SymbolAddress;
Alexey Samsonov464d2e42014-03-17 07:28:19 +000096 if (error(Symbol.getAddress(SymbolAddress)) ||
Alexey Samsonova5f07682014-02-26 13:10:01 +000097 SymbolAddress == UnknownAddressOrSize)
98 return;
Jay Foad52695da2014-11-07 09:08:39 +000099 if (OpdExtractor) {
100 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
101 // function descriptors. The first word of the descriptor is a pointer to
102 // the function's code.
103 // For the purposes of symbolization, pretend the symbol's address is that
104 // of the function's code, not the descriptor.
105 uint64_t OpdOffset = SymbolAddress - OpdAddress;
106 uint32_t OpdOffset32 = OpdOffset;
107 if (OpdOffset == OpdOffset32 &&
108 OpdExtractor->isValidOffsetForAddress(OpdOffset32))
109 SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
110 }
Alexey Samsonova5f07682014-02-26 13:10:01 +0000111 uint64_t SymbolSize;
112 // Getting symbol size is linear for Mach-O files, so assume that symbol
113 // occupies the memory range up to the following symbol.
114 if (isa<MachOObjectFile>(Module))
115 SymbolSize = 0;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000116 else if (error(Symbol.getSize(SymbolSize)) ||
Alexey Samsonova5f07682014-02-26 13:10:01 +0000117 SymbolSize == UnknownAddressOrSize)
118 return;
119 StringRef SymbolName;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000120 if (error(Symbol.getName(SymbolName)))
Alexey Samsonova5f07682014-02-26 13:10:01 +0000121 return;
122 // Mach-O symbol table names have leading underscore, skip it.
123 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
124 SymbolName = SymbolName.drop_front();
125 // FIXME: If a function has alias, there are two entries in symbol table
126 // with same address size. Make sure we choose the correct one.
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000127 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
Alexey Samsonova5f07682014-02-26 13:10:01 +0000128 SymbolDesc SD = { SymbolAddress, SymbolSize };
129 M.insert(std::make_pair(SD, SymbolName));
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000130}
131
132bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
133 std::string &Name, uint64_t &Addr,
134 uint64_t &Size) const {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000135 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
136 if (SymbolMap.empty())
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000137 return false;
Alexey Samsonov5239d582013-06-04 07:57:38 +0000138 SymbolDesc SD = { Address, Address };
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000139 auto SymbolIterator = SymbolMap.upper_bound(SD);
140 if (SymbolIterator == SymbolMap.begin())
Alexey Samsonov35c987d2013-06-07 15:25:27 +0000141 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000142 --SymbolIterator;
143 if (SymbolIterator->first.Size != 0 &&
144 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000145 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000146 Name = SymbolIterator->second.str();
147 Addr = SymbolIterator->first.Addr;
148 Size = SymbolIterator->first.Size;
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000149 return true;
150}
151
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000152DILineInfo ModuleInfo::symbolizeCode(
153 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000154 DILineInfo LineInfo;
155 if (DebugInfoContext) {
156 LineInfo = DebugInfoContext->getLineInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000157 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000158 }
159 // Override function name from symbol table if necessary.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000160 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000161 std::string FunctionName;
162 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000163 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
164 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000165 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000166 }
167 }
168 return LineInfo;
169}
170
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000171DIInliningInfo ModuleInfo::symbolizeInlinedCode(
172 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000173 DIInliningInfo InlinedContext;
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000174
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000175 if (DebugInfoContext) {
176 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000177 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000178 }
179 // Make sure there is at least one frame in context.
180 if (InlinedContext.getNumberOfFrames() == 0) {
181 InlinedContext.addFrame(DILineInfo());
182 }
183 // Override the function name in lower frame with name from symbol table.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000184 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000185 DIInliningInfo PatchedInlinedContext;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000186 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000187 DILineInfo LineInfo = InlinedContext.getFrame(i);
188 if (i == n - 1) {
189 std::string FunctionName;
190 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000191 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
192 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000193 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000194 }
195 }
196 PatchedInlinedContext.addFrame(LineInfo);
197 }
198 InlinedContext = PatchedInlinedContext;
199 }
200 return InlinedContext;
201}
202
203bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
204 uint64_t &Start, uint64_t &Size) const {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000205 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
206 Size);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000207}
208
Alexey Samsonovd6cef102013-02-04 15:55:26 +0000209const char LLVMSymbolizer::kBadString[] = "??";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000210
211std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
212 uint64_t ModuleOffset) {
213 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000214 if (!Info)
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000215 return printDILineInfo(DILineInfo());
216 if (Opts.PrintInlining) {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000217 DIInliningInfo InlinedContext =
218 Info->symbolizeInlinedCode(ModuleOffset, Opts);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000219 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
220 assert(FramesNum > 0);
221 std::string Result;
222 for (uint32_t i = 0; i < FramesNum; i++) {
223 DILineInfo LineInfo = InlinedContext.getFrame(i);
224 Result += printDILineInfo(LineInfo);
225 }
226 return Result;
227 }
228 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
229 return printDILineInfo(LineInfo);
230}
231
232std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
233 uint64_t ModuleOffset) {
234 std::string Name = kBadString;
235 uint64_t Start = 0;
236 uint64_t Size = 0;
237 if (Opts.UseSymbolTable) {
238 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
Alexey Samsonov601beb72013-06-28 12:06:25 +0000239 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
Ed Masteef6fed72014-01-16 17:25:12 +0000240 Name = DemangleName(Name);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000241 }
242 }
243 std::stringstream ss;
244 ss << Name << "\n" << Start << " " << Size << "\n";
245 return ss.str();
246}
247
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000248void LLVMSymbolizer::flush() {
Alexey Samsonovdd71c5b2013-03-19 15:33:18 +0000249 DeleteContainerSeconds(Modules);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000250 ObjectPairForPathArch.clear();
Alexey Samsonovfe3a5d92013-06-28 15:08:29 +0000251 ObjectFileForArch.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000252}
253
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000254// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
255// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
256// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
257// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
258static
259std::string getDarwinDWARFResourceForPath(
260 const std::string &Path, const std::string &Basename) {
261 SmallString<16> ResourceName = StringRef(Path);
262 if (sys::path::extension(Path) != ".dSYM") {
263 ResourceName += ".dSYM";
264 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000265 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
266 sys::path::append(ResourceName, Basename);
267 return ResourceName.str();
268}
269
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000270static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000271 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
272 MemoryBuffer::getFileOrSTDIN(Path);
273 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000274 return false;
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000275 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000276}
277
278static bool findDebugBinary(const std::string &OrigPath,
279 const std::string &DebuglinkName, uint32_t CRCHash,
280 std::string &Result) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000281 std::string OrigRealPath = OrigPath;
282#if defined(HAVE_REALPATH)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000283 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000284 OrigRealPath = RP;
285 free(RP);
286 }
287#endif
288 SmallString<16> OrigDir(OrigRealPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000289 llvm::sys::path::remove_filename(OrigDir);
290 SmallString<16> DebugPath = OrigDir;
291 // Try /path/to/original_binary/debuglink_name
292 llvm::sys::path::append(DebugPath, DebuglinkName);
293 if (checkFileCRC(DebugPath, CRCHash)) {
294 Result = DebugPath.str();
295 return true;
296 }
297 // Try /path/to/original_binary/.debug/debuglink_name
Alexey Samsonova591ae62013-08-26 18:12:03 +0000298 DebugPath = OrigRealPath;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000299 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
300 if (checkFileCRC(DebugPath, CRCHash)) {
301 Result = DebugPath.str();
302 return true;
303 }
304 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
305 DebugPath = "/usr/lib/debug";
306 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
307 DebuglinkName);
308 if (checkFileCRC(DebugPath, CRCHash)) {
309 Result = DebugPath.str();
310 return true;
311 }
312 return false;
313}
314
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000315static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000316 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000317 if (!Obj)
318 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000319 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000320 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000321 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000322 Name = Name.substr(Name.find_first_not_of("._"));
323 if (Name == "gnu_debuglink") {
324 StringRef Data;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000325 Section.getContents(Data);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000326 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
327 uint32_t Offset = 0;
328 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
329 // 4-byte align the offset.
330 Offset = (Offset + 3) & ~0x3;
331 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
332 DebugName = DebugNameStr;
333 CRCHash = DE.getU32(&Offset);
334 return true;
335 }
336 }
337 break;
338 }
339 }
340 return false;
341}
342
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000343static
344bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
345 const MachOObjectFile *Obj) {
346 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
347 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
348 if (dbg_uuid.empty() || bin_uuid.empty())
349 return false;
350 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
351}
352
353ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
354 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
355 // On Darwin we may find DWARF in separate object file in
356 // resource directory.
357 std::vector<std::string> DsymPaths;
358 StringRef Filename = sys::path::filename(ExePath);
359 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
360 for (const auto &Path : Opts.DsymHints) {
361 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
362 }
363 for (const auto &path : DsymPaths) {
364 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
365 std::error_code EC = BinaryOrErr.getError();
366 if (EC != errc::no_such_file_or_directory && !error(EC)) {
367 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
368 ObjectFile *DbgObj =
Lang Hamesf04de6e2014-10-31 21:37:49 +0000369 getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000370 const MachOObjectFile *MachDbgObj =
371 dyn_cast<const MachOObjectFile>(DbgObj);
372 if (!MachDbgObj) continue;
373 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000374 addOwningBinary(std::move(B));
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000375 return DbgObj;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000376 }
377 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000378 }
379 return nullptr;
380}
381
382LLVMSymbolizer::ObjectPair
383LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
384 const std::string &ArchName) {
385 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
386 if (I != ObjectPairForPathArch.end())
387 return I->second;
388 ObjectFile *Obj = nullptr;
389 ObjectFile *DbgObj = nullptr;
390 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
391 if (!error(BinaryOrErr.getError())) {
392 OwningBinary<Binary> &B = BinaryOrErr.get();
Lang Hamesf04de6e2014-10-31 21:37:49 +0000393 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000394 if (!Obj) {
395 ObjectPair Res = std::make_pair(nullptr, nullptr);
396 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
397 return Res;
398 }
399 addOwningBinary(std::move(B));
400 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
401 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000402 // Try to locate the debug binary using .gnu_debuglink section.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000403 if (!DbgObj) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000404 std::string DebuglinkName;
405 uint32_t CRCHash;
406 std::string DebugBinaryPath;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000407 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
Rafael Espindola63da2952014-01-15 19:37:43 +0000408 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
409 BinaryOrErr = createBinary(DebugBinaryPath);
410 if (!error(BinaryOrErr.getError())) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000411 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
Lang Hamesf04de6e2014-10-31 21:37:49 +0000412 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000413 addOwningBinary(std::move(B));
Rafael Espindola63da2952014-01-15 19:37:43 +0000414 }
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000415 }
416 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000417 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000418 if (!DbgObj)
419 DbgObj = Obj;
420 ObjectPair Res = std::make_pair(Obj, DbgObj);
421 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000422 return Res;
423}
424
425ObjectFile *
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000426LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
427 const std::string &ArchName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000428 if (!Bin)
429 return nullptr;
430 ObjectFile *Res = nullptr;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000431 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000432 const auto &I = ObjectFileForArch.find(
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000433 std::make_pair(UB, ArchName));
434 if (I != ObjectFileForArch.end())
435 return I->second;
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000436 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
437 UB->getObjectForArch(Triple(ArchName).getArch());
438 if (ParsedObj) {
439 Res = ParsedObj.get().get();
440 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000441 }
442 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
443 } else if (Bin->isObject()) {
444 Res = cast<ObjectFile>(Bin);
445 }
446 return Res;
447}
448
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000449ModuleInfo *
450LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000451 const auto &I = Modules.find(ModuleName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000452 if (I != Modules.end())
453 return I->second;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000454 std::string BinaryName = ModuleName;
455 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000456 size_t ColonPos = ModuleName.find_last_of(':');
457 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000458 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000459 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000460 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000461 BinaryName = ModuleName.substr(0, ColonPos);
462 ArchName = ArchStr;
463 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000464 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000465 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000466
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000467 if (!Objects.first) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000468 // Failed to find valid object file.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000469 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
470 return nullptr;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000471 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000472 DIContext *Context = nullptr;
473 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
474 // If this is a COFF object, assume it contains PDB debug information. If
475 // we don't find any we will fall back to the DWARF case.
476 std::unique_ptr<IPDBSession> Session;
477 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
478 Objects.first->getFileName(), Session);
Zachary Turnerc007aa42015-05-06 22:26:30 +0000479 if (Error == PDB_ErrorCode::Success) {
480 Context = new PDBContext(*CoffObject, std::move(Session),
481 Opts.RelativeAddresses);
482 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000483 }
484 if (!Context)
485 Context = new DWARFContextInMemory(*Objects.second);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000486 assert(Context);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000487 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000488 Modules.insert(make_pair(ModuleName, Info));
489 return Info;
490}
491
492std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
493 // By default, DILineInfo contains "<invalid>" for function/filename it
494 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
495 static const std::string kDILineInfoBadString = "<invalid>";
496 std::stringstream Result;
Alexey Samsonovcd014722014-05-17 00:07:48 +0000497 if (Opts.PrintFunctions != FunctionNameKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000498 std::string FunctionName = LineInfo.FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000499 if (FunctionName == kDILineInfoBadString)
500 FunctionName = kBadString;
Alexey Samsonov601beb72013-06-28 12:06:25 +0000501 else if (Opts.Demangle)
502 FunctionName = DemangleName(FunctionName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000503 Result << FunctionName << "\n";
504 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000505 std::string Filename = LineInfo.FileName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000506 if (Filename == kDILineInfoBadString)
507 Filename = kBadString;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000508 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000509 return Result.str();
510}
511
512#if !defined(_MSC_VER)
513// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
514extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
515 size_t *length, int *status);
516#endif
517
Alexey Samsonov601beb72013-06-28 12:06:25 +0000518std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000519#if !defined(_MSC_VER)
Ed Masteef6fed72014-01-16 17:25:12 +0000520 // We can spoil names of symbols with C linkage, so use an heuristic
521 // approach to check if the name should be demangled.
522 if (Name.substr(0, 2) != "_Z")
523 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000524 int status = 0;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000525 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000526 if (status != 0)
Alexey Samsonov601beb72013-06-28 12:06:25 +0000527 return Name;
528 std::string Result = DemangledName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000529 free(DemangledName);
Alexey Samsonov601beb72013-06-28 12:06:25 +0000530 return Result;
531#else
Zachary Turnerc007aa42015-05-06 22:26:30 +0000532 char DemangledName[1024] = {0};
533 DWORD result = ::UnDecorateSymbolName(
534 Name.c_str(), DemangledName, 1023,
535 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
536 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
537 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
538 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
539 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
540 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
541
542 return (result == 0) ? Name : std::string(DemangledName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000543#endif
544}
545
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000546} // namespace symbolize
547} // namespace llvm