Skip to content

Commit 18cb3ed

Browse files
committed
std: Use memalign, not posix_memalign, on Android
We've gotten requests to move our Android support as far back as API level 9 where unfortunately the `posix_memalign` API wasn't implemented yet. Thankfully, however, the `memalign` API was and it appears to be usable with `free` on the Android platform (see comments included in commit). This should help fix some of the last few test failures when compiling against API level 9.
1 parent caa6aae commit 18cb3ed

File tree

1 file changed

+34
-7
lines changed

1 file changed

+34
-7
lines changed

src/liballoc_system/lib.rs

+34-7
Original file line numberDiff line numberDiff line change
@@ -80,13 +80,40 @@ mod imp {
8080
if align <= MIN_ALIGN {
8181
libc::malloc(size as libc::size_t) as *mut u8
8282
} else {
83-
let mut out = ptr::null_mut();
84-
let ret = libc::posix_memalign(&mut out, align as libc::size_t, size as libc::size_t);
85-
if ret != 0 {
86-
ptr::null_mut()
87-
} else {
88-
out as *mut u8
89-
}
83+
aligned_malloc(size, align)
84+
}
85+
}
86+
87+
#[cfg(target_os = "android")]
88+
unsafe fn aligned_malloc(size: usize, align: usize) -> *mut u8 {
89+
// On android we currently target API level 9 which unfortunately
90+
// doesn't have the `posix_memalign` API used below. Instead we use
91+
// `memalign`, but this unfortunately has the property on some systems
92+
// where the memory returned cannot be deallocated by `free`!
93+
//
94+
// Upon closer inspection, however, this appears to work just fine with
95+
// Android, so for this platform we should be fine to call `memalign`
96+
// (which is present in API level 9). Some helpful references could
97+
// possibly be chromium using memalign [1], attempts at documenting that
98+
// memalign + free is ok [2] [3], or the current source of chromium
99+
// which still uses memalign on android [4].
100+
//
101+
// [1]: https://codereview.chromium.org/10796020/
102+
// [2]: https://code.google.com/p/android/issues/detail?id=35391
103+
// [3]: https://bugs.chromium.org/p/chromium/issues/detail?id=138579
104+
// [4]: https://chromium.googlesource.com/chromium/src/base/+/master/
105+
// /memory/aligned_memory.cc
106+
libc::memalign(align as libc::size_t, size as libc::size_t) as *mut u8
107+
}
108+
109+
#[cfg(not(target_os = "android"))]
110+
unsafe fn aligned_malloc(size: usize, align: usize) -> *mut u8 {
111+
let mut out = ptr::null_mut();
112+
let ret = libc::posix_memalign(&mut out, align as libc::size_t, size as libc::size_t);
113+
if ret != 0 {
114+
ptr::null_mut()
115+
} else {
116+
out as *mut u8
90117
}
91118
}
92119

0 commit comments

Comments
 (0)