blob: 7aa55e755d2c25c7ddaa6b8a30e19998a137332f [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"
Reid Klecknerdafc5d72016-07-06 16:56:42 +000024#include "llvm/Object/COFF.h"
Alexey Samsonova5f07682014-02-26 13:10:01 +000025#include "llvm/Object/ELFObjectFile.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
Alexey Samsonova591ae62013-08-26 18:12:03 +0000189 DebugPath = OrigRealPath;
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 }
195 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
196 DebugPath = "/usr/lib/debug";
197 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
198 DebuglinkName);
199 if (checkFileCRC(DebugPath, CRCHash)) {
200 Result = DebugPath.str();
201 return true;
202 }
203 return false;
204}
205
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000206bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
207 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000208 if (!Obj)
209 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000210 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000211 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000212 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000213 Name = Name.substr(Name.find_first_not_of("._"));
214 if (Name == "gnu_debuglink") {
215 StringRef Data;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000216 Section.getContents(Data);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000217 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
218 uint32_t Offset = 0;
219 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
220 // 4-byte align the offset.
221 Offset = (Offset + 3) & ~0x3;
222 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
223 DebugName = DebugNameStr;
224 CRCHash = DE.getU32(&Offset);
225 return true;
226 }
227 }
228 break;
229 }
230 }
231 return false;
232}
233
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000234bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
235 const MachOObjectFile *Obj) {
236 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
237 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
238 if (dbg_uuid.empty() || bin_uuid.empty())
239 return false;
240 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
241}
242
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000243} // end anonymous namespace
244
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000245ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
246 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
247 // On Darwin we may find DWARF in separate object file in
248 // resource directory.
249 std::vector<std::string> DsymPaths;
250 StringRef Filename = sys::path::filename(ExePath);
251 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
252 for (const auto &Path : Opts.DsymHints) {
253 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
254 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000255 for (const auto &Path : DsymPaths) {
256 auto DbgObjOrErr = getOrCreateObject(Path, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000257 if (!DbgObjOrErr) {
258 // Ignore errors, the file might not exist.
259 consumeError(DbgObjOrErr.takeError());
Alexey Samsonov884adda2015-11-04 00:30:24 +0000260 continue;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000261 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000262 ObjectFile *DbgObj = DbgObjOrErr.get();
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000263 if (!DbgObj)
264 continue;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000265 const MachOObjectFile *MachDbgObj = dyn_cast<const MachOObjectFile>(DbgObj);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000266 if (!MachDbgObj)
267 continue;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000268 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj))
Alexey Samsonov884adda2015-11-04 00:30:24 +0000269 return DbgObj;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000270 }
271 return nullptr;
272}
273
Alexey Samsonov5365a012015-11-04 00:30:26 +0000274ObjectFile *LLVMSymbolizer::lookUpDebuglinkObject(const std::string &Path,
275 const ObjectFile *Obj,
276 const std::string &ArchName) {
277 std::string DebuglinkName;
278 uint32_t CRCHash;
279 std::string DebugBinaryPath;
280 if (!getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash))
281 return nullptr;
282 if (!findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath))
283 return nullptr;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000284 auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000285 if (!DbgObjOrErr) {
286 // Ignore errors, the file might not exist.
287 consumeError(DbgObjOrErr.takeError());
Alexey Samsonov5365a012015-11-04 00:30:26 +0000288 return nullptr;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000289 }
Alexey Samsonov5365a012015-11-04 00:30:26 +0000290 return DbgObjOrErr.get();
291}
292
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000293Expected<LLVMSymbolizer::ObjectPair>
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000294LLVMSymbolizer::getOrCreateObjectPair(const std::string &Path,
295 const std::string &ArchName) {
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000296 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000297 if (I != ObjectPairForPathArch.end()) {
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000298 return I->second;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000299 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000300
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000301 auto ObjOrErr = getOrCreateObject(Path, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000302 if (!ObjOrErr) {
303 ObjectPairForPathArch.insert(std::make_pair(std::make_pair(Path, ArchName),
304 ObjectPair(nullptr, nullptr)));
305 return ObjOrErr.takeError();
Alexey Samsonov884adda2015-11-04 00:30:24 +0000306 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000307
308 ObjectFile *Obj = ObjOrErr.get();
309 assert(Obj != nullptr);
310 ObjectFile *DbgObj = nullptr;
311
312 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
313 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov5365a012015-11-04 00:30:26 +0000314 if (!DbgObj)
315 DbgObj = lookUpDebuglinkObject(Path, Obj, ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000316 if (!DbgObj)
317 DbgObj = Obj;
318 ObjectPair Res = std::make_pair(Obj, DbgObj);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000319 ObjectPairForPathArch.insert(
320 std::make_pair(std::make_pair(Path, ArchName), Res));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000321 return Res;
322}
323
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000324Expected<ObjectFile *>
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000325LLVMSymbolizer::getOrCreateObject(const std::string &Path,
326 const std::string &ArchName) {
327 const auto &I = BinaryForPath.find(Path);
328 Binary *Bin = nullptr;
329 if (I == BinaryForPath.end()) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000330 Expected<OwningBinary<Binary>> BinOrErr = createBinary(Path);
331 if (!BinOrErr) {
Reid Kleckner4ece1632016-06-06 23:46:14 +0000332 BinaryForPath.insert(std::make_pair(Path, OwningBinary<Binary>()));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000333 return BinOrErr.takeError();
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000334 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000335 Bin = BinOrErr->getBinary();
336 BinaryForPath.insert(std::make_pair(Path, std::move(BinOrErr.get())));
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000337 } else {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000338 Bin = I->second.getBinary();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000339 }
340
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000341 if (!Bin)
342 return static_cast<ObjectFile *>(nullptr);
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000343
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000344 if (MachOUniversalBinary *UB = dyn_cast_or_null<MachOUniversalBinary>(Bin)) {
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000345 const auto &I = ObjectForUBPathAndArch.find(std::make_pair(Path, ArchName));
346 if (I != ObjectForUBPathAndArch.end()) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000347 return I->second.get();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000348 }
Kevin Enderby9acb1092016-05-31 20:35:34 +0000349 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000350 UB->getObjectForArch(ArchName);
Kevin Enderby9acb1092016-05-31 20:35:34 +0000351 if (!ObjOrErr) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000352 ObjectForUBPathAndArch.insert(std::make_pair(
353 std::make_pair(Path, ArchName), std::unique_ptr<ObjectFile>()));
354 return ObjOrErr.takeError();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000355 }
356 ObjectFile *Res = ObjOrErr->get();
357 ObjectForUBPathAndArch.insert(std::make_pair(std::make_pair(Path, ArchName),
358 std::move(ObjOrErr.get())));
Alexey Samsonov884adda2015-11-04 00:30:24 +0000359 return Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000360 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000361 if (Bin->isObject()) {
362 return cast<ObjectFile>(Bin);
363 }
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000364 return errorCodeToError(object_error::arch_not_found);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000365}
366
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000367Expected<SymbolizableModule *>
David Blaikiee5adb682017-07-30 01:34:08 +0000368LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName,
369 StringRef DWPName) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000370 const auto &I = Modules.find(ModuleName);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000371 if (I != Modules.end()) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000372 return I->second.get();
Alexey Samsonov884adda2015-11-04 00:30:24 +0000373 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000374 std::string BinaryName = ModuleName;
375 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000376 size_t ColonPos = ModuleName.find_last_of(':');
377 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000378 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000379 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000380 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000381 BinaryName = ModuleName.substr(0, ColonPos);
382 ArchName = ArchStr;
383 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000384 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000385 auto ObjectsOrErr = getOrCreateObjectPair(BinaryName, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000386 if (!ObjectsOrErr) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000387 // Failed to find valid object file.
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000388 Modules.insert(
389 std::make_pair(ModuleName, std::unique_ptr<SymbolizableModule>()));
390 return ObjectsOrErr.takeError();
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000391 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000392 ObjectPair Objects = ObjectsOrErr.get();
393
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000394 std::unique_ptr<DIContext> Context;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000395 // If this is a COFF object containing PDB info, use a PDBContext to
396 // symbolize. Otherwise, use DWARF.
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000397 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
Saleem Abdulrasool01528022016-08-09 00:25:12 +0000398 const codeview::DebugInfo *DebugInfo;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000399 StringRef PDBFileName;
Saleem Abdulrasool01528022016-08-09 00:25:12 +0000400 auto EC = CoffObject->getDebugPDBInfo(DebugInfo, PDBFileName);
Reid Klecknerd1882f22016-09-01 20:28:59 +0000401 if (!EC && DebugInfo != nullptr && !PDBFileName.empty()) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000402 using namespace pdb;
403 std::unique_ptr<IPDBSession> Session;
404 if (auto Err = loadDataForEXE(PDB_ReaderType::DIA,
405 Objects.first->getFileName(), Session)) {
406 Modules.insert(
407 std::make_pair(ModuleName, std::unique_ptr<SymbolizableModule>()));
408 return std::move(Err);
409 }
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000410 Context.reset(new PDBContext(*CoffObject, std::move(Session)));
Zachary Turnerc007aa42015-05-06 22:26:30 +0000411 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000412 }
413 if (!Context)
David Blaikiee5adb682017-07-30 01:34:08 +0000414 Context = DWARFContext::create(*Objects.second, nullptr,
415 DWARFContext::defaultErrorHandler, DWPName);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000416 assert(Context);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000417 auto InfoOrErr =
Alexey Samsonov8df3a072015-10-29 22:21:37 +0000418 SymbolizableObjectFile::create(Objects.first, std::move(Context));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000419 std::unique_ptr<SymbolizableModule> SymMod;
420 if (InfoOrErr)
421 SymMod = std::move(InfoOrErr.get());
Alexey Samsonov884adda2015-11-04 00:30:24 +0000422 auto InsertResult =
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000423 Modules.insert(std::make_pair(ModuleName, std::move(SymMod)));
Alexey Samsonov884adda2015-11-04 00:30:24 +0000424 assert(InsertResult.second);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000425 if (auto EC = InfoOrErr.getError())
426 return errorCodeToError(EC);
427 return InsertResult.first->second.get();
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000428}
429
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000430namespace {
431
Reid Klecknerc25c7942015-08-10 21:47:11 +0000432// Undo these various manglings for Win32 extern "C" functions:
433// cdecl - _foo
434// stdcall - _foo@12
435// fastcall - @foo@12
436// vectorcall - foo@@12
437// These are all different linkage names for 'foo'.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000438StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
Reid Klecknerc25c7942015-08-10 21:47:11 +0000439 // Remove any '_' or '@' prefix.
440 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
441 if (Front == '_' || Front == '@')
442 SymbolName = SymbolName.drop_front();
443
444 // Remove any '@[0-9]+' suffix.
445 if (Front != '?') {
446 size_t AtPos = SymbolName.rfind('@');
447 if (AtPos != StringRef::npos &&
448 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
449 [](char C) { return C >= '0' && C <= '9'; })) {
450 SymbolName = SymbolName.substr(0, AtPos);
451 }
452 }
453
454 // Remove any ending '@' for vectorcall.
455 if (SymbolName.endswith("@"))
456 SymbolName = SymbolName.drop_back();
457
458 return SymbolName;
459}
460
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000461} // end anonymous namespace
462
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000463#if !defined(_MSC_VER)
464// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
465extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
466 size_t *length, int *status);
467#endif
468
Zachary Turner67c56012017-04-27 16:11:19 +0000469std::string
470LLVMSymbolizer::DemangleName(const std::string &Name,
471 const SymbolizableModule *DbiModuleDescriptor) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000472#if !defined(_MSC_VER)
Ed Masteef6fed72014-01-16 17:25:12 +0000473 // We can spoil names of symbols with C linkage, so use an heuristic
474 // approach to check if the name should be demangled.
Reid Klecknerc25c7942015-08-10 21:47:11 +0000475 if (Name.substr(0, 2) == "_Z") {
476 int status = 0;
477 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
478 if (status != 0)
479 return Name;
480 std::string Result = DemangledName;
481 free(DemangledName);
482 return Result;
483 }
Alexey Samsonov601beb72013-06-28 12:06:25 +0000484#else
Reid Klecknerc25c7942015-08-10 21:47:11 +0000485 if (!Name.empty() && Name.front() == '?') {
486 // Only do MSVC C++ demangling on symbols starting with '?'.
487 char DemangledName[1024] = {0};
488 DWORD result = ::UnDecorateSymbolName(
489 Name.c_str(), DemangledName, 1023,
490 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
491 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
492 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
493 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
494 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
495 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
496 return (result == 0) ? Name : std::string(DemangledName);
497 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000498#endif
Zachary Turner67c56012017-04-27 16:11:19 +0000499 if (DbiModuleDescriptor && DbiModuleDescriptor->isWin32Module())
Reid Klecknerc25c7942015-08-10 21:47:11 +0000500 return std::string(demanglePE32ExternCFunc(Name));
501 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000502}
503
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000504} // namespace symbolize
505} // namespace llvm