Skip to content
systemcoding.dev
Security

Insert a speculation barrier with _mm_lfence

Stop speculative reads after a bounds check with _mm_lfence from immintrin.h, the barrier Intel recommends against Spectre variant 1.

1 min read
Summarize in AI

In Spectre variant 1 the CPU predicts that a bounds check will pass, runs the array read with an out-of-range index, and leaves a trace in the cache before it notices the mistake. lfence does not let later instructions start until earlier ones complete, so placing it between the check and the read makes the CPU resolve the branch first. The compiler intrinsic is _mm_lfence.

spec.cc
#include <immintrin.h>
#include <stddef.h>

extern unsigned char table[256];

unsigned char get(size_t idx, size_t len)
{
    if (idx < len) {
        _mm_lfence();
        return table[idx];
    }
    return 0;
}
Shell
gcc -O2 -S spec.c -o - | grep lfence
Text
	lfence

Use it only at the places where an attacker controls the index, because each fence stalls the pipeline and is far slower than a normal compare. Linux uses array_index_nospec, which clamps the index with a mask and costs less than a fence, and Clang offers -mspeculative-load-hardening. A fence protects only the path you place it on, and it does nothing about other variants such as the ones that target indirect branches. See Intel's speculative execution side channel guidance.

Also inHardware
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.