Skip to content

Instantly share code, notes, and snippets.

@HunterKohler
Last active January 8, 2022 07:17
Show Gist options
  • Save HunterKohler/9a7471db2c0e84cbfb8003931413d463 to your computer and use it in GitHub Desktop.
Save HunterKohler/9a7471db2c0e84cbfb8003931413d463 to your computer and use it in GitHub Desktop.
Replace functions by loading library symbols and writing a unconditional jump. (x86 only)
/*
* Copyright (C) 2021 Hunter Kohler <jhunterkohler@gmail.com>
*/
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include "reljump.h"
size_t page_size()
{
static size_t ret;
return ret ? ret : (ret = sysconf(_SC_PAGESIZE));
}
void *pageof(const void *addr)
{
return (void *)((uintptr_t)addr & ~(page_size() - 1));
}
int replace_func(void *func, void *repl)
{
struct reljmp op = { 0xE9, repl - (func + sizeof(op)) };
void *page = pageof(func);
int error = mprotect(page, sizeof(op), PROT_WRITE);
if (error)
return error;
memcpy(func, &op, sizeof(op));
error = mprotect(page, sizeof(op), PROT_READ | PROT_EXEC);
return error;
}
/*
* Copyright (C) 2021 Hunter Kohler <jhunterkohler@gmail.com>
*/
#ifndef RELJUMP_H_
#define RELJUMP_H_
#include <stdint.h>
struct reljmp {
uint8_t opcode;
int32_t len;
} __attribute__((packed));
int replace_func(void *func, void *repl);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment