sslab-gatech / opensgx

OpenSGX
Other
288 stars 80 forks source link

malloc broken with small allocations #48

Open bbiletch opened 7 years ago

bbiletch commented 7 years ago

It appears that libsgx's malloc implementation does not work correctly with many small allocations. This can be verified with the following program, which incorrectly segfaults:

#include <stdlib.h>

int enclave_main(int argc, char *argv[])
{
    for(int i=0; i<38368; i++)
    {
        malloc(1);
    }

    return 0;
}

Increasing the size that is malloced to 1024 bytes prevents the segfault (although after 1359 allocations, it gives a different error, which I suspect is due to a hardcoded maximum memory limit).

I believe this bug is caused by the way libsgx handles the EAUG/EACCEPT process: when the enclave needs more memory, it will allocate a SECINFO structure (64 bytes) that is used to request another page to be mapped into its memory. However, if there are less than 64 bytes of memory available due to previous small allocations (or just bad luck), this allocation will fail and require allocation of another page, causing a recursion that overflows the stack.

This should be fixable by allocating the SECINFO on initialization and immediately after every EAUG/EACCEPT and then storing it for the next time it is needed, rather than allocating it on-demand just before the EAUG/EACCEPT.