[PATCH 4/4] selftests/sgx: Fix compiler optimizations in test enclave

From: Jo Van Bulck
Date: Thu Jul 20 2023 - 18:17:05 EST


Relocate encl_op_array entries at runtime relative to the enclave base to
ensure correct function pointer when compiling the test enclave with -Os.

Declare the secinfo struct as volatile to prevent compiler optimizations
from passing an unaligned pointer to ENCLU.

Signed-off-by: Jo Van Bulck <jo.vanbulck@xxxxxxxxxxxxxx>
---
tools/testing/selftests/sgx/test_encl.c | 10 ++++++----
1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/tools/testing/selftests/sgx/test_encl.c b/tools/testing/selftests/sgx/test_encl.c
index ea24cdf9e..b580c37f3 100644
--- a/tools/testing/selftests/sgx/test_encl.c
+++ b/tools/testing/selftests/sgx/test_encl.c
@@ -105,7 +105,8 @@ static inline void assert_inside_enclave(uint64_t arg, size_t len)
static void do_encl_emodpe(void *_op)
{
struct encl_op_emodpe op;
- struct sgx_secinfo secinfo __aligned(sizeof(struct sgx_secinfo)) = {0};
+ /* declare secinfo volatile to preserve alignment */
+ volatile struct __aligned(sizeof(struct sgx_secinfo)) sgx_secinfo secinfo = {0};

copy_inside_enclave(&op, _op, sizeof(op));
assert_inside_enclave(op.epc_addr, PAGE_SIZE);
@@ -122,8 +123,9 @@ static void do_encl_emodpe(void *_op)
static void do_encl_eaccept(void *_op)
{
struct encl_op_eaccept op;
- struct sgx_secinfo secinfo __aligned(sizeof(struct sgx_secinfo)) = {0};
int rax;
+ /* declare secinfo volatile to preserve alignment */
+ volatile struct __aligned(sizeof(struct sgx_secinfo)) sgx_secinfo secinfo = {0};

copy_inside_enclave(&op, _op, sizeof(op));
assert_inside_enclave(op.epc_addr, PAGE_SIZE);
@@ -222,7 +224,7 @@ static void do_encl_op_nop(void *_op)

void encl_body(void *rdi, void *rsi)
{
- const void (*encl_op_array[ENCL_OP_MAX])(void *) = {
+ static const void (*encl_op_array[ENCL_OP_MAX])(void *) = {
do_encl_op_put_to_buf,
do_encl_op_get_from_buf,
do_encl_op_put_to_addr,
@@ -237,5 +239,5 @@ void encl_body(void *rdi, void *rsi)
copy_inside_enclave(&op, rdi, sizeof(op));

if (op.type < ENCL_OP_MAX)
- (*encl_op_array[op.type])(rdi);
+ (*(get_enclave_base() + encl_op_array[op.type]))(rdi);
}
--
2.34.1