blob: 326cab5a186041d827caf24eeddb7c5f7a0b93e9 [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
32namespace llvm {
33namespace symbolize {
34
Rafael Espindola4453e42942014-06-13 03:07:50 +000035static bool error(std::error_code ec) {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +000036 if (!ec)
37 return false;
Dmitry Vyukovef8fb722013-02-14 13:06:18 +000038 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
39 return true;
40}
41
Alexey Samsonovdce67342014-05-15 21:24:32 +000042static DILineInfoSpecifier
43getDILineInfoSpecifier(const LLVMSymbolizer::Options &Opts) {
44 return DILineInfoSpecifier(
45 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
Alexey Samsonovcd014722014-05-17 00:07:48 +000046 Opts.PrintFunctions);
Alexey Samsonovea83baf2013-01-22 14:21:19 +000047}
48
Dmitry Vyukovef8fb722013-02-14 13:06:18 +000049ModuleInfo::ModuleInfo(ObjectFile *Obj, DIContext *DICtx)
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +000050 : Module(Obj), DebugInfoContext(DICtx) {
Jay Foad52695da2014-11-07 09:08:39 +000051 std::unique_ptr<DataExtractor> OpdExtractor;
52 uint64_t OpdAddress = 0;
53 // Find the .opd (function descriptor) section if any, for big-endian
54 // PowerPC64 ELF.
55 if (Module->getArch() == Triple::ppc64) {
56 for (section_iterator Section : Module->sections()) {
57 StringRef Name;
58 if (!error(Section->getName(Name)) && Name == ".opd") {
59 StringRef Data;
60 if (!error(Section->getContents(Data))) {
61 OpdExtractor.reset(new DataExtractor(Data, Module->isLittleEndian(),
62 Module->getBytesInAddress()));
63 OpdAddress = Section->getAddress();
64 }
65 break;
66 }
67 }
68 }
Alexey Samsonov464d2e42014-03-17 07:28:19 +000069 for (const SymbolRef &Symbol : Module->symbols()) {
Jay Foad52695da2014-11-07 09:08:39 +000070 addSymbol(Symbol, OpdExtractor.get(), OpdAddress);
Dmitry Vyukovef8fb722013-02-14 13:06:18 +000071 }
Alexey Samsonova5f07682014-02-26 13:10:01 +000072 bool NoSymbolTable = (Module->symbol_begin() == Module->symbol_end());
73 if (NoSymbolTable && Module->isELF()) {
74 // Fallback to dynamic symbol table, if regular symbol table is stripped.
75 std::pair<symbol_iterator, symbol_iterator> IDyn =
76 getELFDynamicSymbolIterators(Module);
77 for (symbol_iterator si = IDyn.first, se = IDyn.second; si != se; ++si) {
Jay Foad52695da2014-11-07 09:08:39 +000078 addSymbol(*si, OpdExtractor.get(), OpdAddress);
Alexey Samsonova5f07682014-02-26 13:10:01 +000079 }
80 }
81}
82
Jay Foad52695da2014-11-07 09:08:39 +000083void ModuleInfo::addSymbol(const SymbolRef &Symbol, DataExtractor *OpdExtractor,
84 uint64_t OpdAddress) {
Alexey Samsonova5f07682014-02-26 13:10:01 +000085 SymbolRef::Type SymbolType;
Alexey Samsonov464d2e42014-03-17 07:28:19 +000086 if (error(Symbol.getType(SymbolType)))
Alexey Samsonova5f07682014-02-26 13:10:01 +000087 return;
Alexey Samsonov464d2e42014-03-17 07:28:19 +000088 if (SymbolType != SymbolRef::ST_Function && SymbolType != SymbolRef::ST_Data)
Alexey Samsonova5f07682014-02-26 13:10:01 +000089 return;
90 uint64_t SymbolAddress;
Alexey Samsonov464d2e42014-03-17 07:28:19 +000091 if (error(Symbol.getAddress(SymbolAddress)) ||
Alexey Samsonova5f07682014-02-26 13:10:01 +000092 SymbolAddress == UnknownAddressOrSize)
93 return;
Jay Foad52695da2014-11-07 09:08:39 +000094 if (OpdExtractor) {
95 // For big-endian PowerPC64 ELF, symbols in the .opd section refer to
96 // function descriptors. The first word of the descriptor is a pointer to
97 // the function's code.
98 // For the purposes of symbolization, pretend the symbol's address is that
99 // of the function's code, not the descriptor.
100 uint64_t OpdOffset = SymbolAddress - OpdAddress;
101 uint32_t OpdOffset32 = OpdOffset;
102 if (OpdOffset == OpdOffset32 &&
103 OpdExtractor->isValidOffsetForAddress(OpdOffset32))
104 SymbolAddress = OpdExtractor->getAddress(&OpdOffset32);
105 }
Alexey Samsonova5f07682014-02-26 13:10:01 +0000106 uint64_t SymbolSize;
107 // Getting symbol size is linear for Mach-O files, so assume that symbol
108 // occupies the memory range up to the following symbol.
109 if (isa<MachOObjectFile>(Module))
110 SymbolSize = 0;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000111 else if (error(Symbol.getSize(SymbolSize)) ||
Alexey Samsonova5f07682014-02-26 13:10:01 +0000112 SymbolSize == UnknownAddressOrSize)
113 return;
114 StringRef SymbolName;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000115 if (error(Symbol.getName(SymbolName)))
Alexey Samsonova5f07682014-02-26 13:10:01 +0000116 return;
117 // Mach-O symbol table names have leading underscore, skip it.
118 if (Module->isMachO() && SymbolName.size() > 0 && SymbolName[0] == '_')
119 SymbolName = SymbolName.drop_front();
120 // FIXME: If a function has alias, there are two entries in symbol table
121 // with same address size. Make sure we choose the correct one.
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000122 auto &M = SymbolType == SymbolRef::ST_Function ? Functions : Objects;
Alexey Samsonova5f07682014-02-26 13:10:01 +0000123 SymbolDesc SD = { SymbolAddress, SymbolSize };
124 M.insert(std::make_pair(SD, SymbolName));
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000125}
126
127bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
128 std::string &Name, uint64_t &Addr,
129 uint64_t &Size) const {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000130 const auto &SymbolMap = Type == SymbolRef::ST_Function ? Functions : Objects;
131 if (SymbolMap.empty())
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000132 return false;
Alexey Samsonov5239d582013-06-04 07:57:38 +0000133 SymbolDesc SD = { Address, Address };
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000134 auto SymbolIterator = SymbolMap.upper_bound(SD);
135 if (SymbolIterator == SymbolMap.begin())
Alexey Samsonov35c987d2013-06-07 15:25:27 +0000136 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000137 --SymbolIterator;
138 if (SymbolIterator->first.Size != 0 &&
139 SymbolIterator->first.Addr + SymbolIterator->first.Size <= Address)
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000140 return false;
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000141 Name = SymbolIterator->second.str();
142 Addr = SymbolIterator->first.Addr;
143 Size = SymbolIterator->first.Size;
Dmitry Vyukovef8fb722013-02-14 13:06:18 +0000144 return true;
145}
146
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000147DILineInfo ModuleInfo::symbolizeCode(
148 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000149 DILineInfo LineInfo;
150 if (DebugInfoContext) {
151 LineInfo = DebugInfoContext->getLineInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000152 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000153 }
154 // Override function name from symbol table if necessary.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000155 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000156 std::string FunctionName;
157 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000158 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
159 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000160 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000161 }
162 }
163 return LineInfo;
164}
165
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000166DIInliningInfo ModuleInfo::symbolizeInlinedCode(
167 uint64_t ModuleOffset, const LLVMSymbolizer::Options &Opts) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000168 DIInliningInfo InlinedContext;
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000169
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000170 if (DebugInfoContext) {
171 InlinedContext = DebugInfoContext->getInliningInfoForAddress(
Alexey Samsonovdce67342014-05-15 21:24:32 +0000172 ModuleOffset, getDILineInfoSpecifier(Opts));
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000173 }
174 // Make sure there is at least one frame in context.
175 if (InlinedContext.getNumberOfFrames() == 0) {
176 InlinedContext.addFrame(DILineInfo());
177 }
178 // Override the function name in lower frame with name from symbol table.
Alexey Samsonovcd014722014-05-17 00:07:48 +0000179 if (Opts.PrintFunctions != FunctionNameKind::None && Opts.UseSymbolTable) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000180 DIInliningInfo PatchedInlinedContext;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000181 for (uint32_t i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000182 DILineInfo LineInfo = InlinedContext.getFrame(i);
183 if (i == n - 1) {
184 std::string FunctionName;
185 uint64_t Start, Size;
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000186 if (getNameFromSymbolTable(SymbolRef::ST_Function, ModuleOffset,
187 FunctionName, Start, Size)) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000188 LineInfo.FunctionName = FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000189 }
190 }
191 PatchedInlinedContext.addFrame(LineInfo);
192 }
193 InlinedContext = PatchedInlinedContext;
194 }
195 return InlinedContext;
196}
197
198bool ModuleInfo::symbolizeData(uint64_t ModuleOffset, std::string &Name,
199 uint64_t &Start, uint64_t &Size) const {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000200 return getNameFromSymbolTable(SymbolRef::ST_Data, ModuleOffset, Name, Start,
201 Size);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000202}
203
Alexey Samsonovd6cef102013-02-04 15:55:26 +0000204const char LLVMSymbolizer::kBadString[] = "??";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000205
206std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
207 uint64_t ModuleOffset) {
208 ModuleInfo *Info = getOrCreateModuleInfo(ModuleName);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000209 if (!Info)
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000210 return printDILineInfo(DILineInfo());
211 if (Opts.PrintInlining) {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000212 DIInliningInfo InlinedContext =
213 Info->symbolizeInlinedCode(ModuleOffset, Opts);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000214 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
215 assert(FramesNum > 0);
216 std::string Result;
217 for (uint32_t i = 0; i < FramesNum; i++) {
218 DILineInfo LineInfo = InlinedContext.getFrame(i);
219 Result += printDILineInfo(LineInfo);
220 }
221 return Result;
222 }
223 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts);
224 return printDILineInfo(LineInfo);
225}
226
227std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
228 uint64_t ModuleOffset) {
229 std::string Name = kBadString;
230 uint64_t Start = 0;
231 uint64_t Size = 0;
232 if (Opts.UseSymbolTable) {
233 if (ModuleInfo *Info = getOrCreateModuleInfo(ModuleName)) {
Alexey Samsonov601beb72013-06-28 12:06:25 +0000234 if (Info->symbolizeData(ModuleOffset, Name, Start, Size) && Opts.Demangle)
Ed Masteef6fed72014-01-16 17:25:12 +0000235 Name = DemangleName(Name);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000236 }
237 }
238 std::stringstream ss;
239 ss << Name << "\n" << Start << " " << Size << "\n";
240 return ss.str();
241}
242
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000243void LLVMSymbolizer::flush() {
Alexey Samsonovdd71c5b2013-03-19 15:33:18 +0000244 DeleteContainerSeconds(Modules);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000245 ObjectPairForPathArch.clear();
Alexey Samsonovfe3a5d92013-06-28 15:08:29 +0000246 ObjectFileForArch.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000247}
248
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000249// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
250// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
251// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
252// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
253static
254std::string getDarwinDWARFResourceForPath(
255 const std::string &Path, const std::string &Basename) {
256 SmallString<16> ResourceName = StringRef(Path);
257 if (sys::path::extension(Path) != ".dSYM") {
258 ResourceName += ".dSYM";
259 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000260 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
261 sys::path::append(ResourceName, Basename);
262 return ResourceName.str();
263}
264
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000265static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000266 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
267 MemoryBuffer::getFileOrSTDIN(Path);
268 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000269 return false;
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000270 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000271}
272
273static bool findDebugBinary(const std::string &OrigPath,
274 const std::string &DebuglinkName, uint32_t CRCHash,
275 std::string &Result) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000276 std::string OrigRealPath = OrigPath;
277#if defined(HAVE_REALPATH)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000278 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000279 OrigRealPath = RP;
280 free(RP);
281 }
282#endif
283 SmallString<16> OrigDir(OrigRealPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000284 llvm::sys::path::remove_filename(OrigDir);
285 SmallString<16> DebugPath = OrigDir;
286 // Try /path/to/original_binary/debuglink_name
287 llvm::sys::path::append(DebugPath, DebuglinkName);
288 if (checkFileCRC(DebugPath, CRCHash)) {
289 Result = DebugPath.str();
290 return true;
291 }
292 // Try /path/to/original_binary/.debug/debuglink_name
Alexey Samsonova591ae62013-08-26 18:12:03 +0000293 DebugPath = OrigRealPath;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000294 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
295 if (checkFileCRC(DebugPath, CRCHash)) {
296 Result = DebugPath.str();
297 return true;
298 }
299 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
300 DebugPath = "/usr/lib/debug";
301 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
302 DebuglinkName);
303 if (checkFileCRC(DebugPath, CRCHash)) {
304 Result = DebugPath.str();
305 return true;
306 }
307 return false;
308}
309
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000310static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000311 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000312 if (!Obj)
313 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000314 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000315 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000316 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000317 Name = Name.substr(Name.find_first_not_of("._"));
318 if (Name == "gnu_debuglink") {
319 StringRef Data;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000320 Section.getContents(Data);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000321 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
322 uint32_t Offset = 0;
323 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
324 // 4-byte align the offset.
325 Offset = (Offset + 3) & ~0x3;
326 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
327 DebugName = DebugNameStr;
328 CRCHash = DE.getU32(&Offset);
329 return true;
330 }
331 }
332 break;
333 }
334 }
335 return false;
336}
337
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000338static
339bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
340 const MachOObjectFile *Obj) {
341 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
342 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
343 if (dbg_uuid.empty() || bin_uuid.empty())
344 return false;
345 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
346}
347
348ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
349 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
350 // On Darwin we may find DWARF in separate object file in
351 // resource directory.
352 std::vector<std::string> DsymPaths;
353 StringRef Filename = sys::path::filename(ExePath);
354 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
355 for (const auto &Path : Opts.DsymHints) {
356 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
357 }
358 for (const auto &path : DsymPaths) {
359 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
360 std::error_code EC = BinaryOrErr.getError();
361 if (EC != errc::no_such_file_or_directory && !error(EC)) {
362 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
363 ObjectFile *DbgObj =
Lang Hamesf04de6e2014-10-31 21:37:49 +0000364 getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000365 const MachOObjectFile *MachDbgObj =
366 dyn_cast<const MachOObjectFile>(DbgObj);
367 if (!MachDbgObj) continue;
368 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000369 addOwningBinary(std::move(B));
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000370 return DbgObj;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000371 }
372 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000373 }
374 return nullptr;
375}
376
377LLVMSymbolizer::ObjectPair
378LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
379 const std::string &ArchName) {
380 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
381 if (I != ObjectPairForPathArch.end())
382 return I->second;
383 ObjectFile *Obj = nullptr;
384 ObjectFile *DbgObj = nullptr;
385 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
386 if (!error(BinaryOrErr.getError())) {
387 OwningBinary<Binary> &B = BinaryOrErr.get();
Lang Hamesf04de6e2014-10-31 21:37:49 +0000388 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000389 if (!Obj) {
390 ObjectPair Res = std::make_pair(nullptr, nullptr);
391 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
392 return Res;
393 }
394 addOwningBinary(std::move(B));
395 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
396 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000397 // Try to locate the debug binary using .gnu_debuglink section.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000398 if (!DbgObj) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000399 std::string DebuglinkName;
400 uint32_t CRCHash;
401 std::string DebugBinaryPath;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000402 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
Rafael Espindola63da2952014-01-15 19:37:43 +0000403 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
404 BinaryOrErr = createBinary(DebugBinaryPath);
405 if (!error(BinaryOrErr.getError())) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000406 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
Lang Hamesf04de6e2014-10-31 21:37:49 +0000407 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000408 addOwningBinary(std::move(B));
Rafael Espindola63da2952014-01-15 19:37:43 +0000409 }
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000410 }
411 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000412 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000413 if (!DbgObj)
414 DbgObj = Obj;
415 ObjectPair Res = std::make_pair(Obj, DbgObj);
416 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000417 return Res;
418}
419
420ObjectFile *
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000421LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
422 const std::string &ArchName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000423 if (!Bin)
424 return nullptr;
425 ObjectFile *Res = nullptr;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000426 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000427 const auto &I = ObjectFileForArch.find(
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000428 std::make_pair(UB, ArchName));
429 if (I != ObjectFileForArch.end())
430 return I->second;
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000431 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
432 UB->getObjectForArch(Triple(ArchName).getArch());
433 if (ParsedObj) {
434 Res = ParsedObj.get().get();
435 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000436 }
437 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
438 } else if (Bin->isObject()) {
439 Res = cast<ObjectFile>(Bin);
440 }
441 return Res;
442}
443
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000444ModuleInfo *
445LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000446 const auto &I = Modules.find(ModuleName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000447 if (I != Modules.end())
448 return I->second;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000449 std::string BinaryName = ModuleName;
450 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000451 size_t ColonPos = ModuleName.find_last_of(':');
452 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000453 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000454 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000455 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000456 BinaryName = ModuleName.substr(0, ColonPos);
457 ArchName = ArchStr;
458 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000459 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000460 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000461
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000462 if (!Objects.first) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000463 // Failed to find valid object file.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000464 Modules.insert(make_pair(ModuleName, (ModuleInfo *)nullptr));
465 return nullptr;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000466 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000467 DIContext *Context = nullptr;
468 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
469 // If this is a COFF object, assume it contains PDB debug information. If
470 // we don't find any we will fall back to the DWARF case.
471 std::unique_ptr<IPDBSession> Session;
472 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
473 Objects.first->getFileName(), Session);
474 if (Error == PDB_ErrorCode::Success)
475 Context = new PDBContext(*CoffObject, std::move(Session));
476 }
477 if (!Context)
478 Context = new DWARFContextInMemory(*Objects.second);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000479 assert(Context);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000480 ModuleInfo *Info = new ModuleInfo(Objects.first, Context);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000481 Modules.insert(make_pair(ModuleName, Info));
482 return Info;
483}
484
485std::string LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo) const {
486 // By default, DILineInfo contains "<invalid>" for function/filename it
487 // cannot fetch. We replace it to "??" to make our output closer to addr2line.
488 static const std::string kDILineInfoBadString = "<invalid>";
489 std::stringstream Result;
Alexey Samsonovcd014722014-05-17 00:07:48 +0000490 if (Opts.PrintFunctions != FunctionNameKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000491 std::string FunctionName = LineInfo.FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000492 if (FunctionName == kDILineInfoBadString)
493 FunctionName = kBadString;
Alexey Samsonov601beb72013-06-28 12:06:25 +0000494 else if (Opts.Demangle)
495 FunctionName = DemangleName(FunctionName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000496 Result << FunctionName << "\n";
497 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000498 std::string Filename = LineInfo.FileName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000499 if (Filename == kDILineInfoBadString)
500 Filename = kBadString;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000501 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000502 return Result.str();
503}
504
505#if !defined(_MSC_VER)
506// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
507extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
508 size_t *length, int *status);
509#endif
510
Alexey Samsonov601beb72013-06-28 12:06:25 +0000511std::string LLVMSymbolizer::DemangleName(const std::string &Name) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000512#if !defined(_MSC_VER)
Ed Masteef6fed72014-01-16 17:25:12 +0000513 // We can spoil names of symbols with C linkage, so use an heuristic
514 // approach to check if the name should be demangled.
515 if (Name.substr(0, 2) != "_Z")
516 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000517 int status = 0;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000518 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000519 if (status != 0)
Alexey Samsonov601beb72013-06-28 12:06:25 +0000520 return Name;
521 std::string Result = DemangledName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000522 free(DemangledName);
Alexey Samsonov601beb72013-06-28 12:06:25 +0000523 return Result;
524#else
525 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000526#endif
527}
528
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000529} // namespace symbolize
530} // namespace llvm