From 782be5b51a62c4908dd33c3b6f0cd32f674ee506 Mon Sep 17 00:00:00 2001 From: Stephan Renatus Date: Fri, 20 Dec 2019 16:29:44 +0100 Subject: [PATCH] Add function to get nul-terminated strings from memory Fixes #1086. Signed-off-by: Stephan Renatus --- CHANGELOG.md | 1 + lib/runtime-core/src/memory/ptr.rs | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fbf7c250fc4..b3f2065768c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## **[Unreleased]** +- [#1092](https://github.com/wasmerio/wasmer/pull/1092) Add `get_utf8_string_with_nul` to `WasmPtr` to read nul-terminated strings from memory. ## 0.12.0 - 2019-12-18 diff --git a/lib/runtime-core/src/memory/ptr.rs b/lib/runtime-core/src/memory/ptr.rs index 5e31627c20f..cb12ff74947 100644 --- a/lib/runtime-core/src/memory/ptr.rs +++ b/lib/runtime-core/src/memory/ptr.rs @@ -137,6 +137,17 @@ impl WasmPtr { let slice: &[u8] = unsafe { std::slice::from_raw_parts(ptr, str_len as usize) }; std::str::from_utf8(slice).ok() } + + /// Get a UTF-8 string representation of this `WasmPtr`, where the string is nul-terminated. + /// Note that this does not account for UTF-8 strings that _contain_ nul themselves, + /// [`get_utf8_string`] has to be used for those. + pub fn get_utf8_string_with_nul<'a>(self, memory: &'a Memory) -> Option<&'a str> { + memory.view::()[(self.offset as usize)..] + .iter() + .map(|cell| cell.get()) + .position(|byte| byte == 0) + .and_then(|length| self.get_utf8_string(memory, length as u32)) + } } unsafe impl WasmExternType for WasmPtr {