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

From: Jo Van Bulck
Date: Wed Jul 19 2023 - 10:49:30 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 5531f5d48..d78596ccf 100644
--- a/tools/testing/selftests/sgx/test_encl.c
+++ b/tools/testing/selftests/sgx/test_encl.c
@@ -88,7 +88,8 @@ static void *memset(void *dest, int c, size_t n)
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};

SAFE_COPY_STRUCT(_op, &op);
ASSERT_INSIDE_ENCLAVE(op.epc_addr, PAGE_SIZE);
@@ -105,8 +106,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};

SAFE_COPY_STRUCT(_op, &op);
ASSERT_INSIDE_ENCLAVE(op.epc_addr, PAGE_SIZE);
@@ -205,7 +207,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,
@@ -220,5 +222,5 @@ void encl_body(void *rdi, void *rsi)
SAFE_COPY_STRUCT(rdi, &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