Skip to content

Instantly share code, notes, and snippets.

@eloj
Created May 5, 2021 08:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eloj/d7d9f3b04cb17aac22d0f2fff784ebe9 to your computer and use it in GitHub Desktop.
Save eloj/d7d9f3b04cb17aac22d0f2fff784ebe9 to your computer and use it in GitHub Desktop.
Using IA32/AMD64 Alignment Check-bit to error on unaligned access
/*
Code not originally by me.
OS must allow changing the status bit (linux does so far)
*/
#include <stdlib.h>
int main(int argc, char **argv)
{
int *iptr;
char *cptr;
#if 1
#if defined(__GNUC__)
# if defined(__i386__)
/* Enable Alignment Checking on x86 */
__asm__("pushf\norl $0x40000,(%esp)\npopf");
# elif defined(__x86_64__)
/* Enable Alignment Checking on x86_64 */
__asm__("pushf\norl $0x40000,(%rsp)\npopf");
# endif
#endif
#endif
/* malloc() always provides aligned memory */
cptr = malloc(sizeof(int) + 1);
/* Increment the pointer by one, making it misaligned */
iptr = (int *) ++cptr;
/* Dereference it as an int pointer, causing an unaligned access */
*iptr = 42;
return 0;
}
@eyalroz
Copy link

eyalroz commented May 6, 2021

Would be nicer if you could make that into a function inside a .h file...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment