Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

linux: make use of mseal(2) #242

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions h_malloc.c
Original file line number Diff line number Diff line change
Expand Up @@ -1285,7 +1285,12 @@ COLD static void init_slow_path(void) {

atomic_store_explicit(&ro.slab_region_end, slab_region_end, memory_order_release);

#if defined(__ANDROID__) && defined(HAS_ARM_MTE)
/* Do not seal to support disabling memory tagging */
if (unlikely(memory_protect_ro(&ro, sizeof(ro)))) {
#else
if (unlikely(memory_protect_seal(&ro, sizeof(ro)))) {
#endif
fatal_error("failed to protect allocator data");
}
memory_set_name(&ro, sizeof(ro), "malloc read-only after init");
Expand Down
18 changes: 18 additions & 0 deletions memory.c
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#include <errno.h>
#include <unistd.h>

#include <sys/mman.h>
#include <sys/syscall.h>

#ifdef LABEL_MEMORY
#include <sys/prctl.h>
Expand Down Expand Up @@ -83,6 +85,22 @@ bool memory_protect_rw_metadata(void *ptr, size_t size) {
return memory_protect_prot(ptr, size, PROT_READ|PROT_WRITE, get_metadata_key());
}

COLD bool memory_protect_seal(void *ptr, size_t size) {
#if defined(__linux__) && defined(__NR_mseal)
/* supported since Linux 6.10 */
int ret = syscall(__NR_mseal, ptr, size, 0);
if (ret == 0)
return false;
if (unlikely(errno == ENOMEM))
return true;
if (errno == ENOSYS)
return memory_protect_ro(ptr, size);
fatal_error("non-ENOMEM and non-ENOSYS mseal failure");
#else
return memory_protect_ro(ptr, size);
#endif
}

#ifdef HAVE_COMPATIBLE_MREMAP
bool memory_remap(void *old, size_t old_size, size_t new_size) {
void *ptr = mremap(old, old_size, new_size, 0);
Expand Down
1 change: 1 addition & 0 deletions memory.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ bool memory_unmap(void *ptr, size_t size);
bool memory_protect_ro(void *ptr, size_t size);
bool memory_protect_rw(void *ptr, size_t size);
bool memory_protect_rw_metadata(void *ptr, size_t size);
bool memory_protect_seal(void *ptr, size_t size);
#ifdef HAVE_COMPATIBLE_MREMAP
bool memory_remap(void *old, size_t old_size, size_t new_size);
bool memory_remap_fixed(void *old, size_t old_size, void *new, size_t new_size);
Expand Down