Skip to content

Instantly share code, notes, and snippets.

@byteandahalf
Last active February 19, 2016 07:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save byteandahalf/bb825d4c2a63c2674aae to your computer and use it in GitHub Desktop.
Save byteandahalf/bb825d4c2a63c2674aae to your computer and use it in GitHub Desktop.
My totally working attempt at hooking 8 byte functions
#include "sys/mman.h"
void tiny_hook(uint32_t* addr, uint32_t hook) {
bool thumb = (uint32_t)addr & 1;
if(thumb)
addr = (uint32_t*) ((uint32_t) addr - 1);
mprotect(addr, 9, PROT_READ | PROT_WRITE);
*addr = (uint32_t) (thumb)? 0xF000F8DF : 0xE51FF008; // LDR PC, [PC] on Thumb and LDR PC, [PC, #-8] on ARM.
*(addr + 1) = hook;
mprotect(addr, 9, PROT_READ | PROT_EXEC);
}
@mackthehobbit
Copy link

When calling mprotect, the values must be aligned with page boundaries, so this code seems like it won't work. (The page containing addr will obviously be executable already, and may be writable too - so perhaps it will work in some cases.) You're also incrementing addr before calling mprotect the second time.

@byteandahalf
Copy link
Author

There, fixed everything except the pagealigning for now.

@byteandahalf
Copy link
Author

Also decrementing addr for thumb before calling the first mprotect so that it changes write access to the same bytes as the second mprotect.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment