1 //===-- MinidumpParser.cpp ---------------------------------------*- 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 
10 // Project includes
11 #include "MinidumpParser.h"
12 #include "NtStructures.h"
13 #include "RegisterContextMinidump_x86_32.h"
14 
15 // Other libraries and framework includes
16 #include "lldb/Target/MemoryRegionInfo.h"
17 #include "lldb/Utility/LLDBAssert.h"
18 
19 // C includes
20 // C++ includes
21 #include <algorithm>
22 #include <map>
23 #include <vector>
24 
25 using namespace lldb_private;
26 using namespace minidump;
27 
28 llvm::Optional<MinidumpParser>
29 MinidumpParser::Create(const lldb::DataBufferSP &data_buf_sp) {
30   if (data_buf_sp->GetByteSize() < sizeof(MinidumpHeader)) {
31     return llvm::None;
32   }
33   return MinidumpParser(data_buf_sp);
34 }
35 
36 MinidumpParser::MinidumpParser(const lldb::DataBufferSP &data_buf_sp)
37     : m_data_sp(data_buf_sp) {}
38 
39 llvm::ArrayRef<uint8_t> MinidumpParser::GetData() {
40   return llvm::ArrayRef<uint8_t>(m_data_sp->GetBytes(),
41                                  m_data_sp->GetByteSize());
42 }
43 
44 llvm::ArrayRef<uint8_t>
45 MinidumpParser::GetStream(MinidumpStreamType stream_type) {
46   auto iter = m_directory_map.find(static_cast<uint32_t>(stream_type));
47   if (iter == m_directory_map.end())
48     return {};
49 
50   // check if there is enough data
51   if (iter->second.rva + iter->second.data_size > m_data_sp->GetByteSize())
52     return {};
53 
54   return llvm::ArrayRef<uint8_t>(m_data_sp->GetBytes() + iter->second.rva,
55                                  iter->second.data_size);
56 }
57 
58 llvm::Optional<std::string> MinidumpParser::GetMinidumpString(uint32_t rva) {
59   auto arr_ref = m_data_sp->GetData();
60   if (rva > arr_ref.size())
61     return llvm::None;
62   arr_ref = arr_ref.drop_front(rva);
63   return parseMinidumpString(arr_ref);
64 }
65 
66 UUID MinidumpParser::GetModuleUUID(const MinidumpModule *module) {
67   auto cv_record =
68       GetData().slice(module->CV_record.rva, module->CV_record.data_size);
69 
70   // Read the CV record signature
71   const llvm::support::ulittle32_t *signature = nullptr;
72   Status error = consumeObject(cv_record, signature);
73   if (error.Fail())
74     return UUID();
75 
76   const CvSignature cv_signature =
77       static_cast<CvSignature>(static_cast<const uint32_t>(*signature));
78 
79   if (cv_signature == CvSignature::Pdb70) {
80     // PDB70 record
81     const CvRecordPdb70 *pdb70_uuid = nullptr;
82     Status error = consumeObject(cv_record, pdb70_uuid);
83     if (!error.Fail())
84       return UUID::fromData(pdb70_uuid, sizeof(*pdb70_uuid));
85   } else if (cv_signature == CvSignature::ElfBuildId)
86     return UUID::fromData(cv_record);
87 
88   return UUID();
89 }
90 
91 llvm::ArrayRef<MinidumpThread> MinidumpParser::GetThreads() {
92   llvm::ArrayRef<uint8_t> data = GetStream(MinidumpStreamType::ThreadList);
93 
94   if (data.size() == 0)
95     return llvm::None;
96 
97   return MinidumpThread::ParseThreadList(data);
98 }
99 
100 llvm::ArrayRef<uint8_t>
101 MinidumpParser::GetThreadContext(const MinidumpThread &td) {
102   if (td.thread_context.rva + td.thread_context.data_size > GetData().size())
103     return {};
104 
105   return GetData().slice(td.thread_context.rva, td.thread_context.data_size);
106 }
107 
108 llvm::ArrayRef<uint8_t>
109 MinidumpParser::GetThreadContextWow64(const MinidumpThread &td) {
110   // On Windows, a 32-bit process can run on a 64-bit machine under WOW64. If
111   // the minidump was captured with a 64-bit debugger, then the CONTEXT we just
112   // grabbed from the mini_dump_thread is the one for the 64-bit "native"
113   // process rather than the 32-bit "guest" process we care about.  In this
114   // case, we can get the 32-bit CONTEXT from the TEB (Thread Environment
115   // Block) of the 64-bit process.
116   auto teb_mem = GetMemory(td.teb, sizeof(TEB64));
117   if (teb_mem.empty())
118     return {};
119 
120   const TEB64 *wow64teb;
121   Status error = consumeObject(teb_mem, wow64teb);
122   if (error.Fail())
123     return {};
124 
125   // Slot 1 of the thread-local storage in the 64-bit TEB points to a structure
126   // that includes the 32-bit CONTEXT (after a ULONG). See:
127   // https://msdn.microsoft.com/en-us/library/ms681670.aspx
128   auto context =
129       GetMemory(wow64teb->tls_slots[1] + 4, sizeof(MinidumpContext_x86_32));
130   if (context.size() < sizeof(MinidumpContext_x86_32))
131     return {};
132 
133   return context;
134   // NOTE:  We don't currently use the TEB for anything else.  If we
135   // need it in the future, the 32-bit TEB is located according to the address
136   // stored in the first slot of the 64-bit TEB (wow64teb.Reserved1[0]).
137 }
138 
139 const MinidumpSystemInfo *MinidumpParser::GetSystemInfo() {
140   llvm::ArrayRef<uint8_t> data = GetStream(MinidumpStreamType::SystemInfo);
141 
142   if (data.size() == 0)
143     return nullptr;
144 
145   return MinidumpSystemInfo::Parse(data);
146 }
147 
148 ArchSpec MinidumpParser::GetArchitecture() {
149   if (m_arch.IsValid())
150     return m_arch;
151 
152   // Set the architecture in m_arch
153   const MinidumpSystemInfo *system_info = GetSystemInfo();
154 
155   if (!system_info)
156     return m_arch;
157 
158   // TODO what to do about big endiand flavors of arm ?
159   // TODO set the arm subarch stuff if the minidump has info about it
160 
161   llvm::Triple triple;
162   triple.setVendor(llvm::Triple::VendorType::UnknownVendor);
163 
164   const MinidumpCPUArchitecture arch =
165       static_cast<const MinidumpCPUArchitecture>(
166           static_cast<const uint32_t>(system_info->processor_arch));
167 
168   switch (arch) {
169   case MinidumpCPUArchitecture::X86:
170     triple.setArch(llvm::Triple::ArchType::x86);
171     break;
172   case MinidumpCPUArchitecture::AMD64:
173     triple.setArch(llvm::Triple::ArchType::x86_64);
174     break;
175   case MinidumpCPUArchitecture::ARM:
176     triple.setArch(llvm::Triple::ArchType::arm);
177     break;
178   case MinidumpCPUArchitecture::ARM64:
179     triple.setArch(llvm::Triple::ArchType::aarch64);
180     break;
181   default:
182     triple.setArch(llvm::Triple::ArchType::UnknownArch);
183     break;
184   }
185 
186   const MinidumpOSPlatform os = static_cast<const MinidumpOSPlatform>(
187       static_cast<const uint32_t>(system_info->platform_id));
188 
189   // TODO add all of the OSes that Minidump/breakpad distinguishes?
190   switch (os) {
191   case MinidumpOSPlatform::Win32S:
192   case MinidumpOSPlatform::Win32Windows:
193   case MinidumpOSPlatform::Win32NT:
194   case MinidumpOSPlatform::Win32CE:
195     triple.setOS(llvm::Triple::OSType::Win32);
196     break;
197   case MinidumpOSPlatform::Linux:
198     triple.setOS(llvm::Triple::OSType::Linux);
199     break;
200   case MinidumpOSPlatform::MacOSX:
201     triple.setOS(llvm::Triple::OSType::MacOSX);
202     triple.setVendor(llvm::Triple::Apple);
203     break;
204   case MinidumpOSPlatform::IOS:
205     triple.setOS(llvm::Triple::OSType::IOS);
206     triple.setVendor(llvm::Triple::Apple);
207     break;
208   case MinidumpOSPlatform::Android:
209     triple.setOS(llvm::Triple::OSType::Linux);
210     triple.setEnvironment(llvm::Triple::EnvironmentType::Android);
211     break;
212   default: {
213     triple.setOS(llvm::Triple::OSType::UnknownOS);
214     std::string csd_version;
215     if (auto s = GetMinidumpString(system_info->csd_version_rva))
216       csd_version = *s;
217     if (csd_version.find("Linux") != std::string::npos)
218       triple.setOS(llvm::Triple::OSType::Linux);
219     break;
220     }
221   }
222   m_arch.SetTriple(triple);
223   return m_arch;
224 }
225 
226 const MinidumpMiscInfo *MinidumpParser::GetMiscInfo() {
227   llvm::ArrayRef<uint8_t> data = GetStream(MinidumpStreamType::MiscInfo);
228 
229   if (data.size() == 0)
230     return nullptr;
231 
232   return MinidumpMiscInfo::Parse(data);
233 }
234 
235 llvm::Optional<LinuxProcStatus> MinidumpParser::GetLinuxProcStatus() {
236   llvm::ArrayRef<uint8_t> data = GetStream(MinidumpStreamType::LinuxProcStatus);
237 
238   if (data.size() == 0)
239     return llvm::None;
240 
241   return LinuxProcStatus::Parse(data);
242 }
243 
244 llvm::Optional<lldb::pid_t> MinidumpParser::GetPid() {
245   const MinidumpMiscInfo *misc_info = GetMiscInfo();
246   if (misc_info != nullptr) {
247     return misc_info->GetPid();
248   }
249 
250   llvm::Optional<LinuxProcStatus> proc_status = GetLinuxProcStatus();
251   if (proc_status.hasValue()) {
252     return proc_status->GetPid();
253   }
254 
255   return llvm::None;
256 }
257 
258 llvm::ArrayRef<MinidumpModule> MinidumpParser::GetModuleList() {
259   llvm::ArrayRef<uint8_t> data = GetStream(MinidumpStreamType::ModuleList);
260 
261   if (data.size() == 0)
262     return {};
263 
264   return MinidumpModule::ParseModuleList(data);
265 }
266 
267 std::vector<const MinidumpModule *> MinidumpParser::GetFilteredModuleList() {
268   llvm::ArrayRef<MinidumpModule> modules = GetModuleList();
269   // map module_name -> pair(load_address, pointer to module struct in memory)
270   llvm::StringMap<std::pair<uint64_t, const MinidumpModule *>> lowest_addr;
271 
272   std::vector<const MinidumpModule *> filtered_modules;
273 
274   llvm::Optional<std::string> name;
275   std::string module_name;
276 
277   for (const auto &module : modules) {
278     name = GetMinidumpString(module.module_name_rva);
279 
280     if (!name)
281       continue;
282 
283     module_name = name.getValue();
284 
285     auto iter = lowest_addr.end();
286     bool exists;
287     std::tie(iter, exists) = lowest_addr.try_emplace(
288         module_name, std::make_pair(module.base_of_image, &module));
289 
290     if (exists && module.base_of_image < iter->second.first)
291       iter->second = std::make_pair(module.base_of_image, &module);
292   }
293 
294   filtered_modules.reserve(lowest_addr.size());
295   for (const auto &module : lowest_addr) {
296     filtered_modules.push_back(module.second.second);
297   }
298 
299   return filtered_modules;
300 }
301 
302 const MinidumpExceptionStream *MinidumpParser::GetExceptionStream() {
303   llvm::ArrayRef<uint8_t> data = GetStream(MinidumpStreamType::Exception);
304 
305   if (data.size() == 0)
306     return nullptr;
307 
308   return MinidumpExceptionStream::Parse(data);
309 }
310 
311 llvm::Optional<minidump::Range>
312 MinidumpParser::FindMemoryRange(lldb::addr_t addr) {
313   llvm::ArrayRef<uint8_t> data = GetStream(MinidumpStreamType::MemoryList);
314   llvm::ArrayRef<uint8_t> data64 = GetStream(MinidumpStreamType::Memory64List);
315 
316   if (data.empty() && data64.empty())
317     return llvm::None;
318 
319   if (!data.empty()) {
320     llvm::ArrayRef<MinidumpMemoryDescriptor> memory_list =
321         MinidumpMemoryDescriptor::ParseMemoryList(data);
322 
323     if (memory_list.empty())
324       return llvm::None;
325 
326     for (const auto &memory_desc : memory_list) {
327       const MinidumpLocationDescriptor &loc_desc = memory_desc.memory;
328       const lldb::addr_t range_start = memory_desc.start_of_memory_range;
329       const size_t range_size = loc_desc.data_size;
330 
331       if (loc_desc.rva + loc_desc.data_size > GetData().size())
332         return llvm::None;
333 
334       if (range_start <= addr && addr < range_start + range_size) {
335         return minidump::Range(range_start,
336                                GetData().slice(loc_desc.rva, range_size));
337       }
338     }
339   }
340 
341   // Some Minidumps have a Memory64ListStream that captures all the heap memory
342   // (full-memory Minidumps).  We can't exactly use the same loop as above,
343   // because the Minidump uses slightly different data structures to describe
344   // those
345 
346   if (!data64.empty()) {
347     llvm::ArrayRef<MinidumpMemoryDescriptor64> memory64_list;
348     uint64_t base_rva;
349     std::tie(memory64_list, base_rva) =
350         MinidumpMemoryDescriptor64::ParseMemory64List(data64);
351 
352     if (memory64_list.empty())
353       return llvm::None;
354 
355     for (const auto &memory_desc64 : memory64_list) {
356       const lldb::addr_t range_start = memory_desc64.start_of_memory_range;
357       const size_t range_size = memory_desc64.data_size;
358 
359       if (base_rva + range_size > GetData().size())
360         return llvm::None;
361 
362       if (range_start <= addr && addr < range_start + range_size) {
363         return minidump::Range(range_start,
364                                GetData().slice(base_rva, range_size));
365       }
366       base_rva += range_size;
367     }
368   }
369 
370   return llvm::None;
371 }
372 
373 llvm::ArrayRef<uint8_t> MinidumpParser::GetMemory(lldb::addr_t addr,
374                                                   size_t size) {
375   // I don't have a sense of how frequently this is called or how many memory
376   // ranges a Minidump typically has, so I'm not sure if searching for the
377   // appropriate range linearly each time is stupid.  Perhaps we should build
378   // an index for faster lookups.
379   llvm::Optional<minidump::Range> range = FindMemoryRange(addr);
380   if (!range)
381     return {};
382 
383   // There's at least some overlap between the beginning of the desired range
384   // (addr) and the current range.  Figure out where the overlap begins and how
385   // much overlap there is.
386 
387   const size_t offset = addr - range->start;
388 
389   if (addr < range->start || offset >= range->range_ref.size())
390     return {};
391 
392   const size_t overlap = std::min(size, range->range_ref.size() - offset);
393   return range->range_ref.slice(offset, overlap);
394 }
395 
396 llvm::Optional<MemoryRegionInfo>
397 MinidumpParser::GetMemoryRegionInfo(lldb::addr_t load_addr) {
398   MemoryRegionInfo info;
399   llvm::ArrayRef<uint8_t> data = GetStream(MinidumpStreamType::MemoryInfoList);
400   if (data.empty())
401     return llvm::None;
402 
403   std::vector<const MinidumpMemoryInfo *> mem_info_list =
404       MinidumpMemoryInfo::ParseMemoryInfoList(data);
405   if (mem_info_list.empty())
406     return llvm::None;
407 
408   const auto yes = MemoryRegionInfo::eYes;
409   const auto no = MemoryRegionInfo::eNo;
410 
411   const MinidumpMemoryInfo *next_entry = nullptr;
412   for (const auto &entry : mem_info_list) {
413     const auto head = entry->base_address;
414     const auto tail = head + entry->region_size;
415 
416     if (head <= load_addr && load_addr < tail) {
417       info.GetRange().SetRangeBase(
418           (entry->state != uint32_t(MinidumpMemoryInfoState::MemFree))
419               ? head
420               : load_addr);
421       info.GetRange().SetRangeEnd(tail);
422 
423       const uint32_t PageNoAccess =
424           static_cast<uint32_t>(MinidumpMemoryProtectionContants::PageNoAccess);
425       info.SetReadable((entry->protect & PageNoAccess) == 0 ? yes : no);
426 
427       const uint32_t PageWritable =
428           static_cast<uint32_t>(MinidumpMemoryProtectionContants::PageWritable);
429       info.SetWritable((entry->protect & PageWritable) != 0 ? yes : no);
430 
431       const uint32_t PageExecutable = static_cast<uint32_t>(
432           MinidumpMemoryProtectionContants::PageExecutable);
433       info.SetExecutable((entry->protect & PageExecutable) != 0 ? yes : no);
434 
435       const uint32_t MemFree =
436           static_cast<uint32_t>(MinidumpMemoryInfoState::MemFree);
437       info.SetMapped((entry->state != MemFree) ? yes : no);
438 
439       return info;
440     } else if (head > load_addr &&
441                (next_entry == nullptr || head < next_entry->base_address)) {
442       // In case there is no region containing load_addr keep track of the
443       // nearest region after load_addr so we can return the distance to it.
444       next_entry = entry;
445     }
446   }
447 
448   // No containing region found. Create an unmapped region that extends to the
449   // next region or LLDB_INVALID_ADDRESS
450   info.GetRange().SetRangeBase(load_addr);
451   info.GetRange().SetRangeEnd((next_entry != nullptr) ? next_entry->base_address
452                                                       : LLDB_INVALID_ADDRESS);
453   info.SetReadable(no);
454   info.SetWritable(no);
455   info.SetExecutable(no);
456   info.SetMapped(no);
457 
458   // Note that the memory info list doesn't seem to contain ranges in kernel
459   // space, so if you're walking a stack that has kernel frames, the stack may
460   // appear truncated.
461   return info;
462 }
463 
464 Status MinidumpParser::Initialize() {
465   Status error;
466 
467   lldbassert(m_directory_map.empty());
468 
469   llvm::ArrayRef<uint8_t> header_data(m_data_sp->GetBytes(),
470                                       sizeof(MinidumpHeader));
471   const MinidumpHeader *header = MinidumpHeader::Parse(header_data);
472   if (header == nullptr) {
473     error.SetErrorString("invalid minidump: can't parse the header");
474     return error;
475   }
476 
477   // A minidump without at least one stream is clearly ill-formed
478   if (header->streams_count == 0) {
479     error.SetErrorString("invalid minidump: no streams present");
480     return error;
481   }
482 
483   struct FileRange {
484     uint32_t offset = 0;
485     uint32_t size = 0;
486 
487     FileRange(uint32_t offset, uint32_t size) : offset(offset), size(size) {}
488     uint32_t end() const { return offset + size; }
489   };
490 
491   const uint32_t file_size = m_data_sp->GetByteSize();
492 
493   // Build a global minidump file map, checking for:
494   // - overlapping streams/data structures
495   // - truncation (streams pointing past the end of file)
496   std::vector<FileRange> minidump_map;
497 
498   // Add the minidump header to the file map
499   if (sizeof(MinidumpHeader) > file_size) {
500     error.SetErrorString("invalid minidump: truncated header");
501     return error;
502   }
503   minidump_map.emplace_back( 0, sizeof(MinidumpHeader) );
504 
505   // Add the directory entries to the file map
506   FileRange directory_range(header->stream_directory_rva,
507                             header->streams_count *
508                                 sizeof(MinidumpDirectory));
509   if (directory_range.end() > file_size) {
510     error.SetErrorString("invalid minidump: truncated streams directory");
511     return error;
512   }
513   minidump_map.push_back(directory_range);
514 
515   // Parse stream directory entries
516   llvm::ArrayRef<uint8_t> directory_data(
517       m_data_sp->GetBytes() + directory_range.offset, directory_range.size);
518   for (uint32_t i = 0; i < header->streams_count; ++i) {
519     const MinidumpDirectory *directory_entry = nullptr;
520     error = consumeObject(directory_data, directory_entry);
521     if (error.Fail())
522       return error;
523     if (directory_entry->stream_type == 0) {
524       // Ignore dummy streams (technically ill-formed, but a number of
525       // existing minidumps seem to contain such streams)
526       if (directory_entry->location.data_size == 0)
527         continue;
528       error.SetErrorString("invalid minidump: bad stream type");
529       return error;
530     }
531     // Update the streams map, checking for duplicate stream types
532     if (!m_directory_map
533              .insert({directory_entry->stream_type, directory_entry->location})
534              .second) {
535       error.SetErrorString("invalid minidump: duplicate stream type");
536       return error;
537     }
538     // Ignore the zero-length streams for layout checks
539     if (directory_entry->location.data_size != 0) {
540       minidump_map.emplace_back(directory_entry->location.rva,
541                                 directory_entry->location.data_size);
542     }
543   }
544 
545   // Sort the file map ranges by start offset
546   std::sort(minidump_map.begin(), minidump_map.end(),
547             [](const FileRange &a, const FileRange &b) {
548               return a.offset < b.offset;
549             });
550 
551   // Check for overlapping streams/data structures
552   for (size_t i = 1; i < minidump_map.size(); ++i) {
553     const auto &prev_range = minidump_map[i - 1];
554     if (prev_range.end() > minidump_map[i].offset) {
555       error.SetErrorString("invalid minidump: overlapping streams");
556       return error;
557     }
558   }
559 
560   // Check for streams past the end of file
561   const auto &last_range = minidump_map.back();
562   if (last_range.end() > file_size) {
563     error.SetErrorString("invalid minidump: truncated stream");
564     return error;
565   }
566 
567   return error;
568 }
569