blob: b6af342a0bc0ed6ce588a4bfd117d83abd684929 [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)) ||
Rafael Espindolad7a32ea2015-06-24 10:20:30 +000097 SymbolAddress == UnknownAddress)
Alexey Samsonova5f07682014-02-26 13:10:01 +000098 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;
Rafael Espindolad7a32ea2015-06-24 10:20:30 +0000112 // Onyl ELF has a size for every symbol so assume that symbol occupies the
113 // memory range up to the following symbol.
114 if (auto *E = dyn_cast<ELFObjectFileBase>(Module))
115 SymbolSize = E->getSymbolSize(Symbol);
116 else
Alexey Samsonova5f07682014-02-26 13:10:01 +0000117 SymbolSize = 0;
Alexey Samsonova5f07682014-02-26 13:10:01 +0000118 StringRef SymbolName;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000119 if (error(Symbol.getName(SymbolName)))
Alexey Samsonova5f07682014-02-26 13:10:01 +0000120 return;
121 // Mach-O symbol table names have leading underscore, skip it.
122 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
123 SymbolName = SymbolName.drop_front();
124 // FIXME: If a function has alias, there are two entries in symbol table
125 // with same address size. Make sure we choose the correct one.
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000126 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
Alexey Samsonova5f07682014-02-26 13:10:01 +0000127 SymbolDesc SD = { SymbolAddress, SymbolSize };
128 M.insert(std::make_pair(SD, SymbolName));
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000129}
130
131bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
132 std::string &Name, uint64_t &Addr,
133 uint64_t &Size) const {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000134 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
135 if (SymbolMap.empty())
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000136 return false;
Alexey Samsonov5239d582013-06-04 07:57:38 +0000137 SymbolDesc SD = { Address, Address };
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000138 auto SymbolIterator = SymbolMap.upper_bound(SD);
139 if (SymbolIterator == SymbolMap.begin())
Alexey Samsonov35c987d2013-06-07 15:25:27 +0000140 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000141 --SymbolIterator;
142 if (SymbolIterator->first.Size != 0 &&
143 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000144 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000145 Name = SymbolIterator->second.str();
146 Addr = SymbolIterator->first.Addr;
147 Size = SymbolIterator->first.Size;
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000148 return true;
149}
150
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000151DILineInfo ModuleInfo::symbolizeCode(
152 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000153 DILineInfo LineInfo;
154 if (DebugInfoContext) {
155 LineInfo = DebugInfoContext->getLineInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000156 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000157 }
158 // Override function name from symbol table if necessary.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000159 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000160 std::string FunctionName;
161 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000162 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
163 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000164 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000165 }
166 }
167 return LineInfo;
168}
169
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000170DIInliningInfo ModuleInfo::symbolizeInlinedCode(
171 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000172 DIInliningInfo InlinedContext;
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000173
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000174 if (DebugInfoContext) {
175 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000176 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000177 }
178 // Make sure there is at least one frame in context.
179 if (InlinedContext.getNumberOfFrames() == 0) {
180 InlinedContext.addFrame(DILineInfo());
181 }
182 // Override the function name in lower frame with name from symbol table.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000183 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000184 DIInliningInfo PatchedInlinedContext;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000185 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000186 DILineInfo LineInfo = InlinedContext.getFrame(i);
187 if (i == n - 1) {
188 std::string FunctionName;
189 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000190 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
191 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000192 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000193 }
194 }
195 PatchedInlinedContext.addFrame(LineInfo);
196 }
197 InlinedContext = PatchedInlinedContext;
198 }
199 return InlinedContext;
200}
201
202bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
203 uint64_t &Start, uint64_t &Size) const {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000204 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
205 Size);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000206}
207
Alexey Samsonovd6cef102013-02-04 15:55:26 +0000208const char LLVMSymbolizer::kBadString[] = "??";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000209
210std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
211 uint64_t ModuleOffset) {
212 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000213 if (!Info)
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000214 return printDILineInfo(DILineInfo());
215 if (Opts.PrintInlining) {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000216 DIInliningInfo InlinedContext =
217 Info->symbolizeInlinedCode(ModuleOffset, Opts);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000218 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
219 assert(FramesNum > 0);
220 std::string Result;
221 for (uint32_t i = 0; i < FramesNum; i++) {
222 DILineInfo LineInfo = InlinedContext.getFrame(i);
223 Result += printDILineInfo(LineInfo);
224 }
225 return Result;
226 }
227 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
228 return printDILineInfo(LineInfo);
229}
230
231std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
232 uint64_t ModuleOffset) {
233 std::string Name = kBadString;
234 uint64_t Start = 0;
235 uint64_t Size = 0;
236 if (Opts.UseSymbolTable) {
237 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
Alexey Samsonov601beb72013-06-28 12:06:25 +0000238 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
Ed Masteef6fed72014-01-16 17:25:12 +0000239 Name = DemangleName(Name);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000240 }
241 }
242 std::stringstream ss;
243 ss << Name << "\n" << Start << " " << Size << "\n";
244 return ss.str();
245}
246
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000247void LLVMSymbolizer::flush() {
Alexey Samsonovdd71c5b2013-03-19 15:33:18 +0000248 DeleteContainerSeconds(Modules);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000249 ObjectPairForPathArch.clear();
Alexey Samsonovfe3a5d92013-06-28 15:08:29 +0000250 ObjectFileForArch.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000251}
252
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000253// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
254// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
255// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
256// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
257static
258std::string getDarwinDWARFResourceForPath(
259 const std::string &Path, const std::string &Basename) {
260 SmallString<16> ResourceName = StringRef(Path);
261 if (sys::path::extension(Path) != ".dSYM") {
262 ResourceName += ".dSYM";
263 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000264 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
265 sys::path::append(ResourceName, Basename);
266 return ResourceName.str();
267}
268
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000269static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000270 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
271 MemoryBuffer::getFileOrSTDIN(Path);
272 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000273 return false;
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000274 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000275}
276
277static bool findDebugBinary(const std::string &OrigPath,
278 const std::string &DebuglinkName, uint32_t CRCHash,
279 std::string &Result) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000280 std::string OrigRealPath = OrigPath;
281#if defined(HAVE_REALPATH)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000282 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000283 OrigRealPath = RP;
284 free(RP);
285 }
286#endif
287 SmallString<16> OrigDir(OrigRealPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000288 llvm::sys::path::remove_filename(OrigDir);
289 SmallString<16> DebugPath = OrigDir;
290 // Try /path/to/original_binary/debuglink_name
291 llvm::sys::path::append(DebugPath, DebuglinkName);
292 if (checkFileCRC(DebugPath, CRCHash)) {
293 Result = DebugPath.str();
294 return true;
295 }
296 // Try /path/to/original_binary/.debug/debuglink_name
Alexey Samsonova591ae62013-08-26 18:12:03 +0000297 DebugPath = OrigRealPath;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000298 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
299 if (checkFileCRC(DebugPath, CRCHash)) {
300 Result = DebugPath.str();
301 return true;
302 }
303 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
304 DebugPath = "/usr/lib/debug";
305 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
306 DebuglinkName);
307 if (checkFileCRC(DebugPath, CRCHash)) {
308 Result = DebugPath.str();
309 return true;
310 }
311 return false;
312}
313
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000314static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000315 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000316 if (!Obj)
317 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000318 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000319 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000320 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000321 Name = Name.substr(Name.find_first_not_of("._"));
322 if (Name == "gnu_debuglink") {
323 StringRef Data;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000324 Section.getContents(Data);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000325 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
326 uint32_t Offset = 0;
327 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
328 // 4-byte align the offset.
329 Offset = (Offset + 3) & ~0x3;
330 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
331 DebugName = DebugNameStr;
332 CRCHash = DE.getU32(&Offset);
333 return true;
334 }
335 }
336 break;
337 }
338 }
339 return false;
340}
341
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000342static
343bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
344 const MachOObjectFile *Obj) {
345 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
346 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
347 if (dbg_uuid.empty() || bin_uuid.empty())
348 return false;
349 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
350}
351
352ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
353 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
354 // On Darwin we may find DWARF in separate object file in
355 // resource directory.
356 std::vector<std::string> DsymPaths;
357 StringRef Filename = sys::path::filename(ExePath);
358 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
359 for (const auto &Path : Opts.DsymHints) {
360 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
361 }
362 for (const auto &path : DsymPaths) {
363 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
364 std::error_code EC = BinaryOrErr.getError();
365 if (EC != errc::no_such_file_or_directory && !error(EC)) {
366 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
367 ObjectFile *DbgObj =
Lang Hamesf04de6e2014-10-31 21:37:49 +0000368 getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000369 const MachOObjectFile *MachDbgObj =
370 dyn_cast<const MachOObjectFile>(DbgObj);
371 if (!MachDbgObj) continue;
372 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000373 addOwningBinary(std::move(B));
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000374 return DbgObj;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000375 }
376 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000377 }
378 return nullptr;
379}
380
381LLVMSymbolizer::ObjectPair
382LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
383 const std::string &ArchName) {
384 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
385 if (I != ObjectPairForPathArch.end())
386 return I->second;
387 ObjectFile *Obj = nullptr;
388 ObjectFile *DbgObj = nullptr;
389 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
390 if (!error(BinaryOrErr.getError())) {
391 OwningBinary<Binary> &B = BinaryOrErr.get();
Lang Hamesf04de6e2014-10-31 21:37:49 +0000392 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000393 if (!Obj) {
394 ObjectPair Res = std::make_pair(nullptr, nullptr);
395 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
396 return Res;
397 }
398 addOwningBinary(std::move(B));
399 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
400 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000401 // Try to locate the debug binary using .gnu_debuglink section.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000402 if (!DbgObj) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000403 std::string DebuglinkName;
404 uint32_t CRCHash;
405 std::string DebugBinaryPath;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000406 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
Rafael Espindola63da2952014-01-15 19:37:43 +0000407 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
408 BinaryOrErr = createBinary(DebugBinaryPath);
409 if (!error(BinaryOrErr.getError())) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000410 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
Lang Hamesf04de6e2014-10-31 21:37:49 +0000411 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000412 addOwningBinary(std::move(B));
Rafael Espindola63da2952014-01-15 19:37:43 +0000413 }
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000414 }
415 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000416 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000417 if (!DbgObj)
418 DbgObj = Obj;
419 ObjectPair Res = std::make_pair(Obj, DbgObj);
420 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000421 return Res;
422}
423
424ObjectFile *
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000425LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
426 const std::string &ArchName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000427 if (!Bin)
428 return nullptr;
429 ObjectFile *Res = nullptr;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000430 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000431 const auto &I = ObjectFileForArch.find(
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000432 std::make_pair(UB, ArchName));
433 if (I != ObjectFileForArch.end())
434 return I->second;
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000435 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
Frederic Rissebc162a2015-06-22 21:33:24 +0000436 UB->getObjectForArch(ArchName);
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000437 if (ParsedObj) {
438 Res = ParsedObj.get().get();
439 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000440 }
441 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
442 } else if (Bin->isObject()) {
443 Res = cast<ObjectFile>(Bin);
444 }
445 return Res;
446}
447
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000448ModuleInfo *
449LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000450 const auto &I = Modules.find(ModuleName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000451 if (I != Modules.end())
452 return I->second;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000453 std::string BinaryName = ModuleName;
454 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000455 size_t ColonPos = ModuleName.find_last_of(':');
456 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000457 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000458 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000459 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000460 BinaryName = ModuleName.substr(0, ColonPos);
461 ArchName = ArchStr;
462 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000463 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000464 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000465
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000466 if (!Objects.first) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000467 // Failed to find valid object file.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000468 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
469 return nullptr;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000470 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000471 DIContext *Context = nullptr;
472 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
473 // If this is a COFF object, assume it contains PDB debug information. If
474 // we don't find any we will fall back to the DWARF case.
475 std::unique_ptr<IPDBSession> Session;
476 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
477 Objects.first->getFileName(), Session);
Zachary Turnerc007aa42015-05-06 22:26:30 +0000478 if (Error == PDB_ErrorCode::Success) {
479 Context = new PDBContext(*CoffObject, std::move(Session),
480 Opts.RelativeAddresses);
481 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000482 }
483 if (!Context)
484 Context = new DWARFContextInMemory(*Objects.second);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000485 assert(Context);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000486 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000487 Modules.insert(make_pair(ModuleName, Info));
488 return Info;
489}
490
491std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
492 // By default, DILineInfo contains "<invalid>" for function/filename it
493 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
494 static const std::string kDILineInfoBadString = "<invalid>";
495 std::stringstream Result;
Alexey Samsonovcd014722014-05-17 00:07:48 +0000496 if (Opts.PrintFunctions != FunctionNameKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000497 std::string FunctionName = LineInfo.FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000498 if (FunctionName == kDILineInfoBadString)
499 FunctionName = kBadString;
Alexey Samsonov601beb72013-06-28 12:06:25 +0000500 else if (Opts.Demangle)
501 FunctionName = DemangleName(FunctionName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000502 Result << FunctionName << "\n";
503 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000504 std::string Filename = LineInfo.FileName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000505 if (Filename == kDILineInfoBadString)
506 Filename = kBadString;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000507 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000508 return Result.str();
509}
510
511#if !defined(_MSC_VER)
512// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
513extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
514 size_t *length, int *status);
515#endif
516
Alexey Samsonov601beb72013-06-28 12:06:25 +0000517std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000518#if !defined(_MSC_VER)
Ed Masteef6fed72014-01-16 17:25:12 +0000519 // We can spoil names of symbols with C linkage, so use an heuristic
520 // approach to check if the name should be demangled.
521 if (Name.substr(0, 2) != "_Z")
522 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000523 int status = 0;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000524 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000525 if (status != 0)
Alexey Samsonov601beb72013-06-28 12:06:25 +0000526 return Name;
527 std::string Result = DemangledName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000528 free(DemangledName);
Alexey Samsonov601beb72013-06-28 12:06:25 +0000529 return Result;
530#else
Zachary Turnerc007aa42015-05-06 22:26:30 +0000531 char DemangledName[1024] = {0};
532 DWORD result = ::UnDecorateSymbolName(
533 Name.c_str(), DemangledName, 1023,
534 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
535 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
536 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
537 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
538 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
539 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
540
541 return (result == 0) ? Name : std::string(DemangledName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000542#endif
543}
544
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000545} // namespace symbolize
546} // namespace llvm