Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
30 changes: 30 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,36 @@ jobs:
- name: Build and run the native image with libffi
run: bb test:native

static:
name: Fully static native image
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: graalvm/setup-graalvm@v1
with:
java-version: '25'
distribution: graalvm
native-image-musl: true
github-token: ${{ secrets.GITHUB_TOKEN }}

- name: Cache dependencies
uses: actions/cache@v4
with:
path: |
~/.m2/repository
~/.gitlibs
key: deps-${{ runner.os }}-${{ hashFiles('deps.edn', 'bb.edn') }}
restore-keys: deps-${{ runner.os }}-

- uses: DeLaGuardo/setup-clojure@13.4
with:
cli: latest
bb: latest

- name: Build and run the static image
run: bb test:native --static

cljs:
name: ClojureScript and shadow-cljs
runs-on: ubuntu-latest
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
[babashka.ffi](https://github.com/babashka/ffi): call C libraries from
Clojure, babashka and Node.js.

## Unreleased

- [#74](https://github.com/babashka/ffi/issues/74): a statically linked executable throws an error that names static linking when it cannot load a library

## 0.1.3 (2026-11-09)

- [#65](https://github.com/babashka/ffi/issues/65): `write-string` writes a NUL-terminated string into existing memory
Expand Down
2 changes: 1 addition & 1 deletion bb.edn
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"-m" "babashka.ffi-test")}
test:native {:doc "Build a native image of babashka.ffi and run test-native against it. Needs GRAALVM_HOME."
:task (do (load-file "script/native_test.clj")
((resolve 'native-test/-main)))}
(apply (resolve 'native-test/-main) *command-line-args*))}
test:cljs {:doc "Run the Node.js tests compiled with ClojureScript. Pass advanced for an :advanced build."
:requires ([babashka.fs :as fs])
:task (if (= "advanced" (first *command-line-args*))
Expand Down
8 changes: 8 additions & 0 deletions doc/ai/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,14 @@ signature are refused. The second links the libffi of the system with -lffi
and checks that they are called. BABASHKA_LIBFFI can also be the path of an
archive. CI runs both on Linux, macOS and Windows.

```sh
bb test:native --static
```

builds a fully static image with musl and checks that babashka.ffi names
static linking when it cannot load a library. It needs a GraalVM with musl
support, so CI runs it on Linux only.

Node.js, needs Node.js 26.1 or newer on PATH. The three commands run
test-node under nbb, ClojureScript and shadow-cljs. The last two need JDK 25
or newer:
Expand Down
117 changes: 65 additions & 52 deletions script/native_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,13 @@
other value is the path of a libffi archive or import library.

bb test:native
BABASHKA_LIBFFI=system bb test:native"
BABASHKA_LIBFFI=system bb test:native

With --static, the image is fully static, linked with musl on Linux, and
checks that babashka.ffi names static linking when it cannot load a
library. Needs a GraalVM with musl support.

bb test:native --static"
(:require [babashka.deps :as deps]
[babashka.fs :as fs]
[babashka.process :as p]
Expand Down Expand Up @@ -58,57 +64,64 @@
[& args]
(-> (deps/clojure (vec args)) deref p/check))

(defn -main [& _]
(fs/delete-tree out)
(fs/create-dirs classes)

(step "the fixture")
(if (fs/windows?)
(p/shell "cl" "/nologo" "/LD" fixture (str "/Fe:" lib)
(str "/Fo:" (fs/path "target" "ffistructs.obj")))
(p/shell "cc" "-shared" "-fPIC" "-o" lib fixture))

(step "javac")
(let [sdk (classpath :native)
cp (str/join fs/path-separator [sdk "test-native" (str classes)])]
(p/shell (graalvm-bin "javac") "--release" "25" "-cp" sdk "-d" (str classes)
"src-java/babashka/ffi/impl/FfiTrampoline.java"
"src-java/babashka/ffi/impl/FfiTrampolineOrdered.java"
"src-java/babashka/ffi/impl/Libffi.java"
"src-java/babashka/ffi/impl/LibffiClosure.java")

(step "compiling the namespaces")
(clojure "-Scp" cp "-J--enable-native-access=ALL-UNNAMED"
"-e" (pr-str (list 'binding ['*compile-path* (str classes)]
'(compile 'babashka.ffi.native-test))))

(step (str "native-image, " (if libffi (str "with libffi: " libffi) "without libffi")))
(apply p/shell {:extra-env {"BABASHKA_FEATURE_LIBFFI" (str (boolean libffi))}}
(graalvm-bin "native-image")
"-cp" cp
"--features=clj_easy.graal_build_time.InitClojureClasses"
"-H:+UnlockExperimentalVMOptions"
"-H:+ForeignAPISupport"
"--enable-native-access=ALL-UNNAMED"
"--no-fallback"
"-O1"
(concat
;; Windows assigns argument registers by position, so its image
;; loads the ordered trampolines, and the upcall shapes only they
;; need are in a metadata file of their own
(when (fs/windows?)
["-H:ConfigurationResourceRoots=babashka/ffi/native-image-windows"])
;; babashka.ffi reads the variable when the image is built, and
;; loads the libffi bindings only then
["-EBABASHKA_FEATURE_LIBFFI"]
(when libffi
[(str "-H:NativeLinkerOption="
(if (= "system" libffi) "-lffi" (str (fs/absolutize libffi))))])
["-o" (str (fs/path out "ffi-native-test"))
"babashka.ffi.native_test"])))

(step "running the image")
(p/shell (str (fs/absolutize image)) lib))
(defn -main [& args]
(let [static? (= "--static" (first args))
libffi (when-not static? libffi)]
(fs/delete-tree out)
(fs/create-dirs classes)

(when-not static?
(step "the fixture")
(if (fs/windows?)
(p/shell "cl" "/nologo" "/LD" fixture (str "/Fe:" lib)
(str "/Fo:" (fs/path "target" "ffistructs.obj")))
(p/shell "cc" "-shared" "-fPIC" "-o" lib fixture)))

(step "javac")
(let [sdk (classpath :native)
cp (str/join fs/path-separator [sdk "test-native" (str classes)])]
(p/shell (graalvm-bin "javac") "--release" "25" "-cp" sdk "-d" (str classes)
"src-java/babashka/ffi/impl/FfiTrampoline.java"
"src-java/babashka/ffi/impl/FfiTrampolineOrdered.java"
"src-java/babashka/ffi/impl/Libffi.java"
"src-java/babashka/ffi/impl/LibffiClosure.java")

(step "compiling the namespaces")
(clojure "-Scp" cp "-J--enable-native-access=ALL-UNNAMED"
"-e" (pr-str (list 'binding ['*compile-path* (str classes)]
'(compile 'babashka.ffi.native-test))))

(step (str "native-image, " (cond static? "fully static"
libffi (str "with libffi: " libffi)
:else "without libffi")))
(apply p/shell {:extra-env {"BABASHKA_FEATURE_LIBFFI" (str (boolean libffi))}}
(graalvm-bin "native-image")
"-cp" cp
"--features=clj_easy.graal_build_time.InitClojureClasses"
"-H:+UnlockExperimentalVMOptions"
"-H:+ForeignAPISupport"
"--enable-native-access=ALL-UNNAMED"
"--no-fallback"
"-O1"
(concat
;; Windows assigns argument registers by position, so its image
;; loads the ordered trampolines, and the upcall shapes only they
;; need are in a metadata file of their own
(when (fs/windows?)
["-H:ConfigurationResourceRoots=babashka/ffi/native-image-windows"])
;; babashka.ffi reads the variable when the image is built, and
;; loads the libffi bindings only then
["-EBABASHKA_FEATURE_LIBFFI"]
(when static?
["--static" "--libc=musl"])
(when libffi
[(str "-H:NativeLinkerOption="
(if (= "system" libffi) "-lffi" (str (fs/absolutize libffi))))])
["-o" (str (fs/path out "ffi-native-test"))
"babashka.ffi.native_test"])))

(step "running the image")
(p/shell (str (fs/absolutize image)) (if static? "--static" lib))))

(when (= *file* (System/getProperty "babashka.file"))
(apply -main *command-line-args*))
56 changes: 51 additions & 5 deletions src/babashka/ffi.clj
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,38 @@

(def ^:private last-lookup-error (volatile! nil))

(declare ^:private native-image?)

(defn- static-elf?
"Returns true if path is a 64-bit little-endian ELF file without a
PT_INTERP program header."
[^String path]
(try
(clojure.core/with-open [f (java.io.RandomAccessFile. path "r")]
(let [hdr (byte-array 64)
_ (.readFully f hdr)
buf (.order (java.nio.ByteBuffer/wrap hdr) java.nio.ByteOrder/LITTLE_ENDIAN)]
(and (= 0x464c457f (.getInt buf 0))
(= 2 (aget hdr 4))
(= 1 (aget hdr 5))
(let [phoff (.getLong buf 0x20)
phentsize (long (.getShort buf 0x36))
phnum (long (.getShort buf 0x38))]
(not-any? (fn [^long i]
(.seek f (+ phoff (* i phentsize)))
(= 3 (Integer/reverseBytes (.readInt f))))
(range phnum))))))
(catch Exception _ false)))

(def ^:private static-executable?
(delay (and native-image?
(= :linux (os-key))
(static-elf? "/proc/self/exe"))))

(defn- static-executable-ex [data cause]
(ex-info "babashka.ffi: a statically linked executable cannot load shared libraries, use a dynamically linked build"
data cause))

(defn- try-lookup ^SymbolLookup [^String path]
(try (SymbolLookup/libraryLookup path (Arena/global))
(catch java.lang.IllegalCallerException e
Expand Down Expand Up @@ -662,6 +694,8 @@
(vector? lib) (mapv str lib)
:else [(str lib)])
m (or (some lookup-one paths)
(when @static-executable?
(throw (static-executable-ex {:library lib} @last-lookup-error)))
(throw (ex-info (str "babashka.ffi: cannot load library: "
(str/join ", " paths)
" (bare names also searched in "
Expand Down Expand Up @@ -706,6 +740,8 @@
(search-dirs))]
(swap! libraries conj (:lookup m))
m)
(when @static-executable?
(throw (static-executable-ex {:library name} @last-lookup-error)))
(throw (ex-info (str "babashka.ffi: cannot find library " name
" (tried " base " and " base ".* in "
(pr-str (vec (search-dirs))) ")")
Expand All @@ -731,12 +767,22 @@
(pr-str lib))
{:library lib})))))

(defn- find-in ^MemorySegment [^SymbolLookup l ^String sym]
(.orElse (.find l sym) nil))

(defn- find-default ^MemorySegment [^String sym]
(try (find-in (.defaultLookup ^Linker @linker*) sym)
(catch Throwable e
(if @static-executable?
(throw (static-executable-ex {:symbol sym} e))
(throw e)))))

(defn- lookup-symbol ^MemorySegment [lib ^String sym]
(let [;; nil? and not truthiness: false is not "no library", it is a wrong one
lookups (if (nil? lib)
(conj @libraries (.defaultLookup ^Linker @linker*))
[(resolve-library lib)])]
(some (fn [^SymbolLookup l] (.orElse (.find l sym) nil)) lookups)))
;; nil? and not truthiness: false is not "no library", it is a wrong one
(if (nil? lib)
(or (some #(find-in % sym) @libraries)
(find-default sym))
(find-in (resolve-library lib) sym)))

(defn- require-symbol ^MemorySegment [lib sym]
(if (instance? MemorySegment sym)
Expand Down
29 changes: 25 additions & 4 deletions test-native/babashka/ffi/native_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,27 @@
(println " expected a message matching" (pr-str (str re)))
(println " actual: " (pr-str msg))))))

(defn- report []
(println)
(if (zero? @failures)
(println "native image: all checks passed")
(do (println "native image:" @failures "failed") (System/exit 1))))

(defn- static-checks []
(println "a fully static image")
(check "static-executable? is true" true (boolean @@#'ffi/static-executable?))
(check-throws "load-library names static linking" #"statically linked"
#(ffi/load-library "libz.so.1"))
(check-throws "load-system-library names static linking" #"statically linked"
#(ffi/load-system-library "z"))
(check-throws "a call through the default lookup names static linking" #"statically linked"
#((ffi/cfn "abs" [:int] :int) -5))
(report))

(defn -main [& args]
(when (= "--static" (first args))
(static-checks)
(System/exit 0))
(let [lib (or (first args) "target/libffistructs.dylib")]
(ffi/load-library lib)

Expand Down Expand Up @@ -250,7 +270,8 @@
(check-throws "a callback with eight arguments" #"libffi"
#(ffi/callback (ffi/global-arena) + (vec (repeat 8 :int)) :int))))

(println)
(if (zero? @failures)
(println "native image: all checks passed")
(do (println "native image:" @failures "failed") (System/exit 1)))))
(println "static linking")
(check "a dynamically linked image is not static" false
(boolean @@#'ffi/static-executable?))

(report)))
33 changes: 33 additions & 0 deletions test/babashka/ffi_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -1127,3 +1127,36 @@
(is (= 0.95 (strtod "0.95" ffi/null))))
(finally
(setlocale lc-numeric original)))))))))

(defn- elf-file [phdr-types]
(let [phnum (count phdr-types)
buf (doto (java.nio.ByteBuffer/allocate (+ 64 (* 56 phnum)))
(.order java.nio.ByteOrder/LITTLE_ENDIAN)
(.putInt 0 0x464c457f)
(.put 4 (byte 2))
(.put 5 (byte 1))
(.putLong 0x20 64)
(.putShort 0x36 (short 56))
(.putShort 0x38 (short phnum)))
f (fs/create-temp-file {:prefix "elf"})]
(doseq [[i t] (map-indexed vector phdr-types)]
(.putInt buf (int (+ 64 (* 56 i))) (int t)))
(fs/write-bytes f (.array buf))
(str f)))

(deftest static-elf-test
(when-not (System/getProperty "babashka.version")
(let [static-elf? @(resolve 'babashka.ffi/static-elf?)]
(testing "an ELF file with PT_LOAD and no PT_INTERP is static"
(is (true? (static-elf? (elf-file [1 1])))))
(testing "an ELF file with PT_INTERP is not static"
(is (false? (static-elf? (elf-file [6 3 1])))))
(testing "a file that is not ELF is not static"
(let [f (fs/create-temp-file)]
(fs/write-bytes f (byte-array 100))
(is (false? (static-elf? (str f))))))
(testing "a missing file is not static"
(is (false? (static-elf? "/nonexistent/exe"))))
(when (fs/exists? "/proc/self/exe")
(testing "the running JVM is not static"
(is (false? (static-elf? "/proc/self/exe"))))))))
Loading