blob: f760a0ef65c45b869a3bd238841f5f24355f2b3a [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
Alexey Samsonov57f88372015-10-26 17:56:12 +000014#include "llvm/DebugInfo/Symbolize/Symbolize.h"
15
Alexey Samsonov8df3a072015-10-29 22:21:37 +000016#include "SymbolizableObjectFile.h"
17
Alexey Samsonovdd71c5b2013-03-19 15:33:18 +000018#include "llvm/ADT/STLExtras.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000019#include "llvm/BinaryFormat/COFF.h"
Alexey Samsonova591ae62013-08-26 18:12:03 +000020#include "llvm/Config/config.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000021#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Zachary Turner20dbd0d2015-04-27 17:19:51 +000022#include "llvm/DebugInfo/PDB/PDB.h"
23#include "llvm/DebugInfo/PDB/PDBContext.h"
Eugene Zemtsovcd72cbc2018-03-07 23:07:34 +000024#include "llvm/Demangle/Demangle.h"
Reid Klecknerdafc5d72016-07-06 16:56:42 +000025#include "llvm/Object/COFF.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000026#include "llvm/Object/MachO.h"
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +000027#include "llvm/Object/MachOUniversal.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000028#include "llvm/Support/Casting.h"
Alexey Samsonov3e9997f2013-08-14 17:09:30 +000029#include "llvm/Support/Compression.h"
30#include "llvm/Support/DataExtractor.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000031#include "llvm/Support/Errc.h"
Alexey Samsonov5239d582013-06-04 07:57:38 +000032#include "llvm/Support/FileSystem.h"
Alexey Samsonov3e9997f2013-08-14 17:09:30 +000033#include "llvm/Support/MemoryBuffer.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000034#include "llvm/Support/Path.h"
Eugene Zelenko35623fb2016-03-28 17:40:08 +000035#include <algorithm>
36#include <cassert>
37#include <cstdlib>
38#include <cstring>
Alexey Samsonovea83baf2013-01-22 14:21:19 +000039
Zachary Turnerc007aa42015-05-06 22:26:30 +000040#if defined(_MSC_VER)
Chandler Carruth6bda14b2017-06-06 11:49:48 +000041#include <Windows.h>
Chandler Carruthaaeada62017-06-06 12:43:20 +000042
43// This must be included after windows.h.
44#include <DbgHelp.h>
Leny Kholodovbebb27b2015-07-02 14:34:57 +000045#pragma comment(lib, "dbghelp.lib")
Reid Klecknerc25c7942015-08-10 21:47:11 +000046
47// Windows.h conflicts with our COFF header definitions.
48#ifdef IMAGE_FILE_MACHINE_I386
49#undef IMAGE_FILE_MACHINE_I386
50#endif
Zachary Turnerc007aa42015-05-06 22:26:30 +000051#endif
52
Alexey Samsonovea83baf2013-01-22 14:21:19 +000053namespace llvm {
54namespace symbolize {
55
David Blaikiee5adb682017-07-30 01:34:08 +000056Expected<DILineInfo>
57LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
58 uint64_t ModuleOffset, StringRef DWPName) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +000059 SymbolizableModule *Info;
David Blaikiee5adb682017-07-30 01:34:08 +000060 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName, DWPName))
Reid Klecknerf27f3f82016-06-03 20:25:09 +000061 Info = InfoOrErr.get();
62 else
63 return InfoOrErr.takeError();
64
65 // A null module means an error has already been reported. Return an empty
66 // result.
67 if (!Info)
68 return DILineInfo();
Reid Klecknere94fef72015-10-09 00:15:01 +000069
70 // If the user is giving us relative addresses, add the preferred base of the
71 // object to the offset before we do the query. It's what DIContext expects.
72 if (Opts.RelativeAddresses)
73 ModuleOffset += Info->getModulePreferredBase();
74
Alexey Samsonov0fb64512015-10-26 22:34:56 +000075 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions,
76 Opts.UseSymbolTable);
Alexey Samsonov68812492015-11-03 21:36:13 +000077 if (Opts.Demangle)
78 LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000079 return LineInfo;
Alexey Samsonovea83baf2013-01-22 14:21:19 +000080}
81
Reid Klecknerf27f3f82016-06-03 20:25:09 +000082Expected<DIInliningInfo>
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000083LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
David Blaikiee5adb682017-07-30 01:34:08 +000084 uint64_t ModuleOffset, StringRef DWPName) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +000085 SymbolizableModule *Info;
David Blaikiee5adb682017-07-30 01:34:08 +000086 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName, DWPName))
Reid Klecknerf27f3f82016-06-03 20:25:09 +000087 Info = InfoOrErr.get();
88 else
89 return InfoOrErr.takeError();
90
91 // A null module means an error has already been reported. Return an empty
92 // result.
93 if (!Info)
94 return DIInliningInfo();
Alexey Samsonov46c1ce62015-10-30 00:40:20 +000095
96 // If the user is giving us relative addresses, add the preferred base of the
97 // object to the offset before we do the query. It's what DIContext expects.
98 if (Opts.RelativeAddresses)
99 ModuleOffset += Info->getModulePreferredBase();
100
101 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
102 ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable);
Alexey Samsonov68812492015-11-03 21:36:13 +0000103 if (Opts.Demangle) {
104 for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
105 auto *Frame = InlinedContext.getMutableFrame(i);
106 Frame->FunctionName = DemangleName(Frame->FunctionName, Info);
107 }
108 }
Alexey Samsonovd6aa8202015-11-03 22:20:52 +0000109 return InlinedContext;
Alexey Samsonov46c1ce62015-10-30 00:40:20 +0000110}
111
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000112Expected<DIGlobal> LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
113 uint64_t ModuleOffset) {
114 SymbolizableModule *Info;
115 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
116 Info = InfoOrErr.get();
117 else
118 return InfoOrErr.takeError();
119
120 // A null module means an error has already been reported. Return an empty
121 // result.
122 if (!Info)
123 return DIGlobal();
Alexey Samsonov68812492015-11-03 21:36:13 +0000124
125 // If the user is giving us relative addresses, add the preferred base of
126 // the object to the offset before we do the query. It's what DIContext
127 // expects.
128 if (Opts.RelativeAddresses)
129 ModuleOffset += Info->getModulePreferredBase();
130
131 DIGlobal Global = Info->symbolizeData(ModuleOffset);
132 if (Opts.Demangle)
133 Global.Name = DemangleName(Global.Name, Info);
Alexey Samsonovd6aa8202015-11-03 22:20:52 +0000134 return Global;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000135}
136
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000137void LLVMSymbolizer::flush() {
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000138 ObjectForUBPathAndArch.clear();
139 BinaryForPath.clear();
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000140 ObjectPairForPathArch.clear();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000141 Modules.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000142}
143
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000144namespace {
145
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000146// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
147// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
148// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
149// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000150std::string getDarwinDWARFResourceForPath(
151 const std::string &Path, const std::string &Basename) {
152 SmallString<16> ResourceName = StringRef(Path);
153 if (sys::path::extension(Path) != ".dSYM") {
154 ResourceName += ".dSYM";
155 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000156 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
157 sys::path::append(ResourceName, Basename);
158 return ResourceName.str();
159}
160
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000161bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000162 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
163 MemoryBuffer::getFileOrSTDIN(Path);
164 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000165 return false;
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000166 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000167}
168
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000169bool findDebugBinary(const std::string &OrigPath,
170 const std::string &DebuglinkName, uint32_t CRCHash,
171 std::string &Result) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000172 std::string OrigRealPath = OrigPath;
173#if defined(HAVE_REALPATH)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000174 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000175 OrigRealPath = RP;
176 free(RP);
177 }
178#endif
179 SmallString<16> OrigDir(OrigRealPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000180 llvm::sys::path::remove_filename(OrigDir);
181 SmallString<16> DebugPath = OrigDir;
182 // Try /path/to/original_binary/debuglink_name
183 llvm::sys::path::append(DebugPath, DebuglinkName);
184 if (checkFileCRC(DebugPath, CRCHash)) {
185 Result = DebugPath.str();
186 return true;
187 }
188 // Try /path/to/original_binary/.debug/debuglink_name
Francis Riccife6cbce2018-03-02 22:56:45 +0000189 DebugPath = OrigDir;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000190 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
191 if (checkFileCRC(DebugPath, CRCHash)) {
192 Result = DebugPath.str();
193 return true;
194 }
Kamil Rytarowskia8448ad2018-06-25 18:49:13 +0000195#if defined(__NetBSD__)
196 // Try /usr/libdata/debug/path/to/original_binary/debuglink_name
197 DebugPath = "/usr/libdata/debug";
198#else
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000199 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
200 DebugPath = "/usr/lib/debug";
Kamil Rytarowskia8448ad2018-06-25 18:49:13 +0000201#endif
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000202 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
203 DebuglinkName);
204 if (checkFileCRC(DebugPath, CRCHash)) {
205 Result = DebugPath.str();
206 return true;
207 }
208 return false;
209}
210
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000211bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
212 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000213 if (!Obj)
214 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000215 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000216 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000217 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000218 Name = Name.substr(Name.find_first_not_of("._"));
219 if (Name == "gnu_debuglink") {
220 StringRef Data;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000221 Section.getContents(Data);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000222 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
223 uint32_t Offset = 0;
224 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
225 // 4-byte align the offset.
226 Offset = (Offset + 3) & ~0x3;
227 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
228 DebugName = DebugNameStr;
229 CRCHash = DE.getU32(&Offset);
230 return true;
231 }
232 }
233 break;
234 }
235 }
236 return false;
237}
238
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000239bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
240 const MachOObjectFile *Obj) {
241 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
242 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
243 if (dbg_uuid.empty() || bin_uuid.empty())
244 return false;
245 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
246}
247
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000248} // end anonymous namespace
249
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000250ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
251 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
252 // On Darwin we may find DWARF in separate object file in
253 // resource directory.
254 std::vector<std::string> DsymPaths;
255 StringRef Filename = sys::path::filename(ExePath);
256 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
257 for (const auto &Path : Opts.DsymHints) {
258 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
259 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000260 for (const auto &Path : DsymPaths) {
261 auto DbgObjOrErr = getOrCreateObject(Path, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000262 if (!DbgObjOrErr) {
263 // Ignore errors, the file might not exist.
264 consumeError(DbgObjOrErr.takeError());
Alexey Samsonov884adda2015-11-04 00:30:24 +0000265 continue;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000266 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000267 ObjectFile *DbgObj = DbgObjOrErr.get();
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000268 if (!DbgObj)
269 continue;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000270 const MachOObjectFile *MachDbgObj = dyn_cast<const MachOObjectFile>(DbgObj);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000271 if (!MachDbgObj)
272 continue;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000273 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj))
Alexey Samsonov884adda2015-11-04 00:30:24 +0000274 return DbgObj;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000275 }
276 return nullptr;
277}
278
Alexey Samsonov5365a012015-11-04 00:30:26 +0000279ObjectFile *LLVMSymbolizer::lookUpDebuglinkObject(const std::string &Path,
280 const ObjectFile *Obj,
281 const std::string &ArchName) {
282 std::string DebuglinkName;
283 uint32_t CRCHash;
284 std::string DebugBinaryPath;
285 if (!getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash))
286 return nullptr;
287 if (!findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath))
288 return nullptr;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000289 auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000290 if (!DbgObjOrErr) {
291 // Ignore errors, the file might not exist.
292 consumeError(DbgObjOrErr.takeError());
Alexey Samsonov5365a012015-11-04 00:30:26 +0000293 return nullptr;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000294 }
Alexey Samsonov5365a012015-11-04 00:30:26 +0000295 return DbgObjOrErr.get();
296}
297
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000298Expected<LLVMSymbolizer::ObjectPair>
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000299LLVMSymbolizer::getOrCreateObjectPair(const std::string &Path,
300 const std::string &ArchName) {
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000301 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000302 if (I != ObjectPairForPathArch.end()) {
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000303 return I->second;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000304 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000305
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000306 auto ObjOrErr = getOrCreateObject(Path, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000307 if (!ObjOrErr) {
308 ObjectPairForPathArch.insert(std::make_pair(std::make_pair(Path, ArchName),
309 ObjectPair(nullptr, nullptr)));
310 return ObjOrErr.takeError();
Alexey Samsonov884adda2015-11-04 00:30:24 +0000311 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000312
313 ObjectFile *Obj = ObjOrErr.get();
314 assert(Obj != nullptr);
315 ObjectFile *DbgObj = nullptr;
316
317 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
318 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov5365a012015-11-04 00:30:26 +0000319 if (!DbgObj)
320 DbgObj = lookUpDebuglinkObject(Path, Obj, ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000321 if (!DbgObj)
322 DbgObj = Obj;
323 ObjectPair Res = std::make_pair(Obj, DbgObj);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000324 ObjectPairForPathArch.insert(
325 std::make_pair(std::make_pair(Path, ArchName), Res));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000326 return Res;
327}
328
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000329Expected<ObjectFile *>
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000330LLVMSymbolizer::getOrCreateObject(const std::string &Path,
331 const std::string &ArchName) {
332 const auto &I = BinaryForPath.find(Path);
333 Binary *Bin = nullptr;
334 if (I == BinaryForPath.end()) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000335 Expected<OwningBinary<Binary>> BinOrErr = createBinary(Path);
336 if (!BinOrErr) {
Reid Kleckner4ece1632016-06-06 23:46:14 +0000337 BinaryForPath.insert(std::make_pair(Path, OwningBinary<Binary>()));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000338 return BinOrErr.takeError();
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000339 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000340 Bin = BinOrErr->getBinary();
341 BinaryForPath.insert(std::make_pair(Path, std::move(BinOrErr.get())));
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000342 } else {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000343 Bin = I->second.getBinary();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000344 }
345
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000346 if (!Bin)
347 return static_cast<ObjectFile *>(nullptr);
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000348
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000349 if (MachOUniversalBinary *UB = dyn_cast_or_null<MachOUniversalBinary>(Bin)) {
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000350 const auto &I = ObjectForUBPathAndArch.find(std::make_pair(Path, ArchName));
351 if (I != ObjectForUBPathAndArch.end()) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000352 return I->second.get();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000353 }
Kevin Enderby9acb1092016-05-31 20:35:34 +0000354 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000355 UB->getObjectForArch(ArchName);
Kevin Enderby9acb1092016-05-31 20:35:34 +0000356 if (!ObjOrErr) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000357 ObjectForUBPathAndArch.insert(std::make_pair(
358 std::make_pair(Path, ArchName), std::unique_ptr<ObjectFile>()));
359 return ObjOrErr.takeError();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000360 }
361 ObjectFile *Res = ObjOrErr->get();
362 ObjectForUBPathAndArch.insert(std::make_pair(std::make_pair(Path, ArchName),
363 std::move(ObjOrErr.get())));
Alexey Samsonov884adda2015-11-04 00:30:24 +0000364 return Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000365 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000366 if (Bin->isObject()) {
367 return cast<ObjectFile>(Bin);
368 }
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000369 return errorCodeToError(object_error::arch_not_found);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000370}
371
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000372Expected<SymbolizableModule *>
David Blaikiee5adb682017-07-30 01:34:08 +0000373LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName,
374 StringRef DWPName) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000375 const auto &I = Modules.find(ModuleName);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000376 if (I != Modules.end()) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000377 return I->second.get();
Alexey Samsonov884adda2015-11-04 00:30:24 +0000378 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000379 std::string BinaryName = ModuleName;
380 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000381 size_t ColonPos = ModuleName.find_last_of(':');
382 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000383 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000384 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000385 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000386 BinaryName = ModuleName.substr(0, ColonPos);
387 ArchName = ArchStr;
388 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000389 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000390 auto ObjectsOrErr = getOrCreateObjectPair(BinaryName, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000391 if (!ObjectsOrErr) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000392 // Failed to find valid object file.
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000393 Modules.insert(
394 std::make_pair(ModuleName, std::unique_ptr<SymbolizableModule>()));
395 return ObjectsOrErr.takeError();
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000396 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000397 ObjectPair Objects = ObjectsOrErr.get();
398
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000399 std::unique_ptr<DIContext> Context;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000400 // If this is a COFF object containing PDB info, use a PDBContext to
401 // symbolize. Otherwise, use DWARF.
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000402 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
Saleem Abdulrasool01528022016-08-09 00:25:12 +0000403 const codeview::DebugInfo *DebugInfo;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000404 StringRef PDBFileName;
Saleem Abdulrasool01528022016-08-09 00:25:12 +0000405 auto EC = CoffObject->getDebugPDBInfo(DebugInfo, PDBFileName);
Reid Klecknerd1882f22016-09-01 20:28:59 +0000406 if (!EC && DebugInfo != nullptr && !PDBFileName.empty()) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000407 using namespace pdb;
408 std::unique_ptr<IPDBSession> Session;
409 if (auto Err = loadDataForEXE(PDB_ReaderType::DIA,
410 Objects.first->getFileName(), Session)) {
411 Modules.insert(
412 std::make_pair(ModuleName, std::unique_ptr<SymbolizableModule>()));
413 return std::move(Err);
414 }
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000415 Context.reset(new PDBContext(*CoffObject, std::move(Session)));
Zachary Turnerc007aa42015-05-06 22:26:30 +0000416 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000417 }
418 if (!Context)
David Blaikiee5adb682017-07-30 01:34:08 +0000419 Context = DWARFContext::create(*Objects.second, nullptr,
420 DWARFContext::defaultErrorHandler, DWPName);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000421 assert(Context);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000422 auto InfoOrErr =
Alexey Samsonov8df3a072015-10-29 22:21:37 +0000423 SymbolizableObjectFile::create(Objects.first, std::move(Context));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000424 std::unique_ptr<SymbolizableModule> SymMod;
425 if (InfoOrErr)
426 SymMod = std::move(InfoOrErr.get());
Alexey Samsonov884adda2015-11-04 00:30:24 +0000427 auto InsertResult =
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000428 Modules.insert(std::make_pair(ModuleName, std::move(SymMod)));
Alexey Samsonov884adda2015-11-04 00:30:24 +0000429 assert(InsertResult.second);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000430 if (auto EC = InfoOrErr.getError())
431 return errorCodeToError(EC);
432 return InsertResult.first->second.get();
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000433}
434
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000435namespace {
436
Reid Klecknerc25c7942015-08-10 21:47:11 +0000437// Undo these various manglings for Win32 extern "C" functions:
438// cdecl - _foo
439// stdcall - _foo@12
440// fastcall - @foo@12
441// vectorcall - foo@@12
442// These are all different linkage names for 'foo'.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000443StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
Reid Klecknerc25c7942015-08-10 21:47:11 +0000444 // Remove any '_' or '@' prefix.
445 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
446 if (Front == '_' || Front == '@')
447 SymbolName = SymbolName.drop_front();
448
449 // Remove any '@[0-9]+' suffix.
450 if (Front != '?') {
451 size_t AtPos = SymbolName.rfind('@');
452 if (AtPos != StringRef::npos &&
453 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
454 [](char C) { return C >= '0' && C <= '9'; })) {
455 SymbolName = SymbolName.substr(0, AtPos);
456 }
457 }
458
459 // Remove any ending '@' for vectorcall.
460 if (SymbolName.endswith("@"))
461 SymbolName = SymbolName.drop_back();
462
463 return SymbolName;
464}
465
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000466} // end anonymous namespace
467
Zachary Turner67c56012017-04-27 16:11:19 +0000468std::string
469LLVMSymbolizer::DemangleName(const std::string &Name,
470 const SymbolizableModule *DbiModuleDescriptor) {
Ed Masteef6fed72014-01-16 17:25:12 +0000471 // We can spoil names of symbols with C linkage, so use an heuristic
472 // approach to check if the name should be demangled.
Reid Klecknerc25c7942015-08-10 21:47:11 +0000473 if (Name.substr(0, 2) == "_Z") {
474 int status = 0;
Eugene Zemtsovcd72cbc2018-03-07 23:07:34 +0000475 char *DemangledName = itaniumDemangle(Name.c_str(), nullptr, nullptr, &status);
Reid Klecknerc25c7942015-08-10 21:47:11 +0000476 if (status != 0)
477 return Name;
478 std::string Result = DemangledName;
479 free(DemangledName);
480 return Result;
481 }
Eugene Zemtsovcd72cbc2018-03-07 23:07:34 +0000482
483#if defined(_MSC_VER)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000484 if (!Name.empty() && Name.front() == '?') {
485 // Only do MSVC C++ demangling on symbols starting with '?'.
486 char DemangledName[1024] = {0};
487 DWORD result = ::UnDecorateSymbolName(
488 Name.c_str(), DemangledName, 1023,
489 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
490 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
491 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
492 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
493 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
494 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
495 return (result == 0) ? Name : std::string(DemangledName);
496 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000497#endif
Zachary Turner67c56012017-04-27 16:11:19 +0000498 if (DbiModuleDescriptor && DbiModuleDescriptor->isWin32Module())
Reid Klecknerc25c7942015-08-10 21:47:11 +0000499 return std::string(demanglePE32ExternCFunc(Name));
500 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000501}
502
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000503} // namespace symbolize
504} // namespace llvm