blob: e2732bf819eb7821968b892f80f53be0c5ebcea5 [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"
Alexey Samsonova5f07682014-02-26 13:10:01 +000023#include "llvm/Object/ELFObjectFile.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000024#include "llvm/Object/MachO.h"
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +000025#include "llvm/Object/MachOUniversal.h"
Reid Klecknerc25c7942015-08-10 21:47:11 +000026#include "llvm/Support/COFF.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000027#include "llvm/Support/Casting.h"
Alexey Samsonov3e9997f2013-08-14 17:09:30 +000028#include "llvm/Support/Compression.h"
29#include "llvm/Support/DataExtractor.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000030#include "llvm/Support/Errc.h"
Alexey Samsonov5239d582013-06-04 07:57:38 +000031#include "llvm/Support/FileSystem.h"
Alexey Samsonov3e9997f2013-08-14 17:09:30 +000032#include "llvm/Support/MemoryBuffer.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000033#include "llvm/Support/Path.h"
Eugene Zelenko35623fb2016-03-28 17:40:08 +000034#include <algorithm>
35#include <cassert>
36#include <cstdlib>
37#include <cstring>
Alexey Samsonovea83baf2013-01-22 14:21:19 +000038
Zachary Turnerc007aa42015-05-06 22:26:30 +000039#if defined(_MSC_VER)
40#include <Windows.h>
41#include <DbgHelp.h>
Leny Kholodovbebb27b2015-07-02 14:34:57 +000042#pragma comment(lib, "dbghelp.lib")
Reid Klecknerc25c7942015-08-10 21:47:11 +000043
44// Windows.h conflicts with our COFF header definitions.
45#ifdef IMAGE_FILE_MACHINE_I386
46#undef IMAGE_FILE_MACHINE_I386
47#endif
Zachary Turnerc007aa42015-05-06 22:26:30 +000048#endif
49
Alexey Samsonovea83baf2013-01-22 14:21:19 +000050namespace llvm {
51namespace symbolize {
52
Reid Klecknerf27f3f82016-06-03 20:25:09 +000053Expected<DILineInfo> LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
Alexey Samsonov884adda2015-11-04 00:30:24 +000054 uint64_t ModuleOffset) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +000055 SymbolizableModule *Info;
56 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
57 Info = InfoOrErr.get();
58 else
59 return InfoOrErr.takeError();
60
61 // A null module means an error has already been reported. Return an empty
62 // result.
63 if (!Info)
64 return DILineInfo();
Reid Klecknere94fef72015-10-09 00:15:01 +000065
66 // If the user is giving us relative addresses, add the preferred base of the
67 // object to the offset before we do the query. It's what DIContext expects.
68 if (Opts.RelativeAddresses)
69 ModuleOffset += Info->getModulePreferredBase();
70
Alexey Samsonov0fb64512015-10-26 22:34:56 +000071 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions,
72 Opts.UseSymbolTable);
Alexey Samsonov68812492015-11-03 21:36:13 +000073 if (Opts.Demangle)
74 LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000075 return LineInfo;
Alexey Samsonovea83baf2013-01-22 14:21:19 +000076}
77
Reid Klecknerf27f3f82016-06-03 20:25:09 +000078Expected<DIInliningInfo>
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000079LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
80 uint64_t ModuleOffset) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +000081 SymbolizableModule *Info;
82 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
83 Info = InfoOrErr.get();
84 else
85 return InfoOrErr.takeError();
86
87 // A null module means an error has already been reported. Return an empty
88 // result.
89 if (!Info)
90 return DIInliningInfo();
Alexey Samsonov46c1ce62015-10-30 00:40:20 +000091
92 // If the user is giving us relative addresses, add the preferred base of the
93 // object to the offset before we do the query. It's what DIContext expects.
94 if (Opts.RelativeAddresses)
95 ModuleOffset += Info->getModulePreferredBase();
96
97 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
98 ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable);
Alexey Samsonov68812492015-11-03 21:36:13 +000099 if (Opts.Demangle) {
100 for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
101 auto *Frame = InlinedContext.getMutableFrame(i);
102 Frame->FunctionName = DemangleName(Frame->FunctionName, Info);
103 }
104 }
Alexey Samsonovd6aa8202015-11-03 22:20:52 +0000105 return InlinedContext;
Alexey Samsonov46c1ce62015-10-30 00:40:20 +0000106}
107
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000108Expected<DIGlobal> LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
109 uint64_t ModuleOffset) {
110 SymbolizableModule *Info;
111 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
112 Info = InfoOrErr.get();
113 else
114 return InfoOrErr.takeError();
115
116 // A null module means an error has already been reported. Return an empty
117 // result.
118 if (!Info)
119 return DIGlobal();
Alexey Samsonov68812492015-11-03 21:36:13 +0000120
121 // If the user is giving us relative addresses, add the preferred base of
122 // the object to the offset before we do the query. It's what DIContext
123 // expects.
124 if (Opts.RelativeAddresses)
125 ModuleOffset += Info->getModulePreferredBase();
126
127 DIGlobal Global = Info->symbolizeData(ModuleOffset);
128 if (Opts.Demangle)
129 Global.Name = DemangleName(Global.Name, Info);
Alexey Samsonovd6aa8202015-11-03 22:20:52 +0000130 return Global;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000131}
132
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000133void LLVMSymbolizer::flush() {
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000134 ObjectForUBPathAndArch.clear();
135 BinaryForPath.clear();
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000136 ObjectPairForPathArch.clear();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000137 Modules.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000138}
139
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000140namespace {
141
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000142// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
143// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
144// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
145// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000146std::string getDarwinDWARFResourceForPath(
147 const std::string &Path, const std::string &Basename) {
148 SmallString<16> ResourceName = StringRef(Path);
149 if (sys::path::extension(Path) != ".dSYM") {
150 ResourceName += ".dSYM";
151 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000152 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
153 sys::path::append(ResourceName, Basename);
154 return ResourceName.str();
155}
156
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000157bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000158 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
159 MemoryBuffer::getFileOrSTDIN(Path);
160 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000161 return false;
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000162 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000163}
164
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000165bool findDebugBinary(const std::string &OrigPath,
166 const std::string &DebuglinkName, uint32_t CRCHash,
167 std::string &Result) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000168 std::string OrigRealPath = OrigPath;
169#if defined(HAVE_REALPATH)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000170 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000171 OrigRealPath = RP;
172 free(RP);
173 }
174#endif
175 SmallString<16> OrigDir(OrigRealPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000176 llvm::sys::path::remove_filename(OrigDir);
177 SmallString<16> DebugPath = OrigDir;
178 // Try /path/to/original_binary/debuglink_name
179 llvm::sys::path::append(DebugPath, DebuglinkName);
180 if (checkFileCRC(DebugPath, CRCHash)) {
181 Result = DebugPath.str();
182 return true;
183 }
184 // Try /path/to/original_binary/.debug/debuglink_name
Alexey Samsonova591ae62013-08-26 18:12:03 +0000185 DebugPath = OrigRealPath;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000186 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
187 if (checkFileCRC(DebugPath, CRCHash)) {
188 Result = DebugPath.str();
189 return true;
190 }
191 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
192 DebugPath = "/usr/lib/debug";
193 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
194 DebuglinkName);
195 if (checkFileCRC(DebugPath, CRCHash)) {
196 Result = DebugPath.str();
197 return true;
198 }
199 return false;
200}
201
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000202bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
203 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000204 if (!Obj)
205 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000206 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000207 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000208 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000209 Name = Name.substr(Name.find_first_not_of("._"));
210 if (Name == "gnu_debuglink") {
211 StringRef Data;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000212 Section.getContents(Data);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000213 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
214 uint32_t Offset = 0;
215 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
216 // 4-byte align the offset.
217 Offset = (Offset + 3) & ~0x3;
218 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
219 DebugName = DebugNameStr;
220 CRCHash = DE.getU32(&Offset);
221 return true;
222 }
223 }
224 break;
225 }
226 }
227 return false;
228}
229
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000230bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
231 const MachOObjectFile *Obj) {
232 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
233 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
234 if (dbg_uuid.empty() || bin_uuid.empty())
235 return false;
236 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
237}
238
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000239} // end anonymous namespace
240
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000241ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
242 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
243 // On Darwin we may find DWARF in separate object file in
244 // resource directory.
245 std::vector<std::string> DsymPaths;
246 StringRef Filename = sys::path::filename(ExePath);
247 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
248 for (const auto &Path : Opts.DsymHints) {
249 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
250 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000251 for (const auto &Path : DsymPaths) {
252 auto DbgObjOrErr = getOrCreateObject(Path, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000253 if (!DbgObjOrErr) {
254 // Ignore errors, the file might not exist.
255 consumeError(DbgObjOrErr.takeError());
Alexey Samsonov884adda2015-11-04 00:30:24 +0000256 continue;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000257 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000258 ObjectFile *DbgObj = DbgObjOrErr.get();
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000259 if (!DbgObj)
260 continue;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000261 const MachOObjectFile *MachDbgObj = dyn_cast<const MachOObjectFile>(DbgObj);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000262 if (!MachDbgObj)
263 continue;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000264 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj))
Alexey Samsonov884adda2015-11-04 00:30:24 +0000265 return DbgObj;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000266 }
267 return nullptr;
268}
269
Alexey Samsonov5365a012015-11-04 00:30:26 +0000270ObjectFile *LLVMSymbolizer::lookUpDebuglinkObject(const std::string &Path,
271 const ObjectFile *Obj,
272 const std::string &ArchName) {
273 std::string DebuglinkName;
274 uint32_t CRCHash;
275 std::string DebugBinaryPath;
276 if (!getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash))
277 return nullptr;
278 if (!findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath))
279 return nullptr;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000280 auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000281 if (!DbgObjOrErr) {
282 // Ignore errors, the file might not exist.
283 consumeError(DbgObjOrErr.takeError());
Alexey Samsonov5365a012015-11-04 00:30:26 +0000284 return nullptr;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000285 }
Alexey Samsonov5365a012015-11-04 00:30:26 +0000286 return DbgObjOrErr.get();
287}
288
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000289Expected<LLVMSymbolizer::ObjectPair>
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000290LLVMSymbolizer::getOrCreateObjectPair(const std::string &Path,
291 const std::string &ArchName) {
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000292 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000293 if (I != ObjectPairForPathArch.end()) {
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000294 return I->second;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000295 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000296
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000297 auto ObjOrErr = getOrCreateObject(Path, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000298 if (!ObjOrErr) {
299 ObjectPairForPathArch.insert(std::make_pair(std::make_pair(Path, ArchName),
300 ObjectPair(nullptr, nullptr)));
301 return ObjOrErr.takeError();
Alexey Samsonov884adda2015-11-04 00:30:24 +0000302 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000303
304 ObjectFile *Obj = ObjOrErr.get();
305 assert(Obj != nullptr);
306 ObjectFile *DbgObj = nullptr;
307
308 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
309 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov5365a012015-11-04 00:30:26 +0000310 if (!DbgObj)
311 DbgObj = lookUpDebuglinkObject(Path, Obj, ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000312 if (!DbgObj)
313 DbgObj = Obj;
314 ObjectPair Res = std::make_pair(Obj, DbgObj);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000315 ObjectPairForPathArch.insert(
316 std::make_pair(std::make_pair(Path, ArchName), Res));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000317 return Res;
318}
319
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000320Expected<ObjectFile *>
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000321LLVMSymbolizer::getOrCreateObject(const std::string &Path,
322 const std::string &ArchName) {
323 const auto &I = BinaryForPath.find(Path);
324 Binary *Bin = nullptr;
325 if (I == BinaryForPath.end()) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000326 Expected<OwningBinary<Binary>> BinOrErr = createBinary(Path);
327 if (!BinOrErr) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000328 BinaryForPath.insert({Path, OwningBinary<Binary>()});
329 return BinOrErr.takeError();
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000330 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000331 Bin = BinOrErr->getBinary();
332 BinaryForPath.insert(std::make_pair(Path, std::move(BinOrErr.get())));
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000333 } else {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000334 Bin = I->second.getBinary();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000335 }
336
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000337 if (!Bin)
338 return static_cast<ObjectFile *>(nullptr);
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000339
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000340 if (MachOUniversalBinary *UB = dyn_cast_or_null<MachOUniversalBinary>(Bin)) {
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000341 const auto &I = ObjectForUBPathAndArch.find(std::make_pair(Path, ArchName));
342 if (I != ObjectForUBPathAndArch.end()) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000343 return I->second.get();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000344 }
Kevin Enderby9acb1092016-05-31 20:35:34 +0000345 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000346 UB->getObjectForArch(ArchName);
Kevin Enderby9acb1092016-05-31 20:35:34 +0000347 if (!ObjOrErr) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000348 ObjectForUBPathAndArch.insert(std::make_pair(
349 std::make_pair(Path, ArchName), std::unique_ptr<ObjectFile>()));
350 return ObjOrErr.takeError();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000351 }
352 ObjectFile *Res = ObjOrErr->get();
353 ObjectForUBPathAndArch.insert(std::make_pair(std::make_pair(Path, ArchName),
354 std::move(ObjOrErr.get())));
Alexey Samsonov884adda2015-11-04 00:30:24 +0000355 return Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000356 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000357 if (Bin->isObject()) {
358 return cast<ObjectFile>(Bin);
359 }
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000360 return errorCodeToError(object_error::arch_not_found);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000361}
362
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000363Expected<SymbolizableModule *>
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000364LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000365 const auto &I = Modules.find(ModuleName);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000366 if (I != Modules.end()) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000367 return I->second.get();
Alexey Samsonov884adda2015-11-04 00:30:24 +0000368 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000369 std::string BinaryName = ModuleName;
370 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000371 size_t ColonPos = ModuleName.find_last_of(':');
372 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000373 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000374 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000375 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000376 BinaryName = ModuleName.substr(0, ColonPos);
377 ArchName = ArchStr;
378 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000379 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000380 auto ObjectsOrErr = getOrCreateObjectPair(BinaryName, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000381 if (!ObjectsOrErr) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000382 // Failed to find valid object file.
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000383 Modules.insert(
384 std::make_pair(ModuleName, std::unique_ptr<SymbolizableModule>()));
385 return ObjectsOrErr.takeError();
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000386 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000387 ObjectPair Objects = ObjectsOrErr.get();
388
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000389 std::unique_ptr<DIContext> Context;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000390 // If this is a COFF object containing PDB info, use a PDBContext to
391 // symbolize. Otherwise, use DWARF.
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000392 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000393 const debug_pdb_info *PDBInfo;
394 StringRef PDBFileName;
395 auto EC = CoffObject->getDebugPDBInfo(PDBInfo, PDBFileName);
396 if (!EC && PDBInfo != nullptr) {
397 using namespace pdb;
398 std::unique_ptr<IPDBSession> Session;
399 if (auto Err = loadDataForEXE(PDB_ReaderType::DIA,
400 Objects.first->getFileName(), Session)) {
401 Modules.insert(
402 std::make_pair(ModuleName, std::unique_ptr<SymbolizableModule>()));
403 return std::move(Err);
404 }
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000405 Context.reset(new PDBContext(*CoffObject, std::move(Session)));
Zachary Turnerc007aa42015-05-06 22:26:30 +0000406 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000407 }
408 if (!Context)
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000409 Context.reset(new DWARFContextInMemory(*Objects.second));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000410 assert(Context);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000411 auto InfoOrErr =
Alexey Samsonov8df3a072015-10-29 22:21:37 +0000412 SymbolizableObjectFile::create(Objects.first, std::move(Context));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000413 std::unique_ptr<SymbolizableModule> SymMod;
414 if (InfoOrErr)
415 SymMod = std::move(InfoOrErr.get());
Alexey Samsonov884adda2015-11-04 00:30:24 +0000416 auto InsertResult =
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000417 Modules.insert(std::make_pair(ModuleName, std::move(SymMod)));
Alexey Samsonov884adda2015-11-04 00:30:24 +0000418 assert(InsertResult.second);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000419 if (auto EC = InfoOrErr.getError())
420 return errorCodeToError(EC);
421 return InsertResult.first->second.get();
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000422}
423
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000424namespace {
425
Reid Klecknerc25c7942015-08-10 21:47:11 +0000426// Undo these various manglings for Win32 extern "C" functions:
427// cdecl - _foo
428// stdcall - _foo@12
429// fastcall - @foo@12
430// vectorcall - foo@@12
431// These are all different linkage names for 'foo'.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000432StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
Reid Klecknerc25c7942015-08-10 21:47:11 +0000433 // Remove any '_' or '@' prefix.
434 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
435 if (Front == '_' || Front == '@')
436 SymbolName = SymbolName.drop_front();
437
438 // Remove any '@[0-9]+' suffix.
439 if (Front != '?') {
440 size_t AtPos = SymbolName.rfind('@');
441 if (AtPos != StringRef::npos &&
442 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
443 [](char C) { return C >= '0' && C <= '9'; })) {
444 SymbolName = SymbolName.substr(0, AtPos);
445 }
446 }
447
448 // Remove any ending '@' for vectorcall.
449 if (SymbolName.endswith("@"))
450 SymbolName = SymbolName.drop_back();
451
452 return SymbolName;
453}
454
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000455} // end anonymous namespace
456
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000457#if !defined(_MSC_VER)
458// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
459extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
460 size_t *length, int *status);
461#endif
462
Reid Klecknerc25c7942015-08-10 21:47:11 +0000463std::string LLVMSymbolizer::DemangleName(const std::string &Name,
Alexey Samsonov8df3a072015-10-29 22:21:37 +0000464 const SymbolizableModule *ModInfo) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000465#if !defined(_MSC_VER)
Ed Masteef6fed72014-01-16 17:25:12 +0000466 // We can spoil names of symbols with C linkage, so use an heuristic
467 // approach to check if the name should be demangled.
Reid Klecknerc25c7942015-08-10 21:47:11 +0000468 if (Name.substr(0, 2) == "_Z") {
469 int status = 0;
470 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
471 if (status != 0)
472 return Name;
473 std::string Result = DemangledName;
474 free(DemangledName);
475 return Result;
476 }
Alexey Samsonov601beb72013-06-28 12:06:25 +0000477#else
Reid Klecknerc25c7942015-08-10 21:47:11 +0000478 if (!Name.empty() && Name.front() == '?') {
479 // Only do MSVC C++ demangling on symbols starting with '?'.
480 char DemangledName[1024] = {0};
481 DWORD result = ::UnDecorateSymbolName(
482 Name.c_str(), DemangledName, 1023,
483 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
484 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
485 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
486 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
487 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
488 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
489 return (result == 0) ? Name : std::string(DemangledName);
490 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000491#endif
Alexey Samsonov76f7ecb2015-10-29 23:49:19 +0000492 if (ModInfo && ModInfo->isWin32Module())
Reid Klecknerc25c7942015-08-10 21:47:11 +0000493 return std::string(demanglePE32ExternCFunc(Name));
494 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000495}
496
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000497} // namespace symbolize
498} // namespace llvm