Last active
February 7, 2018 21:43
-
-
Save twoscomplement/1d03dcbcb22efb407b57295c94f67d88 to your computer and use it in GitHub Desktop.
Watch as the OS rewrites my buggy program. [Windows, SetErrorMode, SEM_NOALIGNMENTFAULTEXCEPT]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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