liveBook · Manning

Speculative execution

As explained in Hacking Cryptography

Speculative execution is processor execution of predicted instruction paths before the corresponding control-flow decisions are resolved.

Speculative execution predicts a branch and continues executing along that path before the decision is resolved. Correct predictions improve performance; wrong predictions flush pipelines and caches. When control flow depends on secrets, these effects can expose timing information through side-channel analysis, even without electronic probes. section 10.5

Threshold-dependent summation

A loop sums array elements only when array[i] exceeds 500. Predictable data lets the processor follow the branch efficiently, while unpredictable data makes the branch costly. A branchless version uses comparison and conditional-move instructions instead, illustrating a defensive alternative for sensitive control flow. section 10.5

Reduce exposure from secret-dependent control flow by:

  • Avoid branching and iterating on sensitive data whenever practical. section 10.5
Listing 10.3 branch-predict.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define ARRAY_SIZE 100000000 
#define THRESHOLD 500

int compare(const void *a, const void *b) {
    return ( *(int*)a - *(int*)b );
}

void fill_array(int *array, size_t size) {
    for(size_t i = 0; i < size; ++i) {
        array[i] = rand() % 1000;
    }
}

long long sum_array(int *array, size_t size, int threshold) {
    long long sum = 0;
    for(size_t i = 0; i < size; ++i) {
        if(array[i] > threshold) {  #1
            sum += array[i];
        }
    }
    return sum;
}

Inspect the ordinary threshold branch that creates predictable or unpredictable processor control flow. section 10.5

How Hacking Cryptography covers it

How deep it goes
Explains prediction, pipeline flushing, cache effects, and a C performance comparison, but stops short of a complete attack trace.
Examples
Uses a 100-million-element integer array, a threshold branch, branchless conditional move, and measured sorted versus unsorted timings.
What it assumes
Assumes awareness of timing attacks and secret-dependent branching while explaining speculative execution through processor pipelines and demand prediction.
What you can do after
Apply branchless comparisons and avoid secret-dependent branching when implementing timing-sensitive cryptographic code.
How it connects
Ties speculative execution to branch prediction, timing attacks, side-channel analysis, caches, and constant-time cryptographic implementation.

Also explained in

Compare how 2 books explain speculative execution →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Hacking Cryptography. The section links point to the parts of the book it draws on.