#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(missing_docs)]
#[cfg(all(feature = "coreclr", target_arch = "x86_64"))]
pub mod attach;
pub mod bindings;
pub mod console;
#[cfg(feature = "coreclr")]
mod coreclr;
mod error;
pub mod jit;
#[cfg(feature = "coreclr")]
mod loader;
#[cfg(feature = "mono")]
mod mono;
#[cfg(feature = "coreclr")]
pub mod profiler;
#[cfg(feature = "reflect")]
pub mod reflect;
#[cfg(feature = "hao")]
pub mod rewrite;
use std::{ffi::c_void, path::Path, sync::Arc};
pub use bindings::{BoundAssembly, Object};
pub use error::{Error, Result};
#[cfg(feature = "hao")]
pub use hao;
#[cfg(feature = "coreclr")]
pub use coreclr::{find_dotnet_root, CoreClrOptions};
#[cfg(feature = "mono")]
pub use mono::MonoOptions;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
#[cfg_attr(feature = "reflect", repr(C))]
pub enum Backend {
CoreClr,
Mono,
}
#[cfg(not(any(feature = "coreclr", feature = "mono")))]
compile_error!("hao-runtime requires a backend feature: enable `coreclr` (the default) or `mono`");
enum Inner {
#[cfg(feature = "coreclr")]
CoreClr(coreclr::CoreClr),
#[cfg(feature = "mono")]
Mono(mono::Mono),
}
#[derive(Clone)]
pub struct Runtime(Arc<Inner>);
impl std::fmt::Debug for Runtime {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Runtime({:?})", self.backend())
}
}
impl Runtime {
#[cfg(feature = "coreclr")]
pub fn coreclr() -> Result<Self> {
Self::coreclr_with(&CoreClrOptions::default())
}
#[cfg(feature = "coreclr")]
pub fn coreclr_with(options: &CoreClrOptions) -> Result<Self> {
Self::coreclr_from(|| coreclr::CoreClr::new(options))
}
#[cfg(feature = "coreclr")]
pub fn coreclr_attach(
host_handle: *mut c_void,
domain_id: u32,
create_delegate: *const c_void,
major: u16,
) -> Result<Self> {
Self::coreclr_from(|| {
coreclr::CoreClr::attach(host_handle, domain_id, create_delegate, major)
})
}
#[cfg(feature = "coreclr")]
fn coreclr_from(make: impl FnOnce() -> Result<coreclr::CoreClr>) -> Result<Self> {
static RUNTIME: std::sync::Mutex<Option<Runtime>> = std::sync::Mutex::new(None);
let mut runtime = RUNTIME.lock().unwrap_or_else(|e| e.into_inner());
if let Some(runtime) = runtime.as_ref() {
return Ok(runtime.clone());
}
let started = Runtime(Arc::new(Inner::CoreClr(make()?)));
*runtime = Some(started.clone());
Ok(started)
}
#[cfg(feature = "mono")]
pub fn mono(options: &MonoOptions) -> Result<Self> {
Self::mono_with(|| mono::Mono::new(options))
}
#[cfg(feature = "mono")]
pub fn mono_attach(options: &MonoOptions) -> Result<Self> {
Self::mono_with(|| mono::Mono::attach(options))
}
#[cfg(feature = "mono")]
fn mono_with(make: impl FnOnce() -> Result<mono::Mono>) -> Result<Self> {
static RUNTIME: std::sync::Mutex<Option<Runtime>> = std::sync::Mutex::new(None);
let mut runtime = RUNTIME.lock().unwrap_or_else(|e| e.into_inner());
if let Some(runtime) = runtime.as_ref() {
return Ok(runtime.clone());
}
let started = Runtime(Arc::new(Inner::Mono(make()?)));
*runtime = Some(started.clone());
Ok(started)
}
pub fn backend(&self) -> Backend {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(_) => Backend::CoreClr,
#[cfg(feature = "mono")]
Inner::Mono(_) => Backend::Mono,
}
}
pub fn attach_thread(&self) {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(_) => {}
#[cfg(feature = "mono")]
Inner::Mono(mono) => mono.attach_thread(),
}
}
pub fn load_assembly(&self, path: impl AsRef<Path>) -> Result<()> {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(clr) => clr.load_assembly(path.as_ref()),
#[cfg(feature = "mono")]
Inner::Mono(mono) => mono.load_assembly(path.as_ref()),
}
}
pub fn load_assembly_bytes(&self, name: &str, bytes: &[u8]) -> Result<()> {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(clr) => {
let _ = name;
clr.load_assembly_bytes(bytes)
}
#[cfg(feature = "mono")]
Inner::Mono(mono) => mono.load_assembly_bytes(name, bytes),
}
}
#[cfg(feature = "hao")]
pub fn load_module(&self, module: &hao::Module) -> Result<()> {
let bytes = module
.write()
.map_err(|e| Error::Other(format!("could not write {}: {}", module.name(), e)))?;
let name = match &module.assembly {
Some(assembly) => assembly.get().name.clone(),
None => module.name().trim_end_matches(".dll").to_string(),
};
self.load_assembly_bytes(&name, &bytes)
}
pub fn function_pointer(
&self,
assembly: &str,
type_name: &str,
method: &str,
) -> Result<*const c_void> {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(clr) => clr.function_pointer(assembly, type_name, method),
#[cfg(feature = "mono")]
Inner::Mono(mono) => mono.function_pointer(assembly, type_name, method),
}
}
pub fn method_pointer(
&self,
assembly: &str,
type_name: &str,
method: &str,
) -> Result<*const c_void> {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(clr) => clr.method_pointer(assembly, type_name, method),
#[cfg(feature = "mono")]
Inner::Mono(mono) => mono.method_pointer(assembly, type_name, method),
}
}
pub fn method_pointer_from_loaded(
&self,
assembly: &str,
type_name: &str,
method: &str,
) -> Result<*const c_void> {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(clr) => clr.method_pointer_from_loaded(assembly, type_name, method),
#[cfg(feature = "mono")]
Inner::Mono(mono) => mono.method_pointer(assembly, type_name, method),
}
}
#[cfg(feature = "hao")]
pub fn corlib_method_pointer(
&self,
method: hao::dotnet::entries::well_known::WellKnownMethod,
) -> Result<*const c_void> {
let (namespace, name) = method.declaring().full_name();
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(clr) => {
let full_name = if namespace.is_empty() {
name.to_string()
} else {
format!("{namespace}.{name}")
};
clr.find_method_from_loaded(
"System.Private.CoreLib",
&full_name,
method.method_name(),
method.param_count() as i32,
None,
)
}
#[cfg(feature = "mono")]
Inner::Mono(mono) => mono.corlib_method_pointer(
namespace,
name,
method.method_name(),
method.param_count() as i32,
),
}
}
pub fn find_method_from_loaded(
&self,
assembly: &str,
type_name: &str,
method: &str,
param_count: i32,
) -> Result<*const c_void> {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(clr) => {
clr.find_method_from_loaded(assembly, type_name, method, param_count, None)
}
#[cfg(feature = "mono")]
Inner::Mono(mono) => mono.find_method(assembly, type_name, method, param_count),
}
}
pub fn find_method_from_loaded_typed(
&self,
assembly: &str,
type_name: &str,
method: &str,
param_count: i32,
first_param: &str,
) -> Result<*const c_void> {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(clr) => clr.find_method_from_loaded(
assembly,
type_name,
method,
param_count,
Some(first_param),
),
#[cfg(feature = "mono")]
Inner::Mono(_) => Err(Error::Other(format!(
"matching {type_name}::{method} by parameter type isn't supported on Mono"
))),
}
}
#[cfg(target_arch = "x86_64")]
pub fn invoke(&self, ptr: usize, args: &[u64]) -> Result<u64> {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(clr) => clr.invoke(ptr, args),
#[cfg(feature = "mono")]
Inner::Mono(_) => Ok(unsafe { jit::call_native(ptr, args) }),
}
}
#[cfg(target_arch = "x86_64")]
pub fn invoke_float(&self, ptr: usize, args: &[u64]) -> Result<f64> {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(clr) => clr.invoke_float(ptr, args),
#[cfg(feature = "mono")]
Inner::Mono(_) => Ok(unsafe { jit::call_native_float(ptr, args) }),
}
}
pub fn suppress_gc(&self, budget: i64) -> Result<bool> {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(clr) => clr.suppress_gc(budget),
#[cfg(feature = "mono")]
Inner::Mono(_) => {
let _ = budget;
Ok(false)
}
}
}
pub fn resume_gc(&self) -> Result<()> {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(clr) => clr.resume_gc(),
#[cfg(feature = "mono")]
Inner::Mono(_) => Ok(()),
}
}
pub fn warm_enumerate(&self) -> Result<()> {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(clr) => clr.warm_enumerate(),
#[cfg(feature = "mono")]
Inner::Mono(mono) => mono.warm_enumerate(),
}
}
pub fn enumerate(&self, obj: usize) -> Result<Vec<usize>> {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(clr) => clr.enumerate(obj),
#[cfg(feature = "mono")]
Inner::Mono(mono) => mono.enumerate(obj),
}
}
pub fn dotnet_major(&self) -> Option<u16> {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(clr) => Some(clr.major()),
#[cfg(feature = "mono")]
Inner::Mono(_) => None,
}
}
pub fn type_names(&self, assembly: &str) -> Result<Vec<String>> {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(clr) => clr.type_names(assembly),
#[cfg(feature = "mono")]
Inner::Mono(mono) => mono.type_names(assembly),
}
}
pub fn method_names(&self, assembly: &str, type_name: &str) -> Result<Vec<String>> {
match &*self.0 {
#[cfg(feature = "coreclr")]
Inner::CoreClr(clr) => clr.method_names(assembly, type_name),
#[cfg(feature = "mono")]
Inner::Mono(mono) => mono.method_names(assembly, type_name),
}
}
}