Skip to content

Commit 6b6a049

Browse files
committed
Add function for undoing stuff done by hookFunction
1 parent 72a6779 commit 6b6a049

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

ttyd-tools/rel/include/patch.h

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,39 @@ Func hookFunction(Func function, Dest destination)
5353
return reinterpret_cast<Func>(trampoline);
5454
}
5555

56+
template<typename Func>
57+
Func unhookFunction(Func trampoline)
58+
{
59+
uint32_t *instructions = reinterpret_cast<uint32_t *>(trampoline);
60+
61+
// Restore the original instruction
62+
uint32_t instructionAddress = reinterpret_cast<uint32_t>(&instructions[1]);
63+
uint32_t branchInstruction = instructions[1];
64+
uint32_t branchLength;
65+
uint32_t *address;
66+
67+
if (branchInstruction >= 0x4A000000)
68+
{
69+
// Branch is negative
70+
branchLength = 0x4C000000 - branchInstruction;
71+
address = reinterpret_cast<uint32_t *>(instructionAddress - branchLength - 0x4);
72+
}
73+
else
74+
{
75+
// Branch is positive
76+
branchLength = branchInstruction - 0x48000000;
77+
address = reinterpret_cast<uint32_t *>(instructionAddress + branchLength - 0x4);
78+
}
79+
80+
*address = instructions[0];
81+
82+
// Clear the cache for both the address and where the instructions were stored
83+
clear_DC_IC_Cache(address, sizeof(uint32_t));
84+
clear_DC_IC_Cache(instructions, sizeof(uint32_t));
85+
86+
// Free the memory used by the trampoline
87+
delete[] (instructions);
88+
return nullptr;
89+
}
90+
5691
}

0 commit comments

Comments
 (0)