Created
March 2, 2024 17:03
-
-
Save dashaw92/29af619004c07f4c39daf759cf08ccd8 to your computer and use it in GitHub Desktop.
Testing Project Panama in JDK 22
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
package me.daniel.panama; | |
import java.lang.foreign.*; | |
import java.lang.invoke.MethodHandle; | |
public class PanamaMain { | |
public static void main(String[] args) throws Throwable { | |
Linker linker = Linker.nativeLinker(); | |
SymbolLookup libc = linker.defaultLookup(); | |
try(Arena arena = Arena.ofConfined()) { | |
tryPrintf(linker, libc).invoke(arena.allocateFrom("Hello from Panama!\n")); | |
SymbolLookup user32 = SymbolLookup.libraryLookup("User32", arena); | |
var mba = MessageBoxA(linker, user32); | |
mba.invoke( | |
MemorySegment.NULL, | |
arena.allocateFrom("Hello from Panama!\nThis works well!"), | |
arena.allocateFrom("Title!"), | |
0 | |
); | |
} | |
} | |
private static MethodHandle tryPrintf(Linker linker, SymbolLookup libc) { | |
FunctionDescriptor printfDesc = FunctionDescriptor.of(ValueLayout.JAVA_INT, AddressLayout.ADDRESS); | |
return libc.find("printf") | |
.map(seg -> linker.downcallHandle(seg, printfDesc)) | |
.orElseThrow(); | |
} | |
private static MethodHandle MessageBoxA(Linker linker, SymbolLookup libc) { | |
FunctionDescriptor mbaDesc = FunctionDescriptor.of( | |
ValueLayout.JAVA_INT, | |
AddressLayout.ADDRESS, | |
AddressLayout.ADDRESS.withTargetLayout(MemoryLayout.sequenceLayout(1024, ValueLayout.JAVA_BYTE)), | |
AddressLayout.ADDRESS.withTargetLayout(MemoryLayout.sequenceLayout(1024, ValueLayout.JAVA_BYTE)), | |
AddressLayout.JAVA_INT | |
); | |
return libc.find("MessageBoxA") | |
.map(seg -> linker.downcallHandle(seg, mbaDesc)) | |
.orElseThrow(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment