| 1 |
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- |
| 2 |
/* Copyright (c) 2007, Google Inc. |
| 3 |
* All rights reserved. |
| 4 |
* |
| 5 |
* Redistribution and use in source and binary forms, with or without |
| 6 |
* modification, are permitted provided that the following conditions are |
| 7 |
* met: |
| 8 |
* |
| 9 |
* * Redistributions of source code must retain the above copyright |
| 10 |
* notice, this list of conditions and the following disclaimer. |
| 11 |
* * Redistributions in binary form must reproduce the above |
| 12 |
* copyright notice, this list of conditions and the following disclaimer |
| 13 |
* in the documentation and/or other materials provided with the |
| 14 |
* distribution. |
| 15 |
* * Neither the name of Google Inc. nor the names of its |
| 16 |
* contributors may be used to endorse or promote products derived from |
| 17 |
* this software without specific prior written permission. |
| 18 |
* |
| 19 |
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 20 |
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 21 |
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 22 |
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 23 |
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 24 |
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| 25 |
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 26 |
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 27 |
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 28 |
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 29 |
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 30 |
* |
| 31 |
* --- |
| 32 |
* Author: Joi Sigurdsson |
| 33 |
* Author: Scott Francis |
| 34 |
* |
| 35 |
* Implementation of PreamblePatcher |
| 36 |
*/ |
| 37 |
|
| 38 |
#include "preamble_patcher.h" |
| 39 |
|
| 40 |
#include "mini_disassembler.h" |
| 41 |
|
| 42 |
// compatibility shims |
| 43 |
#include "base/logging.h" |
| 44 |
|
| 45 |
// Definitions of assembly statements we need |
| 46 |
#define ASM_JMP32REL 0xE9 |
| 47 |
#define ASM_INT3 0xCC |
| 48 |
#define ASM_JMP32ABS_0 0xFF |
| 49 |
#define ASM_JMP32ABS_1 0x25 |
| 50 |
#define ASM_JMP8REL 0xEB |
| 51 |
#define ASM_JCC32REL_0 0x0F |
| 52 |
#define ASM_JCC32REL_1_MASK 0x80 |
| 53 |
#define ASM_NOP 0x90 |
| 54 |
// X64 opcodes |
| 55 |
#define ASM_REXW 0x48 |
| 56 |
#define ASM_MOVRAX_IMM 0xB8 |
| 57 |
#define ASM_JMP 0xFF |
| 58 |
#define ASM_JMP_RAX 0xE0 |
| 59 |
|
| 60 |
namespace sidestep { |
| 61 |
|
| 62 |
PreamblePatcher::PreamblePage* PreamblePatcher::preamble_pages_ = NULL; |
| 63 |
long PreamblePatcher::granularity_ = 0; |
| 64 |
long PreamblePatcher::pagesize_ = 0; |
| 65 |
bool PreamblePatcher::initialized_ = false; |
| 66 |
|
| 67 |
static const unsigned int kPreamblePageMagic = 0x4347414D; // "MAGC" |
| 68 |
|
| 69 |
// Handle a special case that we see with functions that point into an |
| 70 |
// IAT table (including functions linked statically into the |
| 71 |
// application): these function already starts with ASM_JMP32*. For |
| 72 |
// instance, malloc() might be implemented as a JMP to __malloc(). |
| 73 |
// This function follows the initial JMPs for us, until we get to the |
| 74 |
// place where the actual code is defined. If we get to STOP_BEFORE, |
| 75 |
// we return the address before stop_before. The stop_before_trampoline |
| 76 |
// flag is used in 64-bit mode. If true, we will return the address |
| 77 |
// before a trampoline is detected. Trampolines are defined as: |
| 78 |
// |
| 79 |
// nop |
| 80 |
// mov rax, <replacement_function> |
| 81 |
// jmp rax |
| 82 |
// |
| 83 |
// See PreamblePatcher::RawPatchWithStub for more information. |
| 84 |
void* PreamblePatcher::ResolveTargetImpl(unsigned char* target, |
| 85 |
unsigned char* stop_before, |
| 86 |
bool stop_before_trampoline) { |
| 87 |
if (target == NULL) |
| 88 |
return NULL; |
| 89 |
while (1) { |
| 90 |
unsigned char* new_target; |
| 91 |
if (target[0] == ASM_JMP32REL) { |
| 92 |
// target[1-4] holds the place the jmp goes to, but it's |
| 93 |
// relative to the next instruction. |
| 94 |
int relative_offset; // Windows guarantees int is 4 bytes |
| 95 |
SIDESTEP_ASSERT(sizeof(relative_offset) == 4); |
| 96 |
memcpy(reinterpret_cast<void*>(&relative_offset), |
| 97 |
reinterpret_cast<void*>(target + 1), 4); |
| 98 |
new_target = target + 5 + relative_offset; |
| 99 |
} else if (target[0] == ASM_JMP8REL) { |
| 100 |
// Visual Studio 7.1 implements new[] as an 8 bit jump to new |
| 101 |
signed char relative_offset; |
| 102 |
memcpy(reinterpret_cast<void*>(&relative_offset), |
| 103 |
reinterpret_cast<void*>(target + 1), 1); |
| 104 |
new_target = target + 2 + relative_offset; |
| 105 |
} else if (target[0] == ASM_JMP32ABS_0 && |
| 106 |
target[1] == ASM_JMP32ABS_1) { |
| 107 |
jmp32rel: |
| 108 |
// Visual studio seems to sometimes do it this way instead of the |
| 109 |
// previous way. Not sure what the rules are, but it was happening |
| 110 |
// with operator new in some binaries. |
| 111 |
void** new_target_v; |
| 112 |
if (kIs64BitBinary) { |
| 113 |
// In 64-bit mode JMPs are RIP-relative, not absolute |
| 114 |
int target_offset; |
| 115 |
memcpy(reinterpret_cast<void*>(&target_offset), |
| 116 |
reinterpret_cast<void*>(target + 2), 4); |
| 117 |
new_target_v = reinterpret_cast<void**>(target + target_offset + 6); |
| 118 |
} else { |
| 119 |
SIDESTEP_ASSERT(sizeof(new_target) == 4); |
| 120 |
memcpy(&new_target_v, reinterpret_cast<void*>(target + 2), 4); |
| 121 |
} |
| 122 |
new_target = reinterpret_cast<unsigned char*>(*new_target_v); |
| 123 |
} else if (kIs64BitBinary && target[0] == ASM_REXW |
| 124 |
&& target[1] == ASM_JMP32ABS_0 |
| 125 |
&& target[2] == ASM_JMP32ABS_1) { |
| 126 |
// in Visual Studio 2012 we're seeing jump like that: |
| 127 |
// rex.W jmpq *0x11d019(%rip) |
| 128 |
// |
| 129 |
// according to docs I have, rex prefix is actually unneeded and |
| 130 |
// can be ignored. I.e. docs say for jumps like that operand |
| 131 |
// already defaults to 64-bit. But clearly it breaks abs. jump |
| 132 |
// detection above and we just skip rex |
| 133 |
target++; |
| 134 |
goto jmp32rel; |
| 135 |
} else { |
| 136 |
break; |
| 137 |
} |
| 138 |
if (new_target == stop_before) |
| 139 |
break; |
| 140 |
if (stop_before_trampoline && *new_target == ASM_NOP |
| 141 |
&& new_target[1] == ASM_REXW && new_target[2] == ASM_MOVRAX_IMM) |
| 142 |
break; |
| 143 |
target = new_target; |
| 144 |
} |
| 145 |
return target; |
| 146 |
} |
| 147 |
|
| 148 |
// Special case scoped_ptr to avoid dependency on scoped_ptr below. |
| 149 |
class DeleteUnsignedCharArray { |
| 150 |
public: |
| 151 |
DeleteUnsignedCharArray(unsigned char* array) : array_(array) { |
| 152 |
} |
| 153 |
|
| 154 |
~DeleteUnsignedCharArray() { |
| 155 |
if (array_) { |
| 156 |
PreamblePatcher::FreePreambleBlock(array_); |
| 157 |
} |
| 158 |
} |
| 159 |
|
| 160 |
unsigned char* Release() { |
| 161 |
unsigned char* temp = array_; |
| 162 |
array_ = NULL; |
| 163 |
return temp; |
| 164 |
} |
| 165 |
|
| 166 |
private: |
| 167 |
unsigned char* array_; |
| 168 |
}; |
| 169 |
|
| 170 |
SideStepError PreamblePatcher::RawPatchWithStubAndProtections( |
| 171 |
void* target_function, void *replacement_function, |
| 172 |
unsigned char* preamble_stub, unsigned long stub_size, |
| 173 |
unsigned long* bytes_needed) { |
| 174 |
// We need to be able to write to a process-local copy of the first |
| 175 |
// MAX_PREAMBLE_STUB_SIZE bytes of target_function |
| 176 |
DWORD old_target_function_protect = 0; |
| 177 |
BOOL succeeded = ::VirtualProtect(reinterpret_cast<void*>(target_function), |
| 178 |
MAX_PREAMBLE_STUB_SIZE, |
| 179 |
PAGE_EXECUTE_READWRITE, |
| 180 |
&old_target_function_protect); |
| 181 |
if (!succeeded) { |
| 182 |
SIDESTEP_ASSERT(false && "Failed to make page containing target function " |
| 183 |
"copy-on-write."); |
| 184 |
return SIDESTEP_ACCESS_DENIED; |
| 185 |
} |
| 186 |
|
| 187 |
SideStepError error_code = RawPatchWithStub(target_function, |
| 188 |
replacement_function, |
| 189 |
preamble_stub, |
| 190 |
stub_size, |
| 191 |
bytes_needed); |
| 192 |
|
| 193 |
// Restore the protection of the first MAX_PREAMBLE_STUB_SIZE bytes of |
| 194 |
// pTargetFunction to what they were before we started goofing around. |
| 195 |
// We do this regardless of whether the patch succeeded or not. |
| 196 |
succeeded = ::VirtualProtect(reinterpret_cast<void*>(target_function), |
| 197 |
MAX_PREAMBLE_STUB_SIZE, |
| 198 |
old_target_function_protect, |
| 199 |
&old_target_function_protect); |
| 200 |
if (!succeeded) { |
| 201 |
SIDESTEP_ASSERT(false && |
| 202 |
"Failed to restore protection to target function."); |
| 203 |
// We must not return an error here because the function has |
| 204 |
// likely actually been patched, and returning an error might |
| 205 |
// cause our client code not to unpatch it. So we just keep |
| 206 |
// going. |
| 207 |
} |
| 208 |
|
| 209 |
if (SIDESTEP_SUCCESS != error_code) { // Testing RawPatchWithStub, above |
| 210 |
SIDESTEP_ASSERT(false); |
| 211 |
return error_code; |
| 212 |
} |
| 213 |
|
| 214 |
// Flush the instruction cache to make sure the processor doesn't execute the |
| 215 |
// old version of the instructions (before our patch). |
| 216 |
// |
| 217 |
// FlushInstructionCache is actually a no-op at least on |
| 218 |
// single-processor XP machines. I'm not sure why this is so, but |
| 219 |
// it is, yet I want to keep the call to the API here for |
| 220 |
// correctness in case there is a difference in some variants of |
| 221 |
// Windows/hardware. |
| 222 |
succeeded = ::FlushInstructionCache(::GetCurrentProcess(), |
| 223 |
target_function, |
| 224 |
MAX_PREAMBLE_STUB_SIZE); |
| 225 |
if (!succeeded) { |
| 226 |
SIDESTEP_ASSERT(false && "Failed to flush instruction cache."); |
| 227 |
// We must not return an error here because the function has actually |
| 228 |
// been patched, and returning an error would likely cause our client |
| 229 |
// code not to unpatch it. So we just keep going. |
| 230 |
} |
| 231 |
|
| 232 |
return SIDESTEP_SUCCESS; |
| 233 |
} |
| 234 |
|
| 235 |
SideStepError PreamblePatcher::RawPatch(void* target_function, |
| 236 |
void* replacement_function, |
| 237 |
void** original_function_stub) { |
| 238 |
if (!target_function || !replacement_function || !original_function_stub || |
| 239 |
(*original_function_stub) || target_function == replacement_function) { |
| 240 |
SIDESTEP_ASSERT(false && "Preconditions not met"); |
| 241 |
return SIDESTEP_INVALID_PARAMETER; |
| 242 |
} |
| 243 |
|
| 244 |
BOOL succeeded = FALSE; |
| 245 |
|
| 246 |
// First, deal with a special case that we see with functions that |
| 247 |
// point into an IAT table (including functions linked statically |
| 248 |
// into the application): these function already starts with |
| 249 |
// ASM_JMP32REL. For instance, malloc() might be implemented as a |
| 250 |
// JMP to __malloc(). In that case, we replace the destination of |
| 251 |
// the JMP (__malloc), rather than the JMP itself (malloc). This |
| 252 |
// way we get the correct behavior no matter how malloc gets called. |
| 253 |
void* new_target = ResolveTarget(target_function); |
| 254 |
if (new_target != target_function) { |
| 255 |
target_function = new_target; |
| 256 |
} |
| 257 |
|
| 258 |
// In 64-bit mode, preamble_stub must be within 2GB of target function |
| 259 |
// so that if target contains a jump, we can translate it. |
| 260 |
unsigned char* preamble_stub = AllocPreambleBlockNear(target_function); |
| 261 |
if (!preamble_stub) { |
| 262 |
SIDESTEP_ASSERT(false && "Unable to allocate preamble-stub."); |
| 263 |
return SIDESTEP_INSUFFICIENT_BUFFER; |
| 264 |
} |
| 265 |
|
| 266 |
// Frees the array at end of scope. |
| 267 |
DeleteUnsignedCharArray guard_preamble_stub(preamble_stub); |
| 268 |
|
| 269 |
SideStepError error_code = RawPatchWithStubAndProtections( |
| 270 |
target_function, replacement_function, preamble_stub, |
| 271 |
MAX_PREAMBLE_STUB_SIZE, NULL); |
| 272 |
|
| 273 |
if (SIDESTEP_SUCCESS != error_code) { |
| 274 |
SIDESTEP_ASSERT(false); |
| 275 |
return error_code; |
| 276 |
} |
| 277 |
|
| 278 |
// Flush the instruction cache to make sure the processor doesn't execute the |
| 279 |
// old version of the instructions (before our patch). |
| 280 |
// |
| 281 |
// FlushInstructionCache is actually a no-op at least on |
| 282 |
// single-processor XP machines. I'm not sure why this is so, but |
| 283 |
// it is, yet I want to keep the call to the API here for |
| 284 |
// correctness in case there is a difference in some variants of |
| 285 |
// Windows/hardware. |
| 286 |
succeeded = ::FlushInstructionCache(::GetCurrentProcess(), |
| 287 |
target_function, |
| 288 |
MAX_PREAMBLE_STUB_SIZE); |
| 289 |
if (!succeeded) { |
| 290 |
SIDESTEP_ASSERT(false && "Failed to flush instruction cache."); |
| 291 |
// We must not return an error here because the function has actually |
| 292 |
// been patched, and returning an error would likely cause our client |
| 293 |
// code not to unpatch it. So we just keep going. |
| 294 |
} |
| 295 |
|
| 296 |
SIDESTEP_LOG("PreamblePatcher::RawPatch successfully patched."); |
| 297 |
|
| 298 |
// detach the scoped pointer so the memory is not freed |
| 299 |
*original_function_stub = |
| 300 |
reinterpret_cast<void*>(guard_preamble_stub.Release()); |
| 301 |
return SIDESTEP_SUCCESS; |
| 302 |
} |
| 303 |
|
| 304 |
SideStepError PreamblePatcher::Unpatch(void* target_function, |
| 305 |
void* replacement_function, |
| 306 |
void* original_function_stub) { |
| 307 |
SIDESTEP_ASSERT(target_function && replacement_function && |
| 308 |
original_function_stub); |
| 309 |
if (!target_function || !replacement_function || |
| 310 |
!original_function_stub) { |
| 311 |
return SIDESTEP_INVALID_PARAMETER; |
| 312 |
} |
| 313 |
|
| 314 |
// Before unpatching, target_function should be a JMP to |
| 315 |
// replacement_function. If it's not, then either it's an error, or |
| 316 |
// we're falling into the case where the original instruction was a |
| 317 |
// JMP, and we patched the jumped_to address rather than the JMP |
| 318 |
// itself. (For instance, if malloc() is just a JMP to __malloc(), |
| 319 |
// we patched __malloc() and not malloc().) |
| 320 |
unsigned char* target = reinterpret_cast<unsigned char*>(target_function); |
| 321 |
target = reinterpret_cast<unsigned char*>( |
| 322 |
ResolveTargetImpl( |
| 323 |
target, reinterpret_cast<unsigned char*>(replacement_function), |
| 324 |
true)); |
| 325 |
// We should end at the function we patched. When we patch, we insert |
| 326 |
// a ASM_JMP32REL instruction, so look for that as a sanity check. |
| 327 |
if (target[0] != ASM_JMP32REL) { |
| 328 |
SIDESTEP_ASSERT(false && |
| 329 |
"target_function does not look like it was patched."); |
| 330 |
return SIDESTEP_INVALID_PARAMETER; |
| 331 |
} |
| 332 |
|
| 333 |
const unsigned int kRequiredTargetPatchBytes = 5; |
| 334 |
|
| 335 |
// We need to be able to write to a process-local copy of the first |
| 336 |
// kRequiredTargetPatchBytes bytes of target_function |
| 337 |
DWORD old_target_function_protect = 0; |
| 338 |
BOOL succeeded = ::VirtualProtect(reinterpret_cast<void*>(target), |
| 339 |
kRequiredTargetPatchBytes, |
| 340 |
PAGE_EXECUTE_READWRITE, |
| 341 |
&old_target_function_protect); |
| 342 |
if (!succeeded) { |
| 343 |
SIDESTEP_ASSERT(false && "Failed to make page containing target function " |
| 344 |
"copy-on-write."); |
| 345 |
return SIDESTEP_ACCESS_DENIED; |
| 346 |
} |
| 347 |
|
| 348 |
unsigned char* preamble_stub = reinterpret_cast<unsigned char*>( |
| 349 |
original_function_stub); |
| 350 |
|
| 351 |
// Disassemble the preamble of stub and copy the bytes back to target. |
| 352 |
// If we've done any conditional jumps in the preamble we need to convert |
| 353 |
// them back to the original REL8 jumps in the target. |
| 354 |
MiniDisassembler disassembler; |
| 355 |
unsigned int preamble_bytes = 0; |
| 356 |
unsigned int target_bytes = 0; |
| 357 |
while (target_bytes < kRequiredTargetPatchBytes) { |
| 358 |
unsigned int cur_bytes = 0; |
| 359 |
InstructionType instruction_type = |
| 360 |
disassembler.Disassemble(preamble_stub + preamble_bytes, cur_bytes); |
| 361 |
if (IT_JUMP == instruction_type) { |
| 362 |
unsigned int jump_bytes = 0; |
| 363 |
SideStepError jump_ret = SIDESTEP_JUMP_INSTRUCTION; |
| 364 |
if (IsNearConditionalJump(preamble_stub + preamble_bytes, cur_bytes) || |
| 365 |
IsNearRelativeJump(preamble_stub + preamble_bytes, cur_bytes) || |
| 366 |
IsNearAbsoluteCall(preamble_stub + preamble_bytes, cur_bytes) || |
| 367 |
IsNearRelativeCall(preamble_stub + preamble_bytes, cur_bytes)) { |
| 368 |
jump_ret = PatchNearJumpOrCall(preamble_stub + preamble_bytes, |
| 369 |
cur_bytes, target + target_bytes, |
| 370 |
&jump_bytes, MAX_PREAMBLE_STUB_SIZE); |
| 371 |
} |
| 372 |
if (jump_ret == SIDESTEP_JUMP_INSTRUCTION) { |
| 373 |
SIDESTEP_ASSERT(false && |
| 374 |
"Found unsupported jump instruction in stub!!"); |
| 375 |
return SIDESTEP_UNSUPPORTED_INSTRUCTION; |
| 376 |
} |
| 377 |
target_bytes += jump_bytes; |
| 378 |
} else if (IT_GENERIC == instruction_type) { |
| 379 |
if (IsMovWithDisplacement(preamble_stub + preamble_bytes, cur_bytes)) { |
| 380 |
unsigned int mov_bytes = 0; |
| 381 |
if (PatchMovWithDisplacement(preamble_stub + preamble_bytes, cur_bytes, |
| 382 |
target + target_bytes, &mov_bytes, |
| 383 |
MAX_PREAMBLE_STUB_SIZE) |
| 384 |
!= SIDESTEP_SUCCESS) { |
| 385 |
SIDESTEP_ASSERT(false && |
| 386 |
"Found unsupported generic instruction in stub!!"); |
| 387 |
return SIDESTEP_UNSUPPORTED_INSTRUCTION; |
| 388 |
} |
| 389 |
} else { |
| 390 |
memcpy(reinterpret_cast<void*>(target + target_bytes), |
| 391 |
reinterpret_cast<void*>(reinterpret_cast<unsigned char*>( |
| 392 |
original_function_stub) + preamble_bytes), cur_bytes); |
| 393 |
target_bytes += cur_bytes; |
| 394 |
} |
| 395 |
} else { |
| 396 |
SIDESTEP_ASSERT(false && |
| 397 |
"Found unsupported instruction in stub!!"); |
| 398 |
return SIDESTEP_UNSUPPORTED_INSTRUCTION; |
| 399 |
} |
| 400 |
preamble_bytes += cur_bytes; |
| 401 |
} |
| 402 |
|
| 403 |
FreePreambleBlock(reinterpret_cast<unsigned char*>(original_function_stub)); |
| 404 |
|
| 405 |
// Restore the protection of the first kRequiredTargetPatchBytes bytes of |
| 406 |
// target to what they were before we started goofing around. |
| 407 |
succeeded = ::VirtualProtect(reinterpret_cast<void*>(target), |
| 408 |
kRequiredTargetPatchBytes, |
| 409 |
old_target_function_protect, |
| 410 |
&old_target_function_protect); |
| 411 |
|
| 412 |
// Flush the instruction cache to make sure the processor doesn't execute the |
| 413 |
// old version of the instructions (before our patch). |
| 414 |
// |
| 415 |
// See comment on FlushInstructionCache elsewhere in this file. |
| 416 |
succeeded = ::FlushInstructionCache(::GetCurrentProcess(), |
| 417 |
target, |
| 418 |
MAX_PREAMBLE_STUB_SIZE); |
| 419 |
if (!succeeded) { |
| 420 |
SIDESTEP_ASSERT(false && "Failed to flush instruction cache."); |
| 421 |
return SIDESTEP_UNEXPECTED; |
| 422 |
} |
| 423 |
|
| 424 |
SIDESTEP_LOG("PreamblePatcher::Unpatch successfully unpatched."); |
| 425 |
return SIDESTEP_SUCCESS; |
| 426 |
} |
| 427 |
|
| 428 |
void PreamblePatcher::Initialize() { |
| 429 |
if (!initialized_) { |
| 430 |
SYSTEM_INFO si = { 0 }; |
| 431 |
::GetSystemInfo(&si); |
| 432 |
granularity_ = si.dwAllocationGranularity; |
| 433 |
pagesize_ = si.dwPageSize; |
| 434 |
initialized_ = true; |
| 435 |
} |
| 436 |
} |
| 437 |
|
| 438 |
unsigned char* PreamblePatcher::AllocPreambleBlockNear(void* target) { |
| 439 |
PreamblePage* preamble_page = preamble_pages_; |
| 440 |
while (preamble_page != NULL) { |
| 441 |
if (preamble_page->free_ != NULL) { |
| 442 |
__int64 val = reinterpret_cast<__int64>(preamble_page) - |
| 443 |
reinterpret_cast<__int64>(target); |
| 444 |
if ((val > 0 && val + pagesize_ <= INT_MAX) || |
| 445 |
(val < 0 && val >= INT_MIN)) { |
| 446 |
break; |
| 447 |
} |
| 448 |
} |
| 449 |
preamble_page = preamble_page->next_; |
| 450 |
} |
| 451 |
|
| 452 |
// The free_ member of the page is used to store the next available block |
| 453 |
// of memory to use or NULL if there are no chunks available, in which case |
| 454 |
// we'll allocate a new page. |
| 455 |
if (preamble_page == NULL || preamble_page->free_ == NULL) { |
| 456 |
// Create a new preamble page and initialize the free list |
| 457 |
preamble_page = reinterpret_cast<PreamblePage*>(AllocPageNear(target)); |
| 458 |
SIDESTEP_ASSERT(preamble_page != NULL && "Could not allocate page!"); |
| 459 |
void** pp = &preamble_page->free_; |
| 460 |
unsigned char* ptr = reinterpret_cast<unsigned char*>(preamble_page) + |
| 461 |
MAX_PREAMBLE_STUB_SIZE; |
| 462 |
unsigned char* limit = reinterpret_cast<unsigned char*>(preamble_page) + |
| 463 |
pagesize_; |
| 464 |
while (ptr < limit) { |
| 465 |
*pp = ptr; |
| 466 |
pp = reinterpret_cast<void**>(ptr); |
| 467 |
ptr += MAX_PREAMBLE_STUB_SIZE; |
| 468 |
} |
| 469 |
*pp = NULL; |
| 470 |
// Insert the new page into the list |
| 471 |
preamble_page->magic_ = kPreamblePageMagic; |
| 472 |
preamble_page->next_ = preamble_pages_; |
| 473 |
preamble_pages_ = preamble_page; |
| 474 |
} |
| 475 |
unsigned char* ret = reinterpret_cast<unsigned char*>(preamble_page->free_); |
| 476 |
preamble_page->free_ = *(reinterpret_cast<void**>(preamble_page->free_)); |
| 477 |
return ret; |
| 478 |
} |
| 479 |
|
| 480 |
void PreamblePatcher::FreePreambleBlock(unsigned char* block) { |
| 481 |
SIDESTEP_ASSERT(block != NULL); |
| 482 |
SIDESTEP_ASSERT(granularity_ != 0); |
| 483 |
uintptr_t ptr = reinterpret_cast<uintptr_t>(block); |
| 484 |
ptr -= ptr & (granularity_ - 1); |
| 485 |
PreamblePage* preamble_page = reinterpret_cast<PreamblePage*>(ptr); |
| 486 |
SIDESTEP_ASSERT(preamble_page->magic_ == kPreamblePageMagic); |
| 487 |
*(reinterpret_cast<void**>(block)) = preamble_page->free_; |
| 488 |
preamble_page->free_ = block; |
| 489 |
} |
| 490 |
|
| 491 |
void* PreamblePatcher::AllocPageNear(void* target) { |
| 492 |
MEMORY_BASIC_INFORMATION mbi = { 0 }; |
| 493 |
if (!::VirtualQuery(target, &mbi, sizeof(mbi))) { |
| 494 |
SIDESTEP_ASSERT(false && "VirtualQuery failed on target address"); |
| 495 |
return 0; |
| 496 |
} |
| 497 |
if (initialized_ == false) { |
| 498 |
PreamblePatcher::Initialize(); |
| 499 |
SIDESTEP_ASSERT(initialized_); |
| 500 |
} |
| 501 |
void* pv = NULL; |
| 502 |
unsigned char* allocation_base = reinterpret_cast<unsigned char*>( |
| 503 |
mbi.AllocationBase); |
| 504 |
__int64 i = 1; |
| 505 |
bool high_target = reinterpret_cast<__int64>(target) > UINT_MAX; |
| 506 |
while (pv == NULL) { |
| 507 |
__int64 val = reinterpret_cast<__int64>(allocation_base) - |
| 508 |
(i * granularity_); |
| 509 |
if (high_target && |
| 510 |
reinterpret_cast<__int64>(target) - val > INT_MAX) { |
| 511 |
// We're further than 2GB from the target |
| 512 |
break; |
| 513 |
} else if (val <= 0) { |
| 514 |
// Less than 0 |
| 515 |
break; |
| 516 |
} |
| 517 |
pv = ::VirtualAlloc(reinterpret_cast<void*>(allocation_base - |
| 518 |
(i++ * granularity_)), |
| 519 |
pagesize_, MEM_COMMIT | MEM_RESERVE, |
| 520 |
PAGE_EXECUTE_READWRITE); |
| 521 |
} |
| 522 |
|
| 523 |
// We couldn't allocate low, try to allocate high |
| 524 |
if (pv == NULL) { |
| 525 |
i = 1; |
| 526 |
// Round up to the next multiple of page granularity |
| 527 |
allocation_base = reinterpret_cast<unsigned char*>( |
| 528 |
(reinterpret_cast<__int64>(target) & |
| 529 |
(~(granularity_ - 1))) + granularity_); |
| 530 |
while (pv == NULL) { |
| 531 |
__int64 val = reinterpret_cast<__int64>(allocation_base) + |
| 532 |
(i * granularity_) - reinterpret_cast<__int64>(target); |
| 533 |
if (val > INT_MAX || val < 0) { |
| 534 |
// We're too far or we overflowed |
| 535 |
break; |
| 536 |
} |
| 537 |
pv = ::VirtualAlloc(reinterpret_cast<void*>(allocation_base + |
| 538 |
(i++ * granularity_)), |
| 539 |
pagesize_, MEM_COMMIT | MEM_RESERVE, |
| 540 |
PAGE_EXECUTE_READWRITE); |
| 541 |
} |
| 542 |
} |
| 543 |
return pv; |
| 544 |
} |
| 545 |
|
| 546 |
bool PreamblePatcher::IsShortConditionalJump( |
| 547 |
unsigned char* target, |
| 548 |
unsigned int instruction_size) { |
| 549 |
return (*(target) & 0x70) == 0x70 && instruction_size == 2; |
| 550 |
} |
| 551 |
|
| 552 |
bool PreamblePatcher::IsShortJump( |
| 553 |
unsigned char* target, |
| 554 |
unsigned int instruction_size) { |
| 555 |
return target[0] == 0xeb && instruction_size == 2; |
| 556 |
} |
| 557 |
|
| 558 |
bool PreamblePatcher::IsNearConditionalJump( |
| 559 |
unsigned char* target, |
| 560 |
unsigned int instruction_size) { |
| 561 |
return *(target) == 0xf && (*(target + 1) & 0x80) == 0x80 && |
| 562 |
instruction_size == 6; |
| 563 |
} |
| 564 |
|
| 565 |
bool PreamblePatcher::IsNearRelativeJump( |
| 566 |
unsigned char* target, |
| 567 |
unsigned int instruction_size) { |
| 568 |
return *(target) == 0xe9 && instruction_size == 5; |
| 569 |
} |
| 570 |
|
| 571 |
bool PreamblePatcher::IsNearAbsoluteCall( |
| 572 |
unsigned char* target, |
| 573 |
unsigned int instruction_size) { |
| 574 |
return *(target) == 0xff && (*(target + 1) & 0x10) == 0x10 && |
| 575 |
instruction_size == 6; |
| 576 |
} |
| 577 |
|
| 578 |
bool PreamblePatcher::IsNearRelativeCall( |
| 579 |
unsigned char* target, |
| 580 |
unsigned int instruction_size) { |
| 581 |
return *(target) == 0xe8 && instruction_size == 5; |
| 582 |
} |
| 583 |
|
| 584 |
bool PreamblePatcher::IsMovWithDisplacement( |
| 585 |
unsigned char* target, |
| 586 |
unsigned int instruction_size) { |
| 587 |
// In this case, the ModRM byte's mod field will be 0 and r/m will be 101b (5) |
| 588 |
return instruction_size == 7 && *target == 0x48 && *(target + 1) == 0x8b && |
| 589 |
(*(target + 2) >> 6) == 0 && (*(target + 2) & 0x7) == 5; |
| 590 |
} |
| 591 |
|
| 592 |
SideStepError PreamblePatcher::PatchShortConditionalJump( |
| 593 |
unsigned char* source, |
| 594 |
unsigned int instruction_size, |
| 595 |
unsigned char* target, |
| 596 |
unsigned int* target_bytes, |
| 597 |
unsigned int target_size) { |
| 598 |
// note: rel8 offset is signed. Thus we need to ask for signed char |
| 599 |
// to negative offsets right |
| 600 |
unsigned char* original_jump_dest = (source + 2) + static_cast<signed char>(source[1]); |
| 601 |
unsigned char* stub_jump_from = target + 6; |
| 602 |
__int64 fixup_jump_offset = original_jump_dest - stub_jump_from; |
| 603 |
if (fixup_jump_offset > INT_MAX || fixup_jump_offset < INT_MIN) { |
| 604 |
SIDESTEP_ASSERT(false && |
| 605 |
"Unable to fix up short jump because target" |
| 606 |
" is too far away."); |
| 607 |
return SIDESTEP_JUMP_INSTRUCTION; |
| 608 |
} |
| 609 |
|
| 610 |
*target_bytes = 6; |
| 611 |
if (target_size > *target_bytes) { |
| 612 |
// Convert the short jump to a near jump. |
| 613 |
// |
| 614 |
// 0f 8x xx xx xx xx = Jcc rel32off |
| 615 |
unsigned short jmpcode = ((0x80 | (source[0] & 0xf)) << 8) | 0x0f; |
| 616 |
memcpy(reinterpret_cast<void*>(target), |
| 617 |
reinterpret_cast<void*>(&jmpcode), 2); |
| 618 |
memcpy(reinterpret_cast<void*>(target + 2), |
| 619 |
reinterpret_cast<void*>(&fixup_jump_offset), 4); |
| 620 |
} |
| 621 |
|
| 622 |
return SIDESTEP_SUCCESS; |
| 623 |
} |
| 624 |
|
| 625 |
SideStepError PreamblePatcher::PatchShortJump( |
| 626 |
unsigned char* source, |
| 627 |
unsigned int instruction_size, |
| 628 |
unsigned char* target, |
| 629 |
unsigned int* target_bytes, |
| 630 |
unsigned int target_size) { |
| 631 |
// note: rel8 offset is _signed_. Thus we need signed char here. |
| 632 |
unsigned char* original_jump_dest = (source + 2) + static_cast<signed char>(source[1]); |
| 633 |
unsigned char* stub_jump_from = target + 5; |
| 634 |
__int64 fixup_jump_offset = original_jump_dest - stub_jump_from; |
| 635 |
if (fixup_jump_offset > INT_MAX || fixup_jump_offset < INT_MIN) { |
| 636 |
SIDESTEP_ASSERT(false && |
| 637 |
"Unable to fix up short jump because target" |
| 638 |
" is too far away."); |
| 639 |
return SIDESTEP_JUMP_INSTRUCTION; |
| 640 |
} |
| 641 |
|
| 642 |
*target_bytes = 5; |
| 643 |
if (target_size > *target_bytes) { |
| 644 |
// Convert the short jump to a near jump. |
| 645 |
// |
| 646 |
// e9 xx xx xx xx = jmp rel32off |
| 647 |
target[0] = 0xe9; |
| 648 |
memcpy(reinterpret_cast<void*>(target + 1), |
| 649 |
reinterpret_cast<void*>(&fixup_jump_offset), 4); |
| 650 |
} |
| 651 |
|
| 652 |
return SIDESTEP_SUCCESS; |
| 653 |
} |
| 654 |
|
| 655 |
SideStepError PreamblePatcher::PatchNearJumpOrCall( |
| 656 |
unsigned char* source, |
| 657 |
unsigned int instruction_size, |
| 658 |
unsigned char* target, |
| 659 |
unsigned int* target_bytes, |
| 660 |
unsigned int target_size) { |
| 661 |
SIDESTEP_ASSERT(instruction_size == 5 || instruction_size == 6); |
| 662 |
unsigned int jmp_offset_in_instruction = instruction_size == 5 ? 1 : 2; |
| 663 |
unsigned char* original_jump_dest = reinterpret_cast<unsigned char *>( |
| 664 |
reinterpret_cast<__int64>(source + instruction_size) + |
| 665 |
*(reinterpret_cast<int*>(source + jmp_offset_in_instruction))); |
| 666 |
unsigned char* stub_jump_from = target + instruction_size; |
| 667 |
__int64 fixup_jump_offset = original_jump_dest - stub_jump_from; |
| 668 |
if (fixup_jump_offset > INT_MAX || fixup_jump_offset < INT_MIN) { |
| 669 |
SIDESTEP_ASSERT(false && |
| 670 |
"Unable to fix up near jump because target" |
| 671 |
" is too far away."); |
| 672 |
return SIDESTEP_JUMP_INSTRUCTION; |
| 673 |
} |
| 674 |
|
| 675 |
if ((fixup_jump_offset < SCHAR_MAX && fixup_jump_offset > SCHAR_MIN)) { |
| 676 |
*target_bytes = 2; |
| 677 |
if (target_size > *target_bytes) { |
| 678 |
// If the new offset is in range, use a short jump instead of a near jump. |
| 679 |
if (source[0] == ASM_JCC32REL_0 && |
| 680 |
(source[1] & ASM_JCC32REL_1_MASK) == ASM_JCC32REL_1_MASK) { |
| 681 |
unsigned short jmpcode = (static_cast<unsigned char>( |
| 682 |
fixup_jump_offset) << 8) | (0x70 | (source[1] & 0xf)); |
| 683 |
memcpy(reinterpret_cast<void*>(target), |
| 684 |
reinterpret_cast<void*>(&jmpcode), |
| 685 |
2); |
| 686 |
} else { |
| 687 |
target[0] = ASM_JMP8REL; |
| 688 |
target[1] = static_cast<unsigned char>(fixup_jump_offset); |
| 689 |
} |
| 690 |
} |
| 691 |
} else { |
| 692 |
*target_bytes = instruction_size; |
| 693 |
if (target_size > *target_bytes) { |
| 694 |
memcpy(reinterpret_cast<void*>(target), |
| 695 |
reinterpret_cast<void*>(source), |
| 696 |
jmp_offset_in_instruction); |
| 697 |
memcpy(reinterpret_cast<void*>(target + jmp_offset_in_instruction), |
| 698 |
reinterpret_cast<void*>(&fixup_jump_offset), |
| 699 |
4); |
| 700 |
} |
| 701 |
} |
| 702 |
|
| 703 |
return SIDESTEP_SUCCESS; |
| 704 |
} |
| 705 |
|
| 706 |
SideStepError PreamblePatcher::PatchMovWithDisplacement( |
| 707 |
unsigned char* source, |
| 708 |
unsigned int instruction_size, |
| 709 |
unsigned char* target, |
| 710 |
unsigned int* target_bytes, |
| 711 |
unsigned int target_size) { |
| 712 |
SIDESTEP_ASSERT(instruction_size == 7); |
| 713 |
const int mov_offset_in_instruction = 3; // 0x48 0x8b 0x0d <offset> |
| 714 |
unsigned char* original_mov_dest = reinterpret_cast<unsigned char*>( |
| 715 |
reinterpret_cast<__int64>(source + instruction_size) + |
| 716 |
*(reinterpret_cast<int*>(source + mov_offset_in_instruction))); |
| 717 |
unsigned char* stub_mov_from = target + instruction_size; |
| 718 |
__int64 fixup_mov_offset = original_mov_dest - stub_mov_from; |
| 719 |
if (fixup_mov_offset > INT_MAX || fixup_mov_offset < INT_MIN) { |
| 720 |
SIDESTEP_ASSERT(false && |
| 721 |
"Unable to fix up near MOV because target is too far away."); |
| 722 |
return SIDESTEP_UNEXPECTED; |
| 723 |
} |
| 724 |
*target_bytes = instruction_size; |
| 725 |
if (target_size > *target_bytes) { |
| 726 |
memcpy(reinterpret_cast<void*>(target), |
| 727 |
reinterpret_cast<void*>(source), |
| 728 |
mov_offset_in_instruction); |
| 729 |
memcpy(reinterpret_cast<void*>(target + mov_offset_in_instruction), |
| 730 |
reinterpret_cast<void*>(&fixup_mov_offset), |
| 731 |
4); |
| 732 |
} |
| 733 |
return SIDESTEP_SUCCESS; |
| 734 |
} |
| 735 |
|
| 736 |
}; // namespace sidestep |