Manually align ELRANGE now that the kernel doesn't automatically do so for SGX mappings. To guarantee mmap() returns a region that can be naturally aligned, temporarily map 2x the enclave size and do fancy arithmetic to naturally align the base. Signed-off-by: Sean Christopherson <sean.j.christopherson@xxxxxxxxx> --- tools/testing/selftests/x86/sgx/main.c | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/tools/testing/selftests/x86/sgx/main.c b/tools/testing/selftests/x86/sgx/main.c index effcdb3380ad..5bbc60cf7f89 100644 --- a/tools/testing/selftests/x86/sgx/main.c +++ b/tools/testing/selftests/x86/sgx/main.c @@ -130,7 +130,8 @@ static bool encl_create(int dev_fd, unsigned long bin_size, struct sgx_secs *secs) { struct sgx_enclave_create ioc; - void *base; + uint64_t base; + void *basep; int rc; memset(secs, 0, sizeof(*secs)); @@ -141,19 +142,27 @@ static bool encl_create(int dev_fd, unsigned long bin_size, for (secs->size = 4096; secs->size < bin_size; ) secs->size <<= 1; - base = mmap(NULL, secs->size, PROT_NONE, MAP_SHARED, dev_fd, 0); - if (base == MAP_FAILED) { + basep = mmap(NULL, secs->size * 2, PROT_NONE, MAP_SHARED, dev_fd, 0); + if (basep == MAP_FAILED) { perror("mmap"); return false; } + base = (uint64_t)basep; - secs->base = (uint64_t)base; + secs->base = base + secs->size - (base % secs->size); + + if (secs->base != base) + munmap(basep, secs->base - base); + + if (secs->base - secs->size != base) + munmap((void *)(secs->base + secs->size), + base + secs->size - secs->base); ioc.src = (unsigned long)secs; rc = ioctl(dev_fd, SGX_IOC_ENCLAVE_CREATE, &ioc); if (rc) { fprintf(stderr, "ECREATE failed rc=%d, err=%d.\n", rc, errno); - munmap(base, secs->size); + munmap((void *)secs->base, secs->size); return false; } -- 2.22.0