Skip to content

Instantly share code, notes, and snippets.

@sureshg
Created May 9, 2023 01:19
Show Gist options
  • Save sureshg/8f624e3fd0d26f762c95cbe8afc8fa2b to your computer and use it in GitHub Desktop.
Save sureshg/8f624e3fd0d26f762c95cbe8afc8fa2b to your computer and use it in GitHub Desktop.
FFM API crash
#!/usr/bin/env java --enable-preview --enable-native-access=ALL-UNNAMED --source 21
import java.lang.foreign.*;
import java.lang.foreign.MemoryLayout.PathElement;
import java.lang.invoke.MethodHandle;
public class FFMCrash {
static Linker LINKER = Linker.nativeLinker();
static SymbolLookup loaderLookup = SymbolLookup.loaderLookup();
static SymbolLookup SYMBOL_LOOKUP = name -> loaderLookup.find(name).or(() -> LINKER.defaultLookup().find(name));
public static void main(String[] args) throws Throwable {
var winsize =
MemoryLayout.structLayout(
ValueLayout.JAVA_SHORT.withName("ws_row"),
ValueLayout.JAVA_SHORT.withName("ws_col"),
ValueLayout.JAVA_SHORT.withName("ws_xpixel"),
ValueLayout.JAVA_SHORT.withName("ws_ypixel")
)
.withName("winsize");
var wsRow = winsize.varHandle(PathElement.groupElement("ws_row"));
var wsCol = winsize.varHandle(PathElement.groupElement("ws_col"));
var wsXpixel = winsize.varHandle(PathElement.groupElement("ws_xpixel"));
var wsYpixel = winsize.varHandle(PathElement.groupElement("ws_ypixel"));
var ioctlDesc =
FunctionDescriptor.of(
ValueLayout.JAVA_INT,
ValueLayout.JAVA_INT,
ValueLayout.JAVA_LONG,
ValueLayout.ADDRESS.withTargetLayout(winsize));
var ioctl = downcallHandle("ioctl", ioctlDesc);
try (var arena = Arena.ofConfined()) {
var winSeg = arena.allocate(winsize);
var winRet = (int) ioctl.invokeExact(1, 0x40087468L, winSeg);
System.out.println(wsRow.get(winSeg));
System.out.println(wsCol.get(winSeg));
}
}
static MethodHandle downcallHandle(String name, FunctionDescriptor fdesc) {
return SYMBOL_LOOKUP.find(name).
map(addr -> LINKER.downcallHandle(addr, fdesc)).
orElse(null);
}
}
@sureshg
Copy link
Author

sureshg commented May 9, 2023

ENV

MacOS: Ventura ARM64
13.3.1
Software:

    System Software Overview:

      System Version: macOS 13.3.1 (22E261)
      Kernel Version: Darwin 22.4.0

RUN

$ sdk install java  21.ea.21-open
$ sdk u java  21.ea.21-open
$ chmod +x FFMCrash
$ ./FFMCrash

@sureshg
Copy link
Author

sureshg commented May 9, 2023

#include <stdio.h>
#include <unistd.h>
#include <sys/ioctl.h>

int main() {
    struct winsize size;

    if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) == -1) {
        perror("ioctl");
        return 1;
    }

    printf("Terminal size: %d rows x %d columns\n", size.ws_row, size.ws_col);

    return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment