Skip to content

Commit 215c0a3

Browse files
authored
Add hook (#7)
1 parent 406878a commit 215c0a3

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

Sources/SimpleDebugger/SimpleDebugger.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,28 @@ uint32_t setInstruction(vm_address_t address, uint32_t newInst) {
104104
return instruction;
105105
}
106106

107+
int SimpleDebugger::hookFunction(void *originalFunc, void *newFunc) {
108+
uintptr_t addr = reinterpret_cast<uintptr_t>(newFunc);
109+
uint8_t reg = 9;
110+
for (int shift = 0; shift <= 48; shift += 16) {
111+
uint16_t imm16 = (addr >> shift) & 0xFFFF;
112+
113+
uint32_t inst;
114+
if (shift == 0) {
115+
// First instruction: MOVZ
116+
inst = 0xD2800000 | (imm16 << 5) | reg;
117+
} else {
118+
// Subsequent instructions: MOVK
119+
uint32_t shift_enc = (shift / 16) << 21;
120+
inst = 0xF2800000 | shift_enc | (imm16 << 5) | reg;
121+
}
122+
setInstruction((vm_address_t) originalFunc + 4 * (shift/16), inst);
123+
}
124+
// Make sure address fits into 16 bits
125+
setInstruction((vm_address_t) originalFunc + (4 * 4), 0xD61F0120); // Branch to X9
126+
return 0;
127+
}
128+
107129
void SimpleDebugger::setBreakpoint(vm_address_t address) {
108130
uint32_t instruction = setInstruction(address, ARM64_BREAK_INSTRUCTION);
109131
originalInstruction.insert({address, instruction});

Sources/SimpleDebugger/include/SimpleDebugger.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ class SimpleDebugger {
3535
void setExceptionCallback(ExceptionCallback callback);
3636
void setBreakpoint(vm_address_t address);
3737

38+
// The function at originalFunc must be at least 5 instructions
39+
int hookFunction(void *originalFunc, void *newFunc);
40+
3841
~SimpleDebugger();
3942

4043
private:

0 commit comments

Comments
 (0)