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(bool suspend)
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
120 if (!m_sos && suspend)
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 // Set registers for all threads
149 CrashInfo::SetThreadsRegisters(const std::vector<elf_prstatus*> &statuses)
151 for (ThreadInfo* thread : m_threads) {
152 for (elf_prstatus* status : statuses) {
153 if (thread->Tid() == status->pr_pid) {
154 thread->SetRegisters(status);
164 // Gather all the necessary crash dump info.
167 CrashInfo::GatherCrashInfo(MINIDUMP_TYPE minidumpType, bool initialize_threads)
169 // Get the process info
170 if (!GetStatus(m_pid, &m_ppid, &m_tgid, &m_name))
174 if (initialize_threads) {
175 // Get the info about the threads (registers, etc.)
176 for (ThreadInfo* thread : m_threads)
178 if (!thread->Initialize(m_sos ? m_dataTarget : nullptr))
185 if (!GetAuxvEntries())
189 // Gather all the module memory mappings (from /dev/$pid/maps)
190 if (!EnumerateModuleMappings())
194 // Get shared module debug info
200 for (const MemoryRegion& region : m_moduleAddresses)
205 // If full memory dump, include everything regardless of permissions
206 if (minidumpType & MiniDumpWithFullMemory)
208 for (const MemoryRegion& region : m_moduleMappings)
210 InsertMemoryBackedRegion(region);
212 for (const MemoryRegion& region : m_otherMappings)
214 // Don't add uncommitted pages to the full dump
215 if ((region.Permissions() & (PF_R | PF_W | PF_X)) != 0)
217 InsertMemoryBackedRegion(region);
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)
225 for (const MemoryRegion& region : m_otherMappings)
227 uint32_t permissions = region.Permissions();
228 if (permissions == (PF_R | PF_W) || permissions == (PF_R | PF_W | PF_X))
230 InsertMemoryBackedRegion(region);
234 // Gather all the useful memory regions from the DAC
235 if (!EnumerateMemoryRegionsWithDAC(minidumpType))
239 if ((minidumpType & MiniDumpWithFullMemory) == 0)
241 // Add the thread's stack and some code memory to core
242 for (ThreadInfo* thread : m_threads)
244 // Add the thread's stack
245 thread->GetThreadStack(*this);
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)
252 assert(!region.IsBackedByMemory());
253 InsertMemoryRegion(region);
255 for (const MemoryRegion& region : m_otherMappings)
257 assert(!region.IsBackedByMemory());
258 InsertMemoryRegion(region);
261 // Join all adjacent memory regions
262 CombineMemoryRegions();
267 CrashInfo::ResumeThreads()
271 for (ThreadInfo* thread : m_threads)
273 thread->ResumeThread();
279 // Get the auxv entries to use and add to the core dump
282 CrashInfo::GetAuxvEntries()
285 snprintf(auxvPath, sizeof(auxvPath), "/proc/%d/auxv", m_pid);
287 int fd = open(auxvPath, O_RDONLY, 0);
290 fprintf(stderr, "open(%s) FAILED %s\n", auxvPath, strerror(errno));
294 elf_aux_entry auxvEntry;
296 while (read(fd, &auxvEntry, sizeof(elf_aux_entry)) == sizeof(elf_aux_entry))
298 m_auxvEntries.push_back(auxvEntry);
299 if (auxvEntry.a_type == AT_NULL)
303 if (auxvEntry.a_type < AT_MAX)
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);
316 // Get the module mappings for the core dump NT_FILE notes
319 CrashInfo::EnumerateModuleMappings()
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:
324 // [address] [perms] [offset] [dev] [inode] [pathname] - HEADER is not preset in an actual file
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;
339 // Making something like: /proc/123/maps
341 int chars = snprintf(mapPath, sizeof(mapPath), "/proc/%d/maps", m_pid);
342 assert(chars > 0 && (size_t)chars <= sizeof(mapPath));
344 FILE* mapsFile = fopen(mapPath, "r");
345 if (mapsFile == nullptr)
347 fprintf(stderr, "fopen(%s) FAILED %s\n", mapPath, strerror(errno));
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
357 const void* linuxGateAddress = (const void*)m_auxvValues[AT_SYSINFO_EHDR];
359 // Reading maps file line by line
360 while ((read = getline(&line, &lineLen, mapsFile)) != -1)
362 uint64_t start, end, offset;
363 char* permissions = nullptr;
364 char* moduleName = nullptr;
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)
373 // p = private (copy on write)
374 uint32_t regionFlags = 0;
375 if (strchr(permissions, 'r')) {
378 if (strchr(permissions, 'w')) {
381 if (strchr(permissions, 'x')) {
384 if (strchr(permissions, 's')) {
385 regionFlags |= MEMORY_REGION_FLAG_SHARED;
387 if (strchr(permissions, 'p')) {
388 regionFlags |= MEMORY_REGION_FLAG_PRIVATE;
390 MemoryRegion memoryRegion(regionFlags, start, end, offset, moduleName);
392 if (moduleName != nullptr && *moduleName == '/')
394 if (m_coreclrPath.empty())
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);
403 m_moduleMappings.insert(memoryRegion);
407 m_otherMappings.insert(memoryRegion);
409 if (linuxGateAddress != nullptr && reinterpret_cast<void*>(start) == linuxGateAddress)
411 InsertMemoryBackedRegion(memoryRegion);
419 TRACE("Module mappings:\n");
420 for (const MemoryRegion& region : m_moduleMappings)
424 TRACE("Other mappings:\n");
425 for (const MemoryRegion& region : m_otherMappings)
431 free(line); // We didn't allocate line, but as per contract of getline we should free it
438 // All the shared (native) module info to the core dump
441 CrashInfo::GetDSOInfo()
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);
448 if (phnum <= 0 || phdrAddr == nullptr) {
451 uint64_t baseAddress = (uint64_t)phdrAddr - sizeof(Ehdr);
452 ElfW(Dyn)* dynamicAddr = nullptr;
454 TRACE("DSO: base %" PRIA PRIx64 " phdr %p phnum %d\n", baseAddress, phdrAddr, phnum);
456 // Enumerate program headers searching for the PT_DYNAMIC header, etc.
457 if (!EnumerateProgramHeaders(phdrAddr, phnum, baseAddress, &dynamicAddr))
461 if (dynamicAddr == nullptr) {
465 // Search for dynamic debug (DT_DEBUG) entry
466 struct r_debug* rdebugAddr = nullptr;
469 if (!ReadMemory(dynamicAddr, &dyn, sizeof(dyn))) {
470 fprintf(stderr, "ReadMemory(%p, %" PRIx ") dyn FAILED\n", dynamicAddr, sizeof(dyn));
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);
477 else if (dyn.d_tag == DT_NULL) {
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));
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;) {
495 if (!ReadMemory(linkMapAddr, &map, sizeof(map))) {
496 fprintf(stderr, "ReadMemory(%p, %" PRIx ") link_map FAILED\n", linkMapAddr, sizeof(map));
499 // Read the module's name and make sure the memory is added to the core dump
501 if (map.l_name != nullptr) {
502 for (; i < PATH_MAX; i++)
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);
508 if (moduleName[i] == '\0') {
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);
516 // Read the ELF header and info adding it to the core dump
517 if (!GetELFInfo(map.l_addr)) {
520 linkMapAddr = map.l_next;
527 // Add all the necessary ELF headers to the core dump
530 CrashInfo::GetELFInfo(uint64_t baseAddress)
532 if (baseAddress == 0 || baseAddress == m_auxvValues[AT_SYSINFO_EHDR] || baseAddress == m_auxvValues[AT_BASE]) {
536 if (!ReadMemory((void*)baseAddress, &ehdr, sizeof(ehdr))) {
537 TRACE("ReadMemory(%p, %" PRIx ") ehdr FAILED\n", (void*)baseAddress, sizeof(ehdr));
540 int phnum = ehdr.e_phnum;
541 assert(phnum != PN_XNUM);
542 assert(ehdr.e_phentsize == sizeof(Phdr));
544 assert(ehdr.e_ident[EI_CLASS] == ELFCLASS64);
546 assert(ehdr.e_ident[EI_CLASS] == ELFCLASS32);
548 assert(ehdr.e_ident[EI_DATA] == ELFDATA2LSB);
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);
553 if (ehdr.e_phoff != 0 && phnum > 0)
555 Phdr* phdrAddr = reinterpret_cast<Phdr*>(baseAddress + ehdr.e_phoff);
557 if (!EnumerateProgramHeaders(phdrAddr, phnum, baseAddress, nullptr))
567 // Enumerate the program headers adding the build id note, unwind frame
568 // region and module addresses to the crash info.
571 CrashInfo::EnumerateProgramHeaders(Phdr* phdrAddr, int phnum, uint64_t baseAddress, ElfW(Dyn)** pdynamicAddr)
573 uint64_t loadbias = baseAddress;
575 for (int i = 0; i < phnum; i++)
578 if (!ReadMemory(phdrAddr + i, &ph, sizeof(ph))) {
579 fprintf(stderr, "ReadMemory(%p, %" PRIx ") phdr FAILED\n", phdrAddr + i, sizeof(ph));
582 if (ph.p_type == PT_LOAD && ph.p_offset == 0)
584 loadbias -= ph.p_vaddr;
585 TRACE("PHDR: loadbias %" PRIA PRIx64 "\n", loadbias);
590 for (int i = 0; i < phnum; i++)
593 if (!ReadMemory(phdrAddr + i, &ph, sizeof(ph))) {
594 fprintf(stderr, "ReadMemory(%p, %" PRIx ") phdr FAILED\n", phdrAddr + i, sizeof(ph));
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);
603 if (pdynamicAddr != nullptr)
605 *pdynamicAddr = reinterpret_cast<ElfW(Dyn)*>(loadbias + ph.p_vaddr);
608 // fall into InsertMemoryRegion
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);
618 MemoryRegion region(0, loadbias + ph.p_vaddr, loadbias + ph.p_vaddr + ph.p_memsz, baseAddress);
619 m_moduleAddresses.insert(region);
628 // Enumerate all the memory regions using the DAC memory region support given a minidump type
631 CrashInfo::EnumerateMemoryRegionsWithDAC(MINIDUMP_TYPE minidumpType)
633 PFN_CLRDataCreateInstance pfnCLRDataCreateInstance = nullptr;
634 ICLRDataEnumMemoryRegions* pClrDataEnumRegions = nullptr;
635 IXCLRDataProcess* pClrDataProcess = nullptr;
636 HMODULE hdac = nullptr;
640 if (!m_coreclrPath.empty())
642 // We assume that the DAC is in the same location as the libcoreclr.so module
644 dacPath.append(m_coreclrPath);
645 dacPath.append(MAKEDLLNAME_A("mscordaccore"));
647 // Load and initialize the DAC
648 hdac = LoadLibraryA(dacPath.c_str());
651 fprintf(stderr, "LoadLibraryA(%s) FAILED %d\n", dacPath.c_str(), GetLastError());
654 pfnCLRDataCreateInstance = (PFN_CLRDataCreateInstance)GetProcAddress(hdac, "CLRDataCreateInstance");
655 if (pfnCLRDataCreateInstance == nullptr)
657 fprintf(stderr, "GetProcAddress(CLRDataCreateInstance) FAILED %d\n", GetLastError());
660 if ((minidumpType & MiniDumpWithFullMemory) == 0)
662 hr = pfnCLRDataCreateInstance(__uuidof(ICLRDataEnumMemoryRegions), m_dataTarget, (void**)&pClrDataEnumRegions);
665 fprintf(stderr, "CLRDataCreateInstance(ICLRDataEnumMemoryRegions) FAILED %08x\n", hr);
668 // Calls CrashInfo::EnumMemoryRegion for each memory region found by the DAC
669 hr = pClrDataEnumRegions->EnumMemoryRegions(this, minidumpType, CLRDATA_ENUM_MEM_DEFAULT);
672 fprintf(stderr, "EnumMemoryRegions FAILED %08x\n", hr);
676 hr = pfnCLRDataCreateInstance(__uuidof(IXCLRDataProcess), m_dataTarget, (void**)&pClrDataProcess);
679 fprintf(stderr, "CLRDataCreateInstance(IXCLRDataProcess) FAILED %08x\n", hr);
682 if (!EnumerateManagedModules(pClrDataProcess))
688 TRACE("EnumerateMemoryRegionsWithDAC: coreclr not found; not using DAC\n");
690 if (!UnwindAllThreads(pClrDataProcess))
696 if (pClrDataEnumRegions != nullptr)
698 pClrDataEnumRegions->Release();
700 if (pClrDataProcess != nullptr)
702 pClrDataProcess->Release();
712 // Enumerate all the managed modules and replace the module mapping with the module name found.
715 CrashInfo::EnumerateManagedModules(IXCLRDataProcess* pClrDataProcess)
717 CLRDATA_ENUM enumModules = 0;
721 if (FAILED(hr = pClrDataProcess->StartEnumModules(&enumModules))) {
722 fprintf(stderr, "StartEnumModules FAILED %08x\n", hr);
728 ReleaseHolder<IXCLRDataModule> pClrDataModule;
729 if ((hr = pClrDataProcess->EnumModule(&enumModules, &pClrDataModule)) != S_OK) {
733 // Skip any dynamic modules. The Request call below on some DACs crashes on dynamic modules.
735 if ((hr = pClrDataModule->GetFlags(&flags)) != S_OK) {
736 TRACE("MODULE: GetFlags FAILED %08x\n", hr);
739 if (flags & CLRDATA_MODULE_IS_DYNAMIC) {
740 TRACE("MODULE: Skipping dynamic module\n");
744 DacpGetModuleData moduleData;
745 if (SUCCEEDED(hr = moduleData.Request(pClrDataModule.GetPtr())))
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);
750 if (!moduleData.IsDynamic && moduleData.LoadedPEAddress != 0)
752 ArrayHolder<WCHAR> wszUnicodeName = new WCHAR[MAX_LONGPATH + 1];
753 if (SUCCEEDED(hr = pClrDataModule->GetFileName(MAX_LONGPATH, nullptr, wszUnicodeName)))
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");
763 sprintf_s(pszName, MAX_LONGPATH, "%S", (WCHAR*)wszUnicodeName);
764 TRACE(" %s\n", pszName);
766 // Change the module mapping name
767 ReplaceModuleMapping(moduleData.LoadedPEAddress, pszName);
771 TRACE("\nModule.GetFileName FAILED %08x\n", hr);
779 TRACE("moduleData.Request FAILED %08x\n", hr);
783 if (enumModules != 0) {
784 pClrDataProcess->EndEnumModules(enumModules);
791 // Unwind all the native threads to ensure that the dwarf unwind info is added to the core dump.
794 CrashInfo::UnwindAllThreads(IXCLRDataProcess* pClrDataProcess)
796 // For each native and managed thread
797 for (ThreadInfo* thread : m_threads)
799 if (!thread->UnwindThread(*this, pClrDataProcess)) {
807 // Replace an existing module mapping with one with a different name.
810 CrashInfo::ReplaceModuleMapping(CLRDATA_ADDRESS baseAddress, const char* pszName)
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())
818 m_moduleMappings.insert(region);
821 TRACE("MODULE: ADD ");
827 // Create the new memory region with the managed assembly name.
828 MemoryRegion newRegion(*found, pszName);
830 // Remove and cleanup the old one
831 m_moduleMappings.erase(found);
832 const_cast<MemoryRegion&>(*found).Cleanup();
834 // Add the new memory region
835 m_moduleMappings.insert(newRegion);
838 TRACE("MODULE: REPLACE ");
845 // Returns the module base address for the IP or 0.
847 uint64_t CrashInfo::GetBaseAddress(uint64_t ip)
849 MemoryRegion search(0, ip, ip, 0);
850 const MemoryRegion* found = SearchMemoryRegions(m_moduleAddresses, search);
851 if (found == nullptr) {
854 // The memory region Offset() is the base address of the module
855 return found->Offset();
859 // ReadMemory from target and add to memory regions list
862 CrashInfo::ReadMemory(void* address, void* buffer, size_t size)
865 if (FAILED(m_dataTarget->ReadVirtual(reinterpret_cast<CLRDATA_ADDRESS>(address), reinterpret_cast<PBYTE>(buffer), size, &read)))
869 InsertMemoryRegion(reinterpret_cast<uint64_t>(address), size);
874 // Add this memory chunk to the list of regions to be
875 // written to the core dump.
878 CrashInfo::InsertMemoryRegion(uint64_t address, size_t size)
880 assert(size < UINT_MAX);
882 // Round to page boundary
883 uint64_t start = address & PAGE_MASK;
886 // Round up to page boundary
887 uint64_t end = ((address + size) + (PAGE_SIZE - 1)) & PAGE_MASK;
890 InsertMemoryRegion(MemoryRegion(GetMemoryRegionFlags(start) | MEMORY_REGION_FLAG_MEMORY_BACKED, start, end));
894 // Adds a memory backed flagged copy of the memory region. The file name is not preserved.
897 CrashInfo::InsertMemoryBackedRegion(const MemoryRegion& region)
899 InsertMemoryRegion(MemoryRegion(region, region.Flags() | MEMORY_REGION_FLAG_MEMORY_BACKED));
903 // Add a memory region to the list
906 CrashInfo::InsertMemoryRegion(const MemoryRegion& region)
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())
912 // If the region is valid, add the full memory region
913 if (ValidRegion(region)) {
914 m_memoryRegions.insert(region);
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())) {
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();
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;
934 for (size_t p = 0; p < numberPages; p++, start += PAGE_SIZE)
936 MemoryRegion memoryRegionPage(region.Flags(), start, start + PAGE_SIZE);
938 const auto& found = m_memoryRegions.find(memoryRegionPage);
939 if (found == m_memoryRegions.end())
941 // All the single pages added here will be combined in CombineMemoryRegions()
942 if (ValidRegion(memoryRegionPage)) {
943 m_memoryRegions.insert(memoryRegionPage);
947 assert(found->IsBackedByMemory() || !region.IsBackedByMemory());
953 // Get the memory region flags for a start address
956 CrashInfo::GetMemoryRegionFlags(uint64_t start)
958 MemoryRegion search(0, start, start + PAGE_SIZE);
959 const MemoryRegion* region = SearchMemoryRegions(m_moduleMappings, search);
960 if (region != nullptr) {
961 return region->Flags();
963 region = SearchMemoryRegions(m_otherMappings, search);
964 if (region != nullptr) {
965 return region->Flags();
967 TRACE("GetMemoryRegionFlags: FAILED\n");
968 return PF_R | PF_W | PF_X;
972 // Validates a memory region
975 CrashInfo::ValidRegion(const MemoryRegion& region)
977 if (region.IsBackedByMemory())
979 uint64_t start = region.StartAddress();
981 uint64_t numberPages = region.Size() / PAGE_SIZE;
982 for (size_t p = 0; p < numberPages; p++, start += PAGE_SIZE)
987 if (FAILED(m_dataTarget->ReadVirtual(start, buffer, 1, &read)))
997 // Combine any adjacent memory regions into one
1000 CrashInfo::CombineMemoryRegions()
1002 assert(!m_memoryRegions.empty());
1004 std::set<MemoryRegion> memoryRegionsNew;
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;
1012 for (const MemoryRegion& region : m_memoryRegions)
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))))
1018 end = region.EndAddress();
1022 MemoryRegion memoryRegion(flags, start, end);
1023 assert(memoryRegionsNew.find(memoryRegion) == memoryRegionsNew.end());
1024 memoryRegionsNew.insert(memoryRegion);
1026 flags = region.Flags() & (MEMORY_REGION_FLAG_MEMORY_BACKED | MEMORY_REGION_FLAG_PERMISSIONS_MASK);
1027 start = region.StartAddress();
1028 end = region.EndAddress();
1032 assert(start != end);
1033 MemoryRegion memoryRegion(flags, start, end);
1034 assert(memoryRegionsNew.find(memoryRegion) == memoryRegionsNew.end());
1035 memoryRegionsNew.insert(memoryRegion);
1037 m_memoryRegions = memoryRegionsNew;
1041 TRACE("Memory Regions:\n");
1042 for (const MemoryRegion& region : m_memoryRegions)
1050 // Searches for a memory region given an address.
1053 CrashInfo::SearchMemoryRegions(const std::set<MemoryRegion>& regions, const MemoryRegion& search)
1055 std::set<MemoryRegion>::iterator found = regions.find(search);
1056 for (; found != regions.end(); found++)
1058 if (search.StartAddress() >= found->StartAddress() && search.StartAddress() < found->EndAddress())
1067 // Get the process or thread status
1070 CrashInfo::GetStatus(pid_t pid, pid_t* ppid, pid_t* tgid, char** name)
1072 char statusPath[128];
1073 snprintf(statusPath, sizeof(statusPath), "/proc/%d/status", pid);
1075 FILE *statusFile = fopen(statusPath, "r");
1076 if (statusFile == nullptr)
1078 fprintf(stderr, "GetStatus fopen(%s) FAILED\n", statusPath);
1084 char *line = nullptr;
1087 while ((read = getline(&line, &lineLen, statusFile)) != -1)
1089 if (strncmp("PPid:\t", line, 6) == 0)
1091 *ppid = atoll(line + 6);
1093 else if (strncmp("Tgid:\t", line, 6) == 0)
1095 *tgid = atoll(line + 6);
1097 else if (strncmp("Name:\t", line, 6) == 0)
1099 if (name != nullptr)
1101 char* n = strchr(line + 6, '\n');
1106 *name = strdup(line + 6);