summaryrefslogtreecommitdiff
path: root/lib/libc/stdlib/aligned_alloc.c
diff options
context:
space:
mode:
authorKacper <kacper@mail.openlinux.dev>2025-12-07 20:10:31 +0100
committerKacper <kacper@mail.openlinux.dev>2025-12-07 20:10:31 +0100
commitfc00c656c96528112d05cf0edf8631bd5eaea446 (patch)
treea6e0e6c588191a8bd1c64afc3b7a258e3e66c236 /lib/libc/stdlib/aligned_alloc.c
Add build system scaffolding and libc headers
Diffstat (limited to 'lib/libc/stdlib/aligned_alloc.c')
-rw-r--r--lib/libc/stdlib/aligned_alloc.c39
1 files changed, 39 insertions, 0 deletions
diff --git a/lib/libc/stdlib/aligned_alloc.c b/lib/libc/stdlib/aligned_alloc.c
new file mode 100644
index 00000000..f978dfa9
--- /dev/null
+++ b/lib/libc/stdlib/aligned_alloc.c
@@ -0,0 +1,39 @@
+#include <errno.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <sys/mman.h>
+#include <unistd.h>
+
+void *aligned_alloc(size_t alignment, size_t size)
+{
+ if (alignment == 0 || (alignment & (alignment - 1)) != 0) {
+ errno = EINVAL;
+ return NULL;
+ }
+
+ if (size % alignment != 0) {
+ errno = EINVAL;
+ return NULL;
+ }
+
+ if (size == 0) {
+ return NULL;
+ }
+
+ size_t total_size = size + alignment - 1 + sizeof(void *);
+
+ void *raw_ptr = malloc(total_size);
+ if (raw_ptr == NULL) {
+ errno = ENOMEM;
+ return NULL;
+ }
+
+ uintptr_t raw_addr = (uintptr_t)raw_ptr;
+ uintptr_t aligned_addr = (raw_addr + sizeof(void *) + alignment - 1) &
+ ~(alignment - 1);
+
+ void **orig_ptr_slot = (void **)(aligned_addr - sizeof(void *));
+ *orig_ptr_slot = raw_ptr;
+
+ return (void *)aligned_addr;
+}