我正在尝试创建一个程序来跟踪进程的内存.. 我所拥有的是在某个时刻尝试使用我的保护功能来保护所有内存:
static void Protect(void* ptr, size_t size)
{
MemoryMgr& mgr = MemoryMgr::instance();
assert(!(size%s_pageAlign));
assert(ptr == (void*)((unsigned long long)(ptr)&0xfffffffffffff000));
printf("Protecting: 0x%x - 0x%x\n" ,(unsigned long long)(ptr), (unsigned long long)(ptr) + size);
assert(mgr.m_protected.insert(MemoryMgr::Protected_t::value_type(ptr, size)).second);
int r = mprotect(ptr, size, PROT_READ);
if (r) {
perror("mprotect");
cout << "Error: " << r << endl;
cout.flush();
exit(1);
}
s_allocCnt += size / s_pageAlign + ((size%s_pageAlign)? 1 : 0);
}
然后我已经注册了一个中断处理程序:
static void handler(int sig, siginfo_t *si, void *unused) {
MemoryMgr::OnSegFault(si ->si_addr, sig);
}
int MemoryMgr::OnSegFault(void* addr, int serious) {
MemoryMgr& mgr = instance();
Protected_t::iterator ptr = std::find_if(begin(mgr.m_protected), end(mgr.m_protected), [addr](Protected_t::value_type& ptr) -> bool {
return ((ptr.first <= addr) && (addr < (ptr.first + ptr.second)));
});
if (ptr == mgr.m_protected.end()) {
cout << "Ignoring segfault at Addr: " << (unsigned long long)(addr) << endl;
mprotect((void*)((unsigned long long)(addr)&0xfffffffffffff000), s_pageAlign, PROT_READ | PROT_WRITE);
s_ignoredPageFaults++;
return 1;
}
printf("Segaulting at Ptr : 0x%x - 0x%x\n", (unsigned long long)(ptr ->first), (unsigned long long)(ptr ->first) + ptr ->second);
s_segFaultCnt += ptr ->second/s_pageAlign + ((ptr ->second%s_pageAlign)? 1 : 0);
int r = mprotect(ptr ->first, ptr ->second, PROT_READ | PROT_WRITE);
if (r) {
cout << "Mprotect Failed" << endl;
cout.flush();
return 0;
}
return 1;
}
这个过程似乎停留在某个fwrite ...但我可以在日志中看到进程尝试访问的内存早已被segaulted并恢复到正常状态.. 我还可以看到该进程不会停止从该块读取的第一个内存,但经过相当多的页面... 有没有人有任何想法/线索?
感谢。