Commit f8ba23a4 authored by SR_team's avatar SR_team 💬

Added SRHook

parent 32ad3b87
#ifndef SRALLOCATOR_H
#define SRALLOCATOR_H
#ifdef WIN32
# include <windows.h>
#else
# include <sys/mman.h>
#endif
namespace SRHook::Allocator {
namespace private_ {
template<typename T> static bool unprotect( T *ptr, size_t count ) {
size_t size = count * sizeof( T );
#ifdef WIN32
size_t address = (size_t)ptr;
do {
MEMORY_BASIC_INFORMATION mbi;
if ( !::VirtualQuery( reinterpret_cast<PVOID>( address ), &mbi, sizeof( mbi ) ) ) return false;
if ( size > mbi.RegionSize )
size -= mbi.RegionSize;
else
size = 0;
DWORD oldp;
if ( !::VirtualProtect( mbi.BaseAddress, mbi.RegionSize, PAGE_EXECUTE_READWRITE, &oldp ) )
return false;
if ( reinterpret_cast<size_t>( mbi.BaseAddress ) + mbi.RegionSize < address + size )
address = reinterpret_cast<size_t>( mbi.BaseAddress ) + mbi.RegionSize;
} while ( size );
#else
if ( ::mprotect( (void *)ptr, size, PROT_READ | PROT_WRITE | PROT_EXEC ) ) return false;
#endif
return true;
}
}
template<typename T> void dealloc( T *&ptr ){
if ( ptr ) ::free( (void*)ptr );
ptr = nullptr;
}
template<typename T> T *alloc( size_t count ) {
auto addr = (T *)::malloc( count * sizeof( T ) );
if ( addr ) {
if ( private_::unprotect( addr, count * sizeof( T ) ) ) return addr;
dealloc( addr );
}
return nullptr;
}
template<typename T> T *realloc( T *ptr, size_t count ) {
auto addr = (T *)::realloc( (void *)ptr, count * sizeof( T ) );
if ( addr ) {
if ( private_::unprotect( addr, count * sizeof( T ) ) ) return addr;
dealloc( addr );
}
return ptr; // BUG: Не дает понять, по какой причине указатель не изменилась - память аллоцирована по тому же адресу, или произошла ошибка реаллокации?
}
}
#endif // SRALLOCATOR_H
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment