aboutsummaryrefslogtreecommitdiffstats
path: root/src/steamvr_patches/include/trampoline.h
blob: 5a14b9be398b58c4c0f7ac1b83a21931795f7fb3 (plain)
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
/* SPDX-FileCopyrightText: 2026 Tomasz Kramkowski <tomasz@kramkow.ski>
 * SPDX-License-Identifier: CC0-1.0
 */

#ifndef PATCH_TRAMPOLINE_H
#define PATCH_TRAMPOLINE_H

#if defined(__x86_64__)
#define PATCH_ASM_BEGIN ".intel_syntax noprefix\n"
#define PATCH_ASM_END ".att_syntax prefix\n"
#define PATCH_FUNCTION_TYPE "@function"
#elif defined(__aarch64__)
#define PATCH_ASM_BEGIN ""
#define PATCH_ASM_END ""
#define PATCH_FUNCTION_TYPE "%function"
#else
#error Unsupported architecture
#endif

#define TRAMPOLINE(name, body)                                                      \
	__asm__(".pushsection .text.entry,\"ax\"\n"                                 \
		".global " #name "\n"                                               \
		".type " #name "," PATCH_FUNCTION_TYPE "\n" #name                   \
		":\n" PATCH_ASM_BEGIN body PATCH_ASM_END ".size " #name ",.-" #name \
		"\n"                                                                \
		".popsection\n")

#if defined(__x86_64__)
// Restore a register list in the reverse of its save order.
__asm__(".macro patch_pop_regs first, rest:vararg\n"
	"  .ifnb \\first\n"
	"    .ifnb \\rest\n"
	"      patch_pop_regs \\rest\n"
	"    .endif\n"
	"    pop \\first\n"
	"  .endif\n"
	".endm\n");

// Call `func`, preserving `regs`. Pass the value of RSP % 16 as `stack_mod16`.
// `setup` is inserted after saving but before the call.
#define CALL(func, stack_mod16, regs, setup)                         \
	".set .Lpatch_stack_pad, " #stack_mod16 "\n"                 \
	".ifnb " regs "\n"                                           \
	"  .irp reg, " regs "\n"                                     \
	"    push \\reg\n"                                           \
	"    .set .Lpatch_stack_pad, (.Lpatch_stack_pad - 8) & 15\n" \
	"  .endr\n"                                                  \
	".endif\n"                                                   \
	".if .Lpatch_stack_pad\n"                                    \
	"  sub rsp, .Lpatch_stack_pad\n"                             \
	".endif\n" setup "\n"                                        \
	"call " #func "\n"                                           \
	".if .Lpatch_stack_pad\n"                                    \
	"  add rsp, .Lpatch_stack_pad\n"                             \
	".endif\n"                                                   \
	"patch_pop_regs " regs "\n"
#endif

#endif