Skip to content

Inserting large structure in to HashMap causes "memory access out of bounds" #246

Closed
@NathanFlurry

Description

@NathanFlurry

When attempting to insert a large structure in to a HashMap with the wasm32-unknown-unknown target, I get this error:

wasm-00555126-2:79 Uncaught (in promise) RuntimeError: memory access out of bounds
    at _ZN66_$LT$std..collections..hash..table..RawTable$LT$K$C$$u20$V$GT$$GT$26new_uninitialized_internal17h68411f9faf813ecfE (wasm-function[2]:150)
    at _ZN72_$LT$std..collections..hash..map..HashMap$LT$K$C$$u20$V$C$$u20$S$GT$$GT$10try_resize17h6ab1bbea772cb23bE (wasm-function[5]:74)
    at _ZN72_$LT$std..collections..hash..map..HashMap$LT$K$C$$u20$V$C$$u20$S$GT$$GT$6insert17hfec45d344a00f122E (wasm-function[6]:269)
    at crash_wasm (wasm-function[18]:78)
    at fetch.then.then.then.results (http://localhost:8000/:13:26)

This code produces the error:
Rust:

use std::collections::HashMap;

const LARGE_STRUCT_SIZE: usize = 131072;  // Try setting this number to something like 65536 to make the demo work

struct LargeStruct {
    values: [u8; LARGE_STRUCT_SIZE]
}

#[no_mangle]
pub unsafe fn crash_wasm() -> i32 {
    let ls = LargeStruct { values: [0; LARGE_STRUCT_SIZE] };

    let mut hm = HashMap::new();
    hm.insert("test", ls);  // This panics

    // HashSet is broken too, of course, since it uses a `HashMap` under the hood

    // But this works:
//    let b = Box::new(ls);

    42
}

JavaScript:

fetch('main.wasm')
    .then(response => response.arrayBuffer())
    .then(bytes => WebAssembly.instantiate(bytes, {}))
    .then(results => {
        let { crash_wasm } = results.instance.exports
        let result = crash_wasm();
        console.log("result", result);
    });

Build script:

rustc +nightly --target wasm32-unknown-unknown -O --crate-type=cdylib src/lib.rs -o public/main.wasm

The LARGE_STRUCTURE_SIZE cutoff is somewhere between 65536 to 131072 bytes; I get different values with and without stdweb. I've tried this with wee_alloc also with no success.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions