1

I want to launch a JVM and call a static Java method from Rust. Initially everything works fine, I see the expected output in the console. However, before the Java method ends, I get a segmentation fault.

This is the output:

Hello World!
Segmentation fault (core dumped)

Here is the Java class (packaged in a fat Jar):

public class HelloWorld {
    public static void greetings() {
        System.out.println("Hello World!");
    }
}

This is the Rust code that I execute:

extern crate rucaja;

use rucaja::{Jvm, jvalue};

fn main() {

    // The class path must contain the fat JAR.
    let class_path = "-Djava.class.path=./java/target/hello-0.1.0.jar";

    let jvm_options = [class_path];

    unsafe {
        // Instantiate the embedded JVM.
        let jvm = Jvm::new(&jvm_options);

        // Resolve the Java wrapper class from the fat JAR.
        let main_class = jvm.get_class("HelloWorld").expect("Could not find Java class");

        // Resolve Java methods in that wrapper class.
        let greetings_method = jvm.get_static_method(
            &main_class,
            "greetings",
            "()V"
        ).expect("Could not find Java method");

        // Prepare (no) arguments
        let args: Vec<jvalue> = vec![
        ];

        // Call the method
        jvm.call_static_object_method(
            &main_class,
            &greetings_method,
            args.as_ptr()
        );
    }

    println!("Done");
}

I tried running it with gdb, but the stack looks broken:

Program received signal SIGSEGV, Segmentation fault.
0x00007fffe575d2b4 in ?? ()
(gdb) bt
#0  0x00007fffe575d2b4 in ?? ()
#1  0x0000000000000246 in ?? ()
#2  0x00007fffe575d160 in ?? ()
#3  0x00007fffffffd530 in ?? ()
#4  0x00007fffffffd4e0 in ?? ()
#5  0x00007ffff790a6ad in ?? () from /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server/libjvm.so
Backtrace stopped: previous frame inner to this frame (corrupt stack?)

What do you think is the cause of the segmentation fault?

0

1 Answer 1

2

The Java method does not return an object, so jvm.call_static_void_method(...) must be used instead of jvm.call_static_object_method(...).

Correct code:

// Call the method
jvm.call_static_void_method(
    &main_class,
    &greetings_method,
    args.as_ptr()
);

Then the programs runs fine:

Hello World!
Done
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.