blob: 33c3a3afef95b39d8494cea9e288e8a043cd0e8c [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) {
Alexey Samsonova5f07682014-02-26 13:10:01 +000083 SymbolRef::Type SymbolType;
Alexey Samsonov464d2e42014-03-17 07:28:19 +000084 if (error(Symbol.getType(SymbolType)))
Alexey Samsonova5f07682014-02-26 13:10:01 +000085 return;
Alexey Samsonov464d2e42014-03-17 07:28:19 +000086 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
Alexey Samsonova5f07682014-02-26 13:10:01 +000087 return;
88 uint64_t SymbolAddress;
Alexey Samsonov464d2e42014-03-17 07:28:19 +000089 if (error(Symbol.getAddress(SymbolAddress)) ||
Rafael Espindolad7a32ea2015-06-24 10:20:30 +000090 SymbolAddress == UnknownAddress)
Alexey Samsonova5f07682014-02-26 13:10:01 +000091 return;
Jay Foad52695da2014-11-07 09:08:39 +000092 if (OpdExtractor) {
93 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
94 // function descriptors. The first word of the descriptor is a pointer to
95 // the function's code.
96 // For the purposes of symbolization, pretend the symbol's address is that
97 // of the function's code, not the descriptor.
98 uint64_t OpdOffset = SymbolAddress - OpdAddress;
99 uint32_t OpdOffset32 = OpdOffset;
100 if (OpdOffset == OpdOffset32 &&
101 OpdExtractor->isValidOffsetForAddress(OpdOffset32))
102 SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
103 }
Alexey Samsonova5f07682014-02-26 13:10:01 +0000104 StringRef SymbolName;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000105 if (error(Symbol.getName(SymbolName)))
Alexey Samsonova5f07682014-02-26 13:10:01 +0000106 return;
107 // Mach-O symbol table names have leading underscore, skip it.
108 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
109 SymbolName = SymbolName.drop_front();
110 // FIXME: If a function has alias, there are two entries in symbol table
111 // with same address size. Make sure we choose the correct one.
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000112 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
Alexey Samsonova5f07682014-02-26 13:10:01 +0000113 SymbolDesc SD = { SymbolAddress, SymbolSize };
114 M.insert(std::make_pair(SD, SymbolName));
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000115}
116
117bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
118 std::string &Name, uint64_t &Addr,
119 uint64_t &Size) const {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000120 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
121 if (SymbolMap.empty())
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000122 return false;
Alexey Samsonov5239d582013-06-04 07:57:38 +0000123 SymbolDesc SD = { Address, Address };
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000124 auto SymbolIterator = SymbolMap.upper_bound(SD);
125 if (SymbolIterator == SymbolMap.begin())
Alexey Samsonov35c987d2013-06-07 15:25:27 +0000126 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000127 --SymbolIterator;
128 if (SymbolIterator->first.Size != 0 &&
129 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000130 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000131 Name = SymbolIterator->second.str();
132 Addr = SymbolIterator->first.Addr;
133 Size = SymbolIterator->first.Size;
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000134 return true;
135}
136
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000137DILineInfo ModuleInfo::symbolizeCode(
138 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000139 DILineInfo LineInfo;
140 if (DebugInfoContext) {
141 LineInfo = DebugInfoContext->getLineInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000142 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000143 }
144 // Override function name from symbol table if necessary.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000145 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000146 std::string FunctionName;
147 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000148 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
149 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000150 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000151 }
152 }
153 return LineInfo;
154}
155
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000156DIInliningInfo ModuleInfo::symbolizeInlinedCode(
157 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000158 DIInliningInfo InlinedContext;
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000159
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000160 if (DebugInfoContext) {
161 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000162 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000163 }
164 // Make sure there is at least one frame in context.
165 if (InlinedContext.getNumberOfFrames() == 0) {
166 InlinedContext.addFrame(DILineInfo());
167 }
168 // Override the function name in lower frame with name from symbol table.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000169 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000170 DIInliningInfo PatchedInlinedContext;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000171 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000172 DILineInfo LineInfo = InlinedContext.getFrame(i);
173 if (i == n - 1) {
174 std::string FunctionName;
175 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000176 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
177 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000178 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000179 }
180 }
181 PatchedInlinedContext.addFrame(LineInfo);
182 }
183 InlinedContext = PatchedInlinedContext;
184 }
185 return InlinedContext;
186}
187
188bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
189 uint64_t &Start, uint64_t &Size) const {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000190 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
191 Size);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000192}
193
Alexey Samsonovd6cef102013-02-04 15:55:26 +0000194const char LLVMSymbolizer::kBadString[] = "??";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000195
196std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
197 uint64_t ModuleOffset) {
198 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000199 if (!Info)
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000200 return printDILineInfo(DILineInfo());
201 if (Opts.PrintInlining) {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000202 DIInliningInfo InlinedContext =
203 Info->symbolizeInlinedCode(ModuleOffset, Opts);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000204 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
205 assert(FramesNum > 0);
206 std::string Result;
207 for (uint32_t i = 0; i < FramesNum; i++) {
208 DILineInfo LineInfo = InlinedContext.getFrame(i);
209 Result += printDILineInfo(LineInfo);
210 }
211 return Result;
212 }
213 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
214 return printDILineInfo(LineInfo);
215}
216
217std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
218 uint64_t ModuleOffset) {
219 std::string Name = kBadString;
220 uint64_t Start = 0;
221 uint64_t Size = 0;
222 if (Opts.UseSymbolTable) {
223 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
Alexey Samsonov601beb72013-06-28 12:06:25 +0000224 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
Ed Masteef6fed72014-01-16 17:25:12 +0000225 Name = DemangleName(Name);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000226 }
227 }
228 std::stringstream ss;
229 ss << Name << "\n" << Start << " " << Size << "\n";
230 return ss.str();
231}
232
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000233void LLVMSymbolizer::flush() {
Alexey Samsonovdd71c5b2013-03-19 15:33:18 +0000234 DeleteContainerSeconds(Modules);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000235 ObjectPairForPathArch.clear();
Alexey Samsonovfe3a5d92013-06-28 15:08:29 +0000236 ObjectFileForArch.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000237}
238
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000239// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
240// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
241// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
242// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
243static
244std::string getDarwinDWARFResourceForPath(
245 const std::string &Path, const std::string &Basename) {
246 SmallString<16> ResourceName = StringRef(Path);
247 if (sys::path::extension(Path) != ".dSYM") {
248 ResourceName += ".dSYM";
249 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000250 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
251 sys::path::append(ResourceName, Basename);
252 return ResourceName.str();
253}
254
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000255static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000256 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
257 MemoryBuffer::getFileOrSTDIN(Path);
258 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000259 return false;
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000260 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000261}
262
263static bool findDebugBinary(const std::string &OrigPath,
264 const std::string &DebuglinkName, uint32_t CRCHash,
265 std::string &Result) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000266 std::string OrigRealPath = OrigPath;
267#if defined(HAVE_REALPATH)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000268 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000269 OrigRealPath = RP;
270 free(RP);
271 }
272#endif
273 SmallString<16> OrigDir(OrigRealPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000274 llvm::sys::path::remove_filename(OrigDir);
275 SmallString<16> DebugPath = OrigDir;
276 // Try /path/to/original_binary/debuglink_name
277 llvm::sys::path::append(DebugPath, DebuglinkName);
278 if (checkFileCRC(DebugPath, CRCHash)) {
279 Result = DebugPath.str();
280 return true;
281 }
282 // Try /path/to/original_binary/.debug/debuglink_name
Alexey Samsonova591ae62013-08-26 18:12:03 +0000283 DebugPath = OrigRealPath;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000284 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
285 if (checkFileCRC(DebugPath, CRCHash)) {
286 Result = DebugPath.str();
287 return true;
288 }
289 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
290 DebugPath = "/usr/lib/debug";
291 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
292 DebuglinkName);
293 if (checkFileCRC(DebugPath, CRCHash)) {
294 Result = DebugPath.str();
295 return true;
296 }
297 return false;
298}
299
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000300static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000301 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000302 if (!Obj)
303 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000304 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000305 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000306 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000307 Name = Name.substr(Name.find_first_not_of("._"));
308 if (Name == "gnu_debuglink") {
309 StringRef Data;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000310 Section.getContents(Data);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000311 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
312 uint32_t Offset = 0;
313 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
314 // 4-byte align the offset.
315 Offset = (Offset + 3) & ~0x3;
316 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
317 DebugName = DebugNameStr;
318 CRCHash = DE.getU32(&Offset);
319 return true;
320 }
321 }
322 break;
323 }
324 }
325 return false;
326}
327
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000328static
329bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
330 const MachOObjectFile *Obj) {
331 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
332 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
333 if (dbg_uuid.empty() || bin_uuid.empty())
334 return false;
335 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
336}
337
338ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
339 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
340 // On Darwin we may find DWARF in separate object file in
341 // resource directory.
342 std::vector<std::string> DsymPaths;
343 StringRef Filename = sys::path::filename(ExePath);
344 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
345 for (const auto &Path : Opts.DsymHints) {
346 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
347 }
348 for (const auto &path : DsymPaths) {
349 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
350 std::error_code EC = BinaryOrErr.getError();
351 if (EC != errc::no_such_file_or_directory && !error(EC)) {
352 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
353 ObjectFile *DbgObj =
Lang Hamesf04de6e2014-10-31 21:37:49 +0000354 getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000355 const MachOObjectFile *MachDbgObj =
356 dyn_cast<const MachOObjectFile>(DbgObj);
357 if (!MachDbgObj) continue;
358 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000359 addOwningBinary(std::move(B));
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000360 return DbgObj;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000361 }
362 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000363 }
364 return nullptr;
365}
366
367LLVMSymbolizer::ObjectPair
368LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
369 const std::string &ArchName) {
370 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
371 if (I != ObjectPairForPathArch.end())
372 return I->second;
373 ObjectFile *Obj = nullptr;
374 ObjectFile *DbgObj = nullptr;
375 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
376 if (!error(BinaryOrErr.getError())) {
377 OwningBinary<Binary> &B = BinaryOrErr.get();
Lang Hamesf04de6e2014-10-31 21:37:49 +0000378 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000379 if (!Obj) {
380 ObjectPair Res = std::make_pair(nullptr, nullptr);
381 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
382 return Res;
383 }
384 addOwningBinary(std::move(B));
385 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
386 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000387 // Try to locate the debug binary using .gnu_debuglink section.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000388 if (!DbgObj) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000389 std::string DebuglinkName;
390 uint32_t CRCHash;
391 std::string DebugBinaryPath;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000392 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
Rafael Espindola63da2952014-01-15 19:37:43 +0000393 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
394 BinaryOrErr = createBinary(DebugBinaryPath);
395 if (!error(BinaryOrErr.getError())) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000396 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
Lang Hamesf04de6e2014-10-31 21:37:49 +0000397 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000398 addOwningBinary(std::move(B));
Rafael Espindola63da2952014-01-15 19:37:43 +0000399 }
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000400 }
401 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000402 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000403 if (!DbgObj)
404 DbgObj = Obj;
405 ObjectPair Res = std::make_pair(Obj, DbgObj);
406 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000407 return Res;
408}
409
410ObjectFile *
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000411LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
412 const std::string &ArchName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000413 if (!Bin)
414 return nullptr;
415 ObjectFile *Res = nullptr;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000416 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000417 const auto &I = ObjectFileForArch.find(
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000418 std::make_pair(UB, ArchName));
419 if (I != ObjectFileForArch.end())
420 return I->second;
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000421 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
Frederic Rissebc162a2015-06-22 21:33:24 +0000422 UB->getObjectForArch(ArchName);
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000423 if (ParsedObj) {
424 Res = ParsedObj.get().get();
425 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000426 }
427 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
428 } else if (Bin->isObject()) {
429 Res = cast<ObjectFile>(Bin);
430 }
431 return Res;
432}
433
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000434ModuleInfo *
435LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000436 const auto &I = Modules.find(ModuleName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000437 if (I != Modules.end())
438 return I->second;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000439 std::string BinaryName = ModuleName;
440 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000441 size_t ColonPos = ModuleName.find_last_of(':');
442 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000443 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000444 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000445 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000446 BinaryName = ModuleName.substr(0, ColonPos);
447 ArchName = ArchStr;
448 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000449 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000450 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000451
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000452 if (!Objects.first) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000453 // Failed to find valid object file.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000454 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
455 return nullptr;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000456 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000457 DIContext *Context = nullptr;
458 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
459 // If this is a COFF object, assume it contains PDB debug information. If
460 // we don't find any we will fall back to the DWARF case.
461 std::unique_ptr<IPDBSession> Session;
462 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
463 Objects.first->getFileName(), Session);
Zachary Turnerc007aa42015-05-06 22:26:30 +0000464 if (Error == PDB_ErrorCode::Success) {
465 Context = new PDBContext(*CoffObject, std::move(Session),
466 Opts.RelativeAddresses);
467 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000468 }
469 if (!Context)
470 Context = new DWARFContextInMemory(*Objects.second);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000471 assert(Context);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000472 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000473 Modules.insert(make_pair(ModuleName, Info));
474 return Info;
475}
476
477std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
478 // By default, DILineInfo contains "<invalid>" for function/filename it
479 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
480 static const std::string kDILineInfoBadString = "<invalid>";
481 std::stringstream Result;
Alexey Samsonovcd014722014-05-17 00:07:48 +0000482 if (Opts.PrintFunctions != FunctionNameKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000483 std::string FunctionName = LineInfo.FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000484 if (FunctionName == kDILineInfoBadString)
485 FunctionName = kBadString;
Alexey Samsonov601beb72013-06-28 12:06:25 +0000486 else if (Opts.Demangle)
487 FunctionName = DemangleName(FunctionName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000488 Result << FunctionName << "\n";
489 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000490 std::string Filename = LineInfo.FileName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000491 if (Filename == kDILineInfoBadString)
492 Filename = kBadString;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000493 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000494 return Result.str();
495}
496
497#if !defined(_MSC_VER)
498// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
499extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
500 size_t *length, int *status);
501#endif
502
Alexey Samsonov601beb72013-06-28 12:06:25 +0000503std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000504#if !defined(_MSC_VER)
Ed Masteef6fed72014-01-16 17:25:12 +0000505 // We can spoil names of symbols with C linkage, so use an heuristic
506 // approach to check if the name should be demangled.
507 if (Name.substr(0, 2) != "_Z")
508 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000509 int status = 0;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000510 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000511 if (status != 0)
Alexey Samsonov601beb72013-06-28 12:06:25 +0000512 return Name;
513 std::string Result = DemangledName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000514 free(DemangledName);
Alexey Samsonov601beb72013-06-28 12:06:25 +0000515 return Result;
516#else
Zachary Turnerc007aa42015-05-06 22:26:30 +0000517 char DemangledName[1024] = {0};
518 DWORD result = ::UnDecorateSymbolName(
519 Name.c_str(), DemangledName, 1023,
520 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
521 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
522 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
523 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
524 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
525 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
526
527 return (result == 0) ? Name : std::string(DemangledName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000528#endif
529}
530
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000531} // namespace symbolize
532} // namespace llvm