forked from gzc9047/CppFreeMock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runtime_patch.h
59 lines (46 loc) · 1.81 KB
/
runtime_patch.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Copyright 2014 Louix Gu
// Author: [email protected] (Louix Gu)
// CppFreeMock: a tool for mock global function, member function, class static function.
//
// Check os and include the special implement.
#ifndef CPP_FREE_MOCK_RUNTIME_PATCH_H_
#define CPP_FREE_MOCK_RUNTIME_PATCH_H_
#include <vector>
namespace CppFreeMock {
namespace RuntimePatcherImpl {
// Need impl in architecture relevant file.
// OS
static int UnprotectMemoryForOnePage(void* const address);
// CPU
static int SetJump(void* const address, const void* const destination, std::vector<char>& binary_backup);
static void RevertJump(void* address, const std::vector<char>& binary_backup);
}
} // namespace CppFreeMock
#if defined(__x86_64__) || defined(__i386__)
#include "x86/runtime_patch_impl.h"
#endif
#ifdef __APPLE__
#include "posix/runtime_patch_impl.h"
#elif __linux__
#include "posix/runtime_patch_impl.h"
#endif
namespace CppFreeMock {
// Provide 2 interface, GraftFunction and RevertGraft.
struct RuntimePatcher {
template < typename F1, typename F2 >
static int GraftFunction(F1 address, F2 destination, std::vector<char>& binary_backup) {
void* function = reinterpret_cast<void*>((std::size_t&)address);
if (0 != RuntimePatcherImpl::UnprotectMemoryForOnePage(function)) {
std::abort();
} else {
// For mock std::abort, this need not after the 'if'.
return RuntimePatcherImpl::SetJump(function, reinterpret_cast<void*>((std::size_t&)destination), binary_backup);
}
}
template < typename F >
static void RevertGraft(F address, const std::vector<char>& binary_backup) {
RuntimePatcherImpl::RevertJump(reinterpret_cast<void*>((std::size_t&)address), binary_backup);
}
};
} // namespace CppFreeMock
#endif // CPP_FREE_MOCK_RUNTIME_PATCH_H_