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