Skip to content

Instantly share code, notes, and snippets.

@dfyz
Last active May 1, 2023 22:40
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 dfyz/556a0222ef0dd931fd39ba77749a8711 to your computer and use it in GitHub Desktop.
Save dfyz/556a0222ef0dd931fd39ba77749a8711 to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdint.h>
#include <err.h>
#include <sys/mman.h>
#include <sys/random.h>
#include <unistd.h>
void* get_random_ptr() {
void* res;
if (getrandom(&res, sizeof(res), 0) != sizeof(res)) {
err(1, "failed to get random bytes");
}
return res;
}
void* mask_ptr(void* x) {
return (void*)((uintptr_t)x & 0x7ffffffff000ULL);
}
int main() {
void* raw_addr = get_random_ptr();
void* requested_addr = mask_ptr(raw_addr);
printf("raw: %p\n", raw_addr);
printf("req: %p\n", requested_addr);
void* real_addr = mmap(
requested_addr,
1 << 16,
PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED,
-1,
0);
if (real_addr == MAP_FAILED) {
err(1, "mmap() failed");
}
printf("got: %p\n", real_addr);
return 0;
}
> lscpu | grep 'Model name'
Model name: Cortex-A53
> llvm-objdump --disassemble-symbols=mask_ptr --no-leading-addr ./mask_ptr
<mask_ptr>:
00 8c 74 92 and x0, x0, #0xfffffffff000
c0 03 5f d6 ret
> gcc -O2 -std=c17 -o mask_ptr mask_ptr.c && ./mask_ptr
raw: 0xc286004d2cb683e
req: 0x6004d2cb6000
got: 0x6004d2cb6000
> rg 'uarch' /proc/cpuinfo | sort -u
uarch : sifive,u74-mc
> llvm-objdump --disassemble-symbols=mask_ptr --no-leading-addr ./mask_ptr
<mask_ptr>:
b7 07 00 e0 lui a5, 917504
c5 83 srli a5, a5, 17
7d 8d and a0, a0, a5
82 80 ret
user@starfive /home/user/mask_ptr> gcc -O2 -std=c17 -o mask_ptr mask_ptr.c && ./mask_ptr
raw: 0xdf3bc2042627c2f7
req: 0x42042627c000
mask_ptr: mmap() failed: Cannot allocate memory
> rg 'model name' /proc/cpuinfo | sort -u
model name : 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
> llvm-objdump --disassemble-symbols=mask_ptr --no-leading-addr --x86-asm-syntax=intel ./mask_ptr
<mask_ptr>:
48 b8 00 f0 ff ff ff 7f 00 00 movabs rax, 0x7ffffffff000
48 21 f8 and rax, rdi
c3 ret
> gcc -O2 -std=c17 -o mask_ptr mask_ptr.c && ./mask_ptr
raw: 0x595cd8dfb43916b7
req: 0x58dfb4391000
got: 0x58dfb4391000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment