Load policy
The one path through which every compiled artifact is opened, registered, retired and unloaded (src/loading/loadpolicy.jl, #277). The exception types are on Errors.
Loading and lifetime
The user-facing halves of the load path:
RustCall.unload_library(name; close = false)/RustCall.unload_all_libraries(; close = false)— drop everything the registries record about a library. The image stays mapped by default, because a call may still be inside it;close = truereclaims it, and is the caller stating that none is.RustCall.retired_handles()/RustCall.retired_handles(name)— the images that have left the registry and are still mapped.RustCall.list_loaded_libraries()— the registered library names, which now include@rust_cratelibraries.RustCall.RustPanicError— a Rustpanic!caught at the FFI boundary (Errors).RustCall.finalizer_failure_count()— how many Rust destructors raised while being called from a finalizer (non-zero means objects leaked).
See Panics, Visibility and Lifetime for the semantics these guarantee.
Load policy (src/loading/loadpolicy.jl)
RustCall.ALL_LOAD_POLICIES — Constant
ALL_LOAD_POLICIESEvery named policy, in the order the inventory in the #277 PR body lists them (the llvm-ir policy that inventory also listed went with the LLVM IR path, #265). Used by test/test_loadpolicy.jl to pin down the current divergences.
RustCall.ARTIFACT_ALIVE — Constant
ARTIFACT_ALIVElib_name → the liveness flag of the artifact currently registered under it.
The flag is a Ref{Bool} rather than a registry lookup on purpose: a finalizer must be able to answer "is my library still loaded?" with a single load of a captured Ref, taking no lock and touching no dictionary (#249). Flipping the flag is the only thing that makes an object produced by an unloaded library inert; the object itself is unreachable from here by then.
Guarded by REGISTRY_LOCK. An alias (alias_artifact!) shares the flag of the artifact it aliases, so unloading either name retires both.
RustCall.ARTIFACT_GENERATIONS — Constant
ARTIFACT_GENERATIONSlib_name → how many times an image has been installed under that name.
The number a snapshot carries. It is what makes "these values came from one generation" checkable rather than merely intended: a CallTarget, an ArtifactGeneration and a crate module's CrateGeneration all record it, so a test — or a future assertion — can compare two snapshots instead of comparing raw pointers, and the reload stress test can watch for a call that straddled a swap.
Guarded by REGISTRY_LOCK.
RustCall.ARTIFACT_IMAGE_PATHS — Constant
ARTIFACT_IMAGE_PATHSlib_name → the path the image registered under that name was opened from.
An :insert_only loser is handed the incumbent image without learning where it came from, and for one caller that matters: a generic batch member must be opened from the one copy the batch memo names (_batch_copy_is_current), and the incumbent it lost to may be a retired image a stale reader revived from an older copy and has not yet retired again (#397). The memo is current and so is the image, yet it is not the fresh copy the memo names; this table is how the publication can tell. Written with the registry row, dropped with it, and shared by an alias. A name registered without a path (adopt_artifact!) has no entry. Guarded by REGISTRY_LOCK.
RustCall.DEAD_ARTIFACT — Constant
DEAD_ARTIFACTA liveness flag that is false and stays false: the answer for a pointer whose image is neither registered nor retired. Shared, because it is immutable in practice — nothing ever flips it.
RustCall.DLCLOSE_COUNT — Constant
DLCLOSE_COUNTHow many dlclose calls this session has made, process-wide.
One image can be closed more than once: dlopen refcounts, so an image loaded under two names owes two closes, and this counts each of them.
Closing an image twice is not an error the loader can detect after the fact — the second dlclose decrements a refcount that belongs to someone else, or unmaps code another name is still pointing at — so the invariant "one open, one close" is asserted by counting rather than by hoping. close_artifact_handle! is the only place that closes, and test/test_loadpolicy.jl reads this counter to check that unloading a library with an alias closes it once.
RustCall.GENERATION_COPY_HOST_LEN — Constant
GENERATION_COPY_HOST_LENLength of the host tag in a generation copy's name: hex characters of stable_content_hash(gethostname()), truncated by artifact_short_id.
RustCall.GENERATION_COPY_INSTANCE_LEN — Constant
GENERATION_COPY_INSTANCE_LENLength of the per-process instance token in a generation copy's name (_generation_copy_instance): hex characters.
RustCall.GENERATION_COPY_MARKER — Constant
GENERATION_COPY_MARKERThe word in a generation copy's name that says RustCall made it: libfoo.rustcall.<host>.<pid>.<generation>.dylib.
The stale-copy sweep deletes files, so the shape it matches must be one nothing else produces. <stem>.<number>.<number><ext> is not that — a versioned or application-managed libfoo.12345.2.dylib beside libfoo.dylib would be deleted the moment pid 12345 is absent. With the marker, only a file RustCall itself named is ever a candidate.
RustCall.GENERATION_LEASE_SUFFIX — Constant
GENERATION_LEASE_SUFFIXBeside every generation copy loadable_library_copy makes sits <copy>.lease, a file the owning process keeps open and locked for its whole life. A pid proves nothing across pid namespaces — container B's kill(pid, 0) says nothing about container A's process — but an advisory lock on a shared volume is held by whichever process holds it, whatever namespace it runs in, and is released by the kernel when that process ends, cleanly or not. So the stale-copy sweep asks the lease, not the process table: a copy whose lease it can lock has no owner and goes; one whose lease is held stays. This is the shape of the lockfile claim of #256 / PR #313.
RustCall.HANDLE_MIRRORS — Constant
HANDLE_MIRRORSlib_name → the module-local copies of that library's handle and liveness flag that the loader keeps in sync.
A generated @rust_crate module resolves its symbols through its own generation record. The module exposes an owner-qualified StateView and the underlying cell is owned by STATE. A raw copy of a handle goes stale the moment the library is replaced or unloaded: a hot reload retires the previous image, and unload_library drops it, after which a raw copy of the handle would be read against an image nothing points at any more. Registering the module's owned cell here lets the transaction that swaps the handle swap the mirror in the same critical section, so a single record read can never point at a closed image (#277 Phase B).
The mirrors survive an unload rather than being dropped with it: a hot reload is "unload then load under the same name", and the module that registered them is still there waiting for the new handle.
Guarded by REGISTRY_LOCK.
RustCall.OWNED_HANDLES — Constant
OWNED_HANDLESThe handles RustCall itself opened, and is therefore allowed to close.
load_artifact! opens an image and records it here. adopt_artifact! does not: it is handed a handle that somebody else opened — a caller that resolved one its own way, a test registering a value that was never a real image — and closing that would be closing something RustCall does not own. On glibc a dlclose of a stale or foreign handle segfaults inside _dl_close rather than returning an error, so "do not close what you did not open" is not a nicety.
It is a count, not a set. dlopen refcounts: opening the same path twice returns the same handle and needs two dlcloses. A set collapsed those into one entry, so closing the losing duplicate of an :insert_only race deleted the only record and the winner could then never be closed — the image stayed mapped forever. One increment per dlopen this package performs, one decrement per close, so the process closes exactly as many times as it opened.
The count is also what makes closing safe under a race: close_artifact_handle! decrements in the same locked step that decides whether to close, so two callers cannot both decide to perform the last close.
Guarded by REGISTRY_LOCK.
RustCall.PRELOADED_LIBRARIES — Constant
PRELOADED_LIBRARIESThe libraries preload_dependency! has opened, by path, with their handles.
An entry is a dependency some artifact imports by name — a Python runtime DLL — that RustCall opened so the loader could resolve that import. It is never closed: the artifacts that import it may outlive any one of them being retired, and a runtime like Python cannot be unloaded and reloaded within one process anyway. Guarded by REGISTRY_LOCK.
RustCall.QUIET_HOOK_LOCK — Constant
QUIET_HOOK_LOCKSerialises the quiet panic hook's lifecycle for one process (#304).
Two transitions must not interleave: record a loader reference, then install (load_artifact!) and confirm no reference is left, then uninstall (close_artifact_handle!). Without this lock a dlopen of a still-mapped path could record its reference and call the installer — a no-op, because the hook is still marked live — in the window between the other task's zero-count check and its uninstall, leaving a live image with no hook and nothing to restore it (#388 review).
Lock ordering: this lock is taken before REGISTRY_LOCK, never after. Only the two paths above take it, and the only foreign code called under it is the artifact's own installer/uninstaller — a thread-local read and a set_hook/take_hook, with no allocation of ours and no call back into Julia. REGISTRY_LOCK is never held across that call.
RustCall.QUIET_PANIC_HOOK_INSTALLS — Constant
QUIET_PANIC_HOOK_INSTALLS
QUIET_PANIC_HOOK_REMOVALSHow many times this process called an artifact's quiet-hook installer and uninstaller (#304). Counters, not registries: a test asserts that closing an artifact removed its hook without having to reach into the image.
INSTALLS counts calls, and the generated installer is guarded by a mutex over an "installed" flag (not a Once, so it can install again after an uninstall), so loading one image twice calls it twice and installs once. Calling it on every load rather than only on the reference that opened the image is deliberate: two tasks racing on one path would otherwise let the loser call a wrapper before the winner had installed anything. REMOVALS counts only the last reference, because that is the close that unmaps.
RustCall.QUIET_PANIC_INSTALL_SYMBOL — Constant
QUIET_PANIC_INSTALL_SYMBOL
QUIET_PANIC_UNINSTALL_SYMBOLThe two symbols an artifact whose source RustCall generated in full exports for its quiet panic hook (#304). They are spelled in rustcall_julia_core::codegen::{INSTALL,UNINSTALL}_PANIC_HOOK_SYMBOL; a mismatch would show up as the hook never being installed, which test/test_panic_hook.jl asserts against.
RustCall.RELOAD_GENERATION — Constant
RELOAD_GENERATIONA process-wide, monotonic counter for the paths RustCall opens.
Every freshly built library is copied to <lib>.<generation>.<ext> and that copy is opened, so the image already mapped is never the file Cargo is about to write. The counter is per process so a counter restarted with a new HotReloadState cannot collide with a .1. file that is still mapped from an earlier session.
RustCall.RETIRED_HANDLES — Constant
RETIRED_HANDLESEvery image that has left the registry and is still mapped, keyed by handle.
An image leaves the registry two ways — a hot reload replaces it, or unload_library drops it — and neither may close it. In both cases a task can already hold a function pointer it read out of that image: the pointer was resolved before the swap, and the call is in flight. Closing the image under it is a use-after-dlclose, which is a segfault. RustCall has no per-call reader pin that would make closing safe, and adding one would put two atomics on the hot path of every FFI call to guard against something that happens at most once per reload.
So a retired image stays mapped. Nothing new can enter it — the registry, the metadata tables, the panic channels and the module mirrors all stop pointing at it — and the calls already inside finish normally. Its liveness flag stays true, so an object allocated by that image still runs its destructor, which lives in that image and is still mapped: the allocator contract holds by construction (#249). Only closing the image flips the flag, and only then do its objects become inert.
Keyed by handle rather than by library name so a record cannot be lost when the name goes: unload_library(name) removes the name, and the image it retired must remain reclaimable afterwards.
Reclaiming is explicit — unload_library(name; close = true), unload_all_libraries(; close = true) — and is the caller stating that no call into those images is in flight. A REPL session editing Rust in a loop never needs it; a long-running process or a test harness does.
Guarded by REGISTRY_LOCK.
RustCall.SYMBOL_VISIBILITY_RULE — Constant
SYMBOL_VISIBILITY_RULEProse statement of the rule Phase B should apply when choosing RTLD_GLOBAL over RTLD_LOCAL. Kept as data so the tests and the docs quote one text.
The rule: a library is loaded RTLD_GLOBAL only when other libraries loaded later must resolve undefined symbols against it. No artifact RustCall loads is in that category, so every policy is RTLD_LOCAL | RTLD_NOW (#277 Phase B2).
Why the category is empty:
- Nothing in
src/writes accall((:name, "lib"), ...). Every call goes through a pointer obtained fromLibdl.dlsymon a specific handle, anddlsymon a handle works identically whether the image was opened LOCAL or GLOBAL. The cross-library fallback in_resolve_calliterates the handles inRUST_LIBRARIES, not the process-global namespace, so it keeps working too. - Every artifact RustCall builds is a self-contained
cdylib. UnderRTLD_NOWa genuinely unresolved symbol fails at load rather than at first call. - The ownership helper library (
deps/rustcall_helpers) looked like the one exception and is not: every user reaches it throughRUST_HELPERS_LIB[]plusdlsym, and no artifact links against it. - PyO3 crates look like an exception and are not: their
Py_*symbols resolve against libpython, which PythonCall has already loaded globally. RustCall's own flag does not affect that.
What RTLD_LOCAL buys: two rust""" blocks that both export f no longer shadow one another in the process-global namespace, so which one a call reaches stops depending on load order (#250).
Before B2 the rule was exactly inverted — leaf artifacts were mostly RTLD_GLOBAL and the helper library was RTLD_LOCAL — and the split among inline blocks ran along the dependency axis: no // cargo-deps: meant RTLD_LOCAL, // cargo-deps: meant RTLD_GLOBAL, for the same construct.
(RUSTCALL_DLOPEN_GLOBAL=1 restored the old process-global behaviour through v0.4.x and is ignored since v0.5, #417.)
RustCall.CachedCrateTarget — Type
CachedCrateTargetOne @rust_crate call site's remembered snapshot, with the two things that say whether it may still be used: the process that resolved it and the artifact epoch it was resolved at.
target is whatever tuple the arm that produced it returns — a pointer and a channel, those plus a release function, plus a liveness flag, and so on. It is stored and handed back whole, never rebuilt from parts, so the generation rule of #277 is untouched: what is cached is one snapshot of one image.
RustCall.CrateGeneration — Type
CrateGenerationWhat a generated @rust_crate module knows about the image it calls: the handle, the liveness flag of that image, and the generation number — as one immutable value.
Why one value and not three Refs
The module used to keep the handle and the flag in two separate Refs, written by _update_handle_mirrors! under REGISTRY_LOCK and read by the module's wrappers under the module's own lock. Two unrelated locks over two cells is not a snapshot: a constructor could read the old handle, the writer could then run, and the constructor would pair that handle with the replacement's liveness flag. The object then believed itself live after the image it was allocated by had been closed, and its finalizer jumped through an unmapped destructor.
One immutable record removes the question — but only if publishing it is one store, which is what CrateGenerationCell is for. A plain Base.RefValue{CrateGeneration} is not: see that type's docstring for the measurement (#402).
RustCall.CrateGenerationCell — Type
CrateGenerationCell([record])The cell a generated @rust_crate module reads its generation record from, and that _update_handle_mirrors! publishes into. Behaves as a Ref — cell[] and cell[] = record — so every call site reads the same as before.
Why not a Base.RefValue{CrateGeneration} (#402)
Because that tears. CrateGeneration holds a Ref{Bool}, so it is not isbits, and this file used to reason from that: "the Ref holds a pointer to it and publishing a new generation is a single pointer store". That is wrong. Julia stores an immutable struct inline in a RefValue whenever it can, and it can here — sizeof(Base.RefValue{CrateGeneration}) is 24, the struct itself, not 8. So gen_ref[] = published is a 24-byte write and a reader's deref is a 24-byte read, with nothing keeping them apart.
A reader therefore observed records that were never published: one generation's handle with another's number and flag. Measured directly — one writer alternating two records, one reader checking that the three fields came from the same one — 137129 torn reads out of 13211045. It surfaced as the reload stress test pairing one generation number with two different returned values (#402).
How exposed this was, exactly
A generated module reaches its cell through a StateView, and StateView reads take STATE.lock — which is REGISTRY_LOCK (src/RustCall.jl), the lock _update_handle_mirrors! writes under. So no generated wrapper has ever read a torn record: the two sides exclude each other by accident of the container, not by the store being atomic.
What was exposed is everything this type says a caller may do. The paragraph above promised a lock-free read, register_handle_mirror! takes a bare cell so that a caller can have one, and test/test_hot_reload_transaction.jl reads exactly that way — which is how #402 was found. Had a lock-free read been added later, as #253 did for the target cache, it would have been the #291 hazard with no test to catch it: a wrapper pairing a new handle with the previous image's liveness flag, or an object capturing a destructor from one image and a flag from another. The store is atomic now, so the promise is true rather than true-by-coincidence.
@atomic on the field is the fix, and the Union{Nothing, …} is what makes it cheap: an atomic field wider than a pointer falls back to a lock (measured: sizeof 40 for a bare @atomic record::CrateGeneration), while a union with a reference is stored as one pointer — sizeof 8, one store, one load, no lock and no allocation on the read path. CrateTargetCache above is the same shape for the same reason.
test/test_hot_reload_transaction.jl asserts both halves: that the cell does not tear under a writer, and that it is still pointer-sized, so that a later simplification back to a Ref fails instead of silently reintroducing this.
RustCall.CrateTargetCache — Type
CrateTargetCache()One call site's memory of the snapshot it last took out of a generated @rust_crate module (#253).
Why a named binding and not a spliced object
The inline rust""" path (CallTargetCache, src/macros/ruststr.jl) splices its cache straight into the expansion, so it needs no name. A @rust_crate module cannot do that: write_bindings_to_file emits the same module as source text, and an object has no source spelling. So each call site of a generated module declares its cache as a const of that module, which both flavours can write, and which test/test_state.jl accepts because a target cache is not a registry — it holds one immutable snapshot and is invalidated wholesale.
What makes an entry usable
Exactly what makes a CachedTarget usable, and for exactly the same reasons:
ARTIFACT_EPOCHmust not have moved. Every write to the state container bumps it (_state_mutate_storage!), and so does every publication to a module's generation mirror, so a hot reload, an unload, an alias or a newly memoized symbol all invalidate every kept snapshot.SESSION_TOKENmust be this process's. A generated module is routinely precompiled into a package, and a wrapper called from a precompile workload would otherwise serialise a populated cache — raw pointers included — into the.ji, where a matching epoch in the next process would hand a dead pointer toccall.
RustCall.LoadPolicy — Type
LoadPolicyOne explicit record of the load/compile policy for a single compiled artifact.
Construct one through a named constructor (see inline_rustc_policy, inline_cargo_policy, crate_direct_policy, helper_library_policy, and the rest of ALL_LOAD_POLICIES) rather than calling this constructor directly, so that every front door keeps a name.
Fields
name::String— the front door this policy describes, for diagnostics.dlopen_flags::UInt32— the exact flag set handed toLibdl.dlopen:RTLD_LOCAL | RTLD_NOWfor every named policy.global_symbols::Bool— whether the flag set includesRTLD_GLOBAL, i.e. whether this artifact publishes its symbols into the process-global namespace. SeeSYMBOL_VISIBILITY_RULEfor when that is legitimate.panic_strategy::Symbol— the panic strategy the artifact is compiled with, one of::unwind— RustCall pins unwinding:-C panic=unwindon therustccommand line (rustc_panic_flags),panic = "unwind"in a generated[profile.release](cargo_profile_panic_line) andCARGO_PROFILE_<PROFILE>_PANIC=unwindin Cargo's environment, so an inheritedCARGO_PROFILE_RELEASE_PANIC=abortcannot turn it into an aborting build. Every door RustCall builds itself carries this value;:crate_profile— RustCall does not control the build: Cargo runs in the user's crate, so the effective profile (the crate's own[profile.release], a workspace profile,.cargo/config.toml, orCARGO_PROFILE_RELEASE_PANIC) decides, andpanic = "abort"there is honoured, hence a separate value rather than a guess;:abort—-C panic=abort; the keyword constructor's default, which no named policy uses any more (the direct-rustcpath aborted until #244);:cargo_default— Cargo drives the build and RustCall pins nothing, so Cargo's default for the profile applies, subject toCARGO_PROFILE_<PROFILE>_PANICfrom the environment. No named policy uses it any more;effective_panic_strategyresolves it.
boundary_catches_panics::Bool— whether the generatedextern "C"wrapper wraps the user body instd::panic::catch_unwindand reports the panic through the thread-local panic channel.truefor every named policy (#244, #346).registry::Symbol— where the loaded handle is recorded::rust_libraries(theRUST_LIBRARIESdict),:module_local(aRefin the generated@rust_cratemodule),:helper_slot(RUST_HELPERS_LIB), or:none.registry_key_kind::Symbol— the shape of the key used with:rust_libraries::content_hash(rust_<hash>from the inline paths),:lib_basename(unused since #278),:crate_lib_name(hot reload), or:none.:irust_hashwent with@irust(#538).registration_mode::Symbol— whatload_artifact!does when the name is already registered::replace(install the new image and retire the old one) or:insert_only(keep the existing entry and its function-pointer cache, and hand the loser the incumbent image;generics_policy).sets_current_lib::Bool— whether the site also movesCURRENT_LIB[].finalizer_frees::Bool— whether objects produced by this artifact free their Rust allocation in their finalizer.truefor inline#[julia]structs (since #277 Phase B4) and@rust_cratestructs alike (#249);falsefor the generics policy.call_sites::Vector{String}— the sites this policy was written to subsume (#277). Kept as a record of that inventory; itsfile:linereferences date from it and are not maintained.issues::Vector{Int}— the issues behind this policy's decisions.notes::String— free-form description of the policy.
RustCall.LoadPolicy — Method
LoadPolicy(name; kwargs...) -> LoadPolicyKeyword constructor. The defaults are RTLD_LOCAL | RTLD_NOW, panic=abort with no catch_unwind boundary, registration in RUST_LIBRARIES under a content hash replacing any previous entry, CURRENT_LIB untouched, and finalizers that free.
Every named constructor below states its own values; none keeps the :abort default (every door RustCall builds is pinned to :unwind, #244).
RustCall.LoadedArtifact — Type
LoadedArtifactOne loaded shared library, as returned by load_artifact!.
Fields
name::String— theRUST_LIBRARIESkey the artifact is registered under (still meaningful for policies that register nowhere: it names the artifact in diagnostics).handle::Ptr{Cvoid}— the livedlopenhandle. For an:insert_onlypolicy that lost the race this is the existing handle, not the duplicate that was opened and immediately closed.path::String— the file that was opened.policy::LoadPolicy— the policy it was opened under.alive::Ref{Bool}— flipped tofalsebyunload_artifact!and by a:replaceregistration that evicts this artifact. Objects produced by the artifact capture thisRefat construction so their finalizer can skip a call into adlclosed image without taking a lock or doing a lookup (#249): a finalizer may run while the running thread holdsREGISTRY_LOCK, so it must never take it.installed::Bool— whether this call put the handle in the registry.falsefor an:insert_onlypolicy that lost the race and was handed the existing image, and for a helper/module-local policy that found its image already registered; a caller that must undo only what it itself installed (release_generics' revived-batch case, #397) reads this rather than guessing from the handle, which the loser shares with the winner.assumed_unwind::Bool—must_assume_unwindresolved against the environment the artifact was built under (snapshot_env), recorded at load time because the liveENVis not evidence about a cached artifact (#244).
RustCall.RetiredImage — Type
RetiredImageAn image that has left the registry but is still mapped.
Carries what closing it later needs: the liveness flag its objects captured, the names it was known by (for diagnostics and for unload_library(name; close = true)) and how many owned opens it had.
RustCall._acquire_generation_lease — Method
_acquire_generation_lease(copy_path) -> Union{Bool, Nothing}Create <copy>.lease and take its lock for the rest of this process's life (_GENERATION_LEASES). true: held. false: another process holds a lease of that name — the copy path is taken (a collision of host, pid, instance and generation, which the instance token makes all but impossible) and the caller picks another generation. nothing: no lease could be made or locked here; the caller proceeds without one, as before #321.
Windows is always nothing: it has no pid namespaces, so _process_alive sees every process on the machine and the sweep's pid fallback is exact there. A lease held for the life of the process is also a file an active lock keeps DeleteFile from unlinking, which would refuse the test or rebuild that removes a temp tree holding a live copy (EBUSY). The instance token already makes the copy name unique, so nothing is lost.
RustCall._as_env — Method
parse_cargo_env_snapshot(text::AbstractString) -> Dict{String, String}Parse a serialized build-time environment snapshot — one KEY=VALUE per line, the shape PR #272 stores in RustBlockSnapshot.cargo_env — into a dictionary suitable as the env of effective_panic_strategy.
Blank lines and lines without = are skipped; the value keeps everything after the first =, so KEY=a=b yields "a=b". Surrounding whitespace is trimmed from the key only, since a value's whitespace can be significant.
RustCall._generation_copy_host — Method
_generation_copy_host() -> StringThe host tag of this process's generation copies: a fixed-length hex prefix of the digest of the host name.
A pid names a process only on the host that runs it. When the library sits on a volume several hosts share — NFS, a bind mount into a container with its own pid namespace — host B's process table says nothing about host A's pids, so without this tag B could take A's still-running process for dead and delete the copy A is between cp and dlopen of, and two hosts with the same pid and counter could even pick one path. The sweep only ever considers copies carrying this host's own tag. Computed per call rather than at precompile time, so an image built on one machine does not carry that machine's name.
RustCall._generation_copy_instance — Method
_generation_copy_instance() -> StringA token that tells this process apart from every other process that may share the library's volume — including one in another pid namespace with the same pid (#321): a bind mount into two containers that also share the UTS hostname gives both the same host tag and can give both the same pid and the same RELOAD_GENERATION, so without it they would pick one copy path.
Drawn once per process at first use, from /dev/urandom where there is one and otherwise from the clock, the pid and the host, and folded through stable_content_hash; never computed at precompile time, so an image does not carry the token of the process that built it.
RustCall._generation_copy_name — Method
_generation_copy_name(stem, ext, host, pid, instance, generation) -> String<stem>.rustcall.<host>.<pid>.<instance>.<generation><ext>: the one spelling of a generation copy's file name, used by process_generation_path to make one and by _sweep_stale_generation_copies to recognise one.
RustCall._lease_state — Method
_lease_state(copy_path) -> SymbolWhat the lease beside copy_path says about its owner, for the sweep: :held (a process holds it — alive, wherever it runs), :free (the lease exists and nobody holds it — the owner is gone), :none (no lease, or a file system without locking — decide from the process table instead).
RustCall._process_alive — Method
_process_alive(pid) -> BoolWhether a process with this id exists, for the stale-copy sweep.
On Unix kill(pid, 0) delivers nothing and reports ESRCH for a pid nobody holds; any other answer (0, or EPERM for another user's process) counts as alive. On Windows OpenProcess with PROCESS_QUERY_LIMITED_INFORMATION fails with ERROR_INVALID_PARAMETER for a pid nobody holds, and an open handle whose GetExitCodeProcess is STILL_ACTIVE is a running process; anything else — access denied, a query that fails — counts as alive.
The answer matters on Windows too, not only the file system's refusal to delete a mapped DLL: between a process's cp and its dlopen the copy is not mapped yet, so a sweep in another process that treated every pid as dead could delete it in that window. Errs on the side of "alive".
RustCall._sweep_stale_generation_copies — Method
_sweep_stale_generation_copies(built_path)Remove the <lib>.rustcall.<host>.<pid>.<instance>.<generation>.<ext> copies beside built_path that this host made and whose owner is gone, and their leases.
A written bindings module makes one copy per process start, and nothing removes it when that process exits — an image is retired, not closed, and on Windows a mapped DLL cannot be deleted anyway — so an application that keeps launching Julia would accumulate copies without bound (#309). The next process to copy the same library sweeps first. Who is "gone" is decided by the copy's lease (GENERATION_LEASE_SUFFIX, #321): a lease this sweep can lock has no owner anywhere on the volume, in this pid namespace or another, and the copy goes; a lease somebody holds means a live owner, whatever its pid looks like from here, and the copy stays. Only when there is no lease to ask — a copy made without one, or a file system without locking — does the process table decide, as it did before #321. This process's own copies are never candidates; a copy Windows still has mapped refuses the delete and is kept for a later sweep. Only names carrying GENERATION_COPY_MARKER and this host's tag are candidates: the pre-#309 <lib>.<generation>.<ext> shape and anything else beside the library are not RustCall's to delete. The v0.4.x shape without an instance token is still recognised, by pid, for one release. Best effort: nothing here can fail the load.
RustCall._try_lock_lease — Method
_try_lock_lease(io::IOStream) -> Union{Bool, Nothing}Take an exclusive, non-blocking lock on the open lease io: true when acquired, false when another open description holds it (flock reports EWOULDBLOCK; LockFileEx reports ERROR_LOCK_VIOLATION), nothing when the file system offers no locking at all — the sweep then falls back to the process table, and the owner proceeds without a lease.
flock locks belong to the open file description, so a second open of the same lease in the same process conflicts too, which is what lets a test observe the lock; on Windows LockFileEx over the first byte does the same. Both are released when the description is closed or the process ends.
RustCall.adopt_artifact! — Method
adopt_artifact!(policy::LoadPolicy, handle::Ptr{Cvoid};
lib_name, path = "", symbols = (), return_types = (),
eager = (), snapshot_env = nothing, close_duplicate = false,
set_current = policy.sets_current_lib) -> LoadedArtifactThe registration half of load_artifact!, for a handle that is already open.
load_artifact! is dlopen (outside the lock) followed by this. Splitting the two is what lets a caller that obtained a handle some other way — a test registering a preopened image, a generated @rust_crate module that keeps its own module-local Ref — publish it through exactly the same transaction, with the same eviction, liveness and CURRENT_LIB semantics.
It never closes the handle it was given. An :insert_only policy whose key is already taken keeps the incumbent and hands the caller's handle back unused, but closing it is only correct for a caller that opened it — which is load_artifact!, and which therefore passes close_duplicate = true. Closing a handle the caller still owns, or one that was never a real dlopen result, is a segfault inside the dynamic loader.
RustCall.alias_artifact! — Method
alias_artifact!(policy::LoadPolicy, from, to) -> BoolRegister the library already loaded as from under the second name to.
One handle legitimately sits in RUST_LIBRARIES under two names: a reload derives a different identity than the one a precompiled module recorded, and _alias_reloaded_library (#272) makes the stored name resolve to the library that was actually loaded. Both registries are per library (#279), so the alias needs its own symbol mappings and return-type hints — without them a lookup through the stored name resolves f to f, misses the rustcall_f the library exports and falls into the cross-library search.
The alias shares the aliased artifact's liveness flag, so unloading either name retires objects produced through both — and unloading either name removes both, because they name one image: unload_artifact! collects every name of the handle and closes it once (library_names_for_handle). Removing one and leaving the other would leave a registry entry pointing at unmapped code, and closing once per name would close an image the process opened once.
An alias over a name that pointed at a different image retires that image rather than killing it: it is still mapped, so it keeps its liveness flag true and its objects still free through it, exactly as a replaced image does (load_artifact!). It becomes inert only when close_retired_handles! actually closes it. Aliasing over one of several names of a live image does nothing to that image at all.
Returns false when from is not loaded.
RustCall.alive_ref_for_handle — Method
alive_ref_for_handle(handle, lib_name) -> Base.RefValue{Bool}The liveness flag that belongs to the image handle names, not to whatever is registered under lib_name now. Caller holds REGISTRY_LOCK.
This is what a cached pointer needs. artifact_alive_ref(name) answers "is the library called name loaded?", and for a pointer resolved a while ago that is the wrong question: if the library was replaced or unloaded in between, the name's flag belongs to a different image — or, worse, artifact_alive_ref invents a fresh Ref(true) for a name nothing is registered under, and an object holding it believes itself live forever while its destructor points into an image that has since been closed.
So the flag is found by handle: the registered one when handle is still what lib_name resolves to, the retired image's own flag when it has been retired (that flag is flipped when the image is finally closed, which is exactly when the pointer stops being callable), and a permanently-false flag when the image is neither — in which case the object goes inert and leaks rather than calling into nothing.
RustCall.artifact_alive_ref — Method
artifact_alive_ref(lib_name) -> Ref{Bool}The liveness flag of lib_name, created (as true) when the library has none yet — a library loaded before this session's first load_artifact!, or one registered by a path that predates the loader.
Capture this once, at construction time, into any object whose finalizer calls back into the library; never look it up from the finalizer.
RustCall.artifact_generation — Method
artifact_generation(lib_name) -> IntWhich generation of lib_name is installed now; 0 if none ever was.
RustCall.artifact_handle_is_owned — Method
artifact_handle_is_owned(handle) -> BoolWhether RustCall opened this image and may close it.
RustCall.artifact_handle_open_count — Method
artifact_handle_open_count(handle) -> IntHow many times RustCall opened this image and has not yet closed it. dlopen refcounts, so this is how many dlcloses the package still owes.
RustCall.cargo_panic_env_var — Method
cargo_panic_env_var(policy::LoadPolicy) -> StringThe CARGO_PROFILE_<PROFILE>_PANIC variable that overrides this policy's panic strategy, derived from policy.cargo_profile — CARGO_PROFILE_RELEASE_PANIC for every Cargo-backed door today.
RustCall.cargo_profile_panic_line — Method
cargo_profile_panic_line(policy::LoadPolicy) -> Union{String, Nothing}The line the generated [profile.release] section needs to honour the policy's panic strategy, or nothing when the Cargo default already matches. The generated inline-block and @rust_crate wrapper manifests write this line.
:unwind and :abort are both pinned, so both produce a line. Writing panic = "unwind" explicitly even though it is Cargo's release default is the point: without it, CARGO_PROFILE_RELEASE_PANIC=abort in the caller's environment silently produces a library whose catch_unwind boundary can never fire, and the same source aborts the Julia session instead of raising RustPanicError (#244). A manifest key beats the environment variable.
Returns nothing for :cargo_default — "whatever Cargo decides" is by definition not a line to write, and no RustCall-owned door carries that value any more.
Returns missing for :crate_profile: RustCall generates no Cargo.toml for those doors — the manifest is the user's — so there is no line for it to write. A crate that pins panic = "abort" itself aborts on a panic, which is the user's decision and is documented as such.
RustCall.close_artifact_handle! — Method
close_artifact_handle!(handle) -> BoolClose an image RustCall opened, once. The single close point of the package.
Returns whether this call was the one that closed it: false for a handle RustCall does not own (OWNED_HANDLES) and for one that has already been closed.
RustCall.close_retired_handles! — Function
close_retired_handles!(handles = retired_handles()) -> IntRelease retired images and return how many records were released.
The caller guarantees that no call into them is in flight. Each image's liveness flag is flipped to false first, so an object that outlives it becomes inert instead of calling into what is about to be unmapped, and then the image is closed — once, through close_artifact_handle!.
An image RustCall did not open is released from the bookkeeping but not closed: closing it belongs to whoever opened it (OWNED_HANDLES).
RustCall.close_retired_images! — Method
close_retired_images!(images) -> IntClose retired images by identity: handle => alive pairs, each closed only while the retired record under handle still carries that liveness flag. A handle is a pointer value the loader can hand out again once the image is unmapped, so a caller that decided which image may go — and asserted quiescence for that one — must not close whatever retirement the value names by the time it acts; the flag is one per mapped image and names it exactly (#397 review). Returns how many were closed.
RustCall.crate_direct_policy — Method
crate_direct_policy() -> LoadPolicy@rust_crate for a crate that already declares crate-type = ["cdylib"], so RustCall builds it in place: build_crate_directly points a CargoProject at info.path and runs Cargo there. The Cargo root is then the user's manifest, so their [profile.release] panic = "abort", a workspace profile, .cargo/config.toml or CARGO_PROFILE_RELEASE_PANIC all decide — hence :crate_profile, which effective_panic_strategy deliberately leaves unresolved. The generated #[julia] boundary catches an unwinding panic; a crate that pins panic = "abort" itself aborts on one, which is the user's decision (docs/src/panics.md).
Loading and ownership are shared with crate_wrapper_policy. The generated module still keeps its own generation record — that is how its wrappers reach the handle without a registry lookup per call — but the handle is published through load_artifact! since #277 Phase B5, so it appears in RUST_LIBRARIES under crate_library_name(info) and unload_library can see it. The module also captures the artifact's liveness flag, which is what makes its struct finalizers safe against an unload (#249).
RustCall.crate_target_hit — Method
crate_target_hit(cache, T) -> Union{T, Nothing}cache's snapshot if it is still current, nothing otherwise. The whole fast path of a generated @rust_crate call: one atomic load, an identity comparison and an integer comparison — no lock, and no symbol lookup.
T is the tuple type the arm that owns this cache stores, asserted on the way out so the wrapper's ccall stays statically typed.
RustCall.crate_wrapper_policy — Method
crate_wrapper_policy() -> LoadPolicy@rust_crate for a crate without cdylib, where RustCall generates a wrapper crate around it and builds that. The Cargo root is then RustCall's own generated manifest, whose [profile.release] pins panic = "unwind" (cargo_profile_panic_line, in src/crate_bindings/crate_bindings.jl and for the PyO3 wrapper in src/pyo3/pyo3.jl), and Cargo's environment pins it too — so this door is :unwind, like inline_cargo_policy.
The two @rust_crate build paths therefore differ only in who decides the panic strategy, chosen by crate_has_cdylib (#244). Everything else — RTLD_LOCAL | RTLD_NOW, registration under crate_library_name, freeing finalizers — matches crate_direct_policy.
RustCall.dlopen_flags — Method
dlopen_flags(policy::LoadPolicy) -> UInt32The flag set to hand to Libdl.dlopen: policy.dlopen_flags, which is RTLD_LOCAL | RTLD_NOW for every policy since #277 Phase B2 (SYMBOL_VISIBILITY_RULE). Nothing overrides it: the RUSTCALL_DLOPEN_GLOBAL escape hatch of #250 lasted one minor release and was removed in v0.5 (#417). On Windows LoadLibrary has no LOCAL/GLOBAL distinction, so the flag changes nothing there.
RustCall.effective_panic_strategy — Method
effective_panic_strategy(policy::LoadPolicy; env = ENV) -> Symbol
effective_panic_strategy(policy::LoadPolicy, snapshot_env) -> SymbolResolve policy.panic_strategy against the environment a build would inherit.
:abortand:unwindare pinned by RustCall and returned unchanged.:cargo_defaultis resolved by readingcargo_panic_env_var(policy)out of the environment:"abort"gives:abort,"unwind"gives:unwind, and anything else — unset, empty, unrecognised — gives:unwind, Cargo's default for thereleaseprofile. No named policy carries it any more.:crate_profileis returned unchanged: the environment is only one of the inputs there, and the user's manifest — which RustCall does not read for this — can pinpanic.
Which environment
The env = ENV default answers for an artifact built in this process, and only for that. A cached or reloaded artifact was built under the environment that was live at build time, which may differ from the current one, so resolving it against ENV can report the opposite strategy from what the .so on disk actually does. For those, the caller MUST pass the environment captured at build time — PR #272 records it on RustBlockSnapshot.cargo_env as serialized KEY=VALUE text, one entry per line — using the second method:
effective_panic_strategy(policy, snapshot.cargo_env)which accepts that text (parsed by parse_cargo_env_snapshot) or any AbstractDict. Never resolve a cached artifact against the live ENV.
The related cache-identity problem — two artifacts built under different CARGO_PROFILE_* values sharing a key — is closed by the artifact identity (src/artifacts/artifact_id.jl, #272, #278); this function models only the resolution, not the key.
RustCall.effective_rustflags — Method
effective_rustflags(env) -> Vector{String}The flag strings Cargo would actually hand rustc, given env.
Cargo takes rustflags from one source, not their union, in this order: CARGO_ENCODED_RUSTFLAGS, RUSTFLAGS, the per-target CARGO_TARGET_<TRIPLE>_RUSTFLAGS (target.<triple>.rustflags), and CARGO_BUILD_RUSTFLAGS (build.rustflags). Set is what counts, not non-empty: an empty RUSTFLAGS deliberately suppresses what a Cargo configuration would otherwise contribute, which is why ARTIFACT_ENV_ABSENT keeps "absent" and "set to empty" apart at all (src/artifacts/artifact_id.jl).
Every per-target variable at that level is returned rather than the one for the triple being built, which is not known here: erring towards finding a flag errs towards not installing a hook (#388 review).
RustCall.finalizer_frees — Method
finalizer_frees(policy::LoadPolicy) -> BoolWhether objects produced by this artifact free their allocation on finalization (#249).
RustCall.generation_path — Method
generation_path(lib_path, generation) -> Stringlibfoo.dylib → libfoo.3.dylib, next to the original.
Living beside the original rather than in a temporary directory matters on Windows: a DLL resolves its dependencies relative to its own location.
generation is an integer or a ready-made tag such as "rustcall.<host>.<pid>.<n>" (process_generation_path).
RustCall.generics_policy — Method
generics_policy() -> LoadPolicyMonomorphized generic instantiation, registered under rust_generic_<artifact_short_id> and never touching CURRENT_LIB.
The key used to be basename(lib_path). _unique_source_name (src/build/compiler.jl) returns the fixed base name rust_code whenever debug mode is off, so every instantiation compiled into its own temp directory yielded the same librust_code basename and they all collided on one RUST_LIBRARIES entry. Since #278 Phase B the key is the artifact identity of the instantiation (_monomorphization_id), so distinct instantiations are distinct entries.
Registration mode stays :insert_only: the entry is written only if !haskey(RUST_LIBRARIES, lib_name). With a content key a second write would be the same library anyway, and replacing the entry would swap the live handle and throw away the accumulated function-pointer cache.
RustCall.helper_library_policy — Method
helper_library_policy() -> LoadPolicyThe ownership helper library deps/rustcall_helpers — deps/rust_helpers through v0.3.x (#387) — loaded by load_rust_helpers_lib and try_load_rust_helpers (src/ffi/memory.jl) into RUST_HELPERS_LIB, and registered under the name rustcall_helpers.
It looked like the one library other artifacts could legitimately need to resolve symbols against, and is not: every user goes through RUST_HELPERS_LIB[] plus dlsym (src/ffi/memory.jl), and no artifact links against it, so nothing would resolve anything against it even if it were RTLD_GLOBAL. SYMBOL_VISIBILITY_RULE's "provides symbols to other artifacts" category is therefore empty, and this policy stays RTLD_LOCAL (#277 Phase B2).
Panic strategy is :unwind, and pinned twice over: deps/rustcall_helpers/Cargo.toml declares [profile.release] panic = "unwind", and build_native_product (deps/build.jl) passes CARGO_PROFILE_RELEASE_PANIC=unwind to Cargo, so an inherited CARGO_PROFILE_RELEASE_PANIC=abort cannot decide it either (#244). No catch_unwind boundary contains this library, so an aborting build would take the Julia process with it; effective_panic_strategy resolves the value.
RustCall.hot_reload_policy — Method
hot_reload_policy() -> LoadPolicyHot reload of a @rust_crate crate (_reload_library_once in src/loading/hot_reload.jl). Rebuild first, swap last (#255): the environment check, the rescan, the build and the dlopen of a fresh generation copy all complete outside REGISTRY_LOCK and before the previous image is touched, so any failure leaves the previous entry in place (#473). The swap is one load_artifact! with registration_mode = :replace, which retires the previous image rather than closing it: a call in flight finishes in it and its objects keep their own destructor (#277).
Like crate_direct_policy, the panic strategy is :crate_profile: rebuild_crate builds the user's crate as its own Cargo root, exactly as build_crate_directly does, so their profile decides.
RustCall.inline_cargo_policy — Method
inline_cargo_policy() -> LoadPolicyInline rust"""...""" block carrying // cargo-deps:, built through a generated Cargo project.
Covers both cache states (a Cargo cache hit and a fresh build), both loaded RTLD_LOCAL | RTLD_NOW like inline_rustc_policy.
The strategy is pinned to :unwind: the generated Cargo.toml writes panic = "unwind" into [profile.release] (cargo_profile_panic_line, src/build/cargoproject.jl) and build_cargo_project passes CARGO_PROFILE_<PROFILE>_PANIC=unwind to Cargo (src/build/cargobuild.jl), so an inherited CARGO_PROFILE_RELEASE_PANIC=abort cannot produce an artifact whose catch_unwind boundary never fires (#244).
RustCall.inline_rustc_policy — Method
inline_rustc_policy() -> LoadPolicyInline rust"""...""" block with no // cargo-deps:, compiled straight by rustc, on both cache states (a disk-cache hit and a fresh compile). Compiled with -C panic=unwind (rustc_panic_flags, src/build/compiler.jl) behind the generated catch_unwind boundary, and loaded RTLD_LOCAL | RTLD_NOW.
Until #277 Phase B2 this door was RTLD_LOCAL while inline_cargo_policy — the same rust""" construct declaring // cargo-deps: — was RTLD_GLOBAL (#250); until #244 this one aborted on a panic and that one did not. The two doors now agree on every decision.
RustCall.install_quiet_panic_hook! — Method
install_quiet_panic_hook!(handle; snapshot_env = nothing) -> BoolInstall the artifact's quiet panic hook, and say whether it was installed.
Called by load_artifact! right after dlopen and after the loader reference is recorded, before any wrapper of the image can run. That timing is the design: the installer is called by the loader rather than lazily by the first wrapper call, so two first calls to two wrappers cannot race to install it — the defect that sank the per-wrapper attempt in #302.
The image decides, not the policy. __rustcall_install_panic_hook is exported exactly when the image carries the quiet-panic state: a file RustCall writes whole (inline blocks, generics) defines it at its root, and a #[julia] crate — hand-written, or the generated @rust_crate wrapper crate — gets it from the rustcall_julia_macros rlib it links, as long as some generated wrapper references that crate. Asking the image therefore cannot be wrong, and no door can forget to opt in. A LoadPolicy flag was tried first and was exactly that mistake: every @rust_crate module loads with crate_direct_policy(), the generated PyO3 wrapper crate included, so the flag silently excluded wrapper flavours that do carry a hook (#388 review). The doors are listed in docs/src/panics.md for readers; nothing branches on the list.
Returns false — silently, it is not an error — when hooks are disabled for this process, or when the image exports no installer (a crate with no #[julia] wrapper, the hand-written helper library, or an artifact built by RustCall ≤ v0.3.4).
RustCall.library_names_for_handle — Method
library_names_for_handle(handle) -> Vector{String}Every RUST_LIBRARIES name that resolves to handle.
One handle legitimately sits under two names (alias_artifact!), and both are the same loaded image: unloading either one must therefore remove both and close once. Removing one and leaving the other behind leaves a name pointing at code that is about to be unmapped, and closing per name closes an image the process opened once.
The caller must hold REGISTRY_LOCK.
RustCall.load_artifact! — Method
load_artifact!(policy::LoadPolicy, path;
lib_name, symbols = (), return_types = (), eager = (),
snapshot_env = nothing,
set_current = policy.sets_current_lib) -> LoadedArtifactOpen path under policy and publish it, as one transaction.
Libdl.dlopen runs outside REGISTRY_LOCK — it executes arbitrary initialisation code and is slow, and holding the global registry lock across it would serialise every unrelated @rust call. Everything else happens in a single locked block, so no task can observe a half-registered library: the handle, its fresh function-pointer cache (pre-filled from eager), the name-to-symbol mappings (symbols, name => exported symbol, #279), the return-type hints (return_types, name => Type) and CURRENT_LIB all become visible together. That is what closes the window in which a concurrent @rust f(...) could find the library but not yet know that f is exported as rustcall_f.
policy.registration_mode decides what happens when the key is taken:
:replaceevicts the previous entry. The evicted image is retired, not closed (RETIRED_HANDLES): a call that started before the swap may still be running inside it. It keeps its own liveness flag,true, so objects it allocated still free through it — their destructor lives in that image and that image is still mapped. The new generation gets a flag of its own; flags are never reused across images.:insert_onlykeeps the existing entry, together with its accumulated function-pointer cache, anddlcloses the duplicate just opened. Closing that one is safe because nobody ever saw it: it was opened moments ago by this call and lost the race, so no pointer was resolved from it. Two tasks racing on the same path therefore agree on one handle (src/macros/generics.jl).
Policies that register nowhere (:module_local, :helper_slot, :none) still get their dlopen from here — that is what makes the flag set one decision — and come back as a LoadedArtifact with a liveness flag of their own.
snapshot_env is the environment the artifact was built under; it is used only to resolve assumed_unwind. Pass the captured snapshot for a cached or reloaded artifact, never the live ENV (see effective_panic_strategy).
preload names shared libraries the image imports by name that the platform's loader would not find on its own, each as a full path; they are opened first (preload_dependency!), under the same flag set, and stay open for the life of the process. This is how a PyO3 wrapper finds its python3xy.dll on Windows, where there is no rpath and the interpreter's directory need not be on PATH (PyO3LinkPlan.runtime_libraries, #307 review).
Throws if the load fails, leaving the registry untouched.
RustCall.loadable_library_copy — Method
loadable_library_copy(built_path) -> StringA private copy of a freshly built library, for RustCall to open.
RustCall never maps the file Cargo writes. Cargo rewrites its output in place on the next build, and on Windows it cannot: overwriting a mapped DLL fails with Access is denied (os error 5), so the build fails — the whole crate becomes unbuildable for the rest of the session once anything has loaded it. Everywhere else the failure is quieter and worse: dlopen of a path that is already mapped hands back the old image, so a rebuild silently has no effect while objects allocated by the old library start being freed by code from the new one.
Copying to <lib>.rustcall.<host>.<pid>.<instance>.<generation>.<ext> and opening that leaves Cargo's output untouched, and makes every load a genuinely distinct file — across processes, pid namespaces and hosts too, since the counter alone is per process (#255, #277, #309, #321). Before copying, the copies whose owners no longer exist are swept (_sweep_stale_generation_copies), so a library that is loaded by one process after another keeps only the live processes' copies beside it; and before copying, this process takes the copy's lease — <copy>.lease, held open and locked until the process ends — so that no other process's sweep, in this pid namespace or another, can take the copy for abandoned in the window between the copy and its dlopen, or ever after (#321). The lease is taken first: a sweep that sees the copy sees a held lease.
Returns the original path when the copy cannot be made, so a platform or a filesystem that will not take one degrades to the previous behaviour rather than failing the load.
RustCall.must_assume_unwind — Method
must_assume_unwind(policy::LoadPolicy; env = ENV) -> BoolThe conservative resolution of requires_catch_unwind_boundary: true unless the artifact is known to abort or the boundary already catches. An unknown (:crate_profile) strategy resolves to true, because a boundary that catches a panic that cannot happen is merely redundant, while a missing boundary on an unwinding artifact is undefined behaviour (#244).
RustCall.next_reload_generation — Method
next_reload_generation() -> IntThe next generation. Never repeats within a process.
RustCall.prefer_dynamic_build — Method
prefer_dynamic_build(; env = ENV) -> Bool
prefer_dynamic_build(snapshot_env) -> BoolWhether the build env asks rustc for a shared std (-C prefer-dynamic).
It decides whether the quiet hook may be installed at all. With the default static std every image owns its own hook registry, so one image's hook is another image's business only if the registry is shared — and with prefer-dynamic it is: the hook installed from a cdylib is reachable, and droppable, from any other image in the process (#302 review, #304).
snapshot_env is the environment the artifact was built under, recorded at macro-expansion time and replayed by the Cargo build (#272); it is what load_artifact! passes, exactly as effective_panic_strategy takes it. Falling back to the live ENV is right for the direct-rustc doors, which build in this process.
Which variable decides is effective_rustflags, following Cargo's own precedence. A prefer-dynamic that reaches rustc from a place no environment variable mirrors — build.rustflags written in a Cargo configuration file, which RustCall reads nowhere — is invisible here; what that costs is described in docs/src/panics.md, and it is not memory safety: close_artifact_handle! removes the hook before the image is unmapped either way.
RustCall.prefer_dynamic_flag — Method
prefer_dynamic_flag(flags) -> BoolWhether one rustc flag string asks for a shared std.
Tokenised rather than searched for a substring, so -C prefer-dynamic, -Cprefer-dynamic, --codegen prefer-dynamic and the -separated CARGO_ENCODED_RUSTFLAGS form all count, and -C prefer-dynamic=no — which asks for the opposite — does not.
RustCall.preload_dependency! — Method
preload_dependency!(policy::LoadPolicy, path) -> Ptr{Cvoid}Open path — a library some artifact of policy imports by name — under the policy's flag set, once per path, and keep it open for the life of the process (PRELOADED_LIBRARIES). The dlopen runs outside REGISTRY_LOCK, like every other; two tasks racing on one path both open it (the loader refcounts, so the duplicate open is harmless) and the table keeps the first handle.
Throws a RustError naming the path when it cannot be opened, so a wrapper that would fail with a bare "module not found" fails with the dependency that is missing instead.
RustCall.preloaded_libraries — Method
preloaded_libraries() -> Vector{String}The paths preload_dependency! has opened in this process, sorted.
RustCall.process_generation_path — Method
process_generation_path(lib_path, generation) -> Stringlibfoo.dylib → libfoo.rustcall.<host>.<pid>.<instance>.<generation>.dylib: the copy name loadable_library_copy uses; <host> is _generation_copy_host(), <instance> is _generation_copy_instance().
RELOAD_GENERATION is per process, so two Julia processes that load the same built library — two workers of a test run, two sessions using one crate — would both pick libfoo.1.dylib. On Windows the second cannot overwrite the copy the first has mapped, and a copy that fails would fall back to mapping Cargo's output in place, which is the very failure the copy exists to prevent (#309). With the process id in the name, the copies of two live processes on one host never share a path; with the instance token, neither do two processes that share the volume and the pid from different pid namespaces (#321). The rustcall marker is what lets the stale-copy sweep recognise its own files (GENERATION_COPY_MARKER).
RustCall.publish_crate_target! — Method
publish_crate_target!(cache, epoch, target) -> targetRecord target as cache's answer for epoch.
epoch must have been sampled before the snapshot was taken. A write landing in between then leaves the entry stamped with the older epoch and it is resolved again; sampling afterwards could stamp a pre-write snapshot as current and keep it for the life of the process.
RustCall.quiet_panic_hooks_enabled — Method
quiet_panic_hooks_enabled() -> BoolWhether RustCall may install quiet panic hooks in this process.
RUSTCALL_PANIC_HOOK=default turns them off — the escape hatch for the one thing the hook costs: a panic inside a generated artifact but outside any wrapper boundary, on a thread the artifact's own code spawned, is printed by the hook RustCall replaced, and if that hook is gone so is the message. It is also off under prefer_dynamic_build.
RustCall.register_artifact_metadata! — Method
register_artifact_metadata!(policy, lib_name; symbols, return_types,
require_loaded = false,
set_current = policy.sets_current_lib) -> BoolRe-publish the volatile metadata of a library that is already loaded — the name-to-symbol mappings, the return-type hints and the generic functions its block defines (generics, #520) — without opening anything.
require_loaded makes the existence check part of the same critical section as the writes, so an unload_artifact! racing between a caller's haskey and this call cannot leave metadata and CURRENT_LIB[] pointing at a library that is gone. Returns false in that case and writes nothing; the caller then falls through to compiling and loading the library again.
RustCall.register_handle_mirror! — Method
register_handle_mirror!(lib_name, gen_ref)Keep gen_ref — a generated @rust_crate module's _LIB_GEN — in step with the library registered as lib_name, and set it to what is registered now.
Called by the module's __init__, before it loads the library, so that the load_artifact! transaction is what publishes the first generation: an assignment after the load would overwrite whatever a concurrent reload had already published.
Idempotent: a module re-initialised in a new session registers the same Ref again and it is not duplicated.
RustCall.registered_alive_for_handle — Method
registered_alive_for_handle(handle) -> Union{Base.RefValue{Bool}, Nothing}The liveness flag already registered for the image handle names, under any of its names, or nothing when it has none. Caller holds REGISTRY_LOCK.
The invariant this serves is one image, one flag (#291 item 4). A path can be loaded under a second name while the first is still live — dlopen refcounts and answers with the same handle — and minting a fresh flag for that second registration would leave two flags describing one lifetime. unload_artifact! retires the image with one of them; the other is dropped from ARTIFACT_ALIVE and never flipped, so every object that captured it believes itself live after close = true has unmapped the code its destructor calls into. That is a use-after-free reachable without any hot reload: two load_artifact! calls on one path under two names.
RustCall.registers_in_rust_libraries — Method
registers_in_rust_libraries(policy::LoadPolicy) -> BoolWhether load_artifact! / adopt_artifact! register the image in RUST_LIBRARIES.
RustCall.requires_catch_unwind_boundary — Method
requires_catch_unwind_boundary(policy::LoadPolicy; env = ENV) -> Union{Bool, Missing}Whether a generated extern "C" wrapper for this artifact must wrap the user body in std::panic::catch_unwind to keep a panic from crossing the FFI boundary. true exactly when the artifact unwinds and the boundary does not already catch — which no named policy does any more, since every one has boundary_catches_panics (#244).
Routes through effective_panic_strategy, so a :cargo_default policy answers false under CARGO_PROFILE_RELEASE_PANIC=abort. Returns missing for :crate_profile, whose answer depends on the user's manifest. Callers that need a decision rather than a fact should use must_assume_unwind, which resolves the unknown conservatively.
RustCall.retired_handles — Method
retired_handles() -> Vector{Ptr{Cvoid}}
retired_handles(lib_name) -> Vector{Ptr{Cvoid}}The images that have left the registry and are still mapped: all of them, or those that were known by lib_name.
RustCall.rustc_panic_flags — Method
rustc_panic_flags(policy::LoadPolicy) -> Vector{String}The rustc arguments implied by the policy's panic strategy: ["-C", "panic=abort"] for :abort, ["-C", "panic=unwind"] for :unwind, and missing for :cargo_default and :crate_profile, where Cargo drives the build and RustCall does not invoke rustc itself.
:unwind is passed explicitly rather than left to rustc's default so that the strategy is stated at every compile site, and so that the flag list of a policy is evidence of what was built (the panic parity test compares the two inline doors through this function).
RustCall.uninstall_quiet_panic_hook! — Method
uninstall_quiet_panic_hook!(handle) -> BoolRemove the artifact's quiet panic hook before its code is unmapped, and say whether it was removed.
Called by close_artifact_handle!, the one place an image is closed, so the closure leaves std's registry before the memory it lives in does. Asking the image rather than the policy is deliberate: closing goes through one handle-only path, and the exported symbol is a more reliable question than a policy the caller would have to carry along. The generated uninstaller is a no-op when that image never installed anything.
RustCall.unload_artifact! — Method
unload_artifact!(artifact::LoadedArtifact; close = false) -> Bool
unload_artifact!(policy::LoadPolicy, lib_name; close = false, expect_generation = nothing) -> BoolRetire a library: remove everything the registries record about it, in one locked block — the RUST_LIBRARIES entry and its function-pointer cache, the name-to-symbol mappings and return-type hints, the library-scoped FUNCTION_REGISTRY_BY_LIB rows, the MONOMORPHIZED_FUNCTIONS entries that point into it (stale pointers into an image nothing reaches are a use-after-free, #73), its panic channels, the module mirrors that were reading its handle, and CURRENT_LIB if it pointed here. Every name of the handle goes, not just the one asked for: an alias is a second name for the same image.
The image itself is not closed. Unloading is the same act as a hot reload replacing a library, and it is unsafe for the same reason: a call that started a moment ago may still be inside, and there is no per-call reader pin that would make closing safe. The image is retired instead (RETIRED_HANDLES) and keeps its liveness flag true, so an object it allocated still runs its destructor through it.
close = true reclaims it: the liveness flags of the images retired under this library are flipped and the images are closed. That is the caller stating that no call into them is in flight, and it is the only thing that makes objects from those images inert.
Returns whether a RUST_LIBRARIES entry was actually removed.
RustCall.uses_global_symbols — Method
uses_global_symbols(policy::LoadPolicy) -> BoolWhether this policy publishes the artifact's symbols process-globally: false for every policy since #277 Phase B2 (SYMBOL_VISIBILITY_RULE).