blob: cb076aed3aac404ee42a433e60171698e1b084d7 [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
38namespace llvm {
39namespace symbolize {
40
David Blaikiee5adb682017-07-30 01:34:08 +000041Expected<DILineInfo>
Yuanfang Chen5de46922019-07-08 19:28:57 +000042LLVMSymbolizer::symbolizeCodeCommon(SymbolizableModule *Info,
43 object::SectionedAddress ModuleOffset) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +000044 // A null module means an error has already been reported. Return an empty
45 // result.
46 if (!Info)
47 return DILineInfo();
Reid Klecknere94fef72015-10-09 00:15:01 +000048
49 // If the user is giving us relative addresses, add the preferred base of the
50 // object to the offset before we do the query. It's what DIContext expects.
51 if (Opts.RelativeAddresses)
Alexey Lapshin77fc1f62019-02-27 13:17:36 +000052 ModuleOffset.Address += Info->getModulePreferredBase();
Reid Klecknere94fef72015-10-09 00:15:01 +000053
Alexey Samsonov0fb64512015-10-26 22:34:56 +000054 DILineInfo LineInfo = Info->symbolizeCode(ModuleOffset, Opts.PrintFunctions,
55 Opts.UseSymbolTable);
Alexey Samsonov68812492015-11-03 21:36:13 +000056 if (Opts.Demangle)
57 LineInfo.FunctionName = DemangleName(LineInfo.FunctionName, Info);
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000058 return LineInfo;
Alexey Samsonovea83baf2013-01-22 14:21:19 +000059}
60
Yuanfang Chen5de46922019-07-08 19:28:57 +000061Expected<DILineInfo>
62LLVMSymbolizer::symbolizeCode(const ObjectFile &Obj,
63 object::SectionedAddress ModuleOffset) {
64 StringRef ModuleName = Obj.getFileName();
65 auto I = Modules.find(ModuleName);
66 if (I != Modules.end())
67 return symbolizeCodeCommon(I->second.get(), ModuleOffset);
68
69 std::unique_ptr<DIContext> Context =
70 DWARFContext::create(Obj, nullptr, DWARFContext::defaultErrorHandler);
71 Expected<SymbolizableModule *> InfoOrErr =
72 createModuleInfo(&Obj, std::move(Context), ModuleName);
73 if (!InfoOrErr)
74 return InfoOrErr.takeError();
75 return symbolizeCodeCommon(*InfoOrErr, ModuleOffset);
76}
77
78Expected<DILineInfo>
79LLVMSymbolizer::symbolizeCode(const std::string &ModuleName,
80 object::SectionedAddress ModuleOffset) {
81 Expected<SymbolizableModule *> InfoOrErr = getOrCreateModuleInfo(ModuleName);
82 if (!InfoOrErr)
83 return InfoOrErr.takeError();
84 return symbolizeCodeCommon(*InfoOrErr, ModuleOffset);
85}
86
Reid Klecknerf27f3f82016-06-03 20:25:09 +000087Expected<DIInliningInfo>
Alexey Samsonovd6aa8202015-11-03 22:20:52 +000088LLVMSymbolizer::symbolizeInlinedCode(const std::string &ModuleName,
Peter Collingbournee5bdeda2019-06-11 02:32:27 +000089 object::SectionedAddress ModuleOffset) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +000090 SymbolizableModule *Info;
Peter Collingbournee5bdeda2019-06-11 02:32:27 +000091 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
Reid Klecknerf27f3f82016-06-03 20:25:09 +000092 Info = InfoOrErr.get();
93 else
94 return InfoOrErr.takeError();
95
96 // A null module means an error has already been reported. Return an empty
97 // result.
98 if (!Info)
99 return DIInliningInfo();
Alexey Samsonov46c1ce62015-10-30 00:40:20 +0000100
101 // If the user is giving us relative addresses, add the preferred base of the
102 // object to the offset before we do the query. It's what DIContext expects.
103 if (Opts.RelativeAddresses)
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000104 ModuleOffset.Address += Info->getModulePreferredBase();
Alexey Samsonov46c1ce62015-10-30 00:40:20 +0000105
106 DIInliningInfo InlinedContext = Info->symbolizeInlinedCode(
107 ModuleOffset, Opts.PrintFunctions, Opts.UseSymbolTable);
Alexey Samsonov68812492015-11-03 21:36:13 +0000108 if (Opts.Demangle) {
109 for (int i = 0, n = InlinedContext.getNumberOfFrames(); i < n; i++) {
110 auto *Frame = InlinedContext.getMutableFrame(i);
111 Frame->FunctionName = DemangleName(Frame->FunctionName, Info);
112 }
113 }
Alexey Samsonovd6aa8202015-11-03 22:20:52 +0000114 return InlinedContext;
Alexey Samsonov46c1ce62015-10-30 00:40:20 +0000115}
116
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000117Expected<DIGlobal>
118LLVMSymbolizer::symbolizeData(const std::string &ModuleName,
119 object::SectionedAddress ModuleOffset) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000120 SymbolizableModule *Info;
121 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
122 Info = InfoOrErr.get();
123 else
124 return InfoOrErr.takeError();
125
126 // A null module means an error has already been reported. Return an empty
127 // result.
128 if (!Info)
129 return DIGlobal();
Alexey Samsonov68812492015-11-03 21:36:13 +0000130
131 // If the user is giving us relative addresses, add the preferred base of
132 // the object to the offset before we do the query. It's what DIContext
133 // expects.
134 if (Opts.RelativeAddresses)
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000135 ModuleOffset.Address += Info->getModulePreferredBase();
Alexey Samsonov68812492015-11-03 21:36:13 +0000136
137 DIGlobal Global = Info->symbolizeData(ModuleOffset);
138 if (Opts.Demangle)
139 Global.Name = DemangleName(Global.Name, Info);
Alexey Samsonovd6aa8202015-11-03 22:20:52 +0000140 return Global;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000141}
142
Peter Collingbourne9c8282a2019-06-24 20:03:23 +0000143Expected<std::vector<DILocal>>
144LLVMSymbolizer::symbolizeFrame(const std::string &ModuleName,
145 object::SectionedAddress ModuleOffset) {
146 SymbolizableModule *Info;
147 if (auto InfoOrErr = getOrCreateModuleInfo(ModuleName))
148 Info = InfoOrErr.get();
149 else
150 return InfoOrErr.takeError();
151
152 // A null module means an error has already been reported. Return an empty
153 // result.
154 if (!Info)
155 return std::vector<DILocal>();
156
157 // If the user is giving us relative addresses, add the preferred base of
158 // the object to the offset before we do the query. It's what DIContext
159 // expects.
160 if (Opts.RelativeAddresses)
161 ModuleOffset.Address += Info->getModulePreferredBase();
162
163 return Info->symbolizeFrame(ModuleOffset);
164}
165
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000166void LLVMSymbolizer::flush() {
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000167 ObjectForUBPathAndArch.clear();
168 BinaryForPath.clear();
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000169 ObjectPairForPathArch.clear();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000170 Modules.clear();
Dmitry Vyukove8504e22013-03-19 10:24:42 +0000171}
172
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000173namespace {
174
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000175// For Path="/path/to/foo" and Basename="foo" assume that debug info is in
176// /path/to/foo.dSYM/Contents/Resources/DWARF/foo.
177// For Path="/path/to/bar.dSYM" and Basename="foo" assume that debug info is in
178// /path/to/bar.dSYM/Contents/Resources/DWARF/foo.
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000179std::string getDarwinDWARFResourceForPath(
180 const std::string &Path, const std::string &Basename) {
181 SmallString<16> ResourceName = StringRef(Path);
182 if (sys::path::extension(Path) != ".dSYM") {
183 ResourceName += ".dSYM";
184 }
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000185 sys::path::append(ResourceName, "Contents", "Resources", "DWARF");
186 sys::path::append(ResourceName, Basename);
187 return ResourceName.str();
188}
189
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000190bool checkFileCRC(StringRef Path, uint32_t CRCHash) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000191 ErrorOr<std::unique_ptr<MemoryBuffer>> MB =
192 MemoryBuffer::getFileOrSTDIN(Path);
193 if (!MB)
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000194 return false;
Hans Wennborg1e1e3ba2019-10-09 09:06:30 +0000195 return CRCHash == llvm::crc32(arrayRefFromStringRef(MB.get()->getBuffer()));
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000196}
197
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000198bool findDebugBinary(const std::string &OrigPath,
199 const std::string &DebuglinkName, uint32_t CRCHash,
Jordan Rupprecht5b7ad422019-02-11 18:05:48 +0000200 const std::string &FallbackDebugPath,
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000201 std::string &Result) {
Jordan Rupprecht835df272019-02-01 21:04:16 +0000202 SmallString<16> OrigDir(OrigPath);
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000203 llvm::sys::path::remove_filename(OrigDir);
204 SmallString<16> DebugPath = OrigDir;
Jordan Rupprecht5b7ad422019-02-11 18:05:48 +0000205 // Try relative/path/to/original_binary/debuglink_name
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000206 llvm::sys::path::append(DebugPath, DebuglinkName);
207 if (checkFileCRC(DebugPath, CRCHash)) {
208 Result = DebugPath.str();
209 return true;
210 }
Jordan Rupprecht5b7ad422019-02-11 18:05:48 +0000211 // Try relative/path/to/original_binary/.debug/debuglink_name
Francis Riccife6cbce2018-03-02 22:56:45 +0000212 DebugPath = OrigDir;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000213 llvm::sys::path::append(DebugPath, ".debug", DebuglinkName);
214 if (checkFileCRC(DebugPath, CRCHash)) {
215 Result = DebugPath.str();
216 return true;
217 }
Jordan Rupprecht5b7ad422019-02-11 18:05:48 +0000218 // Make the path absolute so that lookups will go to
219 // "/usr/lib/debug/full/path/to/debug", not
220 // "/usr/lib/debug/to/debug"
221 llvm::sys::fs::make_absolute(OrigDir);
222 if (!FallbackDebugPath.empty()) {
223 // Try <FallbackDebugPath>/absolute/path/to/original_binary/debuglink_name
224 DebugPath = FallbackDebugPath;
225 } else {
Kamil Rytarowskia8448ad2018-06-25 18:49:13 +0000226#if defined(__NetBSD__)
Jordan Rupprecht5b7ad422019-02-11 18:05:48 +0000227 // Try /usr/libdata/debug/absolute/path/to/original_binary/debuglink_name
228 DebugPath = "/usr/libdata/debug";
Kamil Rytarowskia8448ad2018-06-25 18:49:13 +0000229#else
Jordan Rupprecht5b7ad422019-02-11 18:05:48 +0000230 // Try /usr/lib/debug/absolute/path/to/original_binary/debuglink_name
231 DebugPath = "/usr/lib/debug";
Kamil Rytarowskia8448ad2018-06-25 18:49:13 +0000232#endif
Jordan Rupprecht5b7ad422019-02-11 18:05:48 +0000233 }
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000234 llvm::sys::path::append(DebugPath, llvm::sys::path::relative_path(OrigDir),
235 DebuglinkName);
236 if (checkFileCRC(DebugPath, CRCHash)) {
237 Result = DebugPath.str();
238 return true;
239 }
240 return false;
241}
242
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000243bool getGNUDebuglinkContents(const ObjectFile *Obj, std::string &DebugName,
244 uint32_t &CRCHash) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000245 if (!Obj)
246 return false;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000247 for (const SectionRef &Section : Obj->sections()) {
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000248 StringRef Name;
George Rimarbcc00e12019-08-14 11:10:11 +0000249 if (Expected<StringRef> NameOrErr = Section.getName())
250 Name = *NameOrErr;
251 else
252 consumeError(NameOrErr.takeError());
253
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000254 Name = Name.substr(Name.find_first_not_of("._"));
255 if (Name == "gnu_debuglink") {
Fangrui Songe1833402019-05-16 13:24:04 +0000256 Expected<StringRef> ContentsOrErr = Section.getContents();
257 if (!ContentsOrErr) {
258 consumeError(ContentsOrErr.takeError());
259 return false;
260 }
261 DataExtractor DE(*ContentsOrErr, Obj->isLittleEndian(), 0);
Igor Kudrinf26a70a2019-08-06 10:49:40 +0000262 uint64_t Offset = 0;
Alexey Samsonov3e9997f2013-08-14 17:09:30 +0000263 if (const char *DebugNameStr = DE.getCStr(&Offset)) {
264 // 4-byte align the offset.
265 Offset = (Offset + 3) & ~0x3;
266 if (DE.isValidOffsetForDataOfSize(Offset, 4)) {
267 DebugName = DebugNameStr;
268 CRCHash = DE.getU32(&Offset);
269 return true;
270 }
271 }
272 break;
273 }
274 }
275 return false;
276}
277
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000278bool darwinDsymMatchesBinary(const MachOObjectFile *DbgObj,
279 const MachOObjectFile *Obj) {
280 ArrayRef<uint8_t> dbg_uuid = DbgObj->getUuid();
281 ArrayRef<uint8_t> bin_uuid = Obj->getUuid();
282 if (dbg_uuid.empty() || bin_uuid.empty())
283 return false;
284 return !memcmp(dbg_uuid.data(), bin_uuid.data(), dbg_uuid.size());
285}
286
Petr Hosek00e436f2019-11-26 17:18:42 -0800287template <typename ELFT>
288Optional<ArrayRef<uint8_t>> getBuildID(const ELFFile<ELFT> *Obj) {
289 if (!Obj)
290 return {};
291 auto PhdrsOrErr = Obj->program_headers();
292 if (!PhdrsOrErr) {
293 consumeError(PhdrsOrErr.takeError());
294 return {};
295 }
296 for (const auto &P : *PhdrsOrErr) {
297 if (P.p_type != ELF::PT_NOTE)
298 continue;
299 Error Err = Error::success();
300 for (const auto &N : Obj->notes(P, Err))
301 if (N.getType() == ELF::NT_GNU_BUILD_ID && N.getName() == ELF::ELF_NOTE_GNU)
302 return N.getDesc();
303 }
304 return {};
305}
306
307Optional<ArrayRef<uint8_t>> getBuildID(const ELFObjectFileBase *Obj) {
308 Optional<ArrayRef<uint8_t>> BuildID;
309 if (auto *O = dyn_cast<ELFObjectFile<ELF32LE>>(Obj))
310 BuildID = getBuildID(O->getELFFile());
311 else if (auto *O = dyn_cast<ELFObjectFile<ELF32BE>>(Obj))
312 BuildID = getBuildID(O->getELFFile());
313 else if (auto *O = dyn_cast<ELFObjectFile<ELF64LE>>(Obj))
314 BuildID = getBuildID(O->getELFFile());
315 else if (auto *O = dyn_cast<ELFObjectFile<ELF64BE>>(Obj))
316 BuildID = getBuildID(O->getELFFile());
317 else
318 llvm_unreachable("unsupported file format");
319 return BuildID;
320}
321
322bool findDebugBinary(const std::vector<std::string> &DebugFileDirectory,
323 const ArrayRef<uint8_t> BuildID,
324 std::string &Result) {
325 auto getDebugPath = [&](StringRef Directory) {
326 SmallString<128> Path{Directory};
327 sys::path::append(Path, ".build-id",
328 llvm::toHex(BuildID[0], /*LowerCase=*/true),
329 llvm::toHex(BuildID.slice(1), /*LowerCase=*/true));
330 Path += ".debug";
331 return Path;
332 };
333 if (DebugFileDirectory.empty()) {
334 SmallString<128> Path = getDebugPath(
335#if defined(__NetBSD__)
336 // Try /usr/libdata/debug/.build-id/../...
337 "/usr/libdata/debug"
338#else
339 // Try /usr/lib/debug/.build-id/../...
340 "/usr/lib/debug"
341#endif
342 );
343 if (llvm::sys::fs::exists(Path)) {
344 Result = Path.str();
345 return true;
346 }
347 } else {
348 for (const auto &Directory : DebugFileDirectory) {
349 // Try <debug-file-directory>/.build-id/../...
350 SmallString<128> Path = getDebugPath(Directory);
351 if (llvm::sys::fs::exists(Path)) {
352 Result = Path.str();
353 return true;
354 }
355 }
356 }
357 return false;
358}
359
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000360} // end anonymous namespace
361
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000362ObjectFile *LLVMSymbolizer::lookUpDsymFile(const std::string &ExePath,
363 const MachOObjectFile *MachExeObj, const std::string &ArchName) {
364 // On Darwin we may find DWARF in separate object file in
365 // resource directory.
366 std::vector<std::string> DsymPaths;
367 StringRef Filename = sys::path::filename(ExePath);
368 DsymPaths.push_back(getDarwinDWARFResourceForPath(ExePath, Filename));
369 for (const auto &Path : Opts.DsymHints) {
370 DsymPaths.push_back(getDarwinDWARFResourceForPath(Path, Filename));
371 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000372 for (const auto &Path : DsymPaths) {
373 auto DbgObjOrErr = getOrCreateObject(Path, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000374 if (!DbgObjOrErr) {
375 // Ignore errors, the file might not exist.
376 consumeError(DbgObjOrErr.takeError());
Alexey Samsonov884adda2015-11-04 00:30:24 +0000377 continue;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000378 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000379 ObjectFile *DbgObj = DbgObjOrErr.get();
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000380 if (!DbgObj)
381 continue;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000382 const MachOObjectFile *MachDbgObj = dyn_cast<const MachOObjectFile>(DbgObj);
Alexey Samsonov884adda2015-11-04 00:30:24 +0000383 if (!MachDbgObj)
384 continue;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000385 if (darwinDsymMatchesBinary(MachDbgObj, MachExeObj))
Alexey Samsonov884adda2015-11-04 00:30:24 +0000386 return DbgObj;
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000387 }
388 return nullptr;
389}
390
Alexey Samsonov5365a012015-11-04 00:30:26 +0000391ObjectFile *LLVMSymbolizer::lookUpDebuglinkObject(const std::string &Path,
392 const ObjectFile *Obj,
393 const std::string &ArchName) {
394 std::string DebuglinkName;
395 uint32_t CRCHash;
396 std::string DebugBinaryPath;
397 if (!getGNUDebuglinkContents(Obj, DebuglinkName, CRCHash))
398 return nullptr;
Jordan Rupprecht5b7ad422019-02-11 18:05:48 +0000399 if (!findDebugBinary(Path, DebuglinkName, CRCHash, Opts.FallbackDebugPath,
400 DebugBinaryPath))
Alexey Samsonov5365a012015-11-04 00:30:26 +0000401 return nullptr;
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000402 auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000403 if (!DbgObjOrErr) {
404 // Ignore errors, the file might not exist.
405 consumeError(DbgObjOrErr.takeError());
Alexey Samsonov5365a012015-11-04 00:30:26 +0000406 return nullptr;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000407 }
Alexey Samsonov5365a012015-11-04 00:30:26 +0000408 return DbgObjOrErr.get();
409}
410
Petr Hosek00e436f2019-11-26 17:18:42 -0800411ObjectFile *LLVMSymbolizer::lookUpBuildIDObject(const std::string &Path,
412 const ELFObjectFileBase *Obj,
413 const std::string &ArchName) {
414 auto BuildID = getBuildID(Obj);
415 if (!BuildID)
416 return nullptr;
417 if (BuildID->size() < 2)
418 return nullptr;
419 std::string DebugBinaryPath;
420 if (!findDebugBinary(Opts.DebugFileDirectory, *BuildID, DebugBinaryPath))
421 return nullptr;
422 auto DbgObjOrErr = getOrCreateObject(DebugBinaryPath, ArchName);
423 if (!DbgObjOrErr) {
424 consumeError(DbgObjOrErr.takeError());
425 return nullptr;
426 }
427 return DbgObjOrErr.get();
428}
429
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000430Expected<LLVMSymbolizer::ObjectPair>
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000431LLVMSymbolizer::getOrCreateObjectPair(const std::string &Path,
432 const std::string &ArchName) {
Fangrui Song22e478f2019-06-21 11:05:26 +0000433 auto I = ObjectPairForPathArch.find(std::make_pair(Path, ArchName));
434 if (I != ObjectPairForPathArch.end())
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000435 return I->second;
Alexey Samsonov884adda2015-11-04 00:30:24 +0000436
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000437 auto ObjOrErr = getOrCreateObject(Path, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000438 if (!ObjOrErr) {
Fangrui Song22e478f2019-06-21 11:05:26 +0000439 ObjectPairForPathArch.emplace(std::make_pair(Path, ArchName),
440 ObjectPair(nullptr, nullptr));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000441 return ObjOrErr.takeError();
Alexey Samsonov884adda2015-11-04 00:30:24 +0000442 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000443
444 ObjectFile *Obj = ObjOrErr.get();
445 assert(Obj != nullptr);
446 ObjectFile *DbgObj = nullptr;
447
448 if (auto MachObj = dyn_cast<const MachOObjectFile>(Obj))
449 DbgObj = lookUpDsymFile(Path, MachObj, ArchName);
Petr Hosek00e436f2019-11-26 17:18:42 -0800450 else if (auto ELFObj = dyn_cast<const ELFObjectFileBase>(Obj))
451 DbgObj = lookUpBuildIDObject(Path, ELFObj, ArchName);
Alexey Samsonov5365a012015-11-04 00:30:26 +0000452 if (!DbgObj)
453 DbgObj = lookUpDebuglinkObject(Path, Obj, ArchName);
Alexander Potapenko7aaf5142014-10-17 00:50:19 +0000454 if (!DbgObj)
455 DbgObj = Obj;
456 ObjectPair Res = std::make_pair(Obj, DbgObj);
Fangrui Song22e478f2019-06-21 11:05:26 +0000457 ObjectPairForPathArch.emplace(std::make_pair(Path, ArchName), Res);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000458 return Res;
459}
460
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000461Expected<ObjectFile *>
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000462LLVMSymbolizer::getOrCreateObject(const std::string &Path,
463 const std::string &ArchName) {
Fangrui Song22e478f2019-06-21 11:05:26 +0000464 Binary *Bin;
465 auto Pair = BinaryForPath.emplace(Path, OwningBinary<Binary>());
466 if (!Pair.second) {
467 Bin = Pair.first->second.getBinary();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000468 } else {
Fangrui Song22e478f2019-06-21 11:05:26 +0000469 Expected<OwningBinary<Binary>> BinOrErr = createBinary(Path);
470 if (!BinOrErr)
471 return BinOrErr.takeError();
472 Pair.first->second = std::move(BinOrErr.get());
473 Bin = Pair.first->second.getBinary();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000474 }
475
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000476 if (!Bin)
477 return static_cast<ObjectFile *>(nullptr);
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000478
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000479 if (MachOUniversalBinary *UB = dyn_cast_or_null<MachOUniversalBinary>(Bin)) {
Fangrui Song22e478f2019-06-21 11:05:26 +0000480 auto I = ObjectForUBPathAndArch.find(std::make_pair(Path, ArchName));
481 if (I != ObjectForUBPathAndArch.end())
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000482 return I->second.get();
Fangrui Song22e478f2019-06-21 11:05:26 +0000483
Kevin Enderby9acb1092016-05-31 20:35:34 +0000484 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Alexander Shaposhnikov4fd11c12019-09-19 00:02:12 +0000485 UB->getMachOObjectForArch(ArchName);
Kevin Enderby9acb1092016-05-31 20:35:34 +0000486 if (!ObjOrErr) {
Fangrui Song22e478f2019-06-21 11:05:26 +0000487 ObjectForUBPathAndArch.emplace(std::make_pair(Path, ArchName),
488 std::unique_ptr<ObjectFile>());
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000489 return ObjOrErr.takeError();
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000490 }
491 ObjectFile *Res = ObjOrErr->get();
Fangrui Song22e478f2019-06-21 11:05:26 +0000492 ObjectForUBPathAndArch.emplace(std::make_pair(Path, ArchName),
493 std::move(ObjOrErr.get()));
Alexey Samsonov884adda2015-11-04 00:30:24 +0000494 return Res;
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000495 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000496 if (Bin->isObject()) {
497 return cast<ObjectFile>(Bin);
498 }
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000499 return errorCodeToError(object_error::arch_not_found);
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000500}
501
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000502Expected<SymbolizableModule *>
Yuanfang Chen5de46922019-07-08 19:28:57 +0000503LLVMSymbolizer::createModuleInfo(const ObjectFile *Obj,
504 std::unique_ptr<DIContext> Context,
505 StringRef ModuleName) {
Peter Collingbournea56d81f2019-08-05 20:59:25 +0000506 auto InfoOrErr = SymbolizableObjectFile::create(Obj, std::move(Context),
507 Opts.UntagAddresses);
Yuanfang Chen5de46922019-07-08 19:28:57 +0000508 std::unique_ptr<SymbolizableModule> SymMod;
509 if (InfoOrErr)
510 SymMod = std::move(*InfoOrErr);
511 auto InsertResult =
512 Modules.insert(std::make_pair(ModuleName, std::move(SymMod)));
513 assert(InsertResult.second);
514 if (std::error_code EC = InfoOrErr.getError())
515 return errorCodeToError(EC);
516 return InsertResult.first->second.get();
517}
518
519Expected<SymbolizableModule *>
Peter Collingbournee5bdeda2019-06-11 02:32:27 +0000520LLVMSymbolizer::getOrCreateModuleInfo(const std::string &ModuleName) {
Fangrui Song22e478f2019-06-21 11:05:26 +0000521 auto I = Modules.find(ModuleName);
522 if (I != Modules.end())
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000523 return I->second.get();
Fangrui Song22e478f2019-06-21 11:05:26 +0000524
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000525 std::string BinaryName = ModuleName;
526 std::string ArchName = Opts.DefaultArch;
Alexey Samsonovb119b462013-07-17 06:45:36 +0000527 size_t ColonPos = ModuleName.find_last_of(':');
528 // Verify that substring after colon form a valid arch name.
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000529 if (ColonPos != std::string::npos) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000530 std::string ArchStr = ModuleName.substr(ColonPos + 1);
NAKAMURA Takumi8ee89c62013-07-17 06:53:51 +0000531 if (Triple(ArchStr).getArch() != Triple::UnknownArch) {
Alexey Samsonovb119b462013-07-17 06:45:36 +0000532 BinaryName = ModuleName.substr(0, ColonPos);
533 ArchName = ArchStr;
534 }
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000535 }
Alexey Samsonov1eaae4c2015-12-18 22:02:14 +0000536 auto ObjectsOrErr = getOrCreateObjectPair(BinaryName, ArchName);
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000537 if (!ObjectsOrErr) {
Alexey Samsonov2ca65362013-06-28 08:15:40 +0000538 // Failed to find valid object file.
Fangrui Song22e478f2019-06-21 11:05:26 +0000539 Modules.emplace(ModuleName, std::unique_ptr<SymbolizableModule>());
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000540 return ObjectsOrErr.takeError();
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000541 }
Alexey Samsonov884adda2015-11-04 00:30:24 +0000542 ObjectPair Objects = ObjectsOrErr.get();
543
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000544 std::unique_ptr<DIContext> Context;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000545 // If this is a COFF object containing PDB info, use a PDBContext to
546 // symbolize. Otherwise, use DWARF.
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000547 if (auto CoffObject = dyn_cast<COFFObjectFile>(Objects.first)) {
Saleem Abdulrasool01528022016-08-09 00:25:12 +0000548 const codeview::DebugInfo *DebugInfo;
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000549 StringRef PDBFileName;
Saleem Abdulrasool01528022016-08-09 00:25:12 +0000550 auto EC = CoffObject->getDebugPDBInfo(DebugInfo, PDBFileName);
Reid Klecknerd1882f22016-09-01 20:28:59 +0000551 if (!EC && DebugInfo != nullptr && !PDBFileName.empty()) {
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000552 using namespace pdb;
553 std::unique_ptr<IPDBSession> Session;
554 if (auto Err = loadDataForEXE(PDB_ReaderType::DIA,
555 Objects.first->getFileName(), Session)) {
Fangrui Song22e478f2019-06-21 11:05:26 +0000556 Modules.emplace(ModuleName, std::unique_ptr<SymbolizableModule>());
Alexandre Ganea6a7efef2018-08-31 17:41:58 +0000557 // Return along the PDB filename to provide more context
558 return createFileError(PDBFileName, std::move(Err));
Reid Klecknerf27f3f82016-06-03 20:25:09 +0000559 }
Alexey Samsonov7a952e52015-10-26 19:41:23 +0000560 Context.reset(new PDBContext(*CoffObject, std::move(Session)));
Zachary Turnerc007aa42015-05-06 22:26:30 +0000561 }
Zachary Turner20dbd0d2015-04-27 17:19:51 +0000562 }
563 if (!Context)
Peter Collingbournee5bdeda2019-06-11 02:32:27 +0000564 Context =
565 DWARFContext::create(*Objects.second, nullptr,
566 DWARFContext::defaultErrorHandler, Opts.DWPName);
Yuanfang Chen5de46922019-07-08 19:28:57 +0000567 return createModuleInfo(Objects.first, std::move(Context), ModuleName);
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000568}
569
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000570namespace {
571
Reid Klecknerc25c7942015-08-10 21:47:11 +0000572// Undo these various manglings for Win32 extern "C" functions:
573// cdecl - _foo
574// stdcall - _foo@12
575// fastcall - @foo@12
576// vectorcall - foo@@12
577// These are all different linkage names for 'foo'.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000578StringRef demanglePE32ExternCFunc(StringRef SymbolName) {
Reid Klecknerc25c7942015-08-10 21:47:11 +0000579 // Remove any '_' or '@' prefix.
580 char Front = SymbolName.empty() ? '\0' : SymbolName[0];
581 if (Front == '_' || Front == '@')
582 SymbolName = SymbolName.drop_front();
583
584 // Remove any '@[0-9]+' suffix.
585 if (Front != '?') {
586 size_t AtPos = SymbolName.rfind('@');
587 if (AtPos != StringRef::npos &&
588 std::all_of(SymbolName.begin() + AtPos + 1, SymbolName.end(),
589 [](char C) { return C >= '0' && C <= '9'; })) {
590 SymbolName = SymbolName.substr(0, AtPos);
591 }
592 }
593
594 // Remove any ending '@' for vectorcall.
595 if (SymbolName.endswith("@"))
596 SymbolName = SymbolName.drop_back();
597
598 return SymbolName;
599}
600
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000601} // end anonymous namespace
602
Zachary Turner67c56012017-04-27 16:11:19 +0000603std::string
604LLVMSymbolizer::DemangleName(const std::string &Name,
605 const SymbolizableModule *DbiModuleDescriptor) {
Ed Masteef6fed72014-01-16 17:25:12 +0000606 // We can spoil names of symbols with C linkage, so use an heuristic
607 // approach to check if the name should be demangled.
Martin Storsjob8f79022019-10-04 07:22:37 +0000608 if (Name.substr(0, 2) == "_Z") {
609 int status = 0;
610 char *DemangledName = itaniumDemangle(Name.c_str(), nullptr, nullptr, &status);
611 if (status != 0)
612 return Name;
613 std::string Result = DemangledName;
614 free(DemangledName);
615 return Result;
616 }
Eugene Zemtsovcd72cbc2018-03-07 23:07:34 +0000617
Martin Storsjob8f79022019-10-04 07:22:37 +0000618 if (!Name.empty() && Name.front() == '?') {
619 // Only do MSVC C++ demangling on symbols starting with '?'.
Martin Storsjoa4f6b592019-10-16 20:38:44 +0000620 int status = 0;
621 char *DemangledName = microsoftDemangle(
622 Name.c_str(), nullptr, nullptr, &status,
623 MSDemangleFlags(MSDF_NoAccessSpecifier | MSDF_NoCallingConvention |
624 MSDF_NoMemberType | MSDF_NoReturnType));
625 if (status != 0)
626 return Name;
627 std::string Result = DemangledName;
628 free(DemangledName);
629 return Result;
Martin Storsjob8f79022019-10-04 07:22:37 +0000630 }
Martin Storsjoa4f6b592019-10-16 20:38:44 +0000631
Zachary Turner67c56012017-04-27 16:11:19 +0000632 if (DbiModuleDescriptor && DbiModuleDescriptor->isWin32Module())
Reid Klecknerc25c7942015-08-10 21:47:11 +0000633 return std::string(demanglePE32ExternCFunc(Name));
634 return Name;
Alexey Samsonovea83baf2013-01-22 14:21:19 +0000635}
636
Alexey Samsonovd5d7bb52013-02-15 08:54:47 +0000637} // namespace symbolize
638} // namespace llvm