use loupe::MemoryUsage;
use std::ptr::NonNull;
use std::sync::Arc;
use wasmer::{
vm::{self, MemoryError, MemoryStyle, TableStyle, VMMemoryDefinition, VMTableDefinition},
MemoryType, Pages, TableType, Tunables,
};
#[derive(MemoryUsage)]
pub struct CustomTunables<T: Tunables> {
limit: Pages,
base: T,
}
impl<T: Tunables> Tunables for CustomTunables<T> {
fn memory_style(&self, memory: &MemoryType) -> MemoryStyle {
let adjusted = self.adjust_memory(memory);
self.base.memory_style(&adjusted)
}
fn table_style(&self, table: &TableType) -> TableStyle {
self.base.table_style(table)
}
fn create_host_memory(
&self,
ty: &MemoryType,
style: &MemoryStyle,
) -> Result<Arc<dyn vm::Memory>, MemoryError> {
let adjusted = self.adjust_memory(ty);
self.validate_memory(&adjusted)?;
self.base.create_host_memory(&adjusted, style)
}
unsafe fn create_vm_memory(
&self,
ty: &MemoryType,
style: &MemoryStyle,
vm_definition_location: NonNull<VMMemoryDefinition>,
) -> Result<Arc<dyn vm::Memory>, MemoryError> {
let adjusted = self.adjust_memory(ty);
self.validate_memory(&adjusted)?;
self.base
.create_vm_memory(&adjusted, style, vm_definition_location)
}
fn create_host_table(
&self,
ty: &TableType,
style: &TableStyle,
) -> Result<Arc<dyn vm::Table>, String> {
self.base.create_host_table(ty, style)
}
unsafe fn create_vm_table(
&self,
ty: &TableType,
style: &TableStyle,
vm_definition_location: NonNull<VMTableDefinition>,
) -> Result<Arc<dyn vm::Table>, String> {
self.base.create_vm_table(ty, style, vm_definition_location)
}
}
impl<T: Tunables> CustomTunables<T> {
pub fn new(base: T, limit: Pages) -> Self {
Self { limit, base }
}
fn adjust_memory(&self, requested: &MemoryType) -> MemoryType {
let mut adjusted = *requested;
if requested.maximum.is_none() {
adjusted.maximum = Some(self.limit);
}
adjusted
}
fn validate_memory(&self, ty: &MemoryType) -> Result<(), MemoryError> {
if ty.minimum > self.limit {
return Err(MemoryError::Generic(
"Minimum limit exceeds the allowed memory limit".to_string(),
));
}
if let Some(max) = ty.maximum {
if max > self.limit {
return Err(MemoryError::Generic(
"Maximum limit exceeds the allowed memory limit".to_string(),
));
}
} else {
return Err(MemoryError::Generic("Maximum limit unset".to_string()));
}
Ok(())
}
}