I was wondering if something like compile time function encryption is possible and if it's possible how can someone achieve it ? And by "compile time function encryption" I mean encrypting the function code during compile time and later on at runtime decrypt the code when you need to call that function.
Thanks in advance!
Standard C++ does not allow access code as data.
That is,
int f(int);
reinterpret_cast<int*>(&f) = 1;
Is not valid, you cannot access "code" as data. Sure you cannot access to code as data at at compile time too. So you cannot neither encrypt nor decrypt your unction.
Still there are some tools that actually do this. But they rely on implementation-specific behavior at runtime. At compile time they just add additional step, which is usually not known to compiler and happens after compilation by tampering with compiler output.
And something may work in portable C++, at least in theory, it is not what you want, but it is a "compile time function encryption" you're asking for.
If you define some grammar for your functions, like, you can parse, say, const char* function = "(a, b, c) { return a + b * c; }"
, then if you can add constexpr
encrypting function, you'll have function in your program that encrypts at compile time, and can be decrypted before execution.
Sure Standard also does not require that calling a constexpr
function to produce static initialization data indeed happens at compile time, but it is something expected from a good implementation.