Skip to content
Open
Show file tree
Hide file tree
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 Jul 13, 2026
834182f
Add export-list generator and generated .lds files
zzcgumn Jul 13, 2026
dd460be
Add cc_shared_library target and export-set test
zzcgumn Jul 13, 2026
322f5df
Add rules_java and a hermetic JDK 25 toolchain for FFM bindings
zzcgumn Jul 13, 2026
a979e89
Add hand-written FFM bindings for the shared library
zzcgumn Jul 14, 2026
c92cae3
Add end-to-end FFM smoke test
zzcgumn Jul 14, 2026
6921f1e
Add docs/jni_interface.md — JVM/FFM interface guide
zzcgumn Jul 14, 2026
868b83e
docs(spec): add shared_library capability for ship_shared_lib
zzcgumn Jul 14, 2026
db43a2c
chore: deletes file generated by claude that was included accidentally.
zzcgumn Jul 14, 2026
fcf2564
Broaden FFM and generator test coverage
zzcgumn Jul 14, 2026
9d0a174
Add rules_jvm_external for Java packaging
zzcgumn Jul 14, 2026
eb5e61b
Add Dds.loadEmbedded() for native-in-jar extraction
zzcgumn Jul 14, 2026
2714749
Add native-embedding java_export dds_ffm_dist
zzcgumn Jul 14, 2026
820f231
Add embedded-load smoke test
zzcgumn Jul 14, 2026
5245f6e
Document native-in-jar packaging and local ~/.m2 install
zzcgumn Jul 14, 2026
8739488
Fix native-in-jar packaging: arch, dedup, Windows copy, version
zzcgumn Jul 14, 2026
073050b
Close the Arena when library load fails
zzcgumn Jul 14, 2026
32a56ac
Derive export_set_test expectations from headers, not the .lds
zzcgumn Jul 14, 2026
370d7d1
Harden native-in-jar staging: shell-free copy, localize platform support
zzcgumn Jul 14, 2026
8efe07e
Add jar self-containedness test
zzcgumn Jul 14, 2026
e965bf3
Make export_set_test's nm usage portable
zzcgumn Jul 14, 2026
94d73e0
Bump bazel_skylib pin to 1.9.0 to match the resolved graph
zzcgumn Jul 14, 2026
d25287a
address PR review feedback
zzcgumn Jul 15, 2026
4cd82ad
address PR review feedback
zzcgumn Jul 15, 2026
189a1fc
address PR review feedback
zzcgumn Jul 15, 2026
aa4200f
address PR review feedback
zzcgumn Jul 15, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .bazelrc
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ test --test_tag_filters=-e2e

common --enable_platform_specific_config

# Java toolchain for the FFM bindings (//jni:*). JDK 25 is the hermetic remote
# JDK shipped by rules_java 9.6.1; being >= 22 it exposes java.lang.foreign as a
# stable (non-preview) API, so no --enable-preview is needed. Inert for the
# C++/WASM/Python targets. Per-test native-access flags live on the java_test.
build --java_language_version=25
build --java_runtime_version=remotejdk_25
build --tool_java_language_version=25
build --tool_java_runtime_version=remotejdk_25

# Platform-specific C++ standard flags
build:macos --cxxopt=-std=c++20
build:macos --host_cxxopt=-std=c++20
Expand Down
13 changes: 13 additions & 0 deletions MODULE.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ module(

bazel_dep(name = "rules_cc", version = "0.2.18")
bazel_dep(name = "platforms", version = "1.1.0")
# copy_file (shell-free, cross-platform) for staging the native lib into the jar.
# Pin to the version the graph resolves (via rules_jvm_external) to avoid a
# direct-dependency mismatch warning on every invocation.
bazel_dep(name = "bazel_skylib", version = "1.9.0")
bazel_dep(name = "googletest", version = "1.17.0.bcr.2")
bazel_dep(name = "pybind11_bazel", version = "3.0.1")
bazel_dep(name = "rules_python", version = "2.0.1")
Expand All @@ -17,6 +21,15 @@ bazel_dep(name = "apple_support", version = "1.24.2")
# WASM builds (//wasm:*, //web:dds_mvp_wasm). If you bump this version,
# rebuild and run web/update_wasm.sh; see docs/wasm_build.md and patch_mvp_wasm.py.
bazel_dep(name = "emsdk", version = "5.0.7")
# Java bindings (//jni:*). Provides the hermetic remote JDK used to build and run
# the FFM (java.lang.foreign) smoke test. rules_java 9.6.1 registers remotejdk_21
# and remotejdk_25; we pin JDK 25 (>= 22, so the Foreign Function & Memory API is
# stable, not preview) via --java_*_version in .bazelrc.
bazel_dep(name = "rules_java", version = "9.6.1")
# Java packaging (//jni:dds_ffm_dist). Provides java_export -> a Maven-coordinate
# jar plus a generated .publish target that supports file:// local repos, used to
# install into ~/.m2 (Phase 1; no remote/public publishing yet).
bazel_dep(name = "rules_jvm_external", version = "7.0")

llvm = use_extension("@toolchains_llvm//toolchain/extensions:llvm.bzl", "llvm")
llvm.toolchain(
Expand Down
494 changes: 441 additions & 53 deletions MODULE.bazel.lock

Large diffs are not rendered by default.

216 changes: 216 additions & 0 deletions docs/jni_interface.md
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
Comment thread
zzcgumn marked this conversation as resolved.
Outdated
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.
Loading
Loading