Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
8204133
Add pure-C ABI shim over the modern SolverContext API
zzcgumn Jul 13, 2026
de826bd
Add export-list generator and generated .lds files
zzcgumn Jul 13, 2026
c4c9c85
Add cc_shared_library target and export-set test
zzcgumn Jul 13, 2026
f48575c
Add rules_java and a hermetic JDK 25 toolchain for FFM bindings
zzcgumn Jul 13, 2026
d3adce3
Add hand-written FFM bindings for the shared library
zzcgumn Jul 14, 2026
17c81c8
Add end-to-end FFM smoke test
zzcgumn Jul 14, 2026
022e674
Add docs/jni_interface.md — JVM/FFM interface guide
zzcgumn Jul 14, 2026
8d9ce0d
docs(spec): add shared_library capability for ship_shared_lib
zzcgumn Jul 14, 2026
d5ec591
chore: deletes file generated by claude that was included accidentally.
zzcgumn Jul 14, 2026
1d8e1d4
Broaden FFM and generator test coverage
zzcgumn Jul 14, 2026
9bcb248
Add rules_jvm_external for Java packaging
zzcgumn Jul 14, 2026
07db6ad
Add Dds.loadEmbedded() for native-in-jar extraction
zzcgumn Jul 14, 2026
354793c
Add native-embedding java_export dds_ffm_dist
zzcgumn Jul 14, 2026
c25196a
Add embedded-load smoke test
zzcgumn Jul 14, 2026
fc8069d
Document native-in-jar packaging and local ~/.m2 install
zzcgumn Jul 14, 2026
d52e864
Fix native-in-jar packaging: arch, dedup, Windows copy, version
zzcgumn Jul 14, 2026
7ba4141
Close the Arena when library load fails
zzcgumn Jul 14, 2026
b56f956
Derive export_set_test expectations from headers, not the .lds
zzcgumn Jul 14, 2026
43710b4
Harden native-in-jar staging: shell-free copy, localize platform support
zzcgumn Jul 14, 2026
3e61d38
Add jar self-containedness test
zzcgumn Jul 14, 2026
0a824d0
Make export_set_test's nm usage portable
zzcgumn Jul 14, 2026
f36c323
Bump bazel_skylib pin to 1.9.0 to match the resolved graph
zzcgumn Jul 14, 2026
6bcdb6a
address PR review feedback
zzcgumn Jul 15, 2026
ed8385b
address PR review feedback
zzcgumn Jul 15, 2026
f9b9dcc
address PR review feedback
zzcgumn Jul 15, 2026
0c5a4df
address PR review feedback
zzcgumn Jul 15, 2026
b61af9d
address PR review feedback
zzcgumn Jul 15, 2026
f68f475
address PR review feedback
zzcgumn Jul 15, 2026
4fe268f
address PR review feedback
zzcgumn Jul 16, 2026
c0ae548
address PR review feedback
zzcgumn Jul 16, 2026
a06b305
Potential fix for pull request finding
zzcgumn Jul 16, 2026
872224a
Potential fix for pull request finding
zzcgumn Jul 16, 2026
6a26c3c
Potential fix for pull request finding
zzcgumn Jul 16, 2026
c72487e
Potential fix for pull request finding
zzcgumn Jul 16, 2026
68d4ae5
Potential fix for pull request finding
zzcgumn Jul 16, 2026
79409f9
Potential fix for pull request finding
zzcgumn Jul 17, 2026
1d28160
address PR review feedback
zzcgumn Jul 17, 2026
1002854
fix: removes final from the Dds class definition.
zzcgumn Jul 17, 2026
3a6f88d
Potential fix for pull request finding
zzcgumn Jul 17, 2026
ab4a10c
Potential fix for pull request finding
zzcgumn Jul 18, 2026
2ef0c47
fix: adds the 64-bit JVM and par_result to the jni_interface doc.
zzcgumn Jul 18, 2026
31d4351
address PR review feedback
zzcgumn Jul 18, 2026
e9978a7
fix: stop rules_android's SDK probe from breaking non-Android builds
zzcgumn Jul 18, 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
21 changes: 21 additions & 0 deletions .bazelrc
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,27 @@ test --test_tag_filters=-e2e

common --enable_platform_specific_config

# We build nothing for Android, but rules_jvm_external (the //jni Maven jar)
# depends on rules_android, whose android_sdk_repository extension probes
# $ANDROID_HOME while analysing *any* target. When ANDROID_HOME is exported but
# the SDK has no platform APIs installed — as on GitHub's ubuntu runners after
# the free-disk-space step removes the SDK — that extension hard-fails and takes
# down unrelated builds (e.g. //wasm, //web). Pinning the var to empty makes the
# extension emit its empty stub repo instead, which is the path non-Android
# builds are meant to take.
common --repo_env=ANDROID_HOME=

# 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. These are
# unconditional build flags (they apply to every build), but only Java compile
# and run actions consult the Java toolchain, so they have no effect on 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.

231 changes: 231 additions & 0 deletions docs/jni_interface.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
# 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 8.x or later.** (The committed `MODULE.bazel.lock` uses lockFileVersion 28; Bazel 7 users must delete/regenerate the lock file.)
- **JVM runtime.** These FFM bindings presume a 64-bit JVM

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,
so the DLL's export set is a **superset** of the Linux/macOS one (see
[Not yet supported](#not-yet-supported)).
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`, `PAR_RESULTS`,
`DDS_INFO`.
- Typed downcall wrappers for the shim functions plus `getDdsInfo`. These
return an `int` [`DdsStatus`](../jni/java/org/dds/ffm/DdsStatus.java)
`RETURN_*` code (`RETURN_NO_FAULT == 1` on success); compare against the named
constants rather than magic numbers, and use `DdsStatus.name(rc)` for
diagnostics.
- `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);
deal.fill((byte) 0); // allocate() is not guaranteed to zero the memory
// deal.fill(...) zeroes the struct; Deal.trump uses strain index 0=S,1=H,2=D,3=C,4=NT (DDS_NOTRUMP), and first=0 is North.
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.
- **A pinned Windows export set** — the Linux and macOS libraries are linked
against a header-derived export list and verified by
`//jni/tests:export_set_test`, but the Windows DLL exports everything marked
`__declspec(dllexport)`, including the modern `dds_*` context API. Matching
the other platforms needs a generated `.def` file and a `dumpbin`-based arm of
the export test; the `//jni` tests are excluded on Windows meanwhile.
- **Hand-written JNI convenience API** (idiomatic `native`-method Java classes)
— deferred; the FFM path above is the supported route.
Loading
Loading