1 //===- DIASession.cpp - DIA implementation of IPDBSession -------*- C++ -*-===//
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 #include "llvm/DebugInfo/PDB/DIA/DIASession.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/DebugInfo/PDB/DIA/DIAEnumDebugStreams.h"
12 #include "llvm/DebugInfo/PDB/DIA/DIAEnumInjectedSources.h"
13 #include "llvm/DebugInfo/PDB/DIA/DIAEnumLineNumbers.h"
14 #include "llvm/DebugInfo/PDB/DIA/DIAEnumSectionContribs.h"
15 #include "llvm/DebugInfo/PDB/DIA/DIAEnumSourceFiles.h"
16 #include "llvm/DebugInfo/PDB/DIA/DIAEnumTables.h"
17 #include "llvm/DebugInfo/PDB/DIA/DIAError.h"
18 #include "llvm/DebugInfo/PDB/DIA/DIARawSymbol.h"
19 #include "llvm/DebugInfo/PDB/DIA/DIASourceFile.h"
20 #include "llvm/DebugInfo/PDB/DIA/DIASupport.h"
21 #include "llvm/DebugInfo/PDB/GenericError.h"
22 #include "llvm/DebugInfo/PDB/PDB.h"
23 #include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
24 #include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
25 #include "llvm/Support/ConvertUTF.h"
26 #include "llvm/Support/Format.h"
27 #include "llvm/Support/FormatVariadic.h"
28 #include "llvm/Support/raw_ostream.h"
29 
30 using namespace llvm;
31 using namespace llvm::pdb;
32 
33 template <typename... Ts>
34 static Error ErrorFromHResult(HRESULT Result, const char *Str, Ts &&... Args) {
35   SmallString<64> MessageStorage;
36   StringRef Context;
37   if (sizeof...(Args) > 0) {
38     MessageStorage = formatv(Str, std::forward<Ts>(Args)...).str();
39     Context = MessageStorage;
40   } else
41     Context = Str;
42 
43   switch (Result) {
44   case E_PDB_NOT_FOUND:
45     return make_error<GenericError>(generic_error_code::invalid_path, Context);
46   case E_PDB_FORMAT:
47     return make_error<DIAError>(dia_error_code::invalid_file_format, Context);
48   case E_INVALIDARG:
49     return make_error<DIAError>(dia_error_code::invalid_parameter, Context);
50   case E_UNEXPECTED:
51     return make_error<DIAError>(dia_error_code::already_loaded, Context);
52   case E_PDB_INVALID_SIG:
53   case E_PDB_INVALID_AGE:
54     return make_error<DIAError>(dia_error_code::debug_info_mismatch, Context);
55   default: {
56     std::string S;
57     raw_string_ostream OS(S);
58     OS << "HRESULT: " << format_hex(static_cast<DWORD>(Result), 10, true)
59        << ": " << Context;
60     return make_error<DIAError>(dia_error_code::unspecified, OS.str());
61   }
62   }
63 }
64 
65 static Error LoadDIA(CComPtr<IDiaDataSource> &DiaDataSource) {
66   if (SUCCEEDED(CoCreateInstance(CLSID_DiaSource, nullptr, CLSCTX_INPROC_SERVER,
67                                  IID_IDiaDataSource,
68                                  reinterpret_cast<LPVOID *>(&DiaDataSource))))
69     return Error::success();
70 
71 // If the CoCreateInstance call above failed, msdia*.dll is not registered.
72 // Try loading the DLL corresponding to the #included DIA SDK.
73 #if !defined(_MSC_VER)
74   return llvm::make_error<GenericError>(
75       "DIA is only supported when using MSVC.");
76 #else
77   const wchar_t *msdia_dll = nullptr;
78 #if _MSC_VER >= 1900 && _MSC_VER < 2000
79   msdia_dll = L"msdia140.dll"; // VS2015
80 #elif _MSC_VER >= 1800
81   msdia_dll = L"msdia120.dll"; // VS2013
82 #else
83 #error "Unknown Visual Studio version."
84 #endif
85 
86   HRESULT HR;
87   if (FAILED(HR = NoRegCoCreate(msdia_dll, CLSID_DiaSource, IID_IDiaDataSource,
88                                 reinterpret_cast<LPVOID *>(&DiaDataSource))))
89     return ErrorFromHResult(HR, "Calling NoRegCoCreate");
90   return Error::success();
91 #endif
92 }
93 
94 DIASession::DIASession(CComPtr<IDiaSession> DiaSession) : Session(DiaSession) {}
95 
96 Error DIASession::createFromPdb(StringRef Path,
97                                 std::unique_ptr<IPDBSession> &Session) {
98   CComPtr<IDiaDataSource> DiaDataSource;
99   CComPtr<IDiaSession> DiaSession;
100 
101   // We assume that CoInitializeEx has already been called by the executable.
102   if (auto E = LoadDIA(DiaDataSource))
103     return E;
104 
105   llvm::SmallVector<UTF16, 128> Path16;
106   if (!llvm::convertUTF8ToUTF16String(Path, Path16))
107     return make_error<GenericError>(generic_error_code::invalid_path);
108 
109   const wchar_t *Path16Str = reinterpret_cast<const wchar_t*>(Path16.data());
110   HRESULT HR;
111   if (FAILED(HR = DiaDataSource->loadDataFromPdb(Path16Str))) {
112     return ErrorFromHResult(HR, "Calling loadDataFromPdb {0}", Path);
113   }
114 
115   if (FAILED(HR = DiaDataSource->openSession(&DiaSession)))
116     return ErrorFromHResult(HR, "Calling openSession");
117 
118   Session.reset(new DIASession(DiaSession));
119   return Error::success();
120 }
121 
122 Error DIASession::createFromExe(StringRef Path,
123                                 std::unique_ptr<IPDBSession> &Session) {
124   CComPtr<IDiaDataSource> DiaDataSource;
125   CComPtr<IDiaSession> DiaSession;
126 
127   // We assume that CoInitializeEx has already been called by the executable.
128   if (auto EC = LoadDIA(DiaDataSource))
129     return EC;
130 
131   llvm::SmallVector<UTF16, 128> Path16;
132   if (!llvm::convertUTF8ToUTF16String(Path, Path16))
133     return make_error<GenericError>(generic_error_code::invalid_path, Path);
134 
135   const wchar_t *Path16Str = reinterpret_cast<const wchar_t *>(Path16.data());
136   HRESULT HR;
137   if (FAILED(HR = DiaDataSource->loadDataForExe(Path16Str, nullptr, nullptr)))
138     return ErrorFromHResult(HR, "Calling loadDataForExe");
139 
140   if (FAILED(HR = DiaDataSource->openSession(&DiaSession)))
141     return ErrorFromHResult(HR, "Calling openSession");
142 
143   Session.reset(new DIASession(DiaSession));
144   return Error::success();
145 }
146 
147 uint64_t DIASession::getLoadAddress() const {
148   uint64_t LoadAddress;
149   bool success = (S_OK == Session->get_loadAddress(&LoadAddress));
150   return (success) ? LoadAddress : 0;
151 }
152 
153 bool DIASession::setLoadAddress(uint64_t Address) {
154   return (S_OK == Session->put_loadAddress(Address));
155 }
156 
157 std::unique_ptr<PDBSymbolExe> DIASession::getGlobalScope() {
158   CComPtr<IDiaSymbol> GlobalScope;
159   if (S_OK != Session->get_globalScope(&GlobalScope))
160     return nullptr;
161 
162   auto RawSymbol = llvm::make_unique<DIARawSymbol>(*this, GlobalScope);
163   auto PdbSymbol(PDBSymbol::create(*this, std::move(RawSymbol)));
164   std::unique_ptr<PDBSymbolExe> ExeSymbol(
165       static_cast<PDBSymbolExe *>(PdbSymbol.release()));
166   return ExeSymbol;
167 }
168 
169 bool DIASession::addressForVA(uint64_t VA, uint32_t &Section,
170                               uint32_t &Offset) const {
171   DWORD ArgSection, ArgOffset = 0;
172   if (S_OK == Session->addressForVA(VA, &ArgSection, &ArgOffset)) {
173     Section = static_cast<uint32_t>(ArgSection);
174     Offset = static_cast<uint32_t>(ArgOffset);
175     return true;
176   }
177   return false;
178 }
179 
180 bool DIASession::addressForRVA(uint32_t RVA, uint32_t &Section,
181                                uint32_t &Offset) const {
182   DWORD ArgSection, ArgOffset = 0;
183   if (S_OK == Session->addressForRVA(RVA, &ArgSection, &ArgOffset)) {
184     Section = static_cast<uint32_t>(ArgSection);
185     Offset = static_cast<uint32_t>(ArgOffset);
186     return true;
187   }
188   return false;
189 }
190 
191 std::unique_ptr<PDBSymbol> DIASession::getSymbolById(uint32_t SymbolId) const {
192   CComPtr<IDiaSymbol> LocatedSymbol;
193   if (S_OK != Session->symbolById(SymbolId, &LocatedSymbol))
194     return nullptr;
195 
196   auto RawSymbol = llvm::make_unique<DIARawSymbol>(*this, LocatedSymbol);
197   return PDBSymbol::create(*this, std::move(RawSymbol));
198 }
199 
200 std::unique_ptr<PDBSymbol>
201 DIASession::findSymbolByAddress(uint64_t Address, PDB_SymType Type) const {
202   enum SymTagEnum EnumVal = static_cast<enum SymTagEnum>(Type);
203 
204   CComPtr<IDiaSymbol> Symbol;
205   if (S_OK != Session->findSymbolByVA(Address, EnumVal, &Symbol)) {
206     ULONGLONG LoadAddr = 0;
207     if (S_OK != Session->get_loadAddress(&LoadAddr))
208       return nullptr;
209     DWORD RVA = static_cast<DWORD>(Address - LoadAddr);
210     if (S_OK != Session->findSymbolByRVA(RVA, EnumVal, &Symbol))
211       return nullptr;
212   }
213   auto RawSymbol = llvm::make_unique<DIARawSymbol>(*this, Symbol);
214   return PDBSymbol::create(*this, std::move(RawSymbol));
215 }
216 
217 std::unique_ptr<IPDBEnumLineNumbers>
218 DIASession::findLineNumbers(const PDBSymbolCompiland &Compiland,
219                             const IPDBSourceFile &File) const {
220   const DIARawSymbol &RawCompiland =
221       static_cast<const DIARawSymbol &>(Compiland.getRawSymbol());
222   const DIASourceFile &RawFile = static_cast<const DIASourceFile &>(File);
223 
224   CComPtr<IDiaEnumLineNumbers> LineNumbers;
225   if (S_OK !=
226       Session->findLines(RawCompiland.getDiaSymbol(), RawFile.getDiaFile(),
227                          &LineNumbers))
228     return nullptr;
229 
230   return llvm::make_unique<DIAEnumLineNumbers>(LineNumbers);
231 }
232 
233 std::unique_ptr<IPDBEnumLineNumbers>
234 DIASession::findLineNumbersByAddress(uint64_t Address, uint32_t Length) const {
235   CComPtr<IDiaEnumLineNumbers> LineNumbers;
236   if (S_OK != Session->findLinesByVA(Address, Length, &LineNumbers)) {
237     ULONGLONG LoadAddr = 0;
238     if (S_OK != Session->get_loadAddress(&LoadAddr))
239       return nullptr;
240     DWORD RVA = static_cast<DWORD>(Address - LoadAddr);
241     if (S_OK != Session->findLinesByRVA(RVA, Length, &LineNumbers))
242       return nullptr;
243   }
244   return llvm::make_unique<DIAEnumLineNumbers>(LineNumbers);
245 }
246 
247 std::unique_ptr<IPDBEnumLineNumbers>
248 DIASession::findLineNumbersByRVA(uint32_t RVA, uint32_t Length) const {
249   CComPtr<IDiaEnumLineNumbers> LineNumbers;
250   if (S_OK != Session->findLinesByRVA(RVA, Length, &LineNumbers))
251     return nullptr;
252 
253   return llvm::make_unique<DIAEnumLineNumbers>(LineNumbers);
254 }
255 
256 std::unique_ptr<IPDBEnumLineNumbers>
257 DIASession::findLineNumbersBySectOffset(uint32_t Section, uint32_t Offset,
258                                         uint32_t Length) const {
259   CComPtr<IDiaEnumLineNumbers> LineNumbers;
260   if (S_OK != Session->findLinesByAddr(Section, Offset, Length, &LineNumbers))
261     return nullptr;
262 
263   return llvm::make_unique<DIAEnumLineNumbers>(LineNumbers);
264 }
265 
266 std::unique_ptr<IPDBEnumSourceFiles>
267 DIASession::findSourceFiles(const PDBSymbolCompiland *Compiland,
268                             llvm::StringRef Pattern,
269                             PDB_NameSearchFlags Flags) const {
270   IDiaSymbol *DiaCompiland = nullptr;
271   CComBSTR Utf16Pattern;
272   if (!Pattern.empty())
273     Utf16Pattern = CComBSTR(Pattern.data());
274 
275   if (Compiland)
276     DiaCompiland = static_cast<const DIARawSymbol &>(Compiland->getRawSymbol())
277                        .getDiaSymbol();
278 
279   Flags = static_cast<PDB_NameSearchFlags>(
280       Flags | PDB_NameSearchFlags::NS_FileNameExtMatch);
281   CComPtr<IDiaEnumSourceFiles> SourceFiles;
282   if (S_OK !=
283       Session->findFile(DiaCompiland, Utf16Pattern.m_str, Flags, &SourceFiles))
284     return nullptr;
285   return llvm::make_unique<DIAEnumSourceFiles>(*this, SourceFiles);
286 }
287 
288 std::unique_ptr<IPDBSourceFile>
289 DIASession::findOneSourceFile(const PDBSymbolCompiland *Compiland,
290                               llvm::StringRef Pattern,
291                               PDB_NameSearchFlags Flags) const {
292   auto SourceFiles = findSourceFiles(Compiland, Pattern, Flags);
293   if (!SourceFiles || SourceFiles->getChildCount() == 0)
294     return nullptr;
295   return SourceFiles->getNext();
296 }
297 
298 std::unique_ptr<IPDBEnumChildren<PDBSymbolCompiland>>
299 DIASession::findCompilandsForSourceFile(llvm::StringRef Pattern,
300                                         PDB_NameSearchFlags Flags) const {
301   auto File = findOneSourceFile(nullptr, Pattern, Flags);
302   if (!File)
303     return nullptr;
304   return File->getCompilands();
305 }
306 
307 std::unique_ptr<PDBSymbolCompiland>
308 DIASession::findOneCompilandForSourceFile(llvm::StringRef Pattern,
309                                           PDB_NameSearchFlags Flags) const {
310   auto Compilands = findCompilandsForSourceFile(Pattern, Flags);
311   if (!Compilands || Compilands->getChildCount() == 0)
312     return nullptr;
313   return Compilands->getNext();
314 }
315 
316 std::unique_ptr<IPDBEnumSourceFiles> DIASession::getAllSourceFiles() const {
317   CComPtr<IDiaEnumSourceFiles> Files;
318   if (S_OK != Session->findFile(nullptr, nullptr, nsNone, &Files))
319     return nullptr;
320 
321   return llvm::make_unique<DIAEnumSourceFiles>(*this, Files);
322 }
323 
324 std::unique_ptr<IPDBEnumSourceFiles> DIASession::getSourceFilesForCompiland(
325     const PDBSymbolCompiland &Compiland) const {
326   CComPtr<IDiaEnumSourceFiles> Files;
327 
328   const DIARawSymbol &RawSymbol =
329       static_cast<const DIARawSymbol &>(Compiland.getRawSymbol());
330   if (S_OK !=
331       Session->findFile(RawSymbol.getDiaSymbol(), nullptr, nsNone, &Files))
332     return nullptr;
333 
334   return llvm::make_unique<DIAEnumSourceFiles>(*this, Files);
335 }
336 
337 std::unique_ptr<IPDBSourceFile>
338 DIASession::getSourceFileById(uint32_t FileId) const {
339   CComPtr<IDiaSourceFile> LocatedFile;
340   if (S_OK != Session->findFileById(FileId, &LocatedFile))
341     return nullptr;
342 
343   return llvm::make_unique<DIASourceFile>(*this, LocatedFile);
344 }
345 
346 std::unique_ptr<IPDBEnumDataStreams> DIASession::getDebugStreams() const {
347   CComPtr<IDiaEnumDebugStreams> DiaEnumerator;
348   if (S_OK != Session->getEnumDebugStreams(&DiaEnumerator))
349     return nullptr;
350 
351   return llvm::make_unique<DIAEnumDebugStreams>(DiaEnumerator);
352 }
353 
354 std::unique_ptr<IPDBEnumTables> DIASession::getEnumTables() const {
355   CComPtr<IDiaEnumTables> DiaEnumerator;
356   if (S_OK != Session->getEnumTables(&DiaEnumerator))
357     return nullptr;
358 
359   return llvm::make_unique<DIAEnumTables>(DiaEnumerator);
360 }
361 
362 template <class T>
363 static CComPtr<T>
364 getTableEnumerator(IDiaSession &Session) {
365   CComPtr<T> Enumerator;
366   CComPtr<IDiaEnumTables> ET;
367   CComPtr<IDiaTable> Table;
368   ULONG Count = 0;
369 
370   if (Session.getEnumTables(&ET) != S_OK)
371     return nullptr;
372 
373   while (ET->Next(1, &Table, &Count) == S_OK && Count == 1) {
374     // There is only one table that matches the given iid
375     if (S_OK ==
376         Table->QueryInterface(__uuidof(T), (void **)&Enumerator))
377       break;
378     Table.Release();
379   }
380   return Enumerator;
381 }
382 std::unique_ptr<IPDBEnumInjectedSources>
383 DIASession::getInjectedSources() const {
384   CComPtr<IDiaEnumInjectedSources> Files =
385       getTableEnumerator<IDiaEnumInjectedSources>(*Session);
386   if (!Files)
387     return nullptr;
388 
389   return llvm::make_unique<DIAEnumInjectedSources>(*this, Files);
390 }
391 
392 std::unique_ptr<IPDBEnumSectionContribs>
393 DIASession::getSectionContribs() const {
394   CComPtr<IDiaEnumSectionContribs> Sections =
395       getTableEnumerator<IDiaEnumSectionContribs>(*Session);
396   if (!Sections)
397     return nullptr;
398 
399   return llvm::make_unique<DIAEnumSectionContribs>(*this, Sections);
400 }
401