From cc06cbce837eef2f967d78d46cd2b90fc75d86cf Mon Sep 17 00:00:00 2001 From: ccgauche Date: Mon, 1 Mar 2021 21:29:18 +0100 Subject: [PATCH] Fixed comments --- client/src/error.rs | 2 +- client/src/lib.rs | 2 +- common/net/src/msg/server.rs | 2 +- common/sys/src/plugin/memory_manager.rs | 24 ++++++++++++++++++------ common/sys/src/plugin/mod.rs | 17 +++++------------ common/sys/src/plugin/module.rs | 15 ++++++++++----- common/sys/src/state.rs | 6 ++---- plugin/api/src/lib.rs | 10 +++++++++- plugin/rt/examples/hello.rs | 2 +- server/src/lib.rs | 1 - server/src/login_provider.rs | 6 +++--- voxygen/src/menu/main/mod.rs | 2 +- 12 files changed, 52 insertions(+), 37 deletions(-) diff --git a/client/src/error.rs b/client/src/error.rs index ef2a94f34c..bf7770998a 100644 --- a/client/src/error.rs +++ b/client/src/error.rs @@ -4,7 +4,7 @@ use network::{ParticipantError, StreamError}; #[derive(Debug)] pub enum Error { - KickedByPlugin(String), + Kicked(String), NetworkErr(NetworkError), ParticipantErr(ParticipantError), StreamErr(StreamError), diff --git a/client/src/lib.rs b/client/src/lib.rs index 866904ec78..f38f2113ba 100644 --- a/client/src/lib.rs +++ b/client/src/lib.rs @@ -500,7 +500,7 @@ impl Client { Err(RegisterError::AuthError(err)) => Err(Error::AuthErr(err)), Err(RegisterError::InvalidCharacter) => Err(Error::InvalidCharacter), Err(RegisterError::NotOnWhitelist) => Err(Error::NotOnWhitelist), - Err(RegisterError::KickedByPlugin(err)) => Err(Error::KickedByPlugin(err)), + Err(RegisterError::Kicked(err)) => Err(Error::Kicked(err)), Err(RegisterError::Banned(reason)) => Err(Error::Banned(reason)), Ok(()) => { self.registered = true; diff --git a/common/net/src/msg/server.rs b/common/net/src/msg/server.rs index 146bde5773..9ea2297a97 100644 --- a/common/net/src/msg/server.rs +++ b/common/net/src/msg/server.rs @@ -191,7 +191,7 @@ pub enum RegisterError { AlreadyLoggedIn, AuthError(String), Banned(String), - KickedByPlugin(String), + Kicked(String), InvalidCharacter, NotOnWhitelist, //TODO: InvalidAlias, diff --git a/common/sys/src/plugin/memory_manager.rs b/common/sys/src/plugin/memory_manager.rs index 5d317fe0fa..b69834c74e 100644 --- a/common/sys/src/plugin/memory_manager.rs +++ b/common/sys/src/plugin/memory_manager.rs @@ -106,6 +106,11 @@ impl MemoryManager { ) } + /// This function writes an object to the wasm memory using the allocator if + /// necessary using length padding. + /// + /// With length padding the first 8 bytes written are the length of the the + /// following slice (The object serialized). pub fn write_data_as_pointer( &self, memory: &Memory, @@ -125,32 +130,39 @@ impl MemoryManager { &self, memory: &Memory, allocator: &Function, - array: &[u8], + bytes: &[u8], ) -> Result<(u64, u64), PluginModuleError> { - let len = array.len(); + let len = bytes.len(); let mem_position = self .get_pointer(len as u32, allocator) .map_err(PluginModuleError::MemoryAllocation)? as usize; memory.view()[mem_position..mem_position + len] .iter() - .zip(array.iter()) + .zip(bytes.iter()) .for_each(|(cell, byte)| cell.set(*byte)); Ok((mem_position as u64, len as u64)) } + /// This function writes bytes to the wasm memory using the allocator if + /// necessary using length padding. + /// + /// With length padding the first 8 bytes written are the length of the the + /// following slice. pub fn write_bytes_as_pointer( &self, memory: &Memory, allocator: &Function, - array: &[u8], + bytes: &[u8], ) -> Result { - let len = array.len(); + let len = bytes.len(); let mem_position = self .get_pointer(len as u32 + 8, allocator) .map_err(PluginModuleError::MemoryAllocation)? as usize; + // Here we write the length as le bytes followed by the slice data itself in + // WASM memory memory.view()[mem_position..mem_position + len + 8] .iter() - .zip((len as u64).to_le_bytes().iter().chain(array.iter())) + .zip((len as u64).to_le_bytes().iter().chain(bytes.iter())) .for_each(|(cell, byte)| cell.set(*byte)); Ok(mem_position as u64) } diff --git a/common/sys/src/plugin/mod.rs b/common/sys/src/plugin/mod.rs index 2d2c0a8342..df1b733457 100644 --- a/common/sys/src/plugin/mod.rs +++ b/common/sys/src/plugin/mod.rs @@ -84,7 +84,6 @@ impl Plugin { pub fn execute_prepared( &self, ecs: &World, - event_name: &str, event: &PreparedEventQuery, ) -> Result, PluginError> where @@ -93,11 +92,11 @@ impl Plugin { self.modules .iter() .flat_map(|module| { - module.try_execute(ecs, event_name, event).map(|x| { + module.try_execute(ecs, event).map(|x| { x.map_err(|e| { PluginError::PluginModuleError( self.data.name.to_owned(), - event_name.to_owned(), + event.get_function_name().to_owned(), e, ) }) @@ -123,7 +122,6 @@ impl PluginMgr { pub fn execute_prepared( &self, ecs: &World, - event_name: &str, event: &PreparedEventQuery, ) -> Result, PluginError> where @@ -132,23 +130,18 @@ impl PluginMgr { Ok(self .plugins .par_iter() - .map(|plugin| plugin.execute_prepared(ecs, event_name, event)) + .map(|plugin| plugin.execute_prepared(ecs, event)) .collect::, _>>()? .into_iter() .flatten() .collect()) } - pub fn execute_event( - &self, - ecs: &World, - event_name: &str, - event: &T, - ) -> Result, PluginError> + pub fn execute_event(&self, ecs: &World, event: &T) -> Result, PluginError> where T: Event, { - self.execute_prepared(ecs, event_name, &PreparedEventQuery::new(event)?) + self.execute_prepared(ecs, &PreparedEventQuery::new(event)?) } pub fn from_dir>(path: P) -> Result { diff --git a/common/sys/src/plugin/module.rs b/common/sys/src/plugin/module.rs index 248e068237..ecc27b07a1 100644 --- a/common/sys/src/plugin/module.rs +++ b/common/sys/src/plugin/module.rs @@ -111,19 +111,18 @@ impl PluginModule { pub fn try_execute( &self, ecs: &World, - event_name: &str, request: &PreparedEventQuery, ) -> Option> where T: Event, { - if !self.events.contains(event_name) { + if !self.events.contains(&request.function_name) { return None; } // Store the ECS Pointer for later use in `retreives` let bytes = match self.ecs.execute_with(ecs, || { let mut state = self.wasm_state.lock().unwrap(); - execute_raw(self, &mut state, event_name, &request.bytes) + execute_raw(self, &mut state, &request.function_name, &request.bytes) }) { Ok(e) => e, Err(e) => return Some(Err(e)), @@ -136,6 +135,7 @@ impl PluginModule { /// reencoding for each module in every plugin) pub struct PreparedEventQuery { bytes: Vec, + function_name: String, _phantom: PhantomData, } @@ -149,9 +149,12 @@ impl PreparedEventQuery { { Ok(Self { bytes: bincode::serialize(&event).map_err(PluginError::Encoding)?, + function_name: event.get_event_name(), _phantom: PhantomData::default(), }) } + + pub fn get_function_name(&self) -> &str { &self.function_name } } pub fn from_u128(i: u128) -> (u64, u64) { @@ -202,8 +205,8 @@ fn execute_raw( .call(&[Value::I64(to_i64(mem_position)), Value::I64(to_i64(len))]) .map_err(PluginModuleError::RunFunction)?; - // Waiting for `multi-value` to be added to LLVM. So we encode the two i32 as an - // i64 + // Waiting for `multi-value` to be added to LLVM. So we encode a pointer to a + // u128 that represent [u64; 2] let u128_pointer = from_i64( function_result[0] @@ -215,6 +218,8 @@ fn execute_raw( // We read the return object and deserialize it + // The first 8 bytes are encoded as le and represent the pointer to the data + // The next 8 bytes are encoded as le and represent the length of the data Ok(memory_manager::read_bytes( &module.memory, u64::from_le_bytes(bytes[0..8].try_into().unwrap()), diff --git a/common/sys/src/state.rs b/common/sys/src/state.rs index 32c6c20327..d53ad1e1e0 100644 --- a/common/sys/src/state.rs +++ b/common/sys/src/state.rs @@ -209,10 +209,8 @@ impl State { #[cfg(feature = "plugins")] ecs.insert(match PluginMgr::from_assets() { Ok(plugin_mgr) => { - if let Err(e) = - plugin_mgr.execute_event(&ecs, "on_load", &plugin_api::event::PluginLoadEvent { - game_mode, - }) + if let Err(e) = plugin_mgr + .execute_event(&ecs, &plugin_api::event::PluginLoadEvent { game_mode }) { tracing::error!(?e, "Failed to run plugin init"); tracing::info!( diff --git a/plugin/api/src/lib.rs b/plugin/api/src/lib.rs index 2d159b3c25..c506fcf699 100644 --- a/plugin/api/src/lib.rs +++ b/plugin/api/src/lib.rs @@ -31,6 +31,8 @@ pub enum RetrieveResult { pub trait Event: Serialize + DeserializeOwned + Send + Sync { type Response: Serialize + DeserializeOwned + Send + Sync; + + fn get_event_name(&self) -> String; } pub mod event { @@ -46,6 +48,8 @@ pub mod event { impl Event for ChatCommandEvent { type Response = Result, String>; + + fn get_event_name(&self) -> String { format!("on_command_{}", self.command) } } #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)] @@ -61,12 +65,14 @@ pub mod event { impl Event for PlayerJoinEvent { type Response = PlayerJoinResult; + + fn get_event_name(&self) -> String { "on_join".to_owned() } } #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)] #[repr(u8)] pub enum PlayerJoinResult { - CloseConnection(String), + Kick(String), None, } @@ -81,6 +87,8 @@ pub mod event { impl Event for PluginLoadEvent { type Response = (); + + fn get_event_name(&self) -> String { "on_load".to_owned() } } // #[derive(Serialize, Deserialize, Debug)] diff --git a/plugin/rt/examples/hello.rs b/plugin/rt/examples/hello.rs index 752a6f32b8..f9009b6525 100644 --- a/plugin/rt/examples/hello.rs +++ b/plugin/rt/examples/hello.rs @@ -36,7 +36,7 @@ static COUNTER: AtomicBool = AtomicBool::new(false); #[event_handler] pub fn on_join(input: PlayerJoinEvent) -> PlayerJoinResult { if COUNTER.swap(!COUNTER.load(Ordering::SeqCst), Ordering::SeqCst) { - PlayerJoinResult::CloseConnection(format!("You are a cheater {:?}", input)) + PlayerJoinResult::Kick(format!("You are a cheater {:?}", input)) } else { PlayerJoinResult::None } diff --git a/server/src/lib.rs b/server/src/lib.rs index 2f049e44c8..70e0d1995c 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -1037,7 +1037,6 @@ impl Server { let plugin_manager = self.state.ecs().read_resource::(); let rs = plugin_manager.execute_event( self.state.ecs(), - &format!("on_command_{}", &kwd), &plugin_api::event::ChatCommandEvent { command: kwd.clone(), command_args: args.split(' ').map(|x| x.to_owned()).collect(), diff --git a/server/src/login_provider.rs b/server/src/login_provider.rs index 6d736b7061..64007e4684 100644 --- a/server/src/login_provider.rs +++ b/server/src/login_provider.rs @@ -79,14 +79,14 @@ impl LoginProvider { return Err(RegisterError::NotOnWhitelist); } - match plugin_manager.execute_event(&world, "on_join", &PlayerJoinEvent { + match plugin_manager.execute_event(&world, &PlayerJoinEvent { player_name: username.clone(), player_id: *uuid.as_bytes(), }) { Ok(e) => { for i in e.into_iter() { - if let PlayerJoinResult::CloseConnection(a) = i { - return Err(RegisterError::KickedByPlugin(a)); + if let PlayerJoinResult::Kick(a) = i { + return Err(RegisterError::Kicked(a)); } } }, diff --git a/voxygen/src/menu/main/mod.rs b/voxygen/src/menu/main/mod.rs index b5ee1da042..80de3e768c 100644 --- a/voxygen/src/menu/main/mod.rs +++ b/voxygen/src/menu/main/mod.rs @@ -134,7 +134,7 @@ impl PlayState for MainMenuState { localized_strings.get("main.login.authentication_error"), e ), - client::Error::KickedByPlugin(e) => e, + client::Error::Kicked(e) => e, client::Error::TooManyPlayers => { localized_strings.get("main.login.server_full").into() },