Categories: Assembly, OpenJDK

OpenJDK SafeFetch Implementation on AArch64

I changed Windows AArch64 exception handling in 8348862: runtime/ErrorHandling/CreateCoredumpOnCrash fails on Windows aarch64 by swesonga · Pull Request #27074 · openjdk/jdk. In the process, I discovered that the safefetch implementation on Windows AArch64 was broken. SafeFetchXX is a function that takes a pointer and an error value and tries to read the value at the pointer. If it is read successfully, that value is returned, otherwise, the error value is returned.

Before my changes, safefetch.hpp included safefetch_windows.hpp, which uses structured exception handling. The read is done in a __try { } __except block. However, the Windows AArch64 port uses vectored exception handling. This is therefore not the right approach. I added the !defined(_M_ARM64) check to ensure that safefetch_static.hpp is included instead. This requires us to implement SafeFetch32_impl and SafeFetchN_impl, the same way the Linux and macosx AArch64 implementation do. These functions are declared as extern C because they will be implemented in assembly, specifically in safefetch_windows_aarch64.S. Here’s the implementation of SafeFetchN_impl (copied to match the other 2 AArch64 platforms):

    ; Support for intptr_t SafeFetchN(intptr_t* address, intptr_t defaultval);
    ;
    ;  x0 : address
    ;  x1 : defaultval

    ALIGN  4
    EXPORT _SafeFetchN_fault
    EXPORT _SafeFetchN_continuation
    EXPORT SafeFetchN_impl

SafeFetchN_impl
_SafeFetchN_fault
    ldr      x0, [x0]
    ret

_SafeFetchN_continuation
    mov      x0, x1
    ret

    END

Notice that it is a 4 assembly instructions function. The ldr instruction tries to dereference the pointer in x0. If the memory access succeeds, the function returns the loaded value successfully. Otherwise, the exception handler will be invoked. The exception handling logic checks whether the exception being handled was caused by the safefetch load. This is where the _SafeFetchN_fault label comes into play. If the exception is an EXCEPTION_ACCESS_VIOLATION, we can check whether the PC was at the _SafeFetchN_fault (the ldr) instruction. If so, the exception handler sets the PC in the OS CONTEXT structure to the _SafeFetchN_continuation instruction. The exception handler then returns EXCEPTION_CONTINUE_EXECUTION to allow execution to resume successfully at the mov instruction, which simply loads x0 with the error value that was passed in x1. The 32-bit safefetch function has an identical structure.

Article info



Leave a Reply

Your email address will not be published. Required fields are marked *