Debian Codegraph @

extra/gperftools/gperftools-2.15/src/windows/preamble_patcher.h

raw
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 * Definition of PreamblePatcher
36 */
37
38 #ifndef GOOGLE_PERFTOOLS_PREAMBLE_PATCHER_H_
39 #define GOOGLE_PERFTOOLS_PREAMBLE_PATCHER_H_
40
41 #include "config.h"
42 #include <windows.h>
43
44 // compatibility shim
45 #include "base/logging.h"
46 #define SIDESTEP_ASSERT(cond) RAW_DCHECK(cond, #cond)
47 #define SIDESTEP_LOG(msg) RAW_VLOG(1, msg)
48
49 // Maximum size of the preamble stub. We overwrite at least the first 5
50 // bytes of the function. Considering the worst case scenario, we need 4
51 // bytes + the max instruction size + 5 more bytes for our jump back to
52 // the original code. With that in mind, 32 is a good number :)
53 #ifdef _M_X64
54 // In 64-bit mode we may need more room. In 64-bit mode all jumps must be
55 // within +/-2GB of RIP. Because of this limitation we may need to use a
56 // trampoline to jump to the replacement function if it is further than 2GB
57 // away from the target. The trampoline is 14 bytes.
58 //
59 // So 4 bytes + max instruction size (17 bytes) + 5 bytes to jump back to the
60 // original code + trampoline size. 64 bytes is a nice number :-)
61 #define MAX_PREAMBLE_STUB_SIZE (64)
62 #else
63 #define MAX_PREAMBLE_STUB_SIZE (32)
64 #endif
65
66 // Determines if this is a 64-bit binary.
67 #ifdef _M_X64
68 static const bool kIs64BitBinary = true;
69 #else
70 static const bool kIs64BitBinary = false;
71 #endif
72
73 namespace sidestep {
74
75 // Possible results of patching/unpatching
76 enum SideStepError {
77 SIDESTEP_SUCCESS = 0,
78 SIDESTEP_INVALID_PARAMETER,
79 SIDESTEP_INSUFFICIENT_BUFFER,
80 SIDESTEP_JUMP_INSTRUCTION,
81 SIDESTEP_FUNCTION_TOO_SMALL,
82 SIDESTEP_UNSUPPORTED_INSTRUCTION,
83 SIDESTEP_NO_SUCH_MODULE,
84 SIDESTEP_NO_SUCH_FUNCTION,
85 SIDESTEP_ACCESS_DENIED,
86 SIDESTEP_UNEXPECTED,
87 };
88
89 #define SIDESTEP_TO_HRESULT(error) \
90 MAKE_HRESULT(SEVERITY_ERROR, FACILITY_NULL, error)
91
92 class DeleteUnsignedCharArray;
93
94 // Implements a patching mechanism that overwrites the first few bytes of
95 // a function preamble with a jump to our hook function, which is then
96 // able to call the original function via a specially-made preamble-stub
97 // that imitates the action of the original preamble.
98 //
99 // NOTE: This patching mechanism should currently only be used for
100 // non-production code, e.g. unit tests, because it is not threadsafe.
101 // See the TODO in preamble_patcher_with_stub.cc for instructions on what
102 // we need to do before using it in production code; it's fairly simple
103 // but unnecessary for now since we only intend to use it in unit tests.
104 //
105 // To patch a function, use either of the typesafe Patch() methods. You
106 // can unpatch a function using Unpatch().
107 //
108 // Typical usage goes something like this:
109 // @code
110 // typedef int (*MyTypesafeFuncPtr)(int x);
111 // MyTypesafeFuncPtr original_func_stub;
112 // int MyTypesafeFunc(int x) { return x + 1; }
113 // int HookMyTypesafeFunc(int x) { return 1 + original_func_stub(x); }
114 //
115 // void MyPatchInitializingFunction() {
116 // original_func_stub = PreamblePatcher::Patch(
117 // MyTypesafeFunc, HookMyTypesafeFunc);
118 // if (!original_func_stub) {
119 // // ... error handling ...
120 // }
121 //
122 // // ... continue - you have patched the function successfully ...
123 // }
124 // @endcode
125 //
126 // Note that there are a number of ways that this method of patching can
127 // fail. The most common are:
128 // - If there is a jump (jxx) instruction in the first 5 bytes of
129 // the function being patched, we cannot patch it because in the
130 // current implementation we do not know how to rewrite relative
131 // jumps after relocating them to the preamble-stub. Note that
132 // if you really really need to patch a function like this, it
133 // would be possible to add this functionality (but at some cost).
134 // - If there is a return (ret) instruction in the first 5 bytes
135 // we cannot patch the function because it may not be long enough
136 // for the jmp instruction we use to inject our patch.
137 // - If there is another thread currently executing within the bytes
138 // that are copied to the preamble stub, it will crash in an undefined
139 // way.
140 //
141 // If you get any other error than the above, you're either pointing the
142 // patcher at an invalid instruction (e.g. into the middle of a multi-
143 // byte instruction, or not at memory containing executable instructions)
144 // or, there may be a bug in the disassembler we use to find
145 // instruction boundaries.
146 //
147 // NOTE: In optimized builds, when you have very trivial functions that
148 // the compiler can reason do not have side effects, the compiler may
149 // reuse the result of calling the function with a given parameter, which
150 // may mean if you patch the function in between your patch will never get
151 // invoked. See preamble_patcher_test.cc for an example.
152 class PERFTOOLS_DLL_DECL PreamblePatcher {
153 public:
154
155 // This is a typesafe version of RawPatch(), identical in all other
156 // ways than it takes a template parameter indicating the type of the
157 // function being patched.
158 //
159 // @param T The type of the function you are patching. Usually
160 // you will establish this type using a typedef, as in the following
161 // example:
162 // @code
163 // typedef BOOL (WINAPI *MessageBoxPtr)(HWND, LPCTSTR, LPCTSTR, UINT);
164 // MessageBoxPtr original = NULL;
165 // PreamblePatcher::Patch(MessageBox, Hook_MessageBox, &original);
166 // @endcode
167 template <class T>
168 static SideStepError Patch(T target_function,
169 T replacement_function,
170 T* original_function_stub) {
171 // NOTE: casting from a function to a pointer is contra the C++
172 // spec. It's not safe on IA64, but is on i386. We use
173 // a C-style cast here to emphasize this is not legal C++.
174 return RawPatch((void*)(target_function),
175 (void*)(replacement_function),
176 (void**)(original_function_stub));
177 }
178
179 // Patches a named function imported from the named module using
180 // preamble patching. Uses RawPatch() to do the actual patching
181 // work.
182 //
183 // @param T The type of the function you are patching. Must
184 // exactly match the function you specify using module_name and
185 // function_name.
186 //
187 // @param module_name The name of the module from which the function
188 // is being imported. Note that the patch will fail if this module
189 // has not already been loaded into the current process.
190 //
191 // @param function_name The name of the function you wish to patch.
192 //
193 // @param replacement_function Your replacement function which
194 // will be called whenever code tries to call the original function.
195 //
196 // @param original_function_stub Pointer to memory that should receive a
197 // pointer that can be used (e.g. in the replacement function) to call the
198 // original function, or NULL to indicate failure.
199 //
200 // @return One of the EnSideStepError error codes; only SIDESTEP_SUCCESS
201 // indicates success.
202 template <class T>
203 static SideStepError Patch(LPCTSTR module_name,
204 LPCSTR function_name,
205 T replacement_function,
206 T* original_function_stub) {
207 SIDESTEP_ASSERT(module_name && function_name);
208 if (!module_name || !function_name) {
209 SIDESTEP_ASSERT(false &&
210 "You must specify a module name and function name.");
211 return SIDESTEP_INVALID_PARAMETER;
212 }
213 HMODULE module = ::GetModuleHandle(module_name);
214 SIDESTEP_ASSERT(module != NULL);
215 if (!module) {
216 SIDESTEP_ASSERT(false && "Invalid module name.");
217 return SIDESTEP_NO_SUCH_MODULE;
218 }
219 FARPROC existing_function = ::GetProcAddress(module, function_name);
220 if (!existing_function) {
221 SIDESTEP_ASSERT(
222 false && "Did not find any function with that name in the module.");
223 return SIDESTEP_NO_SUCH_FUNCTION;
224 }
225 // NOTE: casting from a function to a pointer is contra the C++
226 // spec. It's not safe on IA64, but is on i386. We use
227 // a C-style cast here to emphasize this is not legal C++.
228 return RawPatch((void*)existing_function, (void*)replacement_function,
229 (void**)(original_function_stub));
230 }
231
232 // Patches a function by overwriting its first few bytes with
233 // a jump to a different function. This is the "worker" function
234 // for each of the typesafe Patch() functions. In most cases,
235 // it is preferable to use the Patch() functions rather than
236 // this one as they do more checking at compile time.
237 //
238 // @param target_function A pointer to the function that should be
239 // patched.
240 //
241 // @param replacement_function A pointer to the function that should
242 // replace the target function. The replacement function must have
243 // exactly the same calling convention and parameters as the original
244 // function.
245 //
246 // @param original_function_stub Pointer to memory that should receive a
247 // pointer that can be used (e.g. in the replacement function) to call the
248 // original function, or NULL to indicate failure.
249 //
250 // @param original_function_stub Pointer to memory that should receive a
251 // pointer that can be used (e.g. in the replacement function) to call the
252 // original function, or NULL to indicate failure.
253 //
254 // @return One of the EnSideStepError error codes; only SIDESTEP_SUCCESS
255 // indicates success.
256 //
257 // @note The preamble-stub (the memory pointed to by
258 // *original_function_stub) is allocated on the heap, and (in
259 // production binaries) never destroyed, resulting in a memory leak. This
260 // will be the case until we implement safe unpatching of a method.
261 // However, it is quite difficult to unpatch a method (because other
262 // threads in the process may be using it) so we are leaving it for now.
263 // See however UnsafeUnpatch, which can be used for binaries where you
264 // know only one thread is running, e.g. unit tests.
265 static SideStepError RawPatch(void* target_function,
266 void* replacement_function,
267 void** original_function_stub);
268
269 // Unpatches target_function and deletes the stub that previously could be
270 // used to call the original version of the function.
271 //
272 // DELETES the stub that is passed to the function.
273 //
274 // @param target_function Pointer to the target function which was
275 // previously patched, i.e. a pointer which value should match the value
276 // of the symbol prior to patching it.
277 //
278 // @param replacement_function Pointer to the function target_function
279 // was patched to.
280 //
281 // @param original_function_stub Pointer to the stub returned when
282 // patching, that could be used to call the original version of the
283 // patched function. This function will also delete the stub, which after
284 // unpatching is useless.
285 //
286 // If your original call was
287 // Patch(VirtualAlloc, MyVirtualAlloc, &origptr)
288 // then to undo it you would call
289 // Unpatch(VirtualAlloc, MyVirtualAlloc, origptr);
290 //
291 // @return One of the EnSideStepError error codes; only SIDESTEP_SUCCESS
292 // indicates success.
293 static SideStepError Unpatch(void* target_function,
294 void* replacement_function,
295 void* original_function_stub);
296
297 // A helper routine when patching, which follows jmp instructions at
298 // function addresses, to get to the "actual" function contents.
299 // This allows us to identify two functions that are at different
300 // addresses but actually resolve to the same code.
301 //
302 // @param target_function Pointer to a function.
303 //
304 // @return Either target_function (the input parameter), or if
305 // target_function's body consists entirely of a JMP instruction,
306 // the address it JMPs to (or more precisely, the address at the end
307 // of a chain of JMPs).
308 template <class T>
309 static T ResolveTarget(T target_function) {
310 return (T)ResolveTargetImpl((unsigned char*)target_function, NULL);
311 }
312
313 // Allocates a block of memory of size MAX_PREAMBLE_STUB_SIZE that is as
314 // close (within 2GB) as possible to target. This is done to ensure that
315 // we can perform a relative jump from target to a trampoline if the
316 // replacement function is > +-2GB from target. This means that we only need
317 // to patch 5 bytes in the target function.
318 //
319 // @param target Pointer to target function.
320 //
321 // @return Returns a block of memory of size MAX_PREAMBLE_STUB_SIZE that can
322 // be used to store a function preamble block.
323 static unsigned char* AllocPreambleBlockNear(void* target);
324
325 // Frees a block allocated by AllocPreambleBlockNear.
326 //
327 // @param block Block that was returned by AllocPreambleBlockNear.
328 static void FreePreambleBlock(unsigned char* block);
329
330 private:
331 friend class DeleteUnsignedCharArray;
332
333 // Used to store data allocated for preamble stubs
334 struct PreamblePage {
335 unsigned int magic_;
336 PreamblePage* next_;
337 // This member points to a linked list of free blocks within the page
338 // or NULL if at the end
339 void* free_;
340 };
341
342 // In 64-bit mode, the replacement function must be within 2GB of the original
343 // target in order to only require 5 bytes for the function patch. To meet
344 // this requirement we're creating an allocator within this class to
345 // allocate blocks that are within 2GB of a given target. This member is the
346 // head of a linked list of pages used to allocate blocks that are within
347 // 2GB of the target.
348 static PreamblePage* preamble_pages_;
349
350 // Page granularity
351 static long granularity_;
352
353 // Page size
354 static long pagesize_;
355
356 // Determines if the patcher has been initialized.
357 static bool initialized_;
358
359 // Used to initialize static members.
360 static void Initialize();
361
362 // Patches a function by overwriting its first few bytes with
363 // a jump to a different function. This is similar to the RawPatch
364 // function except that it uses the stub allocated by the caller
365 // instead of allocating it.
366 //
367 // We call VirtualProtect to make the
368 // target function writable at least for the duration of the call.
369 //
370 // @param target_function A pointer to the function that should be
371 // patched.
372 //
373 // @param replacement_function A pointer to the function that should
374 // replace the target function. The replacement function must have
375 // exactly the same calling convention and parameters as the original
376 // function.
377 //
378 // @param preamble_stub A pointer to a buffer where the preamble stub
379 // should be copied. The size of the buffer should be sufficient to
380 // hold the preamble bytes.
381 //
382 // @param stub_size Size in bytes of the buffer allocated for the
383 // preamble_stub
384 //
385 // @param bytes_needed Pointer to a variable that receives the minimum
386 // number of bytes required for the stub. Can be set to NULL if you're
387 // not interested.
388 //
389 // @return An error code indicating the result of patching.
390 static SideStepError RawPatchWithStubAndProtections(
391 void* target_function,
392 void* replacement_function,
393 unsigned char* preamble_stub,
394 unsigned long stub_size,
395 unsigned long* bytes_needed);
396
397 // A helper function used by RawPatchWithStubAndProtections -- it
398 // does everything but the VirtualProtect work. Defined in
399 // preamble_patcher_with_stub.cc.
400 //
401 // @param target_function A pointer to the function that should be
402 // patched.
403 //
404 // @param replacement_function A pointer to the function that should
405 // replace the target function. The replacement function must have
406 // exactly the same calling convention and parameters as the original
407 // function.
408 //
409 // @param preamble_stub A pointer to a buffer where the preamble stub
410 // should be copied. The size of the buffer should be sufficient to
411 // hold the preamble bytes.
412 //
413 // @param stub_size Size in bytes of the buffer allocated for the
414 // preamble_stub
415 //
416 // @param bytes_needed Pointer to a variable that receives the minimum
417 // number of bytes required for the stub. Can be set to NULL if you're
418 // not interested.
419 //
420 // @return An error code indicating the result of patching.
421 static SideStepError RawPatchWithStub(void* target_function,
422 void* replacement_function,
423 unsigned char* preamble_stub,
424 unsigned long stub_size,
425 unsigned long* bytes_needed);
426
427
428 // A helper routine when patching, which follows jmp instructions at
429 // function addresses, to get to the "actual" function contents.
430 // This allows us to identify two functions that are at different
431 // addresses but actually resolve to the same code.
432 //
433 // @param target_function Pointer to a function.
434 //
435 // @param stop_before If, when following JMP instructions from
436 // target_function, we get to the address stop, we return
437 // immediately, the address that jumps to stop_before.
438 //
439 // @param stop_before_trampoline When following JMP instructions from
440 // target_function, stop before a trampoline is detected. See comment in
441 // PreamblePatcher::RawPatchWithStub for more information. This parameter
442 // has no effect in 32-bit mode.
443 //
444 // @return Either target_function (the input parameter), or if
445 // target_function's body consists entirely of a JMP instruction,
446 // the address it JMPs to (or more precisely, the address at the end
447 // of a chain of JMPs).
448 static void* ResolveTargetImpl(unsigned char* target_function,
449 unsigned char* stop_before,
450 bool stop_before_trampoline = false);
451
452 // Helper routine that attempts to allocate a page as close (within 2GB)
453 // as possible to target.
454 //
455 // @param target Pointer to target function.
456 //
457 // @return Returns an address that is within 2GB of target.
458 static void* AllocPageNear(void* target);
459
460 // Helper routine that determines if a target instruction is a short
461 // conditional jump.
462 //
463 // @param target Pointer to instruction.
464 //
465 // @param instruction_size Size of the instruction in bytes.
466 //
467 // @return Returns true if the instruction is a short conditional jump.
468 static bool IsShortConditionalJump(unsigned char* target,
469 unsigned int instruction_size);
470
471 static bool IsShortJump(unsigned char *target, unsigned int instruction_size);
472
473 // Helper routine that determines if a target instruction is a near
474 // conditional jump.
475 //
476 // @param target Pointer to instruction.
477 //
478 // @param instruction_size Size of the instruction in bytes.
479 //
480 // @return Returns true if the instruction is a near conditional jump.
481 static bool IsNearConditionalJump(unsigned char* target,
482 unsigned int instruction_size);
483
484 // Helper routine that determines if a target instruction is a near
485 // relative jump.
486 //
487 // @param target Pointer to instruction.
488 //
489 // @param instruction_size Size of the instruction in bytes.
490 //
491 // @return Returns true if the instruction is a near absolute jump.
492 static bool IsNearRelativeJump(unsigned char* target,
493 unsigned int instruction_size);
494
495 // Helper routine that determines if a target instruction is a near
496 // absolute call.
497 //
498 // @param target Pointer to instruction.
499 //
500 // @param instruction_size Size of the instruction in bytes.
501 //
502 // @return Returns true if the instruction is a near absolute call.
503 static bool IsNearAbsoluteCall(unsigned char* target,
504 unsigned int instruction_size);
505
506 // Helper routine that determines if a target instruction is a near
507 // absolute call.
508 //
509 // @param target Pointer to instruction.
510 //
511 // @param instruction_size Size of the instruction in bytes.
512 //
513 // @return Returns true if the instruction is a near absolute call.
514 static bool IsNearRelativeCall(unsigned char* target,
515 unsigned int instruction_size);
516
517 // Helper routine that determines if a target instruction is a 64-bit MOV
518 // that uses a RIP-relative displacement.
519 //
520 // @param target Pointer to instruction.
521 //
522 // @param instruction_size Size of the instruction in bytes.
523 //
524 // @return Returns true if the instruction is a MOV with displacement.
525 static bool IsMovWithDisplacement(unsigned char* target,
526 unsigned int instruction_size);
527
528 // Helper routine that converts a short conditional jump instruction
529 // to a near conditional jump in a target buffer. Note that the target
530 // buffer must be within 2GB of the source for the near jump to work.
531 //
532 // A short conditional jump instruction is in the format:
533 // 7x xx = Jcc rel8off
534 //
535 // @param source Pointer to instruction.
536 //
537 // @param instruction_size Size of the instruction.
538 //
539 // @param target Target buffer to write the new instruction.
540 //
541 // @param target_bytes Pointer to a buffer that contains the size
542 // of the target instruction, in bytes.
543 //
544 // @param target_size Size of the target buffer.
545 //
546 // @return Returns SIDESTEP_SUCCESS if successful, otherwise an error.
547 static SideStepError PatchShortConditionalJump(unsigned char* source,
548 unsigned int instruction_size,
549 unsigned char* target,
550 unsigned int* target_bytes,
551 unsigned int target_size);
552
553 static SideStepError PatchShortJump(unsigned char* source,
554 unsigned int instruction_size,
555 unsigned char* target,
556 unsigned int* target_bytes,
557 unsigned int target_size);
558
559 // Helper routine that converts an instruction that will convert various
560 // jump-like instructions to corresponding instructions in the target buffer.
561 // What this routine does is fix up the relative offsets contained in jump
562 // instructions to point back to the original target routine. Like with
563 // PatchShortConditionalJump, the target buffer must be within 2GB of the
564 // source.
565 //
566 // We currently handle the following instructions:
567 //
568 // E9 xx xx xx xx = JMP rel32off
569 // 0F 8x xx xx xx xx = Jcc rel32off
570 // FF /2 xx xx xx xx = CALL reg/mem32/mem64
571 // E8 xx xx xx xx = CALL rel32off
572 //
573 // It should not be hard to update this function to support other
574 // instructions that jump to relative targets.
575 //
576 // @param source Pointer to instruction.
577 //
578 // @param instruction_size Size of the instruction.
579 //
580 // @param target Target buffer to write the new instruction.
581 //
582 // @param target_bytes Pointer to a buffer that contains the size
583 // of the target instruction, in bytes.
584 //
585 // @param target_size Size of the target buffer.
586 //
587 // @return Returns SIDESTEP_SUCCESS if successful, otherwise an error.
588 static SideStepError PatchNearJumpOrCall(unsigned char* source,
589 unsigned int instruction_size,
590 unsigned char* target,
591 unsigned int* target_bytes,
592 unsigned int target_size);
593
594 // Helper routine that patches a 64-bit MOV instruction with a RIP-relative
595 // displacement. The target buffer must be within 2GB of the source.
596 //
597 // 48 8B 0D XX XX XX XX = MOV rel32off
598 //
599 // @param source Pointer to instruction.
600 //
601 // @param instruction_size Size of the instruction.
602 //
603 // @param target Target buffer to write the new instruction.
604 //
605 // @param target_bytes Pointer to a buffer that contains the size
606 // of the target instruction, in bytes.
607 //
608 // @param target_size Size of the target buffer.
609 //
610 // @return Returns SIDESTEP_SUCCESS if successful, otherwise an error.
611 static SideStepError PatchMovWithDisplacement(unsigned char* source,
612 unsigned int instruction_size,
613 unsigned char* target,
614 unsigned int* target_bytes,
615 unsigned int target_size);
616 };
617
618 }; // namespace sidestep
619
620 #endif // GOOGLE_PERFTOOLS_PREAMBLE_PATCHER_H_