Skip to content

Instantly share code, notes, and snippets.

@bibhas
Created August 14, 2023 19:43
Show Gist options
  • Save bibhas/fd4eccc32adc577d75dfeb782618eb62 to your computer and use it in GitHub Desktop.
Save bibhas/fd4eccc32adc577d75dfeb782618eb62 to your computer and use it in GitHub Desktop.
// blox.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <time.h>
#include "common/log.h"
#include "sigsegv.h"
#define TOTAL_FAULTS 0x4000
#ifndef MORELLO
#include <mach/task.h>
#include <mach/mach_init.h>
#include <mach/mach_port.h>
#endif
int count = 0;
static sigsegv_dispatcher dispatcher;
static int area_handler(void *fault_address, void *user_arg) {
uintptr_t area = *(uintptr_t *)user_arg;
if (!((uintptr_t)fault_address >= area && (uintptr_t)fault_address - area < TOTAL_FAULTS)) {
abort();
}
if (mprotect((void *)area, TOTAL_FAULTS, PROT_READ | PROT_WRITE) == 0) {
count++;
return 1;
}
return 0;
}
static int handler(void *fault_address, int serious) {
return sigsegv_dispatch(&dispatcher, fault_address);
}
static inline void silence_xcode() {
#ifndef MORELLO
int ret = task_set_exception_ports(mach_task_self(), EXC_MASK_BAD_ACCESS, MACH_PORT_NULL, EXCEPTION_DEFAULT, 0);
/* Add auto breakpoint `proc hand -p true -s false SIGSEGV / SIGBUS` to lldb / xcode */
#endif
}
int main(int argc, const char **argv) {
silence_xcode();
sigsegv_init(&dispatcher);
sigsegv_install_handler(&handler);
void *p = mmap((void *)0x12340000, TOTAL_FAULTS, (PROT_READ | PROT_WRITE), MAP_ANON | MAP_PRIVATE, -1, 0);
if (p == (void *)(-1)) {
BLOX_ERROR("mmap failed!");
exit(2);
}
BLOX_DEBUG("mmap succeeded!");
uintptr_t area1 = (uintptr_t)p;
sigsegv_register(&dispatcher, (void *)area1, TOTAL_FAULTS, &area_handler, &area1);
if (mprotect((void *)area1, TOTAL_FAULTS, PROT_NONE) < 0) {
BLOX_ERROR("mprotect area1 failed!");
exit(2);
}
char *c = (char *)p;
clock_t start = clock();
for (int i = 0; i < TOTAL_FAULTS; i++) {
c[i] = 'b';
if (mprotect((void *)area1, TOTAL_FAULTS, PROT_NONE) < 0) {
BLOX_ERROR("mprotect area1 failed!");
exit(2);
}
}
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
int __faults = TOTAL_FAULTS;
printf("Took : %0.3f seconds to cause %0.0f faults!\n", seconds, (float)__faults);
printf("final count = %0.0f\n", (float)count);
printf("%0.0f\n", (float)c[100]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment