blob: 0561d6a4134b35a327f700f527e47ceabd1d5b27 [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"
Alexey Samsonova591ae62013-08-26 18:12:03 +000019#include "llvm/Config/config.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000020#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Zachary Turner20dbd0d2015-04-27 17:19:51 +000021#include "llvm/DebugInfo/PDB/PDB.h"
22#include "llvm/DebugInfo/PDB/PDBContext.h"
Reid Klecknerdafc5d72016-07-06 16:56:42 +000023#include "llvm/Object/COFF.h"
Alexey Samsonova5f07682014-02-26 13:10:01 +000024#include "llvm/Object/ELFObjectFile.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000025#include "llvm/Object/MachO.h"
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +000026#include "llvm/Object/MachOUniversal.h"
Reid Klecknerc25c7942015-08-10 21:47:11 +000027#include "llvm/Support/COFF.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
Reid Klecknerf27f3f82016-06-03 20:25:09 +000056Expected<DILineInfo> LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
Alexey Samsonov884adda2015-11-04 00:30:24 +000057 uint64_t ModuleOffset) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +000058 SymbolizableModule *Info;
59 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
60 Info = InfoOrErr.get();
61 else
62 return InfoOrErr.takeError();
63
64 // A null module means an error has already been reported. Return an empty
65 // result.
66 if (!Info)
67 return DILineInfo();
Reid Klecknere94fef72015-10-09 00:15:01 +000068
69 // If the user is giving us relative addresses, add the preferred base of the
70 // object to the offset before we do the query. It's what DIContext expects.
71 if (Opts.RelativeAddresses)
72 ModuleOffset += Info->getModulePreferredBase();
73
Alexey Samsonov0fb64512015-10-26 22:34:56 +000074 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions,
75 Opts.UseSymbolTable);
Alexey Samsonov68812492015-11-03 21:36:13 +000076 if (Opts.Demangle)
77 LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000078 return LineInfo;
Alexey Samsonovea83baf2013-01-22 14:21:19 +000079}
80
Reid Klecknerf27f3f82016-06-03 20:25:09 +000081Expected<DIInliningInfo>
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000082LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
83 uint64_t ModuleOffset) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +000084 SymbolizableModule *Info;
85 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
86 Info = InfoOrErr.get();
87 else
88 return InfoOrErr.takeError();
89
90 // A null module means an error has already been reported. Return an empty
91 // result.
92 if (!Info)
93 return DIInliningInfo();
Alexey Samsonov46c1ce62015-10-30 00:40:20 +000094
95 // If the user is giving us relative addresses, add the preferred base of the
96 // object to the offset before we do the query. It's what DIContext expects.
97 if (Opts.RelativeAddresses)
98 ModuleOffset += Info->getModulePreferredBase();
99
100 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
101 ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable);
Alexey Samsonov68812492015-11-03 21:36:13 +0000102 if (Opts.Demangle) {
103 for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
104 auto *Frame = InlinedContext.getMutableFrame(i);
105 Frame->FunctionName = DemangleName(Frame->FunctionName, Info);
106 }
107 }
Alexey Samsonovd6aa8202015-11-03 22:20:52 +0000108 return InlinedContext;
Alexey Samsonov46c1ce62015-10-30 00:40:20 +0000109}
110
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000111Expected<DIGlobal> LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
112 uint64_t ModuleOffset) {
113 SymbolizableModule *Info;
114 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
115 Info = InfoOrErr.get();
116 else
117 return InfoOrErr.takeError();
118
119 // A null module means an error has already been reported. Return an empty
120 // result.
121 if (!Info)
122 return DIGlobal();
Alexey Samsonov68812492015-11-03 21:36:13 +0000123
124 // If the user is giving us relative addresses, add the preferred base of
125 // the object to the offset before we do the query. It's what DIContext
126 // expects.
127 if (Opts.RelativeAddresses)
128 ModuleOffset += Info->getModulePreferredBase();
129
130 DIGlobal Global = Info->symbolizeData(ModuleOffset);
131 if (Opts.Demangle)
132 Global.Name = DemangleName(Global.Name, Info);
Alexey Samsonovd6aa8202015-11-03 22:20:52 +0000133 return Global;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000134}
135
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000136void LLVMSymbolizer::flush() {
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000137 ObjectForUBPathAndArch.clear();
138 BinaryForPath.clear();
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000139 ObjectPairForPathArch.clear();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000140 Modules.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000141}
142
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000143namespace {
144
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000145// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
146// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
147// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
148// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000149std::string getDarwinDWARFResourceForPath(
150 const std::string &Path, const std::string &Basename) {
151 SmallString<16> ResourceName = StringRef(Path);
152 if (sys::path::extension(Path) != ".dSYM") {
153 ResourceName += ".dSYM";
154 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000155 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
156 sys::path::append(ResourceName, Basename);
157 return ResourceName.str();
158}
159
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000160bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000161 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
162 MemoryBuffer::getFileOrSTDIN(Path);
163 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000164 return false;
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000165 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000166}
167
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000168bool findDebugBinary(const std::string &OrigPath,
169 const std::string &DebuglinkName, uint32_t CRCHash,
170 std::string &Result) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000171 std::string OrigRealPath = OrigPath;
172#if defined(HAVE_REALPATH)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000173 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000174 OrigRealPath = RP;
175 free(RP);
176 }
177#endif
178 SmallString<16> OrigDir(OrigRealPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000179 llvm::sys::path::remove_filename(OrigDir);
180 SmallString<16> DebugPath = OrigDir;
181 // Try /path/to/original_binary/debuglink_name
182 llvm::sys::path::append(DebugPath, DebuglinkName);
183 if (checkFileCRC(DebugPath, CRCHash)) {
184 Result = DebugPath.str();
185 return true;
186 }
187 // Try /path/to/original_binary/.debug/debuglink_name
Alexey Samsonova591ae62013-08-26 18:12:03 +0000188 DebugPath = OrigRealPath;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000189 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
190 if (checkFileCRC(DebugPath, CRCHash)) {
191 Result = DebugPath.str();
192 return true;
193 }
194 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
195 DebugPath = "/usr/lib/debug";
196 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
197 DebuglinkName);
198 if (checkFileCRC(DebugPath, CRCHash)) {
199 Result = DebugPath.str();
200 return true;
201 }
202 return false;
203}
204
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000205bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
206 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000207 if (!Obj)
208 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000209 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000210 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000211 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000212 Name = Name.substr(Name.find_first_not_of("._"));
213 if (Name == "gnu_debuglink") {
214 StringRef Data;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000215 Section.getContents(Data);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000216 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
217 uint32_t Offset = 0;
218 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
219 // 4-byte align the offset.
220 Offset = (Offset + 3) & ~0x3;
221 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
222 DebugName = DebugNameStr;
223 CRCHash = DE.getU32(&Offset);
224 return true;
225 }
226 }
227 break;
228 }
229 }
230 return false;
231}
232
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000233bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
234 const MachOObjectFile *Obj) {
235 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
236 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
237 if (dbg_uuid.empty() || bin_uuid.empty())
238 return false;
239 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
240}
241
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000242} // end anonymous namespace
243
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000244ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
245 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
246 // On Darwin we may find DWARF in separate object file in
247 // resource directory.
248 std::vector<std::string> DsymPaths;
249 StringRef Filename = sys::path::filename(ExePath);
250 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
251 for (const auto &Path : Opts.DsymHints) {
252 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
253 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000254 for (const auto &Path : DsymPaths) {
255 auto DbgObjOrErr = getOrCreateObject(Path, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000256 if (!DbgObjOrErr) {
257 // Ignore errors, the file might not exist.
258 consumeError(DbgObjOrErr.takeError());
Alexey Samsonov884adda2015-11-04 00:30:24 +0000259 continue;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000260 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000261 ObjectFile *DbgObj = DbgObjOrErr.get();
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000262 if (!DbgObj)
263 continue;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000264 const MachOObjectFile *MachDbgObj = dyn_cast<const MachOObjectFile>(DbgObj);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000265 if (!MachDbgObj)
266 continue;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000267 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj))
Alexey Samsonov884adda2015-11-04 00:30:24 +0000268 return DbgObj;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000269 }
270 return nullptr;
271}
272
Alexey Samsonov5365a012015-11-04 00:30:26 +0000273ObjectFile *LLVMSymbolizer::lookUpDebuglinkObject(const std::string &Path,
274 const ObjectFile *Obj,
275 const std::string &ArchName) {
276 std::string DebuglinkName;
277 uint32_t CRCHash;
278 std::string DebugBinaryPath;
279 if (!getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash))
280 return nullptr;
281 if (!findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath))
282 return nullptr;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000283 auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000284 if (!DbgObjOrErr) {
285 // Ignore errors, the file might not exist.
286 consumeError(DbgObjOrErr.takeError());
Alexey Samsonov5365a012015-11-04 00:30:26 +0000287 return nullptr;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000288 }
Alexey Samsonov5365a012015-11-04 00:30:26 +0000289 return DbgObjOrErr.get();
290}
291
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000292Expected<LLVMSymbolizer::ObjectPair>
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000293LLVMSymbolizer::getOrCreateObjectPair(const std::string &Path,
294 const std::string &ArchName) {
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000295 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000296 if (I != ObjectPairForPathArch.end()) {
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000297 return I->second;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000298 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000299
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000300 auto ObjOrErr = getOrCreateObject(Path, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000301 if (!ObjOrErr) {
302 ObjectPairForPathArch.insert(std::make_pair(std::make_pair(Path, ArchName),
303 ObjectPair(nullptr, nullptr)));
304 return ObjOrErr.takeError();
Alexey Samsonov884adda2015-11-04 00:30:24 +0000305 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000306
307 ObjectFile *Obj = ObjOrErr.get();
308 assert(Obj != nullptr);
309 ObjectFile *DbgObj = nullptr;
310
311 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
312 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov5365a012015-11-04 00:30:26 +0000313 if (!DbgObj)
314 DbgObj = lookUpDebuglinkObject(Path, Obj, ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000315 if (!DbgObj)
316 DbgObj = Obj;
317 ObjectPair Res = std::make_pair(Obj, DbgObj);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000318 ObjectPairForPathArch.insert(
319 std::make_pair(std::make_pair(Path, ArchName), Res));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000320 return Res;
321}
322
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000323Expected<ObjectFile *>
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000324LLVMSymbolizer::getOrCreateObject(const std::string &Path,
325 const std::string &ArchName) {
326 const auto &I = BinaryForPath.find(Path);
327 Binary *Bin = nullptr;
328 if (I == BinaryForPath.end()) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000329 Expected<OwningBinary<Binary>> BinOrErr = createBinary(Path);
330 if (!BinOrErr) {
Reid Kleckner4ece1632016-06-06 23:46:14 +0000331 BinaryForPath.insert(std::make_pair(Path, OwningBinary<Binary>()));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000332 return BinOrErr.takeError();
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000333 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000334 Bin = BinOrErr->getBinary();
335 BinaryForPath.insert(std::make_pair(Path, std::move(BinOrErr.get())));
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000336 } else {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000337 Bin = I->second.getBinary();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000338 }
339
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000340 if (!Bin)
341 return static_cast<ObjectFile *>(nullptr);
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000342
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000343 if (MachOUniversalBinary *UB = dyn_cast_or_null<MachOUniversalBinary>(Bin)) {
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000344 const auto &I = ObjectForUBPathAndArch.find(std::make_pair(Path, ArchName));
345 if (I != ObjectForUBPathAndArch.end()) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000346 return I->second.get();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000347 }
Kevin Enderby9acb1092016-05-31 20:35:34 +0000348 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000349 UB->getObjectForArch(ArchName);
Kevin Enderby9acb1092016-05-31 20:35:34 +0000350 if (!ObjOrErr) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000351 ObjectForUBPathAndArch.insert(std::make_pair(
352 std::make_pair(Path, ArchName), std::unique_ptr<ObjectFile>()));
353 return ObjOrErr.takeError();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000354 }
355 ObjectFile *Res = ObjOrErr->get();
356 ObjectForUBPathAndArch.insert(std::make_pair(std::make_pair(Path, ArchName),
357 std::move(ObjOrErr.get())));
Alexey Samsonov884adda2015-11-04 00:30:24 +0000358 return Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000359 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000360 if (Bin->isObject()) {
361 return cast<ObjectFile>(Bin);
362 }
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000363 return errorCodeToError(object_error::arch_not_found);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000364}
365
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000366Expected<SymbolizableModule *>
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000367LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000368 const auto &I = Modules.find(ModuleName);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000369 if (I != Modules.end()) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000370 return I->second.get();
Alexey Samsonov884adda2015-11-04 00:30:24 +0000371 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000372 std::string BinaryName = ModuleName;
373 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000374 size_t ColonPos = ModuleName.find_last_of(':');
375 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000376 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000377 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000378 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000379 BinaryName = ModuleName.substr(0, ColonPos);
380 ArchName = ArchStr;
381 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000382 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000383 auto ObjectsOrErr = getOrCreateObjectPair(BinaryName, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000384 if (!ObjectsOrErr) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000385 // Failed to find valid object file.
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000386 Modules.insert(
387 std::make_pair(ModuleName, std::unique_ptr<SymbolizableModule>()));
388 return ObjectsOrErr.takeError();
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000389 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000390 ObjectPair Objects = ObjectsOrErr.get();
391
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000392 std::unique_ptr<DIContext> Context;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000393 // If this is a COFF object containing PDB info, use a PDBContext to
394 // symbolize. Otherwise, use DWARF.
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000395 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
Saleem Abdulrasool01528022016-08-09 00:25:12 +0000396 const codeview::DebugInfo *DebugInfo;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000397 StringRef PDBFileName;
Saleem Abdulrasool01528022016-08-09 00:25:12 +0000398 auto EC = CoffObject->getDebugPDBInfo(DebugInfo, PDBFileName);
Reid Klecknerd1882f22016-09-01 20:28:59 +0000399 if (!EC && DebugInfo != nullptr && !PDBFileName.empty()) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000400 using namespace pdb;
401 std::unique_ptr<IPDBSession> Session;
402 if (auto Err = loadDataForEXE(PDB_ReaderType::DIA,
403 Objects.first->getFileName(), Session)) {
404 Modules.insert(
405 std::make_pair(ModuleName, std::unique_ptr<SymbolizableModule>()));
406 return std::move(Err);
407 }
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000408 Context.reset(new PDBContext(*CoffObject, std::move(Session)));
Zachary Turnerc007aa42015-05-06 22:26:30 +0000409 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000410 }
411 if (!Context)
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000412 Context.reset(new DWARFContextInMemory(*Objects.second));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000413 assert(Context);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000414 auto InfoOrErr =
Alexey Samsonov8df3a072015-10-29 22:21:37 +0000415 SymbolizableObjectFile::create(Objects.first, std::move(Context));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000416 std::unique_ptr<SymbolizableModule> SymMod;
417 if (InfoOrErr)
418 SymMod = std::move(InfoOrErr.get());
Alexey Samsonov884adda2015-11-04 00:30:24 +0000419 auto InsertResult =
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000420 Modules.insert(std::make_pair(ModuleName, std::move(SymMod)));
Alexey Samsonov884adda2015-11-04 00:30:24 +0000421 assert(InsertResult.second);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000422 if (auto EC = InfoOrErr.getError())
423 return errorCodeToError(EC);
424 return InsertResult.first->second.get();
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000425}
426
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000427namespace {
428
Reid Klecknerc25c7942015-08-10 21:47:11 +0000429// Undo these various manglings for Win32 extern "C" functions:
430// cdecl - _foo
431// stdcall - _foo@12
432// fastcall - @foo@12
433// vectorcall - foo@@12
434// These are all different linkage names for 'foo'.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000435StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
Reid Klecknerc25c7942015-08-10 21:47:11 +0000436 // Remove any '_' or '@' prefix.
437 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
438 if (Front == '_' || Front == '@')
439 SymbolName = SymbolName.drop_front();
440
441 // Remove any '@[0-9]+' suffix.
442 if (Front != '?') {
443 size_t AtPos = SymbolName.rfind('@');
444 if (AtPos != StringRef::npos &&
445 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
446 [](char C) { return C >= '0' && C <= '9'; })) {
447 SymbolName = SymbolName.substr(0, AtPos);
448 }
449 }
450
451 // Remove any ending '@' for vectorcall.
452 if (SymbolName.endswith("@"))
453 SymbolName = SymbolName.drop_back();
454
455 return SymbolName;
456}
457
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000458} // end anonymous namespace
459
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000460#if !defined(_MSC_VER)
461// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
462extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
463 size_t *length, int *status);
464#endif
465
Zachary Turner67c56012017-04-27 16:11:19 +0000466std::string
467LLVMSymbolizer::DemangleName(const std::string &Name,
468 const SymbolizableModule *DbiModuleDescriptor) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000469#if !defined(_MSC_VER)
Ed Masteef6fed72014-01-16 17:25:12 +0000470 // We can spoil names of symbols with C linkage, so use an heuristic
471 // approach to check if the name should be demangled.
Reid Klecknerc25c7942015-08-10 21:47:11 +0000472 if (Name.substr(0, 2) == "_Z") {
473 int status = 0;
474 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
475 if (status != 0)
476 return Name;
477 std::string Result = DemangledName;
478 free(DemangledName);
479 return Result;
480 }
Alexey Samsonov601beb72013-06-28 12:06:25 +0000481#else
Reid Klecknerc25c7942015-08-10 21:47:11 +0000482 if (!Name.empty() && Name.front() == '?') {
483 // Only do MSVC C++ demangling on symbols starting with '?'.
484 char DemangledName[1024] = {0};
485 DWORD result = ::UnDecorateSymbolName(
486 Name.c_str(), DemangledName, 1023,
487 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
488 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
489 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
490 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
491 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
492 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
493 return (result == 0) ? Name : std::string(DemangledName);
494 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000495#endif
Zachary Turner67c56012017-04-27 16:11:19 +0000496 if (DbiModuleDescriptor && DbiModuleDescriptor->isWin32Module())
Reid Klecknerc25c7942015-08-10 21:47:11 +0000497 return std::string(demanglePE32ExternCFunc(Name));
498 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000499}
500
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000501} // namespace symbolize
502} // namespace llvm