blob: 51aa0d781f629717a039ee91097682a6401aaaa3 [file] [log] [blame]
Alexey Samsonovea83baf2013-01-22 14:21:19 +00001//===-- LLVMSymbolize.cpp -------------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexey Samsonovea83baf2013-01-22 14:21:19 +00006//
7//===----------------------------------------------------------------------===//
8//
9// Implementation for LLVM symbolization library.
10//
11//===----------------------------------------------------------------------===//
12
Alexey Samsonov57f88372015-10-26 17:56:12 +000013#include "llvm/DebugInfo/Symbolize/Symbolize.h"
14
Alexey Samsonov8df3a072015-10-29 22:21:37 +000015#include "SymbolizableObjectFile.h"
16
Alexey Samsonovdd71c5b2013-03-19 15:33:18 +000017#include "llvm/ADT/STLExtras.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000018#include "llvm/BinaryFormat/COFF.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000019#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Zachary Turner20dbd0d2015-04-27 17:19:51 +000020#include "llvm/DebugInfo/PDB/PDB.h"
21#include "llvm/DebugInfo/PDB/PDBContext.h"
Eugene Zemtsovcd72cbc2018-03-07 23:07:34 +000022#include "llvm/Demangle/Demangle.h"
Reid Klecknerdafc5d72016-07-06 16:56:42 +000023#include "llvm/Object/COFF.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"
Eugene Leviant18873b22019-04-08 12:31:12 +000026#include "llvm/Support/CRC.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>
Eugene Zelenko35623fb2016-03-28 17:40:08 +000036#include <cstring>
Alexey Samsonovea83baf2013-01-22 14:21:19 +000037
Zachary Turnerc007aa42015-05-06 22:26:30 +000038#if defined(_MSC_VER)
Chandler Carruth6bda14b2017-06-06 11:49:48 +000039#include <Windows.h>
Chandler Carruthaaeada62017-06-06 12:43:20 +000040
41// This must be included after windows.h.
42#include <DbgHelp.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
David Blaikiee5adb682017-07-30 01:34:08 +000054Expected<DILineInfo>
Yuanfang Chen5de46922019-07-08 19:28:57 +000055LLVMSymbolizer::symbolizeCodeCommon(SymbolizableModule *Info,
56 object::SectionedAddress ModuleOffset) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +000057 // A null module means an error has already been reported. Return an empty
58 // result.
59 if (!Info)
60 return DILineInfo();
Reid Klecknere94fef72015-10-09 00:15:01 +000061
62 // If the user is giving us relative addresses, add the preferred base of the
63 // object to the offset before we do the query. It's what DIContext expects.
64 if (Opts.RelativeAddresses)
Alexey Lapshin77fc1f62019-02-27 13:17:36 +000065 ModuleOffset.Address += Info->getModulePreferredBase();
Reid Klecknere94fef72015-10-09 00:15:01 +000066
Alexey Samsonov0fb64512015-10-26 22:34:56 +000067 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions,
68 Opts.UseSymbolTable);
Alexey Samsonov68812492015-11-03 21:36:13 +000069 if (Opts.Demangle)
70 LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000071 return LineInfo;
Alexey Samsonovea83baf2013-01-22 14:21:19 +000072}
73
Yuanfang Chen5de46922019-07-08 19:28:57 +000074Expected<DILineInfo>
75LLVMSymbolizer::symbolizeCode(const ObjectFile &Obj,
76 object::SectionedAddress ModuleOffset) {
77 StringRef ModuleName = Obj.getFileName();
78 auto I = Modules.find(ModuleName);
79 if (I != Modules.end())
80 return symbolizeCodeCommon(I->second.get(), ModuleOffset);
81
82 std::unique_ptr<DIContext> Context =
83 DWARFContext::create(Obj, nullptr, DWARFContext::defaultErrorHandler);
84 Expected<SymbolizableModule *> InfoOrErr =
85 createModuleInfo(&Obj, std::move(Context), ModuleName);
86 if (!InfoOrErr)
87 return InfoOrErr.takeError();
88 return symbolizeCodeCommon(*InfoOrErr, ModuleOffset);
89}
90
91Expected<DILineInfo>
92LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
93 object::SectionedAddress ModuleOffset) {
94 Expected<SymbolizableModule *> InfoOrErr = getOrCreateModuleInfo(ModuleName);
95 if (!InfoOrErr)
96 return InfoOrErr.takeError();
97 return symbolizeCodeCommon(*InfoOrErr, ModuleOffset);
98}
99
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000100Expected<DIInliningInfo>
Alexey Samsonovd6aa8202015-11-03 22:20:52 +0000101LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
Peter Collingbournee5bdeda2019-06-11 02:32:27 +0000102 object::SectionedAddress ModuleOffset) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000103 SymbolizableModule *Info;
Peter Collingbournee5bdeda2019-06-11 02:32:27 +0000104 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000105 Info = InfoOrErr.get();
106 else
107 return InfoOrErr.takeError();
108
109 // A null module means an error has already been reported. Return an empty
110 // result.
111 if (!Info)
112 return DIInliningInfo();
Alexey Samsonov46c1ce62015-10-30 00:40:20 +0000113
114 // If the user is giving us relative addresses, add the preferred base of the
115 // object to the offset before we do the query. It's what DIContext expects.
116 if (Opts.RelativeAddresses)
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000117 ModuleOffset.Address += Info->getModulePreferredBase();
Alexey Samsonov46c1ce62015-10-30 00:40:20 +0000118
119 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
120 ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable);
Alexey Samsonov68812492015-11-03 21:36:13 +0000121 if (Opts.Demangle) {
122 for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
123 auto *Frame = InlinedContext.getMutableFrame(i);
124 Frame->FunctionName = DemangleName(Frame->FunctionName, Info);
125 }
126 }
Alexey Samsonovd6aa8202015-11-03 22:20:52 +0000127 return InlinedContext;
Alexey Samsonov46c1ce62015-10-30 00:40:20 +0000128}
129
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000130Expected<DIGlobal>
131LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
132 object::SectionedAddress ModuleOffset) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000133 SymbolizableModule *Info;
134 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
135 Info = InfoOrErr.get();
136 else
137 return InfoOrErr.takeError();
138
139 // A null module means an error has already been reported. Return an empty
140 // result.
141 if (!Info)
142 return DIGlobal();
Alexey Samsonov68812492015-11-03 21:36:13 +0000143
144 // If the user is giving us relative addresses, add the preferred base of
145 // the object to the offset before we do the query. It's what DIContext
146 // expects.
147 if (Opts.RelativeAddresses)
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000148 ModuleOffset.Address += Info->getModulePreferredBase();
Alexey Samsonov68812492015-11-03 21:36:13 +0000149
150 DIGlobal Global = Info->symbolizeData(ModuleOffset);
151 if (Opts.Demangle)
152 Global.Name = DemangleName(Global.Name, Info);
Alexey Samsonovd6aa8202015-11-03 22:20:52 +0000153 return Global;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000154}
155
Peter Collingbourne9c8282a2019-06-24 20:03:23 +0000156Expected<std::vector<DILocal>>
157LLVMSymbolizer::symbolizeFrame(const std::string &ModuleName,
158 object::SectionedAddress ModuleOffset) {
159 SymbolizableModule *Info;
160 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
161 Info = InfoOrErr.get();
162 else
163 return InfoOrErr.takeError();
164
165 // A null module means an error has already been reported. Return an empty
166 // result.
167 if (!Info)
168 return std::vector<DILocal>();
169
170 // If the user is giving us relative addresses, add the preferred base of
171 // the object to the offset before we do the query. It's what DIContext
172 // expects.
173 if (Opts.RelativeAddresses)
174 ModuleOffset.Address += Info->getModulePreferredBase();
175
176 return Info->symbolizeFrame(ModuleOffset);
177}
178
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000179void LLVMSymbolizer::flush() {
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000180 ObjectForUBPathAndArch.clear();
181 BinaryForPath.clear();
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000182 ObjectPairForPathArch.clear();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000183 Modules.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000184}
185
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000186namespace {
187
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000188// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
189// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
190// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
191// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000192std::string getDarwinDWARFResourceForPath(
193 const std::string &Path, const std::string &Basename) {
194 SmallString<16> ResourceName = StringRef(Path);
195 if (sys::path::extension(Path) != ".dSYM") {
196 ResourceName += ".dSYM";
197 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000198 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
199 sys::path::append(ResourceName, Basename);
200 return ResourceName.str();
201}
202
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000203bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000204 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
205 MemoryBuffer::getFileOrSTDIN(Path);
206 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000207 return false;
Eugene Leviant7671a1d2019-04-08 13:40:58 +0000208 return CRCHash == llvm::crc32(0, MB.get()->getBuffer());
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000209}
210
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000211bool findDebugBinary(const std::string &OrigPath,
212 const std::string &DebuglinkName, uint32_t CRCHash,
Jordan Rupprecht5b7ad422019-02-11 18:05:48 +0000213 const std::string &FallbackDebugPath,
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000214 std::string &Result) {
Jordan Rupprecht835df272019-02-01 21:04:16 +0000215 SmallString<16> OrigDir(OrigPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000216 llvm::sys::path::remove_filename(OrigDir);
217 SmallString<16> DebugPath = OrigDir;
Jordan Rupprecht5b7ad422019-02-11 18:05:48 +0000218 // Try relative/path/to/original_binary/debuglink_name
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000219 llvm::sys::path::append(DebugPath, DebuglinkName);
220 if (checkFileCRC(DebugPath, CRCHash)) {
221 Result = DebugPath.str();
222 return true;
223 }
Jordan Rupprecht5b7ad422019-02-11 18:05:48 +0000224 // Try relative/path/to/original_binary/.debug/debuglink_name
Francis Riccife6cbce2018-03-02 22:56:45 +0000225 DebugPath = OrigDir;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000226 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
227 if (checkFileCRC(DebugPath, CRCHash)) {
228 Result = DebugPath.str();
229 return true;
230 }
Jordan Rupprecht5b7ad422019-02-11 18:05:48 +0000231 // Make the path absolute so that lookups will go to
232 // "/usr/lib/debug/full/path/to/debug", not
233 // "/usr/lib/debug/to/debug"
234 llvm::sys::fs::make_absolute(OrigDir);
235 if (!FallbackDebugPath.empty()) {
236 // Try <FallbackDebugPath>/absolute/path/to/original_binary/debuglink_name
237 DebugPath = FallbackDebugPath;
238 } else {
Kamil Rytarowskia8448ad2018-06-25 18:49:13 +0000239#if defined(__NetBSD__)
Jordan Rupprecht5b7ad422019-02-11 18:05:48 +0000240 // Try /usr/libdata/debug/absolute/path/to/original_binary/debuglink_name
241 DebugPath = "/usr/libdata/debug";
Kamil Rytarowskia8448ad2018-06-25 18:49:13 +0000242#else
Jordan Rupprecht5b7ad422019-02-11 18:05:48 +0000243 // Try /usr/lib/debug/absolute/path/to/original_binary/debuglink_name
244 DebugPath = "/usr/lib/debug";
Kamil Rytarowskia8448ad2018-06-25 18:49:13 +0000245#endif
Jordan Rupprecht5b7ad422019-02-11 18:05:48 +0000246 }
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000247 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
248 DebuglinkName);
249 if (checkFileCRC(DebugPath, CRCHash)) {
250 Result = DebugPath.str();
251 return true;
252 }
253 return false;
254}
255
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000256bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
257 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000258 if (!Obj)
259 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000260 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000261 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000262 Section.getName(Name);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000263 Name = Name.substr(Name.find_first_not_of("._"));
264 if (Name == "gnu_debuglink") {
Fangrui Songe1833402019-05-16 13:24:04 +0000265 Expected<StringRef> ContentsOrErr = Section.getContents();
266 if (!ContentsOrErr) {
267 consumeError(ContentsOrErr.takeError());
268 return false;
269 }
270 DataExtractor DE(*ContentsOrErr, Obj->isLittleEndian(), 0);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000271 uint32_t Offset = 0;
272 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
273 // 4-byte align the offset.
274 Offset = (Offset + 3) & ~0x3;
275 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
276 DebugName = DebugNameStr;
277 CRCHash = DE.getU32(&Offset);
278 return true;
279 }
280 }
281 break;
282 }
283 }
284 return false;
285}
286
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000287bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
288 const MachOObjectFile *Obj) {
289 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
290 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
291 if (dbg_uuid.empty() || bin_uuid.empty())
292 return false;
293 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
294}
295
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000296} // end anonymous namespace
297
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000298ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
299 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
300 // On Darwin we may find DWARF in separate object file in
301 // resource directory.
302 std::vector<std::string> DsymPaths;
303 StringRef Filename = sys::path::filename(ExePath);
304 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
305 for (const auto &Path : Opts.DsymHints) {
306 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
307 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000308 for (const auto &Path : DsymPaths) {
309 auto DbgObjOrErr = getOrCreateObject(Path, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000310 if (!DbgObjOrErr) {
311 // Ignore errors, the file might not exist.
312 consumeError(DbgObjOrErr.takeError());
Alexey Samsonov884adda2015-11-04 00:30:24 +0000313 continue;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000314 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000315 ObjectFile *DbgObj = DbgObjOrErr.get();
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000316 if (!DbgObj)
317 continue;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000318 const MachOObjectFile *MachDbgObj = dyn_cast<const MachOObjectFile>(DbgObj);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000319 if (!MachDbgObj)
320 continue;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000321 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj))
Alexey Samsonov884adda2015-11-04 00:30:24 +0000322 return DbgObj;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000323 }
324 return nullptr;
325}
326
Alexey Samsonov5365a012015-11-04 00:30:26 +0000327ObjectFile *LLVMSymbolizer::lookUpDebuglinkObject(const std::string &Path,
328 const ObjectFile *Obj,
329 const std::string &ArchName) {
330 std::string DebuglinkName;
331 uint32_t CRCHash;
332 std::string DebugBinaryPath;
333 if (!getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash))
334 return nullptr;
Jordan Rupprecht5b7ad422019-02-11 18:05:48 +0000335 if (!findDebugBinary(Path, DebuglinkName, CRCHash, Opts.FallbackDebugPath,
336 DebugBinaryPath))
Alexey Samsonov5365a012015-11-04 00:30:26 +0000337 return nullptr;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000338 auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000339 if (!DbgObjOrErr) {
340 // Ignore errors, the file might not exist.
341 consumeError(DbgObjOrErr.takeError());
Alexey Samsonov5365a012015-11-04 00:30:26 +0000342 return nullptr;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000343 }
Alexey Samsonov5365a012015-11-04 00:30:26 +0000344 return DbgObjOrErr.get();
345}
346
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000347Expected<LLVMSymbolizer::ObjectPair>
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000348LLVMSymbolizer::getOrCreateObjectPair(const std::string &Path,
349 const std::string &ArchName) {
Fangrui Song22e478f2019-06-21 11:05:26 +0000350 auto I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
351 if (I != ObjectPairForPathArch.end())
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000352 return I->second;
Alexey Samsonov884adda2015-11-04 00:30:24 +0000353
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000354 auto ObjOrErr = getOrCreateObject(Path, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000355 if (!ObjOrErr) {
Fangrui Song22e478f2019-06-21 11:05:26 +0000356 ObjectPairForPathArch.emplace(std::make_pair(Path, ArchName),
357 ObjectPair(nullptr, nullptr));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000358 return ObjOrErr.takeError();
Alexey Samsonov884adda2015-11-04 00:30:24 +0000359 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000360
361 ObjectFile *Obj = ObjOrErr.get();
362 assert(Obj != nullptr);
363 ObjectFile *DbgObj = nullptr;
364
365 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
366 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Alexey Samsonov5365a012015-11-04 00:30:26 +0000367 if (!DbgObj)
368 DbgObj = lookUpDebuglinkObject(Path, Obj, ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000369 if (!DbgObj)
370 DbgObj = Obj;
371 ObjectPair Res = std::make_pair(Obj, DbgObj);
Fangrui Song22e478f2019-06-21 11:05:26 +0000372 ObjectPairForPathArch.emplace(std::make_pair(Path, ArchName), Res);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000373 return Res;
374}
375
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000376Expected<ObjectFile *>
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000377LLVMSymbolizer::getOrCreateObject(const std::string &Path,
378 const std::string &ArchName) {
Fangrui Song22e478f2019-06-21 11:05:26 +0000379 Binary *Bin;
380 auto Pair = BinaryForPath.emplace(Path, OwningBinary<Binary>());
381 if (!Pair.second) {
382 Bin = Pair.first->second.getBinary();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000383 } else {
Fangrui Song22e478f2019-06-21 11:05:26 +0000384 Expected<OwningBinary<Binary>> BinOrErr = createBinary(Path);
385 if (!BinOrErr)
386 return BinOrErr.takeError();
387 Pair.first->second = std::move(BinOrErr.get());
388 Bin = Pair.first->second.getBinary();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000389 }
390
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000391 if (!Bin)
392 return static_cast<ObjectFile *>(nullptr);
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000393
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000394 if (MachOUniversalBinary *UB = dyn_cast_or_null<MachOUniversalBinary>(Bin)) {
Fangrui Song22e478f2019-06-21 11:05:26 +0000395 auto I = ObjectForUBPathAndArch.find(std::make_pair(Path, ArchName));
396 if (I != ObjectForUBPathAndArch.end())
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000397 return I->second.get();
Fangrui Song22e478f2019-06-21 11:05:26 +0000398
Kevin Enderby9acb1092016-05-31 20:35:34 +0000399 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000400 UB->getObjectForArch(ArchName);
Kevin Enderby9acb1092016-05-31 20:35:34 +0000401 if (!ObjOrErr) {
Fangrui Song22e478f2019-06-21 11:05:26 +0000402 ObjectForUBPathAndArch.emplace(std::make_pair(Path, ArchName),
403 std::unique_ptr<ObjectFile>());
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000404 return ObjOrErr.takeError();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000405 }
406 ObjectFile *Res = ObjOrErr->get();
Fangrui Song22e478f2019-06-21 11:05:26 +0000407 ObjectForUBPathAndArch.emplace(std::make_pair(Path, ArchName),
408 std::move(ObjOrErr.get()));
Alexey Samsonov884adda2015-11-04 00:30:24 +0000409 return Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000410 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000411 if (Bin->isObject()) {
412 return cast<ObjectFile>(Bin);
413 }
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000414 return errorCodeToError(object_error::arch_not_found);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000415}
416
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000417Expected<SymbolizableModule *>
Yuanfang Chen5de46922019-07-08 19:28:57 +0000418LLVMSymbolizer::createModuleInfo(const ObjectFile *Obj,
419 std::unique_ptr<DIContext> Context,
420 StringRef ModuleName) {
Peter Collingbournea56d81f2019-08-05 20:59:25 +0000421 auto InfoOrErr = SymbolizableObjectFile::create(Obj, std::move(Context),
422 Opts.UntagAddresses);
Yuanfang Chen5de46922019-07-08 19:28:57 +0000423 std::unique_ptr<SymbolizableModule> SymMod;
424 if (InfoOrErr)
425 SymMod = std::move(*InfoOrErr);
426 auto InsertResult =
427 Modules.insert(std::make_pair(ModuleName, std::move(SymMod)));
428 assert(InsertResult.second);
429 if (std::error_code EC = InfoOrErr.getError())
430 return errorCodeToError(EC);
431 return InsertResult.first->second.get();
432}
433
434Expected<SymbolizableModule *>
Peter Collingbournee5bdeda2019-06-11 02:32:27 +0000435LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
Fangrui Song22e478f2019-06-21 11:05:26 +0000436 auto I = Modules.find(ModuleName);
437 if (I != Modules.end())
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000438 return I->second.get();
Fangrui Song22e478f2019-06-21 11:05:26 +0000439
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000440 std::string BinaryName = ModuleName;
441 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000442 size_t ColonPos = ModuleName.find_last_of(':');
443 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000444 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000445 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000446 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000447 BinaryName = ModuleName.substr(0, ColonPos);
448 ArchName = ArchStr;
449 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000450 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000451 auto ObjectsOrErr = getOrCreateObjectPair(BinaryName, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000452 if (!ObjectsOrErr) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000453 // Failed to find valid object file.
Fangrui Song22e478f2019-06-21 11:05:26 +0000454 Modules.emplace(ModuleName, std::unique_ptr<SymbolizableModule>());
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000455 return ObjectsOrErr.takeError();
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000456 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000457 ObjectPair Objects = ObjectsOrErr.get();
458
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000459 std::unique_ptr<DIContext> Context;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000460 // If this is a COFF object containing PDB info, use a PDBContext to
461 // symbolize. Otherwise, use DWARF.
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000462 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
Saleem Abdulrasool01528022016-08-09 00:25:12 +0000463 const codeview::DebugInfo *DebugInfo;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000464 StringRef PDBFileName;
Saleem Abdulrasool01528022016-08-09 00:25:12 +0000465 auto EC = CoffObject->getDebugPDBInfo(DebugInfo, PDBFileName);
Reid Klecknerd1882f22016-09-01 20:28:59 +0000466 if (!EC && DebugInfo != nullptr && !PDBFileName.empty()) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000467 using namespace pdb;
468 std::unique_ptr<IPDBSession> Session;
469 if (auto Err = loadDataForEXE(PDB_ReaderType::DIA,
470 Objects.first->getFileName(), Session)) {
Fangrui Song22e478f2019-06-21 11:05:26 +0000471 Modules.emplace(ModuleName, std::unique_ptr<SymbolizableModule>());
Alexandre Ganea6a7efef2018-08-31 17:41:58 +0000472 // Return along the PDB filename to provide more context
473 return createFileError(PDBFileName, std::move(Err));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000474 }
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000475 Context.reset(new PDBContext(*CoffObject, std::move(Session)));
Zachary Turnerc007aa42015-05-06 22:26:30 +0000476 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000477 }
478 if (!Context)
Peter Collingbournee5bdeda2019-06-11 02:32:27 +0000479 Context =
480 DWARFContext::create(*Objects.second, nullptr,
481 DWARFContext::defaultErrorHandler, Opts.DWPName);
Yuanfang Chen5de46922019-07-08 19:28:57 +0000482 return createModuleInfo(Objects.first, std::move(Context), ModuleName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000483}
484
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000485namespace {
486
Reid Klecknerc25c7942015-08-10 21:47:11 +0000487// Undo these various manglings for Win32 extern "C" functions:
488// cdecl - _foo
489// stdcall - _foo@12
490// fastcall - @foo@12
491// vectorcall - foo@@12
492// These are all different linkage names for 'foo'.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000493StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
Reid Klecknerc25c7942015-08-10 21:47:11 +0000494 // Remove any '_' or '@' prefix.
495 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
496 if (Front == '_' || Front == '@')
497 SymbolName = SymbolName.drop_front();
498
499 // Remove any '@[0-9]+' suffix.
500 if (Front != '?') {
501 size_t AtPos = SymbolName.rfind('@');
502 if (AtPos != StringRef::npos &&
503 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
504 [](char C) { return C >= '0' && C <= '9'; })) {
505 SymbolName = SymbolName.substr(0, AtPos);
506 }
507 }
508
509 // Remove any ending '@' for vectorcall.
510 if (SymbolName.endswith("@"))
511 SymbolName = SymbolName.drop_back();
512
513 return SymbolName;
514}
515
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000516} // end anonymous namespace
517
Zachary Turner67c56012017-04-27 16:11:19 +0000518std::string
519LLVMSymbolizer::DemangleName(const std::string &Name,
520 const SymbolizableModule *DbiModuleDescriptor) {
Ed Masteef6fed72014-01-16 17:25:12 +0000521 // We can spoil names of symbols with C linkage, so use an heuristic
522 // approach to check if the name should be demangled.
Reid Klecknerc25c7942015-08-10 21:47:11 +0000523 if (Name.substr(0, 2) == "_Z") {
524 int status = 0;
Eugene Zemtsovcd72cbc2018-03-07 23:07:34 +0000525 char *DemangledName = itaniumDemangle(Name.c_str(), nullptr, nullptr, &status);
Reid Klecknerc25c7942015-08-10 21:47:11 +0000526 if (status != 0)
527 return Name;
528 std::string Result = DemangledName;
529 free(DemangledName);
530 return Result;
531 }
Eugene Zemtsovcd72cbc2018-03-07 23:07:34 +0000532
533#if defined(_MSC_VER)
Reid Klecknerc25c7942015-08-10 21:47:11 +0000534 if (!Name.empty() && Name.front() == '?') {
535 // Only do MSVC C++ demangling on symbols starting with '?'.
536 char DemangledName[1024] = {0};
537 DWORD result = ::UnDecorateSymbolName(
538 Name.c_str(), DemangledName, 1023,
539 UNDNAME_NO_ACCESS_SPECIFIERS | // Strip public, private, protected
540 UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall, etc
541 UNDNAME_NO_THROW_SIGNATURES | // Strip throw() specifications
542 UNDNAME_NO_MEMBER_TYPE | // Strip virtual, static, etc specifiers
543 UNDNAME_NO_MS_KEYWORDS | // Strip all MS extension keywords
544 UNDNAME_NO_FUNCTION_RETURNS); // Strip function return types
545 return (result == 0) ? Name : std::string(DemangledName);
546 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000547#endif
Zachary Turner67c56012017-04-27 16:11:19 +0000548 if (DbiModuleDescriptor && DbiModuleDescriptor->isWin32Module())
Reid Klecknerc25c7942015-08-10 21:47:11 +0000549 return std::string(demanglePE32ExternCFunc(Name));
550 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000551}
552
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000553} // namespace symbolize
554} // namespace llvm