Skip to content
Closed
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
8 changes: 8 additions & 0 deletions .github/workflows/validate_wrapper.yml
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,14 @@ jobs:
--format nm
--tool nm
build/wrapper-contract/libllamadart.so
# The release archives get the same check from
# validate_linux_artifact.py.
- name: Check that no library registers static destructors with the C library
run: |
for library in build/wrapper-contract/libllamadart.so build/wrapper-contract/bin/*.so; do
python3 tools/validate_exports.py --format readelf --tool readelf \
--imports-only --forbid-import __cxa_atexit "$library"
done

msvc-mtmd-link-contract:
needs: changes
Expand Down
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ See `docs/v060_qualification.md` for the v0.6.0 wrapper adapters, candidate lane
and the Android ISA evidence required before publication or downstream adoption.
See `docs/v060_1_wrapper_rebuild.md` for the `v0.6.0-1` header additions and
what each export returns after a caught exception.
See `docs/v060_2_wrapper_rebuild.md` for what C `exit()` does on Linux from
`v0.6.0-2`, and why the llama.cpp libraries register no static destructors
there.

- `.github/workflows/native_release.yml`
- Exact native build + release workflow, used by manual dispatch and the
Expand Down
78 changes: 72 additions & 6 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -188,9 +188,41 @@ endif()

llamadart_attach_android_cpu_backend_score(ggml-cpu)

# Adds src/llama_dart_static_destructors.c to every shared library and backend
# module that llama.cpp builds, whatever backends are enabled. libllamadart
# gets it below.
function(llamadart_drop_static_destructors directory)
get_property(target_names DIRECTORY "${directory}" PROPERTY BUILDSYSTEM_TARGETS)
foreach(target_name IN LISTS target_names)
get_target_property(target_type ${target_name} TYPE)
if (target_type STREQUAL "SHARED_LIBRARY" OR target_type STREQUAL "MODULE_LIBRARY")
target_sources(${target_name} PRIVATE
$<TARGET_OBJECTS:llamadart_static_destructors>)
endif()
endforeach()
get_property(subdirectories DIRECTORY "${directory}" PROPERTY SUBDIRECTORIES)
foreach(subdirectory IN LISTS subdirectories)
llamadart_drop_static_destructors("${subdirectory}")
endforeach()
endfunction()

if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
add_library(llamadart_static_destructors OBJECT
"src/llama_dart_static_destructors.c")
llamadart_drop_static_destructors(
"${CMAKE_CURRENT_SOURCE_DIR}/third_party/llama.cpp")
endif()

add_library(llamadart_lib SHARED
"src/llama_dart_wrapper.cpp"
"src/llama_dart_vulkan_device_info.cpp")
if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
target_sources(llamadart_lib PRIVATE
$<TARGET_OBJECTS:llamadart_static_destructors>)
# Held objects and native finalizer callbacks may outlive a dlclose.
# Retain the wrapper together with the owned statics.
target_link_options(llamadart_lib PRIVATE -Wl,-z,nodelete)
endif()
# The Vulkan device facts need only the Vulkan types: the loader is opened at
# run time, so libllamadart links no Vulkan library and loads without one.
set(LLAMADART_VULKAN_HEADERS_INCLUDE
Expand Down Expand Up @@ -306,8 +338,8 @@ if (LLAMADART_BUILD_TESTS)
src
)
foreach(scenario dispose order repeat in-flight nested settle timeout
idle-wait own-call blocked exit late-static free-in-flight
free-timeout barrier-free barrier-free-idle)
idle-wait own-call blocked exit exit-in-flight late-static
free-in-flight free-timeout barrier-free barrier-free-idle)
add_test(NAME llamadart_exit_teardown_${scenario}
COMMAND llamadart_exit_teardown_test ${scenario})
endforeach()
Expand All @@ -325,14 +357,19 @@ if (LLAMADART_BUILD_TESTS)
"${exit_teardown_vocabulary_model}")
set_tests_properties(llamadart_exit_teardown_barrier-grammar PROPERTIES
FIXTURES_REQUIRED llamadart_exit_teardown_vocabulary_model)
# Teardown runs at exit on Apple only, and only there are the backends part
# of libllamadart, so the scenarios that load a model run there. They use a
# model the test writes itself unless one is given.
# Apple automatic teardown and Linux retained statics are exercised
# with CPU models. They use a model the test writes itself unless one is
# given. On Linux the backends are modules, of which the test loads the
# CPU one.
set(LLAMADART_EXIT_TEARDOWN_TEST_MODEL "" CACHE FILEPATH
"GGUF model for the exit teardown tests instead of the generated one")
set(LLAMADART_EXIT_TEARDOWN_TEST_MMPROJ "" CACHE FILEPATH
"GGUF multimodal projector of that model for the mtmd exit teardown tests")
if (APPLE)
if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
target_compile_definitions(llamadart_exit_teardown_test PRIVATE
LLAMADART_TEST_CPU_BACKEND="$<TARGET_FILE:ggml-cpu>")
endif()
if (APPLE OR CMAKE_SYSTEM_NAME STREQUAL "Linux")
add_test(NAME llamadart_exit_teardown_graph
COMMAND llamadart_exit_teardown_test graph)
set(exit_teardown_model "${LLAMADART_EXIT_TEARDOWN_TEST_MODEL}")
Expand All @@ -356,6 +393,25 @@ if (LLAMADART_BUILD_TESTS)
set_tests_properties(llamadart_exit_teardown_${scenario} PROPERTIES
FIXTURES_REQUIRED llamadart_exit_teardown_model)
endforeach()
# Linux preserves host callbacks and libc flushing. Live-worker raw
# exit cases are diagnostic CPU controls, not the host contract.
if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
foreach(scenario exit-late-calls exit-status)
add_test(NAME llamadart_exit_teardown_${scenario}
COMMAND llamadart_exit_teardown_test ${scenario})
endforeach()
set_tests_properties(llamadart_exit_teardown_exit-status
PROPERTIES TIMEOUT 10)
foreach(scenario model-unguarded-decode model-exit-idle
model-exit-join-idle model-exit-join-generating)
add_test(NAME llamadart_exit_teardown_${scenario}
COMMAND llamadart_exit_teardown_test ${scenario}
"${exit_teardown_model}")
set_tests_properties(llamadart_exit_teardown_${scenario}
PROPERTIES
FIXTURES_REQUIRED llamadart_exit_teardown_model)
endforeach()
endif()
if (LLAMADART_EXIT_TEARDOWN_TEST_MODEL)
add_test(NAME llamadart_exit_teardown_model-speculative-process
COMMAND llamadart_exit_teardown_test model-speculative-process
Expand Down Expand Up @@ -393,6 +449,16 @@ if (LLAMADART_BUILD_TESTS)
endif()
endif()

# The Linux presets give every binary the run path $ORIGIN, which the
# bundle needs, while the build tree keeps the llama.cpp libraries in a
# directory of their own.
if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
get_property(llamadart_tests DIRECTORY PROPERTY TESTS)
set_tests_properties(${llamadart_tests} PROPERTIES
ENVIRONMENT_MODIFICATION
"LD_LIBRARY_PATH=path_list_prepend:$<TARGET_FILE_DIR:llama>;LD_LIBRARY_PATH=path_list_prepend:$<TARGET_FILE_DIR:llamadart_lib>")
endif()

# Contract assertions must execute against optimized Release libraries too.
foreach(test_target llamadart_speculative_api_test llamadart_tts_api_test
llamadart_tts_eval_test llamadart_exit_teardown_test llamadart_mtmd_compat_test
Expand Down
30 changes: 23 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,8 @@ Assets are suffixed with platform/arch, for example:
- `tools/package_linux_artifact.py`: preserves Linux ELF version files and
SONAME symlinks while transporting split CI artifacts.
- `tools/validate_linux_artifact.py`: checks Linux archive members, symlinks,
SONAMEs, and local `DT_NEEDED` dependencies.
SONAMEs, and local `DT_NEEDED` dependencies, that no library built here
imports `__cxa_atexit`, and that `libllamadart.so` cannot be unloaded.
- `tools/package_apple_xcframework.py`: packages Apple `libllamadart` slices as
an SPM-compatible XCFramework zip.
- `tools/apple/PrivacyInfo.xcprivacy`: privacy manifest embedded in every
Expand Down Expand Up @@ -286,15 +287,30 @@ left of it at exit:
upstream function is tracked but not freed at exit, so a caller that has not
switched to the tracked functions keeps its previous exit behavior.

On other platforms nothing runs at exit; `llama_dart_exit_teardown` runs the
same teardown on request and must be followed directly by `exit`. It is for
native hosts: like `llama_dart_exit_call_begin` and `llama_dart_exit_call_end`,
it is not meant to be bound from Dart.
On Linux, Android excepted, owned bundle statics are retained until the
process is gone (`src/llama_dart_static_destructors.c`). C `exit` runs no
wrapper teardown or forced termination: earlier host callbacks, dependency
destructors and normal libc stream flushing proceed. `-z nodelete` keeps
held native objects and finalizer callbacks valid across `dlclose`.

Before C exit, the host must stop and join workers and shut down its Dart
isolates or Flutter engine. Await their exit and native finalizers; a kill
request alone is insufficient. Direct C exit with live Dart isolates can
abort the VM even without llama.cpp ([#977](https://github.com/leehack/llamadart/issues/977)).
Owned static retention does not protect GPU-driver or BLAS destructors.

[`docs/v060_2_wrapper_rebuild.md`](docs/v060_2_wrapper_rebuild.md) describes
the host protocol, preservation regression tests and remaining qualification.

On other platforms nothing runs at exit. `llama_dart_exit_teardown` runs
teardown on request on every platform, frees included, and must be followed
directly by `exit`. It is for native hosts: like `llama_dart_exit_call_begin`
and `llama_dart_exit_call_end`, it is not meant to be bound from Dart.
`src/llama_dart_wrapper.h` documents each function.

`llamadart_exit_teardown_test` covers the registry on every platform. On macOS
it also writes a small decoder and a small encoder model and runs the
scenarios that load one, so ctest needs no model file:
and Linux it also writes a small decoder and a small encoder model and runs
the scenarios that load one, so ctest needs no model file:

```bash
cmake -S . -B build/exit-teardown -G Ninja -DLLAMADART_BUILD_TESTS=ON
Expand Down
3 changes: 3 additions & 0 deletions docs/v060_1_wrapper_rebuild.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,9 @@ Why the Apple mechanism does not carry over:
measure either effect, and the Linux lanes here load no backend, so they run
no model scenario.

`v0.6.0-2` fixes it, with the wait and without the frees as recommended below
but without the gate: see [`v060_2_wrapper_rebuild.md`](v060_2_wrapper_rebuild.md).

Recommended design, for a later rebuild:

1. Compile a small object into every shared library of the bundle that holds
Expand Down
89 changes: 89 additions & 0 deletions docs/v060_2_wrapper_rebuild.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# v0.6.0-2 wrapper rebuild: Linux host shutdown

llama.cpp remains v0.6.0 (`d81235049`). No wrapper export or header layout is
added. Android driver patches and image-token limits are separate work.

## Contract

Before a native host calls C `exit()`, it stops new work, stops and joins its
native workers, and shuts down its Dart isolates or Flutter engine. A kill
request is not completion: await each isolate's exit notification and native
finalizers before exiting. Free contexts before projectors / models. A native
call already in progress completes before its isolate can shut down.

Linux, Android excepted, retains the statics owned by the runtime bundle.
`src/llama_dart_static_destructors.c` supplies a hidden `__cxa_atexit` that drops
owned static destructors; external libraries keep their ordinary exit behavior.
The wrapper remains linked with `-z nodelete` so held objects and finalizer
callbacks remain valid across `dlclose`. Artifact validators reject missing
retention and owned imports of `__cxa_atexit`.

C exit registers no automatic Linux wrapper teardown or exit handler. It does
not set a late-call refusal state, flush streams early, wait, free live objects
or call `_exit`. Normal host callbacks, dependency destructors and libc stdio
flushing run in their normal order. An earlier native-host callback can still
join a worker and free its tracked objects; the wrapper does not park that
worker merely because libc exit began.

Apple automatic teardown and explicit `llama_dart_exit_teardown` are unchanged.
Do not invoke explicit teardown before joining workers: it parks later guarded
calls, so a subsequent host join can hang. Android is unchanged. Windows / musl
hardware qualification is not established by these Linux glibc measurements.

## Why exit must follow host shutdown

A direct C exit with live Dart isolates is unsafe independently of llama.cpp.
With an allocating isolate and an earlier300ms host callback, the VM aborts at
`handles_impl.h:39` without loading any native model (llamadart#977). Retaining
owned statics cannot protect a GPU driver's or BLAS library's destructors either.
Direct C exit while Dart isolates or dependency-using native workers are alive
is outside this contract, including calls from an evaluation callback or an
incomplete model load. CPU raw-exit controls remain diagnostics, not support
claims. A hung native call cannot be called quiescent after a timeout; the host
must withhold normal C exit until it completes or explicitly choose its own
abrupt process-termination policy.

The rejected candidate flushed streams and called `_exit` when a call was in
flight. It skipped earlier host callbacks, and its `fflush(NULL)` deadlocked if
a worker held a FILE lock whose earlier host callback would release it. Removing
only the flush lost buffered output. Both alternatives violate the accepted
preservation contract and are absent from this revision.

## Validation and replay

`llamadart_exit_teardown_exit-status` verifies exit37, the earlier callback,
buffered output, and a host callback joining a marked native worker that holds a
FILE lock. Its10s CTest timeout makes the old unconditional-flush deadlock fail.
`exit-late-calls` verifies the host callback can create and free tracked objects
without an automatic Linux refusal state. These are native compatibility
controls, without a running Dart VM. Apple teardown tests retain their contract.

The maintained manual `tests/manual/dart_host_shutdown_probe.dart` uses worker
NativeFinalizers, per-worker onExit notifications, an allocating isolate, a
slow native call and a slow earlier host callback. Build the adjacent shim as
in `dart_exit_probe.dart`; set `PROBE_STEP_DELAY_MS=300`, then run:

```bash
dart tests/manual/dart_host_shutdown_probe.dart libshim.so <bundle-dir> \
cooperative-finalizer-slow-native <model.gguf>
```

Success requires exit0, `NATIVE_ACTIVE_BEFORE_KILL`, `NATIVE_CALLS_AFTER_EXIT 0`,
`NATIVE_FREE_COUNT_AFTER_EXIT 1`, `HOST_HANDLER_COMPLETED`, and `C_BUFFERED_PAYLOAD`.
`raw-control` reproduces the VM defect; `cooperative-control` verifies allocator
shutdown without loading a native bundle. Neither case requires model downloads.

Pre-implementation prototype evidence (not qualification of this revised head):
Linuxarm64 GCC14/glibc2.41, Dart3.13.1, stories15M CPU, five repeats per case /
build, released baseline vs rejected head vs preservation prototype.60/60
cooperative model cases and15/15 no-model cases retained callbacks / output.
30/30 active native-call cases waited314–339ms before onExit;15/15 finalizers
completed first.15/15 raw no-model controls aborted. The protocol also passed
on the released baseline, so it establishes the lifecycle boundary, not a new
native feature. The GCC13 dependencies were reused read-only; this differs
from Ubuntu24.04/GCC13 release qualification.

Current-head CI, independent audit and exact-runtime replay are required anew.
Remaining release gates include real GPU / OpenBLAS driver shutdown, image
runtime, Flutter Linux host ordering, final published artifacts and device
qualification. No earlier raw-exit result establishes those gates.
26 changes: 26 additions & 0 deletions src/llama_dart_static_destructors.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Linked into every shared library of the Linux bundle: libllamadart and the
// llama.cpp libraries next to it (CMakeLists.txt).
//
// The C++ runtime registers the destructor of each static of a library
// through __cxa_atexit. The linker binds those calls to this definition,
// which registers nothing, so the statics of the library are never destroyed.
//
// C exit() destroys statics while other threads are still inside llama.cpp,
// which then read freed memory (https://github.com/leehack/llamadart/issues/949).
// On Apple platforms llama.cpp is part of libllamadart, whose exit teardown
// runs before the first of those statics is destroyed. Here the libraries are
// separate, and exit handlers run in reverse order of registration: no handler
// of libllamadart precedes the destructor of a static that another library
// creates later, in the middle of a model load for one. The handler that
// libllamadart does register ends the process for a call in flight that it
// counts; a static that is never destroyed stays valid for the calls that it
// does not.
#if defined(__linux__) && !defined(__ANDROID__)
__attribute__((visibility("hidden"), used)) int
__cxa_atexit(void (*destroy)(void *), void *object, void *dso_handle) {
(void)destroy;
(void)object;
(void)dso_handle;
return 0;
}
#endif
14 changes: 12 additions & 2 deletions src/llama_dart_wrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
#include <limits>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <string>
#include <thread>
#include <type_traits>
Expand Down Expand Up @@ -727,6 +728,7 @@ static thread_local bool llama_dart_exit_teardown_thread = false;
// Calls in flight on this thread. The registry counts the outermost one.
static thread_local int32_t llama_dart_exit_call_depth = 0;


// Called with the registry locked. Returns whether the calling thread may go
// on to use tracked objects. Once teardown has begun, teardown waits for a
// thread that is in a call in flight, and the teardown thread gets false. Any
Expand All @@ -749,6 +751,7 @@ static bool llama_dart_exit_admit(llama_dart_exit_registry &registry,
}
}


#if defined(__APPLE__)
struct llama_dart_exit_static_destructor {
void (*destroy)(void *);
Expand Down Expand Up @@ -805,6 +808,7 @@ __cxa_atexit(void (*destroy)(void *), void *object, void *dso_handle) {
}
#endif


// Registers teardown to run at exit once something is tracked, so that it
// does not wait for the first static of this image to be destroyed. atexit
// handlers run in reverse order of registration, so this one runs after the
Expand All @@ -817,6 +821,8 @@ static void llama_dart_exit_arm() {
#endif
}



static bool llama_dart_exit_insert(void *object, void (*free_fn)(void *),
int32_t stage, void *uses_first = nullptr,
void *uses_second = nullptr) {
Expand Down Expand Up @@ -914,7 +920,9 @@ static void llama_dart_exit_begin_call(bool creating) {
}

struct llama_dart_exit_call {
llama_dart_exit_call() { llama_dart_exit_call_begin(); }
llama_dart_exit_call() {
llama_dart_exit_call_begin();
}
~llama_dart_exit_call() { llama_dart_exit_call_end(); }
llama_dart_exit_call(const llama_dart_exit_call &) = delete;
llama_dart_exit_call &operator=(const llama_dart_exit_call &) = delete;
Expand All @@ -923,7 +931,9 @@ struct llama_dart_exit_call {
// A call in flight that tracks what it creates. Teardown waits for it even
// when nothing is tracked yet.
struct llama_dart_exit_creating_call {
llama_dart_exit_creating_call() { llama_dart_exit_begin_call(true); }
llama_dart_exit_creating_call() {
llama_dart_exit_begin_call(true);
}
~llama_dart_exit_creating_call() {
{
auto &registry = llama_dart_exit_state();
Expand Down
Loading
Loading