Elffuss BraidHub

kikocis/kleidiai public

main · 1.9 KiBRawPermalink
1//
2// SPDX-FileCopyrightText: Copyright 2025-2026 Arm Limited and/or its affiliates <open-source-office@arm.com>
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6
7#ifndef __APPLE__
8#include <malloc.h>
9#endif
10
11//#undef VICIOUS_PAGE_SIZE
12
13#include <stdio.h>
14#include <stdlib.h>
15
16#ifdef VICIOUS_PAGE_SIZE
17#include <sys/mman.h>
18#endif
19
20#include "utils.hpp"
21
22void *allocate_aligned_memory(size_t alignment, size_t size) {
23#ifdef __APPLE__
24 size_t real_size = roundup(size, alignment);
25
26 void *r=aligned_alloc(alignment, real_size);
27#else
28#ifdef VICIOUS_PAGE_SIZE
29 // "Vicious" allocaton policy - round the provided size up to the next page, and provide a pointer offset such
30 // that overreading or overwriting will stray into invalid memory.
31
32 // Some kernels deliberately overread by up to 7 bytes.
33 size += 7;
34
35 size_t aligned_size = ((size + VICIOUS_PAGE_SIZE-1) / VICIOUS_PAGE_SIZE) * VICIOUS_PAGE_SIZE;
36 // Track allocations - we need to provide our own addresses to make sure there are gaps.
37 static size_t base_offset=0;
38
39 void *aligned_ptr = mmap((void *)(0xf00000000000 + base_offset), aligned_size, PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
40 void *r;
41
42 base_offset += (aligned_size + VICIOUS_PAGE_SIZE);
43
44 size_t offset = size % VICIOUS_PAGE_SIZE;
45
46 if (offset) {
47 r = aligned_ptr + (VICIOUS_PAGE_SIZE - offset);
48 printf("Allocating %zu bytes, offset=%zu, pointer=%p\n", size, offset, r);
49 } else {
50 r = aligned_ptr;
51 printf("Size already aligned: %zu bytes, pointer=%p\n", size, r);
52 }
53#else
54 void *r=memalign(alignment, size);
55#endif // VICIOUS_PAGE_SIZE
56#endif // ! __APPLE__
57
58 if (r == nullptr) {
59 printf("Memory allocation error.\n");
60 exit(1);
61 }
62
63 return r;
64}
65
66void free_aligned_memory(void *ptr) {
67#ifdef VICIOUS_PAGE_SIZE
68 // Leak for now - would need a table to do this properly.
69#else
70 free(ptr);
71#endif
72}