From 4702aaa37ce8c6c007c46a5144a62a93159bc1ae Mon Sep 17 00:00:00 2001 From: oiupoyt Date: Tue, 29 Sep 2026 17:07:14 +0530 Subject: [PATCH] feat(core): implement Bionic TLS block allocation and TCB self-pointer setup --- crates/molotov-core/src/lib.rs | 1 + crates/molotov-core/src/tls.rs | 41 +++++++++++++++++++++++++++ crates/molotov-core/tests/tls_test.rs | 9 ++++++ 3 files changed, 51 insertions(+) create mode 100644 crates/molotov-core/src/tls.rs create mode 100644 crates/molotov-core/tests/tls_test.rs diff --git a/crates/molotov-core/src/lib.rs b/crates/molotov-core/src/lib.rs index 51bc3ae..cdf6125 100644 --- a/crates/molotov-core/src/lib.rs +++ b/crates/molotov-core/src/lib.rs @@ -4,4 +4,5 @@ pub mod elf; pub mod mmap; pub mod reloc; pub mod symbols; +pub mod tls; pub mod trampoline; diff --git a/crates/molotov-core/src/tls.rs b/crates/molotov-core/src/tls.rs new file mode 100644 index 0000000..0179472 --- /dev/null +++ b/crates/molotov-core/src/tls.rs @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use std::alloc::{alloc_zeroed, dealloc, Layout}; + +pub const BIONIC_TLS_SLOTS: usize = 128; + +pub struct BionicTls { + ptr: *mut u64, + layout: Layout, +} + +impl BionicTls { + pub fn allocate() -> Result { + let layout = Layout::from_size_align(BIONIC_TLS_SLOTS * std::mem::size_of::(), 64) + .map_err(|e| e.to_string())?; + + let ptr = unsafe { alloc_zeroed(layout) as *mut u64 }; + if ptr.is_null() { + Err("Failed to allocate memory for Bionic TLS".to_string()) + } else { + // Android x86_64: slot 0 points to the thread control block itself + unsafe { + *ptr = ptr as u64; + } + Ok(Self { ptr, layout }) + } + } + + pub fn tcb_ptr(&self) -> *mut u64 { + self.ptr + } +} + +impl Drop for BionicTls { + fn drop(&mut self) { + if !self.ptr.is_null() { + unsafe { + dealloc(self.ptr as *mut u8, self.layout); + } + } + } +} diff --git a/crates/molotov-core/tests/tls_test.rs b/crates/molotov-core/tests/tls_test.rs new file mode 100644 index 0000000..a789f2d --- /dev/null +++ b/crates/molotov-core/tests/tls_test.rs @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +use molotov_core::tls::BionicTls; + +#[test] +fn test_bionic_tls_allocation() { + let tls = BionicTls::allocate().expect("Bionic TLS block should allocate cleanly"); + assert!(!tls.tcb_ptr().is_null()); + assert_eq!(tls.tcb_ptr() as usize % 64, 0, "TLS pointer must be 64-byte aligned"); +}