blob: 348c2b00bbefb8b9234871ef4424d2742cdc5ed7 [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"
Reid Klecknerc25c7942015-08-10 21:47:11 +000025#include "llvm/Support/COFF.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000026#include "llvm/Support/Casting.h"
Alexey Samsonov3e9997f2013-08-14 17:09:30 +000027#include "llvm/Support/Compression.h"
28#include "llvm/Support/DataExtractor.h"
Rafael Espindola2a826e42014-06-13 17:20:48 +000029#include "llvm/Support/Errc.h"
Alexey Samsonov5239d582013-06-04 07:57:38 +000030#include "llvm/Support/FileSystem.h"
Alexey Samsonov3e9997f2013-08-14 17:09:30 +000031#include "llvm/Support/MemoryBuffer.h"
Alexey Samsonovea83baf2013-01-22 14:21:19 +000032#include "llvm/Support/Path.h"
Alexey Samsonova591ae62013-08-26 18:12:03 +000033#include <stdlib.h>
Alexey Samsonovea83baf2013-01-22 14:21:19 +000034
Zachary Turnerc007aa42015-05-06 22:26:30 +000035#if defined(_MSC_VER)
36#include <Windows.h>
37#include <DbgHelp.h>
Leny Kholodovbebb27b2015-07-02 14:34:57 +000038#pragma comment(lib, "dbghelp.lib")
Reid Klecknerc25c7942015-08-10 21:47:11 +000039
40// Windows.h conflicts with our COFF header definitions.
41#ifdef IMAGE_FILE_MACHINE_I386
42#undef IMAGE_FILE_MACHINE_I386
43#endif
Zachary Turnerc007aa42015-05-06 22:26:30 +000044#endif
45
Alexey Samsonovea83baf2013-01-22 14:21:19 +000046namespace llvm {
47namespace symbolize {
48
Alexey Samsonov57f88372015-10-26 17:56:12 +000049// FIXME: Move this to llvm-symbolizer tool.
Rafael Espindola4453e42942014-06-13 03:07:50 +000050static bool error(std::error_code ec) {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +000051 if (!ec)
52 return false;
Dmitry Vyukovef8fb722013-02-14 13:06:18 +000053 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
54 return true;
55}
56
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000057DILineInfo LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
58 uint64_t ModuleOffset) {
Alexey Samsonov8df3a072015-10-29 22:21:37 +000059 SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName);
Craig Toppere6cb63e2014-04-25 04:24:47 +000060 if (!Info)
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000061 return DILineInfo();
Reid Klecknere94fef72015-10-09 00:15:01 +000062
63 // If the user is giving us relative addresses, add the preferred base of the
64 // object to the offset before we do the query. It's what DIContext expects.
65 if (Opts.RelativeAddresses)
66 ModuleOffset += Info->getModulePreferredBase();
67
Alexey Samsonov0fb64512015-10-26 22:34:56 +000068 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions,
69 Opts.UseSymbolTable);
Alexey Samsonov68812492015-11-03 21:36:13 +000070 if (Opts.Demangle)
71 LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000072 return LineInfo;
Alexey Samsonovea83baf2013-01-22 14:21:19 +000073}
74
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000075DIInliningInfo
76LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
77 uint64_t ModuleOffset) {
Alexey Samsonov46c1ce62015-10-30 00:40:20 +000078 SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName);
79 if (!Info)
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000080 return DIInliningInfo();
Alexey Samsonov46c1ce62015-10-30 00:40:20 +000081
82 // If the user is giving us relative addresses, add the preferred base of the
83 // object to the offset before we do the query. It's what DIContext expects.
84 if (Opts.RelativeAddresses)
85 ModuleOffset += Info->getModulePreferredBase();
86
87 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
88 ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable);
Alexey Samsonov68812492015-11-03 21:36:13 +000089 if (Opts.Demangle) {
90 for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
91 auto *Frame = InlinedContext.getMutableFrame(i);
92 Frame->FunctionName = DemangleName(Frame->FunctionName, Info);
93 }
94 }
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000095 return InlinedContext;
Alexey Samsonov46c1ce62015-10-30 00:40:20 +000096}
97
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000098DIGlobal LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
99 uint64_t ModuleOffset) {
Alexey Samsonov68812492015-11-03 21:36:13 +0000100 if (!Opts.UseSymbolTable)
Alexey Samsonovd6aa8202015-11-03 22:20:52 +0000101 return DIGlobal();
Alexey Samsonov68812492015-11-03 21:36:13 +0000102 SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName);
103 if (!Info)
Alexey Samsonovd6aa8202015-11-03 22:20:52 +0000104 return DIGlobal();
Alexey Samsonov68812492015-11-03 21:36:13 +0000105
106 // If the user is giving us relative addresses, add the preferred base of
107 // the object to the offset before we do the query. It's what DIContext
108 // expects.
109 if (Opts.RelativeAddresses)
110 ModuleOffset += Info->getModulePreferredBase();
111
112 DIGlobal Global = Info->symbolizeData(ModuleOffset);
113 if (Opts.Demangle)
114 Global.Name = DemangleName(Global.Name, Info);
Alexey Samsonovd6aa8202015-11-03 22:20:52 +0000115 return Global;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000116}
117
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000118void LLVMSymbolizer::flush() {
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000119 Modules.clear();
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000120 ObjectPairForPathArch.clear();
Alexey Samsonovfe3a5d92013-06-28 15:08:29 +0000121 ObjectFileForArch.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000122}
123
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000124// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
125// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
126// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
127// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
128static
129std::string getDarwinDWARFResourceForPath(
130 const std::string &Path, const std::string &Basename) {
131 SmallString<16> ResourceName = StringRef(Path);
132 if (sys::path::extension(Path) != ".dSYM") {
133 ResourceName += ".dSYM";
134 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000135 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
136 sys::path::append(ResourceName, Basename);
137 return ResourceName.str();
138}
139
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000140static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000141 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
142 MemoryBuffer::getFileOrSTDIN(Path);
143 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000144 return false;
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000145 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000146}
147
148static bool findDebugBinary(const std::string &OrigPath,
149 const std::string &DebuglinkName, uint32_t CRCHash,
150 std::string &Result) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000151 std::string OrigRealPath = OrigPath;
152#if defined(HAVE_REALPATH)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000153 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000154 OrigRealPath = RP;
155 free(RP);
156 }
157#endif
158 SmallString<16> OrigDir(OrigRealPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000159 llvm::sys::path::remove_filename(OrigDir);
160 SmallString<16> DebugPath = OrigDir;
161 // Try /path/to/original_binary/debuglink_name
162 llvm::sys::path::append(DebugPath, DebuglinkName);
163 if (checkFileCRC(DebugPath, CRCHash)) {
164 Result = DebugPath.str();
165 return true;
166 }
167 // Try /path/to/original_binary/.debug/debuglink_name
Alexey Samsonova591ae62013-08-26 18:12:03 +0000168 DebugPath = OrigRealPath;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000169 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
170 if (checkFileCRC(DebugPath, CRCHash)) {
171 Result = DebugPath.str();
172 return true;
173 }
174 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
175 DebugPath = "/usr/lib/debug";
176 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
177 DebuglinkName);
178 if (checkFileCRC(DebugPath, CRCHash)) {
179 Result = DebugPath.str();
180 return true;
181 }
182 return false;
183}
184
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000185static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000186 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000187 if (!Obj)
188 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000189 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000190 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000191 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000192 Name = Name.substr(Name.find_first_not_of("._"));
193 if (Name == "gnu_debuglink") {
194 StringRef Data;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000195 Section.getContents(Data);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000196 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
197 uint32_t Offset = 0;
198 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
199 // 4-byte align the offset.
200 Offset = (Offset + 3) & ~0x3;
201 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
202 DebugName = DebugNameStr;
203 CRCHash = DE.getU32(&Offset);
204 return true;
205 }
206 }
207 break;
208 }
209 }
210 return false;
211}
212
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000213static
214bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
215 const MachOObjectFile *Obj) {
216 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
217 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
218 if (dbg_uuid.empty() || bin_uuid.empty())
219 return false;
220 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
221}
222
223ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
224 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
225 // On Darwin we may find DWARF in separate object file in
226 // resource directory.
227 std::vector<std::string> DsymPaths;
228 StringRef Filename = sys::path::filename(ExePath);
229 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
230 for (const auto &Path : Opts.DsymHints) {
231 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
232 }
233 for (const auto &path : DsymPaths) {
234 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
235 std::error_code EC = BinaryOrErr.getError();
236 if (EC != errc::no_such_file_or_directory && !error(EC)) {
237 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
238 ObjectFile *DbgObj =
Lang Hamesf04de6e2014-10-31 21:37:49 +0000239 getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000240 const MachOObjectFile *MachDbgObj =
241 dyn_cast<const MachOObjectFile>(DbgObj);
242 if (!MachDbgObj) continue;
243 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000244 addOwningBinary(std::move(B));
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000245 return DbgObj;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000246 }
247 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000248 }
249 return nullptr;
250}
251
252LLVMSymbolizer::ObjectPair
253LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
254 const std::string &ArchName) {
255 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
256 if (I != ObjectPairForPathArch.end())
257 return I->second;
258 ObjectFile *Obj = nullptr;
259 ObjectFile *DbgObj = nullptr;
260 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
261 if (!error(BinaryOrErr.getError())) {
262 OwningBinary<Binary> &B = BinaryOrErr.get();
Lang Hamesf04de6e2014-10-31 21:37:49 +0000263 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000264 if (!Obj) {
265 ObjectPair Res = std::make_pair(nullptr, nullptr);
266 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
267 return Res;
268 }
269 addOwningBinary(std::move(B));
270 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
271 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000272 // Try to locate the debug binary using .gnu_debuglink section.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000273 if (!DbgObj) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000274 std::string DebuglinkName;
275 uint32_t CRCHash;
276 std::string DebugBinaryPath;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000277 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
Rafael Espindola63da2952014-01-15 19:37:43 +0000278 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
279 BinaryOrErr = createBinary(DebugBinaryPath);
280 if (!error(BinaryOrErr.getError())) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000281 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
Lang Hamesf04de6e2014-10-31 21:37:49 +0000282 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000283 addOwningBinary(std::move(B));
Rafael Espindola63da2952014-01-15 19:37:43 +0000284 }
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000285 }
286 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000287 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000288 if (!DbgObj)
289 DbgObj = Obj;
290 ObjectPair Res = std::make_pair(Obj, DbgObj);
291 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000292 return Res;
293}
294
295ObjectFile *
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000296LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
297 const std::string &ArchName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000298 if (!Bin)
299 return nullptr;
300 ObjectFile *Res = nullptr;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000301 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000302 const auto &I = ObjectFileForArch.find(
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000303 std::make_pair(UB, ArchName));
304 if (I != ObjectFileForArch.end())
305 return I->second;
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000306 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
Frederic Rissebc162a2015-06-22 21:33:24 +0000307 UB->getObjectForArch(ArchName);
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000308 if (ParsedObj) {
309 Res = ParsedObj.get().get();
310 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000311 }
312 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
313 } else if (Bin->isObject()) {
314 Res = cast<ObjectFile>(Bin);
315 }
316 return Res;
317}
318
Alexey Samsonov8df3a072015-10-29 22:21:37 +0000319SymbolizableModule *
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000320LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000321 const auto &I = Modules.find(ModuleName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000322 if (I != Modules.end())
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000323 return I->second.get();
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000324 std::string BinaryName = ModuleName;
325 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000326 size_t ColonPos = ModuleName.find_last_of(':');
327 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000328 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000329 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000330 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000331 BinaryName = ModuleName.substr(0, ColonPos);
332 ArchName = ArchStr;
333 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000334 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000335 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000336
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000337 if (!Objects.first) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000338 // Failed to find valid object file.
Alexey Samsonov8df3a072015-10-29 22:21:37 +0000339 Modules.insert(std::make_pair(ModuleName, nullptr));
Craig Toppere6cb63e2014-04-25 04:24:47 +0000340 return nullptr;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000341 }
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000342 std::unique_ptr<DIContext> Context;
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000343 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
344 // If this is a COFF object, assume it contains PDB debug information. If
345 // we don't find any we will fall back to the DWARF case.
346 std::unique_ptr<IPDBSession> Session;
347 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
348 Objects.first->getFileName(), Session);
Zachary Turnerc007aa42015-05-06 22:26:30 +0000349 if (Error == PDB_ErrorCode::Success) {
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000350 Context.reset(new PDBContext(*CoffObject, std::move(Session)));
Zachary Turnerc007aa42015-05-06 22:26:30 +0000351 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000352 }
353 if (!Context)
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000354 Context.reset(new DWARFContextInMemory(*Objects.second));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000355 assert(Context);
Alexey Samsonov8df3a072015-10-29 22:21:37 +0000356 auto ErrOrInfo =
357 SymbolizableObjectFile::create(Objects.first, std::move(Context));
358 if (error(ErrOrInfo.getError())) {
359 Modules.insert(std::make_pair(ModuleName, nullptr));
360 return nullptr;
361 }
362 SymbolizableModule *Res = ErrOrInfo.get().get();
363 Modules.insert(std::make_pair(ModuleName, std::move(ErrOrInfo.get())));
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000364 return Res;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000365}
366
Reid Klecknerc25c7942015-08-10 21:47:11 +0000367// Undo these various manglings for Win32 extern "C" functions:
368// cdecl - _foo
369// stdcall - _foo@12
370// fastcall - @foo@12
371// vectorcall - foo@@12
372// These are all different linkage names for 'foo'.
373static StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
374 // Remove any '_' or '@' prefix.
375 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
376 if (Front == '_' || Front == '@')
377 SymbolName = SymbolName.drop_front();
378
379 // Remove any '@[0-9]+' suffix.
380 if (Front != '?') {
381 size_t AtPos = SymbolName.rfind('@');
382 if (AtPos != StringRef::npos &&
383 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
384 [](char C) { return C >= '0' && C <= '9'; })) {
385 SymbolName = SymbolName.substr(0, AtPos);
386 }
387 }
388
389 // Remove any ending '@' for vectorcall.
390 if (SymbolName.endswith("@"))
391 SymbolName = SymbolName.drop_back();
392
393 return SymbolName;
394}
395
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000396#if !defined(_MSC_VER)
397// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
398extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
399 size_t *length, int *status);
400#endif
401
Reid Klecknerc25c7942015-08-10 21:47:11 +0000402std::string LLVMSymbolizer::DemangleName(const std::string &Name,
Alexey Samsonov8df3a072015-10-29 22:21:37 +0000403 const SymbolizableModule *ModInfo) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000404#if !defined(_MSC_VER)
Ed Masteef6fed72014-01-16 17:25:12 +0000405 // We can spoil names of symbols with C linkage, so use an heuristic
406 // approach to check if the name should be demangled.
Reid Klecknerc25c7942015-08-10 21:47:11 +0000407 if (Name.substr(0, 2) == "_Z") {
408 int status = 0;
409 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
410 if (status != 0)
411 return Name;
412 std::string Result = DemangledName;
413 free(DemangledName);
414 return Result;
415 }
Alexey Samsonov601beb72013-06-28 12:06:25 +0000416#else
Reid Klecknerc25c7942015-08-10 21:47:11 +0000417 if (!Name.empty() && Name.front() == '?') {
418 // Only do MSVC C++ demangling on symbols starting with '?'.
419 char DemangledName[1024] = {0};
420 DWORD result = ::UnDecorateSymbolName(
421 Name.c_str(), DemangledName, 1023,
422 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
423 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
424 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
425 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
426 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
427 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
428 return (result == 0) ? Name : std::string(DemangledName);
429 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000430#endif
Alexey Samsonov76f7ecb2015-10-29 23:49:19 +0000431 if (ModInfo && ModInfo->isWin32Module())
Reid Klecknerc25c7942015-08-10 21:47:11 +0000432 return std::string(demanglePE32ExternCFunc(Name));
433 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000434}
435
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000436} // namespace symbolize
437} // namespace llvm