blob: 2e6f60416a4e0881a5c2a3eefbd430bfd7bd2289 [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 Samsonovea83baf2013-01-22 14:21:19 +000033#include <sstream>
Alexey Samsonova591ae62013-08-26 18:12:03 +000034#include <stdlib.h>
Alexey Samsonovea83baf2013-01-22 14:21:19 +000035
Zachary Turnerc007aa42015-05-06 22:26:30 +000036#if defined(_MSC_VER)
37#include <Windows.h>
38#include <DbgHelp.h>
Leny Kholodovbebb27b2015-07-02 14:34:57 +000039#pragma comment(lib, "dbghelp.lib")
Reid Klecknerc25c7942015-08-10 21:47:11 +000040
41// Windows.h conflicts with our COFF header definitions.
42#ifdef IMAGE_FILE_MACHINE_I386
43#undef IMAGE_FILE_MACHINE_I386
44#endif
Zachary Turnerc007aa42015-05-06 22:26:30 +000045#endif
46
Alexey Samsonovea83baf2013-01-22 14:21:19 +000047namespace llvm {
48namespace symbolize {
49
Alexey Samsonov57f88372015-10-26 17:56:12 +000050// FIXME: Move this to llvm-symbolizer tool.
Rafael Espindola4453e42942014-06-13 03:07:50 +000051static bool error(std::error_code ec) {
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +000052 if (!ec)
53 return false;
Dmitry Vyukovef8fb722013-02-14 13:06:18 +000054 errs() << "LLVMSymbolizer: error reading file: " << ec.message() << ".\n";
55 return true;
56}
57
Alexey Samsonovea83baf2013-01-22 14:21:19 +000058
Alexey Samsonov76f7ecb2015-10-29 23:49:19 +000059// By default, DILineInfo contains "<invalid>" for function/filename it
60// cannot fetch. We replace it to "??" to make our output closer to addr2line.
61static const char kDILineInfoBadString[] = "<invalid>";
62
Alexey Samsonovd6cef102013-02-04 15:55:26 +000063const char LLVMSymbolizer::kBadString[] = "??";
Alexey Samsonovea83baf2013-01-22 14:21:19 +000064
65std::string LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
66 uint64_t ModuleOffset) {
Alexey Samsonov8df3a072015-10-29 22:21:37 +000067 SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName);
Craig Toppere6cb63e2014-04-25 04:24:47 +000068 if (!Info)
Reid Klecknerc25c7942015-08-10 21:47:11 +000069 return printDILineInfo(DILineInfo(), Info);
Reid Klecknere94fef72015-10-09 00:15:01 +000070
71 // If the user is giving us relative addresses, add the preferred base of the
72 // object to the offset before we do the query. It's what DIContext expects.
73 if (Opts.RelativeAddresses)
74 ModuleOffset += Info->getModulePreferredBase();
75
Alexey Samsonov0fb64512015-10-26 22:34:56 +000076 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions,
77 Opts.UseSymbolTable);
Reid Klecknerc25c7942015-08-10 21:47:11 +000078 return printDILineInfo(LineInfo, Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +000079}
80
Alexey Samsonov46c1ce62015-10-30 00:40:20 +000081std::string LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
82 uint64_t ModuleOffset) {
83 SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName);
84 if (!Info)
85 return printDIInliningInfo(DIInliningInfo(), nullptr);
86
87 // If the user is giving us relative addresses, add the preferred base of the
88 // object to the offset before we do the query. It's what DIContext expects.
89 if (Opts.RelativeAddresses)
90 ModuleOffset += Info->getModulePreferredBase();
91
92 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
93 ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable);
94 return printDIInliningInfo(InlinedContext, Info);
95}
96
Alexey Samsonovea83baf2013-01-22 14:21:19 +000097std::string LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
98 uint64_t ModuleOffset) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +000099 if (Opts.UseSymbolTable) {
Alexey Samsonov8df3a072015-10-29 22:21:37 +0000100 if (SymbolizableModule *Info = getOrCreateModuleInfo(ModuleName)) {
101 // If the user is giving us relative addresses, add the preferred base of
102 // the object to the offset before we do the query. It's what DIContext
103 // expects.
Reid Klecknere94fef72015-10-09 00:15:01 +0000104 if (Opts.RelativeAddresses)
105 ModuleOffset += Info->getModulePreferredBase();
Alexey Samsonov76f7ecb2015-10-29 23:49:19 +0000106 DIGlobal Global = Info->symbolizeData(ModuleOffset);
107 return printDIGlobal(Global, Info);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000108 }
109 }
Alexey Samsonov76f7ecb2015-10-29 23:49:19 +0000110 return printDIGlobal(DIGlobal(), nullptr);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000111}
112
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000113void LLVMSymbolizer::flush() {
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000114 Modules.clear();
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000115 ObjectPairForPathArch.clear();
Alexey Samsonovfe3a5d92013-06-28 15:08:29 +0000116 ObjectFileForArch.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000117}
118
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000119// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
120// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
121// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
122// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
123static
124std::string getDarwinDWARFResourceForPath(
125 const std::string &Path, const std::string &Basename) {
126 SmallString<16> ResourceName = StringRef(Path);
127 if (sys::path::extension(Path) != ".dSYM") {
128 ResourceName += ".dSYM";
129 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000130 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
131 sys::path::append(ResourceName, Basename);
132 return ResourceName.str();
133}
134
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000135static bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000136 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
137 MemoryBuffer::getFileOrSTDIN(Path);
138 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000139 return false;
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000140 return !zlib::isAvailable() || CRCHash == zlib::crc32(MB.get()->getBuffer());
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000141}
142
143static bool findDebugBinary(const std::string &OrigPath,
144 const std::string &DebuglinkName, uint32_t CRCHash,
145 std::string &Result) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000146 std::string OrigRealPath = OrigPath;
147#if defined(HAVE_REALPATH)
Craig Toppere6cb63e2014-04-25 04:24:47 +0000148 if (char *RP = realpath(OrigPath.c_str(), nullptr)) {
Alexey Samsonova591ae62013-08-26 18:12:03 +0000149 OrigRealPath = RP;
150 free(RP);
151 }
152#endif
153 SmallString<16> OrigDir(OrigRealPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000154 llvm::sys::path::remove_filename(OrigDir);
155 SmallString<16> DebugPath = OrigDir;
156 // Try /path/to/original_binary/debuglink_name
157 llvm::sys::path::append(DebugPath, DebuglinkName);
158 if (checkFileCRC(DebugPath, CRCHash)) {
159 Result = DebugPath.str();
160 return true;
161 }
162 // Try /path/to/original_binary/.debug/debuglink_name
Alexey Samsonova591ae62013-08-26 18:12:03 +0000163 DebugPath = OrigRealPath;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000164 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
165 if (checkFileCRC(DebugPath, CRCHash)) {
166 Result = DebugPath.str();
167 return true;
168 }
169 // Try /usr/lib/debug/path/to/original_binary/debuglink_name
170 DebugPath = "/usr/lib/debug";
171 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
172 DebuglinkName);
173 if (checkFileCRC(DebugPath, CRCHash)) {
174 Result = DebugPath.str();
175 return true;
176 }
177 return false;
178}
179
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000180static bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000181 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000182 if (!Obj)
183 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000184 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000185 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000186 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000187 Name = Name.substr(Name.find_first_not_of("._"));
188 if (Name == "gnu_debuglink") {
189 StringRef Data;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000190 Section.getContents(Data);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000191 DataExtractor DE(Data, Obj->isLittleEndian(), 0);
192 uint32_t Offset = 0;
193 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
194 // 4-byte align the offset.
195 Offset = (Offset + 3) & ~0x3;
196 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
197 DebugName = DebugNameStr;
198 CRCHash = DE.getU32(&Offset);
199 return true;
200 }
201 }
202 break;
203 }
204 }
205 return false;
206}
207
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000208static
209bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
210 const MachOObjectFile *Obj) {
211 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
212 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
213 if (dbg_uuid.empty() || bin_uuid.empty())
214 return false;
215 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
216}
217
218ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
219 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
220 // On Darwin we may find DWARF in separate object file in
221 // resource directory.
222 std::vector<std::string> DsymPaths;
223 StringRef Filename = sys::path::filename(ExePath);
224 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
225 for (const auto &Path : Opts.DsymHints) {
226 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
227 }
228 for (const auto &path : DsymPaths) {
229 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(path);
230 std::error_code EC = BinaryOrErr.getError();
231 if (EC != errc::no_such_file_or_directory && !error(EC)) {
232 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
233 ObjectFile *DbgObj =
Lang Hamesf04de6e2014-10-31 21:37:49 +0000234 getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000235 const MachOObjectFile *MachDbgObj =
236 dyn_cast<const MachOObjectFile>(DbgObj);
237 if (!MachDbgObj) continue;
238 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj)) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000239 addOwningBinary(std::move(B));
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000240 return DbgObj;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000241 }
242 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000243 }
244 return nullptr;
245}
246
247LLVMSymbolizer::ObjectPair
248LLVMSymbolizer::getOrCreateObjects(const std::string &Path,
249 const std::string &ArchName) {
250 const auto &I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
251 if (I != ObjectPairForPathArch.end())
252 return I->second;
253 ObjectFile *Obj = nullptr;
254 ObjectFile *DbgObj = nullptr;
255 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Path);
256 if (!error(BinaryOrErr.getError())) {
257 OwningBinary<Binary> &B = BinaryOrErr.get();
Lang Hamesf04de6e2014-10-31 21:37:49 +0000258 Obj = getObjectFileFromBinary(B.getBinary(), ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000259 if (!Obj) {
260 ObjectPair Res = std::make_pair(nullptr, nullptr);
261 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
262 return Res;
263 }
264 addOwningBinary(std::move(B));
265 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
266 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000267 // Try to locate the debug binary using .gnu_debuglink section.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000268 if (!DbgObj) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000269 std::string DebuglinkName;
270 uint32_t CRCHash;
271 std::string DebugBinaryPath;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000272 if (getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash) &&
Rafael Espindola63da2952014-01-15 19:37:43 +0000273 findDebugBinary(Path, DebuglinkName, CRCHash, DebugBinaryPath)) {
274 BinaryOrErr = createBinary(DebugBinaryPath);
275 if (!error(BinaryOrErr.getError())) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000276 OwningBinary<Binary> B = std::move(BinaryOrErr.get());
Lang Hamesf04de6e2014-10-31 21:37:49 +0000277 DbgObj = getObjectFileFromBinary(B.getBinary(), ArchName);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000278 addOwningBinary(std::move(B));
Rafael Espindola63da2952014-01-15 19:37:43 +0000279 }
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000280 }
281 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000282 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000283 if (!DbgObj)
284 DbgObj = Obj;
285 ObjectPair Res = std::make_pair(Obj, DbgObj);
286 ObjectPairForPathArch[std::make_pair(Path, ArchName)] = Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000287 return Res;
288}
289
290ObjectFile *
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000291LLVMSymbolizer::getObjectFileFromBinary(Binary *Bin,
292 const std::string &ArchName) {
Craig Toppere6cb63e2014-04-25 04:24:47 +0000293 if (!Bin)
294 return nullptr;
295 ObjectFile *Res = nullptr;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000296 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Bin)) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000297 const auto &I = ObjectFileForArch.find(
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000298 std::make_pair(UB, ArchName));
299 if (I != ObjectFileForArch.end())
300 return I->second;
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000301 ErrorOr<std::unique_ptr<ObjectFile>> ParsedObj =
Frederic Rissebc162a2015-06-22 21:33:24 +0000302 UB->getObjectForArch(ArchName);
Rafael Espindola4f7932b2014-06-23 20:41:02 +0000303 if (ParsedObj) {
304 Res = ParsedObj.get().get();
305 ParsedBinariesAndObjects.push_back(std::move(ParsedObj.get()));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000306 }
307 ObjectFileForArch[std::make_pair(UB, ArchName)] = Res;
308 } else if (Bin->isObject()) {
309 Res = cast<ObjectFile>(Bin);
310 }
311 return Res;
312}
313
Alexey Samsonov8df3a072015-10-29 22:21:37 +0000314SymbolizableModule *
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000315LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
Alexander Potapenko45bfe372014-10-14 13:40:44 +0000316 const auto &I = Modules.find(ModuleName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000317 if (I != Modules.end())
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000318 return I->second.get();
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000319 std::string BinaryName = ModuleName;
320 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000321 size_t ColonPos = ModuleName.find_last_of(':');
322 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000323 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000324 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000325 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000326 BinaryName = ModuleName.substr(0, ColonPos);
327 ArchName = ArchStr;
328 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000329 }
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000330 ObjectPair Objects = getOrCreateObjects(BinaryName, ArchName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000331
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000332 if (!Objects.first) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000333 // Failed to find valid object file.
Alexey Samsonov8df3a072015-10-29 22:21:37 +0000334 Modules.insert(std::make_pair(ModuleName, nullptr));
Craig Toppere6cb63e2014-04-25 04:24:47 +0000335 return nullptr;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000336 }
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000337 std::unique_ptr<DIContext> Context;
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000338 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
339 // If this is a COFF object, assume it contains PDB debug information. If
340 // we don't find any we will fall back to the DWARF case.
341 std::unique_ptr<IPDBSession> Session;
342 PDB_ErrorCode Error = loadDataForEXE(PDB_ReaderType::DIA,
343 Objects.first->getFileName(), Session);
Zachary Turnerc007aa42015-05-06 22:26:30 +0000344 if (Error == PDB_ErrorCode::Success) {
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000345 Context.reset(new PDBContext(*CoffObject, std::move(Session)));
Zachary Turnerc007aa42015-05-06 22:26:30 +0000346 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000347 }
348 if (!Context)
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000349 Context.reset(new DWARFContextInMemory(*Objects.second));
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000350 assert(Context);
Alexey Samsonov8df3a072015-10-29 22:21:37 +0000351 auto ErrOrInfo =
352 SymbolizableObjectFile::create(Objects.first, std::move(Context));
353 if (error(ErrOrInfo.getError())) {
354 Modules.insert(std::make_pair(ModuleName, nullptr));
355 return nullptr;
356 }
357 SymbolizableModule *Res = ErrOrInfo.get().get();
358 Modules.insert(std::make_pair(ModuleName, std::move(ErrOrInfo.get())));
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000359 return Res;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000360}
361
Alexey Samsonov8df3a072015-10-29 22:21:37 +0000362std::string
363LLVMSymbolizer::printDILineInfo(DILineInfo LineInfo,
364 const SymbolizableModule *ModInfo) const {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000365 std::stringstream Result;
Alexey Samsonovcd014722014-05-17 00:07:48 +0000366 if (Opts.PrintFunctions != FunctionNameKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000367 std::string FunctionName = LineInfo.FunctionName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000368 if (FunctionName == kDILineInfoBadString)
369 FunctionName = kBadString;
Alexey Samsonov601beb72013-06-28 12:06:25 +0000370 else if (Opts.Demangle)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000371 FunctionName = DemangleName(FunctionName, ModInfo);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000372 Result << FunctionName << "\n";
373 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000374 std::string Filename = LineInfo.FileName;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000375 if (Filename == kDILineInfoBadString)
376 Filename = kBadString;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000377 Result << Filename << ":" << LineInfo.Line << ":" << LineInfo.Column << "\n";
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000378 return Result.str();
379}
380
Alexey Samsonov76f7ecb2015-10-29 23:49:19 +0000381std::string
Alexey Samsonov46c1ce62015-10-30 00:40:20 +0000382LLVMSymbolizer::printDIInliningInfo(DIInliningInfo InlinedContext,
383 const SymbolizableModule *ModInfo) const {
384 uint32_t FramesNum = InlinedContext.getNumberOfFrames();
385 if (FramesNum == 0)
386 return printDILineInfo(DILineInfo(), ModInfo);
387 std::string Result;
388 for (uint32_t i = 0; i < FramesNum; i++) {
389 DILineInfo LineInfo = InlinedContext.getFrame(i);
390 Result += printDILineInfo(LineInfo, ModInfo);
391 }
392 return Result;
393}
394
395std::string
Alexey Samsonov76f7ecb2015-10-29 23:49:19 +0000396LLVMSymbolizer::printDIGlobal(DIGlobal Global,
397 const SymbolizableModule *ModInfo) const {
398 std::stringstream Result;
399 std::string Name = Global.Name;
400 if (Name == kDILineInfoBadString)
401 Name = kBadString;
402 else if (Opts.Demangle)
403 Name = DemangleName(Name, ModInfo);
404 Result << Name << "\n";
405 Result << Global.Start << " " << Global.Size << "\n";
406 return Result.str();
407}
408
Reid Klecknerc25c7942015-08-10 21:47:11 +0000409// Undo these various manglings for Win32 extern "C" functions:
410// cdecl - _foo
411// stdcall - _foo@12
412// fastcall - @foo@12
413// vectorcall - foo@@12
414// These are all different linkage names for 'foo'.
415static StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
416 // Remove any '_' or '@' prefix.
417 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
418 if (Front == '_' || Front == '@')
419 SymbolName = SymbolName.drop_front();
420
421 // Remove any '@[0-9]+' suffix.
422 if (Front != '?') {
423 size_t AtPos = SymbolName.rfind('@');
424 if (AtPos != StringRef::npos &&
425 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
426 [](char C) { return C >= '0' && C <= '9'; })) {
427 SymbolName = SymbolName.substr(0, AtPos);
428 }
429 }
430
431 // Remove any ending '@' for vectorcall.
432 if (SymbolName.endswith("@"))
433 SymbolName = SymbolName.drop_back();
434
435 return SymbolName;
436}
437
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000438#if !defined(_MSC_VER)
439// Assume that __cxa_demangle is provided by libcxxabi (except for Windows).
440extern "C" char *__cxa_demangle(const char *mangled_name, char *output_buffer,
441 size_t *length, int *status);
442#endif
443
Reid Klecknerc25c7942015-08-10 21:47:11 +0000444std::string LLVMSymbolizer::DemangleName(const std::string &Name,
Alexey Samsonov8df3a072015-10-29 22:21:37 +0000445 const SymbolizableModule *ModInfo) {
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000446#if !defined(_MSC_VER)
Ed Masteef6fed72014-01-16 17:25:12 +0000447 // We can spoil names of symbols with C linkage, so use an heuristic
448 // approach to check if the name should be demangled.
Reid Klecknerc25c7942015-08-10 21:47:11 +0000449 if (Name.substr(0, 2) == "_Z") {
450 int status = 0;
451 char *DemangledName = __cxa_demangle(Name.c_str(), nullptr, nullptr, &status);
452 if (status != 0)
453 return Name;
454 std::string Result = DemangledName;
455 free(DemangledName);
456 return Result;
457 }
Alexey Samsonov601beb72013-06-28 12:06:25 +0000458#else
Reid Klecknerc25c7942015-08-10 21:47:11 +0000459 if (!Name.empty() && Name.front() == '?') {
460 // Only do MSVC C++ demangling on symbols starting with '?'.
461 char DemangledName[1024] = {0};
462 DWORD result = ::UnDecorateSymbolName(
463 Name.c_str(), DemangledName, 1023,
464 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
465 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
466 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
467 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
468 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
469 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
470 return (result == 0) ? Name : std::string(DemangledName);
471 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000472#endif
Alexey Samsonov76f7ecb2015-10-29 23:49:19 +0000473 if (ModInfo && ModInfo->isWin32Module())
Reid Klecknerc25c7942015-08-10 21:47:11 +0000474 return std::string(demanglePE32ExternCFunc(Name));
475 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000476}
477
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000478} // namespace symbolize
479} // namespace llvm