Created
May 5, 2021 08:27
-
-
Save eloj/d7d9f3b04cb17aac22d0f2fff784ebe9 to your computer and use it in GitHub Desktop.
Using IA32/AMD64 Alignment Check-bit to error on unaligned access
This file contains 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
/* | |
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would be nicer if you could make that into a function inside a
.h
file...