Created
March 15, 2016 00:11
-
-
Save engelmarkus/b3be3f2aeec567356cf8 to your computer and use it in GitHub Desktop.
Calling an assembly function from Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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$ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[BITS 64] | |
GLOBAL Java_AsmTest_addThem | |
Java_AsmTest_addThem: | |
mov rax, rdx | |
add rax, rcx | |
ret |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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