aboutsummaryrefslogtreecommitdiffstats
path: root/src/steamvr_patches/include/trampoline.h
diff options
context:
space:
mode:
Diffstat (limited to 'src/steamvr_patches/include/trampoline.h')
-rw-r--r--src/steamvr_patches/include/trampoline.h59
1 files changed, 59 insertions, 0 deletions
diff --git a/src/steamvr_patches/include/trampoline.h b/src/steamvr_patches/include/trampoline.h
new file mode 100644
index 0000000..5a14b9b
--- /dev/null
+++ b/src/steamvr_patches/include/trampoline.h
@@ -0,0 +1,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