[Tizen] Add a library to retrieve memory regions for a coredump
[platform/upstream/coreclr.git] / src / debug / createdump / crashinfo.cpp
1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4
5 #include "createdump.h"
6
7 // This is for the PAL_VirtualUnwindOutOfProc read memory adapter.
8 CrashInfo* g_crashInfo;
9
10 CrashInfo::CrashInfo(pid_t pid, ICLRDataTarget* dataTarget, bool sos) :
11     m_ref(1),
12     m_pid(pid),
13     m_ppid(-1),
14     m_name(nullptr),
15     m_sos(sos),
16     m_dataTarget(dataTarget)
17 {
18     g_crashInfo = this;
19     dataTarget->AddRef();
20     m_auxvValues.fill(0);
21 }
22
23 CrashInfo::~CrashInfo()
24 {
25     if (m_name != nullptr)
26     {
27         free(m_name);
28     }
29     // Clean up the threads
30     for (ThreadInfo* thread : m_threads)
31     {
32         delete thread;
33     }
34     m_threads.clear();
35
36     // Module and other mappings have a file name to clean up.
37     for (const MemoryRegion& region : m_moduleMappings)
38     {
39         const_cast<MemoryRegion&>(region).Cleanup();
40     }
41     m_moduleMappings.clear();
42     for (const MemoryRegion& region : m_otherMappings)
43     {
44         const_cast<MemoryRegion&>(region).Cleanup();
45     }
46     m_otherMappings.clear();
47     m_dataTarget->Release();
48 }
49
50 STDMETHODIMP
51 CrashInfo::QueryInterface(
52     ___in REFIID InterfaceId,
53     ___out PVOID* Interface)
54 {
55     if (InterfaceId == IID_IUnknown ||
56         InterfaceId == IID_ICLRDataEnumMemoryRegionsCallback)
57     {
58         *Interface = (ICLRDataEnumMemoryRegionsCallback*)this;
59         AddRef();
60         return S_OK;
61     }
62     else
63     {
64         *Interface = nullptr;
65         return E_NOINTERFACE;
66     }
67 }
68
69 STDMETHODIMP_(ULONG)
70 CrashInfo::AddRef()
71 {
72     LONG ref = InterlockedIncrement(&m_ref);
73     return ref;
74 }
75
76 STDMETHODIMP_(ULONG)
77 CrashInfo::Release()
78 {
79     LONG ref = InterlockedDecrement(&m_ref);
80     if (ref == 0)
81     {
82         delete this;
83     }
84     return ref;
85 }
86
87 HRESULT STDMETHODCALLTYPE
88 CrashInfo::EnumMemoryRegion(
89     /* [in] */ CLRDATA_ADDRESS address,
90     /* [in] */ ULONG32 size)
91 {
92     InsertMemoryRegion((ULONG_PTR)address, size);
93     return S_OK;
94 }
95
96 //
97 // Suspends all the threads and creating a list of them. Should be the first before
98 // gather any info about the process.
99 //
100 bool 
101 CrashInfo::EnumerateAndSuspendThreads(bool suspend)
102 {
103     char taskPath[128];
104     snprintf(taskPath, sizeof(taskPath), "/proc/%d/task", m_pid);
105
106     DIR* taskDir = opendir(taskPath);
107     if (taskDir == nullptr)
108     {
109         fprintf(stderr, "opendir(%s) FAILED %s\n", taskPath, strerror(errno));
110         return false;
111     }
112
113     struct dirent* entry;
114     while ((entry = readdir(taskDir)) != nullptr)
115     {
116         pid_t tid = static_cast<pid_t>(strtol(entry->d_name, nullptr, 10));
117         if (tid != 0)
118         {
119             // Don't suspend the threads if running under sos
120             if (!m_sos && suspend)
121             {
122                 //  Reference: http://stackoverflow.com/questions/18577956/how-to-use-ptrace-to-get-a-consistent-view-of-multiple-threads
123                 if (ptrace(PTRACE_ATTACH, tid, nullptr, nullptr) != -1)
124                 {
125                     int waitStatus;
126                     waitpid(tid, &waitStatus, __WALL);
127                 }
128                 else
129                 {
130                     fprintf(stderr, "ptrace(ATTACH, %d) FAILED %s\n", tid, strerror(errno));
131                     closedir(taskDir);
132                     return false;
133                 }
134             }
135             // Add to the list of threads
136             ThreadInfo* thread = new ThreadInfo(tid);
137             m_threads.push_back(thread);
138         }
139     }
140
141     closedir(taskDir);
142     return true;
143 }
144
145 //
146 // Set registers for all threads
147 //
148 bool
149 CrashInfo::SetThreadsRegisters(const std::vector<elf_prstatus*> &statuses)
150 {
151     for (ThreadInfo* thread : m_threads) {
152         for (elf_prstatus* status : statuses) {
153             if (thread->Tid() == status->pr_pid) {
154                 thread->SetRegisters(status);
155                 break;
156             }
157         }
158     }
159
160     return true;
161 }
162
163 //
164 // Gather all the necessary crash dump info.
165 //
166 bool
167 CrashInfo::GatherCrashInfo(MINIDUMP_TYPE minidumpType, bool initialize_threads)
168 {
169     // Get the process info
170     if (!GetStatus(m_pid, &m_ppid, &m_tgid, &m_name))
171     {
172         return false;
173     }
174     if (initialize_threads) {
175         // Get the info about the threads (registers, etc.)
176         for (ThreadInfo* thread : m_threads)
177         {
178             if (!thread->Initialize(m_sos ? m_dataTarget : nullptr))
179             {
180                 return false;
181             }
182         }
183     }
184     // Get the auxv data
185     if (!GetAuxvEntries())
186     {
187         return false;
188     }
189     // Gather all the module memory mappings (from /dev/$pid/maps)
190     if (!EnumerateModuleMappings())
191     {
192         return false;
193     }
194     // Get shared module debug info
195     if (!GetDSOInfo())
196     {
197         return false;
198     }
199
200     for (const MemoryRegion& region : m_moduleAddresses)
201     {
202         region.Trace();
203     }
204
205     // If full memory dump, include everything regardless of permissions
206     if (minidumpType & MiniDumpWithFullMemory)
207     {
208         for (const MemoryRegion& region : m_moduleMappings)
209         {
210             InsertMemoryBackedRegion(region);
211         }
212         for (const MemoryRegion& region : m_otherMappings)
213         {
214             // Don't add uncommitted pages to the full dump
215             if ((region.Permissions() & (PF_R | PF_W | PF_X)) != 0)
216             {
217                 InsertMemoryBackedRegion(region);
218             }
219         }
220     }
221     // Add all the heap read/write memory regions (m_otherMappings contains the heaps). On Alpine
222     // the heap regions are marked RWX instead of just RW.
223     else if (minidumpType & MiniDumpWithPrivateReadWriteMemory)
224     {
225         for (const MemoryRegion& region : m_otherMappings)
226         {
227             uint32_t permissions = region.Permissions();
228             if (permissions == (PF_R | PF_W) || permissions == (PF_R | PF_W | PF_X))
229             {
230                 InsertMemoryBackedRegion(region);
231             }
232         }
233     }
234     // Gather all the useful memory regions from the DAC
235     if (!EnumerateMemoryRegionsWithDAC(minidumpType))
236     {
237         return false;
238     }
239     if ((minidumpType & MiniDumpWithFullMemory) == 0)
240     {
241         // Add the thread's stack and some code memory to core
242         for (ThreadInfo* thread : m_threads)
243         {
244             // Add the thread's stack
245             thread->GetThreadStack(*this);
246         }
247         // All the regions added so far has been backed by memory. Now add the rest of
248         // mappings so the debuggers like lldb see that an address is code (PF_X) even
249         // if it isn't actually in the core dump.
250         for (const MemoryRegion& region : m_moduleMappings)
251         {
252             assert(!region.IsBackedByMemory());
253             InsertMemoryRegion(region);
254         }
255         for (const MemoryRegion& region : m_otherMappings)
256         {
257             assert(!region.IsBackedByMemory());
258             InsertMemoryRegion(region);
259         }
260     }
261     // Join all adjacent memory regions
262     CombineMemoryRegions();
263     return true;
264 }
265
266 void
267 CrashInfo::ResumeThreads()
268 {
269     if (!m_sos)
270     {
271         for (ThreadInfo* thread : m_threads)
272         {
273             thread->ResumeThread();
274         }
275     }
276 }
277
278 //
279 // Get the auxv entries to use and add to the core dump
280 //
281 bool
282 CrashInfo::GetAuxvEntries()
283 {
284     char auxvPath[128];
285     snprintf(auxvPath, sizeof(auxvPath), "/proc/%d/auxv", m_pid);
286
287     int fd = open(auxvPath, O_RDONLY, 0);
288     if (fd == -1)
289     {
290         fprintf(stderr, "open(%s) FAILED %s\n", auxvPath, strerror(errno));
291         return false;
292     }
293     bool result = false;
294     elf_aux_entry auxvEntry;
295
296     while (read(fd, &auxvEntry, sizeof(elf_aux_entry)) == sizeof(elf_aux_entry))
297     {
298         m_auxvEntries.push_back(auxvEntry);
299         if (auxvEntry.a_type == AT_NULL)
300         {
301             break;
302         }
303         if (auxvEntry.a_type < AT_MAX)
304         {
305             m_auxvValues[auxvEntry.a_type] = auxvEntry.a_un.a_val;
306             TRACE("AUXV: %" PRIu " = %" PRIxA "\n", auxvEntry.a_type, auxvEntry.a_un.a_val);
307             result = true;
308         }
309     }
310
311     close(fd);
312     return result;
313 }
314
315 //
316 // Get the module mappings for the core dump NT_FILE notes
317 //
318 bool
319 CrashInfo::EnumerateModuleMappings()
320 {
321     // Here we read /proc/<pid>/maps file in order to parse it and figure out what it says
322     // about a library we are looking for. This file looks something like this:
323     //
324     // [address]          [perms] [offset] [dev] [inode] [pathname] - HEADER is not preset in an actual file
325     //
326     // 35b1800000-35b1820000 r-xp 00000000 08:02 135522  /usr/lib64/ld-2.15.so
327     // 35b1a1f000-35b1a20000 r--p 0001f000 08:02 135522  /usr/lib64/ld-2.15.so
328     // 35b1a20000-35b1a21000 rw-p 00020000 08:02 135522  /usr/lib64/ld-2.15.so
329     // 35b1a21000-35b1a22000 rw-p 00000000 00:00 0       [heap]
330     // 35b1c00000-35b1dac000 r-xp 00000000 08:02 135870  /usr/lib64/libc-2.15.so
331     // 35b1dac000-35b1fac000 ---p 001ac000 08:02 135870  /usr/lib64/libc-2.15.so
332     // 35b1fac000-35b1fb0000 r--p 001ac000 08:02 135870  /usr/lib64/libc-2.15.so
333     // 35b1fb0000-35b1fb2000 rw-p 001b0000 08:02 135870  /usr/lib64/libc-2.15.so
334     char* line = nullptr;
335     size_t lineLen = 0;
336     int count = 0;
337     ssize_t read;
338
339     // Making something like: /proc/123/maps
340     char mapPath[128];
341     int chars = snprintf(mapPath, sizeof(mapPath), "/proc/%d/maps", m_pid);
342     assert(chars > 0 && (size_t)chars <= sizeof(mapPath));
343
344     FILE* mapsFile = fopen(mapPath, "r");
345     if (mapsFile == nullptr)
346     {
347         fprintf(stderr, "fopen(%s) FAILED %s\n", mapPath, strerror(errno));
348         return false;
349     }
350     // linuxGateAddress is the beginning of the kernel's mapping of
351     // linux-gate.so in the process.  It doesn't actually show up in the
352     // maps list as a filename, but it can be found using the AT_SYSINFO_EHDR
353     // aux vector entry, which gives the information necessary to special
354     // case its entry when creating the list of mappings.
355     // See http://www.trilithium.com/johan/2005/08/linux-gate/ for more
356     // information.
357     const void* linuxGateAddress = (const void*)m_auxvValues[AT_SYSINFO_EHDR];
358
359     // Reading maps file line by line
360     while ((read = getline(&line, &lineLen, mapsFile)) != -1)
361     {
362         uint64_t start, end, offset;
363         char* permissions = nullptr;
364         char* moduleName = nullptr;
365
366         int c = sscanf(line, "%" PRIx64 "-%" PRIx64 " %m[-rwxsp] %" PRIx64 " %*[:0-9a-f] %*d %ms\n", &start, &end, &permissions, &offset, &moduleName);
367         if (c == 4 || c == 5)
368         {
369             // r = read
370             // w = write
371             // x = execute
372             // s = shared
373             // p = private (copy on write)
374             uint32_t regionFlags = 0;
375             if (strchr(permissions, 'r')) {
376                 regionFlags |= PF_R;
377             }
378             if (strchr(permissions, 'w')) {
379                 regionFlags |= PF_W;
380             }
381             if (strchr(permissions, 'x')) {
382                 regionFlags |= PF_X;
383             }
384             if (strchr(permissions, 's')) {
385                 regionFlags |= MEMORY_REGION_FLAG_SHARED;
386             }
387             if (strchr(permissions, 'p')) {
388                 regionFlags |= MEMORY_REGION_FLAG_PRIVATE;
389             }
390             MemoryRegion memoryRegion(regionFlags, start, end, offset, moduleName);
391
392             if (moduleName != nullptr && *moduleName == '/')
393             {
394                 if (m_coreclrPath.empty())
395                 {
396                     std::string coreclrPath;
397                     coreclrPath.append(moduleName);
398                     size_t last = coreclrPath.rfind(MAKEDLLNAME_A("coreclr"));
399                     if (last != std::string::npos) {
400                         m_coreclrPath = coreclrPath.substr(0, last);
401                     }
402                 }
403                 m_moduleMappings.insert(memoryRegion);
404             }
405             else
406             {
407                 m_otherMappings.insert(memoryRegion);
408             }
409             if (linuxGateAddress != nullptr && reinterpret_cast<void*>(start) == linuxGateAddress)
410             {
411                 InsertMemoryBackedRegion(memoryRegion);
412             }
413             free(permissions);
414         }
415     }
416
417     if (g_diagnostics)
418     {
419         TRACE("Module mappings:\n");
420         for (const MemoryRegion& region : m_moduleMappings)
421         {
422             region.Trace();
423         }
424         TRACE("Other mappings:\n");
425         for (const MemoryRegion& region : m_otherMappings)
426         {
427             region.Trace();
428         }
429     }
430
431     free(line); // We didn't allocate line, but as per contract of getline we should free it
432     fclose(mapsFile);
433
434     return true;
435 }
436
437 //
438 // All the shared (native) module info to the core dump
439 //
440 bool
441 CrashInfo::GetDSOInfo()
442 {
443     Phdr* phdrAddr = reinterpret_cast<Phdr*>(m_auxvValues[AT_PHDR]);
444     int phnum = m_auxvValues[AT_PHNUM];
445     assert(m_auxvValues[AT_PHENT] == sizeof(Phdr));
446     assert(phnum != PN_XNUM);
447
448     if (phnum <= 0 || phdrAddr == nullptr) {
449         return false;
450     }
451     uint64_t baseAddress = (uint64_t)phdrAddr - sizeof(Ehdr);
452     ElfW(Dyn)* dynamicAddr = nullptr;
453
454     TRACE("DSO: base %" PRIA PRIx64 " phdr %p phnum %d\n", baseAddress, phdrAddr, phnum);
455
456     // Enumerate program headers searching for the PT_DYNAMIC header, etc.
457     if (!EnumerateProgramHeaders(phdrAddr, phnum, baseAddress, &dynamicAddr))
458     {
459         return false;
460     }
461     if (dynamicAddr == nullptr) {
462         return false;
463     }
464
465     // Search for dynamic debug (DT_DEBUG) entry
466     struct r_debug* rdebugAddr = nullptr;
467     for (;;) {
468         ElfW(Dyn) dyn;
469         if (!ReadMemory(dynamicAddr, &dyn, sizeof(dyn))) {
470             fprintf(stderr, "ReadMemory(%p, %" PRIx ") dyn FAILED\n", dynamicAddr, sizeof(dyn));
471             return false;
472         }
473         TRACE("DSO: dyn %p tag %" PRId " (%" PRIx ") d_ptr %" PRIxA "\n", dynamicAddr, dyn.d_tag, dyn.d_tag, dyn.d_un.d_ptr);
474         if (dyn.d_tag == DT_DEBUG) {
475             rdebugAddr = reinterpret_cast<struct r_debug*>(dyn.d_un.d_ptr);
476         }
477         else if (dyn.d_tag == DT_NULL) {
478             break;
479         }
480         dynamicAddr++;
481     }
482
483     // Add the DSO r_debug entry
484     TRACE("DSO: rdebugAddr %p\n", rdebugAddr);
485     struct r_debug debugEntry;
486     if (!ReadMemory(rdebugAddr, &debugEntry, sizeof(debugEntry))) {
487         fprintf(stderr, "ReadMemory(%p, %" PRIx ") r_debug FAILED\n", rdebugAddr, sizeof(debugEntry));
488         return false;
489     }
490
491     // Add the DSO link_map entries
492     ArrayHolder<char> moduleName = new char[PATH_MAX];
493     for (struct link_map* linkMapAddr = debugEntry.r_map; linkMapAddr != nullptr;) {
494         struct link_map map;
495         if (!ReadMemory(linkMapAddr, &map, sizeof(map))) {
496             fprintf(stderr, "ReadMemory(%p, %" PRIx ") link_map FAILED\n", linkMapAddr, sizeof(map));
497             return false;
498         }
499         // Read the module's name and make sure the memory is added to the core dump
500         int i = 0;
501         if (map.l_name != nullptr) {
502             for (; i < PATH_MAX; i++)
503             {
504                 if (!ReadMemory(map.l_name + i, &moduleName[i], 1)) {
505                     TRACE("DSO: ReadMemory link_map name %p + %d FAILED\n", map.l_name, i);
506                     break;
507                 }
508                 if (moduleName[i] == '\0') {
509                     break;
510                 }
511             }
512         }
513         moduleName[i] = '\0';
514         TRACE("\nDSO: link_map entry %p l_ld %p l_addr (Ehdr) %" PRIx " %s\n", linkMapAddr, map.l_ld, map.l_addr, (char*)moduleName);
515
516         // Read the ELF header and info adding it to the core dump
517         if (!GetELFInfo(map.l_addr)) {
518             return false;
519         }
520         linkMapAddr = map.l_next;
521     }
522
523     return true;
524 }
525
526 //
527 // Add all the necessary ELF headers to the core dump
528 //
529 bool
530 CrashInfo::GetELFInfo(uint64_t baseAddress)
531 {
532     if (baseAddress == 0 || baseAddress == m_auxvValues[AT_SYSINFO_EHDR] || baseAddress == m_auxvValues[AT_BASE]) {
533         return true;
534     }
535     Ehdr ehdr;
536     if (!ReadMemory((void*)baseAddress, &ehdr, sizeof(ehdr))) {
537         TRACE("ReadMemory(%p, %" PRIx ") ehdr FAILED\n", (void*)baseAddress, sizeof(ehdr));
538         return true;
539     }
540     int phnum = ehdr.e_phnum;
541     assert(phnum != PN_XNUM);
542     assert(ehdr.e_phentsize == sizeof(Phdr));
543 #ifdef BIT64
544     assert(ehdr.e_ident[EI_CLASS] == ELFCLASS64);
545 #else
546     assert(ehdr.e_ident[EI_CLASS] == ELFCLASS32);
547 #endif
548     assert(ehdr.e_ident[EI_DATA] == ELFDATA2LSB);
549
550     TRACE("ELF: type %d mach 0x%x ver %d flags 0x%x phnum %d phoff %" PRIxA " phentsize 0x%02x shnum %d shoff %" PRIxA " shentsize 0x%02x shstrndx %d\n",
551         ehdr.e_type, ehdr.e_machine, ehdr.e_version, ehdr.e_flags, phnum, ehdr.e_phoff, ehdr.e_phentsize, ehdr.e_shnum, ehdr.e_shoff, ehdr.e_shentsize, ehdr.e_shstrndx);
552
553     if (ehdr.e_phoff != 0 && phnum > 0)
554     {
555         Phdr* phdrAddr = reinterpret_cast<Phdr*>(baseAddress + ehdr.e_phoff);
556
557         if (!EnumerateProgramHeaders(phdrAddr, phnum, baseAddress, nullptr))
558         {
559             return false;
560         }
561     }
562
563     return true;
564 }
565
566 //
567 // Enumerate the program headers adding the build id note, unwind frame
568 // region and module addresses to the crash info.
569 //
570 bool
571 CrashInfo::EnumerateProgramHeaders(Phdr* phdrAddr, int phnum, uint64_t baseAddress, ElfW(Dyn)** pdynamicAddr)
572 {
573     uint64_t loadbias = baseAddress;
574
575     for (int i = 0; i < phnum; i++)
576     {
577         Phdr ph;
578         if (!ReadMemory(phdrAddr + i, &ph, sizeof(ph))) {
579             fprintf(stderr, "ReadMemory(%p, %" PRIx ") phdr FAILED\n", phdrAddr + i, sizeof(ph));
580             return false;
581         }
582         if (ph.p_type == PT_LOAD && ph.p_offset == 0)
583         {
584             loadbias -= ph.p_vaddr;
585             TRACE("PHDR: loadbias %" PRIA PRIx64 "\n", loadbias);
586             break;
587         }
588     }
589
590     for (int i = 0; i < phnum; i++)
591     {
592         Phdr ph;
593         if (!ReadMemory(phdrAddr + i, &ph, sizeof(ph))) {
594             fprintf(stderr, "ReadMemory(%p, %" PRIx ") phdr FAILED\n", phdrAddr + i, sizeof(ph));
595             return false;
596         }
597         TRACE("PHDR: %p type %d (%x) vaddr %" PRIxA " memsz %" PRIxA " paddr %" PRIxA " filesz %" PRIxA " offset %" PRIxA " align %" PRIxA "\n",
598             phdrAddr + i, ph.p_type, ph.p_type, ph.p_vaddr, ph.p_memsz, ph.p_paddr, ph.p_filesz, ph.p_offset, ph.p_align);
599
600         switch (ph.p_type)
601         {
602         case PT_DYNAMIC:
603             if (pdynamicAddr != nullptr)
604             {
605                 *pdynamicAddr = reinterpret_cast<ElfW(Dyn)*>(loadbias + ph.p_vaddr);
606                 break;
607             }
608             // fall into InsertMemoryRegion
609
610         case PT_NOTE:
611         case PT_GNU_EH_FRAME:
612             if (ph.p_vaddr != 0 && ph.p_memsz != 0) {
613                 InsertMemoryRegion(loadbias + ph.p_vaddr, ph.p_memsz);
614             }
615             break;
616
617         case PT_LOAD:
618             MemoryRegion region(0, loadbias + ph.p_vaddr, loadbias + ph.p_vaddr + ph.p_memsz, baseAddress);
619             m_moduleAddresses.insert(region);
620             break;
621         }
622     }
623
624     return true;
625 }
626
627 //
628 // Enumerate all the memory regions using the DAC memory region support given a minidump type
629 //
630 bool
631 CrashInfo::EnumerateMemoryRegionsWithDAC(MINIDUMP_TYPE minidumpType)
632 {
633     PFN_CLRDataCreateInstance pfnCLRDataCreateInstance = nullptr;
634     ICLRDataEnumMemoryRegions* pClrDataEnumRegions = nullptr;
635     IXCLRDataProcess* pClrDataProcess = nullptr;
636     HMODULE hdac = nullptr;
637     HRESULT hr = S_OK;
638     bool result = false;
639
640     if (!m_coreclrPath.empty())
641     {
642         // We assume that the DAC is in the same location as the libcoreclr.so module
643         std::string dacPath;
644         dacPath.append(m_coreclrPath);
645         dacPath.append(MAKEDLLNAME_A("mscordaccore"));
646
647         // Load and initialize the DAC
648         hdac = LoadLibraryA(dacPath.c_str());
649         if (hdac == nullptr)
650         {
651             fprintf(stderr, "LoadLibraryA(%s) FAILED %d\n", dacPath.c_str(), GetLastError());
652             goto exit;
653         }
654         pfnCLRDataCreateInstance = (PFN_CLRDataCreateInstance)GetProcAddress(hdac, "CLRDataCreateInstance");
655         if (pfnCLRDataCreateInstance == nullptr)
656         {
657             fprintf(stderr, "GetProcAddress(CLRDataCreateInstance) FAILED %d\n", GetLastError());
658             goto exit;
659         }
660         if ((minidumpType & MiniDumpWithFullMemory) == 0)
661         {
662             hr = pfnCLRDataCreateInstance(__uuidof(ICLRDataEnumMemoryRegions), m_dataTarget, (void**)&pClrDataEnumRegions);
663             if (FAILED(hr))
664             {
665                 fprintf(stderr, "CLRDataCreateInstance(ICLRDataEnumMemoryRegions) FAILED %08x\n", hr);
666                 goto exit;
667             }
668             // Calls CrashInfo::EnumMemoryRegion for each memory region found by the DAC
669             hr = pClrDataEnumRegions->EnumMemoryRegions(this, minidumpType, CLRDATA_ENUM_MEM_DEFAULT);
670             if (FAILED(hr))
671             {
672                 fprintf(stderr, "EnumMemoryRegions FAILED %08x\n", hr);
673                 goto exit;
674             }
675         }
676         hr = pfnCLRDataCreateInstance(__uuidof(IXCLRDataProcess), m_dataTarget, (void**)&pClrDataProcess);
677         if (FAILED(hr))
678         {
679             fprintf(stderr, "CLRDataCreateInstance(IXCLRDataProcess) FAILED %08x\n", hr);
680             goto exit;
681         }
682         if (!EnumerateManagedModules(pClrDataProcess))
683         {
684             goto exit;
685         }
686     }
687     else {
688         TRACE("EnumerateMemoryRegionsWithDAC: coreclr not found; not using DAC\n");
689     }
690     if (!UnwindAllThreads(pClrDataProcess))
691     {
692         goto exit;
693     }
694     result = true;
695 exit:
696     if (pClrDataEnumRegions != nullptr)
697     {
698         pClrDataEnumRegions->Release();
699     }
700     if (pClrDataProcess != nullptr)
701     {
702         pClrDataProcess->Release();
703     }
704     if (hdac != nullptr)
705     {
706         FreeLibrary(hdac);
707     }
708     return result;
709 }
710
711 //
712 // Enumerate all the managed modules and replace the module mapping with the module name found.
713 //
714 bool
715 CrashInfo::EnumerateManagedModules(IXCLRDataProcess* pClrDataProcess)
716 {
717     CLRDATA_ENUM enumModules = 0;
718     bool result = true;
719     HRESULT hr = S_OK;
720
721     if (FAILED(hr = pClrDataProcess->StartEnumModules(&enumModules))) {
722         fprintf(stderr, "StartEnumModules FAILED %08x\n", hr);
723         return false;
724     }
725
726     while (true)
727     {
728         ReleaseHolder<IXCLRDataModule> pClrDataModule;
729         if ((hr = pClrDataProcess->EnumModule(&enumModules, &pClrDataModule)) != S_OK) {
730             break;
731         }
732
733         // Skip any dynamic modules. The Request call below on some DACs crashes on dynamic modules.
734         ULONG32 flags;
735         if ((hr = pClrDataModule->GetFlags(&flags)) != S_OK) {
736             TRACE("MODULE: GetFlags FAILED %08x\n", hr);
737             continue;
738         }
739         if (flags & CLRDATA_MODULE_IS_DYNAMIC) {
740             TRACE("MODULE: Skipping dynamic module\n");
741             continue;
742         }
743
744         DacpGetModuleData moduleData;
745         if (SUCCEEDED(hr = moduleData.Request(pClrDataModule.GetPtr())))
746         {
747             TRACE("MODULE: %" PRIA PRIx64 " dyn %d inmem %d file %d pe %" PRIA PRIx64 " pdb %" PRIA PRIx64, moduleData.LoadedPEAddress, moduleData.IsDynamic,
748                 moduleData.IsInMemory, moduleData.IsFileLayout, moduleData.PEFile, moduleData.InMemoryPdbAddress);
749
750             if (!moduleData.IsDynamic && moduleData.LoadedPEAddress != 0)
751             {
752                 ArrayHolder<WCHAR> wszUnicodeName = new WCHAR[MAX_LONGPATH + 1];
753                 if (SUCCEEDED(hr = pClrDataModule->GetFileName(MAX_LONGPATH, nullptr, wszUnicodeName)))
754                 {
755                     // If the module file name isn't empty
756                     if (wszUnicodeName[0] != 0) {
757                         char* pszName = (char*)malloc(MAX_LONGPATH + 1);
758                         if (pszName == nullptr) {
759                             fprintf(stderr, "Allocating module name FAILED\n");
760                             result = false;
761                             break;
762                         }
763                         sprintf_s(pszName, MAX_LONGPATH, "%S", (WCHAR*)wszUnicodeName);
764                         TRACE(" %s\n", pszName);
765
766                         // Change the module mapping name
767                         ReplaceModuleMapping(moduleData.LoadedPEAddress, pszName);
768                     }
769                 }
770                 else {
771                     TRACE("\nModule.GetFileName FAILED %08x\n", hr);
772                 }
773             }
774             else {
775                 TRACE("\n");
776             }
777         }
778         else {
779             TRACE("moduleData.Request FAILED %08x\n", hr);
780         }
781     }
782
783     if (enumModules != 0) {
784         pClrDataProcess->EndEnumModules(enumModules);
785     }
786
787     return result;
788 }
789
790 //
791 // Unwind all the native threads to ensure that the dwarf unwind info is added to the core dump.
792 //
793 bool
794 CrashInfo::UnwindAllThreads(IXCLRDataProcess* pClrDataProcess)
795 {
796     // For each native and managed thread
797     for (ThreadInfo* thread : m_threads)
798     {
799         if (!thread->UnwindThread(*this, pClrDataProcess)) {
800             return false;
801         }
802     }
803     return true;
804 }
805
806 //
807 // Replace an existing module mapping with one with a different name.
808 //
809 void
810 CrashInfo::ReplaceModuleMapping(CLRDATA_ADDRESS baseAddress, const char* pszName)
811 {
812     // Add or change the module mapping for this PE image. The managed assembly images are
813     // already in the module mappings list but in .NET 2.0 they have the name "/dev/zero".
814     MemoryRegion region(PF_R | PF_W | PF_X, (ULONG_PTR)baseAddress, (ULONG_PTR)(baseAddress + PAGE_SIZE), 0, pszName);
815     const auto& found = m_moduleMappings.find(region);
816     if (found == m_moduleMappings.end())
817     {
818         m_moduleMappings.insert(region);
819
820         if (g_diagnostics) {
821             TRACE("MODULE: ADD ");
822             region.Trace();
823         }
824     }
825     else
826     {
827         // Create the new memory region with the managed assembly name.
828         MemoryRegion newRegion(*found, pszName);
829
830         // Remove and cleanup the old one
831         m_moduleMappings.erase(found);
832         const_cast<MemoryRegion&>(*found).Cleanup();
833
834         // Add the new memory region
835         m_moduleMappings.insert(newRegion);
836
837         if (g_diagnostics) {
838             TRACE("MODULE: REPLACE ");
839             newRegion.Trace();
840         }
841     }
842 }
843
844 //
845 // Returns the module base address for the IP or 0.
846 //
847 uint64_t CrashInfo::GetBaseAddress(uint64_t ip)
848 {
849     MemoryRegion search(0, ip, ip, 0);
850     const MemoryRegion* found = SearchMemoryRegions(m_moduleAddresses, search);
851     if (found == nullptr) {
852         return 0;
853     }
854     // The memory region Offset() is the base address of the module
855     return found->Offset();
856 }
857
858 //
859 // ReadMemory from target and add to memory regions list
860 //
861 bool
862 CrashInfo::ReadMemory(void* address, void* buffer, size_t size)
863 {
864     uint32_t read = 0;
865     if (FAILED(m_dataTarget->ReadVirtual(reinterpret_cast<CLRDATA_ADDRESS>(address), reinterpret_cast<PBYTE>(buffer), size, &read)))
866     {
867         return false;
868     }
869     InsertMemoryRegion(reinterpret_cast<uint64_t>(address), size);
870     return true;
871 }
872
873 //
874 // Add this memory chunk to the list of regions to be
875 // written to the core dump.
876 //
877 void
878 CrashInfo::InsertMemoryRegion(uint64_t address, size_t size)
879 {
880     assert(size < UINT_MAX);
881
882     // Round to page boundary
883     uint64_t start = address & PAGE_MASK;
884     assert(start > 0);
885
886     // Round up to page boundary
887     uint64_t end = ((address + size) + (PAGE_SIZE - 1)) & PAGE_MASK;
888     assert(end > 0);
889
890     InsertMemoryRegion(MemoryRegion(GetMemoryRegionFlags(start) | MEMORY_REGION_FLAG_MEMORY_BACKED, start, end));
891 }
892
893 //
894 // Adds a memory backed flagged copy of the memory region. The file name is not preserved.
895 //
896 void
897 CrashInfo::InsertMemoryBackedRegion(const MemoryRegion& region)
898 {
899     InsertMemoryRegion(MemoryRegion(region, region.Flags() | MEMORY_REGION_FLAG_MEMORY_BACKED));
900 }
901
902 //
903 // Add a memory region to the list
904 //
905 void
906 CrashInfo::InsertMemoryRegion(const MemoryRegion& region)
907 {
908     // First check if the full memory region can be added without conflicts and is fully valid.
909     const auto& found = m_memoryRegions.find(region);
910     if (found == m_memoryRegions.end())
911     {
912         // If the region is valid, add the full memory region
913         if (ValidRegion(region)) {
914             m_memoryRegions.insert(region);
915             return;
916         }
917     }
918     else
919     {
920         // If the memory region is wholly contained in region found and both have the
921         // same backed by memory state, we're done.
922         if (found->Contains(region) && (found->IsBackedByMemory() == region.IsBackedByMemory())) {
923             return;
924         }
925     }
926     // Either part of the region was invalid, part of it hasn't been added or the backed
927     // by memory state is different.
928     uint64_t start = region.StartAddress();
929
930     // The region overlaps/conflicts with one already in the set so add one page at a
931     // time to avoid the overlapping pages.
932     uint64_t numberPages = region.Size() / PAGE_SIZE;
933
934     for (size_t p = 0; p < numberPages; p++, start += PAGE_SIZE)
935     {
936         MemoryRegion memoryRegionPage(region.Flags(), start, start + PAGE_SIZE);
937
938         const auto& found = m_memoryRegions.find(memoryRegionPage);
939         if (found == m_memoryRegions.end())
940         {
941             // All the single pages added here will be combined in CombineMemoryRegions()
942             if (ValidRegion(memoryRegionPage)) {
943                 m_memoryRegions.insert(memoryRegionPage);
944             }
945         }
946         else {
947             assert(found->IsBackedByMemory() || !region.IsBackedByMemory());
948         }
949     }
950 }
951
952 //
953 // Get the memory region flags for a start address
954 //
955 uint32_t
956 CrashInfo::GetMemoryRegionFlags(uint64_t start)
957 {
958     MemoryRegion search(0, start, start + PAGE_SIZE);
959     const MemoryRegion* region = SearchMemoryRegions(m_moduleMappings, search);
960     if (region != nullptr) {
961         return region->Flags();
962     }
963     region = SearchMemoryRegions(m_otherMappings, search);
964     if (region != nullptr) {
965         return region->Flags();
966     }
967     TRACE("GetMemoryRegionFlags: FAILED\n");
968     return PF_R | PF_W | PF_X;
969 }
970
971 //
972 // Validates a memory region
973 //
974 bool
975 CrashInfo::ValidRegion(const MemoryRegion& region)
976 {
977     if (region.IsBackedByMemory())
978     {
979         uint64_t start = region.StartAddress();
980
981         uint64_t numberPages = region.Size() / PAGE_SIZE;
982         for (size_t p = 0; p < numberPages; p++, start += PAGE_SIZE)
983         {
984             BYTE buffer[1];
985             uint32_t read;
986
987             if (FAILED(m_dataTarget->ReadVirtual(start, buffer, 1, &read)))
988             {
989                 return false;
990             }
991         }
992     }
993     return true;
994 }
995
996 //
997 // Combine any adjacent memory regions into one
998 //
999 void
1000 CrashInfo::CombineMemoryRegions()
1001 {
1002     assert(!m_memoryRegions.empty());
1003
1004     std::set<MemoryRegion> memoryRegionsNew;
1005
1006     // MEMORY_REGION_FLAG_SHARED and MEMORY_REGION_FLAG_PRIVATE are internal flags that
1007     // don't affect the core dump so ignore them when comparing the flags.
1008     uint32_t flags = m_memoryRegions.begin()->Flags() & (MEMORY_REGION_FLAG_MEMORY_BACKED | MEMORY_REGION_FLAG_PERMISSIONS_MASK);
1009     uint64_t start = m_memoryRegions.begin()->StartAddress();
1010     uint64_t end = start;
1011
1012     for (const MemoryRegion& region : m_memoryRegions)
1013     {
1014         // To combine a region it needs to be contiguous, same permissions and memory backed flag.
1015         if ((end == region.StartAddress()) &&
1016             (flags == (region.Flags() & (MEMORY_REGION_FLAG_MEMORY_BACKED | MEMORY_REGION_FLAG_PERMISSIONS_MASK))))
1017         {
1018             end = region.EndAddress();
1019         }
1020         else
1021         {
1022             MemoryRegion memoryRegion(flags, start, end);
1023             assert(memoryRegionsNew.find(memoryRegion) == memoryRegionsNew.end());
1024             memoryRegionsNew.insert(memoryRegion);
1025
1026             flags = region.Flags() & (MEMORY_REGION_FLAG_MEMORY_BACKED | MEMORY_REGION_FLAG_PERMISSIONS_MASK);
1027             start = region.StartAddress();
1028             end = region.EndAddress();
1029         }
1030     }
1031
1032     assert(start != end);
1033     MemoryRegion memoryRegion(flags, start, end);
1034     assert(memoryRegionsNew.find(memoryRegion) == memoryRegionsNew.end());
1035     memoryRegionsNew.insert(memoryRegion);
1036
1037     m_memoryRegions = memoryRegionsNew;
1038
1039     if (g_diagnostics)
1040     {
1041         TRACE("Memory Regions:\n");
1042         for (const MemoryRegion& region : m_memoryRegions)
1043         {
1044             region.Trace();
1045         }
1046     }
1047 }
1048
1049 //
1050 // Searches for a memory region given an address.
1051 //
1052 const MemoryRegion*
1053 CrashInfo::SearchMemoryRegions(const std::set<MemoryRegion>& regions, const MemoryRegion& search)
1054 {
1055     std::set<MemoryRegion>::iterator found = regions.find(search);
1056     for (; found != regions.end(); found++)
1057     {
1058         if (search.StartAddress() >= found->StartAddress() && search.StartAddress() < found->EndAddress())
1059         {
1060             return &*found;
1061         }
1062     }
1063         return nullptr;
1064 }
1065
1066 //
1067 // Get the process or thread status
1068 //
1069 bool
1070 CrashInfo::GetStatus(pid_t pid, pid_t* ppid, pid_t* tgid, char** name)
1071 {
1072     char statusPath[128];
1073     snprintf(statusPath, sizeof(statusPath), "/proc/%d/status", pid);
1074
1075     FILE *statusFile = fopen(statusPath, "r");
1076     if (statusFile == nullptr)
1077     {
1078         fprintf(stderr, "GetStatus fopen(%s) FAILED\n", statusPath);
1079         return false;
1080     }
1081
1082     *ppid = -1;
1083
1084     char *line = nullptr;
1085     size_t lineLen = 0;
1086     ssize_t read;
1087     while ((read = getline(&line, &lineLen, statusFile)) != -1)
1088     {
1089         if (strncmp("PPid:\t", line, 6) == 0)
1090         {
1091             *ppid = atoll(line + 6);
1092         }
1093         else if (strncmp("Tgid:\t", line, 6) == 0)
1094         {
1095             *tgid = atoll(line + 6);
1096         }
1097         else if (strncmp("Name:\t", line, 6) == 0)
1098         {
1099             if (name != nullptr)
1100             {
1101                 char* n = strchr(line + 6, '\n');
1102                 if (n != nullptr)
1103                 {
1104                     *n = '\0';
1105                 }
1106                 *name = strdup(line + 6);
1107             }
1108         }
1109     }
1110
1111     free(line);
1112     fclose(statusFile);
1113     return true;
1114 }