After reading about Spectre & Meltdown vulnerabilities, I learned about speculative execution.
Given the following simple C++ program:
#include <stdlib.h>
void mallocBranch(int i) {
if (i < 500) {
malloc(i);
}
}
int main(int argc, char** argv){
for (i := 0; i < 5000; i++) {
mallocBranch(1);
}
mallocBranch(500000000);
return 0;
}
- I am assuming that the
malloccalls are not optimized out by the compiler.
Q: What happens when mallocBranch(500000000) is called? Will the CPU look at the branch-prediction cache and see that past calls to if (i < 500) succeeded and speculatively execute the branch with malloc(500000000)? Would the number of branches in malloc overwrite the entire contents of the branch-prediction cache each time? If malloc(500000000) is actually speculatively executed, would 500million bytes of memory be allocated to the process, if only temporarily?
ifwill not happen. CPU is able to execute instruction out of order (as listed in memory) as long as it can prove that instruction do not depend on results of other. If branch prediction fails all predictions are doped and everything is evaluated again from scratch.mallocBranch(500000000);is a noop. The resulting program has no branch on that call ("I am assuming that the malloc calls are not optimized out by the compiler." does not change that, because there was no call tomallocin the first place on that call)malloc()won't allocate anyway, because you probably don't have the memorymmap()ed yet. So even if speculative execution runs ahead far enough to find out that fulfilling the allocation request requiresmmap(), that's a syscall, which will have speculative execution mitigations. Even if it doesn't,mmap()will need to modify MMU state, which will require I/O and memory barriers, limiting speculative execution again.