Skip to content

Instantly share code, notes, and snippets.

@erikcorry
Created November 17, 2025 17:34
Show Gist options
  • Select an option

  • Save erikcorry/2062db0cd8a0cf140863c747397239cf to your computer and use it in GitHub Desktop.

Select an option

Save erikcorry/2062db0cd8a0cf140863c747397239cf to your computer and use it in GitHub Desktop.
AVX load instructions can be made to ignore segfaults on unused data
#include <immintrin.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/mman.h>
// Compile with clang++ -g -mavx512bw -mavx512f -o mask-test mask-test.cc
int main() {
char* addr = (char*)mmap(0, 8192, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
int result = mprotect(addr + 4096, 4096, PROT_NONE);
if (result != 0) abort();
__mmask32 mask = 0xFFFFFFFFULL;
for (int i = 0; i < 64; i += 2) {
// This address appears to go over the end of the page into the
// protected page when i != 0 and we load a 512 bit (64 byte) value.
char* bad = addr + 4096 - 64 + i;
// Load 512 bits into register, but use the mask to zero some of the
// 16 bit words.
__m512i input = _mm512_maskz_loadu_epi16(mask, bad);
// Make sure the optimizer doesn't remove the load instruction.
uint16_t values[32];
_mm512_store_si512((__m512i*)values, input);
printf("Values[31] = 0x%04x\n", values[31]);
// For the next iteration we add a bit of masking which will both zero the
// value in the register, but also suppresses faults!
mask >>= 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment