TL;DR
This guide shows you how to use Intel’s Memory Protection Extensions (MPX) for bounds checking in C/C++. It covers compilation, linking, and a simple example of protecting an array access. MPX adds hardware support to detect buffer overflows and underflows at runtime.
Prerequisites
- A processor that supports Intel MPX (e.g., Skylake-SP or newer).
- A compiler that supports MPX (GCC 6+ or Intel Compiler 17+).
- An operating system that supports MPX (Linux, Windows).
1. Compilation Flags
You need to enable MPX during compilation. Use the following flags with GCC or Clang:
gcc -mpopcnt -mbound-checks your_code.c -o your_program
With Intel Compiler, use these flags:
icpc -mpopcnt -qbounds-check your_code.c -o your_program
- -mpopcnt: Enables population count instructions, required by MPX.
- -mbound-checks (GCC) / -qbounds-check (Intel Compiler): Activates bounds checking.
2. Understanding Bounds Checking
MPX uses a set of registers to store the base address and size of protected memory regions. When you access memory within a protected region, MPX checks if the access is valid. If it’s not, a signal (SIGILL on Linux) is raised.
3. Example: Protecting an Array Access
Let’s protect an array access using MPX:
#include
#include
int main() {
int arr[10];
int *protected_arr = arr;
size_t protected_size = sizeof(arr);
// Use MPX to protect the array access.
for (int i = 0; i <= 10; ++i) {
if (i < 10) {
protected_arr[i] = i;
} else {
printf("Accessing out of bounds!");
}
}
for (int i = 0; i < 10; ++i) {
printf("%d ", arr[i]);
}
printf("n");
return 0;
}
Compile this code with the flags mentioned in step 1:
gcc -mpopcnt -mbound-checks example.c -o example
4. Running the Program
When you run the program, it will likely crash when accessing `protected_arr[10]` because that is outside of the bounds defined by `protected_size`. The operating system will terminate the process with a SIGILL signal.
5. Linking Considerations
Ensure your linker supports MPX. Most modern linkers do, but if you encounter issues, check your linker documentation for specific flags or options related to memory protection features.
6. Limitations
- Performance Overhead: MPX adds runtime overhead due to the bounds checks.
- Code Changes: You need to modify your code to use MPX-specific constructs (e.g., declaring protected regions).
- Compiler Support: Not all compilers fully support MPX.

