-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathstub.h
More file actions
686 lines (650 loc) · 23.3 KB
/
Copy pathstub.h
File metadata and controls
686 lines (650 loc) · 23.3 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
#ifndef __STUB_H__
#define __STUB_H__
#ifdef _WIN32
//windows
#include <windows.h>
#include <processthreadsapi.h>
#else
//linux or macos
#include <unistd.h>
#include <sys/mman.h>
#endif
#if defined(__APPLE__)
#include <mach/mach.h>
#include <mach/mach_vm.h>
#include <libkern/OSCacheControl.h>
#endif
//c
#include <cstddef>
#include <cstdint>
#include <cstring>
//c++
#include <map>
//valgrind
#ifdef __VALGRIND__
#include <valgrind/valgrind.h>
#endif
#define ADDR(CLASS_NAME,MEMBER_NAME) (&CLASS_NAME::MEMBER_NAME)
/**********************************************************
replace function
**********************************************************/
#ifdef __VALGRIND__
#define VALGRIND_CACHE_FLUSH(addr, size) VALGRIND_DISCARD_TRANSLATIONS(addr, size)
#else
#define VALGRIND_CACHE_FLUSH(addr, size)
#endif
#ifdef _WIN32
#define CACHEFLUSH(addr, size) FlushInstructionCache(GetCurrentProcess(), addr, size);VALGRIND_CACHE_FLUSH(addr, size)
#else
#define CACHEFLUSH(addr, size) __builtin___clear_cache(addr, addr + size);VALGRIND_CACHE_FLUSH(addr, size)
#endif
#if !defined(__BYTE_ORDER__) || !defined(__ORDER_LITTLE_ENDIAN__) || !defined(__ORDER_BIG_ENDIAN__)
#if defined(_WIN32)
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __ORDER_BIG_ENDIAN__ 4321
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
#else
#include <endian.h>
#endif
#endif
#if defined(__APPLE__)
// On Apple (especially Apple Silicon), a direct store instruction targeted
// at an alias of a __TEXT page deadlocks the current thread when the store
// opcode itself resides on the same physical page as the destination.
// To dodge this, every write to the patch site is routed through libSystem's
// memcpy via a volatile function pointer; that keeps the store opcodes on
// libSystem's pages rather than on our own __TEXT page.
static inline void __stub_apple_memcpy(void* dst, const void* src, std::size_t n)
{
typedef void* (*__stub_memcpy_t)(void*, const void*, std::size_t);
volatile __stub_memcpy_t mc = (__stub_memcpy_t)&std::memcpy;
mc(dst, src, n);
}
#define STUB_WRITE_BYTES(dst, src, n) __stub_apple_memcpy((dst), (src), (n))
#else
#define STUB_WRITE_BYTES(dst, src, n) std::memcpy((dst), (src), (n))
#endif
#if defined(__aarch64__) || defined(_M_ARM64)
#define CODESIZE 16U
#define CODESIZE_MIN 16U
#define CODESIZE_MAX CODESIZE
// ldr x9, +8
// br x9
// addr
#if defined(__APPLE__)
#define REPLACE_FAR(t, fn, fn_stub)\
do {\
uint32_t __stub_buf[4];\
__stub_buf[0] = 0x58000040 | 9;\
__stub_buf[1] = 0xd61f0120 | (9 << 5);\
*(long long *)(&__stub_buf[2]) = (long long)(fn_stub);\
__stub_apple_memcpy((fn), __stub_buf, CODESIZE);\
CACHEFLUSH((char *)(fn), CODESIZE);\
} while(0)
#else
#define REPLACE_FAR(t, fn, fn_stub)\
((uint32_t*)fn)[0] = 0x58000040 | 9;\
((uint32_t*)fn)[1] = 0xd61f0120 | (9 << 5);\
*(long long *)(fn + 8) = (long long )fn_stub;\
CACHEFLUSH((char *)fn, CODESIZE);
#endif
#define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub)
#elif defined(__arm__) || defined(_M_ARM)
#define CODESIZE 8U
#define CODESIZE_MIN 8U
#define CODESIZE_MAX CODESIZE
// ldr pc, [pc, #-4]
#define REPLACE_FAR(t, fn, fn_stub)\
if ((uintptr_t)fn & 0x00000001) { \
*(uint16_t *)&fn[0] = 0xf8df;\
*(uint16_t *)&fn[2] = 0xf000;\
*(uint16_t *)&fn[4] = (uint16_t)(fn_stub & 0xffff);\
*(uint16_t *)&fn[6] = (uint16_t)(fn_stub >> 16);\
} else { \
((uint32_t*)fn)[0] = 0xe51ff004;\
((uint32_t*)fn)[1] = (uint32_t)fn_stub;\
}\
CACHEFLUSH((char *)((uintptr_t)fn & 0xfffffffe), CODESIZE);
#define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub)
#elif defined(__thumb__) || defined(_M_THUMB)
#define CODESIZE 12
#define CODESIZE_MIN 12
#define CODESIZE_MAX CODESIZE
// NOP
// LDR.W PC, [PC]
#define REPLACE_FAR(t, fn, fn_stub)\
uint32_t clearBit0 = (uintptr_t)fn & 0xfffffffe;\
char *f = (char *)clearBit0;\
if (clearBit0 % 4 != 0) {\
*(uint16_t *)&f[0] = 0xbe00;\
}\
*(uint16_t *)&f[2] = 0xf8df;\
*(uint16_t *)&f[4] = 0xf000;\
*(uint16_t *)&f[6] = (uint16_t)(fn_stub & 0xffff);\
*(uint16_t *)&f[8] = (uint16_t)(fn_stub >> 16);\
CACHEFLUSH((char *)f, CODESIZE);
#define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub)
#elif defined(__mips64)
#define CODESIZE 80U
#define CODESIZE_MIN 80U
#define CODESIZE_MAX CODESIZE
//MIPS has no PC pointer, so you need to manually enter and exit the stack
//120000ce0: 67bdffe0 daddiu sp, sp, -32 //enter the stack
//120000ce4: ffbf0018 sd ra, 24(sp)
//120000ce8: ffbe0010 sd s8, 16(sp)
//120000cec: ffbc0008 sd gp, 8(sp)
//120000cf0: 03a0f025 move s8, sp
//120000d2c: 03c0e825 move sp, s8 //exit the stack
//120000d30: dfbf0018 ld ra, 24(sp)
//120000d34: dfbe0010 ld s8, 16(sp)
//120000d38: dfbc0008 ld gp, 8(sp)
//120000d3c: 67bd0020 daddiu sp, sp, 32
//120000d40: 03e00008 jr ra
#define REPLACE_FAR(t, fn, fn_stub)\
((uint32_t *)fn)[0] = 0x67bdffe0;\
((uint32_t *)fn)[1] = 0xffbf0018;\
((uint32_t *)fn)[2] = 0xffbe0010;\
((uint32_t *)fn)[3] = 0xffbc0008;\
((uint32_t *)fn)[4] = 0x03a0f025;\
*(uint16_t *)(fn + 20) = (long long)fn_stub >> 32;\
*(fn + 22) = 0x19;\
*(fn + 23) = 0x24;\
((uint32_t *)fn)[6] = 0x0019cc38;\
*(uint16_t *)(fn + 28) = (long long)fn_stub >> 16;\
*(fn + 30) = 0x39;\
*(fn + 31) = 0x37;\
((uint32_t *)fn)[8] = 0x0019cc38;\
*(uint16_t *)(fn + 36) = (long long)fn_stub;\
*(fn + 38) = 0x39;\
*(fn + 39) = 0x37;\
((uint32_t *)fn)[10] = 0x0320f809;\
((uint32_t *)fn)[11] = 0x00000000;\
((uint32_t *)fn)[12] = 0x00000000;\
((uint32_t *)fn)[13] = 0x03c0e825;\
((uint32_t *)fn)[14] = 0xdfbf0018;\
((uint32_t *)fn)[15] = 0xdfbe0010;\
((uint32_t *)fn)[16] = 0xdfbc0008;\
((uint32_t *)fn)[17] = 0x67bd0020;\
((uint32_t *)fn)[18] = 0x03e00008;\
((uint32_t *)fn)[19] = 0x00000000;\
CACHEFLUSH((char *)fn, CODESIZE);
#define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub)
#elif defined(__riscv) && __riscv_xlen == 64
#define CODESIZE 24U
#define CODESIZE_MIN 24U
#define CODESIZE_MAX CODESIZE
// absolute offset(64)
// auipc t1,0
// addi t1, t1, 16
// ld t1,0(t1)
// jalr x0, t1, 0
// addr
#define REPLACE_FAR(t, fn, fn_stub)\
unsigned int auipc = 0x317;\
*(unsigned int *)(fn) = auipc;\
unsigned int addi = 0x1030313;\
*(unsigned int *)(fn + 4) = addi;\
unsigned int ld = 0x33303;\
*(unsigned int *)(fn + 8) = ld;\
unsigned int jalr = 0x30067;\
*(unsigned int *)(fn + 12) = jalr;\
*(unsigned long long*)(fn + 16) = (unsigned long long)fn_stub;\
CACHEFLUSH((char *)fn, CODESIZE);
#define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub)
#elif defined(__riscv) && __riscv_xlen == 32
#define CODESIZE 20U
#define CODESIZE_MIN 20U
#define CODESIZE_MAX CODESIZE
// absolute offset(32)
// auipc t1,0
// addi t1, t1, 16
// lw t1,0(t1)
// jalr x0, t1, 0
// addr
#define REPLACE_FAR(t, fn, fn_stub)\
unsigned int auipc = 0x317;\
*(unsigned int *)(fn) = auipc;\
unsigned int addi = 0x1030313;\
*(unsigned int *)(fn + 4) = addi;\
unsigned int lw = 0x32303;\
*(unsigned int *)(fn + 8) = lw;\
unsigned int jalr = 0x30067;\
*(unsigned int *)(fn + 12) = jalr;\
*(unsigned int*)(fn + 16) = (unsigned int)fn_stub;\
CACHEFLUSH((char *)fn, CODESIZE);
#define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub)
#elif defined(__loongarch64)
#define CODESIZE 20U
#define CODESIZE_MIN 20U
#define CODESIZE_MAX CODESIZE
// absolute offset(64)
// PCADDI rd, si20 | 0 0 0 1 1 0 0 si20 rd
// LD.D rd, rj, si12 | 0 0 1 0 1 0 0 0 1 1 si12 rj rd
// JIRL rd, rj, offs | 0 1 0 0 1 1 offs[15:0] rj rd
// addr
#define REPLACE_FAR(t, fn, fn_stub)\
unsigned int rd = 17;\
unsigned int off = 12 >> 2;\
unsigned int pcaddi = 0x0c << (32 - 7) | off << 5 | rd ;\
rd = 17;\
int rj = 17;\
off = 0;\
unsigned int ld_d = 0xa3 << 22 | off << 10 | rj << 5 | rd ;\
rd = 0;\
rj = 17;\
off = 0;\
unsigned int jirl = 0x13 << 26 | off << 10 | rj << 5| rd;\
*(unsigned int *)fn = pcaddi;\
*(unsigned int *)(fn + 4) = ld_d;\
*(unsigned int *)(fn + 8) = jirl;\
*(unsigned long long*)(fn + 12) = (unsigned long long)fn_stub;\
CACHEFLUSH((char *)fn, CODESIZE);
#define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub)
#elif defined(__powerpc64__) && __LITTLE_ENDIAN__
// For ppc64le (Little Endian, ELFv2 ABI)
// https://maskray.me/blog/2023-02-26-linker-notes-on-power-isa
// https://llvm.org/devmtg/2014-04/PDFs/Talks/Euro-LLVM-2014-Weigand.pdf
// PowerPC64 LE (ELFv2 ABI) - LEP
// readelf -h test_function : Flags: 0x2, abiv2
#define CODESIZE 28U
#define CODESIZE_MIN 28U
#define CODESIZE_MAX CODESIZE
#define REPLACE_FAR(t, fn, fn_stub) \
do { \
uint64_t addr = (uint64_t)(fn_stub); \
uint32_t* p = (uint32_t*)(fn + 8); \
p[0] = 0x3d800000 | ((addr >> 48) & 0xFFFF); /* lis r12, hi16 */ \
p[1] = 0x618c0000 | ((addr >> 32) & 0xFFFF); /* ori r12, mid16 */ \
p[2] = 0x798c07c6; /* rldicr r12, r12, 32, 31 */ \
p[3] = 0x658c0000 | ((addr >> 16) & 0xFFFF); /* oris r12, midlow16 */ \
p[4] = 0x618c0000 | (addr & 0xFFFF); /* ori r12, low16 */ \
p[5] = 0x7d8903a6; /* mtctr r12 */ \
p[6] = 0x4e800420; /* bctr */ \
CACHEFLUSH((char *)fn, CODESIZE); \
} while (0)
#define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub)
#elif defined(__powerpc64__)
// PowerPC64 BE (ELFv1 ABI) - Use function descriptor to load code + TOC(Table of Contents)
#define CODESIZE 36U
#define CODESIZE_MIN 36U
#define CODESIZE_MAX CODESIZE
#define REPLACE_FAR(t, fn, fn_stub) \
do { \
uint64_t desc_addr = (uint64_t)(fn_stub); \
uint32_t* p = (uint32_t*)(fn); \
p[0] = 0x3d600000 | ((desc_addr >> 48) & 0xFFFF); /* lis r11, hi16 */ \
p[1] = 0x616b0000 | ((desc_addr >> 32) & 0xFFFF); /* ori r11, mid16 */ \
p[2] = 0x796b07c6; /* rldicr r11, r11, 32, 31 */ \
p[3] = 0x616b0000 | ((desc_addr >> 16) & 0xFFFF); /* ori r11, midlow16 */ \
p[4] = 0x616b0000 | (desc_addr & 0xFFFF); /* ori r11, low16 */ \
p[5] = 0xe98b0000; /* ld r12, 0(r11) - code */ \
p[6] = 0xe84b0008; /* ld r2, 8(r11) - toc */ \
p[7] = 0x7d8903a6; /* mtctr r12 */ \
p[8] = 0x4e800420; /* bctr */ \
CACHEFLUSH((char *)fn, CODESIZE); \
} while (0)
#define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub)
#elif defined(__alpha__)
#define CODESIZE 16U
#define CODESIZE_MIN 16U
#define CODESIZE_MAX CODESIZE
// ldah t12, high(fn_stub)
// lda t12, low(fn_stub)(t12)
// jmp zero, (t12), 0
#define REPLACE_FAR(t, fn, fn_stub)\
((uint32_t*)fn)[0] = 0x279f0000 | (((uintptr_t)fn_stub >> 32) & 0xffff);\
((uint32_t*)fn)[1] = 0x201f0000 | ((uintptr_t)fn_stub & 0xffff);\
((uint32_t*)fn)[2] = 0x6bfb0000;\
CACHEFLUSH((char *)fn, CODESIZE);
#define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub)
#elif defined(__sparc__) && defined(__arch64__)
#define CODESIZE 28U // 7 instructions * 4 bytes
#define CODESIZE_MIN 28U
#define CODESIZE_MAX CODESIZE
/*
* Correct 64-bit absolute jump for SPARCv9.
* This sequence loads the full 64-bit address of fn_stub into register %g1
* and then jumps to it.
*
* Assembly:
* 1. sethi %hix(fn_stub), %g1 // bits 63-42
* 2. or %g1, %lox(fn_stub), %g1 // bits 41-32
* 3. sllx %g1, 32, %g1 // shift left by 32
* 4. sethi %hi(fn_stub), %g1 // bits 31-10 (of the lower 32 bits)
* 5. or %g1, %lo(fn_stub), %g1 // bits 9-0
* 6. jmpl %g1, %g0 // jump to address in %g1
* 7. nop // delay slot filler
*/
#define REPLACE_FAR(t, fn, fn_stub)\
do {\
uint64_t addr = (uint64_t)fn_stub;\
/* 1. sethi %hix(addr), %g1 */\
((uint32_t*)fn)[0] = 0x03000000 | ((addr >> 42) & 0x3fffff);\
/* 2. or %g1, %lox(addr), %g1 */\
((uint32_t*)fn)[1] = 0x82104000 | ((addr >> 32) & 0x3ff);\
/* 3. sllx %g1, 32, %g1 */\
((uint32_t*)fn)[2] = 0x83285020;\
/* 4. sethi %hi(addr), %g1 */\
((uint32_t*)fn)[3] = 0x03000000 | ((addr >> 10) & 0x3fffff);\
/* 5. or %g1, %lo(addr), %g1 */\
((uint32_t*)fn)[4] = 0x82104000 | (addr & 0x3ff);\
/* 6. jmpl %g1, %g0 */\
((uint32_t*)fn)[5] = 0x81c04000;\
/* 7. nop */\
((uint32_t*)fn)[6] = 0x01000000;\
CACHEFLUSH((char *)fn, CODESIZE);\
} while(0)
#define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub)
#elif defined(__sw_64__)
#define CODESIZE 12U
#define CODESIZE_MIN 12U
#define CODESIZE_MAX CODESIZE
// bis zero, zero, v0
// ldq v0, fn_stub
// jmp zero, (v0)
#define REPLACE_FAR(t, fn, fn_stub)\
((uint32_t*)fn)[0] = 0x20000000;\
((uint32_t*)fn)[1] = 0xd2000000 | ((uintptr_t)fn_stub & 0xffffffff);\
((uint32_t*)fn)[2] = 0x6bfb0000;\
CACHEFLUSH((char *)fn, CODESIZE);
#define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub)
#elif defined(__s390x__)
#define CODESIZE 16U
#define CODESIZE_MIN 16U
#define CODESIZE_MAX CODESIZE
// lgrl %r1, fn_stub
// br %r1
#define REPLACE_FAR(t, fn, fn_stub)\
((uint32_t*)fn)[0] = 0xc0100000 | (1 << 20) | (0x0);\
((uint32_t*)fn)[1] = 0x07f10000;\
*(uint64_t *)(fn + 8) = (uint64_t)fn_stub;\
CACHEFLUSH((char *)fn, CODESIZE);
#define REPLACE_NEAR(t, fn, fn_stub) REPLACE_FAR(t, fn, fn_stub)
#else //__i386__ _x86_64__ _M_IX86 _M_X64
#define CODESIZE 13U
#define CODESIZE_MIN 5U
#define CODESIZE_MAX CODESIZE
//13 byte(jmp m16:64)
//movabs $0x102030405060708,%r11
//jmpq *%r11
#define REPLACE_FAR(t, fn, fn_stub)\
*fn = 0x49;\
*(fn + 1) = 0xbb;\
*(long long *)(fn + 2) = (long long)fn_stub;\
*(fn + 10) = 0x41;\
*(fn + 11) = 0xff;\
*(fn + 12) = 0xe3;\
CACHEFLUSH((char *)fn, CODESIZE);
//5 byte(jmp rel32)
#define REPLACE_NEAR(t, fn, fn_stub)\
*fn = 0xE9;\
*(int *)(fn + 1) = (int)(fn_stub - fn - CODESIZE_MIN);\
CACHEFLUSH((char *)fn, CODESIZE);
#endif
struct func_stub
{
unsigned char *fn;
unsigned char code_buf[CODESIZE];
bool far_jmp;
};
class Stub
{
public:
Stub()
{
#ifdef _WIN32
SYSTEM_INFO sys_info;
GetSystemInfo(&sys_info);
m_pagesize = sys_info.dwPageSize;
#else
m_pagesize = sysconf(_SC_PAGE_SIZE);
#endif
if (m_pagesize < 0)
{
m_pagesize = 4096;
}
}
~Stub()
{
clear();
}
void clear()
{
std::map<unsigned char*,func_stub*>::iterator iter;
struct func_stub *pstub;
for(iter=m_result.begin(); iter != m_result.end(); iter++)
{
pstub = iter->second;
WriteSession ws;
if (!begin_write(pstub->fn, ws))
{
iter->second = NULL;
delete pstub;
continue;
}
if(pstub->far_jmp)
{
STUB_WRITE_BYTES(ws.write_addr, pstub->code_buf, CODESIZE_MAX);
}
else
{
STUB_WRITE_BYTES(ws.write_addr, pstub->code_buf, CODESIZE_MIN);
}
CACHEFLUSH((char *)pstub->fn, CODESIZE);
end_write(pstub->fn, ws);
iter->second = NULL;
delete pstub;
}
m_result.clear();
return;
}
template<typename T,typename S>
void set(T addr, S addr_stub)
{
unsigned char * fn;
unsigned char * fn_stub;
fn = addrof(addr);
fn_stub = addrof(addr_stub);
struct func_stub *pstub;
pstub = new func_stub;
//start
reset(fn); //
pstub->fn = fn;
if(distanceof(fn, fn_stub))
{
pstub->far_jmp = true;
std::memcpy(pstub->code_buf, fn, CODESIZE_MAX);
}
else
{
pstub->far_jmp = false;
std::memcpy(pstub->code_buf, fn, CODESIZE_MIN);
}
WriteSession ws;
if (!begin_write(pstub->fn, ws))
{
delete pstub;
throw("stub set memory protect to w+r+x faild");
}
unsigned char * write_fn = ws.write_addr;
if(pstub->far_jmp)
{
REPLACE_FAR(this, write_fn, fn_stub);
}
else
{
REPLACE_NEAR(this, write_fn, fn_stub);
}
#if defined(__APPLE__)
// Also flush i-cache at the original executable VA (the alias shares
// the same physical page, but invalidating the original VA explicitly
// is a safety belt for all cache topologies).
sys_icache_invalidate(pstub->fn, CODESIZE);
#endif
if (!end_write(pstub->fn, ws))
{
delete pstub;
throw("stub set memory protect to r+x failed");
}
m_result.insert(std::pair<unsigned char*,func_stub*>(fn,pstub));
return;
}
template<typename T>
void reset(T addr)
{
unsigned char * fn;
fn = addrof(addr);
std::map<unsigned char*,func_stub*>::iterator iter = m_result.find(fn);
if (iter == m_result.end())
{
return;
}
struct func_stub *pstub;
pstub = iter->second;
WriteSession ws;
if (!begin_write(pstub->fn, ws))
{
throw("stub reset memory protect to w+r+x faild");
}
if(pstub->far_jmp)
{
STUB_WRITE_BYTES(ws.write_addr, pstub->code_buf, CODESIZE_MAX);
}
else
{
STUB_WRITE_BYTES(ws.write_addr, pstub->code_buf, CODESIZE_MIN);
}
CACHEFLUSH((char *)pstub->fn, CODESIZE);
#if defined(__APPLE__)
sys_icache_invalidate(pstub->fn, CODESIZE);
#endif
if (!end_write(pstub->fn, ws))
{
throw("stub reset memory protect to r+x failed");
}
m_result.erase(iter);
delete pstub;
return;
}
private:
struct WriteSession
{
unsigned char* write_addr;
#if defined(__APPLE__)
mach_vm_address_t alias;
mach_vm_size_t region_size;
#endif
};
bool begin_write(unsigned char* fn, WriteSession& ws)
{
#if defined(__APPLE__)
// On Apple Silicon (and on hardened runtime Intel Macs) the __TEXT
// segment cannot be made writable via mprotect. Obtain a writable
// alias of the target page(s) via mach_vm_remap + VM_INHERIT_SHARE,
// then escalate the alias to PROT_READ|PROT_WRITE. The alias shares
// the same physical memory as the original executable mapping, so
// writes through the alias are visible at the original address.
//
// Prerequisite (one-time, per-binary): the __TEXT segment's maxprot
// must allow write. See tool/macos_enable_stub.sh which patches the
// Mach-O header and re-signs the binary ad-hoc.
long ps = m_pagesize;
mach_vm_address_t page_start = (mach_vm_address_t)(uintptr_t)fn & ~((mach_vm_address_t)ps - 1);
mach_vm_size_t offset = (mach_vm_size_t)((uintptr_t)fn - page_start);
mach_vm_size_t region_size = ((offset + (mach_vm_size_t)CODESIZE + ps - 1) / ps) * ps;
mach_vm_address_t alias = 0;
vm_prot_t cur_prot = 0;
vm_prot_t max_prot = 0;
kern_return_t kr = mach_vm_remap(mach_task_self(), &alias, region_size, 0,
VM_FLAGS_ANYWHERE, mach_task_self(), page_start, FALSE,
&cur_prot, &max_prot, VM_INHERIT_SHARE);
if (kr != KERN_SUCCESS)
{
return false;
}
kr = mach_vm_protect(mach_task_self(), alias, region_size, FALSE,
VM_PROT_READ | VM_PROT_WRITE);
if (kr != KERN_SUCCESS)
{
mach_vm_deallocate(mach_task_self(), alias, region_size);
return false;
}
ws.alias = alias;
ws.region_size = region_size;
ws.write_addr = (unsigned char*)(uintptr_t)(alias + offset);
return true;
#elif defined(_WIN32)
DWORD lpflOldProtect;
if (0 == VirtualProtect(pageof(fn), m_pagesize * 2, PAGE_EXECUTE_READWRITE, &lpflOldProtect))
{
return false;
}
ws.write_addr = fn;
return true;
#else
if (-1 == mprotect(pageof(fn), m_pagesize * 2, PROT_READ | PROT_WRITE | PROT_EXEC))
{
return false;
}
ws.write_addr = fn;
return true;
#endif
}
bool end_write(unsigned char* fn, WriteSession& ws)
{
#if defined(__APPLE__)
(void)fn;
if (ws.alias)
{
mach_vm_deallocate(mach_task_self(), ws.alias, ws.region_size);
ws.alias = 0;
}
return true;
#elif defined(_WIN32)
(void)ws;
DWORD lpflOldProtect;
return 0 != VirtualProtect(pageof(fn), m_pagesize * 2, PAGE_EXECUTE_READ, &lpflOldProtect);
#else
(void)ws;
return -1 != mprotect(pageof(fn), m_pagesize * 2, PROT_READ | PROT_EXEC);
#endif
}
void *pageof(unsigned char* addr)
{
#ifdef _WIN32
return (void *)((unsigned long long)addr & ~(m_pagesize - 1));
#else
return (void *)((unsigned long)addr & ~(m_pagesize - 1));
#endif
}
template<typename T>
unsigned char* addrof(T addr)
{
union
{
T _s;
unsigned char* _d;
}ut;
ut._s = addr;
return ut._d;
}
bool distanceof(unsigned char* addr, unsigned char* addr_stub)
{
std::ptrdiff_t diff = addr_stub >= addr ? addr_stub - addr : addr - addr_stub;
if((sizeof(addr) > 4) && (((diff >> 31) - 1) > 0))
{
return true;
}
return false;
}
private:
#ifdef _WIN32
//LLP64
long long m_pagesize;
#else
//LP64
long m_pagesize;
#endif
std::map<unsigned char*, func_stub*> m_result;
};
#endif