Path: blob/main/tests/all/component_model/strings.rs
3054 views
#![cfg(not(miri))]12use super::REALLOC_AND_FREE;3use wasmtime::Result;4use wasmtime::component::{Component, Linker};5use wasmtime::{Engine, Store, StoreContextMut, Trap};67const UTF16_TAG: u32 = 1 << 31;89// Special cases that this tries to test:10//11// * utf8 -> utf812// * various code point sizes13//14// * utf8 -> utf16 - the adapter here will make a pessimistic allocation that's15// twice the size of the utf8 encoding for the utf16 destination16// * utf16 byte size is twice the utf8 size17// * utf16 byte size is less than twice the utf8 size18//19// * utf8 -> latin1+utf16 - attempts to convert to latin1 then falls back to a20// pessimistic utf16 allocation that's downsized if necessary21// * utf8 fits exactly in latin122// * utf8 fits latin1 but is bigger byte-wise23// * utf8 is not latin1 and fits utf16 allocation precisely (NOT POSSIBLE)24// * utf8 is not latin1 and utf16 is smaller than allocation25//26// * utf16 -> utf8 - this starts with an optimistic size and then reallocates to27// a pessimistic size, interesting cases are:28// * utf8 size is 0.5x the utf16 byte size (perfect fit in initial alloc)29// * utf8 size is 1.5x the utf16 byte size (perfect fit in larger alloc)30// * utf8 size is 0.5x-1.5x the utf16 size (larger alloc is downsized)31//32// * utf16 -> utf1633// * various code point sizes34//35// * utf16 -> latin1+utf16 - attempts to convert to latin1 then falls back to a36// pessimistic utf16 allocation that's downsized if necessary37// * utf16 fits exactly in latin138// * utf16 fits latin1 but is bigger byte-wise (NOT POSSIBLE)39// * utf16 is not latin1 and fits utf16 allocation precisely40// * utf16 is not latin1 and utf16 is smaller than allocation (NOT POSSIBLE)41//42// * compact-utf16 -> utf8 dynamically determines between one of43// * latin1 -> utf844// * latin1 size matches utf8 size45// * latin1 is smaller than utf8 size46// * utf16 -> utf847// * covered above48//49// * compact-utf16 -> utf16 dynamically determines between one of50// * latin1 -> utf16 - latin1 size always matches utf1651// * test various code points52// * utf16 -> utf1653// * covered above54//55// * compact-utf16 -> compact-utf16 dynamically determines between one of56// * latin1 -> latin157// * not much interesting here58// * utf16 -> compact-utf16-to-compact-probably-utf1659// * utf16 actually fits within latin160// * otherwise not more interesting than utf16 -> utf1661//62const STRINGS: &[&str] = &[63"",64// 1 byte in utf8, 2 bytes in utf1665"x",66"hello this is a particularly long string yes it is it keeps going",67// 35 bytes in utf8, 23 units in utf16, 23 bytes in latin168"à á â ã ä å æ ç è é ê ë",69// 47 bytes in utf8, 31 units in utf1670"Ξ Ο Π Ρ Σ Τ Υ Φ Χ Ψ Ω Ϊ Ϋ ά έ ή",71// 24 bytes in utf8, 8 units in utf1672"STUVWXYZ",73// 16 bytes in utf8, 8 units in utf1674"ËÌÍÎÏÐÑÒ",75// 4 bytes in utf8, 1 unit in utf1676"\u{10000}",77// latin1-compatible prefix followed by utf8/16-requiring suffix78//79// 24 bytes in utf8, 13 units in utf16, first 8 usvs are latin1-compatible80"à ascii VWXYZ",81];8283static ENCODINGS: [&str; 3] = ["utf8", "utf16", "latin1+utf16"];8485#[test]86fn roundtrip() -> Result<()> {87for debug in [true, false] {88let mut config = wasmtime_test_util::component::config();89config.debug_adapter_modules(debug);90let engine = Engine::new(&config)?;91for src in ENCODINGS {92for dst in ENCODINGS {93test_roundtrip(&engine, src, dst)?;94}95}96}97Ok(())98}99100fn test_roundtrip(engine: &Engine, src: &str, dst: &str) -> Result<()> {101println!("src={src} dst={dst}");102103let mk_echo = |name: &str, encoding: &str| {104format!(105r#"106(component {name}107(import "echo" (func $echo (param "a" string) (result string)))108(core instance $libc (instantiate $libc))109(core func $echo (canon lower (func $echo)110(memory $libc "memory")111(realloc (func $libc "realloc"))112string-encoding={encoding}113))114(core instance $echo (instantiate $echo115(with "libc" (instance $libc))116(with "" (instance (export "echo" (func $echo))))117))118(func (export "echo2") (param "a" string) (result string)119(canon lift120(core func $echo "echo")121(memory $libc "memory")122(realloc (func $libc "realloc"))123string-encoding={encoding}124)125)126)127"#128)129};130131let src = mk_echo("$src", src);132let dst = mk_echo("$dst", dst);133let component = format!(134r#"135(component136(import "host" (func $host (param "a" string) (result string)))137138(core module $libc139(memory (export "memory") 1)140{REALLOC_AND_FREE}141)142(core module $echo143(import "" "echo" (func $echo (param i32 i32 i32)))144(import "libc" "memory" (memory 0))145(import "libc" "realloc" (func $realloc (param i32 i32 i32 i32) (result i32)))146147(func (export "echo") (param i32 i32) (result i32)148(local $retptr i32)149(local.set $retptr150(call $realloc151(i32.const 0)152(i32.const 0)153(i32.const 4)154(i32.const 8)))155(call $echo156(local.get 0)157(local.get 1)158(local.get $retptr))159local.get $retptr160)161)162163{src}164{dst}165166(instance $dst (instantiate $dst (with "echo" (func $host))))167(instance $src (instantiate $src (with "echo" (func $dst "echo2"))))168(export "echo" (func $src "echo2"))169)170"#171);172let component = Component::new(engine, &component)?;173let mut store = Store::new(engine, String::new());174let mut linker = Linker::new(engine);175linker.root().func_wrap(176"host",177|store: StoreContextMut<String>, (arg,): (String,)| {178assert_eq!(*store.data(), arg);179Ok((arg,))180},181)?;182let instance = linker.instantiate(&mut store, &component)?;183let func = instance.get_typed_func::<(String,), (String,)>(&mut store, "echo")?;184185for string in STRINGS {186println!("testing string {string:?}");187*store.data_mut() = string.to_string();188let (ret,) = func.call(&mut store, (string.to_string(),))?;189assert_eq!(ret, *string);190}191Ok(())192}193194#[test]195fn ptr_out_of_bounds() -> Result<()> {196let engine = wasmtime_test_util::component::engine();197for src in ENCODINGS {198for dst in ENCODINGS {199test_ptr_out_of_bounds(&engine, src, dst)?;200}201}202Ok(())203}204205fn test_ptr_out_of_bounds(engine: &Engine, src: &str, dst: &str) -> Result<()> {206let test = |len: u32| -> Result<()> {207let component = format!(208r#"209(component210(component $c211(core module $m212(func (export "") (param i32 i32))213(func (export "realloc") (param i32 i32 i32 i32) (result i32) i32.const 0)214(memory (export "memory") 1)215)216(core instance $m (instantiate $m))217(func (export "a") (param "a" string)218(canon lift (core func $m "") (realloc (func $m "realloc")) (memory $m "memory")219string-encoding={dst})220)221)222223(component $c2224(import "a" (func $f (param "a" string)))225(core module $libc226(memory (export "memory") 1)227)228(core instance $libc (instantiate $libc))229(core func $f (canon lower (func $f) string-encoding={src} (memory $libc "memory")))230(core module $m231(import "" "" (func $f (param i32 i32)))232233(func $start (call $f (i32.const 0x8000_0000) (i32.const {len})))234(start $start)235)236(core instance (instantiate $m (with "" (instance (export "" (func $f))))))237)238239(instance $c (instantiate $c))240(instance $c2 (instantiate $c2 (with "a" (func $c "a"))))241)242"#243);244let component = Component::new(engine, &component)?;245let mut store = Store::new(engine, ());246let trap = Linker::new(engine)247.instantiate(&mut store, &component)248.err()249.unwrap()250.downcast::<Trap>()?;251assert_eq!(trap, Trap::StringOutOfBounds);252Ok(())253};254255test(0)?;256test(1)?;257258Ok(())259}260261// Test that even if the ptr+len calculation overflows then a trap still262// happens.263#[test]264fn ptr_overflow() -> Result<()> {265let engine = wasmtime_test_util::component::engine();266for src in ENCODINGS {267for dst in ENCODINGS {268test_ptr_overflow(&engine, src, dst)?;269}270}271Ok(())272}273274fn test_ptr_overflow(engine: &Engine, src: &str, dst: &str) -> Result<()> {275let component = format!(276r#"277(component278(component $c279(core module $m280(func (export "") (param i32 i32))281(func (export "realloc") (param i32 i32 i32 i32) (result i32) i32.const 0)282(memory (export "memory") 1)283)284(core instance $m (instantiate $m))285(func (export "a") (param "a" string)286(canon lift (core func $m "") (realloc (func $m "realloc")) (memory $m "memory")287string-encoding={dst})288)289)290291(component $c2292(import "a" (func $f (param "a" string)))293(core module $libc294(memory (export "memory") 1)295)296(core instance $libc (instantiate $libc))297(core func $f (canon lower (func $f) string-encoding={src} (memory $libc "memory")))298(core module $m299(import "" "" (func $f (param i32 i32)))300301(func (export "f") (param i32) (call $f (i32.const 1000) (local.get 0)))302)303(core instance $m (instantiate $m (with "" (instance (export "" (func $f))))))304(func (export "f") (param "a" u32) (canon lift (core func $m "f")))305)306307(instance $c (instantiate $c))308(instance $c2 (instantiate $c2 (with "a" (func $c "a"))))309(export "f" (func $c2 "f"))310)311"#312);313314let component = Component::new(engine, &component)?;315316let test_overflow = |size: u32| -> Result<()> {317println!("src={src} dst={dst} size={size:#x}");318let mut store = Store::new(engine, ());319let instance = Linker::new(engine).instantiate(&mut store, &component)?;320let func = instance.get_typed_func::<(u32,), ()>(&mut store, "f")?;321let trap = func322.call(&mut store, (size,))323.unwrap_err()324.downcast::<Trap>()?;325assert_eq!(trap, Trap::StringOutOfBounds);326Ok(())327};328329let max = 1 << 31;330331match src {332"utf8" => {333// This exceeds MAX_STRING_BYTE_LENGTH334test_overflow(max)?;335336if dst == "utf16" {337// exceeds MAX_STRING_BYTE_LENGTH when multiplied338test_overflow(max / 2)?;339340// Technically this fails on the first string, not the second.341// Ideally this would test the overflow check on the second342// string though.343test_overflow(max / 2 - 100)?;344} else {345// This will point into unmapped memory346test_overflow(max - 100)?;347}348}349350"utf16" => {351test_overflow(max / 2)?;352test_overflow(max / 2 - 100)?;353}354355"latin1+utf16" => {356test_overflow((max / 2) | UTF16_TAG)?;357// tag a utf16 string with the max length and it should overflow.358test_overflow((max / 2 - 100) | UTF16_TAG)?;359}360361_ => unreachable!(),362}363364Ok(())365}366367// Test that that the pointer returned from `realloc` is bounds-checked.368#[test]369fn realloc_oob() -> Result<()> {370let engine = wasmtime_test_util::component::engine();371for src in ENCODINGS {372for dst in ENCODINGS {373test_realloc_oob(&engine, src, dst)?;374}375}376Ok(())377}378379fn test_realloc_oob(engine: &Engine, src: &str, dst: &str) -> Result<()> {380let component = format!(381r#"382(component383(component $c384(core module $m385(func (export "") (param i32 i32))386(func (export "realloc") (param i32 i32 i32 i32) (result i32) i32.const 100_000)387(memory (export "memory") 1)388)389(core instance $m (instantiate $m))390(func (export "a") (param "a" string)391(canon lift (core func $m "") (realloc (func $m "realloc")) (memory $m "memory")392string-encoding={dst})393)394)395396(component $c2397(import "a" (func $f (param "a" string)))398(core module $libc399(memory (export "memory") 1)400)401(core instance $libc (instantiate $libc))402(core func $f (canon lower (func $f) string-encoding={src} (memory $libc "memory")))403(core module $m404(import "" "" (func $f (param i32 i32)))405406(func (export "f") (call $f (i32.const 1000) (i32.const 10)))407)408(core instance $m (instantiate $m (with "" (instance (export "" (func $f))))))409(func (export "f") (canon lift (core func $m "f")))410)411412(instance $c (instantiate $c))413(instance $c2 (instantiate $c2 (with "a" (func $c "a"))))414(export "f" (func $c2 "f"))415)416"#417);418419let component = Component::new(engine, &component)?;420let mut store = Store::new(engine, ());421422let instance = Linker::new(engine).instantiate(&mut store, &component)?;423let func = instance.get_typed_func::<(), ()>(&mut store, "f")?;424let trap = func.call(&mut store, ()).unwrap_err().downcast::<Trap>()?;425assert_eq!(trap, Trap::StringOutOfBounds);426Ok(())427}428429// Test that that the pointer returned from `realloc` is bounds-checked.430#[test]431fn raw_string_encodings() -> Result<()> {432let engine = wasmtime_test_util::component::engine();433test_invalid_string_encoding(&engine, "utf8", "utf8", &[0xff], 1)?;434let array = b"valid string until \xffthen valid again";435test_invalid_string_encoding(&engine, "utf8", "utf8", array, array.len() as u32)?;436test_invalid_string_encoding(&engine, "utf8", "utf16", array, array.len() as u32)?;437let array = b"symbol \xce\xa3 until \xffthen valid";438test_invalid_string_encoding(&engine, "utf8", "utf8", array, array.len() as u32)?;439test_invalid_string_encoding(&engine, "utf8", "utf16", array, array.len() as u32)?;440test_invalid_string_encoding(&engine, "utf8", "latin1+utf16", array, array.len() as u32)?;441test_invalid_string_encoding(&engine, "utf16", "utf8", &[0x01, 0xd8], 1)?;442test_invalid_string_encoding(&engine, "utf16", "utf16", &[0x01, 0xd8], 1)?;443test_invalid_string_encoding(444&engine,445"utf16",446"latin1+utf16",447&[0xff, 0xff, 0x01, 0xd8],4482,449)?;450test_invalid_string_encoding(451&engine,452"latin1+utf16",453"utf8",454&[0x01, 0xd8],4551 | UTF16_TAG,456)?;457test_invalid_string_encoding(458&engine,459"latin1+utf16",460"utf16",461&[0x01, 0xd8],4621 | UTF16_TAG,463)?;464test_invalid_string_encoding(465&engine,466"latin1+utf16",467"utf16",468&[0xff, 0xff, 0x01, 0xd8],4692 | UTF16_TAG,470)?;471test_invalid_string_encoding(472&engine,473"latin1+utf16",474"latin1+utf16",475&[0xab, 0x00, 0xff, 0xff, 0x01, 0xd8],4763 | UTF16_TAG,477)?;478479// This latin1+utf16 string should get compressed to latin1 across the480// boundary.481test_valid_string_encoding(482&engine,483"latin1+utf16",484"latin1+utf16",485&[0xab, 0x00, 0xff, 0x00],4862 | UTF16_TAG,487)?;488Ok(())489}490491fn test_invalid_string_encoding(492engine: &Engine,493src: &str,494dst: &str,495bytes: &[u8],496len: u32,497) -> Result<()> {498let trap = test_raw_when_encoded(engine, src, dst, bytes, len)?.unwrap();499let src = src.replace("latin1+", "");500assert!(501format!("{trap:?}").contains(&format!("invalid {src} encoding")),502"bad error: {trap:?}",503);504Ok(())505}506507fn test_valid_string_encoding(508engine: &Engine,509src: &str,510dst: &str,511bytes: &[u8],512len: u32,513) -> Result<()> {514let err = test_raw_when_encoded(engine, src, dst, bytes, len)?;515assert!(err.is_none());516Ok(())517}518519fn test_raw_when_encoded(520engine: &Engine,521src: &str,522dst: &str,523bytes: &[u8],524len: u32,525) -> Result<Option<wasmtime::Error>> {526let component = format!(527r#"528(component529(component $c530(core module $m531(func (export "") (param i32 i32))532(func (export "realloc") (param i32 i32 i32 i32) (result i32) i32.const 0)533(memory (export "memory") 1)534)535(core instance $m (instantiate $m))536(func (export "a") (param "a" string)537(canon lift (core func $m "") (realloc (func $m "realloc")) (memory $m "memory")538string-encoding={dst})539)540)541542(component $c2543(import "a" (func $f (param "a" string)))544(core module $libc545(memory (export "memory") 1)546(func (export "realloc") (param i32 i32 i32 i32) (result i32) i32.const 0)547)548(core instance $libc (instantiate $libc))549(core func $f (canon lower (func $f) string-encoding={src} (memory $libc "memory")))550(core module $m551(import "" "" (func $f (param i32 i32)))552553(func (export "f") (param i32 i32 i32) (call $f (local.get 0) (local.get 2)))554)555(core instance $m (instantiate $m (with "" (instance (export "" (func $f))))))556(func (export "f") (param "a" (list u8)) (param "b" u32) (canon lift (core func $m "f")557(memory $libc "memory")558(realloc (func $libc "realloc"))))559)560561(instance $c (instantiate $c))562(instance $c2 (instantiate $c2 (with "a" (func $c "a"))))563(export "f" (func $c2 "f"))564)565"#566);567568let component = Component::new(engine, &component)?;569let mut store = Store::new(engine, ());570571let instance = Linker::new(engine).instantiate(&mut store, &component)?;572let func = instance.get_typed_func::<(&[u8], u32), ()>(&mut store, "f")?;573match func.call(&mut store, (bytes, len)) {574Ok(_) => Ok(None),575Err(e) => Ok(Some(e)),576}577}578579580