From d040c8b8a80ffff8c45226d00c71fb63595d11f6 Mon Sep 17 00:00:00 2001 From: zach Date: Mon, 18 Sep 2023 11:23:36 -0700 Subject: [PATCH] fix(kernel): avoid allocating 0-length blocks (#465) Fixes an issue where the kernel was able to allocate empty blocks, causing some weird memory issues. --- kernel/src/lib.rs | 6 ++++++ runtime/src/current_plugin.rs | 6 ++++++ runtime/src/extism-runtime.wasm | Bin 2694 -> 2725 bytes 3 files changed, 12 insertions(+) diff --git a/kernel/src/lib.rs b/kernel/src/lib.rs index 287fe90..d9de25f 100644 --- a/kernel/src/lib.rs +++ b/kernel/src/lib.rs @@ -310,6 +310,9 @@ impl MemoryBlock { /// Allocate a block of memory and return the offset #[no_mangle] pub unsafe fn extism_alloc(n: Length) -> Pointer { + if n == 0 { + return 0; + } let region = MemoryRoot::new(); let block = region.alloc(n); match block { @@ -321,6 +324,9 @@ pub unsafe fn extism_alloc(n: Length) -> Pointer { /// Free allocated memory #[no_mangle] pub unsafe fn extism_free(p: Pointer) { + if p == 0 { + return; + } let block = MemoryRoot::new().find_block(p); if let Some(block) = block { block.free(); diff --git a/runtime/src/current_plugin.rs b/runtime/src/current_plugin.rs index 9375d56..bf3dc31 100644 --- a/runtime/src/current_plugin.rs +++ b/runtime/src/current_plugin.rs @@ -125,6 +125,12 @@ impl CurrentPlugin { } pub fn memory_alloc(&mut self, n: u64) -> Result { + if n == 0 { + return Ok(MemoryHandle { + offset: 0, + length: 0, + }); + } let (linker, mut store) = self.linker_and_store(); let output = &mut [Val::I64(0)]; if let Some(f) = linker.get(&mut store, "env", "extism_alloc") { diff --git a/runtime/src/extism-runtime.wasm b/runtime/src/extism-runtime.wasm index b252b6fb46c3d151bb749bd2453eb9d9dc72ec3c..67db36261bd9f553fad7d4499d7523344ef3caad 100755 GIT binary patch delta 427 zcmYLFJxc>Y5S^Xb+gxt%B!UNm&D{EdB91mmt9IeY zA%}wm80J}V&A|M@V>bcWUAivwW6vQ@SSc_ zaa0$b*+|k#N|x*rYgEKS0Gm0tL_!idvHEvxw7h0q)`f^}WoTLDT&`}*XuqmOkecSi PN%cVeip>4;(WLqZN>E0W delta 389 zcmYLEu}T9$5S^LbyIgMXB!v;dW^Rq5NZJTCX43@(v5|E48~lUlU6nd;l^-Cf4ut%G z|6y&fm0;y;PRMTYhWFmi+xOaE_TNqjSDRD1!1P1Ms-$NuseVug^=EWl4?2&fI#)@d zX}r5E6xfKB>vl6Y^g=Y=tm3}@1EeoOlmGw#