Ruby 3.3.6p108 (2024-11-05 revision 75015d4c1f6965b5e85e96fb309f1f2129f933c0)
Context.h
1#ifndef COROUTINE_ARM64_CONTEXT_H
2#define COROUTINE_ARM64_CONTEXT_H 1
3
4/*
5 * This file is part of the "Coroutine" project and released under the MIT License.
6 *
7 * Created by Samuel Williams on 10/5/2018.
8 * Copyright, 2018, by Samuel Williams.
9*/
10
11#pragma once
12
13#include <assert.h>
14#include <stddef.h>
15#include <stdint.h>
16#include <string.h>
17
18#define COROUTINE __attribute__((noreturn)) void
19
20enum {COROUTINE_REGISTERS = 0xa0 / 8};
21
22#if defined(__SANITIZE_ADDRESS__)
23 #define COROUTINE_SANITIZE_ADDRESS
24#elif defined(__has_feature)
25 #if __has_feature(address_sanitizer)
26 #define COROUTINE_SANITIZE_ADDRESS
27 #endif
28#endif
29
30#if defined(COROUTINE_SANITIZE_ADDRESS)
31#include <sanitizer/common_interface_defs.h>
32#include <sanitizer/asan_interface.h>
33#endif
34
36{
37 void **stack_pointer;
38 void *argument;
39
40#if defined(COROUTINE_SANITIZE_ADDRESS)
41 void *fake_stack;
42 void *stack_base;
43 size_t stack_size;
44#endif
45};
46
47typedef COROUTINE(* coroutine_start)(struct coroutine_context *from, struct coroutine_context *self);
48
49static inline void coroutine_initialize_main(struct coroutine_context * context) {
50 context->stack_pointer = NULL;
51}
52
53#if defined(__ARM_FEATURE_PAC_DEFAULT) && __ARM_FEATURE_PAC_DEFAULT != 0
54// Sign the given instruction address with the given modifier and key A
55static inline void *ptrauth_sign_instruction_addr(void *addr, void *modifier) {
56 register void *r17 __asm("r17") = addr;
57 register void *r16 __asm("r16") = modifier;
58 // Use HINT mnemonic instead of PACIA1716 for compatibility with older assemblers.
59 asm ("hint #8;" : "+r"(r17) : "r"(r16));
60 addr = r17;
61 return addr;
62}
63#else
64// No-op if PAC is not enabled
65static inline void *ptrauth_sign_instruction_addr(void *addr, void *modifier) {
66 return addr;
67}
68#endif
69
70static inline void coroutine_initialize(
71 struct coroutine_context *context,
72 coroutine_start start,
73 void *stack,
74 size_t size
75) {
76 assert(start && stack && size >= 1024);
77
78#if defined(COROUTINE_SANITIZE_ADDRESS)
79 context->fake_stack = NULL;
80 context->stack_base = stack;
81 context->stack_size = size;
82#endif
83
84 // Stack grows down. Force 16-byte alignment.
85 char * top = (char*)stack + size;
86 top = (char *)((uintptr_t)top & ~0xF);
87 context->stack_pointer = (void**)top;
88
89 context->stack_pointer -= COROUTINE_REGISTERS;
90 memset(context->stack_pointer, 0, sizeof(void*) * COROUTINE_REGISTERS);
91
92 context->stack_pointer[0x98 / 8] = ptrauth_sign_instruction_addr((void*)start, (void*)top);
93}
94
95struct coroutine_context * coroutine_transfer(struct coroutine_context * current, struct coroutine_context * target);
96
97static inline void coroutine_destroy(struct coroutine_context * context)
98{
99}
100
101#endif /* COROUTINE_ARM64_CONTEXT_H */