diff --git a/.github/workflows/validate_wrapper.yml b/.github/workflows/validate_wrapper.yml index dffe9149..b5caec7a 100644 --- a/.github/workflows/validate_wrapper.yml +++ b/.github/workflows/validate_wrapper.yml @@ -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 diff --git a/AGENTS.md b/AGENTS.md index fbbb24b6..b8187b0c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/CMakeLists.txt b/CMakeLists.txt index 700d4cec..eafa2959 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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 + $) + 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 + $) + # 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 @@ -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() @@ -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="$") + 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}") @@ -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 @@ -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:$;LD_LIBRARY_PATH=path_list_prepend:$") + 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 diff --git a/README.md b/README.md index db72b11b..5673e10e 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 diff --git a/docs/v060_1_wrapper_rebuild.md b/docs/v060_1_wrapper_rebuild.md index 11409b73..405ac284 100644 --- a/docs/v060_1_wrapper_rebuild.md +++ b/docs/v060_1_wrapper_rebuild.md @@ -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 diff --git a/docs/v060_2_wrapper_rebuild.md b/docs/v060_2_wrapper_rebuild.md new file mode 100644 index 00000000..d3dcf359 --- /dev/null +++ b/docs/v060_2_wrapper_rebuild.md @@ -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 \ + cooperative-finalizer-slow-native +``` + +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. diff --git a/src/llama_dart_static_destructors.c b/src/llama_dart_static_destructors.c new file mode 100644 index 00000000..cd54473d --- /dev/null +++ b/src/llama_dart_static_destructors.c @@ -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 diff --git a/src/llama_dart_wrapper.cpp b/src/llama_dart_wrapper.cpp index b2d4314f..c698002b 100644 --- a/src/llama_dart_wrapper.cpp +++ b/src/llama_dart_wrapper.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -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 @@ -749,6 +751,7 @@ static bool llama_dart_exit_admit(llama_dart_exit_registry ®istry, } } + #if defined(__APPLE__) struct llama_dart_exit_static_destructor { void (*destroy)(void *); @@ -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 @@ -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) { @@ -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; @@ -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 ®istry = llama_dart_exit_state(); diff --git a/src/llama_dart_wrapper.h b/src/llama_dart_wrapper.h index 563d4078..46cfa036 100644 --- a/src/llama_dart_wrapper.h +++ b/src/llama_dart_wrapper.h @@ -352,8 +352,25 @@ LLAMADART_API int32_t llama_dart_vulkan_get_device_info( // or hot restart does. ggml-metal aborts in its static destructor while any // Metal buffer is still allocated, so teardown has to run before that // destructor. On Apple platforms it runs during exit, before the first static -// of libllamadart is destroyed. Elsewhere it runs only when -// llama_dart_exit_teardown is called. +// of libllamadart is destroyed. +// +// On Linux, Android excepted, owned bundle statics are retained until the +// process is gone. C exit() runs no wrapper handler: normal host callbacks, +// dependency destructors and libc stream flushing proceed without a forced +// _exit, an automatic free, a wait or late-call refusal. +// +// Before a native host calls C exit(), it must stop and join its workers and +// shut down its Dart isolates / Flutter engine. Await isolate exit and native +// finalizer completion, not just a kill request. A direct C exit() with live +// Dart isolates can abort the VM even without llama.cpp (llamadart#977). +// Retaining owned statics does not protect a GPU driver's or BLAS library's +// destructors. Do not call explicit teardown before joining workers: teardown +// parks later guarded calls and can deadlock a host join. +// +// libllamadart remains loaded across dlclose so held native objects and their +// finalizer callbacks stay valid. quick_exit and _exit run no cleanup. +// Elsewhere nothing changes. llama_dart_exit_teardown explicitly frees on +// every platform; automatic Apple exit teardown remains as described above. // // Objects are tracked, before the creating call returns, by // llama_dart_model_load_from_file, llama_dart_init_from_model, diff --git a/tests/exit_teardown_test.cpp b/tests/exit_teardown_test.cpp index 75a8387c..0e0785f5 100644 --- a/tests/exit_teardown_test.cpp +++ b/tests/exit_teardown_test.cpp @@ -30,6 +30,11 @@ #define LLAMADART_TEST_ADDRESS_SANITIZER 1 #endif +#if defined(__linux__) && defined(__GLIBC__) && !defined(__ANDROID__) +#include +#include +#endif + #if defined(LLAMADART_TEST_ADDRESS_SANITIZER) #include #elif defined(__APPLE__) @@ -464,15 +469,65 @@ int test_blocked() { return 0; } +// C exit() runs teardown on Apple platforms: it waits for the calls in +// flight, frees, and blocks the threads that reach libllamadart afterwards. +// Linux retains owned statics and leaves normal libc exit untouched. +// Hosts stop workers and the managed runtime before C exit. #if defined(__APPLE__) -const bool kTeardownRunsAtExit = true; +const bool kExitFreesObjects = true; +const bool kExitWaitsForCalls = true; +const bool kExitEndsProcess = false; +const bool kExitRefusesLateCalls = false; +#elif defined(__linux__) && defined(__GLIBC__) && !defined(__ANDROID__) +const bool kExitFreesObjects = false; +const bool kExitWaitsForCalls = false; +const bool kExitEndsProcess = false; +const bool kExitRefusesLateCalls = false; #else -const bool kTeardownRunsAtExit = false; +const bool kExitFreesObjects = false; +const bool kExitWaitsForCalls = false; +const bool kExitEndsProcess = false; +const bool kExitRefusesLateCalls = false; +#endif + +// Set by a scenario before the exit that a call may run into. +std::atomic g_exit_expected{false}; + +// Whether the calling thread's last call was refused because C exit() had +// passed libllamadart already. +bool refused_by_exit() { + const char *error = llama_dart_last_error(); + return kExitRefusesLateCalls && g_exit_expected.load() && error != nullptr && + strcmp(error, "the process is exiting") == 0; +} + +// For an exit handler that a scenario registers before libllamadart registers +// its own, so that it runs after it. Where the exit ends the process for a +// call in flight, the exit never gets this far in such a scenario. +void expect_process_ended(const char *what) { + if (kExitEndsProcess) { + fprintf(stderr, "the exit went on under %s\n", what); + _Exit(EXIT_FAILURE); + } +} + +// Where the backends are modules next to the llama.cpp libraries and not part +// of libllamadart, a scenario that computes has to load one. The CPU backend +// alone keeps the scenarios the same whatever other modules the build has. +void load_backend_modules() { +#if defined(LLAMADART_TEST_CPU_BACKEND) + assert(ggml_backend_load(LLAMADART_TEST_CPU_BACKEND) != nullptr); #endif +} + +void init_backends() { + llama_backend_init(); + load_backend_modules(); +} void expect_freed_at_exit() { const std::vector expected = - kTeardownRunsAtExit ? kStageOrder : std::vector(); + kExitFreesObjects ? kStageOrder : std::vector(); if (recorded() != expected) { fprintf(stderr, "exit teardown freed %zu objects, expected %zu\n", recorded().size(), expected.size()); @@ -487,6 +542,119 @@ int test_exit() { return 0; } +std::atomic g_call_ended{false}; + +void expect_call_ended_at_exit() { + expect_process_ended("a call in flight"); + if (kExitWaitsForCalls && !g_call_ended.load()) { + fprintf(stderr, "the exit did not wait for the call in flight\n"); + _Exit(EXIT_FAILURE); + } +} + +// The exit sees a call in flight when objects were only tracked, with no +// creating call: it waits for the call, or on Linux ends the process. +int test_exit_in_flight() { + // Registered first, so it runs after the teardown registered by tracking. + assert(atexit(expect_call_ended_at_exit) == 0); + static char object[] = "object"; + assert(llama_dart_exit_track(object, free_named, + LLAMA_DART_EXIT_STAGE_MODEL)); + static std::atomic started{false}; + std::thread([] { + llama_dart_exit_call_begin(); + started.store(true); + sleep_ms(400); + g_call_ended.store(true); + llama_dart_exit_call_end(); + }).detach(); + while (!started.load()) { + sleep_ms(1); + } + return 0; +} + +char kLateObject[] = "late-object"; +llama_dart_ngram *g_created_at_exit = nullptr; + +// An earlier host callback still owns normal wrapper cleanup. No Dart VM +// is active here, and no wrapper teardown has begun. +void make_late_calls() { + assert(llama_dart_exit_tracked_count() == 1); + g_created_at_exit = llama_dart_ngram_simple_init(4, 8); + assert(g_created_at_exit != nullptr); + assert(llama_dart_last_error() == nullptr); + assert(llama_dart_exit_tracked_count() == 2); + llama_dart_exit_free(g_created_at_exit); + llama_dart_exit_free(kLateObject); + assert(llama_dart_exit_tracked_count() == 0); + assert(recorded() == std::vector{"late-object"}); +} + +int test_exit_late_calls() { + assert(atexit(make_late_calls) == 0); + assert(llama_dart_exit_track(kLateObject, free_named, + LLAMA_DART_EXIT_STAGE_MODEL)); + return 0; +} + +#if defined(__linux__) && defined(__GLIBC__) && !defined(__ANDROID__) +std::atomic status_worker_stop{false}; +std::thread *status_worker = nullptr; +FILE *status_locked_stream = nullptr; +void status_host_callback() { + status_worker_stop.store(true); + status_worker->join(); + printf(";host handler ran"); +} +#endif + +// Normal C exit preserves its status, earlier callbacks and buffered output. +// A host callback releases a FILE lock held by a marked native worker: an +// unconditional fflush before that callback would hang. This native-only +// compatibility control does not authorize live-Dart-isolate C exit. +int test_exit_status() { +#if defined(__linux__) && defined(__GLIBC__) && !defined(__ANDROID__) + int output[2]; + assert(pipe(output) == 0); + const pid_t child = fork(); + assert(child >= 0); + if (child == 0) { + close(output[0]); + assert(dup2(output[1], STDOUT_FILENO) >= 0); + assert(atexit(status_host_callback) == 0); + static char object[] = "object"; + assert(llama_dart_exit_track(object, free_named, + LLAMA_DART_EXIT_STAGE_MODEL)); + status_locked_stream = tmpfile(); + assert(status_locked_stream != nullptr); + static std::atomic started{false}; + status_worker = new std::thread([] { + llama_dart_exit_call_begin(); + flockfile(status_locked_stream); + started.store(true); + while (!status_worker_stop.load()) sleep_ms(1); + funlockfile(status_locked_stream); + llama_dart_exit_call_end(); + }); + while (!started.load()) sleep_ms(1); + printf("flushed at exit"); + exit(37); + } + close(output[1]); + std::string text; + char buffer[64]; + for (ssize_t count; (count = read(output[0], buffer, sizeof(buffer))) > 0;) { + text.append(buffer, static_cast(count)); + } + int status = 0; + assert(waitpid(child, &status, 0) == child); + assert(WIFEXITED(status) && WEXITSTATUS(status) == 37); + assert(text == "flushed at exit;host handler ran"); +#endif + return 0; +} + std::string g_system_info; // Uses the static behind llama_print_system_info, which teardown must find @@ -511,7 +679,7 @@ int test_late_static() { g_system_info = llama_print_system_info(); // The reader needs text that lives on the heap for a sanitizer to see a use // after the static is gone. There is none where no backend is loaded. - assert(!kTeardownRunsAtExit || g_system_info.size() > 64); + assert(!kExitFreesObjects || g_system_info.size() > 64); return 0; } @@ -670,7 +838,7 @@ struct model_fixture { }; model_fixture load_model(const char *path, model_options options = {}) { - llama_backend_init(); + init_backends(); model_fixture fixture; auto model_params = llama_model_default_params(); static ggml_backend_dev_t no_devices[] = {nullptr}; @@ -703,7 +871,8 @@ llama_batch prompt(model_fixture &fixture) { } void clear_memory(model_fixture &fixture) { - assert(llama_dart_memory_clear(llama_get_memory(fixture.context), true)); + assert(llama_dart_memory_clear(llama_get_memory(fixture.context), true) || + refused_by_exit()); } llama_sampler *greedy_sampler() { @@ -716,8 +885,11 @@ llama_sampler *greedy_sampler() { // One generation step as the Dart side runs it: decode, then sample. llama_token decode_and_sample(model_fixture &fixture, llama_sampler *sampler) { clear_memory(fixture); - assert(llama_dart_decode(fixture.context, prompt(fixture)) == 0); - return llama_dart_sampler_sample(sampler, fixture.context, -1); + const int32_t status = llama_dart_decode(fixture.context, prompt(fixture)); + assert(status == 0 || refused_by_exit()); + // A decode that was refused has left nothing to sample. + return status == 0 ? llama_dart_sampler_sample(sampler, fixture.context, -1) + : 0; } // Exits with a loaded model and context that nothing frees. @@ -838,7 +1010,7 @@ int test_model_wrappers(const char *path) { } int test_graph() { - llama_backend_init(); + init_backends(); ggml_backend_t backend = llama_dart_ggml_backend_dev_init( ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU), nullptr); assert(backend != nullptr); @@ -1221,6 +1393,7 @@ int exit_while_generating(model_fixture &fixture) { while (steps.load() < 4) { sleep_ms(1); } + g_exit_expected.store(true); g_exiting.store(true); return 0; } @@ -1232,6 +1405,149 @@ int test_model_decode(const char *path) { return exit_while_generating(fixture); } +std::atomic g_computed_after_release{0}; + +// Holds the evaluation and, once it is released, has each tensor computed on +// its own so that the ones computed from then on can be counted. +bool hold_then_count_evaluation(ggml_tensor *tensor, bool ask, void *data) { + if (!ask) { + g_computed_after_release.fetch_add(1); + return true; + } + hold_evaluation(tensor, ask, data); + return g_release_evaluation.load(); +} + +void finish_held_evaluation_at_exit() { + g_release_evaluation.store(true); + const int64_t started = now_ms(); + while (g_computed_after_release.load() < 16) { + if (now_ms() - started > 10000) { + fprintf(stderr, "the held decode did not go on during the exit\n"); + _Exit(EXIT_FAILURE); + } + sleep_ms(1); + } +} + +// Exits while another thread is inside a decode that is not a call in +// flight, so that the exit goes on under it. On Linux no library of the +// bundle registers static destructors, so the decode computes on, with the +// statics the model load created, after the exit has run its handlers. +int test_model_unguarded_decode(const char *path) { + // Registered first, so it runs after the handler of libllamadart and after + // the destructors of the statics that the load creates, where those are + // registered. + assert(atexit(finish_held_evaluation_at_exit) == 0); + static model_fixture fixture; + model_options options; + options.eval_callback = hold_then_count_evaluation; + fixture = load_model(path, options); + decode_prompt(fixture); + clear_memory(fixture); + g_hold_evaluation.store(true); + std::thread([] { + assert(llama_decode(fixture.context, prompt(fixture)) == 0); + }).detach(); + while (!g_evaluation_held.load()) { + sleep_ms(1); + } + return 0; +} + +std::atomic g_returned_from_main_ms{0}; + +void expect_exit_took_no_time() { + const int64_t took = now_ms() - g_returned_from_main_ms.load(); + if (took > 100) { + fprintf(stderr, "the exit took %lld ms with no call in flight\n", + static_cast(took)); + _Exit(EXIT_FAILURE); + } +} + +// On Linux an exit with no call in flight takes no time in libllamadart, +// also right after a guarded call returned: a Dart VM aborts when its +// isolates run while exit() takes its time. +int test_model_exit_idle(const char *path) { + // Registered first, so it runs after the handler of libllamadart. + assert(atexit(expect_exit_took_no_time) == 0); + static model_fixture fixture; + fixture = load_model(path); + llama_sampler *sampler = greedy_sampler(); + assert(decode_and_sample(fixture, sampler) >= 0); + llama_sampler_free(sampler); + g_returned_from_main_ms.store(now_ms()); + return 0; +} + +std::atomic g_worker_stop{false}; +std::atomic g_worker_done{false}; + +// What a host does that stops its worker at exit: the worker must come back. +void stop_and_join_worker() { + g_worker_stop.store(true); + const int64_t started = now_ms(); + while (!g_worker_done.load()) { + if (now_ms() - started > 10000) { + fprintf(stderr, "the worker did not come back during the exit\n"); + _Exit(EXIT_FAILURE); + } + sleep_ms(1); + } +} + +// On Linux the exit blocks no thread: a worker that frees its model when the +// host's own exit handler tells it to returns from the frees, which free +// nothing any more. +int test_model_exit_join_idle(const char *path) { + // Registered first, so it runs after the handler of libllamadart. + assert(atexit(stop_and_join_worker) == 0); + static model_fixture fixture; + fixture = load_model(path); + std::thread([] { + while (!g_worker_stop.load()) { + sleep_ms(1); + } + llama_dart_exit_free(fixture.context); + llama_dart_exit_free(fixture.model); + if (llama_dart_exit_tracked_count() != 0) { + fprintf(stderr, "host worker cleanup left tracked objects\n"); + _Exit(EXIT_FAILURE); + } + g_worker_done.store(true); + }).detach(); + return 0; +} + +// The same with a worker that generates until it is told to stop. An exit +// that finds its decode in flight ends the process; one that falls between +// two calls goes on, every call the worker begins afterwards is refused, and +// the worker comes back. +int test_model_exit_join_generating(const char *path) { + assert(atexit(stop_and_join_worker) == 0); + static model_fixture fixture; + static std::atomic steps{0}; + fixture = load_model(path); + std::thread([] { + llama_sampler *sampler = greedy_sampler(); + while (!g_worker_stop.load()) { + assert(decode_and_sample(fixture, sampler) >= 0); + steps.fetch_add(1); + if (refused_by_exit()) { + sleep_ms(1); + } + } + llama_sampler_free(sampler); + g_worker_done.store(true); + }).detach(); + while (steps.load() < 3) { + sleep_ms(1); + } + g_exit_expected.store(true); + return 0; +} + // Exits while another thread generates on a model whose load created statics // in libllamadart that an earlier, different load had not: a CPU-only load, // then one that maps the file into GPU memory. @@ -1248,9 +1564,22 @@ int test_model_late_load(const char *path) { return exit_while_generating(second); } +std::atomic g_load_resumed{false}; + +void expect_exit_waited_for_load() { + expect_process_ended("a load in flight"); + if (kExitWaitsForCalls && !g_load_resumed.load()) { + fprintf(stderr, "the exit did not wait for the load in flight\n"); + _Exit(EXIT_FAILURE); + } +} + // Exits while another thread is loading the model. int test_model_load(const char *path) { - llama_backend_init(); + // Registered first, so it runs after the handler of libllamadart, which + // nothing but the load in flight makes run: nothing is tracked. + assert(atexit(expect_exit_waited_for_load) == 0); + init_backends(); static std::atomic loading{false}; static const char *model_path = nullptr; model_path = path; @@ -1269,6 +1598,7 @@ int test_model_load(const char *path) { sleep_ms(1); } sleep_ms(500); + g_load_resumed.store(true); return true; }; std::thread([params] { @@ -1285,7 +1615,7 @@ int test_model_load(const char *path) { // Teardown waits for a load in flight although nothing is tracked yet. int test_model_load_wait(const char *path) { - llama_backend_init(); + init_backends(); static std::atomic loading{false}; static std::atomic held{false}; static const char *model_path = nullptr; @@ -1377,6 +1707,7 @@ void free_model_when_teardown_waits(void *object) { } void expect_free_finished_at_exit() { + expect_process_ended("a free in flight"); if (!g_free_finished.load() || g_released_before_teardown.load()) { fprintf(stderr, "the exit did not wait for the free in flight\n"); _Exit(EXIT_FAILURE); @@ -1387,6 +1718,24 @@ void expect_free_finished_at_exit() { // Metal aborts in its static destructor when the exit does not wait for the // free; without Metal the check at exit shows it. int test_model_free_in_flight(const char *path) { +#if defined(__linux__) && !defined(__ANDROID__) + // Linux waits in the host, before libc exit / dependency destructors. + assert(atexit([] { assert(g_free_finished.load()); }) == 0); + auto fixture = load_model(path); + llama_dart_exit_free(fixture.context); + assert(llama_dart_exit_track(fixture.model, [](void *object) { + g_free_started.store(true); + sleep_ms(300); + llama_model_free(static_cast(object)); + g_free_finished.store(true); + }, LLAMA_DART_EXIT_STAGE_MODEL)); + std::thread worker([fixture] { llama_dart_exit_free(fixture.model); }); + while (!g_free_started.load()) sleep_ms(1); + worker.join(); + assert(g_free_finished.load()); + assert(llama_dart_exit_tracked_count() == 0); + return 0; +#else // Registered first, so it runs after teardown and after the Metal device, // which the load creates, is destroyed. assert(atexit(expect_free_finished_at_exit) == 0); @@ -1407,6 +1756,7 @@ int test_model_free_in_flight(const char *path) { } assert(llama_dart_exit_tracked_count() == 0); return 0; +#endif } // Evaluates an image prompt chunk by chunk, as the Dart side does. @@ -2137,7 +2487,7 @@ using tokens = std::vector; // and stops at an end-of-generation token that the draft predicted, as // llama.cpp's common_sampler_sample_and_accept_n does. int test_model_sample_accept(const char *path) { - llama_backend_init(); + init_backends(); auto model_params = llama_model_default_params(); // On the CPU, where every device can run the backend sampler's argmax: the // Metal device of a virtual machine cannot. @@ -2253,6 +2603,10 @@ int main(int argc, char **argv) { const std::string scenario = argc > 1 ? argv[1] : ""; const char *first = argc > 2 ? argv[2] : nullptr; const char *second = argc > 3 ? argv[3] : nullptr; + // Forks, so it runs before anything starts a thread. + if (scenario == "exit-status") { + return test_exit_status(); + } // Keeps llama.cpp's device, load and decode logs out of the test output. llama_dart_set_log_level(3); if (scenario == "dispose") { @@ -2288,6 +2642,12 @@ int main(int argc, char **argv) { if (scenario == "exit") { return test_exit(); } + if (scenario == "exit-in-flight") { + return test_exit_in_flight(); + } + if (scenario == "exit-late-calls") { + return test_exit_late_calls(); + } if (scenario == "late-static") { return test_late_static(); } @@ -2367,6 +2727,18 @@ int main(int argc, char **argv) { if (scenario == "model-decode") { return test_model_decode(first); } + if (scenario == "model-exit-idle") { + return test_model_exit_idle(first); + } + if (scenario == "model-exit-join-idle") { + return test_model_exit_join_idle(first); + } + if (scenario == "model-exit-join-generating") { + return test_model_exit_join_generating(first); + } + if (scenario == "model-unguarded-decode") { + return test_model_unguarded_decode(first); + } if (scenario == "model-late-load") { return test_model_late_load(first); } diff --git a/tests/manual/dart_exit_probe.dart b/tests/manual/dart_exit_probe.dart new file mode 100644 index 00000000..3d649301 --- /dev/null +++ b/tests/manual/dart_exit_probe.dart @@ -0,0 +1,233 @@ +// Manual probe, not run by CI: C exit() through FFI from the main isolate of +// a Dart program while its isolates use libllamadart. It shows what the exit +// handler of libllamadart costs a Dart VM, which aborts when its isolates run +// while exit() takes its time (docs/v060_2_wrapper_rebuild.md). +// +// g++ -std=c++17 -shared -fPIC -Ithird_party/llama.cpp/include \ +// -Ithird_party/llama.cpp/ggml/include \ +// tests/manual/dart_exit_probe_shim.cpp -o libshim.so +// dart tests/manual/dart_exit_probe.dart libshim.so \ +// +// +// holds libllamadart.so and the backend modules. A run is clean +// when it prints EXIT_PROBE_REACHED and exits with code 0. Append -slow-exit +// to a scenario for a host whose own exit handler takes 300 ms, or +// -late-slow-exit to a generating one for a handler that was registered after +// the one of libllamadart. +import 'dart:async'; +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:io'; +import 'dart:isolate'; + +typedef _OpenLibN = Int32 Function(Pointer); +typedef _OpenLibD = int Function(Pointer); +typedef _OpenSesN = Pointer Function(Pointer, Int32); +typedef _OpenSesD = Pointer Function(Pointer, int); +typedef _StepN = Int32 Function(Pointer); +typedef _StepD = int Function(Pointer); + +final _malloc = DynamicLibrary.process() + .lookupFunction< + Pointer Function(IntPtr), + Pointer Function(int) + >('malloc'); + +Pointer _cstr(String s) { + final bytes = utf8.encode(s); + final p = _malloc(bytes.length + 1); + for (var i = 0; i < bytes.length; i++) { + p[i] = bytes[i]; + } + p[bytes.length] = 0; + return p; +} + +Never _cExit() { + stdout.writeln('EXIT_PROBE_REACHED'); + DynamicLibrary.process() + .lookupFunction('exit')(0); + throw StateError('C exit returned'); +} + +void _spin(SendPort ready) { + var rounds = 0; + final bytes = utf8.encode('some text to decode, again and again'); + while (true) { + if (utf8.decode(bytes).isEmpty) throw StateError('unreachable'); + if (++rounds == 100) ready.send(null); + } +} + +// An isolate that wakes every 5 ms and allocates a little, as an app with a +// heartbeat or an animation does. +void _tick(SendPort ready) { + var ticks = 0; + final bytes = utf8.encode('tick'); + Timer.periodic(const Duration(milliseconds: 5), (_) { + final junk = List.generate(2000, (i) => utf8.decode(bytes)); + if (junk.isEmpty) throw StateError('unreachable'); + if (++ticks == 3) ready.send(null); + }); +} + +// Generates as llamadart does: one guarded native step, then Dart work. +void _generate((SendPort, String, String, String, int) a) { + final (ready, shimPath, bundle, model, tokens) = a; + final shim = DynamicLibrary.open(shimPath); + shim.lookupFunction<_OpenLibN, _OpenLibD>('shim_open_library')(_cstr(bundle)); + final session = shim.lookupFunction<_OpenSesN, _OpenSesD>( + 'shim_open_session', + )(_cstr(model), tokens); + final step = shim.lookupFunction<_StepN, _StepD>('shim_step'); + final bytes = utf8.encode('token text'); + var steps = 0; + while (true) { + final status = step(session); + if (status != 0) { + stderr.writeln('PROBE_STEP_STATUS $status'); + } + for (var i = 0; i < 200; i++) { + if (utf8.decode(bytes).isEmpty) throw StateError('unreachable'); + } + if (++steps == 3) ready.send(null); + } +} + +// Runs four steps, reports, then stays idle: llamadart's worker after a +// generation that finished. +void _generateThenIdle((SendPort, String, String, String, int) a) { + final (ready, shimPath, bundle, model, tokens) = a; + final shim = DynamicLibrary.open(shimPath); + shim.lookupFunction<_OpenLibN, _OpenLibD>('shim_open_library')(_cstr(bundle)); + final session = shim.lookupFunction<_OpenSesN, _OpenSesD>( + 'shim_open_session', + )(_cstr(model), tokens); + final step = shim.lookupFunction<_StepN, _StepD>('shim_step'); + for (var i = 0; i < 4; i++) { + step(session); + } + final keepAlive = ReceivePort(); + ready.send(keepAlive.sendPort); +} + +Future main(List args) async { + final [shimPath, bundle, requested, model] = args; + final shim = DynamicLibrary.open(shimPath); + final openLib = shim.lookupFunction<_OpenLibN, _OpenLibD>( + 'shim_open_library', + ); + final openSession = shim.lookupFunction<_OpenSesN, _OpenSesD>( + 'shim_open_session', + ); + final step = shim.lookupFunction<_StepN, _StepD>('shim_step'); + final sleepingAtexit = shim + .lookupFunction( + 'shim_sleeping_atexit', + ); + Future spin() async { + final ready = ReceivePort(); + await Isolate.spawn(_spin, ready.sendPort); + await ready.first; + } + + // A scenario with -slow-exit appended has an exit handler that takes 300 ms. + // It is registered before libllamadart is opened, and so runs after the + // handler of libllamadart. + // With -late-slow-exit the handler is registered right before the exit + // instead, and so runs before the handler of libllamadart. + const slowExit = '-slow-exit'; + const lateSlowExit = '-late-slow-exit'; + final late = requested.endsWith(lateSlowExit); + final scenario = late + ? requested.substring(0, requested.length - lateSlowExit.length) + : requested.endsWith(slowExit) + ? requested.substring(0, requested.length - slowExit.length) + : requested; + if (!late && scenario != requested) sleepingAtexit(300); + + switch (scenario) { + case 'control-spin': // no native library at all + await spin(); + _cExit(); + case 'idle-spin': // model idle for longer than the settle time + openLib(_cstr(bundle)); + final s = openSession(_cstr(model), 8); + step(s); + await spin(); + sleep(const Duration(milliseconds: 400)); + _cExit(); + case 'settle-spin': // exit right after a guarded call ended + openLib(_cstr(bundle)); + final s = openSession(_cstr(model), 8); + await spin(); + step(s); + _cExit(); + case 'generating': // worker isolate alternates guarded calls and Dart + case 'generating-spin': + case 'long-decode-spin': + final ready = ReceivePort(); + await Isolate.spawn(_generate, ( + ready.sendPort, + shimPath, + bundle, + model, + scenario == 'long-decode-spin' ? 1500 : 8, + )); + if (scenario == 'long-decode-spin') { + await spin(); + sleep(const Duration(milliseconds: 300)); + } else { + await ready.first; + if (scenario == 'generating-spin') await spin(); + } + if (late) sleepingAtexit(300); + _cExit(); + case 'loaded-worker-idle': // llamadart's quit-loaded shape + case 'loaded-worker-idle-timer': // the same with a periodic timer in main's group + case 'loaded-worker-idle-spin': + final ready = ReceivePort(); + await Isolate.spawn(_generateThenIdle, ( + ready.sendPort, + shimPath, + bundle, + model, + 8, + )); + if (scenario == 'loaded-worker-idle-spin') await spin(); + if (scenario == 'loaded-worker-idle-timer') { + final ticking = ReceivePort(); + await Isolate.spawn(_tick, ticking.sendPort); + await ticking.first; + } + await ready.first; + _cExit(); + case 'dart-io-exit-generating': // dart:io exit() + final ready = ReceivePort(); + await Isolate.spawn(_generate, ( + ready.sendPort, + shimPath, + bundle, + model, + 8, + )); + await ready.first; + stdout.writeln('EXIT_PROBE_REACHED'); + exit(0); + case 'return-generating': // main returns while a worker generates + final ready = ReceivePort(); + final iso = await Isolate.spawn(_generate, ( + ready.sendPort, + shimPath, + bundle, + model, + 8, + )); + await ready.first; + stdout.writeln('EXIT_PROBE_REACHED'); + ready.close(); + iso.kill(priority: Isolate.immediate); + default: + throw ArgumentError.value(scenario); + } +} diff --git a/tests/manual/dart_exit_probe_shim.cpp b/tests/manual/dart_exit_probe_shim.cpp new file mode 100644 index 00000000..481623dc --- /dev/null +++ b/tests/manual/dart_exit_probe_shim.cpp @@ -0,0 +1,103 @@ +// libllamadart behind functions that tests/manual/dart_exit_probe.dart can +// bind without the structures of llama.h. +#include "llama.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +extern "C" { +llama_model *llama_dart_model_load_from_file(const char *, llama_model_params); +llama_context *llama_dart_init_from_model(llama_model *, llama_context_params); +int32_t llama_dart_decode(llama_context *, llama_batch); +llama_token llama_dart_sampler_sample(llama_sampler *, llama_context *, int32_t); +void llama_dart_set_log_level(int); +void llama_dart_exit_free(void *); +} +static void *g_lib; +static std::atomic active_calls{0}; +static std::atomic free_count{0}; +template static F *sym(const char *n) { + void *s = dlsym(g_lib, n); + if (!s) { fprintf(stderr, "missing %s\n", n); _Exit(3); } + return reinterpret_cast(s); +} +#define BIND(name) auto *name##_ = sym(#name) +struct shim_session { llama_model *model; llama_context *ctx; llama_sampler *sampler; std::vector tokens; }; +extern "C" { +int shim_open_library(const char *bundle) { + if (g_lib) return 0; + g_lib = dlopen((std::string(bundle) + "/libllamadart.so").c_str(), RTLD_LAZY); + if (!g_lib) { fprintf(stderr, "dlopen: %s\n", dlerror()); return 1; } + BIND(llama_dart_set_log_level); BIND(llama_backend_init); BIND(ggml_backend_load_all_from_path); + llama_dart_set_log_level_(4); llama_backend_init_(); ggml_backend_load_all_from_path_(bundle); + return 0; +} +void *shim_open_session(const char *model, int tokens) { + BIND(llama_model_default_params); BIND(llama_dart_model_load_from_file); + BIND(llama_context_default_params); BIND(llama_dart_init_from_model); + BIND(llama_sampler_chain_default_params); BIND(llama_sampler_chain_init); + BIND(llama_sampler_chain_add); BIND(llama_sampler_init_greedy); + auto *s = new shim_session; + auto mp = llama_model_default_params_(); + const char *g = getenv("PROBE_GPU_LAYERS"); + mp.n_gpu_layers = g ? atoi(g) : 0; + s->model = llama_dart_model_load_from_file_(model, mp); + if (!s->model) return nullptr; + auto cp = llama_context_default_params_(); + cp.n_ctx = 2048; cp.n_batch = 2048; cp.n_threads = 3; cp.n_threads_batch = 3; + s->ctx = llama_dart_init_from_model_(s->model, cp); + if (!s->ctx) return nullptr; + s->sampler = llama_sampler_chain_init_(llama_sampler_chain_default_params_()); + llama_sampler_chain_add_(s->sampler, llama_sampler_init_greedy_()); + for (int i = 0; i < tokens; ++i) s->tokens.push_back(100 + i % 400); + return s; +} +// One generation step: guarded decode, then guarded sample. +int shim_step(void *session) { + struct active_guard { active_guard() { ++active_calls; } ~active_guard() { --active_calls; } } guard; + const char *delay = getenv("PROBE_STEP_DELAY_MS"); + if (delay) { fprintf(stderr, "NATIVE_STEP_STARTED\n"); std::this_thread::sleep_for(std::chrono::milliseconds(atoi(delay))); } + BIND(llama_get_memory); BIND(llama_memory_clear); BIND(llama_dart_decode); + BIND(llama_dart_sampler_sample); BIND(llama_batch_get_one); + auto *s = static_cast(session); + llama_memory_clear_(llama_get_memory_(s->ctx), true); + int status = llama_dart_decode_(s->ctx, llama_batch_get_one_(s->tokens.data(), (int32_t)s->tokens.size())); + if (status != 0) return status; + llama_dart_sampler_sample_(s->sampler, s->ctx, -1); + return 0; +} +void shim_sleeping_atexit(int ms) { + static int delay; delay = ms; + atexit([] { std::this_thread::sleep_for(std::chrono::milliseconds(delay)); }); +} + +int shim_free_count() { return free_count.load(); } +int shim_active_calls() { return active_calls.load(); } +void shim_register_host() { + atexit([] { + fprintf(stderr, "HOST_HANDLER_STARTED\n"); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + fprintf(stderr, "HOST_HANDLER_COMPLETED\n"); + }); +} +void shim_buffer_output() { + static char buffer[4096]; + setvbuf(stdout, buffer, _IOFBF, sizeof(buffer)); + fputs("C_BUFFERED_PAYLOAD\n", stdout); +} +void shim_close_session(void *session) { + BIND(llama_sampler_free); BIND(llama_dart_exit_free); + auto *s = static_cast(session); + llama_sampler_free_(s->sampler); + llama_dart_exit_free_(s->ctx); + llama_dart_exit_free_(s->model); + delete s; + ++free_count; + fprintf(stderr, "NATIVE_SESSION_FREE_COMPLETED\n"); +} +} diff --git a/tests/manual/dart_host_shutdown_probe.dart b/tests/manual/dart_host_shutdown_probe.dart new file mode 100644 index 00000000..6b226fcc --- /dev/null +++ b/tests/manual/dart_host_shutdown_probe.dart @@ -0,0 +1,163 @@ +// Manual Linux host-shutdown probe. Build dart_exit_probe_shim.cpp as described +// in dart_exit_probe.dart, then run with PROBE_STEP_DELAY_MS=300: +// dart tests/manual/dart_host_shutdown_probe.dart +// cooperative-finalizer-slow-native verifies a native call is active before +// kill, all worker exits / finalizers complete, and normal C exit preserves +// the earlier host callback and buffered output. raw-control is the known +// Dart VM diagnostic; cooperative-control requires no native bundle. +import 'dart:async'; +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:io'; +import 'dart:isolate'; + +typedef _OpenLibN = Int32 Function(Pointer); +typedef _OpenLibD = int Function(Pointer); +typedef _OpenSesN = Pointer Function(Pointer, Int32); +typedef _OpenSesD = Pointer Function(Pointer, int); +typedef _StepN = Int32 Function(Pointer); +typedef _StepD = int Function(Pointer); + +final _malloc = DynamicLibrary.process() + .lookupFunction< + Pointer Function(IntPtr), + Pointer Function(int) + >('malloc'); + +Pointer _cstr(String s) { + final bytes = utf8.encode(s); + final p = _malloc(bytes.length + 1); + for (var i = 0; i < bytes.length; i++) { + p[i] = bytes[i]; + } + p[bytes.length] = 0; + return p; +} + +Never _cExit() { + stdout.writeln('EXIT_PROBE_REACHED'); + DynamicLibrary.process() + .lookupFunction('exit')(0); + throw StateError('C exit returned'); +} + +void _spin(SendPort ready) { + var rounds = 0; + final bytes = utf8.encode('some text to decode, again and again'); + while (true) { + if (utf8.decode(bytes).isEmpty) throw StateError('unreachable'); + if (++rounds == 100) ready.send(null); + } +} + +// Generates as llamadart does: one guarded native step, then Dart work. +final class _ProbeAnchor implements Finalizable {} + +final _anchors = []; +final _finalizers = []; + +void _generate((SendPort, String, String, String, int) a) { + final (ready, shimPath, bundle, model, tokens) = a; + final shim = DynamicLibrary.open(shimPath); + shim.lookupFunction<_OpenLibN, _OpenLibD>('shim_open_library')(_cstr(bundle)); + final session = shim.lookupFunction<_OpenSesN, _OpenSesD>( + 'shim_open_session', + )(_cstr(model), tokens); + final anchor = _ProbeAnchor(); + final finalizer = NativeFinalizer( + shim.lookup)>>( + 'shim_close_session', + ), + ); + _anchors.add(anchor); + _finalizers.add(finalizer); + finalizer.attach(anchor, session); + final step = shim.lookupFunction<_StepN, _StepD>('shim_step'); + final bytes = utf8.encode('token text'); + var steps = 0; + while (true) { + final status = step(session); + if (status != 0) { + stderr.writeln('PROBE_STEP_STATUS $status'); + } + for (var i = 0; i < 200; i++) { + if (utf8.decode(bytes).isEmpty) throw StateError('unreachable'); + } + if (++steps == 3) ready.send(session.address); + } +} + +Future main(List args) async { + final [shimPath, bundle, scenario, model] = args; + final shim = DynamicLibrary.open(shimPath); + final registerHost = shim.lookupFunction( + 'shim_register_host', + ); + final bufferOutput = shim.lookupFunction( + 'shim_buffer_output', + ); + final freeCount = shim.lookupFunction( + 'shim_free_count', + ); + final activeCalls = shim.lookupFunction( + 'shim_active_calls', + ); + registerHost(); // Registered before the native bundle; must still run later. + final exited = []; + final stopped = >[]; + final isolates = []; + Future spawnWorker( + void Function(T) entry, + T arg, + ReceivePort ready, + ) async { + final onExit = ReceivePort(); + exited.add(onExit); + stopped.add(onExit.first); + isolates.add(await Isolate.spawn(entry, arg, onExit: onExit.sendPort)); + final value = await ready.first; + ready.close(); + return value; + } + + int? sessionAddress; + if (!scenario.contains('control')) { + final ready = ReceivePort(); + sessionAddress = await spawnWorker(_generate, ( + ready.sendPort, + shimPath, + bundle, + model, + scenario.contains('long') ? 1500 : 8, + ), ready) as int; + } + final spinning = ReceivePort(); + await spawnWorker(_spin, spinning.sendPort, spinning); + if (!scenario.startsWith('raw')) { + if (scenario.contains('slow-native')) { + final deadline = DateTime.now().add(const Duration(seconds: 3)); + while (activeCalls() == 0 && DateTime.now().isBefore(deadline)) { + await Future.delayed(const Duration(milliseconds: 1)); + } + if (activeCalls() == 0) throw StateError('slow native call not active'); + stdout.writeln('NATIVE_ACTIVE_BEFORE_KILL'); + } + final watch = Stopwatch()..start(); + for (final isolate in isolates) { + isolate.kill(priority: Isolate.immediate); + } + await Future.wait(stopped).timeout(const Duration(seconds: 20)); + for (final port in exited) { + port.close(); + } + stdout.writeln('ALL_WORKERS_EXITED ${watch.elapsedMicroseconds}'); + stdout.writeln('NATIVE_CALLS_AFTER_EXIT ${activeCalls()}'); + if (activeCalls() != 0) + throw StateError('native call survived worker exit'); + stdout.writeln('NATIVE_FREE_COUNT_AFTER_EXIT ${freeCount()}'); + if (sessionAddress != null && freeCount() != 1) + throw StateError('native finalizer not completed before onExit'); + } + bufferOutput(); + _cExit(); +} diff --git a/tests/test_validate_exports.py b/tests/test_validate_exports.py index 997468e2..fc8f1fbd 100644 --- a/tests/test_validate_exports.py +++ b/tests/test_validate_exports.py @@ -15,6 +15,26 @@ 0000000000004b20 T _llama_dart_decode """ +# readelf -Ws of an ELF library that imports two functions and has a hidden +# definition of __cxa_atexit in its full symbol table. +READELF_OUTPUT = """\ + +Symbol table '.dynsym' contains 3 entries: + Num: Value Size Type Bind Vis Ndx Name + 1: 0000000000000000 0 FUNC WEAK DEFAULT UND __cxa_finalize@GLIBC_2.17 (2) + 2: 0000000000000000 0 FUNC GLOBAL DEFAULT UND dlsym@GLIBC_2.34 (3) + 3: 0000000000004b20 64 FUNC GLOBAL DEFAULT 12 llama_dart_decode + +Symbol table '.symtab' contains 1 entry: + Num: Value Size Type Bind Vis Ndx Name + 1: 000000000000f900 8 FUNC LOCAL DEFAULT 11 __cxa_atexit +""" + +READELF_IMPORT = ( + ' 4: 0000000000000000 0 FUNC GLOBAL DEFAULT UND ' + '__cxa_atexit@GLIBC_2.17 (2)\n' +) + class ValidateExportsTests(unittest.TestCase): def test_nm_exports_and_imports_are_told_apart(self): @@ -25,7 +45,17 @@ def test_nm_exports_and_imports_are_told_apart(self): validate_exports.imported_symbols_from_nm(NM_OUTPUT), {'__cxa_finalize', 'dlsym'}) - def run_tool(self, nm_output, *arguments, library_bytes=b''): + def test_readelf_imports_are_the_undefined_symbols(self): + self.assertEqual( + validate_exports.imported_symbols_from_readelf(READELF_OUTPUT), + {'__cxa_finalize', 'dlsym'}) + self.assertEqual( + validate_exports.imported_symbols_from_readelf( + READELF_OUTPUT + READELF_IMPORT), + {'__cxa_finalize', 'dlsym', '__cxa_atexit'}) + + def run_tool(self, nm_output, *arguments, library_bytes=b'', + tool_format='nm', symbol='llama_dart_decode'): with tempfile.TemporaryDirectory() as temp: library = Path(temp) / 'libllamadart.dylib' library.write_bytes(library_bytes) @@ -36,10 +66,49 @@ def run_tool(self, nm_output, *arguments, library_bytes=b''): tool.chmod(0o755) return subprocess.run( [sys.executable, str(ROOT / 'tools/validate_exports.py'), - '--format', 'nm', '--tool', str(tool), - '--symbol', 'llama_dart_decode', *arguments, str(library)], + '--format', tool_format, '--tool', str(tool), + '--symbol', symbol, *arguments, str(library)], capture_output=True, text=True) + @unittest.skipIf(sys.platform == 'win32', 'the stand-in nm is a shell script') + def test_forbidden_import_in_readelf_output(self): + # The hidden definition in the symbol table is not an import. + absent = self.run_tool( + READELF_OUTPUT, '--forbid-import', '__cxa_atexit', + tool_format='readelf') + self.assertEqual(absent.returncode, 0, absent.stderr) + + imported = self.run_tool( + READELF_OUTPUT + READELF_IMPORT, '--forbid-import', '__cxa_atexit', + tool_format='readelf') + self.assertEqual(imported.returncode, 1) + self.assertIn('__cxa_atexit', imported.stderr) + + @unittest.skipIf(sys.platform == 'win32', 'the stand-in nm is a shell script') + def test_imports_only_skips_the_required_exports(self): + # A llama.cpp library exports none of the wrapper's functions. + missing = self.run_tool( + READELF_OUTPUT, '--forbid-import', '__cxa_atexit', + tool_format='readelf', symbol='llama_dart_encode') + self.assertEqual(missing.returncode, 1) + self.assertIn('llama_dart_encode', missing.stderr) + + skipped = self.run_tool( + READELF_OUTPUT, '--forbid-import', '__cxa_atexit', '--imports-only', + tool_format='readelf', symbol='llama_dart_encode') + self.assertEqual(skipped.returncode, 0, skipped.stderr) + + imported = self.run_tool( + READELF_OUTPUT + READELF_IMPORT, '--forbid-import', '__cxa_atexit', + '--imports-only', tool_format='readelf') + self.assertEqual(imported.returncode, 1) + self.assertIn('__cxa_atexit', imported.stderr) + + unchecked = self.run_tool( + READELF_OUTPUT, '--imports-only', tool_format='readelf') + self.assertEqual(unchecked.returncode, 2) + self.assertIn('--forbid-import', unchecked.stderr) + @unittest.skipIf(sys.platform == 'win32', 'the stand-in nm is a shell script') def test_forbidden_import_fails_only_when_imported(self): absent = self.run_tool(NM_OUTPUT, '--forbid-import', '__cxa_atexit') diff --git a/tests/validate_linux_artifact_test.py b/tests/validate_linux_artifact_test.py index 79e38d0f..809da6cf 100644 --- a/tests/validate_linux_artifact_test.py +++ b/tests/validate_linux_artifact_test.py @@ -16,6 +16,8 @@ from tools.validate_linux_artifact import ( extract_archive, extract_member_safely, + is_nodelete, + parse_imports, resolve_tool, validate_archive, ) @@ -238,6 +240,142 @@ def test_multi_hop_symlink_cycles_are_rejected(self) -> None: errors, ) + def test_imports_are_the_undefined_dynamic_symbols(self) -> None: + readelf = ( + "Symbol table '.dynsym' contains 4 entries:\n" + " Num: Value Size Type Bind Vis Ndx Name\n" + " 0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND \n" + " 1: 0000000000000000 0 FUNC WEAK DEFAULT UND " + "__cxa_finalize@GLIBC_2.17 (2)\n" + " 2: 0000000000000000 0 FUNC GLOBAL DEFAULT UND " + "__cxa_atexit@GLIBC_2.17 (2)\n" + " 3: 0000000000004b20 64 FUNC GLOBAL DEFAULT 12 " + "llama_decode\n" + ) + self.assertEqual( + parse_imports(readelf, "readelf"), {"__cxa_finalize", "__cxa_atexit"} + ) + objdump = ( + "DYNAMIC SYMBOL TABLE:\n" + "0000000000000000 w DF *UND*\t0000000000000000 (GLIBC_2.17) " + "__cxa_finalize\n" + "0000000000000000 DF *UND*\t0000000000000000 (GLIBC_2.17) " + "__cxa_atexit\n" + "0000000000004b20 g DF .text\t0000000000000040 Base " + "llama_decode\n" + ) + self.assertEqual( + parse_imports(objdump, "objdump"), {"__cxa_finalize", "__cxa_atexit"} + ) + + def test_nodelete_is_read_from_readelf_and_objdump(self) -> None: + self.assertTrue( + is_nodelete(" 0x000000006ffffffb (FLAGS_1) Flags: NODELETE\n") + ) + self.assertTrue( + is_nodelete(" 0x000000006ffffffb (FLAGS_1) Flags: NOW NODELETE\n") + ) + self.assertTrue(is_nodelete(" FLAGS_1 0x0000000000000009\n")) + self.assertFalse(is_nodelete(" FLAGS_1 0x0000000000000001\n")) + self.assertFalse( + is_nodelete(" 0x000000006ffffffb (FLAGS_1) Flags: NOW\n") + ) + self.assertFalse(is_nodelete(" 0x000000000000001e (FLAGS) BIND_NOW\n")) + + @unittest.skipIf(sys.platform == "win32", "the stand-in tool is a shell script") + def test_libllamadart_must_not_be_unloadable(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + archive_path = root / "runtime.tar.gz" + with tarfile.open(archive_path, "w:gz") as archive: + for name in ("libllamadart.so", "libmtmd.so.0"): + member = tarfile.TarInfo(name) + member.size = 1 + archive.addfile(member, BytesIO(b"x")) + link = tarfile.TarInfo("libmtmd.so") + link.type = tarfile.SYMTYPE + link.linkname = "libmtmd.so.0" + archive.addfile(link) + tool = root / "readelf" + tool.write_text( + "#!/bin/sh\n" + 'if [ "$1" = "-d" ]; then\n' + " printf ' 0x000000000000000e (SONAME) Library soname: [%s]\\n'" + ' "$(basename "$2")"\n' + "fi\n" + ) + tool.chmod(0o755) + + errors = validate_archive(archive_path, str(tool), "readelf") + + self.assertEqual( + errors, + [ + "libllamadart.so: is not linked with -z nodelete, so a dlclose " + "can unload held native objects and finalizer callbacks" + ], + ) + + @unittest.skipIf(sys.platform == "win32", "the stand-in tool is a shell script") + def test_a_local_library_must_not_import_cxa_atexit(self) -> None: + dynamic = ( + " 0x000000000000000e (SONAME) Library soname: [{soname}]\n" + " 0x000000006ffffffb (FLAGS_1) Flags: NODELETE\n" + ) + imported = ( + " 1: 0000000000000000 0 FUNC GLOBAL DEFAULT UND " + "__cxa_atexit@GLIBC_2.17 (2)\n" + ) + defined = ( + " 1: 000000000000f900 8 FUNC LOCAL DEFAULT 11 " + "__cxa_atexit\n" + ) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + archive_path = root / "runtime.tar.gz" + names = ( + "libllamadart.so", + "libmtmd.so.0", + "libggml-cuda.so", + "libopenblas.so.0", + ) + with tarfile.open(archive_path, "w:gz") as archive: + for name in names: + member = tarfile.TarInfo(name) + member.size = 1 + archive.addfile(member, BytesIO(b"x")) + link = tarfile.TarInfo("libmtmd.so") + link.type = tarfile.SYMTYPE + link.linkname = "libmtmd.so.0" + archive.addfile(link) + + # Answers readelf -d with the file's own name as its SONAME, and + # the symbol listing with the text under test. + symbols = root / "symbols.txt" + tool = root / "readelf" + tool.write_text( + "#!/bin/sh\n" + 'if [ "$1" = "-d" ]; then\n' + f" printf '{dynamic.format(soname='%s')}' \"$(basename \"$2\")\"\n" + "else\n" + f' cat "{symbols}"\n' + "fi\n" + ) + tool.chmod(0o755) + + symbols.write_text(imported) + errors = validate_archive(archive_path, str(tool), "readelf") + self.assertEqual( + errors, + [ + f"{name}: imports __cxa_atexit, so C exit() destroys its statics" + for name in ("libggml-cuda.so", "libllamadart.so", "libmtmd.so.0") + ], + ) + + symbols.write_text(defined) + self.assertEqual(validate_archive(archive_path, str(tool), "readelf"), []) + def test_missing_explicit_tool_reports_a_clean_cli_error(self) -> None: with tempfile.TemporaryDirectory() as directory: missing_tool = Path(directory) / "missing-readelf" diff --git a/tools/validate_exports.py b/tools/validate_exports.py index 03f8f0ad..bd86a56c 100644 --- a/tools/validate_exports.py +++ b/tools/validate_exports.py @@ -126,7 +126,16 @@ def parse_args() -> argparse.Namespace: default=[], help=( "Symbol the library must not import. Supported for --format nm " - "and single-architecture files." + "on Mach-O and --format readelf on ELF, and for " + "single-architecture files." + ), + ) + parser.add_argument( + "--imports-only", + action="store_true", + help=( + "Check only --forbid-import, for a library that has none of the " + "required exports, such as a llama.cpp library next to the wrapper." ), ) return parser.parse_args() @@ -178,6 +187,15 @@ def exported_symbols_from_readelf(output: str) -> set[str]: return symbols +def imported_symbols_from_readelf(output: str) -> set[str]: + symbols: set[str] = set() + for line in output.splitlines(): + parts = line.split() + if len(parts) >= 8 and parts[6] == "UND": + symbols.add(parts[7].split("@", 1)[0]) + return symbols + + def exported_symbols_from_nm(output: str) -> set[str]: symbols: set[str] = set() for line in output.splitlines(): @@ -216,8 +234,13 @@ def exported_symbols_from_dumpbin(output: str) -> set[str]: def main() -> int: args = parse_args() - if args.forbidden_imports and args.format != "nm": - print("--forbid-import requires --format nm", file=sys.stderr) + # nm names are read as Mach-O ones, without their leading underscore, so + # an ELF import such as __cxa_atexit would never match. + if args.forbidden_imports and args.format not in ("nm", "readelf"): + print("--forbid-import requires --format nm or readelf", file=sys.stderr) + return 2 + if args.imports_only and not args.forbidden_imports: + print("--imports-only requires --forbid-import", file=sys.stderr) return 2 # nm lists only the host architecture of a universal file, so the other # slices would go unchecked. @@ -233,7 +256,9 @@ def main() -> int: "nm": exported_symbols_from_nm, "dumpbin": exported_symbols_from_dumpbin, }[args.format](output) - required = args.symbols or DEFAULT_REQUIRED_SYMBOLS + required = ( + [] if args.imports_only else args.symbols or DEFAULT_REQUIRED_SYMBOLS + ) missing = [symbol for symbol in required if symbol not in exported] if missing: print(f"Missing exports in {args.library}:", file=sys.stderr) @@ -241,7 +266,11 @@ def main() -> int: print(f" - {symbol}", file=sys.stderr) return 1 - imported = imported_symbols_from_nm(output) + imported = ( + imported_symbols_from_readelf(output) + if args.format == "readelf" + else imported_symbols_from_nm(output) + ) forbidden = [s for s in args.forbidden_imports if s in imported] if forbidden: print(f"Forbidden imports in {args.library}:", file=sys.stderr) diff --git a/tools/validate_linux_artifact.py b/tools/validate_linux_artifact.py index 96ab30cf..6a2ec076 100644 --- a/tools/validate_linux_artifact.py +++ b/tools/validate_linux_artifact.py @@ -16,6 +16,12 @@ LOCAL_LIBRARY_PREFIXES = ("libllamadart", "libllama", "libggml", "libmtmd") +# The libraries built here bind __cxa_atexit to a definition of their own: +# libllamadart to the one that runs exit teardown first, the llama.cpp +# libraries to the one that registers no static destructor +# (src/llama_dart_static_destructors.c). One that imports it has its statics +# destroyed by C exit() under the calls in flight. +FORBIDDEN_LOCAL_IMPORTS = ("__cxa_atexit",) PLACEHOLDER = "SOVERSION" MAX_ERROR_DETAIL_LENGTH = 512 TARFILE_EXTRACT_SUPPORTS_FILTER = ( @@ -94,6 +100,39 @@ def inspect_dynamic(path: Path, tool: str, mode: str) -> DynamicMetadata: return DynamicMetadata(soname=soname, needed=tuple(needed), raw=raw) +def is_nodelete(raw: str) -> bool: + """Whether readelf -d or objdump -p output has DF_1_NODELETE set.""" + for line in raw.splitlines(): + if "FLAGS_1" not in line: + continue + if "NODELETE" in line: + return True + match = re.search(r"FLAGS_1\s+(0x[0-9a-fA-F]+)\s*$", line) + if match and int(match.group(1), 16) & 0x8: + return True + return False + + +def parse_imports(raw: str, mode: str) -> set[str]: + imports: set[str] = set() + for line in raw.splitlines(): + parts = line.split() + if mode == "objdump": + if "*UND*" in parts and parts[-1] != "*UND*": + imports.add(parts[-1].split("@", 1)[0]) + elif len(parts) >= 8 and parts[6] == "UND": + imports.add(parts[7].split("@", 1)[0]) + return imports + + +def inspect_imports(path: Path, tool: str, mode: str) -> set[str]: + options = ["-T"] if mode == "objdump" else ["--dyn-syms", "-W"] + result = subprocess.run( + [tool, *options, str(path)], check=True, capture_output=True, text=True + ) + return parse_imports(result.stdout, mode) + + def safe_member_name(name: str) -> str: normalized = name.removeprefix("./") path = PurePosixPath(normalized) @@ -237,6 +276,29 @@ def validate_archive(archive_path: Path, tool: str, mode: str) -> list[str]: for dependency in dynamic.needed: if dependency.startswith(LOCAL_LIBRARY_PREFIXES) and dependency not in names: errors.append(f"{name}: local DT_NEEDED dependency is absent: {dependency}") + # Held objects / finalizer callbacks may outlive dlclose. + # Keep the wrapper together with its owned statics. + if name == "libllamadart.so" and not is_nodelete(dynamic.raw): + errors.append( + f"{name}: is not linked with -z nodelete, so a dlclose " + "can unload held native objects and finalizer callbacks" + ) + if name.startswith(LOCAL_LIBRARY_PREFIXES): + try: + imports = inspect_imports(root / name, tool, mode) + except subprocess.CalledProcessError as error: + errors.append( + f"{name}: symbol inspection failed with exit code {error.returncode}" + ) + continue + except OSError as error: + errors.append(f"{name}: symbol inspection failed: {error}") + continue + for symbol in FORBIDDEN_LOCAL_IMPORTS: + if symbol in imports: + errors.append( + f"{name}: imports {symbol}, so C exit() destroys its statics" + ) mtmd = metadata.get("libmtmd.so") if mtmd is None: