* [RFC PATCH v1 0/4] Libffi Static Trampolines [not found] <9bd94fd78a3c8f638b8a0d2269258da99d58e70f> @ 2020-11-24 19:32 ` madvenka 2020-11-24 19:32 ` [RFC PATCH v1 1/4] " madvenka ` (3 more replies) 0 siblings, 4 replies; 12+ messages in thread From: madvenka @ 2020-11-24 19:32 UTC (permalink / raw) To: libffi-discuss; +Cc: fw, dj, madvenka From: "Madhavan T. Venkataraman" <madvenka@linux.microsoft.com> Closures ======== Libffi supports a feature called "Closures". Closures enable a program to call a function whose arguments, argument types and return value are known only at runtime. Also, the calling conventions of the called function can be different from native calling conventions. Closures support a variety of architectures and Application Binary Interfaces or ABIs. The calling conventions are defined in the ABI. Closure Trampoline ================== When a program invokes a closure, a libffi supplied trampoline is executed. The trampoline loads the closure pointer in a designated register or on the stack (depending on the ABI of the target function) and jumps to an ABI handler. The ABI handler extracts arguments from the closure, calls the target function and returns the function's return value in the native ABI. To the program, it appears as if the target function was called natively. Security Issue ============== Currently, the trampoline code used in libffi is not statically defined in a source file (except for MACH). The trampoline is either pre-defined machine code in a data buffer. Or, it is generated at runtime. In order to execute a trampoline, it needs to be placed in a page with executable permissions. Executable data pages are attack surfaces for attackers who may try to inject their own code into the page and contrive to have it executed. The security settings in a system may prevent various tricks used in user land to write code into a page and to have it executed somehow. On such systems, libffi trampolines would not be able to run. NOTE: The ABI handlers are all statically defined. Static Trampoline ================= To solve this problem, the trampoline code needs to be defined statically in a source file, compiled and placed in the text segment so it can be mapped and executed naturally without any tricks. However, the trampoline needs to be able to access the closure pointer at runtime. PC-relative data referencing ============================ The solution implemented in this patch set uses PC-relative data references. The trampoline is mapped in a code page. Adjacent to the code page, a data page is mapped that contains the parameters of the trampoline: - the closure pointer - pointer to the ABI handler to jump to The trampoline code uses an offset relative to its current PC to access its data. Some architectures support PC-relative data references in the ISA itself. E.g., X64 supports RIP-relative references. For others, the PC has to somehow be loaded into a general purpose register to do PC-relative data referencing. To do this, we need to define a get_pc() kind of function and call it to load the PC in a desired register. There are two cases: 1. The call instruction pushes the return address on the stack. In this case, get_pc() will extract the return address from the stack and load it in the desired register and return. 2. The call instruction stores the return address in a designated register. In this case, get_pc() will copy the return address to the desired register and return. Either way, the PC next to the call instruction is obtained. Scratch register ================ In order to do its job, the trampoline code would be required to use a scratch register. Depending on the ABI, there may not be a register available for scratch. This problem needs to be solved so that all ABIs will work. The trampoline will save two values on the stack: - the closure pointer - the original value of the scratch register This is what the stack will look like: sp before trampoline ------> -------------------- | closure pointer | -------------------- | scratch register | sp after trampoline -------> -------------------- The ABI handler can do the following as needed by the ABI: - the closure pointer can be loaded in a desired register - the scratch register can be restored to its original value - the stack pointer can be restored to its original value (when the trampoline was invoked) Thus the ABI handlers will have a couple of lines of code at the very beginning to do this so that all ABIs will work. NOTE: The documentation for this feature will contain information on: - the name of the scratch register for each architecture - the stack offsets at which the closure and the scratch register will be copied Trampoline Table ================ In order to reduce the trampoline memory footprint, the trampoline code would be defined as a code array in the text segment. This array would be mapped into the address space of the caller. The mapping would, therefore, contain a trampoline table. Adjacent to the trampoline table, there will be a data mapping that contains a parameter table, one parameter block for each trampoline. The parameter table will contain: - a pointer to the closure - a pointer to the ABI handler The trampoline code would finally look like this: - Make space on the stack for the closure and the scratch register by moving the stack pointer down - Store the original value of the scratch register on the stack - Using PC-relative reference, get the closure pointer - Store the closure pointer on the stack - Using PC-relative reference, get the ABI handler pointer - Jump to the ABI handler Trampoline API ============== There is a lot of dynamic code out there. They all have the same security issue. Dynamic code can be re-written into static code provided the data required by the static code can be passed to it just like we pass the closure pointer to an ABI handler. So, the same trampoline functions used by libffi internally need to be made available to the rest of the world in the form of an API. The following API has been defined in this solution: int ffi_tramp_is_supported(void); To support static trampolines, code needs to be added to each architecture. Also, the feature itself can be enabled via a configuration option. So, this function tells us if the feature is supported and enabled in the current libffi or not. void *ffi_tramp_alloc (int flags); Allocate a trampoline. Currently, flags are zero. An opaque trampoline structure pointer is returned. Internally, libffi manages trampoline tables and individual trampolines in each table. int ffi_tramp_set_parms (void *tramp, void *target, void *data); Initialize the parameters of a trampoline. That is, the target code that the trampoline should jump to and the data that needs to be passed to the target code. void *ffi_tramp_get_addr (void *tramp); Return the address of the trampoline to invoke the trampoline with. The trampoline can be invoked in one of two ways: - Simply branch to the trampoline address - Treat the trampoline address as a function pointer and call it. Which method is used depends on the target code. void ffi_tramp_free (void *tramp); Free a trampoline. Testing ======= The libffi selftests have been run successfully on X86 and ARM, 32-bit and 64-bit. I also have my own API test that does stress testing of the API. TBD === I need to study how to include my trampoline API test in the libffi selftests. Signed-off-by: Madhavan T. Venkataraman <madvenka@linux.microsoft.com> Madhavan T. Venkataraman (4): Libffi Static Trampolines x86: Support for Static Trampolines aarch64: Support for Static Trampolines arm: Support for Static Trampolines Makefile.am | 3 +- configure.ac | 7 + include/ffi.h.in | 13 +- include/ffi_common.h | 4 + libffi.map.in | 11 + src/aarch64/ffi.c | 16 + src/aarch64/internal.h | 10 + src/aarch64/sysv.S | 46 ++ src/arm/ffi.c | 16 + src/arm/internal.h | 10 + src/arm/sysv.S | 37 ++ src/closures.c | 54 +- src/tramp.c | 563 ++++++++++++++++++++ src/x86/ffi.c | 17 + src/x86/ffi64.c | 19 +- src/x86/ffiw64.c | 8 +- src/x86/internal.h | 10 + src/x86/internal64.h | 10 + src/x86/sysv.S | 52 ++ src/x86/unix64.S | 48 ++ src/x86/win64.S | 4 + testsuite/libffi.closures/closure_loc_fn0.c | 3 + 22 files changed, 952 insertions(+), 9 deletions(-) create mode 100644 src/tramp.c -- 2.25.1 ^ permalink raw reply [flat|nested] 12+ messages in thread
* [RFC PATCH v1 1/4] Static Trampolines 2020-11-24 19:32 ` [RFC PATCH v1 0/4] Libffi Static Trampolines madvenka @ 2020-11-24 19:32 ` madvenka 2020-11-24 19:49 ` Anthony Green 2020-11-24 19:32 ` [RFC PATCH v1 2/4] x86: Support for Static Trampolines madvenka ` (2 subsequent siblings) 3 siblings, 1 reply; 12+ messages in thread From: madvenka @ 2020-11-24 19:32 UTC (permalink / raw) To: libffi-discuss; +Cc: fw, dj, madvenka From: "Madhavan T. Venkataraman" <madvenka@linux.microsoft.com> Closure Trampoline Security Issue ================================= Currently, the trampoline code used in libffi is not statically defined in a source file (except for MACH). The trampoline is either pre-defined machine code in a data buffer. Or, it is generated at runtime. In order to execute a trampoline, it needs to be placed in a page with executable permissions. Executable data pages are attack surfaces for attackers who may try to inject their own code into the page and contrive to have it executed. The security settings in a system may prevent various tricks used in user land to write code into a page and to have it executed somehow. On such systems, libffi trampolines would not be able to run. Static Trampoline ================= To solve this problem, the trampoline code needs to be defined statically in a source file, compiled and placed in the text segment so it can be mapped and executed naturally without any tricks. However, the trampoline needs to be able to access the closure pointer at runtime. PC-relative data referencing ============================ The solution implemented in this patch set uses PC-relative data references. The trampoline is mapped in a code page. Adjacent to the code page, a data page is mapped that contains the parameters of the trampoline: - the closure pointer - pointer to the ABI handler to jump to The trampoline code uses an offset relative to its current PC to access its data. Some architectures support PC-relative data references in the ISA itself. E.g., X64 supports RIP-relative references. For others, the PC has to somehow be loaded into a general purpose register to do PC-relative data referencing. To do this, we need to define a get_pc() kind of function and call it to load the PC in a desired register. There are two cases: 1. The call instruction pushes the return address on the stack. In this case, get_pc() will extract the return address from the stack and load it in the desired register and return. 2. The call instruction stores the return address in a designated register. In this case, get_pc() will copy the return address to the desired register and return. Either way, the PC next to the call instruction is obtained. Scratch register ================ In order to do its job, the trampoline code would be required to use a scratch register. Depending on the ABI, there may not be a register available for scratch. This problem needs to be solved so that all ABIs will work. The trampoline will save two values on the stack: - the closure pointer - the original value of the scratch register This is what the stack will look like: sp before trampoline ------> -------------------- | closure pointer | -------------------- | scratch register | sp after trampoline -------> -------------------- The ABI handler can do the following as needed by the ABI: - the closure pointer can be loaded in a desired register - the scratch register can be restored to its original value - the stack pointer can be restored to its original value (when the trampoline was invoked) Thus the ABI handlers will have a couple of lines of code at the very beginning to do this so that all ABIs will work. NOTE: The documentation for this feature will contain information on: - the name of the scratch register for each architecture - the stack offsets at which the closure and the scratch register will be copied Trampoline Table ================ In order to reduce the trampoline memory footprint, the trampoline code would be defined as a code array in the text segment. This array would be mapped into the address space of the caller. The mapping would, therefore, contain a trampoline table. Adjacent to the trampoline table, there will be a data mapping that contains a parameter table, one parameter block for each trampoline. The parameter table will contain: - a pointer to the closure - a pointer to the ABI handler The trampoline code would finally look like this: - Make space on the stack for the closure and the scratch register by moving the stack pointer down - Store the original value of the scratch register on the stack - Using PC-relative reference, get the closure pointer - Store the closure pointer on the stack - Using PC-relative reference, get the ABI handler pointer - Jump to the ABI handler Trampoline API ============== There is a lot of dynamic code out there. They all have the same security issue. Dynamic code can be re-written into static code provided the data required by the static code can be passed to it just like we pass the closure pointer to an ABI handler. So, the same trampoline functions used by libffi internally need to be made available to the rest of the world in the form of an API. The following API has been defined in this solution: int ffi_tramp_is_supported(void); To support static trampolines, code needs to be added to each architecture. Also, the feature itself can be enabled via a configuration option. So, this function tells us if the feature is supported and enabled in the current libffi or not. void *ffi_tramp_alloc (int flags); Allocate a trampoline. Currently, flags are zero. An opaque trampoline structure pointer is returned. Internally, libffi manages trampoline tables and individual trampolines in each table. int ffi_tramp_set_parms (void *tramp, void *target, void *data); Initialize the parameters of a trampoline. That is, the target code that the trampoline should jump to and the data that needs to be passed to the target code. void *ffi_tramp_get_addr (void *tramp); Return the address of the trampoline to invoke the trampoline with. The trampoline can be invoked in one of two ways: - Simply branch to the trampoline address - Treat the trampoline address as a function pointer and call it. Which method is used depends on the target code. void ffi_tramp_free (void *tramp); Free a trampoline. Configuration ============= A new configuration option, --enable-static-tramp has been added to enable the use of static trampolines. Mapping size ============ The size of the code mapping that contains the trampoline table needs to be determined on a per architecture basis. If a particular architecture supports multiple base page sizes, then the largest base page size needs to be chosen. E.g., we choose 16K for ARM64. Trampoline allocation and free ============================== Static trampolines are allocated in ffi_closure_alloc() and freed in ffi_closure_free(). Normally, applications use these functions. But there are some cases out there where the user of libffi allocates and manages its own closure memory. In such cases, the static trampoline API cannot be used. These will fall back to using legacy trampolines. The user has to make sure that the memory is executable. ffi_closure structure ===================== I did not want to make any changes to the size of the closure structure for this feature to guarantee compatibility. But the opaque static trampoline handle needs to be stored in the closure. I have defined it as follows: - char tramp[FFI_TRAMPOLINE_SIZE]; + union { + char tramp[FFI_TRAMPOLINE_SIZE]; + void *ftramp; + }; If static trampolines are used, then tramp[] is not needed to store a dynamic trampoline. That space can be reused to store the handle. Hence, the union. Signed-off-by: Madhavan T. Venkataraman <madvenka@linux.microsoft.com> --- Makefile.am | 3 +- configure.ac | 7 + include/ffi.h.in | 13 +- include/ffi_common.h | 4 + libffi.map.in | 11 + src/closures.c | 54 +- src/tramp.c | 563 ++++++++++++++++++++ testsuite/libffi.closures/closure_loc_fn0.c | 3 + 8 files changed, 654 insertions(+), 4 deletions(-) create mode 100644 src/tramp.c diff --git a/Makefile.am b/Makefile.am index 7654bf5..1b18198 100644 --- a/Makefile.am +++ b/Makefile.am @@ -38,7 +38,8 @@ toolexeclib_LTLIBRARIES = libffi.la noinst_LTLIBRARIES = libffi_convenience.la libffi_la_SOURCES = src/prep_cif.c src/types.c \ - src/raw_api.c src/java_raw_api.c src/closures.c + src/raw_api.c src/java_raw_api.c src/closures.c \ + src/tramp.c if FFI_DEBUG libffi_la_SOURCES += src/debug.c diff --git a/configure.ac b/configure.ac index 790274e..898ede6 100644 --- a/configure.ac +++ b/configure.ac @@ -360,6 +360,13 @@ AC_ARG_ENABLE(raw-api, AC_DEFINE(FFI_NO_RAW_API, 1, [Define this if you do not want support for the raw API.]) fi) +AC_ARG_ENABLE(static-tramp, +[ --enable-static-tramp use statically defined trampolines], + if test "$enable_static_tramp" = "yes"; then + AC_DEFINE(FFI_EXEC_STATIC_TRAMP, 1, + [Define this if you want to use statically defined trampolines.]) + fi) + AC_ARG_ENABLE(purify-safety, [ --enable-purify-safety purify-safe mode], if test "$enable_purify_safety" = "yes"; then diff --git a/include/ffi.h.in b/include/ffi.h.in index 38885b0..c6a21d9 100644 --- a/include/ffi.h.in +++ b/include/ffi.h.in @@ -310,7 +310,10 @@ typedef struct { void *trampoline_table; void *trampoline_table_entry; #else - char tramp[FFI_TRAMPOLINE_SIZE]; + union { + char tramp[FFI_TRAMPOLINE_SIZE]; + void *ftramp; + }; #endif ffi_cif *cif; void (*fun)(ffi_cif*,void*,void**,void*); @@ -457,6 +460,14 @@ FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue, #endif /* FFI_GO_CLOSURES */ +/* ---- Static Trampoline Definitions -------------------------------------- */ + +FFI_API int ffi_tramp_is_supported(void); +FFI_API void *ffi_tramp_alloc (int flags); +FFI_API int ffi_tramp_set_parms (void *tramp, void *data, void *code); +FFI_API void *ffi_tramp_get_addr (void *tramp); +FFI_API void ffi_tramp_free (void *tramp); + /* ---- Public interface definition -------------------------------------- */ FFI_API diff --git a/include/ffi_common.h b/include/ffi_common.h index 76b9dd6..8743126 100644 --- a/include/ffi_common.h +++ b/include/ffi_common.h @@ -103,6 +103,10 @@ ffi_status ffi_prep_cif_core(ffi_cif *cif, some targets. */ void *ffi_data_to_code_pointer (void *data) FFI_HIDDEN; +/* The arch code calls this to set the code and data parameters for a + closure's static trampoline, if any. */ +int ffi_closure_tramp_set_parms (void *closure, void *code); + /* Extended cif, used in callback from assembly routine */ typedef struct { diff --git a/libffi.map.in b/libffi.map.in index de8778a..049c73e 100644 --- a/libffi.map.in +++ b/libffi.map.in @@ -74,3 +74,14 @@ LIBFFI_GO_CLOSURE_8.0 { ffi_prep_go_closure; } LIBFFI_CLOSURE_8.0; #endif + +#if FFI_EXEC_STATIC_TRAMP +LIBFFI_STATIC_TRAMP_8.0 { + global: + ffi_tramp_is_supported; + ffi_tramp_alloc; + ffi_tramp_set_parms; + ffi_tramp_get_addr; + ffi_tramp_free; +} LIBFFI_BASE_8.0; +#endif diff --git a/src/closures.c b/src/closures.c index 4fe6158..cf1d3de 100644 --- a/src/closures.c +++ b/src/closures.c @@ -109,6 +109,12 @@ ffi_closure_free (void *ptr) munmap(dataseg, rounded_size); munmap(codeseg, rounded_size); } + +int +ffi_closure_tramp_set_parms (void *ptr, void *code) +{ + return 0; +} #else /* !NetBSD with PROT_MPROTECT */ #if !FFI_MMAP_EXEC_WRIT && !FFI_EXEC_TRAMPOLINE_TABLE @@ -843,6 +849,12 @@ dlmmap (void *start, size_t length, int prot, && flags == (MAP_PRIVATE | MAP_ANONYMOUS) && fd == -1 && offset == 0); + if (execfd == -1 && ffi_tramp_is_supported ()) + { + ptr = mmap (start, length, prot & ~PROT_EXEC, flags, fd, offset); + return ptr; + } + if (execfd == -1 && is_emutramp_enabled ()) { ptr = mmap (start, length, prot & ~PROT_EXEC, flags, fd, offset); @@ -922,7 +934,7 @@ segment_holding_code (mstate m, char* addr) void * ffi_closure_alloc (size_t size, void **code) { - void *ptr; + void *ptr, *ftramp; if (!code) return NULL; @@ -934,6 +946,17 @@ ffi_closure_alloc (size_t size, void **code) msegmentptr seg = segment_holding (gm, ptr); *code = add_segment_exec_offset (ptr, seg); + if (!ffi_tramp_is_supported ()) + return ptr; + + ftramp = ffi_tramp_alloc (0); + if (ftramp == NULL) + { + dlfree (FFI_RESTORE_PTR (ptr)); + return NULL; + } + *code = ffi_tramp_get_addr (ftramp); + ((ffi_closure *) ptr)->ftramp = ftramp; } return ptr; @@ -943,12 +966,17 @@ void * ffi_data_to_code_pointer (void *data) { msegmentptr seg = segment_holding (gm, data); + /* We expect closures to be allocated with ffi_closure_alloc(), in which case seg will be non-NULL. However, some users take on the burden of managing this memory themselves, in which case this we'll just return data. */ if (seg) - return add_segment_exec_offset (data, seg); + { + if (!ffi_tramp_is_supported ()) + return add_segment_exec_offset (data, seg); + return ffi_tramp_get_addr (((ffi_closure *) data)->ftramp); + } else return data; } @@ -966,10 +994,26 @@ ffi_closure_free (void *ptr) if (seg) ptr = sub_segment_exec_offset (ptr, seg); #endif + if (ffi_tramp_is_supported ()) + ffi_tramp_free (((ffi_closure *) ptr)->ftramp); dlfree (FFI_RESTORE_PTR (ptr)); } +int +ffi_closure_tramp_set_parms (void *ptr, void *code) +{ + void *ftramp; + + msegmentptr seg = segment_holding (gm, ptr); + if (!seg || !ffi_tramp_is_supported()) + return 0; + + ftramp = ((ffi_closure *) ptr)->ftramp; + ffi_tramp_set_parms (ftramp, code, ptr); + return 1; +} + # else /* ! FFI_MMAP_EXEC_WRIT */ /* On many systems, memory returned by malloc is writable and @@ -998,6 +1042,12 @@ ffi_data_to_code_pointer (void *data) return data; } +int +ffi_closure_tramp_set_parms (void *ptr, void *code) +{ + return 0; +} + # endif /* ! FFI_MMAP_EXEC_WRIT */ #endif /* FFI_CLOSURES */ diff --git a/src/tramp.c b/src/tramp.c new file mode 100644 index 0000000..3170152 --- /dev/null +++ b/src/tramp.c @@ -0,0 +1,563 @@ +/* ----------------------------------------------------------------------- + tramp.c - Copyright (c) 2020 Madhavan T. Venkataraman + + API and support functions for managing statically defined closure + trampolines. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + ``Software''), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + ----------------------------------------------------------------------- */ + +#include <stdio.h> +#include <unistd.h> +#include <stdlib.h> +#include <stdint.h> +#include <fcntl.h> +#include <pthread.h> +#include <sys/mman.h> +#include <linux/limits.h> +#include <linux/types.h> +#include <fficonfig.h> + +#if defined(FFI_EXEC_STATIC_TRAMP) + +#if !defined(__linux__) +#error "FFI_EXEC_STATIC_TRAMP is currently only supported on Linux" +#endif + +#if !defined _GNU_SOURCE +#define _GNU_SOURCE 1 +#endif + +/* + * Each architecture defines static code for a trampoline code table. The + * trampoline code table is mapped into the address space of a process. + * + * The following architecture specific function returns: + * + * - the address of the trampoline code table in the text segment + * - the size of each trampoline in the trampoline code table + * - the size of the mapping for the whole trampoline code table + */ +void __attribute__((weak)) *ffi_tramp_arch (size_t *tramp_size, + size_t *map_size); + +/* ------------------------- Trampoline Data Structures --------------------*/ + +static pthread_mutex_t tramp_lock = PTHREAD_MUTEX_INITIALIZER; + +struct tramp; + +/* + * Trampoline table. Manages one trampoline code table and one trampoline + * parameter table. + * + * prev, next Links in the global trampoline table list. + * code_table Trampoline code table mapping. + * parm_table Trampoline parameter table mapping. + * array Array of trampolines malloced. + * free List of free trampolines. + * nfree Number of free trampolines. + */ +struct tramp_table +{ + struct tramp_table *prev; + struct tramp_table *next; + void *code_table; + void *parm_table; + struct tramp *array; + struct tramp *free; + int nfree; +}; + +/* + * Parameters for each trampoline. + * + * data + * Data for the target code that the trampoline jumps to. + * target + * Target code that the trampoline jumps to. + */ +struct tramp_parm +{ + void *data; + void *target; +}; + +/* + * Trampoline structure for each trampoline. + * + * prev, next Links in the trampoline free list of a trampoline table. + * table Trampoline table to which this trampoline belongs. + * code Address of this trampoline in the code table mapping. + * parm Address of this trampoline's parameters in the parameter + * table mapping. + */ +struct tramp +{ + struct tramp *prev; + struct tramp *next; + struct tramp_table *table; + void *code; + struct tramp_parm *parm; +}; + +/* + * Trampoline globals. + * + * fd + * File descriptor of binary file that contains the trampoline code table. + * offset + * Offset of the trampoline code table in that file. + * map_size + * Size of the trampoline code table mapping. + * size + * Size of one trampoline in the trampoline code table. + * ntramp + * Total number of trampolines in the trampoline code table. + * tables + * List of trampoline tables that contain free trampolines. + * ntables + * Number of trampoline tables that contain free trampolines. + */ +struct tramp_global +{ + int fd; + off_t offset; + size_t map_size; + size_t size; + int ntramp; + struct tramp_table *tables; + int ntables; +}; + +static struct tramp_global gtramp = { -1 }; + +/* ------------------------ Trampoline Initialization ----------------------*/ + +static int ffi_tramp_get_fd_offset (void *tramp_text, off_t *offset); + +/* + * Initialize the static trampoline feature. + */ +static int +ffi_tramp_init (void) +{ + if (ffi_tramp_arch == NULL) + return 0; + + if (gtramp.fd == -1) + { + void *tramp_text; + + gtramp.tables = NULL; + gtramp.ntables = 0; + + /* + * Get trampoline code table information from the architecture. + */ + tramp_text = ffi_tramp_arch (>ramp.size, >ramp.map_size); + gtramp.ntramp = gtramp.map_size / gtramp.size; + + /* + * Get the binary file that contains the trampoline code table and also + * the offset of the table within the file. These are used to mmap() + * the trampoline code table. + */ + gtramp.fd = ffi_tramp_get_fd_offset (tramp_text, >ramp.offset); + } + return gtramp.fd != -1; +} + +/* + * From the address of the trampoline code table in the text segment, find the + * binary file and offset of the trampoline code table from /proc/<pid>/maps. + */ +static int +ffi_tramp_get_fd_offset (void *tramp_text, off_t *offset) +{ + FILE *fp; + char file[PATH_MAX], line[PATH_MAX+100], perm[10], dev[10]; + unsigned long start, end, inode; + uintptr_t addr = (uintptr_t) tramp_text; + int nfields, found; + + snprintf (file, PATH_MAX, "/proc/%d/maps", getpid()); + fp = fopen (file, "r"); + if (fp == NULL) + return -1; + + found = 0; + while (feof (fp) == 0) { + if (fgets (line, sizeof (line), fp) == 0) + break; + + nfields = sscanf (line, "%lx-%lx %s %lx %s %ld %s", + &start, &end, perm, offset, dev, &inode, file); + if (nfields != 7) + continue; + + if (addr >= start && addr < end) { + *offset += (addr - start); + found = 1; + break; + } + } + fclose (fp); + + if (!found) + return -1; + + return open (file, O_RDONLY); +} + +/* ---------------------- Trampoline Table functions ---------------------- */ + +static int tramp_table_map (char **code_table, char **parm_table); +static void tramp_add (struct tramp *tramp); + +/* + * Allocate and initialize a trampoline table. + */ +static int +tramp_table_alloc (void) +{ + char *code_table, *parm_table; + struct tramp_table *table; + struct tramp *tramp_array, *tramp; + size_t size; + char *code, *parm; + int i; + + /* + * If we already have tables with free trampolines, there is no need to + * allocate a new table. + */ + if (gtramp.ntables > 0) + return 1; + + /* + * Allocate a new trampoline table structure. + */ + table = malloc (sizeof (*table)); + if (table == NULL) + return 0; + + /* + * Allocate new trampoline structures. + */ + tramp_array = malloc (sizeof (*tramp) * gtramp.ntramp); + if (tramp_array == NULL) + goto free_table; + + /* + * Map a code table and a parameter table into the caller's address space. + */ + if (!tramp_table_map (&code_table, &parm_table)) + goto free_tramp_array; + + /* + * Initialize the trampoline table. + */ + table->code_table = code_table; + table->parm_table = parm_table; + table->array = tramp_array; + table->free = NULL; + table->nfree = 0; + + /* + * Populate the trampoline table free list. This will also add the trampoline + * table to the global list of trampoline tables. + */ + size = gtramp.size; + code = code_table; + parm = parm_table; + for (i = 0; i < gtramp.ntramp; i++) + { + tramp = &tramp_array[i]; + tramp->table = table; + tramp->code = code; + tramp->parm = (struct tramp_parm *) parm; + tramp_add (tramp); + + code += size; + parm += size; + } + return 1; + +free_tramp_array: + free (tramp_array); +free_table: + free (table); + return 0; +} + +/* + * Create a trampoline code table mapping and a trampoline parameter table + * mapping. The two mappings must be adjacent to each other for PC-relative + * access. + * + * For each trampoline in the code table, there is a corresponding parameter + * block in the parameter table. The size of the parameter block is the same + * as the size of the trampoline. This means that the parameter block is at + * a fixed offset from its trampoline making it easy for a trampoline to find + * its parameters using PC-relative access. + * + * The parameter block will contain a struct tramp_parm. This means that + * sizeof (struct tramp_parm) cannot exceed the size of a parameter block. + */ +static int +tramp_table_map (char **code_table, char **parm_table) +{ + char *addr; + + /* + * Create an anonymous mapping twice the map size. The top half will be used + * for the code table. The bottom half will be used for the parameter table. + */ + addr = mmap (NULL, gtramp.map_size * 2, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (addr == MAP_FAILED) + return 0; + + /* + * Replace the top half of the anonymous mapping with the code table mapping. + */ + *code_table = mmap (addr, gtramp.map_size, PROT_READ | PROT_EXEC, + MAP_PRIVATE | MAP_FIXED, gtramp.fd, gtramp.offset); + if (*code_table == MAP_FAILED) + { + (void) munmap (addr, gtramp.map_size * 2); + return 0; + } + *parm_table = *code_table + gtramp.map_size; + return 1; +} + +/* + * Free a trampoline table. + */ +static void +tramp_table_free (struct tramp_table *table) +{ + (void) munmap (table->code_table, gtramp.map_size); + (void) munmap (table->parm_table, gtramp.map_size); + free (table->array); + free (table); +} + +/* + * Add a new trampoline table to the global table list. + */ +static void +tramp_table_add (struct tramp_table *table) +{ + table->next = gtramp.tables; + table->prev = NULL; + if (gtramp.tables != NULL) + gtramp.tables->prev = table; + gtramp.tables = table; + gtramp.ntables++; +} + +/* + * Delete a trampoline table from the global table list. + */ +static void +tramp_table_del (struct tramp_table *table) +{ + gtramp.ntables--; + if (table->prev != NULL) + table->prev->next = table->next; + if (table->next != NULL) + table->next->prev = table->prev; + if (gtramp.tables == table) + gtramp.tables = table->next; +} + +/* ------------------------- Trampoline functions ------------------------- */ + +/* + * Add a trampoline to its trampoline table. + */ +static void +tramp_add (struct tramp *tramp) +{ + struct tramp_table *table = tramp->table; + + tramp->next = table->free; + tramp->prev = NULL; + if (table->free != NULL) + table->free->prev = tramp; + table->free = tramp; + table->nfree++; + + if (table->nfree == 1) + tramp_table_add (table); + + /* + * We don't want to keep too many free trampoline tables lying around. + */ + if (table->nfree == gtramp.ntramp && gtramp.ntables > 1) + { + tramp_table_del (table); + tramp_table_free (table); + } +} + +/* + * Remove a trampoline from its trampoline table. + */ +static void +tramp_del (struct tramp *tramp) +{ + struct tramp_table *table = tramp->table; + + table->nfree--; + if (tramp->prev != NULL) + tramp->prev->next = tramp->next; + if (tramp->next != NULL) + tramp->next->prev = tramp->prev; + if (table->free == tramp) + table->free = tramp->next; + + if (table->nfree == 0) + tramp_table_del (table); +} + +/* ------------------------ Trampoline API functions ------------------------ */ + +int +ffi_tramp_is_supported(void) +{ + int ret; + + pthread_mutex_lock (&tramp_lock); + ret = ffi_tramp_init (); + pthread_mutex_unlock (&tramp_lock); + return ret; +} + +/* + * Allocate a trampoline and return its opaque address. + */ +void * +ffi_tramp_alloc (int flags) +{ + struct tramp *tramp; + + pthread_mutex_lock (&tramp_lock); + + if (!ffi_tramp_init () || flags != 0) + { + pthread_mutex_unlock (&tramp_lock); + return NULL; + } + + if (!tramp_table_alloc ()) + { + pthread_mutex_unlock (&tramp_lock); + return NULL; + } + + tramp = gtramp.tables->free; + tramp_del (tramp); + + pthread_mutex_unlock (&tramp_lock); + + return tramp; +} + +/* + * Set the parameters for a trampoline. + */ +void +ffi_tramp_set_parms (void *arg, void *target, void *data) +{ + struct tramp *tramp = arg; + + pthread_mutex_lock (&tramp_lock); + tramp->parm->target = target; + tramp->parm->data = data; + pthread_mutex_unlock (&tramp_lock); +} + +/* + * Get the invocation address of a trampoline. + */ +void * +ffi_tramp_get_addr (void *arg) +{ + struct tramp *tramp = arg; + void *addr; + + pthread_mutex_lock (&tramp_lock); + addr = tramp->code; + pthread_mutex_unlock (&tramp_lock); + + return addr; +} + +/* + * Free a trampoline. + */ +void +ffi_tramp_free (void *arg) +{ + struct tramp *tramp = arg; + + pthread_mutex_lock (&tramp_lock); + tramp_add (tramp); + pthread_mutex_unlock (&tramp_lock); +} + +/* ------------------------------------------------------------------------- */ + +#else /* !FFI_EXEC_STATIC_TRAMP */ + +int +ffi_tramp_is_supported(void) +{ + return 0; +} + +void * +ffi_tramp_alloc (int flags) +{ + return NULL; +} + +void +ffi_tramp_set_parms (void *arg, void *target, void *data) +{ +} + +void * +ffi_tramp_get_addr (void *arg) +{ + return NULL; +} + +void +ffi_tramp_free (void *arg) +{ +} + +#endif /* FFI_EXEC_STATIC_TRAMP */ diff --git a/testsuite/libffi.closures/closure_loc_fn0.c b/testsuite/libffi.closures/closure_loc_fn0.c index b3afa0b..ad488ac 100644 --- a/testsuite/libffi.closures/closure_loc_fn0.c +++ b/testsuite/libffi.closures/closure_loc_fn0.c @@ -83,7 +83,10 @@ int main (void) CHECK(ffi_prep_closure_loc(pcl, &cif, closure_loc_test_fn0, (void *) 3 /* userdata */, codeloc) == FFI_OK); +#ifndef FFI_EXEC_STATIC_TRAMP + /* With static trampolines, the codeloc does not point to closure */ CHECK(memcmp(pcl, codeloc, sizeof(*pcl)) == 0); +#endif res = (*((closure_loc_test_type0)codeloc)) (1LL, 2, 3LL, 4, 127, 429LL, 7, 8, 9.5, 10, 11, 12, 13, -- 2.25.1 ^ permalink raw reply [flat|nested] 12+ messages in thread
* Re: [RFC PATCH v1 1/4] Static Trampolines 2020-11-24 19:32 ` [RFC PATCH v1 1/4] " madvenka @ 2020-11-24 19:49 ` Anthony Green 2020-11-24 20:02 ` Madhavan T. Venkataraman 2020-12-02 16:49 ` Madhavan T. Venkataraman 0 siblings, 2 replies; 12+ messages in thread From: Anthony Green @ 2020-11-24 19:49 UTC (permalink / raw) To: madvenka; +Cc: libffi-discuss, fw Thank you for your submission, Madhavan. This will be interesting reading! In the meantime, it would be helpful if you submitted this as a PR on GitHub. This will trigger CI testing for over 20 different systems so we can have an initial look at any build/test problems. AG On Tue, Nov 24, 2020 at 2:32 PM madvenka--- via Libffi-discuss < libffi-discuss@sourceware.org> wrote: > From: "Madhavan T. Venkataraman" <madvenka@linux.microsoft.com> > > Closure Trampoline Security Issue > ================================= > > Currently, the trampoline code used in libffi is not statically defined in > a source file (except for MACH). The trampoline is either pre-defined > machine code in a data buffer. Or, it is generated at runtime. In order to > execute a trampoline, it needs to be placed in a page with executable > permissions. > > Executable data pages are attack surfaces for attackers who may try to > inject their own code into the page and contrive to have it executed. The > security settings in a system may prevent various tricks used in user land > to write code into a page and to have it executed somehow. On such systems, > libffi trampolines would not be able to run. > > Static Trampoline > ================= > > To solve this problem, the trampoline code needs to be defined statically > in a source file, compiled and placed in the text segment so it can be > mapped and executed naturally without any tricks. However, the trampoline > needs to be able to access the closure pointer at runtime. > > PC-relative data referencing > ============================ > > The solution implemented in this patch set uses PC-relative data > references. > The trampoline is mapped in a code page. Adjacent to the code page, a data > page is mapped that contains the parameters of the trampoline: > > - the closure pointer > - pointer to the ABI handler to jump to > > The trampoline code uses an offset relative to its current PC to access its > data. > > Some architectures support PC-relative data references in the ISA itself. > E.g., X64 supports RIP-relative references. For others, the PC has to > somehow be loaded into a general purpose register to do PC-relative data > referencing. To do this, we need to define a get_pc() kind of function and > call it to load the PC in a desired register. > > There are two cases: > > 1. The call instruction pushes the return address on the stack. > > In this case, get_pc() will extract the return address from the stack > and load it in the desired register and return. > > 2. The call instruction stores the return address in a designated register. > > In this case, get_pc() will copy the return address to the desired > register and return. > > Either way, the PC next to the call instruction is obtained. > > Scratch register > ================ > > In order to do its job, the trampoline code would be required to use a > scratch register. Depending on the ABI, there may not be a register > available for scratch. This problem needs to be solved so that all ABIs > will work. > > The trampoline will save two values on the stack: > > - the closure pointer > - the original value of the scratch register > > This is what the stack will look like: > > sp before trampoline ------> -------------------- > | closure pointer | > -------------------- > | scratch register | > sp after trampoline -------> -------------------- > > The ABI handler can do the following as needed by the ABI: > > - the closure pointer can be loaded in a desired register > > - the scratch register can be restored to its original value > > - the stack pointer can be restored to its original value > (when the trampoline was invoked) > > Thus the ABI handlers will have a couple of lines of code at the very > beginning to do this so that all ABIs will work. > > NOTE: > The documentation for this feature will contain information on: > > - the name of the scratch register for each architecture > > - the stack offsets at which the closure and the scratch register > will be copied > > Trampoline Table > ================ > > In order to reduce the trampoline memory footprint, the trampoline code > would be defined as a code array in the text segment. This array would be > mapped into the address space of the caller. The mapping would, therefore, > contain a trampoline table. > > Adjacent to the trampoline table, there will be a data mapping that > contains > a parameter table, one parameter block for each trampoline. The parameter > table will contain: > > - a pointer to the closure > - a pointer to the ABI handler > > The trampoline code would finally look like this: > > - Make space on the stack for the closure and the scratch register > by moving the stack pointer down > - Store the original value of the scratch register on the stack > - Using PC-relative reference, get the closure pointer > - Store the closure pointer on the stack > - Using PC-relative reference, get the ABI handler pointer > - Jump to the ABI handler > > Trampoline API > ============== > > There is a lot of dynamic code out there. They all have the same security > issue. Dynamic code can be re-written into static code provided the data > required by the static code can be passed to it just like we pass the > closure pointer to an ABI handler. > > So, the same trampoline functions used by libffi internally need to be > made available to the rest of the world in the form of an API. The > following API has been defined in this solution: > > int ffi_tramp_is_supported(void); > > To support static trampolines, code needs to be added to each > architecture. Also, the feature itself can be enabled via a > configuration option. So, this function tells us if the feature > is supported and enabled in the current libffi or not. > > void *ffi_tramp_alloc (int flags); > > Allocate a trampoline. Currently, flags are zero. An opaque > trampoline structure pointer is returned. > > Internally, libffi manages trampoline tables and individual > trampolines in each table. > > int ffi_tramp_set_parms (void *tramp, void *target, void *data); > > Initialize the parameters of a trampoline. That is, the target code > that the trampoline should jump to and the data that needs to be > passed to the target code. > > void *ffi_tramp_get_addr (void *tramp); > > Return the address of the trampoline to invoke the trampoline with. > The trampoline can be invoked in one of two ways: > > - Simply branch to the trampoline address > - Treat the trampoline address as a function pointer and > call it. > > Which method is used depends on the target code. > > void ffi_tramp_free (void *tramp); > > Free a trampoline. > > Configuration > ============= > > A new configuration option, --enable-static-tramp has been added to enable > the use of static trampolines. > > Mapping size > ============ > > The size of the code mapping that contains the trampoline table needs to be > determined on a per architecture basis. If a particular architecture > supports multiple base page sizes, then the largest base page size needs to > be chosen. E.g., we choose 16K for ARM64. > > Trampoline allocation and free > ============================== > > Static trampolines are allocated in ffi_closure_alloc() and freed in > ffi_closure_free(). > > Normally, applications use these functions. But there are some cases out > there where the user of libffi allocates and manages its own closure > memory. In such cases, the static trampoline API cannot be used. These > will fall back to using legacy trampolines. The user has to make sure > that the memory is executable. > > ffi_closure structure > ===================== > > I did not want to make any changes to the size of the closure structure for > this feature to guarantee compatibility. But the opaque static trampoline > handle needs to be stored in the closure. I have defined it as follows: > > - char tramp[FFI_TRAMPOLINE_SIZE]; > + union { > + char tramp[FFI_TRAMPOLINE_SIZE]; > + void *ftramp; > + }; > > If static trampolines are used, then tramp[] is not needed to store a > dynamic trampoline. That space can be reused to store the handle. Hence, > the union. > > Signed-off-by: Madhavan T. Venkataraman <madvenka@linux.microsoft.com> > --- > Makefile.am | 3 +- > configure.ac | 7 + > include/ffi.h.in | 13 +- > include/ffi_common.h | 4 + > libffi.map.in | 11 + > src/closures.c | 54 +- > src/tramp.c | 563 ++++++++++++++++++++ > testsuite/libffi.closures/closure_loc_fn0.c | 3 + > 8 files changed, 654 insertions(+), 4 deletions(-) > create mode 100644 src/tramp.c > > diff --git a/Makefile.am b/Makefile.am > index 7654bf5..1b18198 100644 > --- a/Makefile.am > +++ b/Makefile.am > @@ -38,7 +38,8 @@ toolexeclib_LTLIBRARIES = libffi.la > noinst_LTLIBRARIES = libffi_convenience.la > > libffi_la_SOURCES = src/prep_cif.c src/types.c \ > - src/raw_api.c src/java_raw_api.c src/closures.c > + src/raw_api.c src/java_raw_api.c src/closures.c \ > + src/tramp.c > > if FFI_DEBUG > libffi_la_SOURCES += src/debug.c > diff --git a/configure.ac b/configure.ac > index 790274e..898ede6 100644 > --- a/configure.ac > +++ b/configure.ac > @@ -360,6 +360,13 @@ AC_ARG_ENABLE(raw-api, > AC_DEFINE(FFI_NO_RAW_API, 1, [Define this if you do not want support > for the raw API.]) > fi) > > +AC_ARG_ENABLE(static-tramp, > +[ --enable-static-tramp use statically defined trampolines], > + if test "$enable_static_tramp" = "yes"; then > + AC_DEFINE(FFI_EXEC_STATIC_TRAMP, 1, > + [Define this if you want to use statically defined trampolines.]) > + fi) > + > AC_ARG_ENABLE(purify-safety, > [ --enable-purify-safety purify-safe mode], > if test "$enable_purify_safety" = "yes"; then > diff --git a/include/ffi.h.in b/include/ffi.h.in > index 38885b0..c6a21d9 100644 > --- a/include/ffi.h.in > +++ b/include/ffi.h.in > @@ -310,7 +310,10 @@ typedef struct { > void *trampoline_table; > void *trampoline_table_entry; > #else > - char tramp[FFI_TRAMPOLINE_SIZE]; > + union { > + char tramp[FFI_TRAMPOLINE_SIZE]; > + void *ftramp; > + }; > #endif > ffi_cif *cif; > void (*fun)(ffi_cif*,void*,void**,void*); > @@ -457,6 +460,14 @@ FFI_API void ffi_call_go (ffi_cif *cif, void > (*fn)(void), void *rvalue, > > #endif /* FFI_GO_CLOSURES */ > > +/* ---- Static Trampoline Definitions > -------------------------------------- */ > + > +FFI_API int ffi_tramp_is_supported(void); > +FFI_API void *ffi_tramp_alloc (int flags); > +FFI_API int ffi_tramp_set_parms (void *tramp, void *data, void *code); > +FFI_API void *ffi_tramp_get_addr (void *tramp); > +FFI_API void ffi_tramp_free (void *tramp); > + > /* ---- Public interface definition > -------------------------------------- */ > > FFI_API > diff --git a/include/ffi_common.h b/include/ffi_common.h > index 76b9dd6..8743126 100644 > --- a/include/ffi_common.h > +++ b/include/ffi_common.h > @@ -103,6 +103,10 @@ ffi_status ffi_prep_cif_core(ffi_cif *cif, > some targets. */ > void *ffi_data_to_code_pointer (void *data) FFI_HIDDEN; > > +/* The arch code calls this to set the code and data parameters for a > + closure's static trampoline, if any. */ > +int ffi_closure_tramp_set_parms (void *closure, void *code); > + > /* Extended cif, used in callback from assembly routine */ > typedef struct > { > diff --git a/libffi.map.in b/libffi.map.in > index de8778a..049c73e 100644 > --- a/libffi.map.in > +++ b/libffi.map.in > @@ -74,3 +74,14 @@ LIBFFI_GO_CLOSURE_8.0 { > ffi_prep_go_closure; > } LIBFFI_CLOSURE_8.0; > #endif > + > +#if FFI_EXEC_STATIC_TRAMP > +LIBFFI_STATIC_TRAMP_8.0 { > + global: > + ffi_tramp_is_supported; > + ffi_tramp_alloc; > + ffi_tramp_set_parms; > + ffi_tramp_get_addr; > + ffi_tramp_free; > +} LIBFFI_BASE_8.0; > +#endif > diff --git a/src/closures.c b/src/closures.c > index 4fe6158..cf1d3de 100644 > --- a/src/closures.c > +++ b/src/closures.c > @@ -109,6 +109,12 @@ ffi_closure_free (void *ptr) > munmap(dataseg, rounded_size); > munmap(codeseg, rounded_size); > } > + > +int > +ffi_closure_tramp_set_parms (void *ptr, void *code) > +{ > + return 0; > +} > #else /* !NetBSD with PROT_MPROTECT */ > > #if !FFI_MMAP_EXEC_WRIT && !FFI_EXEC_TRAMPOLINE_TABLE > @@ -843,6 +849,12 @@ dlmmap (void *start, size_t length, int prot, > && flags == (MAP_PRIVATE | MAP_ANONYMOUS) > && fd == -1 && offset == 0); > > + if (execfd == -1 && ffi_tramp_is_supported ()) > + { > + ptr = mmap (start, length, prot & ~PROT_EXEC, flags, fd, offset); > + return ptr; > + } > + > if (execfd == -1 && is_emutramp_enabled ()) > { > ptr = mmap (start, length, prot & ~PROT_EXEC, flags, fd, offset); > @@ -922,7 +934,7 @@ segment_holding_code (mstate m, char* addr) > void * > ffi_closure_alloc (size_t size, void **code) > { > - void *ptr; > + void *ptr, *ftramp; > > if (!code) > return NULL; > @@ -934,6 +946,17 @@ ffi_closure_alloc (size_t size, void **code) > msegmentptr seg = segment_holding (gm, ptr); > > *code = add_segment_exec_offset (ptr, seg); > + if (!ffi_tramp_is_supported ()) > + return ptr; > + > + ftramp = ffi_tramp_alloc (0); > + if (ftramp == NULL) > + { > + dlfree (FFI_RESTORE_PTR (ptr)); > + return NULL; > + } > + *code = ffi_tramp_get_addr (ftramp); > + ((ffi_closure *) ptr)->ftramp = ftramp; > } > > return ptr; > @@ -943,12 +966,17 @@ void * > ffi_data_to_code_pointer (void *data) > { > msegmentptr seg = segment_holding (gm, data); > + > /* We expect closures to be allocated with ffi_closure_alloc(), in > which case seg will be non-NULL. However, some users take on the > burden of managing this memory themselves, in which case this > we'll just return data. */ > if (seg) > - return add_segment_exec_offset (data, seg); > + { > + if (!ffi_tramp_is_supported ()) > + return add_segment_exec_offset (data, seg); > + return ffi_tramp_get_addr (((ffi_closure *) data)->ftramp); > + } > else > return data; > } > @@ -966,10 +994,26 @@ ffi_closure_free (void *ptr) > if (seg) > ptr = sub_segment_exec_offset (ptr, seg); > #endif > + if (ffi_tramp_is_supported ()) > + ffi_tramp_free (((ffi_closure *) ptr)->ftramp); > > dlfree (FFI_RESTORE_PTR (ptr)); > } > > +int > +ffi_closure_tramp_set_parms (void *ptr, void *code) > +{ > + void *ftramp; > + > + msegmentptr seg = segment_holding (gm, ptr); > + if (!seg || !ffi_tramp_is_supported()) > + return 0; > + > + ftramp = ((ffi_closure *) ptr)->ftramp; > + ffi_tramp_set_parms (ftramp, code, ptr); > + return 1; > +} > + > # else /* ! FFI_MMAP_EXEC_WRIT */ > > /* On many systems, memory returned by malloc is writable and > @@ -998,6 +1042,12 @@ ffi_data_to_code_pointer (void *data) > return data; > } > > +int > +ffi_closure_tramp_set_parms (void *ptr, void *code) > +{ > + return 0; > +} > + > # endif /* ! FFI_MMAP_EXEC_WRIT */ > #endif /* FFI_CLOSURES */ > > diff --git a/src/tramp.c b/src/tramp.c > new file mode 100644 > index 0000000..3170152 > --- /dev/null > +++ b/src/tramp.c > @@ -0,0 +1,563 @@ > +/* ----------------------------------------------------------------------- > + tramp.c - Copyright (c) 2020 Madhavan T. Venkataraman > + > + API and support functions for managing statically defined closure > + trampolines. > + > + Permission is hereby granted, free of charge, to any person obtaining > + a copy of this software and associated documentation files (the > + ``Software''), to deal in the Software without restriction, including > + without limitation the rights to use, copy, modify, merge, publish, > + distribute, sublicense, and/or sell copies of the Software, and to > + permit persons to whom the Software is furnished to do so, subject to > + the following conditions: > + > + The above copyright notice and this permission notice shall be included > + in all copies or substantial portions of the Software. > + > + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, > + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF > + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND > + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT > + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, > + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, > + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER > + DEALINGS IN THE SOFTWARE. > + > ----------------------------------------------------------------------- */ > + > +#include <stdio.h> > +#include <unistd.h> > +#include <stdlib.h> > +#include <stdint.h> > +#include <fcntl.h> > +#include <pthread.h> > +#include <sys/mman.h> > +#include <linux/limits.h> > +#include <linux/types.h> > +#include <fficonfig.h> > + > +#if defined(FFI_EXEC_STATIC_TRAMP) > + > +#if !defined(__linux__) > +#error "FFI_EXEC_STATIC_TRAMP is currently only supported on Linux" > +#endif > + > +#if !defined _GNU_SOURCE > +#define _GNU_SOURCE 1 > +#endif > + > +/* > + * Each architecture defines static code for a trampoline code table. The > + * trampoline code table is mapped into the address space of a process. > + * > + * The following architecture specific function returns: > + * > + * - the address of the trampoline code table in the text segment > + * - the size of each trampoline in the trampoline code table > + * - the size of the mapping for the whole trampoline code table > + */ > +void __attribute__((weak)) *ffi_tramp_arch (size_t *tramp_size, > + size_t *map_size); > + > +/* ------------------------- Trampoline Data Structures > --------------------*/ > + > +static pthread_mutex_t tramp_lock = PTHREAD_MUTEX_INITIALIZER; > + > +struct tramp; > + > +/* > + * Trampoline table. Manages one trampoline code table and one trampoline > + * parameter table. > + * > + * prev, next Links in the global trampoline table list. > + * code_table Trampoline code table mapping. > + * parm_table Trampoline parameter table mapping. > + * array Array of trampolines malloced. > + * free List of free trampolines. > + * nfree Number of free trampolines. > + */ > +struct tramp_table > +{ > + struct tramp_table *prev; > + struct tramp_table *next; > + void *code_table; > + void *parm_table; > + struct tramp *array; > + struct tramp *free; > + int nfree; > +}; > + > +/* > + * Parameters for each trampoline. > + * > + * data > + * Data for the target code that the trampoline jumps to. > + * target > + * Target code that the trampoline jumps to. > + */ > +struct tramp_parm > +{ > + void *data; > + void *target; > +}; > + > +/* > + * Trampoline structure for each trampoline. > + * > + * prev, next Links in the trampoline free list of a trampoline table. > + * table Trampoline table to which this trampoline belongs. > + * code Address of this trampoline in the code table > mapping. > + * parm Address of this trampoline's parameters in the > parameter > + * table mapping. > + */ > +struct tramp > +{ > + struct tramp *prev; > + struct tramp *next; > + struct tramp_table *table; > + void *code; > + struct tramp_parm *parm; > +}; > + > +/* > + * Trampoline globals. > + * > + * fd > + * File descriptor of binary file that contains the trampoline code > table. > + * offset > + * Offset of the trampoline code table in that file. > + * map_size > + * Size of the trampoline code table mapping. > + * size > + * Size of one trampoline in the trampoline code table. > + * ntramp > + * Total number of trampolines in the trampoline code table. > + * tables > + * List of trampoline tables that contain free trampolines. > + * ntables > + * Number of trampoline tables that contain free trampolines. > + */ > +struct tramp_global > +{ > + int fd; > + off_t offset; > + size_t map_size; > + size_t size; > + int ntramp; > + struct tramp_table *tables; > + int ntables; > +}; > + > +static struct tramp_global gtramp = { -1 }; > + > +/* ------------------------ Trampoline Initialization > ----------------------*/ > + > +static int ffi_tramp_get_fd_offset (void *tramp_text, off_t *offset); > + > +/* > + * Initialize the static trampoline feature. > + */ > +static int > +ffi_tramp_init (void) > +{ > + if (ffi_tramp_arch == NULL) > + return 0; > + > + if (gtramp.fd == -1) > + { > + void *tramp_text; > + > + gtramp.tables = NULL; > + gtramp.ntables = 0; > + > + /* > + * Get trampoline code table information from the architecture. > + */ > + tramp_text = ffi_tramp_arch (>ramp.size, >ramp.map_size); > + gtramp.ntramp = gtramp.map_size / gtramp.size; > + > + /* > + * Get the binary file that contains the trampoline code table and > also > + * the offset of the table within the file. These are used to mmap() > + * the trampoline code table. > + */ > + gtramp.fd = ffi_tramp_get_fd_offset (tramp_text, >ramp.offset); > + } > + return gtramp.fd != -1; > +} > + > +/* > + * From the address of the trampoline code table in the text segment, > find the > + * binary file and offset of the trampoline code table from > /proc/<pid>/maps. > + */ > +static int > +ffi_tramp_get_fd_offset (void *tramp_text, off_t *offset) > +{ > + FILE *fp; > + char file[PATH_MAX], line[PATH_MAX+100], perm[10], dev[10]; > + unsigned long start, end, inode; > + uintptr_t addr = (uintptr_t) tramp_text; > + int nfields, found; > + > + snprintf (file, PATH_MAX, "/proc/%d/maps", getpid()); > + fp = fopen (file, "r"); > + if (fp == NULL) > + return -1; > + > + found = 0; > + while (feof (fp) == 0) { > + if (fgets (line, sizeof (line), fp) == 0) > + break; > + > + nfields = sscanf (line, "%lx-%lx %s %lx %s %ld %s", > + &start, &end, perm, offset, dev, &inode, file); > + if (nfields != 7) > + continue; > + > + if (addr >= start && addr < end) { > + *offset += (addr - start); > + found = 1; > + break; > + } > + } > + fclose (fp); > + > + if (!found) > + return -1; > + > + return open (file, O_RDONLY); > +} > + > +/* ---------------------- Trampoline Table functions > ---------------------- */ > + > +static int tramp_table_map (char **code_table, char **parm_table); > +static void tramp_add (struct tramp *tramp); > + > +/* > + * Allocate and initialize a trampoline table. > + */ > +static int > +tramp_table_alloc (void) > +{ > + char *code_table, *parm_table; > + struct tramp_table *table; > + struct tramp *tramp_array, *tramp; > + size_t size; > + char *code, *parm; > + int i; > + > + /* > + * If we already have tables with free trampolines, there is no need to > + * allocate a new table. > + */ > + if (gtramp.ntables > 0) > + return 1; > + > + /* > + * Allocate a new trampoline table structure. > + */ > + table = malloc (sizeof (*table)); > + if (table == NULL) > + return 0; > + > + /* > + * Allocate new trampoline structures. > + */ > + tramp_array = malloc (sizeof (*tramp) * gtramp.ntramp); > + if (tramp_array == NULL) > + goto free_table; > + > + /* > + * Map a code table and a parameter table into the caller's address > space. > + */ > + if (!tramp_table_map (&code_table, &parm_table)) > + goto free_tramp_array; > + > + /* > + * Initialize the trampoline table. > + */ > + table->code_table = code_table; > + table->parm_table = parm_table; > + table->array = tramp_array; > + table->free = NULL; > + table->nfree = 0; > + > + /* > + * Populate the trampoline table free list. This will also add the > trampoline > + * table to the global list of trampoline tables. > + */ > + size = gtramp.size; > + code = code_table; > + parm = parm_table; > + for (i = 0; i < gtramp.ntramp; i++) > + { > + tramp = &tramp_array[i]; > + tramp->table = table; > + tramp->code = code; > + tramp->parm = (struct tramp_parm *) parm; > + tramp_add (tramp); > + > + code += size; > + parm += size; > + } > + return 1; > + > +free_tramp_array: > + free (tramp_array); > +free_table: > + free (table); > + return 0; > +} > + > +/* > + * Create a trampoline code table mapping and a trampoline parameter table > + * mapping. The two mappings must be adjacent to each other for > PC-relative > + * access. > + * > + * For each trampoline in the code table, there is a corresponding > parameter > + * block in the parameter table. The size of the parameter block is the > same > + * as the size of the trampoline. This means that the parameter block is > at > + * a fixed offset from its trampoline making it easy for a trampoline to > find > + * its parameters using PC-relative access. > + * > + * The parameter block will contain a struct tramp_parm. This means that > + * sizeof (struct tramp_parm) cannot exceed the size of a parameter block. > + */ > +static int > +tramp_table_map (char **code_table, char **parm_table) > +{ > + char *addr; > + > + /* > + * Create an anonymous mapping twice the map size. The top half will be > used > + * for the code table. The bottom half will be used for the parameter > table. > + */ > + addr = mmap (NULL, gtramp.map_size * 2, PROT_READ | PROT_WRITE, > + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); > + if (addr == MAP_FAILED) > + return 0; > + > + /* > + * Replace the top half of the anonymous mapping with the code table > mapping. > + */ > + *code_table = mmap (addr, gtramp.map_size, PROT_READ | PROT_EXEC, > + MAP_PRIVATE | MAP_FIXED, gtramp.fd, gtramp.offset); > + if (*code_table == MAP_FAILED) > + { > + (void) munmap (addr, gtramp.map_size * 2); > + return 0; > + } > + *parm_table = *code_table + gtramp.map_size; > + return 1; > +} > + > +/* > + * Free a trampoline table. > + */ > +static void > +tramp_table_free (struct tramp_table *table) > +{ > + (void) munmap (table->code_table, gtramp.map_size); > + (void) munmap (table->parm_table, gtramp.map_size); > + free (table->array); > + free (table); > +} > + > +/* > + * Add a new trampoline table to the global table list. > + */ > +static void > +tramp_table_add (struct tramp_table *table) > +{ > + table->next = gtramp.tables; > + table->prev = NULL; > + if (gtramp.tables != NULL) > + gtramp.tables->prev = table; > + gtramp.tables = table; > + gtramp.ntables++; > +} > + > +/* > + * Delete a trampoline table from the global table list. > + */ > +static void > +tramp_table_del (struct tramp_table *table) > +{ > + gtramp.ntables--; > + if (table->prev != NULL) > + table->prev->next = table->next; > + if (table->next != NULL) > + table->next->prev = table->prev; > + if (gtramp.tables == table) > + gtramp.tables = table->next; > +} > + > +/* ------------------------- Trampoline functions > ------------------------- */ > + > +/* > + * Add a trampoline to its trampoline table. > + */ > +static void > +tramp_add (struct tramp *tramp) > +{ > + struct tramp_table *table = tramp->table; > + > + tramp->next = table->free; > + tramp->prev = NULL; > + if (table->free != NULL) > + table->free->prev = tramp; > + table->free = tramp; > + table->nfree++; > + > + if (table->nfree == 1) > + tramp_table_add (table); > + > + /* > + * We don't want to keep too many free trampoline tables lying around. > + */ > + if (table->nfree == gtramp.ntramp && gtramp.ntables > 1) > + { > + tramp_table_del (table); > + tramp_table_free (table); > + } > +} > + > +/* > + * Remove a trampoline from its trampoline table. > + */ > +static void > +tramp_del (struct tramp *tramp) > +{ > + struct tramp_table *table = tramp->table; > + > + table->nfree--; > + if (tramp->prev != NULL) > + tramp->prev->next = tramp->next; > + if (tramp->next != NULL) > + tramp->next->prev = tramp->prev; > + if (table->free == tramp) > + table->free = tramp->next; > + > + if (table->nfree == 0) > + tramp_table_del (table); > +} > + > +/* ------------------------ Trampoline API functions > ------------------------ */ > + > +int > +ffi_tramp_is_supported(void) > +{ > + int ret; > + > + pthread_mutex_lock (&tramp_lock); > + ret = ffi_tramp_init (); > + pthread_mutex_unlock (&tramp_lock); > + return ret; > +} > + > +/* > + * Allocate a trampoline and return its opaque address. > + */ > +void * > +ffi_tramp_alloc (int flags) > +{ > + struct tramp *tramp; > + > + pthread_mutex_lock (&tramp_lock); > + > + if (!ffi_tramp_init () || flags != 0) > + { > + pthread_mutex_unlock (&tramp_lock); > + return NULL; > + } > + > + if (!tramp_table_alloc ()) > + { > + pthread_mutex_unlock (&tramp_lock); > + return NULL; > + } > + > + tramp = gtramp.tables->free; > + tramp_del (tramp); > + > + pthread_mutex_unlock (&tramp_lock); > + > + return tramp; > +} > + > +/* > + * Set the parameters for a trampoline. > + */ > +void > +ffi_tramp_set_parms (void *arg, void *target, void *data) > +{ > + struct tramp *tramp = arg; > + > + pthread_mutex_lock (&tramp_lock); > + tramp->parm->target = target; > + tramp->parm->data = data; > + pthread_mutex_unlock (&tramp_lock); > +} > + > +/* > + * Get the invocation address of a trampoline. > + */ > +void * > +ffi_tramp_get_addr (void *arg) > +{ > + struct tramp *tramp = arg; > + void *addr; > + > + pthread_mutex_lock (&tramp_lock); > + addr = tramp->code; > + pthread_mutex_unlock (&tramp_lock); > + > + return addr; > +} > + > +/* > + * Free a trampoline. > + */ > +void > +ffi_tramp_free (void *arg) > +{ > + struct tramp *tramp = arg; > + > + pthread_mutex_lock (&tramp_lock); > + tramp_add (tramp); > + pthread_mutex_unlock (&tramp_lock); > +} > + > +/* > ------------------------------------------------------------------------- */ > + > +#else /* !FFI_EXEC_STATIC_TRAMP */ > + > +int > +ffi_tramp_is_supported(void) > +{ > + return 0; > +} > + > +void * > +ffi_tramp_alloc (int flags) > +{ > + return NULL; > +} > + > +void > +ffi_tramp_set_parms (void *arg, void *target, void *data) > +{ > +} > + > +void * > +ffi_tramp_get_addr (void *arg) > +{ > + return NULL; > +} > + > +void > +ffi_tramp_free (void *arg) > +{ > +} > + > +#endif /* FFI_EXEC_STATIC_TRAMP */ > diff --git a/testsuite/libffi.closures/closure_loc_fn0.c > b/testsuite/libffi.closures/closure_loc_fn0.c > index b3afa0b..ad488ac 100644 > --- a/testsuite/libffi.closures/closure_loc_fn0.c > +++ b/testsuite/libffi.closures/closure_loc_fn0.c > @@ -83,7 +83,10 @@ int main (void) > CHECK(ffi_prep_closure_loc(pcl, &cif, closure_loc_test_fn0, > (void *) 3 /* userdata */, codeloc) == FFI_OK); > > +#ifndef FFI_EXEC_STATIC_TRAMP > + /* With static trampolines, the codeloc does not point to closure */ > CHECK(memcmp(pcl, codeloc, sizeof(*pcl)) == 0); > +#endif > > res = (*((closure_loc_test_type0)codeloc)) > (1LL, 2, 3LL, 4, 127, 429LL, 7, 8, 9.5, 10, 11, 12, 13, > -- > 2.25.1 > > ^ permalink raw reply [flat|nested] 12+ messages in thread
* Re: [RFC PATCH v1 1/4] Static Trampolines 2020-11-24 19:49 ` Anthony Green @ 2020-11-24 20:02 ` Madhavan T. Venkataraman 2020-12-02 16:49 ` Madhavan T. Venkataraman 1 sibling, 0 replies; 12+ messages in thread From: Madhavan T. Venkataraman @ 2020-11-24 20:02 UTC (permalink / raw) To: Anthony Green; +Cc: libffi-discuss, fw Good idea! I will take care of this. Madhavan On 11/24/20 1:49 PM, Anthony Green wrote: > Thank you for your submission, Madhavan. This will be interesting reading! > > In the meantime, it would be helpful if you submitted this as a PR on GitHub. This will trigger CI testing for over 20 different systems so we can have an initial look at any build/test problems. > > AG > > On Tue, Nov 24, 2020 at 2:32 PM madvenka--- via Libffi-discuss <libffi-discuss@sourceware.org <mailto:libffi-discuss@sourceware.org>> wrote: > > From: "Madhavan T. Venkataraman" <madvenka@linux.microsoft.com <mailto:madvenka@linux.microsoft.com>> > > Closure Trampoline Security Issue > ================================= > > Currently, the trampoline code used in libffi is not statically defined in > a source file (except for MACH). The trampoline is either pre-defined > machine code in a data buffer. Or, it is generated at runtime. In order to > execute a trampoline, it needs to be placed in a page with executable > permissions. > > Executable data pages are attack surfaces for attackers who may try to > inject their own code into the page and contrive to have it executed. The > security settings in a system may prevent various tricks used in user land > to write code into a page and to have it executed somehow. On such systems, > libffi trampolines would not be able to run. > > Static Trampoline > ================= > > To solve this problem, the trampoline code needs to be defined statically > in a source file, compiled and placed in the text segment so it can be > mapped and executed naturally without any tricks. However, the trampoline > needs to be able to access the closure pointer at runtime. > > PC-relative data referencing > ============================ > > The solution implemented in this patch set uses PC-relative data references. > The trampoline is mapped in a code page. Adjacent to the code page, a data > page is mapped that contains the parameters of the trampoline: > > - the closure pointer > - pointer to the ABI handler to jump to > > The trampoline code uses an offset relative to its current PC to access its > data. > > Some architectures support PC-relative data references in the ISA itself. > E.g., X64 supports RIP-relative references. For others, the PC has to > somehow be loaded into a general purpose register to do PC-relative data > referencing. To do this, we need to define a get_pc() kind of function and > call it to load the PC in a desired register. > > There are two cases: > > 1. The call instruction pushes the return address on the stack. > > In this case, get_pc() will extract the return address from the stack > and load it in the desired register and return. > > 2. The call instruction stores the return address in a designated register. > > In this case, get_pc() will copy the return address to the desired > register and return. > > Either way, the PC next to the call instruction is obtained. > > Scratch register > ================ > > In order to do its job, the trampoline code would be required to use a > scratch register. Depending on the ABI, there may not be a register > available for scratch. This problem needs to be solved so that all ABIs > will work. > > The trampoline will save two values on the stack: > > - the closure pointer > - the original value of the scratch register > > This is what the stack will look like: > > sp before trampoline ------> -------------------- > | closure pointer | > -------------------- > | scratch register | > sp after trampoline -------> -------------------- > > The ABI handler can do the following as needed by the ABI: > > - the closure pointer can be loaded in a desired register > > - the scratch register can be restored to its original value > > - the stack pointer can be restored to its original value > (when the trampoline was invoked) > > Thus the ABI handlers will have a couple of lines of code at the very > beginning to do this so that all ABIs will work. > > NOTE: > The documentation for this feature will contain information on: > > - the name of the scratch register for each architecture > > - the stack offsets at which the closure and the scratch register > will be copied > > Trampoline Table > ================ > > In order to reduce the trampoline memory footprint, the trampoline code > would be defined as a code array in the text segment. This array would be > mapped into the address space of the caller. The mapping would, therefore, > contain a trampoline table. > > Adjacent to the trampoline table, there will be a data mapping that contains > a parameter table, one parameter block for each trampoline. The parameter > table will contain: > > - a pointer to the closure > - a pointer to the ABI handler > > The trampoline code would finally look like this: > > - Make space on the stack for the closure and the scratch register > by moving the stack pointer down > - Store the original value of the scratch register on the stack > - Using PC-relative reference, get the closure pointer > - Store the closure pointer on the stack > - Using PC-relative reference, get the ABI handler pointer > - Jump to the ABI handler > > Trampoline API > ============== > > There is a lot of dynamic code out there. They all have the same security > issue. Dynamic code can be re-written into static code provided the data > required by the static code can be passed to it just like we pass the > closure pointer to an ABI handler. > > So, the same trampoline functions used by libffi internally need to be > made available to the rest of the world in the form of an API. The > following API has been defined in this solution: > > int ffi_tramp_is_supported(void); > > To support static trampolines, code needs to be added to each > architecture. Also, the feature itself can be enabled via a > configuration option. So, this function tells us if the feature > is supported and enabled in the current libffi or not. > > void *ffi_tramp_alloc (int flags); > > Allocate a trampoline. Currently, flags are zero. An opaque > trampoline structure pointer is returned. > > Internally, libffi manages trampoline tables and individual > trampolines in each table. > > int ffi_tramp_set_parms (void *tramp, void *target, void *data); > > Initialize the parameters of a trampoline. That is, the target code > that the trampoline should jump to and the data that needs to be > passed to the target code. > > void *ffi_tramp_get_addr (void *tramp); > > Return the address of the trampoline to invoke the trampoline with. > The trampoline can be invoked in one of two ways: > > - Simply branch to the trampoline address > - Treat the trampoline address as a function pointer and > call it. > > Which method is used depends on the target code. > > void ffi_tramp_free (void *tramp); > > Free a trampoline. > > Configuration > ============= > > A new configuration option, --enable-static-tramp has been added to enable > the use of static trampolines. > > Mapping size > ============ > > The size of the code mapping that contains the trampoline table needs to be > determined on a per architecture basis. If a particular architecture > supports multiple base page sizes, then the largest base page size needs to > be chosen. E.g., we choose 16K for ARM64. > > Trampoline allocation and free > ============================== > > Static trampolines are allocated in ffi_closure_alloc() and freed in > ffi_closure_free(). > > Normally, applications use these functions. But there are some cases out > there where the user of libffi allocates and manages its own closure > memory. In such cases, the static trampoline API cannot be used. These > will fall back to using legacy trampolines. The user has to make sure > that the memory is executable. > > ffi_closure structure > ===================== > > I did not want to make any changes to the size of the closure structure for > this feature to guarantee compatibility. But the opaque static trampoline > handle needs to be stored in the closure. I have defined it as follows: > > - char tramp[FFI_TRAMPOLINE_SIZE]; > + union { > + char tramp[FFI_TRAMPOLINE_SIZE]; > + void *ftramp; > + }; > > If static trampolines are used, then tramp[] is not needed to store a > dynamic trampoline. That space can be reused to store the handle. Hence, > the union. > > Signed-off-by: Madhavan T. Venkataraman <madvenka@linux.microsoft.com <mailto:madvenka@linux.microsoft.com>> > --- > Makefile.am | 3 +- > configure.ac <http://configure.ac> | 7 + > include/ffi.h.in <http://ffi.h.in> | 13 +- > include/ffi_common.h | 4 + > libffi.map.in <http://libffi.map.in> | 11 + > src/closures.c | 54 +- > src/tramp.c | 563 ++++++++++++++++++++ > testsuite/libffi.closures/closure_loc_fn0.c | 3 + > 8 files changed, 654 insertions(+), 4 deletions(-) > create mode 100644 src/tramp.c > > diff --git a/Makefile.am b/Makefile.am > index 7654bf5..1b18198 100644 > --- a/Makefile.am > +++ b/Makefile.am > @@ -38,7 +38,8 @@ toolexeclib_LTLIBRARIES = libffi.la <http://libffi.la> > noinst_LTLIBRARIES = libffi_convenience.la <http://libffi_convenience.la> > > libffi_la_SOURCES = src/prep_cif.c src/types.c \ > - src/raw_api.c src/java_raw_api.c src/closures.c > + src/raw_api.c src/java_raw_api.c src/closures.c \ > + src/tramp.c > > if FFI_DEBUG > libffi_la_SOURCES += src/debug.c > diff --git a/configure.ac <http://configure.ac> b/configure.ac <http://configure.ac> > index 790274e..898ede6 100644 > --- a/configure.ac <http://configure.ac> > +++ b/configure.ac <http://configure.ac> > @@ -360,6 +360,13 @@ AC_ARG_ENABLE(raw-api, > AC_DEFINE(FFI_NO_RAW_API, 1, [Define this if you do not want support for the raw API.]) > fi) > > +AC_ARG_ENABLE(static-tramp, > +[ --enable-static-tramp use statically defined trampolines], > + if test "$enable_static_tramp" = "yes"; then > + AC_DEFINE(FFI_EXEC_STATIC_TRAMP, 1, > + [Define this if you want to use statically defined trampolines.]) > + fi) > + > AC_ARG_ENABLE(purify-safety, > [ --enable-purify-safety purify-safe mode], > if test "$enable_purify_safety" = "yes"; then > diff --git a/include/ffi.h.in <http://ffi.h.in> b/include/ffi.h.in <http://ffi.h.in> > index 38885b0..c6a21d9 100644 > --- a/include/ffi.h.in <http://ffi.h.in> > +++ b/include/ffi.h.in <http://ffi.h.in> > @@ -310,7 +310,10 @@ typedef struct { > void *trampoline_table; > void *trampoline_table_entry; > #else > - char tramp[FFI_TRAMPOLINE_SIZE]; > + union { > + char tramp[FFI_TRAMPOLINE_SIZE]; > + void *ftramp; > + }; > #endif > ffi_cif *cif; > void (*fun)(ffi_cif*,void*,void**,void*); > @@ -457,6 +460,14 @@ FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue, > > #endif /* FFI_GO_CLOSURES */ > > +/* ---- Static Trampoline Definitions -------------------------------------- */ > + > +FFI_API int ffi_tramp_is_supported(void); > +FFI_API void *ffi_tramp_alloc (int flags); > +FFI_API int ffi_tramp_set_parms (void *tramp, void *data, void *code); > +FFI_API void *ffi_tramp_get_addr (void *tramp); > +FFI_API void ffi_tramp_free (void *tramp); > + > /* ---- Public interface definition -------------------------------------- */ > > FFI_API > diff --git a/include/ffi_common.h b/include/ffi_common.h > index 76b9dd6..8743126 100644 > --- a/include/ffi_common.h > +++ b/include/ffi_common.h > @@ -103,6 +103,10 @@ ffi_status ffi_prep_cif_core(ffi_cif *cif, > some targets. */ > void *ffi_data_to_code_pointer (void *data) FFI_HIDDEN; > > +/* The arch code calls this to set the code and data parameters for a > + closure's static trampoline, if any. */ > +int ffi_closure_tramp_set_parms (void *closure, void *code); > + > /* Extended cif, used in callback from assembly routine */ > typedef struct > { > diff --git a/libffi.map.in <http://libffi.map.in> b/libffi.map.in <http://libffi.map.in> > index de8778a..049c73e 100644 > --- a/libffi.map.in <http://libffi.map.in> > +++ b/libffi.map.in <http://libffi.map.in> > @@ -74,3 +74,14 @@ LIBFFI_GO_CLOSURE_8.0 { > ffi_prep_go_closure; > } LIBFFI_CLOSURE_8.0; > #endif > + > +#if FFI_EXEC_STATIC_TRAMP > +LIBFFI_STATIC_TRAMP_8.0 { > + global: > + ffi_tramp_is_supported; > + ffi_tramp_alloc; > + ffi_tramp_set_parms; > + ffi_tramp_get_addr; > + ffi_tramp_free; > +} LIBFFI_BASE_8.0; > +#endif > diff --git a/src/closures.c b/src/closures.c > index 4fe6158..cf1d3de 100644 > --- a/src/closures.c > +++ b/src/closures.c > @@ -109,6 +109,12 @@ ffi_closure_free (void *ptr) > munmap(dataseg, rounded_size); > munmap(codeseg, rounded_size); > } > + > +int > +ffi_closure_tramp_set_parms (void *ptr, void *code) > +{ > + return 0; > +} > #else /* !NetBSD with PROT_MPROTECT */ > > #if !FFI_MMAP_EXEC_WRIT && !FFI_EXEC_TRAMPOLINE_TABLE > @@ -843,6 +849,12 @@ dlmmap (void *start, size_t length, int prot, > && flags == (MAP_PRIVATE | MAP_ANONYMOUS) > && fd == -1 && offset == 0); > > + if (execfd == -1 && ffi_tramp_is_supported ()) > + { > + ptr = mmap (start, length, prot & ~PROT_EXEC, flags, fd, offset); > + return ptr; > + } > + > if (execfd == -1 && is_emutramp_enabled ()) > { > ptr = mmap (start, length, prot & ~PROT_EXEC, flags, fd, offset); > @@ -922,7 +934,7 @@ segment_holding_code (mstate m, char* addr) > void * > ffi_closure_alloc (size_t size, void **code) > { > - void *ptr; > + void *ptr, *ftramp; > > if (!code) > return NULL; > @@ -934,6 +946,17 @@ ffi_closure_alloc (size_t size, void **code) > msegmentptr seg = segment_holding (gm, ptr); > > *code = add_segment_exec_offset (ptr, seg); > + if (!ffi_tramp_is_supported ()) > + return ptr; > + > + ftramp = ffi_tramp_alloc (0); > + if (ftramp == NULL) > + { > + dlfree (FFI_RESTORE_PTR (ptr)); > + return NULL; > + } > + *code = ffi_tramp_get_addr (ftramp); > + ((ffi_closure *) ptr)->ftramp = ftramp; > } > > return ptr; > @@ -943,12 +966,17 @@ void * > ffi_data_to_code_pointer (void *data) > { > msegmentptr seg = segment_holding (gm, data); > + > /* We expect closures to be allocated with ffi_closure_alloc(), in > which case seg will be non-NULL. However, some users take on the > burden of managing this memory themselves, in which case this > we'll just return data. */ > if (seg) > - return add_segment_exec_offset (data, seg); > + { > + if (!ffi_tramp_is_supported ()) > + return add_segment_exec_offset (data, seg); > + return ffi_tramp_get_addr (((ffi_closure *) data)->ftramp); > + } > else > return data; > } > @@ -966,10 +994,26 @@ ffi_closure_free (void *ptr) > if (seg) > ptr = sub_segment_exec_offset (ptr, seg); > #endif > + if (ffi_tramp_is_supported ()) > + ffi_tramp_free (((ffi_closure *) ptr)->ftramp); > > dlfree (FFI_RESTORE_PTR (ptr)); > } > > +int > +ffi_closure_tramp_set_parms (void *ptr, void *code) > +{ > + void *ftramp; > + > + msegmentptr seg = segment_holding (gm, ptr); > + if (!seg || !ffi_tramp_is_supported()) > + return 0; > + > + ftramp = ((ffi_closure *) ptr)->ftramp; > + ffi_tramp_set_parms (ftramp, code, ptr); > + return 1; > +} > + > # else /* ! FFI_MMAP_EXEC_WRIT */ > > /* On many systems, memory returned by malloc is writable and > @@ -998,6 +1042,12 @@ ffi_data_to_code_pointer (void *data) > return data; > } > > +int > +ffi_closure_tramp_set_parms (void *ptr, void *code) > +{ > + return 0; > +} > + > # endif /* ! FFI_MMAP_EXEC_WRIT */ > #endif /* FFI_CLOSURES */ > > diff --git a/src/tramp.c b/src/tramp.c > new file mode 100644 > index 0000000..3170152 > --- /dev/null > +++ b/src/tramp.c > @@ -0,0 +1,563 @@ > +/* ----------------------------------------------------------------------- > + tramp.c - Copyright (c) 2020 Madhavan T. Venkataraman > + > + API and support functions for managing statically defined closure > + trampolines. > + > + Permission is hereby granted, free of charge, to any person obtaining > + a copy of this software and associated documentation files (the > + ``Software''), to deal in the Software without restriction, including > + without limitation the rights to use, copy, modify, merge, publish, > + distribute, sublicense, and/or sell copies of the Software, and to > + permit persons to whom the Software is furnished to do so, subject to > + the following conditions: > + > + The above copyright notice and this permission notice shall be included > + in all copies or substantial portions of the Software. > + > + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, > + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF > + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND > + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT > + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, > + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, > + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER > + DEALINGS IN THE SOFTWARE. > + ----------------------------------------------------------------------- */ > + > +#include <stdio.h> > +#include <unistd.h> > +#include <stdlib.h> > +#include <stdint.h> > +#include <fcntl.h> > +#include <pthread.h> > +#include <sys/mman.h> > +#include <linux/limits.h> > +#include <linux/types.h> > +#include <fficonfig.h> > + > +#if defined(FFI_EXEC_STATIC_TRAMP) > + > +#if !defined(__linux__) > +#error "FFI_EXEC_STATIC_TRAMP is currently only supported on Linux" > +#endif > + > +#if !defined _GNU_SOURCE > +#define _GNU_SOURCE 1 > +#endif > + > +/* > + * Each architecture defines static code for a trampoline code table. The > + * trampoline code table is mapped into the address space of a process. > + * > + * The following architecture specific function returns: > + * > + * - the address of the trampoline code table in the text segment > + * - the size of each trampoline in the trampoline code table > + * - the size of the mapping for the whole trampoline code table > + */ > +void __attribute__((weak)) *ffi_tramp_arch (size_t *tramp_size, > + size_t *map_size); > + > +/* ------------------------- Trampoline Data Structures --------------------*/ > + > +static pthread_mutex_t tramp_lock = PTHREAD_MUTEX_INITIALIZER; > + > +struct tramp; > + > +/* > + * Trampoline table. Manages one trampoline code table and one trampoline > + * parameter table. > + * > + * prev, next Links in the global trampoline table list. > + * code_table Trampoline code table mapping. > + * parm_table Trampoline parameter table mapping. > + * array Array of trampolines malloced. > + * free List of free trampolines. > + * nfree Number of free trampolines. > + */ > +struct tramp_table > +{ > + struct tramp_table *prev; > + struct tramp_table *next; > + void *code_table; > + void *parm_table; > + struct tramp *array; > + struct tramp *free; > + int nfree; > +}; > + > +/* > + * Parameters for each trampoline. > + * > + * data > + * Data for the target code that the trampoline jumps to. > + * target > + * Target code that the trampoline jumps to. > + */ > +struct tramp_parm > +{ > + void *data; > + void *target; > +}; > + > +/* > + * Trampoline structure for each trampoline. > + * > + * prev, next Links in the trampoline free list of a trampoline table. > + * table Trampoline table to which this trampoline belongs. > + * code Address of this trampoline in the code table mapping. > + * parm Address of this trampoline's parameters in the parameter > + * table mapping. > + */ > +struct tramp > +{ > + struct tramp *prev; > + struct tramp *next; > + struct tramp_table *table; > + void *code; > + struct tramp_parm *parm; > +}; > + > +/* > + * Trampoline globals. > + * > + * fd > + * File descriptor of binary file that contains the trampoline code table. > + * offset > + * Offset of the trampoline code table in that file. > + * map_size > + * Size of the trampoline code table mapping. > + * size > + * Size of one trampoline in the trampoline code table. > + * ntramp > + * Total number of trampolines in the trampoline code table. > + * tables > + * List of trampoline tables that contain free trampolines. > + * ntables > + * Number of trampoline tables that contain free trampolines. > + */ > +struct tramp_global > +{ > + int fd; > + off_t offset; > + size_t map_size; > + size_t size; > + int ntramp; > + struct tramp_table *tables; > + int ntables; > +}; > + > +static struct tramp_global gtramp = { -1 }; > + > +/* ------------------------ Trampoline Initialization ----------------------*/ > + > +static int ffi_tramp_get_fd_offset (void *tramp_text, off_t *offset); > + > +/* > + * Initialize the static trampoline feature. > + */ > +static int > +ffi_tramp_init (void) > +{ > + if (ffi_tramp_arch == NULL) > + return 0; > + > + if (gtramp.fd == -1) > + { > + void *tramp_text; > + > + gtramp.tables = NULL; > + gtramp.ntables = 0; > + > + /* > + * Get trampoline code table information from the architecture. > + */ > + tramp_text = ffi_tramp_arch (>ramp.size, >ramp.map_size); > + gtramp.ntramp = gtramp.map_size / gtramp.size; > + > + /* > + * Get the binary file that contains the trampoline code table and also > + * the offset of the table within the file. These are used to mmap() > + * the trampoline code table. > + */ > + gtramp.fd = ffi_tramp_get_fd_offset (tramp_text, >ramp.offset); > + } > + return gtramp.fd != -1; > +} > + > +/* > + * From the address of the trampoline code table in the text segment, find the > + * binary file and offset of the trampoline code table from /proc/<pid>/maps. > + */ > +static int > +ffi_tramp_get_fd_offset (void *tramp_text, off_t *offset) > +{ > + FILE *fp; > + char file[PATH_MAX], line[PATH_MAX+100], perm[10], dev[10]; > + unsigned long start, end, inode; > + uintptr_t addr = (uintptr_t) tramp_text; > + int nfields, found; > + > + snprintf (file, PATH_MAX, "/proc/%d/maps", getpid()); > + fp = fopen (file, "r"); > + if (fp == NULL) > + return -1; > + > + found = 0; > + while (feof (fp) == 0) { > + if (fgets (line, sizeof (line), fp) == 0) > + break; > + > + nfields = sscanf (line, "%lx-%lx %s %lx %s %ld %s", > + &start, &end, perm, offset, dev, &inode, file); > + if (nfields != 7) > + continue; > + > + if (addr >= start && addr < end) { > + *offset += (addr - start); > + found = 1; > + break; > + } > + } > + fclose (fp); > + > + if (!found) > + return -1; > + > + return open (file, O_RDONLY); > +} > + > +/* ---------------------- Trampoline Table functions ---------------------- */ > + > +static int tramp_table_map (char **code_table, char **parm_table); > +static void tramp_add (struct tramp *tramp); > + > +/* > + * Allocate and initialize a trampoline table. > + */ > +static int > +tramp_table_alloc (void) > +{ > + char *code_table, *parm_table; > + struct tramp_table *table; > + struct tramp *tramp_array, *tramp; > + size_t size; > + char *code, *parm; > + int i; > + > + /* > + * If we already have tables with free trampolines, there is no need to > + * allocate a new table. > + */ > + if (gtramp.ntables > 0) > + return 1; > + > + /* > + * Allocate a new trampoline table structure. > + */ > + table = malloc (sizeof (*table)); > + if (table == NULL) > + return 0; > + > + /* > + * Allocate new trampoline structures. > + */ > + tramp_array = malloc (sizeof (*tramp) * gtramp.ntramp); > + if (tramp_array == NULL) > + goto free_table; > + > + /* > + * Map a code table and a parameter table into the caller's address space. > + */ > + if (!tramp_table_map (&code_table, &parm_table)) > + goto free_tramp_array; > + > + /* > + * Initialize the trampoline table. > + */ > + table->code_table = code_table; > + table->parm_table = parm_table; > + table->array = tramp_array; > + table->free = NULL; > + table->nfree = 0; > + > + /* > + * Populate the trampoline table free list. This will also add the trampoline > + * table to the global list of trampoline tables. > + */ > + size = gtramp.size; > + code = code_table; > + parm = parm_table; > + for (i = 0; i < gtramp.ntramp; i++) > + { > + tramp = &tramp_array[i]; > + tramp->table = table; > + tramp->code = code; > + tramp->parm = (struct tramp_parm *) parm; > + tramp_add (tramp); > + > + code += size; > + parm += size; > + } > + return 1; > + > +free_tramp_array: > + free (tramp_array); > +free_table: > + free (table); > + return 0; > +} > + > +/* > + * Create a trampoline code table mapping and a trampoline parameter table > + * mapping. The two mappings must be adjacent to each other for PC-relative > + * access. > + * > + * For each trampoline in the code table, there is a corresponding parameter > + * block in the parameter table. The size of the parameter block is the same > + * as the size of the trampoline. This means that the parameter block is at > + * a fixed offset from its trampoline making it easy for a trampoline to find > + * its parameters using PC-relative access. > + * > + * The parameter block will contain a struct tramp_parm. This means that > + * sizeof (struct tramp_parm) cannot exceed the size of a parameter block. > + */ > +static int > +tramp_table_map (char **code_table, char **parm_table) > +{ > + char *addr; > + > + /* > + * Create an anonymous mapping twice the map size. The top half will be used > + * for the code table. The bottom half will be used for the parameter table. > + */ > + addr = mmap (NULL, gtramp.map_size * 2, PROT_READ | PROT_WRITE, > + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); > + if (addr == MAP_FAILED) > + return 0; > + > + /* > + * Replace the top half of the anonymous mapping with the code table mapping. > + */ > + *code_table = mmap (addr, gtramp.map_size, PROT_READ | PROT_EXEC, > + MAP_PRIVATE | MAP_FIXED, gtramp.fd, gtramp.offset); > + if (*code_table == MAP_FAILED) > + { > + (void) munmap (addr, gtramp.map_size * 2); > + return 0; > + } > + *parm_table = *code_table + gtramp.map_size; > + return 1; > +} > + > +/* > + * Free a trampoline table. > + */ > +static void > +tramp_table_free (struct tramp_table *table) > +{ > + (void) munmap (table->code_table, gtramp.map_size); > + (void) munmap (table->parm_table, gtramp.map_size); > + free (table->array); > + free (table); > +} > + > +/* > + * Add a new trampoline table to the global table list. > + */ > +static void > +tramp_table_add (struct tramp_table *table) > +{ > + table->next = gtramp.tables; > + table->prev = NULL; > + if (gtramp.tables != NULL) > + gtramp.tables->prev = table; > + gtramp.tables = table; > + gtramp.ntables++; > +} > + > +/* > + * Delete a trampoline table from the global table list. > + */ > +static void > +tramp_table_del (struct tramp_table *table) > +{ > + gtramp.ntables--; > + if (table->prev != NULL) > + table->prev->next = table->next; > + if (table->next != NULL) > + table->next->prev = table->prev; > + if (gtramp.tables == table) > + gtramp.tables = table->next; > +} > + > +/* ------------------------- Trampoline functions ------------------------- */ > + > +/* > + * Add a trampoline to its trampoline table. > + */ > +static void > +tramp_add (struct tramp *tramp) > +{ > + struct tramp_table *table = tramp->table; > + > + tramp->next = table->free; > + tramp->prev = NULL; > + if (table->free != NULL) > + table->free->prev = tramp; > + table->free = tramp; > + table->nfree++; > + > + if (table->nfree == 1) > + tramp_table_add (table); > + > + /* > + * We don't want to keep too many free trampoline tables lying around. > + */ > + if (table->nfree == gtramp.ntramp && gtramp.ntables > 1) > + { > + tramp_table_del (table); > + tramp_table_free (table); > + } > +} > + > +/* > + * Remove a trampoline from its trampoline table. > + */ > +static void > +tramp_del (struct tramp *tramp) > +{ > + struct tramp_table *table = tramp->table; > + > + table->nfree--; > + if (tramp->prev != NULL) > + tramp->prev->next = tramp->next; > + if (tramp->next != NULL) > + tramp->next->prev = tramp->prev; > + if (table->free == tramp) > + table->free = tramp->next; > + > + if (table->nfree == 0) > + tramp_table_del (table); > +} > + > +/* ------------------------ Trampoline API functions ------------------------ */ > + > +int > +ffi_tramp_is_supported(void) > +{ > + int ret; > + > + pthread_mutex_lock (&tramp_lock); > + ret = ffi_tramp_init (); > + pthread_mutex_unlock (&tramp_lock); > + return ret; > +} > + > +/* > + * Allocate a trampoline and return its opaque address. > + */ > +void * > +ffi_tramp_alloc (int flags) > +{ > + struct tramp *tramp; > + > + pthread_mutex_lock (&tramp_lock); > + > + if (!ffi_tramp_init () || flags != 0) > + { > + pthread_mutex_unlock (&tramp_lock); > + return NULL; > + } > + > + if (!tramp_table_alloc ()) > + { > + pthread_mutex_unlock (&tramp_lock); > + return NULL; > + } > + > + tramp = gtramp.tables->free; > + tramp_del (tramp); > + > + pthread_mutex_unlock (&tramp_lock); > + > + return tramp; > +} > + > +/* > + * Set the parameters for a trampoline. > + */ > +void > +ffi_tramp_set_parms (void *arg, void *target, void *data) > +{ > + struct tramp *tramp = arg; > + > + pthread_mutex_lock (&tramp_lock); > + tramp->parm->target = target; > + tramp->parm->data = data; > + pthread_mutex_unlock (&tramp_lock); > +} > + > +/* > + * Get the invocation address of a trampoline. > + */ > +void * > +ffi_tramp_get_addr (void *arg) > +{ > + struct tramp *tramp = arg; > + void *addr; > + > + pthread_mutex_lock (&tramp_lock); > + addr = tramp->code; > + pthread_mutex_unlock (&tramp_lock); > + > + return addr; > +} > + > +/* > + * Free a trampoline. > + */ > +void > +ffi_tramp_free (void *arg) > +{ > + struct tramp *tramp = arg; > + > + pthread_mutex_lock (&tramp_lock); > + tramp_add (tramp); > + pthread_mutex_unlock (&tramp_lock); > +} > + > +/* ------------------------------------------------------------------------- */ > + > +#else /* !FFI_EXEC_STATIC_TRAMP */ > + > +int > +ffi_tramp_is_supported(void) > +{ > + return 0; > +} > + > +void * > +ffi_tramp_alloc (int flags) > +{ > + return NULL; > +} > + > +void > +ffi_tramp_set_parms (void *arg, void *target, void *data) > +{ > +} > + > +void * > +ffi_tramp_get_addr (void *arg) > +{ > + return NULL; > +} > + > +void > +ffi_tramp_free (void *arg) > +{ > +} > + > +#endif /* FFI_EXEC_STATIC_TRAMP */ > diff --git a/testsuite/libffi.closures/closure_loc_fn0.c b/testsuite/libffi.closures/closure_loc_fn0.c > index b3afa0b..ad488ac 100644 > --- a/testsuite/libffi.closures/closure_loc_fn0.c > +++ b/testsuite/libffi.closures/closure_loc_fn0.c > @@ -83,7 +83,10 @@ int main (void) > CHECK(ffi_prep_closure_loc(pcl, &cif, closure_loc_test_fn0, > (void *) 3 /* userdata */, codeloc) == FFI_OK); > > +#ifndef FFI_EXEC_STATIC_TRAMP > + /* With static trampolines, the codeloc does not point to closure */ > CHECK(memcmp(pcl, codeloc, sizeof(*pcl)) == 0); > +#endif > > res = (*((closure_loc_test_type0)codeloc)) > (1LL, 2, 3LL, 4, 127, 429LL, 7, 8, 9.5, 10, 11, 12, 13, > -- > 2.25.1 > ^ permalink raw reply [flat|nested] 12+ messages in thread
* Re: [RFC PATCH v1 1/4] Static Trampolines 2020-11-24 19:49 ` Anthony Green 2020-11-24 20:02 ` Madhavan T. Venkataraman @ 2020-12-02 16:49 ` Madhavan T. Venkataraman 2020-12-02 18:14 ` Anthony Green 1 sibling, 1 reply; 12+ messages in thread From: Madhavan T. Venkataraman @ 2020-12-02 16:49 UTC (permalink / raw) To: Anthony Green; +Cc: libffi-discuss, fw On 11/24/20 1:49 PM, Anthony Green wrote: > Thank you for your submission, Madhavan. This will be interesting reading! > > In the meantime, it would be helpful if you submitted this as a PR on GitHub. This will trigger CI testing for over 20 different systems so we can have an initial look at any build/test problems. > Just submitted the PR: https://github.com/libffi/libffi/pull/603 Thanks. Madhavan > AG > > On Tue, Nov 24, 2020 at 2:32 PM madvenka--- via Libffi-discuss <libffi-discuss@sourceware.org <mailto:libffi-discuss@sourceware.org>> wrote: > > From: "Madhavan T. Venkataraman" <madvenka@linux.microsoft.com <mailto:madvenka@linux.microsoft.com>> > > Closure Trampoline Security Issue > ================================= > > Currently, the trampoline code used in libffi is not statically defined in > a source file (except for MACH). The trampoline is either pre-defined > machine code in a data buffer. Or, it is generated at runtime. In order to > execute a trampoline, it needs to be placed in a page with executable > permissions. > > Executable data pages are attack surfaces for attackers who may try to > inject their own code into the page and contrive to have it executed. The > security settings in a system may prevent various tricks used in user land > to write code into a page and to have it executed somehow. On such systems, > libffi trampolines would not be able to run. > > Static Trampoline > ================= > > To solve this problem, the trampoline code needs to be defined statically > in a source file, compiled and placed in the text segment so it can be > mapped and executed naturally without any tricks. However, the trampoline > needs to be able to access the closure pointer at runtime. > > PC-relative data referencing > ============================ > > The solution implemented in this patch set uses PC-relative data references. > The trampoline is mapped in a code page. Adjacent to the code page, a data > page is mapped that contains the parameters of the trampoline: > > - the closure pointer > - pointer to the ABI handler to jump to > > The trampoline code uses an offset relative to its current PC to access its > data. > > Some architectures support PC-relative data references in the ISA itself. > E.g., X64 supports RIP-relative references. For others, the PC has to > somehow be loaded into a general purpose register to do PC-relative data > referencing. To do this, we need to define a get_pc() kind of function and > call it to load the PC in a desired register. > > There are two cases: > > 1. The call instruction pushes the return address on the stack. > > In this case, get_pc() will extract the return address from the stack > and load it in the desired register and return. > > 2. The call instruction stores the return address in a designated register. > > In this case, get_pc() will copy the return address to the desired > register and return. > > Either way, the PC next to the call instruction is obtained. > > Scratch register > ================ > > In order to do its job, the trampoline code would be required to use a > scratch register. Depending on the ABI, there may not be a register > available for scratch. This problem needs to be solved so that all ABIs > will work. > > The trampoline will save two values on the stack: > > - the closure pointer > - the original value of the scratch register > > This is what the stack will look like: > > sp before trampoline ------> -------------------- > | closure pointer | > -------------------- > | scratch register | > sp after trampoline -------> -------------------- > > The ABI handler can do the following as needed by the ABI: > > - the closure pointer can be loaded in a desired register > > - the scratch register can be restored to its original value > > - the stack pointer can be restored to its original value > (when the trampoline was invoked) > > Thus the ABI handlers will have a couple of lines of code at the very > beginning to do this so that all ABIs will work. > > NOTE: > The documentation for this feature will contain information on: > > - the name of the scratch register for each architecture > > - the stack offsets at which the closure and the scratch register > will be copied > > Trampoline Table > ================ > > In order to reduce the trampoline memory footprint, the trampoline code > would be defined as a code array in the text segment. This array would be > mapped into the address space of the caller. The mapping would, therefore, > contain a trampoline table. > > Adjacent to the trampoline table, there will be a data mapping that contains > a parameter table, one parameter block for each trampoline. The parameter > table will contain: > > - a pointer to the closure > - a pointer to the ABI handler > > The trampoline code would finally look like this: > > - Make space on the stack for the closure and the scratch register > by moving the stack pointer down > - Store the original value of the scratch register on the stack > - Using PC-relative reference, get the closure pointer > - Store the closure pointer on the stack > - Using PC-relative reference, get the ABI handler pointer > - Jump to the ABI handler > > Trampoline API > ============== > > There is a lot of dynamic code out there. They all have the same security > issue. Dynamic code can be re-written into static code provided the data > required by the static code can be passed to it just like we pass the > closure pointer to an ABI handler. > > So, the same trampoline functions used by libffi internally need to be > made available to the rest of the world in the form of an API. The > following API has been defined in this solution: > > int ffi_tramp_is_supported(void); > > To support static trampolines, code needs to be added to each > architecture. Also, the feature itself can be enabled via a > configuration option. So, this function tells us if the feature > is supported and enabled in the current libffi or not. > > void *ffi_tramp_alloc (int flags); > > Allocate a trampoline. Currently, flags are zero. An opaque > trampoline structure pointer is returned. > > Internally, libffi manages trampoline tables and individual > trampolines in each table. > > int ffi_tramp_set_parms (void *tramp, void *target, void *data); > > Initialize the parameters of a trampoline. That is, the target code > that the trampoline should jump to and the data that needs to be > passed to the target code. > > void *ffi_tramp_get_addr (void *tramp); > > Return the address of the trampoline to invoke the trampoline with. > The trampoline can be invoked in one of two ways: > > - Simply branch to the trampoline address > - Treat the trampoline address as a function pointer and > call it. > > Which method is used depends on the target code. > > void ffi_tramp_free (void *tramp); > > Free a trampoline. > > Configuration > ============= > > A new configuration option, --enable-static-tramp has been added to enable > the use of static trampolines. > > Mapping size > ============ > > The size of the code mapping that contains the trampoline table needs to be > determined on a per architecture basis. If a particular architecture > supports multiple base page sizes, then the largest base page size needs to > be chosen. E.g., we choose 16K for ARM64. > > Trampoline allocation and free > ============================== > > Static trampolines are allocated in ffi_closure_alloc() and freed in > ffi_closure_free(). > > Normally, applications use these functions. But there are some cases out > there where the user of libffi allocates and manages its own closure > memory. In such cases, the static trampoline API cannot be used. These > will fall back to using legacy trampolines. The user has to make sure > that the memory is executable. > > ffi_closure structure > ===================== > > I did not want to make any changes to the size of the closure structure for > this feature to guarantee compatibility. But the opaque static trampoline > handle needs to be stored in the closure. I have defined it as follows: > > - char tramp[FFI_TRAMPOLINE_SIZE]; > + union { > + char tramp[FFI_TRAMPOLINE_SIZE]; > + void *ftramp; > + }; > > If static trampolines are used, then tramp[] is not needed to store a > dynamic trampoline. That space can be reused to store the handle. Hence, > the union. > > Signed-off-by: Madhavan T. Venkataraman <madvenka@linux.microsoft.com <mailto:madvenka@linux.microsoft.com>> > --- > Makefile.am | 3 +- > configure.ac <http://configure.ac> | 7 + > include/ffi.h.in <http://ffi.h.in> | 13 +- > include/ffi_common.h | 4 + > libffi.map.in <http://libffi.map.in> | 11 + > src/closures.c | 54 +- > src/tramp.c | 563 ++++++++++++++++++++ > testsuite/libffi.closures/closure_loc_fn0.c | 3 + > 8 files changed, 654 insertions(+), 4 deletions(-) > create mode 100644 src/tramp.c > > diff --git a/Makefile.am b/Makefile.am > index 7654bf5..1b18198 100644 > --- a/Makefile.am > +++ b/Makefile.am > @@ -38,7 +38,8 @@ toolexeclib_LTLIBRARIES = libffi.la <http://libffi.la> > noinst_LTLIBRARIES = libffi_convenience.la <http://libffi_convenience.la> > > libffi_la_SOURCES = src/prep_cif.c src/types.c \ > - src/raw_api.c src/java_raw_api.c src/closures.c > + src/raw_api.c src/java_raw_api.c src/closures.c \ > + src/tramp.c > > if FFI_DEBUG > libffi_la_SOURCES += src/debug.c > diff --git a/configure.ac <http://configure.ac> b/configure.ac <http://configure.ac> > index 790274e..898ede6 100644 > --- a/configure.ac <http://configure.ac> > +++ b/configure.ac <http://configure.ac> > @@ -360,6 +360,13 @@ AC_ARG_ENABLE(raw-api, > AC_DEFINE(FFI_NO_RAW_API, 1, [Define this if you do not want support for the raw API.]) > fi) > > +AC_ARG_ENABLE(static-tramp, > +[ --enable-static-tramp use statically defined trampolines], > + if test "$enable_static_tramp" = "yes"; then > + AC_DEFINE(FFI_EXEC_STATIC_TRAMP, 1, > + [Define this if you want to use statically defined trampolines.]) > + fi) > + > AC_ARG_ENABLE(purify-safety, > [ --enable-purify-safety purify-safe mode], > if test "$enable_purify_safety" = "yes"; then > diff --git a/include/ffi.h.in <http://ffi.h.in> b/include/ffi.h.in <http://ffi.h.in> > index 38885b0..c6a21d9 100644 > --- a/include/ffi.h.in <http://ffi.h.in> > +++ b/include/ffi.h.in <http://ffi.h.in> > @@ -310,7 +310,10 @@ typedef struct { > void *trampoline_table; > void *trampoline_table_entry; > #else > - char tramp[FFI_TRAMPOLINE_SIZE]; > + union { > + char tramp[FFI_TRAMPOLINE_SIZE]; > + void *ftramp; > + }; > #endif > ffi_cif *cif; > void (*fun)(ffi_cif*,void*,void**,void*); > @@ -457,6 +460,14 @@ FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue, > > #endif /* FFI_GO_CLOSURES */ > > +/* ---- Static Trampoline Definitions -------------------------------------- */ > + > +FFI_API int ffi_tramp_is_supported(void); > +FFI_API void *ffi_tramp_alloc (int flags); > +FFI_API int ffi_tramp_set_parms (void *tramp, void *data, void *code); > +FFI_API void *ffi_tramp_get_addr (void *tramp); > +FFI_API void ffi_tramp_free (void *tramp); > + > /* ---- Public interface definition -------------------------------------- */ > > FFI_API > diff --git a/include/ffi_common.h b/include/ffi_common.h > index 76b9dd6..8743126 100644 > --- a/include/ffi_common.h > +++ b/include/ffi_common.h > @@ -103,6 +103,10 @@ ffi_status ffi_prep_cif_core(ffi_cif *cif, > some targets. */ > void *ffi_data_to_code_pointer (void *data) FFI_HIDDEN; > > +/* The arch code calls this to set the code and data parameters for a > + closure's static trampoline, if any. */ > +int ffi_closure_tramp_set_parms (void *closure, void *code); > + > /* Extended cif, used in callback from assembly routine */ > typedef struct > { > diff --git a/libffi.map.in <http://libffi.map.in> b/libffi.map.in <http://libffi.map.in> > index de8778a..049c73e 100644 > --- a/libffi.map.in <http://libffi.map.in> > +++ b/libffi.map.in <http://libffi.map.in> > @@ -74,3 +74,14 @@ LIBFFI_GO_CLOSURE_8.0 { > ffi_prep_go_closure; > } LIBFFI_CLOSURE_8.0; > #endif > + > +#if FFI_EXEC_STATIC_TRAMP > +LIBFFI_STATIC_TRAMP_8.0 { > + global: > + ffi_tramp_is_supported; > + ffi_tramp_alloc; > + ffi_tramp_set_parms; > + ffi_tramp_get_addr; > + ffi_tramp_free; > +} LIBFFI_BASE_8.0; > +#endif > diff --git a/src/closures.c b/src/closures.c > index 4fe6158..cf1d3de 100644 > --- a/src/closures.c > +++ b/src/closures.c > @@ -109,6 +109,12 @@ ffi_closure_free (void *ptr) > munmap(dataseg, rounded_size); > munmap(codeseg, rounded_size); > } > + > +int > +ffi_closure_tramp_set_parms (void *ptr, void *code) > +{ > + return 0; > +} > #else /* !NetBSD with PROT_MPROTECT */ > > #if !FFI_MMAP_EXEC_WRIT && !FFI_EXEC_TRAMPOLINE_TABLE > @@ -843,6 +849,12 @@ dlmmap (void *start, size_t length, int prot, > && flags == (MAP_PRIVATE | MAP_ANONYMOUS) > && fd == -1 && offset == 0); > > + if (execfd == -1 && ffi_tramp_is_supported ()) > + { > + ptr = mmap (start, length, prot & ~PROT_EXEC, flags, fd, offset); > + return ptr; > + } > + > if (execfd == -1 && is_emutramp_enabled ()) > { > ptr = mmap (start, length, prot & ~PROT_EXEC, flags, fd, offset); > @@ -922,7 +934,7 @@ segment_holding_code (mstate m, char* addr) > void * > ffi_closure_alloc (size_t size, void **code) > { > - void *ptr; > + void *ptr, *ftramp; > > if (!code) > return NULL; > @@ -934,6 +946,17 @@ ffi_closure_alloc (size_t size, void **code) > msegmentptr seg = segment_holding (gm, ptr); > > *code = add_segment_exec_offset (ptr, seg); > + if (!ffi_tramp_is_supported ()) > + return ptr; > + > + ftramp = ffi_tramp_alloc (0); > + if (ftramp == NULL) > + { > + dlfree (FFI_RESTORE_PTR (ptr)); > + return NULL; > + } > + *code = ffi_tramp_get_addr (ftramp); > + ((ffi_closure *) ptr)->ftramp = ftramp; > } > > return ptr; > @@ -943,12 +966,17 @@ void * > ffi_data_to_code_pointer (void *data) > { > msegmentptr seg = segment_holding (gm, data); > + > /* We expect closures to be allocated with ffi_closure_alloc(), in > which case seg will be non-NULL. However, some users take on the > burden of managing this memory themselves, in which case this > we'll just return data. */ > if (seg) > - return add_segment_exec_offset (data, seg); > + { > + if (!ffi_tramp_is_supported ()) > + return add_segment_exec_offset (data, seg); > + return ffi_tramp_get_addr (((ffi_closure *) data)->ftramp); > + } > else > return data; > } > @@ -966,10 +994,26 @@ ffi_closure_free (void *ptr) > if (seg) > ptr = sub_segment_exec_offset (ptr, seg); > #endif > + if (ffi_tramp_is_supported ()) > + ffi_tramp_free (((ffi_closure *) ptr)->ftramp); > > dlfree (FFI_RESTORE_PTR (ptr)); > } > > +int > +ffi_closure_tramp_set_parms (void *ptr, void *code) > +{ > + void *ftramp; > + > + msegmentptr seg = segment_holding (gm, ptr); > + if (!seg || !ffi_tramp_is_supported()) > + return 0; > + > + ftramp = ((ffi_closure *) ptr)->ftramp; > + ffi_tramp_set_parms (ftramp, code, ptr); > + return 1; > +} > + > # else /* ! FFI_MMAP_EXEC_WRIT */ > > /* On many systems, memory returned by malloc is writable and > @@ -998,6 +1042,12 @@ ffi_data_to_code_pointer (void *data) > return data; > } > > +int > +ffi_closure_tramp_set_parms (void *ptr, void *code) > +{ > + return 0; > +} > + > # endif /* ! FFI_MMAP_EXEC_WRIT */ > #endif /* FFI_CLOSURES */ > > diff --git a/src/tramp.c b/src/tramp.c > new file mode 100644 > index 0000000..3170152 > --- /dev/null > +++ b/src/tramp.c > @@ -0,0 +1,563 @@ > +/* ----------------------------------------------------------------------- > + tramp.c - Copyright (c) 2020 Madhavan T. Venkataraman > + > + API and support functions for managing statically defined closure > + trampolines. > + > + Permission is hereby granted, free of charge, to any person obtaining > + a copy of this software and associated documentation files (the > + ``Software''), to deal in the Software without restriction, including > + without limitation the rights to use, copy, modify, merge, publish, > + distribute, sublicense, and/or sell copies of the Software, and to > + permit persons to whom the Software is furnished to do so, subject to > + the following conditions: > + > + The above copyright notice and this permission notice shall be included > + in all copies or substantial portions of the Software. > + > + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, > + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF > + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND > + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT > + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, > + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, > + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER > + DEALINGS IN THE SOFTWARE. > + ----------------------------------------------------------------------- */ > + > +#include <stdio.h> > +#include <unistd.h> > +#include <stdlib.h> > +#include <stdint.h> > +#include <fcntl.h> > +#include <pthread.h> > +#include <sys/mman.h> > +#include <linux/limits.h> > +#include <linux/types.h> > +#include <fficonfig.h> > + > +#if defined(FFI_EXEC_STATIC_TRAMP) > + > +#if !defined(__linux__) > +#error "FFI_EXEC_STATIC_TRAMP is currently only supported on Linux" > +#endif > + > +#if !defined _GNU_SOURCE > +#define _GNU_SOURCE 1 > +#endif > + > +/* > + * Each architecture defines static code for a trampoline code table. The > + * trampoline code table is mapped into the address space of a process. > + * > + * The following architecture specific function returns: > + * > + * - the address of the trampoline code table in the text segment > + * - the size of each trampoline in the trampoline code table > + * - the size of the mapping for the whole trampoline code table > + */ > +void __attribute__((weak)) *ffi_tramp_arch (size_t *tramp_size, > + size_t *map_size); > + > +/* ------------------------- Trampoline Data Structures --------------------*/ > + > +static pthread_mutex_t tramp_lock = PTHREAD_MUTEX_INITIALIZER; > + > +struct tramp; > + > +/* > + * Trampoline table. Manages one trampoline code table and one trampoline > + * parameter table. > + * > + * prev, next Links in the global trampoline table list. > + * code_table Trampoline code table mapping. > + * parm_table Trampoline parameter table mapping. > + * array Array of trampolines malloced. > + * free List of free trampolines. > + * nfree Number of free trampolines. > + */ > +struct tramp_table > +{ > + struct tramp_table *prev; > + struct tramp_table *next; > + void *code_table; > + void *parm_table; > + struct tramp *array; > + struct tramp *free; > + int nfree; > +}; > + > +/* > + * Parameters for each trampoline. > + * > + * data > + * Data for the target code that the trampoline jumps to. > + * target > + * Target code that the trampoline jumps to. > + */ > +struct tramp_parm > +{ > + void *data; > + void *target; > +}; > + > +/* > + * Trampoline structure for each trampoline. > + * > + * prev, next Links in the trampoline free list of a trampoline table. > + * table Trampoline table to which this trampoline belongs. > + * code Address of this trampoline in the code table mapping. > + * parm Address of this trampoline's parameters in the parameter > + * table mapping. > + */ > +struct tramp > +{ > + struct tramp *prev; > + struct tramp *next; > + struct tramp_table *table; > + void *code; > + struct tramp_parm *parm; > +}; > + > +/* > + * Trampoline globals. > + * > + * fd > + * File descriptor of binary file that contains the trampoline code table. > + * offset > + * Offset of the trampoline code table in that file. > + * map_size > + * Size of the trampoline code table mapping. > + * size > + * Size of one trampoline in the trampoline code table. > + * ntramp > + * Total number of trampolines in the trampoline code table. > + * tables > + * List of trampoline tables that contain free trampolines. > + * ntables > + * Number of trampoline tables that contain free trampolines. > + */ > +struct tramp_global > +{ > + int fd; > + off_t offset; > + size_t map_size; > + size_t size; > + int ntramp; > + struct tramp_table *tables; > + int ntables; > +}; > + > +static struct tramp_global gtramp = { -1 }; > + > +/* ------------------------ Trampoline Initialization ----------------------*/ > + > +static int ffi_tramp_get_fd_offset (void *tramp_text, off_t *offset); > + > +/* > + * Initialize the static trampoline feature. > + */ > +static int > +ffi_tramp_init (void) > +{ > + if (ffi_tramp_arch == NULL) > + return 0; > + > + if (gtramp.fd == -1) > + { > + void *tramp_text; > + > + gtramp.tables = NULL; > + gtramp.ntables = 0; > + > + /* > + * Get trampoline code table information from the architecture. > + */ > + tramp_text = ffi_tramp_arch (>ramp.size, >ramp.map_size); > + gtramp.ntramp = gtramp.map_size / gtramp.size; > + > + /* > + * Get the binary file that contains the trampoline code table and also > + * the offset of the table within the file. These are used to mmap() > + * the trampoline code table. > + */ > + gtramp.fd = ffi_tramp_get_fd_offset (tramp_text, >ramp.offset); > + } > + return gtramp.fd != -1; > +} > + > +/* > + * From the address of the trampoline code table in the text segment, find the > + * binary file and offset of the trampoline code table from /proc/<pid>/maps. > + */ > +static int > +ffi_tramp_get_fd_offset (void *tramp_text, off_t *offset) > +{ > + FILE *fp; > + char file[PATH_MAX], line[PATH_MAX+100], perm[10], dev[10]; > + unsigned long start, end, inode; > + uintptr_t addr = (uintptr_t) tramp_text; > + int nfields, found; > + > + snprintf (file, PATH_MAX, "/proc/%d/maps", getpid()); > + fp = fopen (file, "r"); > + if (fp == NULL) > + return -1; > + > + found = 0; > + while (feof (fp) == 0) { > + if (fgets (line, sizeof (line), fp) == 0) > + break; > + > + nfields = sscanf (line, "%lx-%lx %s %lx %s %ld %s", > + &start, &end, perm, offset, dev, &inode, file); > + if (nfields != 7) > + continue; > + > + if (addr >= start && addr < end) { > + *offset += (addr - start); > + found = 1; > + break; > + } > + } > + fclose (fp); > + > + if (!found) > + return -1; > + > + return open (file, O_RDONLY); > +} > + > +/* ---------------------- Trampoline Table functions ---------------------- */ > + > +static int tramp_table_map (char **code_table, char **parm_table); > +static void tramp_add (struct tramp *tramp); > + > +/* > + * Allocate and initialize a trampoline table. > + */ > +static int > +tramp_table_alloc (void) > +{ > + char *code_table, *parm_table; > + struct tramp_table *table; > + struct tramp *tramp_array, *tramp; > + size_t size; > + char *code, *parm; > + int i; > + > + /* > + * If we already have tables with free trampolines, there is no need to > + * allocate a new table. > + */ > + if (gtramp.ntables > 0) > + return 1; > + > + /* > + * Allocate a new trampoline table structure. > + */ > + table = malloc (sizeof (*table)); > + if (table == NULL) > + return 0; > + > + /* > + * Allocate new trampoline structures. > + */ > + tramp_array = malloc (sizeof (*tramp) * gtramp.ntramp); > + if (tramp_array == NULL) > + goto free_table; > + > + /* > + * Map a code table and a parameter table into the caller's address space. > + */ > + if (!tramp_table_map (&code_table, &parm_table)) > + goto free_tramp_array; > + > + /* > + * Initialize the trampoline table. > + */ > + table->code_table = code_table; > + table->parm_table = parm_table; > + table->array = tramp_array; > + table->free = NULL; > + table->nfree = 0; > + > + /* > + * Populate the trampoline table free list. This will also add the trampoline > + * table to the global list of trampoline tables. > + */ > + size = gtramp.size; > + code = code_table; > + parm = parm_table; > + for (i = 0; i < gtramp.ntramp; i++) > + { > + tramp = &tramp_array[i]; > + tramp->table = table; > + tramp->code = code; > + tramp->parm = (struct tramp_parm *) parm; > + tramp_add (tramp); > + > + code += size; > + parm += size; > + } > + return 1; > + > +free_tramp_array: > + free (tramp_array); > +free_table: > + free (table); > + return 0; > +} > + > +/* > + * Create a trampoline code table mapping and a trampoline parameter table > + * mapping. The two mappings must be adjacent to each other for PC-relative > + * access. > + * > + * For each trampoline in the code table, there is a corresponding parameter > + * block in the parameter table. The size of the parameter block is the same > + * as the size of the trampoline. This means that the parameter block is at > + * a fixed offset from its trampoline making it easy for a trampoline to find > + * its parameters using PC-relative access. > + * > + * The parameter block will contain a struct tramp_parm. This means that > + * sizeof (struct tramp_parm) cannot exceed the size of a parameter block. > + */ > +static int > +tramp_table_map (char **code_table, char **parm_table) > +{ > + char *addr; > + > + /* > + * Create an anonymous mapping twice the map size. The top half will be used > + * for the code table. The bottom half will be used for the parameter table. > + */ > + addr = mmap (NULL, gtramp.map_size * 2, PROT_READ | PROT_WRITE, > + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); > + if (addr == MAP_FAILED) > + return 0; > + > + /* > + * Replace the top half of the anonymous mapping with the code table mapping. > + */ > + *code_table = mmap (addr, gtramp.map_size, PROT_READ | PROT_EXEC, > + MAP_PRIVATE | MAP_FIXED, gtramp.fd, gtramp.offset); > + if (*code_table == MAP_FAILED) > + { > + (void) munmap (addr, gtramp.map_size * 2); > + return 0; > + } > + *parm_table = *code_table + gtramp.map_size; > + return 1; > +} > + > +/* > + * Free a trampoline table. > + */ > +static void > +tramp_table_free (struct tramp_table *table) > +{ > + (void) munmap (table->code_table, gtramp.map_size); > + (void) munmap (table->parm_table, gtramp.map_size); > + free (table->array); > + free (table); > +} > + > +/* > + * Add a new trampoline table to the global table list. > + */ > +static void > +tramp_table_add (struct tramp_table *table) > +{ > + table->next = gtramp.tables; > + table->prev = NULL; > + if (gtramp.tables != NULL) > + gtramp.tables->prev = table; > + gtramp.tables = table; > + gtramp.ntables++; > +} > + > +/* > + * Delete a trampoline table from the global table list. > + */ > +static void > +tramp_table_del (struct tramp_table *table) > +{ > + gtramp.ntables--; > + if (table->prev != NULL) > + table->prev->next = table->next; > + if (table->next != NULL) > + table->next->prev = table->prev; > + if (gtramp.tables == table) > + gtramp.tables = table->next; > +} > + > +/* ------------------------- Trampoline functions ------------------------- */ > + > +/* > + * Add a trampoline to its trampoline table. > + */ > +static void > +tramp_add (struct tramp *tramp) > +{ > + struct tramp_table *table = tramp->table; > + > + tramp->next = table->free; > + tramp->prev = NULL; > + if (table->free != NULL) > + table->free->prev = tramp; > + table->free = tramp; > + table->nfree++; > + > + if (table->nfree == 1) > + tramp_table_add (table); > + > + /* > + * We don't want to keep too many free trampoline tables lying around. > + */ > + if (table->nfree == gtramp.ntramp && gtramp.ntables > 1) > + { > + tramp_table_del (table); > + tramp_table_free (table); > + } > +} > + > +/* > + * Remove a trampoline from its trampoline table. > + */ > +static void > +tramp_del (struct tramp *tramp) > +{ > + struct tramp_table *table = tramp->table; > + > + table->nfree--; > + if (tramp->prev != NULL) > + tramp->prev->next = tramp->next; > + if (tramp->next != NULL) > + tramp->next->prev = tramp->prev; > + if (table->free == tramp) > + table->free = tramp->next; > + > + if (table->nfree == 0) > + tramp_table_del (table); > +} > + > +/* ------------------------ Trampoline API functions ------------------------ */ > + > +int > +ffi_tramp_is_supported(void) > +{ > + int ret; > + > + pthread_mutex_lock (&tramp_lock); > + ret = ffi_tramp_init (); > + pthread_mutex_unlock (&tramp_lock); > + return ret; > +} > + > +/* > + * Allocate a trampoline and return its opaque address. > + */ > +void * > +ffi_tramp_alloc (int flags) > +{ > + struct tramp *tramp; > + > + pthread_mutex_lock (&tramp_lock); > + > + if (!ffi_tramp_init () || flags != 0) > + { > + pthread_mutex_unlock (&tramp_lock); > + return NULL; > + } > + > + if (!tramp_table_alloc ()) > + { > + pthread_mutex_unlock (&tramp_lock); > + return NULL; > + } > + > + tramp = gtramp.tables->free; > + tramp_del (tramp); > + > + pthread_mutex_unlock (&tramp_lock); > + > + return tramp; > +} > + > +/* > + * Set the parameters for a trampoline. > + */ > +void > +ffi_tramp_set_parms (void *arg, void *target, void *data) > +{ > + struct tramp *tramp = arg; > + > + pthread_mutex_lock (&tramp_lock); > + tramp->parm->target = target; > + tramp->parm->data = data; > + pthread_mutex_unlock (&tramp_lock); > +} > + > +/* > + * Get the invocation address of a trampoline. > + */ > +void * > +ffi_tramp_get_addr (void *arg) > +{ > + struct tramp *tramp = arg; > + void *addr; > + > + pthread_mutex_lock (&tramp_lock); > + addr = tramp->code; > + pthread_mutex_unlock (&tramp_lock); > + > + return addr; > +} > + > +/* > + * Free a trampoline. > + */ > +void > +ffi_tramp_free (void *arg) > +{ > + struct tramp *tramp = arg; > + > + pthread_mutex_lock (&tramp_lock); > + tramp_add (tramp); > + pthread_mutex_unlock (&tramp_lock); > +} > + > +/* ------------------------------------------------------------------------- */ > + > +#else /* !FFI_EXEC_STATIC_TRAMP */ > + > +int > +ffi_tramp_is_supported(void) > +{ > + return 0; > +} > + > +void * > +ffi_tramp_alloc (int flags) > +{ > + return NULL; > +} > + > +void > +ffi_tramp_set_parms (void *arg, void *target, void *data) > +{ > +} > + > +void * > +ffi_tramp_get_addr (void *arg) > +{ > + return NULL; > +} > + > +void > +ffi_tramp_free (void *arg) > +{ > +} > + > +#endif /* FFI_EXEC_STATIC_TRAMP */ > diff --git a/testsuite/libffi.closures/closure_loc_fn0.c b/testsuite/libffi.closures/closure_loc_fn0.c > index b3afa0b..ad488ac 100644 > --- a/testsuite/libffi.closures/closure_loc_fn0.c > +++ b/testsuite/libffi.closures/closure_loc_fn0.c > @@ -83,7 +83,10 @@ int main (void) > CHECK(ffi_prep_closure_loc(pcl, &cif, closure_loc_test_fn0, > (void *) 3 /* userdata */, codeloc) == FFI_OK); > > +#ifndef FFI_EXEC_STATIC_TRAMP > + /* With static trampolines, the codeloc does not point to closure */ > CHECK(memcmp(pcl, codeloc, sizeof(*pcl)) == 0); > +#endif > > res = (*((closure_loc_test_type0)codeloc)) > (1LL, 2, 3LL, 4, 127, 429LL, 7, 8, 9.5, 10, 11, 12, 13, > -- > 2.25.1 > ^ permalink raw reply [flat|nested] 12+ messages in thread
* Re: [RFC PATCH v1 1/4] Static Trampolines 2020-12-02 16:49 ` Madhavan T. Venkataraman @ 2020-12-02 18:14 ` Anthony Green 2020-12-02 21:33 ` Madhavan T. Venkataraman 0 siblings, 1 reply; 12+ messages in thread From: Anthony Green @ 2020-12-02 18:14 UTC (permalink / raw) To: Madhavan T. Venkataraman; +Cc: libffi-discuss, fw Thanks, Madhavan. It seems that the travis-ci testing is stalled -- perhaps because they just changed their policies around free usage. I've reached out to them for help. It's possible we could move some of the load to GitHub Actions, but as far as I know, travis-ci is the only platform with s390 (and perhaps other) support. AG On Wed, Dec 2, 2020 at 11:49 AM Madhavan T. Venkataraman < madvenka@linux.microsoft.com> wrote: > > > On 11/24/20 1:49 PM, Anthony Green wrote: > > Thank you for your submission, Madhavan. This will be interesting > reading! > > > > In the meantime, it would be helpful if you submitted this as a PR on > GitHub. This will trigger CI testing for over 20 different systems so we > can have an initial look at any build/test problems. > > > > Just submitted the PR: > > https://github.com/libffi/libffi/pull/603 > > Thanks. > > Madhavan > > > AG > > > > On Tue, Nov 24, 2020 at 2:32 PM madvenka--- via Libffi-discuss < > libffi-discuss@sourceware.org <mailto:libffi-discuss@sourceware.org>> > wrote: > > > > From: "Madhavan T. Venkataraman" <madvenka@linux.microsoft.com > <mailto:madvenka@linux.microsoft.com>> > > > > Closure Trampoline Security Issue > > ================================= > > > > Currently, the trampoline code used in libffi is not statically > defined in > > a source file (except for MACH). The trampoline is either pre-defined > > machine code in a data buffer. Or, it is generated at runtime. In > order to > > execute a trampoline, it needs to be placed in a page with executable > > permissions. > > > > Executable data pages are attack surfaces for attackers who may try > to > > inject their own code into the page and contrive to have it > executed. The > > security settings in a system may prevent various tricks used in > user land > > to write code into a page and to have it executed somehow. On such > systems, > > libffi trampolines would not be able to run. > > > > Static Trampoline > > ================= > > > > To solve this problem, the trampoline code needs to be defined > statically > > in a source file, compiled and placed in the text segment so it can > be > > mapped and executed naturally without any tricks. However, the > trampoline > > needs to be able to access the closure pointer at runtime. > > > > PC-relative data referencing > > ============================ > > > > The solution implemented in this patch set uses PC-relative data > references. > > The trampoline is mapped in a code page. Adjacent to the code page, > a data > > page is mapped that contains the parameters of the trampoline: > > > > - the closure pointer > > - pointer to the ABI handler to jump to > > > > The trampoline code uses an offset relative to its current PC to > access its > > data. > > > > Some architectures support PC-relative data references in the ISA > itself. > > E.g., X64 supports RIP-relative references. For others, the PC has to > > somehow be loaded into a general purpose register to do PC-relative > data > > referencing. To do this, we need to define a get_pc() kind of > function and > > call it to load the PC in a desired register. > > > > There are two cases: > > > > 1. The call instruction pushes the return address on the stack. > > > > In this case, get_pc() will extract the return address from the > stack > > and load it in the desired register and return. > > > > 2. The call instruction stores the return address in a designated > register. > > > > In this case, get_pc() will copy the return address to the desired > > register and return. > > > > Either way, the PC next to the call instruction is obtained. > > > > Scratch register > > ================ > > > > In order to do its job, the trampoline code would be required to use > a > > scratch register. Depending on the ABI, there may not be a register > > available for scratch. This problem needs to be solved so that all > ABIs > > will work. > > > > The trampoline will save two values on the stack: > > > > - the closure pointer > > - the original value of the scratch register > > > > This is what the stack will look like: > > > > sp before trampoline ------> -------------------- > > | closure pointer | > > -------------------- > > | scratch register | > > sp after trampoline -------> -------------------- > > > > The ABI handler can do the following as needed by the ABI: > > > > - the closure pointer can be loaded in a desired register > > > > - the scratch register can be restored to its original value > > > > - the stack pointer can be restored to its original value > > (when the trampoline was invoked) > > > > Thus the ABI handlers will have a couple of lines of code at the very > > beginning to do this so that all ABIs will work. > > > > NOTE: > > The documentation for this feature will contain information > on: > > > > - the name of the scratch register for each architecture > > > > - the stack offsets at which the closure and the scratch > register > > will be copied > > > > Trampoline Table > > ================ > > > > In order to reduce the trampoline memory footprint, the trampoline > code > > would be defined as a code array in the text segment. This array > would be > > mapped into the address space of the caller. The mapping would, > therefore, > > contain a trampoline table. > > > > Adjacent to the trampoline table, there will be a data mapping that > contains > > a parameter table, one parameter block for each trampoline. The > parameter > > table will contain: > > > > - a pointer to the closure > > - a pointer to the ABI handler > > > > The trampoline code would finally look like this: > > > > - Make space on the stack for the closure and the scratch > register > > by moving the stack pointer down > > - Store the original value of the scratch register on the > stack > > - Using PC-relative reference, get the closure pointer > > - Store the closure pointer on the stack > > - Using PC-relative reference, get the ABI handler pointer > > - Jump to the ABI handler > > > > Trampoline API > > ============== > > > > There is a lot of dynamic code out there. They all have the same > security > > issue. Dynamic code can be re-written into static code provided the > data > > required by the static code can be passed to it just like we pass the > > closure pointer to an ABI handler. > > > > So, the same trampoline functions used by libffi internally need to > be > > made available to the rest of the world in the form of an API. The > > following API has been defined in this solution: > > > > int ffi_tramp_is_supported(void); > > > > To support static trampolines, code needs to be added to each > > architecture. Also, the feature itself can be enabled via a > > configuration option. So, this function tells us if the > feature > > is supported and enabled in the current libffi or not. > > > > void *ffi_tramp_alloc (int flags); > > > > Allocate a trampoline. Currently, flags are zero. An opaque > > trampoline structure pointer is returned. > > > > Internally, libffi manages trampoline tables and individual > > trampolines in each table. > > > > int ffi_tramp_set_parms (void *tramp, void *target, void *data); > > > > Initialize the parameters of a trampoline. That is, the > target code > > that the trampoline should jump to and the data that needs > to be > > passed to the target code. > > > > void *ffi_tramp_get_addr (void *tramp); > > > > Return the address of the trampoline to invoke the > trampoline with. > > The trampoline can be invoked in one of two ways: > > > > - Simply branch to the trampoline address > > - Treat the trampoline address as a function pointer > and > > call it. > > > > Which method is used depends on the target code. > > > > void ffi_tramp_free (void *tramp); > > > > Free a trampoline. > > > > Configuration > > ============= > > > > A new configuration option, --enable-static-tramp has been added to > enable > > the use of static trampolines. > > > > Mapping size > > ============ > > > > The size of the code mapping that contains the trampoline table > needs to be > > determined on a per architecture basis. If a particular architecture > > supports multiple base page sizes, then the largest base page size > needs to > > be chosen. E.g., we choose 16K for ARM64. > > > > Trampoline allocation and free > > ============================== > > > > Static trampolines are allocated in ffi_closure_alloc() and freed in > > ffi_closure_free(). > > > > Normally, applications use these functions. But there are some cases > out > > there where the user of libffi allocates and manages its own closure > > memory. In such cases, the static trampoline API cannot be used. > These > > will fall back to using legacy trampolines. The user has to make sure > > that the memory is executable. > > > > ffi_closure structure > > ===================== > > > > I did not want to make any changes to the size of the closure > structure for > > this feature to guarantee compatibility. But the opaque static > trampoline > > handle needs to be stored in the closure. I have defined it as > follows: > > > > - char tramp[FFI_TRAMPOLINE_SIZE]; > > + union { > > + char tramp[FFI_TRAMPOLINE_SIZE]; > > + void *ftramp; > > + }; > > > > If static trampolines are used, then tramp[] is not needed to store a > > dynamic trampoline. That space can be reused to store the handle. > Hence, > > the union. > > > > Signed-off-by: Madhavan T. Venkataraman < > madvenka@linux.microsoft.com <mailto:madvenka@linux.microsoft.com>> > > --- > > Makefile.am | 3 +- > > configure.ac <http://configure.ac> > | 7 + > > include/ffi.h.in <http://ffi.h.in> | > 13 +- > > include/ffi_common.h | 4 + > > libffi.map.in <http://libffi.map.in> > | 11 + > > src/closures.c | 54 +- > > src/tramp.c | 563 > ++++++++++++++++++++ > > testsuite/libffi.closures/closure_loc_fn0.c | 3 + > > 8 files changed, 654 insertions(+), 4 deletions(-) > > create mode 100644 src/tramp.c > > > > diff --git a/Makefile.am b/Makefile.am > > index 7654bf5..1b18198 100644 > > --- a/Makefile.am > > +++ b/Makefile.am > > @@ -38,7 +38,8 @@ toolexeclib_LTLIBRARIES = libffi.la < > http://libffi.la> > > noinst_LTLIBRARIES = libffi_convenience.la < > http://libffi_convenience.la> > > > > libffi_la_SOURCES = src/prep_cif.c src/types.c \ > > - src/raw_api.c src/java_raw_api.c src/closures.c > > + src/raw_api.c src/java_raw_api.c src/closures.c \ > > + src/tramp.c > > > > if FFI_DEBUG > > libffi_la_SOURCES += src/debug.c > > diff --git a/configure.ac <http://configure.ac> b/configure.ac < > http://configure.ac> > > index 790274e..898ede6 100644 > > --- a/configure.ac <http://configure.ac> > > +++ b/configure.ac <http://configure.ac> > > @@ -360,6 +360,13 @@ AC_ARG_ENABLE(raw-api, > > AC_DEFINE(FFI_NO_RAW_API, 1, [Define this if you do not want > support for the raw API.]) > > fi) > > > > +AC_ARG_ENABLE(static-tramp, > > +[ --enable-static-tramp use statically defined trampolines], > > + if test "$enable_static_tramp" = "yes"; then > > + AC_DEFINE(FFI_EXEC_STATIC_TRAMP, 1, > > + [Define this if you want to use statically defined > trampolines.]) > > + fi) > > + > > AC_ARG_ENABLE(purify-safety, > > [ --enable-purify-safety purify-safe mode], > > if test "$enable_purify_safety" = "yes"; then > > diff --git a/include/ffi.h.in <http://ffi.h.in> b/include/ffi.h.in < > http://ffi.h.in> > > index 38885b0..c6a21d9 100644 > > --- a/include/ffi.h.in <http://ffi.h.in> > > +++ b/include/ffi.h.in <http://ffi.h.in> > > @@ -310,7 +310,10 @@ typedef struct { > > void *trampoline_table; > > void *trampoline_table_entry; > > #else > > - char tramp[FFI_TRAMPOLINE_SIZE]; > > + union { > > + char tramp[FFI_TRAMPOLINE_SIZE]; > > + void *ftramp; > > + }; > > #endif > > ffi_cif *cif; > > void (*fun)(ffi_cif*,void*,void**,void*); > > @@ -457,6 +460,14 @@ FFI_API void ffi_call_go (ffi_cif *cif, void > (*fn)(void), void *rvalue, > > > > #endif /* FFI_GO_CLOSURES */ > > > > +/* ---- Static Trampoline Definitions > -------------------------------------- */ > > + > > +FFI_API int ffi_tramp_is_supported(void); > > +FFI_API void *ffi_tramp_alloc (int flags); > > +FFI_API int ffi_tramp_set_parms (void *tramp, void *data, void > *code); > > +FFI_API void *ffi_tramp_get_addr (void *tramp); > > +FFI_API void ffi_tramp_free (void *tramp); > > + > > /* ---- Public interface definition > -------------------------------------- */ > > > > FFI_API > > diff --git a/include/ffi_common.h b/include/ffi_common.h > > index 76b9dd6..8743126 100644 > > --- a/include/ffi_common.h > > +++ b/include/ffi_common.h > > @@ -103,6 +103,10 @@ ffi_status ffi_prep_cif_core(ffi_cif *cif, > > some targets. */ > > void *ffi_data_to_code_pointer (void *data) FFI_HIDDEN; > > > > +/* The arch code calls this to set the code and data parameters for > a > > + closure's static trampoline, if any. */ > > +int ffi_closure_tramp_set_parms (void *closure, void *code); > > + > > /* Extended cif, used in callback from assembly routine */ > > typedef struct > > { > > diff --git a/libffi.map.in <http://libffi.map.in> b/libffi.map.in < > http://libffi.map.in> > > index de8778a..049c73e 100644 > > --- a/libffi.map.in <http://libffi.map.in> > > +++ b/libffi.map.in <http://libffi.map.in> > > @@ -74,3 +74,14 @@ LIBFFI_GO_CLOSURE_8.0 { > > ffi_prep_go_closure; > > } LIBFFI_CLOSURE_8.0; > > #endif > > + > > +#if FFI_EXEC_STATIC_TRAMP > > +LIBFFI_STATIC_TRAMP_8.0 { > > + global: > > + ffi_tramp_is_supported; > > + ffi_tramp_alloc; > > + ffi_tramp_set_parms; > > + ffi_tramp_get_addr; > > + ffi_tramp_free; > > +} LIBFFI_BASE_8.0; > > +#endif > > diff --git a/src/closures.c b/src/closures.c > > index 4fe6158..cf1d3de 100644 > > --- a/src/closures.c > > +++ b/src/closures.c > > @@ -109,6 +109,12 @@ ffi_closure_free (void *ptr) > > munmap(dataseg, rounded_size); > > munmap(codeseg, rounded_size); > > } > > + > > +int > > +ffi_closure_tramp_set_parms (void *ptr, void *code) > > +{ > > + return 0; > > +} > > #else /* !NetBSD with PROT_MPROTECT */ > > > > #if !FFI_MMAP_EXEC_WRIT && !FFI_EXEC_TRAMPOLINE_TABLE > > @@ -843,6 +849,12 @@ dlmmap (void *start, size_t length, int prot, > > && flags == (MAP_PRIVATE | MAP_ANONYMOUS) > > && fd == -1 && offset == 0); > > > > + if (execfd == -1 && ffi_tramp_is_supported ()) > > + { > > + ptr = mmap (start, length, prot & ~PROT_EXEC, flags, fd, > offset); > > + return ptr; > > + } > > + > > if (execfd == -1 && is_emutramp_enabled ()) > > { > > ptr = mmap (start, length, prot & ~PROT_EXEC, flags, fd, > offset); > > @@ -922,7 +934,7 @@ segment_holding_code (mstate m, char* addr) > > void * > > ffi_closure_alloc (size_t size, void **code) > > { > > - void *ptr; > > + void *ptr, *ftramp; > > > > if (!code) > > return NULL; > > @@ -934,6 +946,17 @@ ffi_closure_alloc (size_t size, void **code) > > msegmentptr seg = segment_holding (gm, ptr); > > > > *code = add_segment_exec_offset (ptr, seg); > > + if (!ffi_tramp_is_supported ()) > > + return ptr; > > + > > + ftramp = ffi_tramp_alloc (0); > > + if (ftramp == NULL) > > + { > > + dlfree (FFI_RESTORE_PTR (ptr)); > > + return NULL; > > + } > > + *code = ffi_tramp_get_addr (ftramp); > > + ((ffi_closure *) ptr)->ftramp = ftramp; > > } > > > > return ptr; > > @@ -943,12 +966,17 @@ void * > > ffi_data_to_code_pointer (void *data) > > { > > msegmentptr seg = segment_holding (gm, data); > > + > > /* We expect closures to be allocated with ffi_closure_alloc(), in > > which case seg will be non-NULL. However, some users take on > the > > burden of managing this memory themselves, in which case this > > we'll just return data. */ > > if (seg) > > - return add_segment_exec_offset (data, seg); > > + { > > + if (!ffi_tramp_is_supported ()) > > + return add_segment_exec_offset (data, seg); > > + return ffi_tramp_get_addr (((ffi_closure *) data)->ftramp); > > + } > > else > > return data; > > } > > @@ -966,10 +994,26 @@ ffi_closure_free (void *ptr) > > if (seg) > > ptr = sub_segment_exec_offset (ptr, seg); > > #endif > > + if (ffi_tramp_is_supported ()) > > + ffi_tramp_free (((ffi_closure *) ptr)->ftramp); > > > > dlfree (FFI_RESTORE_PTR (ptr)); > > } > > > > +int > > +ffi_closure_tramp_set_parms (void *ptr, void *code) > > +{ > > + void *ftramp; > > + > > + msegmentptr seg = segment_holding (gm, ptr); > > + if (!seg || !ffi_tramp_is_supported()) > > + return 0; > > + > > + ftramp = ((ffi_closure *) ptr)->ftramp; > > + ffi_tramp_set_parms (ftramp, code, ptr); > > + return 1; > > +} > > + > > # else /* ! FFI_MMAP_EXEC_WRIT */ > > > > /* On many systems, memory returned by malloc is writable and > > @@ -998,6 +1042,12 @@ ffi_data_to_code_pointer (void *data) > > return data; > > } > > > > +int > > +ffi_closure_tramp_set_parms (void *ptr, void *code) > > +{ > > + return 0; > > +} > > + > > # endif /* ! FFI_MMAP_EXEC_WRIT */ > > #endif /* FFI_CLOSURES */ > > > > diff --git a/src/tramp.c b/src/tramp.c > > new file mode 100644 > > index 0000000..3170152 > > --- /dev/null > > +++ b/src/tramp.c > > @@ -0,0 +1,563 @@ > > +/* > ----------------------------------------------------------------------- > > + tramp.c - Copyright (c) 2020 Madhavan T. Venkataraman > > + > > + API and support functions for managing statically defined closure > > + trampolines. > > + > > + Permission is hereby granted, free of charge, to any person > obtaining > > + a copy of this software and associated documentation files (the > > + ``Software''), to deal in the Software without restriction, > including > > + without limitation the rights to use, copy, modify, merge, > publish, > > + distribute, sublicense, and/or sell copies of the Software, and > to > > + permit persons to whom the Software is furnished to do so, > subject to > > + the following conditions: > > + > > + The above copyright notice and this permission notice shall be > included > > + in all copies or substantial portions of the Software. > > + > > + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, > > + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES > OF > > + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND > > + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT > > + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, > > + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING > FROM, > > + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER > > + DEALINGS IN THE SOFTWARE. > > + > ----------------------------------------------------------------------- */ > > + > > +#include <stdio.h> > > +#include <unistd.h> > > +#include <stdlib.h> > > +#include <stdint.h> > > +#include <fcntl.h> > > +#include <pthread.h> > > +#include <sys/mman.h> > > +#include <linux/limits.h> > > +#include <linux/types.h> > > +#include <fficonfig.h> > > + > > +#if defined(FFI_EXEC_STATIC_TRAMP) > > + > > +#if !defined(__linux__) > > +#error "FFI_EXEC_STATIC_TRAMP is currently only supported on Linux" > > +#endif > > + > > +#if !defined _GNU_SOURCE > > +#define _GNU_SOURCE 1 > > +#endif > > + > > +/* > > + * Each architecture defines static code for a trampoline code > table. The > > + * trampoline code table is mapped into the address space of a > process. > > + * > > + * The following architecture specific function returns: > > + * > > + * - the address of the trampoline code table in the text > segment > > + * - the size of each trampoline in the trampoline code table > > + * - the size of the mapping for the whole trampoline code table > > + */ > > +void __attribute__((weak)) *ffi_tramp_arch (size_t *tramp_size, > > + size_t *map_size); > > + > > +/* ------------------------- Trampoline Data Structures > --------------------*/ > > + > > +static pthread_mutex_t tramp_lock = PTHREAD_MUTEX_INITIALIZER; > > + > > +struct tramp; > > + > > +/* > > + * Trampoline table. Manages one trampoline code table and one > trampoline > > + * parameter table. > > + * > > + * prev, next Links in the global trampoline table list. > > + * code_table Trampoline code table mapping. > > + * parm_table Trampoline parameter table mapping. > > + * array Array of trampolines malloced. > > + * free List of free trampolines. > > + * nfree Number of free trampolines. > > + */ > > +struct tramp_table > > +{ > > + struct tramp_table *prev; > > + struct tramp_table *next; > > + void *code_table; > > + void *parm_table; > > + struct tramp *array; > > + struct tramp *free; > > + int nfree; > > +}; > > + > > +/* > > + * Parameters for each trampoline. > > + * > > + * data > > + * Data for the target code that the trampoline jumps to. > > + * target > > + * Target code that the trampoline jumps to. > > + */ > > +struct tramp_parm > > +{ > > + void *data; > > + void *target; > > +}; > > + > > +/* > > + * Trampoline structure for each trampoline. > > + * > > + * prev, next Links in the trampoline free list of a trampoline > table. > > + * table Trampoline table to which this trampoline belongs. > > + * code Address of this trampoline in the code table > mapping. > > + * parm Address of this trampoline's parameters in > the parameter > > + * table mapping. > > + */ > > +struct tramp > > +{ > > + struct tramp *prev; > > + struct tramp *next; > > + struct tramp_table *table; > > + void *code; > > + struct tramp_parm *parm; > > +}; > > + > > +/* > > + * Trampoline globals. > > + * > > + * fd > > + * File descriptor of binary file that contains the trampoline > code table. > > + * offset > > + * Offset of the trampoline code table in that file. > > + * map_size > > + * Size of the trampoline code table mapping. > > + * size > > + * Size of one trampoline in the trampoline code table. > > + * ntramp > > + * Total number of trampolines in the trampoline code table. > > + * tables > > + * List of trampoline tables that contain free trampolines. > > + * ntables > > + * Number of trampoline tables that contain free trampolines. > > + */ > > +struct tramp_global > > +{ > > + int fd; > > + off_t offset; > > + size_t map_size; > > + size_t size; > > + int ntramp; > > + struct tramp_table *tables; > > + int ntables; > > +}; > > + > > +static struct tramp_global gtramp = { -1 }; > > + > > +/* ------------------------ Trampoline Initialization > ----------------------*/ > > + > > +static int ffi_tramp_get_fd_offset (void *tramp_text, off_t > *offset); > > + > > +/* > > + * Initialize the static trampoline feature. > > + */ > > +static int > > +ffi_tramp_init (void) > > +{ > > + if (ffi_tramp_arch == NULL) > > + return 0; > > + > > + if (gtramp.fd == -1) > > + { > > + void *tramp_text; > > + > > + gtramp.tables = NULL; > > + gtramp.ntables = 0; > > + > > + /* > > + * Get trampoline code table information from the > architecture. > > + */ > > + tramp_text = ffi_tramp_arch (>ramp.size, >ramp.map_size); > > + gtramp.ntramp = gtramp.map_size / gtramp.size; > > + > > + /* > > + * Get the binary file that contains the trampoline code > table and also > > + * the offset of the table within the file. These are used to > mmap() > > + * the trampoline code table. > > + */ > > + gtramp.fd = ffi_tramp_get_fd_offset (tramp_text, > >ramp.offset); > > + } > > + return gtramp.fd != -1; > > +} > > + > > +/* > > + * From the address of the trampoline code table in the text > segment, find the > > + * binary file and offset of the trampoline code table from > /proc/<pid>/maps. > > + */ > > +static int > > +ffi_tramp_get_fd_offset (void *tramp_text, off_t *offset) > > +{ > > + FILE *fp; > > + char file[PATH_MAX], line[PATH_MAX+100], perm[10], dev[10]; > > + unsigned long start, end, inode; > > + uintptr_t addr = (uintptr_t) tramp_text; > > + int nfields, found; > > + > > + snprintf (file, PATH_MAX, "/proc/%d/maps", getpid()); > > + fp = fopen (file, "r"); > > + if (fp == NULL) > > + return -1; > > + > > + found = 0; > > + while (feof (fp) == 0) { > > + if (fgets (line, sizeof (line), fp) == 0) > > + break; > > + > > + nfields = sscanf (line, "%lx-%lx %s %lx %s %ld %s", > > + &start, &end, perm, offset, dev, &inode, file); > > + if (nfields != 7) > > + continue; > > + > > + if (addr >= start && addr < end) { > > + *offset += (addr - start); > > + found = 1; > > + break; > > + } > > + } > > + fclose (fp); > > + > > + if (!found) > > + return -1; > > + > > + return open (file, O_RDONLY); > > +} > > + > > +/* ---------------------- Trampoline Table functions > ---------------------- */ > > + > > +static int tramp_table_map (char **code_table, char **parm_table); > > +static void tramp_add (struct tramp *tramp); > > + > > +/* > > + * Allocate and initialize a trampoline table. > > + */ > > +static int > > +tramp_table_alloc (void) > > +{ > > + char *code_table, *parm_table; > > + struct tramp_table *table; > > + struct tramp *tramp_array, *tramp; > > + size_t size; > > + char *code, *parm; > > + int i; > > + > > + /* > > + * If we already have tables with free trampolines, there is no > need to > > + * allocate a new table. > > + */ > > + if (gtramp.ntables > 0) > > + return 1; > > + > > + /* > > + * Allocate a new trampoline table structure. > > + */ > > + table = malloc (sizeof (*table)); > > + if (table == NULL) > > + return 0; > > + > > + /* > > + * Allocate new trampoline structures. > > + */ > > + tramp_array = malloc (sizeof (*tramp) * gtramp.ntramp); > > + if (tramp_array == NULL) > > + goto free_table; > > + > > + /* > > + * Map a code table and a parameter table into the caller's > address space. > > + */ > > + if (!tramp_table_map (&code_table, &parm_table)) > > + goto free_tramp_array; > > + > > + /* > > + * Initialize the trampoline table. > > + */ > > + table->code_table = code_table; > > + table->parm_table = parm_table; > > + table->array = tramp_array; > > + table->free = NULL; > > + table->nfree = 0; > > + > > + /* > > + * Populate the trampoline table free list. This will also add > the trampoline > > + * table to the global list of trampoline tables. > > + */ > > + size = gtramp.size; > > + code = code_table; > > + parm = parm_table; > > + for (i = 0; i < gtramp.ntramp; i++) > > + { > > + tramp = &tramp_array[i]; > > + tramp->table = table; > > + tramp->code = code; > > + tramp->parm = (struct tramp_parm *) parm; > > + tramp_add (tramp); > > + > > + code += size; > > + parm += size; > > + } > > + return 1; > > + > > +free_tramp_array: > > + free (tramp_array); > > +free_table: > > + free (table); > > + return 0; > > +} > > + > > +/* > > + * Create a trampoline code table mapping and a trampoline > parameter table > > + * mapping. The two mappings must be adjacent to each other for > PC-relative > > + * access. > > + * > > + * For each trampoline in the code table, there is a corresponding > parameter > > + * block in the parameter table. The size of the parameter block is > the same > > + * as the size of the trampoline. This means that the parameter > block is at > > + * a fixed offset from its trampoline making it easy for a > trampoline to find > > + * its parameters using PC-relative access. > > + * > > + * The parameter block will contain a struct tramp_parm. This means > that > > + * sizeof (struct tramp_parm) cannot exceed the size of a parameter > block. > > + */ > > +static int > > +tramp_table_map (char **code_table, char **parm_table) > > +{ > > + char *addr; > > + > > + /* > > + * Create an anonymous mapping twice the map size. The top half > will be used > > + * for the code table. The bottom half will be used for the > parameter table. > > + */ > > + addr = mmap (NULL, gtramp.map_size * 2, PROT_READ | PROT_WRITE, > > + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); > > + if (addr == MAP_FAILED) > > + return 0; > > + > > + /* > > + * Replace the top half of the anonymous mapping with the code > table mapping. > > + */ > > + *code_table = mmap (addr, gtramp.map_size, PROT_READ | PROT_EXEC, > > + MAP_PRIVATE | MAP_FIXED, gtramp.fd, gtramp.offset); > > + if (*code_table == MAP_FAILED) > > + { > > + (void) munmap (addr, gtramp.map_size * 2); > > + return 0; > > + } > > + *parm_table = *code_table + gtramp.map_size; > > + return 1; > > +} > > + > > +/* > > + * Free a trampoline table. > > + */ > > +static void > > +tramp_table_free (struct tramp_table *table) > > +{ > > + (void) munmap (table->code_table, gtramp.map_size); > > + (void) munmap (table->parm_table, gtramp.map_size); > > + free (table->array); > > + free (table); > > +} > > + > > +/* > > + * Add a new trampoline table to the global table list. > > + */ > > +static void > > +tramp_table_add (struct tramp_table *table) > > +{ > > + table->next = gtramp.tables; > > + table->prev = NULL; > > + if (gtramp.tables != NULL) > > + gtramp.tables->prev = table; > > + gtramp.tables = table; > > + gtramp.ntables++; > > +} > > + > > +/* > > + * Delete a trampoline table from the global table list. > > + */ > > +static void > > +tramp_table_del (struct tramp_table *table) > > +{ > > + gtramp.ntables--; > > + if (table->prev != NULL) > > + table->prev->next = table->next; > > + if (table->next != NULL) > > + table->next->prev = table->prev; > > + if (gtramp.tables == table) > > + gtramp.tables = table->next; > > +} > > + > > +/* ------------------------- Trampoline functions > ------------------------- */ > > + > > +/* > > + * Add a trampoline to its trampoline table. > > + */ > > +static void > > +tramp_add (struct tramp *tramp) > > +{ > > + struct tramp_table *table = tramp->table; > > + > > + tramp->next = table->free; > > + tramp->prev = NULL; > > + if (table->free != NULL) > > + table->free->prev = tramp; > > + table->free = tramp; > > + table->nfree++; > > + > > + if (table->nfree == 1) > > + tramp_table_add (table); > > + > > + /* > > + * We don't want to keep too many free trampoline tables lying > around. > > + */ > > + if (table->nfree == gtramp.ntramp && gtramp.ntables > 1) > > + { > > + tramp_table_del (table); > > + tramp_table_free (table); > > + } > > +} > > + > > +/* > > + * Remove a trampoline from its trampoline table. > > + */ > > +static void > > +tramp_del (struct tramp *tramp) > > +{ > > + struct tramp_table *table = tramp->table; > > + > > + table->nfree--; > > + if (tramp->prev != NULL) > > + tramp->prev->next = tramp->next; > > + if (tramp->next != NULL) > > + tramp->next->prev = tramp->prev; > > + if (table->free == tramp) > > + table->free = tramp->next; > > + > > + if (table->nfree == 0) > > + tramp_table_del (table); > > +} > > + > > +/* ------------------------ Trampoline API functions > ------------------------ */ > > + > > +int > > +ffi_tramp_is_supported(void) > > +{ > > + int ret; > > + > > + pthread_mutex_lock (&tramp_lock); > > + ret = ffi_tramp_init (); > > + pthread_mutex_unlock (&tramp_lock); > > + return ret; > > +} > > + > > +/* > > + * Allocate a trampoline and return its opaque address. > > + */ > > +void * > > +ffi_tramp_alloc (int flags) > > +{ > > + struct tramp *tramp; > > + > > + pthread_mutex_lock (&tramp_lock); > > + > > + if (!ffi_tramp_init () || flags != 0) > > + { > > + pthread_mutex_unlock (&tramp_lock); > > + return NULL; > > + } > > + > > + if (!tramp_table_alloc ()) > > + { > > + pthread_mutex_unlock (&tramp_lock); > > + return NULL; > > + } > > + > > + tramp = gtramp.tables->free; > > + tramp_del (tramp); > > + > > + pthread_mutex_unlock (&tramp_lock); > > + > > + return tramp; > > +} > > + > > +/* > > + * Set the parameters for a trampoline. > > + */ > > +void > > +ffi_tramp_set_parms (void *arg, void *target, void *data) > > +{ > > + struct tramp *tramp = arg; > > + > > + pthread_mutex_lock (&tramp_lock); > > + tramp->parm->target = target; > > + tramp->parm->data = data; > > + pthread_mutex_unlock (&tramp_lock); > > +} > > + > > +/* > > + * Get the invocation address of a trampoline. > > + */ > > +void * > > +ffi_tramp_get_addr (void *arg) > > +{ > > + struct tramp *tramp = arg; > > + void *addr; > > + > > + pthread_mutex_lock (&tramp_lock); > > + addr = tramp->code; > > + pthread_mutex_unlock (&tramp_lock); > > + > > + return addr; > > +} > > + > > +/* > > + * Free a trampoline. > > + */ > > +void > > +ffi_tramp_free (void *arg) > > +{ > > + struct tramp *tramp = arg; > > + > > + pthread_mutex_lock (&tramp_lock); > > + tramp_add (tramp); > > + pthread_mutex_unlock (&tramp_lock); > > +} > > + > > +/* > ------------------------------------------------------------------------- */ > > + > > +#else /* !FFI_EXEC_STATIC_TRAMP */ > > + > > +int > > +ffi_tramp_is_supported(void) > > +{ > > + return 0; > > +} > > + > > +void * > > +ffi_tramp_alloc (int flags) > > +{ > > + return NULL; > > +} > > + > > +void > > +ffi_tramp_set_parms (void *arg, void *target, void *data) > > +{ > > +} > > + > > +void * > > +ffi_tramp_get_addr (void *arg) > > +{ > > + return NULL; > > +} > > + > > +void > > +ffi_tramp_free (void *arg) > > +{ > > +} > > + > > +#endif /* FFI_EXEC_STATIC_TRAMP */ > > diff --git a/testsuite/libffi.closures/closure_loc_fn0.c > b/testsuite/libffi.closures/closure_loc_fn0.c > > index b3afa0b..ad488ac 100644 > > --- a/testsuite/libffi.closures/closure_loc_fn0.c > > +++ b/testsuite/libffi.closures/closure_loc_fn0.c > > @@ -83,7 +83,10 @@ int main (void) > > CHECK(ffi_prep_closure_loc(pcl, &cif, closure_loc_test_fn0, > > (void *) 3 /* userdata */, codeloc) == > FFI_OK); > > > > +#ifndef FFI_EXEC_STATIC_TRAMP > > + /* With static trampolines, the codeloc does not point to closure > */ > > CHECK(memcmp(pcl, codeloc, sizeof(*pcl)) == 0); > > +#endif > > > > res = (*((closure_loc_test_type0)codeloc)) > > (1LL, 2, 3LL, 4, 127, 429LL, 7, 8, 9.5, 10, 11, 12, 13, > > -- > > 2.25.1 > > > ^ permalink raw reply [flat|nested] 12+ messages in thread
* Re: [RFC PATCH v1 1/4] Static Trampolines 2020-12-02 18:14 ` Anthony Green @ 2020-12-02 21:33 ` Madhavan T. Venkataraman 2020-12-03 18:45 ` Madhavan T. Venkataraman 0 siblings, 1 reply; 12+ messages in thread From: Madhavan T. Venkataraman @ 2020-12-02 21:33 UTC (permalink / raw) To: Anthony Green; +Cc: libffi-discuss, fw Thanks, Anthony. Madhavan On 12/2/20 12:14 PM, Anthony Green wrote: > Thanks, Madhavan. It seems that the travis-ci testing is stalled -- perhaps because they just changed their policies around free usage. I've reached out to them for help. It's possible we could move some of the load to GitHub Actions, but as far as I know, travis-ci is the only platform with s390 (and perhaps other) support. > > AG > > > On Wed, Dec 2, 2020 at 11:49 AM Madhavan T. Venkataraman <madvenka@linux.microsoft.com <mailto:madvenka@linux.microsoft.com>> wrote: > > > > On 11/24/20 1:49 PM, Anthony Green wrote: > > Thank you for your submission, Madhavan. This will be interesting reading! > > > > In the meantime, it would be helpful if you submitted this as a PR on GitHub. This will trigger CI testing for over 20 different systems so we can have an initial look at any build/test problems. > > > > Just submitted the PR: > > https://github.com/libffi/libffi/pull/603 > > Thanks. > > Madhavan > > > AG > > > > On Tue, Nov 24, 2020 at 2:32 PM madvenka--- via Libffi-discuss <libffi-discuss@sourceware.org <mailto:libffi-discuss@sourceware.org> <mailto:libffi-discuss@sourceware.org <mailto:libffi-discuss@sourceware.org>>> wrote: > > > > From: "Madhavan T. Venkataraman" <madvenka@linux.microsoft.com <mailto:madvenka@linux.microsoft.com> <mailto:madvenka@linux.microsoft.com <mailto:madvenka@linux.microsoft.com>>> > > > > Closure Trampoline Security Issue > > ================================= > > > > Currently, the trampoline code used in libffi is not statically defined in > > a source file (except for MACH). The trampoline is either pre-defined > > machine code in a data buffer. Or, it is generated at runtime. In order to > > execute a trampoline, it needs to be placed in a page with executable > > permissions. > > > > Executable data pages are attack surfaces for attackers who may try to > > inject their own code into the page and contrive to have it executed. The > > security settings in a system may prevent various tricks used in user land > > to write code into a page and to have it executed somehow. On such systems, > > libffi trampolines would not be able to run. > > > > Static Trampoline > > ================= > > > > To solve this problem, the trampoline code needs to be defined statically > > in a source file, compiled and placed in the text segment so it can be > > mapped and executed naturally without any tricks. However, the trampoline > > needs to be able to access the closure pointer at runtime. > > > > PC-relative data referencing > > ============================ > > > > The solution implemented in this patch set uses PC-relative data references. > > The trampoline is mapped in a code page. Adjacent to the code page, a data > > page is mapped that contains the parameters of the trampoline: > > > > - the closure pointer > > - pointer to the ABI handler to jump to > > > > The trampoline code uses an offset relative to its current PC to access its > > data. > > > > Some architectures support PC-relative data references in the ISA itself. > > E.g., X64 supports RIP-relative references. For others, the PC has to > > somehow be loaded into a general purpose register to do PC-relative data > > referencing. To do this, we need to define a get_pc() kind of function and > > call it to load the PC in a desired register. > > > > There are two cases: > > > > 1. The call instruction pushes the return address on the stack. > > > > In this case, get_pc() will extract the return address from the stack > > and load it in the desired register and return. > > > > 2. The call instruction stores the return address in a designated register. > > > > In this case, get_pc() will copy the return address to the desired > > register and return. > > > > Either way, the PC next to the call instruction is obtained. > > > > Scratch register > > ================ > > > > In order to do its job, the trampoline code would be required to use a > > scratch register. Depending on the ABI, there may not be a register > > available for scratch. This problem needs to be solved so that all ABIs > > will work. > > > > The trampoline will save two values on the stack: > > > > - the closure pointer > > - the original value of the scratch register > > > > This is what the stack will look like: > > > > sp before trampoline ------> -------------------- > > | closure pointer | > > -------------------- > > | scratch register | > > sp after trampoline -------> -------------------- > > > > The ABI handler can do the following as needed by the ABI: > > > > - the closure pointer can be loaded in a desired register > > > > - the scratch register can be restored to its original value > > > > - the stack pointer can be restored to its original value > > (when the trampoline was invoked) > > > > Thus the ABI handlers will have a couple of lines of code at the very > > beginning to do this so that all ABIs will work. > > > > NOTE: > > The documentation for this feature will contain information on: > > > > - the name of the scratch register for each architecture > > > > - the stack offsets at which the closure and the scratch register > > will be copied > > > > Trampoline Table > > ================ > > > > In order to reduce the trampoline memory footprint, the trampoline code > > would be defined as a code array in the text segment. This array would be > > mapped into the address space of the caller. The mapping would, therefore, > > contain a trampoline table. > > > > Adjacent to the trampoline table, there will be a data mapping that contains > > a parameter table, one parameter block for each trampoline. The parameter > > table will contain: > > > > - a pointer to the closure > > - a pointer to the ABI handler > > > > The trampoline code would finally look like this: > > > > - Make space on the stack for the closure and the scratch register > > by moving the stack pointer down > > - Store the original value of the scratch register on the stack > > - Using PC-relative reference, get the closure pointer > > - Store the closure pointer on the stack > > - Using PC-relative reference, get the ABI handler pointer > > - Jump to the ABI handler > > > > Trampoline API > > ============== > > > > There is a lot of dynamic code out there. They all have the same security > > issue. Dynamic code can be re-written into static code provided the data > > required by the static code can be passed to it just like we pass the > > closure pointer to an ABI handler. > > > > So, the same trampoline functions used by libffi internally need to be > > made available to the rest of the world in the form of an API. The > > following API has been defined in this solution: > > > > int ffi_tramp_is_supported(void); > > > > To support static trampolines, code needs to be added to each > > architecture. Also, the feature itself can be enabled via a > > configuration option. So, this function tells us if the feature > > is supported and enabled in the current libffi or not. > > > > void *ffi_tramp_alloc (int flags); > > > > Allocate a trampoline. Currently, flags are zero. An opaque > > trampoline structure pointer is returned. > > > > Internally, libffi manages trampoline tables and individual > > trampolines in each table. > > > > int ffi_tramp_set_parms (void *tramp, void *target, void *data); > > > > Initialize the parameters of a trampoline. That is, the target code > > that the trampoline should jump to and the data that needs to be > > passed to the target code. > > > > void *ffi_tramp_get_addr (void *tramp); > > > > Return the address of the trampoline to invoke the trampoline with. > > The trampoline can be invoked in one of two ways: > > > > - Simply branch to the trampoline address > > - Treat the trampoline address as a function pointer and > > call it. > > > > Which method is used depends on the target code. > > > > void ffi_tramp_free (void *tramp); > > > > Free a trampoline. > > > > Configuration > > ============= > > > > A new configuration option, --enable-static-tramp has been added to enable > > the use of static trampolines. > > > > Mapping size > > ============ > > > > The size of the code mapping that contains the trampoline table needs to be > > determined on a per architecture basis. If a particular architecture > > supports multiple base page sizes, then the largest base page size needs to > > be chosen. E.g., we choose 16K for ARM64. > > > > Trampoline allocation and free > > ============================== > > > > Static trampolines are allocated in ffi_closure_alloc() and freed in > > ffi_closure_free(). > > > > Normally, applications use these functions. But there are some cases out > > there where the user of libffi allocates and manages its own closure > > memory. In such cases, the static trampoline API cannot be used. These > > will fall back to using legacy trampolines. The user has to make sure > > that the memory is executable. > > > > ffi_closure structure > > ===================== > > > > I did not want to make any changes to the size of the closure structure for > > this feature to guarantee compatibility. But the opaque static trampoline > > handle needs to be stored in the closure. I have defined it as follows: > > > > - char tramp[FFI_TRAMPOLINE_SIZE]; > > + union { > > + char tramp[FFI_TRAMPOLINE_SIZE]; > > + void *ftramp; > > + }; > > > > If static trampolines are used, then tramp[] is not needed to store a > > dynamic trampoline. That space can be reused to store the handle. Hence, > > the union. > > > > Signed-off-by: Madhavan T. Venkataraman <madvenka@linux.microsoft.com <mailto:madvenka@linux.microsoft.com> <mailto:madvenka@linux.microsoft.com <mailto:madvenka@linux.microsoft.com>>> > > --- > > Makefile.am | 3 +- > > configure.ac <http://configure.ac> <http://configure.ac> | 7 + > > include/ffi.h.in <http://ffi.h.in> <http://ffi.h.in> | 13 +- > > include/ffi_common.h | 4 + > > libffi.map.in <http://libffi.map.in> <http://libffi.map.in> | 11 + > > src/closures.c | 54 +- > > src/tramp.c | 563 ++++++++++++++++++++ > > testsuite/libffi.closures/closure_loc_fn0.c | 3 + > > 8 files changed, 654 insertions(+), 4 deletions(-) > > create mode 100644 src/tramp.c > > > > diff --git a/Makefile.am b/Makefile.am > > index 7654bf5..1b18198 100644 > > --- a/Makefile.am > > +++ b/Makefile.am > > @@ -38,7 +38,8 @@ toolexeclib_LTLIBRARIES = libffi.la <http://libffi.la> <http://libffi.la> > > noinst_LTLIBRARIES = libffi_convenience.la <http://libffi_convenience.la> <http://libffi_convenience.la> > > > > libffi_la_SOURCES = src/prep_cif.c src/types.c \ > > - src/raw_api.c src/java_raw_api.c src/closures.c > > + src/raw_api.c src/java_raw_api.c src/closures.c \ > > + src/tramp.c > > > > if FFI_DEBUG > > libffi_la_SOURCES += src/debug.c > > diff --git a/configure.ac <http://configure.ac> <http://configure.ac> b/configure.ac <http://configure.ac> <http://configure.ac> > > index 790274e..898ede6 100644 > > --- a/configure.ac <http://configure.ac> <http://configure.ac> > > +++ b/configure.ac <http://configure.ac> <http://configure.ac> > > @@ -360,6 +360,13 @@ AC_ARG_ENABLE(raw-api, > > AC_DEFINE(FFI_NO_RAW_API, 1, [Define this if you do not want support for the raw API.]) > > fi) > > > > +AC_ARG_ENABLE(static-tramp, > > +[ --enable-static-tramp use statically defined trampolines], > > + if test "$enable_static_tramp" = "yes"; then > > + AC_DEFINE(FFI_EXEC_STATIC_TRAMP, 1, > > + [Define this if you want to use statically defined trampolines.]) > > + fi) > > + > > AC_ARG_ENABLE(purify-safety, > > [ --enable-purify-safety purify-safe mode], > > if test "$enable_purify_safety" = "yes"; then > > diff --git a/include/ffi.h.in <http://ffi.h.in> <http://ffi.h.in> b/include/ffi.h.in <http://ffi.h.in> <http://ffi.h.in> > > index 38885b0..c6a21d9 100644 > > --- a/include/ffi.h.in <http://ffi.h.in> <http://ffi.h.in> > > +++ b/include/ffi.h.in <http://ffi.h.in> <http://ffi.h.in> > > @@ -310,7 +310,10 @@ typedef struct { > > void *trampoline_table; > > void *trampoline_table_entry; > > #else > > - char tramp[FFI_TRAMPOLINE_SIZE]; > > + union { > > + char tramp[FFI_TRAMPOLINE_SIZE]; > > + void *ftramp; > > + }; > > #endif > > ffi_cif *cif; > > void (*fun)(ffi_cif*,void*,void**,void*); > > @@ -457,6 +460,14 @@ FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue, > > > > #endif /* FFI_GO_CLOSURES */ > > > > +/* ---- Static Trampoline Definitions -------------------------------------- */ > > + > > +FFI_API int ffi_tramp_is_supported(void); > > +FFI_API void *ffi_tramp_alloc (int flags); > > +FFI_API int ffi_tramp_set_parms (void *tramp, void *data, void *code); > > +FFI_API void *ffi_tramp_get_addr (void *tramp); > > +FFI_API void ffi_tramp_free (void *tramp); > > + > > /* ---- Public interface definition -------------------------------------- */ > > > > FFI_API > > diff --git a/include/ffi_common.h b/include/ffi_common.h > > index 76b9dd6..8743126 100644 > > --- a/include/ffi_common.h > > +++ b/include/ffi_common.h > > @@ -103,6 +103,10 @@ ffi_status ffi_prep_cif_core(ffi_cif *cif, > > some targets. */ > > void *ffi_data_to_code_pointer (void *data) FFI_HIDDEN; > > > > +/* The arch code calls this to set the code and data parameters for a > > + closure's static trampoline, if any. */ > > +int ffi_closure_tramp_set_parms (void *closure, void *code); > > + > > /* Extended cif, used in callback from assembly routine */ > > typedef struct > > { > > diff --git a/libffi.map.in <http://libffi.map.in> <http://libffi.map.in> b/libffi.map.in <http://libffi.map.in> <http://libffi.map.in> > > index de8778a..049c73e 100644 > > --- a/libffi.map.in <http://libffi.map.in> <http://libffi.map.in> > > +++ b/libffi.map.in <http://libffi.map.in> <http://libffi.map.in> > > @@ -74,3 +74,14 @@ LIBFFI_GO_CLOSURE_8.0 { > > ffi_prep_go_closure; > > } LIBFFI_CLOSURE_8.0; > > #endif > > + > > +#if FFI_EXEC_STATIC_TRAMP > > +LIBFFI_STATIC_TRAMP_8.0 { > > + global: > > + ffi_tramp_is_supported; > > + ffi_tramp_alloc; > > + ffi_tramp_set_parms; > > + ffi_tramp_get_addr; > > + ffi_tramp_free; > > +} LIBFFI_BASE_8.0; > > +#endif > > diff --git a/src/closures.c b/src/closures.c > > index 4fe6158..cf1d3de 100644 > > --- a/src/closures.c > > +++ b/src/closures.c > > @@ -109,6 +109,12 @@ ffi_closure_free (void *ptr) > > munmap(dataseg, rounded_size); > > munmap(codeseg, rounded_size); > > } > > + > > +int > > +ffi_closure_tramp_set_parms (void *ptr, void *code) > > +{ > > + return 0; > > +} > > #else /* !NetBSD with PROT_MPROTECT */ > > > > #if !FFI_MMAP_EXEC_WRIT && !FFI_EXEC_TRAMPOLINE_TABLE > > @@ -843,6 +849,12 @@ dlmmap (void *start, size_t length, int prot, > > && flags == (MAP_PRIVATE | MAP_ANONYMOUS) > > && fd == -1 && offset == 0); > > > > + if (execfd == -1 && ffi_tramp_is_supported ()) > > + { > > + ptr = mmap (start, length, prot & ~PROT_EXEC, flags, fd, offset); > > + return ptr; > > + } > > + > > if (execfd == -1 && is_emutramp_enabled ()) > > { > > ptr = mmap (start, length, prot & ~PROT_EXEC, flags, fd, offset); > > @@ -922,7 +934,7 @@ segment_holding_code (mstate m, char* addr) > > void * > > ffi_closure_alloc (size_t size, void **code) > > { > > - void *ptr; > > + void *ptr, *ftramp; > > > > if (!code) > > return NULL; > > @@ -934,6 +946,17 @@ ffi_closure_alloc (size_t size, void **code) > > msegmentptr seg = segment_holding (gm, ptr); > > > > *code = add_segment_exec_offset (ptr, seg); > > + if (!ffi_tramp_is_supported ()) > > + return ptr; > > + > > + ftramp = ffi_tramp_alloc (0); > > + if (ftramp == NULL) > > + { > > + dlfree (FFI_RESTORE_PTR (ptr)); > > + return NULL; > > + } > > + *code = ffi_tramp_get_addr (ftramp); > > + ((ffi_closure *) ptr)->ftramp = ftramp; > > } > > > > return ptr; > > @@ -943,12 +966,17 @@ void * > > ffi_data_to_code_pointer (void *data) > > { > > msegmentptr seg = segment_holding (gm, data); > > + > > /* We expect closures to be allocated with ffi_closure_alloc(), in > > which case seg will be non-NULL. However, some users take on the > > burden of managing this memory themselves, in which case this > > we'll just return data. */ > > if (seg) > > - return add_segment_exec_offset (data, seg); > > + { > > + if (!ffi_tramp_is_supported ()) > > + return add_segment_exec_offset (data, seg); > > + return ffi_tramp_get_addr (((ffi_closure *) data)->ftramp); > > + } > > else > > return data; > > } > > @@ -966,10 +994,26 @@ ffi_closure_free (void *ptr) > > if (seg) > > ptr = sub_segment_exec_offset (ptr, seg); > > #endif > > + if (ffi_tramp_is_supported ()) > > + ffi_tramp_free (((ffi_closure *) ptr)->ftramp); > > > > dlfree (FFI_RESTORE_PTR (ptr)); > > } > > > > +int > > +ffi_closure_tramp_set_parms (void *ptr, void *code) > > +{ > > + void *ftramp; > > + > > + msegmentptr seg = segment_holding (gm, ptr); > > + if (!seg || !ffi_tramp_is_supported()) > > + return 0; > > + > > + ftramp = ((ffi_closure *) ptr)->ftramp; > > + ffi_tramp_set_parms (ftramp, code, ptr); > > + return 1; > > +} > > + > > # else /* ! FFI_MMAP_EXEC_WRIT */ > > > > /* On many systems, memory returned by malloc is writable and > > @@ -998,6 +1042,12 @@ ffi_data_to_code_pointer (void *data) > > return data; > > } > > > > +int > > +ffi_closure_tramp_set_parms (void *ptr, void *code) > > +{ > > + return 0; > > +} > > + > > # endif /* ! FFI_MMAP_EXEC_WRIT */ > > #endif /* FFI_CLOSURES */ > > > > diff --git a/src/tramp.c b/src/tramp.c > > new file mode 100644 > > index 0000000..3170152 > > --- /dev/null > > +++ b/src/tramp.c > > @@ -0,0 +1,563 @@ > > +/* ----------------------------------------------------------------------- > > + tramp.c - Copyright (c) 2020 Madhavan T. Venkataraman > > + > > + API and support functions for managing statically defined closure > > + trampolines. > > + > > + Permission is hereby granted, free of charge, to any person obtaining > > + a copy of this software and associated documentation files (the > > + ``Software''), to deal in the Software without restriction, including > > + without limitation the rights to use, copy, modify, merge, publish, > > + distribute, sublicense, and/or sell copies of the Software, and to > > + permit persons to whom the Software is furnished to do so, subject to > > + the following conditions: > > + > > + The above copyright notice and this permission notice shall be included > > + in all copies or substantial portions of the Software. > > + > > + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, > > + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF > > + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND > > + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT > > + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, > > + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, > > + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER > > + DEALINGS IN THE SOFTWARE. > > + ----------------------------------------------------------------------- */ > > + > > +#include <stdio.h> > > +#include <unistd.h> > > +#include <stdlib.h> > > +#include <stdint.h> > > +#include <fcntl.h> > > +#include <pthread.h> > > +#include <sys/mman.h> > > +#include <linux/limits.h> > > +#include <linux/types.h> > > +#include <fficonfig.h> > > + > > +#if defined(FFI_EXEC_STATIC_TRAMP) > > + > > +#if !defined(__linux__) > > +#error "FFI_EXEC_STATIC_TRAMP is currently only supported on Linux" > > +#endif > > + > > +#if !defined _GNU_SOURCE > > +#define _GNU_SOURCE 1 > > +#endif > > + > > +/* > > + * Each architecture defines static code for a trampoline code table. The > > + * trampoline code table is mapped into the address space of a process. > > + * > > + * The following architecture specific function returns: > > + * > > + * - the address of the trampoline code table in the text segment > > + * - the size of each trampoline in the trampoline code table > > + * - the size of the mapping for the whole trampoline code table > > + */ > > +void __attribute__((weak)) *ffi_tramp_arch (size_t *tramp_size, > > + size_t *map_size); > > + > > +/* ------------------------- Trampoline Data Structures --------------------*/ > > + > > +static pthread_mutex_t tramp_lock = PTHREAD_MUTEX_INITIALIZER; > > + > > +struct tramp; > > + > > +/* > > + * Trampoline table. Manages one trampoline code table and one trampoline > > + * parameter table. > > + * > > + * prev, next Links in the global trampoline table list. > > + * code_table Trampoline code table mapping. > > + * parm_table Trampoline parameter table mapping. > > + * array Array of trampolines malloced. > > + * free List of free trampolines. > > + * nfree Number of free trampolines. > > + */ > > +struct tramp_table > > +{ > > + struct tramp_table *prev; > > + struct tramp_table *next; > > + void *code_table; > > + void *parm_table; > > + struct tramp *array; > > + struct tramp *free; > > + int nfree; > > +}; > > + > > +/* > > + * Parameters for each trampoline. > > + * > > + * data > > + * Data for the target code that the trampoline jumps to. > > + * target > > + * Target code that the trampoline jumps to. > > + */ > > +struct tramp_parm > > +{ > > + void *data; > > + void *target; > > +}; > > + > > +/* > > + * Trampoline structure for each trampoline. > > + * > > + * prev, next Links in the trampoline free list of a trampoline table. > > + * table Trampoline table to which this trampoline belongs. > > + * code Address of this trampoline in the code table mapping. > > + * parm Address of this trampoline's parameters in the parameter > > + * table mapping. > > + */ > > +struct tramp > > +{ > > + struct tramp *prev; > > + struct tramp *next; > > + struct tramp_table *table; > > + void *code; > > + struct tramp_parm *parm; > > +}; > > + > > +/* > > + * Trampoline globals. > > + * > > + * fd > > + * File descriptor of binary file that contains the trampoline code table. > > + * offset > > + * Offset of the trampoline code table in that file. > > + * map_size > > + * Size of the trampoline code table mapping. > > + * size > > + * Size of one trampoline in the trampoline code table. > > + * ntramp > > + * Total number of trampolines in the trampoline code table. > > + * tables > > + * List of trampoline tables that contain free trampolines. > > + * ntables > > + * Number of trampoline tables that contain free trampolines. > > + */ > > +struct tramp_global > > +{ > > + int fd; > > + off_t offset; > > + size_t map_size; > > + size_t size; > > + int ntramp; > > + struct tramp_table *tables; > > + int ntables; > > +}; > > + > > +static struct tramp_global gtramp = { -1 }; > > + > > +/* ------------------------ Trampoline Initialization ----------------------*/ > > + > > +static int ffi_tramp_get_fd_offset (void *tramp_text, off_t *offset); > > + > > +/* > > + * Initialize the static trampoline feature. > > + */ > > +static int > > +ffi_tramp_init (void) > > +{ > > + if (ffi_tramp_arch == NULL) > > + return 0; > > + > > + if (gtramp.fd == -1) > > + { > > + void *tramp_text; > > + > > + gtramp.tables = NULL; > > + gtramp.ntables = 0; > > + > > + /* > > + * Get trampoline code table information from the architecture. > > + */ > > + tramp_text = ffi_tramp_arch (>ramp.size, >ramp.map_size); > > + gtramp.ntramp = gtramp.map_size / gtramp.size; > > + > > + /* > > + * Get the binary file that contains the trampoline code table and also > > + * the offset of the table within the file. These are used to mmap() > > + * the trampoline code table. > > + */ > > + gtramp.fd = ffi_tramp_get_fd_offset (tramp_text, >ramp.offset); > > + } > > + return gtramp.fd != -1; > > +} > > + > > +/* > > + * From the address of the trampoline code table in the text segment, find the > > + * binary file and offset of the trampoline code table from /proc/<pid>/maps. > > + */ > > +static int > > +ffi_tramp_get_fd_offset (void *tramp_text, off_t *offset) > > +{ > > + FILE *fp; > > + char file[PATH_MAX], line[PATH_MAX+100], perm[10], dev[10]; > > + unsigned long start, end, inode; > > + uintptr_t addr = (uintptr_t) tramp_text; > > + int nfields, found; > > + > > + snprintf (file, PATH_MAX, "/proc/%d/maps", getpid()); > > + fp = fopen (file, "r"); > > + if (fp == NULL) > > + return -1; > > + > > + found = 0; > > + while (feof (fp) == 0) { > > + if (fgets (line, sizeof (line), fp) == 0) > > + break; > > + > > + nfields = sscanf (line, "%lx-%lx %s %lx %s %ld %s", > > + &start, &end, perm, offset, dev, &inode, file); > > + if (nfields != 7) > > + continue; > > + > > + if (addr >= start && addr < end) { > > + *offset += (addr - start); > > + found = 1; > > + break; > > + } > > + } > > + fclose (fp); > > + > > + if (!found) > > + return -1; > > + > > + return open (file, O_RDONLY); > > +} > > + > > +/* ---------------------- Trampoline Table functions ---------------------- */ > > + > > +static int tramp_table_map (char **code_table, char **parm_table); > > +static void tramp_add (struct tramp *tramp); > > + > > +/* > > + * Allocate and initialize a trampoline table. > > + */ > > +static int > > +tramp_table_alloc (void) > > +{ > > + char *code_table, *parm_table; > > + struct tramp_table *table; > > + struct tramp *tramp_array, *tramp; > > + size_t size; > > + char *code, *parm; > > + int i; > > + > > + /* > > + * If we already have tables with free trampolines, there is no need to > > + * allocate a new table. > > + */ > > + if (gtramp.ntables > 0) > > + return 1; > > + > > + /* > > + * Allocate a new trampoline table structure. > > + */ > > + table = malloc (sizeof (*table)); > > + if (table == NULL) > > + return 0; > > + > > + /* > > + * Allocate new trampoline structures. > > + */ > > + tramp_array = malloc (sizeof (*tramp) * gtramp.ntramp); > > + if (tramp_array == NULL) > > + goto free_table; > > + > > + /* > > + * Map a code table and a parameter table into the caller's address space. > > + */ > > + if (!tramp_table_map (&code_table, &parm_table)) > > + goto free_tramp_array; > > + > > + /* > > + * Initialize the trampoline table. > > + */ > > + table->code_table = code_table; > > + table->parm_table = parm_table; > > + table->array = tramp_array; > > + table->free = NULL; > > + table->nfree = 0; > > + > > + /* > > + * Populate the trampoline table free list. This will also add the trampoline > > + * table to the global list of trampoline tables. > > + */ > > + size = gtramp.size; > > + code = code_table; > > + parm = parm_table; > > + for (i = 0; i < gtramp.ntramp; i++) > > + { > > + tramp = &tramp_array[i]; > > + tramp->table = table; > > + tramp->code = code; > > + tramp->parm = (struct tramp_parm *) parm; > > + tramp_add (tramp); > > + > > + code += size; > > + parm += size; > > + } > > + return 1; > > + > > +free_tramp_array: > > + free (tramp_array); > > +free_table: > > + free (table); > > + return 0; > > +} > > + > > +/* > > + * Create a trampoline code table mapping and a trampoline parameter table > > + * mapping. The two mappings must be adjacent to each other for PC-relative > > + * access. > > + * > > + * For each trampoline in the code table, there is a corresponding parameter > > + * block in the parameter table. The size of the parameter block is the same > > + * as the size of the trampoline. This means that the parameter block is at > > + * a fixed offset from its trampoline making it easy for a trampoline to find > > + * its parameters using PC-relative access. > > + * > > + * The parameter block will contain a struct tramp_parm. This means that > > + * sizeof (struct tramp_parm) cannot exceed the size of a parameter block. > > + */ > > +static int > > +tramp_table_map (char **code_table, char **parm_table) > > +{ > > + char *addr; > > + > > + /* > > + * Create an anonymous mapping twice the map size. The top half will be used > > + * for the code table. The bottom half will be used for the parameter table. > > + */ > > + addr = mmap (NULL, gtramp.map_size * 2, PROT_READ | PROT_WRITE, > > + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); > > + if (addr == MAP_FAILED) > > + return 0; > > + > > + /* > > + * Replace the top half of the anonymous mapping with the code table mapping. > > + */ > > + *code_table = mmap (addr, gtramp.map_size, PROT_READ | PROT_EXEC, > > + MAP_PRIVATE | MAP_FIXED, gtramp.fd, gtramp.offset); > > + if (*code_table == MAP_FAILED) > > + { > > + (void) munmap (addr, gtramp.map_size * 2); > > + return 0; > > + } > > + *parm_table = *code_table + gtramp.map_size; > > + return 1; > > +} > > + > > +/* > > + * Free a trampoline table. > > + */ > > +static void > > +tramp_table_free (struct tramp_table *table) > > +{ > > + (void) munmap (table->code_table, gtramp.map_size); > > + (void) munmap (table->parm_table, gtramp.map_size); > > + free (table->array); > > + free (table); > > +} > > + > > +/* > > + * Add a new trampoline table to the global table list. > > + */ > > +static void > > +tramp_table_add (struct tramp_table *table) > > +{ > > + table->next = gtramp.tables; > > + table->prev = NULL; > > + if (gtramp.tables != NULL) > > + gtramp.tables->prev = table; > > + gtramp.tables = table; > > + gtramp.ntables++; > > +} > > + > > +/* > > + * Delete a trampoline table from the global table list. > > + */ > > +static void > > +tramp_table_del (struct tramp_table *table) > > +{ > > + gtramp.ntables--; > > + if (table->prev != NULL) > > + table->prev->next = table->next; > > + if (table->next != NULL) > > + table->next->prev = table->prev; > > + if (gtramp.tables == table) > > + gtramp.tables = table->next; > > +} > > + > > +/* ------------------------- Trampoline functions ------------------------- */ > > + > > +/* > > + * Add a trampoline to its trampoline table. > > + */ > > +static void > > +tramp_add (struct tramp *tramp) > > +{ > > + struct tramp_table *table = tramp->table; > > + > > + tramp->next = table->free; > > + tramp->prev = NULL; > > + if (table->free != NULL) > > + table->free->prev = tramp; > > + table->free = tramp; > > + table->nfree++; > > + > > + if (table->nfree == 1) > > + tramp_table_add (table); > > + > > + /* > > + * We don't want to keep too many free trampoline tables lying around. > > + */ > > + if (table->nfree == gtramp.ntramp && gtramp.ntables > 1) > > + { > > + tramp_table_del (table); > > + tramp_table_free (table); > > + } > > +} > > + > > +/* > > + * Remove a trampoline from its trampoline table. > > + */ > > +static void > > +tramp_del (struct tramp *tramp) > > +{ > > + struct tramp_table *table = tramp->table; > > + > > + table->nfree--; > > + if (tramp->prev != NULL) > > + tramp->prev->next = tramp->next; > > + if (tramp->next != NULL) > > + tramp->next->prev = tramp->prev; > > + if (table->free == tramp) > > + table->free = tramp->next; > > + > > + if (table->nfree == 0) > > + tramp_table_del (table); > > +} > > + > > +/* ------------------------ Trampoline API functions ------------------------ */ > > + > > +int > > +ffi_tramp_is_supported(void) > > +{ > > + int ret; > > + > > + pthread_mutex_lock (&tramp_lock); > > + ret = ffi_tramp_init (); > > + pthread_mutex_unlock (&tramp_lock); > > + return ret; > > +} > > + > > +/* > > + * Allocate a trampoline and return its opaque address. > > + */ > > +void * > > +ffi_tramp_alloc (int flags) > > +{ > > + struct tramp *tramp; > > + > > + pthread_mutex_lock (&tramp_lock); > > + > > + if (!ffi_tramp_init () || flags != 0) > > + { > > + pthread_mutex_unlock (&tramp_lock); > > + return NULL; > > + } > > + > > + if (!tramp_table_alloc ()) > > + { > > + pthread_mutex_unlock (&tramp_lock); > > + return NULL; > > + } > > + > > + tramp = gtramp.tables->free; > > + tramp_del (tramp); > > + > > + pthread_mutex_unlock (&tramp_lock); > > + > > + return tramp; > > +} > > + > > +/* > > + * Set the parameters for a trampoline. > > + */ > > +void > > +ffi_tramp_set_parms (void *arg, void *target, void *data) > > +{ > > + struct tramp *tramp = arg; > > + > > + pthread_mutex_lock (&tramp_lock); > > + tramp->parm->target = target; > > + tramp->parm->data = data; > > + pthread_mutex_unlock (&tramp_lock); > > +} > > + > > +/* > > + * Get the invocation address of a trampoline. > > + */ > > +void * > > +ffi_tramp_get_addr (void *arg) > > +{ > > + struct tramp *tramp = arg; > > + void *addr; > > + > > + pthread_mutex_lock (&tramp_lock); > > + addr = tramp->code; > > + pthread_mutex_unlock (&tramp_lock); > > + > > + return addr; > > +} > > + > > +/* > > + * Free a trampoline. > > + */ > > +void > > +ffi_tramp_free (void *arg) > > +{ > > + struct tramp *tramp = arg; > > + > > + pthread_mutex_lock (&tramp_lock); > > + tramp_add (tramp); > > + pthread_mutex_unlock (&tramp_lock); > > +} > > + > > +/* ------------------------------------------------------------------------- */ > > + > > +#else /* !FFI_EXEC_STATIC_TRAMP */ > > + > > +int > > +ffi_tramp_is_supported(void) > > +{ > > + return 0; > > +} > > + > > +void * > > +ffi_tramp_alloc (int flags) > > +{ > > + return NULL; > > +} > > + > > +void > > +ffi_tramp_set_parms (void *arg, void *target, void *data) > > +{ > > +} > > + > > +void * > > +ffi_tramp_get_addr (void *arg) > > +{ > > + return NULL; > > +} > > + > > +void > > +ffi_tramp_free (void *arg) > > +{ > > +} > > + > > +#endif /* FFI_EXEC_STATIC_TRAMP */ > > diff --git a/testsuite/libffi.closures/closure_loc_fn0.c b/testsuite/libffi.closures/closure_loc_fn0.c > > index b3afa0b..ad488ac 100644 > > --- a/testsuite/libffi.closures/closure_loc_fn0.c > > +++ b/testsuite/libffi.closures/closure_loc_fn0.c > > @@ -83,7 +83,10 @@ int main (void) > > CHECK(ffi_prep_closure_loc(pcl, &cif, closure_loc_test_fn0, > > (void *) 3 /* userdata */, codeloc) == FFI_OK); > > > > +#ifndef FFI_EXEC_STATIC_TRAMP > > + /* With static trampolines, the codeloc does not point to closure */ > > CHECK(memcmp(pcl, codeloc, sizeof(*pcl)) == 0); > > +#endif > > > > res = (*((closure_loc_test_type0)codeloc)) > > (1LL, 2, 3LL, 4, 127, 429LL, 7, 8, 9.5, 10, 11, 12, 13, > > -- > > 2.25.1 > > > ^ permalink raw reply [flat|nested] 12+ messages in thread
* Re: [RFC PATCH v1 1/4] Static Trampolines 2020-12-02 21:33 ` Madhavan T. Venkataraman @ 2020-12-03 18:45 ` Madhavan T. Venkataraman 2020-12-05 2:38 ` [RFC PATCH v1 1/4] Static Trampolines - Quick question Madhavan T. Venkataraman 0 siblings, 1 reply; 12+ messages in thread From: Madhavan T. Venkataraman @ 2020-12-03 18:45 UTC (permalink / raw) To: Anthony Green; +Cc: libffi-discuss, fw I am fixing the build issues. I have also discovered a compatibility issue for which I need to rework the code a little bit that is executed at the beginning of the ABI handlers for static trampolines and make it cleaner. I will make all these changes, retest and send out version 2. I will include a description of all changes in v2. Thanks. Madhavan On 12/2/20 3:33 PM, Madhavan T. Venkataraman wrote: > Thanks, Anthony. > > Madhavan > > On 12/2/20 12:14 PM, Anthony Green wrote: >> Thanks, Madhavan. It seems that the travis-ci testing is stalled -- perhaps because they just changed their policies around free usage. I've reached out to them for help. It's possible we could move some of the load to GitHub Actions, but as far as I know, travis-ci is the only platform with s390 (and perhaps other) support. >> >> AG >> >> >> On Wed, Dec 2, 2020 at 11:49 AM Madhavan T. Venkataraman <madvenka@linux.microsoft.com <mailto:madvenka@linux.microsoft.com>> wrote: >> >> >> >> On 11/24/20 1:49 PM, Anthony Green wrote: >> > Thank you for your submission, Madhavan. This will be interesting reading! >> > >> > In the meantime, it would be helpful if you submitted this as a PR on GitHub. This will trigger CI testing for over 20 different systems so we can have an initial look at any build/test problems. >> > >> >> Just submitted the PR: >> >> https://github.com/libffi/libffi/pull/603 >> >> Thanks. >> >> Madhavan >> >> > AG >> > >> > On Tue, Nov 24, 2020 at 2:32 PM madvenka--- via Libffi-discuss <libffi-discuss@sourceware.org <mailto:libffi-discuss@sourceware.org> <mailto:libffi-discuss@sourceware.org <mailto:libffi-discuss@sourceware.org>>> wrote: >> > >> > From: "Madhavan T. Venkataraman" <madvenka@linux.microsoft.com <mailto:madvenka@linux.microsoft.com> <mailto:madvenka@linux.microsoft.com <mailto:madvenka@linux.microsoft.com>>> >> > >> > Closure Trampoline Security Issue >> > ================================= >> > >> > Currently, the trampoline code used in libffi is not statically defined in >> > a source file (except for MACH). The trampoline is either pre-defined >> > machine code in a data buffer. Or, it is generated at runtime. In order to >> > execute a trampoline, it needs to be placed in a page with executable >> > permissions. >> > >> > Executable data pages are attack surfaces for attackers who may try to >> > inject their own code into the page and contrive to have it executed. The >> > security settings in a system may prevent various tricks used in user land >> > to write code into a page and to have it executed somehow. On such systems, >> > libffi trampolines would not be able to run. >> > >> > Static Trampoline >> > ================= >> > >> > To solve this problem, the trampoline code needs to be defined statically >> > in a source file, compiled and placed in the text segment so it can be >> > mapped and executed naturally without any tricks. However, the trampoline >> > needs to be able to access the closure pointer at runtime. >> > >> > PC-relative data referencing >> > ============================ >> > >> > The solution implemented in this patch set uses PC-relative data references. >> > The trampoline is mapped in a code page. Adjacent to the code page, a data >> > page is mapped that contains the parameters of the trampoline: >> > >> > - the closure pointer >> > - pointer to the ABI handler to jump to >> > >> > The trampoline code uses an offset relative to its current PC to access its >> > data. >> > >> > Some architectures support PC-relative data references in the ISA itself. >> > E.g., X64 supports RIP-relative references. For others, the PC has to >> > somehow be loaded into a general purpose register to do PC-relative data >> > referencing. To do this, we need to define a get_pc() kind of function and >> > call it to load the PC in a desired register. >> > >> > There are two cases: >> > >> > 1. The call instruction pushes the return address on the stack. >> > >> > In this case, get_pc() will extract the return address from the stack >> > and load it in the desired register and return. >> > >> > 2. The call instruction stores the return address in a designated register. >> > >> > In this case, get_pc() will copy the return address to the desired >> > register and return. >> > >> > Either way, the PC next to the call instruction is obtained. >> > >> > Scratch register >> > ================ >> > >> > In order to do its job, the trampoline code would be required to use a >> > scratch register. Depending on the ABI, there may not be a register >> > available for scratch. This problem needs to be solved so that all ABIs >> > will work. >> > >> > The trampoline will save two values on the stack: >> > >> > - the closure pointer >> > - the original value of the scratch register >> > >> > This is what the stack will look like: >> > >> > sp before trampoline ------> -------------------- >> > | closure pointer | >> > -------------------- >> > | scratch register | >> > sp after trampoline -------> -------------------- >> > >> > The ABI handler can do the following as needed by the ABI: >> > >> > - the closure pointer can be loaded in a desired register >> > >> > - the scratch register can be restored to its original value >> > >> > - the stack pointer can be restored to its original value >> > (when the trampoline was invoked) >> > >> > Thus the ABI handlers will have a couple of lines of code at the very >> > beginning to do this so that all ABIs will work. >> > >> > NOTE: >> > The documentation for this feature will contain information on: >> > >> > - the name of the scratch register for each architecture >> > >> > - the stack offsets at which the closure and the scratch register >> > will be copied >> > >> > Trampoline Table >> > ================ >> > >> > In order to reduce the trampoline memory footprint, the trampoline code >> > would be defined as a code array in the text segment. This array would be >> > mapped into the address space of the caller. The mapping would, therefore, >> > contain a trampoline table. >> > >> > Adjacent to the trampoline table, there will be a data mapping that contains >> > a parameter table, one parameter block for each trampoline. The parameter >> > table will contain: >> > >> > - a pointer to the closure >> > - a pointer to the ABI handler >> > >> > The trampoline code would finally look like this: >> > >> > - Make space on the stack for the closure and the scratch register >> > by moving the stack pointer down >> > - Store the original value of the scratch register on the stack >> > - Using PC-relative reference, get the closure pointer >> > - Store the closure pointer on the stack >> > - Using PC-relative reference, get the ABI handler pointer >> > - Jump to the ABI handler >> > >> > Trampoline API >> > ============== >> > >> > There is a lot of dynamic code out there. They all have the same security >> > issue. Dynamic code can be re-written into static code provided the data >> > required by the static code can be passed to it just like we pass the >> > closure pointer to an ABI handler. >> > >> > So, the same trampoline functions used by libffi internally need to be >> > made available to the rest of the world in the form of an API. The >> > following API has been defined in this solution: >> > >> > int ffi_tramp_is_supported(void); >> > >> > To support static trampolines, code needs to be added to each >> > architecture. Also, the feature itself can be enabled via a >> > configuration option. So, this function tells us if the feature >> > is supported and enabled in the current libffi or not. >> > >> > void *ffi_tramp_alloc (int flags); >> > >> > Allocate a trampoline. Currently, flags are zero. An opaque >> > trampoline structure pointer is returned. >> > >> > Internally, libffi manages trampoline tables and individual >> > trampolines in each table. >> > >> > int ffi_tramp_set_parms (void *tramp, void *target, void *data); >> > >> > Initialize the parameters of a trampoline. That is, the target code >> > that the trampoline should jump to and the data that needs to be >> > passed to the target code. >> > >> > void *ffi_tramp_get_addr (void *tramp); >> > >> > Return the address of the trampoline to invoke the trampoline with. >> > The trampoline can be invoked in one of two ways: >> > >> > - Simply branch to the trampoline address >> > - Treat the trampoline address as a function pointer and >> > call it. >> > >> > Which method is used depends on the target code. >> > >> > void ffi_tramp_free (void *tramp); >> > >> > Free a trampoline. >> > >> > Configuration >> > ============= >> > >> > A new configuration option, --enable-static-tramp has been added to enable >> > the use of static trampolines. >> > >> > Mapping size >> > ============ >> > >> > The size of the code mapping that contains the trampoline table needs to be >> > determined on a per architecture basis. If a particular architecture >> > supports multiple base page sizes, then the largest base page size needs to >> > be chosen. E.g., we choose 16K for ARM64. >> > >> > Trampoline allocation and free >> > ============================== >> > >> > Static trampolines are allocated in ffi_closure_alloc() and freed in >> > ffi_closure_free(). >> > >> > Normally, applications use these functions. But there are some cases out >> > there where the user of libffi allocates and manages its own closure >> > memory. In such cases, the static trampoline API cannot be used. These >> > will fall back to using legacy trampolines. The user has to make sure >> > that the memory is executable. >> > >> > ffi_closure structure >> > ===================== >> > >> > I did not want to make any changes to the size of the closure structure for >> > this feature to guarantee compatibility. But the opaque static trampoline >> > handle needs to be stored in the closure. I have defined it as follows: >> > >> > - char tramp[FFI_TRAMPOLINE_SIZE]; >> > + union { >> > + char tramp[FFI_TRAMPOLINE_SIZE]; >> > + void *ftramp; >> > + }; >> > >> > If static trampolines are used, then tramp[] is not needed to store a >> > dynamic trampoline. That space can be reused to store the handle. Hence, >> > the union. >> > >> > Signed-off-by: Madhavan T. Venkataraman <madvenka@linux.microsoft.com <mailto:madvenka@linux.microsoft.com> <mailto:madvenka@linux.microsoft.com <mailto:madvenka@linux.microsoft.com>>> >> > --- >> > Makefile.am | 3 +- >> > configure.ac <http://configure.ac> <http://configure.ac> | 7 + >> > include/ffi.h.in <http://ffi.h.in> <http://ffi.h.in> | 13 +- >> > include/ffi_common.h | 4 + >> > libffi.map.in <http://libffi.map.in> <http://libffi.map.in> | 11 + >> > src/closures.c | 54 +- >> > src/tramp.c | 563 ++++++++++++++++++++ >> > testsuite/libffi.closures/closure_loc_fn0.c | 3 + >> > 8 files changed, 654 insertions(+), 4 deletions(-) >> > create mode 100644 src/tramp.c >> > >> > diff --git a/Makefile.am b/Makefile.am >> > index 7654bf5..1b18198 100644 >> > --- a/Makefile.am >> > +++ b/Makefile.am >> > @@ -38,7 +38,8 @@ toolexeclib_LTLIBRARIES = libffi.la <http://libffi.la> <http://libffi.la> >> > noinst_LTLIBRARIES = libffi_convenience.la <http://libffi_convenience.la> <http://libffi_convenience.la> >> > >> > libffi_la_SOURCES = src/prep_cif.c src/types.c \ >> > - src/raw_api.c src/java_raw_api.c src/closures.c >> > + src/raw_api.c src/java_raw_api.c src/closures.c \ >> > + src/tramp.c >> > >> > if FFI_DEBUG >> > libffi_la_SOURCES += src/debug.c >> > diff --git a/configure.ac <http://configure.ac> <http://configure.ac> b/configure.ac <http://configure.ac> <http://configure.ac> >> > index 790274e..898ede6 100644 >> > --- a/configure.ac <http://configure.ac> <http://configure.ac> >> > +++ b/configure.ac <http://configure.ac> <http://configure.ac> >> > @@ -360,6 +360,13 @@ AC_ARG_ENABLE(raw-api, >> > AC_DEFINE(FFI_NO_RAW_API, 1, [Define this if you do not want support for the raw API.]) >> > fi) >> > >> > +AC_ARG_ENABLE(static-tramp, >> > +[ --enable-static-tramp use statically defined trampolines], >> > + if test "$enable_static_tramp" = "yes"; then >> > + AC_DEFINE(FFI_EXEC_STATIC_TRAMP, 1, >> > + [Define this if you want to use statically defined trampolines.]) >> > + fi) >> > + >> > AC_ARG_ENABLE(purify-safety, >> > [ --enable-purify-safety purify-safe mode], >> > if test "$enable_purify_safety" = "yes"; then >> > diff --git a/include/ffi.h.in <http://ffi.h.in> <http://ffi.h.in> b/include/ffi.h.in <http://ffi.h.in> <http://ffi.h.in> >> > index 38885b0..c6a21d9 100644 >> > --- a/include/ffi.h.in <http://ffi.h.in> <http://ffi.h.in> >> > +++ b/include/ffi.h.in <http://ffi.h.in> <http://ffi.h.in> >> > @@ -310,7 +310,10 @@ typedef struct { >> > void *trampoline_table; >> > void *trampoline_table_entry; >> > #else >> > - char tramp[FFI_TRAMPOLINE_SIZE]; >> > + union { >> > + char tramp[FFI_TRAMPOLINE_SIZE]; >> > + void *ftramp; >> > + }; >> > #endif >> > ffi_cif *cif; >> > void (*fun)(ffi_cif*,void*,void**,void*); >> > @@ -457,6 +460,14 @@ FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue, >> > >> > #endif /* FFI_GO_CLOSURES */ >> > >> > +/* ---- Static Trampoline Definitions -------------------------------------- */ >> > + >> > +FFI_API int ffi_tramp_is_supported(void); >> > +FFI_API void *ffi_tramp_alloc (int flags); >> > +FFI_API int ffi_tramp_set_parms (void *tramp, void *data, void *code); >> > +FFI_API void *ffi_tramp_get_addr (void *tramp); >> > +FFI_API void ffi_tramp_free (void *tramp); >> > + >> > /* ---- Public interface definition -------------------------------------- */ >> > >> > FFI_API >> > diff --git a/include/ffi_common.h b/include/ffi_common.h >> > index 76b9dd6..8743126 100644 >> > --- a/include/ffi_common.h >> > +++ b/include/ffi_common.h >> > @@ -103,6 +103,10 @@ ffi_status ffi_prep_cif_core(ffi_cif *cif, >> > some targets. */ >> > void *ffi_data_to_code_pointer (void *data) FFI_HIDDEN; >> > >> > +/* The arch code calls this to set the code and data parameters for a >> > + closure's static trampoline, if any. */ >> > +int ffi_closure_tramp_set_parms (void *closure, void *code); >> > + >> > /* Extended cif, used in callback from assembly routine */ >> > typedef struct >> > { >> > diff --git a/libffi.map.in <http://libffi.map.in> <http://libffi.map.in> b/libffi.map.in <http://libffi.map.in> <http://libffi.map.in> >> > index de8778a..049c73e 100644 >> > --- a/libffi.map.in <http://libffi.map.in> <http://libffi.map.in> >> > +++ b/libffi.map.in <http://libffi.map.in> <http://libffi.map.in> >> > @@ -74,3 +74,14 @@ LIBFFI_GO_CLOSURE_8.0 { >> > ffi_prep_go_closure; >> > } LIBFFI_CLOSURE_8.0; >> > #endif >> > + >> > +#if FFI_EXEC_STATIC_TRAMP >> > +LIBFFI_STATIC_TRAMP_8.0 { >> > + global: >> > + ffi_tramp_is_supported; >> > + ffi_tramp_alloc; >> > + ffi_tramp_set_parms; >> > + ffi_tramp_get_addr; >> > + ffi_tramp_free; >> > +} LIBFFI_BASE_8.0; >> > +#endif >> > diff --git a/src/closures.c b/src/closures.c >> > index 4fe6158..cf1d3de 100644 >> > --- a/src/closures.c >> > +++ b/src/closures.c >> > @@ -109,6 +109,12 @@ ffi_closure_free (void *ptr) >> > munmap(dataseg, rounded_size); >> > munmap(codeseg, rounded_size); >> > } >> > + >> > +int >> > +ffi_closure_tramp_set_parms (void *ptr, void *code) >> > +{ >> > + return 0; >> > +} >> > #else /* !NetBSD with PROT_MPROTECT */ >> > >> > #if !FFI_MMAP_EXEC_WRIT && !FFI_EXEC_TRAMPOLINE_TABLE >> > @@ -843,6 +849,12 @@ dlmmap (void *start, size_t length, int prot, >> > && flags == (MAP_PRIVATE | MAP_ANONYMOUS) >> > && fd == -1 && offset == 0); >> > >> > + if (execfd == -1 && ffi_tramp_is_supported ()) >> > + { >> > + ptr = mmap (start, length, prot & ~PROT_EXEC, flags, fd, offset); >> > + return ptr; >> > + } >> > + >> > if (execfd == -1 && is_emutramp_enabled ()) >> > { >> > ptr = mmap (start, length, prot & ~PROT_EXEC, flags, fd, offset); >> > @@ -922,7 +934,7 @@ segment_holding_code (mstate m, char* addr) >> > void * >> > ffi_closure_alloc (size_t size, void **code) >> > { >> > - void *ptr; >> > + void *ptr, *ftramp; >> > >> > if (!code) >> > return NULL; >> > @@ -934,6 +946,17 @@ ffi_closure_alloc (size_t size, void **code) >> > msegmentptr seg = segment_holding (gm, ptr); >> > >> > *code = add_segment_exec_offset (ptr, seg); >> > + if (!ffi_tramp_is_supported ()) >> > + return ptr; >> > + >> > + ftramp = ffi_tramp_alloc (0); >> > + if (ftramp == NULL) >> > + { >> > + dlfree (FFI_RESTORE_PTR (ptr)); >> > + return NULL; >> > + } >> > + *code = ffi_tramp_get_addr (ftramp); >> > + ((ffi_closure *) ptr)->ftramp = ftramp; >> > } >> > >> > return ptr; >> > @@ -943,12 +966,17 @@ void * >> > ffi_data_to_code_pointer (void *data) >> > { >> > msegmentptr seg = segment_holding (gm, data); >> > + >> > /* We expect closures to be allocated with ffi_closure_alloc(), in >> > which case seg will be non-NULL. However, some users take on the >> > burden of managing this memory themselves, in which case this >> > we'll just return data. */ >> > if (seg) >> > - return add_segment_exec_offset (data, seg); >> > + { >> > + if (!ffi_tramp_is_supported ()) >> > + return add_segment_exec_offset (data, seg); >> > + return ffi_tramp_get_addr (((ffi_closure *) data)->ftramp); >> > + } >> > else >> > return data; >> > } >> > @@ -966,10 +994,26 @@ ffi_closure_free (void *ptr) >> > if (seg) >> > ptr = sub_segment_exec_offset (ptr, seg); >> > #endif >> > + if (ffi_tramp_is_supported ()) >> > + ffi_tramp_free (((ffi_closure *) ptr)->ftramp); >> > >> > dlfree (FFI_RESTORE_PTR (ptr)); >> > } >> > >> > +int >> > +ffi_closure_tramp_set_parms (void *ptr, void *code) >> > +{ >> > + void *ftramp; >> > + >> > + msegmentptr seg = segment_holding (gm, ptr); >> > + if (!seg || !ffi_tramp_is_supported()) >> > + return 0; >> > + >> > + ftramp = ((ffi_closure *) ptr)->ftramp; >> > + ffi_tramp_set_parms (ftramp, code, ptr); >> > + return 1; >> > +} >> > + >> > # else /* ! FFI_MMAP_EXEC_WRIT */ >> > >> > /* On many systems, memory returned by malloc is writable and >> > @@ -998,6 +1042,12 @@ ffi_data_to_code_pointer (void *data) >> > return data; >> > } >> > >> > +int >> > +ffi_closure_tramp_set_parms (void *ptr, void *code) >> > +{ >> > + return 0; >> > +} >> > + >> > # endif /* ! FFI_MMAP_EXEC_WRIT */ >> > #endif /* FFI_CLOSURES */ >> > >> > diff --git a/src/tramp.c b/src/tramp.c >> > new file mode 100644 >> > index 0000000..3170152 >> > --- /dev/null >> > +++ b/src/tramp.c >> > @@ -0,0 +1,563 @@ >> > +/* ----------------------------------------------------------------------- >> > + tramp.c - Copyright (c) 2020 Madhavan T. Venkataraman >> > + >> > + API and support functions for managing statically defined closure >> > + trampolines. >> > + >> > + Permission is hereby granted, free of charge, to any person obtaining >> > + a copy of this software and associated documentation files (the >> > + ``Software''), to deal in the Software without restriction, including >> > + without limitation the rights to use, copy, modify, merge, publish, >> > + distribute, sublicense, and/or sell copies of the Software, and to >> > + permit persons to whom the Software is furnished to do so, subject to >> > + the following conditions: >> > + >> > + The above copyright notice and this permission notice shall be included >> > + in all copies or substantial portions of the Software. >> > + >> > + THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, >> > + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF >> > + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND >> > + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT >> > + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, >> > + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, >> > + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER >> > + DEALINGS IN THE SOFTWARE. >> > + ----------------------------------------------------------------------- */ >> > + >> > +#include <stdio.h> >> > +#include <unistd.h> >> > +#include <stdlib.h> >> > +#include <stdint.h> >> > +#include <fcntl.h> >> > +#include <pthread.h> >> > +#include <sys/mman.h> >> > +#include <linux/limits.h> >> > +#include <linux/types.h> >> > +#include <fficonfig.h> >> > + >> > +#if defined(FFI_EXEC_STATIC_TRAMP) >> > + >> > +#if !defined(__linux__) >> > +#error "FFI_EXEC_STATIC_TRAMP is currently only supported on Linux" >> > +#endif >> > + >> > +#if !defined _GNU_SOURCE >> > +#define _GNU_SOURCE 1 >> > +#endif >> > + >> > +/* >> > + * Each architecture defines static code for a trampoline code table. The >> > + * trampoline code table is mapped into the address space of a process. >> > + * >> > + * The following architecture specific function returns: >> > + * >> > + * - the address of the trampoline code table in the text segment >> > + * - the size of each trampoline in the trampoline code table >> > + * - the size of the mapping for the whole trampoline code table >> > + */ >> > +void __attribute__((weak)) *ffi_tramp_arch (size_t *tramp_size, >> > + size_t *map_size); >> > + >> > +/* ------------------------- Trampoline Data Structures --------------------*/ >> > + >> > +static pthread_mutex_t tramp_lock = PTHREAD_MUTEX_INITIALIZER; >> > + >> > +struct tramp; >> > + >> > +/* >> > + * Trampoline table. Manages one trampoline code table and one trampoline >> > + * parameter table. >> > + * >> > + * prev, next Links in the global trampoline table list. >> > + * code_table Trampoline code table mapping. >> > + * parm_table Trampoline parameter table mapping. >> > + * array Array of trampolines malloced. >> > + * free List of free trampolines. >> > + * nfree Number of free trampolines. >> > + */ >> > +struct tramp_table >> > +{ >> > + struct tramp_table *prev; >> > + struct tramp_table *next; >> > + void *code_table; >> > + void *parm_table; >> > + struct tramp *array; >> > + struct tramp *free; >> > + int nfree; >> > +}; >> > + >> > +/* >> > + * Parameters for each trampoline. >> > + * >> > + * data >> > + * Data for the target code that the trampoline jumps to. >> > + * target >> > + * Target code that the trampoline jumps to. >> > + */ >> > +struct tramp_parm >> > +{ >> > + void *data; >> > + void *target; >> > +}; >> > + >> > +/* >> > + * Trampoline structure for each trampoline. >> > + * >> > + * prev, next Links in the trampoline free list of a trampoline table. >> > + * table Trampoline table to which this trampoline belongs. >> > + * code Address of this trampoline in the code table mapping. >> > + * parm Address of this trampoline's parameters in the parameter >> > + * table mapping. >> > + */ >> > +struct tramp >> > +{ >> > + struct tramp *prev; >> > + struct tramp *next; >> > + struct tramp_table *table; >> > + void *code; >> > + struct tramp_parm *parm; >> > +}; >> > + >> > +/* >> > + * Trampoline globals. >> > + * >> > + * fd >> > + * File descriptor of binary file that contains the trampoline code table. >> > + * offset >> > + * Offset of the trampoline code table in that file. >> > + * map_size >> > + * Size of the trampoline code table mapping. >> > + * size >> > + * Size of one trampoline in the trampoline code table. >> > + * ntramp >> > + * Total number of trampolines in the trampoline code table. >> > + * tables >> > + * List of trampoline tables that contain free trampolines. >> > + * ntables >> > + * Number of trampoline tables that contain free trampolines. >> > + */ >> > +struct tramp_global >> > +{ >> > + int fd; >> > + off_t offset; >> > + size_t map_size; >> > + size_t size; >> > + int ntramp; >> > + struct tramp_table *tables; >> > + int ntables; >> > +}; >> > + >> > +static struct tramp_global gtramp = { -1 }; >> > + >> > +/* ------------------------ Trampoline Initialization ----------------------*/ >> > + >> > +static int ffi_tramp_get_fd_offset (void *tramp_text, off_t *offset); >> > + >> > +/* >> > + * Initialize the static trampoline feature. >> > + */ >> > +static int >> > +ffi_tramp_init (void) >> > +{ >> > + if (ffi_tramp_arch == NULL) >> > + return 0; >> > + >> > + if (gtramp.fd == -1) >> > + { >> > + void *tramp_text; >> > + >> > + gtramp.tables = NULL; >> > + gtramp.ntables = 0; >> > + >> > + /* >> > + * Get trampoline code table information from the architecture. >> > + */ >> > + tramp_text = ffi_tramp_arch (>ramp.size, >ramp.map_size); >> > + gtramp.ntramp = gtramp.map_size / gtramp.size; >> > + >> > + /* >> > + * Get the binary file that contains the trampoline code table and also >> > + * the offset of the table within the file. These are used to mmap() >> > + * the trampoline code table. >> > + */ >> > + gtramp.fd = ffi_tramp_get_fd_offset (tramp_text, >ramp.offset); >> > + } >> > + return gtramp.fd != -1; >> > +} >> > + >> > +/* >> > + * From the address of the trampoline code table in the text segment, find the >> > + * binary file and offset of the trampoline code table from /proc/<pid>/maps. >> > + */ >> > +static int >> > +ffi_tramp_get_fd_offset (void *tramp_text, off_t *offset) >> > +{ >> > + FILE *fp; >> > + char file[PATH_MAX], line[PATH_MAX+100], perm[10], dev[10]; >> > + unsigned long start, end, inode; >> > + uintptr_t addr = (uintptr_t) tramp_text; >> > + int nfields, found; >> > + >> > + snprintf (file, PATH_MAX, "/proc/%d/maps", getpid()); >> > + fp = fopen (file, "r"); >> > + if (fp == NULL) >> > + return -1; >> > + >> > + found = 0; >> > + while (feof (fp) == 0) { >> > + if (fgets (line, sizeof (line), fp) == 0) >> > + break; >> > + >> > + nfields = sscanf (line, "%lx-%lx %s %lx %s %ld %s", >> > + &start, &end, perm, offset, dev, &inode, file); >> > + if (nfields != 7) >> > + continue; >> > + >> > + if (addr >= start && addr < end) { >> > + *offset += (addr - start); >> > + found = 1; >> > + break; >> > + } >> > + } >> > + fclose (fp); >> > + >> > + if (!found) >> > + return -1; >> > + >> > + return open (file, O_RDONLY); >> > +} >> > + >> > +/* ---------------------- Trampoline Table functions ---------------------- */ >> > + >> > +static int tramp_table_map (char **code_table, char **parm_table); >> > +static void tramp_add (struct tramp *tramp); >> > + >> > +/* >> > + * Allocate and initialize a trampoline table. >> > + */ >> > +static int >> > +tramp_table_alloc (void) >> > +{ >> > + char *code_table, *parm_table; >> > + struct tramp_table *table; >> > + struct tramp *tramp_array, *tramp; >> > + size_t size; >> > + char *code, *parm; >> > + int i; >> > + >> > + /* >> > + * If we already have tables with free trampolines, there is no need to >> > + * allocate a new table. >> > + */ >> > + if (gtramp.ntables > 0) >> > + return 1; >> > + >> > + /* >> > + * Allocate a new trampoline table structure. >> > + */ >> > + table = malloc (sizeof (*table)); >> > + if (table == NULL) >> > + return 0; >> > + >> > + /* >> > + * Allocate new trampoline structures. >> > + */ >> > + tramp_array = malloc (sizeof (*tramp) * gtramp.ntramp); >> > + if (tramp_array == NULL) >> > + goto free_table; >> > + >> > + /* >> > + * Map a code table and a parameter table into the caller's address space. >> > + */ >> > + if (!tramp_table_map (&code_table, &parm_table)) >> > + goto free_tramp_array; >> > + >> > + /* >> > + * Initialize the trampoline table. >> > + */ >> > + table->code_table = code_table; >> > + table->parm_table = parm_table; >> > + table->array = tramp_array; >> > + table->free = NULL; >> > + table->nfree = 0; >> > + >> > + /* >> > + * Populate the trampoline table free list. This will also add the trampoline >> > + * table to the global list of trampoline tables. >> > + */ >> > + size = gtramp.size; >> > + code = code_table; >> > + parm = parm_table; >> > + for (i = 0; i < gtramp.ntramp; i++) >> > + { >> > + tramp = &tramp_array[i]; >> > + tramp->table = table; >> > + tramp->code = code; >> > + tramp->parm = (struct tramp_parm *) parm; >> > + tramp_add (tramp); >> > + >> > + code += size; >> > + parm += size; >> > + } >> > + return 1; >> > + >> > +free_tramp_array: >> > + free (tramp_array); >> > +free_table: >> > + free (table); >> > + return 0; >> > +} >> > + >> > +/* >> > + * Create a trampoline code table mapping and a trampoline parameter table >> > + * mapping. The two mappings must be adjacent to each other for PC-relative >> > + * access. >> > + * >> > + * For each trampoline in the code table, there is a corresponding parameter >> > + * block in the parameter table. The size of the parameter block is the same >> > + * as the size of the trampoline. This means that the parameter block is at >> > + * a fixed offset from its trampoline making it easy for a trampoline to find >> > + * its parameters using PC-relative access. >> > + * >> > + * The parameter block will contain a struct tramp_parm. This means that >> > + * sizeof (struct tramp_parm) cannot exceed the size of a parameter block. >> > + */ >> > +static int >> > +tramp_table_map (char **code_table, char **parm_table) >> > +{ >> > + char *addr; >> > + >> > + /* >> > + * Create an anonymous mapping twice the map size. The top half will be used >> > + * for the code table. The bottom half will be used for the parameter table. >> > + */ >> > + addr = mmap (NULL, gtramp.map_size * 2, PROT_READ | PROT_WRITE, >> > + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); >> > + if (addr == MAP_FAILED) >> > + return 0; >> > + >> > + /* >> > + * Replace the top half of the anonymous mapping with the code table mapping. >> > + */ >> > + *code_table = mmap (addr, gtramp.map_size, PROT_READ | PROT_EXEC, >> > + MAP_PRIVATE | MAP_FIXED, gtramp.fd, gtramp.offset); >> > + if (*code_table == MAP_FAILED) >> > + { >> > + (void) munmap (addr, gtramp.map_size * 2); >> > + return 0; >> > + } >> > + *parm_table = *code_table + gtramp.map_size; >> > + return 1; >> > +} >> > + >> > +/* >> > + * Free a trampoline table. >> > + */ >> > +static void >> > +tramp_table_free (struct tramp_table *table) >> > +{ >> > + (void) munmap (table->code_table, gtramp.map_size); >> > + (void) munmap (table->parm_table, gtramp.map_size); >> > + free (table->array); >> > + free (table); >> > +} >> > + >> > +/* >> > + * Add a new trampoline table to the global table list. >> > + */ >> > +static void >> > +tramp_table_add (struct tramp_table *table) >> > +{ >> > + table->next = gtramp.tables; >> > + table->prev = NULL; >> > + if (gtramp.tables != NULL) >> > + gtramp.tables->prev = table; >> > + gtramp.tables = table; >> > + gtramp.ntables++; >> > +} >> > + >> > +/* >> > + * Delete a trampoline table from the global table list. >> > + */ >> > +static void >> > +tramp_table_del (struct tramp_table *table) >> > +{ >> > + gtramp.ntables--; >> > + if (table->prev != NULL) >> > + table->prev->next = table->next; >> > + if (table->next != NULL) >> > + table->next->prev = table->prev; >> > + if (gtramp.tables == table) >> > + gtramp.tables = table->next; >> > +} >> > + >> > +/* ------------------------- Trampoline functions ------------------------- */ >> > + >> > +/* >> > + * Add a trampoline to its trampoline table. >> > + */ >> > +static void >> > +tramp_add (struct tramp *tramp) >> > +{ >> > + struct tramp_table *table = tramp->table; >> > + >> > + tramp->next = table->free; >> > + tramp->prev = NULL; >> > + if (table->free != NULL) >> > + table->free->prev = tramp; >> > + table->free = tramp; >> > + table->nfree++; >> > + >> > + if (table->nfree == 1) >> > + tramp_table_add (table); >> > + >> > + /* >> > + * We don't want to keep too many free trampoline tables lying around. >> > + */ >> > + if (table->nfree == gtramp.ntramp && gtramp.ntables > 1) >> > + { >> > + tramp_table_del (table); >> > + tramp_table_free (table); >> > + } >> > +} >> > + >> > +/* >> > + * Remove a trampoline from its trampoline table. >> > + */ >> > +static void >> > +tramp_del (struct tramp *tramp) >> > +{ >> > + struct tramp_table *table = tramp->table; >> > + >> > + table->nfree--; >> > + if (tramp->prev != NULL) >> > + tramp->prev->next = tramp->next; >> > + if (tramp->next != NULL) >> > + tramp->next->prev = tramp->prev; >> > + if (table->free == tramp) >> > + table->free = tramp->next; >> > + >> > + if (table->nfree == 0) >> > + tramp_table_del (table); >> > +} >> > + >> > +/* ------------------------ Trampoline API functions ------------------------ */ >> > + >> > +int >> > +ffi_tramp_is_supported(void) >> > +{ >> > + int ret; >> > + >> > + pthread_mutex_lock (&tramp_lock); >> > + ret = ffi_tramp_init (); >> > + pthread_mutex_unlock (&tramp_lock); >> > + return ret; >> > +} >> > + >> > +/* >> > + * Allocate a trampoline and return its opaque address. >> > + */ >> > +void * >> > +ffi_tramp_alloc (int flags) >> > +{ >> > + struct tramp *tramp; >> > + >> > + pthread_mutex_lock (&tramp_lock); >> > + >> > + if (!ffi_tramp_init () || flags != 0) >> > + { >> > + pthread_mutex_unlock (&tramp_lock); >> > + return NULL; >> > + } >> > + >> > + if (!tramp_table_alloc ()) >> > + { >> > + pthread_mutex_unlock (&tramp_lock); >> > + return NULL; >> > + } >> > + >> > + tramp = gtramp.tables->free; >> > + tramp_del (tramp); >> > + >> > + pthread_mutex_unlock (&tramp_lock); >> > + >> > + return tramp; >> > +} >> > + >> > +/* >> > + * Set the parameters for a trampoline. >> > + */ >> > +void >> > +ffi_tramp_set_parms (void *arg, void *target, void *data) >> > +{ >> > + struct tramp *tramp = arg; >> > + >> > + pthread_mutex_lock (&tramp_lock); >> > + tramp->parm->target = target; >> > + tramp->parm->data = data; >> > + pthread_mutex_unlock (&tramp_lock); >> > +} >> > + >> > +/* >> > + * Get the invocation address of a trampoline. >> > + */ >> > +void * >> > +ffi_tramp_get_addr (void *arg) >> > +{ >> > + struct tramp *tramp = arg; >> > + void *addr; >> > + >> > + pthread_mutex_lock (&tramp_lock); >> > + addr = tramp->code; >> > + pthread_mutex_unlock (&tramp_lock); >> > + >> > + return addr; >> > +} >> > + >> > +/* >> > + * Free a trampoline. >> > + */ >> > +void >> > +ffi_tramp_free (void *arg) >> > +{ >> > + struct tramp *tramp = arg; >> > + >> > + pthread_mutex_lock (&tramp_lock); >> > + tramp_add (tramp); >> > + pthread_mutex_unlock (&tramp_lock); >> > +} >> > + >> > +/* ------------------------------------------------------------------------- */ >> > + >> > +#else /* !FFI_EXEC_STATIC_TRAMP */ >> > + >> > +int >> > +ffi_tramp_is_supported(void) >> > +{ >> > + return 0; >> > +} >> > + >> > +void * >> > +ffi_tramp_alloc (int flags) >> > +{ >> > + return NULL; >> > +} >> > + >> > +void >> > +ffi_tramp_set_parms (void *arg, void *target, void *data) >> > +{ >> > +} >> > + >> > +void * >> > +ffi_tramp_get_addr (void *arg) >> > +{ >> > + return NULL; >> > +} >> > + >> > +void >> > +ffi_tramp_free (void *arg) >> > +{ >> > +} >> > + >> > +#endif /* FFI_EXEC_STATIC_TRAMP */ >> > diff --git a/testsuite/libffi.closures/closure_loc_fn0.c b/testsuite/libffi.closures/closure_loc_fn0.c >> > index b3afa0b..ad488ac 100644 >> > --- a/testsuite/libffi.closures/closure_loc_fn0.c >> > +++ b/testsuite/libffi.closures/closure_loc_fn0.c >> > @@ -83,7 +83,10 @@ int main (void) >> > CHECK(ffi_prep_closure_loc(pcl, &cif, closure_loc_test_fn0, >> > (void *) 3 /* userdata */, codeloc) == FFI_OK); >> > >> > +#ifndef FFI_EXEC_STATIC_TRAMP >> > + /* With static trampolines, the codeloc does not point to closure */ >> > CHECK(memcmp(pcl, codeloc, sizeof(*pcl)) == 0); >> > +#endif >> > >> > res = (*((closure_loc_test_type0)codeloc)) >> > (1LL, 2, 3LL, 4, 127, 429LL, 7, 8, 9.5, 10, 11, 12, 13, >> > -- >> > 2.25.1 >> > >> ^ permalink raw reply [flat|nested] 12+ messages in thread
* Re: [RFC PATCH v1 1/4] Static Trampolines - Quick question 2020-12-03 18:45 ` Madhavan T. Venkataraman @ 2020-12-05 2:38 ` Madhavan T. Venkataraman 0 siblings, 0 replies; 12+ messages in thread From: Madhavan T. Venkataraman @ 2020-12-05 2:38 UTC (permalink / raw) To: libffi-discuss Hi, I am preparing version 2. I have a question. Are we allowed to change FFI_TRAMPOLINE_SIZE, the size of closure->tramp[]? As an example, I checked the git history for ARM. I can see that it has changed a couple of times in the past. Just want to know if there would be any compatibility issues if the size is changed. My solution can be more elegant if the trampoline size can be changed. I recall seeing somewhere that in some cases, a libffi consumer manages closure memory and does not call ffi_closure_alloc() and ffi_closure_free(). In such cases, the consumer would have to be rebuilt if the closure size changed. Do we still support such consumers? Is it OK for them to rebuild? When the size of the closure structure changes, does the library version have to be bumped up? Please advise. Thanks. Madhavan ^ permalink raw reply [flat|nested] 12+ messages in thread
* [RFC PATCH v1 2/4] x86: Support for Static Trampolines 2020-11-24 19:32 ` [RFC PATCH v1 0/4] Libffi Static Trampolines madvenka 2020-11-24 19:32 ` [RFC PATCH v1 1/4] " madvenka @ 2020-11-24 19:32 ` madvenka 2020-11-24 19:32 ` [RFC PATCH v1 3/4] aarch64: " madvenka 2020-11-24 19:32 ` [RFC PATCH v1 4/4] arm: " madvenka 3 siblings, 0 replies; 12+ messages in thread From: madvenka @ 2020-11-24 19:32 UTC (permalink / raw) To: libffi-discuss; +Cc: fw, dj, madvenka From: "Madhavan T. Venkataraman" <madvenka@linux.microsoft.com> - Define the arch-specific initialization function ffi_tramp_arch () that returns trampoline size information to common code. - Define the trampoline code and data mapping sizes. - Introduce a tiny amount of code at the beginning of each ABI handler to retrieve the information saved by the trampoline on stack. - Define the trampoline code table statically. - Call ffi_closure_tramp_init () to initialize static trampoline parameters from ffi_prep_closure_loc (). Signed-off-by: Madhavan T. Venkataraman <madvenka@linux.microsoft.com> --- src/x86/ffi.c | 17 +++++++++++++++ src/x86/ffi64.c | 19 ++++++++++++++-- src/x86/ffiw64.c | 8 ++++--- src/x86/internal.h | 10 +++++++++ src/x86/internal64.h | 10 +++++++++ src/x86/sysv.S | 52 ++++++++++++++++++++++++++++++++++++++++++++ src/x86/unix64.S | 48 ++++++++++++++++++++++++++++++++++++++++ src/x86/win64.S | 4 ++++ 8 files changed, 163 insertions(+), 5 deletions(-) diff --git a/src/x86/ffi.c b/src/x86/ffi.c index 5f7fd81..3407fb8 100644 --- a/src/x86/ffi.c +++ b/src/x86/ffi.c @@ -559,6 +559,9 @@ ffi_prep_closure_loc (ffi_closure* closure, return FFI_BAD_ABI; } + if (ffi_closure_tramp_set_parms (closure, dest)) + goto out; + /* endbr32. */ *(UINT32 *) tramp = 0xfb1e0ff3; @@ -570,6 +573,7 @@ ffi_prep_closure_loc (ffi_closure* closure, tramp[9] = 0xe9; *(unsigned *)(tramp + 10) = (unsigned)dest - ((unsigned)codeloc + 14); +out: closure->cif = cif; closure->fun = fun; closure->user_data = user_data; @@ -767,4 +771,17 @@ ffi_raw_call(ffi_cif *cif, void (*fn)(void), void *rvalue, ffi_raw *avalue) ffi_call_i386 (frame, stack); } #endif /* !FFI_NO_RAW_API */ + +#if defined(FFI_EXEC_STATIC_TRAMP) +void * +ffi_tramp_arch (size_t *tramp_size, size_t *map_size) +{ + extern void *trampoline_code_table; + + *tramp_size = X86_TRAMP_SIZE; + *map_size = X86_TRAMP_MAP_SIZE; + return &trampoline_code_table; +} +#endif + #endif /* __i386__ */ diff --git a/src/x86/ffi64.c b/src/x86/ffi64.c index 39f9598..fdef9b0 100644 --- a/src/x86/ffi64.c +++ b/src/x86/ffi64.c @@ -756,8 +756,11 @@ ffi_prep_closure_loc (ffi_closure* closure, else dest = ffi_closure_unix64; - memcpy (tramp, trampoline, sizeof(trampoline)); - *(UINT64 *)(tramp + sizeof (trampoline)) = (uintptr_t)dest; + if (!ffi_closure_tramp_set_parms (closure, dest)) + { + memcpy (tramp, trampoline, sizeof(trampoline)); + *(UINT64 *)(tramp + sizeof (trampoline)) = (uintptr_t)dest; + } closure->cif = cif; closure->fun = fun; @@ -892,4 +895,16 @@ ffi_prep_go_closure (ffi_go_closure* closure, ffi_cif* cif, #endif /* FFI_GO_CLOSURES */ +#if defined(FFI_EXEC_STATIC_TRAMP) +void * +ffi_tramp_arch (size_t *tramp_size, size_t *map_size) +{ + extern void *trampoline_code_table; + + *tramp_size = UNIX64_TRAMP_SIZE; + *map_size = UNIX64_TRAMP_MAP_SIZE; + return &trampoline_code_table; +} +#endif + #endif /* __x86_64__ */ diff --git a/src/x86/ffiw64.c b/src/x86/ffiw64.c index a43a9eb..74cd092 100644 --- a/src/x86/ffiw64.c +++ b/src/x86/ffiw64.c @@ -185,7 +185,6 @@ EFI64(ffi_call_go)(ffi_cif *cif, void (*fn)(void), void *rvalue, ffi_call_int (cif, fn, rvalue, avalue, closure); } - extern void ffi_closure_win64(void) FFI_HIDDEN; #ifdef FFI_GO_CLOSURES @@ -220,8 +219,11 @@ EFI64(ffi_prep_closure_loc)(ffi_closure* closure, return FFI_BAD_ABI; } - memcpy (tramp, trampoline, sizeof(trampoline)); - *(UINT64 *)(tramp + sizeof (trampoline)) = (uintptr_t)ffi_closure_win64; + if (!ffi_closure_tramp_set_parms (closure, ffi_closure_win64)) + { + memcpy (tramp, trampoline, sizeof(trampoline)); + *(UINT64 *)(tramp + sizeof (trampoline)) = (uintptr_t)ffi_closure_win64; + } closure->cif = cif; closure->fun = fun; diff --git a/src/x86/internal.h b/src/x86/internal.h index 09771ba..f782aad 100644 --- a/src/x86/internal.h +++ b/src/x86/internal.h @@ -27,3 +27,13 @@ #else # define HAVE_FASTCALL 1 #endif + +#if defined(FFI_EXEC_STATIC_TRAMP) +/* + * For the trampoline code table mapping, a mapping size of 4K (base page size) + * is chosen. + */ +#define X86_TRAMP_MAP_SHIFT 12 +#define X86_TRAMP_MAP_SIZE (1 << X86_TRAMP_MAP_SHIFT) +#define X86_TRAMP_SIZE 44 +#endif diff --git a/src/x86/internal64.h b/src/x86/internal64.h index 512e955..272b914 100644 --- a/src/x86/internal64.h +++ b/src/x86/internal64.h @@ -20,3 +20,13 @@ #define UNIX64_FLAG_RET_IN_MEM (1 << 10) #define UNIX64_FLAG_XMM_ARGS (1 << 11) #define UNIX64_SIZE_SHIFT 12 + +#if defined(FFI_EXEC_STATIC_TRAMP) +/* + * For the trampoline code table mapping, a mapping size of 4K (base page size) + * is chosen. + */ +#define UNIX64_TRAMP_MAP_SHIFT 12 +#define UNIX64_TRAMP_MAP_SIZE (1 << UNIX64_TRAMP_MAP_SHIFT) +#define UNIX64_TRAMP_SIZE 40 +#endif diff --git a/src/x86/sysv.S b/src/x86/sysv.S index d8ab4b0..a1d499d 100644 --- a/src/x86/sysv.S +++ b/src/x86/sysv.S @@ -344,6 +344,10 @@ C(ffi_closure_i386): L(UW12): # cfi_startproc _CET_ENDBR +#ifdef FFI_EXEC_STATIC_TRAMP + movl 4(%esp), %eax + add $8, %esp +#endif subl $closure_FS, %esp L(UW13): # cfi_def_cfa_offset(closure_FS + 4) @@ -454,6 +458,10 @@ L(UW24): # cfi_def_cfa(%esp, 8) # cfi_offset(%eip, -8) _CET_ENDBR +#ifdef FFI_EXEC_STATIC_TRAMP + movl (%esp), %eax + add $4, %esp +#endif subl $closure_FS-4, %esp L(UW25): # cfi_def_cfa_offset(closure_FS + 4) @@ -477,6 +485,10 @@ C(ffi_closure_STDCALL): L(UW27): # cfi_startproc _CET_ENDBR +#ifdef FFI_EXEC_STATIC_TRAMP + movl 4(%esp), %eax + add $8, %esp +#endif subl $closure_FS, %esp L(UW28): # cfi_def_cfa_offset(closure_FS + 4) @@ -573,6 +585,46 @@ L(UW31): # cfi_endproc ENDF(C(ffi_closure_STDCALL)) +#if defined(FFI_EXEC_STATIC_TRAMP) +/* + * The trampoline uses register eax. It saves the original value of eax on + * the stack. + * + * The trampoline has two parameters - target code to jump to and data for + * the target code. The trampoline extracts the parameters from its parameter + * block (see tramp_table_map()). The trampoline saves the data address on + * the stack. Finally, it jumps to the target code. + * + * The target code can choose to: + * + * - restore the value of eax + * - load the data address in a register + * - restore the stack pointer to what it was when the trampoline was invoked. + */ + .align X86_TRAMP_MAP_SIZE + .globl C(trampoline_code_table) + FFI_HIDDEN(C(trampoline_code_table)) +C(trampoline_code_table): + .rept X86_TRAMP_MAP_SIZE / X86_TRAMP_SIZE + endbr32 + sub $8, %esp + movl %eax, (%esp) /* Save %eax on stack */ + call 1f /* Get next PC into %eax */ + movl 4081(%eax), %eax /* Copy data into %eax */ + movl %eax, 4(%esp) /* Save data on stack */ + call 1f /* Get next PC into %eax */ + movl 4070(%eax), %eax /* Copy data into %eax */ + jmp *%eax /* Jump to code */ +1: + mov (%esp), %eax + ret + nop /* Pad to 4 byte boundary */ + nop + .endr +ENDF(C(trampoline_code_table)) + .align X86_TRAMP_MAP_SIZE +#endif /* FFI_EXEC_STATIC_TRAMP */ + #if !FFI_NO_RAW_API #define raw_closure_S_FS (16+16+12) diff --git a/src/x86/unix64.S b/src/x86/unix64.S index 89d7db1..c340315 100644 --- a/src/x86/unix64.S +++ b/src/x86/unix64.S @@ -253,6 +253,10 @@ ENDF(C(ffi_call_unix64)) C(ffi_closure_unix64_sse): L(UW5): _CET_ENDBR +#ifdef FFI_EXEC_STATIC_TRAMP + movq 8(%rsp), %r10 + addq $16, %rsp +#endif subq $ffi_closure_FS, %rsp L(UW6): /* cfi_adjust_cfa_offset(ffi_closure_FS) */ @@ -277,6 +281,10 @@ ENDF(C(ffi_closure_unix64_sse)) C(ffi_closure_unix64): L(UW8): _CET_ENDBR +#ifdef FFI_EXEC_STATIC_TRAMP + movq 8(%rsp), %r10 + addq $16, %rsp +#endif subq $ffi_closure_FS, %rsp L(UW9): /* cfi_adjust_cfa_offset(ffi_closure_FS) */ @@ -456,6 +464,46 @@ L(sse_entry2): L(UW17): ENDF(C(ffi_go_closure_unix64)) +#if defined(FFI_EXEC_STATIC_TRAMP) +/* + * The trampoline uses register r10. It saves the original value of r10 on + * the stack. + * + * The trampoline has two parameters - target code to jump to and data for + * the target code. The trampoline extracts the parameters from its parameter + * block (see tramp_table_map()). The trampoline saves the data address on + * the stack. Finally, it jumps to the target code. + * + * The target code can choose to: + * + * - restore the value of r10 + * - load the data address in a register + * - restore the stack pointer to what it was when the trampoline was invoked. + */ + .align UNIX64_TRAMP_MAP_SIZE + .globl trampoline_code_table + FFI_HIDDEN(C(trampoline_code_table)) + +C(trampoline_code_table): + .rept UNIX64_TRAMP_MAP_SIZE / UNIX64_TRAMP_SIZE + endbr64 + subq $16, %rsp /* Make space on the stack */ + movq %r10, (%rsp) /* Save %r10 on stack */ + movq 4077(%rip), %r10 /* Copy data into %r10 */ + movq %r10, 8(%rsp) /* Save data on stack */ + movq 4073(%rip), %r10 /* Copy code into %r10 */ + jmp *%r10 /* Jump to code */ + nop /* Pad to 8 byte boundary */ + nop + nop + nop + nop + nop + .endr +ENDF(C(trampoline_code_table)) + .align UNIX64_TRAMP_MAP_SIZE +#endif /* FFI_EXEC_STATIC_TRAMP */ + /* Sadly, OSX cctools-as doesn't understand .cfi directives at all. */ #ifdef __APPLE__ diff --git a/src/x86/win64.S b/src/x86/win64.S index 8315e8b..5db607c 100644 --- a/src/x86/win64.S +++ b/src/x86/win64.S @@ -200,6 +200,10 @@ C(ffi_go_closure_win64): C(ffi_closure_win64): cfi_startproc _CET_ENDBR +#ifdef FFI_EXEC_STATIC_TRAMP + movq 8(%rsp), %r10 + addq $16, %rsp +#endif /* Save all integer arguments into the incoming reg stack space. */ movq %rcx, 8(%rsp) movq %rdx, 16(%rsp) -- 2.25.1 ^ permalink raw reply [flat|nested] 12+ messages in thread
* [RFC PATCH v1 3/4] aarch64: Support for Static Trampolines 2020-11-24 19:32 ` [RFC PATCH v1 0/4] Libffi Static Trampolines madvenka 2020-11-24 19:32 ` [RFC PATCH v1 1/4] " madvenka 2020-11-24 19:32 ` [RFC PATCH v1 2/4] x86: Support for Static Trampolines madvenka @ 2020-11-24 19:32 ` madvenka 2020-11-24 19:32 ` [RFC PATCH v1 4/4] arm: " madvenka 3 siblings, 0 replies; 12+ messages in thread From: madvenka @ 2020-11-24 19:32 UTC (permalink / raw) To: libffi-discuss; +Cc: fw, dj, madvenka From: "Madhavan T. Venkataraman" <madvenka@linux.microsoft.com> - Define the arch-specific initialization function ffi_tramp_arch () that returns trampoline size information to common code. - Define the trampoline code and data mapping sizes. - Introduce a tiny amount of code at the beginning of each ABI handler to retrieve the information saved by the trampoline on stack. - Define the trampoline code table statically. - Call ffi_closure_tramp_init () to initialize static trampoline parameters from ffi_prep_closure_loc (). Signed-off-by: Madhavan T. Venkataraman <madvenka@linux.microsoft.com> --- src/aarch64/ffi.c | 16 +++++++++++++++ src/aarch64/internal.h | 10 +++++++++ src/aarch64/sysv.S | 46 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 72 insertions(+) diff --git a/src/aarch64/ffi.c b/src/aarch64/ffi.c index ef09f4d..64d36b6 100644 --- a/src/aarch64/ffi.c +++ b/src/aarch64/ffi.c @@ -817,6 +817,9 @@ ffi_prep_closure_loc (ffi_closure *closure, }; char *tramp = closure->tramp; + if (ffi_closure_tramp_set_parms (closure, start)) + goto out; + memcpy (tramp, trampoline, sizeof(trampoline)); *(UINT64 *)(tramp + 16) = (uintptr_t)start; @@ -832,6 +835,7 @@ ffi_prep_closure_loc (ffi_closure *closure, unsigned char *tramp_code = ffi_data_to_code_pointer (tramp); #endif ffi_clear_cache (tramp_code, tramp_code + FFI_TRAMPOLINE_SIZE); +out: #endif closure->cif = cif; @@ -1022,4 +1026,16 @@ ffi_closure_SYSV_inner (ffi_cif *cif, return flags; } +#if defined(FFI_EXEC_STATIC_TRAMP) +void * +ffi_tramp_arch (size_t *tramp_size, size_t *map_size) +{ + extern void *trampoline_code_table; + + *tramp_size = AARCH64_TRAMP_SIZE; + *map_size = AARCH64_TRAMP_MAP_SIZE; + return &trampoline_code_table; +} +#endif + #endif /* (__aarch64__) || defined(__arm64__)|| defined (_M_ARM64)*/ diff --git a/src/aarch64/internal.h b/src/aarch64/internal.h index 3d4d035..de55755 100644 --- a/src/aarch64/internal.h +++ b/src/aarch64/internal.h @@ -66,3 +66,13 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #define N_X_ARG_REG 8 #define N_V_ARG_REG 8 #define CALL_CONTEXT_SIZE (N_V_ARG_REG * 16 + N_X_ARG_REG * 8) + +#if defined(FFI_EXEC_STATIC_TRAMP) +/* + * For the trampoline code table mapping, a mapping size of 16K is chosen to + * cover the base page sizes of 4K and 16K. + */ +#define AARCH64_TRAMP_MAP_SHIFT 14 +#define AARCH64_TRAMP_MAP_SIZE (1 << AARCH64_TRAMP_MAP_SHIFT) +#define AARCH64_TRAMP_SIZE 32 +#endif diff --git a/src/aarch64/sysv.S b/src/aarch64/sysv.S index b720a92..fece3f9 100644 --- a/src/aarch64/sysv.S +++ b/src/aarch64/sysv.S @@ -232,6 +232,10 @@ CNAME(ffi_call_SYSV): .align 4 CNAME(ffi_closure_SYSV_V): cfi_startproc +#if defined(FFI_EXEC_STATIC_TRAMP) + ldr x17, [sp, #8] + add sp, sp, #16 +#endif stp x29, x30, [sp, #-ffi_closure_SYSV_FS]! cfi_adjust_cfa_offset (ffi_closure_SYSV_FS) cfi_rel_offset (x29, 0) @@ -255,6 +259,10 @@ CNAME(ffi_closure_SYSV_V): .align 4 cfi_startproc CNAME(ffi_closure_SYSV): +#if defined(FFI_EXEC_STATIC_TRAMP) + ldr x17, [sp, #8] + add sp, sp, #16 +#endif stp x29, x30, [sp, #-ffi_closure_SYSV_FS]! cfi_adjust_cfa_offset (ffi_closure_SYSV_FS) cfi_rel_offset (x29, 0) @@ -367,6 +375,44 @@ CNAME(ffi_closure_SYSV): .size CNAME(ffi_closure_SYSV), . - CNAME(ffi_closure_SYSV) #endif +#if defined(FFI_EXEC_STATIC_TRAMP) +/* + * The trampoline uses register x17. It saves the original value of x17 on + * the stack. + * + * The trampoline has two parameters - target code to jump to and data for + * the target code. The trampoline extracts the parameters from its parameter + * block (see tramp_table_map()). The trampoline saves the data address on + * the stack. Finally, it jumps to the target code. + * + * The target code can choose to: + * + * - restore the value of x17 + * - load the data address in a register + * - restore the stack pointer to what it was when the trampoline was invoked. + */ + .align AARCH64_TRAMP_MAP_SHIFT +CNAME(trampoline_code_table): + .rept AARCH64_TRAMP_MAP_SIZE / AARCH64_TRAMP_SIZE + sub sp, sp, #16 /* Make space on the stack */ + str x17, [sp] /* Save x17 on stack */ + adr x17, #16376 /* Get data address */ + ldr x17, [x17] /* Copy data into x17 */ + str x17, [sp, #8] /* Save data on stack */ + adr x17, #16372 /* Get code address */ + ldr x17, [x17] /* Load code address into x17 */ + br x17 /* Jump to code */ + .endr + + .globl CNAME(trampoline_code_table) + FFI_HIDDEN(CNAME(trampoline_code_table)) +#ifdef __ELF__ + .type CNAME(trampoline_code_table), #function + .size CNAME(trampoline_code_table), . - CNAME(trampoline_code_table) +#endif + .align AARCH64_TRAMP_MAP_SHIFT +#endif /* FFI_EXEC_STATIC_TRAMP */ + #if FFI_EXEC_TRAMPOLINE_TABLE #ifdef __MACH__ -- 2.25.1 ^ permalink raw reply [flat|nested] 12+ messages in thread
* [RFC PATCH v1 4/4] arm: Support for Static Trampolines 2020-11-24 19:32 ` [RFC PATCH v1 0/4] Libffi Static Trampolines madvenka ` (2 preceding siblings ...) 2020-11-24 19:32 ` [RFC PATCH v1 3/4] aarch64: " madvenka @ 2020-11-24 19:32 ` madvenka 3 siblings, 0 replies; 12+ messages in thread From: madvenka @ 2020-11-24 19:32 UTC (permalink / raw) To: libffi-discuss; +Cc: fw, dj, madvenka From: "Madhavan T. Venkataraman" <madvenka@linux.microsoft.com> - Define the arch-specific initialization function ffi_tramp_arch () that returns trampoline size information to common code. - Define the trampoline code and data mapping sizes. - Introduce a tiny amount of code at the beginning of each ABI handler to retrieve the information saved by the trampoline on stack. - Define the trampoline code table statically. - Call ffi_closure_tramp_init () to initialize static trampoline parameters from ffi_prep_closure_loc (). Signed-off-by: Madhavan T. Venkataraman <madvenka@linux.microsoft.com> --- src/arm/ffi.c | 16 ++++++++++++++++ src/arm/internal.h | 10 ++++++++++ src/arm/sysv.S | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 63 insertions(+) diff --git a/src/arm/ffi.c b/src/arm/ffi.c index 0058390..6529803 100644 --- a/src/arm/ffi.c +++ b/src/arm/ffi.c @@ -612,6 +612,9 @@ ffi_prep_closure_loc (ffi_closure * closure, config[1] = closure_func; #else + if (ffi_closure_tramp_set_parms (closure, closure_func)) + goto out; + #ifndef _M_ARM memcpy(closure->tramp, ffi_arm_trampoline, 8); #else @@ -633,6 +636,7 @@ ffi_prep_closure_loc (ffi_closure * closure, #else *(void (**)(void))(closure->tramp + 8) = closure_func; #endif +out: #endif closure->cif = cif; @@ -873,4 +877,16 @@ layout_vfp_args (ffi_cif * cif) } } +#if defined(FFI_EXEC_STATIC_TRAMP) +void * +ffi_tramp_arch (size_t *tramp_size, size_t *map_size) +{ + extern void *trampoline_code_table; + + *tramp_size = ARM_TRAMP_SIZE; + *map_size = ARM_TRAMP_MAP_SIZE; + return &trampoline_code_table; +} +#endif + #endif /* __arm__ or _M_ARM */ diff --git a/src/arm/internal.h b/src/arm/internal.h index 6cf0b2a..fa8ab0b 100644 --- a/src/arm/internal.h +++ b/src/arm/internal.h @@ -5,3 +5,13 @@ #define ARM_TYPE_INT 4 #define ARM_TYPE_VOID 5 #define ARM_TYPE_STRUCT 6 + +#if defined(FFI_EXEC_STATIC_TRAMP) +/* + * For the trampoline table mapping, a mapping size of 4K (base page size) + * is chosen. + */ +#define ARM_TRAMP_MAP_SHIFT 12 +#define ARM_TRAMP_MAP_SIZE (1 << ARM_TRAMP_MAP_SHIFT) +#define ARM_TRAMP_SIZE 20 +#endif diff --git a/src/arm/sysv.S b/src/arm/sysv.S index 74bc53f..f0a435f 100644 --- a/src/arm/sysv.S +++ b/src/arm/sysv.S @@ -227,6 +227,10 @@ ARM_FUNC_END(ffi_go_closure_SYSV) ARM_FUNC_START(ffi_closure_SYSV) UNWIND(.fnstart) cfi_startproc +#if defined(FFI_EXEC_STATIC_TRAMP) + ldr ip, [sp, #4] + add sp, sp, 8 +#endif stmdb sp!, {r0-r3} @ save argument regs cfi_adjust_cfa_offset(16) @@ -274,6 +278,10 @@ ARM_FUNC_END(ffi_go_closure_VFP) ARM_FUNC_START(ffi_closure_VFP) UNWIND(.fnstart) cfi_startproc +#if defined(FFI_EXEC_STATIC_TRAMP) + ldr ip, [sp, #4] + add sp, sp, 8 +#endif stmdb sp!, {r0-r3} @ save argument regs cfi_adjust_cfa_offset(16) @@ -354,6 +362,35 @@ E(ARM_TYPE_STRUCT) cfi_endproc ARM_FUNC_END(ffi_closure_ret) +#if defined(FFI_EXEC_STATIC_TRAMP) +/* + * The trampoline uses register ip (r12). It saves the original value of ip + * on the stack. + * + * The trampoline has two parameters - target code to jump to and data for + * the target code. The trampoline extracts the parameters from its parameter + * block (see tramp_table_map()). The trampoline saves the data address on + * the stack. Finally, it jumps to the target code. + * + * The target code can choose to: + * + * - restore the value of ip + * - load the data address in a register + * - restore the stack pointer to what it was when the trampoline was invoked. + */ + .align ARM_TRAMP_MAP_SHIFT +ARM_FUNC_START(trampoline_code_table) + .rept ARM_TRAMP_MAP_SIZE / ARM_TRAMP_SIZE + sub sp, sp, #8 /* Make space on the stack */ + str ip, [sp] /* Save ip on stack */ + ldr ip, [pc, #4080] /* Copy data into ip */ + str ip, [sp, #4] /* Save data on stack */ + ldr pc, [pc, #4076] /* Copy code into PC */ + .endr +ARM_FUNC_END(trampoline_code_table) + .align ARM_TRAMP_MAP_SHIFT +#endif /* FFI_EXEC_STATIC_TRAMP */ + #if FFI_EXEC_TRAMPOLINE_TABLE #ifdef __MACH__ -- 2.25.1 ^ permalink raw reply [flat|nested] 12+ messages in thread
end of thread, other threads:[~2020-12-05 2:38 UTC | newest] Thread overview: 12+ messages (download: mbox.gz / follow: Atom feed) -- links below jump to the message on this page -- [not found] <9bd94fd78a3c8f638b8a0d2269258da99d58e70f> 2020-11-24 19:32 ` [RFC PATCH v1 0/4] Libffi Static Trampolines madvenka 2020-11-24 19:32 ` [RFC PATCH v1 1/4] " madvenka 2020-11-24 19:49 ` Anthony Green 2020-11-24 20:02 ` Madhavan T. Venkataraman 2020-12-02 16:49 ` Madhavan T. Venkataraman 2020-12-02 18:14 ` Anthony Green 2020-12-02 21:33 ` Madhavan T. Venkataraman 2020-12-03 18:45 ` Madhavan T. Venkataraman 2020-12-05 2:38 ` [RFC PATCH v1 1/4] Static Trampolines - Quick question Madhavan T. Venkataraman 2020-11-24 19:32 ` [RFC PATCH v1 2/4] x86: Support for Static Trampolines madvenka 2020-11-24 19:32 ` [RFC PATCH v1 3/4] aarch64: " madvenka 2020-11-24 19:32 ` [RFC PATCH v1 4/4] arm: " madvenka
This is a public inbox, see mirroring instructions for how to clone and mirror all data and code used for this inbox; as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).