Skip to content

Commit

Permalink
Cleanup.
Browse files Browse the repository at this point in the history
  • Loading branch information
dbittman committed Nov 29, 2024
1 parent 60c21e4 commit d54d4c2
Show file tree
Hide file tree
Showing 22 changed files with 93 additions and 134 deletions.
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/bin/bootstrap/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ fn start_runtime(_runtime_monitor: ObjID, _runtime_library: ObjID) -> ! {
extern crate twizzler_minruntime;
fn main() {
let subscriber = FmtSubscriber::builder()
.with_max_level(Level::DEBUG)
.with_max_level(Level::INFO)
.finish();

tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
Expand Down
8 changes: 4 additions & 4 deletions src/runtime/dynlink/src/arch/x86_64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ use crate::tls::{Tcb, TlsRegion};
pub(crate) const MINIMUM_TLS_ALIGNMENT: usize = 32;

pub use elf::abi::{
R_X86_64_64 as REL_SYMBOLIC, R_X86_64_COPY as REL_COPY, R_X86_64_DTPMOD64 as REL_DTPMOD,
R_X86_64_DTPOFF64 as REL_DTPOFF, R_X86_64_GLOB_DAT as REL_GOT, R_X86_64_JUMP_SLOT as REL_PLT,
R_X86_64_RELATIVE as REL_RELATIVE, R_X86_64_TPOFF64 as REL_TPOFF,
R_X86_64_64 as REL_SYMBOLIC, R_X86_64_DTPMOD64 as REL_DTPMOD, R_X86_64_DTPOFF64 as REL_DTPOFF,
R_X86_64_GLOB_DAT as REL_GOT, R_X86_64_JUMP_SLOT as REL_PLT, R_X86_64_RELATIVE as REL_RELATIVE,
R_X86_64_TPOFF64 as REL_TPOFF,
};

/// Get a pointer to the current thread control block, using the thread pointer.
Expand All @@ -22,7 +22,7 @@ impl TlsRegion {
/// Get a pointer to the thread control block for this TLS region.
///
/// # Safety
/// The TCB must actually contain runtime data of type T, and be initialized.
/// The TCB must actually contain runtime data of type T, and be initialized.
pub unsafe fn get_thread_control_block<T>(&self) -> *mut Tcb<T> {
self.get_thread_pointer_value() as *mut _
}
Expand Down
3 changes: 1 addition & 2 deletions src/runtime/dynlink/src/compartment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use std::{

use petgraph::stable_graph::NodeIndex;
use talc::{ErrOnOom, Talc};
use tracing::info;

use crate::{context::NewCompartmentFlags, engines::Backing, library::LibraryId, tls::TlsInfo};

Expand Down Expand Up @@ -87,6 +86,6 @@ impl Debug for Compartment {

impl Drop for Compartment {
fn drop(&mut self) {
info!("dynlink: drop compartment {:?}", self);
tracing::debug!("dynlink: drop compartment {:?}", self);
}
}
2 changes: 1 addition & 1 deletion src/runtime/dynlink/src/context.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Management of global context.
use std::{collections::HashMap, fmt::Display, ops::Index};
use std::{collections::HashMap, fmt::Display};

use petgraph::stable_graph::{NodeIndex, StableDiGraph};
use stable_vec::StableVec;
Expand Down
3 changes: 1 addition & 2 deletions src/runtime/dynlink/src/library.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use std::fmt::{Debug, Display};

use elf::{
abi::{DT_FLAGS_1, PT_PHDR, PT_TLS, STB_WEAK},
dynamic::Dyn,
endian::NativeEndian,
segment::{Elf64_Phdr, ProgramHeader},
ParseError,
Expand Down Expand Up @@ -351,7 +350,7 @@ impl Debug for Library {

impl Drop for Library {
fn drop(&mut self) {
tracing::info!("dynlink: drop library: {:?}", self);
tracing::debug!("dynlink: drop library: {:?}", self);
}
}

Expand Down
65 changes: 4 additions & 61 deletions src/runtime/monitor/src/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,70 +19,13 @@ impl InitDynlinkContext {
}

extern "C-unwind" {
fn __is_monitor() -> Option<*mut c_void>;
// Defined by the runtime. Returns a pointer to the runtime init info struct if the runtime is
// in monitor mode, otherwise returns null.
fn __is_monitor() -> *mut c_void;
}
pub(crate) fn bootstrap_dynlink_context() -> Option<InitDynlinkContext> {
let info = unsafe {
__is_monitor()
.unwrap()
.cast::<RuntimeInitInfo>()
.as_mut()
.unwrap()
};
let info = unsafe { __is_monitor().cast::<RuntimeInitInfo>().as_mut().unwrap() };
let ctx = info.ctx as *mut Context;

Some(InitDynlinkContext { ctx })
}

/*
#[no_mangle]
pub unsafe extern "C" fn monitor_entry_from_bootstrap2(rtinfo_ptr: *const RuntimeInfo) {
let rtinfo = unsafe { rtinfo_ptr.as_ref().unwrap() };
if rtinfo.kind != RUNTIME_INIT_MONITOR {
twizzler_abi::klog_println!("cannot initialize monitor without monitor runtime init info");
twizzler_rt_abi::core::twz_rt_abort();
}
let rt_init_info_ptr = rtinfo.init_info.monitor.cast();
unsafe {
RTINFO = Some(rt_init_info_ptr);
twizzler_rt_abi::core::rt0::rust_entry(rtinfo_ptr)
}
}
/*
#[cfg(target_arch = "x86_64")]
#[naked]
#[no_mangle]
pub unsafe extern "C" fn monitor_entry_from_bootstrap(p: *const RuntimeInfo) -> ! {
core::arch::naked_asm!("jmp monitor_entry_from_bootstrap2")
}*/
#[cfg(target_arch = "x86_64")]
core::arch::global_asm!("monitor_entry_from_bootstrap: jmp monitor_entry_from_bootstrap2");
*/
/*
#[allow(improper_ctypes)]
extern "C" {
fn twizzler_call_lang_start(
main: fn(),
argc: isize,
argv: *const *const u8,
sigpipe: u8,
) -> isize;
}
#[cfg(not(test))]
#[no_mangle]
pub extern "C" fn main(argc: i32, argv: *const *const u8) -> i32 {
//TODO: sigpipe?
unsafe { twizzler_call_lang_start(crate::main, argc as isize, argv, 0) as i32 }
}
// TODO: we should probably get this for real.
#[cfg(not(test))]
#[no_mangle]
pub extern "C" fn _init() {}
*/
4 changes: 2 additions & 2 deletions src/runtime/monitor/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pub fn main() {
// For early init, if something breaks, we really want to see everything...
std::env::set_var("RUST_BACKTRACE", "full");
let subscriber = FmtSubscriber::builder()
.with_max_level(Level::DEBUG)
.with_max_level(Level::INFO)
.with_target(false)
.with_span_events(FmtSpan::ACTIVE)
.finish();
Expand Down Expand Up @@ -98,7 +98,7 @@ fn monitor_init() -> miette::Result<()> {
{
let comp: CompartmentHandle =
CompartmentLoader::new("montest", test_name, NewCompartmentFlags::empty())
.args(&["montest", "--nocapture"])
.args(&["montest"])
.load()
.into_diagnostic()?;
let mut eb = 0;
Expand Down
6 changes: 3 additions & 3 deletions src/runtime/monitor/src/mon/compartment.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{collections::HashMap, ffi::CStr, io::BufRead};
use std::{collections::HashMap, ffi::CStr};

use dynlink::{
compartment::CompartmentId,
Expand Down Expand Up @@ -291,15 +291,15 @@ impl super::Monitor {

// parse args
let args_bytes = arg_bytes.split_inclusive(|b| *b == 0);
let mut args = args_bytes
let args = args_bytes
.map(CStr::from_bytes_with_nul)
.try_collect::<Vec<_>>()
.map_err(|_| LoadCompartmentError::Unknown)?;
tracing::debug!("load {}: args: {:?}", compname, args);

// parse env
let envs_bytes = env_bytes.split_inclusive(|b| *b == 0);
let mut env = envs_bytes
let env = envs_bytes
.map(CStr::from_bytes_with_nul)
.try_collect::<Vec<_>>()
.map_err(|_| LoadCompartmentError::Unknown)?;
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/monitor/src/mon/compartment/runcomp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ pub struct RunComp {

impl Drop for RunComp {
fn drop(&mut self) {
//tracing::warn!("todo: runcomp drop");
// TODO: check if we need to do anything.
}
}

Expand Down
23 changes: 14 additions & 9 deletions src/runtime/monitor/src/mon/space.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ fn mapflags_into_prot(flags: MapFlags) -> Protections {
}

extern "C-unwind" {
fn __monitor_get_slot() -> Option<usize>;
fn __monitor_get_pair() -> Option<(usize, usize)>;
fn __monitor_release_pair(pair: (usize, usize));
fn __monitor_get_slot() -> isize;
fn __monitor_get_pair(one: *mut usize, two: *mut usize) -> bool;
fn __monitor_release_pair(one: usize, two: usize);
fn __monitor_release_slot(slot: usize);
}

Expand All @@ -73,7 +73,10 @@ impl Space {
Some(item) => item,
None => {
// Not yet mapped, so allocate a slot and map it.
let slot = unsafe { __monitor_get_slot() }.ok_or(MapError::OutOfResources)?;
let slot = unsafe { __monitor_get_slot() }
.try_into()
.ok()
.ok_or(MapError::OutOfResources)?;

let Ok(_) = sys_object_map(
None,
Expand Down Expand Up @@ -180,20 +183,22 @@ pub(crate) struct UnmapOnDrop {

impl Drop for UnmapOnDrop {
fn drop(&mut self) {
if sys_object_unmap(None, self.slot, UnmapFlags::empty()).is_ok() {
unsafe {
match sys_object_unmap(None, self.slot, UnmapFlags::empty()) {
Ok(_) => unsafe {
__monitor_release_slot(self.slot);
},
Err(_e) => {
// TODO: once the kernel-side works properly, uncomment this.
//tracing::warn!("failed to unmap slot {}: {}", self.slot, e);
}
} else {
tracing::warn!("failed to unmap slot {}", self.slot);
}
}
}

/// Map an object into the address space, without tracking it. This leaks the mapping, but is useful
/// for bootstrapping. See the object mapping gate comments for more details.
pub fn early_object_map(info: MapInfo) -> MappedObjectAddrs {
let slot = unsafe { __monitor_get_slot() }.unwrap();
let slot = unsafe { __monitor_get_slot() }.try_into().unwrap();

sys_object_map(
None,
Expand Down
1 change: 0 additions & 1 deletion src/runtime/monitor/src/mon/thread/cleaner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,6 @@ impl Waits {
}
}

#[tracing::instrument(skip(data, recv))]
fn cleaner_thread_main(data: Pin<Arc<ThreadCleanerData>>, mut recv: Receiver<WaitOp>) {
// TODO (dbittman): when we have support for async thread events, we can use that API.
let mut ops = Vec::new();
Expand Down
4 changes: 0 additions & 4 deletions src/runtime/rt-impl/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,3 @@ stable-vec = "0.4.1"
lru = "0.12.4"
paste = "1"
printf-compat = { version = "0.1", default-features = false }

[features]
runtime = []
default = ["runtime"]
1 change: 1 addition & 0 deletions src/runtime/rt-impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@ pub use error::*;

pub mod preinit;

#[allow(non_snake_case)]
pub mod syms;
5 changes: 4 additions & 1 deletion src/runtime/rt-impl/src/preinit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,10 @@ macro_rules! preinit_println {

#[track_caller]
pub fn preinit_abort() -> ! {
unsafe { core::intrinsics::abort() }
#[allow(unused_unsafe)]
unsafe {
core::intrinsics::abort()
}
}

#[track_caller]
Expand Down
32 changes: 24 additions & 8 deletions src/runtime/rt-impl/src/runtime/core.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
//! Implements the core runtime functions.
use std::{ffi::c_void, sync::OnceLock};
use std::{
collections::BTreeMap,
ffi::{c_char, c_void, CStr, CString},
sync::{Mutex, OnceLock},
};

use dynlink::context::runtime::RuntimeInitInfo;
use monitor_api::{RuntimeThreadControl, SharedCompConfig};
Expand All @@ -23,9 +27,6 @@ use crate::{
runtime::RuntimeState,
};

#[thread_local]
static TLS_TEST: usize = 3222;

#[derive(Copy, Clone)]
struct PtrToInfo(*mut c_void);
unsafe impl Send for PtrToInfo {}
Expand Down Expand Up @@ -63,6 +64,22 @@ impl ReferenceRuntime {
.map(|x| x.0 as *mut _ as *mut c_void)
}

pub fn cgetenv(&self, name: &CStr) -> *const c_char {
// TODO: this approach is very simple, but it leaks if the environment changes a lot.
static ENVMAP: Mutex<BTreeMap<String, CString>> = Mutex::new(BTreeMap::new());
let Ok(name) = name.to_str() else {
return core::ptr::null();
};
let Ok(val) = std::env::var(name) else {
return core::ptr::null();
};
let mut envmap = ENVMAP.lock().unwrap();
envmap
.entry(val.to_string())
.or_insert_with(|| CString::new(val.to_string()).unwrap())
.as_ptr()
}

pub fn runtime_entry(
&self,
rtinfo: *const RuntimeInfo,
Expand All @@ -79,7 +96,7 @@ impl ReferenceRuntime {
.as_ref()
.unwrap()
};
MON_RTINFO.set(Some(PtrToInfo(init_info as *const _ as *mut _)));
let _ = MON_RTINFO.set(Some(PtrToInfo(init_info as *const _ as *mut _)));
self.init_for_monitor(init_info);
}
RUNTIME_INIT_COMP => {
Expand All @@ -91,7 +108,7 @@ impl ReferenceRuntime {
.as_ref()
.unwrap()
};
MON_RTINFO.set(None);
let _ = MON_RTINFO.set(None);
self.init_for_compartment(init_info);
}
x => {
Expand All @@ -114,11 +131,10 @@ impl ReferenceRuntime {
// TODO: control this with env vars
tracing::subscriber::set_global_default(
tracing_subscriber::fmt()
.with_max_level(Level::DEBUG)
.with_max_level(Level::INFO)
.finish(),
)
.unwrap();
preinit_println!("====== {}", TLS_TEST);
if self.state().contains(RuntimeState::IS_MONITOR) {
self.init_slots();
None
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/rt-impl/src/runtime/thread/tcb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ pub(crate) static TLS_GEN_MGR: RwLock<TlsGenMgr> = RwLock::new(TlsGenMgr {
});

impl TlsGenMgr {
pub fn need_new_gen(&self, mygen: Option<u64>) -> bool {
pub fn _need_new_gen(&self, mygen: Option<u64>) -> bool {
let cc = monitor_api::get_comp_config();
let template = unsafe { cc.get_tls_template().as_ref().unwrap() };
mygen.is_some_and(|mygen| mygen == template.gen)
Expand Down
Loading

0 comments on commit d54d4c2

Please sign in to comment.