4

I'm writing some code that has to be well behaved both inside and outside an SGX enclave. To that end, it would be useful to have some way to determine at runtime whether or not the code is executing inside an enclave or not. Unfortunately, after searching the documentation, I haven't been able to find a way to do this.

TL:DR; I'm looking for a bool in_sgx_context() function which I can use to steer application behaviour depending on whether or not my code is running inside a secure enclave or not.

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82
ac101m
  • 41
  • 1
  • Can you explain why you want the behavior to be different when outside an enclave? – prl Sep 10 '21 at 09:29
  • 2
    We need to run some code inside the enclave that attempts to determine CPU features. The CPUID instruction is not available inside the enclave, so this fails. Hard-coded defaults work, but will break in simulation mode if the extensions aren't present. We'd like to use the normal detection code when outside an enclave, but use hard-coded safe defaults when inside. sgx_cpuid() is unfortunately not an option in this circumstance as we can't execute ocalls from this location in the code. – ac101m Sep 10 '21 at 11:11
  • More generally, an SGX enclave is a restrictive environment. It's not difficult to imagine a situation where behaviour of shared code needs to be altered to accommodate for this. – ac101m Sep 10 '21 at 11:14
  • If there isn't a way to detect, then probably the designers assumed that you shouldn't be sharing code between SGX and non-SGX, so any code running in an enclave implicitly knows that, at least at compile time. Thus the `SGX_HW_SIM` compile-time check suggested by an answer. It's possible the architects of SGX didn't foresee your testing / simulation setup. – Peter Cordes Oct 08 '21 at 02:34
  • The setup we're using isn't solely for testing purposes, we have production use cases that would benefit from being able to perform this query at runtime. As such I don't think this is a reasonable assumption for the designers to have made, assuming of course they made any such assumption. – ac101m Oct 18 '21 at 13:59

1 Answers1

0

You should be able to use #ifdef SGX_HW_SIM. If not, define it as a compile flag.

X99
  • 905
  • 10
  • 24