Skip to content

Instantly share code, notes, and snippets.

@HaskellZhangSong
Last active April 22, 2025 11:30
Show Gist options
  • Save HaskellZhangSong/dd058c18f62d900f265f21cbe1a0563e to your computer and use it in GitHub Desktop.
Save HaskellZhangSong/dd058c18f62d900f265f21cbe1a0563e to your computer and use it in GitHub Desktop.
test MAP_32BIT
#include <iostream>
#include <sys/mman.h> // For mmap, munmap, MAP_FAILED, PROT_*, MAP_*
#include <unistd.h> // For sysconf, _SC_PAGESIZE
#include <cstring> // For strerror, memset
#include <cerrno> // For errno
#include <cstdint> // For uintptr_t
int main() {
size_t size = 256 * 1024; // Allocate 4KB, typically one page
#ifdef MAP_32BIT
std::cout << "MAP_32BIT is defined. Using it." << std::endl;
int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_32BIT;
#else
std::cout << "MAP_32BIT is NOT defined. Allocation might be outside 32-bit range." << std::endl;
int flags = MAP_PRIVATE | MAP_ANONYMOUS; // Fallback flags
#endif
std::cout << "Attempting to allocate " << size << " bytes using mmap..." << std::endl;
// Attempt to map memory
void* addr = mmap(NULL, // Let the kernel choose the address
size, // Size of the mapping
PROT_READ | PROT_WRITE,// Memory protection: readable and writable
flags, // Flags (potentially including MAP_32BIT)
-1, // File descriptor (none for anonymous)
0); // Offset (0 for anonymous)
if (addr == MAP_FAILED) {
std::cerr << "mmap failed: " << strerror(errno) << std::endl;
return 1;
}
std::cout << "Memory successfully allocated at address: " << addr << std::endl;
std::cout << "Address as integer: 0x" << std::hex << reinterpret_cast<uintptr_t>(addr) << std::dec << std::endl;
// Verify if the address is indeed within the 32-bit range (should be guaranteed by MAP_32BIT if successful)
if (reinterpret_cast<uintptr_t>(addr) > 0xFFFFFFFF) {
std::cerr << "Warning: Allocated address is outside the 32-bit range despite using MAP_32BIT!" << std::endl;
// This case should ideally not happen if MAP_32BIT works as expected.
} else {
std::cout << "Address is within the 32-bit range." << std::endl;
}
// Use the memory (example: zero it out)
std::cout << "Zeroing allocated memory..." << std::endl;
memset(addr, 0, size);
std::cout << "Memory zeroed." << std::endl;
// Unmap the memory
if (munmap(addr, size) == -1) {
std::cerr << "munmap failed: " << strerror(errno) << std::endl;
return 1;
}
std::cout << "Memory unmapped successfully." << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment