blob: 143dca4e9ab8b7d4a8e62454e1710b8f79b9d18e [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"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000023#include "llvm/Support/Casting.h"
Alexey Samsonov3e9997f2013-08-14 17:09:30 +000024#include "llvm/Support/Compression.h"
25#include "llvm/Support/DataExtractor.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000026#include "llvm/Support/Errc.h"
Alexey Samsonov5239d582013-06-04 07:57:38 +000027#include "llvm/Support/FileSystem.h"
Alexey Samsonov3e9997f2013-08-14 17:09:30 +000028#include "llvm/Support/MemoryBuffer.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000029#include "llvm/Support/Path.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000030#include <sstream>
Alexey Samsonova591ae62013-08-26 18:12:03 +000031#include <stdlib.h>
Alexey Samsonovea83baf2013-01-22 14:21:19 +000032
Zachary Turnerc007aa42015-05-06 22:26:30 +000033#if defined(_MSC_VER)
34#include <Windows.h>
35#include <DbgHelp.h>
36#endif
37
Alexey Samsonovea83baf2013-01-22 14:21:19 +000038namespace llvm {
39namespace symbolize {
40
Rafael Espindola4453e42942014-06-13 03:07:50 +000041static bool error(std::error_code ec) {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +000042 if (!ec)
43 return false;
Dmitry Vyukovef8fb722013-02-14 13:06:18 +000044 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
45 return true;
46}
47
Alexey Samsonovdce67342014-05-15 21:24:32 +000048static DILineInfoSpecifier
49getDILineInfoSpecifier(const LLVMSymbolizer::Options &Opts) {
50 return DILineInfoSpecifier(
51 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
Alexey Samsonovcd014722014-05-17 00:07:48 +000052 Opts.PrintFunctions);
Alexey Samsonovea83baf2013-01-22 14:21:19 +000053}
54
Dmitry Vyukovef8fb722013-02-14 13:06:18 +000055ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +000056 : Module(Obj), DebugInfoContext(DICtx) {
Jay Foad52695da2014-11-07 09:08:39 +000057 std::unique_ptr<DataExtractor> OpdExtractor;
58 uint64_t OpdAddress = 0;
59 // Find the .opd (function descriptor) section if any, for big-endian
60 // PowerPC64 ELF.
61 if (Module->getArch() == Triple::ppc64) {
62 for (section_iterator Section : Module->sections()) {
63 StringRef Name;
64 if (!error(Section->getName(Name)) && Name == ".opd") {
65 StringRef Data;
66 if (!error(Section->getContents(Data))) {
67 OpdExtractor.reset(new DataExtractor(Data, Module->isLittleEndian(),
68 Module->getBytesInAddress()));
69 OpdAddress = Section->getAddress();
70 }
71 break;
72 }
73 }
74 }
Rafael Espindolad8e96ec2015-06-25 15:06:38 +000075 std::vector<std::pair<SymbolRef, uint64_t>> Symbols =
76 computeSymbolSizes(*Module);
77 for (auto &P : Symbols)
78 addSymbol(P.first, P.second, OpdExtractor.get(), OpdAddress);
Alexey Samsonova5f07682014-02-26 13:10:01 +000079}
80
Rafael Espindolad8e96ec2015-06-25 15:06:38 +000081void ModuleInfo::addSymbol(const SymbolRef &Symbol, uint64_t SymbolSize,
82 DataExtractor *OpdExtractor, uint64_t OpdAddress) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +000083 SymbolRef::Type SymbolType = Symbol.getType();
Alexey Samsonov464d2e42014-03-17 07:28:19 +000084 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
Alexey Samsonova5f07682014-02-26 13:10:01 +000085 return;
86 uint64_t SymbolAddress;
Alexey Samsonov464d2e42014-03-17 07:28:19 +000087 if (error(Symbol.getAddress(SymbolAddress)) ||
Rafael Espindolad7a32ea2015-06-24 10:20:30 +000088 SymbolAddress == UnknownAddress)
Alexey Samsonova5f07682014-02-26 13:10:01 +000089 return;
Jay Foad52695da2014-11-07 09:08:39 +000090 if (OpdExtractor) {
91 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
92 // function descriptors. The first word of the descriptor is a pointer to
93 // the function's code.
94 // For the purposes of symbolization, pretend the symbol's address is that
95 // of the function's code, not the descriptor.
96 uint64_t OpdOffset = SymbolAddress - OpdAddress;
97 uint32_t OpdOffset32 = OpdOffset;
98 if (OpdOffset == OpdOffset32 &&
99 OpdExtractor->isValidOffsetForAddress(OpdOffset32))
100 SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
101 }
Alexey Samsonova5f07682014-02-26 13:10:01 +0000102 StringRef SymbolName;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000103 if (error(Symbol.getName(SymbolName)))
Alexey Samsonova5f07682014-02-26 13:10:01 +0000104 return;
105 // Mach-O symbol table names have leading underscore, skip it.
106 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
107 SymbolName = SymbolName.drop_front();
108 // FIXME: If a function has alias, there are two entries in symbol table
109 // with same address size. Make sure we choose the correct one.
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000110 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
Alexey Samsonova5f07682014-02-26 13:10:01 +0000111 SymbolDesc SD = { SymbolAddress, SymbolSize };
112 M.insert(std::make_pair(SD, SymbolName));
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000113}
114
115bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
116 std::string &Name, uint64_t &Addr,
117 uint64_t &Size) const {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000118 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
119 if (SymbolMap.empty())
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000120 return false;
Alexey Samsonov5239d582013-06-04 07:57:38 +0000121 SymbolDesc SD = { Address, Address };
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000122 auto SymbolIterator = SymbolMap.upper_bound(SD);
123 if (SymbolIterator == SymbolMap.begin())
Alexey Samsonov35c987d2013-06-07 15:25:27 +0000124 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000125 --SymbolIterator;
126 if (SymbolIterator->first.Size != 0 &&
127 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000128 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000129 Name = SymbolIterator->second.str();
130 Addr = SymbolIterator->first.Addr;
131 Size = SymbolIterator->first.Size;
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000132 return true;
133}
134
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000135DILineInfo ModuleInfo::symbolizeCode(
136 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000137 DILineInfo LineInfo;
138 if (DebugInfoContext) {
139 LineInfo = DebugInfoContext->getLineInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000140 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000141 }
142 // Override function name from symbol table if necessary.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000143 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000144 std::string FunctionName;
145 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000146 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
147 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000148 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000149 }
150 }
151 return LineInfo;
152}
153
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000154DIInliningInfo ModuleInfo::symbolizeInlinedCode(
155 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000156 DIInliningInfo InlinedContext;
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000157
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000158 if (DebugInfoContext) {
159 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000160 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000161 }
162 // Make sure there is at least one frame in context.
163 if (InlinedContext.getNumberOfFrames() == 0) {
164 InlinedContext.addFrame(DILineInfo());
165 }
166 // Override the function name in lower frame with name from symbol table.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000167 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000168 DIInliningInfo PatchedInlinedContext;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000169 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000170 DILineInfo LineInfo = InlinedContext.getFrame(i);
171 if (i == n - 1) {
172 std::string FunctionName;
173 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000174 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
175 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000176 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000177 }
178 }
179 PatchedInlinedContext.addFrame(LineInfo);
180 }
181 InlinedContext = PatchedInlinedContext;
182 }
183 return InlinedContext;
184}
185
186bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
187 uint64_t &Start, uint64_t &Size) const {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000188 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
189 Size);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000190}
191
Alexey Samsonovd6cef102013-02-04 15:55:26 +0000192const char LLVMSymbolizer::kBadString[] = "??";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000193
194std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
195 uint64_t ModuleOffset) {
196 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000197 if (!Info)
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000198 return printDILineInfo(DILineInfo());
199 if (Opts.PrintInlining) {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000200 DIInliningInfo InlinedContext =
201 Info->symbolizeInlinedCode(ModuleOffset, Opts);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000202 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
203 assert(FramesNum > 0);
204 std::string Result;
205 for (uint32_t i = 0; i < FramesNum; i++) {
206 DILineInfo LineInfo = InlinedContext.getFrame(i);
207 Result += printDILineInfo(LineInfo);
208 }
209 return Result;
210 }
211 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
212 return printDILineInfo(LineInfo);
213}
214
215std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
216 uint64_t ModuleOffset) {
217 std::string Name = kBadString;
218 uint64_t Start = 0;
219 uint64_t Size = 0;
220 if (Opts.UseSymbolTable) {
221 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
Alexey Samsonov601beb72013-06-28 12:06:25 +0000222 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
Ed Masteef6fed72014-01-16 17:25:12 +0000223 Name = DemangleName(Name);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000224 }
225 }
226 std::stringstream ss;
227 ss << Name << "\n" << Start << " " << Size << "\n";
228 return ss.str();
229}
230
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000231void LLVMSymbolizer::flush() {
Alexey Samsonovdd71c5b2013-03-19 15:33:18 +0000232 DeleteContainerSeconds(Modules);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000233 ObjectPairForPathArch.clear();
Alexey Samsonovfe3a5d92013-06-28 15:08:29 +0000234 ObjectFileForArch.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000235}
236
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000237// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
238// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
239// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
240// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
241static
242std::string getDarwinDWARFResourceForPath(
243 const std::string &Path, const std::string &Basename) {
244 SmallString<16> ResourceName = StringRef(Path);
245 if (sys::path::extension(Path) != ".dSYM") {
246 ResourceName += ".dSYM";
247 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000248 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
249 sys::path::append(ResourceName, Basename);
250 return ResourceName.str();
251}
252
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000253static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000254 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
255 MemoryBuffer::getFileOrSTDIN(Path);
256 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000257 return false;
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000258 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000259}
260
261static bool findDebugBinary(const std::string &OrigPath,
262 const std::string &DebuglinkName, uint32_t CRCHash,
263 std::string &Result) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000264 std::string OrigRealPath = OrigPath;
265#if defined(HAVE_REALPATH)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000266 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000267 OrigRealPath = RP;
268 free(RP);
269 }
270#endif
271 SmallString<16> OrigDir(OrigRealPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000272 llvm::sys::path::remove_filename(OrigDir);
273 SmallString<16> DebugPath = OrigDir;
274 // Try /path/to/original_binary/debuglink_name
275 llvm::sys::path::append(DebugPath, DebuglinkName);
276 if (checkFileCRC(DebugPath, CRCHash)) {
277 Result = DebugPath.str();
278 return true;
279 }
280 // Try /path/to/original_binary/.debug/debuglink_name
Alexey Samsonova591ae62013-08-26 18:12:03 +0000281 DebugPath = OrigRealPath;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000282 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
283 if (checkFileCRC(DebugPath, CRCHash)) {
284 Result = DebugPath.str();
285 return true;
286 }
287 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
288 DebugPath = "/usr/lib/debug";
289 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
290 DebuglinkName);
291 if (checkFileCRC(DebugPath, CRCHash)) {
292 Result = DebugPath.str();
293 return true;
294 }
295 return false;
296}
297
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000298static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000299 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000300 if (!Obj)
301 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000302 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000303 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000304 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000305 Name = Name.substr(Name.find_first_not_of("._"));
306 if (Name == "gnu_debuglink") {
307 StringRef Data;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000308 Section.getContents(Data);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000309 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
310 uint32_t Offset = 0;
311 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
312 // 4-byte align the offset.
313 Offset = (Offset + 3) & ~0x3;
314 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
315 DebugName = DebugNameStr;
316 CRCHash = DE.getU32(&Offset);
317 return true;
318 }
319 }
320 break;
321 }
322 }
323 return false;
324}
325
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000326static
327bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
328 const MachOObjectFile *Obj) {
329 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
330 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
331 if (dbg_uuid.empty() || bin_uuid.empty())
332 return false;
333 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
334}
335
336ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
337 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
338 // On Darwin we may find DWARF in separate object file in
339 // resource directory.
340 std::vector<std::string> DsymPaths;
341 StringRef Filename = sys::path::filename(ExePath);
342 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
343 for (const auto &Path : Opts.DsymHints) {
344 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
345 }
346 for (const auto &path : DsymPaths) {
347 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
348 std::error_code EC = BinaryOrErr.getError();
349 if (EC != errc::no_such_file_or_directory && !error(EC)) {
350 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
351 ObjectFile *DbgObj =
Lang Hamesf04de6e2014-10-31 21:37:49 +0000352 getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000353 const MachOObjectFile *MachDbgObj =
354 dyn_cast<const MachOObjectFile>(DbgObj);
355 if (!MachDbgObj) continue;
356 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000357 addOwningBinary(std::move(B));
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000358 return DbgObj;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000359 }
360 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000361 }
362 return nullptr;
363}
364
365LLVMSymbolizer::ObjectPair
366LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
367 const std::string &ArchName) {
368 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
369 if (I != ObjectPairForPathArch.end())
370 return I->second;
371 ObjectFile *Obj = nullptr;
372 ObjectFile *DbgObj = nullptr;
373 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
374 if (!error(BinaryOrErr.getError())) {
375 OwningBinary<Binary> &B = BinaryOrErr.get();
Lang Hamesf04de6e2014-10-31 21:37:49 +0000376 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000377 if (!Obj) {
378 ObjectPair Res = std::make_pair(nullptr, nullptr);
379 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
380 return Res;
381 }
382 addOwningBinary(std::move(B));
383 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
384 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000385 // Try to locate the debug binary using .gnu_debuglink section.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000386 if (!DbgObj) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000387 std::string DebuglinkName;
388 uint32_t CRCHash;
389 std::string DebugBinaryPath;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000390 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
Rafael Espindola63da2952014-01-15 19:37:43 +0000391 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
392 BinaryOrErr = createBinary(DebugBinaryPath);
393 if (!error(BinaryOrErr.getError())) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000394 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
Lang Hamesf04de6e2014-10-31 21:37:49 +0000395 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000396 addOwningBinary(std::move(B));
Rafael Espindola63da2952014-01-15 19:37:43 +0000397 }
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000398 }
399 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000400 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000401 if (!DbgObj)
402 DbgObj = Obj;
403 ObjectPair Res = std::make_pair(Obj, DbgObj);
404 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000405 return Res;
406}
407
408ObjectFile *
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000409LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
410 const std::string &ArchName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000411 if (!Bin)
412 return nullptr;
413 ObjectFile *Res = nullptr;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000414 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000415 const auto &I = ObjectFileForArch.find(
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000416 std::make_pair(UB, ArchName));
417 if (I != ObjectFileForArch.end())
418 return I->second;
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000419 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
Frederic Rissebc162a2015-06-22 21:33:24 +0000420 UB->getObjectForArch(ArchName);
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000421 if (ParsedObj) {
422 Res = ParsedObj.get().get();
423 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000424 }
425 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
426 } else if (Bin->isObject()) {
427 Res = cast<ObjectFile>(Bin);
428 }
429 return Res;
430}
431
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000432ModuleInfo *
433LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000434 const auto &I = Modules.find(ModuleName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000435 if (I != Modules.end())
436 return I->second;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000437 std::string BinaryName = ModuleName;
438 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000439 size_t ColonPos = ModuleName.find_last_of(':');
440 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000441 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000442 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000443 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000444 BinaryName = ModuleName.substr(0, ColonPos);
445 ArchName = ArchStr;
446 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000447 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000448 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000449
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000450 if (!Objects.first) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000451 // Failed to find valid object file.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000452 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
453 return nullptr;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000454 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000455 DIContext *Context = nullptr;
456 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
457 // If this is a COFF object, assume it contains PDB debug information. If
458 // we don't find any we will fall back to the DWARF case.
459 std::unique_ptr<IPDBSession> Session;
460 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
461 Objects.first->getFileName(), Session);
Zachary Turnerc007aa42015-05-06 22:26:30 +0000462 if (Error == PDB_ErrorCode::Success) {
463 Context = new PDBContext(*CoffObject, std::move(Session),
464 Opts.RelativeAddresses);
465 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000466 }
467 if (!Context)
468 Context = new DWARFContextInMemory(*Objects.second);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000469 assert(Context);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000470 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000471 Modules.insert(make_pair(ModuleName, Info));
472 return Info;
473}
474
475std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
476 // By default, DILineInfo contains "<invalid>" for function/filename it
477 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
478 static const std::string kDILineInfoBadString = "<invalid>";
479 std::stringstream Result;
Alexey Samsonovcd014722014-05-17 00:07:48 +0000480 if (Opts.PrintFunctions != FunctionNameKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000481 std::string FunctionName = LineInfo.FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000482 if (FunctionName == kDILineInfoBadString)
483 FunctionName = kBadString;
Alexey Samsonov601beb72013-06-28 12:06:25 +0000484 else if (Opts.Demangle)
485 FunctionName = DemangleName(FunctionName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000486 Result << FunctionName << "\n";
487 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000488 std::string Filename = LineInfo.FileName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000489 if (Filename == kDILineInfoBadString)
490 Filename = kBadString;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000491 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000492 return Result.str();
493}
494
495#if !defined(_MSC_VER)
496// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
497extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
498 size_t *length, int *status);
499#endif
500
Alexey Samsonov601beb72013-06-28 12:06:25 +0000501std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000502#if !defined(_MSC_VER)
Ed Masteef6fed72014-01-16 17:25:12 +0000503 // We can spoil names of symbols with C linkage, so use an heuristic
504 // approach to check if the name should be demangled.
505 if (Name.substr(0, 2) != "_Z")
506 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000507 int status = 0;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000508 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000509 if (status != 0)
Alexey Samsonov601beb72013-06-28 12:06:25 +0000510 return Name;
511 std::string Result = DemangledName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000512 free(DemangledName);
Alexey Samsonov601beb72013-06-28 12:06:25 +0000513 return Result;
514#else
Zachary Turnerc007aa42015-05-06 22:26:30 +0000515 char DemangledName[1024] = {0};
516 DWORD result = ::UnDecorateSymbolName(
517 Name.c_str(), DemangledName, 1023,
518 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
519 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
520 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
521 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
522 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
523 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
524
525 return (result == 0) ? Name : std::string(DemangledName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000526#endif
527}
528
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000529} // namespace symbolize
530} // namespace llvm