blob: 57c818f9d27bf977e8658de0a496a6c66a6ed55d [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)
Zachary Turnerc007aa42015-05-06 22:26:30 +000041#include <DbgHelp.h>
Chandler Carruth6bda14b2017-06-06 11:49:48 +000042#include <Windows.h>
Leny Kholodovbebb27b2015-07-02 14:34:57 +000043#pragma comment(lib, "dbghelp.lib")
Reid Klecknerc25c7942015-08-10 21:47:11 +000044
45// Windows.h conflicts with our COFF header definitions.
46#ifdef IMAGE_FILE_MACHINE_I386
47#undef IMAGE_FILE_MACHINE_I386
48#endif
Zachary Turnerc007aa42015-05-06 22:26:30 +000049#endif
50
Alexey Samsonovea83baf2013-01-22 14:21:19 +000051namespace llvm {
52namespace symbolize {
53
Reid Klecknerf27f3f82016-06-03 20:25:09 +000054Expected<DILineInfo> LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
Alexey Samsonov884adda2015-11-04 00:30:24 +000055 uint64_t ModuleOffset) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +000056 SymbolizableModule *Info;
57 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
58 Info = InfoOrErr.get();
59 else
60 return InfoOrErr.takeError();
61
62 // A null module means an error has already been reported. Return an empty
63 // result.
64 if (!Info)
65 return DILineInfo();
Reid Klecknere94fef72015-10-09 00:15:01 +000066
67 // If the user is giving us relative addresses, add the preferred base of the
68 // object to the offset before we do the query. It's what DIContext expects.
69 if (Opts.RelativeAddresses)
70 ModuleOffset += Info->getModulePreferredBase();
71
Alexey Samsonov0fb64512015-10-26 22:34:56 +000072 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions,
73 Opts.UseSymbolTable);
Alexey Samsonov68812492015-11-03 21:36:13 +000074 if (Opts.Demangle)
75 LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000076 return LineInfo;
Alexey Samsonovea83baf2013-01-22 14:21:19 +000077}
78
Reid Klecknerf27f3f82016-06-03 20:25:09 +000079Expected<DIInliningInfo>
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000080LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
81 uint64_t ModuleOffset) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +000082 SymbolizableModule *Info;
83 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
84 Info = InfoOrErr.get();
85 else
86 return InfoOrErr.takeError();
87
88 // A null module means an error has already been reported. Return an empty
89 // result.
90 if (!Info)
91 return DIInliningInfo();
Alexey Samsonov46c1ce62015-10-30 00:40:20 +000092
93 // If the user is giving us relative addresses, add the preferred base of the
94 // object to the offset before we do the query. It's what DIContext expects.
95 if (Opts.RelativeAddresses)
96 ModuleOffset += Info->getModulePreferredBase();
97
98 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
99 ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable);
Alexey Samsonov68812492015-11-03 21:36:13 +0000100 if (Opts.Demangle) {
101 for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
102 auto *Frame = InlinedContext.getMutableFrame(i);
103 Frame->FunctionName = DemangleName(Frame->FunctionName, Info);
104 }
105 }
Alexey Samsonovd6aa8202015-11-03 22:20:52 +0000106 return InlinedContext;
Alexey Samsonov46c1ce62015-10-30 00:40:20 +0000107}
108
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000109Expected<DIGlobal> LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
110 uint64_t ModuleOffset) {
111 SymbolizableModule *Info;
112 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
113 Info = InfoOrErr.get();
114 else
115 return InfoOrErr.takeError();
116
117 // A null module means an error has already been reported. Return an empty
118 // result.
119 if (!Info)
120 return DIGlobal();
Alexey Samsonov68812492015-11-03 21:36:13 +0000121
122 // If the user is giving us relative addresses, add the preferred base of
123 // the object to the offset before we do the query. It's what DIContext
124 // expects.
125 if (Opts.RelativeAddresses)
126 ModuleOffset += Info->getModulePreferredBase();
127
128 DIGlobal Global = Info->symbolizeData(ModuleOffset);
129 if (Opts.Demangle)
130 Global.Name = DemangleName(Global.Name, Info);
Alexey Samsonovd6aa8202015-11-03 22:20:52 +0000131 return Global;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000132}
133
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000134void LLVMSymbolizer::flush() {
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000135 ObjectForUBPathAndArch.clear();
136 BinaryForPath.clear();
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000137 ObjectPairForPathArch.clear();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000138 Modules.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000139}
140
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000141namespace {
142
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000143// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
144// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
145// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
146// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000147std::string getDarwinDWARFResourceForPath(
148 const std::string &Path, const std::string &Basename) {
149 SmallString<16> ResourceName = StringRef(Path);
150 if (sys::path::extension(Path) != ".dSYM") {
151 ResourceName += ".dSYM";
152 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000153 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
154 sys::path::append(ResourceName, Basename);
155 return ResourceName.str();
156}
157
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000158bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000159 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
160 MemoryBuffer::getFileOrSTDIN(Path);
161 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000162 return false;
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000163 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000164}
165
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000166bool findDebugBinary(const std::string &OrigPath,
167 const std::string &DebuglinkName, uint32_t CRCHash,
168 std::string &Result) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000169 std::string OrigRealPath = OrigPath;
170#if defined(HAVE_REALPATH)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000171 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000172 OrigRealPath = RP;
173 free(RP);
174 }
175#endif
176 SmallString<16> OrigDir(OrigRealPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000177 llvm::sys::path::remove_filename(OrigDir);
178 SmallString<16> DebugPath = OrigDir;
179 // Try /path/to/original_binary/debuglink_name
180 llvm::sys::path::append(DebugPath, DebuglinkName);
181 if (checkFileCRC(DebugPath, CRCHash)) {
182 Result = DebugPath.str();
183 return true;
184 }
185 // Try /path/to/original_binary/.debug/debuglink_name
Alexey Samsonova591ae62013-08-26 18:12:03 +0000186 DebugPath = OrigRealPath;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000187 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
188 if (checkFileCRC(DebugPath, CRCHash)) {
189 Result = DebugPath.str();
190 return true;
191 }
192 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
193 DebugPath = "/usr/lib/debug";
194 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
195 DebuglinkName);
196 if (checkFileCRC(DebugPath, CRCHash)) {
197 Result = DebugPath.str();
198 return true;
199 }
200 return false;
201}
202
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000203bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
204 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000205 if (!Obj)
206 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000207 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000208 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000209 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000210 Name = Name.substr(Name.find_first_not_of("._"));
211 if (Name == "gnu_debuglink") {
212 StringRef Data;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000213 Section.getContents(Data);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000214 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
215 uint32_t Offset = 0;
216 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
217 // 4-byte align the offset.
218 Offset = (Offset + 3) & ~0x3;
219 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
220 DebugName = DebugNameStr;
221 CRCHash = DE.getU32(&Offset);
222 return true;
223 }
224 }
225 break;
226 }
227 }
228 return false;
229}
230
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000231bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
232 const MachOObjectFile *Obj) {
233 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
234 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
235 if (dbg_uuid.empty() || bin_uuid.empty())
236 return false;
237 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
238}
239
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000240} // end anonymous namespace
241
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000242ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
243 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
244 // On Darwin we may find DWARF in separate object file in
245 // resource directory.
246 std::vector<std::string> DsymPaths;
247 StringRef Filename = sys::path::filename(ExePath);
248 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
249 for (const auto &Path : Opts.DsymHints) {
250 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
251 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000252 for (const auto &Path : DsymPaths) {
253 auto DbgObjOrErr = getOrCreateObject(Path, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000254 if (!DbgObjOrErr) {
255 // Ignore errors, the file might not exist.
256 consumeError(DbgObjOrErr.takeError());
Alexey Samsonov884adda2015-11-04 00:30:24 +0000257 continue;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000258 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000259 ObjectFile *DbgObj = DbgObjOrErr.get();
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000260 if (!DbgObj)
261 continue;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000262 const MachOObjectFile *MachDbgObj = dyn_cast<const MachOObjectFile>(DbgObj);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000263 if (!MachDbgObj)
264 continue;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000265 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj))
Alexey Samsonov884adda2015-11-04 00:30:24 +0000266 return DbgObj;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000267 }
268 return nullptr;
269}
270
Alexey Samsonov5365a012015-11-04 00:30:26 +0000271ObjectFile *LLVMSymbolizer::lookUpDebuglinkObject(const std::string &Path,
272 const ObjectFile *Obj,
273 const std::string &ArchName) {
274 std::string DebuglinkName;
275 uint32_t CRCHash;
276 std::string DebugBinaryPath;
277 if (!getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash))
278 return nullptr;
279 if (!findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath))
280 return nullptr;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000281 auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000282 if (!DbgObjOrErr) {
283 // Ignore errors, the file might not exist.
284 consumeError(DbgObjOrErr.takeError());
Alexey Samsonov5365a012015-11-04 00:30:26 +0000285 return nullptr;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000286 }
Alexey Samsonov5365a012015-11-04 00:30:26 +0000287 return DbgObjOrErr.get();
288}
289
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000290Expected<LLVMSymbolizer::ObjectPair>
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000291LLVMSymbolizer::getOrCreateObjectPair(const std::string &Path,
292 const std::string &ArchName) {
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000293 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000294 if (I != ObjectPairForPathArch.end()) {
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000295 return I->second;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000296 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000297
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000298 auto ObjOrErr = getOrCreateObject(Path, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000299 if (!ObjOrErr) {
300 ObjectPairForPathArch.insert(std::make_pair(std::make_pair(Path, ArchName),
301 ObjectPair(nullptr, nullptr)));
302 return ObjOrErr.takeError();
Alexey Samsonov884adda2015-11-04 00:30:24 +0000303 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000304
305 ObjectFile *Obj = ObjOrErr.get();
306 assert(Obj != nullptr);
307 ObjectFile *DbgObj = nullptr;
308
309 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
310 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov5365a012015-11-04 00:30:26 +0000311 if (!DbgObj)
312 DbgObj = lookUpDebuglinkObject(Path, Obj, ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000313 if (!DbgObj)
314 DbgObj = Obj;
315 ObjectPair Res = std::make_pair(Obj, DbgObj);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000316 ObjectPairForPathArch.insert(
317 std::make_pair(std::make_pair(Path, ArchName), Res));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000318 return Res;
319}
320
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000321Expected<ObjectFile *>
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000322LLVMSymbolizer::getOrCreateObject(const std::string &Path,
323 const std::string &ArchName) {
324 const auto &I = BinaryForPath.find(Path);
325 Binary *Bin = nullptr;
326 if (I == BinaryForPath.end()) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000327 Expected<OwningBinary<Binary>> BinOrErr = createBinary(Path);
328 if (!BinOrErr) {
Reid Kleckner4ece1632016-06-06 23:46:14 +0000329 BinaryForPath.insert(std::make_pair(Path, OwningBinary<Binary>()));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000330 return BinOrErr.takeError();
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000331 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000332 Bin = BinOrErr->getBinary();
333 BinaryForPath.insert(std::make_pair(Path, std::move(BinOrErr.get())));
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000334 } else {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000335 Bin = I->second.getBinary();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000336 }
337
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000338 if (!Bin)
339 return static_cast<ObjectFile *>(nullptr);
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000340
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000341 if (MachOUniversalBinary *UB = dyn_cast_or_null<MachOUniversalBinary>(Bin)) {
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000342 const auto &I = ObjectForUBPathAndArch.find(std::make_pair(Path, ArchName));
343 if (I != ObjectForUBPathAndArch.end()) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000344 return I->second.get();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000345 }
Kevin Enderby9acb1092016-05-31 20:35:34 +0000346 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000347 UB->getObjectForArch(ArchName);
Kevin Enderby9acb1092016-05-31 20:35:34 +0000348 if (!ObjOrErr) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000349 ObjectForUBPathAndArch.insert(std::make_pair(
350 std::make_pair(Path, ArchName), std::unique_ptr<ObjectFile>()));
351 return ObjOrErr.takeError();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000352 }
353 ObjectFile *Res = ObjOrErr->get();
354 ObjectForUBPathAndArch.insert(std::make_pair(std::make_pair(Path, ArchName),
355 std::move(ObjOrErr.get())));
Alexey Samsonov884adda2015-11-04 00:30:24 +0000356 return Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000357 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000358 if (Bin->isObject()) {
359 return cast<ObjectFile>(Bin);
360 }
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000361 return errorCodeToError(object_error::arch_not_found);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000362}
363
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000364Expected<SymbolizableModule *>
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000365LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000366 const auto &I = Modules.find(ModuleName);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000367 if (I != Modules.end()) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000368 return I->second.get();
Alexey Samsonov884adda2015-11-04 00:30:24 +0000369 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000370 std::string BinaryName = ModuleName;
371 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000372 size_t ColonPos = ModuleName.find_last_of(':');
373 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000374 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000375 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000376 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000377 BinaryName = ModuleName.substr(0, ColonPos);
378 ArchName = ArchStr;
379 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000380 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000381 auto ObjectsOrErr = getOrCreateObjectPair(BinaryName, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000382 if (!ObjectsOrErr) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000383 // Failed to find valid object file.
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000384 Modules.insert(
385 std::make_pair(ModuleName, std::unique_ptr<SymbolizableModule>()));
386 return ObjectsOrErr.takeError();
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000387 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000388 ObjectPair Objects = ObjectsOrErr.get();
389
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000390 std::unique_ptr<DIContext> Context;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000391 // If this is a COFF object containing PDB info, use a PDBContext to
392 // symbolize. Otherwise, use DWARF.
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000393 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
Saleem Abdulrasool01528022016-08-09 00:25:12 +0000394 const codeview::DebugInfo *DebugInfo;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000395 StringRef PDBFileName;
Saleem Abdulrasool01528022016-08-09 00:25:12 +0000396 auto EC = CoffObject->getDebugPDBInfo(DebugInfo, PDBFileName);
Reid Klecknerd1882f22016-09-01 20:28:59 +0000397 if (!EC && DebugInfo != nullptr && !PDBFileName.empty()) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000398 using namespace pdb;
399 std::unique_ptr<IPDBSession> Session;
400 if (auto Err = loadDataForEXE(PDB_ReaderType::DIA,
401 Objects.first->getFileName(), Session)) {
402 Modules.insert(
403 std::make_pair(ModuleName, std::unique_ptr<SymbolizableModule>()));
404 return std::move(Err);
405 }
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000406 Context.reset(new PDBContext(*CoffObject, std::move(Session)));
Zachary Turnerc007aa42015-05-06 22:26:30 +0000407 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000408 }
409 if (!Context)
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000410 Context.reset(new DWARFContextInMemory(*Objects.second));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000411 assert(Context);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000412 auto InfoOrErr =
Alexey Samsonov8df3a072015-10-29 22:21:37 +0000413 SymbolizableObjectFile::create(Objects.first, std::move(Context));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000414 std::unique_ptr<SymbolizableModule> SymMod;
415 if (InfoOrErr)
416 SymMod = std::move(InfoOrErr.get());
Alexey Samsonov884adda2015-11-04 00:30:24 +0000417 auto InsertResult =
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000418 Modules.insert(std::make_pair(ModuleName, std::move(SymMod)));
Alexey Samsonov884adda2015-11-04 00:30:24 +0000419 assert(InsertResult.second);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000420 if (auto EC = InfoOrErr.getError())
421 return errorCodeToError(EC);
422 return InsertResult.first->second.get();
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000423}
424
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000425namespace {
426
Reid Klecknerc25c7942015-08-10 21:47:11 +0000427// Undo these various manglings for Win32 extern "C" functions:
428// cdecl - _foo
429// stdcall - _foo@12
430// fastcall - @foo@12
431// vectorcall - foo@@12
432// These are all different linkage names for 'foo'.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000433StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
Reid Klecknerc25c7942015-08-10 21:47:11 +0000434 // Remove any '_' or '@' prefix.
435 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
436 if (Front == '_' || Front == '@')
437 SymbolName = SymbolName.drop_front();
438
439 // Remove any '@[0-9]+' suffix.
440 if (Front != '?') {
441 size_t AtPos = SymbolName.rfind('@');
442 if (AtPos != StringRef::npos &&
443 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
444 [](char C) { return C >= '0' && C <= '9'; })) {
445 SymbolName = SymbolName.substr(0, AtPos);
446 }
447 }
448
449 // Remove any ending '@' for vectorcall.
450 if (SymbolName.endswith("@"))
451 SymbolName = SymbolName.drop_back();
452
453 return SymbolName;
454}
455
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000456} // end anonymous namespace
457
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000458#if !defined(_MSC_VER)
459// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
460extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
461 size_t *length, int *status);
462#endif
463
Zachary Turner67c56012017-04-27 16:11:19 +0000464std::string
465LLVMSymbolizer::DemangleName(const std::string &Name,
466 const SymbolizableModule *DbiModuleDescriptor) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000467#if !defined(_MSC_VER)
Ed Masteef6fed72014-01-16 17:25:12 +0000468 // We can spoil names of symbols with C linkage, so use an heuristic
469 // approach to check if the name should be demangled.
Reid Klecknerc25c7942015-08-10 21:47:11 +0000470 if (Name.substr(0, 2) == "_Z") {
471 int status = 0;
472 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
473 if (status != 0)
474 return Name;
475 std::string Result = DemangledName;
476 free(DemangledName);
477 return Result;
478 }
Alexey Samsonov601beb72013-06-28 12:06:25 +0000479#else
Reid Klecknerc25c7942015-08-10 21:47:11 +0000480 if (!Name.empty() && Name.front() == '?') {
481 // Only do MSVC C++ demangling on symbols starting with '?'.
482 char DemangledName[1024] = {0};
483 DWORD result = ::UnDecorateSymbolName(
484 Name.c_str(), DemangledName, 1023,
485 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
486 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
487 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
488 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
489 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
490 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
491 return (result == 0) ? Name : std::string(DemangledName);
492 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000493#endif
Zachary Turner67c56012017-04-27 16:11:19 +0000494 if (DbiModuleDescriptor && DbiModuleDescriptor->isWin32Module())
Reid Klecknerc25c7942015-08-10 21:47:11 +0000495 return std::string(demanglePE32ExternCFunc(Name));
496 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000497}
498
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000499} // namespace symbolize
500} // namespace llvm