Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue: SIGSEGV on sequential unit tests #1381

Closed
jasonterando opened this issue Dec 29, 2023 · 4 comments
Closed

Issue: SIGSEGV on sequential unit tests #1381

jasonterando opened this issue Dec 29, 2023 · 4 comments

Comments

@jasonterando
Copy link

Hi, I'm encountering an issue running rusty v8, version 0.82.0, on Linux (x86 64 bit). I'm writing a crate library that integrates v8 to implement a scripting feature. I've created a function to execute V8 scripts. In the function, I'm using sync::Once to ensure the platform is initialized only once. After that, I create an isolate, scope, compile code, etc. and it's fine. I can call the function more than once and it all works perfectly.

However, if I have two unit tests that call that function, I get a SIGSEGV: invalid memory reference. My first thought was there was some sort of threading issue, but running with --test-threads=1 doesn't help. Below I've included a sample file demonstrating the issue.

I don't think I'm doing anything wrong, but I'm a Rust and V8 newbie, so any advice is appreciated. Obviously, writing unit tests to call V8 is a fringe case, but I want to make sure I'm not doing something else that is causing the SIGSEGV's once I release my library.

You can exercise by running the following:

  • cargo test # executes two calls to v8 in the same function
  • cargo test -F individual # executes two unit tests each calling V8, crashes with SIGSEGV
  • cargo test -F individual -- --test-threads=1 # executes two unit tests each calling V8 with one thread, crashes with SIGSEGV

lib.rs

use std::sync::Once;

use uuid::Uuid;

static V8_INIT: Once = Once::new();

pub fn execute() -> String {
    let callid = Uuid::new_v4().to_string();
    println!();
    println!("{} Before V8 call_once: {}", callid, V8_INIT.is_completed());
    V8_INIT.call_once(|| {
        // Initialize V8
        println!("{} Beginning V8 init", callid);
        let platform = v8::new_default_platform(0, false).make_shared();
        v8::V8::initialize_platform(platform);
        v8::V8::initialize();
        println!("{} Completed V8 init", callid);
    });
    println!("{} After V8 call_once: {}", callid, V8_INIT.is_completed());

    // Create a new Isolate and make it the current one.
    let isolate = &mut v8::Isolate::new(v8::CreateParams::default());

    // Create a stack-allocated handle scope.
    let scope = &mut v8::HandleScope::new(isolate);
    let context = v8::Context::new(scope);
    let scope = &mut v8::ContextScope::new(scope, context);

    let code = String::from("(1 + 1).toString()");

    // Compile and run the source code
    let v8_code = v8::String::new(scope, &code).unwrap();
    let script = v8::Script::compile(scope, v8_code, None).unwrap();
    let value = script.run(scope).unwrap();

    // Extract and return the results
    let result = value.to_string(scope);
    result.unwrap().to_rust_string_lossy(scope)
}


#[cfg(test)]
mod tests {
    use crate::execute;

    #[cfg(not(feature = "individual"))]
    #[test]
    fn test_attempt_combined() {
        assert_eq!(execute(), "2");
        assert_eq!(execute(), "2");
    }

    #[cfg(feature = "individual")]
    #[test]
    fn test_attempt_1() {
        assert_eq!(execute(), "2");
    }

    #[cfg(feature = "individual")]
    #[test]
    fn test_attempt_2() {
        assert_eq!(execute(), "2");
    }
}

Cargo.toml

[package]
name = "v8-demo"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
uuid = { version = "1.6.1", features = ["v4"] }
v8 = "0.82.0"

[features]
individual=[]

Output (two V8 calls in same test function)

$ cargo test
    Finished test [unoptimized + debuginfo] target(s) in 0.00s
     Running unittests src/lib.rs (target/debug/deps/v8_demo-b0467449950f74d0)

running 1 test
test tests::test_attempt_combined ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests v8-demo

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Output (two test functions calling V8 once)

$ cargo test
    Finished test [unoptimized + debuginfo] target(s) in 0.00s
     Running unittests src/lib.rs (target/debug/deps/v8_demo-b0467449950f74d0)

running 1 test
test tests::test_attempt_combined ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests v8-demo

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Output (two unit test functions calling V8 once)

$ cargo test -F individual
    Finished test [unoptimized + debuginfo] target(s) in 0.00s
     Running unittests src/lib.rs (target/debug/deps/v8_demo-baa9331bf38bd06c)

running 2 tests
error: test failed, to rerun pass `--lib`

Caused by:
  process didn't exit successfully: `/mnt/data/projects/Personal/apicize/rust/@apicize/v8-demo/target/debug/deps/v8_demo-baa9331bf38bd06c` (signal: 11, SIGSEGV: invalid memory reference)

Output (two unit test functions calling V8 once, single thread)

$ cargo test -F individual -- --test-threads=1
    Finished test [unoptimized + debuginfo] target(s) in 0.00s
     Running unittests src/lib.rs (target/debug/deps/v8_demo-baa9331bf38bd06c)

running 2 tests
test tests::test_attempt_1 ... ok
test tests::test_attempt_2 ... error: test failed, to rerun pass `--lib`

Caused by:
  process didn't exit successfully: `/mnt/data/projects/Personal/apicize/rust/@apicize/v8-demo/target/debug/deps/v8_demo-baa9331bf38bd06c --test-threads=1` (signal: 11, SIGSEGV: invalid memory reference)
@bartlomieju
Copy link
Member

If your CPU has PKU feature you might need to use v8::new_unprotected_default_platform(). The issue is that if V8 isn't initialized on main thread and PKU is available it might lead to such crashes. Can you try to collect a Rust backtrace (RUST_BACKTRACE=1)?

@jasonterando
Copy link
Author

Hi,

Changing to use the unprotected platform seems to work around the issue (i.e. setting up platform using let platform = v8::new_unprotected_default_platform(0, false).make_shared();). Running lscpu it does appear that my CPU has PKU enabled (under flags, see below).

running with RUST_BACKTRACE=1 doesn't seem to do anything, am I doing something wrong here?...

$ RUST_BACKTRACE=1 cargo test -F individual -- --nocapture
    Finished test [unoptimized + debuginfo] target(s) in 0.00s
     Running unittests src/lib.rs (target/debug/deps/v8_demo-baa9331bf38bd06c)

running 2 tests

e20f1b29-d86f-4350-8cb9-788511bd0403 Before V8 call_once: false
e20f1b29-d86f-4350-8cb9-788511bd0403 Beginning V8 init

18dbb773-778f-4b0c-a163-c9a977fa60ed Before V8 call_once: false
e20f1b29-d86f-4350-8cb9-788511bd0403 Completed V8 init
e20f1b29-d86f-4350-8cb9-788511bd0403 After V8 call_once: true
18dbb773-778f-4b0c-a163-c9a977fa60ed After V8 call_once: true
error: test failed, to rerun pass `--lib`

Caused by:
  process didn't exit successfully: `/mnt/data/projects/Personal/apicize/rust/@apicize/v8-demo/target/debug/deps/v8_demo-baa9331bf38bd06c --nocapture` (signal: 11, SIGSEGV: invalid memory reference)

lscpu

$ lscpu
Architecture:                       x86_64
CPU op-mode(s):                     32-bit, 64-bit
Address sizes:                      39 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             24
On-line CPU(s) list:                0-23
Vendor ID:                          GenuineIntel
Model name:                         13th Gen Intel(R) Core(TM) i7-13700F
CPU family:                         6
Model:                              183
Thread(s) per core:                 2
Core(s) per socket:                 16
Socket(s):                          1
Stepping:                           1
CPU max MHz:                        5200.0000
CPU min MHz:                        800.0000
BogoMIPS:                           4224.00
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize arch_lbr flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          640 KiB (16 instances)
L1i cache:                          768 KiB (16 instances)
L2 cache:                           24 MiB (10 instances)
L3 cache:                           30 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-23
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Not affected
Vulnerability Retbleed:             Not affected
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

@bartlomieju
Copy link
Member

Thanks for the update. Unfortunately this is as much as I can provide right now - this is what we're using in Deno itself. For the actual program (not tests) we're making sure to initialize V8 platform on the main thread to not hit this problem.

@jasonterando
Copy link
Author

Thanks for the info. Just wanted to make sure there wasn't something I was messing up on. It seems like this comes down to that V8 expects to be running on the main thread, and if it isn't, we should use new_unprotected_default_platform. Since cargo's test creates a new thread for testing (even with --thread-count set to 1), then this will always be an issue.

Also, for anybody coming across this thread, there apparently isn't a straightforward way to figure out if you are running in the primary thread or not. There's a crate that supposedly does this, but it's three years' old.

I think the only solution, for now, available to libraries like mine is to document that the application should limit calling the library from the main thread, or provide a fallback option to use new_unprotected_default_platform. This may be worth documenting on the rusty_v8's README

Sharktheone added a commit to Sharktheone/gosub-engine that referenced this issue Feb 1, 2024
See: denoland/rusty_v8#1381

and use null pointers when deallocating the context
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants