Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Watch as the OS rewrites my buggy program. [Windows, SetErrorMode, SEM_NOALIGNMENTFAULTEXCEPT]
/*
Watch as the OS rewrites my buggy program.
Compile with:
cl //Ox movoops.cpp
Output:
0f 28 01
xxxxxxxxxxxxxxx1
0f 10 01
*/
#include <immintrin.h>
#include <stdio.h>
#include <windows.h>
__declspec(noinline) __m128 f(char* a) {
return _mm_load_ps((float*)a);
}
int main()
{
// Dear OS, please clean up my mess.
// "SEM_NOALIGNMENTFAULTEXCEPT: The system automatically fixes memory alignment
// faults and makes them invisible to the application."
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621(v=vs.85).aspx
SetErrorMode(SEM_NOALIGNMENTFAULTEXCEPT);
// Scratch space for unaligned operation
__m128 m[2] = { 0 };
// Print the first three bytes of f():
// movaps x, m
char* b = (char*)&f;
printf("%02x %02x %02x\n", b[0], b[1], b[2]);
// Unalign that address
char* up = (char*)m+1;
// Print the pointer value - observe its unalignedness
printf("%p\n", up);
// Call the function with the unaligned pointer
m[1] = f(up);
// Print the first three bytes of f() again. Observe how they have changed:
// movups x, m
printf("%02x %02x %02x\n", b[0], b[1], b[2]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment