1

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 malloc calls 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?

3
  • 1
    You have completely misunderstood how this works. Branch prediction doesn't mean that evaluation of if will 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. Commented Jun 30, 2021 at 17:13
  • as this is all in a single translation unit the compiler knows all that is needed to know that 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 to malloc in the first place on that call) Commented Jun 30, 2021 at 18:03
  • Assuming that the branch predictor is simple enough to be fooled by this, malloc() won't allocate anyway, because you probably don't have the memory mmap() ed yet. So even if speculative execution runs ahead far enough to find out that fulfilling the allocation request requires mmap(), 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. Commented Jun 30, 2021 at 21:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.