Skip to content

Instantly share code, notes, and snippets.

@engelmarkus
Created March 15, 2016 00:11
Show Gist options
  • Save engelmarkus/b3be3f2aeec567356cf8 to your computer and use it in GitHub Desktop.
Save engelmarkus/b3be3f2aeec567356cf8 to your computer and use it in GitHub Desktop.
Calling an assembly function from Java
Assuming a 64 bit system.
Translate java part:
markus@utopic:/tmp$ javac AsmTest.java
Translate assembly part:
markus@utopic:/tmp$ nasm -f elf64 -o addThem.o addThem.asm
Create a shared object:
markus@utopic:/tmp$ gcc -shared -o libaddThem.so addThem.o
Run the java program:
markus@utopic:/tmp$ java -Djava.library.path=. AsmTest
OpenJDK 64-Bit Server VM warning: You have loaded library /tmp/libaddThem.so which might have disabled stack guard. The VM will try to fix the stack guard now.
It's highly recommended that you fix the library with 'execstack -c <libfile>', or link it with '-z noexecstack'.
Result: 9
markus@utopic:/tmp$
[BITS 64]
GLOBAL Java_AsmTest_addThem
Java_AsmTest_addThem:
mov rax, rdx
add rax, rcx
ret
public class AsmTest {
public static native int addThem(int a, int b);
static {
// Looks for libaddThem.so or addThem.dll, depending on the OS
System.loadLibrary("addThem");
}
public static void main(String[] args) {
int result = addThem(4, 5);
System.out.println("Result: " + result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment