From 74ec8db9d79d02062258d214e66c8e94ac03de00 Mon Sep 17 00:00:00 2001 From: Amber Kowalski Date: Sat, 26 Sep 2020 00:19:00 -0500 Subject: [PATCH] Initial commit --- .gitignore | 7 + Cargo.toml | 2 + LICENSE-APACHE | 201 ++++++++++++++++++++++++++++ LICENSE-MIT | 5 + README.md | 9 ++ sys/Cargo.toml | 15 +++ sys/src/host_externs/free.rs | 47 +++++++ sys/src/host_externs/mod.rs | 9 ++ sys/src/lib.rs | 10 ++ sys/src/module_externs/log.rs | 15 +++ sys/src/module_externs/mod.rs | 10 ++ sys/src/raw/host.rs | 239 ++++++++++++++++++++++++++++++++++ sys/src/raw/mod.rs | 62 +++++++++ sys/src/raw/module.rs | 221 +++++++++++++++++++++++++++++++ 14 files changed, 852 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT create mode 100644 README.md create mode 100644 sys/Cargo.toml create mode 100644 sys/src/host_externs/free.rs create mode 100644 sys/src/host_externs/mod.rs create mode 100644 sys/src/lib.rs create mode 100644 sys/src/module_externs/log.rs create mode 100644 sys/src/module_externs/mod.rs create mode 100644 sys/src/raw/host.rs create mode 100644 sys/src/raw/mod.rs create mode 100644 sys/src/raw/module.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0cf5495 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +debug/ +target/ +Cargo.lock +**/*.rs.bk + +.vscode/ +.idea/ \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..fc77ffe --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,2 @@ +[workspace] +members = ["sys"] diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..e662c78 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,5 @@ +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..45fce1c --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# Quill +Quill is a WebAssembly-based plugin API for Minecraft servers. +Quill is primarily developed Feather, but defines a relatively generic set of interfaces that fit well in any minecraft server architecture based on the ECS pattern. + +# Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. \ No newline at end of file diff --git a/sys/Cargo.toml b/sys/Cargo.toml new file mode 100644 index 0000000..9c7dcda --- /dev/null +++ b/sys/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "quill-sys" +version = "0.1.0-alpha4.0" +authors = ["The Feather Project Developers"] +repository = "https://github.com/feather-rs/quill" +license = "MIT OR Apache-2.0" +edition = "2018" + +[features] +default = [] +host = ["wasmer", "anyhow"] + +[dependencies] +wasmer = { version = "1.0.0-alpha3", optional = true } +anyhow = { version = "1", optional = true } \ No newline at end of file diff --git a/sys/src/host_externs/free.rs b/sys/src/host_externs/free.rs new file mode 100644 index 0000000..85cfc9b --- /dev/null +++ b/sys/src/host_externs/free.rs @@ -0,0 +1,47 @@ +use crate::raw::WasmFree; +use anyhow::Result; +use std::mem::{align_of, size_of}; +use wasmer::{Instance, NativeFunc, WasmPtr}; + +/// Frees a value that has been allocated in WASM that should +/// be freed by the host. +/// +/// Automatically determines the size and align to free, if you +/// need manual control over that use `wasm_free_unsafe`. +pub fn wasm_free(instance: &Instance, ptr: WasmPtr) -> Result<()> { + // Get information about the value we're freeing + let free_size = size_of::() as u32; + let free_align = align_of::() as u32; + + // Get the start of the value as a byte + let as_u8 = WasmPtr::new(ptr.offset()); + + // Try to get the free function + let free_function: NativeFunc<(WasmPtr, u32, u32)> = + instance.exports.get_native_function("__quill_free")?; + + free_function.call(as_u8, free_size, free_align)?; + + Ok(()) +} + +/// Frees memory from WASM with no checks. +/// +/// If you are freeing a value that is `WasmFree` it is recommended to use `wasm_free` as it is guaranteed safe. +/// +/// # Safety +/// There are no checks to ensure size and align are correct, or that the memory that's being freed is meant +/// to be freed by the host. +pub unsafe fn wasm_free_unchecked( + instance: &Instance, + ptr: WasmPtr, + free_size: u32, + free_align: u32, +) -> Result<()> { + let free_function: NativeFunc<(WasmPtr, u32, u32)> = + instance.exports.get_native_function("__quill_free")?; + + free_function.call(ptr, free_size, free_align)?; + + Ok(()) +} diff --git a/sys/src/host_externs/mod.rs b/sys/src/host_externs/mod.rs new file mode 100644 index 0000000..cfff046 --- /dev/null +++ b/sys/src/host_externs/mod.rs @@ -0,0 +1,9 @@ +//! Contains wrappers for calls to a WASM module from the host. +//! +//! The purpose for this crate it to define and implement easy +//! methods for calling module functions, and ensuring they are +//! called correctly. + +mod free; + +pub use free::{wasm_free, wasm_free_unchecked}; diff --git a/sys/src/lib.rs b/sys/src/lib.rs new file mode 100644 index 0000000..fab1127 --- /dev/null +++ b/sys/src/lib.rs @@ -0,0 +1,10 @@ +#![feature(alloc_layout_extra)] +#![deny(improper_ctypes)] + +pub mod raw; + +#[cfg(not(feature = "host"))] +pub mod module_externs; + +#[cfg(feature = "host")] +pub mod host_externs; diff --git a/sys/src/module_externs/log.rs b/sys/src/module_externs/log.rs new file mode 100644 index 0000000..63ce232 --- /dev/null +++ b/sys/src/module_externs/log.rs @@ -0,0 +1,15 @@ +use crate::raw::{LogLevel, PluginRef, PluginString}; + +extern "C" { + fn unsafe_log(level: u8, string: *const PluginRef); +} + +/// Logs a message using the specified `LogLevel` +pub fn log(level: LogLevel, message: S) +where + S: AsRef, +{ + let as_str = message.as_ref(); + + unsafe { unsafe_log(level as u8, &PluginString::from_borrow(as_str)) }; +} diff --git a/sys/src/module_externs/mod.rs b/sys/src/module_externs/mod.rs new file mode 100644 index 0000000..3ba8017 --- /dev/null +++ b/sys/src/module_externs/mod.rs @@ -0,0 +1,10 @@ +//! Contains safe wrappers for calls to a host from WASM. +//! +//! Methods in this crate are only safe to call from within wasm +//! as they require exported functions. The functions called by +//! these wrappers are a standard part of the Quill API and will +//! always be available. + +mod log; + +pub use log::log; diff --git a/sys/src/raw/host.rs b/sys/src/raw/host.rs new file mode 100644 index 0000000..de34f87 --- /dev/null +++ b/sys/src/raw/host.rs @@ -0,0 +1,239 @@ +use anyhow::Result; +use std::convert::TryFrom; +use std::marker::PhantomData; +use std::ops::Deref; +use wasmer::{Array, Instance, Memory, ValueType, WasmPtr}; + +use crate::host_externs::wasm_free_unchecked; + +/// Represents a `Layout`, but this one is safe to send between WASM and the Host. +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct AllocationLayout { + pub size: u32, + pub align: u32, +} + +/// Represents a type that has been allocated on the heap in a WASM module. +/// +/// # Safety +/// Calling `free` on `PluginBox` is required to prevent memory leaks. +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct PluginBox { + pub boxed: T, + layout: AllocationLayout, +} + +impl Deref for PluginBox { + type Target = T; + fn deref(&self) -> &T { + &self.boxed + } +} + +unsafe impl ValueType for PluginBox where T: ValueType {} + +/// Represents a transient reference to memory in a WASM module. +/// +/// # Safety +/// It is UB to use a `PluginRef` after control has been returned to WASM. +/// this is because memory could have shifted due to WASM memory management, +/// or the memory could have been deallocated. +#[repr(transparent)] +#[derive(Copy, Clone, Debug)] +pub struct PluginRef(pub T); + +impl Deref for PluginRef { + type Target = T; + fn deref(&self) -> &T { + &self.0 + } +} + +unsafe impl ValueType for PluginRef where T: ValueType {} + +/// A trait that indicates that a structure has allocations to WASM memory. +/// These allocations **MUST** be freed, not doing so would cause memory leaks. +pub trait WasmFree: ValueType { + /// Frees all allocations in WASM memory for `Self`. + /// + /// It is intended that you also call `free()` on any members that implement it + /// when writing an implementation of the trait. This is to make memory management + /// easier, and it is part of the quill-internals style. + fn free(self, instance: &Instance, memory: &Memory) -> Result<()>; +} + +/// A type that allows Strings to be sent over FFI. +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct PluginString { + pub ptr: u32, + pub len: u32, + string_layout: AllocationLayout, +} + +impl PluginString { + /// Try to convert a `PluginString` to a `String`. + /// + /// This copies the data out of the `PluginString`. + pub fn to_string(&self, memory: &Memory) -> Option { + let ptr: WasmPtr = WasmPtr::new(self.ptr); + + Some(ptr.get_utf8_string(memory, self.len)?.to_owned()) + } +} + +unsafe impl ValueType for PluginString {} + +impl WasmFree for PluginString { + fn free(self, instance: &Instance, _: &Memory) -> Result<()> { + unsafe { + wasm_free_unchecked( + instance, + WasmPtr::new(self.ptr), + self.string_layout.size as u32, + self.string_layout.align as u32, + ) + } + } +} + +/// A type that allows slices to be sent safely over FFI. +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct PluginSlice { + pub len: u32, + pub elements: u32, // *const [T] + slice_layout: AllocationLayout, + _marker: PhantomData, +} + +unsafe impl ValueType for PluginSlice where T: ValueType {} + +impl WasmFree for PluginSlice +where + T: ValueType, +{ + fn free(self, instance: &Instance, _: &Memory) -> Result<()> { + unsafe { + wasm_free_unchecked( + instance, + WasmPtr::new(self.elements), + self.slice_layout.size as u32, + self.slice_layout.align as u32, + ) + } + } +} + +/// A type that allows slices to be sent over FFI. This type is specific to cases +/// where the `T` has freeing logic, as `PluginSlice` cannot handle that. +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct PluginSliceAlloc { + pub len: u32, + pub elements: u32, // *const [T] + slice_layout: AllocationLayout, + _marker: PhantomData, +} + +unsafe impl ValueType for PluginSliceAlloc where T: ValueType + WasmFree {} + +impl WasmFree for PluginSliceAlloc +where + T: ValueType + WasmFree, +{ + fn free(self, instance: &Instance, memory: &Memory) -> Result<()> { + // Start by runnning WasmFree on the slice elements + let slice_ptr: WasmPtr = WasmPtr::new(self.elements); + + let slice = slice_ptr.deref(memory, 0, self.len).unwrap(); + + for element in slice.iter() { + element.get().free(instance, memory)?; + } + + unsafe { + wasm_free_unchecked( + instance, + WasmPtr::new(self.elements), + self.slice_layout.size as u32, + self.slice_layout.align as u32, + ) + } + } +} + +/// A type that allows system definitions to be sent over FFI. +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct PluginSystem { + pub stage: crate::raw::SystemStage, + pub name: PluginString, +} + +unsafe impl ValueType for PluginSystem {} + +impl WasmFree for PluginSystem { + fn free(self, instance: &Instance, memory: &Memory) -> Result<()> { + self.name.free(instance, memory) + } +} + +/// A type that defines a plugin's properties. +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct PluginRegister { + pub name: PluginString, + pub version: PluginString, + pub systems: PluginSliceAlloc, +} + +unsafe impl ValueType for PluginRegister {} + +impl WasmFree for PluginRegister { + fn free(self, instance: &Instance, memory: &Memory) -> Result<()> { + self.name.free(instance, memory)?; + self.version.free(instance, memory)?; + self.systems.free(instance, memory) + } +} + +impl PluginBox { + pub fn free_ptr_to( + self, + ptr: WasmPtr>, + instance: &Instance, + ) -> Result<()> { + // Get layout required to store the type + let layout = self.layout; + unsafe { + wasm_free_unchecked( + instance, + WasmPtr::new(ptr.offset()), + layout.size as u32, + layout.align as u32, + ) + } + } +} + +/// Defines a level that a message should be logged at. +#[repr(u8)] +pub enum LogLevel { + Debug = 1, + Info = 2, +} + +impl TryFrom for LogLevel { + type Error = (); + + fn try_from(from: u8) -> Result { + match from { + 1 => Ok(LogLevel::Debug), + 2 => Ok(LogLevel::Info), + _ => Err(()), + } + } +} diff --git a/sys/src/raw/mod.rs b/sys/src/raw/mod.rs new file mode 100644 index 0000000..0c93c79 --- /dev/null +++ b/sys/src/raw/mod.rs @@ -0,0 +1,62 @@ +//! Defines types that allow data flow between a Plugin host and a loaded +//! plugin. +//! +//! The `host` feature affects the compilation of this module. +//! This is because the same types have different functions on +//! the module and on the host. Additionally, `wasmer` requires +//! that data that can be dereferenced from WASM modules implements +//! a marker trait. +//! +//! The main difference between `module` types and `host` types is all pointers +//! are represented as `u32`. This is because WASM has a 32-bit usize, and using +//! the normal pointer type `*const T` would cause UB due to the difference in +//! usize. Additionally, using `u32` prevents the host from accidentally trying +//! to cast a wasm ptr directly to a reference on the host. Doing so would cause +//! UB on cast, and a segfault on dereference. + +#[cfg(not(feature = "host"))] +mod module; + +#[cfg(not(feature = "host"))] +pub use module::*; + +#[cfg(feature = "host")] +mod host; + +#[cfg(feature = "host")] +pub use host::*; + +use std::convert::TryFrom; + +/// C-Compatible representation of a system stage +#[repr(u8)] +#[derive(Copy, Clone, Debug)] +pub enum SystemStage { + /// Called before main gameplay logic runs. + Pre = 1, + /// Should handle all gameplay logic. + Tick = 2, + /// Should be used to handle events. + HandleEvents = 3, + /// Should be used for packet broadcasting on the + /// server side, and packet sending on the client. + SendPackets = 4, + /// Should be used to clean up / reset resources + /// at the end of the tick. + CleanUp = 5, +} + +impl TryFrom for SystemStage { + type Error = (); + + fn try_from(value: u8) -> Result { + match value { + 1 => Ok(SystemStage::Pre), + 2 => Ok(SystemStage::Tick), + 3 => Ok(SystemStage::HandleEvents), + 4 => Ok(SystemStage::SendPackets), + 5 => Ok(SystemStage::CleanUp), + _ => Err(()), + } + } +} diff --git a/sys/src/raw/module.rs b/sys/src/raw/module.rs new file mode 100644 index 0000000..8997998 --- /dev/null +++ b/sys/src/raw/module.rs @@ -0,0 +1,221 @@ +use std::alloc::Layout; +use std::convert::TryFrom; +use std::ops::Deref; + +/// Represents a `Layout`, but this one is safe to send between WASM and the Host. +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct AllocationLayout { + pub size: usize, + pub align: usize, +} + +impl From for AllocationLayout { + fn from(from: Layout) -> Self { + Self { + size: from.size(), + align: from.align(), + } + } +} + +impl Into for AllocationLayout { + fn into(self) -> Layout { + Layout::from_size_align(self.size, self.align).unwrap() + } +} + +/// Represents a type that has been allocated on the heap in a WASM module. +/// +/// # Safety +/// Calling `free` on `PluginBox` is required to prevent memory leaks. +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct PluginBox { + pub boxed: T, + pub layout: AllocationLayout, +} + +/// Represents a transient reference to memory in a WASM module. +/// +/// # Safety +/// It is UB to use a `PluginRef` after control has been returned to WASM. +/// this is because memory could have shifted due to WASM memory management, +/// or the memory could have been deallocated. +#[repr(transparent)] +#[derive(Copy, Clone, Debug)] +pub struct PluginRef(pub T); + +impl Deref for PluginBox { + type Target = T; + fn deref(&self) -> &T { + &self.boxed + } +} + +impl Deref for PluginRef { + type Target = T; + fn deref(&self) -> &T { + &self.0 + } +} + +/// A type that allows Strings to be sent over FFI. +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct PluginString { + ptr: *const u8, + len: usize, + slice_layout: AllocationLayout, +} + +impl PluginString { + /// Creates a `PluginRef` from a string slice. + /// + /// # Safety + /// The string slice must live longer than the returned `PluginRef` + pub unsafe fn from_borrow(string: &str) -> PluginRef { + PluginRef(Self { + ptr: string.as_ptr(), + len: string.len(), + slice_layout: Layout::new::().repeat(string.len()).unwrap().0.into(), + }) + } +} + +impl From for PluginString { + fn from(string: String) -> Self { + let as_str_boxed = string.into_boxed_str(); + + PluginString { + len: as_str_boxed.len(), + slice_layout: Layout::new::() + .repeat(as_str_boxed.len()) + .unwrap() + .0 + .into(), + ptr: Box::into_raw(as_str_boxed) as *const u8, + } + } +} + +impl From<&str> for PluginString { + fn from(str: &str) -> Self { + let as_str_boxed: Box<[u8]> = Box::from(str.as_bytes()); + + PluginString { + len: as_str_boxed.len(), + slice_layout: Layout::new::().repeat(str.len()).unwrap().0.into(), + ptr: Box::into_raw(as_str_boxed) as *const u8, + } + } +} + +/// A type that allows slices to be sent over FFI. +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct PluginSlice { + len: usize, + elements: *const [T], + slice_layout: AllocationLayout, +} + +impl From<&[T]> for PluginSlice +where + T: Clone + Copy, +{ + fn from(from: &[T]) -> PluginSlice { + let as_box: Box<[T]> = from.into(); + PluginSlice { + len: as_box.len(), + elements: Box::into_raw(as_box), + slice_layout: Layout::new::().repeat(from.len()).unwrap().0.into(), + } + } +} + +/// A type that allows slices to be sent over FFI. This type is specific to cases +/// where the `T` has freeing logic, as `PluginSlice` cannot handle that. +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct PluginSliceAlloc { + len: usize, + elements: *const T, + slice_layout: AllocationLayout, +} + +impl From<&[T]> for PluginSliceAlloc +where + T: Clone + Copy, +{ + fn from(from: &[T]) -> PluginSliceAlloc { + let as_box: Box<[T]> = from.into(); + PluginSliceAlloc { + len: as_box.len(), + slice_layout: Layout::new::().repeat(from.len()).unwrap().0.into(), + elements: Box::into_raw(as_box) as *const T, + } + } +} + +/// A type that allows system definitions to be sent over FFI. +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct PluginSystem { + pub stage: super::SystemStage, + pub name: PluginString, +} + +/// A type that defines a plugin's properties. +/// +/// # Examples +/// Despite the type definition, it is relatively easy to +/// construct. +/// ``` +/// # use quill_internals::raw::{PluginRegister, PluginSystem, SystemStage}; +/// let plugin_register = PluginRegister { +/// name: "Plugin Name".into(), // PluginBox can be created from a &str +/// version: "1.0.0".into(), // See above +/// systems: (&[PluginSystem { +/// stage: SystemStage::Tick, +/// name: "plugin_system".into() +/// }] as &[_]).into() +/// }; +/// ``` +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct PluginRegister { + pub name: PluginString, + pub version: PluginString, + pub systems: PluginSliceAlloc, +} + +impl Into<*const PluginBox> for PluginRegister { + fn into(self) -> *const PluginBox { + let boxed_self = Box::new(PluginBox { + boxed: self, + layout: Layout::new::>().into(), + }); + + Box::into_raw(boxed_self) + } +} + +/// Defines a level that a message should be logged at. +#[repr(u8)] +pub enum LogLevel { + Debug = 1, + Info = 2, +} + +impl TryFrom for LogLevel { + type Error = (); + + fn try_from(from: u8) -> Result { + match from { + 1 => Ok(LogLevel::Debug), + 2 => Ok(LogLevel::Info), + _ => Err(()), + } + } +}