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.
5 #include "createdump.h"
7 // This is for the PAL_VirtualUnwindOutOfProc read memory adapter.
8 CrashInfo* g_crashInfo;
10 CrashInfo::CrashInfo(pid_t pid, ICLRDataTarget* dataTarget, bool sos) :
16 m_dataTarget(dataTarget)
23 CrashInfo::~CrashInfo()
25 if (m_name != nullptr)
29 // Clean up the threads
30 for (ThreadInfo* thread : m_threads)
36 // Module and other mappings have a file name to clean up.
37 for (const MemoryRegion& region : m_moduleMappings)
39 const_cast<MemoryRegion&>(region).Cleanup();
41 m_moduleMappings.clear();
42 for (const MemoryRegion& region : m_otherMappings)
44 const_cast<MemoryRegion&>(region).Cleanup();
46 m_otherMappings.clear();
47 m_dataTarget->Release();
51 CrashInfo::QueryInterface(
52 ___in REFIID InterfaceId,
53 ___out PVOID* Interface)
55 if (InterfaceId == IID_IUnknown ||
56 InterfaceId == IID_ICLRDataEnumMemoryRegionsCallback)
58 *Interface = (ICLRDataEnumMemoryRegionsCallback*)this;
72 LONG ref = InterlockedIncrement(&m_ref);
79 LONG ref = InterlockedDecrement(&m_ref);
87 HRESULT STDMETHODCALLTYPE
88 CrashInfo::EnumMemoryRegion(
89 /* [in] */ CLRDATA_ADDRESS address,
90 /* [in] */ ULONG32 size)
92 InsertMemoryRegion((ULONG_PTR)address, size);
97 // Suspends all the threads and creating a list of them. Should be the first before
98 // gather any info about the process.
101 CrashInfo::EnumerateAndSuspendThreads()
104 snprintf(taskPath, sizeof(taskPath), "/proc/%d/task", m_pid);
106 DIR* taskDir = opendir(taskPath);
107 if (taskDir == nullptr)
109 fprintf(stderr, "opendir(%s) FAILED %s\n", taskPath, strerror(errno));
113 struct dirent* entry;
114 while ((entry = readdir(taskDir)) != nullptr)
116 pid_t tid = static_cast<pid_t>(strtol(entry->d_name, nullptr, 10));
119 // Don't suspend the threads if running under sos
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)
126 waitpid(tid, &waitStatus, __WALL);
130 fprintf(stderr, "ptrace(ATTACH, %d) FAILED %s\n", tid, strerror(errno));
135 // Add to the list of threads
136 ThreadInfo* thread = new ThreadInfo(tid);
137 m_threads.push_back(thread);
146 // Gather all the necessary crash dump info.
149 CrashInfo::GatherCrashInfo(MINIDUMP_TYPE minidumpType)
151 // Get the process info
152 if (!GetStatus(m_pid, &m_ppid, &m_tgid, &m_name))
156 // Get the info about the threads (registers, etc.)
157 for (ThreadInfo* thread : m_threads)
159 if (!thread->Initialize(m_sos ? m_dataTarget : nullptr))
165 if (!GetAuxvEntries())
169 // Gather all the module memory mappings (from /dev/$pid/maps)
170 if (!EnumerateModuleMappings())
174 // Get shared module debug info
180 for (const MemoryRegion& region : m_moduleAddresses)
185 // If full memory dump, include everything regardless of permissions
186 if (minidumpType & MiniDumpWithFullMemory)
188 for (const MemoryRegion& region : m_moduleMappings)
190 InsertMemoryBackedRegion(region);
192 for (const MemoryRegion& region : m_otherMappings)
194 // Don't add uncommitted pages to the full dump
195 if ((region.Permissions() & (PF_R | PF_W | PF_X)) != 0)
197 InsertMemoryBackedRegion(region);
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)
205 for (const MemoryRegion& region : m_otherMappings)
207 uint32_t permissions = region.Permissions();
208 if (permissions == (PF_R | PF_W) || permissions == (PF_R | PF_W | PF_X))
210 InsertMemoryBackedRegion(region);
214 // Gather all the useful memory regions from the DAC
215 if (!EnumerateMemoryRegionsWithDAC(minidumpType))
219 if ((minidumpType & MiniDumpWithFullMemory) == 0)
221 // Add the thread's stack and some code memory to core
222 for (ThreadInfo* thread : m_threads)
224 // Add the thread's stack
225 thread->GetThreadStack(*this);
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)
232 assert(!region.IsBackedByMemory());
233 InsertMemoryRegion(region);
235 for (const MemoryRegion& region : m_otherMappings)
237 assert(!region.IsBackedByMemory());
238 InsertMemoryRegion(region);
241 // Join all adjacent memory regions
242 CombineMemoryRegions();
247 CrashInfo::ResumeThreads()
251 for (ThreadInfo* thread : m_threads)
253 thread->ResumeThread();
259 // Get the auxv entries to use and add to the core dump
262 CrashInfo::GetAuxvEntries()
265 snprintf(auxvPath, sizeof(auxvPath), "/proc/%d/auxv", m_pid);
267 int fd = open(auxvPath, O_RDONLY, 0);
270 fprintf(stderr, "open(%s) FAILED %s\n", auxvPath, strerror(errno));
274 elf_aux_entry auxvEntry;
276 while (read(fd, &auxvEntry, sizeof(elf_aux_entry)) == sizeof(elf_aux_entry))
278 m_auxvEntries.push_back(auxvEntry);
279 if (auxvEntry.a_type == AT_NULL)
283 if (auxvEntry.a_type < AT_MAX)
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);
296 // Get the module mappings for the core dump NT_FILE notes
299 CrashInfo::EnumerateModuleMappings()
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:
304 // [address] [perms] [offset] [dev] [inode] [pathname] - HEADER is not preset in an actual file
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;
319 // Making something like: /proc/123/maps
321 int chars = snprintf(mapPath, sizeof(mapPath), "/proc/%d/maps", m_pid);
322 assert(chars > 0 && (size_t)chars <= sizeof(mapPath));
324 FILE* mapsFile = fopen(mapPath, "r");
325 if (mapsFile == nullptr)
327 fprintf(stderr, "fopen(%s) FAILED %s\n", mapPath, strerror(errno));
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
337 const void* linuxGateAddress = (const void*)m_auxvValues[AT_SYSINFO_EHDR];
339 // Reading maps file line by line
340 while ((read = getline(&line, &lineLen, mapsFile)) != -1)
342 uint64_t start, end, offset;
343 char* permissions = nullptr;
344 char* moduleName = nullptr;
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)
353 // p = private (copy on write)
354 uint32_t regionFlags = 0;
355 if (strchr(permissions, 'r')) {
358 if (strchr(permissions, 'w')) {
361 if (strchr(permissions, 'x')) {
364 if (strchr(permissions, 's')) {
365 regionFlags |= MEMORY_REGION_FLAG_SHARED;
367 if (strchr(permissions, 'p')) {
368 regionFlags |= MEMORY_REGION_FLAG_PRIVATE;
370 MemoryRegion memoryRegion(regionFlags, start, end, offset, moduleName);
372 if (moduleName != nullptr && *moduleName == '/')
374 if (m_coreclrPath.empty())
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);
383 m_moduleMappings.insert(memoryRegion);
387 m_otherMappings.insert(memoryRegion);
389 if (linuxGateAddress != nullptr && reinterpret_cast<void*>(start) == linuxGateAddress)
391 InsertMemoryBackedRegion(memoryRegion);
399 TRACE("Module mappings:\n");
400 for (const MemoryRegion& region : m_moduleMappings)
404 TRACE("Other mappings:\n");
405 for (const MemoryRegion& region : m_otherMappings)
411 free(line); // We didn't allocate line, but as per contract of getline we should free it
418 // All the shared (native) module info to the core dump
421 CrashInfo::GetDSOInfo()
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);
428 if (phnum <= 0 || phdrAddr == nullptr) {
431 uint64_t baseAddress = (uint64_t)phdrAddr - sizeof(Ehdr);
432 ElfW(Dyn)* dynamicAddr = nullptr;
434 TRACE("DSO: base %" PRIA PRIx64 " phdr %p phnum %d\n", baseAddress, phdrAddr, phnum);
436 // Enumerate program headers searching for the PT_DYNAMIC header, etc.
437 if (!EnumerateProgramHeaders(phdrAddr, phnum, baseAddress, &dynamicAddr))
441 if (dynamicAddr == nullptr) {
445 // Search for dynamic debug (DT_DEBUG) entry
446 struct r_debug* rdebugAddr = nullptr;
449 if (!ReadMemory(dynamicAddr, &dyn, sizeof(dyn))) {
450 fprintf(stderr, "ReadMemory(%p, %" PRIx ") dyn FAILED\n", dynamicAddr, sizeof(dyn));
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);
457 else if (dyn.d_tag == DT_NULL) {
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));
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;) {
475 if (!ReadMemory(linkMapAddr, &map, sizeof(map))) {
476 fprintf(stderr, "ReadMemory(%p, %" PRIx ") link_map FAILED\n", linkMapAddr, sizeof(map));
479 // Read the module's name and make sure the memory is added to the core dump
481 if (map.l_name != nullptr) {
482 for (; i < PATH_MAX; i++)
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);
488 if (moduleName[i] == '\0') {
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);
496 // Read the ELF header and info adding it to the core dump
497 if (!GetELFInfo(map.l_addr)) {
500 linkMapAddr = map.l_next;
507 // Add all the necessary ELF headers to the core dump
510 CrashInfo::GetELFInfo(uint64_t baseAddress)
512 if (baseAddress == 0 || baseAddress == m_auxvValues[AT_SYSINFO_EHDR] || baseAddress == m_auxvValues[AT_BASE]) {
516 if (!ReadMemory((void*)baseAddress, &ehdr, sizeof(ehdr))) {
517 TRACE("ReadMemory(%p, %" PRIx ") ehdr FAILED\n", (void*)baseAddress, sizeof(ehdr));
520 int phnum = ehdr.e_phnum;
521 assert(phnum != PN_XNUM);
522 assert(ehdr.e_phentsize == sizeof(Phdr));
524 assert(ehdr.e_ident[EI_CLASS] == ELFCLASS64);
526 assert(ehdr.e_ident[EI_CLASS] == ELFCLASS32);
528 assert(ehdr.e_ident[EI_DATA] == ELFDATA2LSB);
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);
533 if (ehdr.e_phoff != 0 && phnum > 0)
535 Phdr* phdrAddr = reinterpret_cast<Phdr*>(baseAddress + ehdr.e_phoff);
537 if (!EnumerateProgramHeaders(phdrAddr, phnum, baseAddress, nullptr))
547 // Enumerate the program headers adding the build id note, unwind frame
548 // region and module addresses to the crash info.
551 CrashInfo::EnumerateProgramHeaders(Phdr* phdrAddr, int phnum, uint64_t baseAddress, ElfW(Dyn)** pdynamicAddr)
553 uint64_t loadbias = baseAddress;
555 for (int i = 0; i < phnum; i++)
558 if (!ReadMemory(phdrAddr + i, &ph, sizeof(ph))) {
559 fprintf(stderr, "ReadMemory(%p, %" PRIx ") phdr FAILED\n", phdrAddr + i, sizeof(ph));
562 if (ph.p_type == PT_LOAD && ph.p_offset == 0)
564 loadbias -= ph.p_vaddr;
565 TRACE("PHDR: loadbias %" PRIA PRIx64 "\n", loadbias);
570 for (int i = 0; i < phnum; i++)
573 if (!ReadMemory(phdrAddr + i, &ph, sizeof(ph))) {
574 fprintf(stderr, "ReadMemory(%p, %" PRIx ") phdr FAILED\n", phdrAddr + i, sizeof(ph));
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);
583 if (pdynamicAddr != nullptr)
585 *pdynamicAddr = reinterpret_cast<ElfW(Dyn)*>(loadbias + ph.p_vaddr);
588 // fall into InsertMemoryRegion
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);
598 MemoryRegion region(0, loadbias + ph.p_vaddr, loadbias + ph.p_vaddr + ph.p_memsz, baseAddress);
599 m_moduleAddresses.insert(region);
608 // Enumerate all the memory regions using the DAC memory region support given a minidump type
611 CrashInfo::EnumerateMemoryRegionsWithDAC(MINIDUMP_TYPE minidumpType)
613 PFN_CLRDataCreateInstance pfnCLRDataCreateInstance = nullptr;
614 ICLRDataEnumMemoryRegions* pClrDataEnumRegions = nullptr;
615 IXCLRDataProcess* pClrDataProcess = nullptr;
616 HMODULE hdac = nullptr;
620 if (!m_coreclrPath.empty())
622 // We assume that the DAC is in the same location as the libcoreclr.so module
624 dacPath.append(m_coreclrPath);
625 dacPath.append(MAKEDLLNAME_A("mscordaccore"));
627 // Load and initialize the DAC
628 hdac = LoadLibraryA(dacPath.c_str());
631 fprintf(stderr, "LoadLibraryA(%s) FAILED %d\n", dacPath.c_str(), GetLastError());
634 pfnCLRDataCreateInstance = (PFN_CLRDataCreateInstance)GetProcAddress(hdac, "CLRDataCreateInstance");
635 if (pfnCLRDataCreateInstance == nullptr)
637 fprintf(stderr, "GetProcAddress(CLRDataCreateInstance) FAILED %d\n", GetLastError());
640 if ((minidumpType & MiniDumpWithFullMemory) == 0)
642 hr = pfnCLRDataCreateInstance(__uuidof(ICLRDataEnumMemoryRegions), m_dataTarget, (void**)&pClrDataEnumRegions);
645 fprintf(stderr, "CLRDataCreateInstance(ICLRDataEnumMemoryRegions) FAILED %08x\n", hr);
648 // Calls CrashInfo::EnumMemoryRegion for each memory region found by the DAC
649 hr = pClrDataEnumRegions->EnumMemoryRegions(this, minidumpType, CLRDATA_ENUM_MEM_DEFAULT);
652 fprintf(stderr, "EnumMemoryRegions FAILED %08x\n", hr);
656 hr = pfnCLRDataCreateInstance(__uuidof(IXCLRDataProcess), m_dataTarget, (void**)&pClrDataProcess);
659 fprintf(stderr, "CLRDataCreateInstance(IXCLRDataProcess) FAILED %08x\n", hr);
662 if (!EnumerateManagedModules(pClrDataProcess))
668 TRACE("EnumerateMemoryRegionsWithDAC: coreclr not found; not using DAC\n");
670 if (!UnwindAllThreads(pClrDataProcess))
676 if (pClrDataEnumRegions != nullptr)
678 pClrDataEnumRegions->Release();
680 if (pClrDataProcess != nullptr)
682 pClrDataProcess->Release();
692 // Enumerate all the managed modules and replace the module mapping with the module name found.
695 CrashInfo::EnumerateManagedModules(IXCLRDataProcess* pClrDataProcess)
697 CLRDATA_ENUM enumModules = 0;
701 if (FAILED(hr = pClrDataProcess->StartEnumModules(&enumModules))) {
702 fprintf(stderr, "StartEnumModules FAILED %08x\n", hr);
708 ReleaseHolder<IXCLRDataModule> pClrDataModule;
709 if ((hr = pClrDataProcess->EnumModule(&enumModules, &pClrDataModule)) != S_OK) {
713 // Skip any dynamic modules. The Request call below on some DACs crashes on dynamic modules.
715 if ((hr = pClrDataModule->GetFlags(&flags)) != S_OK) {
716 TRACE("MODULE: GetFlags FAILED %08x\n", hr);
719 if (flags & CLRDATA_MODULE_IS_DYNAMIC) {
720 TRACE("MODULE: Skipping dynamic module\n");
724 DacpGetModuleData moduleData;
725 if (SUCCEEDED(hr = moduleData.Request(pClrDataModule.GetPtr())))
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);
730 if (!moduleData.IsDynamic && moduleData.LoadedPEAddress != 0)
732 ArrayHolder<WCHAR> wszUnicodeName = new WCHAR[MAX_LONGPATH + 1];
733 if (SUCCEEDED(hr = pClrDataModule->GetFileName(MAX_LONGPATH, nullptr, wszUnicodeName)))
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");
743 sprintf_s(pszName, MAX_LONGPATH, "%S", (WCHAR*)wszUnicodeName);
744 TRACE(" %s\n", pszName);
746 // Change the module mapping name
747 ReplaceModuleMapping(moduleData.LoadedPEAddress, pszName);
751 TRACE("\nModule.GetFileName FAILED %08x\n", hr);
759 TRACE("moduleData.Request FAILED %08x\n", hr);
763 if (enumModules != 0) {
764 pClrDataProcess->EndEnumModules(enumModules);
771 // Unwind all the native threads to ensure that the dwarf unwind info is added to the core dump.
774 CrashInfo::UnwindAllThreads(IXCLRDataProcess* pClrDataProcess)
776 // For each native and managed thread
777 for (ThreadInfo* thread : m_threads)
779 if (!thread->UnwindThread(*this, pClrDataProcess)) {
787 // Replace an existing module mapping with one with a different name.
790 CrashInfo::ReplaceModuleMapping(CLRDATA_ADDRESS baseAddress, const char* pszName)
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())
798 m_moduleMappings.insert(region);
801 TRACE("MODULE: ADD ");
807 // Create the new memory region with the managed assembly name.
808 MemoryRegion newRegion(*found, pszName);
810 // Remove and cleanup the old one
811 m_moduleMappings.erase(found);
812 const_cast<MemoryRegion&>(*found).Cleanup();
814 // Add the new memory region
815 m_moduleMappings.insert(newRegion);
818 TRACE("MODULE: REPLACE ");
825 // Returns the module base address for the IP or 0.
827 uint64_t CrashInfo::GetBaseAddress(uint64_t ip)
829 MemoryRegion search(0, ip, ip, 0);
830 const MemoryRegion* found = SearchMemoryRegions(m_moduleAddresses, search);
831 if (found == nullptr) {
834 // The memory region Offset() is the base address of the module
835 return found->Offset();
839 // ReadMemory from target and add to memory regions list
842 CrashInfo::ReadMemory(void* address, void* buffer, size_t size)
845 if (FAILED(m_dataTarget->ReadVirtual(reinterpret_cast<CLRDATA_ADDRESS>(address), reinterpret_cast<PBYTE>(buffer), size, &read)))
849 InsertMemoryRegion(reinterpret_cast<uint64_t>(address), size);
854 // Add this memory chunk to the list of regions to be
855 // written to the core dump.
858 CrashInfo::InsertMemoryRegion(uint64_t address, size_t size)
860 assert(size < UINT_MAX);
862 // Round to page boundary
863 uint64_t start = address & PAGE_MASK;
866 // Round up to page boundary
867 uint64_t end = ((address + size) + (PAGE_SIZE - 1)) & PAGE_MASK;
870 InsertMemoryRegion(MemoryRegion(GetMemoryRegionFlags(start) | MEMORY_REGION_FLAG_MEMORY_BACKED, start, end));
874 // Adds a memory backed flagged copy of the memory region. The file name is not preserved.
877 CrashInfo::InsertMemoryBackedRegion(const MemoryRegion& region)
879 InsertMemoryRegion(MemoryRegion(region, region.Flags() | MEMORY_REGION_FLAG_MEMORY_BACKED));
883 // Add a memory region to the list
886 CrashInfo::InsertMemoryRegion(const MemoryRegion& region)
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())
892 // If the region is valid, add the full memory region
893 if (ValidRegion(region)) {
894 m_memoryRegions.insert(region);
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())) {
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();
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;
914 for (size_t p = 0; p < numberPages; p++, start += PAGE_SIZE)
916 MemoryRegion memoryRegionPage(region.Flags(), start, start + PAGE_SIZE);
918 const auto& found = m_memoryRegions.find(memoryRegionPage);
919 if (found == m_memoryRegions.end())
921 // All the single pages added here will be combined in CombineMemoryRegions()
922 if (ValidRegion(memoryRegionPage)) {
923 m_memoryRegions.insert(memoryRegionPage);
927 assert(found->IsBackedByMemory() || !region.IsBackedByMemory());
933 // Get the memory region flags for a start address
936 CrashInfo::GetMemoryRegionFlags(uint64_t start)
938 MemoryRegion search(0, start, start + PAGE_SIZE);
939 const MemoryRegion* region = SearchMemoryRegions(m_moduleMappings, search);
940 if (region != nullptr) {
941 return region->Flags();
943 region = SearchMemoryRegions(m_otherMappings, search);
944 if (region != nullptr) {
945 return region->Flags();
947 TRACE("GetMemoryRegionFlags: FAILED\n");
948 return PF_R | PF_W | PF_X;
952 // Validates a memory region
955 CrashInfo::ValidRegion(const MemoryRegion& region)
957 if (region.IsBackedByMemory())
959 uint64_t start = region.StartAddress();
961 uint64_t numberPages = region.Size() / PAGE_SIZE;
962 for (size_t p = 0; p < numberPages; p++, start += PAGE_SIZE)
967 if (FAILED(m_dataTarget->ReadVirtual(start, buffer, 1, &read)))
977 // Combine any adjacent memory regions into one
980 CrashInfo::CombineMemoryRegions()
982 assert(!m_memoryRegions.empty());
984 std::set<MemoryRegion> memoryRegionsNew;
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;
992 for (const MemoryRegion& region : m_memoryRegions)
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))))
998 end = region.EndAddress();
1002 MemoryRegion memoryRegion(flags, start, end);
1003 assert(memoryRegionsNew.find(memoryRegion) == memoryRegionsNew.end());
1004 memoryRegionsNew.insert(memoryRegion);
1006 flags = region.Flags() & (MEMORY_REGION_FLAG_MEMORY_BACKED | MEMORY_REGION_FLAG_PERMISSIONS_MASK);
1007 start = region.StartAddress();
1008 end = region.EndAddress();
1012 assert(start != end);
1013 MemoryRegion memoryRegion(flags, start, end);
1014 assert(memoryRegionsNew.find(memoryRegion) == memoryRegionsNew.end());
1015 memoryRegionsNew.insert(memoryRegion);
1017 m_memoryRegions = memoryRegionsNew;
1021 TRACE("Memory Regions:\n");
1022 for (const MemoryRegion& region : m_memoryRegions)
1030 // Searches for a memory region given an address.
1033 CrashInfo::SearchMemoryRegions(const std::set<MemoryRegion>& regions, const MemoryRegion& search)
1035 std::set<MemoryRegion>::iterator found = regions.find(search);
1036 for (; found != regions.end(); found++)
1038 if (search.StartAddress() >= found->StartAddress() && search.StartAddress() < found->EndAddress())
1047 // Get the process or thread status
1050 CrashInfo::GetStatus(pid_t pid, pid_t* ppid, pid_t* tgid, char** name)
1052 char statusPath[128];
1053 snprintf(statusPath, sizeof(statusPath), "/proc/%d/status", pid);
1055 FILE *statusFile = fopen(statusPath, "r");
1056 if (statusFile == nullptr)
1058 fprintf(stderr, "GetStatus fopen(%s) FAILED\n", statusPath);
1064 char *line = nullptr;
1067 while ((read = getline(&line, &lineLen, statusFile)) != -1)
1069 if (strncmp("PPid:\t", line, 6) == 0)
1071 *ppid = atoll(line + 6);
1073 else if (strncmp("Tgid:\t", line, 6) == 0)
1075 *tgid = atoll(line + 6);
1077 else if (strncmp("Name:\t", line, 6) == 0)
1079 if (name != nullptr)
1081 char* n = strchr(line + 6, '\n');
1086 *name = strdup(line + 6);