-
Notifications
You must be signed in to change notification settings - Fork 118
Ship a JVM-consumable native shared library #233
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
zzcgumn
wants to merge
26
commits into
develop
Choose a base branch
from
feat/shared_lib_and_jni
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 23 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
4d41f18
Add pure-C ABI shim over the modern SolverContext API
zzcgumn 834182f
Add export-list generator and generated .lds files
zzcgumn dd460be
Add cc_shared_library target and export-set test
zzcgumn 322f5df
Add rules_java and a hermetic JDK 25 toolchain for FFM bindings
zzcgumn a979e89
Add hand-written FFM bindings for the shared library
zzcgumn c92cae3
Add end-to-end FFM smoke test
zzcgumn 6921f1e
Add docs/jni_interface.md — JVM/FFM interface guide
zzcgumn 868b83e
docs(spec): add shared_library capability for ship_shared_lib
zzcgumn db43a2c
chore: deletes file generated by claude that was included accidentally.
zzcgumn fcf2564
Broaden FFM and generator test coverage
zzcgumn 9d0a174
Add rules_jvm_external for Java packaging
zzcgumn eb5e61b
Add Dds.loadEmbedded() for native-in-jar extraction
zzcgumn 2714749
Add native-embedding java_export dds_ffm_dist
zzcgumn 820f231
Add embedded-load smoke test
zzcgumn 5245f6e
Document native-in-jar packaging and local ~/.m2 install
zzcgumn 8739488
Fix native-in-jar packaging: arch, dedup, Windows copy, version
zzcgumn 073050b
Close the Arena when library load fails
zzcgumn 32a56ac
Derive export_set_test expectations from headers, not the .lds
zzcgumn 370d7d1
Harden native-in-jar staging: shell-free copy, localize platform support
zzcgumn 8efe07e
Add jar self-containedness test
zzcgumn e965bf3
Make export_set_test's nm usage portable
zzcgumn 94d73e0
Bump bazel_skylib pin to 1.9.0 to match the resolved graph
zzcgumn d25287a
address PR review feedback
zzcgumn 4cd82ad
address PR review feedback
zzcgumn 189a1fc
address PR review feedback
zzcgumn aa4200f
address PR review feedback
zzcgumn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,216 @@ | ||
| # DDS on the JVM — Foreign Function & Memory (FFM) interface | ||
|
|
||
| This document explains how to build the DDS native shared library and call the | ||
| Double Dummy Solver from Java using the **Foreign Function & Memory API** | ||
| (Project Panama, `java.lang.foreign`). No hand-written JNI C/C++ glue is | ||
| required: the JVM loads the plain C ABI directly. | ||
|
|
||
| The bindings live under [`//jni`](../jni) and mirror how the other language | ||
| bindings work — see [python_interface.md](python_interface.md), | ||
| [dotnet_interface.md](dotnet_interface.md), and [wasm_build.md](wasm_build.md). | ||
|
|
||
| ## Table of Contents | ||
| 1. [Prerequisites](#prerequisites) | ||
| 2. [Building the shared library](#building-the-shared-library) | ||
| 3. [The pure-C ABI shim](#the-pure-c-abi-shim) | ||
| 4. [Using the FFM bindings](#using-the-ffm-bindings) | ||
| 5. [Worked example](#worked-example) | ||
| 6. [Loading and running](#loading-and-running) | ||
| 7. [Packaging & local install](#packaging--local-install) | ||
| 8. [Threading and lifecycle](#threading-and-lifecycle) | ||
| 9. [Not yet supported](#not-yet-supported) | ||
|
|
||
| --- | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| - **JDK 22 or later.** `java.lang.foreign` is a stable API from JDK 22, so no | ||
| `--enable-preview` is needed. The Bazel build is hermetic: `rules_java` | ||
| supplies the JDK (currently pinned to `remotejdk_25` in | ||
| [`.bazelrc`](../.bazelrc)); you do **not** need a system JDK installed. | ||
| - **Bazel 7.x or later**, as for the rest of the project. | ||
|
|
||
| No `jextract` install is required — the bindings are hand-written (see | ||
| [Using the FFM bindings](#using-the-ffm-bindings)). | ||
|
|
||
| ## Building the shared library | ||
|
|
||
| ```bash | ||
| bazel build //jni:dds_shared | ||
| ``` | ||
|
|
||
| This produces one self-contained native library rolling up the entire solver | ||
| (all internal sub-libraries are linked in statically), named per OS: | ||
|
|
||
| | OS | Artifact | Location | | ||
| | ------- | -------------------- | ------------------- | | ||
| | Linux | `libdds.so` | `bazel-bin/jni/` | | ||
| | macOS | `libdds.dylib` | `bazel-bin/jni/` | | ||
| | Windows | `dds.dll` | `bazel-bin/jni/` | | ||
|
|
||
| Only the public C API is exported. Exports are constrained at link time by the | ||
| generated `jni/version_script.lds` (Linux) and `jni/exported_symbols.lds` | ||
| (macOS); on Windows the existing `__declspec(dllexport)` markers drive exports. | ||
| The lists are generated from the headers by `jni/gen_export_lists.py` and | ||
| verified by `//jni/tests:export_set_test`, which asserts the library exports | ||
| exactly the public symbols and leaks no internal C++ symbols. | ||
|
|
||
| ## The pure-C ABI shim | ||
|
|
||
| The modern context API in `library/src/api/dds_api.hpp` takes C++ references and | ||
| C++ types (`const Deal&`, `SolverConfig`, `TTKind`), which are not addressable | ||
| from a pure-C FFI. The shim [`library/src/api/dds_c_api.h`](../library/src/api/dds_c_api.h) | ||
| wraps it with a clean, C-valid, pointer-only, POD-only surface that Java, .NET, | ||
| and ctypes can all bind to: | ||
|
|
||
| - The solver handle is opaque: `typedef void* DDS_C_SOLVER_CTX`. | ||
| - Every struct is passed by pointer; no non-POD C++ type crosses the boundary. | ||
|
|
||
| Shim entry points: `dds_c_create_solvercontext_default`, | ||
| `dds_c_destroy_solvercontext`, `dds_c_solve_board`, `dds_c_calc_dd_table`, | ||
| `dds_c_calc_par`. The flat legacy C API from `dll.h` (`SolveBoard`, | ||
| `CalcDDtable`, `GetDDSInfo`, `ErrorMessage`, …) is exported unchanged and is | ||
| also callable from FFM. | ||
|
|
||
| ## Using the FFM bindings | ||
|
|
||
| `//jni:dds_ffm` provides the Java bindings in package `org.dds.ffm` | ||
| ([`Dds.java`](../jni/java/org/dds/ffm/Dds.java)). They are **hand-written** | ||
| rather than generated by `jextract`: `jextract` is distributed only as | ||
| non-hermetic early-access binaries, and the generated output is just plain | ||
| `java.lang.foreign` code, so the bindings are checked in directly. `Dds` | ||
| exposes: | ||
|
|
||
| - Public `MemoryLayout` constants matching the C structs: `DEAL`, | ||
| `FUTURE_TRICKS`, `DD_TABLE_DEAL`, `DD_TABLE_RESULTS`, `DDS_INFO`. | ||
| - Typed downcall wrappers for the shim functions plus `getDdsInfo`. | ||
| - `Dds.load(Path)` — loads the library via `SymbolLookup.libraryLookup` over an | ||
| owned `Arena`; `Dds` is `AutoCloseable`. | ||
|
|
||
| Depend on it from your own `java_library`/`java_binary`: | ||
|
|
||
| ```python | ||
| java_binary( | ||
| name = "my_app", | ||
| srcs = ["MyApp.java"], | ||
| deps = ["//jni:dds_ffm"], | ||
| data = ["//jni:dds_shared"], | ||
| jvm_flags = ["--enable-native-access=ALL-UNNAMED"], | ||
| ) | ||
| ``` | ||
|
|
||
| ## Worked example | ||
|
|
||
| Solve a single board (North holds all spades with spades trump — 13 tricks): | ||
|
|
||
| ```java | ||
| import static java.lang.foreign.ValueLayout.JAVA_INT; | ||
| import java.lang.foreign.Arena; | ||
| import java.lang.foreign.MemoryLayout.PathElement; | ||
| import java.lang.foreign.MemorySegment; | ||
| import java.nio.file.Path; | ||
| import org.dds.ffm.Dds; | ||
|
|
||
| try (Dds dds = Dds.load(Path.of(System.getProperty("dds.library.path"))); | ||
| Arena arena = Arena.ofConfined()) { | ||
|
|
||
| long remain = Dds.DEAL.byteOffset(PathElement.groupElement("remainCards")); | ||
| MemorySegment deal = arena.allocate(Dds.DEAL); // zero-initialised | ||
| // trump = spades (0), first = North (0) are already 0. | ||
| deal.set(JAVA_INT, remain + 0L * 4, 0x7FFC); // North spades | ||
| deal.set(JAVA_INT, remain + 5L * 4, 0x7FFC); // East hearts | ||
| deal.set(JAVA_INT, remain + 10L * 4, 0x7FFC); // South diamonds | ||
| deal.set(JAVA_INT, remain + 15L * 4, 0x7FFC); // West clubs | ||
|
|
||
| MemorySegment ctx = dds.createSolverContext(); | ||
| try { | ||
| MemorySegment fut = arena.allocate(Dds.FUTURE_TRICKS); | ||
| int rc = dds.solveBoard(ctx, deal, -1, 1, 1, fut); // target, solutions, mode | ||
| long score = Dds.FUTURE_TRICKS.byteOffset(PathElement.groupElement("score")); | ||
| System.out.println("tricks = " + fut.get(JAVA_INT, score)); // 13 | ||
| } finally { | ||
| dds.destroySolverContext(ctx); | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| `remainCards` is a `[hand][suit]` array with 4 suits per hand, so element | ||
| `[hand][suit]` is at index `hand * 4 + suit`. Holdings are 13-bit rank masks | ||
| (`0x7FFC` = all ranks 2..A). See | ||
| [`DdsSmokeTest.java`](../jni/java/org/dds/ffm/DdsSmokeTest.java) for a complete, | ||
| tested program including `GetDDSInfo`. | ||
|
|
||
| ## Loading and running | ||
|
|
||
| There are two ways to load the native library: | ||
|
|
||
| - **`Dds.loadEmbedded()`** (default) — extracts the library bundled in the jar | ||
| for the current OS/arch (from the classpath resource | ||
| `native/<os>-<arch>/<lib>`) to a temp file and loads it. Zero configuration; | ||
| this is what the published jar (below) is for. Host-platform only for now. | ||
| - **`Dds.load(Path)`** — loads a library at an explicit filesystem path via | ||
| `SymbolLookup.libraryLookup`, with no reliance on `System.loadLibrary` / | ||
| `java.library.path`. Useful when you built `//jni:dds_shared` yourself; in | ||
| Bazel, make it a `data` dependency and pass its runfiles path, e.g. | ||
| `-Ddds.library.path=$(rootpath //jni:dds_shared)`. | ||
|
|
||
| FFM downcalls are restricted native operations. Run with | ||
| `--enable-native-access=ALL-UNNAMED` (as a `jvm_flag` or on the `java` | ||
| command line) to grant access and silence the runtime warning. | ||
|
|
||
| The end-to-end smoke tests wire all of this together: | ||
|
|
||
| ```bash | ||
| bazel test //jni:dds_ffm_smoke_test # explicit-path loading | ||
| bazel test //jni:dds_ffm_embedded_smoke_test # loadEmbedded() from the jar | ||
| ``` | ||
|
|
||
| ## Packaging & local install | ||
|
|
||
| `//jni:dds_ffm_dist` is a `java_export` producing a Maven-coordinate jar, | ||
| `org.dds:dds-ffm:3.0.1`, that **embeds the host-platform native library** under | ||
| `native/<os>-<arch>/` — so a consumer needs only the jar and | ||
| `Dds.loadEmbedded()`, no separate `.so`/`.dylib`/`.dll` to locate. | ||
|
|
||
| Install it into your local Maven repository (`~/.m2`): | ||
|
|
||
| ```bash | ||
| bazel run //jni:dds_ffm_dist.publish \ | ||
| --define maven_repo="file://$HOME/.m2/repository" \ | ||
| --define gpg_sign=false | ||
| ``` | ||
|
|
||
| This deposits the main jar plus `-sources`, `-javadoc`, and the generated POM | ||
| under `org/dds/dds-ffm/3.0.1/`. Another project on the same machine can then | ||
| depend on it: | ||
|
|
||
| ```kotlin | ||
| implementation("org.dds:dds-ffm:3.0.1") // Gradle | ||
| ``` | ||
| ```xml | ||
| <dependency><groupId>org.dds</groupId><artifactId>dds-ffm</artifactId><version>3.0.1</version></dependency> | ||
| ``` | ||
|
|
||
| The bundled native library is **host-platform only** — the jar built on macOS | ||
| contains the macOS `.dylib` and so on. A single multi-OS/arch ("fat") jar and | ||
| publishing to a public/remote repository are not yet available (see below). | ||
|
|
||
| ## Threading and lifecycle | ||
|
|
||
| Each `DDS_C_SOLVER_CTX` owns per-context solver state and its own transposition | ||
| table. A context is **not** thread-safe: use one solver context per thread. | ||
| Always release a context with `destroySolverContext` (the example above does so | ||
| in a `finally` block). Because the modern context API owns its state | ||
| per-handle, no global `InitializeStaticMemory` call is required before solving | ||
| through the shim. | ||
|
|
||
| ## Not yet supported | ||
|
|
||
| - **Remote/public publishing** — only local `~/.m2` installs are wired today. | ||
| Publishing to Maven Central (OSSRH + GPG signing) or GitHub Packages is not | ||
| yet set up. | ||
| - **Multi-OS/arch "fat" jar** — the jar bundles only the host platform's native | ||
| library. Producing one jar with every triplet requires a CI matrix building | ||
| each platform and a final assembly step. | ||
| - **Hand-written JNI convenience API** (idiomatic `native`-method Java classes) | ||
| — deferred; the FFM path above is the supported route. | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.