C++17 and C++20 Interesting Features
Last updated
Was this helpful?
Last updated
Was this helpful?
Metaprogramming is very useful when writing polymorphic code that can be used to evade static analysis detections, not only because it permutes the filehash on each compilation, it can be also used for flow graph obfuscation, api hammering among other practical evasion uses.
Consider the following code snippet:
We're using a template function, that accepts two template parameters, size and Fn. Defines a lambda function that pases all outer scope parameters as reference [&] and accepts and index_sequence as parameter.
This lambda function is called immediately, so let's expand the the function, instantiate and unfold it:
Seen this way, the magic resides in the folding expression (((fn(Indexes))), ...);
This is an unary right fold, folding can be intepreted linguistically as reducing a list to a single value, a common use case is checking wheter all of the values in a list are true:
This unary left fold becomes
In this case, of boolean values can be represented as:
In the above case of the lambda function, the comma binary operator is used hich is meant to evaluate the first operator, discard the value and assign the value of the second operator and a right unary unfold would be:
(((fn(5), fn(4)), fn(3), fn(2)))
So evaluation will start backward as it reads in the pseudocode above.
When the source code is compile let's say passing 4 as the size template parameter and using a simple printf function:
Compiler will produce and output the printf function 4 times each
This is actually not a random number generator, but it does generates different numbers at compile time, which might be used for creating complex control flow obfuscation functionality. Use it wisely as it could bloat the heavily the size of your binary.
C++ has an standar MACRO, which is supported by GCC, MSVC and CLANG, which is __TIME__, it will resolve at compilation phase, replacing the macro with the actual timestamp in Y-m-d H:m:s format, it can be used to generate a random 2-12 numbers range using constexpr in C++
This will invoke printf different number of times in each compilation!