commit:     767becaac8ccf0a271fc7633fafe635bf8126f3e
Author:     Mike Frysinger <vapier <AT> gentoo <DOT> org>
AuthorDate: Sat Dec 19 06:41:36 2015 +0000
Commit:     Mike Frysinger <vapier <AT> gentoo <DOT> org>
CommitDate: Sat Dec 19 06:41:36 2015 +0000
URL:        https://gitweb.gentoo.org/proj/sandbox.git/commit/?id=767becaa

libsandbox: fix memory alignment

Some targets (like sparc32) have higher alignment requirements for 64-bit
values than size_t (which is 4 bytes on sparc32).  If we happen to return
4 byte aligned memory which is used to hold a 64-bit, we get bus errors.
Use the same algorithm that dlmalloc does.

URL: https://bugs.gentoo.org/565630
Reported-by: Denis Kaganovich <mahatma <AT> eu.by>
Signed-off-by: Mike Frysinger <vapier <AT> gentoo.org>

 libsandbox/memory.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/libsandbox/memory.c b/libsandbox/memory.c
index 5609208..8581128 100644
--- a/libsandbox/memory.c
+++ b/libsandbox/memory.c
@@ -15,6 +15,9 @@
 #include "libsandbox.h"
 #include "sbutil.h"
 
+/* Pick a value to guarantee alignment requirements. #565630 */
+#define MIN_ALIGN (2 * sizeof(void *))
+
 /* Well screw me sideways, someone decided to override mmap() #290249
  * We probably don't need to include the exact sym version ...
  */
@@ -35,14 +38,14 @@ static int sb_munmap(void *addr, size_t length)
 }
 #define munmap sb_munmap
 
-#define SB_MALLOC_TO_MMAP(ptr) ((void*)(((size_t*)ptr) - 1))
-#define SB_MMAP_TO_MALLOC(ptr) ((void*)(((size_t*)ptr) + 1))
+#define SB_MALLOC_TO_MMAP(ptr) ((void*)((uintptr_t)(ptr) - MIN_ALIGN))
+#define SB_MMAP_TO_MALLOC(ptr) ((void*)((uintptr_t)(ptr) + MIN_ALIGN))
 #define SB_MALLOC_TO_SIZE(ptr) (*((size_t*)SB_MALLOC_TO_MMAP(ptr)))
 
 void *malloc(size_t size)
 {
        size_t *ret;
-       size += sizeof(size_t);
+       size += MIN_ALIGN;
        ret = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 
-1, 0);
        if (ret == MAP_FAILED)
                return NULL;

Reply via email to