Skip to content

Segmentation fault when allocating memory in WASM #51303

Open
@orsett0

Description

@orsett0

Version

v21.5.0

Platform

Linux shortplay 6.1.57-gentoo-x86_64 #2 SMP PREEMPT_DYNAMIC Wed Nov 29 15:55:15 CET 2023 x86_64 AMD Ryzen 5 2500U with Radeon Vega Mobile Gfx AuthenticAMD GNU/Linux

Subsystem

WASI

What steps will reproduce the bug?

Compile the following code with rustc --target=wasm32-wasi main.rs

fn main() {
    let mut total_size: u32 = 0;

    let mut s1 = "".to_owned();
    for _ in 0..8192 {
        for _ in 0..1024 {
            s1 = s1 + "A";
            total_size += 1;
        }
    }
    println!("Successifully allocated {} bytes for s1", total_size);

    let mut s2 = "".to_owned();
    for _ in 0..8198 {
        for _ in 0..1024 {
            s2 = s2 + "A";
            total_size += 1;
        }
        print!("\rSuccessifully allocated {} bytes for s2", total_size);
    }

    println!("\nGoodbye!");
}

This is my index.js:

import { readFileSync } from 'node:fs';
import { WASI } from 'wasi';

(async function () {
  const wasi = new WASI({
    version: 'preview1'
  });

  wasi.start(
    await WebAssembly.instantiate(
      await WebAssembly.compile(readFileSync('./main.wasm')),
      wasi.getImportObject()
    )
  );

})().then(() => console.log("Done"));

How often does it reproduce? Is there a required condition?

Every time you run the code.

This issue appears every time WASM requires to allocate more than (around) 8MiB.

What is the expected behavior? Why is that the expected behavior?

The expected behavior is for no segmentation fault to occur.

What do you see instead?

Segmentation fault, after the execution of the rust code.

Additional information

I noticed this issue in a project I'm working on. It that project WASI fails when trying to read a file larger than around 8MiB.

Unfortunately, I'm unable to identify the exact amount of memory required to trigger this bug, given that it changes based on a lot of different factors, which I wasn't able to identify.

Another thing, in the code I provided the bug is only triggered if you:

  • Excede a defined amount of memory for at least one variable
  • Print any variable.

I found this issue on another machine I don't have access to right now. It's running Arch Linux and Node.js v21.4.0.

Also, on this machine I'm running rustc v1.74.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    wasmIssues and PRs related to WebAssembly.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions