Advertisement
atomen

Memory allocated function

May 4th, 2012
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1. // Header files
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <sys/mman.h>
  6. #include <unistd.h>
  7.  
  8. typedef unsigned char byte;
  9.  
  10. bool ProtectMemory(void * addr, int flags)
  11. {
  12.     // Constant holding the page size value
  13.     const size_t pageSize = sysconf(_SC_PAGE_SIZE);
  14.    
  15.     // Calculate relative page offset
  16.     size_t temp = (size_t) addr;
  17.     temp -= temp % pageSize;
  18.    
  19.     // Update address
  20.     addr = (void*) temp;
  21.    
  22.     // Update memory area protection
  23.     return !mprotect(addr, pageSize, flags);
  24. }
  25.  
  26. typedef int (*testFunc)(int, int);
  27.  
  28. int main(void)
  29. {
  30.     char func[] = {0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d, 0xfc,
  31.     0x89, 0x75, 0xf8, 0x8b, 0x45, 0xf8,
  32.     0x8b, 0x55, 0xfc, 0x8d, 0x04, 0x02,
  33.     0xc9, 0xc3};
  34.  
  35.     testFunc func_copy = (testFunc) malloc(sizeof(func));
  36.     memcpy(func_copy, func, sizeof(func));
  37.  
  38.     ProtectMemory(func_copy, PROT_WRITE | PROT_READ | PROT_EXEC);
  39.  
  40.     printf("1 + 2 = %d\n", func_copy(1,2)); // segfaults here
  41.  
  42.     free(func_copy);
  43.     return 0;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement