207 points · by pjmlp · 2y ago · 143 comments
I have bundled shared libraries for five or six platforms in a java library that needs to make syscalls. It works but it is a pain if anything ever changes or a new platform needs to be brought up. Checking in binaries always feels icky but is necessary if not all targets can be built on a single machine.
The problem with the new api is that people upgrade java very slowly in most contexts. For an oss library developer, I see very little value add in this feature because I'm still stuck for all of my users who are using an older version of java. If I integrate the new ffi api, now I have to support both it and the jni api.
There are several, including SWIG.
All the good bindings I use are generated by custom systems (ie, usually some Python scripts) tailored for the specific way their library works.
> It works but it is a pain if anything ever changes or a new platform needs to be brought up. Checking in binaries always feels icky but is necessary if not all targets can be built on a single machine.
It is definitely a pain when you cannot test all changes on a single local machine. But I would argue that it is true whenever multiple platforms (or maybe even multiple glibc versions) are involved, regardless of what languages/libraries/tools you use.
[1] https://libgdx.com/wiki/utils/jnigen [2] https://github.com/libgdx/libgdx [3] https://github.com/gudzpoz/luajava
Every ffi example I've found seem to operate on the assumption that you want to invoke syscalls or libc, which (with possibly the exception of like madvise and aioring) Java already mostly has decent facilities to interact with even without native calls.
For example, each these jars named "native-$os-$arch.jar" contain a .dll/.so/.dylib: https://repo1.maven.org/maven2/com/aayushatharva/brotli4j/
JNA will extract the appropriate native library (using os.name and os.arch system properties), save the library to a temp file, then load it.
> JNA will extract the appropriate native library ..., save the library to a temp file, then load it.
JNA does this?FYI: JNA = Java Native Access project: https://github.com/java-native-access/jna
Because you would use ffi to interact with libraries that don't have Java wrappers yet: IE, you're writing the wrapper.
Using syscalls or libc is a way to write an example against a known library that you're probably familiar with.
[1]: Technically, this is the only distribution model because all Java runtimes as of JDK 9 are created with jlink, including the runtime included in the JDK (which many people use as-is), but I mean a custom runtime packaged with the application.
Java libraries are still obtained from Maven repositories via Maven/Gradle/Ant/Bazel/etc.
I’ve met many perfectly reasonable developers who do know all those steps can be done but can’t put them all together - maybe because it just hasn’t clicked that you can store a library in a jar. It feels like something tutorials should cover, but I think falls into the, “surely everyone can work it out?” category.
actually you delete it immediately (after load) on anything that's not windows... even then but it's likely to return false.
deleteOnExit just stores the path to delete and uses a shutdownHook to actually call delete. Nothing really special about it
i wonder if there's a way to do this entirely in memory? Because some deployment scenarios might not have disk space at all.
Edit: glibc proposal which was never accepted: https://sourceware.org/bugzilla/show_bug.cgi?id=11767
- Find all the shared libraries in your JARs or configured app inputs (files in your build/source tree)
- Sniff them to figure out what OS and CPU arch they are for
- Bundle them into the right package for each platform that it makes, in the right place to be found by System.loadLibrary()
- Sign them if necessary
- Delete them from the JARs now they are extracted. Optionally extract them from library JARs, sign them and then put them back if your library refuses to load the shared library from disk instead of unpacking it (most libs don't need this)
- JLink a bundled JVM for your app for each platform you target, using jdeps to figure out the right set of modules, and combine that with your shared libs.
When building Debian/Ubuntu packages it will also:
- Read the .so library dependencies, look up the packages that contain those other shared libraries and add package dependencies on those packages, so "apt install" will do the right thing.
So that makes it a lot easier to distribute Java apps that use native code.
I was on the assumption that it was dynamically linking the libarary with the OS dynamic linker, which in no OS I'm aware of is capable of loading libraries inside of zip files.
Not sure where I got that notion. Maybe I was overthinking this.
In C# I can just do something like this conceptual code:
```
// FILE *fopen(const char *filename, const char *mode)
[DllImport("libc")] public unsafe extern nint fopen([MarshalAs(UnmanagedType.LPStr)] string filename, [MarshalAs(UnmanagedType.LPStr)] string mode);
// char *fgets(char *str, int n, FILE *stream)
[DllImport("libc")] public unsafe extern nint fgets([MarshalAs(UnmanagedType.LPStr)] string str, int n, nint stream);
// int fclose(FILE *stream)
[DllImport("libc")] public unsafe extern int fclose(nint stream);
```
So much less code, and so much more precise than any of the Java JNI and FFI stuff.
I'm sure someone will come along and write annotations to do exactly as you describe there. The Java language folks tend to be very conservative about putting stuff in the official API, cuz they know it'll have to stay there for 30+ years. They prefer to let the community write something like annotations over low-level APIs.
Anyway, the GraalVM folks don't have quite the same limitations as Java, so they have annotations already (https://yyhh.org/blog/2021/02/writing-c-code-in-javaclojure-...):
@CStruct("MDB_val")
public interface MDB_val extends PointerBase {
@CField("mv_size")
long get_mv_size();
@CField("mv_size")
void set_mv_size(long value);
@CField("mv_data")
VoidPointer get_mv_data();
@CField("mv_data")
void set_mv_data(VoidPointer value);
} var text = "Hello, World!"u8;
write(1, text, text.Length);
[DllImport("libc")]
static extern nint write(nint fd, ReadOnlySpan<byte> buf, nint count);
(note: it's recommended to use [LibraryImport] instead for p/invoke declarations that require marshalling as it does not require JIT/runtime marshalling but just generates (better) p/invoke stub at build time)[0] https://gist.github.com/raysan5/17392498d40e2cb281f5d09c0a4b...
But if you want to use SDL2 from something higher-level, you will be much better served by C# which will give you minimal FFI cost and most data structures you want to express in C as-is.
When I played with this new java api. I wasn't worried about the FFI cost. It seemed fast enough to me. My toy application was performing about 0.77x of pure C equivalent. I think Java's memory model and heavy heap use might hurt more. Hopefully Java will catch up when it gets value objects with Project Valhalla. Next decade or so :)
In improbable case you may want to try it out, then all it needs is
- SDK from https://dot.net/download (or package manager of your choice if you are on Linux e.g. `sudo apt-get install dotnet-sdk-8.0`, !do not! use Homebrew if you are on macOS however, use .pkg installer)
- C# extension for VS Code (DevKit is not needed)
- SDL2 abstraction: https://github.com/dotnet/Silk.NET (there are all sorts of alternate bindings depending on your preferences)
C# also has function pointers (managed/unmanaged) and C exports with NativeAOT.
Might just build a SDL2-wrapper for ffi just as an FFI and FMI-exercise.
Very useful, especially the prebundled platform bindings.
The Swift folks have put a lot of effort into attaining a stable ABI that's native to their language. They can achieve that because Swift is the officially endorsed language for development on Mac OS and iOS, so it (together with the platform itself) can set a standard that other languages will have to live with.
In a way, software VM's like the JVM and CLR can also be said to define 'ABIs' of sorts within their runtime, that every language implementation on these runtimes will have to deal with.
I can also point to the GCC Inline Assembler as an excellent way to call arbitrary functions whether they implement the standard C procedure call standard or not. By providing the list of arguments and what register they correspond to, along with the clobber list, you know everything you need to know to call the function. So it's more suitable for "fastcall" type functions where you need the arguments to correspond to particular registers.
But of course, ASM isn't portable.
It describes how to adopt memory from C and have C adopt memory you allocate, and gives control over how memory is allocated in an arena.
The arena has lifecycle boundaries, and allocations determine the memory space available. Java guarantees (only) that you can't use unallocated memory or memory outside the arena, and if you access via a (correct) value layout, you should be able to navigate structure correctly.
The interesting stuff is passing function pointers back and forth - look for `downcall method handles`.
Tried it again yesterday on java 22, and the helpers from jextract are waaaay better. I actually completed a MVP implementation this time in a couple of hours. This could perhaps be released as library if I find the effort to wrap it in a meaningful way!
We currently wrap this in java by calling the binary with subprocesses, which has been working great at some latency overhead. The big bonus of this though, is that we can kill the process from java when it misbehaves. Putting this C code inside Java again, means we likely lose that control.
Glad to see things are progressing!!
This is similar, except more boilerplate and much, much slower.
[0] Objects that need pinning are pinned(by toggling a bit in object header), byrefs are pinned by simply storing them on the stack, arguments that need marshalling involve calling corresponding marshalling code. That code can allocate intermediate data on heap, on stack or call NativeMemory.Alloc/.Free C-style.
[1] Overhead can be further reduced by 1. annotating FFI calls with [SuppressGCTransition] which saves on possible arguments stack spills and GC helper call, replacing the call with a single flag check and optional call into GC in epilog, 2. in NativeAOT, p/invokes can be "direct" which saves on initialization checks and indirections (though they are reduced in JIT as it can bake data directly into codegen after static init has finished on recompilation). This has a tradeoff as system's dynamic loader will be used at application startup instead of regular lazy initialization and 3. direct p/invokes can be upgraded to static linking, which transforms them into direct calls identical to regular C calls save for the same GC flag check in post-condition. This comes with compiling .NET executables and libraries into a single statically linked binary (well, statically linked for the native dependencies the user has opted into linking this way).
While a step closer to Valhala, the whole dev experience is still quite lacking versus what .NET offers.
Currently is too much like making direct use of InteropServices.
Doubtful, given that this is something we worked hard to avoid. To be efficient, a P/Invoke-like model places restrictions on the runtime, which inhibits optimisation and flexibility and this cost is worth it only when native calls are relatively common. In Java they are rare and easily abstracted away, so we opted for a model that offers full control without giving up on abstraction, given that only a very small number of experts (<1%) would directly write native calls and then hide them as implementation details. I'm not saying this approach is the right one for all languages, but it's clearly the right one for Java given the frequency of native calls and who makes them.
Of course, you can wrap FFM with a higher-level P/Invoke-like mechanism, but it won't give you as much control.
That's JNI, which really was truly terrible. Java 22 introducing FFM is finally an admission that JNI was crap and a dead end.