[PATCH 1/2] malloc: implement malloc_usable_size()

Sascha Hauer s.hauer at pengutronix.de
Tue Aug 6 03:54:28 PDT 2024


malloc_usable_size() is a standard libc function. Implement it for the
barebox allocators, dlmalloc and tlsf_malloc.

Signed-off-by: Sascha Hauer <s.hauer at pengutronix.de>
---
 common/dlmalloc.c    | 12 ++++++++++++
 common/tlsf_malloc.c | 11 +++++++++++
 include/malloc.h     |  1 +
 3 files changed, 24 insertions(+)

diff --git a/common/dlmalloc.c b/common/dlmalloc.c
index c41487d54b..99f666aada 100644
--- a/common/dlmalloc.c
+++ b/common/dlmalloc.c
@@ -1431,6 +1431,18 @@ void free(void *mem)
 		frontlink(p, sz, idx, bck, fwd);
 }
 
+size_t malloc_usable_size(void *mem)
+{
+	mchunkptr p;
+	size_t size;
+
+	if (!mem)
+		return 0;
+
+	p = mem2chunk(mem);
+	return chunksize(p);
+}
+
 /*
   Realloc algorithm:
 
diff --git a/common/tlsf_malloc.c b/common/tlsf_malloc.c
index 981f09de41..f07ef5645b 100644
--- a/common/tlsf_malloc.c
+++ b/common/tlsf_malloc.c
@@ -38,6 +38,17 @@ void free(void *mem)
 }
 EXPORT_SYMBOL(free);
 
+size_t malloc_usable_size(void *mem)
+{
+	size_t size;
+
+	if (!mem)
+		return 0;
+
+	return tlsf_block_size(mem);
+}
+EXPORT_SYMBOL(malloc_usable_size);
+
 void *realloc(void *oldmem, size_t bytes)
 {
 	void *mem = tlsf_realloc(tlsf_mem_pool, oldmem, bytes);
diff --git a/include/malloc.h b/include/malloc.h
index d63853b91e..5cdff0a4f9 100644
--- a/include/malloc.h
+++ b/include/malloc.h
@@ -6,6 +6,7 @@
 #include <types.h>
 
 void *malloc(size_t) __alloc_size(1);
+size_t malloc_usable_size(void *);
 void free(void *);
 void *realloc(void *, size_t) __realloc_size(2);
 void *memalign(size_t, size_t) __alloc_size(2);
-- 
2.39.2




More information about the barebox mailing list