Missing systrap system call patching on ARM64
Description
It seems that system call patching is not implemented on ARM64, despite the fact that it should be easy since all instructions are 32-bit.
Do you have a specific solution in mind?
The B instruction can be used to provide a 26-bit relative jump, which should hopefully be enough to find free memory in most cases (e.g. libc.so on my system is 2MB and should either be loaded first with free space before or randomized with free space around).
The problem is that post-jump, the stub thread won't be able to find its thread stack which it can use to save the current context's state. On x86 we use the GS register, which is basically unused by userspace applications on Linux: https://cs.opensource.google/gvisor/gvisor/+/master:pkg/sentry/platform/systrap/sysmsg/syshandler_amd64.S;drc=05872f0c3db04db39a1e1e3c0f4e38b1c95b4c13;l=185 . We don't have a similar hack for ARM.
I think I found a solution that doesn't require to make any assumptions about the program as long as atomics are available or enough registers are constant across uses of a single svc instruction (other than being able to allocate memory for the syscall trampoline), and otherwise works assuming that TPIDR_EL0 is a valid pointer.
EDIT: added dynamic specialization and changed to use it as the main mechanism, since it's more efficient, removed no-atomics one-register fallback that doesn't seem worthwhile; also removed flags specialization since it seems we don't need flags, and clarified/expanded things
General scheme
The problem is that to do anything we need a register we can clobber, but on first sight we don't have any. However, the x8 syscall number can only have around 300 valid values, so we can essentially use the instruction pointer to store it, and then x8 is a free register.
Making x8 available
More in detail, the first time we execute an svc instruction, we note the system call number in x8 and create a trampoline that checks whether x8 is that value. If it isn't, it executes another svc and gVisor notices it and regenerates the trampoline checking for both system call number values. This process can continue up to generating a trampoline that checks for all system call numbers (this would be large, but still finite code size, and usually each svc instruction has a single system call number).
The same specialization technique could be used to specialize flags, but it seems that on ARM64 it's possible and in fact easy to lookup things in a hashtable without clobbering flags.
For each branch of the generated trampolines that isn't an svc trap for further trampoline generation, the x8 value is constant and the flags are constant, which means that we clobber the register and the flags and then restore from known flags, and thus have a free general purpose register and usable flags.
Making more registers available
To make more registers available, we can use "dynamic specialization". For each svc instruction, we emulate it the first times and record the register state. Then, on every emulation we check whether the register values and the differences between them and pc and sp changed, keeping a bitmask of which of them are constant.
After the first few emulations, we generate a trampoline that specializes on the registers or register differences that happen to be constant, using a static priority order to be learned from experiment. Since we already have x8 free, we can materialize any immediate there, add sp if needed and compare to the other register.
[For differences between a register and PC, we can still construct PC + any immediate with just one register by first using constructing PC + 24-bit immediate via adr + add lsl#12, then doing a 24-bit right rotation, add and add lsl#12, then again rotation + add + add, then a final rotation, and if carries are possible checking on each step whether there was one with tbz/tbnz and subtracting 1 after further rotation]
If the chosen register or register difference turns out to be not constant, an svc instruction is executed, the constantness bitmap is updated, and a new trampoline can be generated from another constant register or register difference.
If there are none remaining, then it's possible to just fallback to svc emulation in remaining cases, or use of the alternatives below
Final stretch
Now that we have a few available registers, we can use them to lookup the TPIDR_EL0 value in a global concurrent hashtable (we should choose a good algorithm optimized for rare writes and simple read-side code), finding the per-thread gVisor data structures putting the pointer in x8, put the constant x8 value there, restore all dynamically specialized registers, save LR and then call a global routine
The global routine can save all registers except x8, call the gVisor syscall handling code. Then on syscall return, it puts the pointer in x8, restores all registers except x8 and lr, then return to the trampoline.
Finally, the trampoline restores LR and x8 from the area at pointer x8 and branches back via B to the instruction after the syscall.
Without dynamic specialization
If dynamic specialization, fails to find any register, there are still other options. I include this for completeness but I suggest to not implement these at least at first (except if you care about Graviton3 a lot, in which case maybe implement the 256-bit SVE path, if it's indeed feasible)
Table scheme, if swpa is available
Now, we can use the free register to load the TPIDR_EL0 value.
Afterwards, we shift that value and use movk to set the upper 32/48-bits and then shift again, so that we produce an address into a global table of "scratch areas", indexed by some of the bits in TPIDR_EL0, essentially forming an hash of the current thread (which reduces inter-core cache contention).
Then, we iterate the table, incrementing the register and performing an atomic "trylock" until we find a free slot which we lock.
To perform the trylock without extra registers, we represent the locked state as the address of the lock itself, and the unlocked state as its negation.
This way, we use the swpa x8, x8, [x8] instruction and check if the result is negative. If so, we locked it and can negate it to get back our pointer. Otherwise, it was already locked and we got back the same value of x8 and can proceed in the iteration.
If swpa is not supported by the CPU, ldaxr x8, [x8] can be used, but unfortunately stxr requires two registers and so at least one from dynamic specialization (since the ARM64 designers inexplicably decided to use a register to store the stxr status despite having flags in the architecture, and even decided to make it undefined to use the same register for status and address!).
256-bit SVE
Apparently (according to GPT-5.5) only the 0-127 bits of SVE registers are preserved by syscalls and SVE predicates are also not preserved, so if the CPU supports SVE and has at least 256-bit register size, we can store the general purpose registers in the 128-191 bits of SVE registers, using code like this:
// Clobbers only SVE predicate state and z0 bits above 127.
// Leaves z0[127:0] / v0 unchanged.
ptrue p0.b // all predicate bits true
ptrue p1.d, vl2 // first two 64-bit lanes = low 128 bits
not p0.b, p0/z, p1.b // p0 = not(first two d lanes), i.e. upper d lanes
mov z0.d, p0/m, xN // CPY scalar, merging: inactive lanes unchanged
However ARM64 CPUs with 256-bit SVE support seem to be very uncommon (only Graviton 3 but not Graviton 4-5 and some niche HPC CPUs from Fujitsu/SiPearl, and no Apple or mobile SoCs)
Faster/simpler but less general alternatives
Another way to get a free register is to simply save registers to the program stack. However, clobbering the program stack is in principle incorrect and might corrupt data in case of segmented stacks or special stack usage.
Once we have a free register, another possibility is to assume normal TLS usage and use a slot previously allocated by calling the application's pthread_key_create via dlopen (found starting from the ELF executable) or equivalent code in gVisor, hardcoding the slot address in the trampoline.
This looks like a feasible proposal.
One issue is that this depends on unique values of TPIDR_EL0, which generally should be OK for well behaved processes, but is apparently a deal breaker for Go processes specifically because it doesn't seem like Go sets TPIDR_EL0 at all. So we need to make sure that the sentry has a way to disable this entire scheme per subprocess if it sees TPIDR_EL0 reuse.
I am not sure how often "dynamic specialization" would work for general use, so we would definitely have to run this scheme through multiple languages/runtimes and workloads to see how useable it is. My concern is that if we're patching something like the libc syscall wrappers, in those cases really the only thing that's constant is x8 because the patch-site is completely removed from the context leading up to the syscall invocation. In cases where svc is inline this will probably work well. My point is that even for the initial prototype we should make sure to have metric tracking to see how often we hit the happy path.
@lyphyser are you going to give a shot at implementing this?
It seems like that Go just doesn't set it, so a possibility could be to have gVisor set it to the negated stub thread pointer whenever a task is created without SETTLS. It might possibly break something else that creates the TLS lazily and expects a zero, but maybe either nothing does that, or it can be detected.
I think dynamic specialization might work due to frame pointer - sp, pointers to fixed places in the stack, GOT pointers - pc, globals - pc, linker IPR register, large constants materialized in registers, etc.
If it doesn't work out the swpa scratch area table can be used, and if swpa is not available there's also the possibility of restricting the address space and then directly accessing base + TPIDR_EL0 * 8 using the x8 register (which however needs potentially a whole memory page per thread).
Not sure about implementing it myself.
So overall, it seems clear that this is feasible, but there are a lot of possible approaches with pros and cons, and I can't quite find any single one or small set that seems to be "obviously the best" and guaranteed to work.
The best way might be to implement a lot of them and use them conditionally, but that's going to be several thousands lines of code I think. I think AI agents can probably make it feasible to just implement them all (but quite a bit of human input is going to be needed for perfect results), but if I do that myself it's going to be several thousands of lines of nontrivial code to review.
To recap, the possible approaches I found previously plus several new ones are these, where the numbers mean the number of free registers available, with DONE meaning we determine the stub per-thread data structure address.
Expanding from 0 free registers:
- 0->1: x8 syscall number specialization (con: large trampoline if it's not constant)
- 0->any: upper bits of >=256-bit SVE registers (con: almost no CPUs support >=256-bit SVE)
- 0->any: use the application stack (con: may clobber data, there may be no stack/not enough stack space)
- 0->2: just overwrite x16/x17 (linker temporaries) (con: may clobber application data, must be opt-in)
- 0->2 just overwrite caller-saved vector registers (con: may clobber application data, must be opt-in)
- 0->1: write bit-by-bit into SVE vector predicate registers (clobbered by syscalls) via an unrolled tbz+ptrue+eor loop (con: requires SVE, 196 code instructions)
Expanding from 1 free register:
- 1->unknown: dynamic specialization to find constant registers automatically (con: may not find constant registers, may recreate the trampoline several times)
- 1->any: swpa atomic trylock table (con: needs atomics, a bit of overhead)
- 1->3: write bit-by-bit into SVE vector predicate registers (clobbered by syscalls) via a tbz+ptrue+eor loop (con: requires SVE, ~330 executed instructions per GPR with a loop, 196 code instructions if unrolled per GPR)
Expanding from 2+ free registers:
- 2->any: ldxr/stxr trylock table (con: needs 2 free registers to start, a bit of overhead)
Getting the final value:
- 1->DONE: set TPIDR_EL0 ourselves and just use that value (con: only for cases like Go where it's not set by the application)
- 1->DONE: detect the application's libc and use some unused space in their thread structure (con: corrupts TLS if app behavior doesn't match the detected libc, the spaces needs to exist)
- 1->DONE: detect the application TLS layout and allocate a TLS key ourselves with the same algorithm pthread_key_create would use (con: corrupts TLS if app behavior doesn't match the detected libc)
- 1->DONE: find dlopen in the ELF executable, lookup pthread_key_create and call it to allocate a TLS (con: only works for dynamic executables and pthread-based userspace)
- 1->DONE: patch the host Linux kernel to provide an API to set TPIDRRO_EL0 to a value of our choice (con: only works with patched kernels, if we upstream this then apps may start to use it...)
- 1->DONE: direct addressing of base + TPIDR_EL0 * 2^K (con: potentially wastes a whole memory page per thread, needs to either restrict address space by 4 bits or by 1 bits assuming TPIDR_EL0 is a multiple of 8)
- 2->DONE: concurrent hashtable using TPIDR_EL0 using hack that stores the bucket address in TPIDR_EL0 so we can use the two registers for the value read and the original TPIDR_EL0 value to compare - requires stub awareness so signals don't observe the temporary value (con: some overhead, a bit more than the 3-register code)
- 3->DONE: concurrent hashtable using TPIDR_EL0 (con: some overhead)
Maybe a possible plan is to start to implement this subset. (unless someone can find some better strategies).
As long as the CPU supports atomics/LSE (all cloud instances except Graviton 1, all Apple Silicon, Google Pixel 3+, all recent Windows ARM64 devices, Raspberry Pi 5+), this should work in all cases and not have major efficiency or compatibility cliffs (other than maybe multicore cache contention if the one-register TPIDR_EL0 hash can't be made good enough) even though it's going to be a bit suboptimal where other options could have been used.
Expanding from 0 free registers:
- 0->1: x8 syscall number specialization (con: large trampoline if it's not constant)
- 0->any: if an opt-in option is set, use the application stack (con: may clobber data, there may be no stack/not enough stack space)
Expanding from 1 free register:
- 1->any: swpa atomic trylock table (con: needs atomics, a bit of overhead)
Getting the final value:
- 1->DONE: for Go support, when TLS=0 set TPIDR_EL0 ourselves to the negated per-thread stub context pointer and just use that value (con: only for cases like Go where it's not set by the application)
- 3->DONE: concurrent hashtable using TPIDR_EL0 as key (con: some overhead)
I suspect I won't have time to do it myself though.
Hi, I'm working on an ARM64 implementation for this issue and have the AArch64 branch/range handling and ARM64 thread_context offset scaffolding started.
Before implementing the fast-path trampoline, I wanted to confirm the intended mechanism for locating the current thread's sysmsg.
On amd64, setArchSpecificRegs sets GSBase = sysThread.msg.Self, and the trampoline / __syshandler use %gs to access the per-thread sysmsg. On arm64, setArchSpecificRegs is currently empty, while TPIDR_EL0 is application TLS and is saved/restored by Systrap.
Is there a preferred per-thread base mechanism for the ARM64 patched-syscall trampoline? I don't see an existing Systrap mechanism using TPIDRRO_EL0 or TPIDR2_EL0, and deriving the address from the deterministic sysmsg mapping still requires identifying the current thread before switching from the application stack.
I want to confirm the intended ARM64 ABI before reserving architectural state or implementing the trampoline around an assumption. Thanks!
I want to confirm the intended ARM64 ABI before reserving architectural state or implementing the trampoline around an assumption
@namtran1812 this is exactly what @lyphyser was trying to figure out in the discussion in this bug.
I am sorry but this is not a good first issue for a new contributor to work on. It is experimental in nature, non-trivial, and will require thorough review (which I will not do for un-vetted contributors working on this, FYI).
Thanks, that makes sense. I read through the earlier design discussion in more detail.
For an initial prototype, I'm thinking of keeping the scope narrow:
- Use x8 syscall-number specialization to obtain the first scratch register at a patched SVC site.
- Use that register to prototype TPIDR_EL0-based lookup of the per-thread sysmsg/context.
- Fall back to the normal SVC/SIGSYS path when the specialization or lookup assumptions do not hold.
- Instrument the prototype so we can measure specialization success/fallback rates across different runtimes, especially libc wrappers, Go, and inline SVC sites.
I'll keep the branch/range and ARM64 thread_context scaffolding separate from assumptions about the final lookup mechanism.
Does that sound like the right first implementation slice, or would you prefer the initial prototype to start with the SWPA scratch-table approach discussed above?