Debian Codegraph @

extra/gperftools/gperftools-2.15/src/windows/preamble_patcher_with_stub.cc

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 * Implementation of PreamblePatcher
36 */
37
38 #include "preamble_patcher.h"
39
40 #include "mini_disassembler.h"
41
42 // Definitions of assembly statements we need
43 #define ASM_JMP32REL 0xE9
44 #define ASM_INT3 0xCC
45 #define ASM_NOP 0x90
46 // X64 opcodes
47 #define ASM_MOVRAX_IMM 0xB8
48 #define ASM_REXW 0x48
49 #define ASM_JMP 0xFF
50 #define ASM_JMP_RAX 0xE0
51 #define ASM_PUSH 0x68
52 #define ASM_RET 0xC3
53
54 namespace sidestep {
55
56 SideStepError PreamblePatcher::RawPatchWithStub(
57 void* target_function,
58 void* replacement_function,
59 unsigned char* preamble_stub,
60 unsigned long stub_size,
61 unsigned long* bytes_needed) {
62 if ((NULL == target_function) ||
63 (NULL == replacement_function) ||
64 (NULL == preamble_stub)) {
65 SIDESTEP_ASSERT(false &&
66 "Invalid parameters - either pTargetFunction or "
67 "pReplacementFunction or pPreambleStub were NULL.");
68 return SIDESTEP_INVALID_PARAMETER;
69 }
70
71 // TODO(V7:joi) Siggi and I just had a discussion and decided that both
72 // patching and unpatching are actually unsafe. We also discussed a
73 // method of making it safe, which is to freeze all other threads in the
74 // process, check their thread context to see if their eip is currently
75 // inside the block of instructions we need to copy to the stub, and if so
76 // wait a bit and try again, then unfreeze all threads once we've patched.
77 // Not implementing this for now since we're only using SideStep for unit
78 // testing, but if we ever use it for production code this is what we
79 // should do.
80 //
81 // NOTE: Stoyan suggests we can write 8 or even 10 bytes atomically using
82 // FPU instructions, and on newer processors we could use cmpxchg8b or
83 // cmpxchg16b. So it might be possible to do the patching/unpatching
84 // atomically and avoid having to freeze other threads. Note though, that
85 // doing it atomically does not help if one of the other threads happens
86 // to have its eip in the middle of the bytes you change while you change
87 // them.
88 unsigned char* target = reinterpret_cast<unsigned char*>(target_function);
89 unsigned int required_trampoline_bytes = 0;
90 const unsigned int kRequiredStubJumpBytes = 5;
91 const unsigned int kRequiredTargetPatchBytes = 5;
92
93 // Initialize the stub with INT3's just in case.
94 if (stub_size) {
95 memset(preamble_stub, 0xcc, stub_size);
96 }
97 if (kIs64BitBinary) {
98 // In 64-bit mode JMP instructions are always relative to RIP. If the
99 // replacement - target offset is > 2GB, we can't JMP to the replacement
100 // function. In this case, we're going to use a trampoline - that is,
101 // we're going to do a relative jump to a small chunk of code in the stub
102 // that will then do the absolute jump to the replacement function. By
103 // doing this, we only need to patch 5 bytes in the target function, as
104 // opposed to patching 12 bytes if we were to do an absolute jump.
105 //
106 // Note that the first byte of the trampoline is a NOP instruction. This
107 // is used as a trampoline signature that will be detected when unpatching
108 // the function.
109 //
110 // jmp <trampoline>
111 //
112 // trampoline:
113 // nop
114 // mov rax, <replacement_function>
115 // jmp rax
116 //
117 __int64 replacement_target_offset = reinterpret_cast<__int64>(
118 replacement_function) - reinterpret_cast<__int64>(target) - 5;
119 if (replacement_target_offset > INT_MAX
120 || replacement_target_offset < INT_MIN) {
121 // The stub needs to be within 2GB of the target for the trampoline to
122 // work!
123 __int64 trampoline_offset = reinterpret_cast<__int64>(preamble_stub)
124 - reinterpret_cast<__int64>(target) - 5;
125 if (trampoline_offset > INT_MAX || trampoline_offset < INT_MIN) {
126 // We're screwed.
127 SIDESTEP_ASSERT(false
128 && "Preamble stub is too far from target to patch.");
129 return SIDESTEP_UNEXPECTED;
130 }
131 required_trampoline_bytes = 13;
132 }
133 }
134
135 // Let's disassemble the preamble of the target function to see if we can
136 // patch, and to see how much of the preamble we need to take. We need 5
137 // bytes for our jmp instruction, so let's find the minimum number of
138 // instructions to get 5 bytes.
139 MiniDisassembler disassembler;
140 unsigned int preamble_bytes = 0;
141 unsigned int stub_bytes = 0;
142 while (preamble_bytes < kRequiredTargetPatchBytes) {
143 unsigned int cur_bytes = 0;
144 InstructionType instruction_type =
145 disassembler.Disassemble(target + preamble_bytes, cur_bytes);
146 if (IT_JUMP == instruction_type) {
147 unsigned int jump_bytes = 0;
148 SideStepError jump_ret = SIDESTEP_JUMP_INSTRUCTION;
149 if (IsShortConditionalJump(target + preamble_bytes, cur_bytes)) {
150 jump_ret = PatchShortConditionalJump(target + preamble_bytes, cur_bytes,
151 preamble_stub + stub_bytes,
152 &jump_bytes,
153 stub_size - stub_bytes);
154 } else if (IsShortJump(target + preamble_bytes, cur_bytes)) {
155 jump_ret = PatchShortJump(target + preamble_bytes, cur_bytes,
156 preamble_stub + stub_bytes,
157 &jump_bytes,
158 stub_size - stub_bytes);
159 } else if (IsNearConditionalJump(target + preamble_bytes, cur_bytes) ||
160 IsNearRelativeJump(target + preamble_bytes, cur_bytes) ||
161 IsNearAbsoluteCall(target + preamble_bytes, cur_bytes) ||
162 IsNearRelativeCall(target + preamble_bytes, cur_bytes)) {
163 jump_ret = PatchNearJumpOrCall(target + preamble_bytes, cur_bytes,
164 preamble_stub + stub_bytes, &jump_bytes,
165 stub_size - stub_bytes);
166 }
167 if (jump_ret != SIDESTEP_SUCCESS) {
168 SIDESTEP_ASSERT(false &&
169 "Unable to patch because there is an unhandled branch "
170 "instruction in the initial preamble bytes.");
171 return SIDESTEP_JUMP_INSTRUCTION;
172 }
173 stub_bytes += jump_bytes;
174 } else if (IT_RETURN == instruction_type) {
175 SIDESTEP_ASSERT(false &&
176 "Unable to patch because function is too short");
177 return SIDESTEP_FUNCTION_TOO_SMALL;
178 } else if (IT_GENERIC == instruction_type) {
179 if (IsMovWithDisplacement(target + preamble_bytes, cur_bytes)) {
180 unsigned int mov_bytes = 0;
181 if (PatchMovWithDisplacement(target + preamble_bytes, cur_bytes,
182 preamble_stub + stub_bytes, &mov_bytes,
183 stub_size - stub_bytes)
184 != SIDESTEP_SUCCESS) {
185 return SIDESTEP_UNSUPPORTED_INSTRUCTION;
186 }
187 stub_bytes += mov_bytes;
188 } else {
189 memcpy(reinterpret_cast<void*>(preamble_stub + stub_bytes),
190 reinterpret_cast<void*>(target + preamble_bytes), cur_bytes);
191 stub_bytes += cur_bytes;
192 }
193 } else {
194 SIDESTEP_ASSERT(false &&
195 "Disassembler encountered unsupported instruction "
196 "(either unused or unknown");
197 return SIDESTEP_UNSUPPORTED_INSTRUCTION;
198 }
199 preamble_bytes += cur_bytes;
200 }
201
202 if (NULL != bytes_needed)
203 *bytes_needed = stub_bytes + kRequiredStubJumpBytes
204 + required_trampoline_bytes;
205
206 // Inv: cbPreamble is the number of bytes (at least 5) that we need to take
207 // from the preamble to have whole instructions that are 5 bytes or more
208 // in size total. The size of the stub required is cbPreamble +
209 // kRequiredStubJumpBytes (5) + required_trampoline_bytes (0 or 13)
210 if (stub_bytes + kRequiredStubJumpBytes + required_trampoline_bytes
211 > stub_size) {
212 SIDESTEP_ASSERT(false);
213 return SIDESTEP_INSUFFICIENT_BUFFER;
214 }
215
216 // Now, make a jmp instruction to the rest of the target function (minus the
217 // preamble bytes we moved into the stub) and copy it into our preamble-stub.
218 // find address to jump to, relative to next address after jmp instruction
219 #ifdef _MSC_VER
220 #pragma warning(push)
221 #pragma warning(disable:4244)
222 #endif
223 int relative_offset_to_target_rest
224 = ((reinterpret_cast<unsigned char*>(target) + preamble_bytes) -
225 (preamble_stub + stub_bytes + kRequiredStubJumpBytes));
226 #ifdef _MSC_VER
227 #pragma warning(pop)
228 #endif
229 // jmp (Jump near, relative, displacement relative to next instruction)
230 preamble_stub[stub_bytes] = ASM_JMP32REL;
231 // copy the address
232 memcpy(reinterpret_cast<void*>(preamble_stub + stub_bytes + 1),
233 reinterpret_cast<void*>(&relative_offset_to_target_rest), 4);
234
235 if (kIs64BitBinary && required_trampoline_bytes != 0) {
236 // Construct the trampoline
237 unsigned int trampoline_pos = stub_bytes + kRequiredStubJumpBytes;
238 preamble_stub[trampoline_pos] = ASM_NOP;
239 preamble_stub[trampoline_pos + 1] = ASM_REXW;
240 preamble_stub[trampoline_pos + 2] = ASM_MOVRAX_IMM;
241 memcpy(reinterpret_cast<void*>(preamble_stub + trampoline_pos + 3),
242 reinterpret_cast<void*>(&replacement_function),
243 sizeof(void *));
244 preamble_stub[trampoline_pos + 11] = ASM_JMP;
245 preamble_stub[trampoline_pos + 12] = ASM_JMP_RAX;
246
247 // Now update replacement_function to point to the trampoline
248 replacement_function = preamble_stub + trampoline_pos;
249 }
250
251 // Inv: preamble_stub points to assembly code that will execute the
252 // original function by first executing the first cbPreamble bytes of the
253 // preamble, then jumping to the rest of the function.
254
255 // Overwrite the first 5 bytes of the target function with a jump to our
256 // replacement function.
257 // (Jump near, relative, displacement relative to next instruction)
258 target[0] = ASM_JMP32REL;
259
260 // Find offset from instruction after jmp, to the replacement function.
261 #ifdef _MSC_VER
262 #pragma warning(push)
263 #pragma warning(disable:4244)
264 #endif
265 int offset_to_replacement_function =
266 reinterpret_cast<unsigned char*>(replacement_function) -
267 reinterpret_cast<unsigned char*>(target) - 5;
268 #ifdef _MSC_VER
269 #pragma warning(pop)
270 #endif
271 // complete the jmp instruction
272 memcpy(reinterpret_cast<void*>(target + 1),
273 reinterpret_cast<void*>(&offset_to_replacement_function), 4);
274
275 // Set any remaining bytes that were moved to the preamble-stub to INT3 so
276 // as not to cause confusion (otherwise you might see some strange
277 // instructions if you look at the disassembly, or even invalid
278 // instructions). Also, by doing this, we will break into the debugger if
279 // some code calls into this portion of the code. If this happens, it
280 // means that this function cannot be patched using this patcher without
281 // further thought.
282 if (preamble_bytes > kRequiredTargetPatchBytes) {
283 memset(reinterpret_cast<void*>(target + kRequiredTargetPatchBytes),
284 ASM_INT3, preamble_bytes - kRequiredTargetPatchBytes);
285 }
286
287 // Inv: The memory pointed to by target_function now points to a relative
288 // jump instruction that jumps over to the preamble_stub. The preamble
289 // stub contains the first stub_size bytes of the original target
290 // function's preamble code, followed by a relative jump back to the next
291 // instruction after the first cbPreamble bytes.
292 //
293 // In 64-bit mode the memory pointed to by target_function *may* point to a
294 // relative jump instruction that jumps to a trampoline which will then
295 // perform an absolute jump to the replacement function. The preamble stub
296 // still contains the original target function's preamble code, followed by a
297 // jump back to the instructions after the first preamble bytes.
298 //
299 return SIDESTEP_SUCCESS;
300 }
301
302 }; // namespace sidestep