Skip to content

Commit

Permalink
Added: Remaining W^X fixes for M1 macOS
Browse files Browse the repository at this point in the history
  • Loading branch information
Sewer56 committed Sep 11, 2023
1 parent 30cf711 commit 321feca
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src-rust/src/internal/buffer_allocator_osx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,13 +132,25 @@ fn try_allocate_buffer(
continue;
}

// TODO: M1 W^X
// M1 macOS has strict W^X enforcement where pages are not allowed to be writeable
// and executable at the same time. Therefore, we have to work around this by allocating as RW
// and temporarily changing it on every write.

// This is not safe, but later we'll get a better workaround going.
#[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
const PROT: vm_prot_t = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;

#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
const PROT: vm_prot_t = VM_PROT_READ | VM_PROT_WRITE;

kr = unsafe {
mach_vm_protect(
self_task,
allocated,
settings.size as mach_vm_size_t,
0,
VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE,
PROT,
)
};

Expand Down
4 changes: 4 additions & 0 deletions src-rust/src/structs/internal/locator_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,12 +165,14 @@ impl LocatorItem {
/// This function is safe provided that the caller ensures that the buffer is large enough to hold the data.
/// There is no error thrown if size is insufficient.
pub unsafe fn append_bytes(&mut self, data: &[u8]) -> usize {
disable_write_xor_execute(self.base_address.value as *const u8, data.len());
let address = self.base_address.value + self.position as usize;
let data_len = data.len();

std::ptr::copy_nonoverlapping(data.as_ptr(), address as *mut u8, data_len);
self.position += data_len as u32;

restore_write_xor_execute(self.base_address.value as *const u8, data.len());
address
}

Expand All @@ -197,9 +199,11 @@ impl LocatorItem {
where
T: Copy,
{
disable_write_xor_execute(self.base_address.value as *const u8, data.len());
let address = (self.base_address.value + self.position as usize) as *mut T;
*address = data;
self.position += std::mem::size_of::<T>() as u32;
restore_write_xor_execute(self.base_address.value as *const u8, data.len());
address as usize
}
}
Expand Down

0 comments on commit 321feca

Please sign in to comment.