diff --git a/.gitignore b/.gitignore index 064a14647e..3938700e49 100644 --- a/.gitignore +++ b/.gitignore @@ -65,6 +65,7 @@ cpan_smoke_* *.dat logs/ .perlonjava_env_ready +log.txt *.diff *.patch # But allow patch files in import-perl5/patches/ diff --git a/dev/design/README.md b/dev/design/README.md index 82d225dbb1..ac14ecf8e3 100644 --- a/dev/design/README.md +++ b/dev/design/README.md @@ -109,7 +109,7 @@ Proposals and plans for work that is being considered or is in progress. | [perf-dbic-safe-port.md](perf-dbic-safe-port.md) | DBIC-Safe Perf Port Plan | — | | [performance-delivery-selection.md](performance-delivery-selection.md) | Curated performance delivery selection | — | | [performance-over-perl.md](performance-over-perl.md) | Performance over Perl benchmark authority | — | -| [perl-ownership-rewrite.md](perl-ownership-rewrite.md) | Perl-compatible ownership rewrite | Phase 1 closure-pad path is implemented and validated on… | +| [perl-ownership-rewrite.md](perl-ownership-rewrite.md) | Perl-compatible ownership rewrite | Phase 1 is complete; Phase 2 is in progress. HTML-Tree 5.07… | | [perl-regex-library-rfc.md](perl-regex-library-rfc.md) | RFC: Embeddable Perl-Compatible Regex Library for the JVM | — | | [perl-summit.md](perl-summit.md) | — | — | | [perl_debugger.md](perl_debugger.md) | Perl Debugger Implementation for PerlOnJava | — | diff --git a/dev/design/perl-ownership-rewrite.md b/dev/design/perl-ownership-rewrite.md index a3062210dd..17d39c7891 100644 --- a/dev/design/perl-ownership-rewrite.md +++ b/dev/design/perl-ownership-rewrite.md @@ -1,6 +1,555 @@ # Perl-compatible ownership rewrite -**Status:** Phase 1 closure-pad path is implemented and validated on both backends. Full UAT comparison, local gates, selected CPAN workloads, and PR CI pass. PR #1653 remains a draft pending review. +**Status:** Phase 1 is complete; Phase 2 is in progress. HTML-Tree 5.07 `t/refloop.t` passes 8/8 on both backends with corrective sweeps disabled. The full HTML-Tree suite passes 23 files and 989 checks on both backends. `@DB::args` now stores the selected source scalar cells directly, avoiding detached untracked-reference owners. Visible named package IO globs carry a `PACKAGE_GLOB_SLOT` identity through replacement and removal; detached typeglob snapshots and whole-namespace moves now carry explicit component owners before stash slots are removed, including through scalarization of a namespace move. `Symbol::gensym` globs are excluded from package stash ownership and retire their hidden lookup entry after their last IO owner closes. Unblessed array and hash cycles now remain live through their actual element-owner slots; deferred cleanup no longer restores a positive count from a cycle walk. CODE self-capture cleanup restores from verified counted slots rather than a graph walk. Aggregate closure capture release no longer decrements another owner's counted edge. Shared proxy release, ithread weak-slot resurrection, PadWalker rebinding, active CODE ownership, compiled/pinned/localized CODE slot reset, visible stash CODE ownership, and async cleanup regressions pass on both backends. Aggregate clear and replacement now queue IO holder release with scalar referent cleanup. Weak aliases of blessed anonymous globs are excluded from scalar owner backfill, release their IO holder on weaken, and restore it on unweaken. Rescued-object processing now consults live Perl owner identities, and a promoted weak slot gets a second `DESTROY` when its final owner leaves. Production sweep callers have been removed; count alignment still uses verified current owner slots while remaining producer gaps are audited. + +**Current checkpoint (2026-11-06):** #1649 remains in Phase 2 on branch +`wip/issue1649-owner-transition-20261106-035834`, at source commit +`095c1a3101`, based on documentation commit `f8c0a3e4dd`, which includes merge +commit `4865f2dddd` and validated owner-transition commit `c633398d83` on +`origin/master` at `9477c8c68a`. The latest build ran before source commit on +the identical tree; Gradle injected parent identifier `f8c0a3e4dd` into its +launcher. Count arithmetic and owner-token transitions remain centralized in +`RuntimeBase.acquireTrackedOwnerCount` / `releaseTrackedOwnerCount`, +`PerlOwnerSlot`, and scalar replacement/release paths. Fix missing or extra +edges at the producer or storage boundary that creates, transfers, caches, or +retires the Perl value; do not repair those mismatches by reconstructing counts +from reachability. + +The source audit finds the only numeric `RuntimeBase.refCount` increment and +decrement in `RuntimeBase.acquireTrackedOwnerCount` and +`RuntimeBase.releaseTrackedOwnerCount`; the other arithmetic hits belong to +`CustomFileChannel`'s independent IO-state counter. Production owner drops use +exact release tokens. `MortalList.deferDecrement` has no production caller, and +the weak-sweep APIs have no production caller; remaining graph recovery is +confined to the legacy unpaired hook. The write-site inventory is at +`/private/tmp/issue1649-refcount-arithmetic-sites.txt`. The current audit also +removed duplicate owner-trace removals before queued releases; the queue +coordinator already retires those trace records. Zero-count initialization and +lifecycle sentinels remain state transitions rather than owner increments or +decrements. The combined source tree passes +`JPERL_DISABLE_CORRECTIVE_SWEEPS=1 nice -n 19 timeout 1800 make` in 7m58 +(`/tmp/issue1649-batched-owner-audit-make.log`). JVM and interpreter trace +smokes both exit 0 with 367 owner trace records and no `UNPAIRED RELEASE` +(`/tmp/issue1649-owner-trace-{jvm,interpreter}.log`). + +The cloned/shared-storage audit found no count arithmetic outside the owner +transition APIs. A cloned scalar reacquires its child-runtime edge through +`incrementRefCountForContainerStore`; cloned arrays and hashes use the same +container-slot transition as ordinary stores. Plain thread-shared storage keeps +its shared identity, while tied/runtime views are cloned and their child slots +are rebuilt. Snapshot roots use `TEMPORARY_ROOT` identities and do not fabricate +Perl reference counts. Pre-counted argument, return, capture, native, and +scalar-reference-content edges likewise acquire through `PerlOwnerSlot` and the +central counter method. Aggregate recursive cleanup walks the discarded +container's actual child slots to release them; it does not use a root walk to +reconstruct their counts. + +The glob producer audit found a split-owner bug for a weak CODE source: Perl +copies it into the stash as a strong CODE slot, while `GlobalCodeRefMap` reused +the weak scalar and therefore skipped slot-count acquisition. The map now +copies weak inputs before installing the slot, and CODE-definition callers +retain the canonical installed slot. `GlobalCodeRefMapWeakSourceOwnerTest` +failed on the unfixed tree at the distinct-slot assertion, then passes with the +fix. `localized_weak_code_slot_ownership.t` passes 5/5 on system Perl, JVM, and +interpreter. The unfixed gate log is +`/tmp/issue1649-weak-code-owner-unfixed-make.log`; the final no-sweeps +`make` passes in 7m50 (`/tmp/issue1649-weak-code-owner-final-make.log`). The +final-candidate matrix passes nine ownership/lifecycle fixtures on both +backends and HTML-Tree 5.07 `t/refloop.t` 8/8 on system Perl and both backends +(`/tmp/issue1649-final-candidate-matrix-summary.txt`). + +The current candidate snapshots glob arguments in `stat`, `lstat`, and file-test +cache state, so Perl's cached subject does not extend a lexical handle's +lifetime. `filetest_glob_cache_lifetime.t` covers both file tests and `stat`; +`package_root_nested_array_owner_lifetime.t` covers package-rooted nested +aggregate ownership. Both new tests pass system Perl. A bounded standalone +scalar-cell proof is now part of `verifiedCurrentCountedOwnerSlotCount`, and is +applied only when no ordinary verified counted owner was found. This removes a +separate deferred-release recovery branch while preserving its exact owner-slot +contract; it does not reconstruct ownership from reachability. The full +`IOOperator.sysopen` anonymous-handle path now installs the same scalar IO-owner +lease as `open`. `RuntimeScalar` owns the paired counted-edge and IO-lease +release for list-assignment transport copies; `RuntimeList.setFromList` delegates +that transition instead of coordinating both owner systems itself. The new +`SysopenAnonymousGlobOwnerSlotTest` verifies one holder is installed and retired +for a successful anonymous sysopen. The no-sweeps +`nice -n 19 timeout 1800 make` gate passes in 7m50 +(`/tmp/issue1649-owner-producer-batch-no-sweeps-make.log`). With corrective +sweeps disabled, seven Perl lifetime fixtures pass on both backends: borrowed +sysopen aliases (9), File::Temp wrappers (5), PathTiny prerequisites (23), +blessed scalar contents (4), glob cache (4), nested package-root arrays (1), +and the temporary IO method invocant (1). System Perl passes the six available +fixtures, 46 checks; Template Toolkit's invocant fixture skips because that +module is not installed (`/tmp/issue1649-producer-batch-system-perl.log`). +Unchanged HTML::Tree 5.07 `t/refloop.t` also passes 8/8 on system Perl, JVM, and +interpreter; the system test source hash matches the other local 5.07 copies. +Issue #1618 remains open pending integration/merged delivery. Issue #1642 is +closed by merged PR #1746, which is an ancestor of this branch; its remaining +broader CPAN qualification is tracked by #1646. Continue the remaining +producer/release audit and remove ordinary corrective reachability recovery +only after those paths are covered. + +The exact merged checkout passed +`nice -n 19 timeout 1800 env JPERL_DISABLE_CORRECTIVE_SWEEPS=1 make` in 8m02 +(`/private/tmp/issue1649-final-merged-no-sweeps-make.log`); the generated +launcher reports `c03e64d996`. `make check-links` passes with 835 links and zero +errors. The #1794/#1860 and lifecycle matrix passes eight fixtures on both +backends (`/private/tmp/issue1649-final-lifecycle-matrix-summary.txt`). +HTML-Tree 5.07 +`t/refloop.t` passes 8/8 on system Perl, JVM, and interpreter. The candidate is +integrated and validated; continue the producer audit before declaring the +full sweep-removal objective complete. + +`RuntimeList.setFromList` now retires an assignment-materialization cell's +anonymous IO lease alongside its counted edge, preserving that lease when the +same handle is carried in the assignment result. This closes the holder leak +where a temporary scalar carrier was collected with an active +`IO_RESOURCE_HOLDER`. `%^H` restoration also stopped pre-queuing values before +removing them through `RuntimeHash`'s owner-aware map, eliminating a duplicate +edge release. Commit `3ebcdfe796` passes the immutable +`nice -n 19 timeout 1800 make` gate in 7m43 +(`/tmp/issue1649-io-owner-3ebcdfe-make.log`). With corrective sweeps disabled, +`file_temp_path_wrapper_lifetime.t` passes 5/5 and +`refcount/blessed_scalar_reference_contents_destroy.t` passes 4/4 on both +backends; `hint_hash_scope_destroy.t` passes 4/4 on both backends. The +system-Perl file-wrapper oracle passes 5/5. `make check-links` passes with +832 links and zero errors. Logs: +`/tmp/issue1649-filetemp-system-perl-owner-release.log`, +`/tmp/issue1649-materialized-io-filetemp-jvm.log`, +`/tmp/issue1649-materialized-io-filetemp-interpreter.log`, +`/tmp/issue1649-materialized-io-blessed-ref-jvm.log`, +`/tmp/issue1649-materialized-io-blessed-ref-interpreter.log`, +`/tmp/issue1649-io-owner-hinthash-jvm.log`, and +`/tmp/issue1649-io-owner-hinthash-interpreter.log`. + +`RuntimeGraphCloner.cloneScalar` now reacquires a child-runtime anonymous IO +holder when the source scalar owned one. `RuntimeGraphClonerIoOwnerTest` +verifies the clone and parent hold independent leases. Immutable commit +`c47cec61b5` passes `JPERL_DISABLE_CORRECTIVE_SWEEPS=1 nice -n 19 timeout 1800 +make` in 7m22 (`/tmp/issue1649-clone-io-owner-c47cec61b5-make.log`). +Thread-shared plain arrays and hashes keep one canonical backing-storage edge: +the clone creates a runtime-local wrapper around the same synchronized storage, +and shared graph validation excludes IO/glob resources. No second element +owner should be acquired for that wrapper. The remaining audit is focused on +ordinary pre-counted temporaries and the verified-slot/legacy recovery bridges. + +Thread graph cloning now recreates a child-runtime `IO_RESOURCE_HOLDER` for +each cloned strong scalar that owned an anonymous IO holder in the source. +The parent keeps its lease and the clone owns an independent identity on the +cloned glob. `RuntimeGraphClonerIoOwnerTest` verifies the child lease can be +released without changing the parent holder count. The no-sweeps Make gate +passes on immutable commit `c47cec61b5` in 7m22 +(`/tmp/issue1649-clone-io-owner-c47cec61b5-make.log`). The earlier working-tree +gate also passed in 7m56 (`/tmp/issue1649-clone-io-owner-no-sweeps-make.log`). + +The IO producer audit found that `open` and `sysopen` could install a live IO +slot into an existing anonymous glob without acquiring leases for scalar cells +that already referenced that glob. Assignment into an undefined handle already +acquired its lease through the scalar transition, which hid the existing-glob +case. The common `MyVarCleanupStack.retainLiveIoGlobOwners` transition now +consults current counted and untracked scalar owner slots, supplements them +with registered lexicals, and retains the explicit destination scalar. It is +used by `open`, `sysopen`, sockets, pipe ends, IPC::Open3, directory handles, +and fork-open completion. Named package globs keep their existing stash-owned +IO policy. `RuntimeScalarIoOwnerSlotTest` exercises sysopen on an IO-less glob +with two scalar owners and checks each gets an independent lease. Immutable +commit `6dd6b1a6b0` passed the full no-sweeps Make gate in 7m53 +(`/tmp/issue1649-existing-glob-6dd6b1a6b0-make.log`); the expanded producer +routing in `b1a29eb0b6` also passed in 7m41 +(`/tmp/issue1649-io-producers-b1a29eb0b6-make.log`). The sysopen regression +passed within that gate, and `./jperl -v` reported the validated source commit. +On the same built runtime with corrective sweeps disabled, the #1794, #1860, +END-die, async-cancellation, weak-resurrection, and cycle fixtures pass on both +backends (`/tmp/issue1649-final-lifecycle-matrix-summary.txt`). HTML-Tree 5.07 +passes all 23 files and 989 checks on both backends; 11 upstream TODO checks +remain marked TODO (`/tmp/issue1649-htmltree-b1a29-jvm.log` and +`/tmp/issue1649-htmltree-b1a29-interpreter.log`). The remaining ownership +producer/release audit and removal of ordinary corrective recovery are still +in progress. + +Aggregate producers now state their edge kind at acquisition: blessing's +retroactive array/hash owner pass, tracked anonymous array/hash construction, +and list-to-hash materialization pass `ARRAY_ELEMENT` or `HASH_ELEMENT` +directly. The full `nice -n 19 timeout 1800 make` gate passes on immutable +`28bedc5f43` in 10m11; `./jperl -v` reports that commit. With corrective +sweeps disabled, `active_lexical_scalar_referent_owner.t` passes 9/9 and +`path_tiny_runtime_prereqs.t` passes 23/23 on JVM and interpreter. System Perl +passes the scalar-cell regression 9/9, and a focused oracle confirms that a +reference to a scalar cell keeps its current value alive after lexical scope +exit (`/tmp/issue1649-perl-cell-semantics.log`). Logs: +`/tmp/issue1649-explicit-container-owner-kinds-28bedc5f43-make.log`, +`/tmp/issue1649-active-lexical-system-perl.log`, +`/tmp/issue1649-active-lexical-jvm-28bedc5f43.log`, +`/tmp/issue1649-active-lexical-interpreter-28bedc5f43.log`, +`/tmp/issue1649-path-tiny-jvm-28bedc5f43.log`, and +`/tmp/issue1649-path-tiny-interpreter-28bedc5f43.log`. + +The next producer batch now declares `CODE_SLOT`, `RETURN_VALUE`, and +`ARGUMENT_VALUE` during acquisition for CODE stash values, mortal returns, +closure arguments, and tail-call targets. Unweaken, autovivification, blessing, +and blessed-glob alias restoration pass their current storage kind to the same +typed acquisition API. `TailCallCodeRefOwnerSlotTest` verifies the tail-call +slot is released exactly. The full `nice -n 19 timeout 1800 make` gate passes +on `2ad3a0ed0f` in 10m35; the system-Perl/JVM/interpreter +`tailcall_code_owner_lifetime.t` oracle passes 3/3 on each. Logs: +`/tmp/issue1649-tailcall-explicit-owner-2ad3a0ed0f-make.log`, +`/tmp/issue1649-tailcall-code-owner-perl-2ad3a0ed0f.log`, +`/tmp/issue1649-tailcall-code-owner-jvm-2ad3a0ed0f.log`, and +`/tmp/issue1649-tailcall-code-owner-interpreter-2ad3a0ed0f.log`. + +The source audit still finds no production caller of legacy +`MortalList.deferDecrement()` or `ReachabilityWalker.sweepReleasedWeakReferents()`; +those entry points remain for synthetic Java tests. Graph recovery in +`processDeferredBase` is guarded by that legacy unpaired path. Removing verified +active-slot count alignment is not yet safe: an earlier full gate without it +failed Perl-level scope, argument, capture, weak-owner, and package-lifetime +cases. A zero-count deferral experiment also failed 12 existing Java lifecycle +tests that explicitly require live counted slots to restore the selective +count. Keep this non-graph owner-alignment contract while auditing the +producers that create undercounts; do not replace it with root recovery. + +The clean-source full gate passes on rebuilt candidate `b207326996` in 7m43 +(`/tmp/issue1649-restored-985ed-make.log`). With corrective sweeps disabled, +HTML-Tree 5.07 passes 23/23 files and 989/989 checks on both backends; its +`t/refloop.t` is 8/8. The focused no-sweeps matrix for #1794, #1860, +DESTROY/resurrection, cycles, async cancellation, and nested END exit/die passes +7/7 files and 35/35 checks on each backend. Logs: +`/tmp/issue1649-htmltree-jvm-b207.log`, +`/tmp/issue1649-htmltree-interpreter-b207.log`, +`/tmp/issue1649-lifecycle-acceptance-jvm-b207.log`, and +`/tmp/issue1649-lifecycle-acceptance-interpreter-b207.log`. + +The next work is to continue the producer audit, including cloned/shared +storage and remaining pre-counted temporary values, then determine which +verified-slot alignment and legacy recovery bridges can be removed without +breaking normal Perl lifetimes. Root-count reconstruction remains behind the +legacy unpaired hook, which has no production caller; do not treat that +compatibility path as evidence that ordinary owner identities are complete. +After the audit and compatible recovery removal, rerun the #1618/#1642 and +no-sweeps acceptance on one final immutable candidate. + +The first-bless and re-bless paths now acquire an existing scalar's counted +edge through `RuntimeScalar.acquireCountedOwnerForCurrentValue`, removing two +manual `refCount = 1` plus owner-recording sequences. Its validation follows +Perl's `isReference` predicate so the distinct `FORMAT` scalar type remains +blessable. System Perl passes the three ownership oracles (56 assertions) and +`format_ref_bless.t` (6); `nice -n 19 make` passes in 7m41. The focused bless, +DESTROY, and weaken tests pass 62/62 on JVM and interpreter. Logs: +`/tmp/issue1649-bless-perl-oracle.log`, +`/tmp/issue1649-format-ref-perl.log`, +`/tmp/issue1649-bless-owner-centralize-make-final.log`, +`/tmp/issue1649-bless-jvm-focused.log`, and +`/tmp/issue1649-bless-interpreter-focused.log`. + +Count arithmetic is centralized in `RuntimeBase.acquireTrackedOwnerCount` and +`releaseTrackedOwnerCount`; `PerlOwnerSlot` pairs those transitions with stable +owner identities. `MortalList` now coordinates host-side exact-token release +as well as runtime-bound release. `RuntimeScalar.setLargeRefCounted` no longer +has a tokenless decrement or count-reconstruction fallback for a counted +overwrite: a valid overwrite must carry its exact pending slot release. IO +resource leases remain separate from Perl strong edges. +Scalar owner handoffs now move the exact active `PerlOwnerSlot` and the +`refCountOwned` state together, validating that source and destination carry +the same referent. Postfix `++`/`--` uses a separate promotion transition for +Perl's returned old value, including borrowed-source adoption of an existing +count. The full `nice -n 19 timeout 1800 make` gate passes in 7m56, and +`postfix_reference_temporary_owner.t` passes 6/6 on system Perl, JVM, and +interpreter with corrective sweeps disabled. Logs: +`/tmp/issue1649-central-scalar-transfer-make.log` and +`/tmp/issue1649-central-transfer-postfix-{perl,jvm,interpreter}.log`. +Queued counted releases now take their exact slot and clear `refCountOwned` +inside the scalar transition. Array removal and localized scalar restore no +longer clear the flag before queueing. Missing identities are rejected for +tracked referents; the narrow tokenless path remains for old synthetic scalars +that never entered tracked counting. An initial strict gate exposed those two +production pre-clears and synthetic test fixtures; after migrating the +producers and preserving only that fixture bridge, `nice -n 19 timeout 1800 +make` passes in 7m49 (`/tmp/issue1649-central-queued-release-compat-make.log`). +Normal scalar stores now verify that paired acquisition already installed the +active slot instead of recording it afterward. Weakening of legacy scalar +cells, localized legacy CODE slots, and postfix result promotion use an +explicit existing-edge adoption transition, which preserves Perl's +already-counted reference without adding a second count. The record-only API +remains solely for synthetic lifecycle fixtures; no production caller uses it. +An attempt to remove verified-slot count alignment from deferred cleanup +failed 17 Java tests that explicitly require current scalar, aggregate, +invocant, native, and CODE owner identities to repair deliberate transient +undercounts (`/tmp/issue1649-tokenized-release-no-repair-make.log`). That +repair uses exact current owner slots and performs no root walk; it remains a +separate compatibility/lifecycle bridge from graph-based reachability +recovery. Keep it while removing ordinary graph recovery. The latter remains +reachable only through legacy `MortalList.deferDecrement()`; source search has +no production Java caller. CODE capture cleanup likewise retains its +tokenless verified-slot bridge for explicit self-capture lifecycle entry. +Localized CODE restore now releases the scalar's exact counted owner token. +The legacy direct-store fixture has no token, so restore adopts the existing +count only when the current stash-bound scalar proves that CODE edge, then +uses the same `MortalList` release path. `interpreter_globref_code_assignment.t` +passes 5/5 on system Perl, JVM, and interpreter with sweeps disabled. The full +`nice -n 19 make` gate passes in 7m58 on source `574c43e2ce`. +Logs: `/tmp/issue1649-localized-code-system-perl.log`, +`/tmp/issue1649-localized-code-jvm.log`, +`/tmp/issue1649-localized-code-interpreter.log`, and +`/tmp/issue1649-localized-code-owner-adoption-make.log`. +Native counted-owner retirement now goes through `MortalList`'s common +coordinator, including the regex callback count-only policy. Post-`DESTROY` no +longer reconstructs counts from surviving storage. It verifies that a newly +active counted owner has a paired count. The first gate exposed baseline slots +left during forced global teardown; snapshotting active identities at callback +entry fixed the false positive. System Perl, JVM, and interpreter pass +`destroy_exception_resurrection.t` 11/11; full `nice -n 19 make` passes in 7m38, +and `make check-links` reports 832 links with zero errors. + +Corrective sweeps are hard-disabled. The general `sweepWeakRefs` overloads now +return zero directly, and the destroyable-object sweep entrypoints and their +graph walk are removed. `Internals::jperl_gc`, lifecycle scheduling hooks, and +the targeted released-owner walk remain compatibility surfaces; source search +finds no production caller of the targeted walk. The weak-capture inspector is +diagnostic only. `restoreReachableOwnerCount` is reachable only through legacy +unpaired decrements, and `MortalList.deferDecrement()` has no production Java +caller. Exact counted-slot repair remains in deferred release and CODE capture +cleanup; the standalone scalar-cell bridge also remains. Source `25480a466c` +passes `nice -n 19 make` in 7m39 +(`/tmp/issue1649-central-counted-overwrite-release-make.log`). At `574c43e2ce`, +all production `releaseTrackedOwnerCount()` calls outside `RuntimeBase` and +`PerlOwnerSlot` are now in `MortalList`; localized CODE restore no longer +decrements directly. The focused blessing, +weaken/DESTROY, #1794, #1860, and HTML-Tree `t/refloop.t` cases pass on both +backends with corrective sweeps disabled +(`/tmp/issue1649-sweep-api-focused-no-sweeps.log`, +`/tmp/issue1649-sweep-api-refloop-no-sweeps.log`). Next: audit the remaining +normal count-recovery producers, remove recovery only after their release +coverage exists, then run the no-sweeps, #1618, and #1642 acceptance matrix on +one immutable final candidate. Existing Java repair fixtures deliberately +force `refCount` below the active-slot count; they assert compatibility recovery +but do not prove a normal Perl producer is missing a transition. + +The source audit confirms ordinary referent count arithmetic is centralized: +the only `RuntimeBase.refCount++/--` operations are in +`acquireTrackedOwnerCount()` and `releaseTrackedOwnerCount()`. The similarly +named counters in `CustomFileChannel` are channel-state bookkeeping. Owner +acquisition is paired in `PerlOwnerSlot`; lifecycle dispatch remains in +`MortalList` because final scalar, native, invocant, and DESTROY-argument +releases have different semantics. Removing `WeakRefRegistry`'s legacy +missing-slot adoption failed three Java compatibility tests that construct +`refCountOwned` cells directly without an owner token. Keep this bridge while +continuing the audit; its failures do not identify a normal Perl producer that +omits a slot. Evidence: `/tmp/issue1649-weaken-requires-slot-make.log`. + +The Perl model distinguishes a strong SV edge from a runtime resource lease. +When a Perl scalar cell stops owning a reference, its counted edge is released; +the referent reaches `DESTROY` when its last Perl strong owner is gone. An IO +lease can outlive the temporary scalar wrapper that acquired it and therefore +must not count as a Perl owner or resurrect the referent. Conversely, closing +an IO resource is decided by its remaining IO holders, not by a synthetic Perl +reference-count increment. The `IO_RESOURCE_HOLDER` migration follows this +split explicitly. + +Scalar references follow Perl's cell model as well: several references to the +same scalar cell share one owner of that cell's current referent. The +`SCALAR_REFERENCE_CONTENTS` slots are registered on the referenced cell and +deduplicate the count until the last live slot leaves. `RuntimeScalar` no +longer treats the sticky `referencedByScalarReference` history flag as proof +that an old value may be decremented when no live owner slot identifies it. +The alias-lifetime regression passes 12/12 on system Perl, JVM, and interpreter; +retarget and localized-lifetime regressions pass on all three. The full +`nice -n 19 make` gate passes on this source in 8m31; log: +`/tmp/issue1649-scalar-cell-owner-model-make.log`. + +The current call producers also preserve Perl's `@_` alias rule: staged +`CallArguments` materialize each source cell through `setArrayOfAlias`, the +bytecode call paths do the same for list arguments, and native-array call +entry points alias each source cell into the argument array. `RuntimeScalar.addToArray` +still copies for general list/array materialization, but the audited invocation +producers do not use that helper to create `@_`. Its older comment about +argument-list construction describes a legacy path; do not change this generic +copy helper to alias without identifying a current producer and its mutation +semantics. The remaining `@_` ownership work is cleanup of explicit alias and +staging identities, not a blanket alias-on-pass rewrite. + +The 2026-11-05 source audit found no production caller of the legacy unpaired +`MortalList.deferDecrement` API or automatic weak-sweep entry points. Sweep +implementations remain available to compatibility tests, while the runtime +hooks are disabled or no-ops. The full `nice -n 19 make` gate and the current +#1794, #1860, and HTML-Tree JVM cases pass. #1642's Dancer2-Plugin-DBIx-Class +work was merged in PR #1746; broader CPAN release qualification remains in +#1646. + +Evidence on the current built candidate: `nice -n 19 make` passes (log: +`/tmp/issue1649-central-count-full-make.log`); the focused counter and owner +tests pass (`/tmp/issue1649-central-count-focused.log`). The File::Temp path +wrapper and blessed scalar-reference lifetime fixtures pass 9/9 on system +Perl, JVM, and interpreter. #1794 passes 3/3 and #1860 passes 4/4 on both +backends. The full upstream HTML-Tree 5.07 suite passes 23 files / 989 checks +on each backend with `JPERL_DISABLE_CORRECTIVE_SWEEPS=1`. + +On the restored current source, `nice -n 19 make` passes in 7m50 +(`/tmp/issue1649-restored-source-current-make.log`). The +`temporary_io_invocant_survives_nested_render.t` regression and a focused +Path::Class `openw()->write(Template->process(...))` reproducer pass on system +Perl, JVM, and interpreter. The system-Perl check uses the installed Template +Toolkit library from `/Users/fglock/.perlonjava/lib` because the default Perl +installation lacks it. The full cached `App-Scaffolder-HTML` run remains +unverified: `timeout 1200 ./jcpan -t App-Scaffolder-HTML` spent the entire guard +parsing the 40 MB cached CPAN metadata index and did not start tests +(`/tmp/issue1649-app-scaffolder-jcpan.log`). A manual extraction followed by +system-Perl `prove` of `t/app.scaffolder.command.html.t` also stops before its +test body because `App::Cmd::Tester` is unavailable +(`/tmp/issue1649-app-scaffolder-html-system-current.log`). + +The most recent attempt to remove the standalone unregistered scalar-cell +compatibility bridge failed `DeferredReleaseOwnerSlotFastPathTest`, +`MethodInvocantVerifiedOwnerRepairTest`, and `path_tiny_runtime_prereqs.t`; +the bridge has been restored. The path fixture failure was a downstream +count-underflow exception (`counted scalar replacement requires a positive +old reference count`), not a path behavior mismatch. This confirms that +standalone scalar-cell lifetime is a distinct boundary in the current model; +it does not establish that ordinary production release needs a graph walk. + +Still open: audit and migrate the remaining producers guarded by +`restoreVerifiedCurrentCountedOwnerSlotRefCount`, the standalone unregistered +scalar-cell bridge, closure/CODE transfers, cloned/shared storage, and the +remaining untracked aggregate edges. Then remove ordinary count/root recovery +and unused sweep machinery, preserving only explicit teardown and diagnostic +walks. The no-sweeps acceptance matrix still needs to run on the final immutable +candidate. The live issue and PR state was refreshed on 2026-11-05. `.git` +remains read-only, so changes are uncommitted and backed up under `/tmp`. + +The eval-return/argument-unwind batch preserves a caller's pending +`RETURN_VALUE` while retiring only releases created by the argument frames +being unwound. `RuntimeCode.unwindEvalMethodInvocantHolds` drains from the +frame's saved queue boundary, and no-`DESTROY` container cleanup uses its own +mortal mark. `eval_callback_return_owner_release.t` passes 12/12 on system +Perl, JVM, and interpreter. The focused build passed in 1m16, and +`PerlReturnOwnerConsumptionTest` verifies return/source release provenance. +The fixture fails test 10 on parent `b5e6c22568`; evidence is in +`/tmp/issue1649-eval-callback-return-owner-parent.log` and +`/tmp/issue1649-return-owner-batch3.log`. + +The new CODE producer batch routes lexical forward-CV promotion, forward-glob +source-cell replacement, and constructor predeclaration through scalar +transitions. `RuntimeCodeSlotTransitionTest` passes 3/3. The filtered +`nice -n 19 make build` passed in 1m15; `lexical_sub_forward_undefined.t` and +`zz_forward_code_glob_alias.t` pass 23/23 on system Perl and 23/23 on each +PerlOnJava backend. Evidence is in +`/tmp/issue1649-code-slot-batch1-fixedtest.log`, +`/tmp/issue1649-forward-code-existing-perl.log`, +`/tmp/issue1649-forward-code-lexical-jvm.log`, +`/tmp/issue1649-forward-code-lexical-interpreter.log`, +`/tmp/issue1649-forward-code-glob-jvm.log`, and +`/tmp/issue1649-forward-code-glob-interpreter.log`. The first build caught a +test setup that had not registered its scalar as lexical storage; its +preserved log is `/tmp/issue1649-code-slot-batch1.log`. + +Production deferred releases carry slot tokens, while +`restoreReachableOwnerCount` remains reachable only from the legacy unpaired +release hook. The localized-glob manual decrement remains limited to the raw +`type`/`value` writes modeled by existing Java compatibility tests. Ordinary +owner gaps remain open across storage mutation, closure/CODE transfers, +deferred cleanup, clone/shared state, cycles, suspended frames, and resource +holders. The current source and counted-native release refactor pass the full +`nice -n 19 make` gate recorded above; the no-sweeps acceptance matrix still +needs to be rerun after the next runtime-affecting batch. + +The current source has three production callsites of +`restoreVerifiedCurrentCountedOwnerSlotRefCount()`: deferred release, scalar +overwrite, and CODE cleanup before capture release. Post-`DESTROY` no longer +restores counts from surviving slots; it checks newly active counted owners +against their paired count. The first full gate caught an overbroad check because +global teardown deliberately invokes `DESTROY` while baseline owner slots still +exist. Snapshotting active identities at callback entry fixed that distinction. +System Perl, JVM, and interpreter each pass +`destroy_exception_resurrection.t` 11/11. Full `nice -n 19 make` passes on the +working candidate in 7m38; logs are +`/tmp/issue1649-destroy-resurrection-perl-oracle.log`, +`/tmp/issue1649-destroy-resurrection-jvm.log`, +`/tmp/issue1649-destroy-resurrection-interpreter.log`, and +`/tmp/issue1649-no-destroy-count-rebuild2-make.log`. +Separate compatibility paths remain for unregistered scalar cells and legacy +unpaired releases. Regex callback slot retirement, count decrement, and token +completion now use `MortalList`'s counted-native release coordinator; callback +capture release remains an explicit subsequent lifecycle operation and is +covered by `RuntimeRegexCallbackOwnerSlotTest`. + +`tied_handler_nested_value_owner_before_weaken.t` passes 2/2 on system Perl and +on both backends using the existing JAR identified as `ad830f5d9f`. It covers +the normal nested-handler store-before-weaken path. The companion Java +`TiedHandlerNestedOwnerSlotRepairTest` manually sets `refCount` to an +undercount, so it remains defensive coverage and does not establish a normal +producer defect. The requested `deferred_capture_live_argument.t` also passes +3/3 on system Perl and both backends; saved parent logs pass as well, so that +fixture is coverage rather than a demonstrated regression on this branch. + +The existing `temporary_io_invocant_survives_nested_render.t` regression now +runs locally with Template Toolkit 3.106 via `/Users/fglock/.perlonjava/lib`. +System Perl passes 1/1. It fails on the unfixed parent `b6597f9b38` on the JVM +with an empty output file, while the parent interpreter passes. The current +pre-merge JAR from `ad830f5d9f` passes on both backends. Evidence: +`/tmp/issue1649-temporary-io-template-system-perl.log`, +`/tmp/issue1649-temporary-io-template-unfixed-parent-jvm.log`, +`/tmp/issue1649-temporary-io-template-unfixed-parent-interpreter.log`, +`/tmp/issue1649-temporary-io-template-current-jvm.log`, and +`/tmp/issue1649-temporary-io-template-current-interpreter.log`. The isolated +parent `make build` produced its JAR but failed the test shard on this +regression plus four unrelated return-owner tests; the full log is +`/tmp/issue1649-io-unfixed-parent-build.log`. The master merge changed only an +upstream test and documentation, but the merged candidate still needs its own +build and full gate. + +To limit expensive builds, finish the producer audit and group fixes by shared +slot-transition and release contracts before rebuilding. Bundle confirmed +scalar, array, hash, tied, package, glob, and CODE mutations that use the same +slot-transition contract. Separately bundle transfers that use the same exact +release obligation across arguments, captures, returns, suspended frames, +clones/shared storage, cycles, and resource owners. Remove ordinary recovery +only after those producers are covered. Run system Perl first for every new +Perl regression, then use one immutable full `nice -n 19 make` as the build +and Java unit-test gate. Run both PerlOnJava backends and the no-sweeps +acceptance matrix against that same built candidate; skip a separate +`make build`. If those gates expose a code defect, finish the connected fixes +before rebuilding the revised candidate. + +Standard Perl is the oracle for every Perl-visible reference edge and its +lifetime behavior. A reference-slot transition should retain a new strong +referent before publishing it, then release the old referent exactly once; +copy, alias, weak, and transfer operations must remain distinct. Deferred +work must carry the exact old referent and release obligation. `PerlOwnerSlot` +identities are migration/provenance evidence, not a second count model or a +basis for reconstructing counts; the target lifecycle decision follows the +count after every Perl strong edge is represented or counted through an exact +lifecycle token. + +**Sweep policy (2026-10-27):** Corrective sweeps are disabled by default, as +requested. `JPERL_ENABLE_CORRECTIVE_SWEEPS=1` temporarily enables legacy +comparison; a nonempty `JPERL_DISABLE_CORRECTIVE_SWEEPS` overrides it. Disabled +runs skip automatic scheduling, discarded-container sweep preparation, +scope-exit capture candidate processing, and the pre-END reachability sweep. +Post-END global teardown remains separate from ordinary reference release. +The build tracks both switches as test inputs so Gradle's configuration cache +cannot silently reuse another run's policy. Default-off is a migration step, +not evidence that every owner family is complete. + +### Cloned hash replacement releases the displaced slot (2026-10-31) + +`RuntimeHash.putClonedElement` now routes same-key replacement through +`storeOwnedElement`. The destination slot acquires its owner before the old +slot is deferred for release, while retaining cloned-value behavior for tied +scalar magic and avoiding ordinary assignment/FETCH semantics. +`RuntimeHashClonedElementReplacementOwnerTest` verifies the replacement has a +`HASH_ELEMENT` identity, the displaced weak observer clears after deferred +release, and replacing the new slot with `undef` releases its final owner. +The full gate passes on source `c9572eb57`; the focused JUnit case reports one +test and zero failures. + +### Middle array deletion releases the displaced owner (2026-10-31) + +Plain-array `delete` previously cleared an interior slot without scheduling its +counted owner release; deleting the tail already used `pop` and released it. +Deletion now passes the removed storage scalar through the shared array-slot +release helper while returning the fetched result to the caller. The permanent +regression verifies that the returned reference keeps its object alive, that +dropping it triggers `DESTROY` and weak cleanup, and that void-context deletion +releases immediately. System Perl, JVM, and interpreter each pass 6/6. **Tracking:** [#1649](https://github.com/fglock/PerlOnJava/issues/1649) @@ -13,13 +562,11 @@ counter; it does not define this rewrite's phase boundaries. ## Contract -Represent each Perl-visible strong owner as an explicit owner slot with a -unique identity and an owner kind. Acquiring, transferring, and releasing a -slot go through one API. Referent lifecycle state is separate from its -nonnegative strong-owner count. Counted cycles remain retained for the owning -runtime while their Perl owner count is positive. At an unmigrated boundary, -an explicit legacy owner bridge accounts for the edge; no edge may be counted -by both systems or by neither. +The target model follows Perl: every strong SV edge changes the referent's +ordinary reference count when its slot is acquired, transferred, replaced, or +released. Final lifecycle work follows the count reaching zero. Cycles stay +alive through their real internal edges. A deferred release carries the exact +referent and one pending decrement, which completes once after publication. Java references and `RuntimeScalar` wrappers do not by themselves imply Perl owners. In particular, lexical aliases, borrowed call arguments, aggregate @@ -27,8 +574,234 @@ slots, closure pads, and mortal temporaries have different ownership rules. Every path must state whether it creates an owner, borrows a cell, transfers an owner, or creates a deferred mortal owner. +PerlOnJava's current `refCount` is selective, so the migration uses +`PerlOwnerSlot` as a temporary ledger to find missing producers, verify +transfers, and keep exact provenance at deferred-release boundaries. It is not +another reference count. Remove the persistent ledger when normal slot +operations maintain the count directly; keep only the exact pending decrement +while a release is deferred. Java reachability must not decide Perl ownership. + +## Remaining lifecycle fallback audit (updated 2026-11-04) + +The ordinary lifecycle decision sites below still use recovery or graph +reachability. Explicit post-END teardown and diagnostic traversal are separate. +The package-rooted blessed aggregate boundary is covered by +`BlessedPackageOwnerRecursiveReleaseTest`: live owner identities gate recursive +field traversal, and blessed package owners preserve a parent without direct +weak observers. Direct weak observers no longer authorize root recovery in +production deferred releases; the root proof remains behind the legacy +unpaired test hook. Current-slot count restoration still needs producer audit. + +| Lifecycle path | Remaining fallback | Strong edge and acquisition/release sites | Existing coverage and open boundary | +|---|---|---|---| +| Storable `dclone` return | No fallback remains for the root result: it now uses a deferred `RETURN_VALUE` owner instead of leaving an extra `SCALAR_CELL` count on a helper scalar. | `Storable.dclone` acquires the return slot before restoring weak child-to-root edges; `RuntimeCode.returnList` recognizes the mortal return snapshot, and the queued slot token releases it at the caller boundary. | `storable_dclone_return_owner_release.t` proves the clone is destroyed when its final Perl variable is undefined while the original stays alive. It passes on system Perl and both backends; the unfixed parent failed 2/3. Existing `storable_dclone_weak_refs.t` remains covered by the full unit suite. | +| Deferred release | All production queue producers pass a `PendingOwnerRelease` token: counted scalar/element stores, recursive cleanup, return and argument transfers, IO/capture owners, and blessing temporaries. The `restoreReachableOwnerCount` and root/snapshot branches in `processDeferredBase` are reached only by legacy unpaired `deferDecrement`; direct calls in this repository are Java tests, not production code. `restoreVerifiedCurrentCountedOwnerSlotRefCount` and the standalone unregistered-cell bridge still repair count/ledger disagreements from current identities. `deferDecrementRecursive` traverses discarded container contents to release their actual child edges; it no longer uses a root proof. Tail-call release still has a verified-slot count restoration. | Counted cells use `RuntimeScalar.setLargeRefCounted` or `incrementRefCountForContainerStore`; aggregate stores use the array/hash mutation APIs. Internal hash/array cycle edges carry `HASH_ELEMENT`/`ARRAY_ELEMENT` identities acquired by store and released by mutation cleanup. Array pop/shift/delete and localized cleanup capture slot proof before removal, while excluding active argument aliases. Multi-LHS tail replacement uses slot-aware assignment. `CallArguments.add` and active `@_` record `ARGUMENT_ALIAS` identities for borrowed scalar cells. Generated direct calls create the staging frame before evaluating any nonzero argument list, preserving mortal return owners across later argument evaluation; argument-expression exceptions abandon and drain the exact staged frame. Failed targets retire materialized RHS owners, restore caller flush state, and drain exception-created releases; `die` registers lexical cells for unwind cleanup. | `StrongCycleOwnerSlotTest`, `strong_cycle_owner_slots.t`, deferred-release repair tests, `RuntimeScalarCountedOwnerRepairTest`, `ClearedAggregateOwnerIdentityNoRootWalkTest`, `RecursiveCleanupCurrentOwnerIdentityTest`, localized-array and multi-LHS regressions, `splice_args_destroy.t`, `goto_tailcall_args_cleanup.t`, `weak_sweep_keeps_current_args.t`, `deferred_capture_live_argument.t`, `weaken_closure_argument.t`, `weak_shift_temporary.t`, Sub::Quote/Sub::Defer fixtures, and `MethodInvocantVerifiedOwnerRepairTest` cover these paths. Most explicit undercount cases set `refCount` directly and are defensive fixtures; they do not show that normal production can create the mismatch. No production unpaired-release caller has been found. | +| Scalar overwrite | `RuntimeScalar.setLargeRefCounted` no longer queries external roots/live CODE captures, restores counts from unverified counted slots, or defers based on nested call depth. | Scalar cells acquire counted or untracked identities in `setLargeRefCounted`; package scalar, aggregate, CODE, active lexical, and closure slots identify their respective edges. Overwrite acquires the replacement counted slot before retiring the previous edge while preserving slot identity for queued-release provenance. Active forwarded argument aliases are accepted as proof for their current scalar cell. | `PackageRootOwnerSlotFastPathTest`, `PerlOwnerSlotReplacementOrderTest`, counted/untracked owner repair tests, `ForwardedArgumentAliasCurrentOwnerTest`, `weak_localized_cache_lifetime.t`, `weak_return_handoff_assignment.t`, nested weak-parent, recursive-builder, and sliding-window fixtures cover current-owner and nested release lifetimes. The full no-sweeps gate passes on `27e877e19`. | +| Localized package-scalar restore | Restore retires the displaced aggregate edge with the exact `SCALAR_CELL` token after restoring the package map. At zero, an exact-token aggregate release defers final cleanup to any current uncounted owner slot, including a package array/hash slot. Legacy unpaired cleanup keeps its existing snapshot path. | `GlobalRuntimeScalar.dynamicSaveState` installs the localized package scalar; `RuntimeScalar.transitionReferenceSlot` acquires its referent edge. Restore queues the exact scalar-slot release, restores the package scalar and aliases, then drains. `PACKAGE_AGGREGATE_SLOT` remains the strong owner of a package array/hash and releases only when that package slot is cleared. | `issue_1649_localized_scalar_shared_package_aggregate.t` passes 7/7 on system Perl, JVM, and interpreter; the unfixed parent fails package-retention assertions on both backends. The focused shard-0 unit gate passes. A ten-file scalar/aggregate/argument/tied-handler batch passes 69 checks per backend, including `deferred_capture_live_argument.t` and `issue_1649_scalar_slot_transition.t`. Logs are in `/tmp/issue1649-localized-scalar-*` and `/tmp/issue1649-scalar-aggregate-batch-*`. | +| First weaken | Ordinary tracked referents no longer query live CODE captures or general strong-root graphs. Package-nested untracked aggregates rely on current `UNTRACKED_REFERENCE` identities without a compatibility pin or fabricated count. First weaken no longer warms the lexical-root or CODE-root diagnostic caches; reachability diagnostics read active lexical registrations directly. The direct CODE pad-constant owner check remains; cloned-thread acquisition and release still need producer audit. | Strong scalar cells carry `SCALAR_CELL` or `UNTRACKED_REFERENCE`; package scalar/aggregate slots, closure pads, active CODE slots, and tied-handler values have separate identities. Weakening retires the weakened cell's strong edge. | `FirstWeakenUsesCurrentPackageOwnerTest`, `FirstWeakenDoesNotSeedReachabilityCachesTest`, `ReachabilityQueryCostTest`, `WeakCodeRefAggregateRootTest`, `UntrackedReferenceOwnerSlotTest`, and `UntrackedAggregateOwnerSlotTest` cover current owner identities and zero-query first weaken. `tied_handler_nested_value_owner_before_weaken.t` passes 2/2 on system Perl and both backends: the nested hash value was stored before the handler was tied and before the first weaken, and untie releases its final owner. `issue_1649_package_nested_untracked_weak_owner.t` passes 7/7 on system Perl; JVM and interpreter lifecycle probes pass. | +| Cleared aggregate | Scope-exit finalization uses current owner identities, temporary roots, and pending-release state. An external-root walk cannot preserve an aggregate whose owner ledger is empty. Under an explicit reachability-query measurement, the diagnostic traversal still runs for the synthetic query-cost fixture, but its result is ignored. | Production `my @array`/`my %hash` emitters register variables and bind active pad cells; registration backfills a prior binding, and binding acquires `ACTIVE_LEXICAL` when registration happens first. Scope cleanup retires that slot. Package and container edges have their own identities. Suspended lexical cleanup rechecks after its exact `SUSPENDED_FRAME` release. | `ActiveLexicalAggregateOwnerSlotTest`, `ClearedAggregateOwnerIdentityNoRootWalkTest`, `ClearedAggregateReachabilityNotOwnerTest`, `ClearedAggregateOwnerIdentityFinalizationTest`, `ScopeExitHashOwnerSlotTest`, and `active_lexical_aggregate_owner_release.t` cover explicit slots. The new raw-graph regression passes 1/1; full no-sweeps evidence is the `401c3c919` checkpoint log above. | +| Closure, CODE, and cycles | Ordinary capture cleanup follows current closure-pad, scalar-capture, active-CODE, stash-CODE, and pending-return identities. Installed-CODE root indexing and cycle walks remain in `ReachabilityWalker` for explicit sweep/diagnostic paths; no production caller of those sweep entry points was found in the call-site audit. `WeakRefRegistry` still eagerly prepares the CODE root index on first weaken. Frame cleanup and `RuntimeScalar.scopeExitCleanup` request capture release through owner identities; requests defer across active CODE, pending releases, and END owners and retry at owner-release boundaries. `RuntimeScalar.setArrayOfAlias` uses the shared persistent-cell/current-argument identity predicate. | `CLOSURE_PAD`, `SCALAR_CAPTURE`, `CODE_SLOT`, `ACTIVE_CODE`, and `CODE_PAD_CONSTANT` identify capture, stash, active-frame, and optree edges; regex callbacks have `REGEX_CALLBACK`. Generated JVM closures, interpreter closures, named-sub materialization, PadWalker rebinding, and thread clones acquire capture identities. Scalar referents use native `CLOSURE_PAD` slots, matching aggregate capture ownership; runtime scalar capture acquisition no longer uses the former selective-count bridge. Pad `captureCount` bookkeeping and the direct legacy capture helper remain. Explicit release checks slot kind and referent before mutation. Argument staging records `ARGUMENT_ALIAS` before a durable storage marker exists. | `TemporaryCodeArgumentOwnerIdentityTest` proves a temporary CODE cell acquires `ARGUMENT_VALUE` when another cell owns that CODE, and that a forwarded active argument cell remains borrowed. Direct-argument, saved-closure, and weak-closure fixtures pass 9/9 on system Perl and 9/9 per backend. `CaptureReleaseOwnerIdentityTest` fails both scalar and aggregate mismatched-release cases on parent `4c1456755` and passes on `1c142f655`. `TransientArgumentAliasOwnerTest` fails on parent `c416f7af2` and passes on `94d3ae224`; the transient-expression owner test remains green. `ScalarCaptureNativeOwnerTest` fails on parent `aec184796` and passes with the capture-focused suite on `f12bf4387`; seven Perl closure files pass 50/50 on system Perl and each backend. `SharedScalarCaptureNativeOwnerTest` passes on `99231cf2c`, retaining one referent edge through two closure releases with zero root queries or snapshots. Full `timeout 1800 nice -n 19 make` passes on `99231cf2c`. Earlier closure and async evidence is under `/private/tmp/ownership-temp-closure-*`. Remaining work includes legacy pad capture bookkeeping, clone/shared-storage owner transfer, CODE/glob cleanup and state-storage boundaries, and exactly-once release through async and exception unwind. | +| Detached glob and namespace components | `RuntimeStash.deleteGlob` removed a package scalar before constructing the returned glob. `RuntimeStash.deleteNamespace` retained copied maps without owner identities, scalarizing its named glob dropped `NamespaceMove`, and `deleteInContext` ignored void context so discarded detached results kept their component leases. | Detached single-glob and whole-namespace results acquire one `GLOB_COMPONENT_SLOT` identity per slot before package-root removal. Scalarization copies namespace-move owners before releasing the temporary source. `deleteInContext` forwards context and retires detached results immediately in void context. Alias materialization temporarily leases moved components, transfers scalar/array/hash package-root identities to one destination, and lets additional aliases acquire new slots. Durable scalar values acquire `GLOB_VALUE` identities; scalar overwrite/undef and aggregate clear release component edges before publishing the replacement cell state. | `stash_delete_detached_glob_scalar_owner.t` fails on parent `99231cf2c` and passes 4/4 on system Perl, JVM, and interpreter. `stash_delete_namespace_owner.t` fails the final two checks on parent `91b028417` and passes 4/4 on system Perl and both backends. `stash_alias_rebind_void_delete_owner.t` fails checks 4–7 on parent `cfe4b3053` and passes 7/7 on system Perl and both backends. `stash_delete_detached_glob_undef_order.t` and `detached_glob_array_alias_clear_order.t` pass 5/5 and 4/4 on system Perl; the filtered `make build` passes both plus `stash_delete_detached_glob_scalar_owner.t` on JVM, and all three pass on interpreter. The unfixed parent failed scalar destructor order and array alias cleanup. Logs are in `/tmp/issue1649-*detached-glob*` and `/tmp/issue1649-interpreter-*.log`. `NamespaceAliasOwnerTransferTest` fails on parent `9e43e929e` and passes on `d6f985960`; the full no-sweeps gate passes on `d6f985960`. `snapshotStashEntry`, CODE owner transfer, `savedNamespaceMove` lifetime, and IO/FORMAT resource-owner interactions remain under audit. | +| Rescued object cleanup | `DestroyDispatch.processRescuedObjects` no longer infers death from `refCount == 1` or `Integer.MIN_VALUE`; it checks current Perl owner identities. | A weak scalar promoted during `DESTROY` acquires its normal counted slot. The rescue list records pending lifecycle work but is not an owner. Releasing the last identified owner removes the queued marker and re-dispatches `DESTROY`; marker-only rescue proceeds to final cleanup. | `destroy_weak_aggregate_slot_resurrection.t` passes system Perl, JVM, and interpreter; `dbic_deep_cycle_weak_shift_regression.t` passes on both backends and preserves an unrelated strong-cycle rescue. `PerlReferentDestroyLifecycleTest` covers marker-only cleanup. Broader producer coverage and removal of the remaining rescue registry are still open. | +| Temporary evaluation roots | `MortalList` stores temporary roots and the reachability walker follows them during cleanup; temporary roots intentionally do not count as Perl owners. | `pushTemporaryRoot`/`popTemporaryRoot` bracket setter and return cleanup. A temporary root must defer finalization only until its exact removal, without turning it into a persistent Perl edge. | `PerlStrongOwnerProofTest` distinguishes temporary roots from Perl owners; `TemporaryReturnOwnerTraversalTest` covers direct aggregate values. Final cleanup on temporary-root release remains part of the migration. | +| Suspended async frame | Awaited Future values formerly had a separate `suspendedRoots` map consumed by reachability snapshots. That supplemental root is removed. | `InterpreterSuspension` copies the await operand into a scalar cell and attaches a `SUSPENDED_FRAME` slot. Completion, cancellation, and exception cleanup detach the slot and notify weak cleanup. Lexical registers already use per-register `SUSPENDED_FRAME` identities. | `InterpreterSuspensionOwnerTest` verifies acquisition and final release; `issue_1649_cleared_aggregate_async_scope_exit.t` passes on both backends; `issue_1649_cancelled_async_scope_exit.t` verifies cancellation and exactly-once destruction 5/5 on both backends. Chained-await coverage remains in the final matrix. | +| Resource holders | Each anonymous IO resource holder has a native `IO_RESOURCE_HOLDER` identity on its `RuntimeGlob`; `RuntimeScalar.ioOwnerSlot` carries that identity, and `RuntimeGlob.ioHolderCount()` derives the active count from the owner ledger. Resource leases remain separate from Perl strong-reference counts. | `retainUnstashedIoForDurableSlot` acquires a slot for a strong scalar, while `releaseIoOwner` retires it exactly once. Weaken releases a weak scalar's holder after any final destructor dispatch; unweaken reacquires it for a live glob. Detached-value assignment, returned aliases, and localized-global suspension move the same identity. Replacement acquires the new edge before releasing the old one. Aggregate clear queues the owning scalar for release. `RuntimeList.setFromList` retires a materialized scalar's lease with its counted edge and preserves it when the result still carries that handle. Thread cloning reacquires a runtime-local lease for each cloned strong scalar that owned an anonymous IO holder. Shared aggregate views retain the one canonical synchronized backing store and its existing element edges; shared graph validation rejects IO/glob resources. | `WeakGlobIoOwnerSlotTest` verifies weak/strong aliases, holder release, and unweaken. `RuntimeGraphClonerIoOwnerTest` verifies parent/child lease independence. `file_temp_path_wrapper_lifetime.t` passes 5/5 and `blessed_scalar_reference_contents_destroy.t` passes 4/4 on both backends with corrective sweeps disabled; system Perl passes the file-wrapper oracle. The immutable no-sweeps Make gate passes on `c47cec61b5`. Socket return, exception unwind, localization, aggregate clear, selected-glob restoration, and #1794/#1860 remain in the broader audit. Non-socket close policy remains a separate resource decision. | + +### Active lexical aggregate and signature pad owners (2026-11-03) + +`MyVarCleanupStack.register` can run after the compiler has already bound the +aggregate cell into an active lexical pad. In that ordering, the registration +path previously left the pad-map edge without an `ACTIVE_LEXICAL` identity; an +idempotent pad bind also returned before filling the missing slot. The +registration hook now scans all active pad and top-level bindings for the exact +cell and acquires the missing slot for every binding. Normal scope cleanup +retires the slot, which clears final weak observers through the owner-release +lifecycle callback. The original weak array/hash regression passes on system +Perl and both backends, with parent failure evidence. + +The separate signature path lowers parameters to `my (...) = @_`; its +`signatureParameterDeclaration` marker intentionally skips lexical alias +resolution. The interpreter assignment compiler now emits an active-pad bind +after registering each signature scalar or aggregate cell. The expanded +`issue_1649_list_declared_aggregate_weak_owner.t` covers ordinary list +declarations and slurpy array/hash parameters: system Perl, JVM, and interpreter +pass 16/16, while the unfixed interpreter failed the two frame-exit assertions. +The full sweeps-disabled gate passes on immutable source `09a8ef926` in 7m15; +full and focused logs are listed in the current checkpoint above. + +### Localized scalar restore preserves package aggregate owners (2026-11-04) + +`GlobalRuntimeScalar.dynamicRestoreState()` previously removed the localized +scalar's owner identity and manually decremented the aggregate afterward. That +finalizer ignored an active `PACKAGE_AGGREGATE_SLOT`, so restoring a localized +scalar could destroy array/hash members while the package aggregate still owned +them. Restore now queues the exact scalar-slot release, restores the package +scalar map, and drains the pending release afterward. When the count reaches +zero, deferred lifecycle cleanup waits on the current uncounted aggregate +owner identity. This rule applies only to exact-token releases; synthetic +legacy unpaired query-cost cases keep their existing snapshot behavior. + +The new regression passes 7/7 on system Perl, JVM, and interpreter, and fails +on both unfixed PerlOnJava backends. The first focused gate caught an overly +broad version of the aggregate-owner rule through four legacy snapshot-cost +assertions; restricting it to exact-token releases makes the focused +`make test-unit` shard pass. A ten-file neighboring regression batch also +passes 69 checks per backend. The complete no-sweeps suite and lifecycle +acceptance matrix remain open. + +### Scalar overwrite removes root reachability fallback (2026-11-01) + +`RuntimeScalar.setLargeRefCounted` no longer queries external roots or live +CODE captures to decide whether an overwritten aggregate's weak observers +should remain. The migrated scalar, aggregate, package, lexical, and closure +owner slots carry those strong edges through replacement and cleanup. Scalar +overwrite also no longer restores liveness from unverified counted slots. The +standard Perl oracle passes 20/20 across the return-handoff, closure/localized- +cache, nested-container destruction, and active-lexical fixtures. The full +no-sweeps `make` gate passes on immutable source `18707627f` in 7m13s. The +remaining scalar-overwrite nested-call deferrals are an open audit item. + +### Weak blessed glob aliases release scalar and IO owners (2026-11-01) + +First blessing a weak glob scalar previously promoted it as an existing strong +owner, and the blessed-glob alias scan counted weak lexical and package cells. +Both acquisition paths now skip weak scalars. The parent failure also exposed +a separate edge: a weak anonymous glob scalar retained its native +`IO_RESOURCE_HOLDER` slot after `weaken`, so the glob remained alive until +lexical scope exit. Weakening now retires that slot after any final destructor +dispatch; durable-slot acquisition ignores weak scalars, and `unweaken` restores +the IO identity for a live glob. + +`blessed_glob_alias_owner_release.t` passes 5/5 on system Perl, JVM, and +interpreter. Java coverage checks weak scalar owner slots and IO holder counts. +The full no-sweeps `make` passes on source `8245755e9`; parent and intermediate +failure evidence plus final focused logs are listed in the current checkpoint. + +### Multi-LHS array-tail replacement releases displaced owners (2026-11-01) + +`RuntimeList.setFromList` previously assigned the materialized RHS list directly +to a plain array's `elements` field. That skipped cleanup of the displaced +array cells and left temporary RHS cells as the apparent owners. The array +tail now goes through `RuntimeArray.setFromList`, which releases old element +slots, acquires current `ARRAY_ELEMENT` identities for the destination values, +and then retires any counted temporary RHS owners. Tied-array dispatch and +autovivification continue through the same store API. + +`list_assignment_array_tail_releases_displaced_owner.t` passes 5/5 on system +Perl and both backends with sweeps disabled. The unfixed parent fails the two +release checks; the failure and fixed focused logs are recorded above. Full +no-sweeps `make` passes on source `6a208b198`. + +### Multi-LHS hash-tail replacement releases displaced owners (2026-11-01) + +`RuntimeList.setFromList` previously replaced a hash LHS by assigning a newly +created map directly into `runtimeHash.elements`. That skipped release of the +displaced hash slots, left the moved values attached to a temporary hash's +owner identities, bypassed tied-hash assignment, and skipped package-root +marking. Hash tails now flow through `RuntimeHash.setFromList`, and list +assignment returns that API's key/value result while retiring temporary RHS +owners. The new weak-reference and `DESTROY` regression passes on system Perl +and both backends; the parent failure is recorded in the current checkpoint. + +### Multi-LHS assignment exception cleanup releases lexical owners (2026-11-01) + +When a tied `STORE` died during hash-tail assignment, cleanup remained +suppressed, leaving the displaced tied value and materialized RHS owner live. +`RuntimeList.setFromList` now retires remaining RHS transport owners and +restores the caller's flush state in `finally`, draining deferred cleanup after +an exceptional assignment. That exposed a second producer gap: the JVM cleanup +analysis skipped lexical registration for a method whose only exceptional exit +was builtin `die`. `CleanupNeededVisitor` now requires cleanup for explicit +`die`, so reference-valued method lexicals are released during unwind. The +system Perl oracle and both PerlOnJava backends pass the tied-hash exception +regression, and the focused multi-LHS gate passes on the current source; the +full no-sweeps gate passes on immutable source `30ae72581` in 6m15s at +`/private/tmp/ownership-list-assignment-exception-immutable-make-30ae72581.log`. + +### Counted owner replacement acquires before release (2026-11-01) + +`PerlOwnerSlot.acquireCountedIdentity` previously released its current slot +before registering the replacement referent. This left no explicit strong edge +during scalar overwrite and could run weak cleanup while the replacement was +not yet represented. It now retains the replacement's runtime root when +applicable, registers the same stable slot identity on the replacement, then +retires the prior referent and its runtime root. The new Java regression fails +on the parent at +`/private/tmp/owner-slot-replacement-order-parent-focused.log` and passes after +the fix at `/private/tmp/owner-slot-replacement-order-fixed-focused.log`. The +full no-sweeps `make` gate passes on immutable source `27e877e19` in 6m19 at +`/private/tmp/ownership-counted-slot-replacement-immutable-make-27e877e19.log`. + +### Cancelled async frames release suspended owners (2026-11-01) + +`issue_1649_cancelled_async_scope_exit.t` verifies that a suspended lexical +remains live before cancellation, then its weak observer is cleared and +`DESTROY` runs exactly once; repeated cancellation does not release the frame +twice. The test passes 5/5 on JVM and interpreter with corrective sweeps +disabled at `/private/tmp/ownership-async-cancel-jvm.log` and +`/private/tmp/ownership-async-cancel-interpreter.log`. System Perl 5.42 cannot +parse the PerlOnJava `async sub` syntax; the result is at +`/private/tmp/ownership-async-cancel-system-perl.log`. The full no-sweeps gate +passes on immutable source `0ee2739d3` in 6m19 at +`/private/tmp/ownership-async-cancel-immutable-make-0ee2739d3.log`. + ## Baseline ownership map +### Producer audit checkpoint (2026-11-01) + +The array element-list and hash element-map mutation wrappers maintain +`containerOwners` and the current `containerOwner` hint on add, replacement, +bulk insertion, and removal. Hash assignment uses `independentSlot` to avoid +reusing one mutable hash cell for two keys; explicit refaliasing paths +intentionally preserve the aliased scalar cell. Array literal, push, +whole-array assignment, tracked-reference construction, hash assignment, and +tracked hash construction acquire counted element identities at separate call +sites. The common APIs acquire after storage is current, while the direct +helper remains callable before storage and then records `SCALAR_CELL`; the +legacy snapshot tests cover this ordering. The call-site audit has not yet +found an ordinary producer that relies on it, but that audit must finish before +the raw bridge is removed. + +Package scalar, array, hash, and named IO-glob table facades acquire their +`PACKAGE_SCALAR_SLOT`, `PACKAGE_AGGREGATE_SLOT`, and `PACKAGE_GLOB_SLOT` +identities on insertion and retire them on replacement, deletion, or clear. +Stash CODE slots use `CODE_SLOT` bindings. Package aggregate element values +also receive their normal scalar/element owner identities when populated. +These root-slot families are present; the remaining root-walk cleanup paths +must be tied to concrete producers that still lack current slot proof. + +Two existing tests still exercise narrow compatibility boundaries. +`UnblessedAggregateReachabilitySnapshotTest` clears a marker directly to +construct an owner state inconsistent with normal container mutations. +`ReachabilityQueryCostTest` directly registers an aggregate without binding it +to an active lexical pad and measures the external-root snapshot. The +package-nested untracked aggregate no longer needs its first-weaken pin; exact +`UNTRACKED_REFERENCE` owners protect the weak observer. These synthetic +fixtures do not establish a producer defect. Trace normal registration and pad +binding before removing the remaining cleared-aggregate root proof. + +Closure construction records one `SCALAR_CAPTURE` identity per captured scalar +cell and a `CLOSURE_PAD` identity for each captured aggregate. Scalar cells also +carry a `CLOSURE_PAD` edge to the referent; tracked scalar captures still use +the legacy capture-count bridge, while aggregate captures use native owner +slots. `RuntimeCode.releaseCaptures` clears its capture arrays before releasing +slots, then queues the declaring-scope decrement only after the final capture +leaves. Ithread clone paths reconstruct and rebind these identities. The +remaining audit is the mismatch cleanup in `MyVarCleanupStack.scopeExitCleanup` +for `captureCount` values exceeding explicit `SCALAR_CAPTURE` slots, plus the +exception, async-suspend, and nested-CODE paths that can create or transfer +those counts. + +Anonymous IO resource ownership has a separate representation: a scalar's +`ioOwner` boolean pairs with `RuntimeGlob.ioHolderCount`. Durable stores, +lexical cleanup, aggregate clear/replacement, localized array slots, localized +hash proxy slots, and returned values now use explicit retain, release, or +transfer paths, but there is no `PerlOwnerSlot` for the holder token. Socket +lifetime coverage includes #1794 and async cleanup; cloning, exception +transfer, and ordinary anonymous-file close semantics still need a +producer-by-producer audit before resource ownership can be considered +complete. + | Concern | Current implementation | Phase 1 implication | |---|---|---| | Referent identity and lifecycle | `RuntimeBase.refCount` combines selective counts with `-1`, `-2`, and `Integer.MIN_VALUE` sentinels; `blessId`, destruction flags, and owner metadata are separate fields | Count and lifecycle must be split for migrated referents; the legacy fields remain behind the boundary for unmigrated referents | @@ -102,7 +875,10 @@ and first path establish implementation cost. ## Progress tracking -### Current status: Phase 1 complete; merged in PR #1653 as `84f32be179bdc2b351c3eaae1cb26df39964ab6b` (2026-10-07) +### Current status: Phase 1 complete; Phase 2 in progress + +Phase 1 merged in PR #1653 as `84f32be179bdc2b351c3eaae1cb26df39964ab6b` +(2026-10-07). ### Completed @@ -296,19 +1072,69 @@ and first path establish implementation cost. assertion failures remain separately unclassified under [#1646](https://github.com/fglock/PerlOnJava/issues/1646). +### Targeted weak release with owner slots + +`sweepReleasedWeakReferents()` now treats an active owner slot as direct proof +that a pending target is still strongly owned. When every target in the batch +has that proof, it returns without building root snapshots or running the full +walker. Remaining uncounted targets still use the existing fallback. The new +`TargetedWeakReleaseOwnerSlotFastPathTest` passes with sweeps enabled, along +with the existing targeted-query and weak-CODE fallback tests. HTML-Tree +5.07 `t/refloop.t` still passes 8/8 on both backends with sweeps disabled. + +### CODE optree constants receive owner identities (2026-10-31) + +System Perl confirms that a saved coderef keeps a backslash-addressable +constant alive after its named glob is replaced, and that a nested anonymous +optree shares its constant identity across closure instances while its factory +CV remains alive. The expanded permanent Perl regression passes 8/8 on system +Perl. Each compiled optree now has a distinct constant scalar per source +occurrence and one CODE_PAD_CONSTANT slot per strong edge. A parent CV owns +embedded anonymous optrees as templates; each produced closure also owns its +own edges. The interpreter tracks constants from its constant pool and nested +closures in the same owner ledger. Glob replacement retires only the stash +owner, and final CV cleanup releases constant slots and clears weak observers +after the last owner. Runtime lookup uses the owning CV's registered optree +constants; the reachability walker no longer follows pad constants as a +substitute for explicit edges. Full build and backend validation for this +batch is pending. + +The fresh source call-site audit confirms that production code has no caller of +`MortalList.deferDecrement(RuntimeBase)` and no caller of +`ReachabilityWalker.sweepReleasedWeakReferents()`; the latter appears only in +four Java tests. All current `refCountOwned = true` assignments acquire a +`PerlOwnerSlot` or transfer an existing active slot, apart from the explicit +legacy-adoption helper. These findings support retaining the test/compatibility +contracts while continuing to look for a real producer-ordering gap; they do +not justify removing the active exact-slot alignment bridge. + +The next audited producer gap was direct array-element refaliasing: +`RuntimeArrayProxyEntry.aliasToReference` installed the referenced scalar cell +without an `ARRAY_ALIAS_CELL` owner identity. The new regression passed 8/8 on +system Perl, failed on the unfixed JVM and interpreter candidates, and now +passes 8/8 on both backends. The fix acquires the identity before publishing +the slot and carries existing cell identities into array alias views and +tail-call carriers. `nice -n 19 make` passed on this source in 7m23; log: +`/tmp/issue1649-array-refalias-full-make.log`. The ordinary recovery/adoption +audit remains at five mechanisms. Next: continue the producer audit in a batch +before reassessing any compatibility recovery mechanism. + ### Next steps -1. Extend the ownership path through scalar proxies and ordinary array/hash - slots in Phase 2, then resolve the HTML::Tree teardown failures and verify - unchanged `t/refloop.t`. -2. Resolve the strict target failures in the fresh-home CPAN release - acceptance, then rerun that gate on the final candidate. The current run - distinguishes prerequisite/setup timeouts and missing dependencies from - runtime assertions; those outcomes do not yet satisfy #1642's acceptance. -3. Rerun Moo and DBIx::Class after their separate tracked fixes land; classify - the two DBIx::Class assertions independently. -4. Run each repository gate from an immutable commit and record before/after - evidence for each enabled path. +1. Trace `restoreVerifiedCurrentCountedOwnerSlotRefCount` in deferred release + and CODE cleanup, plus the standalone unregistered scalar-cell bridge, back + to their normal producers. Replace real missing transitions with exact + `PerlOwnerSlot` operations; keep synthetic undercount fixtures separate from + producer proof. +2. Audit the legacy localized-CODE adoption and `DESTROY`'s synthetic `$_[0]` + owner for a producer-side slot transition. Remove compatibility adoption + only after the old direct-store producer is migrated. +3. Audit clone/shared storage, suspended frames, cycles and IO holders against + the same owned, borrowed, transferred and deferred-release contract. Then + remove the remaining ordinary recovery branches and unused sweep machinery. +4. Run the final weak-reference, `DESTROY`, resurrection, cycle, cancellation, + #1794, #1860, #1618 and HTML::Tree acceptance matrix on one immutable + candidate; reconcile it with draft PR #1938 and review CI before readiness. ### Open questions and blockers @@ -427,3 +1253,1659 @@ and first path establish implementation cost. investigation is safe snapshot reuse across unchanged root sets or an ownership path that removes the ordinary cleanup fallback. Full release acceptance also remains required before closing the issue. + +### Phase 2 progress (2026-10-27) + +- JVM lexical cleanup now includes captured scalar cells at ordinary scope and + subroutine fall-through boundaries. The new `closure_capture_scope_exit.t` + regression passes on system Perl and both backends. The existing recursive + builder regression also passes on both backends with corrective sweeps + disabled. +- Explicit return cleanup now leaves the interpreter's `RETURN` opcode + decrements queued until the `RuntimeCode` boundary has removed the callee's + lexical registrations. The explicit-return regression passes 6/6 on JVM and + interpreter with corrective sweeps disabled. Declaration-scope provenance + still distinguishes locals from outer cells borrowed by a closure. +- JVM and interpreter closure creation now assign a distinct `SCALAR_CAPTURE` + identity to each captured scalar pad cell. `releaseCaptures`, pad rebinding, + and thread cloning balance those identities; a focused Java test passes. + The slots remain owned by their closure metadata while the selective count + bridge is active. Registering them as a second global root retained a + Catalyst request tempfile, so native root-ledger integration still needs a + closure-liveness boundary. +- [x] Counted scalar, array-element, and hash-element stores now have distinct + `PerlOwnerSlot` identities (2026-10-27). Overwrite preserves the cell's + identity; deferred releases carry an immutable slot identity and sequence, + so draining an old value cannot retire a newer assignment. These slots + identify the selective-count bridge without becoming global roots. + `RuntimeHash.put` acquires its element owner and releases displaced values; + array removal and scope cleanup retain release provenance. A final + identified scalar/element release can destroy its referent directly rather + than restoring a synthetic count from a stale root snapshot. +- [x] Local-array rvalue returns now transfer through distinct `RETURN_VALUE` + slots before lexical cleanup on both backends (2026-10-27). Void returns + retain no element owners; scalar returns yield the count; list returns keep + mortal ownership until the receiving caller consumes the values. The new + [`local_array_return_owner_release.t`](../../src/test/resources/unit/refcount/local_array_return_owner_release.t) + passes 8/8 on system Perl and both backends with corrective sweeps disabled; + the unfixed implementation failed five assertions on each backend. The + equivalent implicit-return probe also passes 8/8 on all three runtimes. +- [x] Weak links and captured/container-owned scalar results are treated as + borrows during recursive release and void discard (2026-10-27). This keeps + self-retaining closure cycles alive after invocation. The existing closure + cycle regression passes 3/3, the weak localized-cache regression 7/7, and + the new repeated-element/cycle regression 6/6 on both backends with sweeps + disabled. Seven Java owner-slot tests cover replacement, shared referents, + queue provenance, weak edges, borrowed captures, and a final element release + with zero root queries or snapshot builds. +- [x] Unchanged HTML-Tree 5.07 `t/refloop.t` passes 8/8 on JVM and interpreter + with `JPERL_DISABLE_CORRECTIVE_SWEEPS=1` (2026-10-27). The full unfiltered + `nice -n 19 make` passes in 6m45s. Focused no-sweep qualification also passes + `destroy_edge_cases.t` (27/27), `weaken_edge_cases.t` (43/43), and END + destruction ordering (5/5) on both backends. +- [x] Successful and throwing `DESTROY` callbacks now share ownership + finalization (2026-10-27). Synthetic callback arguments are balanced before + reblessing and resurrection checks; dead referents clear weak observers and + release owned children even when the callback dies or warning delivery + throws. Real escaped owners preserve the referent and allow its next + destruction. `issue_1649_destroy_exception_cleanup.t` now passes 10/10 + without sweeps on both backends, resolving its two weak-clearing failures. + The new + [`destroy_exception_resurrection.t`](../../src/test/resources/unit/refcount/destroy_exception_resurrection.t) + passes 11/11 on system Perl and both backends without sweeps, covering + resurrection followed by final release, reblessing, cleanup warnings, and + preservation of `$@`. A Java regression verifies observer clearing and + child-owner release with automatic sweeps suppressed. HTML::Tree remains + 8/8 on both backends without sweeps; the latest unfiltered + `nice -n 19 make` passes in 7m05s. + +- [x] Shared scalar/list return boundaries now snapshot reference values, + including CODE values, into mortal `RETURN_VALUE` slots (2026-10-27). + Forwarding an existing temporary avoids duplicate acquisition; lvalue returns + retain their cell aliases. Staged reference-valued list arguments acquire + distinct `ARGUMENT_VALUE` slots and queue their release once, including + repeated referents. Pending return owners protect closure captures until + the caller consumes the result. Five Java transfer tests pass. The new + [`code_return_argument_snapshot.t`](../../src/test/resources/unit/refcount/code_return_argument_snapshot.t) + passes 4/4 on system Perl and both backends without sweeps; the unfixed + implementation failed two assertions on each backend. Focused no-sweep + checks also pass local-array returns (8/8), throwing destructor resurrection + (11/11), self-retaining closure cycles (3/3), explicit closure returns + (6/6), and unchanged HTML::Tree (8/8) on both backends. The bundled + candidate passes the unfiltered `nice -n 19 make` gate in 8m18s. + +- [x] Partially evaluated method arguments now retire their explicit owners + on exceptions and frame exit (2026-10-27). JVM argument emission installs + an exception handler; interpreter inline-eval unwinding retires staging + registers created within that eval. Strong staging registrations and call + depth distinguish abandoned calls from still-active outer evaluations. + Staged argument owners and pending return tokens retain their referents + through the runtime positive-owner registry, releasing that retention once + their exact token drains. Existing corrective sweeps respect these explicit + transfer owners rather than reclaiming them from an incomplete root walk. + Non-local map returns preserve their result mortals during interpreter and + shared-call cleanup. The new + [`argument_evaluation_unwind.t`](../../src/test/resources/unit/refcount/argument_evaluation_unwind.t) + passes 20/20 and + [`argument_evaluation_return.t`](../../src/test/resources/unit/refcount/argument_evaluation_return.t) + passes 18/18 on standard Perl and both backends without sweeps. Unfixed + backends failed six unwind assertions each and six/seven return assertions + on JVM/interpreter respectively. Four Java checks cover repeated argument + identities, caller-frame preservation, non-local return transfer, and child + retention through an explicit argument owner. All Java tests and the + focused normal-mode refcount corpus pass (`nice -n 19 make`, 2m16s). + +### Final owner releases and default-off qualification (2026-10-27) + +- [x] Final weakening and scalar/element overwrite use their identified owner + edge instead of restoring a count from a root walk. Unblessed scalar cells + finalize when their lexical binding or last capture ends; escaped strong + references keep the cell and its contents alive. Scalar capture identities + are visible in the referent's local ledger without becoming global roots. + Legacy sweeps respect those binding/capture owners. Java coverage verifies + final release with zero root queries and no duplicate lifecycle transition. +- [x] Whole-array replacement, undef, and local restoration release only owned + element cells. Clearing aliased `@_` preserves the caller's scalar owners, + including independently weakened probe copies; inserted elements still + release once. Files: `RuntimeArray.java`, `PerlArgumentUnwindOwnerTest.java`. +- [x] JVM and interpreter acquire rvalue return owners before lexical cleanup. + Both interpreter return emitters reserve a separate result register, so + cleanup of an earlier local cannot replace a later local's owner cell. + Referenced scalar cells keep their contents until the receiving caller + releases or overwrites them. Lvalue aliases and socket ownership remain + covered by the existing regressions. Files: `RuntimeCode.java`, + `EmitStatement.java`, `EmitControlFlow.java`, `BytecodeCompiler.java`, + `CompileOperator.java`, `BytecodeInterpreter.java`, `MortalList.java`. +- [x] Temporary-expression protection no longer follows scalar references into + arbitrary hash/array graphs. The referent and its element slots supply + ownership; only direct expression references are inspected. A Java + regression rejects traversal into unrelated metadata. This removes a + recursive Moose metadata walk observed during Catalyst bootstrap: the JVM + probe now reaches its tempfile assertion instead of timing out at 240s. + +New permanent Perl regressions pass on standard Perl and both backends with +sweeps disabled by default: + +| Regression | Assertions | +| --- | --- | +| `refcount/scalar_cell_scope_owner_release.t` | 11/11 | +| `refcount/scalar_cell_return_contents_owner.t` | 8/8 | +| `refcount/argument_array_clear_borrowed_cells.t` | 9/9 | +| `refcount/lexical_return_slot_owner_release.t` | 6/6 | + +The corresponding unfixed failures were retained before each correction. +Existing default-off checks pass on both backends: probe copies (5/5), scalar +assignment guards (6/6), weaken/DESTROY (24/24), scalar weak references +(10/10), sliding-window release (12/12), argument exception/return cleanup +(20/20 and 18/18), local-array returns (8/8), explicit closure returns (6/6), +self-retaining closure cycles (3/3), and unchanged HTML::Tree (8/8). Existing +socket lifetime and blessed-descriptor checks also pass on both backends. + +### Active call owners and final default-off gate (2026-10-27) + +- [x] Every active call frame owns an `ACTIVE_CODE` identity. Recursive calls + retain distinct tokens; removing one frame retires one token. A counted final + release waits for the last active frame, then clears observers and captures + without a root query. Borrowed CODE with no counted release keeps its captures; + template, stash, and pinned CODE ownership still require migration. +- [x] Capture sweeps cannot override explicit live call/capture tokens, including + in legacy comparison mode. Default-off also skips capture candidate queuing + and processing and the pre-END reachability cleanup. The default-policy Java + regression verifies no candidate retention or pre-END root queries. +- [x] Preserve genuine self-capture cycles rather than breaking them at lexical + exit. Assigning CODE into an already captured cell acquires the capture's + referent edge separately from the lexical store. Explicitly breaking the + cycle allows the final external owner to release its captured data. + +New permanent regressions pass on standard Perl and both backends without +sweeps: `active_callback_owner_release.t` (13/13), +`self_capture_cycle_owner.t` (9/9), and `code_template_owner_lifetime.t` (4/4). +The callback and self-cycle failures were retained on the unfixed candidate. +`ActiveCodeOwnerTest` passes all four cases, including zero root queries on +final release. Existing `weak_active_coderef_dispatch.t` now passes 3/3 on both +backends, and unchanged HTML::Tree still passes 8/8 on both. + +### Eval, tied handlers, and native parser arguments (2026-10-27) + +- [x] Tied hash, array, scalar, and handle wrappers acquire distinct + `TIE_HANDLER` identities on independent handler snapshots. Repeated release + retires the owner once. A released snapshot remains borrowable while dynamic + localization restores magic; clearing its payload caused five observed + regressions, all now passing on both backends without sweeps. +- [x] Final container destruction releases magic and child slots independently + of temporary expression borrows. Ordinary lexical cleanup still protects + live aggregates. The final destruction path runs after resurrection checks. + Java coverage verifies hash/array child retirement and final tie release + without root queries. +- [x] JVM eval callback returns clean eval lexicals before returning to their + caller. Interpreter evals consume untargeted callback returns as successful + eval results rather than errors. Explicit return owners protect referenced + results throughout lexical cleanup, abandoned method arguments, invocant + release, and local restoration. Try/finally return paths now unwind lexical + registrations at each frame they leave, on both execution backends. +- [x] Scalar overwrite's external-root fallback cannot clear weak observers + while identified strong slots remain. This exposed an actual native-call + argument leak in `HTMLParser.fireEvent`: freshly owned event-data and call + arrays were never retired. Both arrays now release on success, exceptions, + and absent-method dispatch. Native parser containers use anonymous references + instead of inventing lexical bindings. Accumulated event arrays retain their + own contents until the program clears them. + +Permanent focused Perl coverage passes on standard Perl and both backends +with corrective sweeps off: + +| Regression | Assertions | +| --- | --- | +| `refcount/tied_handler_owner_release.t` | 13/13 | +| `refcount/eval_callback_return_owner_release.t` | 12/12 | +| `refcount/native_parser_callback_owner_release.t` | 9/9 | + +Unfixed failures were retained before the corrections. `TiedHandlerOwnerTest` +adds three Java cases for distinct identities, exactly-once retirement, magic +restoration borrows, and final child release. The latest focused comparison +gate passes in 1m36s: +`JPERL_ENABLE_CORRECTIVE_SWEEPS=1 JPERL_TEST_FILTER=refcount/ nice -n 19 make`. +Log: `/tmp/make-issue1649-native-parser-owner-batch.log`. + +Final direct default-off checks restore unchanged HTML::Tree to **8/8 on both +backends**. All eight existing `html_parser_*.t` regressions pass on both +backends. The preceding default-off reader batch also passes eval/map cleanup +(3/3), simple tied-hash destruction (2/2), explicit closure returns (6/6), +destructor exception/resurrection (11/11), and self-capture cycles (9/9). +The JVM tied-hash autovivification loop passes 6/6. Five compatibility +regressions exposed by clearing retired handler snapshots now pass on both +backends: `eval_tied_local_cleanup.t`, +`issue_1630_repeated_local_alias_io.t`, `signature_eval_tie_caller.t`, +`symbol_table_glob_identity.t`, and `tied_lvalue_sub_return.t`. + +### Conditional scopes and method holds completed (2026-10-27) + +Method invocant holds now have independent `ARGUMENT_VALUE` identities and +retire exactly once, including abandoned calls. Three Java cases cover distinct +holds, deferred final release, and immediate abandoned-call release without +reachability queries. + +The interpreter now closes condition-local scopes. Opcode 639 snapshots their +result before cleanup; the JVM likewise acquires conditional results before +retiring locals. Tied scalar, hash-element, and array-element lvalue results +retain their storage through the caller's STORE. Legacy capture correction +skips pads with identified capture owners. + +Standard Perl and both default-off backends pass the new conditional regressions +(12/12, 6/6, and 7/7). The original tied-hash autovivification regression now +passes 6/6 on both backends. Unchanged HTML::Tree remains 8/8 on both. + +The subsequent unfiltered default-off gate completed in 9m49s with eight +failures: three Perl acceptance cases listed below and five Java cases that +expect legacy sweeps. Log: +`/tmp/make-issue1649-method-conditional-final-full.log`. + +### Final CV state-storage cleanup completed (2026-10-27) + +Final CV destruction now detaches and retires persistent scalar, array, and hash +bindings after CODE destructor callbacks and the resurrection decision. A blessed +CV that resurrects keeps its original state until its final destruction. Escaped scalar cells and aggregates retain their values until their +own last owner ends. Persistent scalar cells are born with a binding rather +than being mistaken for ephemeral returned scalars. + +State aggregate refaliases own separate counted reference slots. Releasing a +CV retires those slots without ending the source aggregate's lexical binding. +Lazy definition adoption shares this ownership metadata with the state maps; +ithread cloning copies it with the cloned graph. + +Permanent regressions `refcount/closure_state_owner_release.t` (10/10), +`refcount/state_aggregate_alias_owner_release.t` (6/6), and +`refcount/blessed_code_state_resurrection.t` (10/10) pass standard Perl and +both backends with sweeps explicitly disabled. Unfixed-parent failures are +retained in `/tmp`. The final focused comparison gate passes in 2m35s: +`/tmp/make-issue1649-state-resurrection-final-batch.log`. Destructor exceptions, +true cycles, and unchanged HTML::Tree 8/8 also pass on both backends: +`/tmp/issue1649-state-resurrection-final-backend-results.txt`. + +The full default-off gate before the final CODE-destructor ordering correction +finished in 7m07s with the same eight known failures and no new failures from +state-storage cleanup. The final ordering correction received the focused and +backend checks above; another full gate remains required before publication. +Evidence: `/tmp/make-issue1649-state-storage-final-full.log` and +`/tmp/issue1649-state-storage-full-failures.txt`. + +Adjacent default-off checks preserve state refaliases, declared-reference list +identity, true self-capture cycles, CODE template lifetimes, and HTML::Tree 8/8 +on both backends. `state.t` passes the JVM; its interpreter failures at 6, 7, +and 13 reproduce on the saved pre-change JAR. Evidence: +`/tmp/issue1649-state-final-backend-results.txt` and +`/tmp/issue1649-state-parent-interpreter.log`. + +This completes state-storage retirement for CVs that actually reach final +release. Named CODE/glob lifetime accounting still prevents that transition in +the remaining named-state acceptance case. No remaining sweep or compatibility +bridge has been removed on the strength of these focused passes. + +### Named CODE-slot ownership completed (2026-10-27) + +One physical CODE slot now owns one counted `CODE_SLOT` identity. Whole-glob +names sharing its scalar share that edge; separate CODE slots have separate +identities. Saved localization, compiled-GV pins, and retained compiled-call +references keep the slot alive across namespace replacement or deletion. +Restoration releases the temporary slot after the saved slot is installed. + +Native CODE final release uses these counted identities instead of historical +stash counters or the discarded-closure root-walk correction. Capture attachment +preserves counts already acquired by named slots. Cache notifications no longer +acquire an extra owner during first assignment to an empty slot. Compatibility +root-index shape metadata survives capture retirement without retaining captured +values or influencing lifetime decisions. + +Interpreter frames borrow a stable self-reference for `__SUB__` and persistent +state operations. Undefining the executing glob therefore leaves its active CV +and state usable until the last frame returns. Thread snapshots reconstruct +tracked CV counts, scalar owner identities, and namespace/compiled-GV bindings +in the child runtime. + +Six `CodeSlotOwnerTest` cases cover independent and shared slot identities, +first assignment and replacement, localization, compiled pins, active calls, +and final release without reachability queries. Three new permanent Perl tests +pass standard Perl and both backends with corrective sweeps explicitly disabled: + +| Regression | Assertions | +| --- | --- | +| `refcount/named_code_state_owner_release.t` | 9/9 | +| `refcount/localized_code_state_owner_release.t` | 9/9 | +| `refcount/compiled_glob_state_owner_release.t` | 4/4 | + +The original `weak_deferred_capture_full_sweep.t` now passes 3/3 on both +backends. Existing glob redefinition, local alias restoration, current-sub map +and sort, glob identity, inheritance cloning, CODE resurrection, and unchanged +HTML::Tree 8/8 also pass on both backends. Evidence: +`/tmp/issue1649-code-pin-final-backend-results.txt`. +The focused comparison build passes in 1m33s: +`/tmp/make-issue1649-code-slot-pin-batch.log`. + +The final unfiltered default-off gate completed in 7m19s with **seven failures**: +the two existing shared-reference cases below and the five Java cases requiring +legacy sweeps. Named state teardown now passes in the full gate, reducing its +failure count from eight to seven. No new full-suite failure was introduced. +Logs: `/tmp/make-issue1649-code-slot-final-full.log` and +`/tmp/issue1649-code-slot-full-failures.txt`. + +Unfixed-parent evidence is retained for named-state release, the first-store +localization leak, and premature state destruction after stash deletion. +The earlier ownership work is preserved in WIP checkpoint `98e611e96`. + +This completes the named-slot retain/release paths tested here. Compiler +templates, per-optree retirement of compiled-GV pins, raw descriptor/embedding +borrows, and complete CODE producer ownership still need audit before the +compatibility bridge can be removed. The complete rewrite remains in progress. + +### Shared proxy and cloned weak-slot cleanup (2026-10-27) + +`SharedElementProxy` is now a local expression borrow; the destination Perl +slot owns the view. Final release clears weak observers on that local view +without cascading into canonical shared storage. + +Ithread snapshots install all cloned weak edges before draining the queued +capture-owner releases. This lets `DESTROY` rescue an existing weak hash slot +after the complete child graph is registered. Scope cleanup also retires +legacy scalar capture counts that have no explicit `SCALAR_CAPTURE` owner. +Async warning-handler retention uses its counted scalar owner, and PadWalker +rebinding records replacement scalar and aggregate captures with explicit owner +slots. + +The following regressions pass on both PerlOnJava backends with corrective +sweeps disabled: `threads_shared_nested_proxies.t` (10/10), +`threads_destroy_weak_slot_rescue.t` (3/3), `padwalker_set_closed_over.t` +(6/6), `direct_closure_padwalker_rebind.t` (3/3), +`custom_warning_async_suspend_state.t` (6/6), and +`refcount/io_async_loop_refcount_lifecycle.t` (2/2). The two deferred-capture +boundary Java cases also pass without sweeps. The two thread regressions also +pass their standard Perl oracle runs. + +Current-JAR requalification also passes `closure_capture_explicit_return.t` +(6/6) and unchanged HTML-Tree 5.07 `t/refloop.t` (8/8) on both backends with +sweeps disabled. Logs: `/tmp/issue1649-current-explicit-return-jvm.log`, +`/tmp/issue1649-current-explicit-return-interpreter.log`, +`/tmp/issue1649-current-html-tree-jvm.log`, and +`/tmp/issue1649-current-html-tree-interpreter.log`. + +Requalification after the scalar-reference return and lazy thread-snapshot fixes +passes the full sweep-enabled `make` gate. The full no-sweep gate completed +1,242 tests with only these three existing sweep-helper cases failing: +`ReachabilityQueryCostTest`'s two targeted weak-release checks and +`WeakBackrefCodeCaptureSweepTest`'s quiet weak-code capture walk. No Perl unit +test failed. The fallback scalar-reference guard, lazy thread-snapshot race, +and unchanged HTML-Tree 5.07 `t/refloop.t` each pass on both backends with +sweeps disabled. Evidence: `/tmp/make-issue1649-final-normal.log`, +`/tmp/make-issue1649-final-no-sweep.log`, and the corresponding +`/tmp/issue1649-*-no-sweep-verified.log` files. + +### Interpreter temporary closure owners retired + +Counted scalar owner slots now hold a weak link to their implementing scalar +cell. At interpreter frame exit, generated closures that are neither active nor +returned release unregistered CODE cells left in borrowed aliased `@_` arrays. +Registered lexicals, package slots, and container-owned CODE refs stay live. +The Catalyst request tempfile regression passes 2/2 on the interpreter with +corrective sweeps disabled; the filtered JVM unit test also passes. Logs: +`/tmp/issue1649-catalyst-interpreter-borrowed-code-cell.log` and +`/tmp/make-issue1649-catalyst-borrowed-code-cell.log`. + +### Temporary CODE argument slots counted + +Temporary closures placed in aliased argument arrays now acquire a counted +`ARGUMENT_VALUE` owner. Returning from the call releases that owner through the +normal scalar cleanup path. `cleanupOwnedArgumentAliases()` no longer uses a +root walk to decide whether to release the CV's captures. `CallArguments` +retains its materialized argument array until finish, so a call rejected before +callee entry also retires the owner; normal callee cleanup and this fallback +are idempotent on the same slot. + +`PerlClosureArgumentOwnerTest` verifies normal and abandoned-call release, the +slot identity, capture retirement, and zero reachability queries. The Perl regression +`issue_1649_temporary_closure_argument_owner.t` passes 5/5 on system Perl and +both PerlOnJava backends with sweeps disabled. The focused Java gate also passes +`PerlArgumentUnwindOwnerTest`, `PerlCallTransferOwnerTest`, and both deferred +capture boundary cases. Current-JAR requalification passes explicit-return +cleanup 6/6 and HTML-Tree 5.07 `t/refloop.t` 8/8 on both backends with sweeps +disabled. Evidence: `/tmp/issue1649-argument-owner-oracle.log`, +`/tmp/make-issue1649-argument-owner-materialized-final.log`, and logs with the +`/tmp/issue1649-argument-owner-materialized-` prefix. + +This closes the temporary CODE-cell argument path only. Aliased `@_` cells, +native buffers, escaping aliases, and the remaining return paths still need +explicit owner-slot accounting. + +### Direct scalar arguments staged through later expressions (2026-10-28) + +`CallArguments` gives each strong scalar return snapshot its own +`ARGUMENT_VALUE` slot until `finish()`. This keeps an earlier argument alive if +a later expression drains its return owner, and keeps a final scalar argument +alive through callee cleanup. Persistent caller cells remain borrowed so +assignment through `@_` can release their previous values normally. + +`CallArgumentsScalarStagingOwnerTest` covers a non-final mortal result, a final +mortal result, and a persistent caller cell. The default-off full +`nice -n 19 make` gate passes. Explicit-return cleanup passes 6/6 and +HTML::Tree 5.07 `t/refloop.t` passes 8/8 on both backends with corrective +sweeps unset. Evidence: `/tmp/make-issue1649-final-argument-owner-verified.log` +and files with the `/tmp/issue1649-final-argument-` prefix. + +This covers scalar return snapshots in direct call arguments. It does not +complete aliased `@_` cell ownership or shared and tail-call cleanup. + +Unresolved acceptance cases: + +- Escaping proxy/lvalue magic and other native call buffers still need explicit + ownership completion; compatibility borrows are not a substitute for strong + alias owners. + +The two targeted-walker assertions in `ReachabilityQueryCostTest` and the quiet +weak-code capture walk in `WeakBackrefCodeCaptureSweepTest` intentionally call +the diagnostic sweep helpers. Runtime cleanup requests now use a separate +corrective-sweep scheduler, which remains gated by the environment policy; the +default-policy test verifies that disabled runtimes do not queue or run those +requests. Keep the existing helper tests intact. + +Phase 2 remains in progress: the integer count is still the compatibility +bridge for these new identities, and argument ownership and other return paths +are not fully migrated. Passing the default-off suite does not establish that +every producer, alias, or cleanup boundary uses semantic ownership alone. + +### Explicit scalar-capture owner release + +Scope-exited scalar captures now use their `SCALAR_CAPTURE` owner slots to +identify each owning `RuntimeCode`. When every capture of a pad has an explicit +owner, cleanup checks the CODE owner ledger and releases ownerless closures +without building END or scalar root graphs. Pads with compatibility-only +captures still use the existing graph fallback. The Java regression +`CaptureOwnerReleaseWithoutWalkerTest` passes; the full sweep-enabled +`nice -n 19 make` gate passes, and HTML-Tree 5.07 `t/refloop.t` passes 8/8 on +both backends with corrective sweeps disabled. + +This removes root walks for migrated capture-owner decisions, but weak +referent candidate discovery and the weak-CODE capture graph are still +sweep-based. + +### Weak referents with explicit owner slots + +Quiet weak sweeps now check a referent's strong owner-slot ledger before +consulting the legacy captured-element proof. A candidate with an active slot +is preserved directly, so the weak-CODE capture graph is built lazily only for +aggregate candidates that still lack owner identities. The new +`WeakBackrefOwnerSlotFastPathTest` covers an array-element owner, while the +existing weak-CODE capture test continues to cover the legacy fallback. The +sweep-enabled full `nice -n 19 make` gate passes, and HTML-Tree 5.07 +`t/refloop.t` passes 8/8 on both backends with sweeps disabled. + +### Closure capture release with an explicit scalar owner (2026-10-28) + +When undefining one CODE scalar, cleanup now checks whether another active +owner-slot identity retains the CV before building a root snapshot. It excludes +the slot being overwritten, so final-owner release still retires captures +through the existing compatibility path. `CodeOwnerSlotReleaseFastPathTest` +checks that the first of two scalar owners releases with zero root queries and +that the final owner still releases the captures. The full sweep-enabled +`nice -n 19 make` gate passes. Ownerless CODEs without explicit identities +still use the root-walk fallback. + +### Package-root release from counted owner slots (2026-10-28) + +When a package-rooted blessed value reaches a transient zero during overwrite, +remaining counted owner-slot identities now repair the compatibility count +before the package-root walker runs. `PackageRootOwnerSlotFastPathTest` keeps a +weak observer alive through an undercounted overwrite, checks that the count +matches the remaining hash slot, and verifies zero root queries. The full +sweep-enabled `nice -n 19 make` gate passes. Values without counted owner slots +retain the existing root-walk fallback. + +### Localized CODE restore with an active owner slot (2026-10-28) + +Whole-glob restore now skips the scalar registry, live capture, and Perl-root +walks when a non-stash owner slot still retains the localized CV. The regression +`LocalizedGlobCodeOwnerSlotFastPathTest` models the legacy direct stash write, +keeps the CV active across restore, and verifies its captures survive with zero +root queries. The sweep-enabled full `nice -n 19 make` gate passes. CVs without +owner slots still take the compatibility checks. + +### Default-off full-suite acceptance (2026-10-28) + +Production cleanup callers now schedule corrective passes through a gated +runtime method. The direct helper APIs remain available to the existing +reachability-cost and weak-CODE capture tests, including the test that requests +one explicit quiet pass at a safe boundary. This keeps diagnostic coverage +while leaving corrective scheduling disabled by default. + +The full `nice -n 19 make` gate passes with both sweep-control variables unset: +212 test suites report 3,095 tests, zero failures, zero errors, and five +skips. `CorrectiveSweepDefaultPolicyTest`, `ReachabilityQueryCostTest`, and +`WeakBackrefCodeCaptureSweepTest` all pass. Against the same build, HTML::Tree +5.07 `t/refloop.t` passes 8/8 and `closure_capture_explicit_return.t` passes +6/6 on both backends with corrective sweeps explicitly disabled. Logs: +`/tmp/make-issue1649-no-sweep-helper-separation-retry.log` and files with the +`/tmp/issue1649-post-gate-` prefix. + +This qualifies the current default-off behavior; it does not remove direct +diagnostic walkers, the integer-count compatibility bridge, or the remaining +reachability fallbacks. + +### Tail-call release from counted owner slots (2026-10-28) + +`releaseTailCallArgElement` now restores a transiently undercounted referent +from its remaining counted owner slots before consulting the weak-referent +root walker. `TailCallArgumentOwnerSlotFastPathTest` models a tail-call +handoff with one surviving array-element owner and verifies that the weak +observer stays live with zero root walks. The default-off full +`nice -n 19 make` gate passes; `goto_tailcall_args_cleanup.t` passes 5/5 and +`goto_weakself_tailcall_refcount.t` passes 2/2 on both backends with sweeps +unset. System Perl passes the weak-self test; its tail-call cleanup test skips +because `Internals` is unavailable. Evidence: `/tmp/make-issue1649-tailcall-owner-fastpath.log`, +`/tmp/issue1649-tailcall-args-*.log`, and +`/tmp/issue1649-tailcall-weakself-*.log`. + +This avoids reachability walks when counted slots prove a surviving owner. +Tail-call arguments without counted slots still use the compatibility walker. + +### Deferred weak release from counted owner slots (2026-10-28) + +Ordinary deferred cleanup now restores the compatibility count from remaining +counted owner slots before asking the root walker for blessed referents. +`DeferredReleaseOwnerSlotFastPathTest` checks that one surviving scalar-cell +slot preserves its weak observer with zero root walks, and that releasing the +final slot still clears it. The unblessed aggregate snapshot path remains in +place to distinguish live Perl roots from stale scalar wrappers. The default-off +full `nice -n 19 make` gate passes. Evidence: +`/tmp/make-issue1649-deferred-owner-fastpath-corrected.log`. + +### Argument-owner ledger bypass for active-frame scans (2026-10-28) + +Deferred weak releases now consult counted owner slots before scanning active +`@_` arrays and staged argument frames for a matching referent. If a blessed +referent has another counted owner, ordinary deferred cleanup repairs the +compatibility count directly. `ActiveArgumentOwnerLedgerFastPathTest` verifies +that a persistent caller cell remains a borrowed alias, avoids the frame scan, +and still clears its weak observer when the final slot is overwritten. The +default-off full `nice -n 19 make` gate passes. Evidence: +`/tmp/make-issue1649-argument-scan-fastpath.log`. + +Uncounted compatibility aliases still use the referent scan; explicit alias +slot ownership remains unfinished. + +### Scalar overwrite recovery from counted owner slots (2026-10-28) + +When a blessed weakly observed referent reaches a transient zero during scalar +overwrite, `RuntimeScalar` now restores the compatibility count from surviving +counted owner slots before invoking nested-call or package-root reachability +fallbacks. `RuntimeScalarCountedOwnerRepairTest` verifies that a remaining +array-element slot preserves the weak observer with zero root queries, and +that releasing the final slot clears it. The default-off full +`nice -n 19 make` gate passes. Evidence: +`/tmp/make-issue1649-scalar-owner-repair-final2.log`. + +### Non-counted identities for staged and active argument cells (2026-10-28) + +`CallArguments` and active `@_` frames now attach `ARGUMENT_ALIAS` identities +only to durable Perl storage cells and already active argument aliases. These +identities follow reference assignments and weak/strong transitions without +changing Perl-visible `refCount`; overwrite and explicit `undef` defer a final +release while an alias is the only owner. Transient expression wrappers retain +their staged return ownership without being treated as caller cells. The alias +identity is recorded in the referent ledger but does not add a separate runtime +root; the active frame already owns its scalar cell. RuntimeBase keeps +constant-time counts for alias and counted slots so ordinary deferred cleanup +does not scan a referent's full owner ledger. + +`ArgumentAliasOwnerSlotTest` covers refcount neutrality, identity transfer from +primitive to reference values, weak-target lifetime through overwrite and +explicit `undef`, exclusion of transient wrappers, no extra runtime roots, and +retirement when a stale cell still points at a destroyed referent. The default-off +full `nice -n 19 make` gate passes. Evidence: +`/tmp/make-issue1649-argument-alias-frame-roots-final.log`. + +This covers durable scalar cells staged for calls and active argument frames. +The tracked `new_from_lol` lifecycle reproducer passes 4/4 on JVM; its +interpreter result (1/4) matches the committed parent `7ba27d774`, so those +three failures predate this change. The TreeBuilder lifecycle reproducer passes +4/4 on both backends. + +### Retire active argument identities when `@_` slots are removed (2026-10-28) + +Active argument-frame identities now retire when their matching array slot is +removed, replaced, cleared, or deleted through a subrange operation. The +element-list hooks cover indexed removal and Java's direct `removeFirst` / +`removeLast` paths. `ArgumentAliasOwnerSlotTest` checks duplicate aliases, +replacement, clearing, and exact one-time retirement when the frame later exits. +`nice -n 19 make` passes. With corrective sweeps unset, explicit-return +cleanup passes 6/6 on both backends and HTML-Tree 5.07 `t/refloop.t` passes 8/8 +on both backends. + +### Argument cleanup decisions use owner identities (2026-10-28) + +`hasActiveArgumentOwner` now checks only the `ARGUMENT_ALIAS` owner-slot count. +The fallback walks through active `@_` arrays and staged argument values were +removed, along with their recursive `CallArguments` referent scan. The +default-off full `nice -n 19 make` gate passes. Against that build, +`weak_nested_form_argument_lifetime.t` passes 29/29 and +`closure_capture_explicit_return.t` passes 6/6 on both backends; HTML-Tree +5.07 `t/refloop.t` passes 8/8 on both backends with sweeps unset. + +### Staged owners for nested list aggregates (2026-10-28) + +`CallArguments` now walks nested `RuntimeList`, `RuntimeArray`, and +`RuntimeHash` values and creates one `ARGUMENT_VALUE` owner for each strong +reference element. `CallArgumentsNestedAggregateOwnerSlotTest` verifies that +array and hash elements nested in lists each retain their own slot through +later argument cleanup and release at call completion. The default-off full +`nice -n 19 make` gate passes. Explicit-return cleanup is 6/6, nested-form +lifetime is 29/29, and HTML-Tree 5.07 `t/refloop.t` is 8/8 on both backends +with sweeps unset. + +### Shared and tail-call argument frame identities (2026-10-28) + +`ArgumentAliasHandoffOwnerSlotTest` verifies that a tail-call target frame gets +its own alias identity and releases it in LIFO order, and that overwriting a +shared scalar cell retires its identity exactly once. The default-off full +`nice -n 19 make` gate passes. With sweeps unset, `goto_tailcall_args_cleanup.t` +passes 5/5, `goto_weakself_tailcall_refcount.t` passes 2/2, and +`threads_shared_nested_proxies.t` passes 10/10 on both backends. + +### Tail-call frame identities and thread cloning (2026-10-28) + +Queued scalar decrements now capture their source argument-frame identity at +enqueue time. Tail-call cleanup matches that identity directly, while retaining +the existing direct-argument and bless-temporary cases. The new +`ArgumentAliasHandoffOwnerSlotTest` verifies copied arguments retain the source +identity in the pending queue and that thread cloning drops this execution-local +identity. `nice -n 19 make` passes; `goto_tailcall_args_cleanup.t`, +`goto_weakself_tailcall_refcount.t`, and `threads_shared_nested_proxies.t` pass +on both backends with corrective sweeps unset. + +### Weakening with a surviving explicit owner (2026-10-28) + +`WeakRefRegistry.weaken()` now skips `reachableOwnerCount()` when another +explicit owner slot remains. `PerlFinalWeakOwnerTest` verifies that weakening a +live lexical owner preserves the weak observer with zero scalar reachability +queries. The default-off full `nice -n 19 make` gate passes; with corrective +sweeps unset, explicit-return cleanup passes 6/6, nested-form lifetime passes +29/29, and HTML-Tree 5.07 `t/refloop.t` passes 8/8 on both backends. + +### Identities for untracked container referents (2026-10-28) + +Array and hash elements that strongly reference an otherwise untracked or +weakly-tracked referent now receive an `UNTRACKED_REFERENCE` slot identity +without promoting the compatibility `refCount`. The identity transfers when +the element is overwritten and retires on container clearing or scalar cleanup; +weaken/unweaken updates the same ownership record. `UntrackedReferenceOwnerSlotTest` +covers `-1` and `WEAKLY_TRACKED` referents and verifies their legacy counts stay +unchanged. The full default-off `nice -n 19 make` gate passes. With corrective +sweeps disabled, explicit-return cleanup passes 6/6, nested-form lifetime +passes 29/29, HTML-Tree 5.07 `t/refloop.t` passes 8/8, and representative +weaken, DESTROY, cycle, and resurrection tests pass on both backends. + +### Durable scalar-cell identities for untracked values (2026-10-28) + +Durable scalar cells now record one `UNTRACKED_REFERENCE` identity for a strong +value edge when the referent is still untracked or already weakly tracked. +This includes lexical cells, package roots, closure captures, CODE slots, and +array/hash element cells whose referents remain untracked or weakly tracked. +These identities leave legacy counts unchanged; anonymous nested aggregate +slots continue through their existing counted path. Assignment transfers the +same identity; lexical registration, replacement, scope exit, capture release, +container clearing, weaken, and unweaken refresh or retire it at their +ownership boundary. `UntrackedReferenceOwnerSlotTest` verifies the +untracked-to-weakly-tracked transfer and that a captured lexical keeps the +identity until its final owner exits. + +`nice -n 19 make` passes. With corrective sweeps disabled, both backends pass +explicit-return cleanup 6/6, nested-form lifetime 29/29, HTML-Tree 5.07 +`t/refloop.t` 8/8, `weaken.t` 4/4, `destroy.t` 15/15, blessed self-cycle 4/4, +and exception resurrection 11/11. + +### Weakening repairs counts from surviving owner slots (2026-10-28) + +When weakening exposes a transient undercount, `WeakRefRegistry` restores the +compatibility count from surviving counted owner slots before walking roots. +`WeakeningCountedOwnerSlotTest` covers the repair with zero root and +scalar-reachability queries. CODE weak-reference cleanup also needs to +distinguish live owners from compatibility pins and expired frame cells; the +next section records that migration. The full +`nice -n 19 make` gate passes. With corrective sweeps disabled, both backends +pass explicit-return cleanup 6/6, nested-form lifetime 29/29, weaken 4/4, +DESTROY 15/15, blessed self-cycle 4/4, exception resurrection 11/11, +Sub::Quote cleanup 8/8, and HTML-Tree 5.07 `t/refloop.t` 8/8. + +### Untracked referent weakening uses slot identities (2026-10-28) + +When an untracked referent has a durable `UNTRACKED_REFERENCE` owner slot, +`weaken()` now avoids the registry-wide corrective sweep and, for aggregates, +the initial root scan. Releasing its final owner queues targeted weak cleanup. +`UntrackedReferenceOwnerSlotTest` checks the no-sweep decision and final-slot cleanup +with corrective sweeps enabled. The focused owner-slot, unblessed-root, and +weak-CODE capture tests pass. `nice -n 19 make` passes; with corrective sweeps +disabled, both backends pass explicit-return cleanup 6/6, nested-form lifetime +29/29, weaken 4/4, DESTROY 15/15, blessed self-cycle 4/4, exception +resurrection 11/11, Sub::Quote cleanup 8/8, and HTML-Tree 5.07 `t/refloop.t` +8/8. + +### CODE weak-reference owners exclude compatibility pins (2026-10-28) + +Before relying on CODE owner slots, `WeakRefRegistry` retires eligible +frame-temporary scalar cells. It accepts remaining non-`CODE_SLOT` identities +as direct Perl owners. `CODE_SLOT` can represent a compatibility pin retained +after a glob is deleted; installed stash refs remain covered by the stash-root +checks. `WeakCodeOwnerSlotTest` verifies that a live lexical CODE slot skips the +scalar-root walk. The existing `subquote_defer_weak_cleanup.t` passes 8/8 on +both backends with sweeps disabled. `nice -n 19 make` passes in 8m14s. With +corrective sweeps disabled, both backends pass explicit-return cleanup 6/6, +nested-form lifetime 29/29, `weaken.t` 4/4, `destroy.t` 15/15, blessed +self-cycle 4/4, exception resurrection 11/11, Sub::Quote cleanup 8/8, and +HTML-Tree 5.07 `t/refloop.t` 8/8. + +### Package scalar roots get per-key owner identities (2026-10-28) + +Each package scalar table key now owns a distinct `PACKAGE_SCALAR_SLOT` +identity for its scalar cell. Replacing, removing, or clearing a key releases +that identity; aliases therefore keep separate identities. Ithread snapshots +rebuild the identities for their cloned scalar table. Package-rooted scalar +cells can now own untracked reference values without promoting the legacy +count. `UntrackedReferenceOwnerSlotTest` covers aliases, key removal, clone rebuild, +and cells already at the legacy destroyed sentinel. `nice -n 19 make` passes in +6m02s. With corrective sweeps disabled, both backends pass explicit-return +cleanup 6/6, nested-form lifetime 29/29, `weaken.t` 4/4, `destroy.t` 15/15, +blessed self-cycle 4/4, exception resurrection 11/11, Sub::Quote cleanup 8/8, +and HTML-Tree 5.07 `t/refloop.t` 8/8. + +### Tied handlers and staged values retain untracked referents (2026-10-28) + +Tied-handler values and staged call/return values now mark their owning scalar +cell as a durable strong slot. That lets the existing +`UNTRACKED_REFERENCE` identity represent their referents without promoting a +legacy `refCount`; release retires the identity once and defers any counted +decrement. Added owner-slot tests cover untracked values, weaken without a root +scan, and idempotent release. Runtime clone setup also tolerates rebuilding +these identities before the destination runtime is bound. The focused tied +storage and owner-slot Java tests pass, followed by the full `nice -n 19 make` +gate (6m30s). With corrective sweeps disabled, all eight lifecycle cases pass +on both backends, including HTML-Tree 5.07 `t/refloop.t` (8/8). + +### Untracked mortal return values release at caller boundaries (2026-10-28) + +Mortal return snapshots whose referents remain untracked or weakly tracked now +receive `UNTRACKED_REFERENCE` identities. Their release follows the existing +mortal mark stack, so nested frames cannot retire a caller's return value; +final owner release clears weak observers directly when corrective sweeps are +disabled. `MortalReturnUntrackedOwnerTest` passes both cases with sweeps +disabled and records zero root queries, snapshots, and scalar reachability +queries for final weak cleanup. The full `nice -n 19 make` gate passes in +6m17s. The sweep-disabled closure, weak/DESTROY, resurrection, cycle, +Sub::Quote, and HTML-Tree matrix passes on both backends; HTML-Tree +`t/refloop.t` is 8/8. + +### Package array and hash roots get per-key owner identities (2026-10-28) + +Each package array or hash key now owns a distinct `PACKAGE_AGGREGATE_SLOT`. +The global-map facade transfers or releases those identities for replacement, +key/value/entry removal, entry replacement, clear, and cloned runtime tables. +Final root release clears weak observers directly when corrective sweeps are +disabled. `SvREFCNT` keeps Perl's special `%^H` count by excluding its hidden +package-root identity. `PackageAggregateOwnerSlotTest` covers aliases, +replacement, clearing, clone reconstruction, and weak cleanup; related tests +now live in new test classes instead of modifying existing test files. +The full `nice -n 19 make` gate passes in 7m05s. With sweeps disabled, 16 +closure, weak/DESTROY, resurrection, cycle, Sub::Quote, and HTML-Tree cases +pass on both backends; HTML-Tree `t/refloop.t` is 8/8. + +### Weak CODE release uses direct owner identities (2026-10-28) + +Package-rooted array and hash cells now register their value ownership when +the aggregate is marked as a package root. `shouldKeepCodeWeakRefs` relies on +active owner slots after checking installed CODE slots, active frames, and +retiring stale frame temporaries. It no longer consults sweep-local live sets, +full-root snapshots, or scalar-root scans. `WeakCodeOwnerSlotTest` verifies +lexical and package-array CODE owners with zero reachability queries. The full +`nice -n 19 make` gate passes in 6m33s, and the 16-case sweeps-disabled +JVM/interpreter matrix passes, including HTML-Tree `t/refloop.t` 8/8. + +### Untracked container values refresh and retire owners (2026-10-28) + +Array and hash writes now refresh untracked scalar referent identities after +the element is installed. Copy construction refreshes only after the new +storage is assigned, and scope cleanup releases each identity before the +no-weak-reference fast return. Repeated cleanup leaves no stale identity. +`UntrackedReferenceOwnerSlotTest` covers raw and normal array/hash writes, +copy construction, removal, and scope exit without root or scalar-reachability +queries. Untracked array/hash referents still use the existing root proof on +their first weak transition; their native release semantics remain to be +migrated. `nice -n 19 make` passes in 9m55s. With corrective sweeps disabled, +the 16-case lifecycle matrix passes on both backends, including HTML-Tree +`t/refloop.t` 8/8. + +### Active lexical pads own aggregate cells (2026-10-28) + +Active lexical frames and top-level pads now keep owner identities for registered +array and hash cells. Lexical scope cleanup releases each pad identity after +aggregate cleanup, allowing weak observers to clear directly when corrective +sweeps are disabled. `ActiveLexicalAggregateOwnerSlotTest` covers both pad +types, and the UNITCHECK capture regression guards against releasing captured +children too early. The full `nice -n 19 make` gate passes in 8m02s. With sweeps +disabled, the UNITCHECK and lifecycle matrix passes on both backends, and +HTML-Tree 5.07 `t/refloop.t` passes 8/8 on both backends. The recursive +`new_from_lol` reduction still fails three interpreter assertions; this is the +known interpreter lifecycle gap tracked below. + +### Untracked aggregate values use explicit owner identities (2026-10-28) + +Durable scalar cells now attach `UNTRACKED_REFERENCE` identities to array and +hash referents as well as scalar referents, without promoting their legacy +counts. First weaken trusts direct uncounted slot identities, including active +lexical and package aggregate roots. Final release of a weakly-tracked aggregate +owner now performs direct destruction and cascading cleanup with sweeps disabled; +blessed aggregates run `DESTROY` before weak observers clear. The new +`UntrackedAggregateOwnerSlotTest` covers two independent scalar owners, lexical +and package roots, zero root queries, and blessed `DESTROY` ordering. The full +`nice -n 19 make` gate passes in 8m48s. With sweeps disabled, the UNITCHECK, +closure, weak/DESTROY/resurrection/cycle, Sub::Quote, and HTML-Tree `t/refloop.t` +8/8 tests pass on both backends. The recursive `new_from_lol` gap was caused by +interpreter scope cleanup emitting releases for captured outer pad registers. +`BytecodeCompiler` now excludes those registers from normal, explicit-return, +condition, and tail-call cleanup, matching the JVM backend. The +`issue_1649_recursive_builder_pad_release.t` regression passes 9/9 on both +backends with corrective sweeps disabled and on system Perl. An earlier +unfiltered `make` reported four JVM lifetime failures: +`catalyst_request_body_tempfile_lifetime.t`, +`file_temp_path_wrapper_lifetime.t`, +`inc_hook_generator_state.t`, and +`refcount/blessed_scalar_reference_contents_destroy.t`. The full no-sweeps +2026-10-29 `make` gate now passes; the AnyEvent listener test remains +environment-dependent because this host cannot allocate its loopback port. + +### Package-rooted untracked aggregate release (2026-10-29) + +When first weaken uses a package-root proof to preserve an untracked aggregate, +the temporary compatibility count now retires after its final untracked owner +slot leaves. `RuntimeScalar.undefine()` refreshes the scalar's owner identity, +and counted-slot promotion records the new owner before releasing the old one. +The new Java two-owner regression and Perl package-array/hash regression pass; +the six Perl assertions pass on system Perl and both PerlOnJava backends with +corrective sweeps disabled. The first-weaken root query now returns from the +owner-slot ledger before inspecting package edges; its regression records one +query and zero edges or nodes visited. The full no-sweeps `nice -n 19 make` +passes in 11m. HTML-Tree 5.07 `t/refloop.t` passes 8/8 on both backends, and +closure, weak, DESTROY, resurrection, and cycle regressions pass on both +backends with sweeps disabled. + +### JVM-live scalar registry is not Perl ownership (2026-10-29) + +The zero-count branch in `WeakRefRegistry.weaken` no longer uses +`isReachableFromLiveScalarRegistry` to rescue a referent. Tail-call cleanup +also stopped using that forced-GC registry scan. A Java-live wrapper in the +weak-key registry is not a Perl owner; durable scalar owners must be +represented by owner slots or another explicit Perl root. +`ScalarRegistryIsNotPerlOwnerTest` covers first-weaken cleanup, and +`TailCallScalarRegistryOwnershipTest` covers the released tail-call owner. +Async Future resume now checks the referent's counted or direct owner-slot +state, excluding temporary evaluation roots. Other sweep and reachability +callers still need to be migrated. `PerlStrongOwnerProofTest` covers counted, +untracked, and temporary owner slots; `FutureAsyncAwaitRuntimeTest` passes in +the full no-sweeps `make` gate. + +### Uncounted owner slots release without a root walk (2026-10-29) + +When weakening the final counted probe leaves an uncounted strong slot, +`WeakRefRegistry.weaken` now trusts that slot directly and transitions the +referent to `WEAKLY_TRACKED`. Releasing the final slot then clears weak +observers immediately, without a graph query or compatibility count. The new +`WeakUncountedOwnerSlotFastPathTest` checks the transition, zero root queries, +and final cleanup. The no-sweeps full `nice -n 19 make` gate passes in 10m30s. +The weak, DESTROY, resurrection, closure, and cycle matrix passes on both +backends; HTML-Tree 5.07 `t/refloop.t` passes 8/8 on both. + +### Untracked first-weaken avoids generic root fallback (2026-10-29) + +First weaken of an otherwise untracked aggregate now keeps the transitional +`WEAKLY_TRACKED` sentinel until a durable owner slot is installed, without +walking the general root graph. The narrow legacy package-root rescue remains +for aggregates already nested in a package global. Added +`UntrackedAggregateFirstWeakenFastPathTest` for the zero-query transition and +direct final-slot cleanup. The no-sweeps full `nice -n 19 make` gate passes in +10m34s; HTML-Tree 5.07 `t/refloop.t` passes 8/8 on both backends. + +### Counted scalar release trusts surviving uncounted slots (2026-10-29) + +When overwriting the last counted scalar reference leaves an uncounted owner +slot, `RuntimeScalar` now transitions a non-CODE referent to `WEAKLY_TRACKED` +directly. The final slot release then clears weak observers without a +package-root query. `RuntimeScalarUncountedOwnerRepairTest` covers the +undercount repair and final release with corrective sweeps disabled. CODE keeps +its native active-frame zero-count protocol; remaining root checks protect +owners that do not yet have slot identities. + +### Localized CODE release uses owner slots (2026-10-29) + +Restoring a localized glob now releases the displaced CODE and its captured +pads when no active frame or owner slot remains. The release path no longer +scans scalar registries or root graphs; the existing active-frame owner test +still protects executing CODE. `LocalizedGlobCodeOwnerReleaseTest` verifies +capture cleanup and zero root queries. The no-sweeps full `nice -n 19 make` +passes in 10m45s. The closure, weak-reference, DESTROY, resurrection, cycle, +localized-glob, and HTML-Tree `t/refloop.t` (8/8) matrix passes on both backends. + +### Uncounted owners defer zero-count cleanup without weak observers (2026-10-29) + +Scalar overwrite, deferred decrement, and tail-call release now recognize a +surviving uncounted aggregate owner slot before reaching root fallbacks. Final +slot release dispatches cleanup even when no weak observer exists. A separate +pending-release marker keeps this path distinct from legacy `WEAKLY_TRACKED` +values. `UncountedOwnerSlotZeroCountReleaseTest` covers all three paths and +verifies exactly one final cleanup with no root query. The scalar-overwrite +path still needs direct owner-slot coverage for scalar and IO referents. + +### Counted slots repair unblessed scalar overwrites (2026-10-29) + +`RuntimeScalar.setLargeRefCounted()` and `MortalList.processDeferredBase()` now +restore transient zeros from verified, current array/hash element slots for +unblessed referents; blessed referents keep the counted-slot path. The check +requires that the owner scalar still points at the referent and remains in its +recorded container. `CountedOwnerSlotRepairsUnblessedReferentTest` covers scalar +overwrite, and `DeferredUnblessedAggregateOwnerSlotRepairTest` covers deferred +release. Both verify no root query or snapshot and weak clearing after the final +slot leaves. Scalar-cell-only owners without container provenance still use the +root snapshot, so stale wrappers are not mistaken for live Perl roots. + +The full no-sweeps `nice -n 19 make` gate passes in 11m03s. Six lifecycle tests +pass 83/83 on both backends, and HTML-Tree 5.07 `t/refloop.t` passes 8/8 on both +backends with sweeps disabled. The existing scalar-wrapper snapshot tests also +pass in the full gate. + +### Tail-call cleanup trusts direct uncounted owner slots (2026-10-29) + +Tail-call release now defers final cleanup when a non-counted Perl owner slot +remains, including package scalar slots. Temporary runtime roots do not count as +Perl owners. `TailCallUncountedOwnerSlotFastPathTest` checks zero root queries +and cleanup after the package slot leaves. The no-sweeps `nice -n 19 make` gate +passed in 10m58s; the regression passed with no skips or failures. + +### Durable uncounted slots survive referent promotion (2026-10-29) + +An existing durable uncounted scalar slot now remains in the ledger when its +referent becomes tracked. Scalar overwrite and deferred release defer cleanup to +that slot instead of trusting a transient zero. Final release checks the exact +owning scalar and its container's Perl ownership, so a temporary argument array +cannot pin the referent after its frame ends. `PromotedUntrackedOwnerSlotTest` +covers package ownership and temporary-container cleanup. The no-sweeps full +`nice -n 19 make` gate passed in 14m59s. Blessed scalar contents, Catalyst +tempfile lifetime, closure cleanup, weak/DESTROY, exception resurrection, +weak-closure, and HTML-Tree `t/refloop.t` (8/8) passed on both backends. + +### Registered CODE owners skip a duplicate scalar query (2026-10-29) + +Void-discard cleanup now accepts registered container membership as direct +proof that a CODE scalar slot is live, without repeating the same check through +`ReachabilityWalker.isScalarReachable()`. `MortalizeRegisteredCodeOwnerFastPathTest` +asserts that cleanup performs zero scalar reachability queries and root walks. +The full `nice -n 19 make` gate passed in 21m18s with corrective sweeps disabled. + +### Captured scalar-cell owners repair transient undercounts (2026-10-29) + +Immediate scalar overwrite and deferred cleanup now restore an unblessed +referent count from its exact current scalar-cell owner when that cell has an +active capture slot whose CODE owner is still live. This avoids root walks for +captured scalar-cell ownership without treating conservative captures as Perl +owners. `CapturedScalarCellOwnerFastPathTest` covers both cleanup paths, checks +that root-query counters stay at zero, and verifies weak cleanup after the last +capture is released. The full no-sweeps `nice -n 19 make` gate passes in 14m02s. + +### Final scalar CODE owner releases captures from the owner ledger (2026-10-29) + +Overwriting the final scalar CODE owner now releases closure captures after +checking other scalar, stash, active-frame, transfer, and installed-global +owners directly. It does not trust a possibly inflated compatibility count or +walk the root graph. `FinalCodeOwnerCaptureReleaseFastPathTest` verifies the +final pad capture is released with zero root queries and snapshots. The full +no-sweeps `nice -n 19 make` gate passes in 13m16s. + +### Aggregate captures release from CODE owner identities (2026-10-29) + +Scope-exit cleanup now decides whether a captured aggregate's CODE owner is +live from owner-slot identities, ignoring a stale positive compatibility +count. Compiled regex callbacks now keep their CODE object through a typed +owner slot, so their captured pads survive until the regex releases that +callback. `ClosureAggregateOwnerIdentityReleaseTest` covers stale-count +release and retention by a scalar owner; the existing callback DESTROY test +covers callback lifetime. The legacy weak-backref graph walk remains for +captures that have no recorded owner identity. The no-sweeps full `make` gate +passed in 15m56s. The callback DESTROY test passed 3/3 on standard Perl and +both PerlOnJava backends; HTML-Tree `t/refloop.t` passed 8/8 on both backends. +The owner-slot regressions cover stale positive CODE counts and preservation by +live scalar and callback owners. + +### Non-captured scalar-cell owners repair transient undercounts (2026-10-29) + +Immediate overwrite and deferred cleanup now restore an unblessed referent +from verified current scalar-cell identities, including return, argument, and +CODE slots. The repair counts current scalar and aggregate owners together; +unrooted wrappers and capture counts without a live CODE owner do not prove +liveness. Focused regressions cover both cleanup paths, mixed owner families, +weak clearing, and zero root snapshots. The no-sweeps `nice -n 19 make` gate +passed in 10m41s. HTML-Tree 5.07 `t/refloop.t` passed 8/8 on both backends; +`make check-links` passed. + +### First-weaken package aggregate proof (2026-10-29) + +First weakening of an untracked package aggregate now validates its active +`UNTRACKED_REFERENCE` scalar owners directly, including whether each owner +still occupies a durable strong slot. This removes the root-reachability call +from that transition. The existing package-nested owner-slot tests pass as +part of the no-sweeps `nice -n 19 make` gate (11m53s), including the proof-only +query with zero graph edges and the final-owner weak-observer release. +HTML-Tree 5.07 `t/refloop.t` passes 8/8 on both backends with sweeps disabled. + +### Tail-call argument owner release without a root walk (2026-10-29) + +Tail-call argument release now finalizes from counted and uncounted owner +identities. The root-graph fallback is removed; a new regression confirms that +a Java-live scalar-registry entry cannot preserve the released Perl referent or +cause a root query. The test passes in the full no-sweeps `nice -n 19 make` +gate (13m06s); HTML-Tree 5.07 `t/refloop.t` passes 8/8 on both backends with +sweeps disabled. + +### Package scalar value slots for tracked referents (2026-10-29) + +A package scalar cell now records an `UNTRACKED_REFERENCE` identity for a +strong referent value when the cell has no counted owner slot. The identity +does not inflate the legacy count and is released with the package scalar slot. +A regression checks that an independent counted owner survives until its own +release. The full no-sweeps `nice -n 19 make` gate passes in 10m35s, and +HTML-Tree 5.07 `t/refloop.t` passes 8/8 on both backends with sweeps disabled. + +Live lexical array and hash cells with no counted owner slot also record an +`UNTRACKED_REFERENCE` identity for their current referent. The slot keeps a +tracked referent alive across another owner's release and clears weak observers +when the aggregate cell releases its final value owner. The new regression and +full no-sweeps `nice -n 19 make` gate pass (12m51s); HTML-Tree 5.07 +`t/refloop.t` passes 8/8 on both backends with sweeps disabled. + +### Package aggregate scalar-cell values (2026-10-29) + +Prepopulated package arrays and hashes now record an `UNTRACKED_REFERENCE` +identity when a value slot points to a scalar cell with no counted owner. The +new regression checks final weak clearing without root queries or snapshots on +both aggregate types. The full no-sweeps `nice -n 19 make` gate passes in 6m53s. +Package aggregate edges to array/hash referents and cross-container aliases +remain on the root-snapshot path. + +### Prepopulated package aggregate values that reference aggregates (2026-10-29) + +When a package array or hash becomes rooted with existing values, its scalar +cells now record an `UNTRACKED_REFERENCE` identity for array/hash referents. +Final value replacement clears weak observers without root queries or +snapshots. The identity is limited to cells present when the package aggregate +becomes a root; values inserted later and cross-container aliases retain the +root-snapshot fallback until their storage provenance is explicit. The new +array/hash regressions and full no-sweeps `nice -n 19 make` gate pass (9m30s). + +### Caller arguments preserve source scalar identity (2026-10-30) + +`caller()` now populates `@DB::args` with the selected frame's existing scalar +cells instead of copied wrappers. Writes through the debugger array therefore +reach the caller's variable, and source-cell cleanup releases the same owner +slot rather than leaving a detached untracked reference behind. Aliased package +arrays no longer promote their borrowed cells to package roots. + +The new `caller_db_args_alias_slot.t` regression passes under system Perl and +both PerlOnJava backends; it fails on the preceding JAR by leaving the caller's +value unchanged. The existing tied-args, freed-argument, DESTROY-capture, +zombie-reference, and failed-constructor weak-cache tests pass on system Perl +and both backends. The full no-sweeps `nice -n 19 make` gate passes, and +HTML-Tree 5.07 `t/refloop.t` passes 8/8 on both backends. + +### Undef releases one weakly tracked owner at a time (2026-10-30) + +`RuntimeScalar.undefine()` now checks the remaining Perl owner identities after +retiring the current cell's untracked owner. A weakly tracked referent stays live +while another owner slot remains; the final slot release clears weak observers +and performs cleanup. This fixes the unconditional cleanup in `undefine()` +instead of relying on a positive legacy count to hide that path. +`WeaklyTrackedUndefOwnerSlotTest` covers two independent lexical cells, and +`weakly_tracked_undef_preserves_other_owner.t` records the standard Perl +behavior. Both backend runs pass with corrective sweeps disabled. The no-sweeps +full `nice -n 19 make` gate passes in 11m55s, and HTML-Tree 5.07 `t/refloop.t` +passes 8/8 on both backends. + +### Package-nested aggregate cleanup uses owner identities (2026-10-30) + +The package-root compatibility count remains required by the existing +root-proof contract, but it now has a dedicated owner-slot identity. The +package element scalar slots remain the Perl ownership evidence; when their final slot +leaves, cleanup retires the compatibility identity and count before clearing +the weak observer. This makes the transitional pin explicit and exactly-once +instead of leaving it as an untracked positive count. A focused Java regression +checks pin identity, final-slot release, idempotence, and unweakened count +preservation; a Perl-level test records the package array lifetime oracle. The +root proof validates direct scalar-owner identities without traversing package +edges. + +### Interpreter return ownership precedes aggregate cleanup (2026-10-30) + +The interpreter previously prepared an explicit return value from scalar +cleanup opcodes. A subroutine with only an array or hash lexical skipped those +opcodes, so aggregate cleanup could release a returned closure's captures +before the closure acquired its return owner. The bytecode now prepares the +return owner once before any scalar, array, or hash cleanup, matching the JVM +backend's ordering. The existing `closure_capture_explicit_return.t` test +reproduces the interpreter failure and passes 6/6 on standard Perl, the JVM, +and the interpreter after the change, with corrective sweeps disabled. The +full no-sweeps `nice -n 19 make` gate passes in 12m47s. The related closure, +weak-reference, DESTROY, resurrection, and cycle matrix passes on both +backends; HTML-Tree 5.07 `t/refloop.t` passes 8/8 on both. + +### Growing recursive output avoids repeated live-root scans (2026-10-30) + +Added `issue_1860_growing_lexical_output.t`, a project-owned reproduction of +Data::Tumbler's recursive path/value/payload results accumulating in a lexical +output array. It passes 4/4 on system Perl and both PerlOnJava backends with +corrective sweeps disabled. `GrowingLexicalOutputOwnerSlotCostTest` grows a +256-row nested output graph while running the corresponding temporary-array +cleanup; its measured work is zero root queries, live/external snapshots, and +edges inspected, while weak observers stay live until the final output owner +is removed. The full no-sweeps `nice -n 19 make` gate passes in 12m39s. +Unchanged Data-Tumbler 0.010 `t/90-stress.t` generates all 65,536 results in +7.38s on the JVM backend and 11.20s on the interpreter; system Perl completes +it in 0.15s. + +### Mojolicious controller teardown follows callback owners (2026-10-30) + +Added focused #1794 coverage for controller destruction after a long-poll +response finishes, controller retention while a WebSocket is open, and release +of a controller captured by transaction callbacks. The three project tests pass +14/14 on system Perl and both PerlOnJava backends with corrective sweeps +disabled. `NestedUntrackedOwnerFinalCellCleanupTest` also passes 1/1: retiring +the nested cell slot preserves an independently counted owner and its weak +observer, which clears when that counted owner leaves. The no-sweeps +`nice -n 19 make test-unit` gate passes in 12m24s. Mojolicious 9.53 +`t/mojolicious/app.t` passes 459/459 and +`t/mojolicious/websocket_lite_app.t` passes 35/35 on all three runtimes. The +pre-fix baseline reproduces the controller teardown failure in both backends; +the WebSocket server-push suite also passes on that baseline, so the added +WebSocket case remains acceptance coverage rather than a reproduced failure. +The full `nice -n 19 make` gate still needs to run after this ownership batch is +complete. + +### Weak CODE capture walk removed from quiet sweep decisions (2026-10-30) + +Quiet weak-reference cleanup no longer builds `WeakBackrefCaptureSnapshot` to +preserve aggregate candidates by traversing captures from weak CODE referents. +Real closure captures already carry `CLOSURE_PAD`, `ARRAY_ELEMENT`, and +`HASH_ELEMENT` owner identities; the regular issue-1649 aggregate lifecycle +tests pass with corrective sweeps disabled on both backends. The weakly held +closure oracle also clears both CODE and captured target on system Perl and +both backends. Full `nice -n 19 make` passes in 7m59s. + +The snapshot helper remains reachable only through the post-DESTROY diagnostic +path in `MortalList.flush`; `WeakBackrefCodeCaptureSweepTest` currently asserts +those diagnostic walk counters. The production corrective sweep constant is +already disabled, so this gate compiled the removal but did not execute that +legacy sweep branch. Remove the remaining diagnostic walk when the test no +longer requires its internal counters. + +### Weakening retires stale untracked owner slots (2026-10-30) + +When the last counted owner is weakened, `WeakRefRegistry.weaken()` now +refreshes `UNTRACKED_REFERENCE` slots against their scalar cell's current +durable storage before preserving the referent. A cell whose container has +lost its Perl owner can no longer leave a stale slot behind and strand the weak +observer until a later sweep. `WeakeningPrunesStaleUntrackedOwnerSlotTest` +checks final weak clearing with zero root queries or snapshots. The full +`nice -n 19 make` gate passes in 8m08s; issue-1649 aggregate and closure-owner +tests pass on both backends, as does HTML-Tree 5.07 `t/refloop.t` (8/8 each). + +### Interpreter pad constants follow the published CV owner (2026-10-31) + +Lazy interpreter materialization left optree constant owner slots on the +temporary `InterpretedCode` wrapper, while the stable placeholder is the +Perl-owned CV. Transfer the direct and embedded pad-constant tree to that +placeholder on both the normal interpreter path and the VerifyError fallback. +The stale-positive-count cleanup check seeds a positive `refCount` in the Java +test to exercise this boundary; it is an invariant test, not evidence that this +scenario naturally leaves a positive count after the last owner exits. In +production, cleanup uses the remaining owner identities instead of treating the +compatibility count as another owner. The +`pad_constant_cv_owner_lifetime.t` oracle passes 10/10 on system Perl and both +backends with corrective sweeps disabled; the new Java owner-slot regression +also checks final pad-tree release with zero root queries or snapshots. The +full `nice -n 19 make` gate passes in 7m27s. HTML-Tree 5.07 `t/refloop.t` +passes 8/8 on all three runtimes. The #1860 growing-output regression and +Data-Tumbler 0.010 `t/90-stress.t` pass on system Perl and both no-sweeps +backends; the stress case generates 65,536 results in 6.56s on JVM and 10.76s +on the interpreter. The #1794 controller and WebSocket regressions pass on +system Perl and both no-sweeps backends. + +### Full upstream HTML::Tree 5.07 suite (2026-10-31) + +Ran all 23 test files from the [upstream HTML-Tree 5.07 distribution](https://metacpan.org/dist/HTML-Tree), +not just the previously extracted `t/refloop.t` fixture. System Perl passes +969 tests; `t/leaktest.t` skips because `Test::LeakTrace` is unavailable. +JVM and interpreter each pass all 23 files with corrective sweeps disabled +(988 TAP checks per backend). The bundled PerlOnJava `Test::LeakTrace` module +is a no-op stub, so its 20 `t/leaktest.t` checks are not leak measurements. +The target `t/refloop.t` remains 8/8 on system Perl and both backends. Logs: +`/private/tmp/html-tree-full-system-perl.log`, +`/private/tmp/html-tree-full-jvm-gate.log`, and +`/private/tmp/html-tree-full-interpreter-gate.log`. + +### Package-root nested weak-owner oracle (2026-10-31) + +Added `src/test/resources/unit/refcount/issue_1649_package_nested_untracked_weak_owner.t` +to exercise an untracked aggregate retained only by a package array, then release +that owner while checking weak-observer cleanup. The second scenario verifies +that `unweaken` creates a strong owner that survives package-array removal and +releases the weak probe only when that scalar is dropped. The test passes 7/7 on +system Perl and both PerlOnJava backends with corrective sweeps disabled; the +full `nice -n 19 make` gate passes in 6m55s with the test included. This records +the observable contract while the package-root compatibility pin remains a +migration bridge; it does not claim the bridge has been removed. + +### Cleared aggregate cleanup ignores legacy count as sole owner proof (2026-10-31) + +The cleared-aggregate scope-exit finalizer now checks current Perl owner +identities independently of `refCount`. A positive legacy count alone no longer +blocks final weak cleanup; temporary roots and the cached external-root proof +still preserve owners at boundaries that have not migrated. The regression +releases a nested untracked scalar owner, leaves a positive compatibility count, +and verifies the weak observer is cleared. The full `nice -n 19 make` gate passes +in 7m17s with the regression included. After this change, the full upstream +HTML-Tree 5.07 suite passes all 23 files and 989 TAP checks on both backends +with corrective sweeps disabled; `t/refloop.t` passes 8/8. The bundled +`Test::LeakTrace` stub makes HTML-Tree's 20 leak-test checks non-measurements. +The #1794 controller and WebSocket regressions pass 3/3 and 6/6 respectively +on both backends, and the #1860 growing-output regression passes 4/4 on both. +A focused post-change weak/DESTROY/resurrection/cycle matrix also passes all +8 fixtures and 68 assertions on each backend. + +The count of `5` in `finalCellCleanupReleasesNestedUntrackedOwnerDespiteLegacyCount` +is assigned directly by the Java test; it is an invariant check, not evidence +that normal runtime operations create that state. A Perl-level async reproducer +did expose a real ordering window: scope-exit finalization can run after a +counted owner slot is retired but before its queued decrement drains. RuntimeBase +now tracks queued owner releases through completion, and cleared-aggregate +finalization leaves those releases to decide the lifecycle transition. A focused +Java regression exercises this real queue path and passes in the full +`nice -n 19 make` gate. The async scope-exit oracle is now tracked as +`issue_1649_cleared_aggregate_async_scope_exit.t`; it suspends on a pending +Future, checks that the frame retains its weakly observed root, then verifies +weak clearing and one `DESTROY` after resume. It passes 3/3 on system Perl and +both no-sweeps backends. This is acceptance coverage for the real Perl cleanup +path; the queued-release ordering regression remains specifically covered by +`PendingOwnerReleaseFinalizationTest`. + +### Explicit returns cross try/finally wrappers (2026-10-31) + +The parser lowers `try/finally` through a synthetic `:lvalue` wrapper so the +expression can preserve aliases when its caller requests an lvalue. Two frame +exit paths missed that wrapper: ordinary rvalue returns skipped acquiring a +return owner because the wrapper is marked `:lvalue`, and non-local returns +could bypass lexical teardown before the enclosing subroutine resumed. The +compiler now snapshots rvalue returns before cleanup while preserving true +lvalue aliases. The JVM wrapper registers its lexical slots even when the +static cleanup heuristic would omit them. The interpreter's lexical register +metadata includes return-specific cleanup opcodes, and both `RETURN_NONLOCAL` +propagation and marker consumption retire the active frame's slots before +leaving it. JVM and interpreter call boundaries unwind their cleanup marks as +well. The focused JUnit regression checks weak-reference and `DESTROY` timing +on both backends, plus lvalue assignment through `finally`. A +`Try::Tiny` oracle validates the standard Perl lifetime contract; system Perl +does not parse PerlOnJava's `finally` syntax directly. +The focused unit gate and full `nice -n 19 make` pass; the full gate took +7m42s. With corrective sweeps disabled, HTML::Tree `t/refloop.t` passes 8/8 +on both backends. `make check-links` and standard Perl lifetime and lvalue +oracles pass. + +### Scalar overwrite uses owner identities (2026-10-31) + +`RuntimeScalar.setLargeRefCounted` now defers cleanup when any remaining +non-counted Perl owner slot proves the value is live, after refreshing the +untracked scalar-cell ledger and repairing current counted owners. This removes +the package-global reachability query from scalar overwrite. Production callers +no longer request corrective sweeps during scalar overwrite/undef, lexical +scope exit, or final weak-owner release; the explicit diagnostic helpers remain +for their focused tests. The first post-rebase compile caught duplicate +`RuntimeHashElementMap` mutator overrides from combining the cache and owner +reconciliation changes. The duplicate block is removed; the owner-aware Map +methods and collection views remain, and collection removal now reconciles the +same owner slot as direct removal. The first full gate then caught three missed +merge behaviors: Map mutators and entry/key views must disable stable-method +caching while retaining owner hooks, and an executing CODE with active frames +must defer final release at refcount zero until its last `ACTIVE_CODE` owner +leaves. Those source paths are corrected. + +Post-rebase validation on 2026-10-31 passes: the full `nice -n 19 make` gate +completed in 22m41s with Gradle limited to one worker for the busy host. Eight +focused lifecycle fixtures covering weaken, DESTROY, exception resurrection, +self-cycles, nested-form weak lifetime, explicit closure return, Sub::Quote +cleanup, and async scope exit pass 80/80 on each backend with corrective +sweeps disabled. The full upstream HTML-Tree 5.07 suite passes all 23 files +and 989 TAP checks on both backends; `t/refloop.t` is 8/8 on system Perl and +both backends. The async scope-exit regression passes 3/3 on system Perl with +standard `Future::AsyncAwait` 0.71 installed in a temporary local Perl library. +Logs: `/private/tmp/ownership-rebased-make-20261031-serial.txt`, files with +the `/private/tmp/ownership-rebased-{jvm,interpreter}-` prefix, +`/private/tmp/ownership-rebased-html-tree-full-jvm.log`, +`/private/tmp/ownership-rebased-html-tree-full-interpreter.log`, +`/private/tmp/ownership-rebased-html-refloop-perl.log`, and +`/private/tmp/ownership-rebased-async-scope-system-perl.log`. + +### DESTROY checks use current owner-slot identities (2026-10-31) + +Global-destruction resurrection checks now compare owner slots before and +after `DESTROY` and validate counted scalar and aggregate slots against their +current storage. Durable untracked scalar owners and optree constant pins are +recognized directly. Staged arguments, return transfers, argument aliases, +active CODE frames, temporary roots, and the weak-tracking compatibility pin +do not count as resurrection. Non-global DESTROY now validates current owner +slots as well; the legacy positive-count rule remains only when no owner-slot +identity exists. Detached scalar cells no longer survive on a stale count, +and neither path walks scalar roots to decide whether destruction should be +deferred. + +`DestroyOwnerSlotResurrectionTest` covers counted and untracked durable owners, +a detached counted cell, a temporary call argument, and non-global checks for +both live and detached counted cells. The focused Make gate and full serial +`nice -n 19 make` pass; the full gate took 22m17s. With corrective sweeps +disabled, #1794 controller release passes 3/3, the long-poll controller test +passes 5/5, and the WebSocket lifetime test passes 6/6 on both backends. The +#1860 growing-output test passes 4/4, tied-hash autovivification passes 6/6, +and both HTML lifecycle reproducers pass 4/4 on each backend. The latter +socket-based tests required extended access to enable loopback sockets. +HTML::Tree 5.07 passes all 23 files and 989 TAP checks on each backend, +including `t/refloop.t` 8/8. Its single `TODO` assertion remains marked TODO; +the bundled `Test::LeakTrace` stub does not measure leaks. Logs: +`/private/tmp/ownership-nonglobal-destroy-owner-full-make-20261031.txt`, +`/private/tmp/ownership-nonglobal-destroy-owner-20261031.txt`, +`/private/tmp/ownership-nonglobal-ext-{jvm,interpreter}-mojo-{controller,websocket}.log`, +`/private/tmp/ownership-nonglobal-{jvm,interpreter}-*-20261031.log`, and +`/private/tmp/ownership-nonglobal-htmltree-{jvm,interpreter}-*-20261031.log`. + +### Scalar-reference contents have retargetable owner slots (2026-10-31) + +Scalar-reference contents now use `SCALAR_REFERENCE_CONTENTS` owner slots +instead of a wrapper boolean and anonymous `refCount` adjustments. Each strong +wrapper has a stable slot identity; aliases to one mutable scalar cell share +one compatibility count. Replacing the cell's value retargets those slots, and +final direct or deferred release carries the slot provenance into counted +destruction. Global and lexical localization transfer the slot identity with +the saved scalar state. `DestroyDispatch` validates the owner wrapper, scalar +cell, and current referent before treating the slot as live. + +`PerlOwnerSlotScalarReferenceContentsTest` covers retargeting, alias release, +and deferred final release. Three Perl regressions cover returned scalar +references, mutable contents, and localized global teardown. The full +single-worker `nice -n 19 make` passes with corrective sweeps disabled in 23m; +all 30 focused ownership, #1794, #1860, weak/DESTROY/resurrection/cycle, and +async cleanup runs pass on both backends. HTML-Tree 5.07 `t/refloop.t` passes +8/8 on system Perl, JVM, and interpreter. Logs: +`/private/tmp/ownership-scalar-reference-full-make-20261031.log`, +`/private/tmp/ownership-scalar-reference-focused-status-20261031.txt`, and +`/private/tmp/ownership-scalar-reference-html-tree-refloop-{system-perl,jvm,interpreter}-20261031.log`. + +### Rescued-object cleanup checks owner identity (2026-10-31) + +After explicit undef, nested weak cleanup now checks live Perl owner identities +directly. The rescued-object queue and temporary evaluation roots do not count +as Perl owners, and this decision no longer walks external roots. The new +`RescuedObjectOwnerIdentityTest` covers durable package ownership and confirms +that rescued and temporary roots do not trigger root queries. + +The full single-worker `nice -n 19 make` passes in 22m56s. With corrective +sweeps disabled, 32 focused ownership, lifecycle, weak-reference, resurrection, +and cycle runs pass across JVM and interpreter. HTML-Tree 5.07 `t/refloop.t` +passes 8/8 on both backends. Logs: +`/private/tmp/ownership-scalar-rescue-owner-full-make-20261031.log`, +`/private/tmp/ownership-rescue-owner-final-status-20261031.txt`, and +`/private/tmp/ownership-rescue-owner-html-tree-refloop-{jvm,interpreter}-20261031.log`. + +### Suspended async frames retain lexical owner identities (2026-10-31) + +Before the active cleanup mark unwinds at `await`, the suspended interpreter +frame now records owner slots for its live lexical registers. Scalar-backed +slots follow reassignment and weakening; each slot leaves at lexical scope exit +or frame completion, failure, or cancellation. The final frame-owner release +rechecks cleared aggregate cleanup after any queued counted release is visible. +That lets async cleanup use exact owner identities without treating a stale +positive compatibility count as a reason to rebuild external roots. + +`ClearedAggregateOwnerIdentityNoRootWalkTest` requires immediate weak-observer +cleanup with zero root queries. `PendingOwnerReleaseFinalizationTest` confirms +queued decrements remain authoritative. The async scope-exit Perl fixture passes +on system Perl, JVM, and interpreter. The full single-worker no-sweeps +`nice -n 19 make` passes in 21m52s. Logs: +`/private/tmp/ownership-async-system-perl-current.txt`, +`/private/tmp/ownership-async-owner-jvm-final-20261031.log`, +`/private/tmp/ownership-async-owner-interpreter-final-20261031.log`, and +`/private/tmp/ownership-async-owner-identities-final-make-20261031.log`. + +### Tied-handler cleanup uses nested owner slots (2026-10-31) + +Deferred release no longer builds a tied-handler root snapshot. A handler's +`TIE_HANDLER` slot keeps the handler alive, while each value in its hash keeps +its own current `HASH_ELEMENT` slot. `TiedHandlerNestedOwnerSlotRepairTest` +models a legacy count undercount, drains the deferred release, and requires the +nested value to survive with zero root queries before its final hash slot +clears the weak observer. The final `nice -n 19 make` gate passed on +`59a4e03eb` in 7m50s with corrective sweeps disabled; `make check-links` +passed at that checkpoint. Full gate log: +`/private/tmp/ownership-tied-handler-no-sweeps-make-resumed-20261031.log`. + +The Perl-level companion `refcount/tied_handler_nested_value_owner.t` covers +the normal producer path: a tie handler's nested hash element owns the target +until `untie` releases the handler. It passes on system Perl, the JVM, and the +interpreter. `TiedHandlerNestedOwnerCountInvariantTest` asserts the normal +nested `HASH_ELEMENT` and scalar owner slots balance `refCount` before and +after first weaken, then checks zero root queries at untie. The filtered +`nice -n 19 make` gate passes in 1m15s; logs: +`/private/tmp/tied-handler-nested-owner-system-perl.log`, +`/private/tmp/tied-handler-nested-owner-jvm.log`, +`/private/tmp/tied-handler-nested-owner-interpreter.log`, and +`/private/tmp/tied-handler-nested-owner-focused-make.log`. +The final full no-sweeps `nice -n 19 make` including this fixture passed on +the immutable commit `cbebfc724` in 6m57s; log: +`/private/tmp/ownership-tied-handler-immutable-make-20261031.log`. + +The remaining `processDeferredBase` recovery paths still mix several owner +families. The next audit distinguishes the semantic edge from the fallback +that currently protects it: + +| Recovery path | Semantic strong edge | Remaining gap before removal | +|---|---|---| +| `restoreReachableOwnerCount` | Counted scalar-cell owner slots, formerly mirrored by `activeOwners`, including nested package-array cells | The audited array and hash mutation wrappers mark current storage; their main count-acquiring APIs do so after insertion. The remaining root-snapshot tests exercise earlier count acquisition: `ReachabilityQueryCostTest.deferredOwnerChecksShareOneRootSnapshotPerDrain` calls `incrementRefCountForContainerStore` before adding the scalar to the nested package array, leaving a `SCALAR_CELL` identity; `UnblessedAggregateReachabilitySnapshotTest.repeatedOwnerScalarChecksShareOneRootSnapshotPerDrain` also clears `containerOwner` directly. No production caller with this exact ordering has been identified in the call-site audit so far. These tests preserve the bridge for synthetic/out-of-order states and do not establish a normal store-path defect. | +| Scalar overwrite (`RuntimeScalar.setLargeRefCounted`) | The scalar cell's old referent edge; new edge is acquired before old release | Scalar-referent cells with a live uncounted lexical/package identity now defer zero-count cleanup to that exact edge. Counted scalar/aggregate slots still repair identified undercounts. External-root/live-CODE checks and the blessed weak-referent raw-count bridge remain for aggregate referents; trace their producers and final release before removal. `ActiveLexicalScalarOwnerLifecycleTest` covers overwrite and observer lifetime. | +| First weaken (`WeakRefRegistry.weaken`) | The scalar cell being weakened and any other current scalar, aggregate, or capture owners | Ordinary tracked owners use current counted-slot identities; general live-CODE and strong-root walks were removed from this path. Package-nested untracked aggregates now use exact `UNTRACKED_REFERENCE` identities without a compatibility pin or fabricated count. The cloned-thread snapshot root and direct CODE pad-constant check remain. `FirstWeakenUsesCurrentPackageOwnerTest`, `WeakeningCountedOwnerSlotTest`, and `PackageNestedUntrackedAggregateReleaseTest` cover current owner identities and weak-observer lifetime. | +| Unblessed aggregate root snapshot | Array/hash elements reachable through lexical or package storage | Normal slots have identities; parser assembly and compatibility mutation paths still need producer-level invariant coverage. `UnblessedAggregateReachabilitySnapshotTest` deliberately exercises the remaining fallback. | +| Strong-cycle graph walk | Internal scalar-reference and aggregate-element edges | The CODE weak-referent cycle walk has been removed; non-final CODE releases restore from verified current counted slots. Self-capture lifetime is covered on both backends. Audit uncounted cycle edge kinds and producer coverage before removing remaining cycle or cleanup recovery. | +| Deferred live/global CODE capture walk | Captured scalar cells, aggregate pads, and persistent CODE state | Persistent state cells and aggregates now carry `CODE_STATE` identities; closure captures use `SCALAR_CAPTURE` / `CLOSURE_PAD` slots. The deferred traversal and its unused live/global query helpers are removed. | +| Nested-call depth pin | Active argument aliases and compiler temporaries | Borrowed aliases and owned argument/return values must remain distinct through unwind and async suspension. | +| Blessed root snapshots and package cache | Package scalar, aggregate, glob, or CODE slots | Package scalar, array/hash, named IO glob, and CODE stash entries now have owner identities. Other glob components and compatibility writes still need producer audit before removing root snapshots. | +| Closure cleanup (`RuntimeCode.releaseCaptures`) | `SCALAR_CAPTURE`, `CLOSURE_PAD`, and aggregate capture slots held by live CODE | Scalar and aggregate referents use native `CLOSURE_PAD` owner slots. Captured pad cells retain `SCALAR_CAPTURE` identities. Closure release no longer queues a raw count decrement: counted cells and elements retire their own edges. Production aggregate capture builders attach owner slots; the public legacy capture API and `captureCount` bookkeeping remain under audit. Exception, nested-CODE, transfer, cloning, and async cancellation paths still need end-to-end owner proofs before graph fallbacks are removed. | +| Final destruction and resurrection (`DestroyDispatch`) | Current durable Perl owner slots, active CODE, and actual internal cycle edges | `processRescuedObjects` now retains objects with current owner identities instead of treating a count of one as a rescue pin. A real weak-slot rescue redispatches `DESTROY` after its final owner leaves; marker-only rescue still completes once. CODE cycle retention uses verified counted owner slots instead of a graph walk. The rescue registry and remaining producer paths still need audit. `DestroyOwnerSlotResurrectionTest` plus the new weak aggregate regression cover current durable slots without root walks. | + +This is an inventory, not evidence that these compatibility paths are safe to +delete. For each row, the next migration must fix acquisition, replacement, +and cleanup at the producer before removing its fallback. There are ten named +areas in the table; the deferred live/global CODE capture walk has since been +removed, leaving nine areas with producer or lifecycle questions. Several share +the same owner transitions and can be handled in a small number of batches. +This is an audit inventory, not a claim that nine independent live fallbacks +have been reproduced; recheck each row against current call sites as it is +migrated. + +### Package aggregate root lookup uses owner identities (2026-10-31) + +`GlobalVariable.isPackageRootedAggregate` now consults active +`PACKAGE_AGGREGATE_SLOT` identities for package array and hash roots, avoiding +map-value scans during lifecycle checks. Explicit root markers still cover +installation-time roots. `PackageRootOwnerIdentityLookupTest` verifies that the +identity alone proves liveness and that releasing the final slot removes that +proof. The immutable source `dd255e847` passes the full repository gate and the +HTML-Tree suite on both backends; the gate logs are recorded in the current +checkpoint above. `nice -n 19 make check-links` also passes (821 links checked). +This removes the package-table membership scan only; deferred +release, first-weaken, closure, and destruction graph fallbacks remain under +audit. + +### Single-value array replacement transfers the counted cell (2026-10-31) + +The deferred-root snapshot tests construct their legacy case by acquiring a +counted scalar owner before inserting it directly into an aggregate. The +ordinary `push`, list assignment, and hash-store producers establish container +storage before `incrementRefCountForContainerStore`, so they already classify +the counted owner correctly. `RuntimeArray.set(RuntimeScalar)` was an omitted +producer: it stored the same cell without acquiring/reclassifying its owner, +and left `elementsOwned` false. It now acquires the element owner after the +store, preserves any existing owner identity, and marks the array as owning the +cell. `RuntimeArraySingleValueOwnerTransferTest` forces an undercount and +requires current-slot repair with zero root queries; final cell overwrite must +clear the weak observer. The full `nice -n 19 make` gate passed in 7m35s, +including the regression (one test, zero failures); log: +`/private/tmp/ownership-array-single-value-owner-make-20261031.log`. + +### Cloned hash replacement releases the displaced slot (2026-10-31) + +`RuntimeHash.putClonedElement` previously wrote and acquired the replacement +directly, leaving any old value at the same key counted after it left the +hash. It now uses `storeOwnedElement`, which applies the same independent-slot +copy rules, installs the new owner before queuing release of the displaced +slot, and balances host-side graph construction. The regression +`RuntimeHashClonedElementReplacementOwnerTest` verifies that replacing the +final hash owner clears its weak observer and that the new slot remains alive +until removal. The full gate passed on source `c9572eb57` in 7m6s; log: +`/private/tmp/ownership-hash-clone-replacement-make-committed-20261031.log`. + +### Array removal preserves the slot identity (2026-11-01) + +When a localized array slot held a blessed reference, unwind removed the scalar +before checking whether the array owned it. The stale `elementsOwned` summary +was false, so the shared helper skipped the still active counted slot. Ordinary +`pop`, `shift`, and middle `delete` had the same ordering. Each path now +validates the current `ARRAY_ELEMENT` identity before mutation and transfers +that proof into deferred release. Borrowed `@_` aliases remain excluded because +they have no counted element identity. The regression verifies returned values +stay alive until dropped, weak observers clear after the final owner leaves, +and `DESTROY` runs once for each value. The unfixed parent fails 4/12; system +Perl and both PerlOnJava backends pass 12/12. Full validation passes on +`a0f50e758`. During this change, the existing +`issue_1646_blessed_io_handle_keeps_descriptor.t` exposed an argument-alias +misclassification: an active `@_` cell had an `ARRAY_ELEMENT` label but was +borrowed by the argument frame. The owner proof now excludes the current +argument alias, and both the focused and full gates pass. + +### Persistent CODE state bindings use owner identities (2026-11-01) + +Source commit `1c893a2bc` adds `CODE_STATE` slots for persistent state scalar +cells, arrays, hashes, and refalias cells. `StateVariable` acquires the slot +when it installs a per-CV binding; replacement acquires the new edge before +retiring the old one. Final state cleanup detaches maps before releasing their +owners, and definition adoption plus `RuntimeGraphCloner` rebind or reconstruct +the identities for the resulting CV. `MortalList.processDeferredBase` no longer +walks live/global CODE capture graphs for unblessed weak referents. + +`CodeStateAggregateOwnerSlotTest` proves deferred cleanup uses the direct state +owner without root queries and covers scalar, array, hash, and alias slots. +`RuntimeCodeStateGraphClonerOwnerTest` verifies cloned state storage receives +independent slots. `closure_state_owner_release.t` passes 10/10 on system Perl +and both backends with sweeps disabled; nine additional closure/state fixtures +also pass on all three engines. Parent and focused candidate evidence is listed +in the current checkpoint above. The full no-sweeps make passed on candidate +`b8ac7b1b9` in 6m20; log: +`/private/tmp/ownership-code-state-immutable-no-sweeps-make-b8ac7b1b9.log`. + +This retires one deferred reachability path. Blessed root snapshots, the raw +count bridge, and corrective-sweep scheduling still have unmigrated producers. + +### Closure aggregate release preserves current owner counts (2026-11-02) + +Every production aggregate-capture builder found in `SubroutineParser`, +`OpcodeHandlerExtended`, `RuntimeCode`, `RuntimeGraphCloner`, and `Internals` +records a `CLOSURE_PAD` owner slot. `RuntimeBase.retainClosureCapture()` has no +main-source caller. Its release path nevertheless queued a raw decrement when +the pad scope ended and a positive count remained, without identifying which +scalar or element had acquired that count. `LegacyClosureAggregateReleaseOwnerTest` +keeps a counted scalar owner live while a legacy capture exits and requires +closure cleanup to leave that count untouched. The test failed on the +unmodified runtime: the release processed one deferred base. + +The closure release now cleans the pad but leaves positive counts to their +acquiring slots. The focused shard passes on `ab4569170` in 6m15s, and the +full no-sweeps `nice -n 19 timeout 3600 make` passes in 7m28s. Parent and +candidate logs are listed in the current checkpoint above. This removes one +raw deferred-release producer; it does not complete the broader closure, +first-weaken, or lifecycle-fallback audit. + +### Package-rooted blessed parents retain nested owners (2026-11-03) + +`BlessedPackageOwnerRecursiveReleaseTest` models a blessed hash with an +untracked package-root owner and one counted outer-hash owner. The parent +contained a child observed through a weak scalar. On `dafb62d40`, clearing the +outer hash both prewalked the child's field and destroyed the parent: recursive +cleanup used `refCount == 1` as its last-owner proof, while deferred aggregate +cleanup checked for an untracked `REFERENCE` scalar and missed the parent's +`HASHREFERENCE` owner. The regression failed on that parent in the focused run +and was the sole failure in the 3,398-test serial unit gate (six skipped). + +The fix makes recursive field cleanup depend on the absence of current Perl +owner identities. Deferred finalization recognizes any untracked aggregate +reference type for blessed parents without direct weak observers; when direct +weak observers exist, their package-root proof still uses the root snapshot. +The regression verifies the child remains live while the package edge owns the +parent, then that removing the last package edge destroys the parent and clears +the child weak observer. The focused group passes all 19 tests, including the +existing snapshot-cost cases. The first full gate exposed four failures from +the broader owner shortcut. After narrowing it, the full no-sweeps gate passes +on immutable checkpoint `6c285e880`: 3,921 tests, 7 skipped, zero failures or +errors in 7m22. Log: `/private/tmp/issue-1649-fullmake-no-sweeps-6c285e880.log`. + +### Counted scalar-owner queries use the slot ledger (2026-11-03) + +`e93b73a16` removes `RuntimeBase.activeOwners`, the duplicate strong set of +scalar wrappers. Counted owner snapshots and counts now derive from each +referent's active counted `PerlOwnerSlot` identities, checking that the slot's +scalar still owns the same referent. `reachableOwnerCount` applies its existing +root proof to those same slot identities, including owners installed before +first weaken. `WeakRefRegistry` and `DestroyDispatch` no longer activate a +separate registry; `activateOwnerTracking()` remains a Java compatibility +no-op because existing tests call it. + +`0ff00785a` also updates reachability diagnostics to report counted slots +instead of the removed set. `CountedOwnerSlotLedgerTest` covers two scalar +owners installed before any weaken call. The complete no-sweeps `make` gate +passes on immutable `0ff00785a`: 3,941 tests, 7 skipped, zero failures/errors +in 7m27. Log: +`/private/tmp/issue-1649-owner-ledger-no-sweeps-0ff00785a.log`. +The ordinary `restoreReachableOwnerCount` root fallback remains; its producers +and final use cases still require audit before removal. + +### Next steps + +1. Keep the `restoreReachableOwnerCount` path isolated to its legacy unpaired + decrement hook. The call-site audit finds no production caller of + `MortalList.deferDecrement(RuntimeBase)`. Every production + `deferDecrementIfTracked` caller passes a `RuntimeScalar`, whose active owner + slot is captured in a `PendingOwnerRelease`; `RuntimeCode.releaseCaptures` + reaches that same scalar-aware path after retiring its capture slot. Thus + ordinary production cleanup does not enter `legacyUnpairedDecrement`. The + only production call to `ReachabilityWalker.isScalarReachable` is through + `restoreReachableOwnerCount`; the remaining root-based recovery branches in + `processDeferredBase` are likewise guarded by that legacy unpaired path. + `finalizeClearedAggregateOwnerAfterScopeExit` may issue a root query only + when query statistics are enabled, and ignores its result. `sweepWeakRefs` + overloads are compatibility no-ops. `sweepReleasedWeakReferents` still has + targeted root/cycle traversal and fixed-point weak-cleanup logic for direct + Java compatibility/test calls; a source call-site audit finds no production + callers. Keep that distinction explicit and retire the implementation only + after its direct callers and tests have a replacement contract. Ordinary + runtime cleanup no longer depends on graph sweeps. +2. Retain verified owner-slot count alignment while its producer gaps are + audited. This checks current scalar, aggregate, invocant, and native owner + identities directly; removing it previously failed lifecycle and Perl-level + owner tests. It is not reachability-based recovery. +3. Continue the remaining producer/release audit and batch any fixes with + focused coverage before rebuilding. The branch now includes current + `origin/master`; rerun the final no-sweeps gate and acceptance matrix on the + exact final commit after the audit. Recheck issue #1649 and PR #1938 before + publication; leave merging to review. diff --git a/dev/design/refcount-owner-ledger.md b/dev/design/refcount-owner-ledger.md index bf6907a7d4..e961ab9b9d 100644 --- a/dev/design/refcount-owner-ledger.md +++ b/dev/design/refcount-owner-ledger.md @@ -14,95 +14,112 @@ capture lifetime, cycles, and deterministic `DESTROY` behavior with system Perl. The implementation must distinguish real Perl ownership from JVM reachability and compiler-generated capture metadata. -Issue #1132 is the first delivery milestone. The complete design also replaces -remaining selective-refcount heuristics with explicit, auditable owner tokens. +Issue #1132 established the owner-ledger work. Issue #2043 is the current +delivery for removing lifecycle decisions based on memory sweeps; #1649 is its +historical origin. The design replaces selective-refcount heuristics with +explicit, auditable owner tokens. -## New Findings +## Current Status (2026-11-24 — resumed) -### Phase 1 owner-source inventory (2026-10-04) +**Delivery issue:** [#2043](https://github.com/PerlOnJava/issues/2043) -A strict source search across `src/main/java/org/perlonjava` finds 135 -non-comment lines that mutate `refCount` (17 `++`, 13 `--`, and 105 direct -assignments) and 36 lines that assign `refCountOwned`. This is a static source -inventory, not a runtime instruction count. It includes lifecycle/sentinel -transitions as well as ownership changes. +**Target PR:** [#1938](https://github.com/PerlOnJava/pull/1938) +**Goal:** deliver Perl-exact owner counts, weak-reference lifetime, and deterministic `DESTROY` behavior without memory-sweep lifecycle decisions. The current source candidate is `1d3e96f2a6`, integrating #2171 and the RSA key-size hardening into #1938. Stale Java tests for removed sweep, snapshot, and diagnostic internals were removed; `WatcherCleanupDoesNotTraverseLiveAggregateTest` adds behavior-level coverage for direct-slot watcher cleanup. `nice -n 19 timeout 1800 make` passes on this exact source commit in 8m11 (`/tmp/issue2043-1d3e96f2a6-make.log`). Net::SSLeay round-trip (29/29) and key-size bounds (10/10) pass on JVM and interpreter; full logs are under `/tmp/issue2043-*-1d3.log`. -| Owner or lifecycle path | Main implementation sites | Classification | -|---|---|---| -| Scalar and lexical slots | `RuntimeScalar.setLargeRefCounted`, `undefine`, `ReferenceOperators` | Counted strong stores can set `refCountOwned` and record an active scalar owner. Some references remain untracked (`refCount == -1`); promoted values can have earlier stores that were never recorded. | -| Array and hash elements | `incrementRefCountForContainerStore`, `RuntimeArray`, `RuntimeHash`, `RuntimeList` | Ordinary stored cells can acquire counted ownership. Alias arrays, borrowed copies, list materialization, and pop/shift/delete paths transfer or deliberately omit a count; the slot flag alone does not describe these transitions. | -| Package globals, stashes, and globs | `GlobalRuntimeScalar/Array/Hash`, `RuntimeStash`, `RuntimeGlob` | Globals and stash entries are strong Perl roots, but several paths use local-binding or root-map state instead of a matching scalar-owner token. Root membership must remain represented independently. | -| Closures and CODE | `RuntimeCode`, `RuntimeScalar` capture transitions, `BytecodeInterpreter`, `SlowOpcodeHandler` | Semantic pad ownership is distinct from conservative captures and temporary invocation holds. `semanticCaptureOwners` models captured pad cells; general `activeOwners` does not. | -| Temporaries and deferred release | `MortalList`, `RuntimeCode`, `DestroyDispatch`, `RuntimeBase` | Some holds are scalar-owned and deferred; others are non-scalar dispatch/rescue holds. Their count is temporary and cannot be treated as a persistent Perl slot. | -| Weakening, sweeping, and destruction | `WeakRefRegistry`, `ReachabilityWalker`, `DestroyDispatch` | `-1`, `WEAKLY_TRACKED`, and `Integer.MIN_VALUE` are tracking or lifecycle states, not owner cardinalities. Sweeps also adjust counts when reconciling stale ownership. | -| Tied, regex, I/O, and thread wrappers | `Tie*`, `RuntimeRegex*`, `runtime/io/*`, `RuntimeGraphCloner` | These classes have resource- or runtime-specific reference holds. Thread cloning reconstructs ownership for cloned cells; it cannot be inferred from the source cell's current flag. | - -This inventory confirms that neither `refCount > 0` nor `activeOwners` can -authorize skipping the AnyEvent weak-reference root walk. `refCount` combines -counted slots, untracked references, local-binding state, transient holds, and -sentinels. `activeOwners` is populated only after tracking activation and only -by selected scalar-store paths. The next audit pass must trace the exact -AnyEvent referent's owners through each owning storage class before choosing -any sweep shortcut. - -The latest unchanged `AnyEvent::Tools/t/02_rw_mutex.t` trace reports repeated -scope-exit requests for `RuntimeArray` targets with `refCount=2` and -`activeOwners=0`. A diagnostic scan of the scalar registry finds 4 to 13 -nonweak cells pointing at these arrays across successive requests; all show -`refCountOwned=false` and `captureRefCountOwned=0`. The cells include `$self`, -`$timer`, and captured `$t` values. Optional registration stacks include -assignments from `AnyEvent::Loop.pm` and the test's timer callbacks, as well as -array materialization paths. These are observed scalar holders, not verified -Perl owner tokens: the flags do not distinguish a shared pad, a temporary -alias, or a stale cell. The two counted references have not yet been traced to -their actual slots. Do not use the positive count or this holder list as a -fast-path until those ownership transitions are established. - -The original issue #1132 plan proposed adding one referent token for each -closure capture when the captured scalar did not already have a -`refCountOwned` token. Verification exposed two problems with that model: - -1. The focused issue reproducer captures a pad scalar that already has - `refCountOwned = true`. A borrowed-only token does not protect its referent - from a weak-reference sweep on either backend. -2. Adding one referent token for every closure makes the issue reproducer live, - but overcounts real Perl references. It regresses existing captured-scalar, - weak-callback, tail-call, and exact-refcount tests. -3. The existing `activeOwners` set is not an authoritative ledger. A referent - activates it only when `weaken()` is first called, and earlier - `recordActiveOwner()` calls are discarded while the set is null. The current - implementation avoids backfilling from `ScalarRefRegistry` because that - path regressed DBIx::Class leak tests. Thus an `activeOwnerCount()` of zero - can mean either “no counted scalar owns this referent” or “its stores - happened before tracking began.” It cannot justify skipping a complete - sweep. -4. In the failing HTML::Tree interpreter test, temporary instrumentation sees - two surviving `HTML::TreeBuilder` objects and two `HTML::Element` objects - after the first tree is dropped; their observer slots still report weak. - A minimal nested hash/array graph with a weak parent edge passes on both - backends, so the parity regression depends on the real parser construction - path. The weak edge itself is installed; the unresolved lifetime is an - extra strong owner or stale owner count. - -A system Perl oracle confirms that a lexical's referent count remains one when -one or two closures share that lexical: +PR #2171 merged as `fe8f9a3113b81b952c667cf7952a9961cf5573d8` after its Ubuntu/Windows builds and CodeQL checks passed. Investigation found that 1024-bit generation was retained only because the project-authored `netssleay_phase5_6.t` test said 2048 was slow; the bundled CPAN Net::SSLeay tests use 2048. The implementation now rejects RSA generation below 2048 bits in both Net::SSLeay and Crypt::OpenSSL::RSA. The round-trip and padding tests remain enabled at 2048, and the Net::SSLeay test guard now recognizes this checkout's `jperl-exec` launcher. CodeQL alert #3 remained on PR head `21dce7e11e`. Its SARIF flow showed low numeric constants passing through generic RuntimeScalar wrappers and `getDouble()` into the NetSSLeay parser, despite runtime rejection. Commit `1d3e96f2a6` parses the scalar string as a BigDecimal, validates the integer range, and removes that generic numeric flow before the JCE sink. Invalid values still become Perl `undef`. Fresh hosted CodeQL analysis is required to determine whether this clears alert #3. No #1938 review decision is recorded. -```text -lexical=1 -one_closure=1 -two_closures=1 -``` +The exact-candidate eight-target CPAN acceptance run completed. PPR, DateTime, Image::ExifTool, Excel::Writer::XLSX, and Template passed. Catalyst failed 2/3,477 assertions across 10 programs, matching the recorded current-master failure. DBIx::Class failed 1/43,020 at the known `t/storage/txn.t` source-line mismatch. Mojolicious failed 1/3,735 because `t/mojo/asset.t` could not fork (`Resource temporarily unavailable`), matching the known host limitation. Full output: `/tmp/issue2043-339bf5cd7a-cpan-acceptance.log`; per-target logs: `/tmp/cpan_random_logs/20261124-014723-8770/`. The run regenerated CPAN reports; preserve those files uncommitted. + +The three classified acceptance failures are tracked separately: [Catalyst's `role { ... }` parser ambiguity (#2168)](https://github.com/fglock/PerlOnJava/issues/2168), [Mojolicious host fork exhaustion (#2169)](https://github.com/fglock/PerlOnJava/issues/2169), and [DBIx transaction caller source locations (#2170)](https://github.com/fglock/PerlOnJava/issues/2170). + +The first full-master build at `ae3f87c122` failed the new installer-lifetime regression because reconciliation had dropped the interpreter file-optree and JVM noncapturing-CODE owner registrations. Cherry-picking `3776bfa487` restored those paths; the focused test and full `make` now pass on `28240779ea`. Gate output: `/private/tmp/issue2043-fullmaster-template-fix-make.log`; focused logs: `/private/tmp/issue2043-fullmaster-template-fix-installer-{jvm,interpreter}.log`. + +The eight-target CPAN acceptance rerun on source commit `316886c227` completed all target logs. DateTime passed 3,592 assertions; Image::ExifTool passed 113 files / 600 assertions; Template Toolkit passed 121 files / 3,180 assertions; PPR passed 1,255 assertions; and Excel::Writer::XLSX passed 1,247 files / 5,138 assertions. Mojolicious failed 37 assertions across 45 test programs because subprocesses could not fork under host resource pressure. Catalyst failed two assertions across ten test programs; the same `unit_core_plugin.t` and `unit_core_script_run_options.t` failures reproduce with the current-master JAR at `1ee4ff572d`. DBIx::Class had its single `t/storage/txn.t` source-line mismatch (expected 451, got 448 and 447), reproduced earlier on baseline `278c12be27`. Full output: `/private/tmp/issue2043-fullmaster-template-fix-cpan-acceptance.log`; per-target logs: `/tmp/cpan_random_logs/20261123-142534-68681/`. The run regenerated the three CPAN report files; keep them uncommitted. + +### Checkpoint and diagnosis + +The explicit-`exit` path previously ran END before active Perl frames retired their lexical owners. `WarnDie.exit()` now unwinds those registrations before flushing deferred releases and dispatching END. The new `dbix_schema_init_shutdown_lifecycle.t` passes on system Perl, JVM, and interpreter with DBICTest LeakTracer reporting no retained references. Full Make passes on the narrowed candidate; logs: `/private/tmp/issue2043-exit-unwind-final-make.log` and `/private/tmp/issue2043-schema-final-{perl-dbic,jvm,interpreter}.log`. + +The eight-target acceptance run on the preceding committed candidate `f012dac872` completed with Excel::Writer::XLSX, PPR, Template Toolkit, Catalyst, File::RandomAccess, and DateTime passing. Mojolicious failed one assertion in `t/mojo/asset.t`; DBIx::Class failed LeakTracer checks in `t/inflate/core.t`, `t/inflate/datetime.t`, and `t/relationship/core.t`, plus a transaction error-line mismatch in `t/storage/txn.t`. A separate master worktree passed upstream `t/relationship/core.t` (82 tests, LeakTracer clean), confirming that the relationship leak was a candidate regression. Its focused case used `set_producers([$producer], { attribute => 2 })` followed by an undirected relationship list. The root cause was that anonymous array references passed as arguments lacked the staged owner token already used for anonymous hashes. `RuntimeCode.CallArguments` now stages that owner; the new temporary-array and DBIx shutdown regressions pass on system Perl, JVM, and interpreter. Upstream DBIx `t/relationship/core.t`, `t/inflate/core.t`, and `t/inflate/datetime.t` now pass on JVM with clean LeakTracer checks. `t/storage/txn.t` still has a PerlOnJava error-line mismatch at test 89. + +The Mojolicious `t/mojo/asset.t` fork assertion fails on both the candidate and master JVMs with `Can't fork: Resource temporarily unavailable`; system Perl passes. This remains unclassified and is consistent with host process pressure. + +The final eight-target acceptance run on `11838413af` (`nice -n 19 timeout 28860 make test-cpan-release-acceptance`) passed Excel::Writer::XLSX, PPR, Template Toolkit, Catalyst, File::RandomAccess, and DateTime. DBIx::Class reports one assertion failure in `t/storage/txn.t` (expected source line 451, got lines 448 and 447); its three shutdown LeakTracer failures are resolved. Mojolicious `t/mojo/asset.t` still fails its fork assertion with `Can't fork: Resource temporarily unavailable`, as it did on master; this remains covered by the user's prior waiver. The acceptance build phase passed in 8m17 and regenerated the launcher JAR with SHA-256 `d34af367d8fc07806c55de82d6ecbd512073753cddcdf6661570255d6c8ce626`. Full output is `/private/tmp/issue2043-package-root-cpan-acceptance.log`; per-target logs are under `/tmp/cpan_random_logs/20261122-230238-55924/`. The generated compatibility reports now contain this run's updates and must be preserved. PR #1938 remains open at `75dd7d542f1f86bff930beb1c5779be74fa27955`, is DIRTY against current master, and has no human review. The source fixes, focused regressions, full Make gate, and upstream DBIx relationship/inflate leak tests are verified; the remaining acceptance failures are the existing transaction-line mismatch and waived Mojolicious fork limitation. + +### Permanent regression evidence -The closure retains the lexical pad scalar. The pad scalar, in turn, owns one -strong edge to its referent. Multiple closures sharing the pad do not each own -the referent independently. +The DBIx tests are permanent project-owned Perl tests under `src/test/resources/unit/refcount`: `diamond_prefetch_cursor_leak.t`, `diamond_prefetch_cursor_leak_permutations.t`, and `diamond_prefetch_shutdown_leak.t`. They require `DBIC_CLASS_TEST_ROOT` and skip cleanly otherwise. Before the proxy fix, JVM and interpreter each failed four weak-witness checks (Schema, Storage, DBH, combined), while system Perl collected the witnesses. With the candidate, all three project tests pass on JVM and interpreter; the shutdown case passes 768 functional checks and the permutation case passes 772 assertions. Standard Perl passes all three as well, and DBICTest LeakTracer reports no retained references. Upstream DBIx `t/prefetch/diamond.t` passes 768 assertions, `t/60core.t` passes 125 assertions, and `t/52leaks.t` exits 0 on JVM. Moo's `t/accessor-weaken.t` (19 assertions) and Template Toolkit's `t/string.t` (95 assertions) pass on JVM and interpreter. The full `jcpan -t DBIx::Class` run reached storage tests and timed out after one hour (exit 124). Earlier candidate runs of all 12 `t/resultset/*.t` files found shutdown leaks in `plus_select.t` and `rowparser_internals.t`; a scoped reproduction isolated the JVM-only inflated-result lifetime issue to `Relationship::Base::catch`. The frame-exit fix described above resolves those failures: all 12 resultset files now pass on JVM, and LeakTracer reports no retained references in each. The system-Perl resultset sweep passes 11 files; its three `update_delete.t` SQL execution-status mismatches are unrelated to leak witnesses. The interpreter resultset sweep passes 7 files; five exceed 600 seconds and remain unclassified. Current and historical evidence is retained in `/private/tmp/issue2043-resultset-*` and `/private/tmp/issue2043-latest-dbix-*`. Devel::FindRef is unavailable because its distribution requires XS and cannot be installed by `jcpan`. -The current reachability walker deliberately excludes captured and -scope-exited scalars to avoid treating conservative captures as Perl roots. -Consequently, a weak sweep can destroy an issue #1132 referent even while the -captured pad retains a positive selective count. The fix therefore requires an -authoritative ownership distinction, not broader walking or unconditional -capture increments. +The exception-unwind regression passes on system Perl, JVM, and interpreter. It fails on the unfixed `aebe3b0742` source (the JVM reports `first` before `second`) and passes on the current candidate. The complete `nice -n 19 timeout 900 make` gate passed after adding it (all five unit shards, Joni, and home integration). A full Make run on the unfixed baseline failed 11 other JVM unit assertions across three shards; the focused regression result is separately captured in `/private/tmp/issue2043-unfixed-lifo-direct.log`. + +`nested_untracked_aggregate_owner_release.t` adds six system-Perl-validated checks for nested array/hash release, a surviving shared owner, weak observers, and destructor rescue. It passes on JVM and interpreter. Ordinary final array/hash cleanup now retires direct element owners and lets final child-container release cascade through that container's own slots; it no longer allocates `RecursiveAggregateReleaseWalker` worksets or probes descendants with `CleanupTargetProbe`. Scope-exit's existing liveness guards and one-level eligibility checks remain, as does `CleanupTargetProbe` for global destruction. The package-array root-marking fast path and paired performance/allocation evidence are recorded under Current Work; the measurements cover the Excel workloads and do not claim a portfolio-wide effect. + + +The latest Excel::Writer::XLSX 1.15 run covered all 1,247 distribution test files against the rebuilt candidate: 1,246 passed and the optional `t/utility/xl_parse_date.t` was skipped because Date::Manip and Date::Calc are unavailable. The first `jcpan -t` batch reached its one-hour timeout without failures; a correctly scoped MakeMaker batch passed the remaining 498 files (4,276 assertions), and the optional test was run separately to record its skip. Logs: `/private/tmp/issue2043-excel-writer-xlsx-final-candidate.log`, `/private/tmp/issue2043-excel-writer-xlsx-final-resumed.log`, and `/private/tmp/issue2043-excel-writer-xlsx-final-optional.log`. + +With the latest launcher JAR and the installed DBIx::Class 0.082844 dependency tree, all three focused `diamond_prefetch_*` issue tests pass on JVM and interpreter: `/private/tmp/issue2043-latest-diamond_prefetch_cursor_leak.t-{jvm,interp}.log`, `/private/tmp/issue2043-latest-diamond_prefetch_cursor_leak_permutations.t-{jvm,interp}.log`, and `/private/tmp/issue2043-latest-diamond_prefetch_shutdown_leak.t-{jvm,interp}.log`. + +The `chart_axis28.t` workload was measured against an isolated before artifact that retains the recursive release walker and the same other current-source changes. Seven randomized persistent-worker pairs each passed the normalized XLSX checksum; all pairs passed the warmup stability limits with observed nice 19. Candidate/before throughput geometric mean is 0.970, with bootstrap 95% interval [0.869, 1.075], so this test does not show a reliable end-to-end gain. Diagnostic counters for 100 workbook writes show aggregate release walkers/worksets 9,298→0, release roots 26,537→0, recursive-probe worksets 3,888→1, and probe roots 14,574→184; owner-slot visits changed 6,349,994→6,343,314. Queue counters are also captured: transient RHS appends/drains are 13,294/13,294 on both artifacts, with 19,213 handoffs; frame queues allocate 6 and reuse 5,441 times; boundary queues allocate 0 with 14,241 marks; entry/boundary buffer growths are 14/13 on both. Separate JFR allocation samples total 7.804 GB before and 7.808 GB candidate; this sampled total is effectively unchanged and does not support an allocation-reduction claim for that change alone. Reports and raw profiles: `/private/tmp/issue2043-chart-axis-persistent-paired.json`, `/private/tmp/issue2043-chart-axis-before.jfr`, `/private/tmp/issue2043-chart-axis-candidate.jfr`, and the corresponding `*-diag-*.json` files. The baseline full Make gate failed only `ReachabilityQueryCostTest.repeatedContainerScopeCleanupDoesNotEnumerateNestedStashRoots`, which is the expected scan-count difference; all candidate shards pass. + +The same paired workload was repeated on the latest source and launcher JAR (`f0a5437ed9a1db3ae11720b0831b4818ff99ba71c460062ea6e049ff0d1bb9f0`) with seven stable, checksum-matched pairs and worker niceness 20. Candidate/before throughput geometric mean is 0.993, with bootstrap 95% interval [0.886, 1.128]. This interval also includes no change, so the latest candidate has no demonstrated end-to-end speedup on this workload. The first rerun had no effective low-priority setting and was excluded. Valid report and logs: `/private/tmp/issue2043-chart-axis-persistent-paired-latest-nice.json`, `/private/tmp/issue2043-chart-axis-paired-latest-nice.log`; excluded run: `/private/tmp/issue2043-chart-axis-persistent-paired-latest.json`. + +A broader persistent-worker profile wrote three checksum-identical workbooks, each with four 30-row data sheets, formulas, formatting, tables, conditional formatting, merged cells, and a chart. The same output hash was produced by both JARs. Elapsed time was 86.14s before and 87.06s on the candidate; this is a single diagnostic profile and does not establish a slowdown or speedup. Lifecycle counters changed from 2,447 aggregate walkers / 6,791 roots / 4,274 probe roots to 0 / 0 / 112, while owner-slot visits stayed nearly flat (3,781,284→3,779,397). JFR execution samples were dominated on both artifacts by `IdentityHashMap.containsKey` through `RuntimeScalar.markPrepopulatedPackageAggregateOwner` and `GlobalVariable.markPackageGlobalRoot`; allocation samples were led by `IdentityHashMap.init`. This identifies a separate package-root marking hotspot for further source-path and mutation audit; no change has been made from this profile alone. Artifacts: `/private/tmp/issue2043-excel-broad-profile-v2.json`, both `/private/tmp/issue2043-excel-broad-v2-{before,candidate}.jfr` recordings and their `*-diag-*.json` files. The initial 300-row worker exceeded its 120s timeout; the reduced workload was smoke-checked with system Perl and completed on both JARs. + +The next narrow allocation change makes `WeakRefRegistry.releaseDetachedUntrackedReferenceOwners` iterate the existing untracked-owner index instead of allocating and filtering a snapshot of every owner slot. Full `nice -n 19 timeout 1800 make` passes on `339bf5cd7a` (`/tmp/issue2043-339bf5cd7a-make.log`). Seven randomized persistent-worker pairs on `chart_axis28.t` have stable warmups, matching workbook checksums, and observed nice 20; candidate/before throughput is 1.074 with bootstrap 95% interval [1.061, 1.088]. JFR allocation sample weights changed from 8.126 GB to 7.617 GB overall (about 6.3% lower), from 257.5 MB to 203.3 MB for `IdentityHashMap`, and from 22.3 MB to 1.4 MB on stacks beginning with `ownerSlotSnapshot`. These are sampled weights, not exact allocation totals. The paired report is `/private/tmp/issue2043-untracked-index-paired.json`; the exact JAR hashes and raw profiles are recorded there and in `/private/tmp/issue2043-untracked-index-{before,candidate}.jfr`. + + +### Completed milestones + +| Date | Delivered scope | Evidence | +|---|---|---| +| 2026-11-19 | Cached hot owner-kind counts, narrow identity indexes, and reusable cleanup/probe worksets | Owner-ledger unit gate passed; earlier performance measurements remain inconclusive and are not a broad speedup claim. | +| 2026-11-19 | Correct nested hash-slot `B::REFCNT` reporting during `DESTROY` | System-Perl-validated regression; DBIx `t/60core.t` and `t/101populate_rs.t` passed. | +| 2026-11-21 | Retain interpreter foreach source owners through normal and `last` exits (`4edc5faa51`) | System Perl, JVM, interpreter, and focused DBIx diamond regression passed. | +| 2026-11-21 | Release overwritten temporary call-argument owners, including Test2 Amnesty facets (`eb8907f362`) | System Perl, JVM, and interpreter regressions passed; source build succeeded. | +| 2026-11-21 | Restore eval/die `DESTROY` LIFO ordering and the owner-trace snapshot prefix | System Perl, JVM, and interpreter checks pass; filtered refcount Make shard passes on the current candidate. These edits remain uncommitted and are not full acceptance. | +| 2026-11-21 | Repair weak-tracked scalar storage, raw untracked slots, legacy count adoption, and async foreach owner restoration | Full `nice -n 19 timeout 900 make` passed all five shards, Joni, and home integration on the tested working tree; focused lifecycle Perl tests passed on JVM and interpreter. | +| 2026-11-21 | Cascade ordinary aggregate cleanup through direct outgoing storage slots | `nice -n 19 timeout 900 make` passed all five shards, Joni, and home integration after restoring scope-exit eligibility guards; new nested untracked aggregate test passes on system Perl, JVM, and interpreter. No performance claim yet. | +| 2026-11-21 | Complete Excel::Writer::XLSX 1.15 test surface in two bounded batches | Across the original CPAN run and resumed `make test TEST_FILES=...`, all 1,247 discovered tests have results: 1,246 pass and one optional `xl_parse_date.t` skip for missing Date::Manip/Date::Calc. No test failures. Candidate JAR SHA-256: `59e46391b0836faa350ce71ad86e312d9b138565cd66f41f51bdcaeaa58313b0`. | +| 2026-11-22 | Measure direct-slot cleanup against its isolated recursive-walker baseline | Seven stable, checksum-matched pairs complete. The interval includes no change; lifecycle counters show walker/workset/probe reductions, while total sampled JFR allocation weight is unchanged. No speedup claim. | +| 2026-11-22 | Remove ordinary scope-exit pre-scans and preserve tied-array cleanup behavior | Full `make` passes in 7m13; new ownership, tied-array, and taint tests pass on the applicable backends. JAR SHA-256 is recorded below. | +| 2026-11-22 | Repeat paired `chart_axis28.t` measurement on the latest JAR | Seven stable, checksum-matched pairs at nice 20; throughput ratio 0.993, bootstrap 95% interval [0.886, 1.128]. No reliable end-to-end gain. | +| 2026-11-22 | Profile a broader multi-sheet Excel workload against before and latest JARs | Three matching workbooks per artifact; lifecycle walker/workset counts 2,447→0 and probe roots 4,274→112. Single-profile elapsed times are nearly equal; JFR points to repeated package-root marking as a separate hotspot. | +| 2026-11-22 | Separate runtime-only eval captures from semantic closure owners | New regression passes on system Perl, JVM, and interpreter; DBIx row-parser shutdown repro reports no leaks on both PerlOnJava backends. Full Make passes after the runtime change. | +| 2026-11-22 | Add focused coverage for DBIx inflated `+select` result shutdown | The regression first exposed four JVM DBIx Storage/Schema/DBH shutdown leaks. The JVM frame-exit fix resolves them; the project regression passes on system Perl and both backends with no LeakTracer-retained references. | +| 2026-11-22 | Run the full repository gate after adding both DBIx regressions | `nice -n 19 timeout 900 make` passes in 8m01 (`/private/tmp/issue2043-make-with-dbix-regression.log`). The optional external DBIx tests were run separately with `DBIC_CLASS_TEST_ROOT` set. | +| 2026-11-22 | Revalidate the resultset section after the JVM frame-exit fix | All 12 upstream resultset files pass on JVM with no retained references. System Perl passes 11; interpreter passes 7 and has five 600-second timeouts. The current full repository gate passes in 7m16. | + +The latest full gate, `nice -n 19 timeout 1800 make`, passed in 8m33 on commit `11838413af` (`/private/tmp/issue2043-package-root-make.log`). It completed all five Java/Perl unit shards, Joni tests, home integration tests, and `PackageArrayRootMarkingFastPathTest`. That build's launcher JAR SHA-256 was `dada35bd36b0a0346604193d4ee924664e25f4fb886bf69f1981021854d37404`; the later acceptance build regenerated the same source commit's JAR as recorded above. + +The current-master baseline `nice -n 19 timeout 900 make` passed at `506371c134` in 6m50 (`/private/tmp/issue2043-master-baseline-make.log`). The pre-edit candidate run at `aebe3b0742`, `JPERL_TEST_SHARD=0 nice -n 19 timeout 900 make`, reported 11 Java test failures in 5m52 (`/private/tmp/issue2043-pre-edit-shard0-make.log`). The ten failures in the later full candidate gate and the one extra pre-edit reachability-query failure are resolved on the current working tree. The latest full gate also completed the thread-shared queue clone test without reproducing its earlier `ConcurrentModificationException`. + +Direct runs against the final rebuilt JAR passed `destroy_eval_die.t` (10/10), `issue_2043_nested_aggregate_destroy_lifo.t` (2/2), `list_assignment_hash_tail_releases_displaced_owner.t` (5/5), `owner_trace_snapshot.t` (3/3), and `issue_2043_interpreted_foreach_source_lifetime.t` (7/7) on JVM and interpreter. The full repository gate does not replace DBIx acceptance with that dependency available. + +### Remaining acceptance work + +| Area | Evidence | Next action | +|---|---|---| +| Excel::Writer::XLSX performance and allocation evidence | The package-array root scan comparison on `11838413af` showed 11.92× throughput on `chart_axis28.t` and 6.64× on package-array reads against exact parent `2362185545`. The latest seven-pair comparison of `339bf5cd7a` against `3e97440c60` shows 1.074× throughput [95% interval 1.061, 1.088], matching checksums and stable warmups at nice 20. JFR sampled allocation weight fell about 6.3% overall, with the `ownerSlotSnapshot` stack falling 93.6%. Reports: `/private/tmp/issue2043-package-root-excel-paired.json`, `/private/tmp/issue2043-package-array-paired.json`, and `/private/tmp/issue2043-untracked-index-paired.json`. | The allocation path is now directly targeted and measured; treat JFR as sampled evidence and avoid claiming a portfolio-wide speedup. | +| DBIx::Class acceptance | The exact `339bf5cd7a` eight-target run completed 325 DBIx test programs / 43,020 assertions with one failure: `t/storage/txn.t` expected source line 451, got 448 and 447. Baseline `278c12be27` reproduces it. The interpreter resultset timeouts and three system-Perl `update_delete.t` SQL-status mismatches are also classified against current master. | No owner-ledger-specific DBIx failure remains in the acceptance evidence; retain these baseline limitations and do not claim all-backend DBIx acceptance. | +| Catalyst acceptance | The exact `339bf5cd7a` acceptance run has the same two assertion failures across ten programs as the current-master reproduction at `1ee4ff572d`; the pre-merge candidate passed the target. | Treat as current-master baseline behavior; no owner-ledger fix is indicated. | +| Mojolicious acceptance | The exact `339bf5cd7a` run fails one assertion in `t/mojo/asset.t` with `Can't fork: Resource temporarily unavailable`; this matches the previously recorded host limitation. | The host fork limit is waived; retain the run log and do not interpret dependent missing assertions as product failures. | +| Focused compatibility retests | Moo weak accessor and Template Toolkit string tests pass on both backends. Standard Perl passes Moo; its Template Toolkit run could not load `Template::Stash::XS` because the temporary standard-Perl environment lacks that native build. | No focused retest remains; preserve the standard-Perl Template Toolkit environment limitation. | +| PR integration | PR #1938 is published through `ecb14f5881`; local source candidate `1d3e96f2a6` passes the full Make gate and focused JVM/interpreter RSA tests. | Publish the parser dataflow update, inspect fresh hosted CodeQL and build checks, then wait for human review. | + +### Complete step-by-step delivery plan + +1. **Resume from this checkpoint.** On 2026-11-24, PR #1938 contains the owner-ledger work, the merged #2171 change, and the RSA minimum-size update. The three classified CPAN failures have separate issues (#2168–#2170). Keep the generated CPAN report changes uncommitted. +2. **Use TDD for every distinct failure.** Keep existing tests unchanged. Where coverage is missing, add a focused permanent test under `src/test/resources/unit` or the owning Java unit-test tree before production changes. For Perl tests, run system Perl first and save complete output. Prove the regression on the unfixed parent and preserve the failure log. +3. **Retain the lifecycle fixes.** The ten full-candidate shard-0 failures and the extra pre-edit reachability-query failure now pass; the latest full Make gate passes. Keep the owner-ledger and async foreach changes together because they address current ownership and resume boundaries. +4. **Reconfirm the proxy-owner fix.** The three diamond regressions and upstream `t/prefetch/diamond.t` and `t/60core.t` pass with the DBIx prerequisite available. Preserve the pre-fix/fixed logs. Confirm the optional DBIx dependency skip behavior remains clean. +5. **Complete DBIx acceptance.** Focused `t/prefetch/diamond.t`, `t/60core.t`, and `t/52leaks.t` previously passed. All 12 upstream `t/resultset/*.t` files now pass on JVM, including the earlier `plus_select` and row-parser shutdown leaks. Focused project regressions pass on system Perl and both backends. Investigate the five interpreter resultset timeouts and three system-Perl `update_delete.t` SQL-status mismatches before claiming cross-backend DBIx acceptance; then run the broader DBIx suite on the final candidate. +6. **Complete remaining compatibility gates.** Focused Moo and Template Toolkit checks pass on both backends. Rerun them with the final lifecycle candidate after fixing the JVM-only inflated-result leak. For product failures, add permanent tests first and validate expected Perl behavior; capture full outputs, exit status, command, and source identity. +7. **Review and document the final source.** Run `git diff --check`, review all runtime/support code, verify tests are in `src/`, and remove temporary diagnostics that are not needed. The Work in progress changelog now includes the eval exception, async foreach, and owner-slot lifecycle behavior. Run `make check-links` and offline link checking for changed Markdown. +8. **Commit and run immutable gates.** Commit the reviewed candidate before the final repository gate. Run `nice -n 19 timeout 900 make` on that exact source commit and focused acceptance gates. If any source changes follow, commit them and rerun affected tests plus `make`. +9. **Verify the published PR candidate.** After local gates pass, update #1938 to the candidate integrating merged #2171; inspect all hosted checks and current review state. +10. **Close delivery after review.** Record final PR checks and review evidence here. Wait for human review and maintainer merge; then verify issue #2043 is resolved and archive the design as directed by the design-document workflow. + +Preflight backups of the dirty source state are `/tmp/wip-unstaged-20261121-144256.patch`, `/tmp/wip-staged-20261121-144256.patch`, `/tmp/wip-status-20261121-144256.txt`, and the later post-timeout snapshot `/tmp/wip-unstaged-20261121-154419.patch`, `/tmp/wip-staged-20261121-154419.patch`, `/tmp/wip-status-20261121-154419.txt`. ## Semantic Ownership Model @@ -128,7 +145,7 @@ These edges have different meanings: 5. Reassignment releases the old pad token before acquiring the new one. 6. `weaken()` releases the pad token and captures do not recreate it. 7. The final pad owner releases the token exactly once. -8. Weak sweeping cannot destroy a referent with authoritative strong owners. +8. Lifecycle decisions follow owner slots directly; Java reachability does not create or retire Perl owners. 9. Java reachability alone cannot create a Perl owner. 10. Strong Perl cycles remain alive until a strong edge is explicitly broken. @@ -220,87 +237,39 @@ Temporary aliases, generated fields, and conservative captures must not produce authoritative tokens. During migration, legacy or uncertain holds must be recorded separately so they cannot prevent weak cleanup indefinitely. -## Weak Sweeping and Reachability - -Weak-reference cleanup must follow these rules: - -1. Never clear or destroy a referent with authoritative strong owners. -2. Do not traverse arbitrary closure fields or conservative captures as Perl - roots. -3. Use explicit semantic pad ownership to protect captured referents. -4. Preserve strong cycles because their real strong edges keep authoritative - counts positive, matching Perl reference counting. -5. Use `ReachabilityWalker` only for still-unmodelled roots, diagnostics, and - migration checks—not as the source of closure semantics. -6. Gradually eliminate `WEAKLY_TRACKED` heuristics by reconstructing real - scalar, aggregate, and package owners when an untracked referent first - requires weak-reference accounting. - -## Implementation Phases - -### Phase 0: Preserve and specify - -- Keep the pre-flight patches and WIP snapshot of the failed walker experiment. -- Replace the current partial capture-token implementation before runtime work - proceeds. -- Retain the new issue regression test, but align its assertions with shared-pad - ownership rather than per-closure tokens. -- Document invariants and owner transitions in this design. - -### Phase 1: Perl oracle and owner instrumentation - -- Add system-Perl-validated tests for stable `B::REFCNT` observations. -- Add owner-ledger tracing and balance assertions without changing behavior. -- Inventory every direct refcount increment, decrement, promotion, and - `Integer.MIN_VALUE` transition. -- Record which existing counts are authoritative, conservative, or temporary. - -### Phase 2: Captured-pad lifecycle - -- Implement semantic versus metadata capture counts. -- Preserve the pad's single referent token after declaring-scope exit. -- Release the token when both scope ownership and semantic captures reach zero. -- Promote borrowed semantic captures to one pad-slot owner. -- Make reassignment, weakening, unweakening, and closure release generation-safe - so deferred decrements cannot target a newly assigned referent. -- Update CODE recursion and ithread clone paths. - -### Phase 3: Weak-sweep authority - -- Make authoritative owner tokens protect weak referents. -- Remove captured-pad dependence on broad capture walking. -- Keep generated and conservative captures opaque. -- Assert that the walker cannot destroy a referent with authoritative owners. -- Preserve DBIx::Class, Moo, Sub::Quote, and Sub::Defer cleanup by ensuring - metadata captures never enter the owner ledger. - -Issue #1132 is deliverable after Phases 0 through 3 pass their acceptance gates. - -### Phase 4: Complete owner-source migration - -Audit and convert all ownership paths: - -- Scalar assignments, aliases, references, localization, and returns -- Hash and array stores, removals, and clears -- Globals, stashes, globs, and CODE slots -- Arguments, temporaries, tail calls, and lvalue returns -- Tied variables and handlers -- Pad constants and installed subroutines -- Resurrection and repeated `DESTROY` -- Threads and runtime graph cloning - -Direct refcount mutation outside the owner API should become forbidden except -inside the destruction state machine. - -### Phase 5: Remove superseded heuristics - -- Remove `WEAKLY_TRACKED` premature-clearing heuristics where owner coverage is - complete. -- Retire class-specific and capture-specific walker exceptions superseded by - authoritative ownership. -- Keep the walker for diagnostics and explicit graph queries. -- Add property tests for balanced owners, cycles, weak edges, and deterministic - destruction. +## Lifecycle Ownership and Diagnostic Queries + +Weak-reference cleanup and destruction follow current owner-slot identities. A +referent remains alive while any Perl strong slot remains, including edges in +strong cycles. Releasing the final slot performs cleanup through the ordinary +container and lifecycle paths. + +No root traversal, snapshot, or sweep may change reference counts, weak +observers, or destruction timing. The reachability walker and scalar registry +are removed; lifecycle code uses owner-slot identities for final-release +decisions. Temporary leases and suspended-frame owners remain explicit slots. + +## Current Work + +1. Ordinary final array/hash cleanup now retires direct outgoing slots; the + recursive walker and one-level eligibility pre-scans are gone from that + path. Existing liveness guards remain. Tied arrays use raw local storage + access during slot retirement so cleanup does not call Perl `FETCHSIZE`. + Global destruction still uses `CleanupTargetProbe`. +2. Skip repeated package-root marking when `getGlobalArray` reads an already + rooted aggregate; global table writes establish the root and array mutation + paths register later slots. The fast-path regression passes, and the + seven-pair `chart_axis28.t` comparison against exact parent `2362185545` + measures 11.92× throughput (95% interval [10.53, 13.68]) with matching + normalized workbook checksums. The paired evidence is in + `/private/tmp/issue2043-package-root-excel-paired.json`; the focused + package-array workload and JFR samples are retained alongside it. +3. Exact-candidate release acceptance is complete. The three failures are + classified as current-master or host-resource issues; the generated CPAN + report files remain uncommitted. +4. The local PR reconciliation candidate is validated, but remote PR #1938 has + not been updated. Recheck its live state and obtain explicit authorization + before pushing the candidate. ## Regression Matrix @@ -346,7 +315,7 @@ Preserve and run: - DBIx::Class leak-tracer and weak-registry tests - Exact-refcount tests using `B::REFCNT` or `Test2::Tools::Refcount` -## Issue #1132 and Ecosystem Acceptance +## Historical issue #1132 ecosystem acceptance Run on JVM and interpreter backends with `timeout` and complete output logs: @@ -366,191 +335,34 @@ Run on JVM and interpreter backends with `timeout` and complete output logs: - Run `make` with complete captured output and zero failures. - Run `make check-links` and offline `lychee` where required. - Verify no unexpected high-CPU PerlOnJava JVM remains. -- Rebase onto current `master`, rerun focused and full gates on the exact commit, +- Integrate current `master`, rerun focused and full gates on the exact commit, and only then mark the issue-fix PR ready. ## Progress Tracking -### Current Status: Net::Async::HTTP captured-owner, hash-slice, and eval-capture finalization fixes complete - -The designated issue branch, `fix/issue-1132-closure-lifetime`, includes the -handoff commits below. On 2026-09-01, the required pre-change `make` rebuilt -the classes and JAR but its four unit-test workers were SIGKILLed (exit 137) -while concurrent PerlOnJava worktrees exhausted host resources. This is an -invalid gate, not a test assertion failure; rerun a clean full gate after the -external workload has drained before changing runtime source. - -### Completed Work - -- [x] Closure captures now retain tracked referents through captured pads, and - weak callback targets with semantic capture owners are not cleared early. - The focused Future regression is covered by - `unit/refcount/closure_capture_weak_callback_slot.t`. -- [x] `IO::Handle` supplies `fileno` for normal and tied handles. Direct - `IO::Socket->socketpair` and `IO::Async::OS->pipepair` fileno probes work on - both backends. -- [x] Return-scope cleanup preserves IO ownership for materialized list - returns, including the interpreter path used by `IO::Async::OS->socketpair`. -- [x] Added `unit/io_socket_method_fileno.t`. System Perl passes its 12 - assertions, including the callback-captured socket-pair shape used by - IO::Async. -- [x] JVM explicit-return cleanup now leaves constructor-captured scalar pads - to their enclosing frame. A callback can retain one end of - `IO::Async::OS->socketpair` while returning the other. -- [x] The focused regression passes on JVM and interpreter; `make` passes. - Net::Async::HTTP `t/05redir.t` and its socket/stream follow-on tests pass. -- [x] `B::SV::REFCNT` no longer applies its DBIx destruction-only aggregate - adjustment to ordinary lexical probes. The new fresh-runtime regression - passes on system Perl and both PerlOnJava backends. -- [x] Future's exact-count programs `10wait_all`, `11wait_any`, - `12needs_all`, `13needs_any`, and `25retain` now pass on the JVM. -- [x] `Internals::jperl_refstate` reports active scalar-store and semantic - captured-pad owner counts for focused ownership diagnosis. -- [x] Reproduced the remaining Net::Async::HTTP exact-count failures in the - distribution's normal socket-enabled environment. `t/30timeout.t` reports - 3 rather than 1 references at EOF; after the script scope drains, the raw - `$http` count is 2, so the `B::REFCNT` probe supplies the third reference. - `t/32remove.t` similarly reports 7 rather than 4 and 4 rather than 1; its - raw connection count is 3 after script-scope cleanup. -- [x] Scoped `PJ_REFCOUNT_TRACE` confirms these residual counts are not - semantic captured-pad owners. It also exposed a diagnostic gap: the trace - removes a scalar's provenance when `deferDecrementIfTracked()` queues its - decrement, before the deferred work is applied. A residual raw count can - therefore outlive all entries in the shutdown owner dump without revealing - the originating scalar-store path. -- [x] Deferred owner-release tracing now retains immutable provenance from - `deferDecrementIfTracked()` queueing until the matching drain or explicit - runtime-state cancellation; a still-pending record is included in the - shutdown report. The record includes the source scalar - identity, stable referent generation, acquisition site, queue site, and - drain site. The parallel queue metadata is trace-only, so it creates no - runtime owner or reachability edge. Files: `RuntimeBase.java`, - `LifecycleRuntimeState.java`, and `MortalList.java`. `make` passes; a - `PJ_REFCOUNT_TRACE` smoke run reports the retained pending provenance. -- [x] Added `Internals::jperl_owner_trace($referent)`, a referent-filtered - assertion-boundary snapshot of active scalar-store tokens and queued - deferred releases. It is observational when `PJ_REFCOUNT_TRACE` is absent; - when tracing is enabled it reports the source scalar identity, referent - generation, acquisition site, and queue site without retaining runtime - objects. `unit/refcount/owner_trace_snapshot.t` passes on system Perl - (guarded skip), JVM, and interpreter. Files: `RuntimeBase.java`, - `Internals.java`, and `owner_trace_snapshot.t`. -- [x] Rebuilt the provenance instrumentation and ran the normal socket-enabled - `Net::Async::HTTP` `t/30timeout.t` with a scoped trace. The final assertion - still observes three refs where Perl expects one; after the script-scope - token drains, `$http` has the known raw count of two. Neither surplus is an - active scalar-store owner. The shutdown report currently includes a large - number of unrelated queued releases, so the next diagnostic step needs an - assertion-boundary snapshot filtered to the selected referent rather than a - broader trace or any capture-accounting adjustment. -- [x] Ran the filtered snapshot at the normal socket-enabled Net assertion - boundaries. `t/30timeout.t` shows one active scalar-store token and no - semantic capture owner for `$http`; `t/32remove.t` shows the same for - `$conn`. An explicit `jperl_freetmps()` does not reduce either failing - count. The surplus is therefore not a missed boundary drain, captured pad, - or currently ledgered scalar-store token. Historic queued-release trace - records also do not account for the raw count and must not be treated as - live owners. -- [x] Added trace-only non-scalar owner kinds for method-invocant holds and - first-bless mortal temporaries. Parallel owner metadata is now removed in - lockstep with deferred entries during `flushAboveMark()` and - `popAndFlush()`, eliminating false unpaired trace releases. The full - `make` gate passes. Net tracing shows `transient=[]` at the failing boundary: - those two owner kinds balance correctly. -- [x] Mapped `$http` through the Net timeout lifecycle: it has one active - scalar-store token after construction, two after loop registration, four - before loop removal (while still showing only those two active tokens), and - three after removal (one active token). The extra two counts are introduced - by request processing, not loop registration/removal, captured pads, - method holds, or bless temporaries. -- [x] Added balanced trace-only tokens for scalar-reference contents, - weak-reference promotion, closure-capture referents, and all tie-wrapper - holds (`TiedVariableBase`, `TieHash`, `TieArray`, and `TieHandle`). The - scalar-reference regression now enables tracing before the hold is acquired - and verifies that its release leaves `transient=[]`; it passes on both - execution backends. Full `make` passes. -- [x] Re-ran normal socket-enabled `Net::Async::HTTP` `t/30timeout.t` with - the expanded ledger. On the JVM, the failing boundary still has raw count 3 - with one scalar-store token and `transient=[]`; no `unweaken` event or - closure-capture/tie token was acquired for that referent. The interpreter - remains balanced (two owners before loop removal, one after) and exits 0. - These direct mutation paths are therefore not the JVM's two surplus - request-path owners. -- [x] Added the existing semantic captured-pad owner count to the - assertion-boundary snapshot. The focused diagnostic passes on JVM and - interpreter; the JVM Net boundary reports `semanticCaptureOwners=0` both - before and after loop removal. Captured-pad transfer cannot account for the - two surplus raw counts. Focused JVM/interpreter tests and `make check-links` - pass. Full `make` is deliberately handed to the receiving worker because a - concurrent external workload caused the local full-gate attempt to time out - after its unit shards completed. -- [x] Installed `Net::Async::HTTP` 0.50 and its CPAN dependency chain through - `jcpan`. In the socket-enabled distribution environment, JVM - `t/30timeout.t` reproduces the documented final `$http` count of 3 rather - than 1; the interpreter reaches 1. At the exact assertion, both backends - have one active scalar-store owner and no pending, transient, or semantic - capture owner. The JVM's two surplus counts therefore originate in compiled - `IO::Async::Loop`/`Notifier` cleanup before the final top-level flush, not - captured pads or method-invocant holds. `t/32remove.t` also has broader - connection-count drift in this newly installed environment (JVM 7/4 and - interpreter 8/5), which remains a separate investigation. -- [x] Tested and rejected two JVM-only cleanup hypotheses against clean full - `make` gates: including compiler-marked captures at ordinary block exit and - flushing untracked compiled-sub return values. Neither changed the JVM - `t/30timeout.t` count of 3. The surplus is not a deferred mortal awaiting a - block or return boundary; continue from direct unledgered increment and - release paths rather than widening capture or flush behavior. -- [x] Direct increment tracing found two JVM-only - `releaseCapturedDecrement()` ownership transfers for the failing `$http`. - Root-path tracing showed that the temporary global - `$IO::Async::Loop::ONE_TRUE_LOOP->{notifiers}` registration triggered each - transfer. The loop later removes that entry correctly, but the discarded - capture token was never restored, leaving two surplus counts. Captured - owners now always schedule their ordinary deferred decrement. Added - `unit/refcount/captured_global_owner_release.t`: the test passes on system - Perl and both PerlOnJava backends, while the unfixed implementation reported - two references. The normal socket-enabled Net::Async::HTTP `t/30timeout.t` - now passes all 25 assertions on JVM and interpreter. Full `make` passed in - 6m 08s before the final source-comment cleanup. -- [x] The remaining interpreter-only `Net::Async::HTTP` `t/32remove.t` - difference was traced to `HASH_SLICE_SET`: the compiler-created RHS array - and its `addToArray()` staging copies each retained a scalar-store owner - after `RuntimeHash.setSlice()` had created the durable slot. The interpreter - now transfers both temporary owners immediately. Added - `unit/refcount/interpreter_hash_slice_staging_ownership.t`; it passes on - system Perl and both PerlOnJava backends, while the unfixed interpreter - reported 3 then 2 references instead of 2 then 1. `t/32remove.t` now passes - its exact 4 then 1 checks on JVM and interpreter, and `t/30timeout.t` passes - all 25 assertions on both backends. Full `make` passed on 2026-09-01. -- [x] A scope-exited typed lexical captured only by a discarded `eval STRING` - no longer retains a stale semantic capture owner through global destruction. - The pre-`END` reachability pass now releases that owner only after proving - that no `END` block can reach the capture. Existing permanent core coverage - in `perl5_t/t/run/fresh_perl.t` test 75 now passes, restoring the baseline - 73/91 result; the other 18 historical failures are unchanged. Full `make` - passed in the isolated PR worktree on 2026-09-02. - -### Handoff: issue #1132 / PR #1204 - -This work must be continued on the issue-linked PR -[#1204](https://github.com/fglock/PerlOnJava/pull/1204), branch -`fix/issue-1132-closure-lifetime` (not on a new owner-ledger PR). The commits -to retain are `5b693177f`, `1702edb70`, `4832540d6`, `9fcab6e81`, and -`87b4fdee3`. The receiving worker must run a clean full `make` before further -source changes or PR completion; the prior full gate was invalidated only by -an external concurrent workload and timed out after test shards completed. +### Current checkpoint + +The current status and evidence are maintained in the +[ownership rewrite handoff](perl-ownership-rewrite.md#current-handoff-2026-11-15). +The candidate has removed production reachability decisions and sweep +infrastructure. The DBIx and Test2 owner transitions have focused regressions; +the merged candidate passes the focused DBIx leak tests and direct survivor +checks. CI passes on the published candidate and PR #1938 is ready for human +review. The broader 37-program failure inventory is retained as historical +integration context. #2037 and #2034 remain separate post-merge follow-ups. + +### Historical handoff: issue #1132 / PR #1204 + +This section records the earlier issue-linked PR +[#1204](https://github.com/PerlOnJava/pull/1204) handoff. Its branch was +`fix/issue-1132-closure-lifetime`; retained commits were `5b693177f`, +`1702edb70`, `4832540d6`, `9fcab6e81`, and `87b4fdee3`. These historical +branch instructions do not define the current continuation. The Net::Async::HTTP 0.50 distribution is installed through `jcpan` in the local CPAN cache. JVM and interpreter `t/30timeout.t` and `t/32remove.t` now pass. Preserve both focused ownership regressions when evolving the ledger. -### Next Steps - -1. Continue the owner-source migration inventory and remove only diagnosed - ownership heuristics with permanent system-Perl-validated regressions. -2. Keep Cookie2 formatting and content-coding exception handling separate from - this ownership work. - ### Open Questions - Can additional compiler-created aggregate temporaries be made explicit in diff --git a/dev/modules/dbix_as_query_releases_schema.t b/dev/modules/dbix_as_query_releases_schema.t new file mode 100644 index 0000000000..c402273f8f --- /dev/null +++ b/dev/modules/dbix_as_query_releases_schema.t @@ -0,0 +1,34 @@ +use strict; +use warnings; + +use Test::More; +use Scalar::Util qw(weaken); + +use lib $ENV{DBIX_CLASS_LIB} + // die "Set DBIX_CLASS_LIB to the installed DBIx::Class lib directory\n"; +use lib $ENV{DBIX_CLASS_TEST_LIB} + // die "Set DBIX_CLASS_TEST_LIB to the DBIx::Class t/lib directory\n"; +use DBICTest; + +my $weak_schema; +{ + my $schema = DBICTest->init_schema(); + weaken($weak_schema = $schema); + + my $rs = $schema->resultset('Artist')->search( + {}, + { + join => 'cds', + distinct => 1, + '+select' => [ { count => 'cds.cdid', -as => 'amount_of_cds' } ], + '+as' => [qw/num_cds/], + order_by => { -desc => 'amount_of_cds' }, + }, + ); + + my $query = $rs->as_query; + ok(ref($query), 'as_query returns the packed query'); +} + +ok(!defined($weak_schema), 'discarded as_query result releases its schema'); +done_testing(); diff --git a/dev/modules/dbix_cascade_delete_releases_schema.t b/dev/modules/dbix_cascade_delete_releases_schema.t new file mode 100644 index 0000000000..f7242bdddb --- /dev/null +++ b/dev/modules/dbix_cascade_delete_releases_schema.t @@ -0,0 +1,24 @@ +use strict; +use warnings; + +use Test::More; + +use lib ($ENV{DBIX_CLASS_LIB} + // die "Set DBIX_CLASS_LIB to the installed DBIx::Class lib directory\n"), 't/lib'; +use DBICTest; + +my $schema = DBICTest->init_schema(); +$schema->populate('Artist', [ + [qw/name cds/], + ['Cascade cleanup artist', [ + { title => 'Cascade cleanup CD', year => 2026 }, + ]], +]); + +$schema->resultset('Artist')->find({ + name => 'Cascade cleanup artist', +})->delete; + +ok(1, 'populate and cascading delete completed'); + +done_testing(); diff --git a/dev/modules/dbix_class.md b/dev/modules/dbix_class.md index bb794d4f82..ab4a5b44c5 100644 --- a/dev/modules/dbix_class.md +++ b/dev/modules/dbix_class.md @@ -44,15 +44,21 @@ done | sort | File | Count | Status | |------|-------|--------| -| `t/52leaks.t` | 7 (tests 12-18) | Deep — refCount inflation in DBIC LeakTracer's `visit_refs` + ResultSource back-ref chain. Needs refCount-inflation audit; hasn't reproduced in simpler tests | -| `t/52leaks.t` (line 430, harness-only) | **NEW — INVESTIGATE NEXT** | "Unable to perform storage-dependent operations with a detached result source (source 'Artist' is not associated with a schema)". Test passes standalone (11/11 in 46s) but raises this exception when run as part of `./jcpan -t DBIx::Class` after ~20 prior tests. Schema's weak ref to ResultSource (or RS's strong ref to schema?) is being cleared *prematurely* — DESTROY firing on the schema while a child resultset still expects it. Different failure mode from tests 12-18 (which is a leak, this is over-eager DESTROY). See "Investigation Plan: Schema-Detached Bug" below. | +| `t/52leaks.t` | 7 (tests 12-18) | Open on candidate `36b9205453`: six objects belong to one Artist/CD/Schema/ResultSource graph; test 18 is a separate nested-dclone hash. The former line-430 phantom-chain failure now passes; current root cause is unconfirmed. See Fix 10 current evidence below. | +| `t/52leaks.t` (diagnostic after test 18) | Classified | After the seven failed weak-registry checks, LeakTracer's Dumper raises a detached `Artist` ResultSource error at `Data::Dumper.pm` line 339. This is formatting fallout; the earlier phantom-chain assertions 1-8 pass on candidate `36b9205453`. | | `t/storage/txn_scope_guard.t` | 1 (test 18) | Needs DESTROY resurrection semantics (strong ref via @DB::args after MIN_VALUE). Tried refCount-reset approach — caused infinite DESTROY loops when __WARN__ handler re-triggers captures. Needs architectural redesign (separate "destroying" state from MIN_VALUE sentinel) | `t/storage/txn.t` — **FIXED** (90/90 pass) via Fix 10m (eq/ne fallback semantics). --- -## Investigation Plan: Schema-Detached Bug in t/52leaks.t (line 430) — IN PROGRESS +## Historical Investigation: Schema-Detached Bug in t/52leaks.t (line 430) + +The pre-candidate line-430 runtime failure is no longer reproduced on +`36b9205453`; assertions 1-8, including the phantom chain, pass. The detached +ResultSource exception in the current run happens after assertion 18 fails, +while LeakTracer's Dumper formats that retained clone. The notes below describe +the earlier failure and remain for context only. ### Symptom @@ -576,11 +582,32 @@ can't ship a regression behind that flag. All 7 fail at line 526 `assert_empty_weakregistry` — weak refs still `defined`. +### Current evidence (2026-11-12) + +On candidate `36b9205453`, the callback/argument-frame regression is fixed and +the full repository `make` passes. DBIx `t/100populate.t` passes 108/108 with +no LeakTracer refs. In `t/52leaks.t`, assertions 1-8 (including the phantom +chain through line 440) pass; only object-collection checks 12-18 remain. +Checks 12-17 refer to the original connected Artist/CD/schema/source graph; +check 18 refers to the independently cloned `basic rerefrozen` hash. The +detached-source exception happens after check 18 fails, while LeakTracer formats +the object, so it does not establish a runtime failure in phantom chaining. + +System Perl with the local DBIx dependency directory completes the ordinary +leak check. Its two reference-cycle cases are marked TODO and its optional +persistent-process checks are skipped. The current PerlOnJava failures still +need diagnosis; the system comparison does not prove a shared root cause. + +Next, inspect current owner-slot identities for checks 12-17 and separately +trace the nested-dclone hash for check 18. Make the diagnostic fail-soft before +`Devel::FindRef` tracking so Dumper cannot abort that inspection. Add focused +project-owned regressions only after those two owner paths are isolated. + ### Key Timing Constraint Assertion runs **during test execution** (line 526), not in an END block. `clearAllBlessedWeakRefs()` (END-time sweep) is too late. -### Root Cause: Parent Container Inflation +### Earlier hypothesis: Parent Container Inflation (unconfirmed) `$base_collection` (parent anonymous hash) has refCount inflated by JVM temporaries from: - `visit_refs()` deep walk (passes hashref as function arg) @@ -590,16 +617,23 @@ Assertion runs **during test execution** (line 526), not in an END block. `clear When scope exits, scalar releases 1 reference but hash stays at refCount > 0. `callDestroy` never fires → `scopeExitCleanupHash` never walks elements → weak refs persist. -**Implication**: Fixes that hook into callDestroy/scopeExit for the parent hash are blocked because it never dies. Our minimal reproducers (`/tmp/dbic_like.pl`, `/tmp/blessed_leak.pl`, `/tmp/circular_leak.pl`) no longer leak, but the real DBIC pattern still does. +This was a working hypothesis from earlier runs, not a confirmed explanation +for the current seven failures. Owner-slot traces are still needed before +concluding that the parent hash itself remains live or that a broader collector +is required. ### Diagnostic Facts - **B::REFCNT inflates by +1** vs actual: `B::svref_2object($x)->REFCNT` calls `Internals::SvREFCNT($self->{ref})` which bumps via B::SV's blessed hash slot. Failure inventory values are actual refCount + 1 (or 0 when refCount = MIN_VALUE). - **Unicode confirmed irrelevant**: t/52leaks.t uses only ASCII data. -### Next Steps +### Earlier blocked assessment (superseded) -Both remaining failures (t/52leaks.t tests 12-18 and t/storage/txn_scope_guard.t test 18) hit **fundamental limitations** of PerlOnJava's selective refCounting that can't be solved without a major architectural change: +The following assessment predates candidate `36b9205453` and is retained as +history, not as the current diagnosis. It classified both remaining failures +(`t/52leaks.t` tests 12-18 and `t/storage/txn_scope_guard.t` test 18) as +fundamental selective-refcounting limitations before the current owner-slot +traces were available: #### Why t/52leaks.t tests 12-18 Are Blocked @@ -630,7 +664,9 @@ Either: See [`dev/design/refcount_alignment_plan.md`](../design/refcount_alignment_plan.md) for a phased plan that implements both. -Deferred until such architectural work becomes practical. +That deferral was based on the earlier, unconfirmed hypothesis and is +superseded. Diagnose current owner-slot paths before deciding whether broader +architecture work is needed. ### Historical notes (previously attempted) diff --git a/dev/modules/dbix_failed_connect_releases_handle.t b/dev/modules/dbix_failed_connect_releases_handle.t new file mode 100644 index 0000000000..533cca7cc4 --- /dev/null +++ b/dev/modules/dbix_failed_connect_releases_handle.t @@ -0,0 +1,36 @@ +use strict; +use warnings; + +use Test::More; +use Scalar::Util qw(weaken); + +use lib $ENV{DBIX_CLASS_LIB} + // die "Set DBIX_CLASS_LIB to the installed DBIx::Class lib directory\n"; +use lib $ENV{DBIX_CLASS_TEST_LIB} + // die "Set DBIX_CLASS_TEST_LIB to the DBIx::Class t/lib directory\n"; +use DBICTest; + +my $weak_dbh; +{ + my $schema = DBICTest->init_schema( + no_deploy => 1, + on_connect_call => sub { + my $storage = shift; + weaken($weak_dbh = $storage->_dbh); + $storage->_dbh->do('_NOPE_'); + }, + ); + my $storage = $schema->storage; + + my $error; + eval { $storage->ensure_connected; 1 } or $error = $@; + like($error, qr/_NOPE_|syntax|near/i, + 'failed on-connect SQL is reported to the caller'); + ok(!defined($storage->_dbh), + 'failed on-connect action clears the storage database handle'); +} + +ok(!defined($weak_dbh), + 'failed, unreturned DBI handle is released after its schema leaves scope'); + +done_testing(); diff --git a/dev/modules/dbix_failed_connect_releases_storage.t b/dev/modules/dbix_failed_connect_releases_storage.t new file mode 100644 index 0000000000..53ee454d00 --- /dev/null +++ b/dev/modules/dbix_failed_connect_releases_storage.t @@ -0,0 +1,36 @@ +use strict; +use warnings; + +use Test::More; +use Scalar::Util qw(weaken); + +use lib $ENV{DBIX_CLASS_LIB} + // die "Set DBIX_CLASS_LIB to the installed DBIx::Class lib directory\n"; +use DBIx::Class::Schema; + +my ($weak_dbh, $weak_storage); +{ + my $schema = DBIx::Class::Schema->connect( + 'dbi:SQLite:dbname=:memory:', '', '', + { + RaiseError => 1, + PrintError => 0, + on_connect_do => '_NOPE_', + }, + ); + my $storage = $schema->storage; + weaken($weak_storage = $storage); + + my $error; + eval { $storage->ensure_connected; 1 } or $error = $@; + like($error, qr/_NOPE_|syntax|near/i, + 'failed on-connect SQL is reported to the caller'); + ok(!defined($storage->_dbh), + 'failed on-connect action clears the storage database handle'); +} + +ok(!defined($weak_dbh), 'failed connect does not retain an unreturned handle'); +ok(!defined($weak_storage), + 'failed connect releases DBIx Storage after its schema leaves scope'); + +done_testing(); diff --git a/dev/modules/dbix_prefetch_diamond_releases_schema.t b/dev/modules/dbix_prefetch_diamond_releases_schema.t new file mode 100644 index 0000000000..8282cffb77 --- /dev/null +++ b/dev/modules/dbix_prefetch_diamond_releases_schema.t @@ -0,0 +1,107 @@ +use strict; +use warnings; + +use Test::More; +use Scalar::Util qw(weaken); + +use lib $ENV{DBIX_CLASS_LIB} + // die "Set DBIX_CLASS_LIB to the installed DBIx::Class lib directory\n"; +use lib $ENV{DBIX_CLASS_TEST_LIB} + // die "Set DBIX_CLASS_TEST_LIB to the DBIx::Class t/lib directory\n"; +use DBICTest; + +my $schema = DBICTest->init_schema(); +my $weak_schema; +weaken($weak_schema = $schema); + +$schema->populate('Artwork', [[qw/cd_id/], [1]]); +$schema->populate('Artwork_to_Artist', [[qw/artwork_cd_id artist_id/], [1, 2]]); + +my $ars = $schema->resultset('Artwork'); +my $cd_paths = { + 'no cd' => [], 'no cd empty' => [''], 'no cd undef' => [undef], + 'no cd href' => [{}], 'no cd aoh' => [[{}]], + 'no cd complex' => [[[undef]]], 'cd' => ['cd'], + 'cd->artist1' => [{ cd => 'artist' }], +}; +my $a2a_paths = { + 'no a2a' => [], 'no a2a empty' => [''], 'no a2a undef' => [undef], + 'no a2a href' => [{}], 'no a2a aoh' => [[{}]], + 'no a2a complex' => [['']], 'a2a' => ['artwork_to_artist'], + 'a2a->artist2' => [{ artwork_to_artist => 'artist' }], +}; + +# Keep the ResultSets in file-scope storage like DBIx::Class's diamond test. +# Releasing an equivalent cache inside a helper sub does not reproduce the +# lifecycle failure. +my %tests; +for my $cd_path (keys %$cd_paths) { + for my $a2a_path (keys %$a2a_paths) { + $tests{"join $cd_path, $a2a_path"} = $ars->search({}, { + join => [@{$cd_paths->{$cd_path}}, @{$a2a_paths->{$a2a_path}}], + prefetch => [], + }); + $tests{"prefetch $cd_path, $a2a_path"} = $ars->search({}, { + join => [], + prefetch => [@{$cd_paths->{$cd_path}}, @{$a2a_paths->{$a2a_path}}], + }); + $tests{"join $cd_path, prefetch $a2a_path"} = $ars->search({}, { + join => [@{$cd_paths->{$cd_path}}], + prefetch => [@{$a2a_paths->{$a2a_path}}], + }); + $tests{"join $a2a_path, prefetch $cd_path"} = $ars->search({}, { + join => [@{$a2a_paths->{$a2a_path}}], + prefetch => [@{$cd_paths->{$cd_path}}], + }); + } +} + +my $rows_seen = 0; +my (@weak_cds, @weak_cd_artists, @weak_associations, @weak_association_artists); +for my $name (keys %tests) { + for my $artwork ($tests{$name}->all()) { + die "$name returned the wrong artwork" unless $artwork->id == 1; + my $cd = $artwork->cd; + push @weak_cds, $cd; + weaken($weak_cds[-1]); + my $cd_artist = $cd->artist; + push @weak_cd_artists, $cd_artist; + weaken($weak_cd_artists[-1]); + my $association = $artwork->artwork_to_artist->first; + push @weak_associations, $association; + weaken($weak_associations[-1]); + my $association_artist = $association->artist; + push @weak_association_artists, $association_artist; + weaken($weak_association_artists[-1]); + die "$name returned the wrong cd artist" + unless $cd_artist->artistid == 1; + die "$name returned the wrong association artist" + unless $association_artist->artistid == 2; + ++$rows_seen; + } +} + +is($rows_seen, 256, 'all diamond join/prefetch resultsets return the expected row'); + +my @weak_resultsets; +for my $name (keys %tests) { + push @weak_resultsets, $tests{$name}; + weaken($weak_resultsets[-1]); +} + +undef %tests; +undef $ars; +undef $schema; +is(scalar(grep { defined $_ } @weak_cds), 0, + 'CD rows are released after the diamond resultsets are discarded'); +is(scalar(grep { defined $_ } @weak_cd_artists), 0, + 'CD artist rows are released after the diamond resultsets are discarded'); +is(scalar(grep { defined $_ } @weak_associations), 0, + 'association rows are released after the diamond resultsets are discarded'); +is(scalar(grep { defined $_ } @weak_association_artists), 0, + 'association artist rows are released after the diamond resultsets are discarded'); +is(scalar(grep { defined $_ } @weak_resultsets), 0, + 'discarded diamond cache releases every resultset'); +ok(!defined($weak_schema), 'discarded diamond resultset cache releases its schema'); + +done_testing(); diff --git a/docs/about/changelog.md b/docs/about/changelog.md index d4f3bd89d9..c793a20da9 100644 --- a/docs/about/changelog.md +++ b/docs/about/changelog.md @@ -6,7 +6,35 @@ priorities and future plans. ## Work in progress -- Bound Net::SSLeay RSA key generation to 1024–8192 bits, retaining 1024 bits for the bundled fast RSA round-trip test and legacy callers while rejecting weaker or unbounded sizes. +- Require Net::SSLeay and Crypt::OpenSSL::RSA key generation to use 2048–8192 bits; reject weaker and unbounded sizes and keep the RSA round-trip and padding tests active at the minimum supported size. +- Retire active lexical owners on explicit `exit` before dispatching `END` blocks (#2043). +- Retain noncapturing anonymous CODE templates through their source optrees on both backends while allowing eval-created CVs to be released after escape (#2043). +- Stage temporary anonymous array references as call-argument owners so their elements remain alive through the call and release afterward (#2043). +- Skip redundant package-root scans when reading an already-rooted global array, while preserving mutation-time ownership of added slots (#2043). + +- Preserve imported CV owners through global destruction, keep runtime-only `eval STRING` captures usable without treating them as semantic closure owners, and release DBI handles after failed `prepare` or `do` (#2043). +- Preserve reacquired counted referents when deferred zero-count lifecycle cleanup drains (#2043). +- Preserve Perl cleanup order across eval exceptions and resumed async foreach calls (#2043). +- Keep current weak-tracked aggregate value slots and raw untracked owner identities alive through their matching release boundaries (#2043). +- Report the active Perl helper argument in `B::REFCNT` for nested hash-slot values during `DESTROY` (#2043). +- Keep temporary foreach-source values alive until normal or `last` exits in the bytecode interpreter, matching JVM cleanup and preventing premature destruction of list-returned rows (#2043). +- Remove reachability-based lifetime decisions, root-query state, and sweep-only hooks; use current Perl owner slots for cleanup (#2043). +- Notify destroyed watchers only on scalar slots of the aggregate being released, leaving live nested referents to their own final-owner cleanup (#2043). +- Reuse cycle-detection worksets while releasing outgoing values from dying arrays and hashes, reducing per-element queue and visited-set initialization (#2043). +- Restore array-literal flush state on early exits, unwind generated JVM frames at eval/try boundaries, and exclude expression-only owner leases from `B::REFCNT` (#2043). +- Reuse cleanup-target pre-scan worksets across candidate roots, skip probes for zero-count or currently owned aggregates, and fold direct weak-reference checks into that traversal (#2043). +- Release abandoned JVM direct-call owners when code generation falls back to the interpreter, allowing redefined CV optree constants to be reaped (#2043). +- Release DBIx::Class phantom-chain result sources after fresh anonymous hash arguments leave their call frame (#2043). +- Preserve caller lexical cleanup ownership through interpreter aliases so failed-connect DBIx::Class Storage can be released at scope exit (#2043). +- Construct DBI handles with core `bless`, matching native DBI and avoiding false leak reports for its cached driver handle (#2043). +- Retire overwritten temporary call arguments after callbacks, releasing Test2 Amnesty facets while preserving returned values (#2043). +- Load nested `do` and `require` files in the active runtime package, preserving Mojolicious Lite sandbox namespaces through eval strings (#2043). +- Remove the tokenless decrement compatibility path and its root-count repair now that releases identify their owner slots (#2043). +- Keep temporary list-assignment results from becoming owners of their scalar LHS cells (#2043). +- Release list-assignment temporary cell owners after returned values reach the caller, so weak fields no longer pin optree constants (#2043). +- Represent untracked, tracked, and weak-tracked referents separately from their nonnegative owner counts (#2043). +- Drain scoped owner releases at block exit even while statement flushing is suppressed, preserving earlier pending releases (#2043). + - Honor overloaded logical negation, warn on distinct constant-sub redefinitions with equal values, and preserve reference-valued scalar slots through localized glob aliases (#2122, #2075, #1939). - Preserve the `Can't use a hash as a reference` diagnostic for `%$hashref->{key}` and hash slices (#2132). - Preserve file contents on `sysopen` without `O_TRUNC`, fail `open` on undefined paths, avoid duplicate `closedir` warnings, and match Socket lookup flags and return values (#2128, #2125, #2095). @@ -51,8 +79,42 @@ priorities and future plans. - Prevent active overload-handler redispatch, expose subroutine arguments through English `@ARG`, keep deleted namespaces absent after scalar reads, and compare false Neo4j boolean properties consistently with JSON booleans (#2007, #2006, #1980, #2017). - Apply declared XML encodings to byte and UTF-8 flagged scalar input in `XML::LibXML` string parsing (#1989). - Preserve qualified indirect constructors under `strict subs`, `__DATA__` hash keys, inline terminal source markers, `our` self-references under `strict vars`, and bare unary `fc` after conditional feature imports (#2027, #2010, #2008, #1979). +- Retain eval-block direct-call targets with their parent CV across repeated execution (#1649). +- Preserve temporary-root identity across implicit return preparation so scope cleanup pops the root it pushed (#1649). +- Follow strong references held by temporary list returns during root reachability checks (#1649). +- Preserve control-flow return payloads and pending suspended-frame owners during END-boundary root checks; trim temporary roots skipped by exceptional call and eval unwinds (#1649). +- Root current package CODE slots by stash identity, including anonymous and eval-defined closures, and ignore detached glob slots after their aliases move (#1649). +- Track IO handle replacement and executable regex callback owners through their current runtime slots (#1649). +- Clear weak observers from rescued object graphs at the END boundary while preserving independently rooted objects and strong Perl edges (#1649). +- Short-circuit temporary-root reachability checks when direct strong edges prove the referent is reachable (#1649). +- Skip rescued-graph END traversal when the runtime has no registered weak observers (#1649). +- Load `Exporter::Heavy` before compile-time imports so `export_to_level` targets the importing package (#1649). +- Preserve aggregate element ownership when a foreach lexical aliases a stored scalar during scope cleanup (#1649). +- Resolve `SvREFCNT` live-scalar adjustments from current owner slots instead of scanning the lexical registry (#1649). +- Preserve hash-held anonymous IO owners when interpreter scope cleanup returns that hash (#1649). +- Ignore stale untracked scalar slots in exited argument containers when deciding whether a weak CODE ref remains live (#1649). - Normalize out-of-range calendar fields in `Time::Piece->strptime`, matching Perl date overflow behavior (#2001). - Reduce GC pressure in inner `eval STRING` compilation: replace `FastStack`'s default lazy ArrayList initialisation (first-push allocates `Object[10]`) with an explicit `super(2)` constructor, cutting per-stack array allocation 5× for the 16 `FastStack` fields in each snapshot `ScopedSymbolTable`; replace the O(N log N) `getAllVisibleVariables()` `TreeMap`+`HashSet` build inside `getVisibleVariableRegistry()` and `getVisibleOurRegistry()` with direct O(N) iteration of `symbolTableStack` using `putIfAbsent` for shadowing, caching results until the next `clearVisibleVariablesCache()` invalidation — eliminating `TreeMap.put`, `TreeMap.successor`, and `HashSet.add` allocations from the JFR execution-sample profile for inner eval compilation. +- Release localized CODE-slot owners when restoring a glob, allowing closure captures and their Perl referents to finalize at scope exit (#1649). +- Keep a scalar referent alive through an outer lexical refalias after the source lexical exits, then release it with the final alias (#1649). +- Increment and release scalar-cell refalias counts correctly across JVM and interpreter scope exits, including eval exceptions (#1649). +- Keep hash owner lookup constant-time during large hash hydration by indexing stored scalar-cell identities (#1649). +- Index semantic Perl owner-slot membership and skip referent-owner scans for primitive scalar stores (#1649). +- Route primitive and string scalar setters through owner-slot transitions when replacing tracked values (#1649). +- Release replaced nested hash and array objects from shared aggregate slots at assignment time, without retaining an unowned fetched view (#1649). +- Reacquire anonymous IO holder identities for cloned Perl scalars in child thread runtimes (#1649). +- Acquire anonymous IO holder identities for existing scalar and aggregate aliases whenever IO is installed into an existing glob (#1649). +- Release temporary anonymous IO holder leases with list-assignment scalar owners while preserving handles carried in assignment results (#1649). +- Finalize cleared aggregates from current owner identities; root reachability no longer preserves an ownerless referent (#1649). +- Release `Storable::dclone` results when their last Perl owner is dropped, without leaving an extra counted return helper (#1649). +- Release compiler, module, and postfix reference-transfer temporaries through their exact counted slot transition, including subroutine return slots, list assignment, hash slices, refalias setup, and Storable hooks (#1649). +- Hold an array or hash container through the lifetime of an aliased element argument, including after `shift @_` (#1649). +- Keep a replacement reference's RHS temporary alive through reentrant cleanup of the overwritten scalar slot (#1649). +- Preserve tied hash and array magic through aliased element arguments, including `untie` during the callee, and release the handler at frame exit (#1649). +- Acquire replacement ownership before publishing array and hash slots, then release displaced values against the updated storage state (#1649). +- Snapshot glob arguments retained by file-test and stat caches, and retain the anonymous IO lease assigned by `sysopen` (#1649). +- Copy weakened CODE references into independent strong stash scalars so glob slots acquire and release their own `CODE_SLOT` owner (#1649). +- Use owner-slot transitions for named CODE vivification and typeglob aliases instead of direct replacement or parallel stash counts (#1649). - Replace the O(N) `getAllVisibleVariables()` scan in `recycleTemporaryRegisters()` (called after every compiled statement) with an O(1) read of `ScopedSymbolTable.getTopScopeNextIndex()`: the innermost scope's `index` field is already the exact high-water mark for all allocated variable registers (maintained by `enterScope`/`exitScope` propagation and `addVariable`/`addVariableWithIndex`), so no full symbol-table traversal is needed. Removes `getHighestVariableRegister` from the JFR execution-sample profile entirely and reduces `recycleTemporaryRegisters` samples from ~138 to ~5, yielding ~11–13% wall-clock speedup on a 2 M-iteration `eval STRING` benchmark (10.67 s vs 12.07 s). @@ -94,6 +156,73 @@ priorities and future plans. - Recognize a bareword filehandle when `print`'s implicit `$_` list ends at a block close (#1948). - Accept YAML-style mapping syntax in `YAML::Syck::LoadJSON`, matching Syck's JSON loader behavior (#1942). +- Acquire replacement ownership before publishing array and hash slots, then release displaced values against the updated storage state (#1649). +- Release temporary JVM reference-alias RHS owners after scalar-context assignments so the final aliased cell can clean up (#1649). +- Track first-bless mortal references with deferred owner identities while preserving weak-source behavior (#1649). +- Defer weakly tracked `undef` cleanup to current argument-alias identities, preserving the tracking sentinel (#1649). +- Release aggregate closure captures without decrementing another owner's counted edge (#1649). +- Disable corrective sweeps by default while migrating to explicit reference ownership; retain temporary scalar call and mortal return values through their caller boundaries, and balance argument, scalar-cell, closure, aggregate, package scalar/array/hash roots, tied-handler, shared-view, named CODE, persistent state, and destructor lifetimes (#1649). +- Keep queued END callbacks live through their current queue owner and active-code handoff, without a synthetic positive count (#1649). +- Publish pending return-owner identities before detaching counted scalar slots, preserving imported END callbacks through queue publication (#1649). +- Validate counted scalar-cell owners through current array and hash storage during deferred cleanup, avoiding root snapshots for migrated edges (#1649). +- Track persistent CV scalar, array, hash, and refalias state bindings with `CODE_STATE` owner identities, including replacement and cloning; remove deferred live/global CODE capture recovery traversal (#1649). +- Use live scalar-owner slots to preserve nested untracked aggregates on first weaken, avoid package-root walks, and clear weak observers at final release (#1649). +- Release detached typeglob snapshot owners after namespace rebinding so stale stash values finalize with their last Perl owner (#1649). +- Release tail-call arguments from explicit owner slots without a root-graph fallback (#1649). +- Record uncounted value ownership for tracked referents held in package scalar cells (#1649). +- Give borrowed scalar cells in live lexical aggregates owner identities for their strong values (#1649). +- Preserve non-CODE weak referents directly from surviving uncounted owner slots when a scalar releases its last counted slot (#1649). +- Release displaced localized CODE captures from active-frame and owner-slot identities, without scalar-registry or root-graph scans (#1649). +- Defer zero-count cleanup for aggregates with surviving owner slots across scalar, deferred, and tail-call releases (#1649). +- Preserve live uncounted scalar owner slots through referent promotion, and prune temporary-container slots at final release (#1649). +- Avoid duplicate scalar reachability queries when a registered container proves a live CODE owner (#1649). +- Use direct non-counted Perl owner slots to defer tail-call cleanup without a root walk; ignore temporary runtime roots (#1649). +- Repair transient unblessed referent undercounts from verified array/hash element slots during overwrite and deferred cleanup, avoiding root walks (#1649). +- Resolve scalar-overwrite liveness from current owner-slot identities, removing external-root/live-CODE queries, unverified raw-count restoration, and nested-call depth deferrals (#1649). +- Use active-code and current storage owner identities during deferred CODE cleanup, removing the nested-call depth positive-count pin (#1649). +- Repair unblessed referent undercounts from captured scalar-cell owners only while a live closure owns the cell, in overwrite and deferred cleanup (#1649). +- Release captures from a final scalar CODE owner using explicit owner identities instead of a root walk (#1649). +- Release aggregate closure captures at scope exit from CODE owner identities, ignoring stale compatibility counts (#1649). +- Pair compiled regex callback owner slots with only their acquired CODE count, and release captures after the final callback owner leaves (#1649). +- Repair unblessed referent undercounts from verified scalar and aggregate owner slots in immediate and deferred cleanup, without root snapshots (#1649). +- Remove live-scalar-registry reachability from first-weaken, tail-call, and async-Future owner decisions. +- Release weakly tracked referents from their final uncounted owner slot without a root walk. +- Detect global `DESTROY` resurrection from current owner-slot identities instead of walking Perl roots, while excluding temporary call owners (#1649). +- Detect non-global `DESTROY` resurrection from validated owner slots, avoiding repeated root walks and stale detached-cell retention (#1649, #1860). +- Give mutable scalar-reference contents stable owner-slot identities, share the contents count across aliases, and carry slot identity through localization and deferred release (#1649). +- Preserve localized package array and hash element owners across async suspension, resume, and cancellation with explicit suspended-frame identities (#1649). +- Clear nested weak observers after explicit undef from validated Perl owner identities, without treating rescued or temporary roots as owners (#1649). +- Keep async lexical values owned while interpreter frames are suspended, then finalize cleared aggregate weak observers from current slots without stale-count root walks (#1649, #1860). +- Give each awaited Future a `SUSPENDED_FRAME` owner identity and remove its separate reachability-root registry (#1649). +- Repair deferred undercounts for values nested in tied handlers from their explicit hash slots, removing the tied-root reachability snapshot from deferred cleanup (#1649). +- Resolve package aggregate liveness from active package-root owner slots instead of scanning package tables (#1649). +- Transfer scalar-cell owner identity into a single-value array replacement so deferred cleanup validates the current element slot without a root walk (#1649). +- Release displaced hash element owners when cloned values replace an existing slot (#1649). +- Release deleted middle-array element owners after transferring the result to the caller (#1649). +- Release displaced array-element owners when multi-LHS list assignment replaces an array tail (#1649). +- Carry exact array-element owner identities through pop, shift, delete, and localized unwind while preserving borrowed `@_` aliases, so removed references release despite stale array ownership summaries (#1649). +- Track visible named package IO globs with per-stash owner identities, excluding anonymous `Symbol::gensym` handles from package ownership (#1649). +- Track the Perl object retained by each `PerlIO::via` layer through `POPPED`, pairing its owner identity with the selective count when applicable (#1649). +- Track the current tied-hash iterator key by owner identity, pair its direct count when tracked, and release it on `NEXTKEY`, exhaustion, and iterator resets (#1649). +- Preserve moved scalar, array, hash, and CODE slots while deleting a whole namespace, and release them with the detached namespace glob (#1649). +- Honor void context when deleting stash entries, releasing detached glob and namespace owners immediately (#1649). +- Transfer package scalar, array, and hash owner identities while materializing stash aliases (#1649). +- Track saved namespace moves with stash owner slots and release them when consumed or when the stale stash dies (#1649). +- Acquire active lexical owner identities when aggregate registration follows the initial pad bind, and clear weak aggregate observers on normal scope exit (#1649). +- Release scalar-cell pad owners after lexical cleanup, clearing weak observers at the correct scope exit (#1649). +- Exclude weak glob aliases from strong-owner backfill; release their anonymous IO holder on weaken and restore it on unweaken (#1649). +- Release displaced hash-element owners when multi-LHS list assignment replaces a hash tail, through the normal tied and package-root-aware store path (#1649). +- Release materialized list-assignment owners and restore lexical cleanup when tied hash assignment throws from `STORE` (#1649). +- Acquire replacement counted owner slots before releasing prior referents, preserving slot identity across overwrite and deferred release (#1649). +- Recognize weak-slot resurrection from durable storage identities and rebuild the post-`DESTROY` count, so final release redispatches `DESTROY` and clears weak observers (#1649). +- Queue zero-count void-context result cleanup as explicit lifecycle work instead of raising a synthetic positive reference count (#1649). +- Track cloned thread snapshot roots with temporary owner identities and retire them at entry cleanup or runtime teardown, removing the cloned-root reachability fallback from first weaken (#1649). +- Preserve captured weak referents through semantic closure-pad owner identities; release scalar cells after the last capture and retry weak cleanup after pending owner release (#1649). +- Defer legacy semantic closure-pad cleanup to its owner-slot release, removing the final capture-path positive-count pin (#1649). +- Bind signature parameter cells that skip lexical alias resolution into active pads so slurpy aggregates release weak observers at frame exit (#1649). + + + - Bundle `Devel::Size` with JVM-based `size` and `total_size` estimates. @@ -140,6 +269,15 @@ priorities and future plans. - Preserve scalar context for short-circuit expressions passed to scalar prototypes (#1891). - Include operating-system CA bundles and the Windows root store in verified `HTTP::Tiny` HTTPS connections while retaining JVM trust roots. - Keep nested Rose::HTML::Objects form results alive with counted argument owners so weak parent links and qualified field names survive argument evaluation (#1851). +- Preserve caller argument identity in @DB::args so borrowed debugger slots share source-cell cleanup instead of creating detached untracked references (#1649). +- Keep weakly tracked referents alive while an explicit Perl owner slot remains; undef now retires only the released cell's identity (#1649). +- Track package-root weak compatibility pins by owner-slot identity and retire each pin with the final scalar owner (#1649). +- Finalize cleared aggregate weak references from live owner identities even when a legacy count remains; retain reachability checks only for unmigrated owner cases (#1649). +- Keep queued owner releases visible to cleared-aggregate cleanup until their deferred count transition completes (#1649). +- Keep backslash-addressed optree constants alive through saved CODE references, transfer interpreter optree owner trees to published CVs, and release each constant edge with its CV owner (#1649). +- Acquire interpreter return owners before lexical cleanup so returned closures retain captured aggregates (#1649). +- Unwind lexical owners on returns through try/finally wrappers while preserving returned reference and lvalue behavior (#1649). +- Keep recursive output cleanup on explicit owner slots as lexical result graphs grow, avoiding repeated live-root snapshots (#1860). - Preserve multiline regex searches when positive lookaheads constrain a lazy any-character prefix, restoring Text::YAWikiFormater formatting (#1596). - Compile executable format argument expressions at write time on both backends, scope line-local lexicals correctly, preserve literal-only pictures, and refresh deferred lexical bindings (#1234). - Diagnose malformed and out-of-class Object::Pad `BUILD` declarations during parsing (#1808). diff --git a/docs/reference/feature-matrix.md b/docs/reference/feature-matrix.md index ada738aeda..cb4b0e512d 100644 --- a/docs/reference/feature-matrix.md +++ b/docs/reference/feature-matrix.md @@ -941,10 +941,8 @@ The `:encoding()` layer supports all encodings provided by Java's `Charset.forNa - ✅ **YAML::Syck** compatibility module backed by bundled `YAML::PP`. - ✅ **IO::Socket::SSL** module backed by Java `javax.net.ssl` SSLEngine. - ✅ **Net::SSLeay** module backed by Java security APIs (2327 CPAN tests pass). - `RSA_generate_key` accepts 1024–8192-bit requests. The 1024-bit legacy floor - remains because `netssleay_phase5_6.t` uses it to keep the RSA round-trip test - fast; 1024-bit RSA is not suitable for new key material. Use at least 2048 - bits for new keys ([CodeQL guidance](https://codeql.github.com/codeql-query-help/java/java-insufficient-key-size/)); + `RSA_generate_key` accepts 2048–8192-bit requests, rejecting weaker and + unbounded sizes ([CodeQL guidance](https://codeql.github.com/codeql-query-help/java/java-insufficient-key-size/)); 3072 bits provides 128-bit NIST security strength ([SP 800-57, Part 1 Rev. 5](https://csrc.nist.gov/pubs/sp/800/57/pt1/r5/final)). - ✅ **Plack::Handler::Netty** PSGI web server with HTTP/HTTPS, streaming, 32k+ req/sec. See [Web Server Guide](../../examples/http_server_plack/README.md). diff --git a/src/main/java/org/perlonjava/app/scriptengine/PerlLanguageProvider.java b/src/main/java/org/perlonjava/app/scriptengine/PerlLanguageProvider.java index 21ef0d6ea5..cc865d68fa 100644 --- a/src/main/java/org/perlonjava/app/scriptengine/PerlLanguageProvider.java +++ b/src/main/java/org/perlonjava/app/scriptengine/PerlLanguageProvider.java @@ -132,8 +132,7 @@ public static void resetAll() { resetAllGlobals(); SpecialBlockParser.resetTopLevelState(); WeakRefRegistry.resetState(); - ScalarRefRegistry.resetState(); - MortalList.clearSuspendedRoots(); + MortalList.clearTemporaryRoots(); // A prior script may have closed its Perl-level STDIN glob. Script // engine resets run multiple top-level programs in one JVM, so give // the next program a fresh wrapper around the process standard input. @@ -681,23 +680,7 @@ public static RuntimeList executePerlAST(Node ast, * @return The result of the Perl code execution. */ private static RuntimeList executeCode(RuntimeCode runtimeCode, Node ast, EmitterContext ctx, boolean isMainProgram, int callerContext) throws Exception { - // Phase B2a (refcount_alignment_52leaks_plan.md): mark this - // body as module-initialization for the sake of the - // reachability-walker auto-sweep, UNLESS it's the main - // program body. DBIC's LeakTracer and similar leak-detection - // code is sensitive to weak refs being cleared mid-initializer - // chain, so auto-sweep inhibits itself while this counter is - // positive. - boolean guardEntered = false; - if (!isMainProgram) { - ModuleInitGuard.enter(); - guardEntered = true; - } - try { - return executeCodeImpl(runtimeCode, ast, ctx, isMainProgram, callerContext); - } finally { - if (guardEntered) ModuleInitGuard.exit(); - } + return executeCodeImpl(runtimeCode, ast, ctx, isMainProgram, callerContext); } private static RuntimeList executeCodeImpl(RuntimeCode runtimeCode, Node ast, EmitterContext ctx, boolean isMainProgram, int callerContext) throws Exception { @@ -981,6 +964,16 @@ private static RuntimeCode compileToExecutable(Node ast, EmitterContext ctx) thr generatedClass, ctx ); + RuntimeBase[] padConstants = ctx.javaClassInfo.padConstants == null + ? new RuntimeBase[0] + : ctx.javaClassInfo.padConstants.toArray(new RuntimeBase[0]); + if (padConstants.length != 0 || !ctx.javaClassInfo.embeddedPadConstants.isEmpty()) { + compiled.installPadConstantTree( + ctx.javaClassInfo.javaClassName, + padConstants, + ctx.javaClassInfo.embeddedPadConstants, + ctx.javaClassInfo.embeddedPadConstantDescendants); + } // File-scope `our` declarations, for PadWalker::peek_our(0) at file scope Map ourDeclarations = VariableCollectorVisitor.declaredOurVariables(ast); compiled.declaredOurVariables = ourDeclarations.isEmpty() ? null : ourDeclarations; @@ -994,6 +987,7 @@ private static RuntimeCode compileToExecutable(Node ast, EmitterContext ctx) thr if (showFallback) { System.err.println("Note: Using interpreter fallback (ASM frame compute crash)."); } + EmitterMethodCreator.discardUninstalledDirectCallDescriptors(ctx); return fallback.interpretedCode; } catch (Throwable e) { // Check if this is a recoverable compilation error that can use interpreter fallback @@ -1033,6 +1027,7 @@ private static RuntimeCode compileToExecutable(Node ast, EmitterContext ctx) thr ctx.errorUtil ); InterpretedCode interpretedCode = compiler.compile(ast, fallbackCtx); + EmitterMethodCreator.discardUninstalledDirectCallDescriptors(ctx); if (ctx.symbolTable != null && fallbackCtx.symbolTable != null) { ctx.symbolTable.copyFlagsFrom(fallbackCtx.symbolTable); } diff --git a/src/main/java/org/perlonjava/backend/bytecode/BytecodeCompiler.java b/src/main/java/org/perlonjava/backend/bytecode/BytecodeCompiler.java index fdf60b7775..09fe1215c7 100644 --- a/src/main/java/org/perlonjava/backend/bytecode/BytecodeCompiler.java +++ b/src/main/java/org/perlonjava/backend/bytecode/BytecodeCompiler.java @@ -295,6 +295,9 @@ private void registerGotoLoopRanges(int bodyStartPc, int bodyEndPc) { // Non-final so the cached eval constructor can inject a pooled instance instead of // creating a fresh one for each of 2M warm-path eval compilations. ScopedSymbolTable symbolTable; + /** Names for lexical scalar registers, retained after their scopes leave the symbol table. */ + private final Map> myScalarNamesByRegister = + new LinkedHashMap<>(); // Goto label support: maps label names to their PC addresses for intra-function goto. // pendingGotos tracks forward references (goto before label) needing patch-up. // These are null by default; initialized lazily in compile() only when goto/labels are present. @@ -574,6 +577,8 @@ boolean isCompilingForeachList() { final int sourceLine; // Non-final + no field initializer: pooled on the cached eval path (round 21). private List constants; + /** Read-only scalar literals addressed by backslash in this optree. */ + private final List padConstants = new ArrayList<>(); private List stringPool; private final Map stringPoolIndex = new HashMap<>(16); // O(1) lookup private final Map constantPoolIndex = new HashMap<>(16); // O(1) lookup @@ -651,6 +656,10 @@ private void emitNormalLoopResult() { // Track current calling context for subroutine calls int currentCallContext = RuntimeContextType.LIST; // Default to LIST Map capturedVarIndices; // Name → register index + // Register identities for actual captured pad cells. capturedVarIndices also + // includes synthetic reservations for referenced names, so it cannot decide + // which lexical slots scope cleanup must leave alone. + private final Set capturedPadRegisterIndices = new HashSet<>(); // Declaration metadata for captured package variables. Keep this // separately from the register table because closure analysis may first // materialize a reference as a lexical before the body reaches `local`. @@ -834,6 +843,7 @@ public BytecodeCompiler(String sourceName, int sourceLine, ErrorMessageUtil erro int regIndex = entry.getValue(); if (regIndex >= 3) { capturedVarIndices.put(varName, regIndex); + capturedPadRegisterIndices.add(regIndex); } } @@ -1170,10 +1180,14 @@ private void exitScope() { * is on the stack. */ private void exitScope(boolean flush) { + exitScope(flush, false); + } + + private void exitScope(boolean flush, boolean markAtScopeEntry) { if (!scopeIndices.isEmpty()) { int scopeIdx = scopeIndices.pop(); - emitScopeCleanup(scopeIdx, flush); + emitScopeCleanup(scopeIdx, flush, markAtScopeEntry); symbolTable.exitScope(scopeIdx); if (!savedNextRegister.isEmpty()) { @@ -1194,23 +1208,41 @@ private void exitScope(boolean flush) { } } + int separateReturnRegister(int sourceReg) { + int resultReg = allocateRegister(); + emit(Opcodes.ALIAS); + emitReg(resultReg); + emitReg(sourceReg); + return resultReg; + } + private void emitScopeCleanup(int scopeIdx, boolean flush) { + emitScopeCleanup(scopeIdx, flush, false); + } + + private void emitScopeCleanup(int scopeIdx, boolean flush, boolean markAtScopeEntry) { // Gather variable indices to determine if cleanup is needed. - java.util.List scalarIndices = symbolTable.getMyScalarIndicesInScope(scopeIdx); + java.util.List scalarIndices = myScalarCleanupIndicesInScope(scopeIdx); java.util.Map scalarNames = symbolTable.getMyScalarNamesInScope(scopeIdx); - java.util.List hashIndices = symbolTable.getMyHashIndicesInScope(scopeIdx); - java.util.List arrayIndices = symbolTable.getMyArrayIndicesInScope(scopeIdx); - - // Only emit pushMark/popAndFlush when there are variables that need cleanup. - // Scopes with no my-variables skip this entirely. - boolean needsCleanup = flush - && (!scalarIndices.isEmpty() || !hashIndices.isEmpty() || !arrayIndices.isEmpty()); - - // Push mark so popAndFlush only drains entries added by - // scopeExitCleanup. Entries from method returns within the block - // that are below the mark will be processed by the next setLarge() - // or undefine() flush, or by the enclosing scope's exit. - if (needsCleanup) { + for (Map.Entry entry : scalarNames.entrySet()) { + myScalarNamesByRegister.computeIfAbsent( + entry.getKey(), ignored -> new java.util.LinkedHashSet<>()) + .add(entry.getValue()); + } + java.util.List hashIndices = myHashCleanupIndicesInScope(scopeIdx); + java.util.List arrayIndices = myArrayCleanupIndicesInScope(scopeIdx); + + // Ordinary scopes need a local mark only when lexical cleanup can add + // releases. Fresh-result do blocks already pushed their mark at entry, + // and must close it even when they declare no lexicals. + boolean hasScopeVariables = !scalarIndices.isEmpty() + || !hashIndices.isEmpty() || !arrayIndices.isEmpty(); + boolean needsCleanup = flush && (markAtScopeEntry || hasScopeVariables); + + // For ordinary scopes, push immediately before cleanup so only + // cleanup releases drain here. A fresh-result do block uses its + // earlier entry mark to include temporaries created by its body. + if (needsCleanup && !markAtScopeEntry) { emit(Opcodes.MORTAL_PUSH_MARK); } @@ -1220,33 +1252,47 @@ private void emitScopeCleanup(int scopeIdx, boolean flush) { // implicit `($left, $right)` return closes both socketpair ends before // the caller receives them. boolean preserveImplicitReturn = scopeIndices.isEmpty() && lastResultReg >= 0; + if (preserveImplicitReturn) { + // Return materialization replaces this register with an owned RV + // snapshot. Keep it separate from every lexical register, since + // an earlier local's cleanup can prepare a later local's value. + lastResultReg = separateReturnRegister(lastResultReg); + emit(Opcodes.PREPARE_SCOPE_RETURN); + emitReg(lastResultReg); + } + + // Perl releases hash values before scalar pads and arrays at scope exit. + // DESTROY methods can observe objects released earlier in this sequence, + // so keep this order identical in both execution backends. + for (int reg : hashIndices) { + emit(preserveImplicitReturn + ? Opcodes.RETURN_SCOPE_CLEANUP_HASH : Opcodes.SCOPE_EXIT_CLEANUP_HASH); + emitReg(reg); + if (preserveImplicitReturn) emitReg(lastResultReg); + } // Emit SCOPE_EXIT_CLEANUP for each my-scalar register in the exiting scope. // This calls RuntimeScalar.scopeExitCleanup() which handles: // 1. IO fd recycling for anonymous filehandle globs // 2. refCount decrement for blessed references with DESTROY for (int reg : scalarIndices) { - // Remove the active eval lexical binding while the register still - // contains its cell. SCOPE_EXIT_CLEANUP clears it afterwards. String name = scalarNames.get(reg); + emit(preserveImplicitReturn + ? Opcodes.RETURN_SCOPE_CLEANUP : Opcodes.SCOPE_EXIT_CLEANUP); + emitReg(reg); + if (preserveImplicitReturn) emitReg(lastResultReg); + // Keep the active pad slot through scalar cleanup. A scalar cell + // whose final owner is this lexical may need scopeExitCleanup to + // clear localBindingExists before releasing the pad identity can + // finish its weak-reference lifecycle. if (name != null && !preserveImplicitReturn) { emit(Opcodes.UNBIND_ACTIVE_LEXICAL); emitReg(reg); emit(addToStringPool(name)); } - emit(preserveImplicitReturn - ? Opcodes.RETURN_SCOPE_CLEANUP : Opcodes.SCOPE_EXIT_CLEANUP); - emitReg(reg); - if (preserveImplicitReturn) emitReg(lastResultReg); } - // Walk hash/array variables for nested blessed references. - for (int reg : hashIndices) { - emit(preserveImplicitReturn - ? Opcodes.RETURN_SCOPE_CLEANUP_HASH : Opcodes.SCOPE_EXIT_CLEANUP_HASH); - emitReg(reg); - if (preserveImplicitReturn) emitReg(lastResultReg); - } + // Walk array variables last, after hash values and scalar pads. for (int reg : arrayIndices) { emit(preserveImplicitReturn ? Opcodes.RETURN_SCOPE_CLEANUP_ARRAY : Opcodes.SCOPE_EXIT_CLEANUP_ARRAY); @@ -1256,8 +1302,42 @@ private void emitScopeCleanup(int scopeIdx, boolean flush) { // Pop mark and flush only entries added since the mark. if (needsCleanup) { - emit(Opcodes.MORTAL_POP_FLUSH); + emit(markAtScopeEntry + ? Opcodes.MORTAL_POP_SCOPE_FLUSH : Opcodes.MORTAL_POP_FLUSH); + } + } + + private boolean isCapturedVariableIndex(int index) { + return capturedPadRegisterIndices.contains(index); + } + + private List withoutCapturedVariables(List indices) { + if (indices.isEmpty() || capturedVarIndices == null || capturedVarIndices.isEmpty()) { + return indices; } + List filtered = new ArrayList<>(indices.size()); + for (int index : indices) { + if (!isCapturedVariableIndex(index)) { + filtered.add(index); + } + } + return filtered; + } + + List myScalarCleanupIndicesInScope(int scopeIdx) { + return withoutCapturedVariables(symbolTable.getMyScalarIndicesInScope(scopeIdx)); + } + + List myHashCleanupIndicesInScope(int scopeIdx) { + return withoutCapturedVariables(symbolTable.getMyHashIndicesInScope(scopeIdx)); + } + + List myArrayCleanupIndicesInScope(int scopeIdx) { + return withoutCapturedVariables(symbolTable.getMyArrayIndicesInScope(scopeIdx)); + } + + List myVariableCleanupIndicesInScope(int scopeIdx) { + return withoutCapturedVariables(symbolTable.getMyVariableIndicesInScope(scopeIdx)); } private void emitLoopControlScopeCleanup(LoopInfo loopInfo) { @@ -1296,10 +1376,10 @@ private List indicesAddedSince(List indices, Set befo private MyVarCleanupRegisters myVariablesAddedSince(Set before) { return new MyVarCleanupRegisters( - indicesAddedSince(symbolTable.getMyScalarIndicesInScope(0), before), - indicesAddedSince(symbolTable.getMyHashIndicesInScope(0), before), - indicesAddedSince(symbolTable.getMyArrayIndicesInScope(0), before), - indicesAddedSince(symbolTable.getMyVariableIndicesInScope(0), before)); + indicesAddedSince(myScalarCleanupIndicesInScope(0), before), + indicesAddedSince(myHashCleanupIndicesInScope(0), before), + indicesAddedSince(myArrayCleanupIndicesInScope(0), before), + indicesAddedSince(myVariableCleanupIndicesInScope(0), before)); } private void emitMyVarCleanup(MyVarCleanupRegisters cleanup, boolean flush) { @@ -1307,14 +1387,15 @@ private void emitMyVarCleanup(MyVarCleanupRegisters cleanup, boolean flush) { return; } - for (int reg : cleanup.scalarRegs) { - emit(Opcodes.SCOPE_EXIT_CLEANUP); - emitReg(reg); - } + // Keep the lexical cleanup order used by normal scope exit. for (int reg : cleanup.hashRegs) { emit(Opcodes.SCOPE_EXIT_CLEANUP_HASH); emitReg(reg); } + for (int reg : cleanup.scalarRegs) { + emit(Opcodes.SCOPE_EXIT_CLEANUP); + emitReg(reg); + } for (int reg : cleanup.arrayRegs) { emit(Opcodes.SCOPE_EXIT_CLEANUP_ARRAY); emitReg(reg); @@ -1828,6 +1909,24 @@ public InterpretedCode compile(Node node, EmitterContext ctx) { evalSitePragmaFlags.isEmpty() ? null : evalSitePragmaFlags, warningBitsString ); + Map> lexicalNames = new LinkedHashMap<>(); + for (Map.Entry> entry + : myScalarNamesByRegister.entrySet()) { + lexicalNames.put(entry.getKey(), new ArrayList<>(entry.getValue())); + } + code.setMyScalarNamesByRegister(lexicalNames); + List ownedPadConstants = new ArrayList<>(padConstants); + for (Object constant : constants) { + RuntimeCode nestedCode = constant instanceof RuntimeCode codeConstant + ? codeConstant + : constant instanceof RuntimeScalar codeRef + && codeRef.value instanceof RuntimeCode codeValue + ? codeValue : null; + if (nestedCode != null) { + Collections.addAll(ownedPadConstants, nestedCode.padConstantOwnerReferents()); + } + } + code.installPadConstants(ownedPadConstants.toArray(new RuntimeBase[0])); if (metadataScope != null) { code.setLexicalDisabledWarningCategories( metadataScope.getDisabledWarningCategories()); @@ -1939,6 +2038,7 @@ private void detectClosureVariables(Node ast, EmitterContext ctx) { // by the closure body. if (usedVars != null && !usedVars.contains(name)) continue; capturedVarIndices.put(name, reg); + capturedPadRegisterIndices.add(reg); outerVarNames.add(name); outerVarDecls.add(entry.decl()); outerVarPackages.add(entry.perlPackage()); @@ -2139,6 +2239,18 @@ public void visit(BlockNode node) { if (node.getBooleanAnnotation("givenBlock")) givenBlockDepth++; enterScope(); + // A fresh-result do block can flush its complete dynamic extent: its + // result cannot retain any value created inside the block. Record the + // boundary before evaluating the body so constructor mortals created + // there are included in the exit flush. + boolean isSubroutineBlock = node.getBooleanAnnotation("blockIsSubroutine"); + boolean isDoBlock = node.getBooleanAnnotation("blockIsDoBlock"); + boolean freshDoBlockScope = !isSubroutineBlock && isDoBlock + && DoBlockResultAnalysis.isAlwaysFresh(node); + if (freshDoBlockScope) { + emit(Opcodes.MORTAL_PUSH_SCOPE_MARK); + } + int regexSaveReg = -1; if (evalStringHasEvalOrRegex && !node.getBooleanAnnotation("blockIsSubroutine") @@ -2335,7 +2447,7 @@ public void visit(BlockNode node) { } if (i < lastMeaningfulIndex) { - emit(Opcodes.MORTAL_FLUSH); + emit(Opcodes.MORTAL_STATEMENT_FLUSH); } // Recycle temporary registers after each statement @@ -2401,11 +2513,9 @@ public void visit(BlockNode node) { // may still refer to an inner lexical. A do-block ending in an always-fresh // scalar operator is safe: its result is independent, so FREETMPS can run at // block exit and transient objects are destroyed before the caller proceeds. - boolean isSubroutine = node.getBooleanAnnotation("blockIsSubroutine"); - boolean isDoBlock = node.getBooleanAnnotation("blockIsDoBlock"); - boolean flushAtScopeExit = !isSubroutine - && (isDoBlock ? DoBlockResultAnalysis.isAlwaysFresh(node) : outerResultReg < 0); - exitScope(flushAtScopeExit); + boolean flushAtScopeExit = !isSubroutineBlock + && (isDoBlock ? freshDoBlockScope : outerResultReg < 0); + exitScope(flushAtScopeExit, freshDoBlockScope); if (blockLoopInfo != null) { emit(Opcodes.POP_CONTROL_BLOCK); } @@ -3221,7 +3331,7 @@ void handleHashSlice(BinaryOperatorNode node, OperatorNode leftOp) { // local @hash{...} needs key-aware proxies so dynamic restore can // re-resolve entries after hash mutation and remove newly-created keys. int rdSlice = allocateRegister(); - emit(shouldEmitHashFetchForLocal() + emit(shouldEmitHashSliceForLocal() ? Opcodes.HASH_SLICE_FOR_LOCAL : Opcodes.HASH_SLICE); emitReg(rdSlice); @@ -4023,9 +4133,8 @@ void compileVariableDeclaration(OperatorNode node, String op) { } if (op.equals("my")) { // The BEGIN cell becomes the live lexical pad slot - // when the main code retrieves it. Keep it visible - // to interpreter reachability sweeps from this - // point until the declaring scope exits. + // when the main code retrieves it. Register that + // slot with its declaring scope for normal cleanup. emit(Opcodes.REGISTER_MY_VAR); emitReg(reg); } @@ -4159,13 +4268,10 @@ void compileVariableDeclaration(OperatorNode node, String op) { } emit(Opcodes.REGISTER_MY_VAR); emitReg(reg); - if (sigil.equals("$")) { - // Keep the active CV pad visible to deferred format - // argument evaluation. Format declarations can occur - // after a write in the source while Perl still binds - // the format to this invocation's lexical cell. - emitActiveLexicalBinding(reg, varName); - } + // Keep the active CV pad visible to runtime lexical lookup. + // Deferred format argument evaluation can also refer to + // scalar cells declared earlier in the invocation. + emitActiveLexicalBinding(reg, varName); // Runtime attribute dispatch for my variables with attributes emitVarAttrsIfNeeded(node, reg, sigil); @@ -4591,9 +4697,11 @@ void compileVariableDeclaration(OperatorNode node, String op) { emit(Opcodes.REGISTER_MY_VAR); emitReg(reg); - if (sigil.equals("$")) { - emitActiveLexicalBinding(reg, varName); - } + // Signature parameters skip EMIT_LEXICAL_ALIAS + // because they bind fresh value cells. Bind all + // sigils here so slurpy array/hash pads acquire + // their ACTIVE_LEXICAL owner after registration. + emitActiveLexicalBinding(reg, varName); // Runtime attribute dispatch for list variable declarations. // Attributes are stored on the parent my/state node, propagate to each element. @@ -6224,13 +6332,13 @@ void compileVariableReference(OperatorNode node, String op) { int rd = allocateOutputRegister(); if (isStrictRefsEnabled()) { // strict refs: scalarDeref() — throws for non-refs - emitWithToken(Opcodes.DEREF_SCALAR_STRICT, node.getIndex()); + emitWithToken(Opcodes.DEREF_SCALAR_STRICT_TEMP, node.getIndex()); emitReg(rd); emitReg(blockResultReg); } else { // no strict refs: scalarDerefNonStrict(pkg) — allows symrefs int pkgIdx = addToStringPool(getCurrentPackage()); - emitWithToken(Opcodes.DEREF_SCALAR_NONSTRICT, node.getIndex()); + emitWithToken(Opcodes.DEREF_SCALAR_NONSTRICT_TEMP, node.getIndex()); emitReg(rd); emitReg(blockResultReg); emit(pkgIdx); @@ -6572,10 +6680,33 @@ void compileVariableReference(OperatorNode node, String op) { if (node.getBooleanAnnotation("directNamedCall")) { int rd = allocateOutputRegister(); int nameIdx = addToStringPool(subName); - RuntimeScalar cachedCallRef = node.getBooleanAnnotation("preserveHashConstantCall") - && node.getAnnotation("parseTimeCodeRef") instanceof RuntimeScalar codeRef - ? codeRef : new RuntimeScalar(); + RuntimeScalar parseTimeCallRef = + node.getAnnotation("parseTimeCodeRef") instanceof RuntimeScalar codeRef + ? codeRef : null; + RuntimeScalar deferredCallTarget = + node.getAnnotation("deferredDirectCallTarget") instanceof RuntimeScalar target + ? target : null; + RuntimeScalar emissionTimeCallRef = + GlobalVariable.getVisibleGlobalCodeRefForDirectCall(subName); + RuntimeScalar initialCallRef = parseTimeCallRef != null + ? deferredCallTarget != null ? deferredCallTarget : parseTimeCallRef + : emissionTimeCallRef != null + ? emissionTimeCallRef + : GlobalVariable.getGlobalCodeRefForFreshLookup(subName); + boolean compileTimePinned = parseTimeCallRef != null + && emissionTimeCallRef != parseTimeCallRef; + boolean retainTargetIfDeletedBeforeCallsiteInstall = + node.getBooleanAnnotation("retainTargetIfDeletedBeforeCallsiteInstall"); + RuntimeScalar cachedCallRef = new RuntimeScalar(); + int siteIndex = padConstants.size(); + cachedCallRef.configureCompiledDirectCallSite( + subName, siteIndex, initialCallRef, compileTimePinned, + retainTargetIfDeletedBeforeCallsiteInstall); + cachedCallRef.setCompiledDirectCallHasDeferredParseOwner( + deferredCallTarget != null); + cachedCallRef.setCompiledDirectCallPinSlot(parseTimeCallRef); int cacheIdx = addToConstantPool(cachedCallRef); + padConstants.add(cachedCallRef); Object classMethod = node.getAnnotation("directClassMethod"); int classNameIdx = classMethod instanceof String className ? addToStringPool(className) : -1; @@ -6769,6 +6900,7 @@ void compileVariableReference(OperatorNode node, String op) { emit(Opcodes.LOAD_CONST); emitReg(valueReg); emit(addToConstantPool(constant)); + padConstants.add(constant); if (emitterContext != null && emitterContext.javaClassInfo != null) { emitterContext.javaClassInfo.addPadConstant(constant); } @@ -7204,6 +7336,17 @@ public void endLocalHashLvalueCompile() { } private boolean shouldEmitHashFetchForLocal() { + return (currentCallContext == RuntimeContextType.LVALUE + || currentCallContext == RuntimeContextType.LVALUE_LIST + || localHashLvalueCompileDepth > 0 || compilingForeachList) + && suppressLocalHashFetchForLocal == 0; + } + + private boolean shouldEmitHashSliceForLocal() { + // HASH_SLICE_FOR_LOCAL is specifically for Perl's local @hash{...}. + // Ordinary lvalue slices must keep their element cells and scalarize + // from the slice values; returning localization proxies changes both + // their postincrement value and their writeback behavior. return (localHashLvalueCompileDepth > 0 || compilingForeachList) && suppressLocalHashFetchForLocal == 0; } @@ -7723,6 +7866,7 @@ private void visitAnonymousSubroutine(SubroutineNode node) { && (node.attributes == null || !node.attributes.contains("const")) && !subCompiler.hasStateVariableDeclarations) { // No closures - just wrap the InterpretedCode + subCode.isOptreeCodeTemplate = true; RuntimeScalar codeScalar = new RuntimeScalar(subCode); subCode.__SUB__ = codeScalar; // Set __SUB__ for self-reference RuntimeScalar compileTimeAttributeCodeRef = @@ -8560,6 +8704,12 @@ && blockEndsInDefer(bodyBlock)) { patchJump(explicitLoopExitPatch, loopEndPc); } + // The JVM emitter restores temporary foreach source owners at this + // boundary. The bytecode interpreter retains the same source values + // from ITERATOR_CREATE until every normal or `last` exit reaches here. + emit(Opcodes.FOREACH_SOURCE_RELEASE); + emitReg(iterReg); + if (!multiVarRegs.isEmpty()) { for (int heldReg : multiVarAliasHeldRegs) { if (heldReg >= 0) { @@ -9154,6 +9304,23 @@ public void visit(IfNode node) { patchIntOffset(gotoEndPos + 1, endPos); lastResultReg = resultReg; } + boolean conditionOwnsLocals = !myScalarCleanupIndicesInScope(ifScopeIndex).isEmpty() + || !myHashCleanupIndicesInScope(ifScopeIndex).isEmpty() + || !myArrayCleanupIndicesInScope(ifScopeIndex).isEmpty(); + if (conditionOwnsLocals) { + if (lastResultReg >= 0 && currentCallContext != RuntimeContextType.VOID) { + // A conditional can yield its declaring lexical, including a + // false overloaded reference or a reference to a local hash. + // Acquire the expression's own owners before retiring that scope. + int sourceReg = lastResultReg; + lastResultReg = allocateRegister(); + emit(Opcodes.SNAPSHOT_SCOPE_RESULT); + emitReg(lastResultReg); + emitReg(sourceReg); + emit(currentCallContext); + } + emitScopeCleanup(ifScopeIndex, true); + } symbolTable.exitScope(ifScopeIndex); } @@ -9340,7 +9507,14 @@ boolean hasTryFinallyReturnTarget() { void emitTryFinallyReturn(int valueReg) { TryFinallyReturnTarget target = tryFinallyReturnTargets.peek(); - emitAliasWithTarget(target.valueReg, valueReg); + // A return crossing the synthetic try/finally wrapper must acquire its + // result owner before the wrapper's lexical cleanup runs. Keep the + // source register intact because it may be a lexical cell that cleanup + // will retire before RETURN_NONLOCAL reaches the enclosing subroutine. + int returnReg = separateReturnRegister(valueReg); + emit(Opcodes.PREPARE_SCOPE_RETURN); + emitReg(returnReg); + emitAliasWithTarget(target.valueReg, returnReg); emit(Opcodes.LOAD_INT); emitReg(target.pendingReg); emitInt(1); diff --git a/src/main/java/org/perlonjava/backend/bytecode/BytecodeInterpreter.java b/src/main/java/org/perlonjava/backend/bytecode/BytecodeInterpreter.java index 18e5c51b2c..fbc80918e2 100644 --- a/src/main/java/org/perlonjava/backend/bytecode/BytecodeInterpreter.java +++ b/src/main/java/org/perlonjava/backend/bytecode/BytecodeInterpreter.java @@ -104,7 +104,7 @@ private static boolean lexicalAssignmentMustPreserveSlot(RuntimeBase val) { if (!(val instanceof RuntimeScalar scalar)) return false; return scalar instanceof ReadOnlyAlias || scalar.threadShared - || scalar.captureCount > 0 + || scalar.hasClosureCaptureOwner() || scalar.captureRefCountOwned() > 0 || scalar.referencedByScalarReference || scalar.hasLiveSubstrLvalueObservers() @@ -113,31 +113,15 @@ private static boolean lexicalAssignmentMustPreserveSlot(RuntimeBase val) { || scalar.type == RuntimeScalarType.READONLY_SCALAR; } - private static boolean returnListContainsTrackedReference(RuntimeList retList) { - if (retList == null || retList instanceof RuntimeControlFlowList) return true; - for (RuntimeBase elem : retList.elements) { - if (runtimeBaseIsTrackedReference(elem)) { - return true; - } - } - return false; - } - - private static boolean runtimeBaseIsTrackedReference(RuntimeBase elem) { - if (elem == null) return false; - if (elem instanceof RuntimeScalar scalar) { - if (!RuntimeScalarType.isReference(scalar)) { - return false; - } - if (!(scalar.value instanceof RuntimeBase base)) { + private static boolean releaseConsumedTemp(RuntimeBase temp, RuntimeBase target) { + if (temp instanceof RuntimeList list) { + if (list.elements.size() != 1 || !(list.elements.getFirst() instanceof RuntimeScalar scalar)) { return false; } - return base.blessId != 0 || base.refCount >= 0; + boolean released = scalar == target || releaseConsumedTemp(scalar, target); + if (released) list.elements.clear(); + return released; } - return elem.blessId != 0 || elem.refCount >= 0; - } - - private static void releaseConsumedTemp(RuntimeBase temp, RuntimeBase target) { if (!(temp instanceof RuntimeScalar tempScalar) || !(target instanceof RuntimeScalar targetScalar) || tempScalar == targetScalar @@ -147,41 +131,51 @@ private static void releaseConsumedTemp(RuntimeBase temp, RuntimeBase target) { || tempScalar.value != targetScalar.value || !(tempScalar.value instanceof RuntimeBase base) || base.refCount <= 0) { - return; + return false; } - tempScalar.refCountOwned = false; - if (base.refCountTrace) { - base.traceRefCount(-1, "BytecodeInterpreter.releaseConsumedTemp"); - base.releaseOwner(tempScalar, "releaseConsumedTemp"); - } - base.releaseActiveOwner(tempScalar); - base.refCount--; + MortalList.releaseCountedOwnerImmediately( + tempScalar, "BytecodeInterpreter.releaseConsumedTemp"); + return true; } private static java.util.Set collectReturnedClosures(RuntimeBase value) { java.util.IdentityHashMap closures = new java.util.IdentityHashMap<>(); - collectReturnedClosures(value, closures); + java.util.IdentityHashMap visited = new java.util.IdentityHashMap<>(); + collectReturnedClosures(value, closures, visited); return closures.isEmpty() ? null : closures.keySet(); } - private static void collectReturnedClosures(RuntimeBase value, java.util.IdentityHashMap closures) { - if (value == null) { - return; - } + private static void collectReturnedClosures( + RuntimeBase value, + java.util.IdentityHashMap closures, + java.util.IdentityHashMap visited) { + if (value == null || visited.put(value, Boolean.TRUE) != null) return; if (value instanceof RuntimeScalar scalar) { if (scalar.type == RuntimeScalarType.CODE && scalar.value instanceof RuntimeCode code) { closures.put(code, Boolean.TRUE); + } else if (RuntimeScalarType.isReference(scalar) + && scalar.value instanceof RuntimeBase referent + && !WeakRefRegistry.isweak(scalar)) { + collectReturnedClosures(referent, closures, visited); } return; } if (value instanceof RuntimeControlFlowList flow && flow.returnValue != null) { - collectReturnedClosures(flow.returnValue, closures); + collectReturnedClosures(flow.returnValue, closures, visited); return; } if (value instanceof RuntimeList list) { for (RuntimeBase element : list.elements) { - collectReturnedClosures(element, closures); + collectReturnedClosures(element, closures, visited); + } + } else if (value instanceof RuntimeArray array) { + for (RuntimeScalar element : array.elements) { + collectReturnedClosures(element, closures, visited); + } + } else if (value instanceof RuntimeHash hash) { + for (RuntimeScalar element : hash.elements.values()) { + collectReturnedClosures(element, closures, visited); } } } @@ -232,44 +226,65 @@ static void abandon(SuspendedInterpreterFrame frame) { if (!frame.suspended) return; frame.suspended = false; frame.suspendedRuntimeDisabledWarningCategories = null; + int pendingBeforeCleanup = MortalList.pendingSize(); for (RuntimeCode closure : frame.createdClosures) { if ((closure.capturedScalars != null || closure.capturedAggregates != null) - && closure.refCount == 0 - && closure.stashRefCount <= 0 && (frame.returnedClosures == null || !frame.returnedClosures.contains(closure))) { - closure.releaseCaptures(); + closure.requestCaptureReleaseWhenUnowned(); } } + InterpretedCode code = frame.code; + RuntimeBase[] registers = frame.registers; + boolean needsFlush = cleanupMyVarRegisters(frame); + frame.releaseSuspendedLexicalOwners(); + if (needsFlush || MortalList.pendingSize() > pendingBeforeCleanup) { + MortalList.flush(); + } + code.releaseRegisters(); + } + + /** Release the active frame's lexical slots without draining their mortals. */ + private static boolean cleanupMyVarRegisters(SuspendedInterpreterFrame frame) { InterpretedCode code = frame.code; RuntimeBase[] registers = frame.registers; int firstMyVarReg = 3 + (code.capturedVars != null ? code.capturedVars.length : 0); BitSet myVars = code.myVarRegisters; boolean needsFlush = false; - for (int i = myVars.nextSetBit(firstMyVarReg); - i >= 0 && i < registers.length; - i = myVars.nextSetBit(i + 1)) { + // Higher registers are declared later, so clean them first to preserve + // Perl's reverse declaration order for DESTROY. + for (int i = myVars.previousSetBit(registers.length - 1); + i >= firstMyVarReg; + i = myVars.previousSetBit(i - 1)) { RuntimeBase reg = registers[i]; if (reg == null) continue; - if (reg instanceof RuntimeScalar rs) { - RuntimeScalar.scopeExitCleanup(rs); + if (reg instanceof RuntimeScalar scalar) { + RuntimeScalar.scopeExitCleanup(scalar); + unbindActiveLexicalNamesForRegister(code, i, reg); needsFlush = true; - } else if (reg instanceof RuntimeHash rh) { - MortalList.scopeExitCleanupHash(rh); + } else if (reg instanceof RuntimeHash hash) { + MortalList.scopeExitCleanupHash(hash); needsFlush = true; - } else if (reg instanceof RuntimeArray ra) { - MortalList.scopeExitCleanupArray(ra); + } else if (reg instanceof RuntimeArray array) { + MortalList.scopeExitCleanupArray(array); needsFlush = true; } + frame.releaseSuspendedOwnerForRegister(i); MyVarCleanupStack.unregister(reg); registers[i] = null; } - if (needsFlush) { - MortalList.flush(); + return needsFlush; + } + + /** Remove named pad entries for one local when an exception skips normal unbind opcodes. */ + private static void unbindActiveLexicalNamesForRegister( + InterpretedCode code, int register, RuntimeBase cell) { + if (code == null || cell == null) return; + for (String name : code.myScalarNamesByRegister.getOrDefault(register, java.util.List.of())) { + RuntimeCode.unbindCurrentActiveLexical(cell, name); } - code.releaseRegisters(); } /** @@ -478,11 +493,11 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { int firstMyVarReg = 3 + (code.capturedVars != null ? code.capturedVars.length : 0); // Track closures created by CREATE_CLOSURE in this frame. - // At frame exit, we release captures for closures that were never stored - // via set() (refCount stayed at 0). This handles eval STRING map/grep - // block closures that over-capture all visible variables but are temporary. - // This matches the JVM-compiled path where scopeExitCleanup releases - // captures for CODE refs with refCount=0 (RuntimeScalar.java line ~2185). + // At frame exit, request capture retirement for temporary closures that + // were not returned. The CODE owner ledger keeps captures while a Perl + // owner remains, independent of the compatibility count. + // This matches the JVM-compiled path where scopeExitCleanup asks the + // owner ledger to retire temporary CODE captures. java.util.List createdClosures = frame.createdClosures; // Scope-exit cleanup emitted by BytecodeCompiler is bracketed by @@ -540,26 +555,42 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { } case Opcodes.MORTAL_FLUSH -> { - // Statement-boundary FREETMPS for the current function scope. + // Scope/control cleanup without advancing a Perl + // statement boundary. MortalList.flushAboveMark(); } + case Opcodes.MORTAL_STATEMENT_FLUSH -> + MortalList.flushStatementBoundary(); + case Opcodes.MORTAL_PUSH_MARK -> { // Push mark before scope-exit cleanup (SAVETMPS equivalent) MortalList.pushMark(); scopeCleanupBatches.push(new java.util.ArrayList<>()); } - case Opcodes.MORTAL_POP_FLUSH -> { + case Opcodes.MORTAL_PUSH_SCOPE_MARK -> { + // The mark belongs to a fresh-result do block and + // must exist even if tracking activates in its body. + MortalList.pushScopeMark(); + scopeCleanupBatches.push(new java.util.ArrayList<>()); + } + + case Opcodes.MORTAL_POP_FLUSH, Opcodes.MORTAL_POP_SCOPE_FLUSH -> { if (!scopeCleanupBatches.isEmpty()) { for (int cleanupReg : scopeCleanupBatches.pop()) { RuntimeBase slot = registers[cleanupReg]; + frame.releaseSuspendedOwnerForRegister(cleanupReg); MyVarCleanupStack.unregister(slot); registers[cleanupReg] = null; } } // Pop mark and flush only entries added since it (scoped FREETMPS) - MortalList.popAndFlush(); + if (opcode == Opcodes.MORTAL_POP_SCOPE_FLUSH) { + MortalList.popScopeMarkAndFlush(); + } else { + MortalList.popAndFlush(); + } } case Opcodes.SCOPE_EXIT_CLEANUP -> { @@ -593,8 +624,13 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { if (slot instanceof RuntimeScalar rs) { RuntimeScalar.scopeExitCleanup(rs); } + frame.releaseSuspendedOwnerForRegister(reg); if (!scopeCleanupBatches.isEmpty()) { scopeCleanupBatches.peek().add(reg); + } else if (pc < bytecode.length + && bytecode[pc] == Opcodes.UNBIND_ACTIVE_LEXICAL) { + // Preserve the cell for the following + // exact-name pad unbind. } else { MyVarCleanupStack.unregister(slot); registers[reg] = null; @@ -604,7 +640,27 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { case Opcodes.UNBIND_ACTIVE_LEXICAL -> { int reg = bytecode[pc++]; int nameIdx = bytecode[pc++]; - code.unbindActiveLexical(code.stringPool[nameIdx], registers[reg]); + RuntimeBase slot = registers[reg]; + code.unbindActiveLexical(code.stringPool[nameIdx], slot); + MyVarCleanupStack.unregisterAfterActiveLexicalUnbind(slot); + registers[reg] = null; + } + + case Opcodes.SNAPSHOT_SCOPE_RESULT -> { + int destination = bytecode[pc++]; + int source = bytecode[pc++]; + int resultContext = bytecode[pc++]; + if (resultContext == RuntimeContextType.RUNTIME) resultContext = callContext; + registers[destination] = RuntimeCode.prepareScopeResult( + registers[source], resultContext); + } + + case Opcodes.PREPARE_SCOPE_RETURN -> { + int returnReg = bytecode[pc++]; + registers[returnReg] = RuntimeCode.prepareScopeReturn( + registers[returnReg], callContext, + !RuntimeCode.isLvalueCode(code) + || code.isTryExpressionWrapper); } case Opcodes.RETURN_SCOPE_CLEANUP -> { @@ -693,6 +749,7 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { if (slot instanceof RuntimeHash rh) { MortalList.scopeExitCleanupHash(rh); } + frame.releaseSuspendedOwnerForRegister(reg); if (!scopeCleanupBatches.isEmpty()) { scopeCleanupBatches.peek().add(reg); } else { @@ -739,6 +796,7 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { if (slot instanceof RuntimeArray ra) { MortalList.scopeExitCleanupArray(ra); } + frame.releaseSuspendedOwnerForRegister(reg); if (!scopeCleanupBatches.isEmpty()) { scopeCleanupBatches.peek().add(reg); } else { @@ -752,6 +810,9 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { int returnReg = bytecode[pc++]; RuntimeBase slot = registers[reg]; if (slot instanceof RuntimeArray ra) { + registers[returnReg] = RuntimeCode.prepareLocalArrayReturn( + registers[returnReg], ra, callContext, + !RuntimeCode.isLvalueCode(code)); MortalList.scopeExitCleanupArray(ra, registers[returnReg]); } } @@ -778,7 +839,7 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { savedLocalLevel + relativeLevel); } unwindEvalMethodInvocantHolds( - evalMethodInvocantHoldDepthStack, methodInvocantHolds); + evalMethodInvocantHoldDepthStack, methodInvocantHolds, evalBaseRegStack, registers); pc = evalCatchStack.pop(); RuntimeCode.decrementEvalDepth(); popEvalCallerFrame(frame); @@ -786,14 +847,18 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { } RuntimeCode.requireInterpreterLvalueReturn(code, retVal, callContext); RuntimeList retList = RuntimeCode.returnList( - retVal, callContext, !RuntimeCode.isLvalueCode(code)); + retVal, callContext, + !RuntimeCode.isLvalueCode(code) + || code.isTryExpressionWrapper); RuntimeCode.materializeSpecialVarsInResult( retList, RuntimeCode.currentRawCallContext()); frame.returnedClosures = collectReturnedClosures(retList); - if (!returnListContainsTrackedReference(retList)) { - MortalList.flushAboveMark(); - } - + // Leave frame-local decrements queued here. The + // RuntimeCode call boundary releases lexical + // registrations before flushing them; flushing + // at the opcode can still see the returning + // frame as an owner and postpone DESTROY until + // the owner release at the call boundary. return retList; } @@ -812,6 +877,10 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { retList, RuntimeCode.currentRawCallContext()); frame.returnedClosures = collectReturnedClosures(retList); + // This opcode exits the active interpreted frame + // directly. Run its lexical teardown before the + // RETURN marker crosses into the caller. + cleanupMyVarRegisters(frame); return new RuntimeControlFlowList(retList, code.sourceName, code.sourceLine); } @@ -990,7 +1059,18 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { int dest = bytecode[pc++]; int src = bytecode[pc++]; RuntimeBase srcVal = registers[src]; - registers[dest] = isImmutableProxy(srcVal) ? ensureMutableScalar(srcVal) : srcVal; + RuntimeBase aliasValue = isImmutableProxy(srcVal) + ? ensureMutableScalar(srcVal) : srcVal; + RuntimeBase displaced = registers[dest]; + boolean callerOwned = RuntimeCode.isActiveLexicalCellInCallerFrame( + displaced, code); + if (!callerOwned) { + MyVarCleanupStack.replace(displaced, aliasValue); + } + // A register can be a borrowed alias to a caller's + // lexical cell. Do not move that caller's cleanup-stack + // entry into this frame; the caller still owns the cell. + registers[dest] = aliasValue; } case Opcodes.ALIAS_LVALUE_REFERENCE -> { @@ -1384,7 +1464,7 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { String name = code.stringPool[nameIdx]; if (name.equals("__SUB__")) { // __SUB__ returns the current subroutine being executed - RuntimeScalar selfReference = code.__SUB__; + RuntimeScalar selfReference = frame.selfReference; if (code.isQuotedRegexCallback) { // A qr// callback is compiled once but can be invoked by // different enclosing CVs. At execution time the active @@ -1526,7 +1606,7 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { // Undef assignment must release the value through // the existing scalar cell. Replacing the cell // defers weakly observed aggregate cleanup until - // a later sweep, after Perl code can observe it. + // normal owner-slot cleanup after Perl code can observe it. if (sourceScalar.type == RuntimeScalarType.UNDEF || lexicalAssignmentMustPreserveSlot(target) || (sourceScalar.type == RuntimeScalarType.GLOBREFERENCE @@ -1706,6 +1786,13 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { pc = OpcodeHandlerExtended.executeIteratorNext(bytecode, pc, registers); } + case Opcodes.FOREACH_SOURCE_RELEASE -> { + // Release the temporary source-value lease acquired with the iterator. + int iterReg = bytecode[pc++]; + OpcodeHandlerExtended.releaseForeachSourceOwners( + (RuntimeScalar) registers[iterReg]); + } + case Opcodes.FOREACH_NEXT_OR_EXIT -> { // Superinstruction for foreach loops (do-while layout). // Combines: hasNext check, next() call, and conditional jump to body. @@ -2131,6 +2218,11 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { // Handle RETURN markers: consume at non-map/grep boundaries, propagate in map/grep if (flow.getControlFlowType() == ControlFlowType.RETURN) { if (!code.isMapGrepBlock) { + // Consuming this marker returns directly from the + // active interpreter frame, bypassing RETURN and its + // ordinary lexical teardown opcodes. Retire that + // frame's slots before returning the value. + cleanupMyVarRegisters(frame); // Consume: unwrap and return the value from this subroutine RuntimeBase retVal = flow.getReturnValue(); return retVal != null ? retVal.getList() : new RuntimeList(); @@ -2223,7 +2315,7 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { } unwindEvalMethodInvocantHolds( evalMethodInvocantHoldDepthStack, - methodInvocantHolds); + methodInvocantHolds, evalBaseRegStack, registers); // Jump to eval catch handler pc = evalCatchStack.pop(); popEvalCallerFrame(frame); @@ -2411,7 +2503,7 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { } unwindEvalMethodInvocantHolds( evalMethodInvocantHoldDepthStack, - methodInvocantHolds); + methodInvocantHolds, evalBaseRegStack, registers); pc = evalCatchStack.pop(); popEvalCallerFrame(frame); RuntimeCode.decrementEvalDepth(); @@ -2911,8 +3003,11 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { // Push catch PC onto eval stack evalCatchStack.push(catchPc); + frame.evalMortalMarkDepthStack.push(MortalList.markDepth()); + frame.evalScopeCleanupBatchDepthStack.push(scopeCleanupBatches.size()); frame.evalControlBlockDepthStack.push(new int[]{ - controlBlockStack.size(), labeledBlockStack.size()}); + controlBlockStack.size(), labeledBlockStack.size(), + visibleEvalFrame ? 1 : 0}); // Save first body register for scope cleanup on exception evalBaseRegStack.push(firstBodyReg); @@ -2950,6 +3045,12 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { if (!evalCatchStack.isEmpty()) { evalCatchStack.pop(); } + if (!frame.evalMortalMarkDepthStack.isEmpty()) { + frame.evalMortalMarkDepthStack.pop(); + } + if (!frame.evalScopeCleanupBatchDepthStack.isEmpty()) { + frame.evalScopeCleanupBatchDepthStack.pop(); + } popEvalCallerFrame(frame); // Pop the base register (not needed on success path) @@ -2983,6 +3084,21 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { int rd = bytecode[pc++]; int context = bytecode[pc++]; + // The exception jumped over lexical block exits + // in the eval body. Discard their mortal marks and + // deferred cleanup batches before continuing at the + // catch site. + if (!frame.evalMortalMarkDepthStack.isEmpty()) { + MortalList.restoreMarkDepth( + frame.evalMortalMarkDepthStack.pop()); + } + if (!frame.evalScopeCleanupBatchDepthStack.isEmpty()) { + int batchDepth = frame.evalScopeCleanupBatchDepthStack.pop(); + while (scopeCleanupBatches.size() > batchDepth) { + scopeCleanupBatches.pop(); + } + } + // WarnDie.catchEval() should have already been called to set $@ // Perl returns an empty list from a failed eval in list context, // but undef in scalar context. @@ -3193,7 +3309,7 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { Opcodes.STATE_RETRIEVE_ARRAY, Opcodes.STATE_IS_INITIALIZED, Opcodes.STATE_MARK_INITIALIZED, Opcodes.STATE_ALIAS_ARRAY, Opcodes.STATE_ALIAS_HASH, Opcodes.STATE_RETRIEVE_HASH -> { - pc = executeScopeOps(opcode, bytecode, pc, registers, code); + pc = executeScopeOps(opcode, bytecode, pc, registers, code, frame.selfReference); } // Group 6-8: System Calls and IPC (132-150) @@ -3234,7 +3350,9 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { case Opcodes.EVAL_STRING, Opcodes.SELECT_OP, Opcodes.LOAD_GLOB, Opcodes.LOAD_GLOB_CANONICAL, Opcodes.SLEEP_OP, Opcodes.ALARM_OP, Opcodes.DEREF_GLOB, Opcodes.DEREF_GLOB_NONSTRICT, Opcodes.LOAD_GLOB_DYNAMIC, Opcodes.DEREF_SCALAR_STRICT, - Opcodes.DEREF_SCALAR_NONSTRICT, Opcodes.CODE_DEREF_NONSTRICT, + Opcodes.DEREF_SCALAR_STRICT_TEMP, + Opcodes.DEREF_SCALAR_NONSTRICT, Opcodes.DEREF_SCALAR_NONSTRICT_TEMP, + Opcodes.CODE_DEREF_NONSTRICT, Opcodes.CODE_DEREF_STRICT, Opcodes.REFALIAS_CODE_REFERENCE, Opcodes.REFALIAS_SCALAR_REFERENCE, Opcodes.NAMED_CODE_REFERENCE, Opcodes.DIRECT_NAMED_CODE_CALL, @@ -3748,6 +3866,7 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { } frame.pc = pc; + frame.retainSuspendedLexicalOwners(); frame.suspendedRegexState = new RegexState(); frame.suspendedPackage = currentPackageScalar.toString(); frame.suspended = true; @@ -3790,7 +3909,7 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { int catchPc = evalCatchStack.pop(); popEvalCallerFrame(frame); unwindEvalMethodInvocantHolds( - evalMethodInvocantHoldDepthStack, methodInvocantHolds); + evalMethodInvocantHoldDepthStack, methodInvocantHolds, evalBaseRegStack, registers); // Restore local variables pushed inside the eval block if (!evalLocalLevelStack.isEmpty()) { int relativeLevel = evalLocalLevelStack.pop(); @@ -3830,6 +3949,54 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { frame.propagatingException = e; throw e; } catch (Throwable e) { + if (e instanceof PerlNonLocalReturnException transfer + && transfer.targetCode == null && !evalCatchStack.isEmpty() + && !frame.evalControlBlockDepthStack.isEmpty() + && frame.evalControlBlockDepthStack.peek()[2] != 0) { + int catchPc = evalCatchStack.pop(); + if (!frame.evalMortalMarkDepthStack.isEmpty()) { + MortalList.restoreMarkDepth( + frame.evalMortalMarkDepthStack.pop()); + } + if (!frame.evalScopeCleanupBatchDepthStack.isEmpty()) { + int batchDepth = frame.evalScopeCleanupBatchDepthStack.pop(); + while (scopeCleanupBatches.size() > batchDepth) { + scopeCleanupBatches.pop(); + } + } + int baseReg = evalBaseRegStack.peek(); + java.util.ArrayList locals = new java.util.ArrayList<>(); + BitSet myVars = code.myVarRegisters; + for (int i = myVars.nextSetBit(baseReg); + i >= 0 && i < registers.length; i = myVars.nextSetBit(i + 1)) { + if (registers[i] != null) locals.add(registers[i]); + } + int resultReg = bytecode[catchPc + 1]; + int resultContext = bytecode[catchPc + 2]; + if (resultContext == RuntimeContextType.RUNTIME) resultContext = callContext; + registers[resultReg] = RuntimeCode.finishEvalCallbackReturn( + transfer, locals.toArray(), resultContext, () -> { + popEvalCallerFrame(frame); + unwindEvalMethodInvocantHolds(evalMethodInvocantHoldDepthStack, + methodInvocantHolds, evalBaseRegStack, registers); + evalBaseRegStack.pop(); + if (!evalLocalLevelStack.isEmpty()) { + int relativeLevel = evalLocalLevelStack.pop(); + DynamicVariableManager.popToLocalLevel(savedLocalLevel + relativeLevel); + } + RuntimeCode.decrementEvalDepth(); + }); + for (int i = myVars.nextSetBit(baseReg); + i >= 0 && i < registers.length; i = myVars.nextSetBit(i + 1)) { + if (i != resultReg) { + frame.releaseSuspendedOwnerForRegister(i); + registers[i] = null; + } + } + // Skip the failed-eval result opcode: this transfer succeeded. + pc = catchPc + 3; + continue outer; + } // Check if we're inside an eval block if (!evalCatchStack.isEmpty()) { Throwable evalException = e; @@ -3837,7 +4004,7 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { int catchPc = evalCatchStack.pop(); // Pop the catch handler popEvalCallerFrame(frame); unwindEvalMethodInvocantHolds( - evalMethodInvocantHoldDepthStack, methodInvocantHolds); + evalMethodInvocantHoldDepthStack, methodInvocantHolds, evalBaseRegStack, registers); // Scope exit cleanup for lexical variables allocated inside the eval body. // When die throws a PerlDieException, the SCOPE_EXIT_CLEANUP opcodes @@ -3847,13 +4014,16 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { int baseReg = evalBaseRegStack.pop(); boolean needsFlush = false; BitSet myVars = code.myVarRegisters; - for (int i = myVars.nextSetBit(baseReg); - i >= 0 && i < registers.length; - i = myVars.nextSetBit(i + 1)) { + // Registers are allocated in declaration order. Exception + // cleanup must therefore visit them in reverse order so + // deferred DESTROY calls preserve Perl's lexical LIFO order. + for (int i = registers.length - 1; i >= baseReg; i--) { + if (!myVars.get(i)) continue; RuntimeBase reg = registers[i]; if (reg == null) continue; if (reg instanceof RuntimeScalar rs) { RuntimeScalar.scopeExitCleanup(rs); + unbindActiveLexicalNamesForRegister(code, i, reg); needsFlush = true; } else if (reg instanceof RuntimeHash rh) { MortalList.scopeExitCleanupHash(rh); @@ -3862,6 +4032,7 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { MortalList.scopeExitCleanupArray(ra); needsFlush = true; } + frame.releaseSuspendedOwnerForRegister(i); MyVarCleanupStack.unregister(reg); registers[i] = null; } @@ -3942,21 +4113,32 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { releaseMethodInvocantHoldsAbove(methodInvocantHolds, 0); } - // Release captures for interpreter closures created in this frame - // that were never stored via set() (refCount stayed at 0). + // Request capture retirement for interpreter closures created in + // this frame that were not returned. The CODE owner ledger decides + // whether a strong owner still needs the captures. // This handles eval STRING map/grep block closures that over-capture // all visible variables but are temporary and should release captures. - // Closures stored via set() have refCount > 0 and are skipped. - // This matches the JVM-compiled path where scopeExitCleanup releases - // captures for CODE refs with refCount=0 (see RuntimeScalar.java + // Also retire unregistered temporary CODE scalar cells that only + // appear as borrowed values in an aliased @_ array. + // This matches the JVM-compiled path where scopeExitCleanup asks the + // owner ledger to retire temporary CODE captures (see RuntimeScalar.java // scopeExitCleanup special case for CODE refs). if (!frame.suspended && !createdClosures.isEmpty()) { + boolean releasedTemporaryCodeOwner = false; + for (RuntimeCode closure : createdClosures) { + if ((closure.capturedScalars == null && closure.capturedAggregates == null) + || RuntimeCode.isActiveCode(closure) + || (frame.returnedClosures != null + && frame.returnedClosures.contains(closure))) continue; + releasedTemporaryCodeOwner |= closure.releaseTemporaryCodeScalarOwners(); + } + if (releasedTemporaryCodeOwner) { + MortalList.flush(); + } for (RuntimeCode closure : createdClosures) { if ((closure.capturedScalars != null || closure.capturedAggregates != null) - && closure.refCount == 0 - && closure.stashRefCount <= 0 && (frame.returnedClosures == null || !frame.returnedClosures.contains(closure))) { - closure.releaseCaptures(); + closure.requestCaptureReleaseWhenUnowned(); } } } @@ -3972,13 +4154,13 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { // would incorrectly decrement refCounts, causing premature DESTROY. BitSet myVars = code.myVarRegisters; boolean needsFlush = false; - for (int i = myVars.nextSetBit(firstMyVarReg); - i >= 0 && i < registers.length; - i = myVars.nextSetBit(i + 1)) { + for (int i = registers.length - 1; i >= firstMyVarReg; i--) { + if (!myVars.get(i)) continue; RuntimeBase reg = registers[i]; if (reg == null) continue; if (reg instanceof RuntimeScalar rs) { RuntimeScalar.scopeExitCleanup(rs); + unbindActiveLexicalNamesForRegister(code, i, reg); needsFlush = true; } else if (reg instanceof RuntimeHash rh) { MortalList.scopeExitCleanupHash(rh); @@ -3987,6 +4169,7 @@ private static RuntimeList execute(SuspendedInterpreterFrame frame) { MortalList.scopeExitCleanupArray(ra); needsFlush = true; } + frame.releaseSuspendedOwnerForRegister(i); MyVarCleanupStack.unregister(reg); registers[i] = null; } @@ -4043,11 +4226,28 @@ private static void releaseMethodInvocantHoldsAbove( private static void unwindEvalMethodInvocantHolds( ArrayDeque evalMethodInvocantHoldDepthStack, - ArrayList methodInvocantHolds) { + ArrayList methodInvocantHolds, + ArrayDeque evalBaseRegStack, RuntimeBase[] registers) { + // Inline evals share their enclosing call frame. Retire only staging + // temporaries allocated in this eval; an outer call can still be + // evaluating its later arguments when the inner eval catches a die. + boolean releasedArguments = false; + if (!evalBaseRegStack.isEmpty()) { + for (int i = evalBaseRegStack.peek(); i < registers.length; i++) { + if (registers[i] instanceof RuntimeCode.CallArguments arguments) { + arguments.finish(); + registers[i] = null; + releasedArguments = true; + } + } + } if (!evalMethodInvocantHoldDepthStack.isEmpty()) { releaseMethodInvocantHoldsAbove( methodInvocantHolds, evalMethodInvocantHoldDepthStack.pop()); } + if (releasedArguments) { + MortalList.flushAboveMark(); + } } /** @@ -4526,7 +4726,8 @@ private static int executeArrayStringOps(int opcode, int[] bytecode, int pc, * Handles: RETRIEVE_BEGIN_*, LOCAL_SCALAR */ private static int executeScopeOps(int opcode, int[] bytecode, int pc, - RuntimeBase[] registers, InterpretedCode code) { + RuntimeBase[] registers, InterpretedCode code, + RuntimeScalar selfReference) { switch (opcode) { case Opcodes.RETRIEVE_BEGIN_SCALAR -> { return SlowOpcodeHandler.executeRetrieveBeginScalar(bytecode, pc, registers, code); @@ -4570,7 +4771,7 @@ private static int executeScopeOps(int opcode, int[] bytecode, int pc, // State belongs to the executing closure, not the interpreter // process. Falling back to an undefined code ref put every // anonymous-sub clone into the same global state cell. - RuntimeScalar codeRef = code.__SUB__ != null ? code.__SUB__ : new RuntimeScalar(); + RuntimeScalar codeRef = selfReference != null ? selfReference : new RuntimeScalar(); // Retrieve without removing (unlike RETRIEVE_BEGIN_SCALAR) RuntimeScalar stateVar = StateVariable.retrieveStateScalar(codeRef, varName, persistId); registers[rd] = stateVar; @@ -4587,7 +4788,7 @@ private static int executeScopeOps(int opcode, int[] bytecode, int pc, int nameIdx = bytecode[pc++]; int persistId = bytecode[pc++]; String varName = code.stringPool[nameIdx]; - RuntimeScalar codeRef = code.__SUB__ != null ? code.__SUB__ : new RuntimeScalar(); + RuntimeScalar codeRef = selfReference != null ? selfReference : new RuntimeScalar(); RuntimeArray stateArr = StateVariable.retrieveStateArray(codeRef, varName, persistId); registers[rd] = stateArr; RuntimeScalar isInit = StateVariable.isInitializedStateVariable(codeRef, varName, persistId); @@ -4601,7 +4802,7 @@ private static int executeScopeOps(int opcode, int[] bytecode, int pc, int rd = bytecode[pc++]; int nameIdx = bytecode[pc++]; int persistId = bytecode[pc++]; - RuntimeScalar codeRef = code.__SUB__ != null ? code.__SUB__ : new RuntimeScalar(); + RuntimeScalar codeRef = selfReference != null ? selfReference : new RuntimeScalar(); registers[rd] = StateVariable.retrieveStateArray(codeRef, code.stringPool[nameIdx], persistId); return pc; } @@ -4609,7 +4810,7 @@ private static int executeScopeOps(int opcode, int[] bytecode, int pc, int rd = bytecode[pc++]; int nameIdx = bytecode[pc++]; int persistId = bytecode[pc++]; - RuntimeScalar codeRef = code.__SUB__ != null ? code.__SUB__ : new RuntimeScalar(); + RuntimeScalar codeRef = selfReference != null ? selfReference : new RuntimeScalar(); registers[rd] = StateVariable.retrieveStateHash(codeRef, code.stringPool[nameIdx], persistId); return pc; } @@ -4618,7 +4819,7 @@ private static int executeScopeOps(int opcode, int[] bytecode, int pc, int sourceReg = bytecode[pc++]; int nameIdx = bytecode[pc++]; int persistId = bytecode[pc++]; - RuntimeScalar codeRef = code.__SUB__ != null ? code.__SUB__ : new RuntimeScalar(); + RuntimeScalar codeRef = selfReference != null ? selfReference : new RuntimeScalar(); RuntimeBase source = registers[sourceReg]; // Whole-array refaliasing may provide the aggregate directly // (for an array literal) or as the scalar array reference @@ -4635,7 +4836,7 @@ private static int executeScopeOps(int opcode, int[] bytecode, int pc, int sourceReg = bytecode[pc++]; int nameIdx = bytecode[pc++]; int persistId = bytecode[pc++]; - RuntimeScalar codeRef = code.__SUB__ != null ? code.__SUB__ : new RuntimeScalar(); + RuntimeScalar codeRef = selfReference != null ? selfReference : new RuntimeScalar(); RuntimeBase source = registers[sourceReg]; RuntimeHash hash = source instanceof RuntimeHash direct ? direct : source.scalar().hashDeref(); @@ -4649,7 +4850,7 @@ private static int executeScopeOps(int opcode, int[] bytecode, int pc, int nameIdx = bytecode[pc++]; int persistId = bytecode[pc++]; String varName = code.stringPool[nameIdx]; - RuntimeScalar codeRef = code.__SUB__ != null ? code.__SUB__ : new RuntimeScalar(); + RuntimeScalar codeRef = selfReference != null ? selfReference : new RuntimeScalar(); RuntimeHash stateHash = StateVariable.retrieveStateHash(codeRef, varName, persistId); registers[rd] = stateHash; RuntimeScalar isInit = StateVariable.isInitializedStateVariable(codeRef, varName, persistId); @@ -4664,7 +4865,7 @@ private static int executeScopeOps(int opcode, int[] bytecode, int pc, int nameIdx = bytecode[pc++]; int persistId = bytecode[pc++]; String varName = code.stringPool[nameIdx]; - RuntimeScalar codeRef = code.__SUB__ != null ? code.__SUB__ : new RuntimeScalar(); + RuntimeScalar codeRef = selfReference != null ? selfReference : new RuntimeScalar(); registers[rd] = StateVariable.retrieveStateScalar(codeRef, varName, persistId); return pc; } @@ -4673,7 +4874,7 @@ private static int executeScopeOps(int opcode, int[] bytecode, int pc, int nameIdx = bytecode[pc++]; int persistId = bytecode[pc++]; String varName = code.stringPool[nameIdx]; - RuntimeScalar codeRef = code.__SUB__ != null ? code.__SUB__ : new RuntimeScalar(); + RuntimeScalar codeRef = selfReference != null ? selfReference : new RuntimeScalar(); registers[rd] = StateVariable.isInitializedStateVariable(codeRef, varName, persistId); return pc; } @@ -4681,7 +4882,7 @@ private static int executeScopeOps(int opcode, int[] bytecode, int pc, int nameIdx = bytecode[pc++]; int persistId = bytecode[pc++]; String varName = code.stringPool[nameIdx]; - RuntimeScalar codeRef = code.__SUB__ != null ? code.__SUB__ : new RuntimeScalar(); + RuntimeScalar codeRef = selfReference != null ? selfReference : new RuntimeScalar(); StateVariable.markInitializedStateVariable(codeRef, varName, persistId); return pc; } @@ -4916,6 +5117,9 @@ private static int executeSpecialIO(int opcode, int[] bytecode, int pc, case Opcodes.DEREF_SCALAR_STRICT -> { return SlowOpcodeHandler.executeDerefScalarStrict(bytecode, pc, registers); } + case Opcodes.DEREF_SCALAR_STRICT_TEMP -> { + return SlowOpcodeHandler.executeDerefScalarStrictTemp(bytecode, pc, registers); + } case Opcodes.REJECT_LOCALIZE_REFERENCE -> { return SlowOpcodeHandler.executeRejectLocalizeReference(bytecode, pc, registers); } @@ -4937,6 +5141,9 @@ private static int executeSpecialIO(int opcode, int[] bytecode, int pc, case Opcodes.DEREF_SCALAR_NONSTRICT -> { return SlowOpcodeHandler.executeDerefScalarNonStrict(bytecode, pc, registers, code); } + case Opcodes.DEREF_SCALAR_NONSTRICT_TEMP -> { + return SlowOpcodeHandler.executeDerefScalarNonStrictTemp(bytecode, pc, registers, code); + } case Opcodes.CODE_DEREF_NONSTRICT -> { return SlowOpcodeHandler.executeCodeDerefNonStrict(bytecode, pc, registers, code); } diff --git a/src/main/java/org/perlonjava/backend/bytecode/CompileAssignment.java b/src/main/java/org/perlonjava/backend/bytecode/CompileAssignment.java index 2964cafd0f..ef9c992913 100644 --- a/src/main/java/org/perlonjava/backend/bytecode/CompileAssignment.java +++ b/src/main/java/org/perlonjava/backend/bytecode/CompileAssignment.java @@ -2510,6 +2510,11 @@ && isLocalizedArraySliceReferenceTarget(referenceOp.operand)) { } bytecodeCompiler.emit(Opcodes.REGISTER_MY_VAR); bytecodeCompiler.emitReg(reg); + if (leftOp.getBooleanAnnotation("signatureParameterDeclaration")) { + // Signature defaults bypass lexical-alias resolution, + // so bind their fresh scalar cell explicitly. + bytecodeCompiler.emitActiveLexicalBinding(reg, varName); + } bytecodeCompiler.emitVarAttrsIfNeeded(leftOp, reg, "$"); bytecodeCompiler.emit(Opcodes.SET_SCALAR); bytecodeCompiler.emitReg(reg); @@ -2523,6 +2528,9 @@ && isLocalizedArraySliceReferenceTarget(referenceOp.operand)) { } bytecodeCompiler.emit(Opcodes.REGISTER_MY_VAR); bytecodeCompiler.emitReg(reg); + if (leftOp.getBooleanAnnotation("signatureParameterDeclaration")) { + bytecodeCompiler.emitActiveLexicalBinding(reg, varName); + } bytecodeCompiler.emit(Opcodes.SET_SCALAR); bytecodeCompiler.emitReg(reg); bytecodeCompiler.emitReg(valueReg); @@ -2827,6 +2835,11 @@ && isLocalizedArraySliceReferenceTarget(referenceOp.operand)) { } bytecodeCompiler.emit(Opcodes.REGISTER_MY_VAR); bytecodeCompiler.emitReg(varReg); + if (leftOp.getBooleanAnnotation("signatureParameterDeclaration")) { + // Signature parameters skip APPLY_LEXICAL_ALIAS; + // bind the constructed pad cell after registration. + bytecodeCompiler.emitActiveLexicalBinding(varReg, varName); + } bytecodeCompiler.emitVarAttrsIfNeeded(leftOp, varReg, sigil); } varRegs.add(varReg); @@ -3956,6 +3969,15 @@ && isLexicalSubStorage(hiddenScalar)) { bytecodeCompiler.emitReg(targetReg); bytecodeCompiler.emitReg(sourceReg); } + if (!bytecodeCompiler.isStateVariable(varName)) { + // Refaliasing makes this lexical name another + // owner of the shared cell. Keep its pad + // identity attached to the aliased cell so the + // source lexical can leave scope without + // releasing the final owner. + bytecodeCompiler.emitActiveLexicalBinding( + targetReg, varName); + } // `\$left = \$right` is itself a reference // expression. Keep the original RHS reference // for callers such as foo(\$left = \$right), diff --git a/src/main/java/org/perlonjava/backend/bytecode/CompileOperator.java b/src/main/java/org/perlonjava/backend/bytecode/CompileOperator.java index 46cc91329f..2a7612869e 100644 --- a/src/main/java/org/perlonjava/backend/bytecode/CompileOperator.java +++ b/src/main/java/org/perlonjava/backend/bytecode/CompileOperator.java @@ -27,18 +27,18 @@ private static String posAggregateOperand(Node operand) { } private static void emitSubroutineExitCleanup(BytecodeCompiler bc, int returnReg) { - java.util.List scalarIdxs = bc.symbolTable.getMyScalarIndicesInScope(0); + java.util.List scalarIdxs = bc.myScalarCleanupIndicesInScope(0); for (int idx : scalarIdxs) { if (idx == returnReg) continue; bc.emit(Opcodes.SCOPE_EXIT_CLEANUP); bc.emitReg(idx); } - java.util.List hashIdxs = bc.symbolTable.getMyHashIndicesInScope(0); + java.util.List hashIdxs = bc.myHashCleanupIndicesInScope(0); for (int idx : hashIdxs) { bc.emit(Opcodes.SCOPE_EXIT_CLEANUP_HASH); bc.emitReg(idx); } - java.util.List arrayIdxs = bc.symbolTable.getMyArrayIndicesInScope(0); + java.util.List arrayIdxs = bc.myArrayCleanupIndicesInScope(0); for (int idx : arrayIdxs) { bc.emit(Opcodes.SCOPE_EXIT_CLEANUP_ARRAY); bc.emitReg(idx); @@ -1447,19 +1447,22 @@ public static void visitOperator(BytecodeCompiler bytecodeCompiler, OperatorNode // Explicit 'return' bypasses the normal block-end cleanup. // Use return-specific cleanup opcodes so the returned register remains // readable by RETURN while lexical owner counts are still released. - java.util.List scalarIdxs = bytecodeCompiler.symbolTable.getMyScalarIndicesInScope(0); + exprReg = bytecodeCompiler.separateReturnRegister(exprReg); + bytecodeCompiler.emit(Opcodes.PREPARE_SCOPE_RETURN); + bytecodeCompiler.emitReg(exprReg); + java.util.List scalarIdxs = bytecodeCompiler.myScalarCleanupIndicesInScope(0); for (int idx : scalarIdxs) { bytecodeCompiler.emit(Opcodes.RETURN_SCOPE_CLEANUP); bytecodeCompiler.emitReg(idx); bytecodeCompiler.emitReg(exprReg); } - java.util.List hashIdxs = bytecodeCompiler.symbolTable.getMyHashIndicesInScope(0); + java.util.List hashIdxs = bytecodeCompiler.myHashCleanupIndicesInScope(0); for (int idx : hashIdxs) { bytecodeCompiler.emit(Opcodes.RETURN_SCOPE_CLEANUP_HASH); bytecodeCompiler.emitReg(idx); bytecodeCompiler.emitReg(exprReg); } - java.util.List arrayIdxs = bytecodeCompiler.symbolTable.getMyArrayIndicesInScope(0); + java.util.List arrayIdxs = bytecodeCompiler.myArrayCleanupIndicesInScope(0); for (int idx : arrayIdxs) { bytecodeCompiler.emit(Opcodes.RETURN_SCOPE_CLEANUP_ARRAY); bytecodeCompiler.emitReg(idx); diff --git a/src/main/java/org/perlonjava/backend/bytecode/Disassemble.java b/src/main/java/org/perlonjava/backend/bytecode/Disassemble.java index fdd55630df..23349aed36 100644 --- a/src/main/java/org/perlonjava/backend/bytecode/Disassemble.java +++ b/src/main/java/org/perlonjava/backend/bytecode/Disassemble.java @@ -32,22 +32,49 @@ public static String disassemble(InterpretedCode interpretedCode) { case Opcodes.MORTAL_FLUSH: sb.append("MORTAL_FLUSH\n"); break; + case Opcodes.MORTAL_STATEMENT_FLUSH: + sb.append("MORTAL_STATEMENT_FLUSH\n"); + break; case Opcodes.MORTAL_PUSH_MARK: sb.append("MORTAL_PUSH_MARK\n"); break; case Opcodes.MORTAL_POP_FLUSH: sb.append("MORTAL_POP_FLUSH\n"); break; + case Opcodes.MORTAL_PUSH_SCOPE_MARK: + sb.append("MORTAL_PUSH_SCOPE_MARK\n"); + break; + case Opcodes.MORTAL_POP_SCOPE_FLUSH: + sb.append("MORTAL_POP_SCOPE_FLUSH\n"); + break; case Opcodes.SCOPE_EXIT_CLEANUP: int secReg = interpretedCode.bytecode[pc++]; sb.append("SCOPE_EXIT_CLEANUP r").append(secReg).append("\n"); break; + case Opcodes.DEREF_SCALAR_STRICT_TEMP: + int dstStrictTemp = interpretedCode.bytecode[pc++]; + int srcStrictTemp = interpretedCode.bytecode[pc++]; + sb.append("DEREF_SCALAR_STRICT_TEMP r").append(dstStrictTemp) + .append(" = ${r").append(srcStrictTemp).append("}\n"); + break; case Opcodes.UNBIND_ACTIVE_LEXICAL: int ualReg = interpretedCode.bytecode[pc++]; int ualName = interpretedCode.bytecode[pc++]; sb.append("UNBIND_ACTIVE_LEXICAL r").append(ualReg) .append(" ").append(interpretedCode.stringPool[ualName]).append("\n"); break; + case Opcodes.SNAPSHOT_SCOPE_RESULT: + int ssrDestination = interpretedCode.bytecode[pc++]; + int ssrSource = interpretedCode.bytecode[pc++]; + int ssrContext = interpretedCode.bytecode[pc++]; + sb.append("SNAPSHOT_SCOPE_RESULT r").append(ssrDestination) + .append(" source=r").append(ssrSource) + .append(" context=").append(ssrContext).append("\n"); + break; + case Opcodes.PREPARE_SCOPE_RETURN: + int psrReturnReg = interpretedCode.bytecode[pc++]; + sb.append("PREPARE_SCOPE_RETURN return=r").append(psrReturnReg).append("\n"); + break; case Opcodes.RETURN_SCOPE_CLEANUP: int rscReg = interpretedCode.bytecode[pc++]; int rscReturnReg = interpretedCode.bytecode[pc++]; @@ -1604,6 +1631,10 @@ public static String disassemble(InterpretedCode interpretedCode) { rs = interpretedCode.bytecode[pc++]; sb.append("ITERATOR_NEXT r").append(rd).append(" = r").append(rs).append(".next()\n"); break; + case Opcodes.FOREACH_SOURCE_RELEASE: + rs = interpretedCode.bytecode[pc++]; + sb.append("FOREACH_SOURCE_RELEASE r").append(rs).append("\n"); + break; case Opcodes.FOREACH_NEXT_OR_EXIT: { rd = interpretedCode.bytecode[pc++]; int iterReg = interpretedCode.bytecode[pc++]; @@ -1824,6 +1855,14 @@ public static String disassemble(InterpretedCode interpretedCode) { nameIdx = interpretedCode.bytecode[pc++]; sb.append("DEREF_SCALAR_NONSTRICT r").append(rd).append(" = ${r").append(rs).append("} pkg=").append(interpretedCode.stringPool[nameIdx]).append("\n"); break; + case Opcodes.DEREF_SCALAR_NONSTRICT_TEMP: + rd = interpretedCode.bytecode[pc++]; + rs = interpretedCode.bytecode[pc++]; + nameIdx = interpretedCode.bytecode[pc++]; + sb.append("DEREF_SCALAR_NONSTRICT_TEMP r").append(rd) + .append(" = ${r").append(rs).append("} pkg=") + .append(interpretedCode.stringPool[nameIdx]).append("\n"); + break; case Opcodes.CODE_DEREF_NONSTRICT: rd = interpretedCode.bytecode[pc++]; rs = interpretedCode.bytecode[pc++]; diff --git a/src/main/java/org/perlonjava/backend/bytecode/FutureAsyncAwaitRuntime.java b/src/main/java/org/perlonjava/backend/bytecode/FutureAsyncAwaitRuntime.java index 4161e505cc..82ea88a16e 100644 --- a/src/main/java/org/perlonjava/backend/bytecode/FutureAsyncAwaitRuntime.java +++ b/src/main/java/org/perlonjava/backend/bytecode/FutureAsyncAwaitRuntime.java @@ -98,14 +98,19 @@ private static void attach(InterpreterSuspension suspension, AwaitState state) { } return; } - // Future::AsyncAwait requires cancellation to flow from the Future returned by - // the async sub to the Future currently being awaited. Do this for every - // suspension segment, since a resumed frame may await a different Future. - call(outer, "AWAIT_CHAIN_CANCEL", - new RuntimeArray(suspension.awaited), RuntimeContextType.VOID); - PerlRuntime runtime = PerlRuntime.current(); - RuntimeCode callback = new RuntimeCode((callbackArgs, callbackContext) -> { + suspension.frame.registerSuspendedContinuation(runtime.executionState()); + + AtomicBoolean callbackEntered = new AtomicBoolean(); + try { + // Future::AsyncAwait requires cancellation to flow from the Future returned by + // the async sub to the Future currently being awaited. Do this for every + // suspension segment, since a resumed frame may await a different Future. + call(outer, "AWAIT_CHAIN_CANCEL", + new RuntimeArray(suspension.awaited), RuntimeContextType.VOID); + + RuntimeCode callback = new RuntimeCode((callbackArgs, callbackContext) -> { + callbackEntered.set(true); // Capture the callback's dynamic warning handler before enqueueing. // Nested Future completions can defer this resume until after the // readiness callback (and its localized %SIG scope) has returned. @@ -118,15 +123,25 @@ private static void attach(InterpreterSuspension suspension, AwaitState state) { state.callbackActive.set(false); } if (callbackWarningHandler != null) { - callbackWarningHandler.releaseClosureCapture(); RuntimeScalar.scopeExitCleanup(callbackWarningHandler); } } }); return new RuntimeList(); - }, null).bindCallbackTo(runtime); - call(suspension.awaited, "AWAIT_ON_READY", - new RuntimeArray(new RuntimeScalar(callback)), RuntimeContextType.VOID); + }, null).bindCallbackTo(runtime); + call(suspension.awaited, "AWAIT_ON_READY", + new RuntimeArray(new RuntimeScalar(callback)), RuntimeContextType.VOID); + } catch (RuntimeException | Error attachFailure) { + if (!callbackEntered.get()) { + state.terminal.set(true); + try { + suspension.releaseAwaitedOwner(); + } finally { + cleanupAbandonedFrame(suspension.frame); + } + } + throw attachFailure; + } } private static void resume(InterpreterSuspension suspension, AwaitState state, @@ -215,6 +230,7 @@ private static void resume(InterpreterSuspension suspension, AwaitState state, outer = state.outerAfterResume(); if (outer == null) { state.terminal.set(true); + suspension.frame.releaseSuspendedLexicalOwners(); warnLostReturningFuture(suspension.frame, callbackWarningHandler); return; } @@ -223,9 +239,13 @@ private static void resume(InterpreterSuspension suspension, AwaitState state, } try { if (isCancelled(outer)) { + suspension.frame.releaseSuspendedLexicalOwners(); state.clearOuterProbe(); return; } + // The interpreter has produced and transferred its return value; + // retire frame lexicals before AWAIT_DONE can invoke callbacks. + suspension.frame.releaseSuspendedLexicalOwners(); call(outer, "AWAIT_DONE", new RuntimeArray(result), RuntimeContextType.VOID); state.clearOuterProbe(); } catch (Throwable error) { @@ -238,6 +258,7 @@ private static void completeFailure(AwaitState state, SuspendedInterpreterFrame RuntimeScalar outer = state.outerAfterResume(); if (outer == null) { state.terminal.set(true); + frame.releaseSuspendedLexicalOwners(); warnAbandonedFailure(frame, error, callbackWarningHandler); return; } @@ -245,9 +266,11 @@ private static void completeFailure(AwaitState state, SuspendedInterpreterFrame return; } if (isCancelled(outer)) { + frame.releaseSuspendedLexicalOwners(); state.clearOuterProbe(); return; } + frame.releaseSuspendedLexicalOwners(); call(outer, "AWAIT_FAIL", new RuntimeArray(exceptionValue(error)), RuntimeContextType.VOID); state.clearOuterProbe(); @@ -322,9 +345,7 @@ RuntimeScalar outerAfterResume() { return null; } if (outerWeak.value instanceof RuntimeBase referent - && !ReachabilityWalker.isReachableFromRoots(referent) - && !ReachabilityWalker.isReachableFromLiveScalarRegistry(referent) - && !ReachabilityWalker.isReachableFromLiveCodeCaptures(referent)) { + && !referent.hasPerlStrongOwner()) { WeakRefRegistry.clearWeakRefsTo(referent); return null; } @@ -446,7 +467,6 @@ private static RuntimeScalar retainCurrentWarningHandler() { // anonymous handler and its lexical captures before it emits the // self-abandonment warning. Keep the closure graph alive until the // queued resume has completed. - retained.retainClosureCapture(); return retained; } diff --git a/src/main/java/org/perlonjava/backend/bytecode/InterpretedCode.java b/src/main/java/org/perlonjava/backend/bytecode/InterpretedCode.java index 0f9aa6fe03..9188bdd05e 100644 --- a/src/main/java/org/perlonjava/backend/bytecode/InterpretedCode.java +++ b/src/main/java/org/perlonjava/backend/bytecode/InterpretedCode.java @@ -56,6 +56,8 @@ public ScalarPin scalarPin(int nameIdx) { public int maxRegisters; // Number of registers needed public RuntimeBase[] capturedVars; // Closure support (captured from outer scope) public final Map variableRegistry; // Variable name → register index (for eval STRING) + /** All lexical scalar names by register, including names from exited compiler scopes. */ + public Map> myScalarNamesByRegister = Map.of(); public final List> evalSiteRegistries; // Per-eval-site variable registries public final List> evalSiteLexicalSubroutineBindings; public final List> evalSiteParserKeywordPlugins; @@ -119,22 +121,21 @@ public void releaseRegisters() { public final ErrorMessageUtil errorUtil; // For converting token index to line numbers // BitSet of register indices that are actual "my" variables (not temporaries). - // Computed from SCOPE_EXIT_CLEANUP opcodes in the bytecode. - // Used by exception propagation cleanup to avoid calling scopeExitCleanup - // on temporaries that may alias hash/array elements (which would incorrectly - // decrement refCounts and cause premature DESTROY). + // Computed from scope-exit cleanup opcodes in the bytecode. + // Used by early frame teardown (exceptions and non-local returns) to avoid + // calling scopeExitCleanup on temporaries that may alias hash/array elements + // (which would incorrectly decrement refCounts and cause premature DESTROY). public final BitSet myVarRegisters; /** - * Scan bytecodes for SCOPE_EXIT_CLEANUP, SCOPE_EXIT_CLEANUP_HASH, and - * SCOPE_EXIT_CLEANUP_ARRAY opcodes to identify which registers hold actual - * "my" variables. These are the only registers that should get - * scopeExitCleanup during exception propagation. + * Scan bytecodes for scope-exit cleanup opcodes to identify registers + * holding actual "my" variables. These are the registers that should get + * scopeExitCleanup when early control flow bypasses ordinary block teardown. *

* Uses a simple scan: looks for the specific opcode values and reads the - * next int as the register index. Since SCOPE_EXIT_CLEANUP opcodes have - * high values (463, 466, 467) that are unlikely to appear as register - * indices, false positives are extremely rare. + * next int as the register index. Since these opcodes have high values + * (463 through 496) that are unlikely to appear as register indices, false + * positives are extremely rare. */ private static BitSet scanMyVarRegisters(int[] bytecode, int maxRegisters) { BitSet result = new BitSet(); @@ -142,7 +143,10 @@ private static BitSet scanMyVarRegisters(int[] bytecode, int maxRegisters) { int opcode = bytecode[i]; if (opcode == Opcodes.SCOPE_EXIT_CLEANUP || opcode == Opcodes.SCOPE_EXIT_CLEANUP_HASH - || opcode == Opcodes.SCOPE_EXIT_CLEANUP_ARRAY) { + || opcode == Opcodes.SCOPE_EXIT_CLEANUP_ARRAY + || opcode == Opcodes.RETURN_SCOPE_CLEANUP + || opcode == Opcodes.RETURN_SCOPE_CLEANUP_HASH + || opcode == Opcodes.RETURN_SCOPE_CLEANUP_ARRAY) { int register = bytecode[i + 1]; // This lightweight scan also sees opcode-shaped values in // instruction operands. Never let a following sentinel (for @@ -151,7 +155,10 @@ private static BitSet scanMyVarRegisters(int[] bytecode, int maxRegisters) { if (register >= 0 && register < maxRegisters) { result.set(register); } - i++; // skip the operand + // RETURN_SCOPE_CLEANUP and RETURN_SCOPE_CLEANUP_ARRAY have + // both a lexical register and a return-value register. + i += opcode == Opcodes.RETURN_SCOPE_CLEANUP + || opcode == Opcodes.RETURN_SCOPE_CLEANUP_ARRAY ? 2 : 1; } } return result; @@ -278,6 +285,19 @@ private InterpretedCode(int[] bytecode, Object[] constants, String[] stringPool, // exception propagation. Temporaries (hash element aliases, method return // values) are NOT in this set and should NOT get scopeExitCleanup. this.myVarRegisters = scanMyVarRegisters(bytecode, maxRegisters); + retainCodeTemplateConstants(); + } + + /** Record optree owners for file-compiled anonymous CODE templates. */ + private void retainCodeTemplateConstants() { + if (constants == null || sourceName == null || sourceName.startsWith("(eval ")) return; + for (Object constant : constants) { + if (constant instanceof RuntimeScalar scalar + && scalar.value instanceof RuntimeCode template + && template.isOptreeCodeTemplate) { + RuntimeCode.retainOptreeCodeTemplate(this, scalar); + } + } } private static String sourceTextFromErrorUtil(ErrorMessageUtil errorUtil) { @@ -448,6 +468,13 @@ public RuntimeList apply(RuntimeArray args, int callContext) { // retaining async initial-result wrapping from master. RuntimeList result = BytecodeInterpreter.execute( this, args, effectiveContext, this.subName); + if (result instanceof RuntimeControlFlowList flow + && flow.getControlFlowType() != ControlFlowType.TAILCALL) { + // A non-local control marker leaves this interpreted frame + // without reaching its normal block teardown opcodes. The + // tailcall trampoline owns the separate argument transfer. + MyVarCleanupStack.unwindTo(cleanupMark); + } result = RuntimeCode.handleEscapingLoopControl( result, generatedClassConstructor, classAdjustBlock); if (isSortComparator && result instanceof RuntimeControlFlowList flow) { @@ -470,6 +497,11 @@ public RuntimeList apply(RuntimeArray args, int callContext) { } MyVarCleanupStack.releaseOrTransferSocketOwnersOnReturn(cleanupMark, returned); return returned; + } catch (PerlNonLocalReturnException e) { + // The enclosing RuntimeCode boundary consumes the result; preserve + // its mortal owners while this frame's lexical cleanup is queued. + MyVarCleanupStack.unwindTo(cleanupMark); + throw e; } catch (RuntimeException e) { if (!(e instanceof PerlExitException)) { MyVarCleanupStack.unwindTo(cleanupMark); @@ -543,6 +575,9 @@ public RuntimeList apply(String subroutineName, RuntimeArray args, int callConte } return RuntimeCode.coerceScalarCallResult( result, effectiveContext, callContext, !RuntimeCode.isLvalueCode(this)); + } catch (PerlNonLocalReturnException e) { + // A map/grep return carries a value through this frame's unwind. + throw e; } catch (RuntimeException e) { if (!(e instanceof PerlExitException)) { MyVarCleanupStack.unwindTo(cleanupMark); @@ -569,13 +604,14 @@ public RuntimeList apply(String subroutineName, RuntimeArray args, int callConte } /** - * Override RuntimeCode.defined() to return true for InterpretedCode. - * InterpretedCode doesn't use methodHandle, so the parent defined() check fails. - * But InterpretedCode instances are always "defined" - they contain executable bytecode. + * InterpretedCode has executable bytecode instead of a methodHandle, so an + * installed interpreted CV is defined while its CODE reference is valid. + * `undef &name` explicitly retires that callable definition even though + * the bytecode object remains available to existing Java references. */ @Override public boolean defined() { - return true; + return !codeReferenceUndefined; } /** @@ -614,6 +650,8 @@ public InterpretedCode withCapturedVars(RuntimeBase[] capturedVars) { true, this.deparseSourceText ); + copy.installPadConstants(this.padConstants); + copy.setMyScalarNamesByRegister(this.myScalarNamesByRegister); copy.prototype = this.prototype; copy.isConstantCv = this.isConstantCv; copy.isLexicalConstantCv = this.isLexicalConstantCv; @@ -714,6 +752,19 @@ public void setEvalCapturedVars(RuntimeBase[] capturedVars) { } } + /** Preserve lexical names needed to unbind exact pad entries during exceptional unwind. */ + public void setMyScalarNamesByRegister(Map> namesByRegister) { + if (namesByRegister == null || namesByRegister.isEmpty()) { + myScalarNamesByRegister = Map.of(); + return; + } + Map> copy = new java.util.LinkedHashMap<>(); + for (Map.Entry> entry : namesByRegister.entrySet()) { + copy.put(entry.getKey(), List.copyOf(entry.getValue())); + } + myScalarNamesByRegister = Map.copyOf(copy); + } + private void validateAsyncSignature(RuntimeArray args) { if (!futureAsyncAwaitSub || signatureMinArgs < 0) { return; diff --git a/src/main/java/org/perlonjava/backend/bytecode/InterpreterSuspension.java b/src/main/java/org/perlonjava/backend/bytecode/InterpreterSuspension.java index 2afa8c068f..0d3cbbc68c 100644 --- a/src/main/java/org/perlonjava/backend/bytecode/InterpreterSuspension.java +++ b/src/main/java/org/perlonjava/backend/bytecode/InterpreterSuspension.java @@ -3,16 +3,15 @@ import org.perlonjava.runtime.runtimetypes.RuntimeBase; import org.perlonjava.runtime.runtimetypes.RuntimeList; import org.perlonjava.runtime.runtimetypes.RuntimeScalar; -import org.perlonjava.runtime.runtimetypes.RuntimeScalarType; -import org.perlonjava.runtime.runtimetypes.MortalList; +import org.perlonjava.runtime.runtimetypes.PerlOwnerSlot; +import org.perlonjava.runtime.runtimetypes.WeakRefRegistry; /** Internal result used only between the interpreter and async-sub wrapper. */ final class InterpreterSuspension extends RuntimeList { final SuspendedInterpreterFrame frame; final RuntimeScalar awaited; private final RuntimeScalar awaitedOwner; - private final RuntimeBase awaitedRoot; - private boolean awaitedRootRetained; + private final PerlOwnerSlot awaitedFrameOwner; final int destinationRegister; final int context; @@ -25,10 +24,8 @@ final class InterpreterSuspension extends RuntimeList { this.awaited = new RuntimeScalar(); this.awaited.set(awaited); this.awaitedOwner = this.awaited; - this.awaitedRoot = RuntimeScalarType.isReference(this.awaited) - && this.awaited.value instanceof RuntimeBase base ? base : null; - MortalList.retainSuspendedRoot(awaitedRoot); - this.awaitedRootRetained = awaitedRoot != null; + this.awaitedFrameOwner = new PerlOwnerSlot(PerlOwnerSlot.Kind.SUSPENDED_FRAME); + awaitedOwner.attachSuspendedFrameOwner(awaitedFrameOwner); this.destinationRegister = destinationRegister; this.context = context; } @@ -38,12 +35,17 @@ void setResult(RuntimeBase value) { } void releaseAwaitedOwner() { - if (awaitedOwner.getDefinedBoolean()) { - awaitedOwner.set(new RuntimeScalar()); - } - if (awaitedRootRetained) { - MortalList.releaseSuspendedRoot(awaitedRoot); - awaitedRootRetained = false; + RuntimeBase previousReferent = awaitedFrameOwner.referent(); + try { + if (awaitedOwner.getDefinedBoolean()) { + awaitedOwner.set(new RuntimeScalar()); + } + } finally { + try { + awaitedOwner.detachSuspendedFrameOwner(awaitedFrameOwner); + } finally { + WeakRefRegistry.onSuspendedFrameOwnerReleased(previousReferent); + } } } } diff --git a/src/main/java/org/perlonjava/backend/bytecode/OpcodeHandlerExtended.java b/src/main/java/org/perlonjava/backend/bytecode/OpcodeHandlerExtended.java index 8da5749e35..c18ee3c8a9 100644 --- a/src/main/java/org/perlonjava/backend/bytecode/OpcodeHandlerExtended.java +++ b/src/main/java/org/perlonjava/backend/bytecode/OpcodeHandlerExtended.java @@ -1099,6 +1099,7 @@ public static int executeCreateClosure(int[] bytecode, int pc, RuntimeBase[] reg // Without this, scopeExitCleanup() doesn't know the variable is still alive // via this closure, and may prematurely clear weak references to its value. java.util.List capturedScalars = new java.util.ArrayList<>(); + java.util.List capturedScalarOwnerSlots = new java.util.ArrayList<>(); java.util.List capturedAggregates = new java.util.ArrayList<>(); java.util.List capturedAggregateOwnerSlots = new java.util.ArrayList<>(); java.util.Set seenScalars = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>()); @@ -1107,16 +1108,18 @@ public static int executeCreateClosure(int[] bytecode, int pc, RuntimeBase[] reg if (captured instanceof RuntimeScalar s) { if (!seenScalars.add(s)) continue; capturedScalars.add(s); - s.retainClosureCapture(); + capturedScalarOwnerSlots.add(s.retainClosureCaptureSlot(closureCode)); } else if (captured instanceof RuntimeArray || captured instanceof RuntimeHash) { if (!seenAggregates.add(captured)) continue; capturedAggregates.add(captured); - PerlOwnerSlot ownerSlot = captured.retainClosureCaptureOwner(); + PerlOwnerSlot ownerSlot = captured.retainClosureCaptureOwner(closureCode); capturedAggregateOwnerSlots.add(ownerSlot); } } if (!capturedScalars.isEmpty()) { closureCode.capturedScalars = capturedScalars.toArray(new RuntimeScalar[0]); + closureCode.capturedScalarOwnerSlots = + capturedScalarOwnerSlots.toArray(new PerlOwnerSlot[0]); } if (!capturedAggregates.isEmpty()) { closureCode.capturedAggregates = capturedAggregates.toArray(new RuntimeBase[0]); @@ -1124,7 +1127,7 @@ public static int executeCreateClosure(int[] bytecode, int pc, RuntimeBase[] reg new PerlOwnerSlot[0]); } if (!capturedScalars.isEmpty() || !capturedAggregates.isEmpty()) { - closureCode.refCount = 0; + closureCode.startRefCountTracking(); } // Wrap in RuntimeScalar and set __SUB__ for self-reference @@ -1152,14 +1155,55 @@ public static int executeIteratorCreate(int[] bytecode, int pc, RuntimeBase[] re int rs = bytecode[pc++]; RuntimeBase iterable = registers[rs]; - java.util.Iterator iterator = iterable.iterator(); - - // Store iterator as a constant (preserve the Iterator object) - // Wrap in RuntimeScalar for storage - registers[rd] = new RuntimeScalar(iterator); + int sourceOwnerDepth = MortalList.pushForeachSourceOwners(iterable); + try { + java.util.Iterator iterator = iterable.iterator(); + registers[rd] = new RuntimeScalar( + new ForeachSourceIterator(iterator, sourceOwnerDepth)); + } catch (RuntimeException | Error failure) { + MortalList.restoreForeachSourceOwnerDepth(sourceOwnerDepth); + throw failure; + } return pc; } + /** Release the source-value owners paired with an interpreted foreach iterator. */ + public static void releaseForeachSourceOwners(RuntimeScalar iteratorScalar) { + if (iteratorScalar != null + && iteratorScalar.value instanceof ForeachSourceIterator iterator) { + iterator.releaseSourceOwners(); + } + } + + private static final class ForeachSourceIterator + implements java.util.Iterator { + private final java.util.Iterator delegate; + private final int sourceOwnerDepth; + private boolean released; + + private ForeachSourceIterator( + java.util.Iterator delegate, int sourceOwnerDepth) { + this.delegate = delegate; + this.sourceOwnerDepth = sourceOwnerDepth; + } + + @Override + public boolean hasNext() { + return delegate.hasNext(); + } + + @Override + public RuntimeScalar next() { + return delegate.next(); + } + + private void releaseSourceOwners() { + if (released) return; + released = true; + MortalList.restoreForeachSourceOwnerDepth(sourceOwnerDepth); + } + } + /** * Execute iterator has next operation. * Format: ITERATOR_HAS_NEXT rd iterReg diff --git a/src/main/java/org/perlonjava/backend/bytecode/Opcodes.java b/src/main/java/org/perlonjava/backend/bytecode/Opcodes.java index c1553a0a5e..ca081f8da5 100644 --- a/src/main/java/org/perlonjava/backend/bytecode/Opcodes.java +++ b/src/main/java/org/perlonjava/backend/bytecode/Opcodes.java @@ -2333,6 +2333,12 @@ public class Opcodes { */ public static final short MORTAL_POP_FLUSH = 465; + /** Push an unconditional dynamic-scope mark before a fresh-result block. */ + public static final short MORTAL_PUSH_SCOPE_MARK = 643; + + /** Pop and flush the matching unconditional fresh-result block mark. */ + public static final short MORTAL_POP_SCOPE_FLUSH = 644; + /** * Scope-exit cleanup for a my-hash register. * Walks hash values recursively for tracked blessed references @@ -2787,6 +2793,22 @@ public class Opcodes { /** Restore a loop regex baseline and retain a fresh baseline for its next iteration. Format: register. */ public static final short RESTORE_LOOP_REGEX_STATE = 631; + /** Preserve rvalue reference owners before a nested scope exits. Format: rd sourceReg context. */ + public static final short SNAPSHOT_SCOPE_RESULT = 639; + + /** Dereference a compiler-owned scalar temporary and release it after lookup. Format: rd rs. */ + public static final short DEREF_SCALAR_STRICT_TEMP = 640; + /** Non-strict scalar dereference that consumes its scalar input. Format: rd rs pkgIdx. */ + public static final short DEREF_SCALAR_NONSTRICT_TEMP = 641; + + /** Acquire the subroutine return owner before any lexical cleanup. Format: returnReg. */ + public static final short PREPARE_SCOPE_RETURN = 642; + + /** Flush mortals and advance the Perl statement-lifetime boundary. */ + public static final short MORTAL_STATEMENT_FLUSH = 645; + /** Release the foreach source-value lease acquired with ITERATOR_CREATE. Format: iteratorReg. */ + public static final short FOREACH_SOURCE_RELEASE = 646; + private Opcodes() { } // Utility class - no instantiation } diff --git a/src/main/java/org/perlonjava/backend/bytecode/SlowOpcodeHandler.java b/src/main/java/org/perlonjava/backend/bytecode/SlowOpcodeHandler.java index bfc6a4f365..67d15776fd 100644 --- a/src/main/java/org/perlonjava/backend/bytecode/SlowOpcodeHandler.java +++ b/src/main/java/org/perlonjava/backend/bytecode/SlowOpcodeHandler.java @@ -517,6 +517,32 @@ public static int executeDerefScalarStrict( return pc; } + public static int executeDerefScalarStrictTemp( + int[] bytecode, + int pc, + RuntimeBase[] registers) { + int rd = bytecode[pc++]; + int rs = bytecode[pc++]; + RuntimeBase temp = registers[rs]; + RuntimeScalar result = null; + boolean completed = false; + try { + result = guardReadOnlyScalarDeref( + registers[rs].scalar().scalarDeref()); + registers[rd] = result; + completed = true; + } finally { + try { + if (temp != result && temp instanceof RuntimeScalar scalar) { + RuntimeScalar.scopeExitCleanup(scalar); + } + } finally { + if (rd != rs || !completed) registers[rs] = null; + } + } + return pc; + } + public static int executeRejectLocalizeReference( int[] bytecode, int pc, RuntimeBase[] registers) { int rs = bytecode[pc++]; @@ -579,6 +605,35 @@ public static int executeDerefScalarNonStrict( return pc; } + public static int executeDerefScalarNonStrictTemp( + int[] bytecode, + int pc, + RuntimeBase[] registers, + InterpretedCode code) { + int rd = bytecode[pc++]; + int rs = bytecode[pc++]; + int pkgIdx = bytecode[pc++]; + String pkg = code.stringPool[pkgIdx]; + RuntimeBase temp = registers[rs]; + RuntimeScalar result = null; + boolean completed = false; + try { + result = guardReadOnlyScalarDeref( + registers[rs].scalar().scalarDerefNonStrict(pkg)); + registers[rd] = result; + completed = true; + } finally { + try { + if (temp != result && temp instanceof RuntimeScalar scalar) { + RuntimeScalar.scopeExitCleanup(scalar); + } + } finally { + if (rd != rs || !completed) registers[rs] = null; + } + } + return pc; + } + private static RuntimeScalar guardReadOnlyScalarDeref(RuntimeScalar target) { if (target instanceof RuntimeScalarReadOnly && !(target instanceof ReadOnlyAlias)) { @@ -1359,10 +1414,8 @@ private static void releaseHashSliceTemporaryOwner(RuntimeScalar value) { if (value != null && value.refCountOwned && RuntimeScalarType.isReference(value) && value.value instanceof RuntimeBase base && base.refCount > 0) { - base.releaseOwner(value, "HASH_SLICE_SET temporary owner transfer"); - base.releaseActiveOwner(value); - base.refCount--; - value.refCountOwned = false; + MortalList.releaseCountedOwnerImmediately( + value, "HASH_SLICE_SET temporary owner transfer"); } } @@ -1618,9 +1671,12 @@ public static int executeDirectNamedCodeCall(int[] bytecode, int pc, int cacheIdx = bytecode[pc++]; int classNameIdx = bytecode[pc++]; int labelIdx = bytecode[pc++]; - RuntimeScalar cached = (RuntimeScalar) code.constants[cacheIdx]; + RuntimeScalar descriptor = (RuntimeScalar) code.constants[cacheIdx]; String name = code.stringPool[nameIdx]; - RuntimeScalar codeRef = GlobalVariable.getGlobalCodeRefForDirectCall(name, cached); + RuntimeScalar codeRef = descriptor.compiledDirectCallSiteName() == null + ? GlobalVariable.getGlobalCodeRefForDirectCall(name, descriptor) + : RuntimeCode.resolveCompiledDirectCallForActive( + name, null, descriptor.compiledDirectCallSiteIndex()); // The normal RuntimeCode.apply path owns ordinary direct-call errors. // Preflight only labelled statements, where the diagnostic needs the // parser-provided "close to label" hint. A goto &name also reuses this diff --git a/src/main/java/org/perlonjava/backend/bytecode/SuspendedInterpreterFrame.java b/src/main/java/org/perlonjava/backend/bytecode/SuspendedInterpreterFrame.java index d9f60fa25b..3d545cb0fe 100644 --- a/src/main/java/org/perlonjava/backend/bytecode/SuspendedInterpreterFrame.java +++ b/src/main/java/org/perlonjava/backend/bytecode/SuspendedInterpreterFrame.java @@ -1,14 +1,23 @@ package org.perlonjava.backend.bytecode; import org.perlonjava.runtime.runtimetypes.RegexState; +import org.perlonjava.runtime.runtimetypes.RuntimeArray; import org.perlonjava.runtime.runtimetypes.RuntimeBase; import org.perlonjava.runtime.runtimetypes.RuntimeCode; +import org.perlonjava.runtime.runtimetypes.RuntimeHash; +import org.perlonjava.runtime.runtimetypes.RuntimeScalar; import org.perlonjava.runtime.runtimetypes.DynamicVariableManager; +import org.perlonjava.runtime.runtimetypes.ExecutionRuntimeState; +import org.perlonjava.runtime.runtimetypes.PerlOwnerSlot; +import org.perlonjava.runtime.runtimetypes.WeakRefRegistry; import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.BitSet; +import java.util.HashMap; import java.util.Set; import java.util.List; +import java.util.Map; /** * Heap-owned execution state for an interpreter invocation that may cross an @@ -23,6 +32,7 @@ public final class SuspendedInterpreterFrame { final RuntimeBase[] registers; final int callContext; final String subroutineName; + final RuntimeScalar selfReference; int pc; int virtualEvalFrameDepth; @@ -31,6 +41,8 @@ public final class SuspendedInterpreterFrame { Set returnedClosures; final ArrayDeque evalCatchStack = new ArrayDeque<>(); + final ArrayDeque evalMortalMarkDepthStack = new ArrayDeque<>(); + final ArrayDeque evalScopeCleanupBatchDepthStack = new ArrayDeque<>(); final ArrayDeque evalCallerFrameStack = new ArrayDeque<>(); final ArrayDeque evalControlBlockDepthStack = new ArrayDeque<>(); final ArrayDeque evalLocalLevelStack = new ArrayDeque<>(); @@ -42,6 +54,8 @@ public final class SuspendedInterpreterFrame { final ArrayList createdClosures = new ArrayList<>(); final ArrayList methodInvocantHolds = new ArrayList<>(); final ArrayDeque> scopeCleanupBatches = new ArrayDeque<>(); + private final Map suspendedLexicalOwners = new HashMap<>(); + private ExecutionRuntimeState registeredExecutionState; List suspendedDynamicStates; boolean suspended; @@ -56,5 +70,99 @@ public final class SuspendedInterpreterFrame { this.registers = registers; this.callContext = callContext; this.subroutineName = subroutineName; + // ACTIVE_CODE owns this invocation. Borrow its CV value independently + // of a mutable glob slot, which Perl may undefine during the call. + this.selfReference = code.__SUB__ == null ? null : new RuntimeScalar(code.__SUB__); + } + + /** Register this live continuation so runtime reset waits for its completion. */ + void registerSuspendedContinuation(ExecutionRuntimeState state) { + if (state == null) return; + synchronized (this) { + if (registeredExecutionState == state) return; + if (registeredExecutionState != null) { + throw new IllegalStateException("suspended frame is registered to another runtime"); + } + registeredExecutionState = state; + state.registerSuspendedContinuation(this); + } + } + + /** Retire the reset guard after terminal frame cleanup releases its slots. */ + private void unregisterSuspendedContinuation() { + ExecutionRuntimeState state; + synchronized (this) { + state = registeredExecutionState; + registeredExecutionState = null; + } + if (state != null) state.unregisterSuspendedContinuation(this); + } + + /** Retain the current strong values in lexical registers across an await. */ + void retainSuspendedLexicalOwners() { + BitSet myVars = code.myVarRegisters; + int firstMyVarReg = 3 + (code.capturedVars != null ? code.capturedVars.length : 0); + BitSet retainedRegisters = new BitSet(registers.length); + for (int i = myVars.nextSetBit(firstMyVarReg); + i >= 0 && i < registers.length; i = myVars.nextSetBit(i + 1)) { + RuntimeBase registerValue = registers[i]; + if (registerValue == null) continue; + PerlOwnerSlot owner = suspendedLexicalOwners.get(i); + if (registerValue instanceof RuntimeScalar scalar) { + if (owner != null && owner.suspendedScalarOwner() != scalar) { + releaseSuspendedOwnerForRegister(i); + owner = null; + } + if (owner == null) { + owner = new PerlOwnerSlot(PerlOwnerSlot.Kind.SUSPENDED_FRAME); + suspendedLexicalOwners.put(i, owner); + } + if (owner.suspendedScalarOwner() != scalar) { + scalar.attachSuspendedFrameOwner(owner); + } + } else { + RuntimeBase referent = suspendedLexicalReferent(registerValue); + if (referent == null) continue; + if (owner != null && owner.suspendedScalarOwner() != null) { + releaseSuspendedOwnerForRegister(i); + owner = null; + } + if (owner == null) { + owner = new PerlOwnerSlot(PerlOwnerSlot.Kind.SUSPENDED_FRAME); + suspendedLexicalOwners.put(i, owner); + } + owner.acquireSuspendedFrameIdentity(referent); + } + retainedRegisters.set(i); + } + for (Integer register : new ArrayList<>(suspendedLexicalOwners.keySet())) { + if (!retainedRegisters.get(register)) releaseSuspendedOwnerForRegister(register); + } + } + + /** Retire the suspended owner for one lexical as its scope exits. */ + void releaseSuspendedOwnerForRegister(int register) { + PerlOwnerSlot owner = suspendedLexicalOwners.remove(register); + if (owner == null) return; + RuntimeBase previousReferent = owner.referent(); + RuntimeScalar scalarOwner = owner.suspendedScalarOwner(); + if (scalarOwner != null) scalarOwner.detachSuspendedFrameOwner(owner); + else owner.release(); + WeakRefRegistry.onSuspendedFrameOwnerReleased(previousReferent); + } + + /** Retire all remaining suspended-frame owners after completion or cancellation. */ + void releaseSuspendedLexicalOwners() { + for (Integer register : new ArrayList<>(suspendedLexicalOwners.keySet())) { + releaseSuspendedOwnerForRegister(register); + } + unregisterSuspendedContinuation(); + } + + private static RuntimeBase suspendedLexicalReferent(RuntimeBase value) { + if (value instanceof RuntimeArray || value instanceof RuntimeHash) { + return value.isPerlDestroyed() ? null : value; + } + return null; } } diff --git a/src/main/java/org/perlonjava/backend/bytecode/VariableCollectorVisitor.java b/src/main/java/org/perlonjava/backend/bytecode/VariableCollectorVisitor.java index 98956568b4..72cb503d82 100644 --- a/src/main/java/org/perlonjava/backend/bytecode/VariableCollectorVisitor.java +++ b/src/main/java/org/perlonjava/backend/bytecode/VariableCollectorVisitor.java @@ -200,11 +200,14 @@ public void visit(OperatorNode node) { String op = node.operator; // Detect eval STRING (eval BLOCK is represented as a SubroutineNode, not here). - // When eval STRING is present, any variable could be referenced dynamically - // at runtime, so we must capture all visible variables. + // Runtime-generated source normally requires all visible variables. A + // constant source string with no sigils and no nested eval cannot name a + // Perl variable, so it does not need to pin an unrelated lexical pad. if (op.equals("eval") || op.equals("evalbytes")) { hasEvalString = true; - requiresAllRuntimeLexicals = true; + if (evalMayReadRuntimeLexicals(node)) { + requiresAllRuntimeLexicals = true; + } } else if (op.equals("regexTemplate")) { requiresAllRuntimeLexicals = true; } else if ((op.equals("quoteRegex") || op.equals("matchRegex")) @@ -250,6 +253,30 @@ && hasDynamicRegexPattern(node)) { } } + private boolean evalMayReadRuntimeLexicals(OperatorNode node) { + Node operand = node.operand; + if (operand instanceof ListNode list + && list.elements != null + && list.elements.size() == 1) { + operand = list.elements.getFirst(); + } + if (!(operand instanceof StringNode literal)) { + return true; + } + + String source = literal.value; + // Any sigil may name a lexical, including in code that is itself + // generated by the eval. A nested eval can then refer to variables not + // present in this constant source, so retain the broad capture set. + if (source.indexOf('$') >= 0 || source.indexOf('@') >= 0 + || source.indexOf('%') >= 0 || source.indexOf('&') >= 0) { + return true; + } + // Even without a literal sigil, nested runtime compilation can build a + // variable name dynamically (for example with chr(36)). + return source.matches("(?s).*\\beval(?:bytes)?\\b.*"); + } + @Override public void visit(BinaryOperatorNode node) { if ("=".equals(node.operator) && containsDeclaration(node.left)) { diff --git a/src/main/java/org/perlonjava/backend/jvm/Dereference.java b/src/main/java/org/perlonjava/backend/jvm/Dereference.java index ae9815a6c1..e9d4f1aa80 100644 --- a/src/main/java/org/perlonjava/backend/jvm/Dereference.java +++ b/src/main/java/org/perlonjava/backend/jvm/Dereference.java @@ -455,6 +455,11 @@ static void handleArrayElementOperator(EmitterVisitor emitterVisitor, BinaryOper */ public static void handleHashElementOperator(EmitterVisitor emitterVisitor, BinaryOperatorNode node, String hashOperation) { if (CompilerOptions.DEBUG_ENABLED) emitterVisitor.ctx.logDebug("handleHashElementOperator " + node + " in context " + emitterVisitor.ctx.contextType); + if ("get".equals(hashOperation) + && (emitterVisitor.ctx.contextType == RuntimeContextType.LVALUE + || emitterVisitor.ctx.contextType == RuntimeContextType.LVALUE_LIST)) { + hashOperation = "getForLocal"; + } EmitterVisitor scalarVisitor = emitterVisitor.with(RuntimeContextType.SCALAR); // execute operands in scalar context @@ -632,6 +637,7 @@ public static void handleHashElementOperator(EmitterVisitor emitterVisitor, Bina // Use strict version (throws error on symbolic references) String methodName = switch (hashOperation) { case "get" -> "hashDerefGet"; + case "getForLocal" -> "hashDerefGetForLocal"; case "delete" -> "hashDerefDeleteInContext"; case "exists" -> "hashDerefExists"; default -> @@ -648,6 +654,7 @@ public static void handleHashElementOperator(EmitterVisitor emitterVisitor, Bina // Use non-strict version (allows symbolic references) String methodName = switch (hashOperation) { case "get" -> "hashDerefGetNonStrict"; + case "getForLocal" -> "hashDerefGetForLocalNonStrict"; case "delete" -> "hashDerefDeleteInContextNonStrict"; case "exists" -> "hashDerefExistsNonStrict"; default -> @@ -675,6 +682,7 @@ public static void handleHashElementOperator(EmitterVisitor emitterVisitor, Bina // Use strict version (throws error on symbolic references) String methodName = switch (hashOperation) { case "get" -> "hashDerefGet"; + case "getForLocal" -> "hashDerefGetForLocal"; case "delete" -> "hashDerefDeleteInContext"; case "exists" -> "hashDerefExists"; default -> @@ -691,6 +699,7 @@ public static void handleHashElementOperator(EmitterVisitor emitterVisitor, Bina // Use non-strict version (allows symbolic references) String methodName = switch (hashOperation) { case "get" -> "hashDerefGetNonStrict"; + case "getForLocal" -> "hashDerefGetForLocalNonStrict"; case "delete" -> "hashDerefDeleteInContextNonStrict"; case "exists" -> "hashDerefExistsNonStrict"; default -> @@ -969,12 +978,16 @@ static void handleArrowOperator(EmitterVisitor emitterVisitor, BinaryOperatorNod object = new StringNode(className, ((IdentifierNode) object).tokenIndex); } - // Wanted reports OBJECT when a method result is immediately used - // as the invocant of another method call ($obj->first->second). - if (object instanceof BinaryOperatorNode innerArrow + // A method result used as another method's invocant needs an + // explicit Perl owner while the outer method name and arguments + // are evaluated. The interpreter emits the matching hold/release + // opcodes; keep the JVM path on the same lifetime boundary. + boolean holdInvocantDuringArguments = object instanceof BinaryOperatorNode innerArrow && "->".equals(innerArrow.operator) && innerArrow.right instanceof BinaryOperatorNode innerCall - && "(".equals(innerCall.operator)) { + && "(".equals(innerCall.operator); + if (holdInvocantDuringArguments) { + BinaryOperatorNode innerArrow = (BinaryOperatorNode) object; innerArrow.setAnnotation("wantedObjectContext", true); } @@ -1002,6 +1015,35 @@ static void handleArrowOperator(EmitterVisitor emitterVisitor, BinaryOperatorNod } object.accept(scalarVisitor); + int objectSlot = emitterVisitor.ctx.javaClassInfo.acquireSpillSlot(); + boolean pooledObject = objectSlot >= 0; + if (!pooledObject) { + objectSlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable(); + } + mv.visitVarInsn(Opcodes.ASTORE, objectSlot); + + int holdSlot = -1; + boolean pooledHold = false; + Label holdStart = null; + if (holdInvocantDuringArguments) { + holdSlot = emitterVisitor.ctx.javaClassInfo.acquireSpillSlot(); + pooledHold = holdSlot >= 0; + if (!pooledHold) { + holdSlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable(); + } + mv.visitVarInsn(Opcodes.ALOAD, objectSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "acquireMethodInvocantHold", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)" + + "Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;", + false); + mv.visitVarInsn(Opcodes.ASTORE, holdSlot); + emitterVisitor.ctx.javaClassInfo.activeMethodInvocantHoldSlots.push(holdSlot); + holdStart = new Label(); + mv.visitLabel(holdStart); + } + method.accept(scalarVisitor); // Push __SUB__ @@ -1021,13 +1063,6 @@ static void handleArrowOperator(EmitterVisitor emitterVisitor, BinaryOperatorNod } mv.visitVarInsn(Opcodes.ASTORE, methodSlot); - int objectSlot = emitterVisitor.ctx.javaClassInfo.acquireSpillSlot(); - boolean pooledObject = objectSlot >= 0; - if (!pooledObject) { - objectSlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable(); - } - mv.visitVarInsn(Opcodes.ASTORE, objectSlot); - // For small literal calls, keep values in JVM locals until every // expression has run, then build @_ directly. Other calls retain // the array path so tied and aggregate argument expansion keeps @@ -1098,6 +1133,13 @@ static void handleArrowOperator(EmitterVisitor emitterVisitor, BinaryOperatorNod "(I)Lorg/perlonjava/runtime/runtimetypes/RuntimeCode$CallArguments;", false); mv.visitVarInsn(Opcodes.ASTORE, argsArraySlot); + // Argument evaluation can throw before the RuntimeCode call + // wrapper gets a chance to finish this staging frame. + Label argumentsStart = new Label(); + Label argumentsEnd = new Label(); + Label argumentsFailure = new Label(); + Label argumentsReady = new Label(); + mv.visitLabel(argumentsStart); for (int index = 0; index < argCount; index++) { int argSlot = emitterVisitor.ctx.javaClassInfo.acquireSpillSlot(); boolean pooledArg = argSlot >= 0; @@ -1111,6 +1153,20 @@ static void handleArrowOperator(EmitterVisitor emitterVisitor, BinaryOperatorNod "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;)V", false); if (pooledArg) emitterVisitor.ctx.javaClassInfo.releaseSpillSlot(); } + mv.visitLabel(argumentsEnd); + mv.visitJumpInsn(Opcodes.GOTO, argumentsReady); + mv.visitLabel(argumentsFailure); + // Keep the original throwable on the operand stack while + // releasing only this call's acquired argument owners. + mv.visitVarInsn(Opcodes.ALOAD, argsArraySlot); + mv.visitInsn(Opcodes.SWAP); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, + "org/perlonjava/runtime/runtimetypes/RuntimeCode$CallArguments", "abandon", + "(Ljava/lang/Throwable;)Ljava/lang/Throwable;", false); + mv.visitInsn(Opcodes.ATHROW); + mv.visitLabel(argumentsReady); + // Register after the body so inner eval handlers take priority. + mv.visitTryCatchBlock(argumentsStart, argumentsEnd, argumentsFailure, null); } // The call context is NOT stored in a local slot (see EmitSubroutine.java comment for why: @@ -1171,6 +1227,43 @@ static void handleArrowOperator(EmitterVisitor emitterVisitor, BinaryOperatorNod "(ILorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;" + argsDescriptor + "Ljava/lang/String;I)Lorg/perlonjava/runtime/runtimetypes/RuntimeList;", false); // generate a cached .call() + if (holdInvocantDuringArguments) { + // Keep the returned list on the operand stack while releasing + // the temporary owner, matching RELEASE_METHOD_INVOCANT in + // the interpreter. Exceptions from argument evaluation or + // dispatch abandon the hold immediately and rethrow unchanged. + Label holdEnd = new Label(); + Label holdHandler = new Label(); + Label afterHoldCleanup = new Label(); + mv.visitLabel(holdEnd); + mv.visitVarInsn(Opcodes.ALOAD, holdSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "releaseMethodInvocantHold", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;)V", + false); + mv.visitJumpInsn(Opcodes.GOTO, afterHoldCleanup); + mv.visitLabel(holdHandler); + int holdThrowableSlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable(); + mv.visitVarInsn(Opcodes.ASTORE, holdThrowableSlot); + mv.visitVarInsn(Opcodes.ALOAD, holdSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "releaseAbandonedMethodInvocantHold", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;)V", + false); + mv.visitVarInsn(Opcodes.ALOAD, holdThrowableSlot); + mv.visitInsn(Opcodes.ATHROW); + mv.visitLabel(afterHoldCleanup); + // Register after argument-evaluation cleanup so that handler + // abandons the staged arguments before this owner is retired. + mv.visitTryCatchBlock(holdStart, holdEnd, holdHandler, null); + int activeHoldSlot = emitterVisitor.ctx.javaClassInfo.activeMethodInvocantHoldSlots.pop(); + if (activeHoldSlot != holdSlot) { + throw new IllegalStateException("method invocant hold stack is unbalanced"); + } + } + // Tagged returns control-flow handling for method calls: // If RuntimeCode.callCached() returned a RuntimeControlFlowList marker (TAILCALL), handle it here. if (emitterVisitor.ctx.javaClassInfo.returnLabel != null @@ -1333,6 +1426,9 @@ static void handleArrowOperator(EmitterVisitor emitterVisitor, BinaryOperatorNod if (pooledMethod) { emitterVisitor.ctx.javaClassInfo.releaseSpillSlot(); } + if (pooledHold) { + emitterVisitor.ctx.javaClassInfo.releaseSpillSlot(); + } if (pooledObject) { emitterVisitor.ctx.javaClassInfo.releaseSpillSlot(); } diff --git a/src/main/java/org/perlonjava/backend/jvm/EmitBlock.java b/src/main/java/org/perlonjava/backend/jvm/EmitBlock.java index d15730246b..effbdfbe80 100644 --- a/src/main/java/org/perlonjava/backend/jvm/EmitBlock.java +++ b/src/main/java/org/perlonjava/backend/jvm/EmitBlock.java @@ -577,6 +577,18 @@ public static void emitBlock(EmitterVisitor emitterVisitor, BlockNode node) { if (CompilerOptions.DEBUG_ENABLED) emitterVisitor.ctx.logDebug("generateCodeBlock start context:" + emitterVisitor.ctx.contextType); int scopeIndex = emitterVisitor.ctx.symbolTable.enterScope(); + boolean isSubBody = node.getBooleanAnnotation("blockIsSubroutine"); + boolean isDoBlock = node.getBooleanAnnotation("blockIsDoBlock"); + boolean doBlockFreshResult = isDoBlock && DoBlockResultAnalysis.isAlwaysFresh(node); + boolean markAtScopeEntry = !isSubBody && doBlockFreshResult; + if (markAtScopeEntry) { + // The fresh result cannot retain values created in this block. + // Mark before evaluating it so constructor mortals are included + // with lexical releases at block exit. + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "pushScopeMark", "()V", false); + } EmitterVisitor voidVisitor = emitterVisitor.with(RuntimeContextType.VOID); // statements in the middle of the block have context VOID List list = node.elements; @@ -730,6 +742,7 @@ public static void emitBlock(EmitterVisitor emitterVisitor, BlockNode node) { // In this case, we need to evaluate the For1Node's list before emitting the local operator For1Node preEvalForNode = null; int savedPreEvaluatedArrayIndex = -1; + int savedPreEvaluatedForeachSourceOwnerDepthIndex = -1; if (list.size() >= 2 && list.get(0) instanceof OperatorNode localOp && localOp.operator.equals("local") && @@ -742,10 +755,22 @@ public static void emitBlock(EmitterVisitor emitterVisitor, BlockNode node) { EmitForeach.emitForeachSource(emitterVisitor, forNode.list); mv.visitVarInsn(Opcodes.ASTORE, tempArrayIndex); + int ownerDepthIndex = emitterVisitor.ctx.symbolTable.allocateLocalVariable(); + mv.visitVarInsn(Opcodes.ALOAD, tempArrayIndex); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "pushForeachSourceOwners", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;)I", + false); + mv.visitVarInsn(Opcodes.ISTORE, ownerDepthIndex); + // Mark the For1Node to use the pre-evaluated array preEvalForNode = forNode; savedPreEvaluatedArrayIndex = forNode.preEvaluatedArrayIndex; + savedPreEvaluatedForeachSourceOwnerDepthIndex = + forNode.preEvaluatedForeachSourceOwnerDepthIndex; forNode.preEvaluatedArrayIndex = tempArrayIndex; + forNode.preEvaluatedForeachSourceOwnerDepthIndex = ownerDepthIndex; } int savedStatementTokenIndex = emitterVisitor.ctx.javaClassInfo.statementTokenIndex; @@ -853,7 +878,7 @@ public static void emitBlock(EmitterVisitor emitterVisitor, BlockNode node) { if (i < lastNonNullIndex) { mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/perlonjava/runtime/runtimetypes/MortalList", - "flushAboveMark", + "flushStatementBoundary", "()V", false); } @@ -863,6 +888,8 @@ public static void emitBlock(EmitterVisitor emitterVisitor, BlockNode node) { emitterVisitor.ctx.javaClassInfo.statementTokenIndex = savedStatementTokenIndex; if (preEvalForNode != null) { preEvalForNode.preEvaluatedArrayIndex = savedPreEvaluatedArrayIndex; + preEvalForNode.preEvaluatedForeachSourceOwnerDepthIndex = + savedPreEvaluatedForeachSourceOwnerDepthIndex; } } @@ -934,9 +961,6 @@ public static void emitBlock(EmitterVisitor emitterVisitor, BlockNode node) { // container. For those we DO flush, fixing op/do.t RT 124248 // (DESTROY firing on do-block exit for transient my-vars) without // risking DBIC's `do { my $x = ...; $x }` patterns. - boolean isSubBody = node.getBooleanAnnotation("blockIsSubroutine"); - boolean isDoBlock = node.getBooleanAnnotation("blockIsDoBlock"); - boolean doBlockFreshResult = isDoBlock && DoBlockResultAnalysis.isAlwaysFresh(node); Object blockResultRegObj = node.getAnnotation("resultRegister"); boolean hasBlockResultRegister = blockResultRegObj instanceof Integer && (Integer) blockResultRegObj >= 0; boolean blockMayNeedResultAfterScopeExit = emitterVisitor.ctx.contextType != RuntimeContextType.VOID @@ -956,22 +980,26 @@ public static void emitBlock(EmitterVisitor emitterVisitor, BlockNode node) { } boolean protectReturnedWeakOwner = returnedLvalueSlot >= 0 && emitterVisitor.ctx.javaClassInfo.cleanupNeeded; + int protectedReturnRootSlot = -1; if (protectReturnedWeakOwner) { - // A weakly observed local may also be the implicit sub return. - // Keep that return value as an explicit root while lexical cleanup - // runs so noteVarLeftScope can avoid a global reachability sweep - // during the caller's callback dispatch. + // Scope cleanup may replace returnedLvalueSlot with a prepared + // return snapshot. Keep the original value in a separate local so + // the exact root pushed here is also the one popped below. + protectedReturnRootSlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable(); mv.visitVarInsn(Opcodes.ALOAD, returnedLvalueSlot); + mv.visitVarInsn(Opcodes.ASTORE, protectedReturnRootSlot); + mv.visitVarInsn(Opcodes.ALOAD, protectedReturnRootSlot); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/perlonjava/runtime/runtimetypes/MortalList", "pushTemporaryRoot", "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;)V", false); } - EmitStatement.emitScopeExitNullStores(emitterVisitor.ctx, scopeIndex, flushAtScopeExit, returnedLvalueSlot); + EmitStatement.emitScopeExitNullStores(emitterVisitor.ctx, scopeIndex, flushAtScopeExit, + returnedLvalueSlot, markAtScopeEntry); if (returnedLvalueSlot >= 0) { if (protectReturnedWeakOwner) { - mv.visitVarInsn(Opcodes.ALOAD, returnedLvalueSlot); + mv.visitVarInsn(Opcodes.ALOAD, protectedReturnRootSlot); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/perlonjava/runtime/runtimetypes/MortalList", "popTemporaryRoot", diff --git a/src/main/java/org/perlonjava/backend/jvm/EmitControlFlow.java b/src/main/java/org/perlonjava/backend/jvm/EmitControlFlow.java index 590bd8710b..3c90e16c1e 100644 --- a/src/main/java/org/perlonjava/backend/jvm/EmitControlFlow.java +++ b/src/main/java/org/perlonjava/backend/jvm/EmitControlFlow.java @@ -41,6 +41,7 @@ private static boolean containsAggregateReferenceReturn(Node node) { } static void emitSubroutineExitCleanup(EmitterContext ctx) { + emitAbandonedMethodInvocantHolds(ctx); java.util.List scalarIndices = EmitStatement.withoutCaptured(ctx, ctx.symbolTable.getMyScalarIndicesInScope(0)); java.util.List hashIndices = @@ -48,20 +49,21 @@ static void emitSubroutineExitCleanup(EmitterContext ctx) { java.util.List arrayIndices = EmitStatement.withoutCaptured(ctx, ctx.symbolTable.getMyArrayIndicesInScope(0)); - for (int idx : scalarIndices) { + // Match Perl's scope-exit ordering: hash values, scalar pads, arrays. + for (int idx : hashIndices) { ctx.mv.visitVarInsn(Opcodes.ALOAD, idx); ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/perlonjava/runtime/runtimetypes/MortalList", - "deferDecrementIfNotCaptured", - "(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)V", + "scopeExitCleanupHash", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeHash;)V", false); } - for (int idx : hashIndices) { + for (int idx : scalarIndices) { ctx.mv.visitVarInsn(Opcodes.ALOAD, idx); ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/perlonjava/runtime/runtimetypes/MortalList", - "scopeExitCleanupHash", - "(Lorg/perlonjava/runtime/runtimetypes/RuntimeHash;)V", + "deferDecrementIfNotCaptured", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)V", false); } for (int idx : arrayIndices) { @@ -74,6 +76,16 @@ static void emitSubroutineExitCleanup(EmitterContext ctx) { } } + static void emitAbandonedMethodInvocantHolds(EmitterContext ctx) { + for (int holdSlot : ctx.javaClassInfo.activeMethodInvocantHoldSlots) { + ctx.mv.visitVarInsn(Opcodes.ALOAD, holdSlot); + ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "releaseAbandonedMethodInvocantHold", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;)V", false); + } + } + private static boolean isAtUnderscore(Node node) { if (node instanceof ListNode list && list.elements.size() == 1) { @@ -244,9 +256,11 @@ static void handleNextOperator(EmitterVisitor emitterVisitor, OperatorNode node) // bypass the cleanup at returnLabel, leaving `local` variables un-restored. if (ctx.javaClassInfo.returnLabel != null) { ctx.mv.visitVarInsn(Opcodes.ASTORE, ctx.javaClassInfo.returnValueSlot); + emitAbandonedMethodInvocantHolds(ctx); emitMortalFlushAboveMark(ctx); ctx.mv.visitJumpInsn(Opcodes.GOTO, ctx.javaClassInfo.returnLabel); } else { + emitAbandonedMethodInvocantHolds(ctx); emitMortalFlushAboveMark(ctx); ctx.mv.visitInsn(Opcodes.ARETURN); } @@ -311,6 +325,7 @@ static void handleNextOperator(EmitterVisitor emitterVisitor, OperatorNode node) Label label = operator.equals("next") ? loopLabels.nextLabel : operator.equals("last") ? loopLabels.lastLabel : loopLabels.redoLabel; + emitAbandonedMethodInvocantHolds(ctx); emitLoopControlScopeCleanup(ctx, loopLabels, operator.equals("last")); emitMortalFlushAboveMark(ctx); emitLoopRegexStateRestore(ctx, loopLabels); @@ -394,6 +409,8 @@ private static void emitMortalFlushAboveMark(EmitterContext ctx) { */ static void handleReturnOperator(EmitterVisitor emitterVisitor, OperatorNode node) { EmitterContext ctx = emitterVisitor.ctx; + boolean copyScopeReturn = !ctx.javaClassInfo.isLvalueSubroutine + || ctx.javaClassInfo.isTryExpressionWrapper; // Check if we're inside a defer block - return out of defer is prohibited if (ctx.javaClassInfo.isInDeferBlock) { @@ -512,8 +529,7 @@ static void handleReturnOperator(EmitterVisitor emitterVisitor, OperatorNode nod // returns, whose DESTROY timing must remain unchanged. if (protectsLexicalAggregate) { ctx.mv.visitVarInsn(Opcodes.ILOAD, 2); - ctx.mv.visitInsn(ctx.javaClassInfo.isLvalueSubroutine - ? Opcodes.ICONST_0 : Opcodes.ICONST_1); + ctx.mv.visitInsn(copyScopeReturn ? Opcodes.ICONST_1 : Opcodes.ICONST_0); ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/perlonjava/runtime/runtimetypes/RuntimeCode", "returnList", @@ -521,6 +537,12 @@ static void handleReturnOperator(EmitterVisitor emitterVisitor, OperatorNode nod false); } + ctx.mv.visitVarInsn(Opcodes.ILOAD, 2); + ctx.mv.visitInsn(copyScopeReturn ? Opcodes.ICONST_1 : Opcodes.ICONST_0); + ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", "prepareScopeReturn", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;IZ)Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;", + false); ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/perlonjava/runtime/runtimetypes/RuntimeCode", "materializeReturnedIoAliases", @@ -534,6 +556,7 @@ static void handleReturnOperator(EmitterVisitor emitterVisitor, OperatorNode nod // Perl subroutine, not the synthetic expression wrapper. Save it, // run finally, then unwind through RuntimeCode's non-local-return // boundary. + emitAbandonedMethodInvocantHolds(ctx); ctx.mv.visitVarInsn(Opcodes.ASTORE, tryFinally.returnValueSlot); ctx.mv.visitInsn(Opcodes.ICONST_1); ctx.mv.visitVarInsn(Opcodes.ISTORE, tryFinally.returnPendingSlot); @@ -553,14 +576,32 @@ static void handleReturnOperator(EmitterVisitor emitterVisitor, OperatorNode nod if (!allScalarIndices.isEmpty() || !hashIndices.isEmpty() || !arrayIndices.isEmpty()) { JavaClassInfo.SpillRef spillRef = ctx.javaClassInfo.acquireSpillRefOrAllocate(ctx.symbolTable); ctx.javaClassInfo.storeSpillRef(ctx.mv, spillRef); + int protectedReturnRootSlot = -1; if (protectsLexicalAggregate) { + // Array cleanup may replace spillRef with a prepared copy of + // the return value. Keep the exact original root in a stable + // local so the matching pop cannot leave it on the temp stack. + protectedReturnRootSlot = ctx.symbolTable.allocateLocalVariable(); ctx.javaClassInfo.loadSpillRef(ctx.mv, spillRef); + ctx.mv.visitVarInsn(Opcodes.ASTORE, protectedReturnRootSlot); + ctx.mv.visitVarInsn(Opcodes.ALOAD, protectedReturnRootSlot); ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/perlonjava/runtime/runtimetypes/MortalList", "pushTemporaryRoot", "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;)V", false); } + // Release hash values before scalar pads, matching Perl's destructor + // order. Arrays remain last so aggregate teardown sees the same edge + // sequence as ordinary scope exit. + for (int idx : hashIndices) { + ctx.mv.visitVarInsn(Opcodes.ALOAD, idx); + ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "scopeExitCleanupHash", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeHash;)V", + false); + } // Captured scalar slots belong to the enclosing closure frame. // They can receive an anonymous socket while this callback runs, // but returning from the callback must not release that enclosing @@ -582,17 +623,18 @@ static void handleReturnOperator(EmitterVisitor emitterVisitor, OperatorNode nod "(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)V", false); } - // Also process hash/array variables — their elements may hold tracked - // references that need refCount decrements on scope exit. - for (int idx : hashIndices) { + // Arrays are released after hash values and scalar pads. + for (int idx : arrayIndices) { + ctx.javaClassInfo.loadSpillRef(ctx.mv, spillRef); ctx.mv.visitVarInsn(Opcodes.ALOAD, idx); + ctx.mv.visitVarInsn(Opcodes.ILOAD, 2); + ctx.mv.visitInsn(copyScopeReturn ? Opcodes.ICONST_1 : Opcodes.ICONST_0); ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, - "org/perlonjava/runtime/runtimetypes/MortalList", - "scopeExitCleanupHash", - "(Lorg/perlonjava/runtime/runtimetypes/RuntimeHash;)V", + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "prepareLocalArrayReturn", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;Lorg/perlonjava/runtime/runtimetypes/RuntimeArray;IZ)Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;", false); - } - for (int idx : arrayIndices) { + ctx.javaClassInfo.storeSpillRef(ctx.mv, spillRef); ctx.mv.visitVarInsn(Opcodes.ALOAD, idx); ctx.javaClassInfo.loadSpillRef(ctx.mv, spillRef); ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, @@ -602,7 +644,7 @@ static void handleReturnOperator(EmitterVisitor emitterVisitor, OperatorNode nod false); } if (protectsLexicalAggregate) { - ctx.javaClassInfo.loadSpillRef(ctx.mv, spillRef); + ctx.mv.visitVarInsn(Opcodes.ALOAD, protectedReturnRootSlot); ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/perlonjava/runtime/runtimetypes/MortalList", "popTemporaryRoot", @@ -613,6 +655,7 @@ static void handleReturnOperator(EmitterVisitor emitterVisitor, OperatorNode nod ctx.javaClassInfo.releaseSpillRef(spillRef); } + emitAbandonedMethodInvocantHolds(ctx); ctx.mv.visitVarInsn(Opcodes.ASTORE, ctx.javaClassInfo.returnValueSlot); ctx.mv.visitJumpInsn(Opcodes.GOTO, ctx.javaClassInfo.returnLabel); } @@ -1025,6 +1068,7 @@ static void handleGotoLabel(EmitterVisitor emitterVisitor, OperatorNode node) { ctx.mv.visitTypeInsn(Opcodes.CHECKCAST, "org/perlonjava/runtime/runtimetypes/RuntimeList"); ctx.mv.visitVarInsn(Opcodes.ASTORE, ctx.javaClassInfo.returnValueSlot); + emitAbandonedMethodInvocantHolds(ctx); ctx.mv.visitJumpInsn(Opcodes.GOTO, ctx.javaClassInfo.returnLabel); return; } @@ -1116,6 +1160,7 @@ static void handleGotoLabel(EmitterVisitor emitterVisitor, OperatorNode node) { // Local goto: use fast GOTO (existing code) // Emit the goto instruction + emitAbandonedMethodInvocantHolds(ctx); ctx.mv.visitJumpInsn(Opcodes.GOTO, targetLabel.gotoLabel); } diff --git a/src/main/java/org/perlonjava/backend/jvm/EmitEval.java b/src/main/java/org/perlonjava/backend/jvm/EmitEval.java index f4fcb10b94..29facdfa91 100644 --- a/src/main/java/org/perlonjava/backend/jvm/EmitEval.java +++ b/src/main/java/org/perlonjava/backend/jvm/EmitEval.java @@ -219,6 +219,16 @@ static void handleEvalOperator(EmitterVisitor emitterVisitor, OperatorNode node) Label tryEnd = new Label(); Label catchBlock = new Label(); Label endCatch = new Label(); + int temporaryRootDepthSlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable(); + int foreachSourceOwnerDepthSlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable(); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "temporaryRootDepth", "()I", false); + mv.visitVarInsn(Opcodes.ISTORE, temporaryRootDepthSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "foreachSourceOwnerDepth", "()I", false); + mv.visitVarInsn(Opcodes.ISTORE, foreachSourceOwnerDepthSlot); mv.visitTryCatchBlock(tryStart, tryEnd, catchBlock, "java/lang/Throwable"); mv.visitLabel(tryStart); @@ -255,6 +265,14 @@ static void handleEvalOperator(EmitterVisitor emitterVisitor, OperatorNode node) "(Ljava/lang/Throwable;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false); mv.visitInsn(Opcodes.POP); + mv.visitVarInsn(Opcodes.ILOAD, temporaryRootDepthSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "restoreTemporaryRootDepth", "(I)V", false); + mv.visitVarInsn(Opcodes.ILOAD, foreachSourceOwnerDepthSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "restoreForeachSourceOwnerDepth", "(I)V", false); if (emitterVisitor.ctx.contextType == RuntimeContextType.LIST) { mv.visitTypeInsn(Opcodes.NEW, "org/perlonjava/runtime/runtimetypes/RuntimeList"); mv.visitInsn(Opcodes.DUP); diff --git a/src/main/java/org/perlonjava/backend/jvm/EmitForeach.java b/src/main/java/org/perlonjava/backend/jvm/EmitForeach.java index 93f3ab3cd9..ce183897f0 100644 --- a/src/main/java/org/perlonjava/backend/jvm/EmitForeach.java +++ b/src/main/java/org/perlonjava/backend/jvm/EmitForeach.java @@ -162,6 +162,7 @@ public static void emitFor1(EmitterVisitor emitterVisitor, For1Node node) { // in the enclosing scope, not trapped inside the for loop's inner scope. // In Perl, the list in a foreach is always evaluated once in the enclosing scope. int preEvalListLocal = -1; + int foreachSourceOwnerDepth = -1; if (node.preEvaluatedArrayIndex < 0) { // A key/value hash slice used as a foreach source supplies its // values only. Keep this marker narrowly scoped to emission so @@ -169,6 +170,25 @@ public static void emitFor1(EmitterVisitor emitterVisitor, For1Node node) { emitForeachSource(emitterVisitor, node.list); preEvalListLocal = emitterVisitor.ctx.symbolTable.allocateLocalVariable(); mv.visitVarInsn(Opcodes.ASTORE, preEvalListLocal); + foreachSourceOwnerDepth = emitterVisitor.ctx.symbolTable.allocateLocalVariable(); + mv.visitVarInsn(Opcodes.ALOAD, preEvalListLocal); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "pushForeachSourceOwners", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;)I", + false); + mv.visitVarInsn(Opcodes.ISTORE, foreachSourceOwnerDepth); + } else if (node.preEvaluatedForeachSourceOwnerDepthIndex >= 0) { + foreachSourceOwnerDepth = node.preEvaluatedForeachSourceOwnerDepthIndex; + } else { + foreachSourceOwnerDepth = emitterVisitor.ctx.symbolTable.allocateLocalVariable(); + mv.visitVarInsn(Opcodes.ALOAD, node.preEvaluatedArrayIndex); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "pushForeachSourceOwners", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;)I", + false); + mv.visitVarInsn(Opcodes.ISTORE, foreachSourceOwnerDepth); } int scopeIndex = emitterVisitor.ctx.symbolTable.enterScope(); @@ -1050,6 +1070,14 @@ public static void emitFor1(EmitterVisitor emitterVisitor, For1Node node) { emitterVisitor.ctx.javaClassInfo.jvmFrameStateSlot); EmitStatement.emitScopeExitNullStores(emitterVisitor.ctx, scopeIndex, true); + if (foreachSourceOwnerDepth >= 0) { + mv.visitVarInsn(Opcodes.ILOAD, foreachSourceOwnerDepth); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "restoreForeachSourceOwnerDepth", + "(I)V", + false); + } emitterVisitor.ctx.symbolTable.exitScope(scopeIndex); if (emitterVisitor.ctx.contextType != RuntimeContextType.VOID) { diff --git a/src/main/java/org/perlonjava/backend/jvm/EmitLiteral.java b/src/main/java/org/perlonjava/backend/jvm/EmitLiteral.java index 5169283b71..cfcaaebd42 100644 --- a/src/main/java/org/perlonjava/backend/jvm/EmitLiteral.java +++ b/src/main/java/org/perlonjava/backend/jvm/EmitLiteral.java @@ -96,6 +96,12 @@ public static void emitArrayLiteral(EmitterVisitor emitterVisitor, ArrayLiteralN "suppressFlush", "(Z)Z", false); int wasFlushingSlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable(); mv.visitVarInsn(Opcodes.ISTORE, wasFlushingSlot); + int arrayLiteralThrowableSlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable(); + Label arrayLiteralTryStart = new Label(); + Label arrayLiteralTryEnd = new Label(); + Label arrayLiteralCatch = new Label(); + Label arrayLiteralDone = new Label(); + mv.visitLabel(arrayLiteralTryStart); // Create a new RuntimeArray instance mv.visitTypeInsn(Opcodes.NEW, "org/perlonjava/runtime/runtimetypes/RuntimeArray"); @@ -132,6 +138,7 @@ public static void emitArrayLiteral(EmitterVisitor emitterVisitor, ArrayLiteralN mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/perlonjava/runtime/runtimetypes/RuntimeBase", "createReferenceWithTrackedElements", "()Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false); // Stack: [RuntimeScalar] (the array reference we'll return) + mv.visitLabel(arrayLiteralTryEnd); // Restore previous suppressFlush state. We deliberately do NOT call // MortalList.flush() here: doing so would drain the entire pending @@ -159,6 +166,25 @@ public static void emitArrayLiteral(EmitterVisitor emitterVisitor, ArrayLiteralN "org/perlonjava/runtime/runtimetypes/MortalList", "suppressFlush", "(Z)Z", false); mv.visitInsn(Opcodes.POP); + mv.visitJumpInsn(Opcodes.GOTO, arrayLiteralDone); + + // If evaluating an element throws, abandon this literal's suppression + // scope before an enclosing eval or Perl try handler sees the exception. + mv.visitLabel(arrayLiteralCatch); + mv.visitVarInsn(Opcodes.ASTORE, arrayLiteralThrowableSlot); + mv.visitVarInsn(Opcodes.ILOAD, wasFlushingSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "suppressFlush", "(Z)Z", false); + mv.visitInsn(Opcodes.POP); + mv.visitVarInsn(Opcodes.ALOAD, arrayLiteralThrowableSlot); + mv.visitInsn(Opcodes.ATHROW); + + mv.visitLabel(arrayLiteralDone); + // Register after nested handlers emitted by array elements so inner + // eval/try blocks retain their normal chance to catch exceptions first. + mv.visitTryCatchBlock(arrayLiteralTryStart, arrayLiteralTryEnd, + arrayLiteralCatch, "java/lang/Throwable"); if (CompilerOptions.DEBUG_ENABLED) emitterVisitor.ctx.logDebug("visit(ArrayLiteralNode) end"); } @@ -359,16 +385,10 @@ private static void emitCachedStringLiteral( } /** - * Emits a string operand for {@code \\} (ref-to-literal) using the string cache's - * singleton scalars ({@link RuntimeScalarCache#getScalarByteString(int)} / - * {@link RuntimeScalarCache#getScalarString(int)}) for cacheable literals, and records - * them on {@link JavaClassInfo#addPadConstant}. - * - *

Ordinary {@link #emitString} uses {@link RuntimeScalarCache#materializeByteStringLiteral(int)} - * / {@link RuntimeScalarCache#materializeStringLiteral(int)} so each literal occurrence - * has a distinct SV (needed for {@code pos()} / {@code \\G}). Ref-to-literal in Perl shares one - * const SV in the CV; weak refs (e.g. Moo {@code weak_ref}) and {@link RuntimeCode#clearPadConstantWeakRefs} - * must target that same object identity.

+ * Emits the stable scalar owned by this optree for a backslash-addressed + * string literal. Each source occurrence gets its own read-only scalar; + * the owning CV and any enclosing anonymous-code template retain it by + * explicit pad-constant slots. */ public static void emitStringForRefToLiteral(EmitterContext ctx, StringNode node) { if (ctx.contextType == RuntimeContextType.VOID) { @@ -379,54 +399,56 @@ public static void emitStringForRefToLiteral(EmitterContext ctx, StringNode node emitStringValue(mv, node.value); return; } - if (node.isVString) { - // No cache slot; same as plain literal (optree reaping may not match Perl for \\v). + if (ctx.javaClassInfo == null) { + // Some deferred compilation contexts do not have an owning class yet. emitString(ctx, node); return; } - if (!node.forceUnicodeString && (node.forceByteString - || (!ctx.symbolTable.isStrictOptionEnabled(HINT_UTF8) - && !ctx.compilerOptions.isUnicodeSource))) { - boolean hasWideChars = false; + // RuntimeScalarCache is only an interning aid for ordinary literals. A + // backslash-addressed literal is a distinct Perl scalar identity even + // when it is too large for that cache or represents a v-string. Build + // that identity once while compiling and let the generated CODE retain + // it through its explicit pad-constant owner slot. + RuntimeScalarReadOnly constant = new RuntimeScalarReadOnly(node.value); + if (node.isVString) { + constant.type = RuntimeScalarType.VSTRING; + } else if (isByteStringLiteral(ctx, node)) { + constant.type = RuntimeScalarType.BYTE_STRING; + } + int padIndex = ctx.javaClassInfo.addPadConstant(constant); + emitPadConstantReference(ctx, padIndex); + } + + private static boolean isByteStringLiteral(EmitterContext ctx, StringNode node) { + if (node.forceUnicodeString) return false; + if (!node.forceByteString) { + boolean asciiOnly = true; for (int i = 0; i < node.value.length(); i++) { - if (node.value.charAt(i) > 255) { - hasWideChars = true; + if (node.value.charAt(i) > 127) { + asciiOnly = false; break; } } - if (!hasWideChars) { - int stringIndex = RuntimeScalarCache.getOrCreateByteStringIndex(node.value); - if (stringIndex >= 0) { - mv.visitLdcInsn(stringIndex); - mv.visitMethodInsn( - Opcodes.INVOKESTATIC, - "org/perlonjava/runtime/runtimetypes/RuntimeScalarCache", - "getScalarByteString", - "(I)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", - false); - ctx.javaClassInfo.addPadConstant(RuntimeScalarCache.getScalarByteString(stringIndex)); - return; - } - emitString(ctx, node); - return; + if (!asciiOnly && ctx.symbolTable.isStrictOptionEnabled(HINT_UTF8)) { + return false; } - // fall through — wide chars use UTF-8 string path (same as emitString) } - - int stringIndex = RuntimeScalarCache.getOrCreateStringIndex(node.value); - if (stringIndex >= 0) { - mv.visitLdcInsn(stringIndex); - mv.visitMethodInsn( - Opcodes.INVOKESTATIC, - "org/perlonjava/runtime/runtimetypes/RuntimeScalarCache", - "getScalarString", - "(I)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", - false); - ctx.javaClassInfo.addPadConstant(RuntimeScalarCache.getScalarString(stringIndex)); - } else { - emitString(ctx, node); + for (int i = 0; i < node.value.length(); i++) { + if (node.value.charAt(i) > 255) return false; } + return true; + } + + private static void emitPadConstantReference(EmitterContext ctx, int padIndex) { + MethodVisitor mv = ctx.mv; + mv.visitLdcInsn(ctx.javaClassInfo.javaClassName); + mv.visitLdcInsn(padIndex); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "getPadConstant", + "(Ljava/lang/String;I)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", + false); } /** diff --git a/src/main/java/org/perlonjava/backend/jvm/EmitOperator.java b/src/main/java/org/perlonjava/backend/jvm/EmitOperator.java index 32bafeab68..758343e6ca 100644 --- a/src/main/java/org/perlonjava/backend/jvm/EmitOperator.java +++ b/src/main/java/org/perlonjava/backend/jvm/EmitOperator.java @@ -2147,7 +2147,7 @@ static void handleCreateReference(EmitterVisitor emitterVisitor, OperatorNode no } if (node.operand instanceof StringNode strNode) { - // Singleton cache scalars + padConstants; see EmitLiteral.emitStringForRefToLiteral. + // Per-optree scalar identities + pad-owner slots; see EmitLiteral.emitStringForRefToLiteral. EmitLiteral.emitStringForRefToLiteral( emitterVisitor.with(contextType).ctx, strNode); } else if (node.operand instanceof NumberNode numberNode) { diff --git a/src/main/java/org/perlonjava/backend/jvm/EmitStatement.java b/src/main/java/org/perlonjava/backend/jvm/EmitStatement.java index 7fb362b8fb..32a08ae157 100644 --- a/src/main/java/org/perlonjava/backend/jvm/EmitStatement.java +++ b/src/main/java/org/perlonjava/backend/jvm/EmitStatement.java @@ -77,11 +77,10 @@ static void emitScopeExitNullStores(EmitterContext ctx, int scopeIndex) { * Same as {@link #emitScopeExitNullStores(EmitterContext, int)} but with * an option to flush the MortalList after cleanup. *

- * When {@code flush} is true, emits a scoped flush using - * {@code MortalList.pushMark()} before cleanup and - * {@code MortalList.popAndFlush()} after. This only processes entries - * added by the scope-exit cleanup itself (not entries from outer scopes - * or prior operations), matching Perl 5's SAVETMPS/FREETMPS scoping. + * When {@code flush} is true, flushes entries above the active function + * boundary after cleanup. Callers that opened a mark at block entry use + * the overload with {@code markAtScopeEntry=true} to pop and flush that + * complete block extent, including temporaries created before cleanup. *

* {@code flush=true} is safe for bare blocks, loops, and control structures. * It must be {@code false} for subroutine body blocks where the implicit @@ -97,7 +96,13 @@ static void emitScopeExitNullStores(EmitterContext ctx, int scopeIndex, boolean } static void emitScopeExitNullStores(EmitterContext ctx, int scopeIndex, boolean flush, int returnedLvalueSlot) { - emitScopeExitNullStores(ctx, scopeIndex, flush, returnedLvalueSlot, false); + emitScopeExitNullStores(ctx, scopeIndex, flush, returnedLvalueSlot, false, false); + } + + static void emitScopeExitNullStores(EmitterContext ctx, int scopeIndex, boolean flush, + int returnedLvalueSlot, boolean markAtScopeEntry) { + emitScopeExitNullStores(ctx, scopeIndex, flush, returnedLvalueSlot, false, + markAtScopeEntry); } static void emitLoopControlScopeExit(EmitterContext ctx, int scopeIndex) { @@ -107,12 +112,12 @@ static void emitLoopControlScopeExit(EmitterContext ctx, int scopeIndex) { // captures from an enclosing class retain their original `my` // declaration metadata, so exclude their known slots just like an // ordinary scope exit; they belong to the enclosing scope. - emitScopeExitNullStores(ctx, scopeIndex, true, -1, false); + emitScopeExitNullStores(ctx, scopeIndex, true, -1, false, false); } private static void emitScopeExitNullStores( EmitterContext ctx, int scopeIndex, boolean flush, - int returnedLvalueSlot, boolean includeCaptured) { + int returnedLvalueSlot, boolean includeCaptured, boolean markAtScopeEntry) { // Gather variable indices for this scope first, to determine if cleanup is needed. java.util.List scalarIndices = includeCaptured ? ctx.symbolTable.getMyScalarIndicesInScope(scopeIndex) @@ -124,7 +129,9 @@ private static void emitScopeExitNullStores( ? ctx.symbolTable.getMyArrayIndicesInScope(scopeIndex) : withoutCaptured(ctx, ctx.symbolTable.getMyArrayIndicesInScope(scopeIndex)); - // Record my-variable indices for eval exception cleanup. + java.util.Map scalarNames = + ctx.symbolTable.getMyScalarNamesInScope(scopeIndex); + // Record my-variable indices and scalar pad names for eval exception cleanup. // When evalCleanupLocals is non-null (set by EmitterMethodCreator for eval blocks), // we record all my-variable local indices so the catch handler can emit cleanup // for variables whose normal SCOPE_EXIT_CLEANUP was skipped by die. @@ -132,6 +139,9 @@ private static void emitScopeExitNullStores( ctx.javaClassInfo.evalCleanupLocals.addAll(scalarIndices); ctx.javaClassInfo.evalCleanupLocals.addAll(hashIndices); ctx.javaClassInfo.evalCleanupLocals.addAll(arrayIndices); + if (ctx.javaClassInfo.evalCleanupScalarNames != null) { + ctx.javaClassInfo.evalCleanupScalarNames.putAll(scalarNames); + } } // Fast path: when CleanupNeededVisitor proved the sub has no @@ -170,7 +180,29 @@ private static void emitScopeExitNullStores( // scope exits (e.g., Foo->new()->method() chain temporaries) may need processing. boolean needsCleanup = !scalarIndices.isEmpty() || !hashIndices.isEmpty() || !arrayIndices.isEmpty(); - // Phase 1: Run scopeExitCleanup for scalar variables. + if (needsCleanup && returnedLvalueSlot >= 0) { + ctx.mv.visitVarInsn(Opcodes.ALOAD, returnedLvalueSlot); + ctx.mv.visitVarInsn(Opcodes.ILOAD, 2); + ctx.mv.visitInsn(ctx.javaClassInfo.isLvalueSubroutine ? Opcodes.ICONST_0 : Opcodes.ICONST_1); + ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", "prepareScopeReturn", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;IZ)Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;", + false); + ctx.mv.visitVarInsn(Opcodes.ASTORE, returnedLvalueSlot); + } + + // Perl releases hash values before scalar pads and arrays at scope exit. + // DESTROY methods can observe objects released earlier in this sequence. + for (int idx : hashIndices) { + ctx.mv.visitVarInsn(Opcodes.ALOAD, idx); + ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "scopeExitCleanupHash", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeHash;)V", + false); + } + + // Run scopeExitCleanup for scalar variables after hash values. // This defers refCount decrements for blessed references with DESTROY, // and handles IO fd recycling for anonymous filehandle globs. for (int idx : scalarIndices) { @@ -190,20 +222,36 @@ private static void emitScopeExitNullStores( false); } } - // Phase 1b: Walk hash/array variables for nested blessed references. - // When a hash/array goes out of scope, any blessed refs stored inside - // (or nested inside sub-containers) need their refCounts decremented. - for (int idx : hashIndices) { + // The JVM keeps one RuntimeScalar cell for refaliased lexical names. + // Retire the exact pad binding as that name leaves scope; ordinary + // unregister only sees the shared cell identity and cannot distinguish + // it from another still-live lexical name for the same cell. + for (int idx : scalarIndices) { + String name = scalarNames.get(idx); + if (name == null) continue; ctx.mv.visitVarInsn(Opcodes.ALOAD, idx); + ctx.mv.visitLdcInsn(name); ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, - "org/perlonjava/runtime/runtimetypes/MortalList", - "scopeExitCleanupHash", - "(Lorg/perlonjava/runtime/runtimetypes/RuntimeHash;)V", + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "unbindCurrentActiveLexical", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;Ljava/lang/String;)V", false); } + // Arrays are released after hash values and scalar pads. for (int idx : arrayIndices) { - ctx.mv.visitVarInsn(Opcodes.ALOAD, idx); if (returnedLvalueSlot >= 0) { + ctx.mv.visitVarInsn(Opcodes.ALOAD, returnedLvalueSlot); + ctx.mv.visitVarInsn(Opcodes.ALOAD, idx); + ctx.mv.visitVarInsn(Opcodes.ILOAD, 2); + ctx.mv.visitInsn(ctx.javaClassInfo.isLvalueSubroutine + ? Opcodes.ICONST_0 : Opcodes.ICONST_1); + ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "prepareLocalArrayReturn", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;Lorg/perlonjava/runtime/runtimetypes/RuntimeArray;IZ)Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;", + false); + ctx.mv.visitVarInsn(Opcodes.ASTORE, returnedLvalueSlot); + ctx.mv.visitVarInsn(Opcodes.ALOAD, idx); ctx.mv.visitVarInsn(Opcodes.ALOAD, returnedLvalueSlot); ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/perlonjava/runtime/runtimetypes/MortalList", @@ -212,6 +260,7 @@ private static void emitScopeExitNullStores( false); continue; } + ctx.mv.visitVarInsn(Opcodes.ALOAD, idx); ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/perlonjava/runtime/runtimetypes/MortalList", "scopeExitCleanupArray", @@ -224,15 +273,9 @@ private static void emitScopeExitNullStores( java.util.List allIndices = includeCaptured ? ctx.symbolTable.getMyVariableIndicesInScope(scopeIndex) : withoutCaptured(ctx, ctx.symbolTable.getMyVariableIndicesInScope(scopeIndex)); - // Phase E (refcount_alignment_52leaks_plan.md): deregister each - // my-variable from MyVarCleanupStack before nulling the local slot. - // Without this, the static stack holds strong references to - // block-scoped scalars until the enclosing subroutine returns, - // preventing JVM GC and keeping their RuntimeBase targets alive - // past their Perl-level scope. The reachability walker would then - // treat the scalar as a live lexical and mark its referent as - // reachable, causing false-positive leaks (basic rerefrozen in - // DBIC's t/52leaks.t). + // Deregister each my-variable before nulling its local slot. Otherwise + // the cleanup stack retains a stale lexical cell after its Perl scope + // ends and lifecycle checks can treat it as live. // // When skipMyVarCleanup is true (CleanupNeededVisitor proved this // sub never uses bless/weaken/user-sub-calls/etc.), the stack is @@ -264,7 +307,7 @@ private static void emitScopeExitNullStores( if (flush) { ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/perlonjava/runtime/runtimetypes/MortalList", - "flushAboveMark", + markAtScopeEntry ? "popScopeMarkAndFlush" : "flushAboveMark", "()V", false); } @@ -438,8 +481,7 @@ public static void emitIf(EmitterVisitor emitterVisitor, IfNode node) { int scopeIndex = emitterVisitor.ctx.symbolTable.enterScope(); node.thenBranch.accept(branchVisitor(emitterVisitor, node.thenBranch)); - emitScopeExitNullStores(emitterVisitor.ctx, scopeIndex, - emitterVisitor.ctx.contextType == RuntimeContextType.VOID); + emitConditionalScopeExit(emitterVisitor.ctx, scopeIndex); emitterVisitor.ctx.symbolTable.exitScope(scopeIndex); for (int i = 0; i < branchLabelsPushed; i++) { @@ -454,8 +496,7 @@ public static void emitIf(EmitterVisitor emitterVisitor, IfNode node) { int scopeIndex = emitterVisitor.ctx.symbolTable.enterScope(); node.elseBranch.accept(branchVisitor(emitterVisitor, node.elseBranch)); - emitScopeExitNullStores(emitterVisitor.ctx, scopeIndex, - emitterVisitor.ctx.contextType == RuntimeContextType.VOID); + emitConditionalScopeExit(emitterVisitor.ctx, scopeIndex); emitterVisitor.ctx.symbolTable.exitScope(scopeIndex); for (int i = 0; i < branchLabelsPushed; i++) { @@ -562,8 +603,7 @@ public static void emitIf(EmitterVisitor emitterVisitor, IfNode node) { emitterVisitor.ctx.mv.visitLabel(endLabel); // Exit the scope in the symbol table - emitScopeExitNullStores(emitterVisitor.ctx, scopeIndex, - emitterVisitor.ctx.contextType == RuntimeContextType.VOID); + emitConditionalScopeExit(emitterVisitor.ctx, scopeIndex); emitterVisitor.ctx.symbolTable.exitScope(scopeIndex); for (int i = 0; i < branchLabelsPushed; i++) { @@ -573,6 +613,31 @@ public static void emitIf(EmitterVisitor emitterVisitor, IfNode node) { if (CompilerOptions.DEBUG_ENABLED) emitterVisitor.ctx.logDebug("IF end"); } + /** The conditional's result must own returned references before its lexicals end. */ + private static void emitConditionalScopeExit(EmitterContext ctx, int scopeIndex) { + if (ctx.contextType != RuntimeContextType.VOID + && !ctx.symbolTable.getMyVariableIndicesInScope(scopeIndex).isEmpty()) { + if (ctx.contextType == RuntimeContextType.RUNTIME) { + ctx.mv.visitVarInsn(Opcodes.ILOAD, 2); + } else { + ctx.mv.visitLdcInsn(ctx.contextType); + } + ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", "prepareScopeResult", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;I)Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;", + false); + // Native magic cleanup can flush its own releases. Keep result + // owners below this mark until the caller receives the expression. + ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", "pushMark", "()V", false); + emitScopeExitNullStores(ctx, scopeIndex, false); + ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", "popAndFlush", "()V", false); + return; + } + emitScopeExitNullStores(ctx, scopeIndex, ctx.contextType == RuntimeContextType.VOID); + } + /** Return the branch that emitIf will retain, or null when both branches remain dynamic. */ static Boolean constantIfConditionValue(IfNode node, String currentPackage) { Boolean constantValue = ConstantFoldingVisitor.getConstantConditionValue( @@ -1019,6 +1084,14 @@ public static void emitTryCatch(EmitterVisitor emitterVisitor, TryNode node) { emitterVisitor.ctx.javaClassInfo.activeTryFinallyContext = tryFinallyContext; } + int jvmFrameDepthSlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable(); + mv.visitVarInsn(Opcodes.ALOAD, emitterVisitor.ctx.javaClassInfo.jvmFrameStateSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "jvmFrameDepth", + "(Lorg/perlonjava/runtime/runtimetypes/ExecutionRuntimeState;)I", false); + mv.visitVarInsn(Opcodes.ISTORE, jvmFrameDepthSlot); + // Define the try-catch block before visiting labels for maximum ASM compatibility mv.visitTryCatchBlock(tryStart, tryEnd, catchBlock, "java/lang/Throwable"); @@ -1036,6 +1109,13 @@ public static void emitTryCatch(EmitterVisitor emitterVisitor, TryNode node) { // Exception handler mv.visitLabel(catchBlock); + mv.visitVarInsn(Opcodes.ALOAD, emitterVisitor.ctx.javaClassInfo.jvmFrameStateSlot); + mv.visitVarInsn(Opcodes.ILOAD, jvmFrameDepthSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "unwindJvmFramesToDepth", + "(Lorg/perlonjava/runtime/runtimetypes/ExecutionRuntimeState;I)V", false); + // --------- Store the exception in the catch parameter --------- // Preserve a reference passed to die; non-Perl exceptions become strings. mv.visitMethodInsn(Opcodes.INVOKESTATIC, diff --git a/src/main/java/org/perlonjava/backend/jvm/EmitSubroutine.java b/src/main/java/org/perlonjava/backend/jvm/EmitSubroutine.java index 5e5f8a1bb7..070bd64184 100644 --- a/src/main/java/org/perlonjava/backend/jvm/EmitSubroutine.java +++ b/src/main/java/org/perlonjava/backend/jvm/EmitSubroutine.java @@ -263,6 +263,8 @@ && isDirectLeafIntegerAddition(node.block, directLeafCaptures, JavaClassInfo newJavaClassInfo = new JavaClassInfo(); newJavaClassInfo.isSubroutineBody = !node.useTryCatch || node.name != null && !node.name.equals("(eval)"); + newJavaClassInfo.isTryExpressionWrapper = + node.getBooleanAnnotation("tryExpressionWrapper"); newJavaClassInfo.isSmartmatchPredicate = node.getBooleanAnnotation("smartmatchPredicate"); newJavaClassInfo.isSortComparator = node.getBooleanAnnotation("isSortComparator"); // Eval blocks are compiled as separate methods, but a goto inside one @@ -441,11 +443,35 @@ && isDirectLeafIntegerAddition(node.block, directLeafCaptures, deparseFlags |= RuntimeCode.DEPARSE_FLAG_WARNINGS; } - // Transfer pad constants (cached string literals referenced via \) from compile time - // to a registry so makeCodeObject() can attach them to the RuntimeCode at runtime. - if (subCtx.javaClassInfo.padConstants != null && !subCtx.javaClassInfo.padConstants.isEmpty()) { + // Register this optree's constants and nested anonymous optrees. + // The parent CV owns nested anonymous constants as the template + // from which later closure instances are created. + RuntimeBase[] padConstants = subCtx.javaClassInfo.padConstants == null + ? new RuntimeBase[0] + : subCtx.javaClassInfo.padConstants.toArray(new RuntimeBase[0]); + Map embeddedPadConstants = + subCtx.javaClassInfo.embeddedPadConstants; + Map> embeddedPadDescendants = + subCtx.javaClassInfo.embeddedPadConstantDescendants; + if (padConstants.length != 0 || !embeddedPadConstants.isEmpty()) { RuntimeCode.registerPadConstants(subCtx.javaClassInfo.javaClassName, - subCtx.javaClassInfo.padConstants.toArray(new RuntimeBase[0])); + padConstants, embeddedPadConstants, embeddedPadDescendants); + // Eval-block code is still a persistent part of its parent + // CV's compiled body. The try/catch wrapper changes how the + // block executes, not who owns its direct-call sites and pad + // constants across repeated executions. + boolean embeddedAnonymousOptree = node.useTryCatch + || node.name == null || node.name.equals("") + || node.getBooleanAnnotation("isMapGrepBlock") + || node.getBooleanAnnotation("inheritsSelfReference") + || node.getBooleanAnnotation("regexCallbackPseudoBlock"); + if (embeddedAnonymousOptree && ctx.javaClassInfo != null) { + ctx.javaClassInfo.addEmbeddedPadConstants( + subCtx.javaClassInfo.javaClassName, + padConstants, + embeddedPadConstants, + embeddedPadDescendants); + } } // Direct instantiation approach - no reflection needed! @@ -941,6 +967,21 @@ && isDirectLeafIntegerAddition(node.block, directLeafCaptures, false); } + // A noncapturing anonymous CV is a literal template owned by this + // optree, even after its result is stored and later cleared. + if ((node.name == null || node.name.equals("")) + && (visibleVariables.size() <= skipVariables + || node.getBooleanAnnotation("lexicalLiteralConstantCv"))) { + mv.visitInsn(Opcodes.DUP); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "retainActiveOptreeCodeTemplate", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)" + + "Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", + false); + mv.visitInsn(Opcodes.POP); + } + // 6. Clean up the stack if context is VOID if (ctx.contextType == RuntimeContextType.VOID) { mv.visitInsn(Opcodes.POP); // Remove the RuntimeScalar object from the stack @@ -1021,31 +1062,42 @@ static void handleApplyOperator(EmitterVisitor emitterVisitor, BinaryOperatorNod RuntimeScalar parseTimeCodeRef = operatorNode.getAnnotation("parseTimeCodeRef") instanceof RuntimeScalar codeRef ? codeRef : null; + RuntimeScalar deferredCallTarget = + operatorNode.getAnnotation("deferredDirectCallTarget") instanceof RuntimeScalar target + ? target : null; RuntimeScalar emissionTimeCodeRef = parseTimeCodeRef == null ? null - : GlobalVariable.getGlobalCodeRefForDirectCall(directName); - if (parseTimeCodeRef != null && emissionTimeCodeRef != parseTimeCodeRef) { - // A BEGIN block displaced this call site's original CV while - // the surrounding file was still compiling. Perl keeps that - // already-compiled call bound to the original CV. - int codeRefId = GlobalVariable.registerCompiledCodeRef(parseTimeCodeRef); - mv.visitLdcInsn(codeRefId); - mv.visitMethodInsn(Opcodes.INVOKESTATIC, - "org/perlonjava/runtime/runtimetypes/GlobalVariable", - "getCompiledCodeRef", - "(I)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", - false); - } else { - if (parseTimeCodeRef == null) { - GlobalVariable.getGlobalCodeRefForFreshLookup(directName); - } - mv.visitLdcInsn(directName); - mv.visitMethodInsn(Opcodes.INVOKESTATIC, - "org/perlonjava/runtime/runtimetypes/GlobalVariable", - "getGlobalCodeRefForDirectCall", - "(Ljava/lang/String;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", - false); - } + : GlobalVariable.getVisibleGlobalCodeRefForDirectCall(directName); + // Each generated CV owns one direct-call edge. The callsite + // descriptor carries the parse-time target only as metadata; the + // RuntimeCode installs an owner identity when it receives this + // pad-constant tree. + RuntimeScalar initialCallRef = parseTimeCodeRef != null + ? deferredCallTarget != null ? deferredCallTarget : parseTimeCodeRef + : emissionTimeCodeRef != null + ? emissionTimeCodeRef + : GlobalVariable.getGlobalCodeRefForFreshLookup(directName); + boolean compileTimePinned = parseTimeCodeRef != null + && emissionTimeCodeRef != parseTimeCodeRef; + boolean retainTargetIfDeletedBeforeCallsiteInstall = + operatorNode.getBooleanAnnotation("retainTargetIfDeletedBeforeCallsiteInstall"); + RuntimeScalar descriptor = new RuntimeScalar(); + String className = emitterVisitor.ctx.javaClassInfo.javaClassName; + int siteIndex = emitterVisitor.ctx.javaClassInfo.addPadConstant(descriptor); + descriptor.configureCompiledDirectCallSite( + directName, siteIndex, initialCallRef, compileTimePinned, + retainTargetIfDeletedBeforeCallsiteInstall); + descriptor.setCompiledDirectCallHasDeferredParseOwner( + deferredCallTarget != null); + descriptor.setCompiledDirectCallPinSlot(parseTimeCodeRef); + mv.visitLdcInsn(directName); + mv.visitLdcInsn(className); + mv.visitLdcInsn(siteIndex); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "resolveCompiledDirectCallForActive", + "(Ljava/lang/String;Ljava/lang/String;I)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", + false); } else if (node.left instanceof OperatorNode operatorNode && operatorNode.operator.equals("&") && operatorNode.operand instanceof IdentifierNode identifierNode) { @@ -1233,7 +1285,8 @@ static void handleApplyOperator(EmitterVisitor emitterVisitor, BinaryOperatorNod mv.visitLdcInsn(subroutineName); mv.visitVarInsn(Opcodes.ASTORE, nameSlot); - // Generate native RuntimeBase[] array for parameters instead of RuntimeList + // Keep evaluated arguments in a staging frame. A returned temporary can + // otherwise be released before the generated call reaches applyAtLocation. ListNode paramList = ListNode.makeList(node.right); if (paramList.elements.size() >= 2 && unwrapScalarAnonymousInvocation(paramList.elements.get(0)) instanceof BinaryOperatorNode invocation @@ -1254,14 +1307,23 @@ && unwrapScalarAnonymousInvocation(paramList.elements.get(0)) instanceof BinaryO argsArraySlot = emitterVisitor.ctx.symbolTable.allocateLocalVariable(); } - if (argCount <= 5) { - mv.visitInsn(Opcodes.ICONST_0 + argCount); - } else if (argCount <= 127) { - mv.visitIntInsn(Opcodes.BIPUSH, argCount); + boolean stagedArguments = argCount > 0; + if (stagedArguments) { + if (argCount <= 5) { + mv.visitInsn(Opcodes.ICONST_0 + argCount); + } else if (argCount <= 127) { + mv.visitIntInsn(Opcodes.BIPUSH, argCount); + } else { + mv.visitIntInsn(Opcodes.SIPUSH, argCount); + } + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", "newCallArguments", + "(I)Lorg/perlonjava/runtime/runtimetypes/RuntimeCode$CallArguments;", false); } else { - mv.visitIntInsn(Opcodes.SIPUSH, argCount); + mv.visitInsn(Opcodes.ICONST_0); + mv.visitTypeInsn(Opcodes.ANEWARRAY, + "org/perlonjava/runtime/runtimetypes/RuntimeBase"); } - mv.visitTypeInsn(Opcodes.ANEWARRAY, "org/perlonjava/runtime/runtimetypes/RuntimeBase"); mv.visitVarInsn(Opcodes.ASTORE, argsArraySlot); EmitterVisitor listVisitor = emitterVisitor.with(RuntimeContextType.LIST); @@ -1271,6 +1333,11 @@ && unwrapScalarAnonymousInvocation(paramList.elements.get(0)) instanceof BinaryO && node.left != null && node.left.getIndex() > 0) { emitterVisitor.ctx.javaClassInfo.callerLineTokenOverride = node.left.getIndex(); } + Label argumentsStart = stagedArguments ? new Label() : null; + Label argumentsEnd = stagedArguments ? new Label() : null; + Label argumentsFailure = stagedArguments ? new Label() : null; + Label argumentsReady = stagedArguments ? new Label() : null; + if (stagedArguments) mv.visitLabel(argumentsStart); try { for (int index = 0; index < argCount; index++) { int argSlot = emitterVisitor.ctx.javaClassInfo.acquireSpillSlot(); @@ -1292,16 +1359,12 @@ && unwrapScalarAnonymousInvocation(paramList.elements.get(0)) instanceof BinaryO mv.visitVarInsn(Opcodes.ASTORE, argSlot); } - mv.visitVarInsn(Opcodes.ALOAD, argsArraySlot); - if (index <= 5) { - mv.visitInsn(Opcodes.ICONST_0 + index); - } else if (index <= 127) { - mv.visitIntInsn(Opcodes.BIPUSH, index); - } else { - mv.visitIntInsn(Opcodes.SIPUSH, index); - } mv.visitVarInsn(Opcodes.ALOAD, argSlot); - mv.visitInsn(Opcodes.AASTORE); + mv.visitVarInsn(Opcodes.ALOAD, argsArraySlot); + mv.visitInsn(Opcodes.SWAP); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, + "org/perlonjava/runtime/runtimetypes/RuntimeCode$CallArguments", "add", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;)V", false); if (pooledArg) { emitterVisitor.ctx.javaClassInfo.releaseSpillSlot(); @@ -1311,6 +1374,19 @@ && unwrapScalarAnonymousInvocation(paramList.elements.get(0)) instanceof BinaryO emitterVisitor.ctx.javaClassInfo.callerLineTokenOverride = savedArgumentCallerLineOverride; } + if (stagedArguments) { + mv.visitLabel(argumentsEnd); + mv.visitJumpInsn(Opcodes.GOTO, argumentsReady); + mv.visitLabel(argumentsFailure); + mv.visitVarInsn(Opcodes.ALOAD, argsArraySlot); + mv.visitInsn(Opcodes.SWAP); + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, + "org/perlonjava/runtime/runtimetypes/RuntimeCode$CallArguments", "abandon", + "(Ljava/lang/Throwable;)Ljava/lang/Throwable;", false); + mv.visitInsn(Opcodes.ATHROW); + mv.visitLabel(argumentsReady); + mv.visitTryCatchBlock(argumentsStart, argumentsEnd, argumentsFailure, null); + } // Undefined direct-call diagnostics report the line containing the // function token, while caller() inside a successfully entered sub sees @@ -1398,7 +1474,9 @@ && unwrapScalarAnonymousInvocation(paramList.elements.get(0)) instanceof BinaryO Opcodes.INVOKESTATIC, "org/perlonjava/runtime/runtimetypes/RuntimeCode", "applyAtLocation", - "(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Ljava/lang/String;[Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;ILjava/lang/String;Ljava/lang/String;I)Lorg/perlonjava/runtime/runtimetypes/RuntimeList;", + stagedArguments + ? "(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Ljava/lang/String;Lorg/perlonjava/runtime/runtimetypes/RuntimeCode$CallArguments;ILjava/lang/String;Ljava/lang/String;I)Lorg/perlonjava/runtime/runtimetypes/RuntimeList;" + : "(Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Ljava/lang/String;[Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;ILjava/lang/String;Ljava/lang/String;I)Lorg/perlonjava/runtime/runtimetypes/RuntimeList;", false); // Generate an .apply() call if (pooledArgsArray) { diff --git a/src/main/java/org/perlonjava/backend/jvm/EmitVariable.java b/src/main/java/org/perlonjava/backend/jvm/EmitVariable.java index 2501d758b5..4235c4b976 100644 --- a/src/main/java/org/perlonjava/backend/jvm/EmitVariable.java +++ b/src/main/java/org/perlonjava/backend/jvm/EmitVariable.java @@ -142,6 +142,12 @@ private static boolean isBuiltinSpecialContainerVar(String sigil, String name) { * @param sigil The variable sigil (@ or %) */ private static void emitRuntimeContextConversion(EmitterVisitor emitterVisitor, String sigil) { + emitRuntimeContextConversion(emitterVisitor, sigil, false); + } + + /** Convert an array result, optionally retiring a temporary's scalar-context elements. */ + private static void emitRuntimeContextConversion( + EmitterVisitor emitterVisitor, String sigil, boolean discardTemporaryArrayElements) { MethodVisitor mv = emitterVisitor.ctx.mv; // Stack has the array/hash. We need to check wantarray (slot 2) and decide: @@ -172,8 +178,17 @@ private static void emitRuntimeContextConversion(EmitterVisitor emitterVisitor, // Scalar context: load array/hash and call .scalar(), store to result mv.visitVarInsn(Opcodes.ALOAD, inputSlot); - mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "org/perlonjava/runtime/runtimetypes/RuntimeBase", "scalar", - "()Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false); + if (discardTemporaryArrayElements && sigil.equals("@")) { + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "scalarAndDiscardTemporaryArray", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeArray;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", + false); + } else { + mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, + "org/perlonjava/runtime/runtimetypes/RuntimeBase", "scalar", + "()Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false); + } mv.visitVarInsn(Opcodes.ASTORE, resultSlot); mv.visitJumpInsn(Opcodes.GOTO, done); @@ -1654,8 +1669,32 @@ static void handleAssignOperator(EmitterVisitor emitterVisitor, BinaryOperatorNo "Unexpected state refalias target: " + varNode.operator); } } else { + // Move this lexical's exceptional-cleanup + // registration to the cell it now aliases. + mv.visitInsn(Opcodes.DUP); + mv.visitVarInsn(Opcodes.ALOAD, symEntry.index()); + mv.visitInsn(Opcodes.SWAP); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MyVarCleanupStack", + "replace", + "(Ljava/lang/Object;Ljava/lang/Object;)V", + false); mv.visitInsn(Opcodes.DUP); mv.visitVarInsn(Opcodes.ASTORE, symEntry.index()); + // Refaliasing replaces the cell bound to this + // lexical name. Transfer its active pad owner + // to the shared cell before the source name + // can leave scope. + new OperatorNode("__SUB__", null, varNode.tokenIndex) + .accept(emitterVisitor.with(RuntimeContextType.SCALAR)); + mv.visitVarInsn(Opcodes.ALOAD, symEntry.index()); + mv.visitInsn(Opcodes.SWAP); + mv.visitLdcInsn(varName); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "bindActiveLexical", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;Ljava/lang/String;)V", + false); } if (pooledRhs) { @@ -2554,12 +2593,14 @@ && emitConditionalReferenceAliasTarget(emitterVisitor, ternary, rhsListSlot, i)) mv.visitInsn(Opcodes.POP); mv.visitVarInsn(Opcodes.ALOAD, rhsListSlot); if (ctx.contextType == RuntimeContextType.RUNTIME) { - emitRuntimeContextConversion(emitterVisitor, "@"); + emitRuntimeContextConversion(emitterVisitor, "@", true); } else if (ctx.contextType != RuntimeContextType.LIST && ctx.contextType != RuntimeContextType.LVALUE_LIST) { - mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, - "org/perlonjava/runtime/runtimetypes/RuntimeArray", "scalar", - "()Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "scalarAndDiscardTemporaryArray", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeArray;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", + false); } if (pooledRhsList) ctx.javaClassInfo.releaseSpillSlot(); } @@ -3366,6 +3407,19 @@ static void handleMyOperator(EmitterVisitor emitterVisitor, OperatorNode node) { false); } + if (operator.equals("my") && (sigil.equals("@") || sigil.equals("%"))) { + // The active pad map is a strong runtime owner of this + // aggregate. Give it an identity after the lexical has + // been registered so scope cleanup can retire it. + emitterVisitor.ctx.mv.visitLdcInsn(var); + emitterVisitor.ctx.mv.visitVarInsn(Opcodes.ALOAD, varIndex); + emitterVisitor.ctx.mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "registerCurrentActiveLexical", + "(Ljava/lang/String;Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;)V", + false); + } + // Emit runtime attribute dispatch for my/state variables. // For 'our', attributes were already dispatched at compile time. if (!operator.equals("our") && node.annotations != null diff --git a/src/main/java/org/perlonjava/backend/jvm/EmitterMethodCreator.java b/src/main/java/org/perlonjava/backend/jvm/EmitterMethodCreator.java index 8d2affebce..e3c295a64e 100644 --- a/src/main/java/org/perlonjava/backend/jvm/EmitterMethodCreator.java +++ b/src/main/java/org/perlonjava/backend/jvm/EmitterMethodCreator.java @@ -385,6 +385,7 @@ public static byte[] getBytecode(EmitterContext ctx, Node ast, boolean useTryCat throw tooLarge; } catch (InterpreterFallbackException fallback) { discardPendingFormatExpressions(ctx); + discardUninstalledDirectCallDescriptors(ctx); // Re-throw - caller will handle interpreter fallback throw fallback; } catch (ArrayIndexOutOfBoundsException frameComputeCrash) { @@ -431,6 +432,7 @@ public static byte[] getBytecode(EmitterContext ctx, Node ast, boolean useTryCat // Compile to interpreter as fallback InterpretedCode interpretedCode = compileToInterpreter(ast, ctx, useTryCatch); + discardUninstalledDirectCallDescriptors(ctx); String[] envNames = ctx.capturedEnv != null ? ctx.capturedEnv : ctx.symbolTable.getVariableNames(); throw new InterpreterFallbackException(interpretedCode, envNames); } catch (PerlCompilerException compileError) { @@ -464,6 +466,18 @@ private static void discardPendingFormatExpressions(EmitterContext ctx) { } } + /** Release direct-call owners created by JVM generation that did not install an optree. */ + public static void discardUninstalledDirectCallDescriptors(EmitterContext ctx) { + if (ctx == null || ctx.javaClassInfo == null) return; + JavaClassInfo info = ctx.javaClassInfo; + if (info.padConstants != null) { + RuntimeCode.discardUninstalledCompiledDirectCallDescriptors( + info.padConstants.toArray(new RuntimeBase[0])); + } + info.embeddedPadConstants.values().forEach( + RuntimeCode::discardUninstalledCompiledDirectCallDescriptors); + } + private static boolean causedByAsmFrameMerge(Throwable error) { for (Throwable cause = error; cause != null; cause = cause.getCause()) { for (StackTraceElement frame : cause.getStackTrace()) { @@ -712,7 +726,11 @@ private static byte[] getBytecodeInternal(EmitterContext ctx, Node ast, boolean org.perlonjava.frontend.analysis.CleanupNeededVisitor cleanupVisitor = new org.perlonjava.frontend.analysis.CleanupNeededVisitor(); ast.accept(cleanupVisitor); - ctx.javaClassInfo.cleanupNeeded = cleanupVisitor.needsCleanup(); + // A try-expression wrapper can leave via PerlNonLocalReturnException + // after its finally block. Its locals need cleanup-stack registrations + // even when ordinary AST analysis sees no user calls or blesses. + ctx.javaClassInfo.cleanupNeeded = ctx.javaClassInfo.isTryExpressionWrapper + || cleanupVisitor.needsCleanup(); } // Manual frames removed - using COMPUTE_FRAMES for automatic frame computation @@ -827,6 +845,14 @@ private static byte[] getBytecodeInternal(EmitterContext ctx, Node ast, boolean // Recorded my-variable local indices for eval exception cleanup. // Populated during ast.accept(visitor) when useTryCatch is true. java.util.List evalCleanupLocals = null; + java.util.Map evalCleanupScalarNames = null; + int evalArgumentDepthSlot = -1; + int evalMethodInvocantDepthSlot = -1; + int evalMortalMarkDepthSlot = -1; + int evalTemporaryRootDepthSlot = -1; + int evalForeachSourceOwnerDepthSlot = -1; + int evalJvmFrameDepthSlot = -1; + int evalThrowableSlot = -1; if (useTryCatch) { if (CompilerOptions.DEBUG_ENABLED) ctx.logDebug("useTryCatch"); @@ -839,12 +865,55 @@ private static byte[] getBytecodeInternal(EmitterContext ctx, Node ast, boolean mv.visitInsn(Opcodes.ACONST_NULL); mv.visitVarInsn(Opcodes.ASTORE, evalErrorSlot); + // Record runtime-owned call frames before the protected eval + // body starts. The catch path finishes only staged arguments + // and chained invocant holds created inside this boundary. + evalArgumentDepthSlot = ctx.symbolTable.allocateLocalVariable(); + mv.visitVarInsn(Opcodes.ALOAD, ctx.javaClassInfo.jvmFrameStateSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "callArgumentFrameDepth", + "(Lorg/perlonjava/runtime/runtimetypes/ExecutionRuntimeState;)I", false); + mv.visitVarInsn(Opcodes.ISTORE, evalArgumentDepthSlot); + + evalMethodInvocantDepthSlot = ctx.symbolTable.allocateLocalVariable(); + mv.visitVarInsn(Opcodes.ALOAD, ctx.javaClassInfo.jvmFrameStateSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "methodInvocantHoldDepth", + "(Lorg/perlonjava/runtime/runtimetypes/ExecutionRuntimeState;)I", false); + mv.visitVarInsn(Opcodes.ISTORE, evalMethodInvocantDepthSlot); + + evalMortalMarkDepthSlot = ctx.symbolTable.allocateLocalVariable(); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "markDepth", "()I", false); + mv.visitVarInsn(Opcodes.ISTORE, evalMortalMarkDepthSlot); + evalTemporaryRootDepthSlot = ctx.symbolTable.allocateLocalVariable(); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "temporaryRootDepth", "()I", false); + mv.visitVarInsn(Opcodes.ISTORE, evalTemporaryRootDepthSlot); + evalForeachSourceOwnerDepthSlot = ctx.symbolTable.allocateLocalVariable(); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "foreachSourceOwnerDepth", "()I", false); + mv.visitVarInsn(Opcodes.ISTORE, evalForeachSourceOwnerDepthSlot); + evalJvmFrameDepthSlot = ctx.symbolTable.allocateLocalVariable(); + mv.visitVarInsn(Opcodes.ALOAD, ctx.javaClassInfo.jvmFrameStateSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "jvmFrameDepth", + "(Lorg/perlonjava/runtime/runtimetypes/ExecutionRuntimeState;)I", false); + mv.visitVarInsn(Opcodes.ISTORE, evalJvmFrameDepthSlot); + evalThrowableSlot = ctx.symbolTable.allocateLocalVariable(); + tryStart = new Label(); tryEnd = new Label(); catchBlock = new Label(); endCatch = new Label(); - // Define the try-catch block + // Define the try-catch block before visiting body labels. mv.visitTryCatchBlock(tryStart, tryEnd, catchBlock, "java/lang/Throwable"); mv.visitLabel(tryStart); @@ -869,12 +938,15 @@ private static byte[] getBytecodeInternal(EmitterContext ctx, Node ast, boolean // when die unwinds through the eval (exception handler). // Enable recording of my-variable indices for eval exception cleanup. ctx.javaClassInfo.evalCleanupLocals = new java.util.ArrayList<>(); + ctx.javaClassInfo.evalCleanupScalarNames = new java.util.HashMap<>(); ast.accept(visitor); // Snapshot and disable recording of my-variable indices. evalCleanupLocals = ctx.javaClassInfo.evalCleanupLocals; + evalCleanupScalarNames = ctx.javaClassInfo.evalCleanupScalarNames; ctx.javaClassInfo.evalCleanupLocals = null; + ctx.javaClassInfo.evalCleanupScalarNames = null; // Normal fallthrough return: spill and jump with empty operand stack. mv.visitVarInsn(Opcodes.ASTORE, returnValueSlot); @@ -1115,6 +1187,15 @@ private static byte[] getBytecodeInternal(EmitterContext ctx, Node ast, boolean // Start of the catch block mv.visitLabel(catchBlock); + // Direct JVM-to-JVM calls do not pass through RuntimeCode.apply. + // Remove generated frames that were bypassed by this eval catch. + mv.visitVarInsn(Opcodes.ALOAD, ctx.javaClassInfo.jvmFrameStateSlot); + mv.visitVarInsn(Opcodes.ILOAD, evalJvmFrameDepthSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "unwindJvmFramesToDepth", + "(Lorg/perlonjava/runtime/runtimetypes/ExecutionRuntimeState;I)V", false); + // Re-throw PerlNonLocalReturnException - eval BLOCK must not catch non-local returns // from map/grep blocks. The Throwable is on the stack. mv.visitInsn(Opcodes.DUP); @@ -1122,43 +1203,136 @@ private static byte[] getBytecodeInternal(EmitterContext ctx, Node ast, boolean "org/perlonjava/runtime/runtimetypes/PerlNonLocalReturnException"); Label notNonLocalReturn = new Label(); mv.visitJumpInsn(Opcodes.IFEQ, notNonLocalReturn); - mv.visitInsn(Opcodes.ATHROW); // Re-throw PerlNonLocalReturnException + // Untargeted map/grep return belongs to this eval boundary. + // A targeted try/finally return continues to its containing CV. + mv.visitInsn(Opcodes.DUP); + mv.visitTypeInsn(Opcodes.CHECKCAST, + "org/perlonjava/runtime/runtimetypes/PerlNonLocalReturnException"); + mv.visitFieldInsn(Opcodes.GETFIELD, + "org/perlonjava/runtime/runtimetypes/PerlNonLocalReturnException", + "targetCode", "Lorg/perlonjava/runtime/runtimetypes/RuntimeCode;"); + Label targetedReturn = new Label(); + mv.visitJumpInsn(Opcodes.IFNONNULL, targetedReturn); + mv.visitTypeInsn(Opcodes.CHECKCAST, + "org/perlonjava/runtime/runtimetypes/PerlNonLocalReturnException"); + java.util.List returnCleanupLocals = evalCleanupLocals == null + ? java.util.List.of() : new java.util.ArrayList<>( + new java.util.LinkedHashSet<>(evalCleanupLocals)); + mv.visitLdcInsn(returnCleanupLocals.size()); + mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); + for (int i = 0; i < returnCleanupLocals.size(); i++) { + mv.visitInsn(Opcodes.DUP); + mv.visitLdcInsn(i); + mv.visitVarInsn(Opcodes.ALOAD, returnCleanupLocals.get(i)); + mv.visitInsn(Opcodes.AASTORE); + } + mv.visitVarInsn(Opcodes.ILOAD, 2); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "finishEvalCallbackReturn", + "(Lorg/perlonjava/runtime/runtimetypes/PerlNonLocalReturnException;[Ljava/lang/Object;I)Lorg/perlonjava/runtime/runtimetypes/RuntimeList;", false); + mv.visitVarInsn(Opcodes.ASTORE, returnListSlot); + // The eval boundary consumed the transfer and retained its + // returned Perl owners, so discard temporary roots skipped + // by the non-local return's emitted cleanup. + mv.visitVarInsn(Opcodes.ILOAD, evalTemporaryRootDepthSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "restoreTemporaryRootDepth", "(I)V", false); + mv.visitVarInsn(Opcodes.ILOAD, evalForeachSourceOwnerDepthSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "restoreForeachSourceOwnerDepth", "(I)V", false); + emitEvalMethodInvocantCleanup(mv, ctx.javaClassInfo.jvmFrameStateSlot, + evalArgumentDepthSlot, evalMethodInvocantDepthSlot); + emitEvalDepthDecrement(mv); + mv.visitJumpInsn(Opcodes.GOTO, endCatch); + mv.visitLabel(targetedReturn); + mv.visitVarInsn(Opcodes.ASTORE, evalThrowableSlot); + emitEvalMethodInvocantCleanup(mv, ctx.javaClassInfo.jvmFrameStateSlot, + evalArgumentDepthSlot, evalMethodInvocantDepthSlot); + mv.visitVarInsn(Opcodes.ALOAD, ctx.javaClassInfo.jvmFrameStateSlot); + mv.visitVarInsn(Opcodes.ALOAD, 0); + mv.visitFieldInsn(Opcodes.GETFIELD, ctx.javaClassInfo.javaClassName, + "__SUB__", "Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;"); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "popJvmFrame", + "(Lorg/perlonjava/runtime/runtimetypes/ExecutionRuntimeState;Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)V", + false); + // Leave the target return's roots in place while it propagates; + // its RuntimeCode.apply boundary restores its own entry depth. + mv.visitVarInsn(Opcodes.ALOAD, evalThrowableSlot); + mv.visitInsn(Opcodes.ATHROW); mv.visitLabel(notNonLocalReturn); + mv.visitVarInsn(Opcodes.ASTORE, evalThrowableSlot); + emitEvalMethodInvocantCleanup(mv, ctx.javaClassInfo.jvmFrameStateSlot, + evalArgumentDepthSlot, evalMethodInvocantDepthSlot); + // Track eval depth for $^S: RuntimeCode.evalDepth-- - // Note: Throwable is on the stack but GETSTATIC/PUTSTATIC don't affect it emitEvalDepthDecrement(mv); - // The throwable object is on the stack // Catch the throwable + mv.visitVarInsn(Opcodes.ALOAD, evalThrowableSlot); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/perlonjava/runtime/operators/WarnDie", "catchEval", "(Ljava/lang/Throwable;)Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;", false); mv.visitInsn(Opcodes.POP); + // Generated block-return roots can be left behind when an + // exception skips their emitted pop. Preserve caller roots + // and discard only roots created inside this eval boundary. + mv.visitVarInsn(Opcodes.ILOAD, evalTemporaryRootDepthSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "restoreTemporaryRootDepth", "(I)V", false); + mv.visitVarInsn(Opcodes.ILOAD, evalForeachSourceOwnerDepthSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "restoreForeachSourceOwnerDepth", "(I)V", false); + + // Scope marks opened inside eval were bypassed by the thrown + // exception. Restore the eval-entry boundary before the + // explicit lexical cleanup below drains their releases. + mv.visitVarInsn(Opcodes.ILOAD, evalMortalMarkDepthSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/MortalList", + "restoreMarkDepth", "(I)V", false); + // Scope-exit cleanup for lexical variables allocated inside the eval body. // When die throws a PerlDieException, Java exception handling jumps directly // to this catch handler, skipping the emitScopeExitNullStores calls that // would normally run at each block exit. This loop ensures DESTROY fires - // for blessed objects that went out of scope during die. + // for blessed objects that went out of scope during die. The recorded + // locals are already in scope-teardown order: inner scopes are emitted + // before their parents, and each scope's pad indices are sorted in Perl's + // cleanup order. Keep the first occurrence when a local appears in more + // than one enclosing scope's cleanup list. // Note: DestroyDispatch.doCallDestroy saves/restores $@ around DESTROY, // so this is safe to do before the $@ snapshot below. if (evalCleanupLocals != null && !evalCleanupLocals.isEmpty()) { - // De-duplicate indices while preserving order. - // A variable may appear in multiple nested scopes - we want the last - // occurrence (from the innermost scope) to win, and cleanup should - // happen in reverse order (LIFO) to match Perl's DESTROY semantics. + // De-duplicate indices while preserving recorded teardown order. java.util.List uniqueLocals = new java.util.ArrayList<>( new java.util.LinkedHashSet<>(evalCleanupLocals)); - // Reverse to get LIFO order (innermost scope first) - java.util.Collections.reverse(uniqueLocals); for (int localIdx : uniqueLocals) { mv.visitVarInsn(Opcodes.ALOAD, localIdx); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/perlonjava/runtime/runtimetypes/MortalList", "evalExceptionScopeCleanup", "(Ljava/lang/Object;)V", false); + String variableName = evalCleanupScalarNames == null + ? null : evalCleanupScalarNames.get(localIdx); + if (variableName != null) { + mv.visitVarInsn(Opcodes.ALOAD, localIdx); + mv.visitLdcInsn(variableName); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "unbindCurrentActiveLexical", + "(Lorg/perlonjava/runtime/runtimetypes/RuntimeBase;Ljava/lang/String;)V", + false); + } mv.visitVarInsn(Opcodes.ALOAD, localIdx); mv.visitMethodInsn(Opcodes.INVOKESTATIC, "org/perlonjava/runtime/runtimetypes/MyVarCleanupStack", @@ -1406,6 +1580,7 @@ private static byte[] getBytecodeInternal(EmitterContext ctx, Node ast, boolean "(Lorg/perlonjava/runtime/runtimetypes/ExecutionRuntimeState;Lorg/perlonjava/runtime/runtimetypes/RuntimeScalar;)V", false); mv.visitInsn(Opcodes.ARETURN); // Returns an Object + mv.visitMaxs(0, 0); // Automatically computed mv.visitEnd(); @@ -2116,6 +2291,16 @@ public static RuntimeCode createRuntimeCode( System.err.println("Note: JVM compilation succeeded."); } RuntimeCode code = wrapAsCompiledCode(generatedClass, ctx, ast); + RuntimeBase[] padConstants = ctx.javaClassInfo.padConstants == null + ? new RuntimeBase[0] + : ctx.javaClassInfo.padConstants.toArray(new RuntimeBase[0]); + if (padConstants.length != 0 || !ctx.javaClassInfo.embeddedPadConstants.isEmpty()) { + code.installPadConstantTree( + ctx.javaClassInfo.javaClassName, + padConstants, + ctx.javaClassInfo.embeddedPadConstants, + ctx.javaClassInfo.embeddedPadConstantDescendants); + } code.setJvmClosureFrameRequired(ctx.javaClassInfo.jvmClosureFrameRequired); code.setPristineArgsSnapshotRequired( ctx.javaClassInfo.pristineArgsSnapshotRequired); @@ -2130,6 +2315,7 @@ public static RuntimeCode createRuntimeCode( System.err.println("Note: Method too large, using interpreter backend."); } RuntimeCode code = compileToInterpreter(ast, ctx, useTryCatch); + discardUninstalledDirectCallDescriptors(ctx); preservePristineArgsSnapshotMetadata(code, ctx); code.applySignatureMetadata(ast); return code; @@ -2141,6 +2327,7 @@ public static RuntimeCode createRuntimeCode( System.err.println("Note: JVM " + e.getClass().getSimpleName() + " (" + e.getMessage().split("\n")[0] + "), using interpreter backend."); } RuntimeCode code = compileToInterpreter(ast, ctx, useTryCatch); + discardUninstalledDirectCallDescriptors(ctx); preservePristineArgsSnapshotMetadata(code, ctx); code.applySignatureMetadata(ast); return code; @@ -2152,8 +2339,9 @@ public static RuntimeCode createRuntimeCode( System.err.println("Note: JVM compilation needs interpreter fallback (" + e.getMessage().split("\n")[0] + ")."); e.printStackTrace(System.err); } - return preservePristineArgsSnapshotMetadata( - compileToInterpreter(ast, ctx, useTryCatch), ctx); + RuntimeCode code = compileToInterpreter(ast, ctx, useTryCatch); + discardUninstalledDirectCallDescriptors(ctx); + return preservePristineArgsSnapshotMetadata(code, ctx); } throw e; } catch (InterpreterFallbackException e) { @@ -2161,6 +2349,7 @@ public static RuntimeCode createRuntimeCode( if (SHOW_FALLBACK) { System.err.println("Note: Using interpreter fallback (ASM frame compute crash)."); } + discardUninstalledDirectCallDescriptors(ctx); return preservePristineArgsSnapshotMetadata(e.interpretedCode, ctx); } catch (RuntimeException e) { if (USE_INTERPRETER_FALLBACK && needsInterpreterFallback(e)) { @@ -2168,8 +2357,9 @@ public static RuntimeCode createRuntimeCode( System.err.println("Note: JVM compilation needs interpreter fallback (" + getRootMessage(e) + ")."); e.printStackTrace(System.err); } - return preservePristineArgsSnapshotMetadata( - compileToInterpreter(ast, ctx, useTryCatch), ctx); + RuntimeCode code = compileToInterpreter(ast, ctx, useTryCatch); + discardUninstalledDirectCallDescriptors(ctx); + return preservePristineArgsSnapshotMetadata(code, ctx); } throw e; } @@ -2491,4 +2681,16 @@ private static void emitEvalDepthDecrement(MethodVisitor mv) { "org/perlonjava/runtime/runtimetypes/RuntimeCode", "decrementEvalDepth", "()V", false); } + + private static void emitEvalMethodInvocantCleanup( + MethodVisitor mv, int executionStateSlot, + int argumentDepthSlot, int methodInvocantDepthSlot) { + mv.visitVarInsn(Opcodes.ALOAD, executionStateSlot); + mv.visitVarInsn(Opcodes.ILOAD, argumentDepthSlot); + mv.visitVarInsn(Opcodes.ILOAD, methodInvocantDepthSlot); + mv.visitMethodInsn(Opcodes.INVOKESTATIC, + "org/perlonjava/runtime/runtimetypes/RuntimeCode", + "unwindEvalMethodInvocantHolds", + "(Lorg/perlonjava/runtime/runtimetypes/ExecutionRuntimeState;II)V", false); + } } diff --git a/src/main/java/org/perlonjava/backend/jvm/JavaClassInfo.java b/src/main/java/org/perlonjava/backend/jvm/JavaClassInfo.java index 5abe663795..6611bbfa13 100644 --- a/src/main/java/org/perlonjava/backend/jvm/JavaClassInfo.java +++ b/src/main/java/org/perlonjava/backend/jvm/JavaClassInfo.java @@ -240,6 +240,9 @@ public String integerLiteralField(NumberNode node, ClassWriter cw) { */ public boolean isLvalueSubroutine; + /** A synthetic lvalue wrapper must use the caller's context for returns. */ + public boolean isTryExpressionWrapper; + /** * Counter tracking nesting depth inside finally blocks. * Control flow statements (last, next, redo, return, goto) are prohibited in finally blocks. @@ -289,6 +292,13 @@ public boolean isCapturedVariableIndex(int index) { */ public List evalCleanupLocals; + /** Active-pad names paired with scalar locals for exact eval unwind cleanup. */ + public Map evalCleanupScalarNames; + + + /** Active chained-method invocant local slots for direct control-flow exits. */ + public final Deque activeMethodInvocantHoldSlots = new ArrayDeque<>(); + /** * A stack of loop labels for managing nested loops. */ @@ -325,6 +335,10 @@ public boolean isCapturedVariableIndex(int index) { * are cleared to emulate Perl 5's "optree reaping" behavior. */ public List padConstants; + /** Constants owned by anonymous optrees embedded in this code body. */ + public final Map embeddedPadConstants = new LinkedHashMap<>(); + /** Embedded optree descendant class names, grouped by their immediate template. */ + public final Map> embeddedPadConstantDescendants = new LinkedHashMap<>(); /** * Constructs a new JavaClassInfo object. @@ -370,11 +384,38 @@ public void ensureGotoCollections() { /** * Records a cached constant that was referenced via backslash in this subroutine. */ - public void addPadConstant(RuntimeBase constant) { + public int addPadConstant(RuntimeBase constant) { if (padConstants == null) { padConstants = new ArrayList<>(); } padConstants.add(constant); + return padConstants.size() - 1; + } + + /** Retain an embedded anonymous optree's constants with this CV template. */ + public void addEmbeddedPadConstants( + String className, + RuntimeBase[] constants, + Map descendants, + Map> descendantTrees) { + if (className != null && !className.isEmpty()) { + embeddedPadConstants.put(className, + constants == null ? new RuntimeBase[0] : constants.clone()); + Set descendantsForClass = descendants == null + ? new LinkedHashSet<>() : new LinkedHashSet<>(descendants.keySet()); + embeddedPadConstantDescendants.put(className, descendantsForClass); + } + if (descendants != null) { + descendants.forEach((nestedClassName, nestedConstants) -> + embeddedPadConstants.put(nestedClassName, + nestedConstants == null ? new RuntimeBase[0] : nestedConstants.clone())); + } + if (descendantTrees != null) { + descendantTrees.forEach((nestedClassName, nestedClasses) -> + embeddedPadConstantDescendants.put(nestedClassName, + nestedClasses == null ? new LinkedHashSet<>() + : new LinkedHashSet<>(nestedClasses))); + } } public int acquireSpillSlot() { diff --git a/src/main/java/org/perlonjava/frontend/analysis/CleanupNeededVisitor.java b/src/main/java/org/perlonjava/frontend/analysis/CleanupNeededVisitor.java index 954dabfb66..b2c3396104 100644 --- a/src/main/java/org/perlonjava/frontend/analysis/CleanupNeededVisitor.java +++ b/src/main/java/org/perlonjava/frontend/analysis/CleanupNeededVisitor.java @@ -20,8 +20,8 @@ *

  • bless — creates blessed-with-DESTROY targets that need * refCount decrement on scope exit.
  • *
  • weaken / isweak (any Scalar::Util qualified form) - * — sets the global {@code weakRefsExist} flag and requires the - * reachability walker to see our live lexicals.
  • + * — changes weak-reference lifecycle state and requires full lexical + * scope cleanup. *
  • local — dynamic-scope bookkeeping changes.
  • *
  • eval STRING — can do anything.
  • *
  • nested SubroutineNode — might capture our lexicals via @@ -91,6 +91,13 @@ public void visit(OperatorNode node) { mark(); return; } + // An explicit die skips emitted normal scope-exit cleanup. Lexicals + // that receive reference arguments must still be registered so the + // call boundary can retire their owners while unwinding the error. + if ("die".equals(node.operator)) { + mark(); + return; + } if (node.operand != null) node.operand.accept(this); } @@ -127,21 +134,19 @@ public void visit(BinaryOperatorNode node) { mark(); return; } - // Method call: $obj->method or $obj->method(args). - // In AST form, the RHS is either IdentifierNode(method_name) or - // BinaryOperatorNode("(", IdentifierNode(method_name), args). - // Array/hash derefs ($x->[i], $x->{k}) have ArrayLiteralNode / - // HashLiteralNode on the RHS — those are safe (no user code runs). + // Method or indirect CODE call. An indirect invocation such as + // $callback->() can throw while this sub's lexical argument cells are + // live, so it needs the same exceptional cleanup registration as a + // named call. Only array/hash dereferences ($x->[i], $x->{k}) are + // known not to invoke user code. if ("->".equals(node.operator)) { Node right = node.right; - if (right instanceof IdentifierNode - || right instanceof BinaryOperatorNode binOp && "(".equals(binOp.operator)) { - mark(); + if (right instanceof ArrayLiteralNode || right instanceof HashLiteralNode) { + if (node.left != null) node.left.accept(this); + if (right != null) right.accept(this); return; } - // Array/hash deref — recurse into children only. - if (node.left != null) node.left.accept(this); - if (node.right != null) node.right.accept(this); + mark(); return; } if (node.left != null) node.left.accept(this); diff --git a/src/main/java/org/perlonjava/frontend/analysis/TempLocalCountVisitor.java b/src/main/java/org/perlonjava/frontend/analysis/TempLocalCountVisitor.java index 84cf536d0d..93a81779b4 100644 --- a/src/main/java/org/perlonjava/frontend/analysis/TempLocalCountVisitor.java +++ b/src/main/java/org/perlonjava/frontend/analysis/TempLocalCountVisitor.java @@ -98,6 +98,15 @@ public void visit(BinaryOperatorNode node) { @Override public void visit(BlockNode node) { + if (node.elements.size() == 2 + && node.elements.get(0) instanceof OperatorNode localOp + && localOp.operator.equals("local") + && node.elements.get(1) instanceof For1Node forNode + && forNode.needsArrayOfAlias) { + // EmitBlock pre-evaluates the foreach source and retains its owner + // depth across the skipped `local $_` statement boundary. + countTemp(); + } for (Node element : node.elements) { if (element != null) { element.accept(this); diff --git a/src/main/java/org/perlonjava/frontend/astnode/For1Node.java b/src/main/java/org/perlonjava/frontend/astnode/For1Node.java index f858b81fb0..1e739dd9f5 100644 --- a/src/main/java/org/perlonjava/frontend/astnode/For1Node.java +++ b/src/main/java/org/perlonjava/frontend/astnode/For1Node.java @@ -39,6 +39,13 @@ public class For1Node extends AbstractNode { */ public int preEvaluatedArrayIndex = -1; + /** + * If nonnegative, the foreach source owners were acquired alongside + * {@link #preEvaluatedArrayIndex} before the implicit {@code local $_} + * statement boundary. + */ + public int preEvaluatedForeachSourceOwnerDepthIndex = -1; + /** * Constructs a new For1Node with the specified parts of the for loop. * diff --git a/src/main/java/org/perlonjava/frontend/parser/ClassTransformer.java b/src/main/java/org/perlonjava/frontend/parser/ClassTransformer.java index 766884c428..5e170caab4 100644 --- a/src/main/java/org/perlonjava/frontend/parser/ClassTransformer.java +++ b/src/main/java/org/perlonjava/frontend/parser/ClassTransformer.java @@ -1117,13 +1117,12 @@ private static void predeclareConstructor(String className) { // Initialize as a code reference if needed if (codeRef.value == null) { - codeRef.type = RuntimeScalarType.CODE; RuntimeCode code = new RuntimeCode("new", null); code.packageName = className; code.subName = "new"; // No prototype for constructors - they accept any arguments code.prototype = null; - codeRef.value = code; + codeRef.set(new RuntimeScalar(code)); } } } diff --git a/src/main/java/org/perlonjava/frontend/parser/DataSection.java b/src/main/java/org/perlonjava/frontend/parser/DataSection.java index 1fb12fa2eb..addb93daab 100644 --- a/src/main/java/org/perlonjava/frontend/parser/DataSection.java +++ b/src/main/java/org/perlonjava/frontend/parser/DataSection.java @@ -292,7 +292,7 @@ private static void createDataHandle( RuntimeScalar contentScalar = dataContentScalar(content); ScalarBackedIO newScalarIO = new ScalarBackedIO(contentScalar); newScalarIO.seek(initialPosition, IOHandle.SEEK_SET); - existingIO.ioHandle = newScalarIO; + existingIO.replaceIOHandle(newScalarIO); if (CompilerOptions.DEBUG_ENABLED) parser.ctx.logDebug("Updated existing DATA handle with new content"); } else { // Fallback: create new handle if no placeholder exists diff --git a/src/main/java/org/perlonjava/frontend/parser/SubroutineParser.java b/src/main/java/org/perlonjava/frontend/parser/SubroutineParser.java index b9cc13e251..b27d34d83a 100644 --- a/src/main/java/org/perlonjava/frontend/parser/SubroutineParser.java +++ b/src/main/java/org/perlonjava/frontend/parser/SubroutineParser.java @@ -929,6 +929,18 @@ && isHashReferenceConstant(constantCode) } } codeRefNode.setAnnotation("parseTimeCodeRef", parseTimeCodeRef); + if (codeRefNode.getBooleanAnnotation("directNamedCall") + && parseTimeCodeRef.type == RuntimeScalarType.CODE + && parseTimeCodeRef.value instanceof RuntimeCode parseTimeCode + && parseTimeCode.defined()) { + // A generated closure may be emitted after compile-time + // namespace cleanup has removed this imported CV's stash + // entry. Keep the parse-time target owned until its + // compiled callsite takes over, as for explicit &name calls. + codeRefNode.setAnnotation("retainTargetIfDeletedBeforeCallsiteInstall", true); + codeRefNode.setAnnotation("deferredDirectCallTarget", + GlobalVariable.snapshotDeferredDirectCallTarget(parseTimeCodeRef)); + } if (parseTimeCodeRef.value instanceof RuntimeCode code && RuntimeCode.isLvalueCode(code)) { codeRefNode.setAnnotation("directLvalueCall", true); @@ -2239,8 +2251,10 @@ public static ListNode handleNamedSubWithFilter(Parser parser, String subName, S // would lose the fact that a body was already defined and incorrectly // let a late :lvalue declaration change that body. if (codeRef.value == null || (isRedefinition && block != null)) { - codeRef.type = RuntimeScalarType.CODE; - codeRef.value = new RuntimeCode(subName, attributes); + // Keep the stash scalar cell, but replace its referent through the + // ordinary slot transition. Directly assigning `value` leaves a + // CODE_SLOT owner attached to the previous CV after redefinition. + codeRef.set(new RuntimeScalar(new RuntimeCode(subName, attributes))); } // Mark as explicitly declared so *{glob}{CODE} returns this code ref. // In Perl 5, declared subs (even forward declarations) are visible via *{glob}{CODE}. @@ -2396,6 +2410,9 @@ public static ListNode handleNamedSubWithFilter(Parser parser, String subName, S placeholder.ourVariableRegistry = visibleOurs.isEmpty() ? null : new LinkedHashMap<>(visibleOurs); explicitlyUsedVars = usedVarSet; + // Runtime eval may read lexicals from the sub's definition context. + // Keep its broad capture set unless the collector proved the eval + // source is a constant string that cannot name a lexical. if (!collector.requiresAllRuntimeLexicals()) { usedVars = usedVarSet; } @@ -2550,7 +2567,7 @@ && isLexicalSubStorageReferenced(explicitlyUsedVars, entry.name()) // Eval STRING requires conservatively retaining every visible // runtime value, but that implementation capture is not a // semantic closure edge. Record only names explicitly used by - // the sub AST for lifecycle/reachability decisions. + // the sub AST for lifecycle decisions. capturedNames.add((!entry.decl().equals("our") || isEvalSeedLexical(entry)) && explicitlyUsedVars.contains(entry.name()) ? entry.name() : null); @@ -2793,6 +2810,7 @@ && isLexicalSubStorageReferenced(explicitlyUsedVars, entry.name()) placeholder, capturedNames, materializedCaptures); placeholder.cvStartFile = compiledCode.cvStartFile; placeholder.cvStartLine = compiledCode.cvStartLine; + compiledCode.transferPadConstantTreeTo(placeholder); } else if (runtimeCode instanceof InterpretedCode interpretedCode) { // InterpretedCode path - update placeholder in-place (not replace codeRef.value) @@ -2846,6 +2864,10 @@ && isLexicalSubStorageReferenced(explicitlyUsedVars, entry.name()) installClosureCaptureMetadata(placeholder, materializedCaptures); placeholder.cvStartFile = interpretedCode.cvStartFile; placeholder.cvStartLine = interpretedCode.cvStartLine; + // The published placeholder is the Perl-owned CV. Move + // the interpreter optree's constant edges onto it so the + // temporary executable wrapper cannot pin pad literals. + interpretedCode.transferPadConstantTreeTo(placeholder); } } catch (VerifyError ve) { // VerifyError extends Error (not Exception), so it's not caught by catch(Exception). @@ -2899,19 +2921,12 @@ && isLexicalSubStorageReferenced(explicitlyUsedVars, entry.name()) installClosureCaptureMetadata(placeholder, materializedCaptures); placeholder.cvStartFile = interpretedCode.cvStartFile; placeholder.cvStartLine = interpretedCode.cvStartLine; + interpretedCode.transferPadConstantTreeTo(placeholder); } catch (Exception e) { // Handle any exceptions during subroutine creation throw new PerlCompilerException("Subroutine error: " + e.getMessage()); } - // Transfer pad constants (cached string literals referenced via \) - // from compile context to the RuntimeCode for optree reaping. - if (newCtx.javaClassInfo.padConstants != null && !newCtx.javaClassInfo.padConstants.isEmpty()) { - placeholder.padConstants = newCtx.javaClassInfo.padConstants.toArray( - new org.perlonjava.runtime.runtimetypes.RuntimeBase[0]); - GlobalVariable.invalidateGlobalCodeRefGraphRoots(); - } - // Clear the compilerSupplier once done (use the captured placeholder variable) // This prevents the Supplier from being invoked multiple times placeholder.compilerSupplier = null; @@ -2993,22 +3008,14 @@ private static List closureCapturesForMaterialization( private static void installClosureCaptureMetadata( RuntimeCode code, List capturedNames, List capturedValues) { - // Named subs created through the parser populate an existing stash - // scalar in place rather than going through RuntimeGlob's CODE-slot - // assignment path. Account for that persistent stash owner so a - // temporary copy of \&name cannot release the named CV's pad. - if (code != null && code.stashRefCount == 0) { - for (RuntimeScalar installed : GlobalVariable.globalCodeRefs.values()) { - if (installed != null && installed.value == code) { - code.hadStashRef = true; - code.stashRefCount = 1; - break; - } - } + // Named subs populate their stash scalar in place. Its CODE_SLOT + // identity is the persistent owner proof even though installation did + // not pass through RuntimeGlob's value-replacement path. + if (code != null && code.hasStashCodeSlotOwner()) { + code.hadStashRef = true; } if (code != null) { code.captureFieldsRecorded = true; - GlobalVariable.invalidateGlobalCodeRefGraphRoots(); } if (code == null || capturedValues == null || capturedValues.isEmpty() || code.capturedScalars != null || code.capturedAggregates != null) { @@ -3016,10 +3023,19 @@ private static void installClosureCaptureMetadata( } ArrayList capturedScalars = new ArrayList<>(); + ArrayList capturedScalarOwnerSlots = new ArrayList<>(); ArrayList capturedAggregates = new ArrayList<>(); ArrayList capturedAggregateOwnerSlots = new ArrayList<>(); for (int i = 0; i < capturedValues.size(); i++) { Object value = capturedValues.get(i); + // Dynamic eval keeps broad implementation captures so its source + // can resolve lexical names at runtime. Those cells are not + // semantic closure edges unless the sub body references them + // directly; do not let the owner ledger extend their lifetime. + if (capturedNames == null || i >= capturedNames.size() + || capturedNames.get(i) == null) { + continue; + } if (capturedNames != null && i < capturedNames.size() && capturedNames.get(i) != null && value instanceof RuntimeBase runtimeValue) { if (code.closedOverVariables == null) { @@ -3029,24 +3045,26 @@ private static void installClosureCaptureMetadata( } if (value instanceof RuntimeScalar scalar) { capturedScalars.add(scalar); - scalar.retainClosureCapture(); + capturedScalarOwnerSlots.add(scalar.retainClosureCaptureSlot(code)); } else if (value instanceof RuntimeArray || value instanceof RuntimeHash) { RuntimeBase aggregate = (RuntimeBase) value; capturedAggregates.add(aggregate); - capturedAggregateOwnerSlots.add(aggregate.retainClosureCaptureOwner()); + capturedAggregateOwnerSlots.add(aggregate.retainClosureCaptureOwner(code)); } } if (!capturedScalars.isEmpty()) { code.capturedScalars = capturedScalars.toArray(new RuntimeScalar[0]); + code.capturedScalarOwnerSlots = + capturedScalarOwnerSlots.toArray(new PerlOwnerSlot[0]); } if (!capturedAggregates.isEmpty()) { code.capturedAggregates = capturedAggregates.toArray(new RuntimeBase[0]); code.capturedAggregateOwnerSlots = capturedAggregateOwnerSlots.toArray(new PerlOwnerSlot[0]); } - GlobalVariable.invalidateGlobalCodeRefGraphRoots(); - if (!capturedScalars.isEmpty() || !capturedAggregates.isEmpty()) { - code.refCount = 0; + if ((!capturedScalars.isEmpty() || !capturedAggregates.isEmpty()) + && code.isRefCountUntracked()) { + code.startRefCountTracking(); } } diff --git a/src/main/java/org/perlonjava/frontend/parser/Variable.java b/src/main/java/org/perlonjava/frontend/parser/Variable.java index 7d65decd22..3ff0bfe0e8 100644 --- a/src/main/java/org/perlonjava/frontend/parser/Variable.java +++ b/src/main/java/org/perlonjava/frontend/parser/Variable.java @@ -1124,6 +1124,18 @@ static Node parseCoderefVariable(Parser parser, LexerToken token) { && operatorNode.operator.equals("&") && operatorNode.operand instanceof IdentifierNode) { operatorNode.setAnnotation("directNamedCall", true); + operatorNode.setAnnotation("retainTargetIfDeletedBeforeCallsiteInstall", true); + Object parseTimeRef = operatorNode.getAnnotation("parseTimeCodeRef"); + if (parseTimeRef instanceof RuntimeScalar codeRef + && codeRef.type == RuntimeScalarType.CODE + && codeRef.value instanceof RuntimeCode) { + // This call may live in a lazily compiled subroutine. Keep its + // parse-time CV alive in an independent scalar until RuntimeCode + // installs the callsite owner. The visible glob slot itself can + // be emptied by deletion before lazy compilation happens. + operatorNode.setAnnotation("deferredDirectCallTarget", + GlobalVariable.snapshotDeferredDirectCallTarget(codeRef)); + } } Node list; diff --git a/src/main/java/org/perlonjava/frontend/semantic/ScopedSymbolTable.java b/src/main/java/org/perlonjava/frontend/semantic/ScopedSymbolTable.java index a51de9f0b5..1ab8aca441 100644 --- a/src/main/java/org/perlonjava/frontend/semantic/ScopedSymbolTable.java +++ b/src/main/java/org/perlonjava/frontend/semantic/ScopedSymbolTable.java @@ -502,6 +502,11 @@ public java.util.List getMyHashIndicesInScope(int scopeIndex) { } } } + // Perl destroys lexical hashes in reverse declaration order. The + // symbol maps are HashMaps, so their iteration order cannot define + // observable DESTROY ordering. Pad indices increase with declaration + // order and remain unique across the active scope chain. + indices.sort(java.util.Comparator.reverseOrder()); return indices; } @@ -519,6 +524,8 @@ public java.util.List getMyArrayIndicesInScope(int scopeIndex) { } } } + // Native Perl clears lexical arrays in declaration order. + indices.sort(java.util.Comparator.naturalOrder()); return indices; } @@ -540,6 +547,9 @@ public java.util.List getMyScalarIndicesInScope(int scopeIndex) { } } } + // DESTROY order is observable; scalar pads leave scope in reverse + // declaration order, independent of HashMap iteration order. + indices.sort(java.util.Comparator.reverseOrder()); return indices; } diff --git a/src/main/java/org/perlonjava/runtime/HintHashRegistry.java b/src/main/java/org/perlonjava/runtime/HintHashRegistry.java index 491e9b060e..a9431150d1 100644 --- a/src/main/java/org/perlonjava/runtime/HintHashRegistry.java +++ b/src/main/java/org/perlonjava/runtime/HintHashRegistry.java @@ -65,7 +65,7 @@ public static void exitScope() { state().clearedConstantHandlerCategoryStack.pop(); // %^H scope guards implement compile-time callbacks in DESTROY. // They must run before parsing/executing the next statement, not - // at the interpreter's later top-level mortal sweep. + // at the interpreter's later top-level mortal cleanup. MortalList.flush(); } } @@ -343,17 +343,18 @@ public static Map getCurrentCallSiteScalarHintHash() { * Object::HashBase's deferred Role::Tiny composition). */ public static void restoreHintHash(RuntimeHash active, Map saved) { - List discarded = new ArrayList<>(); List discardedKeys = new ArrayList<>(); for (Map.Entry entry : active.elements.entrySet()) { RuntimeScalar retained = saved.get(entry.getKey()); RuntimeScalar current = entry.getValue(); if (retained == null || retained.type != current.type || retained.value != current.value) { - discarded.add(current); discardedKeys.add(entry.getKey()); } } - MortalList.deferDestroyForContainerClear(discarded); + // RuntimeHash.elements is an owner-aware map. Removing through it retires + // the %^H slot identity and queues any compile-time scope-guard DESTROY. + // Do not separately defer the values here: that would release each + // discarded Perl edge twice. for (String key : discardedKeys) { active.elements.remove(key); } diff --git a/src/main/java/org/perlonjava/runtime/WarningBitsRegistry.java b/src/main/java/org/perlonjava/runtime/WarningBitsRegistry.java index efe2d49ba4..d05e106182 100644 --- a/src/main/java/org/perlonjava/runtime/WarningBitsRegistry.java +++ b/src/main/java/org/perlonjava/runtime/WarningBitsRegistry.java @@ -374,23 +374,6 @@ private static java.util.Map snapshotHintHashStackScalars() { - java.util.ArrayList out = new java.util.ArrayList<>(); - CompilationRuntimeState state = state(); - Deque> stack = state.callerHintHashStack; - for (java.util.Map frame : stack) { - out.addAll(frame.values()); - } - out.addAll(state.callSiteHintHash.values()); - return out; - } - /** * Restores the caller's %^H from the caller stack. * Called by RuntimeCode.apply() after a subroutine returns. diff --git a/src/main/java/org/perlonjava/runtime/io/CustomFileChannel.java b/src/main/java/org/perlonjava/runtime/io/CustomFileChannel.java index 7798612ce3..d89ce8c7e1 100644 --- a/src/main/java/org/perlonjava/runtime/io/CustomFileChannel.java +++ b/src/main/java/org/perlonjava/runtime/io/CustomFileChannel.java @@ -894,7 +894,22 @@ private void releaseCurrentLock() throws IOException { @Override public RuntimeScalar sysread(int length) { - return doRead(length, StandardCharsets.ISO_8859_1); + if (length <= 0) return doRead(length, StandardCharsets.ISO_8859_1); + + // Keep each channel read bounded, but continue until the requested + // amount has been read or the file reaches EOF. Perl's sysread on a + // regular file can fill a request larger than MAX_READ_CHUNK; returning + // only the first internal chunk breaks callers that slide their window + // by the count returned from sysread. + StringBuilder result = new StringBuilder(Math.min(length, MAX_READ_CHUNK)); + while (result.length() < length) { + int remaining = length - result.length(); + RuntimeScalar chunk = doRead(Math.min(remaining, MAX_READ_CHUNK), StandardCharsets.ISO_8859_1); + String data = chunk.toString(); + if (data.isEmpty()) break; + result.append(data); + } + return new RuntimeScalar(result.toString()); } @Override diff --git a/src/main/java/org/perlonjava/runtime/io/LayeredIOHandle.java b/src/main/java/org/perlonjava/runtime/io/LayeredIOHandle.java index 09c2cd661d..75dbbbc212 100644 --- a/src/main/java/org/perlonjava/runtime/io/LayeredIOHandle.java +++ b/src/main/java/org/perlonjava/runtime/io/LayeredIOHandle.java @@ -9,6 +9,7 @@ import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; import java.util.function.Function; diff --git a/src/main/java/org/perlonjava/runtime/io/NativeFdIOHandle.java b/src/main/java/org/perlonjava/runtime/io/NativeFdIOHandle.java index 16f1fd9adf..173ab093d5 100644 --- a/src/main/java/org/perlonjava/runtime/io/NativeFdIOHandle.java +++ b/src/main/java/org/perlonjava/runtime/io/NativeFdIOHandle.java @@ -161,7 +161,7 @@ public RuntimeIO registerInIOSystem() { // Create a RuntimeIO wrapping this handle RuntimeIO rio = new RuntimeIO(); - rio.ioHandle = this; + rio.replaceIOHandle(this); rio.registerExternalFd(nativeFd); return rio; diff --git a/src/main/java/org/perlonjava/runtime/io/ViaLayer.java b/src/main/java/org/perlonjava/runtime/io/ViaLayer.java index 9350db6faa..e496deaae8 100644 --- a/src/main/java/org/perlonjava/runtime/io/ViaLayer.java +++ b/src/main/java/org/perlonjava/runtime/io/ViaLayer.java @@ -2,9 +2,9 @@ import org.perlonjava.runtime.mro.InheritanceResolver; import org.perlonjava.runtime.operators.ModuleOperators; -import org.perlonjava.runtime.runtimetypes.DestroyDispatch; import org.perlonjava.runtime.runtimetypes.GlobalVariable; import org.perlonjava.runtime.runtimetypes.NameNormalizer; +import org.perlonjava.runtime.runtimetypes.PerlOwnerSlot; import org.perlonjava.runtime.runtimetypes.RuntimeArray; import org.perlonjava.runtime.runtimetypes.RuntimeBase; import org.perlonjava.runtime.runtimetypes.RuntimeCode; @@ -17,6 +17,8 @@ import org.perlonjava.runtime.runtimetypes.RuntimeScalarType; import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; /** * Perl-implemented PerlIO layer, created by :via(...). @@ -41,7 +43,37 @@ public class ViaLayer implements IOLayer { private final RuntimeScalar poppedMethod; private boolean popped; - private boolean holdsSelfReference; + private SelfReferenceOwner selfReferenceOwner; + + /** Owner identity for the Java layer's retained Perl {@code PUSHED} value. */ + static final class SelfReferenceOwner { + final PerlOwnerSlot ownerSlot; + private boolean released; + + private SelfReferenceOwner(RuntimeBase referent) { + ownerSlot = new PerlOwnerSlot(PerlOwnerSlot.Kind.IO_VIA_LAYER); + ownerSlot.acquireCountedNativeOwner(referent, "ViaLayer retains PUSHED object"); + } + + static SelfReferenceOwner retain(RuntimeScalar self) { + if (self == null || !RuntimeScalarType.isReference(self) + || !(self.value instanceof RuntimeBase base) + || base.isPerlDestroyed()) { + return null; + } + return new SelfReferenceOwner(base); + } + + PerlOwnerSlot ownerSlot() { + return ownerSlot; + } + + synchronized void release() { + if (released) return; + released = true; + ownerSlot.releaseNativeOwner(); + } + } public ViaLayer(String requestedPackage, IOHandle belowHandle, String mode) { this.belowIO = new RuntimeIO(new BorrowedIOHandle(belowHandle)); @@ -319,25 +351,13 @@ private String callbackPackage() { } private void holdSelfReference() { - if (RuntimeScalarType.isReference(self) - && self.value instanceof RuntimeBase base - && base.refCount >= 0) { - base.refCount++; - holdsSelfReference = true; - } + selfReferenceOwner = SelfReferenceOwner.retain(self); } private void releaseSelfReference() { - if (!holdsSelfReference) { - return; - } - if (RuntimeScalarType.isReference(self) && self.value instanceof RuntimeBase base) { - if (base.refCount > 0 && --base.refCount == 0) { - base.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(base); - } - } - holdsSelfReference = false; + SelfReferenceOwner owner = selfReferenceOwner; + selfReferenceOwner = null; + if (owner != null) owner.release(); } private static boolean isPushFailure(RuntimeScalar result) { diff --git a/src/main/java/org/perlonjava/runtime/operators/Directory.java b/src/main/java/org/perlonjava/runtime/operators/Directory.java index ea462168d1..898d5a2234 100644 --- a/src/main/java/org/perlonjava/runtime/operators/Directory.java +++ b/src/main/java/org/perlonjava/runtime/operators/Directory.java @@ -205,6 +205,7 @@ public static RuntimeScalar opendir(RuntimeList args) { if ((dirHandle.type == RuntimeScalarType.GLOB || dirHandle.type == RuntimeScalarType.GLOBREFERENCE) && dirHandle.value instanceof RuntimeGlob glob) { glob.setIO(newDirectoryIO); + MyVarCleanupStack.retainLiveIoGlobOwners(glob, dirHandle); } else { RuntimeScalar directoryGlob = new RuntimeGlob(null) .setIO(newDirectoryIO).createReference(); diff --git a/src/main/java/org/perlonjava/runtime/operators/FileTestOperator.java b/src/main/java/org/perlonjava/runtime/operators/FileTestOperator.java index 33821e95a2..91753857e3 100644 --- a/src/main/java/org/perlonjava/runtime/operators/FileTestOperator.java +++ b/src/main/java/org/perlonjava/runtime/operators/FileTestOperator.java @@ -78,9 +78,13 @@ static void updateLastStat(RuntimeScalar arg, boolean ok, int errno) { updateLastStat(arg, ok, errno, false); } - private static RuntimeScalar snapshotStatArgument(RuntimeScalar arg) { + static RuntimeScalar snapshotStatArgument(RuntimeScalar arg) { if (arg.type == RuntimeScalarType.GLOB || arg.type == RuntimeScalarType.GLOBREFERENCE) { - return arg; + // Perl's cached stat buffer retains the result and the displayed + // subject, not a new strong reference to the caller's glob. Keep + // an immutable scalar snapshot so file-test bookkeeping cannot + // extend a lexical handle's lifetime past its last Perl owner. + return new RuntimeScalar(arg.toString()); } return new RuntimeScalar(arg.toString()); } @@ -306,7 +310,7 @@ public static RuntimeScalar fileTest(String operator, RuntimeScalar fileHandle) // object as its subject. There is no native stat result // to cache, but the bytecode stack form consumes the // current file-test subject through the same cache slot. - state().lastFileHandle.set(fileHandle); + state().lastFileHandle.set(snapshotStatArgument(fileHandle)); updateLastStat(fileHandle, true, 0); state().lastOverloadedFileTestSubject.set(fileHandle); state().hasLastOverloadedFileTestSubject = true; diff --git a/src/main/java/org/perlonjava/runtime/operators/IOOperator.java b/src/main/java/org/perlonjava/runtime/operators/IOOperator.java index dd944bd1bf..1d074578bd 100644 --- a/src/main/java/org/perlonjava/runtime/operators/IOOperator.java +++ b/src/main/java/org/perlonjava/runtime/operators/IOOperator.java @@ -40,6 +40,10 @@ public class IOOperator { private static final int O_NONBLOCK = NativeUtils.IS_MAC ? 4 : 04000; + private static void retainLiveIoGlobOwners(RuntimeGlob glob, RuntimeScalar handle) { + MyVarCleanupStack.retainLiveIoGlobOwners(glob, handle); + } + // File descriptor to RuntimeIO mapping for duplication support private static Map fileDescriptorMap() { return PerlRuntime.current().ioRegistryState.operatorFileDescriptors; @@ -836,6 +840,7 @@ public static RuntimeScalar open(int ctx, RuntimeBase... args) { // registered on the global glob, so callers can find it by name. } } + retainLiveIoGlobOwners(targetGlob, fileHandle); } else { RuntimeScalar newGlob = new RuntimeScalar(); newGlob.type = RuntimeScalarType.GLOBREFERENCE; @@ -1094,6 +1099,7 @@ else if (secondArg.type == RuntimeScalarType.GLOB || secondArg.type == RuntimeSc System.err.flush(); } targetGlob.openIO(fh); + retainLiveIoGlobOwners(targetGlob, fileHandle); } else { // Create a new anonymous GLOB and assign it to the lvalue RuntimeScalar newGlob = new RuntimeScalar(); @@ -2038,13 +2044,15 @@ public static RuntimeScalar sysopen(int ctx, RuntimeBase... args) { if (targetGlob != null) { targetGlob.openIO(fh); + retainLiveIoGlobOwners(targetGlob, fileHandle); } else { RuntimeScalar newGlob = new RuntimeScalar(); newGlob.type = RuntimeScalarType.GLOBREFERENCE; RuntimeGlob anonGlob = new RuntimeGlob(null).setIO(fh); newGlob.value = anonGlob; RuntimeIO.registerGlobForFdRecycling(anonGlob, fh); - fileHandle.set(newGlob); + RuntimeScalar assignedHandle = fileHandle.set(newGlob); + RuntimeScalar.retainUnstashedIoForDurableSlot(assignedHandle); } return scalarTrue; } @@ -2571,8 +2579,7 @@ public static RuntimeScalar socket(int ctx, RuntimeBase... args) { if (targetGlob != null) { targetGlob.setIO(socketIO); - MyVarCleanupStack.retainLiveIoGlobOwners(targetGlob); - RuntimeScalar.retainUnstashedIoForDurableSlot(socketHandle); + retainLiveIoGlobOwners(targetGlob, socketHandle); } else { // Create a new anonymous GLOB and assign it to the lvalue RuntimeScalar newGlob = new RuntimeScalar(); @@ -2857,8 +2864,7 @@ public static RuntimeScalar accept(int ctx, RuntimeBase... args) { if (targetGlob != null) { targetGlob.setIO(clientRuntimeIO); targetGlob.acceptedSocket = true; - MyVarCleanupStack.retainLiveIoGlobOwners(targetGlob); - RuntimeScalar.retainUnstashedIoForDurableSlot(newSocketHandle); + retainLiveIoGlobOwners(targetGlob, newSocketHandle); } else { // Create a new anonymous GLOB and assign it to the lvalue RuntimeScalar newGlob = new RuntimeScalar(); @@ -2933,10 +2939,10 @@ public static RuntimeScalar pipe(int ctx, RuntimeBase... args) { // Create RuntimeIO objects for the handles RuntimeIO readerIO = new RuntimeIO(); - readerIO.ioHandle = readerHandle; + readerIO.replaceIOHandle(readerHandle); RuntimeIO writerIO = new RuntimeIO(); - writerIO.ioHandle = writerHandle; + writerIO.replaceIOHandle(writerHandle); // Handle autovivification for read handle (like open() does) RuntimeGlob readGlob = null; @@ -2950,6 +2956,7 @@ public static RuntimeScalar pipe(int ctx, RuntimeBase... args) { } if (readGlob != null) { readGlob.setIO(readerIO); + retainLiveIoGlobOwners(readGlob, readHandle); } else { // Create a new anonymous GLOB and assign it to the lvalue RuntimeScalar newGlob = new RuntimeScalar(); @@ -2972,6 +2979,7 @@ public static RuntimeScalar pipe(int ctx, RuntimeBase... args) { } if (writeGlob != null) { writeGlob.setIO(writerIO); + retainLiveIoGlobOwners(writeGlob, writeHandle); } else { // Create a new anonymous GLOB and assign it to the lvalue RuntimeScalar newGlob = new RuntimeScalar(); @@ -3792,14 +3800,14 @@ private static RuntimeIO createBorrowedHandle(RuntimeIO source) { } RuntimeIO borrowed = new RuntimeIO(); if (source.ioHandle instanceof BorrowedIOHandle existingBorrow) { - borrowed.ioHandle = BorrowedIOHandle.addBorrow(existingBorrow); + borrowed.replaceIOHandle(BorrowedIOHandle.addBorrow(existingBorrow)); } else { // The lexical source handle may leave scope immediately after this // open(). Replace it with the source half of a shared lifecycle so // GC cleanup cannot close the delegate while this alias is live. BorrowedIOHandle[] pair = BorrowedIOHandle.createPair(source.ioHandle); - source.ioHandle = pair[0]; - borrowed.ioHandle = pair[1]; + source.replaceIOHandle(pair[0]); + borrowed.replaceIOHandle(pair[1]); } borrowed.currentLineNumber = source.currentLineNumber; // Share the source's fileno (parsimonious dup = same fd) @@ -3827,7 +3835,7 @@ private static RuntimeIO duplicateFileHandle(RuntimeIO original) { if (original.ioHandle instanceof DupIOHandle existingDup) { // Already reference-counted — add another dup sharing the same delegate - duplicate.ioHandle = DupIOHandle.addDup(existingDup); + duplicate.replaceIOHandle(DupIOHandle.addDup(existingDup)); } else { // First duplication — wrap both original and duplicate in DupIOHandles // so they share a refcount and get distinct filenos. @@ -3860,11 +3868,11 @@ private static RuntimeIO duplicateFileHandle(RuntimeIO original) { DupIOHandle[] pair = DupIOHandle.createPair(dupTarget, origFd); if (layeredWrapper != null) { - original.ioHandle = cloneLayeredHandle(layeredWrapper, pair[0]); - duplicate.ioHandle = cloneLayeredHandle(layeredWrapper, pair[1]); + original.replaceIOHandle(cloneLayeredHandle(layeredWrapper, pair[0])); + duplicate.replaceIOHandle(cloneLayeredHandle(layeredWrapper, pair[1])); } else { - original.ioHandle = pair[0]; // Replace original's handle with refcounted wrapper - duplicate.ioHandle = pair[1]; // New handle with unique fd + original.replaceIOHandle(pair[0]); // Replace with refcounted wrapper + duplicate.replaceIOHandle(pair[1]); // New handle with unique fd } } @@ -4010,11 +4018,11 @@ public static RuntimeScalar socketpair(int ctx, RuntimeBase... args) { socket2.setDatagramPeer(socket1); RuntimeIO io1 = new RuntimeIO(); - io1.ioHandle = socket1; + io1.replaceIOHandle(socket1); io1.assignFileno(); RuntimeIO io2 = new RuntimeIO(); - io2.ioHandle = socket2; + io2.replaceIOHandle(socket2); io2.assignFileno(); setSocketOnHandle(sock1Handle, io1); @@ -4071,11 +4079,11 @@ public static RuntimeScalar socketpair(int ctx, RuntimeBase... args) { // Create RuntimeIO objects for both sockets using NIO channels RuntimeIO io1 = new RuntimeIO(); - io1.ioHandle = socket1; + io1.replaceIOHandle(socket1); io1.assignFileno(); RuntimeIO io2 = new RuntimeIO(); - io2.ioHandle = socket2; + io2.replaceIOHandle(socket2); io2.assignFileno(); // Set IO slot on each handle, following the same pattern as socket() @@ -4111,8 +4119,7 @@ private static void setSocketOnHandle(RuntimeScalar handle, RuntimeIO io) { } else { targetGlob.setIO(io); } - MyVarCleanupStack.retainLiveIoGlobOwners(targetGlob); - RuntimeScalar.retainUnstashedIoForDurableSlot(handle); + retainLiveIoGlobOwners(targetGlob, handle); } else { // Create a new anonymous GLOB and assign it to the lvalue RuntimeScalar newGlob = new RuntimeScalar(); diff --git a/src/main/java/org/perlonjava/runtime/operators/ListOperators.java b/src/main/java/org/perlonjava/runtime/operators/ListOperators.java index 21a4297477..5f1a268e86 100644 --- a/src/main/java/org/perlonjava/runtime/operators/ListOperators.java +++ b/src/main/java/org/perlonjava/runtime/operators/ListOperators.java @@ -11,18 +11,69 @@ public class ListOperators { /** - * Perl evaluates the input list before entering a map/grep-style block. - * Keep the scalar objects (and therefore their aliasing) but detach the - * iteration order from a source array that the block may mutate. + * Perl evaluates map's input list before entering the block. Keep its + * scalar cells and detach iteration order from a source array the block + * may replace. */ - private static List snapshotElements(RuntimeList runtimeList) { + private static ElementSnapshot snapshotElements(RuntimeList runtimeList) { + return new ElementSnapshot(runtimeList); + } + + private static List snapshotValues(RuntimeList runtimeList) { List snapshot = new ArrayList<>(); - for (RuntimeScalar element : runtimeList) { - snapshot.add(element); - } + for (RuntimeScalar element : runtimeList) snapshot.add(element); return snapshot; } + /** + * The evaluated list keeps each source scalar cell alive for the complete + * map, even if the block replaces the aggregate that supplied the list. + * Each entry aliases the original scalar cell; it is not a copied value. + */ + private static final class ElementSnapshot { + private final List elements = new ArrayList<>(); + private final List owners = new ArrayList<>(); + + private ElementSnapshot(RuntimeList runtimeList) { + try { + for (RuntimeScalar element : runtimeList) { + elements.add(element); + owners.add(element.retainArgumentAliasOwner()); + } + } catch (Throwable acquisitionFailure) { + try { + releaseOwners(acquisitionFailure); + } catch (RuntimeException | Error combinedFailure) { + throw combinedFailure; + } + throw new IllegalStateException(acquisitionFailure); + } + } + + private void releaseOwners(Throwable pendingFailure) { + RuntimeScalar.ArgumentAliasOwner[] pending = + owners.toArray(new RuntimeScalar.ArgumentAliasOwner[0]); + owners.clear(); + for (RuntimeScalar.ArgumentAliasOwner owner : pending) { + try { + owner.release(); + } catch (Throwable cleanupFailure) { + if (pendingFailure == null) pendingFailure = cleanupFailure; + else if (pendingFailure != cleanupFailure) pendingFailure.addSuppressed(cleanupFailure); + } + } + if (pendingFailure != null && pendingFailure instanceof RuntimeException runtimeException) { + throw runtimeException; + } + if (pendingFailure instanceof Error error) throw error; + if (pendingFailure != null) throw new IllegalStateException(pendingFailure); + } + + private void close() { + releaseOwners(null); + } + } + /** * Eagerly release captured variable references from an ephemeral grep/map/all/any * block closure. Like eval BLOCK closures, these blocks execute and are immediately @@ -61,6 +112,7 @@ public static RuntimeList map(RuntimeList runtimeList, RuntimeScalar perlMapClos boolean savedTemporaryAlias = GlobalVariable.isTemporaryGlobalAlias("main::_"); // Map results are captured by the caller after the operator returns; // flushing between iterations can destroy blessed return values early. + ElementSnapshot elements = snapshotElements(runtimeList); boolean wasFlushing = MortalList.suppressFlush(true); try { @@ -69,7 +121,7 @@ public static RuntimeList map(RuntimeList runtimeList, RuntimeScalar perlMapClos RuntimeArray mapArgs = outerArgs != null ? outerArgs : new RuntimeArray(); // Iterate over the list value captured before the block starts. - for (RuntimeScalar element : snapshotElements(runtimeList)) { + for (RuntimeScalar element : elements.elements) { // Create $_ argument for the map subroutine GlobalVariable.aliasTemporaryGlobalVariable("main::_", element); @@ -132,9 +184,16 @@ public static RuntimeList map(RuntimeList runtimeList, RuntimeScalar perlMapClos return transformedList; } } finally { - MortalList.suppressFlush(wasFlushing); - GlobalVariable.restoreTemporaryGlobalVariable("main::_", saveValue, savedTemporaryAlias); - releaseEphemeralCaptures(perlMapClosure); + try { + MortalList.suppressFlush(wasFlushing); + GlobalVariable.restoreTemporaryGlobalVariable("main::_", saveValue, savedTemporaryAlias); + } finally { + try { + elements.close(); + } finally { + releaseEphemeralCaptures(perlMapClosure); + } + } } } @@ -360,7 +419,9 @@ public static RuntimeList grep(RuntimeList runtimeList, RuntimeScalar perlFilter RuntimeArray filterArgs = outerArgs != null ? outerArgs : new RuntimeArray(); // Iterate over the list value captured before the block starts. - for (RuntimeScalar element : snapshotElements(runtimeList)) { + for (RuntimeScalar element : snapshotValues(runtimeList)) { + RuntimeScalar.ArgumentAliasOwner elementOwner = + element.retainArgumentAliasOwner(); try { // Create $_ argument for the filter subroutine GlobalVariable.aliasTemporaryGlobalVariable("main::_", element); @@ -396,6 +457,8 @@ public static RuntimeList grep(RuntimeList runtimeList, RuntimeScalar perlFilter } catch (Exception e) { // Wrap any exceptions thrown by the filter subroutine in a RuntimeException throw new RuntimeException(e); + } finally { + elementOwner.release(); } } @@ -444,7 +507,7 @@ public static RuntimeList all(RuntimeList runtimeList, RuntimeScalar perlFilterC RuntimeArray filterArgs = outerArgs != null ? outerArgs : new RuntimeArray(); // Iterate over the list value captured before the block starts. - for (RuntimeScalar element : snapshotElements(runtimeList)) { + for (RuntimeScalar element : snapshotValues(runtimeList)) { try { // Create $_ argument for the filter subroutine GlobalVariable.aliasTemporaryGlobalVariable("main::_", element); @@ -504,7 +567,7 @@ public static RuntimeList any(RuntimeList runtimeList, RuntimeScalar perlFilterC RuntimeArray filterArgs = outerArgs != null ? outerArgs : new RuntimeArray(); // Iterate over the list value captured before the block starts. - for (RuntimeScalar element : snapshotElements(runtimeList)) { + for (RuntimeScalar element : snapshotValues(runtimeList)) { try { // Create $_ argument for the filter subroutine GlobalVariable.aliasTemporaryGlobalVariable("main::_", element); diff --git a/src/main/java/org/perlonjava/runtime/operators/ModuleOperators.java b/src/main/java/org/perlonjava/runtime/operators/ModuleOperators.java index 278b0044d7..f2266b4a2b 100644 --- a/src/main/java/org/perlonjava/runtime/operators/ModuleOperators.java +++ b/src/main/java/org/perlonjava/runtime/operators/ModuleOperators.java @@ -129,38 +129,22 @@ public static RuntimeBase doFile(RuntimeScalar runtimeScalar, int ctx) { /** * JVM-backend wrapper for `do FILE` that accepts the compile-time - * current package. We temporarily override the runtime package tracker - * so the loaded file inherits the caller's namespace (Perl 5 semantics). + * current package as a fallback when the runtime package is not available. + * An active package established by runtime eval remains authoritative. */ public static RuntimeBase doFileInPackage(RuntimeScalar runtimeScalar, int ctx, String callerPackage) { try (PerlRuntime.Binding ignored = PerlRuntime.current().bind()) { - String savedPackage = InterpreterState.currentPackage.get().toString(); - try { - if (callerPackage != null && !callerPackage.isEmpty()) { - InterpreterState.currentPackage.get().set(callerPackage); - } - return doFile(runtimeScalar, true, false, ctx); - } finally { - InterpreterState.currentPackage.get().set(savedPackage); - } + return doFile(runtimeScalar, true, false, ctx, callerPackage); } } /** * JVM-backend wrapper for `require FILE` that accepts the compile-time - * current package (see doFileInPackage above). + * current package as a fallback (see doFileInPackage above). */ public static RuntimeScalar requireInPackage(RuntimeScalar runtimeScalar, String callerPackage) { try (PerlRuntime.Binding ignored = PerlRuntime.current().bind()) { - String savedPackage = InterpreterState.currentPackage.get().toString(); - try { - if (callerPackage != null && !callerPackage.isEmpty()) { - InterpreterState.currentPackage.get().set(callerPackage); - } - return require(runtimeScalar); - } finally { - InterpreterState.currentPackage.get().set(savedPackage); - } + return require(runtimeScalar, callerPackage); } } @@ -204,6 +188,25 @@ public static RuntimeScalar requireInPackage(RuntimeScalar runtimeScalar, String * @return Result of execution (undef on error, with $@ or $! set) */ private static RuntimeBase doFile(RuntimeScalar runtimeScalar, boolean setINC, boolean isRequire, int ctx) { + return doFile(runtimeScalar, setINC, isRequire, ctx, null); + } + + private static String initialPackageForLoad(String runtimePackage, String explicitPackage, + String callerPackage) { + if (isNonMainPackage(runtimePackage)) return runtimePackage; + if (isNonMainPackage(explicitPackage)) return explicitPackage; + if (isNonMainPackage(callerPackage)) return callerPackage; + if (runtimePackage != null && !runtimePackage.isEmpty()) return runtimePackage; + if (explicitPackage != null && !explicitPackage.isEmpty()) return explicitPackage; + return callerPackage; + } + + private static boolean isNonMainPackage(String packageName) { + return packageName != null && !packageName.isEmpty() && !"main".equals(packageName); + } + + private static RuntimeBase doFile(RuntimeScalar runtimeScalar, boolean setINC, boolean isRequire, int ctx, + String explicitInitialPackage) { List incEntriesChecked = INC_ENTRIES_CHECKED.get(); incEntriesChecked.clear(); if (runtimeScalar == null || !runtimeScalar.getDefinedBoolean() @@ -851,19 +854,13 @@ else if (code == null) { // declarations in the JVM backend (see EmitOperator.handlePackageOperator). CallerStack.CallerInfo loadCaller = CallerStack.peek(0); String callerPackage = loadCaller == null ? null : loadCaller.packageName(); - // A non-main caller frame is the most precise context for runtime - // require and for `use`, which pushes its parser package explicitly. - // Compile-time special blocks can leave a main-package frame on the - // stack while requireInPackage has already supplied a non-main package - // through InterpreterState.currentPackage; do not let that stale main - // frame erase the explicit package context. - parsedArgs.initialPackage = callerPackage != null - && !callerPackage.isEmpty() - && (!"main".equals(callerPackage) - || savedPackage == null || savedPackage.isEmpty() - || "main".equals(savedPackage)) - ? callerPackage - : savedPackage; + // The runtime package is scoped by `package` statements, including + // package declarations inside eval STRING. It is therefore more + // accurate than a CallerStack frame when a runtime eval dispatches a + // nested do/require. Use the compiler-supplied package or caller frame + // only when the active package is still main/unknown. + parsedArgs.initialPackage = initialPackageForLoad( + savedPackage, explicitInitialPackage, callerPackage); // Save and clear %^H (hints hash) to prevent hint leakage into required modules. // In Perl >= 5.11 (which we emulate), hints don't leak into require'd files. @@ -1060,6 +1057,11 @@ private static boolean isDirectoryResource(URL resource) { */ public static RuntimeScalar require(RuntimeScalar runtimeScalar) { try (PerlRuntime.Binding ignored = PerlRuntime.current().bind()) { + return require(runtimeScalar, null); + } + } + + private static RuntimeScalar require(RuntimeScalar runtimeScalar, String explicitInitialPackage) { LAST_LOADED_SCOPE.remove(); // https://perldoc.perl.org/functions/require @@ -1119,7 +1121,8 @@ public static RuntimeScalar require(RuntimeScalar runtimeScalar) { // Call doFile with require-specific behavior - set %INC optimistically // require always runs in scalar context - RuntimeBase baseResult = doFile(runtimeScalar, true, true, RuntimeContextType.SCALAR); + RuntimeBase baseResult = doFile(runtimeScalar, true, true, RuntimeContextType.SCALAR, + explicitInitialPackage); RuntimeScalar result = baseResult.scalar(); String requireDebug = System.getenv("JPERL_REQUIRE_DEBUG"); @@ -1187,7 +1190,6 @@ public static RuntimeScalar require(RuntimeScalar runtimeScalar) { // If module_true was disabled, result will be the module's actual return value runRequireAfterHooks(postAction, fileName); return result; - } } private static RuntimeScalar runRequireBeforeHook(RuntimeScalar fileName) { diff --git a/src/main/java/org/perlonjava/runtime/operators/ReferenceOperators.java b/src/main/java/org/perlonjava/runtime/operators/ReferenceOperators.java index 259354130a..11678ec77e 100644 --- a/src/main/java/org/perlonjava/runtime/operators/ReferenceOperators.java +++ b/src/main/java/org/perlonjava/runtime/operators/ReferenceOperators.java @@ -136,18 +136,12 @@ private static RuntimeScalar bless(RuntimeScalar runtimeScalar, RuntimeScalar cl // "perhaps you forgot to load" hint. GlobalVariable.ensurePackageStash(str); - // Phase D-W6.10: arm targeted refCount tracing for classes - // matching the walker-gate heuristic (Class::MOP/Moose/Moo) - // when env-flag PJ_REFCOUNT_TRACE is set. Lets us pinpoint - // which specific increment/decrement site causes the - // metaclass refCount underflow during CMOP bootstrap. + // Optionally arm targeted refCount tracing for one selected class. String traceClass = System.getenv("PJ_REFCOUNT_TRACE_CLASS"); boolean traceClassMatch = traceClass != null && !traceClass.isEmpty() && str.contains(traceClass); - if (RuntimeBase.refCountTraceEnabled() - && (traceClassMatch || org.perlonjava.runtime.runtimetypes.DestroyDispatch - .classNeedsWalkerGate(newBlessId))) { + if (RuntimeBase.refCountTraceEnabled() && traceClassMatch) { referent.refCountTrace = true; System.err.println("[REFCOUNT] *** ARMED *** base=" + System.identityHashCode(referent) @@ -156,25 +150,18 @@ private static RuntimeScalar bless(RuntimeScalar runtimeScalar, RuntimeScalar cl + " refCount=" + referent.refCount); } - if (referent.refCount >= 0) { + if (referent.isRefCountTracked()) { // Already-tracked referent (e.g., anonymous hash from `bless {}`). // Always keep tracking — even classes without DESTROY need // cascading cleanup of their hash/array elements when freed. if (referent.blessId == 0) { - // First bless of a tracked referent. Mortal-ize: bump refCount - // and queue a deferred decrement so that if the blessed ref is - // never stored in a named variable (method-chain temporaries like - // `Foo->new()->method()`), the flush brings refCount back to 0 - // and fires DESTROY. If the ref IS stored (the common - // `my $self = bless {}, $class` pattern), setLargeRefCounted() - // increments refCount first, so the mortal flush leaves it at the - // correct count. + // First bless of a tracked referent. The mortal reference + // remains an identified owner until its deferred boundary, so + // an unstored expression reaches zero and fires DESTROY while + // a subsequent scalar store leaves that scalar's count intact. referent.setBlessId(newBlessId); - referent.traceRefCount(+1, "ReferenceOperators.bless tracked referent"); - referent.refCount++; // 0 → 1 (or N → N+1 for edge cases) - referent.acquireTransientTraceOwner("bless mortal temporary", - "ReferenceOperators.bless tracked referent"); - MortalList.deferDecrement(referent, "bless mortal temporary"); + MortalList.deferBlessTemporary(referent, + !WeakRefRegistry.isweak(runtimeScalar)); } else { // Re-bless: update class, keep refCount. referent.setBlessId(newBlessId); @@ -190,7 +177,7 @@ private static RuntimeScalar bless(RuntimeScalar runtimeScalar, RuntimeScalar cl // Retroactively count references stored in existing elements. // When the hash/array was created (e.g., bless { key => $ref }), // elements were stored while the container was untracked - // (refCount == -1). Those stores did NOT increment referents' + // while the referent was untracked. Those stores did NOT increment referents' // refCounts. Now that we're transitioning to tracked, we must // count these as strong references so scopeExitCleanupHash // correctly decrements them when the container is destroyed. @@ -200,39 +187,39 @@ private static RuntimeScalar bless(RuntimeScalar runtimeScalar, RuntimeScalar cl // held by a ResultSet's {result_source} hash element). if (referent instanceof RuntimeHash hash) { for (RuntimeScalar elem : hash.elements.values()) { - RuntimeScalar.incrementRefCountForContainerStore(elem); + RuntimeScalar.incrementRefCountForContainerStore( + elem, PerlOwnerSlot.Kind.HASH_ELEMENT); } } else if (referent instanceof RuntimeArray arr) { for (RuntimeScalar elem : arr.elements) { - RuntimeScalar.incrementRefCountForContainerStore(elem); + RuntimeScalar.incrementRefCountForContainerStore( + elem, PerlOwnerSlot.Kind.ARRAY_ELEMENT); } } + // Scalar owners may already hold this referent inside an + // untracked container or temporary list. Promote those exact + // owner-slot identities now; blessing changes lifecycle + // tracking, but it does not create or remove Perl edges. + referent.startRefCountTracking(); + referent.promoteUntrackedScalarOwners(); + if (wasAlreadyBlessed) { // Re-bless from untracked class: the scalar being blessed // already holds a reference that was never counted (because // tracking wasn't active at assignment time). Count it as 1. - referent.refCount = 1; - referent.recordOwner(runtimeScalar, "rebless from untracked"); - runtimeScalar.refCountOwned = true; + if (!runtimeScalar.refCountOwned) { + RuntimeScalar.acquireCountedOwnerForCurrentValue( + runtimeScalar, referent, runtimeScalar.countedOwnerKind(), + "ReferenceOperators.bless rebless from untracked"); + } } else { - // First bless: start at refCount=1 and add to MortalList. - // The mortal entry will decrement back to 0 at the next - // statement-boundary flush (FREETMPS equivalent). - // - // If the blessed ref is stored in a named variable (the - // common `my $self = bless {}, $class` pattern), setLarge() - // increments refCount to 2. The mortal flush then brings it - // back to 1, which is correct: only the variable owns it. - // - // If the blessed ref is returned directly without storage - // (e.g., `sub new { bless {}, shift }`), the mortal entry - // ensures the object is properly cleaned up when the caller's - // statement boundary flushes, fixing method chain temporaries - // like `Foo->new()->method()` where the invocant was never - // tracked. + // Establish only the owners that already exist. The + // identified bless temporary below supplies its own count; + // a later scalar store acquires a separate count as usual. boolean existingScalarOwner = RuntimeScalarType.isReference(runtimeScalar) + && !WeakRefRegistry.isweak(runtimeScalar) && !runtimeScalar.refCountOwned && (runtimeScalar instanceof GlobalRuntimeScalar || GlobalVariable.scalarSlots().containsValue(runtimeScalar) @@ -244,15 +231,14 @@ private static RuntimeScalar bless(RuntimeScalar runtimeScalar, RuntimeScalar cl && scalarReferent.referencedByScalarReference) { scalarReferent.localBindingExists = true; } - referent.refCount = existingScalarOwner ? 2 : 1; if (existingScalarOwner) { - referent.recordOwner(runtimeScalar, "first bless of existing scalar ref"); - runtimeScalar.refCountOwned = true; + RuntimeScalar.acquireCountedOwnerForCurrentValue( + runtimeScalar, referent, runtimeScalar.countedOwnerKind(), + "ReferenceOperators.bless first bless of existing scalar ref"); } - referent.acquireTransientTraceOwner("bless mortal temporary", - "ReferenceOperators.first bless"); - MortalList.deferDecrement(referent, "bless mortal temporary"); } + MortalList.deferBlessTemporary(referent, + !WeakRefRegistry.isweak(runtimeScalar)); // Activate the mortal mechanism MortalList.setActive(true); } diff --git a/src/main/java/org/perlonjava/runtime/operators/Stat.java b/src/main/java/org/perlonjava/runtime/operators/Stat.java index 89be6c5290..102269affe 100644 --- a/src/main/java/org/perlonjava/runtime/operators/Stat.java +++ b/src/main/java/org/perlonjava/runtime/operators/Stat.java @@ -199,7 +199,7 @@ public static RuntimeBase lstat(RuntimeScalar arg, int ctx) { public static RuntimeList stat(RuntimeScalar arg) { arg = dereferenceAndFetch(arg); - state().lastFileHandle.set(arg); + state().lastFileHandle.set(snapshotStatArgument(arg)); RuntimeList res = new RuntimeList(); if (arg.type == RuntimeScalarType.GLOB || arg.type == RuntimeScalarType.GLOBREFERENCE) { @@ -353,7 +353,7 @@ public static RuntimeList stat(RuntimeScalar arg) { public static RuntimeList lstat(RuntimeScalar arg) { arg = dereferenceAndFetch(arg); - state().lastFileHandle.set(arg); + state().lastFileHandle.set(snapshotStatArgument(arg)); RuntimeList res = new RuntimeList(); if (arg.type == RuntimeScalarType.GLOB || arg.type == RuntimeScalarType.GLOBREFERENCE) { diff --git a/src/main/java/org/perlonjava/runtime/operators/SystemOperator.java b/src/main/java/org/perlonjava/runtime/operators/SystemOperator.java index 0da028d38c..73de78e6b7 100644 --- a/src/main/java/org/perlonjava/runtime/operators/SystemOperator.java +++ b/src/main/java/org/perlonjava/runtime/operators/SystemOperator.java @@ -1510,6 +1510,7 @@ private static RuntimeScalar completeForkOpen(List flattenedArgs, boolea existing.replaceStateFrom(input); } else if (pending.fileHandle.value instanceof RuntimeGlob glob) { glob.setIO(input); + MyVarCleanupStack.retainLiveIoGlobOwners(glob, pending.fileHandle); } else { pending.fileHandle.set(input); } diff --git a/src/main/java/org/perlonjava/runtime/operators/TieOperators.java b/src/main/java/org/perlonjava/runtime/operators/TieOperators.java index 9f65ac6b92..b288997b17 100644 --- a/src/main/java/org/perlonjava/runtime/operators/TieOperators.java +++ b/src/main/java/org/perlonjava/runtime/operators/TieOperators.java @@ -163,7 +163,6 @@ public static RuntimeScalar tie(int ctx, RuntimeBase... scalars) { RuntimeScalar directPvioWrapper = directPvioWrapper(variable); RuntimeGlob glob = variable.globDeref(); RuntimeIO previousValue = (RuntimeIO) glob.IO.value; - glob.IO.type = TIED_SCALAR; boolean selfIsTiedGlob = self != null && (self.value == glob || isSameHandle(self, previousValue)); TieHandle tieHandle = new TieHandle(className, previousValue, self, !selfIsTiedGlob); @@ -172,13 +171,12 @@ public static RuntimeScalar tie(int ctx, RuntimeBase... scalars) { if (previousValue != null) { tieHandle.globName = previousValue.globName; } - glob.IO.value = tieHandle; + glob.setTiedIOHandle(tieHandle); if (selfIsTiedGlob) { RuntimeIO.registerTiedAlias(previousValue, tieHandle); } - if (directPvioWrapper != null) { - directPvioWrapper.type = TIED_SCALAR; - directPvioWrapper.value = tieHandle; + if (directPvioWrapper != null && directPvioWrapper != glob.IO) { + RuntimeGlob.installTiedIOHandle(directPvioWrapper, tieHandle); } // Update selectedHandle so that `print` without explicit filehandle // goes through the tied handle (e.g., Test2::Plugin::IOEvents) @@ -362,7 +360,10 @@ private static void warnUntieReferences(RuntimeScalar self) { if (self == null || !(self.value instanceof RuntimeBase base)) { return; } - int externalReferences = Math.max(0, base.refCount - 1); + int argumentAliasReferences = base.ownerSlotCount( + PerlOwnerSlot.Kind.ARGUMENT_TIE_HANDLER); + int externalReferences = Math.max(0, + base.refCount - 1 - argumentAliasReferences); if (externalReferences != 0) { WarnDie.warnWithCategory(new RuntimeScalar("untie attempted while " + externalReferences + " inner references still exist"), RuntimeScalarCache.scalarEmptyString, "untie"); diff --git a/src/main/java/org/perlonjava/runtime/operators/WarnDie.java b/src/main/java/org/perlonjava/runtime/operators/WarnDie.java index 5afa6bd2bb..df4955a14c 100644 --- a/src/main/java/org/perlonjava/runtime/operators/WarnDie.java +++ b/src/main/java/org/perlonjava/runtime/operators/WarnDie.java @@ -1036,6 +1036,10 @@ public static RuntimeScalar exit(RuntimeScalar runtimeScalar) { if ("START".equals(phase) || "CHECK".equals(phase)) { throw new PerlExitException(exitCode); } + // exit() bypasses the normal return epilogues of active Perl frames. + // Retire those lexical owners before END blocks, as ordinary frame + // unwinding does for other exceptional exits. + MyVarCleanupStack.unwindTo(0); // Flush file-scoped lexical cleanup before END blocks MortalList.flush(); // Match normal shutdown: destroy captures unrelated to END now, while diff --git a/src/main/java/org/perlonjava/runtime/perlmodule/Attributes.java b/src/main/java/org/perlonjava/runtime/perlmodule/Attributes.java index e4582bf5a6..3e1bd32d90 100644 --- a/src/main/java/org/perlonjava/runtime/perlmodule/Attributes.java +++ b/src/main/java/org/perlonjava/runtime/perlmodule/Attributes.java @@ -423,8 +423,12 @@ public static void runtimeDispatchModifyCodeAttributes(String packageName, Runti RuntimeCode clone = originalCode.cloneForClosure(); clone.__SUB__ = new RuntimeScalar(clone); originalCode.isClosurePrototype = true; - codeRef.type = CODE; - codeRef.value = clone; + RuntimeScalar replacement = new RuntimeScalar(clone); + replacement.globalCodeRefFqn = codeRef.globalCodeRefFqn; + // A codeRef can already own the prototype through a scalar + // cell or a CODE slot. Move that edge to the callable clone + // through the normal retain-before-release transition. + codeRef.set(replacement); } } else { // No MODIFY_CODE_ATTRIBUTES handler — all non-builtin attrs are invalid diff --git a/src/main/java/org/perlonjava/runtime/perlmodule/CryptOpenSSLRSA.java b/src/main/java/org/perlonjava/runtime/perlmodule/CryptOpenSSLRSA.java index cbc7178c65..5e6ae1deeb 100644 --- a/src/main/java/org/perlonjava/runtime/perlmodule/CryptOpenSSLRSA.java +++ b/src/main/java/org/perlonjava/runtime/perlmodule/CryptOpenSSLRSA.java @@ -48,7 +48,7 @@ public class CryptOpenSSLRSA extends PerlModuleBase { private static final String CLASS_NAME = "Crypt::OpenSSL::RSA"; private static final String STATE_KEY = "_rsa_state"; - private static final int MIN_RSA_KEY_BITS = 1024; + private static final int MIN_RSA_KEY_BITS = 2048; private static final int MAX_RSA_KEY_BITS = 8192; // Register Bouncy Castle as a JCE provider once, so that signature @@ -209,11 +209,8 @@ public static RuntimeList generate_key(RuntimeArray args, int ctx) { // would require RSAKeyGenParameterSpec with a BigInteger — not worth // the dependency on args.get(2) being a valid public exponent for OAuth. // NIST SP 800-131A Rev. 2 requires RSA moduli of at least 2048 - // bits for signature generation. Keep the upstream API's explicit - // 1024-bit request as a legacy compatibility exception; it is not - // suitable for generating keys for new security-sensitive uses. + // bits for signature generation. // The 8192-bit cap bounds provider work for caller-controlled sizes. - // codeql[java/insufficient-key-size] kpg.initialize(bits); KeyPair kp = kpg.generateKeyPair(); @@ -231,7 +228,7 @@ public static RuntimeList generate_key(RuntimeArray args, int ctx) { private static int validateRsaKeySize(RuntimeScalar requestedBits) { String message = "RSA key size must be an integer from " + MIN_RSA_KEY_BITS + " through " + MAX_RSA_KEY_BITS + " bits, in multiples of 8" - + " (1024-bit generation is retained for legacy compatibility)"; + + " (RSA keys below 2048 bits are not supported)"; try { BigInteger bitCount; int type = RuntimeScalarType.effectiveType(requestedBits); diff --git a/src/main/java/org/perlonjava/runtime/perlmodule/CryptX.java b/src/main/java/org/perlonjava/runtime/perlmodule/CryptX.java index 9cca846f2d..11cd18ebcc 100644 --- a/src/main/java/org/perlonjava/runtime/perlmodule/CryptX.java +++ b/src/main/java/org/perlonjava/runtime/perlmodule/CryptX.java @@ -4,8 +4,12 @@ import org.perlonjava.frontend.parser.StringParser; import org.perlonjava.runtime.runtimetypes.*; +import javax.crypto.AEADBadTagException; +import javax.crypto.Cipher; import javax.crypto.Mac; import javax.crypto.SecretKey; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -62,6 +66,8 @@ public static void initialize() { CryptX misc = new CryptX("Crypt::Misc"); CryptX digest = new CryptX("Crypt::Digest"); CryptX hmac = new CryptX("Crypt::Mac::HMAC"); + CryptX keyDerivation = new CryptX("Crypt::KeyDerivation"); + CryptX chacha20Poly1305 = new CryptX("Crypt::AuthEnc::ChaCha20Poly1305"); try { core.registerMethod("_ltc_build_settings", "buildSettings", null); core.registerMethod("_ltc_mp_name", "mpName", null); @@ -87,6 +93,13 @@ public static void initialize() { hmac.registerMethod("hmac_b64", "hmacBase64", null); hmac.registerMethod("hmac_b64u", "hmacBase64Url", null); + keyDerivation.registerMethod("pbkdf2", "pbkdf2", null); + + chacha20Poly1305.registerMethod("chacha20poly1305_encrypt_authenticate", + "chacha20poly1305EncryptAuthenticate", null); + chacha20Poly1305.registerMethod("chacha20poly1305_decrypt_verify", + "chacha20poly1305DecryptVerify", null); + } catch (NoSuchMethodException e) { throw new IllegalStateException("Unable to initialize " + MODULE, e); } @@ -271,6 +284,102 @@ private static RuntimeList calculateHmac(RuntimeArray args, int output) { } } + public static RuntimeList pbkdf2(RuntimeArray args, int ctx) { + byte[] password = bytes(arg(args, 0), "Crypt::KeyDerivation::pbkdf2 password"); + byte[] salt = bytes(arg(args, 1), "Crypt::KeyDerivation::pbkdf2 salt"); + int iterations = args.size() > 2 ? args.get(2).getInt() : 5000; + String algorithm = args.size() > 3 ? args.get(3).toString() : "SHA256"; + int outputLength = args.size() > 4 ? args.get(4).getInt() : 32; + if (iterations < 1) { + throw new PerlCompilerException( + "FATAL: Crypt::KeyDerivation::pbkdf2 iterations must be positive"); + } + if (outputLength < 0) { + throw new PerlCompilerException( + "FATAL: Crypt::KeyDerivation::pbkdf2 length must be nonnegative"); + } + + try { + Mac mac = mac(algorithm); + mac.init(new RawKey(password, mac.getAlgorithm())); + int digestLength = mac.getMacLength(); + byte[] result = new byte[outputLength]; + int resultOffset = 0; + for (int block = 1; resultOffset < outputLength; block++) { + byte[] firstInput = java.util.Arrays.copyOf(salt, salt.length + 4); + firstInput[salt.length] = (byte) (block >>> 24); + firstInput[salt.length + 1] = (byte) (block >>> 16); + firstInput[salt.length + 2] = (byte) (block >>> 8); + firstInput[salt.length + 3] = (byte) block; + + byte[] u = mac.doFinal(firstInput); + byte[] derived = u.clone(); + for (int iteration = 1; iteration < iterations; iteration++) { + u = mac.doFinal(u); + for (int i = 0; i < digestLength; i++) derived[i] ^= u[i]; + } + + int copyLength = Math.min(digestLength, outputLength - resultOffset); + System.arraycopy(derived, 0, result, resultOffset, copyLength); + resultOffset += copyLength; + } + return new RuntimeScalar(result).getList(); + } catch (PerlCompilerException e) { + throw e; + } catch (Exception e) { + throw cryptoError("Crypt::KeyDerivation", algorithm, e); + } + } + + public static RuntimeList chacha20poly1305EncryptAuthenticate(RuntimeArray args, int ctx) { + byte[] key = bytes(arg(args, 0), "ChaCha20-Poly1305 key"); + byte[] nonce = bytes(arg(args, 1), "ChaCha20-Poly1305 nonce"); + byte[] aad = bytes(arg(args, 2), "ChaCha20-Poly1305 additional data"); + byte[] plaintext = bytes(arg(args, 3), "ChaCha20-Poly1305 plaintext"); + try { + Cipher cipher = chacha20Poly1305(Cipher.ENCRYPT_MODE, key, nonce, aad); + byte[] encrypted = cipher.doFinal(plaintext); + int tagOffset = encrypted.length - 16; + RuntimeList result = new RuntimeList(); + result.elements.add(new RuntimeScalar(java.util.Arrays.copyOf(encrypted, tagOffset))); + result.elements.add(new RuntimeScalar( + java.util.Arrays.copyOfRange(encrypted, tagOffset, encrypted.length))); + return result; + } catch (Exception e) { + throw cryptoError("Crypt::AuthEnc::ChaCha20Poly1305", "ChaCha20-Poly1305", e); + } + } + + public static RuntimeList chacha20poly1305DecryptVerify(RuntimeArray args, int ctx) { + byte[] key = bytes(arg(args, 0), "ChaCha20-Poly1305 key"); + byte[] nonce = bytes(arg(args, 1), "ChaCha20-Poly1305 nonce"); + byte[] aad = bytes(arg(args, 2), "ChaCha20-Poly1305 additional data"); + byte[] ciphertext = bytes(arg(args, 3), "ChaCha20-Poly1305 ciphertext"); + byte[] tag = bytes(arg(args, 4), "ChaCha20-Poly1305 tag"); + try { + byte[] input = java.util.Arrays.copyOf(ciphertext, ciphertext.length + tag.length); + System.arraycopy(tag, 0, input, ciphertext.length, tag.length); + Cipher cipher = chacha20Poly1305(Cipher.DECRYPT_MODE, key, nonce, aad); + return new RuntimeScalar(cipher.doFinal(input)).getList(); + } catch (AEADBadTagException e) { + return new RuntimeScalar().getList(); + } catch (Exception e) { + throw cryptoError("Crypt::AuthEnc::ChaCha20Poly1305", "ChaCha20-Poly1305", e); + } + } + + private static Cipher chacha20Poly1305(int mode, byte[] key, byte[] nonce, byte[] aad) throws Exception { + Cipher cipher; + try { + cipher = Cipher.getInstance("ChaCha20-Poly1305"); + } catch (Exception first) { + cipher = Cipher.getInstance("ChaCha20-Poly1305", "BC"); + } + cipher.init(mode, new SecretKeySpec(key, "ChaCha20"), new IvParameterSpec(nonce)); + cipher.updateAAD(aad); + return cipher; + } + private static MessageDigest messageDigest(String algorithm) throws Exception { String name = digestName(algorithm); try { diff --git a/src/main/java/org/perlonjava/runtime/perlmodule/DBI.java b/src/main/java/org/perlonjava/runtime/perlmodule/DBI.java index 86d29576d3..fd2315808c 100644 --- a/src/main/java/org/perlonjava/runtime/perlmodule/DBI.java +++ b/src/main/java/org/perlonjava/runtime/perlmodule/DBI.java @@ -222,7 +222,6 @@ public static RuntimeList connect(RuntimeArray args, int ctx) { public static RuntimeList prepare(RuntimeArray args, int ctx) { RuntimeHash dbh = args.get(0).hashDeref(); RuntimeHash sth = new RuntimeHash(); - sth.put("Database", dbh.createReference()); return executeWithErrorHandling(() -> { if (args.size() < 2) { @@ -306,6 +305,14 @@ public static RuntimeList prepare(RuntimeArray args, int ctx) { } sth.put("NUM_OF_PARAMS", new RuntimeScalar(numParams)); + // Do not give a not-yet-returned statement handle a strong edge + // back to its database handle. Preparing can throw (for example, + // on invalid SQL); an unreachable partial sth has no Perl owner + // whose release could retire this edge when graph sweeps are off. + // The Perl DBI wrapper installs its weak Database back-reference + // after this method returns. + sth.put("Database", dbh.createReference()); + // Create blessed reference for statement handle RuntimeScalar sthRef = ReferenceOperators.bless( sth.createReferenceWithTrackedElements(), new RuntimeScalar("DBI::st")); diff --git a/src/main/java/org/perlonjava/runtime/perlmodule/HTMLParser.java b/src/main/java/org/perlonjava/runtime/perlmodule/HTMLParser.java index a3c366e79c..ff85335799 100644 --- a/src/main/java/org/perlonjava/runtime/perlmodule/HTMLParser.java +++ b/src/main/java/org/perlonjava/runtime/perlmodule/HTMLParser.java @@ -133,7 +133,7 @@ public static RuntimeList _alloc_pstate(RuntimeArray args, int ctx) { handlers.put(event + "_cb", scalarUndef); handlers.put(event + "_argspec", scalarUndef); } - pstate.put("_handlers", handlers.createReference()); + pstate.put("_handlers", handlers.createAnonymousReference()); // State tracking pstate.put("_parsing", scalarFalse); @@ -147,7 +147,7 @@ public static RuntimeList _alloc_pstate(RuntimeArray args, int ctx) { pstate.put("_input_is_byte_string", scalarFalse); pstate.put("_literal_mode", new RuntimeScalar("")); pstate.put("_ignore_current_element", scalarFalse); - pstate.put("_ignore_elements", new RuntimeArray().createReference()); + pstate.put("_ignore_elements", new RuntimeArray().createAnonymousReference()); pstate.put("_pending_end_tag", new RuntimeScalar("")); pstate.put("_bool_attr_val", scalarUndef); pstate.put("_in_cdata", scalarFalse); @@ -162,7 +162,7 @@ public static RuntimeList _alloc_pstate(RuntimeArray args, int ctx) { pstate.put("_event_column", new RuntimeScalar(1)); // Store in self - selfHash.put("_hparser_xs_state", pstate.createReference()); + selfHash.put("_hparser_xs_state", pstate.createAnonymousReference()); return new RuntimeList(); } @@ -369,7 +369,7 @@ public static RuntimeList tagListAccessor(RuntimeArray args, int ctx) { RuntimeArray.push(replacement, arg); } } - pstate.put("_ignore_elements", replacement.createReference()); + pstate.put("_ignore_elements", replacement.createAnonymousReference()); } RuntimeList result = new RuntimeList(); for (int i = 0; i < previous.size(); i++) result.add(previous.get(i)); @@ -558,48 +558,44 @@ private static void fireEvent(RuntimeScalar self, RuntimeHash selfHash, RuntimeH // Build event data per argspec and push as array ref onto accumulator RuntimeArray accum = (RuntimeArray) cb.value; RuntimeArray eventData = buildEventDataFromArgspec(argspec, eventName, eventArgs, self, false, pstate); - RuntimeArray.push(accum, eventData.createReference()); - } else if (cb.type == RuntimeScalarType.STRING || cb.type == RuntimeScalarType.BYTE_STRING) { - // Method name - call as $self->method(...) - String methodName = cb.toString(); + RuntimeArray.push(accum, eventData.createAnonymousReference()); + } else if (cb.type == RuntimeScalarType.STRING || cb.type == RuntimeScalarType.BYTE_STRING + || cb.type == RuntimeScalarType.REFERENCE || cb.type == RuntimeScalarType.CODE) { + boolean methodCallback = cb.type == RuntimeScalarType.STRING + || cb.type == RuntimeScalarType.BYTE_STRING; RuntimeArray callArgs = new RuntimeArray(); - RuntimeArray.push(callArgs, self); - // Build args from argspec if available, otherwise pass raw eventArgs - // skipSelf=true: "self" in argspec specifies the invocant for method dispatch - // but should NOT be duplicated in the method arguments - if (!argspec.isEmpty()) { - RuntimeArray eventData = buildEventDataFromArgspec(argspec, eventName, eventArgs, self, true, pstate); - for (int idx = 0; idx < eventData.size(); idx++) { - RuntimeArray.push(callArgs, eventData.get(idx)); - } - } else { - for (RuntimeScalar arg : eventArgs) { - RuntimeArray.push(callArgs, arg); - } - } - // Look up method in the object's class hierarchy using the blessed class - int blessId = RuntimeScalarType.blessedId(self); - String className = (blessId != 0) ? - NameNormalizer.getBlessStr(blessId) : "HTML::Parser"; - RuntimeScalar method = InheritanceResolver.findMethodInHierarchy( - methodName, className, null, 0); - if (method != null) { - RuntimeCode.apply(method, callArgs, RuntimeContextType.VOID); - } - } else if (cb.type == RuntimeScalarType.REFERENCE || cb.type == RuntimeScalarType.CODE) { - // Code reference - call directly - RuntimeArray callArgs = new RuntimeArray(); - if (!argspec.isEmpty()) { - RuntimeArray eventData = buildEventDataFromArgspec(argspec, eventName, eventArgs, self, false, pstate); - for (int idx = 0; idx < eventData.size(); idx++) { - RuntimeArray.push(callArgs, eventData.get(idx)); + RuntimeArray eventData = null; + try { + if (methodCallback) RuntimeArray.push(callArgs, self); + if (!argspec.isEmpty()) { + // A method's invocant is already in callArgs. CODE callbacks + // receive self only when their argspec explicitly requests it. + eventData = buildEventDataFromArgspec( + argspec, eventName, eventArgs, self, methodCallback, pstate); + for (int idx = 0; idx < eventData.size(); idx++) { + RuntimeArray.push(callArgs, eventData.get(idx)); + } + } else { + for (RuntimeScalar arg : eventArgs) RuntimeArray.push(callArgs, arg); } - } else { - for (RuntimeScalar arg : eventArgs) { - RuntimeArray.push(callArgs, arg); + if (methodCallback) { + int blessId = RuntimeScalarType.blessedId(self); + String className = blessId != 0 + ? NameNormalizer.getBlessStr(blessId) : "HTML::Parser"; + RuntimeScalar method = InheritanceResolver.findMethodInHierarchy( + cb.toString(), className, null, 0); + if (method != null) RuntimeCode.apply(method, callArgs, RuntimeContextType.VOID); + } else { + RuntimeCode.apply(cb, callArgs, RuntimeContextType.VOID); } + } finally { + // These are owned native call buffers, including when callback + // dispatch fails or a method is absent. Escaped @_ references + // keep their own aggregate owner and remain usable. + MortalList.scopeExitCleanupArray(callArgs); + MortalList.scopeExitCleanupArray(eventData); + MortalList.flushAboveMark(); } - RuntimeCode.apply(cb, callArgs, RuntimeContextType.VOID); } } @@ -679,7 +675,7 @@ private static RuntimeArray buildEventDataFromArgspec(String argspec, String eve RuntimeArray.push(result, eventArgs[1]); } else { // Return empty hash ref for non-start events - RuntimeArray.push(result, new RuntimeHash().createReference()); + RuntimeArray.push(result, new RuntimeHash().createAnonymousReference()); } break; @@ -688,7 +684,7 @@ private static RuntimeArray buildEventDataFromArgspec(String argspec, String eve if ("start".equals(eventName) && eventArgs.length > 2) { RuntimeArray.push(result, eventArgs[2]); } else { - RuntimeArray.push(result, new RuntimeArray().createReference()); + RuntimeArray.push(result, new RuntimeArray().createAnonymousReference()); } break; @@ -834,7 +830,7 @@ private static RuntimeArray buildEventDataFromArgspec(String argspec, String eve // declaration => [declaration_body] // process => [pi_body] RuntimeArray.push(result, - buildTokensArray(eventName, eventArgs).createReference()); + buildTokensArray(eventName, eventArgs).createAnonymousReference()); break; case "tokenpos": @@ -852,9 +848,9 @@ private static RuntimeArray buildEventDataFromArgspec(String argspec, String eve RuntimeArray pair = new RuntimeArray(); RuntimeArray.push(pair, new RuntimeScalar(0)); RuntimeArray.push(pair, new RuntimeScalar(0)); - RuntimeArray.push(pos, pair.createReference()); + RuntimeArray.push(pos, pair.createAnonymousReference()); } - RuntimeArray.push(result, pos.createReference()); + RuntimeArray.push(result, pos.createAnonymousReference()); } break; @@ -1311,8 +1307,8 @@ private static void parseHtml(RuntimeScalar self, RuntimeHash selfHash, RuntimeH if (!ignoreElement) { fireEvent(self, selfHash, pstate, "start", new RuntimeScalar(tagName), - attrs.createReference(), - attrSeq.createReference(), + attrs.createAnonymousReference(), + attrSeq.createAnonymousReference(), new RuntimeScalar(origText)); } diff --git a/src/main/java/org/perlonjava/runtime/perlmodule/IPCOpen3.java b/src/main/java/org/perlonjava/runtime/perlmodule/IPCOpen3.java index b3515dce70..bdffbdd90e 100644 --- a/src/main/java/org/perlonjava/runtime/perlmodule/IPCOpen3.java +++ b/src/main/java/org/perlonjava/runtime/perlmodule/IPCOpen3.java @@ -654,7 +654,7 @@ public static RuntimeList _open2(RuntimeArray args, int ctx) { */ private static void setupWriteHandle(RuntimeScalar handleRef, OutputStream out) { RuntimeIO io = new RuntimeIO(); - io.ioHandle = new ProcessOutputHandle(out); + io.replaceIOHandle(new ProcessOutputHandle(out)); // Dereference to get the inner value RuntimeScalar inner; @@ -667,7 +667,9 @@ private static void setupWriteHandle(RuntimeScalar handleRef, OutputStream out) // If the inner value is already a GLOBREFERENCE (e.g., \*FOO typeglob), // set the IO slot on the existing glob so the bareword handle works if (inner.type == RuntimeScalarType.GLOBREFERENCE && inner.value instanceof RuntimeGlob) { - ((RuntimeGlob) inner.value).setIO(io); + RuntimeGlob glob = (RuntimeGlob) inner.value; + glob.setIO(io); + MyVarCleanupStack.retainLiveIoGlobOwners(glob, inner); } else { // Create a new GLOB reference for the handle RuntimeGlob glob = new RuntimeGlob(null); @@ -687,7 +689,7 @@ private static void setupWriteHandle(RuntimeScalar handleRef, OutputStream out) */ private static void setupReadHandle(RuntimeScalar handleRef, InputStream in, Process process) { RuntimeIO io = new RuntimeIO(); - io.ioHandle = new ProcessInputHandle(in, process); + io.replaceIOHandle(new ProcessInputHandle(in, process)); // Dereference to get the inner value RuntimeScalar inner; @@ -700,7 +702,9 @@ private static void setupReadHandle(RuntimeScalar handleRef, InputStream in, Pro // If the inner value is already a GLOBREFERENCE (e.g., \*FOO typeglob), // set the IO slot on the existing glob so the bareword handle works if (inner.type == RuntimeScalarType.GLOBREFERENCE && inner.value instanceof RuntimeGlob) { - ((RuntimeGlob) inner.value).setIO(io); + RuntimeGlob glob = (RuntimeGlob) inner.value; + glob.setIO(io); + MyVarCleanupStack.retainLiveIoGlobOwners(glob, inner); } else { // Create a new GLOB reference for the handle RuntimeGlob glob = new RuntimeGlob(null); diff --git a/src/main/java/org/perlonjava/runtime/perlmodule/Internals.java b/src/main/java/org/perlonjava/runtime/perlmodule/Internals.java index 29464bc28a..77fa50d614 100644 --- a/src/main/java/org/perlonjava/runtime/perlmodule/Internals.java +++ b/src/main/java/org/perlonjava/runtime/perlmodule/Internals.java @@ -36,26 +36,13 @@ public static void initialize() { // allowed-but-absent keys separately, so there are no physical // placeholder entries to remove. internals.registerMethod("hv_clear_placeholders", "hvClearPlaceholders", "\\%"); - // Phase 0 diagnostic: expose PerlOnJava-internal refcount state - // (refCount, flags, tracking mode) for differential testing - // against native Perl. See dev/design/refcount_alignment_plan.md. + // Ownership diagnostics expose runtime refcount state and owner + // slots for focused differential tests against system Perl. internals.registerMethod("jperl_refstate", "jperl_refstate", "$"); internals.registerMethod("jperl_refstate_str", "jperl_refstate_str", "$"); internals.registerMethod("jperl_owner_trace", "jperlOwnerTrace", "$"); internals.registerMethod("jperl_reference_by_address", "jperlReferenceByAddress", "$"); - // Phase 4 (refcount_alignment_plan.md): On-demand reachability - // sweep. Walks Perl-visible roots (globals, stashes, rescued - // objects) and clears weak refs for unreachable objects. Returns - // the number of weak refs cleared. - internals.registerMethod("jperl_gc", "jperl_gc", ""); - internals.registerMethod("jperl_gc_quiet", "jperl_gc_quiet", ""); - internals.registerMethod("jperl_sweep_destroyables_no_jvm_gc", "jperl_sweep_destroyables_no_jvm_gc", ""); internals.registerMethod("jperl_freetmps", "jperl_freetmps", ""); - // Phase 4 diagnostic: trace a reachable path from any Perl root - // to the given referent. Returns the first-found path string or - // undef if unreachable. Used to debug why an object that should - // be GC'd remains reachable from the walker's point of view. - internals.registerMethod("jperl_trace_to", "jperl_trace_to", "$"); internals.registerMethod("initialize_state_variable", "initializeStateVariable", "$$"); internals.registerMethod("initialize_state_array", "initializeStateArray", "$$"); internals.registerMethod("initialize_state_hash", "initializeStateHash", "$$"); @@ -80,6 +67,7 @@ public static void initialize() { internals.registerMethod("jperl_mark_pseudo_constant", "jperlMarkPseudoConstant", "$$"); internals.registerMethod("jperl_end_av_ref", "jperlEndAvRef", ""); internals.registerMethod("jperl_b_object_2svref", "jperlBObject2svref", "$"); + internals.registerMethod("jperl_b_object_store_reference", "jperlBObjectStoreReference", "$$"); internals.registerMethod("jperl_b_scalar_flags", "jperlBScalarFlags", "$"); internals.registerMethod("jperl_set_closed_over", "jperlSetClosedOver", null); internals.registerMethod("jperl_closed_over", "jperlClosedOver", null); @@ -100,6 +88,17 @@ public static RuntimeList jperlEndAvRef(RuntimeArray args, int ctx) { return SpecialBlock.getEndBlocks().createReference().getList(); } + /** Store a B wrapper's raw referent view without adding a Perl owner. */ + public static RuntimeList jperlBObjectStoreReference(RuntimeArray args, int ctx) { + if (args.size() != 2 || !(args.get(0).value instanceof RuntimeHash wrapper) + || !(args.get(1).value instanceof RuntimeBase)) { + throw new IllegalArgumentException( + "Usage: Internals::jperl_b_object_store_reference(B_OBJECT, REFERENT)"); + } + wrapper.putBObjectReference("ref", args.get(1)); + return new RuntimeList(); + } + /** Resolve a reference pseudo-address previously exposed by stringification. */ public static RuntimeList jperlBObject2svref(RuntimeArray args, int ctx) { if (args.size() != 1) { @@ -399,9 +398,18 @@ private static void replaceCaptureTracking( && code.capturedScalars != null) { for (int i = 0; i < code.capturedScalars.length; i++) { if (code.capturedScalars[i] == previous) { - scalar.retainClosureCapture(); - previous.releaseClosureCapture(); + PerlOwnerSlot replacementOwner = scalar.retainClosureCaptureSlot(code); + PerlOwnerSlot[] ownerSlots = code.capturedScalarOwnerSlots; + PerlOwnerSlot previousOwner = ownerSlots != null + && i < ownerSlots.length + ? ownerSlots[i] : null; + ((RuntimeScalar) previous).releaseClosureCaptureSlot(previousOwner); code.capturedScalars[i] = scalar; + if (ownerSlots == null || ownerSlots.length != code.capturedScalars.length) { + ownerSlots = new PerlOwnerSlot[code.capturedScalars.length]; + code.capturedScalarOwnerSlots = ownerSlots; + } + ownerSlots[i] = replacementOwner; return; } } @@ -412,7 +420,7 @@ private static void replaceCaptureTracking( for (int i = 0; i < code.capturedAggregates.length; i++) { if (code.capturedAggregates[i] == previous) { PerlOwnerSlot replacementOwner = - replacement.retainClosureCaptureOwner(); + replacement.retainClosureCaptureOwner(code); PerlOwnerSlot[] ownerSlots = code.capturedAggregateOwnerSlots; PerlOwnerSlot previousOwner = ownerSlots != null && i < ownerSlots.length @@ -429,8 +437,70 @@ private static void replaceCaptureTracking( } } - if (previous != null) previous.releaseClosureCapture(); - replacement.retainClosureCapture(); + if (previous instanceof RuntimeScalar previousScalar + && replacement instanceof RuntimeScalar replacementScalar) { + previousScalar.releaseClosureCapture(); + appendScalarCapture(code, replacementScalar); + return; + } + if (previous != null && replacement != null) { + previous.releaseClosureCapture(); + appendAggregateCapture(code, replacement); + } + } + + private static void appendScalarCapture(RuntimeCode code, RuntimeScalar replacement) { + RuntimeScalar[] existing = code.capturedScalars == null + ? new RuntimeScalar[0] : code.capturedScalars; + PerlOwnerSlot[] existingSlots = code.capturedScalarOwnerSlots; + java.util.ArrayList captures = new java.util.ArrayList<>( + java.util.Arrays.asList(existing)); + java.util.ArrayList slots = new java.util.ArrayList<>(existing.length); + for (int i = 0; i < existing.length; i++) { + PerlOwnerSlot slot = existingSlots != null && i < existingSlots.length + ? existingSlots[i] : null; + if (slot == null || !slot.isActive()) { + RuntimeScalar captured = existing[i]; + if (captured.legacyCaptureOwnerCount() > 0) { + captured.releaseClosureCapture(); + } + slot = captured.retainClosureCaptureSlot(code); + } + slots.add(slot); + } + if (!captures.contains(replacement)) { + captures.add(replacement); + slots.add(replacement.retainClosureCaptureSlot(code)); + } + code.capturedScalars = captures.toArray(new RuntimeScalar[0]); + code.capturedScalarOwnerSlots = slots.toArray(new PerlOwnerSlot[0]); + } + + private static void appendAggregateCapture(RuntimeCode code, RuntimeBase replacement) { + RuntimeBase[] existing = code.capturedAggregates == null + ? new RuntimeBase[0] : code.capturedAggregates; + PerlOwnerSlot[] existingSlots = code.capturedAggregateOwnerSlots; + java.util.ArrayList captures = new java.util.ArrayList<>( + java.util.Arrays.asList(existing)); + java.util.ArrayList slots = new java.util.ArrayList<>(existing.length); + for (int i = 0; i < existing.length; i++) { + PerlOwnerSlot slot = existingSlots != null && i < existingSlots.length + ? existingSlots[i] : null; + if (slot == null || !slot.isActive()) { + RuntimeBase captured = existing[i]; + if (captured.legacyCaptureOwnerCount() > 0) { + captured.releaseClosureCapture(); + } + slot = captured.retainClosureCaptureOwner(code); + } + slots.add(slot); + } + if (!captures.contains(replacement)) { + captures.add(replacement); + slots.add(replacement.retainClosureCaptureOwner(code)); + } + code.capturedAggregates = captures.toArray(new RuntimeBase[0]); + code.capturedAggregateOwnerSlots = slots.toArray(new PerlOwnerSlot[0]); } /** @@ -504,13 +574,34 @@ public static RuntimeList svRefcount(RuntimeArray args, int ctx) { } if (base != null) { int rc = base.refCount; - if (rc == Integer.MIN_VALUE) return new RuntimeScalar(0).getList(); - int nativeCaptureOwners = base.nativeCaptureOwnerCount(); - if (rc < 0) { - if (nativeCaptureOwners == 0) return new RuntimeScalar(1).getList(); // untracked - rc = nativeCaptureOwners; + boolean compileHintsHash = base == GlobalVariable.getGlobalHash( + GlobalContext.encodeSpecialVar("H")); + // Expression leases keep runtime temporaries alive while values + // cross statement and foreach boundaries. They are not Perl SV + // owners, so hide both their native identities and any paired + // selective counts from SvREFCNT. + int expressionOwners = base.ownerSlotCount(PerlOwnerSlot.Kind.EXPRESSION_VALUE); + int countedExpressionOwners = base.countedNativeOwnerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_VALUE); + int nativeOwners = base.nativeOwnerSlotCount() - expressionOwners; + if (base.isRefCountTracked()) rc -= countedExpressionOwners; + if (compileHintsHash) { + // The package-root identity records the strong table edge for + // lifecycle cleanup, but Perl's SvREFCNT helper deliberately + // hides this special global slot from the reported count. + nativeOwners -= base.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT); + } else if (nativeOwners > 0 && base.localBindingExists + && base.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL) > 0) { + // ACTIVE_LEXICAL is the lifecycle identity for a named pad + // edge. The lexical-binding adjustment below already reports + // that same Perl owner, so do not count its identity twice. + nativeOwners--; + } + if (!base.isRefCountTracked()) { + if (nativeOwners == 0) return new RuntimeScalar(1).getList(); // untracked + rc = nativeOwners; } else { - rc += nativeCaptureOwners; + rc += nativeOwners; } // An ampersand-style call may pass a weak qr// scalar directly // (qr-72922's refcount_is helper does this). The call-frame alias @@ -554,26 +645,8 @@ public static RuntimeList svRefcount(RuntimeArray args, int ctx) { // runtime, but Perl's core refcount helper does not expose that // bookkeeping slot as a lexical pad owner. Its helper also // compensates for the ampersand-call argument alias below. - boolean compileHintsHash = base == GlobalVariable.getGlobalHash( - GlobalContext.encodeSpecialVar("H")); int extra = (base.localBindingExists && !compileHintsHash ? 1 : 0) + base.foreachAliasCount; - if (rc == 2 - && args.size() > 1 - && args.get(1).getBoolean() - && DestroyDispatch.isInsideDestroy() - && !ReachabilityWalker.hasLiveStrongScalarReferentOtherThan(base, arg)) { - // B::SV's private hash slot is one of the two selective - // owners. Ordinarily it is the temporary owner discounted - // below (a single live lexical therefore reports one). If - // there is no independently live scalar pad, the other owner - // is a real aggregate slot, as in DBIx::Class Schema's source - // registry during DESTROY, and must remain visible to B. This - // distinction is only meaningful while DESTROY is active: - // outside it, an unregistered lexical can look identical and - // must still report its single owner. - extra++; - } // Legacy fudge: anonymous tracked container with no counted // owners -- still report 1 to indicate "live SV". Used by // Sub::Quote / Moo introspection paths that probe for liveness. @@ -589,20 +662,39 @@ public static RuntimeList svRefcount(RuntimeArray args, int ctx) { boolean fieldOwnedMethodResult = rc == 1 && !base.localBindingExists && base.hashSlotOwnerCount > 0 - && !ReachabilityWalker.hasLiveStrongScalarReferentOtherThan(base, arg); + && !base.hasLiveStrongScalarOwnerSlotOtherThan(arg); boolean bObjectProbe = args.size() > 1 && args.get(1).getBoolean(); int adjust = compileHintsHash ? -1 : base.localBindingExists || fieldOwnedMethodResult ? 0 : -1; - // B::SV keeps its referent in a PerlOnJava hash slot, unlike the - // native B object which stores an SV pointer without owning the - // referent. For named aggregates, the local-binding adjustment - // already accounts for the pad, so discount this extra wrapper - // slot instead of counting both as Perl owners. - if (bObjectProbe && base.localBindingExists && !compileHintsHash) { - adjust = -1; + if (bObjectProbe) { + // B's raw pointer view is not a Perl owner, so the query itself + // contributes no argument reference to discount. Keep the + // ordinary anonymous-value adjustment only for ordinary probes; + // any actual active argument-frame owners are discounted exactly. + if (!compileHintsHash && !base.localBindingExists && !fieldOwnedMethodResult) { + adjust++; + } + int argumentFrameOwners = base.currentArgumentFrameReferentOwnerCount(); + adjust -= argumentFrameOwners; + boolean pendingBlessTemporary = fieldOwnedMethodResult + && argumentFrameOwners == 0 + && MortalList.hasPendingBlessTemporaryFor(base); + boolean activeArgumentOwner = fieldOwnedMethodResult + && argumentFrameOwners == 0 + && RuntimeCode.hasUncountedActiveHashArgumentOwner(base); + if (pendingBlessTemporary) { + // The first bless result remains a mortal Perl owner until + // its deferred temp boundary drains. The hash slot is a + // second owner but is not in the selective refCount bridge. + adjust++; + } + if (activeArgumentOwner) { + adjust++; + } } - return new RuntimeScalar(rc + extra + adjust).getList(); + int reported = rc + extra + adjust; + return new RuntimeScalar(reported).getList(); } return new RuntimeScalar(1).getList(); } @@ -708,31 +800,6 @@ public static RuntimeList jperlOwnerTrace(RuntimeArray args, int ctx) { return new RuntimeScalar("NOT_REF").getList(); } - /** - * Phase 4 (refcount_alignment_plan.md): Run a reachability sweep from - * Perl roots (globals, rescued objects) and clear weak refs for - * unreachable objects. Returns the number of weak refs cleared. This - * is jperl-only; under native Perl it should be treated as a no-op. - */ - public static RuntimeList jperl_gc(RuntimeArray args, int ctx) { - // Two passes: the first pass fires DESTROY on unreachable - // objects, which may break circular refs and make more objects - // unreachable. The second pass catches those cascades. - int cleared = ReachabilityWalker.sweepWeakRefs(); - int secondPass = ReachabilityWalker.sweepWeakRefs(); - return new RuntimeScalar(cleared + secondPass).getList(); - } - - /** - * Quiet statement-boundary sweep. Unlike jperl_gc(), this does not drain - * rescued DBIC-style objects before END-time cleanup. - */ - public static RuntimeList jperl_gc_quiet(RuntimeArray args, int ctx) { - int cleared = ReachabilityWalker.sweepWeakRefs(true); - int secondPass = ReachabilityWalker.sweepWeakRefs(true); - return new RuntimeScalar(cleared + secondPass).getList(); - } - /** * Drain Perl-style mortal temporaries without asking the JVM to run GC. * This mirrors Perl's FREETMPS boundary for refcounted RuntimeBase objects. @@ -742,121 +809,6 @@ public static RuntimeList jperl_freetmps(RuntimeArray args, int ctx) { return new RuntimeScalar(0).getList(); } - /** - * Reconcile destroyable objects that require deterministic DESTROY side - * effects but are not weak-ref referents, without clearing arbitrary weak - * refs and without forcing HotSpot GC. Used by DBI statement polling to - * match Perl's cursor DESTROY/finish timing. - */ - public static RuntimeList jperl_sweep_destroyables_no_jvm_gc(RuntimeArray args, int ctx) { - int destroyed = ReachabilityWalker.sweepDestroyableObjects(false); - if (destroyed > 0) { - destroyed += ReachabilityWalker.sweepDestroyableObjects(false); - } - return new RuntimeScalar(destroyed).getList(); - } - - /** - * Phase 4 diagnostic: find a reachable path from Perl roots to the - * given referent. Returns the path as a string ("$some::global{key}[3]") - * or undef if unreachable. - */ - public static RuntimeList jperl_trace_to(RuntimeArray args, int ctx) { - RuntimeScalar arg = args.get(0); - if (!(arg.value instanceof RuntimeBase base)) { - return new RuntimeScalar().getList(); - } - // Phase I: when JPERL_TRACE_SKIP_LEX=1, omit ScalarRefRegistry seeds - // from path discovery — forces the trace through Perl-semantic - // roots so diagnostics show which global/stash data structure - // keeps the object alive (not just "live-lexical"). - boolean skipLex = System.getenv("JPERL_TRACE_SKIP_LEX") != null; - java.util.List path = ReachabilityWalker.findPathTo(base, skipLex); - if (path == null) return new RuntimeScalar().getList(); - // Also dump all direct lexical-holders for debugging deep leaks - if (System.getenv("JPERL_TRACE_ALL") != null) { - System.err.println("jperl_trace_to target addr=" - + System.identityHashCode(base) - + " class=" + base.getClass().getSimpleName()); - int matchIdx = 0; - int totalLexIdx = 0; - // Collect candidate parent hashes (those with any key pointing at base) - // when no direct holder exists. Useful for traces like - // "{random_results}" where target is reached via - // a parent hash rather than directly held. - java.util.ArrayList parentScalars = new java.util.ArrayList<>(); - for (RuntimeScalar sc : ScalarRefRegistry.snapshot()) { - if (sc == null) continue; - if (sc.captureCount > 0) continue; - if (WeakRefRegistry.isweak(sc)) continue; - if (!RuntimeScalarType.isReference(sc)) continue; - totalLexIdx++; - if (sc.value == base) { - System.err.println(" direct holder #" + (matchIdx++) - + " scId=" + System.identityHashCode(sc) - + " type=" + sc.type - + " rcO=" + sc.refCountOwned - + " captureCount=" + sc.captureCount); - Throwable st = ScalarRefRegistry.stackFor(sc); - if (st != null) { - StackTraceElement[] frames = st.getStackTrace(); - int shown = Math.min(frames.length, 40); - for (int fi = 0; fi < shown; fi++) { - System.err.println(" at " + frames[fi]); - } - if (frames.length > shown) { - System.err.println(" ... " - + (frames.length - shown) + " more"); - } - } - } else if (sc.value instanceof RuntimeHash h - && h.elements.values().stream().anyMatch(v -> v != null && v.value == base)) { - parentScalars.add(sc); - } else if (sc.value instanceof RuntimeArray a - && a.elements.stream().anyMatch(v -> v != null && v.value == base)) { - parentScalars.add(sc); - } - } - System.err.println(" total direct holders=" + matchIdx - + " total lexicals scanned=" + totalLexIdx); - if (matchIdx == 0 && !parentScalars.isEmpty()) { - System.err.println(" --- parent-holder candidates (" - + parentScalars.size() + ") ---"); - int pIdx = 0; - for (RuntimeScalar ps : parentScalars) { - System.err.println(" parent #" + (pIdx++) - + " scId=" + System.identityHashCode(ps) - + " type=" + ps.type - + " rcO=" + ps.refCountOwned - + " parentClass=" - + (ps.value != null ? ps.value.getClass().getSimpleName() : "null")); - if (ps.value instanceof RuntimeHash ph) { - java.util.List keys = new java.util.ArrayList<>(); - for (Map.Entry ent : ph.elements.entrySet()) { - if (ent.getValue() != null && ent.getValue().value == base) { - keys.add(ent.getKey()); - } - } - System.err.println(" via keys: " + keys); - } - Throwable pst = ScalarRefRegistry.stackFor(ps); - if (pst != null) { - StackTraceElement[] frames = pst.getStackTrace(); - int shown = Math.min(frames.length, 30); - for (int fi = 0; fi < shown; fi++) { - System.err.println(" at " + frames[fi]); - } - } - if (pIdx >= 5) { - System.err.println(" ... " + (parentScalars.size() - 5) + " more parents"); - break; - } - } - } - } - return new RuntimeScalar(String.join(" -> ", path)).getList(); - } - /** * Sets or gets the read-only status of a variable. * diff --git a/src/main/java/org/perlonjava/runtime/perlmodule/NetSSLeay.java b/src/main/java/org/perlonjava/runtime/perlmodule/NetSSLeay.java index a61f698616..eaf95353d5 100644 --- a/src/main/java/org/perlonjava/runtime/perlmodule/NetSSLeay.java +++ b/src/main/java/org/perlonjava/runtime/perlmodule/NetSSLeay.java @@ -366,7 +366,7 @@ private Map delegate() { private static final Map EVP_MD_CTX_HANDLES = new CurrentRuntimeMap<>(s -> s.evpMdContexts); private static final Map HMAC_CTX_HANDLES = new CurrentRuntimeMap<>(s -> s.hmacContexts); private static final Map RSA_HANDLES = new CurrentRuntimeMap<>(s -> s.rsaKeys); - private static final int MIN_RSA_KEY_BITS = 1024; + private static final int MIN_RSA_KEY_BITS = 2048; private static final int MAX_RSA_KEY_BITS = 8192; private static final Map ASN1_TIME_HANDLES = new CurrentRuntimeMap<>(s -> s.asn1Times); private static final Map CTX_HANDLES = new CurrentRuntimeMap<>(s -> s.sslContexts); @@ -3800,8 +3800,10 @@ public static RuntimeList BIO_eof(RuntimeArray args, int ctx) { public static RuntimeList RSA_generate_key(RuntimeArray args, int ctx) { // RSA_generate_key(bits, e, [cb], [cb_arg]) - int bits = args.size() > 0 ? parseRsaKeySize(args.get(0)) : 2048; - if (bits < MIN_RSA_KEY_BITS || bits > MAX_RSA_KEY_BITS) { + int bits; + try { + bits = args.size() > 0 ? parseRsaKeySize(args.get(0)) : MIN_RSA_KEY_BITS; + } catch (IllegalArgumentException e) { return new RuntimeScalar().getList(); } // e (public exponent) is typically 65537 — Java handles this internally @@ -3826,12 +3828,8 @@ public static RuntimeList RSA_generate_key(RuntimeArray args, int ctx) { try { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); - // src/test/resources/unit/netssleay_phase5_6.t uses 1024 bits to keep its - // RSA round-trip test fast. Preserve that OpenSSL-compatible legacy request. - // 1024-bit RSA is not suitable for new keys; use at least 2048 bits. - // Reject weaker and unbounded sizes above; suppress only this documented - // legacy-compatible generation call. - // codeql[java/insufficient-key-size] + // RSA_generate_key is limited to sizes accepted by parseRsaKeySize. + // The minimum is 2048 bits because this API also supports signing. kpg.initialize(bits, SECURE_RANDOM); // Call callback during key generation if provided @@ -3867,19 +3865,14 @@ public static RuntimeList RSA_generate_key(RuntimeArray args, int ctx) { private static int parseRsaKeySize(RuntimeScalar requestedBits) { try { - int type = RuntimeScalarType.effectiveType(requestedBits); - if (type == RuntimeScalarType.INTEGER || type == RuntimeScalarType.DOUBLE) { - double number = requestedBits.getDouble(); - if (!Double.isFinite(number) || number != Math.rint(number) - || number < MIN_RSA_KEY_BITS || number > MAX_RSA_KEY_BITS) { - return -1; - } - return (int) number; - } String text = requestedBits.toString().trim(); - return new java.math.BigDecimal(text).intValueExact(); + int bits = new java.math.BigDecimal(text).intValueExact(); + if (bits < MIN_RSA_KEY_BITS || bits > MAX_RSA_KEY_BITS) { + throw new IllegalArgumentException("Invalid RSA key size"); + } + return bits; } catch (NumberFormatException | ArithmeticException e) { - return -1; + throw new IllegalArgumentException("Invalid RSA key size", e); } } diff --git a/src/main/java/org/perlonjava/runtime/perlmodule/POSIX.java b/src/main/java/org/perlonjava/runtime/perlmodule/POSIX.java index 61107cfe94..5413ed452f 100644 --- a/src/main/java/org/perlonjava/runtime/perlmodule/POSIX.java +++ b/src/main/java/org/perlonjava/runtime/perlmodule/POSIX.java @@ -131,6 +131,7 @@ public static void initialize() { module.registerMethod("_const_SEEK_SET", "const_SEEK_SET", null); module.registerMethod("_const_SEEK_CUR", "const_SEEK_CUR", null); module.registerMethod("_const_SEEK_END", "const_SEEK_END", null); + module.registerMethod("_const_LONG_MAX", "const_LONG_MAX", null); // Signal constants module.registerMethod("_const_SIGHUP", "const_SIGHUP", null); @@ -1326,18 +1327,18 @@ public static RuntimeList dup2(RuntimeArray args, int ctx) { int origFd = source.getAssignedFileno(); if (origFd < 0) origFd = oldFd; DupIOHandle[] pair = DupIOHandle.createPairAt(sourceHandle, origFd, newFd); - source.ioHandle = pair[0]; // Replace source's handle with ref-counted wrapper + source.replaceIOHandle(pair[0]); // Replace source's handle with ref-counted wrapper dupHandle = pair[1]; } if (target != null) { // Reuse existing RuntimeIO — just replace its ioHandle in-place. // This preserves references from Perl glob variables. - target.ioHandle = dupHandle; + target.replaceIOHandle(dupHandle); } else { // No existing RuntimeIO at newFd — create a fresh one target = new RuntimeIO(); - target.ioHandle = dupHandle; + target.replaceIOHandle(dupHandle); target.registerExternalFd(newFd); IOOperator.registerFileDescriptor(newFd, target); } @@ -1396,6 +1397,17 @@ public static RuntimeList const_SEEK_END(RuntimeArray args, int ctx) { return new RuntimeScalar(2).getList(); } + // C long is 32 bits on Windows (including 64-bit Windows) and follows + // the pointer width on the supported Unix platforms. + public static RuntimeList const_LONG_MAX(RuntimeArray args, int ctx) { + String os = System.getProperty("os.name", "").toLowerCase(); + String model = System.getProperty("sun.arch.data.model", "64"); + long max = os.startsWith("windows") || "32".equals(model) + ? Integer.MAX_VALUE + : Long.MAX_VALUE; + return new RuntimeScalar(max).getList(); + } + // Fcntl constants public static RuntimeList const_F_DUPFD(RuntimeArray a, int c) { return new RuntimeScalar(0).getList(); } public static RuntimeList const_F_GETFD(RuntimeArray a, int c) { return new RuntimeScalar(1).getList(); } diff --git a/src/main/java/org/perlonjava/runtime/perlmodule/ScalarUtil.java b/src/main/java/org/perlonjava/runtime/perlmodule/ScalarUtil.java index fd848f99f8..96ac5683f3 100644 --- a/src/main/java/org/perlonjava/runtime/perlmodule/ScalarUtil.java +++ b/src/main/java/org/perlonjava/runtime/perlmodule/ScalarUtil.java @@ -255,58 +255,9 @@ public static RuntimeList isweak(RuntimeArray args, int ctx) { } RuntimeScalar ref = args.get(0); boolean wasWeak = WeakRefRegistry.isweak(ref); - if (wasWeak - && DestroyDispatch.hasRescuedObjects() - && isLeakTracerWeakRegistryCleanupCheck() - && !ModuleInitGuard.inModuleInit()) { - // DBIC is asking whether one registry slot is weak while other - // unrelated objects can still form intentional strong cycles. - // Drain the pending DESTROY rescues explicitly, then use quiet - // sweeps so those cycle islands retain Perl refcount semantics. - // A full non-quiet sweep is intentionally aggressive and would - // clear DBIC's own shifted diagnostic reference mid-expression. - DestroyDispatch.clearRescuedWeakRefs(); - ReachabilityWalker.sweepWeakRefs(true); - ReachabilityWalker.sweepWeakRefs(true); - return new RuntimeScalar(true).getList(); - } return new RuntimeScalar(wasWeak).getList(); } - private static boolean isLeakTracerWeakRegistryCleanupCheck() { - for (int i = 0; i < 8; i++) { - RuntimeCode code = RuntimeCode.getActiveCodeAt(i); - if (code == null) break; - String filename = code.cvStartFile; - String packageName = code.packageName; - if ("DBICTest::Util::LeakTracer".equals(packageName) - || (filename != null && filename.endsWith("DBICTest/Util/LeakTracer.pm"))) { - String subName = code.subName; - if (subName == null || !subName.endsWith("assert_empty_weakregistry")) { - continue; - } - RuntimeArray args = RuntimeCode.getActiveArgsAt(i); - if (args == null || args.size() == 0) return false; - RuntimeScalar registryRef = args.get(0); - if (!RuntimeScalarType.isReference(registryRef) - || !(registryRef.value instanceof RuntimeHash registry)) { - return false; - } - // t/52leaks uses a large outer registry and a one-entry inner - // diagnostic. Quiet END checks are also outer cleanup points, - // even when a test registered only one schema or storage. - return registry.size() > 5 - || (args.size() > 1 && args.get(1).getBoolean()); - } - } - return false; - } - - // isweak() normally reports weak-ref metadata only. DBIC's LeakTracer is a - // narrow compatibility exception: real Perl would already have cleared the - // rescued weak slots it is inspecting, so we drain those rescues and run - // cycle-preserving quiet sweeps while returning the pre-sweep weak status. - /** * Dualvar functionality. * diff --git a/src/main/java/org/perlonjava/runtime/perlmodule/Storable.java b/src/main/java/org/perlonjava/runtime/perlmodule/Storable.java index c81c9751ef..eafeac55a7 100644 --- a/src/main/java/org/perlonjava/runtime/perlmodule/Storable.java +++ b/src/main/java/org/perlonjava/runtime/perlmodule/Storable.java @@ -257,12 +257,11 @@ public static RuntimeList dclone(RuntimeArray args, int ctx) { RuntimeScalar data = args.get(0); CloneContext cloneContext = new CloneContext(); RuntimeScalar result = deepClone(data, cloneContext); - // The returned scalar is a live strong owner while dclone is - // finishing, just as a Perl temporary SV is. Acquire that owner - // before restoring weak child-to-root edges; otherwise a graph - // whose root is referenced only weakly from within itself reaches - // refCount zero before the caller can receive it. - RuntimeScalar.incrementRefCountForContainerStore(result); + // Use the caller's exact deferred return owner while restoring + // weak child-to-root edges. A separate counted helper scalar here + // would survive after RuntimeCode copied the result into its own + // return slot, leaving an owner with no Perl storage. + result = RuntimeScalar.copyToMortalReturnSlot(result); // Restore weak edges only after every strong container edge has // acquired ownership. Weakening during recursion can take a // newly-created referent to refCount zero when the weak edge @@ -349,10 +348,8 @@ public static void releaseApplyArgs(RuntimeArray args) { if (elem == null) continue; if (elem.refCountOwned && elem.value instanceof RuntimeBase base && base.refCount > 0) { - base.releaseOwner(elem, "Storable.releaseApplyArgs"); - base.releaseActiveOwner(elem); - base.refCount--; - elem.refCountOwned = false; + MortalList.releaseCountedOwnerImmediately( + elem, "Storable.releaseApplyArgs"); } } args.elements.clear(); diff --git a/src/main/java/org/perlonjava/runtime/perlmodule/Symbol.java b/src/main/java/org/perlonjava/runtime/perlmodule/Symbol.java index 34bb23aa2d..25782c2233 100644 --- a/src/main/java/org/perlonjava/runtime/perlmodule/Symbol.java +++ b/src/main/java/org/perlonjava/runtime/perlmodule/Symbol.java @@ -54,6 +54,7 @@ public static RuntimeList gensym(RuntimeArray args, int ctx) { // Create a unique anonymous glob String globName = "Symbol::GEN" + EmitterMethodCreator.classCounter.getAndIncrement(); RuntimeGlob glob = new RuntimeGlob(globName); + glob.symbolGensym = true; // Return a reference to the glob (not the glob itself) RuntimeScalar globRef = new RuntimeScalar(); diff --git a/src/main/java/org/perlonjava/runtime/regex/JoniRegexPattern.java b/src/main/java/org/perlonjava/runtime/regex/JoniRegexPattern.java index 49ab7d8b79..c3043ff6d2 100644 --- a/src/main/java/org/perlonjava/runtime/regex/JoniRegexPattern.java +++ b/src/main/java/org/perlonjava/runtime/regex/JoniRegexPattern.java @@ -1885,7 +1885,7 @@ public void finish(boolean matched) { } } } finally { - callbackMutations.clear(); + discardCallbackMutations(); DynamicVariableManager.popToLocalLevel(initialLocalLevel); } } @@ -1899,7 +1899,7 @@ private void recordFailedNestedCaptureState(String lastClosed, String lastParen) void abort() { // Perl retains ordinary assignments performed before a callback // exception; only dynamic local() scope is unwound here. - callbackMutations.clear(); + discardCallbackMutations(); DynamicVariableManager.popToLocalLevel(initialLocalLevel); } @@ -1924,6 +1924,12 @@ private void restoreCallbackMutations() { } } + private void discardCallbackMutations() { + while (!callbackMutations.isEmpty()) { + callbackMutations.removeLast().discard(); + } + } + private static MatchView dynamicCaptureView( MatchView current, CaptureSnapshot previous) { if (previous == null || previous.position() >= current.currentBytePosition()) return current; diff --git a/src/main/java/org/perlonjava/runtime/regex/RuntimeRegex.java b/src/main/java/org/perlonjava/runtime/regex/RuntimeRegex.java index f25d0d7f83..4122f9becc 100644 --- a/src/main/java/org/perlonjava/runtime/regex/RuntimeRegex.java +++ b/src/main/java/org/perlonjava/runtime/regex/RuntimeRegex.java @@ -390,7 +390,7 @@ private RuntimeRegex cloneTrackedWithCallbacks(List callba copy.failedParseDebugTrace = this.failedParseDebugTrace; // replacement and callerArgs are not copied — they are set per-substitution // matched is not copied — each qr// object tracks its own m?PAT? state - copy.refCount = 0; // Enable refCount tracking + copy.startRefCountTracking(); return copy; } @@ -409,16 +409,32 @@ String userPropertyPackage() { private void setExecutableCallbacks(List callbacks) { List retained = List.copyOf(callbacks); - for (RuntimeRegexCallback callback : retained) callback.retainOwner(); + int retainedCount = 0; + try { + for (RuntimeRegexCallback callback : retained) { + callback.retainOwner(this); + retainedCount++; + } + } catch (RuntimeException | Error failure) { + for (int i = 0; i < retainedCount; i++) { + retained.get(i).releaseOwner(this); + } + throw failure; + } + List previous = executableCallbacks; + boolean previousReleased = executableCallbacksReleased; executableCallbacks = retained; executableCallbacksReleased = false; + if (!previousReleased) { + for (RuntimeRegexCallback callback : previous) callback.releaseOwner(this); + } } /** Release closure captures owned by this tracked qr// value. */ public void releaseExecutableCallbacks() { - if (executableCallbacksReleased || executableCallbacks.isEmpty()) return; + if (executableCallbacksReleased) return; executableCallbacksReleased = true; - for (RuntimeRegexCallback callback : executableCallbacks) callback.releaseOwner(); + for (RuntimeRegexCallback callback : executableCallbacks) callback.releaseOwner(this); } /** Strong Perl references held by this qr//'s executable callbacks. */ @@ -2905,7 +2921,7 @@ public static RuntimeScalar getQuotedRegex( regex.regexFlags = mergeRegexFlags(originalRegex.regexFlags, modifierStr, originalRegex.patternString); regex.hasPreservesMatch = regex.hasPreservesMatch || regex.regexFlags.preservesMatch(); regex.useGAssertion = regex.regexFlags.useGAssertion(); - regex.refCount = 0; // Track for proper weak ref handling + regex.startRefCountTracking(); return new RuntimeScalar(regex).propagateTaint(patternString); } @@ -2955,7 +2971,7 @@ public static RuntimeScalar getQuotedRegex( regex.regexFlags = mergeRegexFlags(originalRegex.regexFlags, modifierStr, originalRegex.patternString); regex.hasPreservesMatch = regex.hasPreservesMatch || regex.regexFlags.preservesMatch(); regex.useGAssertion = regex.regexFlags.useGAssertion(); - regex.refCount = 0; // Track for proper weak ref handling + regex.startRefCountTracking(); return new RuntimeScalar(regex).propagateTaint(patternString, overloadedResult); } @@ -3548,7 +3564,7 @@ public static RuntimeScalar getReplacementRegex(RuntimeScalar patternString, Run regex.trustedCalloutCount = resolvedRegex.trustedCalloutCount; regex.compiledRegexCacheKey = resolvedRegex.compiledRegexCacheKey; regex.userPropertyPackage = resolvedRegex.userPropertyPackage; - regex.executableCallbacks = resolvedRegex.executableCallbacks; + regex.setExecutableCallbacks(resolvedRegex.executableCallbacks); regex.patternString = resolvedRegex.patternString; regex.debugPatternString = resolvedRegex.debugPatternString; regex.sourcePatternByteBacked = resolvedRegex.sourcePatternByteBacked; @@ -3599,7 +3615,7 @@ public static RuntimeScalar getReplacementRegex(RuntimeScalar patternString, Run regex.trustedCalloutCount = recompiledRegex.trustedCalloutCount; regex.compiledRegexCacheKey = recompiledRegex.compiledRegexCacheKey; regex.userPropertyPackage = recompiledRegex.userPropertyPackage; - regex.executableCallbacks = resolvedRegex.executableCallbacks; + regex.setExecutableCallbacks(resolvedRegex.executableCallbacks); regex.patternString = recompiledRegex.patternString; regex.debugPatternString = recompiledRegex.debugPatternString; regex.sourcePatternByteBacked = diff --git a/src/main/java/org/perlonjava/runtime/regex/RuntimeRegexCallback.java b/src/main/java/org/perlonjava/runtime/regex/RuntimeRegexCallback.java index b9141f639b..6a7909a135 100644 --- a/src/main/java/org/perlonjava/runtime/regex/RuntimeRegexCallback.java +++ b/src/main/java/org/perlonjava/runtime/regex/RuntimeRegexCallback.java @@ -1,9 +1,14 @@ package org.perlonjava.runtime.regex; import org.perlonjava.runtime.runtimetypes.RuntimeCode; +import org.perlonjava.runtime.runtimetypes.PerlOwnerSlot; import org.perlonjava.runtime.runtimetypes.RuntimeScalar; import org.perlonjava.runtime.operators.WarnDie; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; import java.util.function.Function; /** A parser-created executable segment in a regex template. */ @@ -27,6 +32,19 @@ boolean isBlock() { final String source; final boolean uninitializedWarningsEnabled; private int ownerCount; + private int unassociatedOwnerCount; + private PerlOwnerSlot codeOwnerSlot; + /** Regex owners are provenance only; the callback must not keep them alive. */ + private final List regexOwners = new ArrayList<>(); + + private static final class RegexOwnerReference { + final WeakReference owner; + int references = 1; + + RegexOwnerReference(RuntimeRegex owner) { + this.owner = new WeakReference<>(owner); + } + } private RuntimeRegexCallback( RuntimeCode code, Kind kind, String sourceLocation, String lexicalPackage, @@ -40,23 +58,73 @@ private RuntimeRegexCallback( } synchronized void retainOwner() { - if (code.refCount < 0) return; - if (ownerCount++ == 0) { - code.refCount++; + retainOwnerReference(null); + unassociatedOwnerCount++; + } + + synchronized void retainOwner(RuntimeRegex owner) { + if (owner == null) return; + retainOwnerReference(owner); + } + + private void retainOwnerReference(RuntimeRegex owner) { + if (ownerCount == 0 && !code.isPerlDestroyed()) { + PerlOwnerSlot slot = new PerlOwnerSlot(PerlOwnerSlot.Kind.REGEX_CALLBACK); + slot.acquireCountedNativeOwner(code, "RuntimeRegexCallback.retainOwner"); + codeOwnerSlot = slot; + } + ownerCount++; + if (owner != null) { + RegexOwnerReference ownerReference = findOwner(owner); + if (ownerReference == null) { + regexOwners.add(new RegexOwnerReference(owner)); + } else { + ownerReference.references++; + } } } synchronized void releaseOwner() { - if (code.refCount < 0) return; - if (ownerCount <= 0) return; + if (unassociatedOwnerCount <= 0) return; + unassociatedOwnerCount--; + releaseOwnerReference(); + } + + synchronized void releaseOwner(RuntimeRegex owner) { + if (ownerCount <= 0 || owner == null) return; + RegexOwnerReference ownerReference = findOwner(owner); + if (ownerReference == null) return; + if (--ownerReference.references == 0) regexOwners.remove(ownerReference); + releaseOwnerReference(); + } + + private void releaseOwnerReference() { ownerCount--; + PerlOwnerSlot slot = codeOwnerSlot; if (ownerCount != 0) return; - if (code.refCount > 0) code.refCount--; - if (code.refCount == 0 && code.stashRefCount <= 0) { + if (slot != null) { + codeOwnerSlot = null; + slot.releaseRegexCallbackOwner("RuntimeRegexCallback.releaseOwner"); + } + if (!code.isPerlDestroyed() + && !code.hasPerlOwnerForCaptureOtherThan(null)) { code.releaseCaptures(); } } + /** Find an owner's weak provenance record, pruning owners already collected. */ + private RegexOwnerReference findOwner(RuntimeRegex owner) { + RegexOwnerReference found = null; + for (Iterator iterator = regexOwners.iterator(); + iterator.hasNext();) { + RegexOwnerReference reference = iterator.next(); + RuntimeRegex current = reference.owner.get(); + if (current == null) iterator.remove(); + else if (current == owner) found = reference; + } + return found; + } + /** Exact metadata copy for an ithread graph clone with a child-owned CODE pad. */ public RuntimeRegexCallback cloneForThread( Function codeCloner) { diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/AutovivificationArray.java b/src/main/java/org/perlonjava/runtime/runtimetypes/AutovivificationArray.java index dc8b750c16..b11d44ab3b 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/AutovivificationArray.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/AutovivificationArray.java @@ -47,11 +47,15 @@ public static void vivify(RuntimeArray array) { RuntimeScalar referent = arrayProxy.scalarToAutovivify; if (referent instanceof RuntimeBaseProxy proxy) { - proxy.set(array.createReference()); + // This array is owned through the scalar slot being + // autovivified. It has no separate named @array binding; + // the scalar slot's counted owner keeps it alive. + proxy.set(array.createAnonymousReference()); } else { referent.value = array; referent.type = RuntimeScalarType.ARRAYREFERENCE; - RuntimeScalar.incrementRefCountForContainerStore(referent); + RuntimeScalar.incrementRefCountForContainerStore( + referent, referent.countedOwnerKind()); } } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/AutovivificationHash.java b/src/main/java/org/perlonjava/runtime/runtimetypes/AutovivificationHash.java index 825227c693..9c351551f8 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/AutovivificationHash.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/AutovivificationHash.java @@ -48,7 +48,9 @@ public static void vivify(RuntimeHash hash) { hashProxy.scalarToAutovivify.value = hash; hashProxy.scalarToAutovivify.type = HASHREFERENCE; - RuntimeScalar.incrementRefCountForContainerStore(hashProxy.scalarToAutovivify); + RuntimeScalar.incrementRefCountForContainerStore( + hashProxy.scalarToAutovivify, + hashProxy.scalarToAutovivify.countedOwnerKind()); } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/CompiledDirectCallSite.java b/src/main/java/org/perlonjava/runtime/runtimetypes/CompiledDirectCallSite.java new file mode 100644 index 0000000000..e958e6ece6 --- /dev/null +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/CompiledDirectCallSite.java @@ -0,0 +1,90 @@ +package org.perlonjava.runtime.runtimetypes; + +/** One compiled named-call edge owned by the CV whose optree contains it. */ +final class CompiledDirectCallSite { + private final String name; + private final RuntimeScalar cachedRef; + private final boolean compileTimePinned; + private boolean ownsRetiredTarget; + + CompiledDirectCallSite( + String name, + RuntimeScalar cachedRef, + RuntimeCode initialTarget, + boolean compileTimePinned, + boolean retainTargetIfDeletedBeforeInstall) { + this.name = name; + this.cachedRef = cachedRef; + this.compileTimePinned = compileTimePinned; + RuntimeScalar visible = GlobalVariable.getVisibleGlobalCodeRefForDirectCall(name); + boolean targetWasRemovedBeforeInstallation = retainTargetIfDeletedBeforeInstall + && initialTarget != null + && initialTarget.defined() + && !RuntimeCode.isCodeDefined(visible); + RuntimeCode ownedTarget = compileTimePinned || targetWasRemovedBeforeInstallation + ? initialTarget : null; + cachedRef.initializeCompiledDirectCallCache( + name, cachedRef.compiledDirectCallSiteIndex(), ownedTarget, + compileTimePinned); + if (ownedTarget != null) { + cachedRef.retainCodeSlotBinding(); + ownsRetiredTarget = true; + } + GlobalVariable.registerCompiledDirectCallSite(name, this); + } + + String name() { + return name; + } + + int index() { + return cachedRef.compiledDirectCallSiteIndex(); + } + + RuntimeScalar resolve() { + if (compileTimePinned || ownsRetiredTarget) return cachedRef; + RuntimeScalar visible = GlobalVariable.getVisibleGlobalCodeRefForDirectCall(name); + return visible != null ? visible : GlobalVariable.getGlobalCodeRefForDirectCall(name); + } + + /** Transfer the callsite's lifetime to a CV only when its stash slot is removed. */ + void visibleCodeSlotChanged(RuntimeScalar previous, RuntimeScalar replacement) { + if (compileTimePinned) return; + if (replacement != null) { + // namespace::clean removes the imported CODE entry by deleting + // its glob, then restores the other glob components. That restore + // can materialize a fresh, undefined CODE slot. Existing call + // sites still refer to the CV compiled before cleanup; an empty + // placeholder is not a replacement CV and must not retire their + // owner. + if (previous == null && !RuntimeCode.isCodeDefined(replacement)) return; + releaseRetiredTarget(); + return; + } + if (ownsRetiredTarget || previous == null + || previous.type != RuntimeScalarType.CODE + || !(previous.value instanceof RuntimeCode removedTarget)) { + return; + } + cachedRef.initializeCompiledDirectCallCache(name, + cachedRef.compiledDirectCallSiteIndex(), removedTarget, false); + cachedRef.retainCodeSlotBinding(); + ownsRetiredTarget = true; + } + + void release() { + GlobalVariable.unregisterCompiledDirectCallSite(name, this); + releaseRetiredTarget(); + cachedRef.type = RuntimeScalarType.UNDEF; + cachedRef.value = null; + cachedRef.globalCodeRefFqn = null; + } + + private void releaseRetiredTarget() { + if (!ownsRetiredTarget) return; + cachedRef.releaseCodeSlotBinding(); + ownsRetiredTarget = false; + cachedRef.initializeCompiledDirectCallCache(name, + cachedRef.compiledDirectCallSiteIndex(), null, false); + } +} diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/ControlFlowMarker.java b/src/main/java/org/perlonjava/runtime/runtimetypes/ControlFlowMarker.java index d243124d60..4bce1e07c7 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/ControlFlowMarker.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/ControlFlowMarker.java @@ -23,11 +23,13 @@ public class ControlFlowMarker { /** * The arguments for TAILCALL (goto &NAME) */ - public final RuntimeArray args; + public RuntimeArray args; /** Ownership-only carrier for temporary aliases transferred from {@link #args}. */ - public final RuntimeArray ownedArgs; + public RuntimeArray ownedArgs; + /** Active source {@code @_} value owners carried to the target frame. */ + RuntimeCode.TailCallArgumentOwners argumentOwners; /** Snapshot identity of the source call's pristine argument frame. */ - public final Object argumentFrame; + public Object argumentFrame; public final String namedTarget; public final String evalScope; /** Whether the tail call itself was issued by the active sort comparator. */ @@ -75,6 +77,7 @@ public ControlFlowMarker(ControlFlowType type, String label, String fileName, in this.codeRef = null; this.args = null; this.ownedArgs = null; + this.argumentOwners = null; this.argumentFrame = null; this.namedTarget = null; this.evalScope = evalScope; @@ -103,6 +106,7 @@ public ControlFlowMarker(RuntimeScalar codeRef, RuntimeArray args, String fileNa this.codeRef = codeRef; this.args = args; this.ownedArgs = args != null ? args.takeTailCallOwnership() : null; + this.argumentOwners = RuntimeCode.takeTailCallArgumentOwners(args); this.argumentFrame = args != null && !args.elements.isEmpty() ? RuntimeCode.currentArgumentAliasFrame(args.elements.get(0)) : null; this.namedTarget = namedTarget; @@ -111,6 +115,14 @@ public ControlFlowMarker(RuntimeScalar codeRef, RuntimeArray args, String fileNa this.switchControlOperator = null; } + /** Drop the consumed source frame and argument graph after tail-call handoff. */ + void clearTailCallHandoff() { + args = null; + ownedArgs = null; + argumentOwners = null; + argumentFrame = null; + } + /** * Debug method to print control flow information. */ diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/DestroyDispatch.java b/src/main/java/org/perlonjava/runtime/runtimetypes/DestroyDispatch.java index 5c74b3ad83..7a4be84053 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/DestroyDispatch.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/DestroyDispatch.java @@ -41,10 +41,6 @@ static void markDestroyTargetRescued() { } } - static void requestSweepAfterOuterDestroy() { - state().sweepPendingAfterOuterDestroy = true; - } - public static void registerIfDestroyable(RuntimeBase referent, int blessId) { if (referent == null || blessId == 0) return; String className = NameNormalizer.getBlessStr(blessId); @@ -100,26 +96,8 @@ static ArrayList snapshotStatementBoundaryDestroyableObjects() { } } - // Rescued objects whose weak refs need deferred clearing. - // We cannot clear weak refs immediately after rescue because that would also - // clear back-references from sibling objects (e.g., $source->{schema}) that - // are still needed during the test. Instead, we collect rescued objects here - // and clear their weak refs (with a deep sweep into nested blessed objects) - // just before END blocks run, when all test code has finished and the - // back-references are no longer needed. - /** - * Phase 4 (refcount_alignment_plan.md): Snapshot the rescued-objects - * list for use by {@link ReachabilityWalker}. Rescued objects (the - * result of Schema-style DESTROY self-save) are roots of the live - * graph even though they've "already fired" DESTROY. - */ - public static java.util.List snapshotRescuedForWalk() { - java.util.List objects = state().rescuedObjects; - synchronized (objects) { - return new java.util.ArrayList<>(objects); - } - } - + // Rescued objects stay in this lifecycle list until their exact owner slots + // leave. The list is bookkeeping and never owns or traverses the object graph. public static boolean isRescued(RuntimeBase referent) { if (referent == null) return false; java.util.List objects = state().rescuedObjects; @@ -140,42 +118,6 @@ public static boolean hasRescuedObjects() { * @param className the Perl class name * @return true if DESTROY (or AUTOLOAD) is defined in the class hierarchy */ - /** - * Phase D-W2c: walker-gated destroy is restricted to known-needed - * class hierarchies (Class::MOP and Moose / Moo). The gate is - * essential for those modules' bootstrap (their metaclasses and - * %METAS rely on transient refCount drift being absorbed by the - * walker), but it actively breaks DBIC's lazy-cache pattern and - * other CDBI / DBIx::Class flows where rows are MEANT to be - * destroyed at refCount=0 even when stack-local my-vars - * transiently reference them. - * - * The gate applies if and only if the class is in the - * Class::MOP / Moose family. The check is fast: a per-blessId - * BitSet lookup after the first miss-and-resolve. - * - * Patterns outside this family (e.g. user weak-ref cycles - * documented in dev/sandbox/walker_gate_dbic_minimal.t) do NOT - * get the gate; they were already broken on master and need a - * separate fix path. - */ - public static boolean classNeedsWalkerGate(int blessId) { - LifecycleRuntimeState state = state(); - int idx = Math.abs(blessId); - if (state.walkerGateChecked.get(idx)) return state.walkerGateClasses.get(idx); - String cn = NameNormalizer.getBlessStr(blessId); - boolean needs = cn != null && ( - cn.startsWith("Class::MOP") - || cn.startsWith("Moose::") - || cn.equals("Moose") - || cn.startsWith("Moo::") - || cn.equals("Moo") - ); - state.walkerGateChecked.set(idx); - if (needs) state.walkerGateClasses.set(idx); - return needs; - } - public static boolean classHasDestroy(int blessId, String className) { LifecycleRuntimeState state = state(); int idx = Math.abs(blessId); @@ -211,13 +153,23 @@ public static void invalidateCache() { } /** - * Call DESTROY on a referent whose refCount has reached 0. - * The caller MUST have already set refCount to Integer.MIN_VALUE. + * Finish destruction for a referent whose final owner has been released. * * @param referent the RuntimeBase object to destroy */ public static void callDestroy(RuntimeBase referent) { - // refCount is already MIN_VALUE (set by caller) + callDestroy(referent, false); + } + + static void callDestroyFromCountedOwner(RuntimeBase referent) { + callDestroy(referent, true); + } + + private static void callDestroy(RuntimeBase referent, boolean finalCountedOwner) { + if (referent instanceof RuntimeCode code && code.hasActiveCodeOwner()) { + code.deferFinalReleaseToActiveCode(); + return; + } // Shared canonical objects carry a published class name across // runtimes, but numeric bless IDs are runtime-local. Destruction may @@ -225,15 +177,20 @@ public static void callDestroy(RuntimeBase referent) { // in a child, so resolve the published name before method lookup. referent.synchronizePublishedSharedBlessing(); - // A shared aggregate may have runtime-local fetch views in another - // ithread. Canonical deletion waits for those views; the runtime that - // releases the last view performs the one Perl DESTROY callback. - if (referent.deferSharedDestroy()) return; + // A shared aggregate may have runtime-local fetch views. Canonical + // deletion waits for those views; an otherwise-unowned fetch proxy + // still clears weak references to its local Perl identity without + // cascading into shared backing storage. + RuntimeBase.SharedDestroyDisposition sharedDisposition = + referent.sharedDestroyDisposition(); + if (sharedDisposition == RuntimeBase.SharedDestroyDisposition.DEFER) return; + if (sharedDisposition == RuntimeBase.SharedDestroyDisposition.CLEAR_LOCAL_VIEW) { + referent.beginPerlDestruction(); + WeakRefRegistry.clearWeakRefsTo(referent, finalCountedOwner); + referent.markPerlDestroyed(); + return; + } - // The explicit lifecycle is authoritative once final cleanup has - // completed. Keep refCount's sentinel interpretation at the legacy - // bridge, while preventing a repeated count transition from entering - // the destruction path a second time. if (referent.perlLifecycleState() == RuntimeBase.PerlLifecycleState.DESTROYED) return; // Phase 3 (refcount_alignment_plan.md): Re-entry guard. @@ -244,12 +201,7 @@ public static void callDestroy(RuntimeBase referent) { // DESTROY can still track references, then return. The outer // doCallDestroy will handle final cleanup based on refCount when // its Perl body returns. - if (referent.currentlyDestroying) { - if (referent.refCount == Integer.MIN_VALUE) { - referent.refCount = 0; - } - return; - } + if (referent.currentlyDestroying) return; unregisterDestroyable(referent); // Phase 3 (refcount_alignment_plan.md): Resurrection re-fire. @@ -261,6 +213,7 @@ public static void callDestroy(RuntimeBase referent) { // resurrected objects (DBIC detected_reinvoked_destructor pattern). if (referent.destroyFired && referent.needsReDestroy) { referent.needsReDestroy = false; + removeRescuedObject(referent); String cn = NameNormalizer.getBlessStr(referent.blessId); if (cn != null && !cn.isEmpty()) { doCallDestroy(referent, cn); @@ -277,30 +230,27 @@ public static void callDestroy(RuntimeBase referent) { // subsequent callDestroy invocations just do cleanup (weak ref clearing + // cascade) without re-calling the Perl DESTROY method. if (referent.destroyFired) { - // If this object was rescued by DESTROY (e.g., Schema::DESTROY self-save) - // and is still in the rescuedObjects list, skip cleanup entirely. The weak - // refs and internal fields must remain intact because the phantom chain - // (or other code) may still access the object through its weak refs. - // Proper cleanup happens at END time via clearRescuedWeakRefs. + // A DESTROY-rescued object stays intact while its current Perl owner + // slots remain. The rescue queue only schedules this exact owner check. if (state().rescuedObjects.contains(referent)) { referent.markPerlResurrected(); return; } referent.beginPerlDestruction(); - WeakRefRegistry.clearWeakRefsTo(referent); + WeakRefRegistry.clearWeakRefsTo(referent, finalCountedOwner); + releaseTiedContainerOwner(referent); if (referent instanceof RuntimeHash hash) { - MortalList.scopeExitCleanupHash(hash); + MortalList.scopeExitCleanupDestroyedHash(hash); MortalList.flush(); } else if (referent instanceof RuntimeArray arr) { - MortalList.scopeExitCleanupArray(arr); + MortalList.scopeExitCleanupDestroyedArray(arr); MortalList.flush(); } else if (referent instanceof RuntimeScalar scalar) { - RuntimeScalar.scopeExitCleanup(scalar); + RuntimeScalar.scopeExitCleanupDestroyed(scalar); + MortalList.flush(); + } else if (referent instanceof RuntimeCode code) { + code.releaseStateStorage(); MortalList.flush(); - } - if ((referent instanceof RuntimeHash || referent instanceof RuntimeArray) - && MortalList.requestWeakSweepsForDestroyedContainer(referent)) { - MortalList.requestImmediateWeakSweep(); } referent.markPerlDestroyed(); return; @@ -309,30 +259,14 @@ public static void callDestroy(RuntimeBase referent) { // Release closure captures when a CODE ref's refCount hits 0. // This allows captured variables to be properly cleaned up // (e.g., blessed objects in captured scalars can fire DESTROY). - // However, skip releaseCaptures if the CODE ref is still installed in the - // stash (stashRefCount > 0). The selective refCount can falsely reach 0 - // for stash-installed closures because glob assignments, closure captures, - // and other JVM-level references aren't always counted. Releasing captures - // prematurely would cascade to clear weak references (e.g., in Sub::Defer's - // %DEFERRED hash), causing infinite recursion in Moo/DBIx::Class. + // A current counted CODE_SLOT owner must still have its paired count. if (referent instanceof RuntimeCode code) { - if (code.stashRefCount <= 0) { - // A queued END block is an owning CV slot even though it is - // not installed in a stash. Selective refCount can transiently - // reach zero while an assertion or callback releases another - // capture of the same lexical pad. Keep the queued CV's capture - // edges until the END queue consumes that owner. + if (code.hasCountedCodeSlots || !code.hasStashCodeSlotOwner()) { if (SpecialBlock.hasPendingEndBlock(code)) { - code.refCount = 1; - return; - } - if (code.activeEndBlockExecutions > 0) { - code.refCount = 1; - code.rescuedActiveEndBlockOwner = true; - return; - } - if (ReachabilityWalker.strongCycleRetainsWeakReferent(code)) { - code.refCount = 1; + // The current END queue cell is a strong owner even if + // its legacy count is unavailable. Defer cleanup until + // that exact queue slot transfers or releases the code. + code.deferFinalReleaseToActiveCode(); return; } code.releaseCaptures(); @@ -355,15 +289,26 @@ public static void callDestroy(RuntimeBase referent) { // Unblessed object — clear weak refs immediately and cascade into elements // to decrement refCounts of any tracked references they hold. referent.beginPerlDestruction(); - WeakRefRegistry.clearWeakRefsTo(referent); - if (referent instanceof RuntimeHash hash) { - MortalList.scopeExitCleanupHash(hash); - } else if (referent instanceof RuntimeArray arr) { - MortalList.scopeExitCleanupArray(arr); - } else if (referent instanceof RuntimeScalar scalar) { - RuntimeScalar.scopeExitCleanup(scalar); + WeakRefRegistry.clearWeakRefsTo(referent, finalCountedOwner); + releaseTiedContainerOwner(referent); + // This path can run inside another object's DESTROY callback. + // Drain only the outgoing releases added by this dying referent + // before returning to that Perl code; otherwise its B::REFCNT + // checks observe child edges from a hash already marked destroyed. + MortalList.pushMark(); + try { + if (referent instanceof RuntimeHash hash) { + MortalList.scopeExitCleanupDestroyedHash(hash); + } else if (referent instanceof RuntimeArray arr) { + MortalList.scopeExitCleanupDestroyedArray(arr); + } else if (referent instanceof RuntimeScalar scalar) { + RuntimeScalar.scopeExitCleanupDestroyed(scalar); + } else if (referent instanceof RuntimeCode code) { + code.releaseStateStorage(); + } + } finally { + MortalList.popAndFlush(); } - MortalList.requestWeakSweepsForDestroyedContainer(referent); referent.markPerlDestroyed(); return; } @@ -399,40 +344,39 @@ private static void doCallDestroy(RuntimeBase referent, String className) { // to decrement refCounts of any tracked references they hold. // Without this, blessed objects without DESTROY (e.g., Moo objects like // DBIx::Class::Storage::BlockRunner) leak their contained references. - WeakRefRegistry.clearWeakRefsTo(referent); - if (referent instanceof RuntimeHash hash) { - MortalList.scopeExitCleanupHash(hash); - MortalList.flush(); - } else if (referent instanceof RuntimeArray arr) { - MortalList.scopeExitCleanupArray(arr); - MortalList.flush(); - } else if (referent instanceof RuntimeScalar scalar) { - RuntimeScalar.scopeExitCleanup(scalar); - MortalList.flush(); - } - if ((referent instanceof RuntimeHash || referent instanceof RuntimeArray) - && MortalList.requestWeakSweepsForDestroyedContainer(referent)) { - MortalList.requestImmediateWeakSweep(); + MortalList.pushMark(); + try { + WeakRefRegistry.clearWeakRefsTo(referent); + releaseTiedContainerOwner(referent); + if (referent instanceof RuntimeHash hash) { + MortalList.scopeExitCleanupDestroyedHash(hash); + } else if (referent instanceof RuntimeArray arr) { + MortalList.scopeExitCleanupDestroyedArray(arr); + } else if (referent instanceof RuntimeScalar scalar) { + RuntimeScalar.scopeExitCleanupDestroyed(scalar); + } else if (referent instanceof RuntimeCode code) { + code.releaseStateStorage(); + } + } finally { + // A no-DESTROY cleanup is a nested lifecycle boundary. Drain + // only releases created while clearing this referent; a global + // flush here can consume an unrelated RETURN_VALUE that the + // enclosing expression has not transferred to its receiver. + MortalList.popAndFlush(); } referent.markPerlDestroyed(); return; } - // A non-weak referent may not have activated the scalar-owner ledger - // yet. Turn it on before invoking DESTROY so temporary callback slots - // can be distinguished from real resurrection during teardown. There - // is intentionally no backfill: package roots are themselves being - // dismantled, while any new owner created by DESTROY is recorded. - String globalPhase = GlobalVariable.getGlobalVariable( - GlobalContext.GLOBAL_PHASE).toString(); - boolean checkingGlobalOwnerDelta = "DESTRUCT".equals(globalPhase) - || MortalList.isDrainingTopLevelTemporary(); - Set activeOwnersAtStart = null; - Set ownerSlotsAtStart = null; - if (checkingGlobalOwnerDelta) { - referent.activateOwnerTracking(); - activeOwnersAtStart = referent.activeOwnerSnapshot(); - ownerSlotsAtStart = referent.ownerSlotSnapshot(); + // Snapshot explicit owner identities before invoking DESTROY so + // callback argument slots are not mistaken for resurrection. This + // decision is based on owner changes in every phase, not on whether + // cleanup happens during a top-level flush. + boolean checkingOwnerSlotDelta = true; + Set ownerSlotsAtStart = Collections.newSetFromMap( + new IdentityHashMap<>()); + for (PerlOwnerSlot ownerSlot : referent.ownerSlotSnapshot()) { + if (ownerSlot.isActive()) ownerSlotsAtStart.add(ownerSlot); } // Mark as destroyed only once we will run Perl DESTROY. Setting destroyFired @@ -468,16 +412,10 @@ private static void doCallDestroy(RuntimeBase referent, String className) { state.currentDestroyTarget = referent; state.destroyTargetRescued = false; - // Phase 3 (refcount_alignment_plan.md): Transition from MIN_VALUE - // back to 0 so increments/decrements inside DESTROY work normally. - // currentlyDestroying guards callDestroy re-entry from transient - // decrement-to-0 events (see callDestroy's entry check). boolean savedCurrentlyDestroying = referent.currentlyDestroying; referent.currentlyDestroying = true; - if (referent.refCount == Integer.MIN_VALUE) { - referent.refCount = 0; - } + boolean callbackCompleted = false; try { // Build $self reference to pass as $_[0] RuntimeScalar self = new RuntimeScalar(); @@ -509,12 +447,10 @@ private static void doCallDestroy(RuntimeBase referent, String className) { // added during apply (shift @_, $self scope exit) without // clobbering outer-scope pending entries. int pendingBefore = MortalList.pendingSize(); - MortalList.invalidateAllRootSnapshots(); try { RuntimeCode.apply(destroyMethod, args, RuntimeContextType.VOID); } finally { - MortalList.invalidateAllRootSnapshots(); - try { + try { // Drain entries added by DESTROY even when the Perl body // throws; scope cleanup must finish before its callback // owner is released. @@ -523,19 +459,14 @@ private static void doCallDestroy(RuntimeBase referent, String className) { // Balance the args.push(self) increment on both normal // and exceptional exits. If DESTROY consumed the element // via shift, args.elements is empty and MortalList already - // released that owner. Otherwise this direct decrement - // avoids recursively entering callDestroy while the same - // referent is still in its DESTROY frame. + // released that owner. Otherwise retire its exact slot and + // paired count without recursively entering callDestroy + // while the same referent is still in its DESTROY frame. for (RuntimeScalar elem : args.elements) { if (elem != null && elem.refCountOwned - && elem.value instanceof RuntimeBase base - && base.refCount > 0) { - if (base.refCountTrace) { - base.releaseOwner(elem, "doCallDestroy args balance"); - } - base.releaseActiveOwner(elem); - base.refCount--; - elem.refCountOwned = false; + && elem.value instanceof RuntimeBase) { + MortalList.releaseDestroySelfArgument( + elem, "DestroyDispatch.doCallDestroy args balance"); } } args.elements.clear(); @@ -543,105 +474,9 @@ private static void doCallDestroy(RuntimeBase referent, String className) { } } - // Reblessing an object while its DESTROY method is running starts - // a new destruction lifecycle for the new class. The original - // one-shot guard belongs to the old class, so do not let it - // suppress the new class's DESTROY (op/ref.t's _B -> A case). - // Invoke it directly while the object is still protected by the - // current DESTROY frame; going through callDestroy() here would - // be treated as re-entrance and discarded. - if (referent.blessId != destroyBlessId) { - String reblessedClassName = NameNormalizer.getBlessStr(referent.blessId); - // A same-class bless may receive a fresh runtime-local ID after - // method-cache invalidation. It does not start a new Perl - // destruction lifecycle: cache implementations such as - // Class::Std::Fast use it while retaining the object. Compare - // the Perl class names rather than their ephemeral IDs. - if (reblessedClassName != null && !reblessedClassName.isEmpty() - && !reblessedClassName.equals(className)) { - referent.destroyFired = false; - doCallDestroy(referent, reblessedClassName); - return; - } - } - - // Phase 3: Resurrection detection. If refCount > 0 at this point, - // a strong ref to the object escaped DESTROY (e.g. Devel::StackTrace- - // like @DB::args capture into a persistent array, or Schema-style - // self-save). Mark needsReDestroy and let the next decrement-to-0 - // re-invoke DESTROY. Don't clear weak refs or cascade — the object - // is still alive. - if (hasEscapedPerlOwner(referent, checkingGlobalOwnerDelta, - activeOwnersAtStart, ownerSlotsAtStart) - && !state.destroyTargetRescued) { - warnIfResurrectedDuringGlobalDestruction(referent, className); - referent.needsReDestroy = true; - return; - } - - // Check if DESTROY rescued the object by storing $self somewhere. - // If destroyTargetRescued was set during DESTROY (detected by - // RuntimeScalar.setLargeRefCounted when the old value was a weak ref - // to currentDestroyTarget being overwritten by a strong ref to the - // same target), the object should survive — skip cascade cleanup. - // - // Example: Schema::DESTROY re-attaches itself to a ResultSource via - // $source->{schema} = $self - // This triggers rescue detection because the old value ($source->{schema}, - // a weak ref to Schema) is being replaced by a strong ref to Schema. - if (state.destroyTargetRescued) { - if ("DESTRUCT".equals(GlobalVariable.getGlobalVariable( - GlobalContext.GLOBAL_PHASE).toString())) { - warnIfResurrectedDuringGlobalDestruction(referent, className); - } - // Object was rescued by DESTROY (e.g., Schema::DESTROY self-save). - // - // refCount has been set to 1 by setLargeRefCounted during rescue - // detection (MIN_VALUE → 1). This represents the rescue container's - // single counted reference (e.g., $source->{schema} = $self). - // - // When the rescue source eventually dies and its DESTROY weakens - // source->{schema}, refCount goes 1→0→callDestroy. That callDestroy - // is intercepted by the rescuedObjects check (skip cleanup), keeping - // Schema's internals intact during the phantom chain. Proper cleanup - // happens later via processRescuedObjects at block scope exit. - // - // Keep destroyFired=true to prevent infinite DESTROY loops. - // - // Don't clear weak refs here — the rescued object is still alive, - // and other sources may still have weak refs to it that need to - // remain defined until the object truly dies. - // - // Don't cascade — the rescued object's internal fields (Storage, - // DBI::db, ResultSources) must remain intact because the object - // is still alive. - // - // Track rescued objects so clearRescuedWeakRefs can clean up - // at END time. - state.rescuedObjects.add(referent); - MortalList.invalidateExternalRootSnapshot(); - return; - } - - // Object was NOT rescued — clear weak refs now (deferred from callDestroy). - // In Perl 5, weak refs are cleared after DESTROY only if the object - // wasn't resurrected. We match that by clearing here. - WeakRefRegistry.clearWeakRefsTo(referent); - - // Cascading destruction: after DESTROY runs and the object was NOT rescued, - // walk the destroyed object's internal fields for any blessed references - // and defer their refCount decrements. This ensures nested objects - // (e.g., $self->{inner}) are destroyed when their parent is destroyed. - if (referent instanceof RuntimeHash hash) { - MortalList.scopeExitCleanupHash(hash); - MortalList.flush(); - } else if (referent instanceof RuntimeArray arr) { - MortalList.scopeExitCleanupArray(arr); - MortalList.flush(); - } else if (referent instanceof RuntimeScalar scalar) { - RuntimeScalar.scopeExitCleanup(scalar); - MortalList.flush(); - } + callbackCompleted = true; + finishDestroyOwnership(referent, className, destroyBlessId, + checkingOwnerSlotDelta, ownerSlotsAtStart); } catch (Exception e) { String msg = e.getMessage(); if (msg == null) msg = e.getClass().getName(); @@ -657,11 +492,18 @@ private static void doCallDestroy(RuntimeBase referent, String className) { && dieException.getWarningBits() != null ? dieException.getWarningBits() : RuntimeCode.getWarningBitsForCode(code); - if (!(e instanceof PerlDieException dieException - && dieException.isMiscWarningSuppressed())) { - WarnDie.warnWithCategoryFromCode( - new RuntimeScalar(warning), - new RuntimeScalar(""), "misc", warningBits); + try { + if (!(e instanceof PerlDieException dieException + && dieException.isMiscWarningSuppressed())) { + WarnDie.warnWithCategoryFromCode( + new RuntimeScalar(warning), + new RuntimeScalar(""), "misc", warningBits); + } + } finally { + if (!callbackCompleted) { + finishDestroyOwnership(referent, className, destroyBlessId, + checkingOwnerSlotDelta, ownerSlotsAtStart); + } } } finally { if (referent.needsReDestroy || state.destroyTargetRescued @@ -673,80 +515,240 @@ private static void doCallDestroy(RuntimeBase referent, String className) { // Restore the DESTROY target and rescue flag for nested DESTROY calls state.currentDestroyTarget = savedTarget; state.destroyTargetRescued = savedRescued; - // Phase 3: Exit DESTROY state. If refCount is still 0 and we're - // not taking the resurrection path, set MIN_VALUE so future - // callDestroy enters the normal cleanup path. + // Phase 3: Exit DESTROY state. A weak slot promoted during the + // callback acquires its paired count and owner identity through + // the ordinary unweaken/store transition. Do not rebuild a count + // from surviving storage here: that would hide a missing producer. referent.currentlyDestroying = savedCurrentlyDestroying; - if (referent.refCount == 0 && !referent.needsReDestroy) { - referent.refCount = Integer.MIN_VALUE; + int newCurrentCountedOwners = countNewCurrentCountedOwnerSlots( + referent, ownerSlotsAtStart); + if ((!referent.isRefCountTracked() || referent.refCount == 0) + && newCurrentCountedOwners != 0) { + throw new IllegalStateException("DESTROY returned with " + + newCurrentCountedOwners + " newly acquired counted Perl owner slot(s) " + + "but refCount is zero for " + + referent.getClass().getSimpleName()); } // Restore $@ — must happen whether DESTROY succeeded or threw. // Without this, die inside DESTROY would clobber the caller's $@. dollarAt.type = savedDollarAt.type; dollarAt.value = savedDollarAt.value; - // Phase D: outermost DESTROY is finishing. If any nested set() - // released a cyclic blessed-with-DESTROY ref, fire one walker - // sweep to clear any now-orphaned weak refs. This amortizes - // the sweep cost to at most one per top-level DESTROY instead - // of per-set(). Gated by ModuleInitGuard to avoid tripping - // during require/use load. - if (savedTarget == null && state.sweepPendingAfterOuterDestroy - && !ModuleInitGuard.inModuleInit()) { - state.sweepPendingAfterOuterDestroy = false; - ReachabilityWalker.sweepWeakRefs(false, false); + } + } + + /** Final destruction releases magic even when an expression still borrows the container. */ + private static void releaseTiedContainerOwner(RuntimeBase referent) { + if (referent instanceof RuntimeHash hash && hash.elements instanceof TieHash tieHash) { + tieHash.releaseTiedObject(); + } else if (referent instanceof RuntimeArray array && array.elements instanceof TieArray tieArray) { + tieArray.releaseTiedObject(); + } + } + + /** The callback's success or failure does not change its ownership obligations. */ + private static void finishDestroyOwnership( + RuntimeBase referent, String className, int destroyBlessId, + boolean checkingGlobalOwnerDelta, Set ownerSlotsAtStart) { + LifecycleRuntimeState state = state(); + if (referent.blessId != destroyBlessId) { + String reblessedClassName = NameNormalizer.getBlessStr(referent.blessId); + // Compare names: a same-class bless can receive a new runtime-local + // ID without starting a new destruction lifecycle. Dispatch directly + // while the current DESTROY frame still guards callDestroy reentry. + if (reblessedClassName != null && !reblessedClassName.isEmpty() + && !reblessedClassName.equals(className)) { + referent.destroyFired = false; + doCallDestroy(referent, reblessedClassName); + return; } } + if (hasEscapedPerlOwner(referent, checkingGlobalOwnerDelta, + ownerSlotsAtStart) && !state.destroyTargetRescued) { + referent.needsReDestroy = true; + warnIfResurrectedDuringGlobalDestruction(referent, className); + return; + } + if (state.destroyTargetRescued) { + if ("DESTRUCT".equals(GlobalVariable.getGlobalVariable( + GlobalContext.GLOBAL_PHASE).toString())) { + warnIfResurrectedDuringGlobalDestruction(referent, className); + } + // A weak slot promoted to a rescuing strong owner keeps the + // object's contents and observers until its rescue lifetime ends. + // Its final release must dispatch DESTROY again, as Perl does for + // an object whose first destructor installed a current Perl owner. + // A rescue marker without an owner identity is only lifecycle + // bookkeeping and should proceed directly to final cleanup. + referent.needsReDestroy = hasLivePerlOwnerIdentity(referent); + state.rescuedObjects.add(referent); + return; + } + WeakRefRegistry.clearWeakRefsTo(referent); + releaseTiedContainerOwner(referent); + if (referent instanceof RuntimeHash hash) { + MortalList.scopeExitCleanupDestroyedHash(hash); + } else if (referent instanceof RuntimeArray array) { + MortalList.scopeExitCleanupDestroyedArray(array); + } else if (referent instanceof RuntimeScalar scalar) { + RuntimeScalar.scopeExitCleanupDestroyed(scalar); + } else if (referent instanceof RuntimeCode code) { + // Blessed CVs may resurrect in DESTROY. Their state pad remains + // intact through the callback and the resurrection decision. + code.releaseStateStorage(); + } else { + return; + } + MortalList.flush(); } /** - * Decide resurrection from Perl owner slots when the owner ledger is - * active. During global destruction the legacy selective count can still - * include temporary argument aliases after their Perl owners have gone; - * those aliases are not resurrection. Objects which have not activated - * owner tracking retain the legacy count-based behavior. + * Decide resurrection from Perl owner slots. Counts include runtime + * temporaries and lifecycle bridges, so a positive value without a current + * Perl owner identity is not evidence that DESTROY installed a reference. */ - private static boolean hasEscapedPerlOwner(RuntimeBase referent, - boolean checkingGlobalOwnerDelta, - Set activeOwnersAtStart, - Set ownerSlotsAtStart) { + static boolean hasEscapedPerlOwner(RuntimeBase referent, + boolean checkingGlobalOwnerDelta, + Set ownerSlotsAtStart) { if (checkingGlobalOwnerDelta) { - for (RuntimeScalar owner : referent.activeOwnerSnapshot()) { - // DESTROY commonly creates short-lived aliases while it calls - // methods on $self. They are new ledger entries, but they do - // not resurrect the object if their Perl slots are gone by the - // time the destructor returns. During global teardown, package - // roots are still available to the reachability walker, so - // require a new scalar owner to remain rooted before warning. - if (!activeOwnersAtStart.contains(owner) - && ReachabilityWalker.isScalarReachable(owner)) return true; - } - for (PerlOwnerSlot ownerSlot : referent.ownerSlotSnapshot()) { - if (!ownerSlotsAtStart.contains(ownerSlot)) return true; + return hasNewPerlOwnerSlot(referent, ownerSlotsAtStart); + } + Set ownerSlots = referent.ownerSlotSnapshot(); + if (hasCurrentPerlOwnerSlot(referent, ownerSlots)) return true; + if (referent.hasSemanticCaptureOwner()) return true; + return false; + } + + static boolean hasNewPerlOwnerSlot( + RuntimeBase referent, Set ownerSlotsAtStart) { + for (PerlOwnerSlot ownerSlot : referent.ownerSlotSnapshot()) { + if ((ownerSlotsAtStart == null || !ownerSlotsAtStart.contains(ownerSlot)) + && isCurrentPerlOwnerSlot(referent, ownerSlot)) return true; + } + return false; + } + + private static int countNewCurrentCountedOwnerSlots( + RuntimeBase referent, Set ownerSlotsAtStart) { + int count = 0; + for (PerlOwnerSlot ownerSlot : referent.ownerSlotSnapshot()) { + if (ownerSlotsAtStart != null && ownerSlotsAtStart.contains(ownerSlot)) continue; + if (PerlOwnerSlot.isCountedKind(ownerSlot.kind()) + && isCurrentPerlOwnerSlot(referent, ownerSlot)) { + count++; } - return false; } - if (referent.activeOwners == null) { - return referent.refCount > 0; + return count; + } + + static boolean hasCurrentPerlOwnerSlot(RuntimeBase referent) { + return referent != null && referent.hasCurrentPerlOwnerSlotIdentity(); + } + + /** + * Whether a live Perl owner remains apart from the rescued-object queue, + * temporary roots, and compatibility counts. The rescued-object caller + * uses this after an explicit overwrite to decide whether nested weak + * callbacks still have an owning Perl path. + */ + static boolean hasLivePerlOwnerIdentity(RuntimeBase referent) { + return referent != null + && (referent.localBindingExists + || referent.hasPendingReturnOwner() + || referent.hasSemanticCaptureOwner() + || hasCurrentPerlOwnerSlot(referent)); + } + + private static boolean hasCurrentPerlOwnerSlot( + RuntimeBase referent, Set ownerSlots) { + for (PerlOwnerSlot ownerSlot : ownerSlots) { + if (isCurrentPerlOwnerSlot(referent, ownerSlot)) return true; + } + return false; + } + + /** + * Check one newly installed slot as an owner after DESTROY. Call and + * return transfer slots, argument aliases, active frames, and temporary + * roots are runtime scaffolding at this boundary. Durable counted slots + * are checked against their current scalar or container storage; + * identity-only slots are already tied to their + * owning storage lifecycle. + */ + static boolean isCurrentPerlOwnerSlot(RuntimeBase referent, PerlOwnerSlot slot) { + if (slot == null || !slot.isActive() || slot.referent() != referent) return false; + PerlOwnerSlot.Kind kind = slot.kind(); + if (!PerlOwnerSlot.isPerlOwnerKind(kind)) return false; + switch (kind) { + case TEMPORARY_ROOT, ARGUMENT_ALIAS, ARGUMENT_VALUE, RETURN_VALUE, ACTIVE_CODE -> { + return false; + } + case ARGUMENT_CONTAINER -> { + RuntimeScalar owner = slot.countedScalarOwner(); + return owner != null && owner.isCurrentCountedScalarOwner(referent, slot); + } + case ARRAY_ELEMENT, HASH_ELEMENT -> { + RuntimeScalar owner = slot.countedScalarOwner(); + return owner != null + && owner.hasCurrentAggregateElementPerlStorageOwner(referent, slot); + } + case SCALAR_CELL, CODE_SLOT, TIE_HANDLER, ARGUMENT_TIE_HANDLER -> { + RuntimeScalar owner = slot.countedScalarOwner(); + return owner != null && owner.isCurrentCountedScalarOwner(referent, slot); + } + case UNTRACKED_REFERENCE -> { + RuntimeScalar owner = slot.untrackedScalarOwner(); + return owner != null + && !owner.isTransientArgumentValueOwner() + && (owner.hasLiveDurableStrongValueSlot() + || ((referent.blessId != 0 + || referent.isWeaklyRefCountTracked()) + && owner.hasCurrentAggregateStorageSlot())) + && !WeakRefRegistry.isweak(owner) + && (owner.type & RuntimeScalarType.REFERENCE_BIT) != 0 + && owner.value == referent; + } + case SCALAR_REFERENCE_CONTENTS -> { + RuntimeScalar owner = slot.scalarContentsOwner(); + RuntimeScalar scalarCell = slot.scalarReferenceCell(); + return owner != null && scalarCell != null + && !owner.isTransientArgumentValueOwner() + && owner.scalarReferenceContentsOwner == slot + && owner.hasLiveDurableStrongValueSlot() + && !WeakRefRegistry.isweak(owner) + && owner.type == RuntimeScalarType.REFERENCE + && owner.value == scalarCell + && !WeakRefRegistry.isweak(scalarCell) + && (scalarCell.type & RuntimeScalarType.REFERENCE_BIT) != 0 + && scalarCell.value == referent; + } + case SCALAR_CAPTURE -> { + RuntimeCode captureOwner = slot.captureOwner(); + return captureOwner != null && captureOwner.hasPerlOwnerForCapture(); + } + case CLOSURE_PAD -> { + return slot.isNativeCaptureOwner() || slot.legacyCaptureCount() > 0; + } + case IO_VIA_LAYER -> { + return true; + } + case CODE_PAD_CONSTANT -> { + return true; + } + default -> { + return slot.isNativeOwner(); + } } - // A DESTROY frame can still leave refCountOwned call-frame aliases in - // activeOwners after the Perl-visible owner has gone away. Those are - // bookkeeping remnants, not resurrection. Count only slots the root - // walker can still reach; otherwise a DBH with dead CachedKids can be - // marked needsReDestroy and skip its aggregate cleanup permanently. - return referent.reachableOwnerCount() > 0 || referent.hasSemanticCaptureOwner(); } /** * Warn when a destructor revives an object during global teardown. * - * Perl drains top-level temporaries immediately before changing - * {@code ${^GLOBAL_PHASE}} to {@code DESTRUCT}. Those objects survive - * into teardown just like objects destroyed after the phase change, while - * an ordinary nested lexical resurrection must remain silent. + * The global phase is the lifecycle boundary. An ordinary statement-level + * temporary flush must not make a RUN-phase resurrection look like teardown. */ private static void warnIfResurrectedDuringGlobalDestruction(RuntimeBase referent, String className) { String phase = GlobalVariable.getGlobalVariable(GlobalContext.GLOBAL_PHASE).toString(); - if (!"DESTRUCT".equals(phase) && !MortalList.isDrainingTopLevelTemporary()) return; + if (!"DESTRUCT".equals(phase)) return; String name = className == null || className.isEmpty() ? NameNormalizer.getBlessStr(referent.blessId) : className; WarnDie.warn(new RuntimeScalar( @@ -756,21 +758,10 @@ private static void warnIfResurrectedDuringGlobalDestruction(RuntimeBase referen } /** - * Process rescued objects at block scope exit (called from {@link MortalList#popAndFlush}). - *

    - * Rescued objects are kept alive during the scope where they were rescued (e.g., during - * the DBIC phantom chain). At block scope exit, we check if they are ready for cleanup: - *

      - *
    • refCount == 1: The rescue container's counted reference is the only one left. - * No code path holds a live reference to the object.
    • - *
    • refCount == MIN_VALUE: The weaken cascade already brought refCount to 0, and - * callDestroy was called but skipped because the object was in rescuedObjects. - * The object is definitely dead and needs cleanup.
    • - *
    - *

    - * For each such object, we remove it from rescuedObjects and call callDestroy, which - * (now that the object is no longer in rescuedObjects) will clear weak refs and cascade - * into elements. This ensures DBIC's leak tracer sees the weak refs as undef. + * Recheck objects preserved after Perl DESTROY because their destructor may have + * installed a new owner slot. The rescue list schedules these checks but is not itself + * a Perl owner. An object with no current Perl owner can finish destruction now; + * otherwise it stays queued until a later owner release. */ public static void processRescuedObjects() { java.util.List rescuedObjects = state().rescuedObjects; @@ -781,21 +772,18 @@ public static void processRescuedObjects() { snapshot = new java.util.ArrayList<>(rescuedObjects); rescuedObjects.clear(); } - MortalList.invalidateExternalRootSnapshot(); boolean anyProcessed = false; for (RuntimeBase obj : snapshot) { - if (obj.destroyFired && (obj.refCount == 1 || obj.refCount == Integer.MIN_VALUE)) { - // Object is dead — either the rescue container was the only reference - // (refCount == 1), or the weaken cascade already triggered callDestroy - // which was skipped (refCount == MIN_VALUE). Clean up now. - obj.refCount = Integer.MIN_VALUE; - callDestroy(obj); // destroyFired=true, NOT in rescuedObjects → clearWeakRefsTo + cascade + if (obj.destroyFired && !hasLivePerlOwnerIdentity(obj)) { + // The rescue list is lifecycle bookkeeping, not an owning + // reference. A positive count can belong to a real promoted + // slot, so only current Perl owner identities decide whether + // the object is still alive. + callDestroy(obj); anyProcessed = true; } else { - // Object still has external references or unexpected state. - // Keep tracking it for later processing. + // Keep tracking it until its last current Perl owner leaves. rescuedObjects.add(obj); - MortalList.invalidateExternalRootSnapshot(); } } if (anyProcessed) { @@ -803,148 +791,10 @@ public static void processRescuedObjects() { } } - /** - * Clear weak refs for all objects that were rescued by DESTROY. - * Called by MortalList.flushDeferredCaptures() before END blocks run. - *

    - * This deferred approach is necessary because clearing weak refs immediately - * after rescue would destroy back-references from sibling objects that are - * still needed (e.g., other ResultSources' $source->{schema} weak refs). - * By deferring until just before END blocks, all test code has finished - * executing and the back-references are no longer needed. - *

    - * For each rescued object: - * 1. Clear its own weak refs (for DBIC's leak tracer registry) - * 2. Deep-sweep its hash contents for nested blessed objects (Storage, DBI::db) - * and clear their weak refs too - */ - public static void clearRescuedWeakRefs() { + private static void removeRescuedObject(RuntimeBase referent) { java.util.List rescuedObjects = state().rescuedObjects; - if (rescuedObjects.isEmpty()) return; - java.util.List snapshot; - synchronized (rescuedObjects) { - snapshot = new java.util.ArrayList<>(rescuedObjects); - rescuedObjects.clear(); - } - MortalList.invalidateExternalRootSnapshot(); - for (RuntimeBase rescued : snapshot) { - WeakRefRegistry.clearWeakRefsTo(rescued); - if (rescued instanceof RuntimeHash hash) { - deepClearWeakRefs(hash); - } - } - } - - /** - * Clear weak refs for one specific object that was rescued by DESTROY. - * Used when user code explicitly undefines that object but the DESTROY body - * self-saves it. Other rescued objects may still be live and must remain - * available until their normal deferred cleanup point. - */ - public static boolean clearRescuedWeakRefsTo(RuntimeBase rescued) { - if (rescued == null) return false; - java.util.List rescuedObjects = state().rescuedObjects; - boolean removed; synchronized (rescuedObjects) { - removed = rescuedObjects.remove(rescued); - } - if (!removed) return false; - MortalList.invalidateExternalRootSnapshot(); - - WeakRefRegistry.clearWeakRefsTo(rescued); - if (rescued instanceof RuntimeHash hash) { - deepClearWeakRefs(hash); - } - return true; - } - - /** - * Clear weak refs to the rescued object itself, but keep the rescued object - * queued for the normal deferred deep cleanup. Explicit {@code undef $obj} - * should make weak refs to {@code $obj} go undef, but if DESTROY rescued the - * object its owned internals are still live and must not have their weak refs - * cleared until the pre-END rescued-object sweep. - */ - public static boolean clearRescuedWeakRefsToSelfOnly(RuntimeBase rescued) { - if (rescued == null) return false; - java.util.List rescuedObjects = state().rescuedObjects; - boolean present; - synchronized (rescuedObjects) { - present = rescuedObjects.contains(rescued); - } - if (!present) return false; - WeakRefRegistry.clearWeakRefsTo(rescued); - return true; - } - - /** - * Clear weak callbacks to objects owned by a rescued aggregate while - * preserving weak back-references to the rescued root itself. - * - *

    DBIx::Class keeps a rescued Schema usable through ResultSource - * back-references after the user's schema lexical is undefined. At the - * same time, a separately retained DBI handle must observe that the nested - * Storage object has gone away and use its fallback HandleError callback. - * The normal final rescued-object sweep still clears the complete graph.

    - */ - public static boolean clearNestedWeakRefsForRescued(RuntimeBase rescued) { - if (!(rescued instanceof RuntimeHash hash)) return false; - java.util.List rescuedObjects = state().rescuedObjects; - synchronized (rescuedObjects) { - if (!rescuedObjects.contains(rescued)) return false; - } - deepClearWeakRefsImpl(hash, 5, rescued); - return true; - } - - /** - * Recursively walk a hash's values and clear weak refs for any blessed - * objects found, including nested hashes and arrays. This is used after - * DESTROY rescue to clear weak refs for objects contained inside the - * rescued object (e.g., Storage::DBI and DBI::db inside a Schema hash). - *

    - * Unlike {@link MortalList#scopeExitCleanupHash}, this method does NOT - * decrement refcounts or trigger DESTROY on the found objects. It only - * clears weak refs. This is critical because the rescued object is still - * alive and its internals must remain intact for future use. - *

    - * Uses a depth limit to avoid infinite recursion on circular references - * (which are common in DBIC — Schema → Storage → DBI::db → Schema). - * - * @param hash The hash to walk - */ - private static void deepClearWeakRefs(RuntimeHash hash) { - deepClearWeakRefsImpl(hash, 5, null); - } - - /** - * Implementation of deep weak-ref clearing with depth limit. - * - * @param hash The hash to walk - * @param maxDepth Maximum recursion depth (prevents infinite loops on circular refs) - */ - private static void deepClearWeakRefsImpl( - RuntimeHash hash, int maxDepth, RuntimeBase excludedRoot) { - if (maxDepth <= 0) return; - for (RuntimeScalar val : hash.elements.values()) { - // Check for any reference type (REFERENCE, HASHREFERENCE, ARRAYREFERENCE, etc.) - // using the REFERENCE_BIT flag. A blessed hash stored as $schema->{storage} - // may have type HASHREFERENCE rather than plain REFERENCE. - if ((val.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && val.value instanceof RuntimeBase base) { - if (base == excludedRoot) continue; - // Clear weak refs for this blessed object (e.g., Storage::DBI, DBI::db). - // Only clear if the object is blessed (blessId != 0) to avoid clearing - // weak refs for plain unblessed containers that might be shared. - if (base.blessId != 0) { - WeakRefRegistry.clearWeakRefsTo(base); - } - // Recurse into nested hashes to find deeper blessed objects - // (e.g., Schema → {storage} → Storage → {_dbh} → DBI::db) - if (base instanceof RuntimeHash nestedHash) { - deepClearWeakRefsImpl(nestedHash, maxDepth - 1, excludedRoot); - } - } + rescuedObjects.remove(referent); } } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/DynamicState.java b/src/main/java/org/perlonjava/runtime/runtimetypes/DynamicState.java index 2fdb182ec3..fa23d9f2b0 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/DynamicState.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/DynamicState.java @@ -44,6 +44,16 @@ public interface DynamicState { */ void dynamicRestoreState(); + /** + * Current Perl object that must remain owned while this state is detached. + * Dynamic aggregate implementations expose their active value so the + * suspend path can acquire its owner identity before removing a package or + * local slot. + */ + default RuntimeBase suspendedOwnerValue() { + return null; + } + /** * Detaches this state while an interpreter frame is suspended. The default * implementation preserves the existing save/restore protocol; state types diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/DynamicVariableManager.java b/src/main/java/org/perlonjava/runtime/runtimetypes/DynamicVariableManager.java index e769dc1453..3bf81f2f7c 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/DynamicVariableManager.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/DynamicVariableManager.java @@ -18,7 +18,8 @@ public class DynamicVariableManager { private static final ThreadLocal DEFER_EXECUTION_DEPTH = ThreadLocal.withInitial(() -> 0); - public record SuspendedState(DynamicState state, Object token) {} + public record SuspendedState( + DynamicState state, Object token, List ownerSlots) {} public record CapturedFrame(T result, List states) {} static final class FrameCapture { @@ -267,18 +268,121 @@ private static List suspendAbove( List result = new ArrayList<>(); while (variableStack.size() > targetLocalLevel) { DynamicState state = variableStack.removeLast(); - result.add(0, new SuspendedState(state, state.dynamicSuspendState())); + List ownerSlots = new ArrayList<>(2); + Object token; + try { + RuntimeBase currentOwner = state.suspendedOwnerValue(); + retainSuspendedOwner(currentOwner, ownerSlots); + token = state.dynamicSuspendState(); + if (token instanceof RuntimeBase tokenOwner && tokenOwner != currentOwner) { + retainSuspendedOwner(tokenOwner, ownerSlots); + } + } catch (Throwable failure) { + // A suspension callback may fail after earlier states have + // already been detached. Restore the current and remaining + // stack states, then retire every temporary owner acquired + // for this incomplete frame capture. + variableStack.addLast(state); + try { + popToLocalLevel(executionState, targetLocalLevel); + } catch (Throwable cleanupFailure) { + failure = cleanupFailure; + } + try { + releaseSuspendedOwners(ownerSlots); + } catch (Throwable releaseFailure) { + failure = releaseFailure; + } + rethrow(releaseSuspendedOwners(result, 0, failure)); + return List.of(); + } + result.add(0, new SuspendedState(state, token, List.copyOf(ownerSlots))); } return result; } - /** Reinstall detached states in their original stack order. */ + private static void retainSuspendedOwner( + RuntimeBase referent, List ownerSlots) { + if (referent == null) return; + PerlOwnerSlot owner = new PerlOwnerSlot(PerlOwnerSlot.Kind.SUSPENDED_FRAME); + owner.acquireSuspendedFrameIdentity(referent); + ownerSlots.add(owner); + } + + private static void releaseSuspendedOwners(List ownerSlots) { + Throwable pendingException = null; + for (int i = ownerSlots.size() - 1; i >= 0; i--) { + try { + ownerSlots.get(i).release(); + } catch (Throwable failure) { + pendingException = failure; + } + } + rethrow(pendingException); + } + + private static Throwable releaseSuspendedOwners( + List states, int firstState, Throwable pendingException) { + for (int i = states.size() - 1; i >= firstState; i--) { + try { + releaseSuspendedOwners(states.get(i).ownerSlots()); + } catch (Throwable failure) { + pendingException = failure; + } + } + return pendingException; + } + + /** + * Reinstall detached states in their original stack order. A restore can + * invoke Perl callbacks, so a failure stops later restores, unwinds the + * current and already reattached states, and releases the remaining + * suspended owners before the failure is propagated. + */ public static void resumeSuspended(List states) { if (states == null) return; Deque variableStack = variableStack(); - for (SuspendedState suspended : states) { - suspended.state().dynamicResumeState(suspended.token()); + int originalLocalLevel = variableStack.size(); + for (int i = 0; i < states.size(); i++) { + SuspendedState suspended = states.get(i); + try { + suspended.state().dynamicResumeState(suspended.token()); + } catch (Throwable failure) { + // Implementations save the callback's current state before + // applying the suspended value, so include the failing state + // in the normal unwind as well. + variableStack.addLast(suspended.state()); + try { + popToLocalLevel(originalLocalLevel); + } catch (Throwable cleanupFailure) { + failure = cleanupFailure; + } + rethrow(releaseSuspendedOwners(states, i, failure)); + return; + } variableStack.addLast(suspended.state()); + try { + releaseSuspendedOwners(suspended.ownerSlots()); + } catch (Throwable failure) { + try { + popToLocalLevel(originalLocalLevel); + } catch (Throwable cleanupFailure) { + failure = cleanupFailure; + } + rethrow(releaseSuspendedOwners(states, i + 1, failure)); + return; + } + } + } + + private static void rethrow(Throwable failure) { + if (failure == null) return; + if (failure instanceof RuntimeException runtimeException) { + throw runtimeException; + } + if (failure instanceof Error error) { + throw error; } + throw new RuntimeException(failure); } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/ExecutionRuntimeState.java b/src/main/java/org/perlonjava/runtime/runtimetypes/ExecutionRuntimeState.java index bd96255253..3948dd0181 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/ExecutionRuntimeState.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/ExecutionRuntimeState.java @@ -16,11 +16,28 @@ /** Per-interpreter execution and dynamic-scope state migrated in Phase 5. */ public final class ExecutionRuntimeState { final PerlRuntime ownerRuntime; + private final IdentityHashMap suspendedContinuations = + new IdentityHashMap<>(); ExecutionRuntimeState(PerlRuntime ownerRuntime) { this.ownerRuntime = ownerRuntime; } + /** Register one live continuation so reset cannot discard its active frame. */ + public synchronized void registerSuspendedContinuation(Object continuation) { + if (continuation != null) suspendedContinuations.put(continuation, Boolean.TRUE); + } + + /** Retire one continuation after its frame owners have been released. */ + public synchronized void unregisterSuspendedContinuation(Object continuation) { + if (continuation != null) suspendedContinuations.remove(continuation); + } + + /** Whether reset would discard a still-live suspended continuation. */ + public synchronized boolean hasSuspendedContinuations() { + return !suspendedContinuations.isEmpty(); + } + /** Set once the interpreter enters its global destruction phase. */ boolean globalDestruction; @@ -39,7 +56,7 @@ public final class ExecutionRuntimeState { final Stack globalScalarStates = new Stack<>(); final Stack globalArrayStates = new Stack<>(); final Stack globalHashStates = new Stack<>(); - final Stack hashProxyStates = new Stack<>(); + final Stack hashProxyStates = new Stack<>(); final Stack arrayProxyIndexStates = new Stack<>(); final Stack arrayProxyStates = new Stack<>(); final Stack arrayProxySavedSizes = new Stack<>(); @@ -73,9 +90,19 @@ public final class ExecutionRuntimeState { public final Deque activeEvalSources = new ArrayDeque<>(); public final ArrayDeque> syntheticCallerFrames = new ArrayDeque<>(); public final Deque argsStack = new ArrayDeque<>(); - /** Weak roots for JVM call arguments while their expressions are evaluated. */ - final ArrayList> callArgumentFrames = + final Deque> argumentAliasOwnerFrames = + new ArrayDeque<>(); + /** Source-frame alias owners awaiting adoption by a tail-call target frame. */ + final Deque pendingTailCallArgumentOwners = + new ArrayDeque<>(); + /** Counted owners for aggregates containing the active aliased argument slots. */ + final Deque> argumentContainerOwnerFrames = + new ArrayDeque<>(); + /** Explicit owners for staged arguments, retired by call completion or frame exit. */ + final ArrayList callArgumentFrames = new ArrayList<>(); + /** Temporary chained-method invocant owners active in the generated caller. */ + final ArrayList methodInvocantHolds = new ArrayList<>(); public final Deque activeCodeStack = new ArrayDeque<>(); /** Perl source callsites aligned with the active Perl code frames. */ public final Deque activeCodeCallSites = new ArrayDeque<>(); @@ -85,6 +112,8 @@ public final class ExecutionRuntimeState { public final Deque activeJvmSelfReferences = new ArrayDeque<>(); /** Sort pseudo-block state for active JVM-generated Perl methods. */ public final Deque activeJvmSortComparators = new ArrayDeque<>(); + /** Dynamic state captured at entry to JVM-generated Perl method frames. */ + public final Deque activeJvmFrameSnapshots = new ArrayDeque<>(); /** Dynamic extent of a sort comparator invocation, including called subs. */ public int activeSortComparatorInvocations; /** Combined Perl frame depth immediately before each sort comparator call. */ @@ -99,6 +128,8 @@ public final class ExecutionRuntimeState { public Object reusableActiveLexicalFrame; /** Lexical cells owned by the top-level compilation unit. */ public final Map topLevelLexicals = new LinkedHashMap<>(); + /** Owner identities for aggregate cells held by top-level lexical names. */ + final Map topLevelLexicalOwnerSlots = new LinkedHashMap<>(); public final Deque> pristineArgsStack = new ArrayDeque<>(); /** Reusable one-scalar return lists, populated only after scalar extraction. */ final Deque availableScalarResultLists = new ArrayDeque<>(); @@ -123,7 +154,6 @@ public final class ExecutionRuntimeState { public boolean taintMode; public boolean taintWarnings; public boolean joinTaint; - public int moduleInitDepth; public final IdentityHashMap unhandledDieHandlerSeen = new IdentityHashMap<>(); public boolean insideUnhandledDieHandler; @@ -139,7 +169,6 @@ public final class ExecutionRuntimeState { final ArrayList myVarCleanupStack = new ArrayList<>(); final IdentityHashMap registeredMyVarCounts = new IdentityHashMap<>(); - final IdentityHashMap liveMyVarCounts = new IdentityHashMap<>(); private final IdentityHashMap callDepths = new IdentityHashMap<>(); private RuntimeCode lastCallDepthCode; diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalDestruction.java b/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalDestruction.java index a7cc2b8656..7898a34804 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalDestruction.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalDestruction.java @@ -11,7 +11,7 @@ * Handles global destruction at program exit. *

    * Walks all package stashes and global variables to find blessed objects - * with refCount >= 0 that still need DESTROY. This covers globals, stash + * whose count tracking is active and still need DESTROY. This covers globals, stash * entries, and values inside global arrays and hashes. *

    * Matches Perl 5 behavior where global destruction runs after END blocks. @@ -23,16 +23,15 @@ public class GlobalDestruction { * on any tracked blessed references that haven't been destroyed yet. */ public static void runGlobalDestruction() { - runGlobalDestruction(true); - } - - /** Run global destruction, optionally scanning otherwise unreachable cycles. */ - public static void runGlobalDestruction(boolean scanUnrootedCycles) { // Set ${^GLOBAL_PHASE} to "DESTRUCT" PerlRuntime.current().executionState.globalDestruction = true; GlobalVariable.getGlobalVariable(GlobalContext.GLOBAL_PHASE).set("DESTRUCT"); Set visited = Collections.newSetFromMap(new IdentityHashMap<>()); + Set deferredCodeCleanup = + Collections.newSetFromMap(new IdentityHashMap<>()); + MortalList.CleanupTargetProbe cleanupTargetProbe = + new MortalList.CleanupTargetProbe(); // Snapshot the collections before iterating: a DESTROY callback may // mutate GlobalVariable.{globalVariables,globalArrays,globalHashes} @@ -44,7 +43,7 @@ public static void runGlobalDestruction(boolean scanUnrootedCycles) { // Walk all global scalars for (RuntimeScalar val : new ArrayList<>(GlobalVariable.scalarSlots().values())) { - destroyIfTracked(val, visited); + destroyIfTracked(val, visited, deferredCodeCleanup, cleanupTargetProbe); } // CODE slots are kept in a separate namespace map from ordinary @@ -54,7 +53,7 @@ public static void runGlobalDestruction(boolean scanUnrootedCycles) { if (code != null && code.value instanceof RuntimeCode runtimeCode) { runtimeCode.releaseCaptures(); } - destroyIfTracked(code, visited); + destroyIfTracked(code, visited, deferredCodeCleanup, cleanupTargetProbe); } // Walk global arrays for blessed ref elements @@ -72,7 +71,7 @@ public static void runGlobalDestruction(boolean scanUnrootedCycles) { continue; } for (RuntimeScalar elem : new ArrayList<>(arr.elements)) { - destroyIfTracked(elem, visited); + destroyIfTracked(elem, visited, deferredCodeCleanup, cleanupTargetProbe); } } @@ -90,24 +89,7 @@ public static void runGlobalDestruction(boolean scanUnrootedCycles) { continue; } for (RuntimeScalar elem : new ArrayList<>(hash.elements.values())) { - destroyIfTracked(elem, visited); - } - } - - // File-scope lexical roots can disappear before this pass while - // leaving blessed objects in reference cycles. Perl still invokes - // their DESTROY methods during global destruction. The runtime keeps - // weak records of all live objects whose classes define DESTROY; - // these records find cycle members without extending their lifetime. - // Use the same visited set so objects reached through both package - // roots and the cycle registry are dispatched only once. - if (scanUnrootedCycles) { - ReachabilityWalker.RootReachabilitySnapshot perlRoots = - ReachabilityWalker.reachableFromRootsSnapshotWithStatus(); - for (RuntimeBase object : DestroyDispatch.snapshotGlobalDestroyables()) { - if (!perlRoots.isReachable(object)) { - destroyBaseIfTracked(object, visited); - } + destroyIfTracked(elem, visited, deferredCodeCleanup, cleanupTargetProbe); } } @@ -118,6 +100,15 @@ public static void runGlobalDestruction(boolean scanUnrootedCycles) { // RuntimeIO.closeAllHandles() closes the stream. destroyStandardOutputHandle(visited); + // Let blessed objects in package aggregates finish DESTROY before + // releasing the CODE slots their methods use. Global stashes and + // method caches are walked in an order where eager CV cleanup here + // would clear imported direct-call owners before objects in global + // arrays and hashes receive their destructor call. + MortalList.flush(); + for (RuntimeCode code : deferredCodeCleanup) { + DestroyDispatch.callDestroy(code); + } // Releasing a global closure can enqueue the final decrement for a // captured lexical. Drain that decrement before global teardown ends. MortalList.flush(); @@ -141,51 +132,62 @@ private static void destroyStandardOutputHandle(Set visited) { stdout.setBlessId(blessId); } if (!visited.add(stdout)) return; - stdout.refCount = Integer.MIN_VALUE; DestroyDispatch.callDestroy(stdout); } /** * Call DESTROY on a scalar if it holds a tracked blessed reference. */ - private static void destroyIfTracked(RuntimeScalar val, Set visited) { + private static void destroyIfTracked( + RuntimeScalar val, + Set visited, + Set deferredCodeCleanup, + MortalList.CleanupTargetProbe cleanupTargetProbe) { if (val != null && (val.type & RuntimeScalarType.REFERENCE_BIT) != 0 && val.value instanceof RuntimeBase base // A global object can be blessed before its class installs // DESTROY. Its initial transient cleanup then leaves the - // object untracked (or at MIN_VALUE), but a later method + // object untracked, but a later method // definition must still be observed at global destruction. - && (base.refCount >= 0 || (base.blessId != 0 && !base.destroyFired))) { - destroyBaseIfTracked(base, visited); + && (base.isRefCountTracked() || (base.blessId != 0 && !base.destroyFired))) { + destroyBaseIfTracked(base, visited, deferredCodeCleanup, cleanupTargetProbe); } } - private static void destroyBaseIfTracked(RuntimeBase base, Set visited) { + private static void destroyBaseIfTracked( + RuntimeBase base, + Set visited, + Set deferredCodeCleanup, + MortalList.CleanupTargetProbe cleanupTargetProbe) { if (base == null - || (base.refCount < 0 && (base.blessId == 0 || base.destroyFired)) + || (!base.isRefCountTracked() && (base.blessId == 0 || base.destroyFired)) || !visited.add(base)) { return; } - if (base.blessId != 0 || WeakRefRegistry.hasWeakRefsTo(base) || base instanceof RuntimeCode) { - if (base instanceof RuntimeCode code) { - // A global named subroutine can be the last owner of a - // closure's lexical pad. Release that pad before dispatching - // destruction so objects held only by captured lexicals are - // also finalized during global destruction. - code.releaseCaptures(); + if (base instanceof RuntimeCode code) { + code.releaseCaptures(); + if (base.blessId == 0) { + // Methods remain callable while global aggregates dispatch + // destructors. Retire their state only after those roots have + // had their final DESTROY opportunity. + deferredCodeCleanup.add(code); + return; } - base.refCount = Integer.MIN_VALUE; + } + if (base.blessId != 0 || WeakRefRegistry.hasWeakRefsTo(base) || base instanceof RuntimeCode) { DestroyDispatch.callDestroy(base); return; } - if (base instanceof RuntimeArray arr && MortalList.containerMayContainCleanupTargets(base)) { + if (base instanceof RuntimeArray arr + && cleanupTargetProbe.mayContainCleanupTargets(base)) { for (RuntimeScalar elem : new ArrayList<>(arr.elements)) { - destroyIfTracked(elem, visited); + destroyIfTracked(elem, visited, deferredCodeCleanup, cleanupTargetProbe); } - } else if (base instanceof RuntimeHash hash && MortalList.containerMayContainCleanupTargets(base)) { + } else if (base instanceof RuntimeHash hash + && cleanupTargetProbe.mayContainCleanupTargets(base)) { for (RuntimeScalar elem : new ArrayList<>(hash.elements.values())) { - destroyIfTracked(elem, visited); + destroyIfTracked(elem, visited, deferredCodeCleanup, cleanupTargetProbe); } } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalRuntimeArray.java b/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalRuntimeArray.java index 80e28db625..795c0399a6 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalRuntimeArray.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalRuntimeArray.java @@ -66,8 +66,17 @@ public void dynamicSaveState() { } } + @Override + public RuntimeBase suspendedOwnerValue() { + return GlobalVariable.getGlobalArray(fullName); + } + @Override public void dynamicRestoreState() { + restoreState(false); + } + + private void restoreState(boolean preserveSuspendedArray) { Stack localizedStack = localizedStack(); if (!localizedStack.isEmpty()) { SavedGlobalArrayState saved = localizedStack.peek(); @@ -80,10 +89,9 @@ public void dynamicRestoreState() { // discarded. Test: postfixderef.t #38 "no stooges outlast // their scope". RuntimeArray localArray = GlobalVariable.globalArrays.get(saved.fullName); - if (localArray != null && localArray.blessId != 0 + if (!preserveSuspendedArray && localArray != null && localArray.blessId != 0 && !localArray.destroyFired && (saved.originalArray == null || localArray != saved.originalArray)) { - localArray.refCount = Integer.MIN_VALUE; DestroyDispatch.callDestroy(localArray); } @@ -91,7 +99,8 @@ public void dynamicRestoreState() { // Release references held by the temporary localized array // before discarding it, matching RuntimeArray's local-scope // restoration path. - if (localArray != null && localArray != saved.originalArray) { + if (!preserveSuspendedArray && localArray != null + && localArray != saved.originalArray) { // A $# proxy made inside local @array belongs to the // discarded temporary AV, not the restored package array. localArray.orphanArraySizeLvalues(); @@ -119,26 +128,20 @@ public void dynamicRestoreState() { @Override public Object dynamicSuspendState() { RuntimeArray activeVariable = GlobalVariable.getGlobalArray(fullName); - RuntimeArray activeState = new RuntimeArray(); - if (activeVariable != null) { - activeState.type = activeVariable.type; - activeState.blessId = activeVariable.blessId; - activeState.scalarContextSize = activeVariable.scalarContextSize; - activeState.elements.addAll(activeVariable.elements); - } - dynamicRestoreState(); - return activeState; + restoreState(true); + return activeVariable; } @Override public void dynamicResumeState(Object token) { dynamicSaveState(); - if (token instanceof RuntimeArray activeState) { - RuntimeArray activeVariable = GlobalVariable.getGlobalArray(fullName); - activeVariable.type = activeState.type; - activeVariable.blessId = activeState.blessId; - activeVariable.scalarContextSize = activeState.scalarContextSize; - activeVariable.elements.addAll(activeState.elements); + if (token instanceof RuntimeArray activeVariable) { + GlobalVariable.globalArrays.put(fullName, activeVariable); + for (String alias : GlobalVariable.getGlobAliasGroup(fullName)) { + if (!alias.equals(fullName)) { + GlobalVariable.globalArrays.put(alias, activeVariable); + } + } } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalRuntimeHash.java b/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalRuntimeHash.java index a68aa8796f..392dec54a2 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalRuntimeHash.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalRuntimeHash.java @@ -59,8 +59,17 @@ public void dynamicSaveState() { } } + @Override + public RuntimeBase suspendedOwnerValue() { + return GlobalVariable.getGlobalHash(fullName); + } + @Override public void dynamicRestoreState() { + restoreState(false); + } + + private void restoreState(boolean preserveSuspendedHash) { Stack localizedStack = localizedStack(); if (!localizedStack.isEmpty()) { SavedGlobalHashState saved = localizedStack.peek(); @@ -70,10 +79,9 @@ public void dynamicRestoreState() { // Fire DESTROY if the local hash was blessed during the scope. // Test: postfixderef.t #38 "no stooges outlast their scope". RuntimeHash localHash = GlobalVariable.globalHashes.get(saved.fullName); - if (localHash != null && localHash.blessId != 0 + if (!preserveSuspendedHash && localHash != null && localHash.blessId != 0 && !localHash.destroyFired && (saved.originalHash == null || localHash != saved.originalHash)) { - localHash.refCount = Integer.MIN_VALUE; DestroyDispatch.callDestroy(localHash); } @@ -83,7 +91,8 @@ public void dynamicRestoreState() { // local %hash (notably Test::Deep's %WrapCache) can retain // weakly-referenced arguments past the scope that localized // it. - if (localHash != null && localHash != saved.originalHash) { + if (!preserveSuspendedHash && localHash != null + && localHash != saved.originalHash) { MortalList.deferDestroyForContainerClear(localHash.elements.values()); } GlobalVariable.globalHashes.put(saved.fullName, saved.originalHash); @@ -102,28 +111,20 @@ public void dynamicRestoreState() { @Override public Object dynamicSuspendState() { RuntimeHash activeVariable = GlobalVariable.getGlobalHash(fullName); - RuntimeHash activeState = new RuntimeHash(); - if (activeVariable != null) { - activeState.type = activeVariable.type; - activeState.blessId = activeVariable.blessId; - activeState.byteKeys = activeVariable.byteKeys != null - ? new java.util.HashSet<>(activeVariable.byteKeys) : null; - activeState.elements.putAll(activeVariable.elements); - } - dynamicRestoreState(); - return activeState; + restoreState(true); + return activeVariable; } @Override public void dynamicResumeState(Object token) { dynamicSaveState(); - if (token instanceof RuntimeHash activeState) { - RuntimeHash activeVariable = GlobalVariable.getGlobalHash(fullName); - activeVariable.type = activeState.type; - activeVariable.blessId = activeState.blessId; - activeVariable.byteKeys = activeState.byteKeys != null - ? new java.util.HashSet<>(activeState.byteKeys) : null; - activeVariable.elements.putAll(activeState.elements); + if (token instanceof RuntimeHash activeVariable) { + GlobalVariable.globalHashes.put(fullName, activeVariable); + for (String alias : GlobalVariable.getGlobAliasGroup(fullName)) { + if (!alias.equals(fullName)) { + GlobalVariable.globalHashes.put(alias, activeVariable); + } + } } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalRuntimeScalar.java b/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalRuntimeScalar.java index 61b73e7919..49f38ca60b 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalRuntimeScalar.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalRuntimeScalar.java @@ -160,6 +160,11 @@ public void dynamicSaveState() { } else { newLocal = new GlobalRuntimeScalar(fullName); } + // The temporary scalar is installed in the package scalar table for + // the duration of local(). Treat it as a durable package slot so + // assignment acquires value and anonymous-IO owners just as it does + // for the original global scalar. + newLocal.isPackageGlobalRoot = true; String savedRuntimeWarningBits = fullName.equals(GlobalContext.WARNING_SCOPE) ? WarningBitsRegistry.getRuntimeWarningBits() : null; @@ -204,93 +209,113 @@ public void dynamicRestoreState() { GlobalVariable.clearForeachGlobalAlias(saved.fullName); RuntimeScalar localVar = saved.localizedVariable; RuntimeBase displacedBase = null; - RuntimeScalar scalarReferenceContents = null; + PerlOwnerSlot scalarContentsOwner = null; + // The localized package scalar owns its anonymous IO holder + // independently of the value saved from the outer slot. + // Retire that holder before restoring the original scalar. + RuntimeScalar.releaseIoOwner(localVar); // Release container-owned values only when this localized // scalar is dropping the container's last counted owner. A // localized alias to a still-live request or cache must not // release its fields while another Perl owner can still use // them (Dancer2 uploads keep their File::Temp handle there). - boolean releasesLastContainerOwner = localVar != null + PerlOwnerSlot localValueOwner = localVar == null + ? null : localVar.countedOwnerSlot(); + boolean releasesLastPerlOwner = localVar != null && localVar.refCountOwned && (localVar.type & RuntimeScalarType.REFERENCE_BIT) != 0 && localVar.value instanceof RuntimeBase localBase - && localBase.refCount == 1 - && !localBase.localBindingExists; - if (releasesLastContainerOwner && localVar.value instanceof RuntimeHash localHash) { - MortalList.deferDestroyForContainerClear(localHash.elements.values()); - } else if (releasesLastContainerOwner && localVar.value instanceof RuntimeArray localArray) { - MortalList.deferDestroyForContainerClear(localArray.elements); - } - if (localVar != null + && localValueOwner != null + && localValueOwner.isActive() + && localValueOwner.referent() == localBase + && !localBase.hasCurrentPerlOwnerIdentityOtherThan(localValueOwner); + boolean releaseDisplacedCountedOwner = localVar != null && localVar.refCountOwned && (localVar.type & RuntimeScalarType.REFERENCE_BIT) != 0 && localVar.value instanceof RuntimeBase base - && base.refCount > 0) { - displacedBase = base; - localVar.refCountOwned = false; - displacedBase.releaseActiveOwner(localVar); - } - if (localVar != null - && localVar.ownsScalarReferenceContents - && localVar.type == RuntimeScalarType.REFERENCE - && localVar.value instanceof RuntimeScalar scalarReferent) { - scalarReferenceContents = scalarReferent; + && localValueOwner != null + && localValueOwner.isActive() + && localValueOwner.referent() == base; + if (releaseDisplacedCountedOwner) { + displacedBase = (RuntimeBase) localVar.value; + MortalList.pushMark(); } + try { + boolean releasesLastContainerOwner = releasesLastPerlOwner + && (localVar.value instanceof RuntimeArray + || localVar.value instanceof RuntimeHash); + if (releasesLastContainerOwner + && localVar.value instanceof RuntimeHash localHash) { + MortalList.deferDestroyForContainerClear(localHash.elements.values()); + } else if (releasesLastContainerOwner + && localVar.value instanceof RuntimeArray localArray) { + MortalList.deferDestroyForContainerClear(localArray.elements); + } + if (releaseDisplacedCountedOwner) { + MortalList.deferDecrementFromScalarSlot( + displacedBase, localVar, "GlobalRuntimeScalar.dynamicRestoreState"); + } + if (localVar != null && localVar.hasScalarReferenceContentsOwner()) { + scalarContentsOwner = localVar.scalarReferenceContentsOwner; + } - // Restore the internal separator values if this was an output separator variable - if (saved.originalVariable instanceof OutputRecordSeparator) { - OutputRecordSeparator.restoreInternalORS(); - } else if (saved.originalVariable instanceof OutputFieldSeparator) { - OutputFieldSeparator.restoreInternalOFS(); - } + // Restore the internal separator values if this was an output separator variable + if (saved.originalVariable instanceof OutputRecordSeparator) { + OutputRecordSeparator.restoreInternalORS(); + } else if (saved.originalVariable instanceof OutputFieldSeparator) { + OutputFieldSeparator.restoreInternalOFS(); + } - // Restore the original variable in the global symbol table - GlobalVariable.scalarSlots().put(saved.fullName, saved.originalVariable); + // Restore the original variable in the global symbol table + GlobalVariable.scalarSlots().put(saved.fullName, saved.originalVariable); - if (saved.fullName.equals(GlobalContext.WARNING_SCOPE)) { - WarningBitsRegistry.setRuntimeWarningBits(saved.savedRuntimeWarningBits); - } + if (saved.fullName.equals(GlobalContext.WARNING_SCOPE)) { + WarningBitsRegistry.setRuntimeWarningBits(saved.savedRuntimeWarningBits); + } - // Also restore all glob aliases to the original shared variable - java.util.List aliasGroup = GlobalVariable.getGlobAliasGroup(saved.fullName); - for (String alias : aliasGroup) { - if (!alias.equals(saved.fullName)) { - GlobalVariable.scalarSlots().put(alias, saved.originalVariable); + // Also restore all glob aliases to the original shared variable + java.util.List aliasGroup = GlobalVariable.getGlobAliasGroup(saved.fullName); + for (String alias : aliasGroup) { + if (!alias.equals(saved.fullName)) { + GlobalVariable.scalarSlots().put(alias, saved.originalVariable); + } } - } - // Decrement refCount of the displaced local value after restoring - // the global slot, so DESTROY sees the restored variable state. - boolean displacedWillDestroy = false; - if (displacedBase != null && displacedBase.refCount == 1) { - String className = NameNormalizer.getBlessStr(displacedBase.blessId); - displacedWillDestroy = className != null && !className.isEmpty() - && DestroyDispatch.classHasDestroy(displacedBase.blessId, className); - } - if ((displacedWillDestroy || scalarReferenceContents != null) - && localVar != null && localVar != saved.originalVariable) { - // Compiled code may still hold the localized scalar object - // directly. Mirror the restored value into it just before - // DESTROY so both lookup paths observe the restored state. - if (saved.originalVariable == null) { - localVar.type = RuntimeScalarType.UNDEF; - localVar.value = null; - localVar.blessId = 0; - } else { - localVar.type = saved.originalVariable.type; - localVar.value = saved.originalVariable.value; - localVar.blessId = saved.originalVariable.blessId; + // Decrement the displaced local value after restoring the + // global slot, so DESTROY sees the restored variable state. + boolean displacedWillDestroy = false; + if (displacedBase != null && displacedBase.refCount == 1 + && releasesLastPerlOwner) { + String className = NameNormalizer.getBlessStr(displacedBase.blessId); + displacedWillDestroy = className != null && !className.isEmpty() + && DestroyDispatch.classHasDestroy(displacedBase.blessId, className); } - localVar.refCountOwned = false; - } - if (localVar != null) { - localVar.ownsScalarReferenceContents = false; - } - RuntimeScalar.releaseScalarReferenceContents(scalarReferenceContents); - if (displacedBase != null && displacedBase.refCount > 0 - && --displacedBase.refCount == 0) { - displacedBase.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(displacedBase); + if ((displacedWillDestroy || scalarContentsOwner != null) + && localVar != null && localVar != saved.originalVariable) { + // Compiled code may still hold the localized scalar object + // directly. Mirror the restored value into it just before + // DESTROY so both lookup paths observe the restored state. + if (saved.originalVariable == null) { + localVar.type = RuntimeScalarType.UNDEF; + localVar.value = null; + localVar.blessId = 0; + } else { + localVar.type = saved.originalVariable.type; + localVar.value = saved.originalVariable.value; + localVar.blessId = saved.originalVariable.blessId; + } + localVar.refCountOwned = false; + } + if (localVar != null) { + localVar.scalarReferenceContentsOwner = null; + localVar.isPackageGlobalRoot = false; + } + if (scalarContentsOwner != null) { + scalarContentsOwner.releaseScalarReferenceContents(); + } + if (releaseDisplacedCountedOwner) MortalList.flushAboveMark(); + } finally { + if (releaseDisplacedCountedOwner) MortalList.popMark(); } } } @@ -301,6 +326,15 @@ public Object dynamicSuspendState() { RuntimeScalar activeVariable = GlobalVariable.getGlobalVariable(fullName); RuntimeScalar activeState = activeVariable != null ? new RuntimeScalar(activeVariable) : new RuntimeScalar(); + if (activeVariable != null) { + RuntimeScalar.transferIoOwner(activeVariable, activeState); + activeState.scalarReferenceContentsOwner = activeVariable.scalarReferenceContentsOwner; + if (activeState.scalarReferenceContentsOwner != null) { + activeState.scalarReferenceContentsOwner + .transferScalarReferenceContentsOwner(activeState); + } + activeVariable.scalarReferenceContentsOwner = null; + } boolean tied = activeVariable != null && activeVariable.type == RuntimeScalarType.TIED_SCALAR; RuntimeScalar tiedValue = tied ? activeVariable.tiedFetch() : null; @@ -321,8 +355,15 @@ public void dynamicResumeState(Object token) { RuntimeScalar activeState = suspended.value; activeVariable.type = activeState.type; activeVariable.value = activeState.value; + RuntimeScalar.transferIoOwner(activeState, activeVariable); activeVariable.blessId = activeState.blessId; - activeVariable.ownsScalarReferenceContents = activeState.ownsScalarReferenceContents; + activeVariable.scalarReferenceContentsOwner = + activeState.scalarReferenceContentsOwner; + activeState.scalarReferenceContentsOwner = null; + if (activeVariable.scalarReferenceContentsOwner != null) { + activeVariable.scalarReferenceContentsOwner + .transferScalarReferenceContentsOwner(activeVariable); + } activeVariable.referencedByScalarReference = activeState.referencedByScalarReference; activeVariable.tainted = activeState.tainted; activeVariable.numericLiteralText = activeState.numericLiteralText; diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalRuntimeState.java b/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalRuntimeState.java index 962308a5c1..ca6932c4df 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalRuntimeState.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalRuntimeState.java @@ -2,10 +2,12 @@ import org.perlonjava.backend.jvm.CustomClassLoader; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.HashSet; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; @@ -24,8 +26,11 @@ public final class GlobalRuntimeState { private static final AtomicInteger NEXT_THREAD_COMPILED_CODE_REF_BASE = new AtomicInteger(COMPILED_CODE_REF_RANGE_SIZE); private final Map scalarValues = new HashMap<>(); + private final Map packageScalarOwnerSlots = new HashMap<>(); private final Map arrayValues = new HashMap<>(); + private final Map packageArrayOwnerSlots = new HashMap<>(); private final Map hashValues = new HashMap<>(); + private final Map packageHashOwnerSlots = new HashMap<>(); private final Map foreachScalarAliases = new HashMap<>(); private final Map temporaryScalarAliases = new HashMap<>(); private final Map importedSubs = new HashMap<>(); @@ -40,10 +45,14 @@ public final class GlobalRuntimeState { private final Map pinnedCodeRefs = new HashMap<>(); private final Set deletedCodeRefPins = new HashSet<>(); private final Map compiledCodeRefs = new HashMap<>(); + /** Weak observers dispatch visible CODE-slot changes to their owning optrees. */ + private final Map>> + compiledDirectCallSites = new HashMap<>(); private final Map localizedCodeRefDepth = new HashMap<>(); - private final IdentityHashMap displacedLocalizedCodeRefs = + private final IdentityHashMap> displacedLocalizedCodeRefs = new IdentityHashMap<>(); private final Map ioSlots = new HashMap<>(); + private final Map packageIoGlobOwnerSlots = new HashMap<>(); private final Map formatSlots = new HashMap<>(); private final Set hiddenIoSlotsAfterStashDelete = new HashSet<>(); /** Packages whose current stashes were made anonymous by undef %Pkg::. */ @@ -73,13 +82,6 @@ public final class GlobalRuntimeState { private int nextCompiledCodeRefId = 1; private long stashEnumerationVersion; private long codeRefVersion; - private long codeRefGraphVersion; - private long cachedInstalledCodeRefsVersion = -1; - private Set cachedInstalledCodeRefs; - private long cachedCodeRefEdgeRootsVersion = -1; - private long cachedCodeRefEdgeRootsCodeVersion = -1; - private List cachedCodeRefEdgeRoots; - private java.util.ArrayList cachedCodeRefEdgeRootValues; private long cachedStashEnumerationVersion = -1; private boolean coreGlobalsInitialized; private final AtomicLong scalarBindingVersion = new AtomicLong(); @@ -89,6 +91,67 @@ public Map scalarValues() { return scalarValues; } + Map packageScalarOwnerSlots() { + return packageScalarOwnerSlots; + } + + void rebuildPackageScalarOwnerSlots() { + for (PerlOwnerSlot ownerSlot : packageScalarOwnerSlots.values()) { + RuntimeScalar previous = ownerSlot.referent() instanceof RuntimeScalar scalar + ? scalar : null; + ownerSlot.release(); + if (previous != null) previous.refreshUntrackedReferenceOwner(); + } + packageScalarOwnerSlots.clear(); + for (Map.Entry entry : scalarValues.entrySet()) { + RuntimeScalar scalar = entry.getValue(); + if (scalar == null) continue; + PerlOwnerSlot ownerSlot = new PerlOwnerSlot( + PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT); + ownerSlot.acquirePackageScalarIdentity(scalar); + packageScalarOwnerSlots.put(entry.getKey(), ownerSlot); + scalar.refreshUntrackedReferenceOwner(); + } + } + + Map packageArrayOwnerSlots() { + return packageArrayOwnerSlots; + } + + Map packageHashOwnerSlots() { + return packageHashOwnerSlots; + } + + void rebuildPackageAggregateOwnerSlots() { + releasePackageAggregateOwnerSlots(packageArrayOwnerSlots, false); + releasePackageAggregateOwnerSlots(packageHashOwnerSlots, false); + rebuildPackageAggregateOwnerSlots(arrayValues, packageArrayOwnerSlots); + rebuildPackageAggregateOwnerSlots(hashValues, packageHashOwnerSlots); + } + + private static void rebuildPackageAggregateOwnerSlots( + Map values, + Map slots) { + for (Map.Entry entry : values.entrySet()) { + RuntimeBase aggregate = entry.getValue(); + if (aggregate == null) continue; + PerlOwnerSlot ownerSlot = new PerlOwnerSlot( + PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT); + ownerSlot.acquirePackageAggregateIdentity(aggregate); + slots.put(entry.getKey(), ownerSlot); + } + } + + private static void releasePackageAggregateOwnerSlots( + Map slots, boolean finalRelease) { + for (PerlOwnerSlot ownerSlot : slots.values()) { + RuntimeBase aggregate = ownerSlot.referent(); + ownerSlot.release(); + if (finalRelease) WeakRefRegistry.onStrongOwnerSlotReleased(aggregate); + } + slots.clear(); + } + long scalarBindingVersion() { return scalarBindingVersion.get(); } @@ -156,11 +219,73 @@ synchronized RuntimeScalar getCompiledCodeRef(int id) { return compiledCodeRefs.get(id); } + synchronized void registerCompiledDirectCallSite( + String key, CompiledDirectCallSite callSite) { + if (key == null || callSite == null) return; + ArrayList> sites = + compiledDirectCallSites.computeIfAbsent(key, ignored -> new ArrayList<>()); + for (WeakReference reference : sites) { + if (reference.get() == callSite) return; + } + sites.add(new WeakReference<>(callSite)); + } + + synchronized void unregisterCompiledDirectCallSite(CompiledDirectCallSite callSite) { + if (callSite == null) return; + compiledDirectCallSites.values().removeIf(sites -> { + sites.removeIf(reference -> { + CompiledDirectCallSite value = reference.get(); + return value == null || value == callSite; + }); + return sites.isEmpty(); + }); + } + + synchronized CompiledDirectCallSite findCompiledDirectCallSite(String key, int siteIndex) { + ArrayList> sites = compiledDirectCallSites.get(key); + if (sites == null) return null; + CompiledDirectCallSite match = null; + var iterator = sites.iterator(); + while (iterator.hasNext()) { + CompiledDirectCallSite site = iterator.next().get(); + if (site == null) { + iterator.remove(); + } else if (site.index() == siteIndex) { + // A pad-constant tree can transfer from a compiled body to its + // published CV. The latest live registration owns that transfer. + match = site; + } + } + if (sites.isEmpty()) compiledDirectCallSites.remove(key); + return match; + } + + void notifyCompiledDirectCallSites( + String key, RuntimeScalar previous, RuntimeScalar replacement) { + if (key == null) return; + ArrayList live = new ArrayList<>(); + synchronized (this) { + ArrayList> sites = + compiledDirectCallSites.get(key); + if (sites == null) return; + sites.removeIf(reference -> { + CompiledDirectCallSite site = reference.get(); + if (site == null) return true; + live.add(site); + return false; + }); + if (sites.isEmpty()) compiledDirectCallSites.remove(key); + } + for (CompiledDirectCallSite site : live) { + site.visibleCodeSlotChanged(previous, replacement); + } + } + Map localizedCodeRefDepth() { return localizedCodeRefDepth; } - IdentityHashMap displacedLocalizedCodeRefs() { + IdentityHashMap> displacedLocalizedCodeRefs() { return displacedLocalizedCodeRefs; } @@ -168,6 +293,28 @@ Map ioSlots() { return ioSlots; } + Map packageIoGlobOwnerSlots() { + return packageIoGlobOwnerSlots; + } + + void rebuildPackageIoGlobOwnerSlots() { + releasePackageIoGlobOwnerSlots(); + for (Map.Entry entry : ioSlots.entrySet()) { + RuntimeGlob glob = entry.getValue(); + if (glob == null || hiddenIoSlotsAfterStashDelete.contains(entry.getKey())) continue; + PerlOwnerSlot ownerSlot = new PerlOwnerSlot(PerlOwnerSlot.Kind.PACKAGE_GLOB_SLOT); + ownerSlot.acquirePackageGlobIdentity(glob); + packageIoGlobOwnerSlots.put(entry.getKey(), ownerSlot); + } + } + + void releasePackageIoGlobOwnerSlots() { + for (PerlOwnerSlot ownerSlot : packageIoGlobOwnerSlots.values()) { + ownerSlot.release(); + } + packageIoGlobOwnerSlots.clear(); + } + Map formatSlots() { return formatSlots; } @@ -279,6 +426,7 @@ void cachedStashEnumerationVersion(long version) { synchronized int registerCompiledCodeRef(RuntimeScalar ref) { int id = nextCompiledCodeRefId++; + if (ref != null) ref.retainCodeSlotBinding(); compiledCodeRefs.put(id, ref); return id; } @@ -295,82 +443,10 @@ long codeRefVersion() { return codeRefVersion; } - void invalidateCodeRefs() { + void noteCodeRefMutation() { codeRefVersion++; } - void noteCodeRefMutation(RuntimeScalar previous, RuntimeScalar replacement) { - boolean canUpdateCachedRoots = cachedCodeRefEdgeRootValues != null - && cachedCodeRefEdgeRootsCodeVersion == codeRefVersion - && cachedCodeRefEdgeRootsVersion == codeRefGraphVersion; - codeRefVersion++; - if (!canUpdateCachedRoots) { - cachedCodeRefEdgeRoots = null; - cachedCodeRefEdgeRootValues = null; - cachedCodeRefEdgeRootsCodeVersion = -1; - cachedCodeRefEdgeRootsVersion = -1; - return; - } - - if (previous != null) { - for (int i = 0; i < cachedCodeRefEdgeRootValues.size(); i++) { - if (cachedCodeRefEdgeRootValues.get(i) == previous) { - cachedCodeRefEdgeRootValues.remove(i); - break; - } - } - } - if (isCodeRefEdgeRoot(replacement)) { - cachedCodeRefEdgeRootValues.add(replacement); - } - cachedCodeRefEdgeRootsCodeVersion = codeRefVersion; - } - - private static boolean isCodeRefEdgeRoot(RuntimeScalar scalar) { - if (scalar == null) return false; - return !(scalar.value instanceof RuntimeCode code) - || ReachabilityWalker.hasWalkableCodeEdges(code, true); - } - - /** Identity set of globally installed RuntimeCode values, cached by slot version. */ - Set installedCodeRefs() { - if (cachedInstalledCodeRefs == null - || cachedInstalledCodeRefsVersion != codeRefVersion) { - Set installed = Collections.newSetFromMap(new IdentityHashMap<>()); - for (RuntimeScalar scalar : codeRefs.values()) { - if (scalar != null - && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && scalar.value instanceof RuntimeCode code) { - installed.add(code); - } - } - cachedInstalledCodeRefs = Collections.unmodifiableSet(installed); - cachedInstalledCodeRefsVersion = codeRefVersion; - } - return cachedInstalledCodeRefs; - } - - void invalidateCodeRefGraphRoots() { - codeRefGraphVersion++; - } - - List codeRefRootsWithEdges() { - if (cachedCodeRefEdgeRoots == null - || cachedCodeRefEdgeRootsCodeVersion != codeRefVersion - || cachedCodeRefEdgeRootsVersion != codeRefGraphVersion) { - java.util.ArrayList roots = new java.util.ArrayList<>(); - for (RuntimeScalar scalar : codeRefs.values()) { - if (scalar == null) continue; - if (isCodeRefEdgeRoot(scalar)) roots.add(scalar); - } - cachedCodeRefEdgeRootValues = roots; - cachedCodeRefEdgeRoots = Collections.unmodifiableList(cachedCodeRefEdgeRootValues); - cachedCodeRefEdgeRootsVersion = codeRefGraphVersion; - cachedCodeRefEdgeRootsCodeVersion = codeRefVersion; - } - return cachedCodeRefEdgeRoots; - } - /** Return whether this runtime already installed its core globals. */ public boolean coreGlobalsInitialized() { return coreGlobalsInitialized; @@ -388,6 +464,18 @@ public void resetCoreGlobalsInitialization() { void clearCoreValues() { scalarValues.clear(); + for (PerlOwnerSlot ownerSlot : packageScalarOwnerSlots.values()) { + RuntimeScalar scalar = ownerSlot.referent() instanceof RuntimeScalar value + ? value : null; + ownerSlot.release(); + if (scalar != null) { + scalar.refreshUntrackedReferenceOwner(); + WeakRefRegistry.onStrongOwnerSlotReleased(scalar); + } + } + packageScalarOwnerSlots.clear(); + releasePackageAggregateOwnerSlots(packageArrayOwnerSlots, true); + releasePackageAggregateOwnerSlots(packageHashOwnerSlots, true); invalidateScalarBindingCache(); arrayValues.clear(); hashValues.clear(); @@ -405,9 +493,22 @@ void clearCodeValues() { codeRefs.clear(); pseudoConstants.clear(); compactStashValues.clear(); + for (RuntimeScalar slot : pinnedCodeRefs.values()) { + if (slot != null) slot.releaseCodeSlotBinding(); + } pinnedCodeRefs.clear(); deletedCodeRefPins.clear(); + for (RuntimeScalar slot : compiledCodeRefs.values()) { + if (slot != null) slot.releaseCodeSlotBinding(); + } compiledCodeRefs.clear(); + compiledDirectCallSites.clear(); + for (Map.Entry> entry : displacedLocalizedCodeRefs.entrySet()) { + RuntimeScalar slot = entry.getKey(); + ArrayList bindings = entry.getValue(); + if (slot == null || bindings == null) continue; + for (int i = 0; i < bindings.size(); i++) slot.releaseCodeSlotBinding(); + } localizedCodeRefDepth.clear(); displacedLocalizedCodeRefs.clear(); nextCompiledCodeRefId = 1; @@ -415,6 +516,7 @@ void clearCodeValues() { } void clearIoAndFormatValues() { + releasePackageIoGlobOwnerSlots(); ioSlots.clear(); formatSlots.clear(); hiddenIoSlotsAfterStashDelete.clear(); @@ -455,9 +557,11 @@ synchronized void snapshotInto(GlobalRuntimeState target, RuntimeGraphCloner clo cloneMap(foreachScalarAliases, target.foreachScalarAliases, cloner, RuntimeScalar.class); cloneMap(temporaryScalarAliases, target.temporaryScalarAliases, cloner, RuntimeScalar.class); cloneMap(codeRefs, target.codeRefs, cloner, RuntimeScalar.class); + cloner.restoreStashCodeSlotBindings(target.codeRefs.values()); cloneMap(pseudoConstants, target.pseudoConstants, cloner, RuntimeScalar.class); cloneMap(compactStashValues, target.compactStashValues, cloner, RuntimeScalar.class); cloneMap(pinnedCodeRefs, target.pinnedCodeRefs, cloner, RuntimeScalar.class); + cloner.restoreCodeSlotBindings(target.pinnedCodeRefs.values()); // Parsers register many inert glob placeholders (notably through eval). // Cloning all of them into every ithread makes snapshot cost quadratic // for regex matrices that compile thousands of evals. Only an IO slot @@ -474,6 +578,7 @@ synchronized void snapshotInto(GlobalRuntimeState target, RuntimeGraphCloner clo target.compiledCodeRefs.put(entry.getKey(), (RuntimeScalar) cloner.cloneValue(entry.getValue())); } + cloner.restoreCodeSlotBindings(target.compiledCodeRefs.values()); target.importedSubs.putAll(importedSubs); target.subsPragmaDeclarations.putAll(subsPragmaDeclarations); @@ -525,6 +630,9 @@ synchronized void snapshotCompiledCodeRefsInto( + entry.getKey()); } target.compiledCodeRefs.put(entry.getKey(), cloned); + if (existing == null && cloned != null) { + cloner.restoreCodeSlotBindings(java.util.List.of(cloned)); + } } target.nextCompiledCodeRefId = Math.max(target.nextCompiledCodeRefId, nextCompiledCodeRefId); diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalVariable.java b/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalVariable.java index 70e49f48a2..e292529df8 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalVariable.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/GlobalVariable.java @@ -160,16 +160,80 @@ static long codeRefVersion() { } private static void invalidateCodeRefNames() { - globalState().invalidateCodeRefs(); + globalState().noteCodeRefMutation(); } - private static void noteCodeRefMutation(RuntimeScalar previous, RuntimeScalar replacement) { - globalState().noteCodeRefMutation(previous, replacement); + private static void noteCodeRefMutation( + String key, RuntimeScalar previous, RuntimeScalar replacement) { + globalState().noteCodeRefMutation(); + if (key == null) return; + for (String related : compiledDirectCallSiteKeys(key)) { + globalState().notifyCompiledDirectCallSites(related, previous, replacement); + } } - /** Invalidate CODE-root caches after a stash CODE slot changes in place. */ + /** Advance the compiled CODE-name cache version after an in-place slot change. */ static void noteGlobalCodeRefSlotMutation(RuntimeScalar slot) { - globalState().noteCodeRefMutation(slot, slot); + globalState().noteCodeRefMutation(); + if (slot != null && slot.globalCodeRefFqn != null) { + for (String related : compiledDirectCallSiteKeys(slot.globalCodeRefFqn)) { + globalState().notifyCompiledDirectCallSites(related, slot, slot); + } + } + } + + static void registerCompiledDirectCallSite(String key, CompiledDirectCallSite site) { + if (key == null || site == null) return; + for (String related : compiledDirectCallSiteKeys(key)) { + globalState().registerCompiledDirectCallSite(related, site); + } + } + + static void unregisterCompiledDirectCallSite(String key, CompiledDirectCallSite site) { + if (site != null) globalState().unregisterCompiledDirectCallSite(site); + } + + static RuntimeScalar resolveRegisteredCompiledDirectCallSite(String key, int siteIndex) { + if (key == null) return new RuntimeScalar(); + String resolvedKey = resolveAliasedFqn(key); + CompiledDirectCallSite site = globalState().findCompiledDirectCallSite( + resolvedKey, siteIndex); + if (site == null && !resolvedKey.equals(key)) { + site = globalState().findCompiledDirectCallSite(key, siteIndex); + } + return site == null ? getGlobalCodeRefForDirectCall(key) : site.resolve(); + } + + private static Set compiledDirectCallSiteKeys(String key) { + Set keys = new java.util.LinkedHashSet<>(); + if (key != null) { + keys.add(key); + String resolved = resolveAliasedFqn(key); + if (resolved != null) keys.add(resolved); + } + return keys; + } + + /** Current visible CODE slot for an already compiled direct call, if any. */ + public static RuntimeScalar getVisibleGlobalCodeRefForDirectCall(String key) { + if (key == null) return null; + String resolvedKey = resolveAliasedFqn(key); + RuntimeScalar current = globalCodeRefs.get(resolvedKey); + if (current == null && !resolvedKey.equals(key)) { + current = globalCodeRefs.get(key); + } + return current; + } + + /** Release a compile-time compatibility pin after a callsite owns its CV. */ + static void releaseCompiledDirectCallPin(String key, RuntimeScalar expectedSlot) { + if (key == null || expectedSlot == null) return; + for (String related : compiledDirectCallSiteKeys(key)) { + RuntimeScalar pinned = pinnedCodeRefs().get(related); + if (pinned == expectedSlot) { + unpinCodeRef(related); + } + } } private static GlobalRuntimeState globalState() { @@ -248,7 +312,7 @@ private static Map localizedCodeRefDepth() { return globalState().localizedCodeRefDepth(); } - private static IdentityHashMap displacedLocalizedCodeRefs() { + private static IdentityHashMap> displacedLocalizedCodeRefs() { return globalState().displacedLocalizedCodeRefs(); } @@ -332,6 +396,94 @@ private void noteScalarBindingMutation() { } } + private boolean ownsPackageScalarSlots(GlobalRuntimeState state) { + return (Object) table.apply(state) == state.scalarValues(); + } + + private Map packageAggregateOwnerSlots( + GlobalRuntimeState state) { + Object values = table.apply(state); + if (values == state.arrayValues()) return state.packageArrayOwnerSlots(); + if (values == state.hashValues()) return state.packageHashOwnerSlots(); + return null; + } + + private void updatePackageScalarOwner( + GlobalRuntimeState state, String key, RuntimeScalar nextScalar) { + if (!ownsPackageScalarSlots(state)) return; + Map slots = state.packageScalarOwnerSlots(); + PerlOwnerSlot slot = slots.get(key); + RuntimeScalar previousScalar = slot != null + && slot.referent() instanceof RuntimeScalar previous ? previous : null; + if (nextScalar == null) { + if (slot != null) { + slots.remove(key, slot); + slot.release(); + } + } else { + if (slot == null) { + slot = new PerlOwnerSlot(PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT); + slots.put(key, slot); + } + slot.acquirePackageScalarIdentity(nextScalar); + } + if (previousScalar != null && previousScalar != nextScalar) { + previousScalar.refreshUntrackedReferenceOwner(); + WeakRefRegistry.onStrongOwnerSlotReleased(previousScalar); + } + if (nextScalar != null) nextScalar.refreshUntrackedReferenceOwner(); + } + + private void updatePackageAggregateOwner( + GlobalRuntimeState state, String key, RuntimeBase nextAggregate) { + Map slots = packageAggregateOwnerSlots(state); + if (slots == null) return; + PerlOwnerSlot slot = slots.get(key); + RuntimeBase previousAggregate = slot == null ? null : slot.referent(); + if (nextAggregate == null) { + if (slot != null) { + slots.remove(key, slot); + slot.release(); + WeakRefRegistry.onStrongOwnerSlotReleased(previousAggregate); + } + return; + } + if (slot == null) { + slot = new PerlOwnerSlot(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT); + slots.put(key, slot); + } + slot.acquirePackageAggregateIdentity(nextAggregate); + if (previousAggregate != null && previousAggregate != nextAggregate) { + WeakRefRegistry.onStrongOwnerSlotReleased(previousAggregate); + } + } + + private void releasePackageScalarOwners(GlobalRuntimeState state) { + if (!ownsPackageScalarSlots(state)) return; + Map slots = state.packageScalarOwnerSlots(); + for (Map.Entry entry : new ArrayList<>(slots.entrySet())) { + RuntimeScalar scalar = entry.getValue().referent() instanceof RuntimeScalar value + ? value : null; + entry.getValue().release(); + if (scalar != null) { + scalar.refreshUntrackedReferenceOwner(); + WeakRefRegistry.onStrongOwnerSlotReleased(scalar); + } + } + slots.clear(); + } + + private void releasePackageAggregateOwners(GlobalRuntimeState state) { + Map slots = packageAggregateOwnerSlots(state); + if (slots == null) return; + for (PerlOwnerSlot ownerSlot : new ArrayList<>(slots.values())) { + RuntimeBase aggregate = ownerSlot.referent(); + ownerSlot.release(); + WeakRefRegistry.onStrongOwnerSlotReleased(aggregate); + } + slots.clear(); + } + @Override public T get(Object key) { return delegate().get(key); @@ -359,15 +511,25 @@ public boolean isEmpty() { @Override public T put(String key, T value) { + GlobalRuntimeState state = globalState(); boolean newKey = !delegate().containsKey(key); markStashEntryVisible(key); - markPackageGlobalRoot(value); + // List operators own their current topic alias through the active + // argument frame. Preserve the saved package slot for restoration, + // and do not turn the temporary alias into a package owner. + boolean temporaryScalarAlias = value instanceof RuntimeScalar scalar + && temporaryGlobalAliases().get(key) == scalar; + if (!temporaryScalarAlias) markPackageGlobalRoot(value); T previous = delegate().put(key, value); + if (!temporaryScalarAlias) { + updatePackageScalarOwner(state, key, + value instanceof RuntimeScalar scalar ? scalar : null); + } + updatePackageAggregateOwner(state, key, value); noteScalarBindingMutation(); if (newKey) { invalidateStashEnumerationCache(); } - invalidatePackageRootSnapshot(); return previous; } @@ -376,6 +538,10 @@ public T putIfAbsent(String key, T value) { T previous = delegate().get(key); if (previous != null) { markPackageGlobalRoot(previous); + GlobalRuntimeState state = globalState(); + updatePackageScalarOwner(state, key, + previous instanceof RuntimeScalar scalar ? scalar : null); + updatePackageAggregateOwner(state, key, previous); return previous; } return put(key, value); @@ -383,34 +549,43 @@ public T putIfAbsent(String key, T value) { @Override public T remove(Object key) { + GlobalRuntimeState state = globalState(); T previous = delegate().remove(key); if (previous != null) { + if (key == null || key instanceof String) { + updatePackageScalarOwner(state, (String) key, null); + updatePackageAggregateOwner(state, (String) key, null); + } noteScalarBindingMutation(); invalidateStashEnumerationCache(); - invalidatePackageRootSnapshot(); } return previous; } @Override public void clear() { - if (!delegate().isEmpty()) { + GlobalRuntimeState state = globalState(); + boolean hadEntries = !delegate().isEmpty(); + delegate().clear(); + releasePackageScalarOwners(state); + releasePackageAggregateOwners(state); + if (hadEntries) { noteScalarBindingMutation(); invalidateStashEnumerationCache(); - invalidatePackageRootSnapshot(); } - delegate().clear(); } @Override public Set> entrySet() { - Map entries = delegate(); + GlobalRuntimeState ownerState = globalState(); + Map entries = table.apply(ownerState); return new AbstractSet<>() { @Override public Iterator> iterator() { Iterator> iterator = entries.entrySet().iterator(); return new Iterator<>() { private boolean canRemove; + private String lastKey; @Override public boolean hasNext() { return iterator.hasNext(); } @@ -419,6 +594,7 @@ public Entry next() { Entry current = iterator.next(); canRemove = true; String key = current.getKey(); + lastKey = key; return new SimpleEntry<>(key, current.getValue()) { @Override public T setValue(T value) { @@ -433,10 +609,12 @@ public T setValue(T value) { public void remove() { if (!canRemove) throw new IllegalStateException("next() has not been called"); iterator.remove(); + updatePackageScalarOwner(ownerState, lastKey, null); + updatePackageAggregateOwner(ownerState, lastKey, null); canRemove = false; + lastKey = null; noteScalarBindingMutation(); invalidateStashEnumerationCache(); - invalidatePackageRootSnapshot(); } }; } @@ -457,6 +635,14 @@ private Map delegate() { return globalState().codeRefs(); } + private static RuntimeScalar strongStashSlotValue(RuntimeScalar value) { + // A Perl assignment copies a weak reference as a strong value. A + // glob CODE slot is an independent owner, so keep its scalar cell + // separate from a weakened source cell before acquiring the slot. + return value != null && WeakRefRegistry.isweak(value) + ? new RuntimeScalar(value) : value; + } + private static void maybeInvalidateMethodCacheForCodeRefPut(String key, RuntimeScalar previous, RuntimeScalar value) { if (key == null || value == null) { return; @@ -471,26 +657,28 @@ private static void maybeInvalidateMethodCacheForCodeRefPut(String key, RuntimeS @Override public RuntimeScalar put(String key, RuntimeScalar value) { boolean newKey = !delegate().containsKey(key); + RuntimeScalar stashValue = strongStashSlotValue(value); markStashEntryVisible(key); - markPackageGlobalRoot(value); - RuntimeScalar old = delegate().put(key, value); - if (old != value) { - noteCodeRefMutation(old, value); + markPackageGlobalRoot(stashValue); + RuntimeScalar old = delegate().put(key, stashValue); + if (old != stashValue) { + if (stashValue != null) stashValue.retainStashCodeSlotBinding(); + noteCodeRefMutation(key, old, stashValue); } if (newKey) { invalidateStashEnumerationCache(); } - invalidatePackageRootSnapshot(); - if (old != null && old != value) { + if (old != null && old != stashValue) { old.globalCodeRefFqn = null; } - if (value != null) { - value.globalCodeRefFqn = key; - if (value.value instanceof RuntimeCode code) { + if (stashValue != null) { + stashValue.globalCodeRefFqn = key; + if (stashValue.value instanceof RuntimeCode code) { code.hadStashRef = true; } } - maybeInvalidateMethodCacheForCodeRefPut(key, old, value); + maybeInvalidateMethodCacheForCodeRefPut(key, old, stashValue); + if (old != null && old != stashValue) old.releaseStashCodeSlotBinding(); return old; } @@ -508,19 +696,20 @@ public RuntimeScalar putIfAbsent(String key, RuntimeScalar value) { public RuntimeScalar remove(Object key) { RuntimeScalar prev = delegate().remove(key); if (prev != null) { - noteCodeRefMutation(prev, null); + noteCodeRefMutation(key instanceof String name ? name : null, prev, null); invalidateStashEnumerationCache(); - invalidatePackageRootSnapshot(); prev.globalCodeRefFqn = null; } if (key instanceof String s) { InheritanceResolver.invalidateMethodLookupCachesForStashSubKey(s); } + if (prev != null) prev.releaseStashCodeSlotBinding(); return prev; } @Override public void clear() { + java.util.List previous = new java.util.ArrayList<>(delegate().values()); if (!isEmpty()) { invalidateCodeRefNames(); invalidateStashEnumerationCache(); @@ -531,9 +720,11 @@ public void clear() { } InheritanceResolver.invalidateMethodLookupCachesForStashSubKey(entry.getKey()); } - invalidatePackageRootSnapshot(); } delegate().clear(); + for (RuntimeScalar slot : previous) { + if (slot != null) slot.releaseStashCodeSlotBinding(); + } } @Override public RuntimeScalar get(Object key) { return delegate().get(key); } @@ -574,12 +765,12 @@ public void remove() { String key = current.getKey(); RuntimeScalar value = current.getValue(); iterator.remove(); - noteCodeRefMutation(value, null); + noteCodeRefMutation(key, value, null); canRemove = false; if (value != null) value.globalCodeRefFqn = null; invalidateStashEnumerationCache(); - invalidatePackageRootSnapshot(); InheritanceResolver.invalidateMethodLookupCachesForStashSubKey(key); + if (value != null) value.releaseStashCodeSlotBinding(); } }; } @@ -590,50 +781,11 @@ public void remove() { } } - /** Read-only, allocation-free view for hot reachability traversals. */ + /** Read-only view used while running registered global CODE blocks at END. */ static Collection globalCodeRefValuesView() { return globalState().codeRefs().values(); } - static Set installedGlobalCodeRefsView() { - return globalState().installedCodeRefs(); - } - - static List globalCodeRefEdgeRootsView() { - return globalState().codeRefRootsWithEdges(); - } - - /** Invalidate the cached CODE-root edge list after capture/state metadata changes. */ - public static void invalidateGlobalCodeRefGraphRoots() { - globalState().invalidateCodeRefGraphRoots(); - MortalList.invalidateExternalRootSnapshot(); - } - - /** Read-only backing-map views for reachability walks; bypass map facade entries. */ - static Collection globalVariableValuesView() { - return globalState().scalarValues().values(); - } - - static Collection globalArrayValuesView() { - return globalState().arrayValues().values(); - } - - static Collection globalHashValuesView() { - return globalState().hashValues().values(); - } - - static Set> globalVariableEntriesView() { - return globalState().scalarValues().entrySet(); - } - - static Set> globalArrayEntriesView() { - return globalState().arrayValues().entrySet(); - } - - static Set> globalHashEntriesView() { - return globalState().hashValues().entrySet(); - } - /** Runtime-selecting facade for named IO and FORMAT stash slots. */ private static final class StashSlotMap extends AbstractMap { private final Function> table; @@ -646,6 +798,43 @@ private Map delegate() { return table.apply(globalState()); } + private Map packageIoGlobOwnerSlots(GlobalRuntimeState state) { + return table.apply(state) == state.ioSlots() + ? state.packageIoGlobOwnerSlots() : null; + } + + private void updatePackageIoGlobOwner( + GlobalRuntimeState state, String key, T value) { + RuntimeGlob nextGlob = value instanceof RuntimeGlob glob ? glob : null; + if (packageIoGlobOwnerSlots(state) == null) return; + updatePackageIoGlobOwnerForState(state, key, nextGlob); + } + + private static void updatePackageIoGlobOwnerForState( + GlobalRuntimeState state, String key, RuntimeGlob nextGlob) { + Map ownerSlots = state.packageIoGlobOwnerSlots(); + if (isSymbolGensymName(key)) { + state.hiddenIoSlotsAfterStashDelete().add(key); + } + if (state.hiddenIoSlotsAfterStashDelete().contains(key)) { + nextGlob = null; + } + PerlOwnerSlot ownerSlot = ownerSlots.get(key); + if (nextGlob == null) { + if (ownerSlot != null) { + ownerSlots.remove(key, ownerSlot); + ownerSlot.release(); + } + return; + } + if (ownerSlot != null && ownerSlot.referent() == nextGlob) return; + if (ownerSlot == null) { + ownerSlot = new PerlOwnerSlot(PerlOwnerSlot.Kind.PACKAGE_GLOB_SLOT); + ownerSlots.put(key, ownerSlot); + } + ownerSlot.acquirePackageGlobIdentity(nextGlob); + } + @Override public T get(Object key) { return delegate().get(key); } @Override public boolean containsKey(Object key) { return delegate().containsKey(key); } @Override public int size() { return delegate().size(); } @@ -653,8 +842,11 @@ private Map delegate() { @Override public T put(String key, T value) { - boolean newKey = !delegate().containsKey(key); - T previous = delegate().put(key, value); + GlobalRuntimeState state = globalState(); + Map entries = table.apply(state); + boolean newKey = !entries.containsKey(key); + T previous = entries.put(key, value); + updatePackageIoGlobOwner(state, key, value); if (newKey) { invalidateStashEnumerationCache(); } @@ -663,8 +855,11 @@ public T put(String key, T value) { @Override public T putIfAbsent(String key, T value) { - T previous = delegate().putIfAbsent(key, value); + GlobalRuntimeState state = globalState(); + Map entries = table.apply(state); + T previous = entries.putIfAbsent(key, value); if (previous == null) { + updatePackageIoGlobOwner(state, key, value); invalidateStashEnumerationCache(); } return previous; @@ -672,8 +867,12 @@ public T putIfAbsent(String key, T value) { @Override public T remove(Object key) { - T previous = delegate().remove(key); + GlobalRuntimeState state = globalState(); + T previous = table.apply(state).remove(key); if (previous != null) { + if (key instanceof String name) { + updatePackageIoGlobOwner(state, name, null); + } invalidateStashEnumerationCache(); } return previous; @@ -681,15 +880,20 @@ public T remove(Object key) { @Override public void clear() { + GlobalRuntimeState state = globalState(); if (!isEmpty()) { invalidateStashEnumerationCache(); } - delegate().clear(); + table.apply(state).clear(); + if (packageIoGlobOwnerSlots(state) != null) { + state.releasePackageIoGlobOwnerSlots(); + } } @Override public Set> entrySet() { - Map entries = delegate(); + GlobalRuntimeState ownerState = globalState(); + Map entries = table.apply(ownerState); return new AbstractSet<>() { @Override public Iterator> iterator() { @@ -718,7 +922,9 @@ public T setValue(T value) { @Override public void remove() { if (!canRemove) throw new IllegalStateException("next() has not been called"); + String key = current.getKey(); iterator.remove(); + updatePackageIoGlobOwner(ownerState, key, null); canRemove = false; invalidateStashEnumerationCache(); } @@ -729,6 +935,14 @@ public void remove() { @Override public void clear() { StashSlotMap.this.clear(); } }; } + + private static void refreshPackageIoGlobOwner(GlobalRuntimeState state, String key) { + updatePackageIoGlobOwnerForState(state, key, state.ioSlots().get(key)); + } + } + + private static void refreshPackageIoGlobOwner(String key) { + StashSlotMap.refreshPackageIoGlobOwner(globalState(), key); } static T markPackageGlobalRoot(T root) { @@ -748,6 +962,10 @@ static T markPackageGlobalRoot(T root) { } for (RuntimeScalar value : hash.elements.values()) { hash.markPackageRootedValue(value); + if (value != null) { + value.markPrepopulatedPackageAggregateOwner(hash); + value.refreshUntrackedReferenceOwner(); + } } } else if (root instanceof RuntimeArray array) { // Package-root marking may race with another thread mutating a @@ -756,13 +974,27 @@ static T markPackageGlobalRoot(T root) { // fail-fast ConcurrentModificationException into Perl code. for (RuntimeScalar value : array.elements.toArray(RuntimeScalar[]::new)) { array.markPackageRootedValue(value); + if (value != null) { + value.markPrepopulatedPackageAggregateOwner(array); + value.refreshUntrackedReferenceOwner(); + } } } return root; } - static void invalidatePackageRootSnapshot() { - MortalList.invalidateExternalRootSnapshot(); + /** Whether an aggregate has a package-root owner slot or a package-root marker. */ + static boolean isPackageRootedAggregate(RuntimeBase value) { + if (PerlRuntime.currentOrNull() == null) return false; + if (value instanceof RuntimeArray array) { + return array.isPackageGlobalRoot + || array.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT) != 0; + } + if (value instanceof RuntimeHash hash) { + return hash.isPackageRootedHash() + || hash.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT) != 0; + } + return false; } /** @@ -900,7 +1132,6 @@ public static void resetAllGlobals() { // Reset lib module static state (ORIG_INC) org.perlonjava.runtime.perlmodule.Lib.resetState(); - MortalList.invalidateAllRootSnapshots(); } public static void setStashAlias(String dstNamespace, String srcNamespace) { @@ -909,7 +1140,6 @@ public static void setStashAlias(String dstNamespace, String srcNamespace) { preserveAliasesBeforeStashRebind(dst); stashAliases.put(dst, src); resolvedStashAliasCache.clear(); - invalidatePackageRootSnapshot(); InheritanceResolver.noteIsaMutation(); } @@ -939,42 +1169,96 @@ private static void preserveAliasesBeforeStashRebind(String sourcePrefix) { RuntimeGlob.NamespaceMove move = new RuntimeGlob.NamespaceMove( sourcePrefix, scalars, arrays, hashes, codes); - globalCodeRefs.keySet().removeIf(key -> key.startsWith(sourcePrefix)); - clearGlobalPseudoConstantsForNamespace(sourcePrefix); - globalVariables.keySet().removeIf(key -> key.startsWith(sourcePrefix)); - globalArrays.keySet().removeIf(key -> key.startsWith(sourcePrefix)); - globalHashes.keySet().removeIf(key -> key.startsWith(sourcePrefix)); - removeGlobalIORefsForNamespace(sourcePrefix); - globalFormatRefs.keySet().removeIf(key -> key.startsWith(sourcePrefix)); - clearHiddenIORefsForNamespace(sourcePrefix); - clearPinnedCodeRefsForNamespace(sourcePrefix); - invalidateStashEnumerationCache(); - - for (String destination : destinations) { - installNamespaceMove(move, destination); - clearStashAlias(destination); - } + // Keep the snapshot alive while the source package owners are removed + // and the destination roots are installed. The raw maps in + // NamespaceMove are transport data, not Perl owners. + RuntimeGlob moveOwner = RuntimeGlob.createDetachedNamespaceMove(move); + try { + // The source package-slot identities follow the moved roots to one + // destination. Additional aliases acquire independent identities + // when their package entries are installed below. + transferPackageRootOwners(move, destinations.get(0)); + + globalCodeRefs.keySet().removeIf(key -> key.startsWith(sourcePrefix)); + clearGlobalPseudoConstantsForNamespace(sourcePrefix); + globalVariables.keySet().removeIf(key -> key.startsWith(sourcePrefix)); + globalArrays.keySet().removeIf(key -> key.startsWith(sourcePrefix)); + globalHashes.keySet().removeIf(key -> key.startsWith(sourcePrefix)); + removeGlobalIORefsForNamespace(sourcePrefix); + globalFormatRefs.keySet().removeIf(key -> key.startsWith(sourcePrefix)); + clearHiddenIORefsForNamespace(sourcePrefix); + clearPinnedCodeRefsForNamespace(sourcePrefix); + invalidateStashEnumerationCache(); - // Aliases below a destination may have pointed into the old source - // subtree (e.g. Alias::Nested:: -> Source::Inner::). Keep them attached - // to the materialised subtree instead of following Source's new binding. - for (Map.Entry alias : new HashMap<>(stashAliases).entrySet()) { - if (!alias.getValue().startsWith(sourcePrefix)) { - continue; + for (String destination : destinations) { + installNamespaceMove(move, destination); + clearStashAlias(destination); } - String destination = null; - for (String candidate : destinations) { - if (alias.getKey().startsWith(candidate) - && (destination == null || candidate.length() > destination.length())) { - destination = candidate; + + // Aliases below a destination may have pointed into the old source + // subtree (e.g. Alias::Nested:: -> Source::Inner::). Keep them attached + // to the materialised subtree instead of following Source's new binding. + for (Map.Entry alias : new HashMap<>(stashAliases).entrySet()) { + if (!alias.getValue().startsWith(sourcePrefix)) { + continue; + } + String destination = null; + for (String candidate : destinations) { + if (alias.getKey().startsWith(candidate) + && (destination == null || candidate.length() > destination.length())) { + destination = candidate; + } + } + if (destination != null) { + stashAliases.put(alias.getKey(), + destination + alias.getValue().substring(sourcePrefix.length())); } } - if (destination != null) { - stashAliases.put(alias.getKey(), - destination + alias.getValue().substring(sourcePrefix.length())); + resolvedStashAliasCache.clear(); + } finally { + moveOwner.releaseDetachedComponentsIfUnowned(); + } + } + + private static void transferPackageRootOwners( + RuntimeGlob.NamespaceMove move, String destinationPrefix) { + GlobalRuntimeState state = globalState(); + transferPackageRootOwners( + state.packageScalarOwnerSlots(), move.scalars, + move.sourcePrefix, destinationPrefix); + transferPackageRootOwners( + state.packageArrayOwnerSlots(), move.arrays, + move.sourcePrefix, destinationPrefix); + transferPackageRootOwners( + state.packageHashOwnerSlots(), move.hashes, + move.sourcePrefix, destinationPrefix); + } + + private static void transferPackageRootOwners( + Map ownerSlots, + Map movedValues, + String sourcePrefix, String destinationPrefix) { + for (Map.Entry entry : movedValues.entrySet()) { + String sourceKey = entry.getKey(); + String destinationKey = destinationPrefix + + sourceKey.substring(sourcePrefix.length()); + if (sourceKey.equals(destinationKey)) continue; + PerlOwnerSlot sourceOwner = ownerSlots.get(sourceKey); + if (sourceOwner == null) continue; + if (sourceOwner.referent() != entry.getValue()) { + throw new IllegalStateException( + "package root owner does not match moved namespace slot: " + sourceKey); + } + ownerSlots.remove(sourceKey, sourceOwner); + PerlOwnerSlot displacedOwner = ownerSlots.put(destinationKey, sourceOwner); + if (displacedOwner != null && displacedOwner != sourceOwner) { + RuntimeBase displacedReferent = displacedOwner.referent(); + displacedOwner.release(); + if (displacedReferent instanceof RuntimeScalar scalar) { + scalar.refreshUntrackedReferenceOwner(); + } } } - resolvedStashAliasCache.clear(); } private static Map snapshotNamespace(Map values, String prefix) { @@ -987,13 +1271,27 @@ private static Map snapshotNamespace(Map values, Strin return snapshot; } - static RuntimeGlob.NamespaceMove detachNamespaceForStaleStash(String namespace) { + static RuntimeGlob detachNamespaceForStaleStash( + String namespace, RuntimeStash staleStash) { String prefix = normalizeStashNamespace(namespace); Map scalars = snapshotNamespace(globalVariables, prefix); Map arrays = snapshotNamespace(globalArrays, prefix); Map hashes = snapshotNamespace(globalHashes, prefix); hashes.remove(prefix); + // The stash is a root binding, not one of its namespace components. + // Its key may use a different spelling from the normalized prefix + // (for example `main::Pkg::` versus `Pkg::`). Capturing it by key alone + // makes the saved move own the stale stash that owns the saved move, + // preventing both from reaching their final release. + if (staleStash != null) { + hashes.entrySet().removeIf(entry -> entry.getValue() == staleStash); + } Map codes = snapshotNamespace(globalCodeRefs, prefix); + RuntimeGlob.NamespaceMove move = new RuntimeGlob.NamespaceMove( + prefix, scalars, arrays, hashes, codes); + // The saved move can outlive the package-map transaction. Give it + // component identities before removing any package-root identities. + RuntimeGlob moveOwner = RuntimeGlob.createDetachedNamespaceMove(move); globalVariables.keySet().removeIf(key -> key.startsWith(prefix)); globalArrays.keySet().removeIf(key -> key.startsWith(prefix)); globalHashes.keySet().removeIf(key -> key.startsWith(prefix) && !key.equals(prefix)); @@ -1003,7 +1301,7 @@ static RuntimeGlob.NamespaceMove detachNamespaceForStaleStash(String namespace) clearHiddenIORefsForNamespace(prefix); clearPinnedCodeRefsForNamespace(prefix); invalidateStashEnumerationCache(); - return new RuntimeGlob.NamespaceMove(prefix, scalars, arrays, hashes, codes); + return moveOwner; } static void installNamespaceMove(RuntimeGlob.NamespaceMove move, String destinationPrefix) { @@ -1028,7 +1326,6 @@ static void installNamespaceMove(RuntimeGlob.NamespaceMove move, String destinat for (Map.Entry entry : move.codes.entrySet()) { globalCodeRefs.put(destinationPrefix + entry.getKey().substring(move.sourcePrefix.length()), entry.getValue()); } - invalidatePackageRootSnapshot(); InheritanceResolver.invalidateCache(); clearPackageCache(); } @@ -1052,7 +1349,6 @@ private static String normalizeStashNamespace(String namespace) { public static void clearStashAlias(String namespace) { String key = namespace.endsWith("::") ? namespace : namespace + "::"; if (stashAliases.remove(key) != null) { - invalidatePackageRootSnapshot(); InheritanceResolver.noteIsaMutation(); } resolvedStashAliasCache.clear(); @@ -1192,21 +1488,45 @@ static void hideIORefAfterStashDelete(String key) { invalidateStashEnumerationCache(); return; } - if (key != null && globalIORefs.containsKey(key)) { - if (hiddenIORefsAfterStashDelete().add(key)) { - invalidateStashEnumerationCache(); - } + if (key != null && hiddenIORefsAfterStashDelete().add(key)) { + refreshPackageIoGlobOwner(key); + invalidateStashEnumerationCache(); + } + } + + static boolean isSymbolGensymName(String key) { + if (key == null) return false; + String name = key.startsWith("main::") ? key.substring("main::".length()) : key; + String prefix = "Symbol::GEN"; + if (!name.startsWith(prefix) || name.length() == prefix.length()) return false; + for (int i = prefix.length(); i < name.length(); i++) { + if (!Character.isDigit(name.charAt(i))) return false; + } + return true; + } + + /** Drop a hidden lookup entry after its final scalar IO owner closes. */ + static void retireHiddenIORef(String key) { + if (key == null || !hiddenIORefsAfterStashDelete().contains(key)) return; + globalIORefs.remove(key); + if (hiddenIORefsAfterStashDelete().remove(key)) { + invalidateStashEnumerationCache(); } } static void markStashEntryVisible(String key) { if (key != null) { + if (isSymbolGensymName(key)) { + hideIORefAfterStashDelete(key); + return; + } PerlRuntime runtime = PerlRuntime.currentOrNull(); if (runtime != null && runtime.standardIOGlob(key) != null) { runtime.showStandardIOGlob(key); invalidateStashEnumerationCache(); } if (hiddenIORefsAfterStashDelete().remove(key)) { + refreshPackageIoGlobOwner(key); invalidateStashEnumerationCache(); } } @@ -1287,12 +1607,10 @@ public static void setGlobAlias(String fromGlob, String toGlob) { // Don't create self-loops if (!fromGlob.equals(canonical)) { globAliases.put(fromGlob, canonical); - invalidatePackageRootSnapshot(); } // Also ensure toGlob points to the canonical name (unless it would create a self-loop) if (!toGlob.equals(canonical) && !toGlob.equals(fromGlob)) { globAliases.put(toGlob, canonical); - invalidatePackageRootSnapshot(); } } @@ -1360,7 +1678,6 @@ public static String detachAliasedGlobForLocalization(String globName) { globAliases.put(alias, identity); } globAliases.remove(globName); - invalidatePackageRootSnapshot(); return identity; } @@ -1409,10 +1726,8 @@ public static String resolveCodeDefinitionGlobAlias(String globName) { static void restoreGlobAlias(String globName, String savedTarget) { if (savedTarget == null) { if (globAliases.remove(globName) != null) { - invalidatePackageRootSnapshot(); } } else if (!savedTarget.equals(globAliases.put(globName, savedTarget))) { - invalidatePackageRootSnapshot(); } } @@ -1497,7 +1812,6 @@ public static RuntimeScalar getGlobalVariable(String key) { markPackageGlobalRoot(var); tagGeneratedLexicalSubStorage(storageKey, var); globalVariables.put(storageKey, var); - invalidatePackageRootSnapshot(); } else if (temporaryGlobalAliases().get(key) != var) { markPackageGlobalRoot(var); } @@ -1560,7 +1874,6 @@ public static RuntimeScalar aliasGlobalVariable(String key, String to) { clearForeachGlobalAlias(key); markPackageGlobalRoot(var); globalVariables.put(key, var); - invalidatePackageRootSnapshot(); return var; } @@ -1573,7 +1886,6 @@ public static void aliasGlobalScalarSlot(String key, RuntimeScalar var) { clearForeachGlobalAlias(key); markPackageGlobalRoot(var); globalVariables.put(key, var); - invalidatePackageRootSnapshot(); } public static void aliasGlobalVariable(String key, RuntimeScalar var) { @@ -1587,7 +1899,6 @@ public static void aliasGlobalVariable(String key, RuntimeScalar var) { } markPackageGlobalRoot(var); globalVariables.put(key, var); - invalidatePackageRootSnapshot(); } public static void aliasGlobalArray(String key, RuntimeArray array) { @@ -1596,24 +1907,23 @@ public static void aliasGlobalArray(String key, RuntimeArray array) { } markPackageGlobalRoot(array); globalArrays.put(key, array); - invalidatePackageRootSnapshot(); } public static void aliasGlobalHash(String key, RuntimeHash hash) { markPackageGlobalRoot(hash); globalHashes.put(key, hash); - invalidatePackageRootSnapshot(); } /** Replace a package CODE slot with the supplied code reference. */ public static void aliasGlobalCodeRef(String key, RuntimeScalar codeRef) { - globalCodeRefs.put(key, codeRef); + // CODE refaliasing aliases the CV, not the RHS scalar variable. + globalCodeRefs.put(key, new RuntimeScalar(codeRef)); } /** * Temporarily aliases a package scalar without permanently labelling the * aliased value as package-global. Operators such as map and grep localize - * {@code $_} to each input element; the global slot is a reachability root + * {@code $_} to each input element; the global slot is a Perl owner * while the alias is installed, but the input SV must become ephemeral * again when the operator restores the old slot. */ @@ -1621,7 +1931,6 @@ public static void aliasTemporaryGlobalVariable(String key, RuntimeScalar var) { clearForeachGlobalAlias(key); temporaryGlobalAliases().put(key, var); globalVariables.put(key, var); - invalidatePackageRootSnapshot(); } public static boolean isTemporaryGlobalAlias(String key) { @@ -1644,7 +1953,6 @@ public static void restoreTemporaryGlobalVariable( temporaryGlobalAliases().remove(key); } globalVariables.put(key, var); - invalidatePackageRootSnapshot(); } public static void aliasForeachGlobalVariable(String key, RuntimeScalar var) { @@ -1664,7 +1972,6 @@ public static void aliasForeachGlobalVariable(String key, RuntimeScalar var) { foreachGlobalAliases().put(key, var); markPackageGlobalRoot(var); globalVariables.put(key, var); - invalidatePackageRootSnapshot(); } public static void clearForeachGlobalAlias(String key) { @@ -1678,7 +1985,6 @@ public static void clearForeachGlobalAlias(String key) { public static void restoreForeachGlobalVariable(String key, RuntimeScalar value) { clearForeachGlobalAlias(key); globalVariables.put(key, value); - invalidatePackageRootSnapshot(); } /** Restore a read-only implicit-foreach alias when an IO operator needs its lvalue. */ @@ -1704,20 +2010,11 @@ public static RuntimeScalar restoreForeachAliasForIo(RuntimeScalar target) { } public static void retainForeachAlias(RuntimeScalar scalar) { - if (scalar != null - && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && scalar.value instanceof RuntimeBase base) { - base.foreachAliasCount++; - } + if (scalar != null) scalar.retainForeachRefCountOwner(); } public static void releaseForeachAlias(RuntimeScalar scalar) { - if (scalar != null - && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && scalar.value instanceof RuntimeBase base - && base.foreachAliasCount > 0) { - base.foreachAliasCount--; - } + if (scalar != null) scalar.releaseForeachRefCountOwner(); } /** Retain a foreach reference and return a stable hold for its referent. */ @@ -1797,7 +2094,6 @@ public static boolean isGlobalVariableDefined(String key) { public static RuntimeScalar removeGlobalVariable(String key) { clearGlobalPseudoConstant(key); RuntimeScalar removed = globalVariables.remove(key); - if (removed != null) invalidatePackageRootSnapshot(); return removed; } @@ -1979,7 +2275,6 @@ public static RuntimeArray getGlobalArray(String key) { resolved = new RuntimeArray(); markPackageGlobalRoot(resolved); globalArrays.put(resolvedKey, resolved); - invalidatePackageRootSnapshot(); } if (isaArray || resolvedKey.endsWith("::ISA")) { resolved.markIsaArray(key); @@ -2021,8 +2316,10 @@ public static RuntimeArray getGlobalArray(String key) { markPackageGlobalRoot(var); globalArrays.put(key, var); } - invalidatePackageRootSnapshot(); - } else { + } else if (!var.isPackageGlobalRoot) { + // Global-array table writes mark the aggregate, and its mutation + // paths mark subsequently stored cells. Rewalking every existing + // array on each package-variable read only repeats owner checks. markPackageGlobalRoot(var); } if (isaArray) { @@ -2056,7 +2353,6 @@ public static boolean existsGlobalArray(String key) { public static RuntimeArray removeGlobalArray(String key) { RuntimeArray removed = globalArrays.remove(key); if (removed != null) { - invalidatePackageRootSnapshot(); if (key.endsWith("::ISA")) { InheritanceResolver.noteIsaMutation(); } @@ -2143,11 +2439,10 @@ public static RuntimeHash getGlobalHash(String key) { } // D-W6.18: mark as package-global so values stored here // get the storedInPackageGlobal flag (replaces class-name - // heuristic in walker gate). + // class-name heuristic). markPackageGlobalRoot(var); globalHashes.put(key, var); } - invalidatePackageRootSnapshot(); } else if (!var.isPackageGlobalRoot || !var.isGlobalPackageHash) { // The first installation marks both the hash and its element-map // mutation hooks. Rewalking an already-rooted hash on every package @@ -2205,7 +2500,6 @@ public static boolean existsGlobalHash(String key) { public static RuntimeHash removeGlobalHash(String key) { RuntimeHash removed = globalHashes.remove(key); if (removed != null) { - invalidatePackageRootSnapshot(); if (key.endsWith("::") && !key.equals("main::")) { String packageName = key.startsWith("main::") ? key.substring(6) : key; if (packageName.endsWith("::")) { @@ -2263,7 +2557,7 @@ public static RuntimeScalar getGlobalCodeRef(String key) { } RuntimeScalar resolvedVar = globalCodeRefs.get(resolvedKey); if (resolvedVar != null) { - pinnedCodeRefs().put(resolvedKey, resolvedVar); + pinCodeRef(resolvedKey, resolvedVar); return resolvedVar; } } @@ -2281,13 +2575,12 @@ public static RuntimeScalar getGlobalCodeRef(String key) { var = createEmptyCodeRef(key); markPackageGlobalRoot(var); globalCodeRefs.put(key, var); - invalidatePackageRootSnapshot(); } else { markPackageGlobalRoot(var); } // Pin the RuntimeScalar so it survives stash deletion - pinnedCodeRefs().put(key, var); + pinCodeRef(key, var); return var; } @@ -2413,7 +2706,7 @@ public static RuntimeScalar getGlobalCodeRefForFreshLookup(String key) { RuntimeScalar resolvedVar = globalCodeRefs.get(resolvedKey); if (resolvedVar != null) { if (!deletedCodeRefPins().contains(resolvedKey)) { - pinnedCodeRefs().put(resolvedKey, resolvedVar); + pinCodeRef(resolvedKey, resolvedVar); } return resolvedVar; } @@ -2425,12 +2718,11 @@ public static RuntimeScalar getGlobalCodeRefForFreshLookup(String key) { var = createEmptyCodeRef(key); markPackageGlobalRoot(var); globalCodeRefs.put(key, var); - invalidatePackageRootSnapshot(); } else { markPackageGlobalRoot(var); } if (!deletedCodeRefPins().contains(key)) { - pinnedCodeRefs().put(key, var); + pinCodeRef(key, var); } return var; } @@ -2469,15 +2761,13 @@ public static RuntimeScalar getGlobalCodeRefForNamedReference(String key) { if (slot == null) { globalCodeRefs.put(alias, shared); } else { - slot.type = RuntimeScalarType.CODE; - slot.value = sharedCode; + slot.set(new RuntimeScalar(sharedCode)); } if (!deletedCodeRefPins().contains(alias)) { - pinnedCodeRefs().put(alias, globalCodeRefs.get(alias)); + pinCodeRef(alias, globalCodeRefs.get(alias)); } } markPackageGlobalRoot(shared); - invalidatePackageRootSnapshot(); InheritanceResolver.invalidateCache(); return globalCodeRefs.get(key); } @@ -2486,8 +2776,12 @@ public static RuntimeScalar getGlobalCodeRefForNamedReference(String key) { RuntimeScalar codeRef = getGlobalCodeRefForFreshLookup(key); if (codeRef.type != RuntimeScalarType.CODE || !(codeRef.value instanceof RuntimeCode)) { RuntimeScalar fresh = createEmptyCodeRef(key); - codeRef.type = fresh.type; - codeRef.value = fresh.value; + // A named CODE slot may already be bound to the stash while its + // value is undef (for example after `local *name` followed by a + // runtime `\&name`). Assign through the scalar transition so the + // bound slot acquires its own CODE_SLOT count and owner identity. + codeRef.set(fresh); + codeRef.globalCodeRefFqn = key; InheritanceResolver.invalidateCache(); } RuntimeCode runtimeCode = (RuntimeCode) codeRef.value; @@ -2617,7 +2911,7 @@ public static RuntimeScalar defineGlobalCodeRef(String key) { ref = pinned; markPackageGlobalRoot(ref); globalCodeRefs.put(resolvedKey, ref); - invalidatePackageRootSnapshot(); + ref = globalCodeRefs.get(resolvedKey); } else { ref = getGlobalCodeRefForFreshLookup(resolvedKey); } @@ -2626,12 +2920,12 @@ public static RuntimeScalar defineGlobalCodeRef(String key) { if (!globalCodeRefs.containsKey(resolvedKey)) { markPackageGlobalRoot(ref); globalCodeRefs.put(resolvedKey, ref); - invalidatePackageRootSnapshot(); + ref = globalCodeRefs.get(resolvedKey); } else { markPackageGlobalRoot(ref); } deletedCodeRefPins().remove(resolvedKey); - pinnedCodeRefs().put(resolvedKey, ref); + pinCodeRef(resolvedKey, ref); return ref; } @@ -2668,22 +2962,67 @@ public static boolean existsGlobalCodeRef(String key) { * @param key The glob name key. * @param codeRef The new RuntimeScalar to pin (typically a new empty one). */ + private static void pinCodeRef(String key, RuntimeScalar codeRef) { + RuntimeScalar previous = pinnedCodeRefs().get(key); + if (previous == codeRef) return; + if (codeRef != null) codeRef.retainCodeSlotBinding(); + pinnedCodeRefs().put(key, codeRef); + if (previous != null) previous.releaseCodeSlotBinding(); + } + + private static void unpinCodeRef(String key) { + RuntimeScalar previous = pinnedCodeRefs().remove(key); + if (previous == null) return; + previous.releaseCodeSlotBinding(); + } + + /** Snapshot and own a parsed direct-call CV until its containing CV is compiled. */ + public static RuntimeScalar snapshotDeferredDirectCallTarget(RuntimeScalar source) { + if (source == null) return null; + RuntimeScalar snapshot = new RuntimeScalar(); + snapshot.type = source.type; + snapshot.value = source.value; + snapshot.globalCodeRefFqn = source.globalCodeRefFqn; + snapshot.retainCodeSlotBinding(); + snapshot.markDeferredDirectCallOwnerBinding(); + return snapshot; + } + + /** Transfer a deferred parser owner after the compiled callsite has acquired its edge. */ + public static void releaseDeferredDirectCallOwner(RuntimeScalar codeRef) { + if (codeRef != null && codeRef.consumeDeferredDirectCallOwnerBinding()) { + codeRef.releaseCodeSlotBinding(); + } + } + static void replacePinnedCodeRef(String key, RuntimeScalar codeRef) { if (pinnedCodeRefs().containsKey(key)) { - pinnedCodeRefs().put(key, codeRef); + pinCodeRef(key, codeRef); } } static void enterLocalizedCodeRef(String key, RuntimeScalar displacedCodeRef) { localizedCodeRefDepth().merge(key, 1, Integer::sum); if (displacedCodeRef != null) { - displacedLocalizedCodeRefs().put(displacedCodeRef, key); + displacedCodeRef.retainCodeSlotBinding(); + displacedLocalizedCodeRefs().computeIfAbsent( + displacedCodeRef, ignored -> new ArrayList<>()).add(key); } } static void exitLocalizedCodeRef(String key, RuntimeScalar displacedCodeRef) { if (displacedCodeRef != null) { - displacedLocalizedCodeRefs().remove(displacedCodeRef); + ArrayList bindings = displacedLocalizedCodeRefs().get(displacedCodeRef); + if (bindings != null) { + for (int i = bindings.size() - 1; i >= 0; i--) { + if (java.util.Objects.equals(bindings.get(i), key)) { + bindings.remove(i); + break; + } + } + if (bindings.isEmpty()) displacedLocalizedCodeRefs().remove(displacedCodeRef); + } + displacedCodeRef.releaseCodeSlotBinding(); } Integer depth = localizedCodeRefDepth().get(key); if (depth == null) { @@ -2698,7 +3037,8 @@ static void exitLocalizedCodeRef(String key, RuntimeScalar displacedCodeRef) { public static RuntimeScalar getLocalizedCodeRefForDirectCall(String key, RuntimeScalar fallback) { if ((key == null || key.isEmpty()) && fallback != null) { - key = displacedLocalizedCodeRefs().get(fallback); + ArrayList bindings = displacedLocalizedCodeRefs().get(fallback); + if (bindings != null && !bindings.isEmpty()) key = bindings.getLast(); } if (key == null || key.isEmpty() || !localizedCodeRefDepth().containsKey(key)) { return fallback; @@ -2807,6 +3147,23 @@ public static RuntimeScalar definedGlobalCodeRefAsScalar(RuntimeScalar key, Stri return definedGlobalCodeRefAsScalar(glob.globName); } if (key.type == RuntimeScalarType.CODE && key.value instanceof RuntimeCode runtimeCode) { + // A compiled `defined(&name)` probe carries the parse-time CODE + // slot scalar. The interpreter can execute that bytecode against + // a fresh runtime symbol table, so the scalar may still contain + // the parse-time CV after the visible slot has been redefined. + // Follow the live slot when it exists, but preserve the compiled + // CV behavior after stash deletion instead of vivifying or + // retargeting the name to a later unrelated slot. + if (key.globalCodeRefFqn != null) { + String resolvedName = resolveAliasedFqn(key.globalCodeRefFqn); + RuntimeScalar visible = globalCodeRefs.get(resolvedName); + if (visible == null && !resolvedName.equals(key.globalCodeRefFqn)) { + visible = globalCodeRefs.get(key.globalCodeRefFqn); + } + if (visible != null) { + return definedGlobalCodeRefAsScalar(visible); + } + } return runtimeCode.defined() ? scalarTrue : scalarFalse; } @@ -2824,13 +3181,9 @@ public static RuntimeScalar removeGlobalCodeRefForStashDelete(String key) { if (deleted != null || pinnedCodeRefs().containsKey(key)) { deletedCodeRefPins().add(key); clearPackageCache(); - invalidatePackageRootSnapshot(); } - // Decrement stashRefCount on the removed CODE ref if (deleted != null && deleted.value instanceof RuntimeCode removedCode) { - if (removedCode.stashRefCount > 0) { - removedCode.stashRefCount--; - } + removedCode.noteStashOwnerReleased(); } return deleted; } @@ -2867,7 +3220,11 @@ public static RuntimeScalar deleteGlobalCodeRefAsScalar(RuntimeScalar key, Strin * @param prefix The namespace prefix (e.g., "Foo::") to clear. */ public static void clearPinnedCodeRefsForNamespace(String prefix) { - pinnedCodeRefs().keySet().removeIf(k -> k.startsWith(prefix)); + for (String key : new java.util.ArrayList<>(pinnedCodeRefs().keySet())) { + if (!key.startsWith(prefix)) continue; + RuntimeScalar removed = pinnedCodeRefs().remove(key); + if (removed != null) removed.releaseCodeSlotBinding(); + } deletedCodeRefPins().removeIf(k -> k.startsWith(prefix)); } @@ -2979,6 +3336,14 @@ public static RuntimeGlob getGlobalIO(String key) { RuntimeGlob glob = globalIORefs.get(resolvedKey); if (glob == null) { glob = new RuntimeGlob(resolvedKey); + // Symbol::gensym may return a detached RuntimeGlob without first + // materializing its name in this table. Later symbolic handle + // access resolves the same name here; preserve the anonymous + // slot behavior on that canonical object too. + if (isSymbolGensymName(resolvedKey) + || hiddenIORefsAfterStashDelete().contains(resolvedKey)) { + glob.symbolGensym = true; + } globalIORefs.put(resolvedKey, glob); } RuntimeScalar visibleCode = globalCodeRefs.get(resolvedKey); diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/HashSpecialVariable.java b/src/main/java/org/perlonjava/runtime/runtimetypes/HashSpecialVariable.java index 486fbb687c..e14f20d40d 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/HashSpecialVariable.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/HashSpecialVariable.java @@ -392,7 +392,6 @@ public RuntimeScalar put(String key, RuntimeScalar value) { // Any stash mutation can affect method lookup; clear method resolution caches. InheritanceResolver.invalidateCache(); - GlobalVariable.invalidatePackageRootSnapshot(); return oldValue; } @@ -416,9 +415,8 @@ public RuntimeScalar remove(Object key) { return scalarUndef; } - // Remove only from the visible stash, not from pinned code refs: - // compiled call sites keep their CV, while future lookups must see - // the deletion and create an undefined slot. + // Removing the visible slot notifies compiled call sites first; + // each caller then owns its CV until that caller is released. RuntimeScalar code = GlobalVariable.removeGlobalCodeRefForStashDelete(fullKey); GlobalVariable.clearGlobalPseudoConstant(fullKey); RuntimeScalar scalar = GlobalVariable.scalarSlots().remove(fullKey); @@ -429,7 +427,6 @@ public RuntimeScalar remove(Object key) { GlobalVariable.hideIORefAfterStashDelete(fullKey); } RuntimeScalar format = GlobalVariable.globalFormatRefs.remove(fullKey); - GlobalVariable.invalidatePackageRootSnapshot(); // Any stash mutation can affect method lookup; clear method resolution caches. InheritanceResolver.invalidateCache(); @@ -456,7 +453,6 @@ public void clear() { GlobalVariable.globalFormatRefs.keySet().removeIf(k -> k.startsWith(prefix)); GlobalVariable.invalidateStashEnumerationCache(); GlobalVariable.clearHiddenIORefsForNamespace(prefix); - GlobalVariable.invalidatePackageRootSnapshot(); InheritanceResolver.invalidateCache(); GlobalVariable.clearPackageCache(); diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/LifecycleHotPathDiagnostics.java b/src/main/java/org/perlonjava/runtime/runtimetypes/LifecycleHotPathDiagnostics.java new file mode 100644 index 0000000000..cb7b425a97 --- /dev/null +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/LifecycleHotPathDiagnostics.java @@ -0,0 +1,143 @@ +package org.perlonjava.runtime.runtimetypes; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.concurrent.atomic.LongAdder; + +/** Opt-in counters for measuring lifecycle scans and deferred-list cleanup. */ +final class LifecycleHotPathDiagnostics { + static final boolean ENABLED = Boolean.getBoolean("perlonjava.lifecycleHotPathDiagnostics"); + private static final String OUTPUT = + System.getProperty("perlonjava.lifecycleHotPathDiagnosticsOutput"); + + private static final LongAdder OWNER_SLOTS_VISITED = new LongAdder(); + private static final LongAdder OWNER_SLOT_IDENTITY_FAST_PATHS = new LongAdder(); + private static final LongAdder TRANSIENT_RHS_APPENDS = new LongAdder(); + private static final LongAdder TRANSIENT_RHS_DRAINS = new LongAdder(); + private static final LongAdder TRANSIENT_RHS_HANDOFFS = new LongAdder(); + private static final LongAdder FRAME_QUEUE_ALLOCATIONS = new LongAdder(); + private static final LongAdder FRAME_QUEUE_REUSES = new LongAdder(); + private static final LongAdder BOUNDARY_QUEUE_ALLOCATIONS = new LongAdder(); + private static final LongAdder BOUNDARY_MARKS = new LongAdder(); + private static final LongAdder BOUNDARY_ORDER_REGRESSIONS = new LongAdder(); + private static final LongAdder ENTRY_BUFFER_GROWTHS = new LongAdder(); + private static final LongAdder BOUNDARY_BUFFER_GROWTHS = new LongAdder(); + private static final LongAdder AGGREGATE_RELEASE_WALKERS = new LongAdder(); + private static final LongAdder AGGREGATE_RELEASE_WORKSET_ALLOCATIONS = new LongAdder(); + private static final LongAdder AGGREGATE_RELEASE_ROOTS = new LongAdder(); + private static final LongAdder AGGREGATE_RELEASE_PROBE_WORKSET_ALLOCATIONS = new LongAdder(); + private static final LongAdder AGGREGATE_RELEASE_PROBE_ROOTS = new LongAdder(); + + static { + if (ENABLED && OUTPUT != null && !OUTPUT.isBlank()) { + Runtime.getRuntime().addShutdownHook(new Thread( + LifecycleHotPathDiagnostics::writeReport, + "perlonjava-lifecycle-hot-path-diagnostics")); + } + } + + private LifecycleHotPathDiagnostics() { } + + static void ownerSlotsVisited(long count) { + if (ENABLED && count > 0) OWNER_SLOTS_VISITED.add(count); + } + + static void ownerSlotIdentityFastPath() { + if (ENABLED) OWNER_SLOT_IDENTITY_FAST_PATHS.increment(); + } + + static void transientRhsAppended() { + if (ENABLED) TRANSIENT_RHS_APPENDS.increment(); + } + + static void transientRhsDrained() { + if (ENABLED) TRANSIENT_RHS_DRAINS.increment(); + } + + static void transientRhsHandedOff() { + if (ENABLED) TRANSIENT_RHS_HANDOFFS.increment(); + } + + static void frameQueueAllocated() { + if (ENABLED) FRAME_QUEUE_ALLOCATIONS.increment(); + } + + static void transientRhsFrameQueueReused() { + if (ENABLED) FRAME_QUEUE_REUSES.increment(); + } + + static void boundaryQueueAllocated() { + if (ENABLED) BOUNDARY_QUEUE_ALLOCATIONS.increment(); + } + + static void transientRhsBoundaryMarked() { + if (ENABLED) BOUNDARY_MARKS.increment(); + } + + static void transientRhsBoundaryOrderRegression() { + if (ENABLED) BOUNDARY_ORDER_REGRESSIONS.increment(); + } + + static void transientRhsEntryBufferGrown() { + if (ENABLED) ENTRY_BUFFER_GROWTHS.increment(); + } + + static void transientRhsBoundaryBufferGrown() { + if (ENABLED) BOUNDARY_BUFFER_GROWTHS.increment(); + } + + static void aggregateReleaseWalkerAllocated() { + if (ENABLED) AGGREGATE_RELEASE_WALKERS.increment(); + } + + static void aggregateReleaseWorksetAllocated() { + if (ENABLED) AGGREGATE_RELEASE_WORKSET_ALLOCATIONS.increment(); + } + + static void aggregateReleaseRootProcessed() { + if (ENABLED) AGGREGATE_RELEASE_ROOTS.increment(); + } + + static void aggregateReleaseProbeWorksetAllocated() { + if (ENABLED) AGGREGATE_RELEASE_PROBE_WORKSET_ALLOCATIONS.increment(); + } + + static void aggregateReleaseProbeRootProcessed() { + if (ENABLED) AGGREGATE_RELEASE_PROBE_ROOTS.increment(); + } + + private static void writeReport() { + long pid = ProcessHandle.current().pid(); + String json = "{\n" + + " \"kind\": \"perlonjava-lifecycle-hot-path-diagnostics\",\n" + + " \"process_id\": " + pid + ",\n" + + " \"owner_slots_visited\": " + OWNER_SLOTS_VISITED.sum() + ",\n" + + " \"owner_slot_identity_fast_paths\": " + + OWNER_SLOT_IDENTITY_FAST_PATHS.sum() + ",\n" + + " \"transient_rhs_appends\": " + TRANSIENT_RHS_APPENDS.sum() + ",\n" + + " \"transient_rhs_drains\": " + TRANSIENT_RHS_DRAINS.sum() + ",\n" + + " \"transient_rhs_handoffs\": " + TRANSIENT_RHS_HANDOFFS.sum() + ",\n" + + " \"frame_queue_allocations\": " + FRAME_QUEUE_ALLOCATIONS.sum() + ",\n" + + " \"frame_queue_reuses\": " + FRAME_QUEUE_REUSES.sum() + ",\n" + + " \"boundary_queue_allocations\": " + BOUNDARY_QUEUE_ALLOCATIONS.sum() + ",\n" + + " \"boundary_marks\": " + BOUNDARY_MARKS.sum() + ",\n" + + " \"boundary_order_regressions\": " + BOUNDARY_ORDER_REGRESSIONS.sum() + ",\n" + + " \"entry_buffer_growths\": " + ENTRY_BUFFER_GROWTHS.sum() + ",\n" + + " \"boundary_buffer_growths\": " + BOUNDARY_BUFFER_GROWTHS.sum() + ",\n" + + " \"aggregate_release_walkers\": " + AGGREGATE_RELEASE_WALKERS.sum() + ",\n" + + " \"aggregate_release_workset_allocations\": " + + AGGREGATE_RELEASE_WORKSET_ALLOCATIONS.sum() + ",\n" + + " \"aggregate_release_roots\": " + AGGREGATE_RELEASE_ROOTS.sum() + ",\n" + + " \"aggregate_release_probe_workset_allocations\": " + + AGGREGATE_RELEASE_PROBE_WORKSET_ALLOCATIONS.sum() + ",\n" + + " \"aggregate_release_probe_roots\": " + + AGGREGATE_RELEASE_PROBE_ROOTS.sum() + "\n" + + "}\n"; + try { + Path output = Path.of(OUTPUT + "-" + pid + ".json"); + java.nio.file.Files.writeString(output, json); + } catch (IOException | RuntimeException e) { + System.err.println("cannot write lifecycle hot-path diagnostics: " + e.getMessage()); + } + } +} diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/LifecycleRuntimeState.java b/src/main/java/org/perlonjava/runtime/runtimetypes/LifecycleRuntimeState.java index 746ed83359..87a06e0410 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/LifecycleRuntimeState.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/LifecycleRuntimeState.java @@ -5,6 +5,7 @@ import java.util.Arrays; import java.util.BitSet; import java.util.Collections; +import java.util.HashMap; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; @@ -13,7 +14,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; -/** Runtime-owned mortal, weak-reference, DESTROY, and reachability sweep state. */ +/** Runtime-owned mortal, weak-reference, DESTROY, and owner-slot state. */ final class LifecycleRuntimeState { final AtomicBoolean boundaryWorkRegistered = new AtomicBoolean(); boolean mortalActive = true; @@ -24,71 +25,393 @@ final class LifecycleRuntimeState { // Parallel to pending. Weak provenance permits a tail-call handoff to // drain only the decrement whose owning argument it actually replaces. final ArrayList> pendingOwnerScalars = new ArrayList<>(); + // Parallel to pending. Captured when a scalar decrement is queued so a + // tail-call handoff can match its source argument frame by identity. + final ArrayList pendingArgumentFrames = new ArrayList<>(); // Parallel to pending. A non-scalar transient owner kind is recorded only - // for trace attribution; it never changes runtime reachability. + // for trace attribution; it does not create a Perl owner. final ArrayList pendingTransientOwnerKinds = new ArrayList<>(); final ArrayList deferredArgumentOwnerReleases = new ArrayList<>(); final ArrayList pendingTiedReleases = new ArrayList<>(); final ArrayList pendingIoReleases = new ArrayList<>(); + final ArrayList pendingUntrackedReturnOwnerReleases = new ArrayList<>(); + // One-shot list-assignment arrays keep their copied cells alive through the + // receiving caller's statement boundary when a subroutine returns them. + static final class TransientListAssignmentFrame { + final RuntimeCode executionCode; + final int executionDepth; + + TransientListAssignmentFrame(RuntimeCode executionCode, int executionDepth) { + this.executionCode = executionCode; + this.executionDepth = executionDepth; + } + + @Override + public boolean equals(Object other) { + return other instanceof TransientListAssignmentFrame frame + && frame.executionCode == executionCode + && frame.executionDepth == executionDepth; + } + + @Override + public int hashCode() { + return 31 * System.identityHashCode(executionCode) + executionDepth; + } + } + + static final class PendingTransientListAssignmentRhs { + final RuntimeArray array; + final long enqueueSequence; + long drainAtStatementBoundary; + + PendingTransientListAssignmentRhs(RuntimeArray array, long enqueueSequence, + long drainAtStatementBoundary) { + this.array = array; + this.enqueueSequence = enqueueSequence; + this.drainAtStatementBoundary = drainAtStatementBoundary; + } + } + + /** Compact per-frame append buffer; boundaries are monotonic in normal use. */ + static final class TransientListAssignmentQueue { + private RuntimeArray[] arrays = new RuntimeArray[8]; + private long[] enqueueSequences = new long[8]; + private long[] boundaries = new long[4]; + private int[] boundaryEnds = new int[4]; + private int size; + private int boundaryCount; + private int firstBoundary; + private java.util.TreeMap> + orderedFallback; + TransientListAssignmentQueue nextReusable; + + boolean isEmpty() { + return orderedFallback == null + ? size == 0 : orderedFallback.isEmpty(); + } + + /** Append without allocating a per-boundary collection. */ + void append(RuntimeArray array, long sequence, long boundary) { + if (orderedFallback != null) { + appendToFallback(array, sequence, boundary); + return; + } + if (firstBoundary < boundaryCount + && boundary < boundaries[boundaryCount - 1]) { + promoteToOrderedFallback(); + appendToFallback(array, sequence, boundary); + return; + } + appendOrdered(array, sequence, boundary); + } + + private void appendOrdered(RuntimeArray array, long sequence, long boundary) { + ensureEntryCapacity(size + 1); + arrays[size] = array; + enqueueSequences[size] = sequence; + size++; + if (firstBoundary < boundaryCount + && boundaries[boundaryCount - 1] == boundary) { + boundaryEnds[boundaryCount - 1] = size; + return; + } + ensureBoundaryCapacity(boundaryCount + 1); + boundaries[boundaryCount] = boundary; + boundaryEnds[boundaryCount] = size; + boundaryCount++; + LifecycleHotPathDiagnostics.transientRhsBoundaryMarked(); + } + + private void appendToFallback(RuntimeArray array, long sequence, long boundary) { + ArrayDeque entries = + orderedFallback.get(boundary); + if (entries == null) { + entries = new ArrayDeque<>(); + orderedFallback.put(boundary, entries); + LifecycleHotPathDiagnostics.boundaryQueueAllocated(); + } + entries.addLast(new PendingTransientListAssignmentRhs(array, sequence, boundary)); + } + + private void promoteToOrderedFallback() { + orderedFallback = new java.util.TreeMap<>(); + int start = firstBoundary == 0 ? 0 : boundaryEnds[firstBoundary - 1]; + for (int boundaryIndex = firstBoundary; + boundaryIndex < boundaryCount; boundaryIndex++) { + long boundary = boundaries[boundaryIndex]; + ArrayDeque entries = new ArrayDeque<>(); + int end = boundaryEnds[boundaryIndex]; + for (int entryIndex = start; entryIndex < end; entryIndex++) { + RuntimeArray array = arrays[entryIndex]; + if (array != null) { + entries.addLast(new PendingTransientListAssignmentRhs( + array, enqueueSequences[entryIndex], boundary)); + } + } + if (!entries.isEmpty()) { + orderedFallback.put(boundary, entries); + LifecycleHotPathDiagnostics.boundaryQueueAllocated(); + } + start = end; + } + clearBufferedEntries(); + LifecycleHotPathDiagnostics.transientRhsBoundaryOrderRegression(); + } + + void drainAtBoundary(long currentBoundary) { + if (orderedFallback != null) { + java.util.Map.Entry> due = + orderedFallback.floorEntry(currentBoundary); + while (due != null) { + orderedFallback.remove(due.getKey()); + ArrayDeque entries = due.getValue(); + while (!entries.isEmpty()) { + PendingTransientListAssignmentRhs pending = entries.removeLast(); + LifecycleHotPathDiagnostics.transientRhsDrained(); + MortalList.releaseTransientListAssignmentRhs(pending.array); + } + due = orderedFallback.floorEntry(currentBoundary); + } + if (orderedFallback.isEmpty()) resetForReuse(); + return; + } + + int dueBoundaryEnd = firstBoundary; + while (dueBoundaryEnd < boundaryCount + && boundaries[dueBoundaryEnd] <= currentBoundary) { + dueBoundaryEnd++; + } + for (int boundaryIndex = dueBoundaryEnd - 1; + boundaryIndex >= firstBoundary; boundaryIndex--) { + int start = boundaryIndex == 0 ? 0 : boundaryEnds[boundaryIndex - 1]; + int end = boundaryEnds[boundaryIndex]; + for (int entryIndex = end - 1; entryIndex >= start; entryIndex--) { + RuntimeArray array = arrays[entryIndex]; + if (array != null) { + arrays[entryIndex] = null; + enqueueSequences[entryIndex] = 0; + LifecycleHotPathDiagnostics.transientRhsDrained(); + MortalList.releaseTransientListAssignmentRhs(array); + } + } + } + firstBoundary = dueBoundaryEnd; + if (firstBoundary == boundaryCount) { + resetForReuse(); + } else { + compactConsumedPrefix(); + } + } + + /** Move this frame's FIFO sequence to the caller's next LIFO bucket. */ + void handoffTo(TransientListAssignmentQueue target, long nextBoundary) { + if (orderedFallback != null) { + for (ArrayDeque entries + : orderedFallback.values()) { + for (PendingTransientListAssignmentRhs pending : entries) { + target.append(pending.array, pending.enqueueSequence, nextBoundary); + LifecycleHotPathDiagnostics.transientRhsHandedOff(); + } + } + } else { + int start = firstBoundary == 0 ? 0 : boundaryEnds[firstBoundary - 1]; + for (int entryIndex = start; entryIndex < size; entryIndex++) { + RuntimeArray array = arrays[entryIndex]; + if (array != null) { + target.append(array, enqueueSequences[entryIndex], nextBoundary); + LifecycleHotPathDiagnostics.transientRhsHandedOff(); + } + } + } + resetForReuse(); + } + + /** Retag a source queue when it becomes the caller queue directly. */ + void retagAll(long boundary) { + if (orderedFallback != null) { + java.util.TreeMap> old = + orderedFallback; + orderedFallback = null; + clearBufferedEntries(); + for (ArrayDeque entries : old.values()) { + for (PendingTransientListAssignmentRhs pending : entries) { + appendOrdered(pending.array, pending.enqueueSequence, boundary); + } + } + old.clear(); + return; + } + int start = firstBoundary == 0 ? 0 : boundaryEnds[firstBoundary - 1]; + int write = 0; + for (int entryIndex = start; entryIndex < size; entryIndex++) { + RuntimeArray array = arrays[entryIndex]; + if (array != null) { + arrays[write] = array; + enqueueSequences[write] = enqueueSequences[entryIndex]; + write++; + } + } + Arrays.fill(arrays, write, size, null); + Arrays.fill(enqueueSequences, write, size, 0); + size = write; + boundaryCount = 0; + firstBoundary = 0; + if (size > 0) { + ensureBoundaryCapacity(1); + boundaries[0] = boundary; + boundaryEnds[0] = size; + boundaryCount = 1; + } + } + + void collectPending(List destination) { + if (orderedFallback != null) { + for (ArrayDeque entries + : orderedFallback.values()) { + destination.addAll(entries); + } + return; + } + int start = firstBoundary == 0 ? 0 : boundaryEnds[firstBoundary - 1]; + for (int entryIndex = start; entryIndex < size; entryIndex++) { + RuntimeArray array = arrays[entryIndex]; + if (array != null) { + destination.add(new PendingTransientListAssignmentRhs( + array, enqueueSequences[entryIndex], 0)); + } + } + } + + private void compactConsumedPrefix() { + if (firstBoundary < 4 || firstBoundary * 2 < boundaryCount) return; + int consumedEntries = boundaryEnds[firstBoundary - 1]; + int remainingEntries = size - consumedEntries; + System.arraycopy(arrays, consumedEntries, arrays, 0, remainingEntries); + System.arraycopy(enqueueSequences, consumedEntries, + enqueueSequences, 0, remainingEntries); + Arrays.fill(arrays, remainingEntries, size, null); + Arrays.fill(enqueueSequences, remainingEntries, size, 0); + int remainingBoundaries = boundaryCount - firstBoundary; + System.arraycopy(boundaries, firstBoundary, boundaries, 0, remainingBoundaries); + System.arraycopy(boundaryEnds, firstBoundary, boundaryEnds, 0, remainingBoundaries); + for (int i = 0; i < remainingBoundaries; i++) { + boundaryEnds[i] -= consumedEntries; + } + size = remainingEntries; + boundaryCount = remainingBoundaries; + firstBoundary = 0; + } + + private void ensureEntryCapacity(int required) { + if (required <= arrays.length) return; + int capacity = arrays.length * 2; + while (capacity < required) capacity *= 2; + arrays = Arrays.copyOf(arrays, capacity); + enqueueSequences = Arrays.copyOf(enqueueSequences, capacity); + LifecycleHotPathDiagnostics.transientRhsEntryBufferGrown(); + } + + private void ensureBoundaryCapacity(int required) { + if (required <= boundaries.length) return; + int capacity = boundaries.length * 2; + while (capacity < required) capacity *= 2; + boundaries = Arrays.copyOf(boundaries, capacity); + boundaryEnds = Arrays.copyOf(boundaryEnds, capacity); + LifecycleHotPathDiagnostics.transientRhsBoundaryBufferGrown(); + } + + private void clearBufferedEntries() { + Arrays.fill(arrays, 0, size, null); + Arrays.fill(enqueueSequences, 0, size, 0); + size = 0; + boundaryCount = 0; + firstBoundary = 0; + } + + void resetForReuse() { + if (orderedFallback != null) { + orderedFallback.clear(); + orderedFallback = null; + } + clearBufferedEntries(); + } + } + + // Each active Perl frame owns one compact queue. A statement flush visits + // only its due boundary segments; returning a frame hands the queue to its + // caller. Segment marks are integer indexes into the append-only arrays. + final Map pendingTransientListAssignmentRhsByFrame = + new HashMap<>(); + TransientListAssignmentQueue reusableTransientListAssignmentQueues; + + TransientListAssignmentQueue obtainTransientListAssignmentQueue() { + TransientListAssignmentQueue queue = reusableTransientListAssignmentQueues; + if (queue == null) return new TransientListAssignmentQueue(); + reusableTransientListAssignmentQueues = queue.nextReusable; + queue.nextReusable = null; + return queue; + } + + void recycleTransientListAssignmentQueue(TransientListAssignmentQueue queue) { + if (queue == null) return; + queue.resetForReuse(); + queue.nextReusable = reusableTransientListAssignmentQueues; + reusableTransientListAssignmentQueues = queue; + } + long nextTransientListAssignmentSequence; + long statementBoundarySequence; final ArrayList deferredCaptures = new ArrayList<>(); final IdentityHashMap deferredCapturesSet = new IdentityHashMap<>(); - final Set deferredScopeExitCaptureCandidates = - Collections.newSetFromMap(new IdentityHashMap<>()); // Strong semantic referents retained by explicit Perl owner slots. Counts // are per referent because several independent pad slots can own one base. final IdentityHashMap positiveOwnerReferents = new IdentityHashMap<>(); boolean deferredCapturesMayBeReady; - final ArrayDeque temporaryRoots = new ArrayDeque<>(); - final IdentityHashMap suspendedRoots = new IdentityHashMap<>(); + final ArrayDeque temporaryRoots = new ArrayDeque<>(); + final ArrayDeque foreachSourceOwners = new ArrayDeque<>(); private static final int INITIAL_MARK_CAPACITY = 16; int[] marks = new int[INITIAL_MARK_CAPACITY]; int[] tiedReleaseMarks = new int[INITIAL_MARK_CAPACITY]; int[] ioReleaseMarks = new int[INITIAL_MARK_CAPACITY]; + int[] untrackedReturnOwnerMarks = new int[INITIAL_MARK_CAPACITY]; int markDepth; boolean flushing; - int reachabilityDrainDepth; - int topLevelFlushDepth; - // Start within the configured quiet-sweep throttle window. A zero value - // would trigger a full root walk at the first statement boundary, often - // between callbacks that are expected to dispatch together. - long lastAutoSweepNanos = System.nanoTime(); - boolean inAutoSweep; - /** Suppress sweeps while clone hooks and the first child entry build Perl roots. */ - int weakSweepSuppressionDepth; - boolean immediateWeakSweepRequested; - boolean deferCaptureReachabilityToBoundarySweep; - final ArrayList deferredCaptureSweepCandidates = new ArrayList<>(); - long boundaryWeakSweepGeneration; - long deferredCaptureSweepGeneration; - final Set targetedWeakSweepReferents = - Collections.newSetFromMap(new IdentityHashMap<>()); - Set flushReachableCache; - ReachabilityWalker.TiedHashReachabilitySnapshot flushTiedReachableCache; - ReachabilityWalker.ExternalRootSnapshot externalRootSnapshot; - ReachabilityWalker.LiveRootSnapshot liveRootSnapshot; - ReachabilityWalker.ScalarRootReachabilitySnapshot scalarRootSnapshot; - final Set unblessedAggregateDrainRoots = - Collections.newSetFromMap(new IdentityHashMap<>()); - boolean unblessedAggregateDrainSnapshotIncomplete; - Set weakSweepLiveReferents; - - ReachabilityWalker.RootReachabilitySnapshot fullRootSnapshot; - ReachabilityWalker.RootReachabilitySnapshot unblessedAggregateRootSnapshot; - final IdentityHashMap - weakSweepRootWitnesses = new IdentityHashMap<>(); - ReachabilityQueryStats activeReachabilityQueryStats; - - void pushMortalMark(int pendingSize, int tiedReleaseSize, int ioReleaseSize) { + boolean flushSuppressed; + int deferredReleaseDrainDepth; + // Reusable primitive stack for nested releases appended while a boundary + // drains its owner queue. This keeps destruction depth-first without + // allocating a boxed cursor for each aggregate edge. + int[] pendingReleaseResumeStack; + int pendingReleaseResumeDepth; + + void pushPendingReleaseResume(int cursor, int floor) { + int required = (pendingReleaseResumeDepth + 1) * 2; + if (pendingReleaseResumeStack == null) { + pendingReleaseResumeStack = new int[16]; + } else if (required > pendingReleaseResumeStack.length) { + pendingReleaseResumeStack = Arrays.copyOf( + pendingReleaseResumeStack, pendingReleaseResumeStack.length * 2); + } + int offset = pendingReleaseResumeDepth * 2; + pendingReleaseResumeStack[offset] = cursor; + pendingReleaseResumeStack[offset + 1] = floor; + pendingReleaseResumeDepth++; + } + + void pushMortalMark(int pendingSize, int tiedReleaseSize, int ioReleaseSize, + int untrackedReturnOwnerReleaseSize) { if (markDepth == marks.length) { int capacity = marks.length * 2; marks = Arrays.copyOf(marks, capacity); tiedReleaseMarks = Arrays.copyOf(tiedReleaseMarks, capacity); ioReleaseMarks = Arrays.copyOf(ioReleaseMarks, capacity); + untrackedReturnOwnerMarks = Arrays.copyOf(untrackedReturnOwnerMarks, capacity); } marks[markDepth] = pendingSize; tiedReleaseMarks[markDepth] = tiedReleaseSize; ioReleaseMarks[markDepth] = ioReleaseSize; + untrackedReturnOwnerMarks[markDepth] = untrackedReturnOwnerReleaseSize; markDepth++; } @@ -117,20 +440,104 @@ void popMortalMark() { Collections.synchronizedSet(Collections.newSetFromMap(new IdentityHashMap<>())); RuntimeBase currentDestroyTarget; boolean destroyTargetRescued; - boolean sweepPendingAfterOuterDestroy; final List rescuedObjects = Collections.synchronizedList(new ArrayList<>()); - final BitSet walkerGateClasses = new BitSet(); - final BitSet walkerGateChecked = new BitSet(); boolean blessedObjectExists; final Map> traceOwners = Collections.synchronizedMap(new IdentityHashMap<>()); - final ScalarRefRegistry.WeakIdentityMap scalarRegistry = - new ScalarRefRegistry.WeakIdentityMap<>(); - final ScalarRefRegistry.WeakIdentityMap scalarRegisterStacks = - new ScalarRefRegistry.WeakIdentityMap<>(); + + /** One expression-root stack entry and its exact temporary owner identity. */ + static final class TemporaryRootLease { + private final RuntimeBase root; + private final PerlOwnerSlot ownerSlot; + + TemporaryRootLease(RuntimeBase root) { + this.root = root; + if (root.isPerlDestroyed()) { + // Keep the boundary balanced without reviving a destroyed value. + this.ownerSlot = null; + } else { + if (root.isRefCountUntracked() && root.refCount > 0) { + // Adopt a positive legacy count before acquiring the + // expression owner so the native lease pairs with it. + root.setTrackedRefCount(root.refCount); + } + PerlOwnerSlot owner = new PerlOwnerSlot(PerlOwnerSlot.Kind.EXPRESSION_VALUE); + owner.acquireCountedNativeOwner(root, "MortalList temporary expression value"); + this.ownerSlot = owner; + } + } + + RuntimeBase root() { + return root; + } + + void release() { + if (ownerSlot != null) ownerSlot.releaseNativeOwner(); + if (root.localBindingExists || root.hasCurrentPerlStorageOwner()) return; + if (root instanceof RuntimeArray array) { + MortalList.scopeExitCleanupArray(array); + } else if (root instanceof RuntimeHash hash) { + MortalList.scopeExitCleanupHash(hash); + } + } + } + + /** Explicit temporary owners for references in one evaluated foreach list. */ + static final class ForeachSourceOwnerLease { + private final List owners = new ArrayList<>(); + + void retain(RuntimeScalar scalar) { + if (scalar == null || scalar.nonOwningBObjectReference + || (scalar.type & RuntimeScalarType.REFERENCE_BIT) == 0 + || WeakRefRegistry.isweak(scalar) + || !(scalar.value instanceof RuntimeBase referent)) { + return; + } + retainReferent(referent); + } + + void retainReferent(RuntimeBase referent) { + if (referent == null || referent.isPerlDestroyed()) return; + PerlOwnerSlot owner = new PerlOwnerSlot(PerlOwnerSlot.Kind.EXPRESSION_VALUE); + owner.acquireCountedNativeOwner(referent, "foreach source list value"); + owners.add(owner); + } + + void release() { + Throwable failure = null; + for (int i = owners.size() - 1; i >= 0; i--) { + try { + owners.get(i).releaseNativeOwner(); + } catch (RuntimeException | Error cleanupFailure) { + if (failure == null) failure = cleanupFailure; + else failure.addSuppressed(cleanupFailure); + } + } + owners.clear(); + if (failure instanceof RuntimeException runtimeFailure) throw runtimeFailure; + if (failure instanceof Error errorFailure) throw errorFailure; + } + } void clear() { mortalActive = true; + while (!pendingTransientListAssignmentRhsByFrame.isEmpty()) { + ArrayList pendingRhs = new ArrayList<>(); + for (TransientListAssignmentQueue queue + : pendingTransientListAssignmentRhsByFrame.values()) { + queue.collectPending(pendingRhs); + } + pendingTransientListAssignmentRhsByFrame.clear(); + reusableTransientListAssignmentQueues = null; + pendingRhs.sort((left, right) -> Long.compare( + right.enqueueSequence, left.enqueueSequence)); + for (PendingTransientListAssignmentRhs pending : pendingRhs) { + if (pending != null && pending.array != null) { + LifecycleHotPathDiagnostics.transientRhsDrained(); + MortalList.releaseTransientListAssignmentRhs(pending.array); + } + } + } for (int i = 0; i < pending.size(); i++) { RuntimeBase.PendingOwnerRelease release = pendingOwnerReleases.get(i); if (release != null) { @@ -143,42 +550,28 @@ void clear() { pending.clear(); pendingOwnerReleases.clear(); pendingOwnerScalars.clear(); + pendingArgumentFrames.clear(); pendingTransientOwnerKinds.clear(); pendingTiedReleases.clear(); pendingIoReleases.clear(); + statementBoundarySequence = 0; + for (RuntimeScalar scalar : pendingUntrackedReturnOwnerReleases) { + if (scalar != null) scalar.releaseMortalReturnValueOwner(); + } + pendingUntrackedReturnOwnerReleases.clear(); deferredCaptures.clear(); deferredCapturesSet.clear(); - deferredScopeExitCaptureCandidates.clear(); synchronized (this) { positiveOwnerReferents.clear(); } deferredCapturesMayBeReady = false; - temporaryRoots.clear(); - suspendedRoots.clear(); + while (!temporaryRoots.isEmpty()) temporaryRoots.pop().release(); + while (!foreachSourceOwners.isEmpty()) foreachSourceOwners.pop().release(); markDepth = 0; flushing = false; - reachabilityDrainDepth = 0; - topLevelFlushDepth = 0; - lastAutoSweepNanos = System.nanoTime(); - inAutoSweep = false; - fullRootSnapshot = null; - unblessedAggregateRootSnapshot = null; - weakSweepRootWitnesses.clear(); - activeReachabilityQueryStats = null; - immediateWeakSweepRequested = false; - deferCaptureReachabilityToBoundarySweep = false; - deferredCaptureSweepCandidates.clear(); - boundaryWeakSweepGeneration = 0; - deferredCaptureSweepGeneration = 0; - targetedWeakSweepReferents.clear(); - flushReachableCache = null; - flushTiedReachableCache = null; - externalRootSnapshot = null; - liveRootSnapshot = null; - scalarRootSnapshot = null; - unblessedAggregateDrainRoots.clear(); - unblessedAggregateDrainSnapshotIncomplete = false; - weakSweepLiveReferents = null; + flushSuppressed = false; + deferredReleaseDrainDepth = 0; + pendingReleaseResumeDepth = 0; weakScalars.clear(); referentToWeakRefs.clear(); weakRefsExist = false; @@ -190,13 +583,9 @@ void clear() { statementBoundaryDestroyableObjects.clear(); currentDestroyTarget = null; destroyTargetRescued = false; - sweepPendingAfterOuterDestroy = false; rescuedObjects.clear(); - walkerGateClasses.clear(); - walkerGateChecked.clear(); blessedObjectExists = false; traceOwners.clear(); - scalarRegistry.clear(); - scalarRegisterStacks.clear(); } + } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/ModuleInitGuard.java b/src/main/java/org/perlonjava/runtime/runtimetypes/ModuleInitGuard.java deleted file mode 100644 index ad21fa01c0..0000000000 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/ModuleInitGuard.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.perlonjava.runtime.runtimetypes; - -/** - * Phase B2a (refcount_alignment_52leaks_plan.md): module-init guard. - *

    - * A thread-local counter that tracks how deep we are inside - * module-initialization code ({@code require} / {@code use} / BEGIN - * blocks / {@code eval STRING}). Auto-triggered reachability sweeps - * consult {@link #inModuleInit()} and skip firing when it's true — - * module-init chains (like DBICTest::BaseResult's {@code use} - * sequence) rely on weak-refed intermediate state remaining defined, - * and firing a sweep mid-init corrupts that. - *

    - * Expected usage: any code path that runs Perl-compiled code on - * behalf of {@code require}/{@code use}/{@code BEGIN}/{@code eval - * STRING} wraps the call in {@code try { enter(); ... } finally { exit(); }}. - *

    - * Not thread-safe across JVM threads, but per-thread state is - * correctly isolated. Matches PerlOnJava's single-threaded - * execution model (see {@code weaken-destroy.md} §5 Limitations). - */ -public class ModuleInitGuard { - - /** Enter module-initialization state (increments depth). */ - public static void enter() { - PerlRuntime.current().executionState().moduleInitDepth++; - } - - /** Exit module-initialization state (decrements depth). */ - public static void exit() { - ExecutionRuntimeState state = PerlRuntime.current().executionState(); - if (state.moduleInitDepth > 0) state.moduleInitDepth--; - } - - /** True if currently inside require/use/BEGIN/eval-STRING execution. */ - public static boolean inModuleInit() { - return PerlRuntime.current().executionState().moduleInitDepth > 0; - } - - /** Diagnostic: current depth. */ - public static int currentDepth() { - return PerlRuntime.current().executionState().moduleInitDepth; - } -} diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/MortalList.java b/src/main/java/org/perlonjava/runtime/runtimetypes/MortalList.java index e356557ac4..a650ea0519 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/MortalList.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/MortalList.java @@ -5,6 +5,7 @@ import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; +import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; @@ -19,35 +20,16 @@ * trigger DESTROY at statement end, not immediately during delete. */ public class MortalList { - private static final int MAX_UNBLESSED_AGGREGATE_DRAIN_ROOTS = 50_000; private static final AtomicInteger runtimesWithBoundaryWork = new AtomicInteger(); - - static final class DeferredArgumentOwnerRelease { - final RuntimeBase base; - final RuntimeBase.PendingOwnerRelease ownerRelease; - final String transientOwnerKind; - final java.lang.ref.WeakReference ownerScalar; - - DeferredArgumentOwnerRelease(RuntimeBase base, - RuntimeBase.PendingOwnerRelease ownerRelease, - String transientOwnerKind, - RuntimeScalar ownerScalar) { - this.base = base; - this.ownerRelease = ownerRelease; - this.transientOwnerKind = transientOwnerKind; - this.ownerScalar = new java.lang.ref.WeakReference<>(ownerScalar); - } - } + private static final ThreadLocal activeReachabilityQueryStats = + new ThreadLocal<>(); static final class ReachabilityQueryMeasurement implements AutoCloseable { - private final LifecycleRuntimeState state; private final ReachabilityQueryStats stats; private final ReachabilityQueryStats previous; - private ReachabilityQueryMeasurement(LifecycleRuntimeState state, - ReachabilityQueryStats stats, - ReachabilityQueryStats previous) { - this.state = state; + private ReachabilityQueryMeasurement( + ReachabilityQueryStats stats, ReachabilityQueryStats previous) { this.stats = stats; this.previous = previous; } @@ -58,27 +40,46 @@ ReachabilityQueryStats stats() { @Override public void close() { - if (state.activeReachabilityQueryStats == stats) { - state.activeReachabilityQueryStats = previous; + if (activeReachabilityQueryStats.get() == stats) { + if (previous == null) activeReachabilityQueryStats.remove(); + else activeReachabilityQueryStats.set(previous); } } } static ReachabilityQueryMeasurement measureReachabilityQueries() { - LifecycleRuntimeState state = state(); - ReachabilityQueryStats previous = state.activeReachabilityQueryStats; + ReachabilityQueryStats previous = activeReachabilityQueryStats.get(); ReachabilityQueryStats stats = new ReachabilityQueryStats(); - state.activeReachabilityQueryStats = stats; - return new ReachabilityQueryMeasurement(state, stats, previous); + activeReachabilityQueryStats.set(stats); + return new ReachabilityQueryMeasurement(stats, previous); } static ReachabilityQueryStats activeReachabilityQueryStats() { - return state().activeReachabilityQueryStats; + return activeReachabilityQueryStats.get(); + } + + static final class DeferredArgumentOwnerRelease { + final RuntimeBase base; + final RuntimeBase.PendingOwnerRelease ownerRelease; + final String transientOwnerKind; + + DeferredArgumentOwnerRelease(RuntimeBase base, + RuntimeBase.PendingOwnerRelease ownerRelease, + String transientOwnerKind) { + this.base = base; + this.ownerRelease = ownerRelease; + this.transientOwnerKind = transientOwnerKind; + } } + private record PendingOwnerEntry( + RuntimeBase base, + RuntimeBase.PendingOwnerRelease ownerRelease, + String transientOwnerKind) {} + // Always-on: refCount tracking for birth-tracked objects (anonymous hashes, // arrays, closures with captures) requires balanced increment/decrement. - // The increment side fires unconditionally in setLarge() when refCount >= 0, + // The increment side fires unconditionally in setLarge() when count tracking is active, // so the decrement side (deferDecrementIfTracked, flush, etc.) must also // be active from the start. The per-method `!active` guards are retained // as a trivially-predicted branch; the JIT will elide them. @@ -99,11 +100,9 @@ private static void refreshBoundaryWork(LifecycleRuntimeState state) { boolean needed = !state.pending.isEmpty() || !state.pendingTiedReleases.isEmpty() || !state.pendingIoReleases.isEmpty() - || state.deferredCapturesMayBeReady - || state.immediateWeakSweepRequested - || !state.targetedWeakSweepReferents.isEmpty() - || !state.statementBoundaryDestroyableObjects.isEmpty() - || state.weakRefsExist; + || !state.pendingUntrackedReturnOwnerReleases.isEmpty() + || !state.pendingTransientListAssignmentRhsByFrame.isEmpty() + || state.deferredCapturesMayBeReady; if (!needed && state.boundaryWorkRegistered.compareAndSet(true, false)) { runtimesWithBoundaryWork.decrementAndGet(); } @@ -130,120 +129,329 @@ public static void setActive(boolean active) { public static void pushTemporaryRoot(RuntimeBase root) { if (root != null) { - state().temporaryRoots.push(root); + state().temporaryRoots.push(new LifecycleRuntimeState.TemporaryRootLease(root)); } } public static void popTemporaryRoot(RuntimeBase root) { if (root != null) { - ArrayDeque roots = state().temporaryRoots; - if (!roots.isEmpty() && roots.peek() == root) { - roots.pop(); - } else { - roots.removeFirstOccurrence(root); + LifecycleRuntimeState state = state(); + ArrayDeque roots = state.temporaryRoots; + if (!roots.isEmpty() && roots.peek().root() == root) { + roots.pop().release(); + return; + } + var iterator = roots.iterator(); + while (iterator.hasNext()) { + LifecycleRuntimeState.TemporaryRootLease lease = iterator.next(); + if (lease.root() == root) { + iterator.remove(); + lease.release(); + return; + } } } } - public static java.util.List snapshotTemporaryRoots() { - return new java.util.ArrayList<>(state().temporaryRoots); - } - public static boolean hasTemporaryRoots() { return !state().temporaryRoots.isEmpty(); } - static boolean temporaryRootDirectlyReferences(RuntimeBase target) { - for (RuntimeBase root : state().temporaryRoots) { - if (directlyReferences(root, target)) return true; + /** Current expression-root depth for an exception boundary. */ + public static int temporaryRootDepth() { + return state().temporaryRoots.size(); + } + + /** Drop temporary roots added after an exception boundary was entered. */ + public static void restoreTemporaryRootDepth(int depth) { + if (depth < 0) { + throw new IllegalArgumentException("Invalid temporary root depth: " + depth); } - return false; + ArrayDeque roots = state().temporaryRoots; + while (roots.size() > depth) roots.pop().release(); } - private static boolean directlyReferences(RuntimeBase value, RuntimeBase target) { - return directlyReferences(value, target, new IdentityHashMap<>()); + /** Diagnostic direct-edge query; lifecycle decisions do not call this method. */ + static boolean temporaryRootDirectlyReferences(RuntimeBase target) { + if (target == null) return false; + if (target.hasTemporaryRootOwnerSlotIdentity()) return true; + for (LifecycleRuntimeState.TemporaryRootLease lease : state().temporaryRoots) { + if (directlyReferencesTemporaryRootValue(lease.root(), target)) return true; + } + return false; } - private static boolean directlyReferences(RuntimeBase value, RuntimeBase target, - IdentityHashMap visited) { + private static boolean directlyReferencesTemporaryRootValue( + RuntimeBase value, RuntimeBase target) { if (value == target) return true; - if (value == null || visited.put(value, Boolean.TRUE) != null) return false; - if (value instanceof RuntimeScalar scalar - && !WeakRefRegistry.isweak(scalar) - && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && scalar.value instanceof RuntimeBase referent) { - return directlyReferences(referent, target, visited); + if (value instanceof RuntimeScalar scalar) { + return !WeakRefRegistry.isweak(scalar) + && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 + && scalar.value == target; } - if (value instanceof RuntimeList list) { - for (RuntimeBase element : list.elements) { - if (directlyReferences(element, target, visited)) return true; - } - } else if (value instanceof RuntimeArray array) { + if (value instanceof RuntimeArray array) { + if (array.elements == null) return false; for (RuntimeScalar element : array.elements) { - if (directlyReferences(element, target, visited)) return true; + if (element == target || element != null + && !WeakRefRegistry.isweak(element) + && (element.type & RuntimeScalarType.REFERENCE_BIT) != 0 + && element.value == target) return true; } - } else if (value instanceof RuntimeHash hash) { - for (RuntimeScalar element : hash.elements.values()) { - if (directlyReferences(element, target, visited)) return true; + return false; + } + if (value instanceof RuntimeHash hash) { + if (hash.elements == null) return false; + for (java.util.Map.Entry entry : hash.elements.entrySet()) { + RuntimeScalar element = entry.getValue(); + if (element == target || element != null + && !WeakRefRegistry.isweak(element) + && (element.type & RuntimeScalarType.REFERENCE_BIT) != 0 + && element.value == target) return true; + } + return false; + } + if (value instanceof RuntimeList list) { + if (list instanceof RuntimeControlFlowList flow + && directlyReferencesTemporaryRootValue(flow.getReturnValue(), target)) { + return true; + } + for (RuntimeBase element : list.elements) { + if (element == target || element instanceof RuntimeScalar scalar + && directlyReferencesTemporaryRootValue(scalar, target)) return true; } } return false; } - public static void retainSuspendedRoot(RuntimeBase root) { - if (root != null) { - state().suspendedRoots.merge(root, 1, Integer::sum); - invalidateAllRootSnapshots(); - } + public static void clearTemporaryRoots() { + LifecycleRuntimeState state = state(); + ArrayDeque roots = state.temporaryRoots; + while (!roots.isEmpty()) roots.pop().release(); } - public static void releaseSuspendedRoot(RuntimeBase root) { - if (root == null) return; + /** + * Retain reference values in an evaluated list source until its foreach + * finishes. The returned depth is the matching cleanup point. + */ + public static int pushForeachSourceOwners(RuntimeBase source) { LifecycleRuntimeState state = state(); - Integer count = state.suspendedRoots.get(root); - if (count == null) return; - if (count <= 1) state.suspendedRoots.remove(root); - else state.suspendedRoots.put(root, count - 1); - invalidateAllRootSnapshots(); + int depth = state.foreachSourceOwners.size(); + if (!(source instanceof RuntimeList) && !(source instanceof RuntimeArray)) return depth; + + LifecycleRuntimeState.ForeachSourceOwnerLease lease = + new LifecycleRuntimeState.ForeachSourceOwnerLease(); + try { + if (source instanceof RuntimeArray array) { + // A durable array slot already owns its element references. + // Temporary result arrays need direct item owners because + // their container slots do not outlive the statement flush + // that precedes the first foreach iteration. + if (!array.hasPersistentPerlStrongOwnerIdentity()) { + for (RuntimeScalar value : array.elements) lease.retain(value); + lease.retainReferent(array); + } + } else { + RuntimeList list = (RuntimeList) source; + for (java.util.Iterator values = list.iterator(); values.hasNext();) { + lease.retain(values.next()); + } + } + state.foreachSourceOwners.push(lease); + return depth; + } catch (RuntimeException | Error failure) { + try { + lease.release(); + } catch (RuntimeException | Error cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + throw failure; + } } - public static java.util.List snapshotSuspendedRoots() { - return new java.util.ArrayList<>(state().suspendedRoots.keySet()); + /** Current foreach source owner depth for frame and eval cleanup. */ + public static int foreachSourceOwnerDepth() { + return state().foreachSourceOwners.size(); } - public static void clearSuspendedRoots() { - state().suspendedRoots.clear(); - state().temporaryRoots.clear(); - invalidateAllRootSnapshots(); + /** Release foreach source owners acquired after {@code depth}. */ + public static void restoreForeachSourceOwnerDepth(int depth) { + if (depth < 0) { + throw new IllegalArgumentException("Invalid foreach source owner depth: " + depth); + } + LifecycleRuntimeState state = state(); + if (state.foreachSourceOwners.size() < depth) { + // An awaited callback can resume and complete a foreach whose + // source lease was part of this caller's saved depth. The resumed + // continuation already released that lease; this older Java frame + // must not try to restore a stack depth from before the await. + return; + } + while (state.foreachSourceOwners.size() > depth) { + state.foreachSourceOwners.pop().release(); + } } - /** - * Phase I: O(1) check whether the given scalar is in - * {@link #deferredCaptures}. Used by the reachability walker to - * filter out stale {@link ScalarRefRegistry} seeds. - */ public static boolean isDeferredCapture(RuntimeScalar scalar) { if (scalar == null) return false; return state().deferredCapturesSet.containsKey(scalar); } /** - * Schedule a deferred refCount decrement for a tracked referent. - * Called from delete() when removing a tracked blessed reference - * from a container. + * Whether a release for this exact referent is queued while a call argument + * is being staged. The staging scalar is a live argument alias, so it must + * acquire that identity before the queued temporary release can drain. */ - public static void deferDecrement(RuntimeBase base) { - deferDecrement(base, null); + static boolean hasPendingStrongReleaseFor(RuntimeBase referent) { + if (referent == null) return false; + for (RuntimeBase pending : state().pending) { + if (pending == referent) return true; + } + return false; } - /** Queue a decrement paired with a trace-only non-scalar owner kind. */ - public static void deferDecrement(RuntimeBase base, String transientOwnerKind) { - if (base.refCountTrace) { - base.traceRefCount(0, "MortalList.deferDecrement (queued)"); + /** Whether this referent still has its first-bless mortal owner queued. */ + public static boolean hasPendingBlessTemporaryFor(RuntimeBase referent) { + if (referent == null) return false; + LifecycleRuntimeState state = state(); + for (int i = 0; i < state.pending.size(); i++) { + if (state.pending.get(i) == referent + && "bless mortal temporary".equals( + state.pendingTransientOwnerKinds.get(i))) { + return true; + } } + return false; + } + + /** Find the pending release for this exact scalar slot and referent. */ + static PerlOwnerSlot.PendingRelease pendingCountedReleaseFor( + RuntimeScalar owner, RuntimeBase referent) { + if (owner == null || referent == null) return null; + LifecycleRuntimeState state = state(); + for (int i = 0; i < state.pending.size(); i++) { + if (state.pending.get(i) != referent) continue; + java.lang.ref.WeakReference ownerReference = + state.pendingOwnerScalars.get(i); + if (ownerReference == null || ownerReference.get() != owner) continue; + RuntimeBase.PendingOwnerRelease pendingRelease = + state.pendingOwnerReleases.get(i); + if (pendingRelease != null && pendingRelease.ownerSlotRelease != null) { + return pendingRelease.ownerSlotRelease; + } + } + return null; + } + + /** + * Complete the exact return and source releases after a receiving scalar + * has acquired the returned referent. Source provenance is a stable slot + * identity plus its release sequence; unrelated pending owners of the + * same object remain queued. + */ + static void consumeMortalReturnValue(RuntimeScalar returned, RuntimeBase destinationReferent) { + if (!isActive() || returned == null || !returned.hasMortalReturnSnapshot() + || returned.value != destinationReferent || destinationReferent == null + || RuntimeCode.hasActiveCallArgumentFrame()) { + return; + } + LifecycleRuntimeState state = state(); + if (state.flushing || state.flushSuppressed) return; + + int returnIndex = -1; + int sourceIndex = -1; + for (int i = 0; i < state.pending.size(); i++) { + if (state.pending.get(i) != destinationReferent) continue; + RuntimeBase.PendingOwnerRelease ownerRelease = + state.pendingOwnerReleases.get(i); + PerlOwnerSlot.PendingRelease slotRelease = ownerRelease == null + ? null : ownerRelease.ownerSlotRelease; + if (slotRelease == null) continue; + if (slotRelease.kind() == PerlOwnerSlot.Kind.RETURN_VALUE) { + java.lang.ref.WeakReference ownerReference = + state.pendingOwnerScalars.get(i); + if (ownerReference != null && ownerReference.get() == returned) { + returnIndex = i; + continue; + } + } + if (slotRelease.ownerSlotIdentity() == returned.mortalReturnSourceOwnerIdentity() + && slotRelease.sequence() == returned.mortalReturnSourceReleaseSequence() + && destinationReferent == returned.mortalReturnSourceReferent()) { + sourceIndex = i; + } + } + + int untrackedReturnIndex = state.pendingUntrackedReturnOwnerReleases + .indexOf(returned); + PendingOwnerEntry returnEntry = null; + PendingOwnerEntry sourceEntry = null; + state.flushing = true; + try { + if (returnIndex >= 0 && returnIndex == sourceIndex) { + sourceIndex = -1; + } + if (returnIndex > sourceIndex) { + returnEntry = removePendingOwnerEntry(state, returnIndex); + if (sourceIndex >= 0) sourceEntry = removePendingOwnerEntry(state, sourceIndex); + } else { + if (sourceIndex >= 0) sourceEntry = removePendingOwnerEntry(state, sourceIndex); + if (returnIndex >= 0) returnEntry = removePendingOwnerEntry(state, returnIndex); + } + + if (sourceEntry != null) { + processDeferredBase(sourceEntry.base(), false, + sourceEntry.ownerRelease(), sourceEntry.transientOwnerKind()); + } + if (returnEntry != null) { + processDeferredBase(returnEntry.base(), false, + returnEntry.ownerRelease(), returnEntry.transientOwnerKind()); + } + if (untrackedReturnIndex >= 0) { + state.pendingUntrackedReturnOwnerReleases.remove(untrackedReturnIndex); + returned.releaseMortalReturnValueOwner(); + } + returned.finishMortalReturnHandoff(); + } finally { + state.flushing = false; + } + refreshBoundaryWork(state); + } + + private static PendingOwnerEntry removePendingOwnerEntry( + LifecycleRuntimeState state, int index) { + RuntimeBase base = state.pending.remove(index); + RuntimeBase.PendingOwnerRelease ownerRelease = + state.pendingOwnerReleases.remove(index); + state.pendingOwnerScalars.remove(index); + state.pendingArgumentFrames.remove(index); + String transientOwnerKind = state.pendingTransientOwnerKinds.remove(index); + return new PendingOwnerEntry(base, ownerRelease, transientOwnerKind); + } + + /** + * Acquire and queue the mortal reference created by the first bless of a + * referent. Unlike an ordinary removed storage edge, this temporary stays + * live until the deferred boundary processes its release. + */ + public static void deferBlessTemporary(RuntimeBase base, boolean strongPerlOwner) { + if (base == null) return; + if (base.isPerlDestroyed()) { + throw new IllegalStateException("cannot bless a destroyed referent"); + } + PerlOwnerSlot temporaryOwner = new PerlOwnerSlot(PerlOwnerSlot.Kind.SCALAR_CELL); + temporaryOwner.acquireCountedTemporaryOwner( + base, "ReferenceOperators.bless mortal temporary"); + base.acquireTransientTraceOwner("bless mortal temporary", + "ReferenceOperators.bless"); + PerlOwnerSlot.PendingRelease slotRelease = strongPerlOwner + ? temporaryOwner.releaseCountedIdentityAtCompletion() + : temporaryOwner.releaseCountedIdentity(); + LifecycleRuntimeState state = state(); markBoundaryWork(state); - queueDeferredBase(state, base, null, transientOwnerKind); + RuntimeBase.PendingOwnerRelease ownerRelease = + base.queueOwnerSlotRelease(slotRelease); + queueDeferredBase(state, base, ownerRelease, "bless mortal temporary"); } /** Queue the deferred release together with the array scalar that owned it. */ @@ -252,6 +460,20 @@ public static void deferDecrementFromArraySlot( if (base.refCountTrace) { base.traceRefCount(0, releaseSite + " (array-slot decrement queued)"); } + deferCountedSlotRelease(base, ownerScalar, releaseSite); + } + + /** Queue a mutable scalar cell's counted release before its value is restored. */ + public static void deferDecrementFromScalarSlot( + RuntimeBase base, RuntimeScalar ownerScalar, String releaseSite) { + if (base.refCountTrace) { + base.traceRefCount(0, releaseSite + " (scalar-slot decrement queued)"); + } + deferCountedSlotRelease(base, ownerScalar, releaseSite); + } + + private static void deferCountedSlotRelease( + RuntimeBase base, RuntimeScalar ownerScalar, String releaseSite) { LifecycleRuntimeState state = state(); markBoundaryWork(state); RuntimeBase.PendingOwnerRelease ownerRelease = @@ -262,8 +484,15 @@ public static void deferDecrementFromArraySlot( /** Queue a closure-capture bridge decrement with owner-slot provenance. */ static void deferOwnerSlotDecrement(RuntimeBase base, String transientOwnerKind, PerlOwnerSlot.PendingRelease slotRelease) { + deferOwnerSlotDecrement(base, transientOwnerKind, slotRelease, + "MortalList.deferOwnerSlotDecrement"); + } + + private static void deferOwnerSlotDecrement(RuntimeBase base, String transientOwnerKind, + PerlOwnerSlot.PendingRelease slotRelease, + String releaseSite) { if (base.refCountTrace) { - base.traceRefCount(0, "MortalList.deferOwnerSlotDecrement (queued)"); + base.traceRefCount(0, releaseSite + " (queued)"); } LifecycleRuntimeState state = state(); markBoundaryWork(state); @@ -271,6 +500,247 @@ static void deferOwnerSlotDecrement(RuntimeBase base, String transientOwnerKind, queueDeferredBase(state, base, ownerRelease, transientOwnerKind); } + /** Consume one exact scalar-edge release after its replacement is published. */ + static void releaseCountedOwnerSlotImmediately( + RuntimeBase base, PerlOwnerSlot.PendingRelease slotRelease, String releaseSite) { + releaseCountedOwnerSlotImmediately(base, slotRelease, null, releaseSite); + } + + /** Retire an exact scalar edge while building host-side storage. */ + static void releaseCountedOwnerWithoutPerlRuntime( + RuntimeScalar owner, RuntimeBase referent, String releaseSite) { + Objects.requireNonNull(owner, "owner"); + Objects.requireNonNull(referent, "referent"); + Objects.requireNonNull(releaseSite, "releaseSite"); + if (PerlRuntime.currentOrNull() != null) { + throw new IllegalStateException( + "host-side counted release cannot run inside a Perl runtime"); + } + PerlOwnerSlot slot = owner.countedOwnerSlot(); + if (!owner.refCountOwned || owner.value != referent + || slot == null || !slot.isActive() || slot.referent() != referent + || slot.countedScalarOwner() != owner + || !PerlOwnerSlot.isCountedKind(slot.kind())) { + throw new IllegalStateException( + "host-side counted release lost its current scalar owner at " + releaseSite); + } + if (referent.refCount <= 0) { + throw new IllegalStateException( + "host-side counted release requires a positive reference count at " + + releaseSite); + } + + PerlOwnerSlot.PendingRelease release = + owner.releaseCountedOwnerIdentity(referent, releaseSite, true); + if (release == null) { + throw new IllegalStateException( + "host-side counted release lost its release token at " + releaseSite); + } + releaseCountedOwnerSlotImmediately( + referent, release, null, releaseSite, false, true); + } + + static void releaseCountedOwnerSlotImmediately( + RuntimeBase base, PerlOwnerSlot.PendingRelease slotRelease, + String transientOwnerKind, String releaseSite) { + releaseCountedOwnerSlotImmediately( + base, slotRelease, transientOwnerKind, releaseSite, false); + } + + private static void releaseCountedOwnerSlotImmediately( + RuntimeBase base, PerlOwnerSlot.PendingRelease slotRelease, + String transientOwnerKind, String releaseSite, + boolean clearWeakRefsForLocalBinding) { + releaseCountedOwnerSlotImmediately( + base, slotRelease, transientOwnerKind, releaseSite, + clearWeakRefsForLocalBinding, false); + } + + private static void releaseCountedOwnerSlotImmediately( + RuntimeBase base, PerlOwnerSlot.PendingRelease slotRelease, + String transientOwnerKind, String releaseSite, + boolean clearWeakRefsForLocalBinding, boolean hostCountOnly) { + if (base == null || slotRelease == null) return; + if (PerlRuntime.currentOrNull() == null) { + if (hostCountOnly) { + if (base.refCount <= 0) { + throw new IllegalStateException( + "host-side owner-slot release requires a positive reference count at " + + releaseSite); + } + base.releaseTrackedOwnerCount(releaseSite); + slotRelease.complete(); + return; + } + // A host-side owner transition can retire a non-final count without + // a Perl execution context. Keep this path limited to count-only + // releases and empty unblessed aggregates; any final Perl lifecycle + // work still requires the owning runtime to be bound. + if (base.currentlyDestroying || !base.isRefCountTracked() + || base.isPerlDestroyed()) { + slotRelease.complete(); + return; + } + if (base.refCount > 1) { + base.releaseTrackedOwnerCount(releaseSite); + slotRelease.complete(); + return; + } + if (base.refCount == 1 && base.blessId == 0 + && !base.hasOwnerSlots() && isEmptyUnblessedAggregate(base)) { + base.releaseTrackedOwnerCount(releaseSite); + slotRelease.complete(); + return; + } + throw new IllegalStateException( + "final Perl owner release requires a bound PerlRuntime at " + releaseSite); + } + int checkpoint = pendingSize(); + deferOwnerSlotDecrement(base, transientOwnerKind, slotRelease, releaseSite); + // Scalar overwrite and weaken historically leave weak observers alone + // when an unrelated local binding keeps the referent alive. + drainPendingSince(checkpoint, clearWeakRefsForLocalBinding); + } + + private static boolean isEmptyUnblessedAggregate(RuntimeBase base) { + return base instanceof RuntimeArray array + && (array.elements == null || array.elements.isEmpty()) + || base instanceof RuntimeHash hash + && (hash.elements == null || hash.elements.isEmpty()); + } + + /** Release a counted native owner through the normal destruction transition. */ + public static void releaseCountedNativeOwner( + RuntimeBase base, PerlOwnerSlot ownerSlot) { + releaseCountedNativeOwner(base, ownerSlot, + CountedNativeReleasePolicy.FINALIZE_REFERENT, + "MortalList.releaseCountedNativeOwner"); + } + + /** Retire a regex callback's count before its callback owner releases CODE captures. */ + static void releaseRegexCallbackOwner( + RuntimeBase base, PerlOwnerSlot ownerSlot, String releaseSite) { + if (ownerSlot == null || ownerSlot.kind() != PerlOwnerSlot.Kind.REGEX_CALLBACK) { + throw new IllegalArgumentException( + "regex callback release requires a regex callback owner slot"); + } + releaseCountedNativeOwner(base, ownerSlot, + CountedNativeReleasePolicy.RETIRE_COUNT_ONLY, releaseSite); + } + + private enum CountedNativeReleasePolicy { + FINALIZE_REFERENT, + RETIRE_COUNT_ONLY + } + + /** Keep slot retirement, paired count decrement, and lifecycle policy together. */ + private static void releaseCountedNativeOwner( + RuntimeBase base, PerlOwnerSlot ownerSlot, + CountedNativeReleasePolicy policy, String releaseSite) { + if (base == null || ownerSlot == null || ownerSlot.referent() != base) return; + if (!ownerSlot.isCountedNativeOwner()) { + ownerSlot.release(); + return; + } + PerlOwnerSlot.PendingRelease release = ownerSlot.releaseCountedNativeIdentity(); + if (release == null) return; + if (policy == CountedNativeReleasePolicy.RETIRE_COUNT_ONLY) { + if (base.refCount > 0) base.releaseTrackedOwnerCount(releaseSite); + release.complete(); + return; + } + if (base.refCount <= 0) { + release.complete(); + return; + } + releaseCountedOwnerSlotImmediately( + base, release, null, releaseSite, true); + } + + /** Release a direct method-invocant edge, deferring its final count to the result boundary. */ + static void releaseCountedMethodInvocantOwner( + RuntimeBase base, PerlOwnerSlot ownerSlot, String releaseSite, + boolean abandoned) { + if (base == null || ownerSlot == null + || !ownerSlot.isMethodInvocantOwner(base)) return; + PerlOwnerSlot.PendingRelease release = ownerSlot.releaseCountedIdentity(); + if (release == null) return; + if (base.refCount <= 0) { + release.complete(); + return; + } + if (base.currentlyDestroying) { + // This temporary call edge has ended, even though the referent is + // still inside DESTROY. Retire its count without starting another + // destruction pass; the active DESTROY boundary decides whether + // any newly acquired owners resurrected the object. + base.releaseTrackedOwnerCount(releaseSite); + release.complete(); + return; + } + if (base.refCount > 1) { + base.releaseTrackedOwnerCount(releaseSite); + release.complete(); + return; + } + int checkpoint = pendingSize(); + deferOwnerSlotDecrement(base, null, release); + if (abandoned) drainPendingSince(checkpoint); + } + + /** Release one exact scalar-backed owner at the operation that drops its Perl edge. */ + public static void releaseCountedOwnerImmediately(RuntimeScalar owner, String releaseSite) { + if (owner == null || !owner.refCountOwned + || !(owner.value instanceof RuntimeBase base)) return; + PerlOwnerSlot ownerSlot = owner.countedOwnerSlot(); + if (ownerSlot == null || !ownerSlot.isActive() || ownerSlot.referent() != base + || !PerlOwnerSlot.isCountedKind(ownerSlot.kind())) { + throw new IllegalStateException( + "counted argument owner lost its active slot at " + releaseSite); + } + PerlOwnerSlot.PendingRelease release = + owner.releaseCountedOwnerIdentity(base, releaseSite, true); + if (release == null) { + throw new IllegalStateException( + "counted argument owner lost its release token at " + releaseSite); + } + if (base.refCount <= 0) { + release.complete(); + return; + } + if (base.currentlyDestroying) { + // The storage edge is gone. Keep the no-reentrant-DESTROY guard, + // but do not leave its legacy count behind if this object is + // rescued before the current destructor returns. + base.releaseTrackedOwnerCount(releaseSite); + release.complete(); + return; + } + releaseCountedOwnerSlotImmediately(base, release, releaseSite); + } + + /** Balance DESTROY's synthetic $_[0] edge without re-entering destruction. */ + static void releaseDestroySelfArgument(RuntimeScalar owner, String releaseSite) { + if (owner == null || !owner.refCountOwned + || !(owner.value instanceof RuntimeBase base)) return; + PerlOwnerSlot ownerSlot = owner.countedOwnerSlot(); + if (!base.currentlyDestroying || base.refCount <= 0 + || ownerSlot == null || !ownerSlot.isActive() + || ownerSlot.referent() != base || ownerSlot.countedScalarOwner() != owner + || !PerlOwnerSlot.isCountedKind(ownerSlot.kind())) { + throw new IllegalStateException( + "DESTROY self argument lost its counted owner at " + releaseSite); + } + PerlOwnerSlot.PendingRelease release = + owner.releaseCountedOwnerIdentity(base, releaseSite, true); + if (release == null) { + throw new IllegalStateException( + "DESTROY self argument lost its release token at " + releaseSite); + } + base.releaseTrackedOwnerCount(releaseSite); + release.complete(); + } + private static void queueDeferredBase(LifecycleRuntimeState state, RuntimeBase base, RuntimeBase.PendingOwnerRelease ownerRelease) { queueDeferredBase(state, base, ownerRelease, null); @@ -289,6 +759,8 @@ private static void queueDeferredBase(LifecycleRuntimeState state, RuntimeBase b state.pendingOwnerReleases.add(ownerRelease); state.pendingOwnerScalars.add(ownerScalar == null ? null : new java.lang.ref.WeakReference<>(ownerScalar)); + state.pendingArgumentFrames.add( + RuntimeCode.argumentAliasFrameForOwner(ownerScalar)); state.pendingTransientOwnerKinds.add(transientOwnerKind); } @@ -301,14 +773,116 @@ public static void deferTiedObjectRelease(TiedVariableBase tiedVariable) { public static void deferIoOwnerRelease(RuntimeScalar scalar) { LifecycleRuntimeState state = state(); - if (!state.mortalActive || scalar == null || !scalar.ioOwner) return; + if (!state.mortalActive || scalar == null || !scalar.hasIoOwner()) return; markBoundaryWork(state); state.pendingIoReleases.add(scalar); } + /** Queue an untracked mortal return slot for its caller's normal boundary. */ + static void deferUntrackedReturnValueOwnerRelease(RuntimeScalar scalar) { + if (scalar == null || scalar.untrackedReferenceOwnerSlot() == null) return; + LifecycleRuntimeState state = state(); + markBoundaryWork(state); + state.pendingUntrackedReturnOwnerReleases.add(scalar); + } + + /** Retire a one-shot list-assignment RHS at its enclosing Perl mortal boundary. */ + static void deferTransientListAssignmentRhs(RuntimeArray rhs) { + if (rhs == null) return; + LifecycleRuntimeState state = state(); + if (!state.mortalActive) { + releaseTransientListAssignmentRhs(rhs); + return; + } + RuntimeCode executionCode = RuntimeCode.getActiveCodeAt(0); + int executionDepth = RuntimeCode.currentExecutionDepth(); + boolean topLevel = RuntimeCode.isCurrentExecutionTopLevel(); + int drainAtExecutionDepth = topLevel + ? executionDepth : Math.max(0, executionDepth - 1); + RuntimeCode drainAtExecutionCode = drainAtExecutionDepth == executionDepth + ? executionCode : RuntimeCode.getActiveCodeAt(1); + LifecycleRuntimeState.TransientListAssignmentFrame frame = + new LifecycleRuntimeState.TransientListAssignmentFrame( + drainAtExecutionCode, drainAtExecutionDepth); + long drainAtStatementBoundary = state.statementBoundarySequence + 1; + markBoundaryWork(state); + LifecycleRuntimeState.TransientListAssignmentQueue queue = + state.pendingTransientListAssignmentRhsByFrame.get(frame); + if (queue == null) { + boolean reusing = state.reusableTransientListAssignmentQueues != null; + queue = state.obtainTransientListAssignmentQueue(); + if (reusing) LifecycleHotPathDiagnostics.transientRhsFrameQueueReused(); + else LifecycleHotPathDiagnostics.frameQueueAllocated(); + state.pendingTransientListAssignmentRhsByFrame.put(frame, queue); + } + queue.append(rhs, ++state.nextTransientListAssignmentSequence, + drainAtStatementBoundary); + LifecycleHotPathDiagnostics.transientRhsAppended(); + } + + /** Hand pending returned-list copies to the caller when their frame exits. */ + static void handoffTransientListAssignmentRhs( + LifecycleRuntimeState state, + RuntimeCode executionCode, int executionDepth, + RuntimeCode callerCode, int callerDepth) { + if (state == null || executionDepth <= 0) return; + LifecycleRuntimeState.TransientListAssignmentFrame source = + new LifecycleRuntimeState.TransientListAssignmentFrame( + executionCode, executionDepth); + LifecycleRuntimeState.TransientListAssignmentQueue sourceQueue = + state.pendingTransientListAssignmentRhsByFrame.remove(source); + if (sourceQueue == null || sourceQueue.isEmpty()) { + if (sourceQueue != null) state.recycleTransientListAssignmentQueue(sourceQueue); + return; + } + + LifecycleRuntimeState.TransientListAssignmentFrame target = + new LifecycleRuntimeState.TransientListAssignmentFrame( + callerCode, Math.max(0, callerDepth)); + long nextBoundary = state.statementBoundarySequence + 1; + LifecycleRuntimeState.TransientListAssignmentQueue targetQueue = + state.pendingTransientListAssignmentRhsByFrame.get(target); + if (targetQueue == null) { + sourceQueue.retagAll(nextBoundary); + state.pendingTransientListAssignmentRhsByFrame.put(target, sourceQueue); + } else { + sourceQueue.handoffTo(targetQueue, nextBoundary); + state.recycleTransientListAssignmentQueue(sourceQueue); + } + } + + static void releaseTransientListAssignmentRhs(RuntimeArray rhs) { + if (rhs == null) return; + if (rhs.elements != null) { + for (RuntimeScalar cell : rhs.elements) { + if (cell != null && cell.getContainerOwner() == rhs) { + cell.releaseContainerOwner(rhs); + } + } + rhs.elements.clear(); + } + rhs.transientListAssignmentRhs = false; + } + private static void releaseTransientListAssignmentRhsAtBoundary( + LifecycleRuntimeState state) { + RuntimeCode executionCode = RuntimeCode.getActiveCodeAt(0); + int executionDepth = RuntimeCode.currentExecutionDepth(); + LifecycleRuntimeState.TransientListAssignmentFrame frame = + new LifecycleRuntimeState.TransientListAssignmentFrame( + executionCode, executionDepth); + LifecycleRuntimeState.TransientListAssignmentQueue queue = + state.pendingTransientListAssignmentRhsByFrame.get(frame); + if (queue == null) return; + queue.drainAtBoundary(state.statementBoundarySequence); + if (queue.isEmpty()) { + state.pendingTransientListAssignmentRhsByFrame.remove(frame); + state.recycleTransientListAssignmentQueue(queue); + } + } + /** * Record a captured scalar whose scope has exited but whose refCount - * could not be decremented because {@code captureCount > 0}. + * could not be decremented because a closure owner remains. * Called from {@link RuntimeScalar#scopeExitCleanup} for non-CODE * blessed references that are captured by closures. *

    @@ -321,77 +895,11 @@ public static void addDeferredCapture(RuntimeScalar scalar) { markBoundaryWork(state); state.deferredCaptures.add(scalar); state.deferredCapturesSet.merge(scalar, 1, Integer::sum); - noteDeferredScopeExitCaptureCandidate(state, scalar); - if (scalar.captureCount == 0 && scalar.scopeExited) { + if (!scalar.hasClosureCaptureOwner() && scalar.scopeExited) { state.deferredCapturesMayBeReady = true; } } - public static void noteDeferredScopeExitCaptureCandidate(RuntimeScalar scalar) { - if (scalar == null || !scalar.scopeExited - || (scalar.type & RuntimeScalarType.REFERENCE_BIT) == 0 - || !(scalar.value instanceof RuntimeBase base) - || !isDeferredScopeExitCandidate(base)) return; - noteDeferredScopeExitCaptureCandidate(state(), scalar); - } - - private static void noteDeferredScopeExitCaptureCandidate( - LifecycleRuntimeState state, RuntimeScalar scalar) { - if (scalar.value instanceof RuntimeBase base && isDeferredScopeExitCandidate(base)) { - state.deferredScopeExitCaptureCandidates.add(scalar); - } - } - - private static boolean isDeferredScopeExitCandidate(RuntimeBase base) { - if (base == null || base.blessId == 0) return false; - if (WeakRefRegistry.hasWeakRefsTo(base)) return true; - String className = NameNormalizer.getBlessStr(base.blessId); - return className != null && DestroyDispatch.classHasDestroy(base.blessId, className); - } - - /** - * Release eval STRING over-captures whose declaring scope just exited and - * which cannot be reached by live code or an END block. Reachability sweeps - * also perform this check, but waiting for their cadence can keep request - * objects alive across unrelated calls (and defer their cleanup until - * global destruction). - */ - private static void processUnreachableScopeExitCaptureCandidates( - LifecycleRuntimeState state) { - if (state.deferredScopeExitCaptureCandidates.isEmpty()) return; - - Set endReachable = ReachabilityWalker.walkEndBlockRoots(); - Set cycleProtected = ReachabilityWalker.strongCycleProtectedReferents(); - boolean found = false; - for (RuntimeScalar scalar : new ArrayList<>(state.deferredScopeExitCaptureCandidates)) { - if (!scalar.scopeExited) continue; - RuntimeBase base = scalar.value instanceof RuntimeBase value ? value : null; - boolean scalarReachable = ReachabilityWalker.isScalarReachable(scalar) - || ReachabilityWalker.isReachableFromRoots(scalar); - boolean retained = endReachable.contains(scalar) - || (base != null && endReachable.contains(base)) - || (base != null && cycleProtected.contains(base)) - || scalarReachable; - if (retained) continue; - - scalar.releaseUnreachableSemanticCaptureOwner(); - Integer deferredCount = state.deferredCapturesSet.get(scalar); - if (deferredCount != null) { - for (int i = state.deferredCaptures.size() - 1; i >= 0; i--) { - if (state.deferredCaptures.get(i) != scalar) continue; - deferDecrementIfTracked(scalar); - state.deferredCaptures.remove(i); - removeFromDeferredSet(scalar); - } - } else if (base != null) { - requestTargetedWeakSweep(base); - } - found = true; - } - state.deferredScopeExitCaptureCandidates.clear(); - if (found) flushAboveMark(); - } - static void noteDeferredCaptureMayBeReady() { LifecycleRuntimeState state = state(); if (!state.deferredCaptures.isEmpty()) { @@ -401,18 +909,18 @@ static void noteDeferredCaptureMayBeReady() { } /** - * Process deferred captures whose captureCount has already reached 0. + * Process deferred captures after their final closure owner has left. * Called from {@link #popAndFlush()} at block scope exit, AFTER the * mortal list has been processed (which may trigger callDestroy → - * releaseCaptures → captureCount decrements on captured variables). + * releaseCaptures → capture owners are retired from captured variables). *

    * This bridges the gap between deferred capture registration (at scope - * exit when captureCount > 0) and flushDeferredCaptures (after the main + * exit while a closure owner remains) and flushDeferredCaptures (after the main * script returns). Without this, objects whose captures are fully * released at block exit still appear "alive" to leak tracers like * DBIC's assert_empty_weakregistry, which runs inside the main script. *

    - * Only processes entries where captureCount == 0 AND scopeExited == true, + * Only processes entries with no closure owner AND scopeExited == true, * leaving others for later processing (either a subsequent block exit * or flushDeferredCaptures at script end). */ @@ -423,7 +931,7 @@ private static void processReadyDeferredCaptures(LifecycleRuntimeState state) { boolean found = false; for (int i = state.deferredCaptures.size() - 1; i >= 0; i--) { RuntimeScalar scalar = state.deferredCaptures.get(i); - if (scalar.captureCount == 0 && scalar.scopeExited) { + if (!scalar.hasClosureCaptureOwner() && scalar.scopeExited) { deferDecrementIfTracked(scalar); state.deferredCaptures.remove(i); removeFromDeferredSet(scalar); @@ -459,72 +967,25 @@ private static void removeFromDeferredSet(RuntimeScalar scalar) { */ public static void flushDeferredCaptures() { LifecycleRuntimeState state = state(); - if (state.deferredCaptures.isEmpty()) return; - for (RuntimeScalar scalar : state.deferredCaptures) { - deferDecrementIfTracked(scalar); + if (!state.deferredCaptures.isEmpty()) { + for (RuntimeScalar scalar : state.deferredCaptures) { + deferDecrementIfTracked(scalar); + } + state.deferredCaptures.clear(); + state.deferredCapturesSet.clear(); + state.deferredCapturesMayBeReady = false; + flush(); } - state.deferredCaptures.clear(); - state.deferredCapturesSet.clear(); - state.deferredCapturesMayBeReady = false; - flush(); - - // After flushing deferred captures, clear weak refs for objects that - // were rescued by DESTROY (e.g., Schema::DESTROY self-save pattern). - // This must happen AFTER the flush above so that all pending refCount - // decrements have been processed and before global destruction. - DestroyDispatch.clearRescuedWeakRefs(); - - // Final sweep: clear weak refs for ALL remaining blessed objects. - // At this point the main script has returned and all lexical scopes - // have exited. Some objects may still have inflated selective - // refCounts (due to JVM temporaries, method-call copies, interpreter - // captures) that prevent DESTROY from firing. Their weak refs would - // remain defined forever, causing DBIC's leak tracer to report false - // leaks. Clearing weak refs here is safe because: - // 1. Only weak refs are cleared — the Java objects remain alive - // 2. CODE refs are excluded (they may still be called from stashes) - // 3. END blocks have completed, so real closure captures are no longer needed - WeakRefRegistry.clearAllBlessedWeakRefs(); + + // Release rescued lifecycle bookkeeping from current Perl owner slots + // after END. The queue itself is not a Perl owner. + DestroyDispatch.processRescuedObjects(); + } - /** - * Release scope-exited captures that cannot be reached by an END block or - * a package CODE slot, while retaining genuine END-visible captures for - * the unconditional post-END drain in {@link #flushDeferredCaptures()}. - * - * This preserves Perl's ordering: unrelated file lexicals are destroyed - * before END, but values captured by code that END can invoke stay alive - * until END has completed. - */ + /** Process rescued objects from current Perl owner slots before END callbacks. */ public static void flushDeferredCapturesBeforeEnd() { - LifecycleRuntimeState state = state(); - Set endReachable = ReachabilityWalker.walkEndBlockRoots(); - ReachabilityWalker.releaseUnreachableScopeExitedCaptureOwners( - WeakRefRegistry.snapshotWeakRefReferents(), endReachable); - boolean found = false; - for (int i = state.deferredCaptures.size() - 1; i >= 0; i--) { - RuntimeScalar scalar = state.deferredCaptures.get(i); - boolean retained = endReachable.contains(scalar) - || (scalar.value instanceof RuntimeBase base && endReachable.contains(base)); - if (retained) continue; - - // This scope-exited pad was captured by eval STRING, but no END - // block can reach it. Its semantic capture edge must not keep a - // blessed referent alive through global destruction merely because - // the compiled eval object is still Java-reachable. - scalar.releaseUnreachableSemanticCaptureOwner(); - deferDecrementIfTracked(scalar); - state.deferredCaptures.remove(i); - removeFromDeferredSet(scalar); - found = true; - } - if (found) flush(); - - // Weak-reference leak tracers commonly run from END. Selective - // refcounts can remain inflated by JVM temporaries even after all Perl - // owners have gone away, so clear only referents outside the semantic - // END graph now. Retained captures are cleared by the post-END drain. - WeakRefRegistry.clearBlessedWeakRefsExcept(endReachable); + DestroyDispatch.processRescuedObjects(); } /** @@ -535,38 +996,30 @@ public static void flushDeferredCapturesBeforeEnd() { */ public static void deferDecrementIfTracked(RuntimeScalar scalar) { if (!isActive() || scalar == null) return; + if (scalar.hasCodeSlotBinding()) return; if (!scalar.refCountOwned) return; if (((scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 || scalar.type == RuntimeScalarType.GLOB) && scalar.value instanceof RuntimeBase base) { if (base.refCount > 0) { - scalar.refCountOwned = false; if (base.refCountTrace) { - base.traceRefCount(0, "MortalList.deferDecrementIfTracked (queued, scalar.refCountOwned->false)"); + base.traceRefCount(0, "MortalList.deferDecrementIfTracked (queued owner release)"); } - base.releaseActiveOwner(scalar); LifecycleRuntimeState state = state(); markBoundaryWork(state); RuntimeBase.PendingOwnerRelease ownerRelease = base.queueOwnerRelease( scalar, "MortalList.deferDecrementIfTracked"); queueDeferredBase(state, base, ownerRelease, null, scalar); - } else if (base.refCount == 0 + } else if (base.isRefCountTracked() && base.refCount == 0 && base.clearedOwnedAggregateElement && WeakRefRegistry.hasWeakRefsTo(base)) { - // A nested-call reachability guard may have preserved this object - // at a selective count of zero. The scalar still represents a live - // Perl owner even though there is no count left to decrement. Drop - // that stale ownership marker and ask the reachability walker to - // decide at the next safe (non-nested) boundary whether the weak - // observers should be cleared. - scalar.refCountOwned = false; - if (base.refCountTrace) { - base.releaseOwner(scalar, "deferDecrementIfTracked zero-count owner"); - } - base.releaseActiveOwner(scalar); - requestImmediateWeakSweep(); + // A nested-call guard may preserve this object at a selective + // count of zero. Retire the stale scalar owner identity; scope + // exit or the final remaining owner slot performs cleanup. + base.retireZeroCountOwnerIdentity( + scalar, "deferDecrementIfTracked zero-count owner"); } - // Note: WEAKLY_TRACKED (-2) objects are NOT scheduled for destruction + // Note: weak-tracked objects are NOT scheduled for destruction // on scope exit. We can't count strong refs for non-DESTROY objects // (refs created before weaken() weren't tracked), so scope exit of // ONE reference doesn't mean there are no other strong refs (e.g., @@ -575,6 +1028,40 @@ public static void deferDecrementIfTracked(RuntimeScalar scalar) { } } + /** + * Complete one compiler-owned CODE-slot release at an isolated mortal mark. + * Compiled optree retirement is an exact CV-owner transition, not a statement + * boundary for older temporary releases in the caller's scope. + */ + public static void releaseTrackedCodeSlotAtExactBoundary(RuntimeScalar scalar) { + if (!isActive() || scalar == null || scalar.hasCodeSlotBinding() + || !scalar.refCountOwned || scalar.type != RuntimeScalarType.CODE + || !(scalar.value instanceof RuntimeCode code) || code.refCount <= 0) { + return; + } + LifecycleRuntimeState state = state(); + if (state.flushing || state.flushSuppressed || state.deferredReleaseDrainDepth != 0) { + deferDecrementIfTracked(scalar); + return; + } + + int pendingMark = state.pending.size(); + int tiedMark = state.pendingTiedReleases.size(); + int ioMark = state.pendingIoReleases.size(); + int returnOwnerMark = state.pendingUntrackedReturnOwnerReleases.size(); + pushMark(state); + deferDecrementIfTracked(scalar); + boolean queuedRelease = state.pending.size() > pendingMark + || state.pendingTiedReleases.size() > tiedMark + || state.pendingIoReleases.size() > ioMark + || state.pendingUntrackedReturnOwnerReleases.size() > returnOwnerMark; + if (queuedRelease) { + popAndFlush(); + } else { + popMark(state); + } + } + /** Release the tracked owner held by a scope-exited closure capture. */ public static void releaseCapturedDecrement(RuntimeScalar scalar) { if (!isActive() || scalar == null) return; @@ -585,13 +1072,28 @@ public static void releaseCapturedDecrement(RuntimeScalar scalar) { /** * Like {@link #deferDecrementIfTracked}, but delegates to * {@link RuntimeScalar#scopeExitCleanup} if the scalar is captured - * by a closure ({@code captureCount > 0}). + * by a closure owner. * Used by the explicit {@code return} bytecode path which bypasses * {@link RuntimeScalar#scopeExitCleanup}. */ public static void deferDecrementIfNotCaptured(RuntimeScalar scalar) { if (!isActive() || scalar == null) return; - if (scalar.captureCount > 0) { + PerlOwnerSlot countedOwner = scalar.countedOwnerSlot(); + if (scalar.refCountOwned + && ((scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 + || scalar.type == RuntimeScalarType.GLOB) + && scalar.value instanceof RuntimeBase referent + && countedOwner != null + && (countedOwner.kind() == PerlOwnerSlot.Kind.ARRAY_ELEMENT + || countedOwner.kind() == PerlOwnerSlot.Kind.HASH_ELEMENT) + && scalar.isCurrentAggregateElementOwner(referent, countedOwner)) { + // A foreach lexical aliases the aggregate's scalar cell. Scope + // cleanup must not retire that cell's persistent container edge + // as though the alias owned a second reference. + return; + } + if (scalar.hasClosureCaptureOwner() + || (scalar.referencedByScalarReference && scalar.localBindingExists)) { // Delegate to scopeExitCleanup which handles: // - Self-referential cycle detection (eval STRING closures) // - Setting scopeExited flag for deferred cleanup via releaseCaptures @@ -611,8 +1113,21 @@ public static void deferDecrementIfNotCaptured(RuntimeScalar scalar) { * Never-stored blessed objects (refCount == 0) are bumped to ensure DESTROY fires. */ public static void deferDestroyForContainerClear(Iterable elements) { - if (!isActive()) return; + if (elements == null) return; + boolean active = isActive(); for (RuntimeScalar scalar : elements) { + boolean aliasedScalarCell = scalar != null + && scalar.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ALIAS_CELL) != 0; + if (aliasedScalarCell) continue; + if (scalar != null && scalar.untrackedReferenceOwnerSlot() != null) { + scalar.refreshUntrackedReferenceOwner(); + } + // Aggregate clear/replacement retires the durable slot that kept + // an anonymous IO glob alive. Queue the holder release beside the + // referent cleanup so bulk mutation has the same lifecycle as + // delete and lexical scope exit. + deferIoOwnerRelease(scalar); + if (!active) continue; // Use the recursive path so a discarded wrapper/container also // releases references stored in its fields. Test::Deep's // temporary comparator is a blessed hash whose `val` field can @@ -622,6 +1137,21 @@ public static void deferDestroyForContainerClear(Iterable element } } + /** + * Scalarize a temporary RHS array whose elements are no longer needed. + * Reference-alias list assignment returns only its element count in scalar + * and void contexts; release the temporary reference wrappers after + * computing that count so they do not keep aliased scalar cells alive. + */ + public static RuntimeScalar scalarAndDiscardTemporaryArray(RuntimeArray array) { + if (array == null) return new RuntimeScalar(); + RuntimeScalar result = array.scalar(); + deferDestroyForContainerClear(array.elements); + array.elements.clear(); + array.elementsOwned = false; + return result; + } + /** * Scope-exit cleanup for a single JVM local variable of unknown type. * Used by the JVM backend's eval exception handler to clean up all @@ -651,94 +1181,62 @@ public static void evalExceptionScopeCleanup(Object local) { * arrays/hashes). Called at scope exit for {@code my %hash} variables. */ public static void scopeExitCleanupHash(RuntimeHash hash) { - scopeExitCleanupHash(hash, null); + scopeExitCleanupHash(hash, null, false); } /** Scope-exit cleanup with a return value whose hash references must survive. */ public static void scopeExitCleanupHash(RuntimeHash hash, RuntimeBase returned) { + scopeExitCleanupHash(hash, returned, false); + } + + static void scopeExitCleanupDestroyedHash(RuntimeHash hash) { + scopeExitCleanupHash(hash, null, true); + } + + private static void scopeExitCleanupHash( + RuntimeHash hash, RuntimeBase returned, boolean finalRelease) { if (!isActive() || hash == null) return; - // An aggregate borrowed through @_ belongs to its caller. Its - // current frame can end while the caller's lexical is still live; - // leave its lexical-owner marker for the caller's own scope cleanup. - // Clearing it here - // makes Internals::SvREFCNT under-report the caller's reference and - // lets Const::Fast freeze the original instead of its clone. - if (RuntimeCode.deferCleanupForActiveArgumentAggregate(hash)) return; + // An aggregate borrowed through @_ belongs to its caller. Its current + // frame can end while the caller's lexical is still live. + if (!finalRelease && RuntimeCode.deferCleanupForActiveArgumentAggregate(hash)) return; + scopeExitCleanupHashBody(hash, returned, finalRelease); + } + + private static void scopeExitCleanupHashBody( + RuntimeHash hash, RuntimeBase returned, boolean finalRelease) { // Clear localBindingExists: the named variable's scope is ending. // This allows subsequent refCount==0 events (from setLargeRefCounted // or flush) to correctly trigger callDestroy, since the local // variable no longer holds a strong reference. - boolean hadLocalBinding = hash.localBindingExists; hash.localBindingExists = false; - if (hash.captureCount > 0) { + if (!finalRelease) RuntimeCode.releaseActiveLexicalOwner(hash); + hash.releaseUnownedClosureCaptures(); + hash.recheckProxyValueOwnersIfUnowned(); + if (!finalRelease && hash.hasClosureCaptureOwner()) { hash.scopeExited = true; return; } - if (directlyReferences(returned, hash)) return; // A live reference keeps the container and its IO element slots alive. - // Do not release anonymous filehandle ownership before this check: a - // returned \%hash can keep its slots alive even when the interpreter's - // selective refcount has not been incremented. - if (hash.refCount > 0 || temporaryRootDirectlyReferences(hash)) return; + if (!finalRelease && (hash.refCount > 0 || hash.hasCurrentPerlOwnerSlotIdentity())) return; + if (hash instanceof RuntimeStash stash) { + stash.releaseSavedNamespaceMove(); + } for (RuntimeScalar val : hash.elements.values()) { RuntimeScalar.releaseIoOwner(val); + if (val != null) val.releaseContainerOwner(hash); } - // Skip container walks only when there are NO blessed objects AND NO - // weak refs anywhere in the JVM. If weak refs exist (even to unblessed - // data), we must still cascade decrements so their weak-ref entries - // can be cleared when the referent's refCount reaches 0. if (!RuntimeBase.blessedObjectExists() && !WeakRefRegistry.weakRefsExist() && !RuntimeScalar.watcherCleanupNeeded()) return; - // If the hash has outstanding references (e.g., from \%hash stored elsewhere), - // do NOT clean up elements — the hash is still alive and its elements are - // accessible through the reference. Cleanup will happen when the last - // reference is released (in DestroyDispatch.callDestroy). if (RuntimeScalar.watcherCleanupNeeded()) { - RuntimeScalar.notifyDestroyedWatchersRecursively(hash); + RuntimeScalar.notifyDestroyedWatchersForAggregateSlots(hash); } if (hash.type == RuntimeHash.TIED_HASH && hash.elements instanceof TieHash tieHash) { tieHash.releaseTiedObject(); } - // Quick scan: skip if no value could transitively contain blessed/tracked refs. - boolean needsWalk = RuntimeScalar.watcherCleanupNeeded(); + // Retire the direct storage slots. A final child-container owner + // triggers cleanup of that child's own outgoing slots. for (RuntimeScalar val : hash.elements.values()) { - if (val != null && (val.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && val.value instanceof RuntimeBase rb) { - if (rb.blessId != 0 || rb.refCount >= 0) { - needsWalk = true; - break; - } - // Container ref — peek at children for any reference-type elements - if (rb instanceof RuntimeArray innerArr) { - for (RuntimeScalar inner : innerArr.elements) { - if (inner != null && (inner.type & RuntimeScalarType.REFERENCE_BIT) != 0) { - needsWalk = true; - break; - } - } - } else if (rb instanceof RuntimeHash innerHash) { - for (RuntimeScalar inner : innerHash.elements.values()) { - if (inner != null && (inner.type & RuntimeScalarType.REFERENCE_BIT) != 0) { - needsWalk = true; - break; - } - } - } - if (needsWalk) break; - } - } - if (!needsWalk) return; - // Refcount drift can miss an escaped hash reference. DBIC's - // source_registrations hash is assigned into the live schema while the - // original hash later exits; walking it here would destroy ResultSources - // still reachable through the schema. - if (hadLocalBinding - && hash.refCount >= 0 - && hash.hadCountedReference - && isReachableFromExternalRootCached(hash)) return; - List valuesInDestructionOrder = new ArrayList<>(hash.elements.values()); - Collections.reverse(valuesInDestructionOrder); - for (RuntimeScalar val : valuesInDestructionOrder) { + if (preserveEscapedScalarCellValueOwner(val)) continue; deferDecrementRecursive(val); } } @@ -754,6 +1252,14 @@ public static void scopeExitCleanupArray(RuntimeArray arr) { /** Scope-exit cleanup with a returned aggregate whose IO aliases must survive. */ public static void scopeExitCleanupArray(RuntimeArray arr, RuntimeBase returned) { + scopeExitCleanupArray(arr, returned, false); + } + + static void scopeExitCleanupDestroyedArray(RuntimeArray arr) { + scopeExitCleanupArray(arr, null, true); + } + + private static void scopeExitCleanupArray(RuntimeArray arr, RuntimeBase returned, boolean finalRelease) { if (!isActive() || arr == null) return; // A threads::shared array has canonical storage that outlives each // runtime-local wrapper. Its elements are released by mutations of @@ -762,19 +1268,30 @@ public static void scopeExitCleanupArray(RuntimeArray arr, RuntimeBase returned) // See scopeExitCleanupHash: an active @_ alias does not end the // caller's lexical lifetime. In particular, Const::Fast uses // SvREFCNT to decide whether it must clone a referenced aggregate. - if (RuntimeCode.deferCleanupForActiveArgumentAggregate(arr)) return; + if (!finalRelease && RuntimeCode.deferCleanupForActiveArgumentAggregate(arr)) return; + scopeExitCleanupArrayBody(arr, returned, finalRelease); + } + + private static void scopeExitCleanupArrayBody( + RuntimeArray arr, RuntimeBase returned, boolean finalRelease) { // Clear localBindingExists: the named variable's scope is ending. // This allows subsequent refCount==0 events (from setLargeRefCounted // or flush) to correctly trigger callDestroy, since the local // variable no longer holds a strong reference. arr.localBindingExists = false; - if (arr.captureCount > 0) { + if (!finalRelease) RuntimeCode.releaseActiveLexicalOwner(arr); + arr.releaseUnownedClosureCaptures(); + arr.recheckProxyValueOwnersIfUnowned(); + if (!finalRelease && arr.hasClosureCaptureOwner()) { arr.scopeExited = true; return; } // Alias arrays such as @_ do not own their original element slots. - if (arr.refCount > 0 || temporaryRootDirectlyReferences(arr) - || directlyReferences(returned, arr)) return; + if (!finalRelease && (arr.refCount > 0 || arr.hasCurrentPerlOwnerSlotIdentity())) return; + // A refalias list owns the scalar cells even though those cells are + // not ordinary copied array values. Retire those cell identities only + // when this RuntimeArray itself is no longer Perl-owned. + arr.releaseReferenceListAliasCellOwners(); // \$#array creates a scalar proxy, not an array reference. Once the // lexical AV exits, that proxy becomes an orphaned undef lvalue; it // must not retain this Java RuntimeArray merely through its backing @@ -784,23 +1301,19 @@ public static void scopeExitCleanupArray(RuntimeArray arr, RuntimeBase returned) for (RuntimeScalar elem : arr.elements) { if (returned == null) RuntimeScalar.releaseIoOwner(elem); else RuntimeScalar.releaseIoOwnerPreservingReturned(elem, returned); + if (elem != null) elem.releaseContainerOwner(arr); } } else if (arr.ownedAliasElements != null) { for (RuntimeScalar elem : arr.ownedAliasElements) { if (returned == null) RuntimeScalar.releaseIoOwner(elem); else RuntimeScalar.releaseIoOwnerPreservingReturned(elem, returned); + if (elem != null) elem.releaseContainerOwner(arr); } } - // Skip container walks only when there are NO blessed objects AND NO - // weak refs anywhere in the JVM (see scopeExitCleanupHash for details). if (!RuntimeBase.blessedObjectExists() && !WeakRefRegistry.weakRefsExist() && !RuntimeScalar.watcherCleanupNeeded()) return; - // If the array has outstanding references (e.g., from \@array stored elsewhere), - // do NOT clean up elements — the array is still alive and its elements are - // accessible through the reference. Cleanup will happen when the last - // reference is released (in DestroyDispatch.callDestroy). if (RuntimeScalar.watcherCleanupNeeded()) { - RuntimeScalar.notifyDestroyedWatchersRecursively(arr); + RuntimeScalar.notifyDestroyedWatchersForAggregateSlots(arr); } if (arr.type == RuntimeArray.TIED_ARRAY && arr.elements instanceof TieArray tieArray) { tieArray.releaseTiedObject(); @@ -812,47 +1325,55 @@ public static void scopeExitCleanupArray(RuntimeArray arr, RuntimeBase returned) if (arr.ownedAliasElements == null || arr.ownedAliasElements.isEmpty()) return; RuntimeScalar[] owned = arr.ownedAliasElements.toArray(new RuntimeScalar[0]); for (RuntimeScalar elem : owned) { + if (preserveEscapedScalarCellValueOwner(elem)) { + arr.forgetOwnedAliasElement(elem); + continue; + } deferDecrementRecursive(elem); arr.forgetOwnedAliasElement(elem); } return; } - // Quick scan: check if any element either: - // 1. Owns a refCount (was assigned via setLarge with a tracked referent), OR - // 2. Is a direct blessed reference (blessId != 0), OR - // 3. Is a container (array/hash ref) that might hold nested blessed refs - // For case 3, we peek one level deep to avoid false positives for arrays - // of plain-data arrayrefs (like the life_bitpacked @grid). - boolean needsWalk = RuntimeScalar.watcherCleanupNeeded(); - for (RuntimeScalar elem : arr.elements) { - if (elem == null || (elem.type & RuntimeScalarType.REFERENCE_BIT) == 0) continue; - // Fast check: refCountOwned means this ref was properly tracked via setLarge - if (elem.refCountOwned) { needsWalk = true; break; } - if (!(elem.value instanceof RuntimeBase rb)) continue; - // Direct blessed ref - if (rb.blessId != 0 || rb.refCount >= 0) { needsWalk = true; break; } - // Container ref — peek at children for reference-type elements - if (rb instanceof RuntimeArray innerArr) { - for (RuntimeScalar inner : innerArr.elements) { - if (inner != null && (inner.type & RuntimeScalarType.REFERENCE_BIT) != 0) { - needsWalk = true; break; - } - } - } else if (rb instanceof RuntimeHash innerHash) { - for (RuntimeScalar inner : innerHash.elements.values()) { - if (inner != null && (inner.type & RuntimeScalarType.REFERENCE_BIT) != 0) { - needsWalk = true; break; - } - } - } - if (needsWalk) break; - } - if (!needsWalk) return; - for (RuntimeScalar elem : arr.elements) { + // Array element values are released from the end toward the beginning. + TieArray tiedStorage = arr.type == RuntimeArray.TIED_ARRAY + && arr.elements instanceof TieArray tieArray ? tieArray : null; + int storageSize = tiedStorage == null ? arr.elements.size() : tiedStorage.rawStorageSize(); + for (int index = storageSize - 1; index >= 0; index--) { + RuntimeScalar elem = tiedStorage == null + ? arr.elements.get(index) : tiedStorage.rawStorageGet(index); + if (preserveEscapedScalarCellValueOwner(elem)) continue; deferDecrementRecursive(elem); } } + /** + * Keep a scalar cell's existing value edge after its aggregate storage + * goes away if a Perl scalar reference still owns that cell. The counted + * slot moves from aggregate storage to the cell itself; the final cell + * owner release will then retire the same count through scope cleanup. + */ + private static boolean preserveEscapedScalarCellValueOwner(RuntimeScalar cell) { + if (cell == null) return false; + if (!cell.referencedByScalarReference + || (!cell.localBindingExists + && !cell.hasPendingReturnOwner() + && !cell.hasScalarCellStorageOwnerSlotIdentity())) { + return false; + } + + PerlOwnerSlot slot = cell.countedOwnerSlot(); + if (!cell.refCountOwned || slot == null || !slot.isActive() + || slot.countedScalarOwner() != cell || slot.referent() != cell.value) { + return false; + } + if (slot.kind() == PerlOwnerSlot.Kind.ARRAY_ELEMENT + || slot.kind() == PerlOwnerSlot.Kind.HASH_ELEMENT) { + slot.reclassifyCountedIdentity(PerlOwnerSlot.Kind.SCALAR_CELL); + return true; + } + return slot.kind() == PerlOwnerSlot.Kind.SCALAR_CELL; + } + public static void releaseTailCallArgs(RuntimeArray args) { if (args == null || !isActive() || !args.elementsOwned) return; if (args.elementsAliased) { @@ -901,28 +1422,7 @@ public static void releaseTailCallCodeRef(RuntimeScalar codeRef) { || code.refCount <= 0) { return; } - - codeRef.refCountOwned = false; - if (code.refCountTrace) { - code.traceRefCount(-1, "MortalList.releaseTailCallCodeRef"); - code.releaseOwner(codeRef, "releaseTailCallCodeRef"); - } - code.releaseActiveOwner(codeRef); - - if (--code.refCount > 0) return; - - if (code.stashRefCount > 0) { - code.refCount = 0; - return; - } - - if (code.localBindingExists) { - code.refCount = 1; - return; - } - - code.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(code); + releaseCountedOwnerImmediately(codeRef, "MortalList.releaseTailCallCodeRef"); } private static void releaseTailCallArgElement(RuntimeScalar scalar) { @@ -933,208 +1433,68 @@ private static void releaseTailCallArgElement(RuntimeScalar scalar) { || base.refCount <= 0) { return; } - - scalar.refCountOwned = false; - if (base.refCountTrace) { - base.traceRefCount(-1, "MortalList.releaseTailCallArgElement"); - base.releaseOwner(scalar, "releaseTailCallArgElement"); - } - base.releaseActiveOwner(scalar); - - if (--base.refCount > 0) return; - - if (base.localBindingExists || reachableTailCallArgReferent(base)) { - base.refCount = 1; - return; - } - - base.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(base); - } - - private static boolean reachableTailCallArgReferent(RuntimeBase base) { - return WeakRefRegistry.hasWeakRefsTo(base) - && (ReachabilityWalker.isReachableFromRoots(base) - || ReachabilityWalker.isReachableFromLiveScalarRegistry(base) - || ReachabilityWalker.isReachableFromLiveCodeCaptures(base)); + releaseCountedOwnerImmediately(scalar, "MortalList.releaseTailCallArgElement"); } - /** - * Iteratively process a scalar value: if it holds a reference to a - * tracked blessed object and owns a refCount, defer a decrement. - * If it holds a reference to an unblessed container, walk into - * its elements (iteratively with cycle detection to avoid - * StackOverflowError on circular data structures like ExifTool's). - */ + /** Release only this scalar's direct owner edge. Aggregate destruction + * releases its own outgoing element slots through the storage-owner path. */ private static void deferDecrementRecursive(RuntimeScalar scalar) { - if (scalar == null || (scalar.type & RuntimeScalarType.REFERENCE_BIT) == 0) return; - if (!(scalar.value instanceof RuntimeBase topBase)) return; - - // Fast path for leaf references (the overwhelmingly common case): - // unblessed, untracked referents with no nested containers to walk. - if (topBase.blessId == 0 && topBase.refCount == -1) { - // Unblessed, untracked — nothing to do unless it's a container. - if (topBase instanceof RuntimeArray arr) { - // Check if any element is a tracked ref before iterating. - boolean hasTracked = false; - for (RuntimeScalar elem : arr.elements) { - if (elem != null && (elem.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && elem.value instanceof RuntimeBase eb - && (eb.blessId != 0 || eb.refCount >= 0)) { - hasTracked = true; - break; - } - } - if (!hasTracked) return; - } else if (topBase instanceof RuntimeHash hash) { - boolean hasTracked = false; - for (RuntimeScalar val : hash.elements.values()) { - if (val != null && (val.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && val.value instanceof RuntimeBase vb - && (vb.blessId != 0 || vb.refCount >= 0)) { - hasTracked = true; - break; - } - } - if (!hasTracked) return; + if (!isActive() || scalar == null || scalar.hasCodeSlotBinding() + || (scalar.type & RuntimeScalarType.REFERENCE_BIT) == 0 + || WeakRefRegistry.isweak(scalar) + || !(scalar.value instanceof RuntimeBase base)) return; + if (scalar.refCountOwned) { + if (base.isPerlDestroyed() && base.refCount <= 0) { + base.retireZeroCountOwnerIdentity( + scalar, "MortalList.deferDecrementRecursive destroyed referent"); } else { - return; // Non-container unblessed untracked leaf — nothing to do + deferDecrementIfTracked(scalar); } + } else if (base.blessId != 0 && base.isRefCountTracked() + && base.refCount == 0) { + LifecycleRuntimeState state = state(); + markBoundaryWork(state); + RuntimeBase.PendingOwnerRelease ownerRelease = base.queueLifecycleOnlyAtZero( + "MortalList.deferDecrementRecursive zero-count temporary"); + queueDeferredBase(state, base, ownerRelease, null, scalar); } + } - // Slow path: tracked or blessed referents need full walk with cycle detection. - // Use an explicit work queue + visited set to avoid stack overflow - // on circular references (e.g., ExifTool's self-referential hashes). - ArrayDeque work = new ArrayDeque<>(); - Set visited = Collections.newSetFromMap(new IdentityHashMap<>()); - work.add(scalar); + /** Reusable scratch for the cleanup-target pre-scan of nested aggregates. */ + static final class CleanupTargetProbe { + private ArrayDeque work; + private Set visited; - while (!work.isEmpty()) { - RuntimeScalar s = work.poll(); - if (s == null || (s.type & RuntimeScalarType.REFERENCE_BIT) == 0) continue; - if (!(s.value instanceof RuntimeBase base)) continue; - if (!visited.add(base)) continue; // already visited — cycle + boolean mayContainCleanupTargets(RuntimeBase base) { + if (!(base instanceof RuntimeArray || base instanceof RuntimeHash)) return false; + if (work == null) { + work = new ArrayDeque<>(); + visited = Collections.newSetFromMap(new IdentityHashMap<>()); + LifecycleHotPathDiagnostics.aggregateReleaseProbeWorksetAllocated(); + } + LifecycleHotPathDiagnostics.aggregateReleaseProbeRootProcessed(); + work.add(base); - if (base.blessId != 0) { - boolean releasingLastOwner = false; - if (s.refCountOwned && base.refCount > 0) { - s.refCountOwned = false; - if (base.refCountTrace) { - base.traceRefCount(0, "MortalList.deferDecrementRecursive (blessed, queued)"); - base.releaseOwner(s, "deferDecrementRecursive blessed"); - } - base.releaseActiveOwner(s); - // refCount is the authoritative ownership count here. - // activeOwners is diagnostic and can retain a stale - // call-frame alias until the enclosing sub returns. - releasingLastOwner = base.refCount == 1; - LifecycleRuntimeState state = state(); - markBoundaryWork(state); - queueDeferredBase(state, base, null, null, s); - } else if (base.refCount == 0) { - if (base.refCountTrace) { - base.traceRefCount(+1, "MortalList.deferDecrementRecursive (blessed never-stored bump+queue)"); - } - base.refCount = 1; - LifecycleRuntimeState state = state(); - markBoundaryWork(state); - queueDeferredBase(state, base, null, null, s); - // A zero-count blessed container returned from a helper - // has no counted owner to release, but its fields still - // disappear when this temporary dies. - releasingLastOwner = true; - } - // A blessed hash/array is still a container. When this slot - // releases its final counted owner, its fields disappear with - // it and must release their own referents too. Do not walk a - // shared object: another strong owner may still use its fields - // (Sub::Quote keeps exactly this kind of external metadata - // owner while its registry entry is weak). - if (releasingLastOwner) { - if (base instanceof RuntimeArray arr) { + try { + while (!work.isEmpty()) { + RuntimeBase cur = work.poll(); + if (cur == null || !visited.add(cur)) continue; + if (cur instanceof RuntimeArray arr) { for (RuntimeScalar elem : arr.elements) { - if (elem != null) work.add(elem); + if (scalarMayContainCleanupTarget(elem, work)) return true; } - } else if (base instanceof RuntimeHash hash) { - for (RuntimeScalar val : hash.elements.values()) { - if (val != null) work.add(val); + } else if (cur instanceof RuntimeHash hash) { + for (RuntimeScalar value : hash.elements.values()) { + if (scalarMayContainCleanupTarget(value, work)) return true; } } } - } else { - boolean hasDirectWeakElementRefs = containerHasWeakElementRefs(base); - boolean hasCleanupTargets = hasDirectWeakElementRefs - || containerMayContainCleanupTargets(base); - if (s.refCountOwned && base.refCount > 0) { - s.refCountOwned = false; - if (base.refCountTrace) { - base.traceRefCount(0, "MortalList.deferDecrementRecursive (unblessed container, queued)"); - } - base.releaseActiveOwner(s); - LifecycleRuntimeState state = state(); - markBoundaryWork(state); - queueDeferredBase(state, base, null, null, s); - if (!WeakRefRegistry.weakRefsExist() && base.refCount > 1) { - continue; - } - if (!hasCleanupTargets - || base.activeOwnerCount() > 0 - || (base.refCount > 1 - && !hasDirectWeakElementRefs - && isReachableFromExternalRootCached(base))) { - continue; - } - } else if (base.refCount > 0 - && !WeakRefRegistry.weakRefsExist()) { - // A non-owning copy of a still-counted unblessed container - // must not release that container's children. With no weak - // refs anywhere, there is no weak-ref cleanup that requires - // peeking inside before the container's own count reaches 0. - continue; - } else if (base.refCount > 0 - && (!hasCleanupTargets - || base.activeOwnerCount() > 0 - || (!hasDirectWeakElementRefs - && isReachableFromExternalRootCached(base)))) { - // This scalar is a non-owning copy of a still-live container. - // Cleaning it up must not walk into the shared container and - // release the original owner's children. - continue; - } - // Walk into unblessed containers to find nested blessed refs - if (base instanceof RuntimeArray arr) { - for (RuntimeScalar elem : arr.elements) { - if (elem != null) work.add(elem); - } - } else if (base instanceof RuntimeHash hash) { - for (RuntimeScalar val : hash.elements.values()) { - if (val != null) work.add(val); - } - } - } - } - } - - static boolean containerMayContainCleanupTargets(RuntimeBase base) { - if (!(base instanceof RuntimeArray || base instanceof RuntimeHash)) return false; - ArrayDeque work = new ArrayDeque<>(); - Set visited = Collections.newSetFromMap(new IdentityHashMap<>()); - work.add(base); - - while (!work.isEmpty()) { - RuntimeBase cur = work.poll(); - if (cur == null || !visited.add(cur)) continue; - if (cur instanceof RuntimeArray arr) { - for (RuntimeScalar elem : arr.elements) { - if (scalarMayContainCleanupTarget(elem, work)) return true; - } - } else if (cur instanceof RuntimeHash hash) { - for (RuntimeScalar value : hash.elements.values()) { - if (scalarMayContainCleanupTarget(value, work)) return true; - } + return false; + } finally { + work.clear(); + visited.clear(); } } - return false; } private static boolean scalarMayContainCleanupTarget(RuntimeScalar scalar, @@ -1147,30 +1507,12 @@ private static boolean scalarMayContainCleanupTarget(RuntimeScalar scalar, if (base.blessId != 0) return true; if (base instanceof RuntimeArray || base instanceof RuntimeHash) { work.add(base); - } else if (base instanceof RuntimeCode && base.refCount >= 0) { + } else if (base instanceof RuntimeCode && base.isRefCountTracked()) { return true; } return false; } - private static boolean containerHasWeakElementRefs(RuntimeBase base) { - if (!WeakRefRegistry.weakRefsExist()) return false; - if (base instanceof RuntimeArray arr) { - for (RuntimeScalar elem : arr.elements) { - if (elem != null && WeakRefRegistry.hasWeakRefsTo(elem)) { - return true; - } - } - } else if (base instanceof RuntimeHash hash) { - for (RuntimeScalar value : hash.elements.values()) { - if (value != null && WeakRefRegistry.hasWeakRefsTo(value)) { - return true; - } - } - } - return false; - } - /** * Mortal-ize blessed refs with refCount==0 in a RuntimeList that will be * discarded (void-context call result). Without this, objects that were @@ -1183,36 +1525,39 @@ public static void mortalizeForVoidDiscard(RuntimeList result) { if (elem instanceof RuntimeScalar scalar && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 && scalar.value instanceof RuntimeBase base) { + if (scalar.hasStorageOwnerForVoidDiscard()) continue; boolean unblessedDiscardableContainer = base.blessId == 0 && (base instanceof RuntimeHash || base instanceof RuntimeArray || base instanceof RuntimeCode); boolean reachableCodeRef = base instanceof RuntimeCode - && scalar.isStoredInRegisteredContainerOwner() - && ReachabilityWalker.isScalarReachable(scalar); + && scalar.isStoredInRegisteredContainerOwner(); if (scalar.refCountOwned && base.refCount > 0 && unblessedDiscardableContainer && !reachableCodeRef) { - scalar.refCountOwned = false; if (base.refCountTrace) { base.traceRefCount(0, "MortalList.mortalizeForVoidDiscard (queued owned container discard)"); - base.releaseOwner(scalar, "mortalizeForVoidDiscard container"); } - base.releaseActiveOwner(scalar); + RuntimeBase.PendingOwnerRelease ownerRelease = base.queueOwnerRelease( + scalar, "MortalList.mortalizeForVoidDiscard"); LifecycleRuntimeState state = state(); markBoundaryWork(state); - queueDeferredBase(state, base, null); - } else if (base.refCount == 0 + queueDeferredBase(state, base, ownerRelease, null, scalar); + } else if (base.isRefCountTracked() && base.refCount == 0 && (base.blessId != 0 || base instanceof RuntimeHash || base instanceof RuntimeArray || base instanceof RuntimeCode)) { - if (base.refCountTrace) { - base.traceRefCount(+1, "MortalList.mortalizeForVoidDiscard (refCount=1 bump+queue)"); + RuntimeBase.PendingOwnerRelease ownerRelease; + if (scalar.refCountOwned) { + ownerRelease = base.queueOwnerRelease( + scalar, "MortalList.mortalizeForVoidDiscard zero-count owner"); + } else { + ownerRelease = base.queueLifecycleOnlyAtZero( + "MortalList.mortalizeForVoidDiscard zero-count temporary"); } - base.refCount = 1; LifecycleRuntimeState state = state(); markBoundaryWork(state); - queueDeferredBase(state, base, null); + queueDeferredBase(state, base, ownerRelease, null, scalar); } } } @@ -1222,40 +1567,36 @@ public static void mortalizeForVoidDiscard(RuntimeList result) { // Each mark records the pending list size at scope entry, so that // popAndFlush() only processes entries added within that scope. private static void processDeferredEntriesFrom( - int pendingStartIdx, int tiedReleaseStartIdx, int ioReleaseStartIdx) { + int pendingStartIdx, int tiedReleaseStartIdx, int ioReleaseStartIdx, + int untrackedReturnOwnerStartIdx) { LifecycleRuntimeState state = state(); - boolean previousCaptureSweepDeferral = - state.deferCaptureReachabilityToBoundarySweep; - state.deferCaptureReachabilityToBoundarySweep = - previousCaptureSweepDeferral || canDeferCapturedTargetCheckToBoundarySweep(state); - state.reachabilityDrainDepth++; + state.deferredReleaseDrainDepth++; try { int pendingIdx = pendingStartIdx; int tiedReleaseIdx = tiedReleaseStartIdx; int ioReleaseIdx = ioReleaseStartIdx; + int untrackedReturnOwnerIdx = untrackedReturnOwnerStartIdx; while (pendingIdx < state.pending.size() || tiedReleaseIdx < state.pendingTiedReleases.size() - || ioReleaseIdx < state.pendingIoReleases.size()) { + || ioReleaseIdx < state.pendingIoReleases.size() + || untrackedReturnOwnerIdx < state.pendingUntrackedReturnOwnerReleases.size()) { while (tiedReleaseIdx < state.pendingTiedReleases.size()) { - // Releasing a tie handler changes the graph represented by - // the per-drain tied-reachability snapshot. - state.flushTiedReachableCache = null; state.pendingTiedReleases.get(tiedReleaseIdx++).releaseTiedObject(); } while (pendingIdx < state.pending.size()) { + int currentIndex = pendingIdx++; RuntimeBase.PendingOwnerRelease ownerRelease = - state.pendingOwnerReleases.get(pendingIdx); - String transientOwnerKind = state.pendingTransientOwnerKinds.get(pendingIdx); - RuntimeBase base = state.pending.get(pendingIdx); - java.lang.ref.WeakReference ownerRef = - state.pendingOwnerScalars.get(pendingIdx++); - RuntimeScalar ownerScalar = ownerRef == null ? null : ownerRef.get(); - if (base.blessId != 0 - && WeakRefRegistry.hasWeakRefsTo(base) - && RuntimeCode.hasActiveArgumentOwner(ownerScalar)) { + state.pendingOwnerReleases.get(currentIndex); + String transientOwnerKind = + state.pendingTransientOwnerKinds.get(currentIndex); + RuntimeBase base = state.pending.get(currentIndex); + boolean argumentAliasOwnsBase = + base.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS) != 0 + && base.countedOwnerSlotCount() == 0; + if (argumentAliasOwnsBase) { state.deferredArgumentOwnerReleases.add( new DeferredArgumentOwnerRelease(base, ownerRelease, - transientOwnerKind, ownerScalar)); + transientOwnerKind)); } else { processDeferredBase(base, false, ownerRelease, transientOwnerKind); } @@ -1263,14 +1604,89 @@ private static void processDeferredEntriesFrom( while (ioReleaseIdx < state.pendingIoReleases.size()) { RuntimeScalar.releaseIoOwner(state.pendingIoReleases.get(ioReleaseIdx++)); } + while (untrackedReturnOwnerIdx + < state.pendingUntrackedReturnOwnerReleases.size()) { + RuntimeScalar scalar = + state.pendingUntrackedReturnOwnerReleases.get(untrackedReturnOwnerIdx++); + if (scalar != null) scalar.releaseMortalReturnValueOwner(); + } } } finally { - state.reachabilityDrainDepth--; - state.deferCaptureReachabilityToBoundarySweep = previousCaptureSweepDeferral; + state.deferredReleaseDrainDepth--; } drainDeferredArgumentOwnerReleases(); } + /** Drain the selected pending range depth-first, preserving frame LIFO order. */ + private static void processDeferredOwnerEntriesLifoFrom( + int startIdx, boolean clearWeakRefsForLocalBinding) { + LifecycleRuntimeState state = state(); + int resumeDepth = state.pendingReleaseResumeDepth; + int floor = startIdx; + int cursor = state.pending.size() - 1; + int observedSize = state.pending.size(); + try { + while (true) { + int liveSize = state.pending.size(); + if (cursor >= liveSize) cursor = liveSize - 1; + if (floor > liveSize) floor = liveSize; + if (observedSize > liveSize) observedSize = liveSize; + if (cursor < floor) { + if (state.pendingReleaseResumeDepth > resumeDepth) { + int resumeIndex = --state.pendingReleaseResumeDepth; + int offset = resumeIndex * 2; + cursor = state.pendingReleaseResumeStack[offset]; + floor = state.pendingReleaseResumeStack[offset + 1]; + continue; + } + int currentSize = state.pending.size(); + if (currentSize > observedSize) { + floor = observedSize; + cursor = currentSize - 1; + observedSize = currentSize; + continue; + } + observedSize = currentSize; + break; + } + + int currentIndex = cursor--; + int previousSize = state.pending.size(); + RuntimeBase.PendingOwnerRelease ownerRelease = + state.pendingOwnerReleases.get(currentIndex); + if (ownerRelease != null && ownerRelease.completed.get()) continue; + String transientOwnerKind = + state.pendingTransientOwnerKinds.get(currentIndex); + RuntimeBase base = state.pending.get(currentIndex); + boolean argumentAliasOwnsBase = + base.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS) != 0 + && base.countedOwnerSlotCount() == 0; + if (argumentAliasOwnsBase) { + state.deferredArgumentOwnerReleases.add( + new DeferredArgumentOwnerRelease(base, ownerRelease, + transientOwnerKind)); + } else { + processDeferredBase(base, clearWeakRefsForLocalBinding, + ownerRelease, transientOwnerKind); + } + + int currentSize = state.pending.size(); + if (currentSize > previousSize) { + state.pushPendingReleaseResume(cursor, floor); + floor = previousSize; + cursor = currentSize - 1; + observedSize = currentSize; + } else if (currentSize < observedSize) { + // A nested exact drain may have truncated its own tail. + // Allow later appends to reuse those queue positions. + observedSize = currentSize; + } + } + } finally { + state.pendingReleaseResumeDepth = resumeDepth; + } + } + static void drainDeferredArgumentOwnerReleases() { LifecycleRuntimeState state = state(); if (state.deferredArgumentOwnerReleases.isEmpty()) return; @@ -1278,8 +1694,10 @@ static void drainDeferredArgumentOwnerReleases() { new ArrayList<>(state.deferredArgumentOwnerReleases); state.deferredArgumentOwnerReleases.clear(); for (DeferredArgumentOwnerRelease deferred : pending) { - RuntimeScalar ownerScalar = deferred.ownerScalar.get(); - if (RuntimeCode.hasActiveArgumentOwner(ownerScalar)) { + if (deferred.base.countedOwnerSlotCount() != 0) { + processDeferredBase(deferred.base, false, deferred.ownerRelease, + deferred.transientOwnerKind); + } else if (deferred.base.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS) != 0) { state.deferredArgumentOwnerReleases.add(deferred); } else { processDeferredBase(deferred.base, false, deferred.ownerRelease, @@ -1288,22 +1706,6 @@ static void drainDeferredArgumentOwnerReleases() { } } - private static void finalizeDeferredCaptureSweepCandidates( - LifecycleRuntimeState state) { - if (state.deferredCaptureSweepCandidates.isEmpty()) return; - if (state.boundaryWeakSweepGeneration > state.deferredCaptureSweepGeneration) { - state.deferredCaptureSweepCandidates.clear(); - state.deferredCaptureSweepGeneration = state.boundaryWeakSweepGeneration; - } - } - - private static boolean canDeferCapturedTargetCheckToBoundarySweep( - LifecycleRuntimeState state) { - return !AUTO_GC_DISABLED - && !state.inAutoSweep - && !ModuleInitGuard.inModuleInit(); - } - /** * Process all pending decrements. Called at statement boundaries. * Equivalent to Perl 5's FREETMPS. @@ -1333,448 +1735,158 @@ private static boolean canDeferCapturedTargetCheckToBoundarySweep( */ public static boolean suppressFlush(boolean suppress) { LifecycleRuntimeState state = state(); - boolean prev = state.flushing; - state.flushing = suppress; + boolean prev = state.flushSuppressed; + state.flushSuppressed = suppress; return prev; } - // Phase B2a (refcount_alignment_52leaks_plan.md): throttled - // auto-sweep of the weak-ref registry, gated by ModuleInitGuard. - // Runs at statement boundaries (flush points) but skips while - // inside require/use/do/BEGIN/eval-STRING code paths — those - // often rely on weak-refed intermediate state that the sweep - // would prematurely clear. - // Tuned for DBIC-scale tests: 5s throttle. Shorter intervals - // (100ms, 500ms) fire too frequently — 52leaks.t creates thousands - // of weaken'd refs and each sweep's System.gc() + weak-ref cascade - // can run for tens of seconds. 5s gives the walker time to amortize. - // - // Trade-off: tests that rely on deterministic DESTROY after `undef` - // of a blessed ref (e.g. t/storage/error.t test 49) need explicit - // Internals::jperl_gc() to fire the walker within their short - // wall-clock. - private static final long AUTO_SWEEP_MIN_INTERVAL_NS = 5_000_000_000L; - private static final boolean AUTO_GC_DISABLED = - System.getenv("JPERL_NO_AUTO_GC") != null; - private static final boolean AUTO_GC_DEBUG = - System.getenv("JPERL_GC_DEBUG") != null; - private static final boolean WEAK_SWEEP_REQUEST_DEBUG = - System.getenv("JPERL_WEAK_SWEEP_REQUEST_DEBUG") != null; - // Phase D-W6.20 (debug knob): force the auto-sweep on EVERY flush() - // call, bypassing the 5-s throttle and the `weakRefsExist` gate. - // Used to reproduce timing-dependent walker bugs (e.g. the - // ScalarRefRegistry-vs-forceGc race that surfaces as DBIC's - // "detached result source" mid-test crash). Off by default; when on, - // every Perl statement boundary triggers a full sweepWeakRefs walk — - // very slow, only for diagnostics. - private static final boolean FORCE_SWEEP_EVERY_FLUSH = - System.getenv("JPERL_FORCE_SWEEP_EVERY_FLUSH") != null; - - // Objects explicitly released by undef while JVM statement temporaries may - // still make them appear reachable. Recheck only these referents at the - // next Perl statement boundary; a full nested-call sweep can invalidate - // unrelated weak callback graphs whose caller-owned return values have not - // reached a walker-visible lexical yet. - public static void requestImmediateWeakSweep() { - LifecycleRuntimeState state = state(); - markBoundaryWork(state); - state.immediateWeakSweepRequested = true; - if (WEAK_SWEEP_REQUEST_DEBUG) { - StackTraceElement[] stack = Thread.currentThread().getStackTrace(); - StackTraceElement caller = stack.length > 2 ? stack[2] : null; - System.err.println("[WEAK_SWEEP_REQUEST] caller=" + caller); - } - } - - public static void requestTargetedWeakSweep(RuntimeBase referent) { - if (referent != null) { - LifecycleRuntimeState state = state(); - markBoundaryWork(state); - state.targetedWeakSweepReferents.add(referent); - } - } - - /** - * Finish targeted releases queued by an explicit aggregate discard after - * the assignment's temporary scalar roots have been removed. Unlike the - * global quiet sweep, this walk is safe at nested statement boundaries - * because it considers only referents reached from the discarded graph. - */ - public static void flushReleasedWeakSweepsIfSafe() { - LifecycleRuntimeState state = state(); - if (state.targetedWeakSweepReferents.isEmpty()) return; - Set releasedTargets = Collections.newSetFromMap(new IdentityHashMap<>()); - releasedTargets.addAll(state.targetedWeakSweepReferents); - state.targetedWeakSweepReferents.clear(); - ReachabilityWalker.ReleasedWeakSweepResult releasedSweepResult = - ReachabilityWalker.sweepReleasedWeakReferents(releasedTargets); - - // A complete quiet sweep may already be required at this safe boundary. - // Reuse the targeted pass's root set for that registry-wide cleanup, - // avoiding a second traversal when releasing these referents caused no - // DESTROY cascade that would have changed the graph. - if (releasedSweepResult.live() == null - || !state.immediateWeakSweepRequested - || AUTO_GC_DISABLED - || FORCE_SWEEP_EVERY_FLUSH - || state.inAutoSweep - || ModuleInitGuard.inModuleInit() - || RuntimeCode.argsStackDepth() > 1 - || !state.temporaryRoots.isEmpty()) { - return; - } - state.immediateWeakSweepRequested = false; - state.lastAutoSweepNanos = System.nanoTime(); - state.inAutoSweep = true; - try { - ReachabilityWalker.sweepWeakRefs( - true, false, releasedTargets, releasedSweepResult); - state.boundaryWeakSweepGeneration++; - finalizeDeferredCaptureSweepCandidates(state); - } finally { - state.inAutoSweep = false; - } - } - - /** - * Register weakly tracked referents whose last strong edge may disappear - * with a container temporary. References to ordinary scalar referents - * cannot participate in the selective refCount scheme, so a discarded - * anonymous array/hash must explicitly ask the statement-boundary walker - * to reconsider them. This is the aggregate equivalent of assigning - * {@code undef} to a scalar that contains a WEAKLY_TRACKED reference. - */ - public static boolean requestWeakSweepsForDestroyedContainer(RuntimeBase container) { - if (!(container instanceof RuntimeArray) && !(container instanceof RuntimeHash)) return false; - - ArrayDeque work = new ArrayDeque<>(); - Set visited = Collections.newSetFromMap(new IdentityHashMap<>()); - work.add(container); - boolean requested = WeakRefRegistry.hasWeakRefsTo(container); - if (requested) requestTargetedWeakSweep(container); - - while (!work.isEmpty()) { - RuntimeBase current = work.removeFirst(); - if (!visited.add(current)) continue; - - // A stash is a symbol-table view, not an owned aggregate. Walking - // its dynamic HashSpecialVariable map enumerates package globals - // on every scope exit (Catalyst creates many short-lived - // containers), repeatedly traversing the whole program graph. - // Its values are roots already handled by the normal weak sweep. - if (current instanceof RuntimeStash) continue; - - Iterable values; - if (current instanceof RuntimeArray array) { - values = array.elements; - } else if (current instanceof RuntimeHash hash) { - values = hash.elements.values(); - } else { - continue; - } - - for (RuntimeScalar value : values) { - if (value == null - || (value.type & RuntimeScalarType.REFERENCE_BIT) == 0 - || !(value.value instanceof RuntimeBase referent)) { - continue; - } - if (WeakRefRegistry.hasWeakRefsTo(referent)) { - requestTargetedWeakSweep(referent); - requested = true; - } - if (referent instanceof RuntimeArray || referent instanceof RuntimeHash) { - work.add(referent); - } - } - } - return requested; + /** Return whether deferred-owner flushing is currently suppressed. */ + public static boolean isFlushSuppressed() { + return state().flushSuppressed; } static void finalizeClearedAggregateOwnerAfterScopeExit(RuntimeBase base) { if (!isActive() || base == null - || base.refCount != 0 || !base.clearedOwnedAggregateElement || !WeakRefRegistry.hasWeakRefsTo(base)) { return; } - // This check runs at individual lexical scope exits, often many times - // while a package is loading. Keep package-root traversal cached - // across those exits; the live lexical snapshot is independently - // invalidated as each lexical leaves scope. - if (isReachableFromExternalRootCached(base)) { - return; - } - base.refCount = Integer.MIN_VALUE; + // Scope cleanup retires the exact lexical owner before reaching this + // point. Package, container, and capture edges have their own owner + // slots; temporary roots are checked separately because they are + // evaluation scaffolding rather than Perl ownership. Use validated + // identities so stale slots and compatibility counts cannot preserve + // an aggregate after its final owner cell is cleared. + if (DestroyDispatch.hasLivePerlOwnerIdentity(base)) return; + // A deferred count release has already retired its live owner slot, + // but the compatibility count is not decremented until the mortal + // queue drains. Let that exact release decide finalization instead of + // racing it with scope-exit cleanup. + if (base.hasPendingOwnerRelease()) return; DestroyDispatch.callDestroy(base); } - // D-W6.18 perf: cached reachable-set, valid for the duration of a - // single flush() invocation. The walker BFS is O(globals); without - // this cache, calling it once per pending target turns flush into - // O(targets × globals). DBIC stresses this hard because many - // blessed objects are stored-in-package-global AND have weak refs - // (Schema/ResultSource back-refs) — every flush would re-walk the - // full global graph for each one. Computed lazily on first need. - private static boolean isReachableCached(RuntimeBase base) { - LifecycleRuntimeState state = state(); - if (state.flushReachableCache == null) { - ReachabilityWalker w = new ReachabilityWalker(); - state.flushReachableCache = w.walk(); - } - return state.flushReachableCache.contains(base); - } - - static boolean isReachableFromExternalRootCached(RuntimeBase base) { - if (ReachabilityWalker.isReachableFromTemporaryRoots(base)) { - return true; - } - return isReachableFromPersistentRootCached(base); - } - - static boolean isReachableFromPersistentRootCached(RuntimeBase base) { - LifecycleRuntimeState state = state(); - if (state.externalRootSnapshot == null) { - state.externalRootSnapshot = new ReachabilityWalker.ExternalRootSnapshot(); - } - if (state.externalRootSnapshot.isReachableFromNonLexicalRoot(base)) { - return true; - } - if (!state.externalRootSnapshot.complete()) { - // An incomplete external-root walk cannot prove this target has - // no other owner. Keep it alive without rebuilding the broader - // full-root graph, which also cannot preserve this query's - // direct-lexical exclusion semantics. - return true; - } - if (state.liveRootSnapshot == null) { - state.liveRootSnapshot = new ReachabilityWalker.LiveRootSnapshot(); - } - return state.liveRootSnapshot.isReachable(base); - } - - static void invalidateExternalRootSnapshot() { - state().externalRootSnapshot = null; - state().fullRootSnapshot = null; - state().unblessedAggregateRootSnapshot = null; - state().scalarRootSnapshot = null; - } - - static void invalidateAllRootSnapshots() { - invalidateExternalRootSnapshot(); - invalidateLiveRootSnapshot(); - } - - private static boolean isReachableFromFullRootSnapshot(RuntimeBase base) { - LifecycleRuntimeState state = state(); - if (state.fullRootSnapshot == null) { - state.fullRootSnapshot = ReachabilityWalker.reachableFromRootsSnapshotWithStatus(); - } - return state.fullRootSnapshot.isReachable(base); - } - - static boolean isUnblessedAggregateReachableDuringDrain(RuntimeBase base) { - LifecycleRuntimeState state = state(); - boolean drainActive = state.flushing || state.reachabilityDrainDepth > 0; - if (drainActive && state.unblessedAggregateDrainSnapshotIncomplete) return true; - if (drainActive && state.unblessedAggregateDrainRoots.contains(base)) return true; - if (state.fullRootSnapshot != null) { - return recordUnblessedAggregateSnapshotResult( - state, state.fullRootSnapshot, base, drainActive); - } - if (state.unblessedAggregateRootSnapshot != null) { - return recordUnblessedAggregateSnapshotResult( - state, state.unblessedAggregateRootSnapshot, base, drainActive); - } - if (ReachabilityWalker.isReachableFromTemporaryRoots(base)) return true; - if (state.externalRootSnapshot != null - && state.externalRootSnapshot.isReachableFromNonLexicalRoot(base)) { - if (drainActive) state.unblessedAggregateDrainRoots.add(base); - return true; - } - if (state.liveRootSnapshot != null && state.liveRootSnapshot.isReachable(base)) { - if (drainActive) state.unblessedAggregateDrainRoots.add(base); - return true; - } - // The package-root and live-lexical snapshots cover the same strong - // roots without tying their lifetimes together. Scope exits invalidate - // the lexical view frequently, while package roots often stay stable; - // rebuilding a combined graph here repeats the full package walk for - // each cleanup batch during module loading and request handling. - boolean reachable = isReachableFromExternalRootCached(base); - if (drainActive) { - boolean incomplete = state.externalRootSnapshot == null - || !state.externalRootSnapshot.complete() - || (state.liveRootSnapshot != null - && !state.liveRootSnapshot.complete()); - if (incomplete) { - state.unblessedAggregateDrainSnapshotIncomplete = true; - state.unblessedAggregateDrainRoots.clear(); - } else if (reachable && !state.unblessedAggregateDrainRoots.contains(base)) { - if (state.unblessedAggregateDrainRoots.size() - >= MAX_UNBLESSED_AGGREGATE_DRAIN_ROOTS) { - state.unblessedAggregateDrainSnapshotIncomplete = true; - state.unblessedAggregateDrainRoots.clear(); - } else { - state.unblessedAggregateDrainRoots.add(base); - ReachabilityQueryStats stats = activeReachabilityQueryStats(); - if (stats != null) { - stats.unblessedAggregateDrainPositiveProofsCached++; - } - } - } - } - return reachable; - } - - private static boolean recordUnblessedAggregateSnapshotResult( - LifecycleRuntimeState state, - ReachabilityWalker.RootReachabilitySnapshot snapshot, - RuntimeBase base, - boolean drainActive) { - boolean reachable = snapshot.isReachable(base); - if (drainActive) { - if (!snapshot.complete()) { - state.unblessedAggregateDrainSnapshotIncomplete = true; - state.unblessedAggregateDrainRoots.clear(); - } else if (reachable && !state.unblessedAggregateDrainRoots.contains(base)) { - if (state.unblessedAggregateDrainRoots.size() - >= MAX_UNBLESSED_AGGREGATE_DRAIN_ROOTS) { - state.unblessedAggregateDrainSnapshotIncomplete = true; - state.unblessedAggregateDrainRoots.clear(); - } else { - state.unblessedAggregateDrainRoots.add(base); - ReachabilityQueryStats stats = activeReachabilityQueryStats(); - if (stats != null) { - stats.unblessedAggregateDrainPositiveProofsCached++; - } - } - } - } - return reachable; - } - - /** - * Check an owner scalar through its containing aggregate using the shared - * drain snapshot. Owner scalars nested below package roots are otherwise - * verified by a separate full root walk for every deferred referent. - */ - static boolean isScalarReachableThroughRootedContainer(RuntimeScalar scalar) { - LifecycleRuntimeState state = state(); - if ((!state.flushing && state.reachabilityDrainDepth == 0) - || scalar == null || WeakRefRegistry.isweak(scalar)) { - return false; - } - RuntimeBase container = scalar.containerOwner; - boolean containsScalar; - if (container instanceof RuntimeHash hash) { - containsScalar = hash.elements.containsValue(scalar); - } else if (container instanceof RuntimeArray array) { - containsScalar = array.elements.contains(scalar); - } else { - containsScalar = false; - } - return containsScalar && isReachableFromFullRootSnapshot(container); - } - - static void invalidateLiveRootSnapshot() { - state().liveRootSnapshot = null; - state().fullRootSnapshot = null; - state().unblessedAggregateRootSnapshot = null; - state().scalarRootSnapshot = null; - } - - static void invalidateFullRootSnapshotIfReachable(RuntimeBase changedNode) { - PerlRuntime runtime = PerlRuntime.currentOrNull(); - if (runtime == null) return; - LifecycleRuntimeState state = runtime.lifecycleState; - ReachabilityWalker.LiveRootSnapshot liveSnapshot = state.liveRootSnapshot; - boolean liveReachable = liveSnapshot != null && liveSnapshot.mayContain(changedNode); - ReachabilityWalker.RootReachabilitySnapshot snapshot = state.fullRootSnapshot; - boolean fullReachable = snapshot != null && snapshot.isReachable(changedNode); - ReachabilityWalker.RootReachabilitySnapshot unblessedSnapshot = - state.unblessedAggregateRootSnapshot; - boolean unblessedReachable = unblessedSnapshot != null - && unblessedSnapshot.isReachable(changedNode); - if ((snapshot != null && (!snapshot.complete() || fullReachable)) - || (unblessedSnapshot != null - && (!unblessedSnapshot.complete() || unblessedReachable))) { - state.fullRootSnapshot = null; - state.unblessedAggregateRootSnapshot = null; - } - if (liveReachable) state.liveRootSnapshot = null; - } - - static void invalidateFullRootSnapshotForScalarClear() { - PerlRuntime runtime = PerlRuntime.currentOrNull(); - if (runtime != null) { - runtime.lifecycleState.liveRootSnapshot = null; - runtime.lifecycleState.fullRootSnapshot = null; - runtime.lifecycleState.unblessedAggregateRootSnapshot = null; - } - } - - /** - * Reuse scalar-owner reachability across one cleanup drain. Return - * {@code null} outside a drain so callers retain the target-specific walk - * and its original lifetime semantics. - */ - static Boolean isScalarReachableFromDrainSnapshot(RuntimeScalar scalar) { - LifecycleRuntimeState state = state(); - if (!state.flushing && state.reachabilityDrainDepth == 0) return null; - if (state.scalarRootSnapshot == null) { - state.scalarRootSnapshot = - ReachabilityWalker.scalarReachabilitySnapshot(); - } - return state.scalarRootSnapshot.isReachable(scalar); - } - - private static void invalidateDrainReachabilityCaches() { - LifecycleRuntimeState state = state(); - state.flushReachableCache = null; - state.flushTiedReachableCache = null; - state.scalarRootSnapshot = null; - state.fullRootSnapshot = null; - if (!state.flushing && state.reachabilityDrainDepth == 0) { - state.unblessedAggregateDrainRoots.clear(); - state.unblessedAggregateDrainSnapshotIncomplete = false; - } - } - - private static boolean isReachableThroughTiedHashCached(RuntimeBase base) { - LifecycleRuntimeState state = state(); - if (state.flushTiedReachableCache == null) { - state.flushTiedReachableCache = - ReachabilityWalker.reachableThroughTiedHashes(); - } - return state.flushTiedReachableCache.contains(base); - } - private static void processDeferredBase(RuntimeBase base, boolean clearWeakRefsForLocalBinding, RuntimeBase.PendingOwnerRelease ownerRelease, String transientOwnerKind) { + if (base.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS) != 0 + && base.countedOwnerSlotCount() == 0) { + state().deferredArgumentOwnerReleases.add( + new DeferredArgumentOwnerRelease(base, ownerRelease, + transientOwnerKind)); + return; + } ReachabilityQueryStats queryStats = activeReachabilityQueryStats(); if (queryStats != null) queryStats.deferredBasesProcessed++; - base.completeQueuedOwnerRelease(ownerRelease, "MortalList.processDeferredBase"); + if (ownerRelease != null + && !base.completeQueuedOwnerRelease( + ownerRelease, "MortalList.processDeferredBase")) { + // A release token can be encountered through more than one nested + // drain. Its count transition and lifecycle decision are one + // obligation, so a completed token must not decrement the referent + // again. + return; + } base.releaseTransientTraceOwner(transientOwnerKind, "MortalList.processDeferredBase"); boolean hasWeakRefs = WeakRefRegistry.hasWeakRefsTo(base); + // A lifecycle-only-at-zero token requests cleanup only if the referent + // is still unowned when the queue drains. If a real owner has acquired + // it since queueing, completing that token must leave the new count + // untouched. + boolean finalRelease = false; if (base.refCount > 0) { - base.traceRefCount(-1, "MortalList.flush (deferred decrement)"); - } - if (base.refCount > 0 && --base.refCount == 0) { + if (ownerRelease == null || !ownerRelease.isLifecycleOnlyAtZero()) { + finalRelease = base.releaseTrackedOwnerCount( + "MortalList.flush (deferred decrement)"); + } + } else if (base.isRefCountTracked() && base.refCount == 0 + && ownerRelease != null) { + // The queue token may represent a real edge released after a + // transient undercount, or an explicit zero-count temporary + // finalization request. Process that lifecycle boundary directly; + // do not manufacture a positive refCount just to enter this path. + finalRelease = true; + } + // Counted slots are detached before their queued decrement runs. Their + // slot-release callback therefore still sees the old count as a live + // parent owner. Recheck proxy-backed scalar values after the count + // transition, when the parent may have lost its final Perl owner. + if (base instanceof RuntimeArray || base instanceof RuntimeHash) { + base.recheckProxyValueOwnersIfUnowned(); + } + if (finalRelease) { + boolean aggregateReferent = base instanceof RuntimeArray || base instanceof RuntimeHash; + // Aggregate owner slots have their own deferred-release rule below. + // Refresh scalar-cell owners here for other referents before the + // final counted release checks whether any owner slot remains. + boolean hasUntrackedReferenceOwner = !aggregateReferent + && base.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE) != 0 + && base.hasUntrackedReferenceOwnerSlotIdentity(); + // A closure pad can outlive its CV's final Perl owner until the + // captured referent next reaches a lifecycle boundary. Retire only + // pads whose CODE owner ledger is already empty before deciding + // that the capture itself keeps this referent alive. if (base.hasSemanticCaptureOwner()) { - // Captured aggregate pads use native owner slots. Keep the - // legacy count at zero while one is active; its final release - // will perform the lifecycle transition. Scalar captures still - // have a legacy bridge count and retain the old compatibility - // sentinel behavior. - if (base.nativeCaptureOwnerCount() == 0) base.refCount = 1; - } else if (base.localBindingExists) { + base.releaseUnownedClosureCaptures(); + } + if (base instanceof RuntimeCode code && code.hasActiveCodeOwner()) { + code.deferFinalReleaseToActiveCode(); + } else if (base.hasSemanticCaptureOwner()) { + // Both native and legacy closure-pad slots identify the Perl + // edge that keeps this referent alive. The direct PerlIO::via + // hold is runtime scaffolding around PUSHED; when POPPED drops + // it, retain the tracked zero count and let the closure slot + // carry the remaining lifecycle. Ordinary scalar weakening + // continues to use weak-tracked state while a semantic capture is + // the only remaining strong path. + boolean releasedViaLayerOwner = ownerRelease != null + && ownerRelease.ownerSlotRelease != null + && ownerRelease.ownerSlotRelease.kind() + == PerlOwnerSlot.Kind.IO_VIA_LAYER; + if (ownerRelease == null || releasedViaLayerOwner) { + base.deferZeroCountFinalReleaseToUncountedOwnerSlots(); + } else { + base.deferFinalReleaseToUncountedOwnerSlots(); + } + } else if (base instanceof RuntimeScalar scalar + && scalar.referencedByScalarReference + && (scalar.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ALIAS_CELL) != 0 + || scalar.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ALIAS_CELL) != 0)) { + // Refalias aggregate slots own scalar cells without adding a + // legacy reference count. Keep the zero-count cell alive + // until its last alias slot releases and runs scalar cleanup. + base.deferZeroCountFinalReleaseToUncountedOwnerSlots(); + } else if (base instanceof RuntimeScalar scalar + && scalar.referencedByScalarReference + && base.hasScalarCellStorageOwnerSlotIdentity() + && base.hasUncountedPerlOwnerSlotIdentity()) { + // A registered lexical/package scalar cell is itself the + // referent of \$cell. Retain that lifetime at refCount zero + // through its exact storage identity; localBindingExists is + // metadata and cannot stand in for the Perl edge. + base.deferZeroCountFinalReleaseToUncountedOwnerSlots(); + } else if (base.hasTemporaryRootOwnerSlotIdentity()) { + // A snapshot root is a runtime lease, not a Perl strong edge. + // Keep its cloned weak observers intact for the lease lifetime + // without fabricating a positive refCount. Releasing the last + // lease completes the pending weak cleanup through the slot. + base.deferFinalReleaseToTemporaryRootSlots(); + } else if ((ownerRelease != null + || base.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE) != 0) + && base.hasCurrentUncountedPerlOwnerSlotIdentity()) { + // An exact release token makes current uncounted Perl edges + // authoritative. Persistent CODE state is also a direct owner + // when a legacy bridge decrement has no token. Other tokenless + // synthetic releases retain the compatibility recovery below + // until their producers are migrated. Temporary roots and IO + // resource leases are excluded by the Perl-owner predicate. + base.deferFinalReleaseToUncountedOwnerSlots(); + } else if (base.localBindingExists && !(base instanceof RuntimeCode)) { if (base instanceof RuntimeScalar scalar && scalar.referencedByScalarReference - && scalar.captureCount == 0 + && !scalar.hasClosureCaptureOwner() && !MyVarCleanupStack.isRegistered(scalar)) { // The declaring lexical is gone and this was the last // counted scalar reference. A returned blessed CODE @@ -1783,7 +1895,6 @@ private static void processDeferredBase(RuntimeBase base, boolean clearWeakRefsF // subroutine exits. Do not let that stale lexical marker // suppress DESTROY after the final container deletion. base.localBindingExists = false; - base.refCount = Integer.MIN_VALUE; DestroyDispatch.callDestroy(base); return; } @@ -1798,293 +1909,119 @@ private static void processDeferredBase(RuntimeBase base, boolean clearWeakRefsF if (clearWeakRefsForLocalBinding) { WeakRefRegistry.clearWeakRefsTo(base); } - } else if (base instanceof RuntimeCode code - && hasWeakRefs - && (RuntimeCode.isActiveCode(code) - || (!code.hadStashRef && RuntimeCode.argsStackDepth() > 1))) { - // Sub::Defer stores a weak self-reference in the deferred - // CODE's captured info array. Selective refcounts can reach - // zero while the wrapper is still executing or nested - // generation is wiring Moo metadata. Clearing then makes - // nested dispatch call undefer_sub(undef). - base.refCount = 1; + } else if (base.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_GLOB_SLOT) != 0) { + // A named IO stash slot directly owns its typeglob even though + // that edge does not participate in the legacy referent count. + // Keep weak observers until the exact stash entry is removed. + base.deferFinalReleaseToUncountedOwnerSlots(); + } else if (base.hasCurrentUncountedPerlOwnerSlotIdentity()) { + // A current lexical, package, alias, or resource slot proves + // that the referent still has a Perl owner. + // Carry the lifecycle obligation on the exact identity instead + // of searching for another owner. + base.deferFinalReleaseToUncountedOwnerSlots(); + } else if (isFinalCountedReferentRelease(base, ownerRelease)) { + // This decrement retired an identified scalar/element edge. + // Every other migrated edge is already absent from the ledger; + // there is no remaining Perl owner to preserve. + DestroyDispatch.callDestroyFromCountedOwner(base); } else if (base instanceof RuntimeScalarReadOnly - && hasWeakRefs && RuntimeCode.isInstalledPadConstant(base)) { - // A readonly scalar referenced through \("literal") belongs to - // its defining subroutine's pad. Constructor/call temporaries - // are selectively counted, but that pad ownership is not. - // Preserve the weak ref while the sub remains installed; - // RuntimeCode.clearPadConstantWeakRefs() clears it when the - // sub's glob is replaced, matching Perl optree reaping. - base.refCount = 1; - } else if (hasWeakRefs && restoreReachableOwnerCount(base)) { - // A counted owner that is still reachable through a real - // Perl root is authoritative, including for classes with - // DESTROY. Pure-Perl tied containers expose this shape: - // Test::Spec stores a context in Tie::IxHash and weakens the - // child's parent link. Method/argument temporaries can make - // the selective count dip to zero, but the tied handler's - // array slot remains a strong owner. Destroying here clears - // that weak parent and corrupts the context tree. - } else if (base.blessId == 0 - && (base instanceof RuntimeArray || base instanceof RuntimeHash) - && isUnblessedAggregateReachableDuringDrain(base)) { - // Unblessed aggregates can reach zero while a parser is - // assembling a tree, before it installs the first weak parent - // edge. A temporary reference can make the selective count - // reach zero even though an enclosing live aggregate already - // owns the node. Consult the shared drain snapshot before a - // later weaken() sees a destroyed referent. The next cleanup - // boundary can still reclaim a tree after its Perl root goes - // away. - base.refCount = 1; - } else if (hasWeakRefs - && base.possiblyStoredInTiedHandler - && isReachableThroughTiedHashCached(base)) { - // The active-owner set starts recording at the first weaken, - // so a handler slot populated just before weaken can be absent - // from it. Confirm the missing ownership through the narrower - // tied-handler root walk before protecting DESTROY objects. - base.refCount = 1; - } else if (base.blessId == 0 - && hasWeakRefs - && ReachabilityWalker.hasStrongCycle(base)) { - // Perl keeps unblessed strong cycles alive even without an - // external root. Decide this before deferring to a registry - // sweep: the cycle itself proves the target is still alive. - base.refCount = 1; - } else if (base.blessId == 0 - && hasWeakRefs - && (ReachabilityWalker.isReachableFromLiveCodeCaptures(base) - || ReachabilityWalker.isReachableFromGlobalCodeCaptures(base))) { - // A positive capture query is conclusive for this unblessed - // target. Keep it alive without requesting a registry-wide - // sweep; unknown targets still use the complete-boundary path. - base.refCount = 1; - } else if (base.blessId == 0 - && hasWeakRefs - && canDeferCapturedTargetCheckToBoundarySweep(state())) { - // Carry released unblessed targets to the next safe complete - // sweep. This avoids scanning live and installed CODE captures - // repeatedly after an inconclusive query while keeping their - // weak observers valid until the sweep decides reachability. - if (state().deferredCaptureSweepCandidates.isEmpty()) { - state().deferredCaptureSweepGeneration = - state().boundaryWeakSweepGeneration; - } - // Keep the target alive until the next safe complete sweep - // decides whether a live CODE capture still owns it. - base.refCount = 1; - state().deferredCaptureSweepCandidates.add(base); - requestImmediateWeakSweep(); - } else if (base.blessId == 0 - && hasWeakRefs - && RuntimeCode.argsStackDepth() > 1) { - // A returned aggregate can be reparented into another aggregate - // while a nested call still owns the only compiler-visible - // temporary. Mojo::DOM58 does this when it parses replacement - // markup, weakens child-to-parent links, and splices the parsed - // nodes into the live DOM. Selective refcounts can hit zero as - // the temporary parser tree unwinds even though the outer call - // already holds the parent strongly. Defer the unblessed weak - // target just as we do for ordinary blessed objects below; a - // later top-level sweep can still clear a genuinely dead tree. - base.refCount = 1; - } else if (base.blessId != 0 - && hasWeakRefs - && (isReachableFromExternalRootCached(base) - || isReachableFromFullRootSnapshot(base))) { - // A nested request can temporarily consume the selective owner - // count of an object that is still retained below a package - // root. Mojolicious::Lite keeps its route tree in a package - // singleton; a mounted route also has a weak parent link from - // the embedded application's route root. When the request Match - // object is destroyed, its endpoint release can make that live - // route dip to zero even though the singleton's children array - // still owns it. The inherited Mojo::Base::DESTROY method makes - // the ordinary no-DESTROY guard inapplicable, and recursively - // destroying the route tears down the mounted renderer helper - // namespace. Preserve only objects proven reachable from a - // live Perl root; final owner removal still destroys them at - // a later boundary. - base.refCount = 1; - } else if (base.blessId != 0 - && hasWeakRefs - && !blessedClassHasDestroy(base) - && (isReachableFromExternalRootCached(base) - || isReachableFromFullRootSnapshot(base))) { - // A weakened probe copy can make the selective count reach - // zero while an ordinary blessed object is still held by a - // live lexical. Test::Refcount exercises this shape; clearing - // weak refs here drops callback invocants that should remain - // valid. Real roots and explicit method-invocant holds still - // protect live objects. Classes with DESTROY keep the stricter - // path. - base.refCount = 1; - } else if (base.blessId != 0 - && hasWeakRefs - && !blessedClassHasDestroy(base) - && RuntimeCode.argsStackDepth() > 1 - && !base.clearedOwnedAggregateElement) { - // Nested calls can retain expression temporaries which are not - // selective refcount owners. Leave the count at zero and let - // the next outer statement boundary decide from Perl-visible - // reachability. Retaining a synthetic count here leaks weak - // observers after a method-local alias releases the final real - // owner (Algorithm::SlidingWindow). - requestTargetedWeakSweep(base); - } else if (base.blessId != 0 - && base.storedInPackageGlobal - && hasWeakRefs - && isReachableCached(base)) { - // Module-global metadata such as Moose/Class::MOP metaclasses - // can transiently hit zero in the selective refcount model. - // If the walker can still reach the object from Perl-visible - // roots, keep weak links to it intact. + // A readonly scalar referenced through \("literal") has an + // explicit owner slot from each live CV optree that contains it. + // Defer lifecycle cleanup to those slots instead of fabricating + // a legacy count that has no corresponding Perl reference. + base.deferFinalReleaseToUncountedOwnerSlots(); + } else if (base.hasNonPackageAggregateUncountedOwnerSlotIdentity() + || (aggregateReferent + ? (base.blessId != 0 && !hasWeakRefs + && base.hasUntrackedReferenceOwnerSlotIdentity()) + : hasUntrackedReferenceOwner)) { + // A surviving non-package aggregate slot, or an untracked + // package owner of a blessed aggregate without direct weak + // observers, defers cleanup until its release. + base.deferFinalReleaseToUncountedOwnerSlots(); } else { - base.refCount = Integer.MIN_VALUE; + // Call depth is not ownership. If every counted and direct + // owner check above is empty, a weak referent is final here; + // deferring cleanup would strand the weak scalars. DestroyDispatch.callDestroy(base); } } - } - - private static boolean blessedClassHasDestroy(RuntimeBase base) { - String className = NameNormalizer.getBlessStr(base.blessId); - return className != null && DestroyDispatch.classHasDestroy(base.blessId, className); - } - - private static boolean restoreReachableOwnerCount(RuntimeBase base) { - int ownerCount = base.reachableOwnerCount(); - if (ownerCount == 0) return false; - base.refCount = ownerCount; - return true; + // A nested scope may defer destruction while another active owner + // remains. Recheck the ledger after the final counted release so the + // last trusted slot completes cleanup here. + if (base.isRefCountTracked() && base.refCount == 0 + && isFinalCountedReferentRelease(base, ownerRelease) + && !base.localBindingExists + && !base.hasClosureCaptureOwner() + && !base.hasPendingReturnOwner() + && !GlobalVariable.isPackageRootedAggregate(base) + && !(base instanceof RuntimeCode code + && (code.hasActiveCodeOwner() + || code.hasStashCodeSlotOwner()))) { + DestroyDispatch.callDestroyFromCountedOwner(base); + } + if (base instanceof RuntimeCode code) code.finishActiveCodeOwnerRelease(); + if (base instanceof RuntimeScalar scalar) { + PerlOwnerSlot.finishDeferredScalarCellRelease(scalar); + } + } + + static boolean canTrustFinalCountedRelease(RuntimeBase base) { + boolean supportedReferent = base instanceof RuntimeArray || base instanceof RuntimeHash + || (base instanceof RuntimeScalar scalar + && !(scalar instanceof RuntimeScalarReadOnly) + && !scalar.hasClosureCaptureOwner()) + || (base instanceof RuntimeCode code + && (code.hasCountedCodeSlots || !code.hasStashCodeSlotOwner()) + && !SpecialBlock.hasPendingEndBlock(code)); + return supportedReferent && !base.hasOwnerSlots(); + } + + private static boolean isFinalCountedReferentRelease( + RuntimeBase base, RuntimeBase.PendingOwnerRelease release) { + if (release == null || release.ownerSlotRelease == null) return false; + PerlOwnerSlot.Kind kind = release.ownerSlotRelease.kind(); + if (kind == PerlOwnerSlot.Kind.IO_VIA_LAYER) return !base.hasOwnerSlots(); + if (!canTrustFinalCountedRelease(base)) return false; + return switch (kind) { + case SCALAR_CELL, CODE_SLOT, ARRAY_ELEMENT, HASH_ELEMENT, ARGUMENT_VALUE, + ARGUMENT_CONTAINER, RETURN_VALUE, TIE_HANDLER, + ARGUMENT_TIE_HANDLER, SCALAR_REFERENCE_CONTENTS -> true; + default -> false; + }; } public static void flush() { LifecycleRuntimeState state = state(); if (!state.mortalActive) return; - if (state.flushing) return; - boolean topLevel = !state.hasMortalMarks(); + if (state.flushing || state.flushSuppressed) return; if (state.pending.isEmpty() && state.pendingTiedReleases.isEmpty() - && state.pendingIoReleases.isEmpty()) { + && state.pendingIoReleases.isEmpty() + && state.pendingUntrackedReturnOwnerReleases.isEmpty() + && state.pendingTransientListAssignmentRhsByFrame.isEmpty()) { processReadyDeferredCaptures(state); - maybeAutoSweep(state); - finalizeDeferredCaptureSweepCandidates(state); refreshBoundaryWork(state); return; } - invalidateDrainReachabilityCaches(); state.flushing = true; - if (topLevel) state.topLevelFlushDepth++; try { - processDeferredEntriesFrom(0, 0, 0); + releaseTransientListAssignmentRhsAtBoundary(state); + processDeferredEntriesFrom(0, 0, 0, 0); state.pending.clear(); state.pendingOwnerReleases.clear(); state.pendingOwnerScalars.clear(); + state.pendingArgumentFrames.clear(); state.pendingTransientOwnerKinds.clear(); state.pendingTiedReleases.clear(); state.pendingIoReleases.clear(); + state.pendingUntrackedReturnOwnerReleases.clear(); state.markDepth = 0; // All entries drained; marks are meaningless now } finally { - if (topLevel) state.topLevelFlushDepth--; state.flushing = false; - invalidateDrainReachabilityCaches(); } processReadyDeferredCaptures(state); - maybeAutoSweep(state); - finalizeDeferredCaptureSweepCandidates(state); - refreshBoundaryWork(state); - } - - private static void maybeAutoSweep() { - maybeAutoSweep(state()); - } - - private static void maybeAutoSweep(LifecycleRuntimeState state) { - maybeAutoSweep(state, Collections.emptySet(), null); - } - - private static void maybeAutoSweep( - LifecycleRuntimeState state, - Set releasedTargets, - ReachabilityWalker.ReleasedWeakSweepResult releasedSweepResult) { - if (state.weakSweepSuppressionDepth > 0) return; - if (AUTO_GC_DISABLED) return; - if (state.inAutoSweep) return; - boolean immediateSweep = state.immediateWeakSweepRequested; - // FORCE_SWEEP_EVERY_FLUSH bypasses the weakRefsExist gate AND the - // 5-s throttle so reproducers can deterministically trigger the - // walker at every statement boundary. - if (!FORCE_SWEEP_EVERY_FLUSH && !state.weakRefsExist && !immediateSweep) return; - // Phase B2a: skip while require/use/BEGIN/eval-STRING is running. - // Those paths depend on weak-refed intermediate state staying - // defined until the init completes. - if (ModuleInitGuard.inModuleInit()) return; - // Sweeps must stay out of nested calls. Active call frames can hold - // temporaries and closure metadata through JVM locals that are not - // complete Perl-visible walker roots yet. - if (RuntimeCode.argsStackDepth() > 1) return; - if (!state.temporaryRoots.isEmpty()) return; - if (!FORCE_SWEEP_EVERY_FLUSH && !immediateSweep) { - long now = System.nanoTime(); - if (now - state.lastAutoSweepNanos < AUTO_SWEEP_MIN_INTERVAL_NS) return; - state.lastAutoSweepNanos = now; - } - state.inAutoSweep = true; - try { - if (immediateSweep) { - state.immediateWeakSweepRequested = false; - state.lastAutoSweepNanos = System.nanoTime(); - } - // Quiet auto-sweeps run from normal statement-boundary checks. - // Do not force HotSpot GC here: current live-lexical tracking is - // driven by MyVarCleanupStack, and forcing JVM GC at this cadence - // dominates DBIC-scale runtimes. Keep the old forced behavior only - // for the diagnostic "sweep every flush" mode. - int cleared = ReachabilityWalker.sweepWeakRefs( - true, FORCE_SWEEP_EVERY_FLUSH, releasedTargets, releasedSweepResult); - state.boundaryWeakSweepGeneration++; - if (AUTO_GC_DEBUG) { - System.err.println("DBG auto-sweep reason=" - + (immediateSweep ? "immediate" : "cadence") - + " cleared=" + cleared); - } - } finally { - state.inAutoSweep = false; - } - } - - private static void maybeAutoSweepIfRequested(LifecycleRuntimeState state) { - if (state.immediateWeakSweepRequested) { - maybeAutoSweep(state); - } - } - - private static void maybeAutoSweepAtStatementBoundary( - LifecycleRuntimeState state, boolean topLevel) { - if (state.weakSweepSuppressionDepth > 0) return; - Set releasedTargets = Collections.emptySet(); - ReachabilityWalker.ReleasedWeakSweepResult releasedSweepResult = null; - if (!state.targetedWeakSweepReferents.isEmpty() && state.temporaryRoots.isEmpty()) { - releasedTargets = Collections.newSetFromMap(new IdentityHashMap<>()); - releasedTargets.addAll(state.targetedWeakSweepReferents); - state.targetedWeakSweepReferents.clear(); - releasedSweepResult = - ReachabilityWalker.sweepReleasedWeakReferents(releasedTargets); - } - if (topLevel) { - maybeAutoSweep(state, releasedTargets, releasedSweepResult); - finalizeDeferredCaptureSweepCandidates(state); - } - } - - private static void maybeSweepStatementBoundaryDestroyables() { - LifecycleRuntimeState state = state(); - if (!ModuleInitGuard.inModuleInit() - && DestroyDispatch.hasStatementBoundaryDestroyableObjects()) { - ReachabilityWalker.sweepStatementBoundaryDestroyableObjects(); - } refreshBoundaryWork(state); } @@ -2110,24 +2047,30 @@ public static int pendingSize() { * @param startIdx the {@link #pendingSize} captured before apply() */ public static void drainPendingSince(int startIdx) { + drainPendingSince(startIdx, true); + } + + private static void drainPendingSince( + int startIdx, boolean clearWeakRefsForLocalBinding) { if (!isActive()) return; if (startIdx < 0) startIdx = 0; LifecycleRuntimeState state = state(); if (startIdx >= state.pending.size()) return; - invalidateDrainReachabilityCaches(); - state.reachabilityDrainDepth++; - // Loop because DESTROY may add further entries - int i = startIdx; + state.deferredReleaseDrainDepth++; + int pendingIdx = startIdx; try { - while (i < state.pending.size()) { - processDeferredBase(state.pending.get(i), true, - state.pendingOwnerReleases.get(i), - state.pendingTransientOwnerKinds.get(i)); - i++; + // Exact operation-boundary releases keep queue order. Frame marks + // use depth-first LIFO draining; this path can be nested inside a + // destructor's count probe and must preserve its established order. + while (pendingIdx < state.pending.size()) { + int currentIndex = pendingIdx++; + processDeferredBase(state.pending.get(currentIndex), + clearWeakRefsForLocalBinding, + state.pendingOwnerReleases.get(currentIndex), + state.pendingTransientOwnerKinds.get(currentIndex)); } } finally { - state.reachabilityDrainDepth--; - invalidateDrainReachabilityCaches(); + state.deferredReleaseDrainDepth--; } // Truncate the pending list back to startIdx to mark these entries // as processed. Outer flush won't re-process them. @@ -2135,6 +2078,7 @@ public static void drainPendingSince(int startIdx) { state.pending.remove(state.pending.size() - 1); state.pendingOwnerReleases.remove(state.pendingOwnerReleases.size() - 1); state.pendingOwnerScalars.remove(state.pendingOwnerScalars.size() - 1); + state.pendingArgumentFrames.remove(state.pendingArgumentFrames.size() - 1); state.pendingTransientOwnerKinds.remove(state.pendingTransientOwnerKinds.size() - 1); } } @@ -2155,8 +2099,7 @@ public static void drainPendingTailCallArgs( owners.addAll(args.elements); LifecycleRuntimeState state = state(); - if (state.flushing) return; - invalidateDrainReachabilityCaches(); + if (state.flushing || state.flushSuppressed) return; state.flushing = true; try { for (int i = state.pending.size() - 1; i >= 0; i--) { @@ -2165,20 +2108,23 @@ public static void drainPendingTailCallArgs( RuntimeScalar owner = ownerRef == null ? null : ownerRef.get(); RuntimeBase pending = state.pending.get(i); boolean directOwner = owner != null && owners.contains(owner); - boolean frameCopy = owner != null && owner.copiedFromArgumentFrame(argumentFrame); + boolean frameOwner = argumentFrame != null + && state.pendingArgumentFrames.get(i) == argumentFrame; boolean abandonedBirthTemporary = owner == null && "bless mortal temporary".equals(state.pendingTransientOwnerKinds.get(i)) && args.elements.stream().anyMatch(argument -> argument != null && argument.value == pending); // A CORE::GLOBAL wrapper can tail-call the bless override with - // a newly blessed argument and return that same reference. - // Its bless temporary is the return value's only owner until - // the caller materializes the result, so keep the pending - // decrement queued for the caller's normal scope cleanup. - if (abandonedBirthTemporary && directlyReferences(returnedResult, pending)) { + // a newly blessed argument. Keep its mortal decrement queued + // while either the tail-call argument list or the completed + // result still carries that reference; the receiving call + // boundary will retire it after the handoff. + if (abandonedBirthTemporary + && (pending.hasCurrentPerlOwnerSlotIdentity() + || pending.hasPendingReturnOwner())) { continue; } - if ((!directOwner && !frameCopy && !abandonedBirthTemporary) + if ((!directOwner && !frameOwner && !abandonedBirthTemporary) || (owner == null && !abandonedBirthTemporary)) continue; RuntimeBase.PendingOwnerRelease ownerRelease = state.pendingOwnerReleases.get(i); @@ -2186,21 +2132,21 @@ public static void drainPendingTailCallArgs( state.pending.remove(i); state.pendingOwnerReleases.remove(i); state.pendingOwnerScalars.remove(i); + state.pendingArgumentFrames.remove(i); state.pendingTransientOwnerKinds.remove(i); processDeferredBase(pending, true, ownerRelease, transientOwnerKind); } } finally { state.flushing = false; - invalidateDrainReachabilityCaches(); } refreshBoundaryWork(state); } /** * Push a mark recording the current pending list size. - * Called before scope-exit cleanup so that popAndFlush() only - * processes entries added by the cleanup (not earlier entries - * from outer scopes or prior operations). + * Called before scope-exit cleanup for ordinary scopes, or at block + * entry when the complete block lifetime must be flushed. popAndFlush() + * then processes only entries added after that dynamic boundary. * Also called at function entry (RuntimeCode.apply) to establish * a function-scoped mortal boundary — entries from the caller's * scope stay below the mark and are not processed by statement- @@ -2214,7 +2160,36 @@ public static void pushMark() { static void pushMark(LifecycleRuntimeState state) { if (!state.mortalActive) return; state.pushMortalMark(state.pending.size(), state.pendingTiedReleases.size(), - state.pendingIoReleases.size()); + state.pendingIoReleases.size(), + state.pendingUntrackedReturnOwnerReleases.size()); + } + + /** Push a block boundary even when its first tracked value is created later. */ + public static void pushScopeMark() { + LifecycleRuntimeState state = state(); + state.pushMortalMark(state.pending.size(), state.pendingTiedReleases.size(), + state.pendingIoReleases.size(), + state.pendingUntrackedReturnOwnerReleases.size()); + } + + /** Current nesting depth for exception boundaries that must unwind marks. */ + public static int markDepth() { + return state().markDepth; + } + + /** + * Discard marks opened after {@code depth} without processing their + * entries. Exception cleanup releases lexical owners and drains the + * resulting queue separately. + */ + public static void restoreMarkDepth(int depth) { + LifecycleRuntimeState state = state(); + if (depth < 0) { + throw new IllegalArgumentException("Invalid mortal mark depth: " + depth + + " (current " + state.markDepth + ")"); + } + if (depth > state.markDepth) return; + state.markDepth = depth; } /** @@ -2248,13 +2223,12 @@ public static void flushAboveMark() { if (runtimesWithBoundaryWork.get() == 0) return; LifecycleRuntimeState state = state(); if (!state.mortalActive) return; - if (state.flushing) return; - boolean topLevel = !state.hasMortalMarks(); + if (state.flushing || state.flushSuppressed) return; if (state.pending.isEmpty() && state.pendingTiedReleases.isEmpty() - && state.pendingIoReleases.isEmpty()) { + && state.pendingIoReleases.isEmpty() + && state.pendingUntrackedReturnOwnerReleases.isEmpty() + && state.pendingTransientListAssignmentRhsByFrame.isEmpty()) { processReadyDeferredCaptures(state); - processUnreachableScopeExitCaptureCandidates(state); - maybeAutoSweepAtStatementBoundary(state, topLevel); refreshBoundaryWork(state); return; } @@ -2263,24 +2237,26 @@ public static void flushAboveMark() { ? state.tiedReleaseMarks[state.markDepth - 1] : 0; int ioMark = state.hasMortalMarks() ? state.ioReleaseMarks[state.markDepth - 1] : 0; + int untrackedReturnOwnerMark = state.hasMortalMarks() + ? state.untrackedReturnOwnerMarks[state.markDepth - 1] : 0; if (state.pending.size() <= mark && state.pendingTiedReleases.size() <= tiedMark - && state.pendingIoReleases.size() <= ioMark) { + && state.pendingIoReleases.size() <= ioMark + && state.pendingUntrackedReturnOwnerReleases.size() <= untrackedReturnOwnerMark + && state.pendingTransientListAssignmentRhsByFrame.isEmpty()) { processReadyDeferredCaptures(state); - processUnreachableScopeExitCaptureCandidates(state); - maybeAutoSweepAtStatementBoundary(state, topLevel); refreshBoundaryWork(state); return; } - invalidateDrainReachabilityCaches(); state.flushing = true; - if (topLevel) state.topLevelFlushDepth++; try { - processDeferredEntriesFrom(mark, tiedMark, ioMark); + releaseTransientListAssignmentRhsAtBoundary(state); + processDeferredEntriesFrom(mark, tiedMark, ioMark, untrackedReturnOwnerMark); // Remove only entries above the mark while (state.pending.size() > mark) { state.pending.removeLast(); state.pendingOwnerReleases.removeLast(); state.pendingOwnerScalars.removeLast(); + state.pendingArgumentFrames.removeLast(); state.pendingTransientOwnerKinds.removeLast(); } while (state.pendingTiedReleases.size() > tiedMark) { @@ -2289,25 +2265,23 @@ public static void flushAboveMark() { while (state.pendingIoReleases.size() > ioMark) { state.pendingIoReleases.removeLast(); } + while (state.pendingUntrackedReturnOwnerReleases.size() > untrackedReturnOwnerMark) { + state.pendingUntrackedReturnOwnerReleases.removeLast(); + } } finally { - if (topLevel) state.topLevelFlushDepth--; state.flushing = false; - invalidateDrainReachabilityCaches(); } processReadyDeferredCaptures(state); - processUnreachableScopeExitCaptureCandidates(state); - maybeAutoSweepAtStatementBoundary(state, topLevel); refreshBoundaryWork(state); } - /** - * Whether cleanup is currently running at a top-level Perl statement - * boundary. A top-level temporary can be finalized immediately before - * {@code ${^GLOBAL_PHASE}} changes to {@code DESTRUCT}; Perl still treats - * a destructor resurrection there as global-destruction resurrection. - */ - public static boolean isDrainingTopLevelTemporary() { - return state().topLevelFlushDepth > 0; + /** Advance Perl statement-lifetime temporaries at a compiled statement end. */ + public static void flushStatementBoundary() { + if (runtimesWithBoundaryWork.get() == 0) return; + LifecycleRuntimeState state = state(); + if (!state.mortalActive) return; + state.statementBoundarySequence++; + flushAboveMark(); } /** @@ -2323,26 +2297,25 @@ public static void popAndFlush() { int mark = state.marks[markIndex]; int tiedMark = state.tiedReleaseMarks[markIndex]; int ioMark = state.ioReleaseMarks[markIndex]; + int untrackedReturnOwnerMark = state.untrackedReturnOwnerMarks[markIndex]; if (state.pending.size() <= mark && state.pendingTiedReleases.size() <= tiedMark - && state.pendingIoReleases.size() <= ioMark) { + && state.pendingIoReleases.size() <= ioMark + && state.pendingUntrackedReturnOwnerReleases.size() <= untrackedReturnOwnerMark) { // Even if no mortal entries to process, check deferred captures - // that may have become ready (captureCount reached 0) during + // that may have become ready after their final closure owner left during // scope cleanup. processReadyDeferredCaptures(state); - processUnreachableScopeExitCaptureCandidates(state); - maybeSweepStatementBoundaryDestroyables(); - maybeAutoSweepIfRequested(state); - finalizeDeferredCaptureSweepCandidates(state); + DestroyDispatch.processRescuedObjects(); return; } - invalidateDrainReachabilityCaches(); // Process entries from mark onwards (DESTROY may add new entries) - processDeferredEntriesFrom(mark, tiedMark, ioMark); + processDeferredEntriesFrom(mark, tiedMark, ioMark, untrackedReturnOwnerMark); // Remove only the entries we processed (keep entries before mark) while (state.pending.size() > mark) { state.pending.removeLast(); state.pendingOwnerReleases.removeLast(); state.pendingOwnerScalars.removeLast(); + state.pendingArgumentFrames.removeLast(); state.pendingTransientOwnerKinds.removeLast(); } while (state.pendingTiedReleases.size() > tiedMark) { @@ -2351,13 +2324,31 @@ public static void popAndFlush() { while (state.pendingIoReleases.size() > ioMark) { state.pendingIoReleases.removeLast(); } - invalidateDrainReachabilityCaches(); + while (state.pendingUntrackedReturnOwnerReleases.size() > untrackedReturnOwnerMark) { + state.pendingUntrackedReturnOwnerReleases.removeLast(); + } // After processing mortals (which may have triggered releaseCaptures // via callDestroy), check if any deferred captures are now ready. processReadyDeferredCaptures(state); - processUnreachableScopeExitCaptureCandidates(state); - maybeSweepStatementBoundaryDestroyables(); - maybeAutoSweepIfRequested(state); - finalizeDeferredCaptureSweepCandidates(state); + DestroyDispatch.processRescuedObjects(); + } + + /** Pop a mark opened by {@link #pushScopeMark()}, including before tracking activates. */ + public static void popScopeMarkAndFlush() { + LifecycleRuntimeState state = state(); + if (!state.hasMortalMarks()) return; + if (!state.mortalActive) { + state.popMortalMark(); + return; + } + // A surrounding deferred-entry drain owns the queue cursor and will + // process entries appended by this nested cleanup after the callback + // returns. Flush suppression is separate: a scoped mark can still + // safely drain only the entries created after that mark. + if (state.deferredReleaseDrainDepth > 0) { + state.popMortalMark(); + return; + } + popAndFlush(); } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/MyVarCleanupStack.java b/src/main/java/org/perlonjava/runtime/runtimetypes/MyVarCleanupStack.java index 807c62df40..a3cf0d607c 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/MyVarCleanupStack.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/MyVarCleanupStack.java @@ -4,11 +4,12 @@ import java.util.IdentityHashMap; /** - * Runtime cleanup stack for my-variables during exception unwinding. + * Runtime cleanup stack for my-variables when a Perl frame exits early. *

    * Parallels the {@code local} mechanism (InterpreterState save/restore): - * my-variables are registered at creation time, and cleaned up on exception - * via {@link #unwindTo(int)}. On normal scope exit, existing + * my-variables are registered at creation time, and cleaned up when an + * exception or non-local control-flow return bypasses normal teardown via + * {@link #unwindTo(int)}. On normal scope exit, existing * {@code scopeExitCleanup} bytecodes handle cleanup, and {@link #popMark(int)} * discards the registrations without cleanup. *

    @@ -32,60 +33,26 @@ private static ArrayList stack() { return PerlRuntime.current().executionState().myVarCleanupStack; } - // Phase I: parallel identity-counted set for O(1) `isLive(var)` check - // from the reachability walker. Maps var -> registration count - // (a single var can be registered multiple times if declared in - // nested scopes with the same slot reuse). - private static IdentityHashMap liveCounts() { - return PerlRuntime.current().executionState().liveMyVarCounts; - } - private static IdentityHashMap registeredCounts() { return PerlRuntime.current().executionState().registeredMyVarCounts; } - /** - * Phase I: O(1) check whether the given object is currently registered - * (its declaration scope hasn't exited). Used by the reachability - * walker to filter out stale ScalarRefRegistry entries — scalars - * whose scopes have exited but whose Java-level lifetime persists - * (e.g. via MortalList.deferredCaptures) were falsely marking - * their referents as reachable. - */ + /** True when the declaration scope for this lexical has not exited. */ public static boolean isLive(Object var) { - if (var == null) return false; - return liveCounts().containsKey(var); + return isRegistered(var); } /** - * True when {@code var} is currently registered as a lexical, regardless - * of whether weak-ref tracking has populated the live-count map. Used by - * first-bless paths that can run before the first {@code weaken()} call. - * The identity-counted registration map keeps this check O(1). + * True when {@code var} is currently registered as a lexical. Used by + * lifecycle checks that need to distinguish an active lexical from a + * stale Java reference. The identity-counted registration map keeps this + * check O(1). */ public static boolean isRegistered(Object var) { if (var == null) return false; return registeredCounts().containsKey(var); } - /** - * Snapshot the currently-live my-variables. Used by the - * reachability walker's per-object query - * ({@link ReachabilityWalker#isReachableFromRoots}) to seed from - * still-in-scope lexical containers (e.g. {@code my %METAS} - * declared at file scope of a still-loading module). The - * live-counts map keys are stable identity references to - * RuntimeScalar / RuntimeArray / RuntimeHash instances. - */ - public static java.util.List snapshotLiveVars() { - return new java.util.ArrayList<>(liveCounts().keySet()); - } - - /** Snapshot registered lexical slots without requiring weak-ref tracking. */ - public static java.util.List snapshotRegisteredVars() { - return new java.util.ArrayList<>(stack()); - } - /** * Called at subroutine entry (in {@code RuntimeCode.apply()}). * Returns a mark position for later {@link #popMark(int)} or @@ -114,47 +81,22 @@ static int pushMark(ExecutionRuntimeState executionState) { */ public static void register(Object var) { stack().add(var); - if (var != null) registeredCounts().merge(var, 1, Integer::sum); - // liveCounts is consulted by ReachabilityWalker.sweepWeakRefs and - // .isReachableFromRoots. We populate it lazily — only after the - // first weaken() call (which sets WeakRefRegistry.weakRefsExist). - // Tests that never weaken pay zero per-`my` cost; tests that do - // weaken trigger a one-time backfill via - // {@link #snapshotStackToLiveCounts()} from WeakRefRegistry, - // which seeds liveCounts with all already-registered my-vars. - if (var != null && WeakRefRegistry.weakRefsExist()) { - liveCounts().merge(var, 1, Integer::sum); - MortalList.invalidateLiveRootSnapshot(); + if (var != null) { + registeredCounts().merge(var, 1, Integer::sum); } - } - - /** - * Phase D-W2b (perf): one-time backfill of the live-count map with - * all currently registered my-vars. Called by - * {@link WeakRefRegistry#registerWeakRef} the first time - * {@code weakRefsExist} flips to true. Without this, my-vars - * declared before the first {@code weaken()} would never be - * inserted into {@code liveCounts} and the walker would miss them. - */ - public static synchronized void snapshotStackToLiveCounts() { - IdentityHashMap liveCounts = liveCounts(); - for (Object var : stack()) { - if (var != null) { - liveCounts.merge(var, 1, Integer::sum); - } + if (var instanceof RuntimeScalar scalar) scalar.refreshUntrackedReferenceOwner(); + if (var instanceof RuntimeBase base) { + RuntimeCode.noteMyVarRegistered(base); } - MortalList.invalidateLiveRootSnapshot(); } /** * Called by emitted bytecode at normal block scope exit AFTER * {@code scopeExitCleanup} has run. Removes the most recent entry - * matching {@code var} (by object identity) so the static stack no - * longer holds the scalar alive. Without this, block-scoped - * my-variables stayed registered until the enclosing subroutine - * returned, keeping their RuntimeBase targets alive past their - * Perl-level scope and causing leaks visible through the - * reachability walker. + * matching {@code var} (by object identity) so scope-exit and owner-slot + * checks stop treating that lexical cell as live. Without this, + * block-scoped my-variables stayed registered until the enclosing + * subroutine returned. *

    * Paired with {@link #register(Object)} — every register has a * matching unregister on normal exit, and a matching @@ -163,6 +105,15 @@ public static synchronized void snapshotStackToLiveCounts() { * @param var the RuntimeScalar/Array/Hash previously registered */ public static void unregister(Object var) { + unregister(var, true); + } + + /** Remove a registration after the exact named lexical owner was unbound. */ + public static void unregisterAfterActiveLexicalUnbind(Object var) { + unregister(var, false); + } + + private static void unregister(Object var, boolean releaseActiveOwner) { if (var == null) return; // Block-scoped my-vars pop in reverse declaration order, so // scan from the top of the stack for a fast amortized match. @@ -171,7 +122,6 @@ public static void unregister(Object var) { if (stack.get(i) == var) { stack.remove(i); decRegisteredCount(var); - decLiveCount(var); if (var instanceof RuntimeBase base && (base instanceof RuntimeArray || base instanceof RuntimeHash) && !isRegistered(var)) { @@ -180,6 +130,13 @@ public static void unregister(Object var) { // callers that release a lexical slot directly. base.localBindingExists = false; } + if (releaseActiveOwner) { + releaseActiveAggregateOwnerAfterCleanup(var); + } else if (var instanceof RuntimeBase base + && !MyVarCleanupStack.isRegistered(base)) { + RuntimeCode.releaseAllActiveLexicalOwners(base); + recheckProxyValueOwnersAfterLexicalRelease(base); + } noteVarLeftScope(var); return; } @@ -190,24 +147,22 @@ public static void unregister(Object var) { * Replace the Java object backing a live lexical slot without ending the * lexical's Perl scope. The interpreter uses replace-on-assignment for * ordinary scalars, so leaving the old object on this stack would make - * reachability analysis overlook references stored in the new slot. + * lifecycle checks observe the stale cell instead of the current slot. */ public static void replace(Object oldVar, Object newVar) { if (oldVar == null || newVar == null || oldVar == newVar) return; ArrayList stack = stack(); IdentityHashMap registeredCounts = registeredCounts(); - IdentityHashMap liveCounts = liveCounts(); for (int i = stack.size() - 1; i >= 0; i--) { if (stack.get(i) == oldVar) { stack.set(i, newVar); decCount(registeredCounts, oldVar); registeredCounts.merge(newVar, 1, Integer::sum); - Integer count = liveCounts.get(oldVar); - if (count != null) { - if (count <= 1) liveCounts.remove(oldVar); - else liveCounts.put(oldVar, count - 1); - liveCounts.merge(newVar, 1, Integer::sum); - MortalList.invalidateLiveRootSnapshot(); + if (oldVar instanceof RuntimeScalar scalar) { + scalar.refreshUntrackedReferenceOwner(); + } + if (newVar instanceof RuntimeScalar scalar) { + scalar.refreshUntrackedReferenceOwner(); } return; } @@ -225,20 +180,11 @@ private static void decCount(IdentityHashMap counts, Object var else counts.put(var, count - 1); } - private static void decLiveCount(Object var) { - IdentityHashMap liveCounts = liveCounts(); - Integer c = liveCounts.get(var); - if (c == null) return; - if (c <= 1) liveCounts.remove(var); - else liveCounts.put(var, c - 1); - MortalList.invalidateLiveRootSnapshot(); - } - private static void noteVarLeftScope(Object var) { - if (var instanceof RuntimeBase base - && (base instanceof RuntimeArray || base instanceof RuntimeHash) - && WeakRefRegistry.weakRefsExist()) { - MortalList.requestWeakSweepsForDestroyedContainer(base); + if (var instanceof RuntimeScalar scalar) { + PerlOwnerSlot valueOwner = scalar.untrackedReferenceOwnerSlot(); + RuntimeBase referent = valueOwner == null ? null : valueOwner.referent(); + scalar.finalizeUntrackedValueAfterScopeExit(referent); } if (var instanceof RuntimeBase base && WeakRefRegistry.hasWeakRefsTo(base)) { requestWeakCleanupAfterScopeExit(base); @@ -252,15 +198,11 @@ private static void noteVarLeftScope(Object var) { private static void requestWeakCleanupAfterScopeExit(RuntimeBase base) { MortalList.finalizeClearedAggregateOwnerAfterScopeExit(base); - // Selective owner records can outlive the Perl lexical that created - // them when a closure graph is being torn down. Recheck weak refs at - // the scope boundary so the reachability walker can reconcile those - // records with the remaining Perl-visible roots. - MortalList.requestImmediateWeakSweep(); } /** - * Called on exception in {@code RuntimeCode.apply()}. + * Called when a Perl frame exits before its ordinary scope cleanup runs. + * This includes exception propagation and non-local returns. * Runs {@link MortalList#evalExceptionScopeCleanup(Object)} for all * registered-but-not-yet-cleaned variables since the mark, in LIFO order. *

    @@ -283,13 +225,37 @@ private static void unwindTo(int mark, ArrayList stack) { Object var = stack.removeLast(); if (var != null) { decRegisteredCount(var); - decLiveCount(var); MortalList.evalExceptionScopeCleanup(var); + releaseActiveAggregateOwnerAfterCleanup(var); noteVarLeftScope(var); } } } + private static void releaseActiveAggregateOwnerAfterCleanup(Object var) { + if (!(var instanceof RuntimeBase base) + || (!(base instanceof RuntimeArray) && !(base instanceof RuntimeHash) + && !(base instanceof RuntimeScalar scalar + && scalar.referencedByScalarReference))) return; + // Multiple lexical names may alias the same cell. Keep its pad owners + // while any such lexical registration remains; the last registration + // retires all pad bindings left by normal or exceptional scope exit. + if (!MyVarCleanupStack.isRegistered(base)) { + RuntimeCode.releaseAllActiveLexicalOwners(base); + recheckProxyValueOwnersAfterLexicalRelease(base); + } + } + + private static void recheckProxyValueOwnersAfterLexicalRelease(RuntimeBase base) { + if (base instanceof RuntimeArray || base instanceof RuntimeHash) { + // Scope cleanup runs before the stack entry is removed, so a + // proxy-backed scalar can still see this aggregate as live during + // that first pass. Recheck after registration and active lexical + // owners have both been retired. + base.recheckProxyValueOwnersIfUnowned(); + } + } + /** * Called on normal exit in {@code RuntimeCode.apply()}. * Discards registrations without running cleanup (normal scope-exit @@ -311,7 +277,27 @@ private static void popMark(int mark, ArrayList stack) { Object var = stack.removeLast(); if (var != null) { decRegisteredCount(var); - decLiveCount(var); + if (var instanceof RuntimeScalar scalar && scalar.refCountOwned + && scalar.countedOwnerSlot() != null + && scalar.countedOwnerSlot().kind() == PerlOwnerSlot.Kind.ARRAY_ELEMENT + && scalar.containerOwner instanceof RuntimeArray args + && scalar.countedOwnerSlot().countedAggregateOwner() == args + && !RuntimeCode.snapshotArgsStack().contains(args) + && !args.hasCurrentPerlStorageOwner() + && !scalar.hasStorageOwnerForVoidDiscard() + && !RuntimeCode.isCurrentArgumentAlias(scalar) + && !scalar.hasActiveMortalReturnValueOwner()) { + // A value-cell edge transported through an exited + // temporary @_ array can outlive both that array and its + // lexical registration. Retire only that exact edge here. + MortalList.deferDecrementIfTracked(scalar); + } + if (var instanceof RuntimeBase base + && (base instanceof RuntimeArray || base instanceof RuntimeHash) + && !isRegistered(var)) { + base.localBindingExists = false; + } + releaseActiveAggregateOwnerAfterCleanup(var); noteVarLeftScope(var); } } @@ -331,10 +317,46 @@ public static void releaseOrTransferSocketOwnersOnReturn(int mark, RuntimeBase r } } - /** Acquire IO ownership for every currently-live lexical alias of a glob. */ + /** + * Acquire IO ownership for current scalar-cell aliases and registered + * lexical aliases of a glob after its IO slot becomes live. + * + *

    The glob's owner ledger finds scalar and aggregate storage. The cleanup + * stack supplements it for registered lexicals whose referent has not + * entered selective counting.

    + */ public static void retainLiveIoGlobOwners(RuntimeGlob glob) { if (glob == null) return; IdentityHashMap seen = new IdentityHashMap<>(); + for (PerlOwnerSlot slot : glob.ownerSlotSnapshot()) { + RuntimeScalar scalar = null; + if (slot.kind() == PerlOwnerSlot.Kind.UNTRACKED_REFERENCE) { + RuntimeScalar candidate = slot.untrackedScalarOwner(); + if (candidate != null + && candidate.untrackedReferenceOwnerSlot() == slot + && candidate.value == glob + && candidate.type == RuntimeScalarType.GLOBREFERENCE + && !WeakRefRegistry.isweak(candidate)) { + scalar = candidate; + } + } else if (PerlOwnerSlot.isCountedKind(slot.kind())) { + RuntimeScalar candidate = slot.countedScalarOwner(); + if (candidate != null + && candidate.value == glob + && candidate.type == RuntimeScalarType.GLOBREFERENCE + && !WeakRefRegistry.isweak(candidate)) { + boolean current = switch (slot.kind()) { + case ARRAY_ELEMENT, HASH_ELEMENT -> + candidate.isCurrentAggregateElementOwner(glob, slot); + default -> candidate.isCurrentCountedScalarOwner(glob, slot); + }; + if (current) scalar = candidate; + } + } + if (scalar != null && seen.put(scalar, Boolean.TRUE) == null) { + RuntimeScalar.retainUnstashedIoForDurableSlot(scalar); + } + } for (Object var : stack()) { if (var instanceof RuntimeScalar scalar && scalar.type == RuntimeScalarType.GLOBREFERENCE @@ -345,6 +367,12 @@ public static void retainLiveIoGlobOwners(RuntimeGlob glob) { } } + /** Acquire leases for current aliases and the explicit destination scalar. */ + public static void retainLiveIoGlobOwners(RuntimeGlob glob, RuntimeScalar handle) { + retainLiveIoGlobOwners(glob); + RuntimeScalar.retainUnstashedIoForDurableSlot(handle); + } + /** * Count every currently-live lexical alias when an open glob is blessed. * Open handles can enter as {@code GLOB} scalars, which ordinary reference @@ -360,14 +388,12 @@ public static void retainBlessedGlobAliases(RuntimeGlob glob, RuntimeBase refere && (scalar.type == RuntimeScalarType.GLOB || scalar.type == RuntimeScalarType.GLOBREFERENCE) && scalar.value == glob + && !WeakRefRegistry.isweak(scalar) && !scalar.refCountOwned && seen.put(scalar, Boolean.TRUE) == null) { - scalar.refCountOwned = true; - referent.recordOwner(scalar, "blessed glob lexical alias"); - referent.recordActiveOwner(scalar); - referent.traceRefCount(+1, "MyVarCleanupStack.retainBlessedGlobAliases"); - referent.refCount++; - referent.hadCountedReference = true; + RuntimeScalar.acquireCountedOwnerForCurrentValue( + scalar, referent, scalar.countedOwnerKind(), + "MyVarCleanupStack.retainBlessedGlobAliases (lexical alias)"); } } for (RuntimeScalar scalar : GlobalVariable.scalarSlots().values()) { @@ -375,14 +401,12 @@ public static void retainBlessedGlobAliases(RuntimeGlob glob, RuntimeBase refere && (scalar.type == RuntimeScalarType.GLOB || scalar.type == RuntimeScalarType.GLOBREFERENCE) && scalar.value == glob + && !WeakRefRegistry.isweak(scalar) && !scalar.refCountOwned && seen.put(scalar, Boolean.TRUE) == null) { - scalar.refCountOwned = true; - referent.recordOwner(scalar, "blessed glob package alias"); - referent.recordActiveOwner(scalar); - referent.traceRefCount(+1, "MyVarCleanupStack.retainBlessedGlobAliases"); - referent.refCount++; - referent.hadCountedReference = true; + RuntimeScalar.acquireCountedOwnerForCurrentValue( + scalar, referent, scalar.countedOwnerKind(), + "MyVarCleanupStack.retainBlessedGlobAliases (package alias)"); } } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/PerlOwnerSlot.java b/src/main/java/org/perlonjava/runtime/runtimetypes/PerlOwnerSlot.java index 5cf83c1ded..97e5d2b2a8 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/PerlOwnerSlot.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/PerlOwnerSlot.java @@ -1,11 +1,16 @@ package org.perlonjava.runtime.runtimetypes; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; /** - * Identity for one Perl strong-owner slot. + * Identity for one Perl strong-owner slot or explicitly tracked runtime + * compatibility hold. * *

    The current runtime still uses selective {@link RuntimeBase#refCount} * transitions as its lifecycle bridge. This object records the slot identity @@ -17,17 +22,107 @@ public final class PerlOwnerSlot { private static final AtomicLong NEXT_ID = new AtomicLong(); public enum Kind { - CLOSURE_PAD + CLOSURE_PAD, + SCALAR_CAPTURE, + SCALAR_CELL, + CODE_SLOT, + /** Compiled CODE optree retaining one backslash-addressable pad constant. */ + CODE_PAD_CONSTANT, + /** Executable regex callback retaining its closure CODE object. */ + REGEX_CALLBACK, + /** PerlIO::via layer retaining the object returned by PUSHED. */ + IO_VIA_LAYER, + /** Tied-hash iterator retaining a key between FIRSTKEY/NEXTKEY calls. */ + TIED_HASH_ITERATOR_KEY, + ARRAY_ELEMENT, + /** RuntimeArray refalias binding retaining one scalar cell. */ + ARRAY_ALIAS_CELL, + /** RuntimeHash refalias binding retaining one scalar cell. */ + HASH_ALIAS_CELL, + HASH_ELEMENT, + ARGUMENT_VALUE, + /** Argument frame retaining the aggregate that contains an aliased lvalue. */ + ARGUMENT_CONTAINER, + ARGUMENT_ALIAS, + RETURN_VALUE, + ACTIVE_CODE, + TIE_HANDLER, + /** Tied-element magic retained only for an active argument alias. */ + ARGUMENT_TIE_HANDLER, + /** Package scalar table entry owning one scalar cell. */ + PACKAGE_SCALAR_SLOT, + /** Package array or hash table entry owning one aggregate. */ + PACKAGE_AGGREGATE_SLOT, + /** Named IO stash entry owning one typeglob. */ + PACKAGE_GLOB_SLOT, + /** Detached typeglob slot retaining one scalar, aggregate, or CODE cell. */ + GLOB_COMPONENT_SLOT, + /** RuntimeStash field retaining a deferred namespace move. */ + STASH_NAMESPACE_MOVE, + /** Scalar value retaining a detached typeglob snapshot. */ + GLOB_VALUE, + /** Active lexical frame or top-level pad entry owning a scalar cell or aggregate. */ + ACTIVE_LEXICAL, + /** Strong value held by a lexical register in a suspended interpreter frame. */ + SUSPENDED_FRAME, + /** Strong container edge whose referent is not on the legacy refcount bridge. */ + UNTRACKED_REFERENCE, + /** Scalar slot retaining an anonymous IO glob's live resource. */ + IO_RESOURCE_HOLDER, + /** Runtime snapshot root retained while a thread or graph snapshot is built. */ + TEMPORARY_ROOT, + /** A Perl temporary expression value retained through its temp scope. */ + EXPRESSION_VALUE, + /** Persistent scalar or aggregate state binding retained by a CODE object. */ + CODE_STATE, + /** Scalar wrapper retaining the current contents of a referenced scalar cell. */ + SCALAR_REFERENCE_CONTENTS; + + /** Compatibility name used by temporary-root lifecycle tests. */ + public static final Kind EXPRESSION_TEMPORARY_ROOT = EXPRESSION_VALUE; } - private final Kind kind; + private Kind kind; private final RuntimeScalar padCell; private final long identity = NEXT_ID.incrementAndGet(); private RuntimeBase referent; + /** Scalar cell that owns an untracked value edge; weak to avoid retaining its source. */ + private WeakReference untrackedScalarOwner; + /** Whether this slot contributes to its referent's transient-owner fast-path count. */ + private boolean transientUntrackedOwnerCounted; + /** Weak back-reference to the scalar implementing a counted cell owner. */ + private WeakReference countedScalarOwner; + /** Aggregate storage that owns an ARRAY_ELEMENT or HASH_ELEMENT edge. */ + private WeakReference countedAggregateOwner; + /** Scalar cell currently carrying a non-counted native resource identity. */ + private WeakReference resourceScalarOwner; + /** Last carrier identity for diagnostics, retained after its wrapper is gone. */ + private int resourceScalarIdentity; + /** CODE object that owns a closure-pad identity; weak to avoid a metadata cycle. */ + private WeakReference captureOwner; + /** Referenced scalar cell whose contents this wrapper keeps alive. */ + private WeakReference scalarReferenceCell; + /** Scalar wrapper that currently carries this scalar-reference identity. */ + private WeakReference scalarContentsOwner; + /** Lexical cell whose current value is retained by a suspended frame. */ + private WeakReference suspendedScalarOwner; + /** Weak provenance for a detached glob's component edge. */ + private WeakReference globComponentOwner; + /** Array whose refalias slot owns a scalar-cell identity. */ + private WeakReference arrayAliasOwner; + /** Hash whose refalias slot owns a scalar-cell identity. */ + private WeakReference hashAliasOwner; private PerlRuntime ownerRuntime; private LifecycleRuntimeState ownerRuntimeState; + private boolean registeredInOwnerLedger; + /** Aggregate parent whose loss can invalidate an untracked proxy value edge. */ + private RuntimeBase proxyValueParent; + /** True only for the direct, counted hold created for one method invocant. */ + private boolean methodInvocantOwner; + /** Whether an IO_VIA_LAYER identity contributes its paired direct count. */ + private boolean countedNativeOwner; private int legacyCaptureCount; - private volatile boolean nativeCaptureOwner; + private volatile boolean nativeOwner; private long nextReleaseSequence; /** Provenance token carried with one queued legacy decrement. */ @@ -36,11 +131,39 @@ public static final class PendingRelease { private final long sequence; private final Kind kind; private final AtomicBoolean completed = new AtomicBoolean(); + private final LifecycleRuntimeState retainedState; + private final RuntimeBase retainedReferent; + private final PerlOwnerSlot releaseAtCompletion; + private final PerlOwnerSlot resourceReleaseAtCompletion; private PendingRelease(long ownerSlotIdentity, long sequence, Kind kind) { + this(ownerSlotIdentity, sequence, kind, null, null); + } + + private PendingRelease(long ownerSlotIdentity, long sequence, Kind kind, + RuntimeBase referent) { + this(ownerSlotIdentity, sequence, kind, referent, null); + } + + private PendingRelease(long ownerSlotIdentity, long sequence, Kind kind, + RuntimeBase referent, PerlOwnerSlot releaseAtCompletion) { + this(ownerSlotIdentity, sequence, kind, referent, releaseAtCompletion, null); + } + + private PendingRelease(long ownerSlotIdentity, long sequence, Kind kind, + RuntimeBase referent, PerlOwnerSlot releaseAtCompletion, + PerlOwnerSlot resourceReleaseAtCompletion) { this.ownerSlotIdentity = ownerSlotIdentity; this.sequence = sequence; this.kind = kind; + this.releaseAtCompletion = releaseAtCompletion; + this.resourceReleaseAtCompletion = resourceReleaseAtCompletion; + PerlRuntime runtime = PerlRuntime.currentOrNull(); + boolean transfer = kind == Kind.ARGUMENT_VALUE || kind == Kind.RETURN_VALUE + || kind == Kind.CODE_SLOT; + retainedReferent = transfer ? referent : null; + retainedState = retainedReferent == null || runtime == null + ? null : runtime.retainOwnerSlotReferent(retainedReferent); } public long ownerSlotIdentity() { @@ -60,7 +183,13 @@ public boolean isCompleted() { } void complete() { - completed.set(true); + if (completed.compareAndSet(false, true)) { + if (releaseAtCompletion != null) releaseAtCompletion.release(); + if (resourceReleaseAtCompletion != null) { + RuntimeScalar.releaseDeferredIoOwner(resourceReleaseAtCompletion); + } + PerlRuntime.releaseOwnerSlotReferent(retainedState, retainedReferent); + } } } @@ -81,18 +210,233 @@ public long identity() { return identity; } + /** Sequence the next deferred release of this stable storage identity will use. */ + synchronized long nextReleaseSequenceValue() { + return nextReleaseSequence + 1; + } + RuntimeScalar padCell() { return padCell; } + synchronized void associateUntrackedScalarOwner(RuntimeScalar scalar) { + if (kind != Kind.UNTRACKED_REFERENCE) { + throw new IllegalStateException("scalar owner association requires an untracked-reference slot"); + } + untrackedScalarOwner = scalar == null ? null : new WeakReference<>(scalar); + refreshTransientUntrackedOwnerClassification(); + } + + synchronized void associateUntrackedProxyValueParent(RuntimeBase parent) { + if (kind != Kind.UNTRACKED_REFERENCE) { + throw new IllegalStateException("proxy parent association requires an untracked-reference slot"); + } + if (proxyValueParent == parent) return; + RuntimeBase nextParent = parent != null && parent.addProxyValueOwnerSlot(this) + ? parent : null; + RuntimeBase previousParent = proxyValueParent; + proxyValueParent = nextParent; + if (previousParent != null) previousParent.removeProxyValueOwnerSlot(this); + } + + /** Reclassify the live edge when its scalar changes transient ownership state. */ + synchronized void refreshTransientUntrackedOwnerClassification() { + RuntimeBase current = referent; + RuntimeScalar scalar = untrackedScalarOwner == null ? null : untrackedScalarOwner.get(); + PerlRuntime runtime = PerlRuntime.currentOrNull(); + boolean weak = runtime != null && scalar != null && WeakRefRegistry.isweak(scalar); + boolean shouldCount = kind == Kind.UNTRACKED_REFERENCE + && registeredInOwnerLedger && current != null && scalar != null + && scalar.untrackedReferenceOwnerSlot() == this + && scalar.isTransientArgumentValueOwner() + && !weak + && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 + && scalar.value == current; + if (shouldCount == transientUntrackedOwnerCounted) return; + transientUntrackedOwnerCounted = shouldCount; + current.adjustTransientUntrackedReferenceOwnerCount(shouldCount ? 1 : -1); + } + + synchronized RuntimeScalar untrackedScalarOwner() { + return untrackedScalarOwner == null ? null : untrackedScalarOwner.get(); + } + + synchronized boolean hasUntrackedScalarOwnerAssociation() { + return untrackedScalarOwner != null; + } + boolean isNativeCaptureOwner() { - return nativeCaptureOwner; + return kind == Kind.CLOSURE_PAD && nativeOwner; + } + + /** True while this active slot is counted directly by the semantic owner ledger. */ + public boolean isNativeOwner() { + return nativeOwner && referent != null; + } + + /** Mark a direct count paired with a native owner identity. */ + public synchronized void markCountedNativeOwner() { + if ((kind != Kind.IO_VIA_LAYER && kind != Kind.REGEX_CALLBACK + && kind != Kind.TIED_HASH_ITERATOR_KEY + && kind != Kind.EXPRESSION_VALUE) + || referent == null || !nativeOwner + || countedNativeOwner) { + throw new IllegalStateException("counted native owner requires an active supported slot"); + } + countedNativeOwner = true; + } + + /** Whether this active native slot contributes one direct count. */ + public synchronized boolean isCountedNativeOwner() { + return (kind == Kind.IO_VIA_LAYER || kind == Kind.REGEX_CALLBACK + || kind == Kind.TIED_HASH_ITERATOR_KEY + || kind == Kind.EXPRESSION_VALUE) + && referent != null && countedNativeOwner; + } + + /** True if this slot uses native-ledger release semantics, including after release. */ + public boolean usesNativeOwnerLedger() { + return nativeOwner; } public synchronized RuntimeBase referent() { return referent; } + /** Source cell for a suspended-frame owner, if that register is scalar-backed. */ + public synchronized RuntimeScalar suspendedScalarOwner() { + return suspendedScalarOwner == null ? null : suspendedScalarOwner.get(); + } + + synchronized void associateSuspendedScalarOwner(RuntimeScalar owner) { + if (kind != Kind.SUSPENDED_FRAME) { + throw new IllegalStateException("scalar association requires a suspended-frame slot"); + } + suspendedScalarOwner = owner == null ? null : new WeakReference<>(owner); + } + + /** Scalar cell implementing this counted edge, when it has one. */ + public synchronized RuntimeScalar countedScalarOwner() { + return countedScalarOwner == null ? null : countedScalarOwner.get(); + } + + synchronized RuntimeBase countedAggregateOwner() { + return countedAggregateOwner == null ? null : countedAggregateOwner.get(); + } + + synchronized void associateCountedAggregateOwner(RuntimeBase owner) { + boolean matchingKind = kind == Kind.ARRAY_ELEMENT && owner instanceof RuntimeArray + || kind == Kind.HASH_ELEMENT && owner instanceof RuntimeHash; + if (!isCountedKind(kind) || (owner != null && !matchingKind)) { + throw new IllegalStateException( + "aggregate owner association requires a matching element slot"); + } + countedAggregateOwner = owner == null ? null : new WeakReference<>(owner); + } + + synchronized void associateCountedAggregateOwnerIfAbsent(RuntimeBase owner) { + boolean matchingKind = kind == Kind.ARRAY_ELEMENT && owner instanceof RuntimeArray + || kind == Kind.HASH_ELEMENT && owner instanceof RuntimeHash; + if (!isCountedKind(kind) || !matchingKind) { + throw new IllegalStateException( + "aggregate owner association requires a matching element slot"); + } + if (countedAggregateOwner == null || countedAggregateOwner.get() == null) { + countedAggregateOwner = new WeakReference<>(owner); + } + } + + synchronized void associateResourceScalarOwner(RuntimeScalar scalar) { + if (kind != Kind.IO_RESOURCE_HOLDER) { + throw new IllegalStateException("resource scalar association requires an IO holder slot"); + } + resourceScalarOwner = scalar == null ? null : new WeakReference<>(scalar); + if (scalar != null) resourceScalarIdentity = System.identityHashCode(scalar); + } + + synchronized RuntimeScalar resourceScalarOwner() { + return resourceScalarOwner == null ? null : resourceScalarOwner.get(); + } + + synchronized int resourceScalarIdentity() { + return resourceScalarIdentity; + } + + synchronized RuntimeScalar scalarReferenceCell() { + return scalarReferenceCell == null ? null : scalarReferenceCell.get(); + } + + synchronized RuntimeScalar scalarContentsOwner() { + return scalarContentsOwner == null ? null : scalarContentsOwner.get(); + } + + synchronized void transferScalarReferenceContentsOwner(RuntimeScalar owner) { + if (kind != Kind.SCALAR_REFERENCE_CONTENTS) { + throw new IllegalStateException( + "scalar-reference owner transfer requires a scalar-contents slot"); + } + if (referent == null) { + throw new IllegalStateException("cannot transfer an inactive scalar-contents owner"); + } + scalarContentsOwner = owner == null ? null : new WeakReference<>(owner); + } + + synchronized void associateCountedScalarOwner(RuntimeScalar scalar) { + if (!isCountedKind(kind)) { + throw new IllegalStateException("scalar owner association requires a counted slot"); + } + countedScalarOwner = scalar == null ? null : new WeakReference<>(scalar); + } + + /** Acquire an ARGUMENT_VALUE identity for a direct method-invocant hold. */ + synchronized void acquireMethodInvocantIdentity(RuntimeBase target) { + if (kind != Kind.ARGUMENT_VALUE || referent != null || nativeOwner + || legacyCaptureCount != 0 || methodInvocantOwner) { + throw new IllegalStateException("method-invocant slot is not available"); + } + Objects.requireNonNull(target, "target"); + if (target.isPerlDestroyed()) { + throw new IllegalStateException("cannot hold a destroyed method invocant"); + } + methodInvocantOwner = true; + transferWithoutRuntimeRoot(target, false); + } + + /** Acquire the method-invocant slot and its paired selective count together. */ + public synchronized void acquireCountedMethodInvocantOwner( + RuntimeBase target, String acquisitionSite) { + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(acquisitionSite, "acquisitionSite"); + if (!target.isRefCountTracked() || target.refCount == Integer.MAX_VALUE) { + throw new IllegalStateException( + "method-invocant acquisition requires an available tracked count"); + } + acquireMethodInvocantIdentity(target); + target.acquireTrackedOwnerCount(acquisitionSite); + } + + /** Acquire a bless-created temporary edge together with its selective count. */ + public synchronized void acquireCountedTemporaryOwner( + RuntimeBase target, String acquisitionSite) { + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(acquisitionSite, "acquisitionSite"); + if (kind != Kind.SCALAR_CELL || referent != null || nativeOwner + || legacyCaptureCount != 0 || methodInvocantOwner) { + throw new IllegalStateException("temporary counted-owner slot is not available"); + } + if (!target.isRefCountTracked() || target.refCount == Integer.MAX_VALUE) { + throw new IllegalStateException( + "temporary-owner acquisition requires an available tracked count"); + } + acquireCountedIdentity(target); + target.acquireTrackedOwnerCount(acquisitionSite); + } + + /** Whether this slot still represents its direct method-invocant hold. */ + synchronized boolean isMethodInvocantOwner(RuntimeBase target) { + return methodInvocantOwner && kind == Kind.ARGUMENT_VALUE && referent == target; + } + public synchronized boolean isActive() { return referent != null; } @@ -104,7 +448,7 @@ public synchronized int legacyCaptureCount() { /** Acquire one closure-pad referent count through the legacy bridge. */ public synchronized void acquireLegacyCapture(RuntimeBase target) { Objects.requireNonNull(target, "target"); - if (target.refCount < 0) { + if (!target.isRefCountTracked()) { throw new IllegalStateException("closure capture bridge requires a tracked referent"); } if (target.refCount == Integer.MAX_VALUE @@ -117,23 +461,849 @@ public synchronized void acquireLegacyCapture(RuntimeBase target) { } transferTo(target); } - target.traceRefCount(+1, "RuntimeScalar.retainClosureCaptureReferent"); - target.refCount++; - target.hadCountedReference = true; + target.acquireTrackedOwnerCount("RuntimeScalar.retainClosureCaptureReferent"); target.acquireTransientTraceOwner("closure capture", "RuntimeScalar.closureCapture"); legacyCaptureCount++; } /** Acquire a captured aggregate pad as an explicit owner slot. */ public synchronized void acquireCapture(RuntimeBase target) { + acquireCapture(target, null); + } + + /** Acquire an aggregate pad capture and record the CODE owner of this slot. */ + public synchronized void acquireCapture(RuntimeBase target, RuntimeCode owner) { + if (kind != Kind.CLOSURE_PAD) { + throw new IllegalStateException("capture acquisition requires a closure-pad slot"); + } + acquireNativeOwner(target); + captureOwner = owner == null ? null : new WeakReference<>(owner); + } + + /** Acquire this slot as one semantic Perl owner, without touching refCount. */ + public synchronized void acquireNativeOwner(RuntimeBase target) { Objects.requireNonNull(target, "target"); - if (target.refCount == Integer.MIN_VALUE) { - throw new IllegalStateException("cannot capture a destroyed referent"); + if (target.isPerlDestroyed()) { + throw new IllegalStateException("cannot own a destroyed referent"); + } + if (legacyCaptureCount != 0) { + throw new IllegalStateException("cannot migrate a slot with pending legacy releases"); } - nativeCaptureOwner = true; + nativeOwner = true; transferTo(target); } + /** + * Acquire a native owner and its selective count as one slot transition. + * + *

    Some runtime-owned Perl edges participate in the selective count while + * others are represented only by the owner identity. This operation keeps + * that distinction at the producer: a tracked referent gets exactly one + * count paired with this slot; an untracked referent gets only the slot.

    + * + * @return whether the referent's selective count was incremented + */ + public synchronized boolean acquireCountedNativeOwner( + RuntimeBase target, String acquisitionSite) { + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(acquisitionSite, "acquisitionSite"); + if (kind != Kind.IO_VIA_LAYER && kind != Kind.REGEX_CALLBACK + && kind != Kind.TIED_HASH_ITERATOR_KEY + && kind != Kind.EXPRESSION_VALUE) { + throw new IllegalStateException("unsupported counted native owner slot: " + kind); + } + if (referent != null || nativeOwner || countedNativeOwner) { + throw new IllegalStateException("counted native acquisition requires an empty slot"); + } + if (target.isPerlDestroyed()) { + throw new IllegalStateException("cannot own a destroyed referent"); + } + boolean counted = target.isRefCountTracked(); + if (counted && target.refCount == Integer.MAX_VALUE) { + throw new IllegalStateException("native owner count overflow"); + } + + try { + acquireNativeOwner(target); + if (!counted) return false; + target.acquireTrackedOwnerCount(acquisitionSite); + countedNativeOwner = true; + return true; + } catch (RuntimeException | Error failure) { + if (referent == target) { + if (countedNativeOwner) { + target.releaseTrackedOwnerCount(acquisitionSite + " (rollback)"); + countedNativeOwner = false; + } + release(); + } + throw failure; + } + } + + /** Release a native owner and its paired count through normal lifecycle cleanup. */ + public void releaseNativeOwner() { + RuntimeBase target; + boolean counted; + synchronized (this) { + if (referent == null) return; + if (!nativeOwner) { + throw new IllegalStateException("native release requires a native owner slot"); + } + target = referent; + counted = countedNativeOwner; + } + if (counted) MortalList.releaseCountedNativeOwner(target, this); + else release(); + } + + /** Retire a regex callback count without dispatching referent destruction. */ + public void releaseRegexCallbackOwner(String releaseSite) { + RuntimeBase target; + synchronized (this) { + if (referent == null) return; + if (kind != Kind.REGEX_CALLBACK || !nativeOwner) { + throw new IllegalStateException( + "regex callback release requires a regex callback owner slot"); + } + target = referent; + } + MortalList.releaseRegexCallbackOwner(target, this, releaseSite); + } + + /** Record one package scalar table entry as an identity-owned scalar cell. */ + synchronized void acquirePackageScalarIdentity(RuntimeScalar target) { + if (kind != Kind.PACKAGE_SCALAR_SLOT) { + throw new IllegalStateException("package scalar acquisition requires a package-slot identity"); + } + Objects.requireNonNull(target, "target"); + if (legacyCaptureCount != 0) { + throw new IllegalStateException("package scalar slot has pending legacy releases"); + } + transferWithoutRuntimeRoot(target, true); + } + + /** Record one compiled CODE optree's strong reference to a pad constant. */ + synchronized void acquireCodePadConstantIdentity(RuntimeBase target) { + if (kind != Kind.CODE_PAD_CONSTANT) { + throw new IllegalStateException("pad-constant acquisition requires a CODE-pad slot"); + } + Objects.requireNonNull(target, "target"); + if (target.isPerlDestroyed()) { + throw new IllegalStateException("cannot own a destroyed pad constant"); + } + if (legacyCaptureCount != 0) { + throw new IllegalStateException("pad-constant slot has pending legacy releases"); + } + transferWithoutRuntimeRoot(target, false); + } + + /** Record one package array/hash table entry as an identity-owned aggregate root. */ + synchronized void acquirePackageAggregateIdentity(RuntimeBase target) { + if (kind != Kind.PACKAGE_AGGREGATE_SLOT) { + throw new IllegalStateException("package aggregate acquisition requires an aggregate-slot identity"); + } + Objects.requireNonNull(target, "target"); + if (legacyCaptureCount != 0) { + throw new IllegalStateException("package aggregate slot has pending legacy releases"); + } + transferWithoutRuntimeRoot(target, true); + } + + /** Record one persistent CODE state binding as an identity-owned Perl edge. */ + synchronized void acquireCodeStateIdentity(RuntimeBase target, RuntimeCode owner) { + if (kind != Kind.CODE_STATE) { + throw new IllegalStateException("CODE state acquisition requires a CODE-state identity"); + } + Objects.requireNonNull(target, "target"); + if (legacyCaptureCount != 0) { + throw new IllegalStateException("CODE state slot has pending legacy releases"); + } + transferWithoutRuntimeRoot(target, true); + captureOwner = owner == null ? null : new WeakReference<>(owner); + } + + /** Record one named IO stash entry as an identity-owned typeglob root. */ + synchronized void acquirePackageGlobIdentity(RuntimeGlob target) { + if (kind != Kind.PACKAGE_GLOB_SLOT) { + throw new IllegalStateException("package glob acquisition requires a glob-slot identity"); + } + Objects.requireNonNull(target, "target"); + if (legacyCaptureCount != 0) { + throw new IllegalStateException("package glob slot has pending legacy releases"); + } + transferWithoutRuntimeRoot(target, true); + } + + /** Record one detached typeglob's strong edge to a component slot. */ + synchronized void acquireGlobComponentIdentity(RuntimeGlob owner, RuntimeBase target) { + if (kind != Kind.GLOB_COMPONENT_SLOT) { + throw new IllegalStateException("glob component acquisition requires a glob-component slot"); + } + Objects.requireNonNull(owner, "owner"); + Objects.requireNonNull(target, "target"); + if (legacyCaptureCount != 0) { + throw new IllegalStateException("glob component slot has pending legacy releases"); + } + globComponentOwner = new WeakReference<>(owner); + transferWithoutRuntimeRoot(target, false); + } + + synchronized RuntimeGlob globComponentOwner() { + return globComponentOwner == null ? null : globComponentOwner.get(); + } + + /** Record a stash field's strong edge to its deferred namespace move. */ + synchronized void acquireStashNamespaceMoveIdentity(RuntimeGlob target) { + if (kind != Kind.STASH_NAMESPACE_MOVE) { + throw new IllegalStateException("stash namespace-move acquisition requires a stash-move slot"); + } + Objects.requireNonNull(target, "target"); + if (legacyCaptureCount != 0) { + throw new IllegalStateException("stash namespace-move slot has pending legacy releases"); + } + transferWithoutRuntimeRoot(target, true); + } + + /** Record one scalar value's edge to a detached glob snapshot. */ + synchronized void acquireGlobValueIdentity(RuntimeGlob target) { + if (kind != Kind.GLOB_VALUE) { + throw new IllegalStateException("glob-value acquisition requires a glob-value slot"); + } + Objects.requireNonNull(target, "target"); + if (legacyCaptureCount != 0) { + throw new IllegalStateException("glob-value slot has pending legacy releases"); + } + transferWithoutRuntimeRoot(target, false); + } + + /** Record one active lexical pad entry that owns a scalar referent or aggregate. */ + synchronized void acquireActiveLexicalIdentity(RuntimeBase target) { + if (kind != Kind.ACTIVE_LEXICAL) { + throw new IllegalStateException("active lexical acquisition requires an active-lexical slot"); + } + Objects.requireNonNull(target, "target"); + if (!(target instanceof RuntimeArray || target instanceof RuntimeHash) + && !(target instanceof RuntimeScalar scalar + && scalar.referencedByScalarReference)) { + throw new IllegalArgumentException( + "active lexical owner slots require an aggregate or scalar reference cell"); + } + if (legacyCaptureCount != 0) { + throw new IllegalStateException("active lexical slot has pending legacy releases"); + } + transferWithoutRuntimeRoot(target, true); + } + + /** Record one strong lexical value retained while its interpreter frame is suspended. */ + public synchronized void acquireSuspendedFrameIdentity(RuntimeBase target) { + if (kind != Kind.SUSPENDED_FRAME) { + throw new IllegalStateException("suspended-frame acquisition requires a suspended-frame slot"); + } + Objects.requireNonNull(target, "target"); + if (target.isPerlDestroyed()) { + throw new IllegalStateException("cannot own a destroyed suspended-frame value"); + } + if (legacyCaptureCount != 0) { + throw new IllegalStateException("suspended-frame slot has pending legacy releases"); + } + transferWithoutRuntimeRoot(target, true); + } + + /** Keep a suspended lexical owner synchronized with its mutable scalar cell. */ + synchronized void updateSuspendedFrameIdentity(RuntimeBase target) { + if (kind != Kind.SUSPENDED_FRAME) { + throw new IllegalStateException("suspended-frame update requires a suspended-frame slot"); + } + if (target != null && target.isPerlDestroyed()) target = null; + transferWithoutRuntimeRoot(target, target != null); + } + + /** Record a strong edge without promoting an untracked referent's legacy count. */ + synchronized void acquireUntrackedIdentity(RuntimeBase target) { + if (kind != Kind.UNTRACKED_REFERENCE) { + throw new IllegalStateException("untracked acquisition requires an untracked-reference slot"); + } + Objects.requireNonNull(target, "target"); + if (target.isPerlDestroyed()) { + throw new IllegalStateException("cannot own a destroyed referent"); + } + if (nativeOwner || legacyCaptureCount != 0) { + throw new IllegalStateException("untracked identity cannot replace native or capture ownership"); + } + transferWithoutRuntimeRoot(target, false); + if (target.refCountTrace && RuntimeBase.refCountTraceEnabled()) { + System.err.println("[REFCOUNT-UNTRACKED-ACQUIRE] base=" + + System.identityHashCode(target) + " slot=" + identity); + StackTraceElement[] stack = new Throwable().getStackTrace(); + for (int i = 1; i < Math.min(stack.length, 14); i++) { + System.err.println(" at " + stack[i]); + } + } + } + + /** Attach one scalar wrapper's identity to a referenced cell's contents. */ + synchronized void acquireScalarReferenceContents( + RuntimeBase target, RuntimeScalar referenceCell, RuntimeScalar owner) { + if (kind != Kind.SCALAR_REFERENCE_CONTENTS) { + throw new IllegalStateException( + "scalar-reference acquisition requires a scalar-contents slot"); + } + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(referenceCell, "referenceCell"); + Objects.requireNonNull(owner, "owner"); + if (!target.isRefCountTracked()) { + throw new IllegalStateException("scalar-reference contents must be tracked"); + } + if (referent != null) { + if (referent == target && scalarReferenceCell() == referenceCell + && scalarContentsOwner() == owner) return; + throw new IllegalStateException("active scalar-contents owner cannot be reacquired"); + } + + boolean firstOwnerForCell = !referenceCell.hasScalarReferenceContentsOwner(this, target); + if (firstOwnerForCell && target.refCount == Integer.MAX_VALUE) { + throw new IllegalStateException("scalar-reference contents count overflow"); + } + scalarReferenceCell = new WeakReference<>(referenceCell); + scalarContentsOwner = new WeakReference<>(owner); + referenceCell.registerScalarReferenceContentsOwner(this); + transferWithoutRuntimeRoot(target, false); + if (firstOwnerForCell) { + target.acquireTrackedOwnerCount("PerlOwnerSlot.acquireScalarReferenceContents"); + target.acquireTransientTraceOwner( + "scalar-reference contents", "PerlOwnerSlot.scalarReferenceContents"); + } + } + + /** Retarget this alias when its scalar cell receives new contents. */ + void retargetScalarReferenceContents(RuntimeBase nextTarget) { + ScalarReferenceContentsRelease displaced = + retargetScalarReferenceContentsSlot(nextTarget); + if (displaced != null && displaced.release() != null) { + MortalList.releaseCountedOwnerSlotImmediately( + displaced.referent(), displaced.release(), "scalar-reference contents", + "PerlOwnerSlot.retargetScalarReferenceContents"); + } + } + + private synchronized ScalarReferenceContentsRelease retargetScalarReferenceContentsSlot( + RuntimeBase nextTarget) { + if (kind != Kind.SCALAR_REFERENCE_CONTENTS) { + throw new IllegalStateException( + "scalar-reference retargeting requires a scalar-contents slot"); + } + RuntimeBase previous = referent; + if (previous == nextTarget) return null; + RuntimeScalar referenceCell = scalarReferenceCell(); + if (referenceCell == null) { + throw new IllegalStateException("active scalar-contents owner lost its reference cell"); + } + if (nextTarget != null && !nextTarget.isRefCountTracked()) nextTarget = null; + boolean firstOwnerForNextTarget = nextTarget != null + && !referenceCell.hasScalarReferenceContentsOwner(this, nextTarget); + if (firstOwnerForNextTarget && nextTarget.refCount == Integer.MAX_VALUE) { + throw new IllegalStateException("scalar-reference contents count overflow"); + } + if (firstOwnerForNextTarget) { + nextTarget.acquireTrackedOwnerCount("PerlOwnerSlot.retargetScalarReferenceContents"); + nextTarget.acquireTransientTraceOwner( + "scalar-reference contents", "PerlOwnerSlot.scalarReferenceContents"); + } + + transferWithoutRuntimeRoot(nextTarget, false); + if (nextTarget == null) { + referenceCell.unregisterScalarReferenceContentsOwner(this); + scalarReferenceCell = null; + scalarContentsOwner = null; + } + if (previous != null + && !referenceCell.hasScalarReferenceContentsOwner(this, previous)) { + if (previous.refCount <= 0) { + previous.releaseTransientTraceOwner( + "scalar-reference contents", + "PerlOwnerSlot.retargetScalarReferenceContents"); + return null; + } + return new ScalarReferenceContentsRelease(previous, + new PendingRelease(identity, ++nextReleaseSequence, kind, previous)); + } + return null; + } + + private record ScalarReferenceContentsRelease(RuntimeBase referent, PendingRelease release) {} + + /** Detach this alias and produce one count obligation for the final cell owner. */ + private synchronized ScalarReferenceContentsRelease detachScalarReferenceContents() { + if (kind != Kind.SCALAR_REFERENCE_CONTENTS) { + throw new IllegalStateException( + "scalar-reference release requires a scalar-contents slot"); + } + RuntimeBase target = referent; + RuntimeScalar referenceCell = scalarReferenceCell(); + if (referenceCell != null) referenceCell.unregisterScalarReferenceContentsOwner(this); + boolean finalCellOwner = target != null && (referenceCell == null + || !referenceCell.hasScalarReferenceContentsOwner(this, target)); + transferWithoutRuntimeRoot(null, false); + scalarReferenceCell = null; + scalarContentsOwner = null; + if (!finalCellOwner || target == null) return null; + if (target.refCount <= 0) { + target.releaseTransientTraceOwner( + "scalar-reference contents", "PerlOwnerSlot.releaseScalarReferenceContents"); + return null; + } + return new ScalarReferenceContentsRelease(target, + new PendingRelease(identity, ++nextReleaseSequence, kind, target)); + } + + /** Release this alias through the shared exact-slot lifecycle transition. */ + void releaseScalarReferenceContents() { + ScalarReferenceContentsRelease detached = detachScalarReferenceContents(); + if (detached != null && detached.release() != null) { + MortalList.releaseCountedOwnerSlotImmediately( + detached.referent(), detached.release(), "scalar-reference contents", + "PerlOwnerSlot.releaseScalarReferenceContents"); + } + } + + /** Defer the final alias's shared contents decrement with its exact slot identity. */ + PendingRelease deferScalarReferenceContentsRelease() { + ScalarReferenceContentsRelease detached = detachScalarReferenceContents(); + if (detached == null || detached.release() == null) return null; + MortalList.deferOwnerSlotDecrement( + detached.referent(), "scalar-reference contents", detached.release()); + return detached.release(); + } + + /** Record one direct value retained by a runtime temporary root. */ + synchronized void acquireTemporaryRootIdentity(RuntimeBase target) { + if (kind != Kind.TEMPORARY_ROOT) { + throw new IllegalStateException("temporary-root acquisition requires a temporary-root slot"); + } + Objects.requireNonNull(target, "target"); + if (referent != null || nativeOwner || legacyCaptureCount != 0) { + throw new IllegalStateException("temporary-root slot is already active"); + } + if (target.isPerlDestroyed()) { + throw new IllegalStateException("cannot retain a destroyed temporary root"); + } + transferWithoutRuntimeRoot(target, false); + } + + private void transferWithoutRuntimeRoot(RuntimeBase target, boolean nextNativeOwner) { + if (referent == target) { + if (ownerRuntimeState != null) { + PerlRuntime.releaseOwnerSlotReferent(ownerRuntimeState, referent); + } + ownerRuntime = null; + ownerRuntimeState = null; + nativeOwner = nextNativeOwner; + return; + } + RuntimeBase previous = referent; + LifecycleRuntimeState previousState = ownerRuntimeState; + boolean previousRegistered = registeredInOwnerLedger; + if (transientUntrackedOwnerCounted) { + transientUntrackedOwnerCounted = false; + previous.adjustTransientUntrackedReferenceOwnerCount(-1); + } + referent = target; + ownerRuntime = null; + ownerRuntimeState = null; + nativeOwner = nextNativeOwner; + registeredInOwnerLedger = target != null; + if (registeredInOwnerLedger) target.addOwnerSlot(this); + refreshTransientUntrackedOwnerClassification(); + if (previous != null && previousRegistered) previous.removeOwnerSlot(this); + if (previous != null && previousRegistered) { + PerlRuntime.releaseOwnerSlotReferent(previousState, previous); + } + finishDeferredCodeRelease(previous); + finishDeferredScalarCellRelease(previous); + WeakRefRegistry.onStrongOwnerSlotReleased(previous); + } + + /** + * Record a scalar-capture identity held by its RuntimeCode owner. The + * closure already strongly owns the pad cell through capturedScalars, so + * registering a second runtime root would let an unreachable closure's + * slot outlive the closure and retain request resources. + */ + public synchronized void acquireCaptureIdentity(RuntimeBase target) { + acquireCaptureIdentity(target, null); + } + + /** Record a scalar-pad identity and the CODE object that owns the capture. */ + public synchronized void acquireCaptureIdentity(RuntimeBase target, RuntimeCode owner) { + if (kind != Kind.SCALAR_CAPTURE) { + throw new IllegalStateException("capture identity requires a scalar-capture slot"); + } + Objects.requireNonNull(target, "target"); + if (referent != null || nativeOwner) { + throw new IllegalStateException("capture identity is already active"); + } + if (target.isPerlDestroyed()) { + throw new IllegalStateException("cannot capture a destroyed pad cell"); + } + referent = target; + captureOwner = owner == null ? null : new WeakReference<>(owner); + registeredInOwnerLedger = true; + target.addOwnerSlot(this); + } + + synchronized RuntimeCode captureOwner() { + return captureOwner == null ? null : captureOwner.get(); + } + + synchronized void rebindCaptureOwner(RuntimeCode owner) { + if (kind != Kind.SCALAR_CAPTURE && kind != Kind.CLOSURE_PAD + && kind != Kind.CODE_STATE) { + throw new IllegalStateException("only closure-pad slots have a CODE owner"); + } + if (referent == null) return; + captureOwner = owner == null ? null : new WeakReference<>(owner); + } + + /** The active frame already retains the CV; no second global root is needed. */ + synchronized void acquireActiveCodeIdentity(RuntimeCode target) { + if (kind != Kind.ACTIVE_CODE || referent != null) { + throw new IllegalStateException("active CODE slot is not available"); + } + referent = Objects.requireNonNull(target, "target"); + nativeOwner = true; + registeredInOwnerLedger = true; + target.addOwnerSlot(this); + } + + /** Record an array refalias edge to a scalar cell without a legacy count. */ + synchronized void acquireArrayAliasCellIdentity(RuntimeScalar target, RuntimeArray owner) { + if (kind != Kind.ARRAY_ALIAS_CELL || referent != null || nativeOwner) { + throw new IllegalStateException("array alias-cell slot is not available"); + } + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(owner, "owner"); + if (target.isPerlDestroyed()) { + throw new IllegalStateException("cannot alias a destroyed scalar cell"); + } + arrayAliasOwner = new WeakReference<>(owner); + transferWithoutRuntimeRoot(target, true); + } + + RuntimeArray arrayAliasOwner() { + return arrayAliasOwner == null ? null : arrayAliasOwner.get(); + } + + /** Record a hash refalias edge to a scalar cell without a legacy count. */ + synchronized void acquireHashAliasCellIdentity(RuntimeScalar target, RuntimeHash owner) { + if (kind != Kind.HASH_ALIAS_CELL || referent != null || nativeOwner) { + throw new IllegalStateException("hash alias-cell slot is not available"); + } + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(owner, "owner"); + if (target.isPerlDestroyed()) { + throw new IllegalStateException("cannot alias a destroyed scalar cell"); + } + hashAliasOwner = new WeakReference<>(owner); + transferWithoutRuntimeRoot(target, true); + } + + RuntimeHash hashAliasOwner() { + return hashAliasOwner == null ? null : hashAliasOwner.get(); + } + + /** Identify a counted scalar or element edge without adding a global root. */ + public synchronized void acquireCountedIdentity(RuntimeBase target) { + if (!isCountedKind(kind)) { + throw new IllegalStateException("counted acquisition requires a scalar or element slot"); + } + Objects.requireNonNull(target, "target"); + if (nativeOwner || legacyCaptureCount != 0) { + throw new IllegalStateException("counted identity cannot replace native or capture ownership"); + } + if (referent == target) return; + + // A stored value replacement is acquire-before-release. Keep this + // slot's stable identity for pending-release provenance, but install + // its new referent in the ledger before retiring the old edge so a + // destructor or weak observer cannot see a gap in strong ownership. + RuntimeBase previous = referent; + LifecycleRuntimeState previousState = ownerRuntimeState; + boolean previousRegistered = registeredInOwnerLedger; + PerlRuntime nextRuntime = null; + LifecycleRuntimeState nextState = null; + if (kind == Kind.ARGUMENT_VALUE) { + nextRuntime = PerlRuntime.currentOrNull(); + if (nextRuntime == null) nextRuntime = ownerRuntime; + nextState = nextRuntime == null + ? null : nextRuntime.retainOwnerSlotReferent(target); + } + referent = target; + registeredInOwnerLedger = true; + target.addOwnerSlot(this); + ownerRuntime = nextRuntime; + ownerRuntimeState = nextState; + + if (previous != null && previousRegistered) { + previous.removeOwnerSlot(this); + PerlRuntime.releaseOwnerSlotReferent(previousState, previous); + } + finishDeferredCodeRelease(previous); + finishDeferredScalarCellRelease(previous); + WeakRefRegistry.onStrongOwnerSlotReleased(previous); + } + + /** Acquire one scalar-backed Perl edge, pairing its identity with refCount. */ + synchronized void acquireCountedScalarOwner( + RuntimeScalar scalar, RuntimeBase target, String acquisitionSite) { + Objects.requireNonNull(scalar, "scalar"); + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(acquisitionSite, "acquisitionSite"); + if (!isCountedKind(kind) || scalar.refCountOwned || referent != null + || !target.isRefCountTracked() || target.refCount == Integer.MAX_VALUE) { + throw new IllegalStateException("invalid counted scalar owner acquisition"); + } + acquireCountedIdentity(target); + associateCountedScalarOwner(scalar); + target.acquireTrackedOwnerCount(acquisitionSite); + scalar.refCountOwned = true; + target.recordOwner(scalar, acquisitionSite); + } + + /** + * Acquire a replacement edge while a scalar's stale aggregate slot is + * still active until the new value is published. The caller installs this + * fresh slot as the scalar's current identity after publication, then + * retires the stale slot without decrementing its already-zero referent. + */ + synchronized void acquireCountedScalarReplacementOwner( + RuntimeScalar scalar, RuntimeBase target, String acquisitionSite) { + Objects.requireNonNull(scalar, "scalar"); + Objects.requireNonNull(target, "target"); + Objects.requireNonNull(acquisitionSite, "acquisitionSite"); + if (!isCountedKind(kind) || !scalar.refCountOwned || referent != null + || nativeOwner || legacyCaptureCount != 0 + || !target.isRefCountTracked() || target.refCount == Integer.MAX_VALUE + || target.isPerlDestroyed()) { + throw new IllegalStateException("invalid counted scalar replacement owner acquisition"); + } + acquireCountedIdentity(target); + associateCountedScalarOwner(scalar); + target.acquireTrackedOwnerCount(acquisitionSite); + target.recordOwner(scalar, acquisitionSite); + } + + /** Replace one scalar edge while acquiring the replacement count and release token. */ + synchronized PendingRelease replaceCountedScalarOwnerAndAcquire( + RuntimeBase previous, RuntimeBase next, RuntimeScalar scalar, + String acquisitionSite) { + Objects.requireNonNull(previous, "previous"); + Objects.requireNonNull(next, "next"); + Objects.requireNonNull(scalar, "scalar"); + Objects.requireNonNull(acquisitionSite, "acquisitionSite"); + if (!isCountedKind(kind) || referent != previous + || countedScalarOwner() != scalar || !scalar.refCountOwned + || nativeOwner || legacyCaptureCount != 0) { + throw new IllegalStateException( + "scalar replacement requires its current counted owner identity"); + } + if (!next.isRefCountTracked() || next.refCount == Integer.MAX_VALUE) { + throw new IllegalStateException( + "scalar replacement requires an available tracked reference count"); + } + + PerlOwnerSlot resourceRelease = next == previous ? null + : RuntimeScalar.detachIoOwnerForDeferredRelease(scalar, previous); + PendingRelease previousRelease = new PendingRelease(identity, + ++nextReleaseSequence, kind, previous, null, resourceRelease); + next.acquireTrackedOwnerCount(acquisitionSite); + if (next != previous) acquireCountedIdentity(next); + associateCountedScalarOwner(scalar); + if (next != previous) { + previous.releaseOwner(scalar, acquisitionSite + " displaced"); + } + next.recordOwner(scalar, acquisitionSite); + return previousRelease; + } + + /** + * Record an active {@code @_} alias to a scalar cell without adding a + * second Perl-visible reference count for the aliased value. + */ + synchronized void acquireArgumentAliasIdentity(RuntimeBase target) { + if (kind != Kind.ARGUMENT_ALIAS) { + throw new IllegalStateException("argument-alias acquisition requires an alias slot"); + } + Objects.requireNonNull(target, "target"); + if (target.isPerlDestroyed()) { + release(); + return; + } + if (nativeOwner || legacyCaptureCount != 0) { + throw new IllegalStateException("argument alias cannot replace native ownership"); + } + if (referent == target) return; + + // The call frame already strongly owns the scalar cell, which in turn + // owns its current value. Record the slot identity on the referent for + // cleanup decisions without adding a second runtime root. + RuntimeBase previous = referent; + LifecycleRuntimeState previousState = ownerRuntimeState; + referent = target; + ownerRuntime = null; + ownerRuntimeState = null; + if (previous != null && registeredInOwnerLedger) { + previous.removeOwnerSlot(this); + PerlRuntime.releaseOwnerSlotReferent(previousState, previous); + } + registeredInOwnerLedger = true; + target.addOwnerSlot(this); + finishDeferredScalarCellRelease(previous); + WeakRefRegistry.onStrongOwnerSlotReleased(previous); + } + + synchronized void reclassifyCountedIdentity(Kind nextKind) { + if (nativeOwner || !isCountedKind(kind) || !isCountedKind(nextKind)) { + throw new IllegalStateException("only counted scalar and element slots can move storage"); + } + Kind previousKind = kind; + if (previousKind != nextKind) countedAggregateOwner = null; + if (previousKind != nextKind && referent != null) { + if (nextKind == Kind.ARGUMENT_VALUE) { + ownerRuntime = PerlRuntime.currentOrNull(); + ownerRuntimeState = ownerRuntime == null + ? null : ownerRuntime.retainOwnerSlotReferent(referent); + } else if (previousKind == Kind.ARGUMENT_VALUE) { + PerlRuntime.releaseOwnerSlotReferent(ownerRuntimeState, referent); + ownerRuntime = null; + ownerRuntimeState = null; + } + } + if (referent != null) { + referent.reclassifyOwnerSlotKind(this, previousKind, nextKind); + } else { + kind = nextKind; + } + } + + /** Called under the referent ledger lock to keep its per-kind indexes aligned. */ + void setKindFromOwnerLedger(Kind nextKind) { + kind = nextKind; + } + + static boolean isCountedKind(Kind kind) { + return kind == Kind.SCALAR_CELL || kind == Kind.CODE_SLOT || kind == Kind.ARRAY_ELEMENT + || kind == Kind.HASH_ELEMENT || kind == Kind.ARGUMENT_VALUE + || kind == Kind.ARGUMENT_CONTAINER || kind == Kind.RETURN_VALUE + || kind == Kind.TIE_HANDLER || kind == Kind.ARGUMENT_TIE_HANDLER; + } + + /** Whether this identity represents a Perl strong reference to its referent. */ + static boolean isPerlOwnerKind(Kind kind) { + return kind != Kind.TEMPORARY_ROOT && kind != Kind.IO_RESOURCE_HOLDER; + } + + /** Retire this edge and carry its identity through one deferred decrement. */ + public synchronized PendingRelease releaseCountedIdentity() { + return releaseCountedIdentity(false); + } + + /** + * Retire this edge after publishing its pending-release identity. The owner + * observer runs synchronously from {@link #release()}; a CODE owner must see + * the pending return edge before its last active scalar slot is detached. + */ + synchronized PendingRelease releaseCountedIdentity(boolean pendingOwnerRelease) { + if (referent == null) return null; + if (nativeOwner || legacyCaptureCount != 0) { + throw new IllegalStateException("counted release requires a counted identity"); + } + RuntimeBase releasedReferent = referent; + RuntimeScalar owner = countedScalarOwner(); + traceBaseResultSetOwnerRelease(releasedReferent, owner); + PerlOwnerSlot resourceRelease = RuntimeScalar.detachIoOwnerForDeferredRelease( + owner, releasedReferent); + PendingRelease pending = new PendingRelease( + identity, ++nextReleaseSequence, kind, releasedReferent, null, resourceRelease); + if (pendingOwnerRelease) releasedReferent.registerPendingOwnerRelease(pending); + release(); + return pending; + } + + private void traceBaseResultSetOwnerRelease(RuntimeBase target, RuntimeScalar owner) { + if (!RuntimeBase.refCountTraceEnabled() || !(target instanceof RuntimeHash) + || target.refCount > 2 + || !"DBICTest::BaseResultSet".equals(NameNormalizer.getBlessStr(target.blessId))) { + return; + } + RuntimeBase container = owner == null ? null : owner.getContainerOwner(); + String location = ""; + if (owner != null && container instanceof RuntimeHash hash && hash.elements != null) { + for (var entry : hash.elements.entrySet()) { + if (entry.getValue() == owner) { + location = " key=" + entry.getKey(); + break; + } + } + } else if (owner != null && container instanceof RuntimeArray array + && array.elements != null) { + location = " index=" + array.elements.indexOf(owner); + } + System.err.println("[RESULTSET-COUNTED-SLOT-RELEASE] referent=" + + System.identityHashCode(target) + " generation=" + + RuntimeBase.traceReferentGeneration(target) + " refCount=" + target.refCount + + " aliasOwners=" + + target.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS) + + " slot=" + identity + " kind=" + kind + " owner=" + + (owner == null ? 0 : System.identityHashCode(owner)) + " ownerActive=" + + (owner != null && owner.refCountOwned) + " container=" + + (container == null ? 0 : System.identityHashCode(container)) + location); + new Throwable().printStackTrace(System.err); + } + + /** + * Queue a counted edge whose owner remains live until its deferred release + * is processed. The pending token retires this slot exactly once when + * completed; ordinary overwritten or removed slots should continue to use + * {@link #releaseCountedIdentity()} because their storage edge is already + * gone when the decrement is queued. + */ + public synchronized PendingRelease releaseCountedIdentityAtCompletion() { + if (referent == null) return null; + if (nativeOwner || legacyCaptureCount != 0) { + throw new IllegalStateException("counted release requires a counted identity"); + } + RuntimeScalar owner = countedScalarOwner(); + PerlOwnerSlot resourceRelease = RuntimeScalar.detachIoOwnerForDeferredRelease(owner, referent); + return new PendingRelease( + identity, ++nextReleaseSequence, kind, referent, this, resourceRelease); + } + + /** Retire a counted native owner together with its paired direct count. */ + public synchronized PendingRelease releaseCountedNativeIdentity() { + if (!isCountedNativeOwner()) return null; + PendingRelease release = new PendingRelease(identity, ++nextReleaseSequence, kind); + release(); + return release; + } + + /** Replace this native slot's referent while retaining the slot identity. */ + public synchronized void replaceNativeOwner(RuntimeBase nextReferent) { + if (!nativeOwner || referent == null) { + throw new IllegalStateException("cannot replace a slot that is not a native owner"); + } + Objects.requireNonNull(nextReferent, "nextReferent"); + if (nextReferent.isPerlDestroyed()) { + throw new IllegalStateException("cannot own a destroyed referent"); + } + transferTo(nextReferent); + } + + /** Read the current referent as a borrow; this does not acquire ownership. */ + public synchronized RuntimeBase borrowReferent() { + return referent; + } + /** Queue one closure-pad count release and retain its slot provenance. */ public synchronized PendingRelease deferLegacyCaptureRelease(RuntimeBase target) { if (legacyCaptureCount <= 0) return null; @@ -158,6 +1328,7 @@ public synchronized void transferTo(RuntimeBase nextReferent) { RuntimeBase previous = referent; PerlRuntime previousRuntime = ownerRuntime; LifecycleRuntimeState previousState = ownerRuntimeState; + boolean previousRegistered = registeredInOwnerLedger; PerlRuntime nextRuntime = nextReferent == null ? null : PerlRuntime.currentOrNull(); if (nextReferent != null && nextRuntime == null) nextRuntime = previousRuntime; @@ -166,22 +1337,82 @@ public synchronized void transferTo(RuntimeBase nextReferent) { ownerRuntime = nextRuntime; ownerRuntimeState = nextRuntime == null || nextReferent == null ? null : nextRuntime.retainOwnerSlotReferent(nextReferent); - if (previous != null) previous.removeOwnerSlot(this); - if (previous != null) { + registeredInOwnerLedger = nextReferent != null; + if (registeredInOwnerLedger) nextReferent.addOwnerSlot(this); + if (previous != null && previousRegistered) previous.removeOwnerSlot(this); + if (previous != null && previousRegistered) { PerlRuntime.releaseOwnerSlotReferent(previousState, previous); } - if (nextReferent != null) nextReferent.addOwnerSlot(this); + finishDeferredCodeRelease(previous); + finishDeferredScalarCellRelease(previous); + WeakRefRegistry.onStrongOwnerSlotReleased(previous); } /** Release this slot. Repeated releases are harmless. */ public synchronized void release() { + if (kind == Kind.SCALAR_REFERENCE_CONTENTS) { + releaseScalarReferenceContents(); + return; + } RuntimeBase previous = referent; LifecycleRuntimeState previousState = ownerRuntimeState; + RuntimeBase previousProxyParent = proxyValueParent; + proxyValueParent = null; + if (transientUntrackedOwnerCounted) { + transientUntrackedOwnerCounted = false; + previous.adjustTransientUntrackedReferenceOwnerCount(-1); + } referent = null; + methodInvocantOwner = false; + countedNativeOwner = false; + countedScalarOwner = null; + countedAggregateOwner = null; + captureOwner = null; + scalarReferenceCell = null; + scalarContentsOwner = null; + suspendedScalarOwner = null; + globComponentOwner = null; + arrayAliasOwner = null; + hashAliasOwner = null; ownerRuntime = null; ownerRuntimeState = null; - if (previous != null) previous.removeOwnerSlot(this); - if (previous != null) PerlRuntime.releaseOwnerSlotReferent(previousState, previous); + if (previous != null && registeredInOwnerLedger) previous.removeOwnerSlot(this); + if (previousProxyParent != null) { + previousProxyParent.removeProxyValueOwnerSlot(this); + } + if (previous != null && registeredInOwnerLedger) { + PerlRuntime.releaseOwnerSlotReferent(previousState, previous); + } + registeredInOwnerLedger = false; + finishDeferredCodeRelease(previous); + finishDeferredScalarCellRelease(previous); + WeakRefRegistry.onStrongOwnerSlotReleased(previous); + if (kind == Kind.ACTIVE_LEXICAL) { + WeakRefRegistry.onActiveLexicalOwnerReleased(previous); + } } + private static void finishDeferredCodeRelease(RuntimeBase previous) { + if (previous instanceof RuntimeCode code) { + code.finishActiveCodeOwnerRelease(); + } + } + + /** Retry escaped scalar-cell cleanup after its final Perl owner leaves. */ + static void finishDeferredScalarCellRelease(RuntimeBase previous) { + if (!(previous instanceof RuntimeScalar scalar) + || !scalar.referencedByScalarReference + || scalar.perlLifecycleState() == RuntimeBase.PerlLifecycleState.DESTROYED + || scalar.refCount > 0 + || scalar.hasClosureCaptureOwner() + || scalar.localBindingExists + || MyVarCleanupStack.isRegistered(scalar) + || scalar.hasScalarCellOwner() + || PerlRuntime.currentOrNull() == null) { + return; + } + RuntimeScalar.scopeExitCleanup(scalar); + } + + } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/PerlRuntime.java b/src/main/java/org/perlonjava/runtime/runtimetypes/PerlRuntime.java index aa8c01ffcb..4c05742ec7 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/PerlRuntime.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/PerlRuntime.java @@ -21,10 +21,14 @@ import java.lang.ref.WeakReference; import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; +import java.util.IdentityHashMap; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -94,6 +98,8 @@ public final class PerlRuntime implements AutoCloseable { public boolean storableLastOpInNetorder; public final Set xsShimLoadingInProgress = new HashSet<>(); private final Map> referenceAddresses = new ConcurrentHashMap<>(); + private final Set retainedRootSnapshots = Collections.synchronizedSet( + Collections.newSetFromMap(new IdentityHashMap<>())); RuntimeIO ioStdout; RuntimeIO ioStderr; @@ -205,7 +211,6 @@ LifecycleRuntimeState retainOwnerSlotReferent(RuntimeBase referent) { synchronized (state) { state.positiveOwnerReferents.merge(referent, 1, Integer::sum); } - MortalList.invalidateAllRootSnapshots(); return state; } @@ -218,7 +223,83 @@ static void releaseOwnerSlotReferent( if (count <= 1) state.positiveOwnerReferents.remove(referent); else state.positiveOwnerReferents.put(referent, count - 1); } - MortalList.invalidateAllRootSnapshots(); + } + + private void retainRootSnapshot(RootSnapshot snapshot) { + retainedRootSnapshots.add(snapshot); + } + + private void releaseRootSnapshot(RootSnapshot snapshot) { + executionLock.lock(); + try { + if (snapshot.ownersReleased()) return; + retainedRootSnapshots.remove(snapshot); + if (closed) { + snapshot.releaseOwnerSlots(); + return; + } + try (Binding ignored = bind()) { + snapshot.releaseOwnerSlots(); + } + } finally { + executionLock.unlock(); + } + } + + /** Release every external root lease before clearing or replacing this runtime. */ + private void releaseRetainedRootSnapshots() { + List snapshots; + synchronized (retainedRootSnapshots) { + snapshots = new ArrayList<>(retainedRootSnapshots); + retainedRootSnapshots.clear(); + } + Throwable pendingException = null; + for (int i = snapshots.size() - 1; i >= 0; i--) { + RootSnapshot snapshot = snapshots.get(i); + pendingException = attemptCleanup(pendingException, snapshot::releaseOwnerSlots); + } + rethrowCleanupFailure(pendingException); + } + + private static void rethrowCleanupFailure(Throwable failure) { + if (failure == null) return; + if (failure instanceof RuntimeException runtimeException) { + throw runtimeException; + } + if (failure instanceof Error error) { + throw error; + } + throw new RuntimeException(failure); + } + + private static Throwable attemptCleanup(Throwable pendingException, Runnable cleanup) { + try { + cleanup.run(); + } catch (Throwable failure) { + if (pendingException == null) return failure; + if (pendingException != failure) pendingException.addSuppressed(failure); + } + return pendingException; + } + + private static Throwable closeSnapshotAfterFailure( + RootSnapshot snapshot, Throwable pendingException) { + try { + snapshot.close(); + } catch (Throwable cleanupFailure) { + pendingException = cleanupFailure; + } + return closeRuntimeAfterFailure(snapshot.runtime(), pendingException); + } + + private static Throwable closeRuntimeAfterFailure( + PerlRuntime runtime, Throwable pendingException) { + try { + runtime.close(); + } catch (Throwable cleanupFailure) { + pendingException = cleanupFailure; + } + return pendingException; } int positiveOwnerSlotReferentCount(RuntimeBase referent) { @@ -232,15 +313,6 @@ boolean retainsPositiveOwnerSlotReferent(RuntimeBase referent) { return positiveOwnerSlotReferentCount(referent) > 0; } - static java.util.List snapshotOwnerSlotReferents() { - PerlRuntime runtime = currentOrNull(); - if (runtime == null) return java.util.List.of(); - LifecycleRuntimeState state = runtime.lifecycleState; - synchronized (state) { - return java.util.List.copyOf(state.positiveOwnerReferents.keySet()); - } - } - /** Record the address exposed by Perl reference stringification for B introspection. */ public void registerReferenceAddress(RuntimeBase value) { registerReferenceAddress(referenceAddress(value), value); @@ -437,6 +509,10 @@ public PerlRuntime reset() { if (activeBindings.get() != 0) { throw new IllegalStateException("PerlRuntime reset requires all bindings to be closed"); } + if (executionState.hasSuspendedContinuations()) { + throw new IllegalStateException( + "PerlRuntime reset requires suspended async frames to finish"); + } if (threadRegistry.size() != 0) { throw new IllegalStateException("PerlRuntime reset requires all child threads to finish"); } @@ -454,6 +530,7 @@ public PerlRuntime reset() { try { try (Binding ignored = bind()) { releaseResettableResources(); + releaseRetainedRootSnapshots(); } replaceRuntimeState(); initialized = false; @@ -490,7 +567,56 @@ public RootSnapshot snapshotCloneWithRoots(java.util.List return snapshotCloneInternal(new PerlThreadRegistry(), 0, roots); } - public record RootSnapshot(PerlRuntime runtime, java.util.List roots) {} + /** A runtime snapshot and the explicit temporary owner slots for its external roots. */ + public static final class RootSnapshot implements AutoCloseable { + private final PerlRuntime runtime; + private final List roots; + private final List ownerSlots; + private final java.util.function.Consumer ownerSlotReleaser; + private final java.util.concurrent.atomic.AtomicBoolean ownersReleased = + new java.util.concurrent.atomic.AtomicBoolean(); + + RootSnapshot( + PerlRuntime runtime, List roots, List ownerSlots) { + this(runtime, roots, ownerSlots, PerlOwnerSlot::release); + } + + RootSnapshot( + PerlRuntime runtime, List roots, List ownerSlots, + java.util.function.Consumer ownerSlotReleaser) { + this.runtime = Objects.requireNonNull(runtime, "runtime"); + this.roots = Collections.unmodifiableList(new ArrayList<>(roots)); + this.ownerSlots = List.copyOf(ownerSlots); + this.ownerSlotReleaser = Objects.requireNonNull( + ownerSlotReleaser, "ownerSlotReleaser"); + runtime.retainRootSnapshot(this); + } + + public PerlRuntime runtime() { return runtime; } + public List roots() { return roots; } + + private boolean ownersReleased() { return ownersReleased.get(); } + + private void releaseOwnerSlots() { + if (!ownersReleased.compareAndSet(false, true)) return; + Throwable pendingException = null; + // A cloned scalar root is followed by a lease on its referent. + // Release in acquisition order so the scalar's root edge retires + // before its referent lease can trigger final lifecycle work. + for (int i = 0; i < ownerSlots.size(); i++) { + PerlOwnerSlot owner = ownerSlots.get(i); + pendingException = attemptCleanup( + pendingException, () -> ownerSlotReleaser.accept(owner)); + } + rethrowCleanupFailure(pendingException); + } + + /** Release this snapshot's external root identities before the runtime closes. */ + @Override + public void close() { + runtime.releaseRootSnapshot(this); + } + } RootSnapshot snapshotCloneForThread( PerlThreadRegistry registry, long threadId, @@ -539,27 +665,47 @@ private RootSnapshot snapshotCloneInternal( org.perlonjava.app.scriptengine.PerlLanguageProvider.COMPILE_LOCK.lock(); try { PerlRuntime child = new PerlRuntime(registry, threadId); - nameNormalizerState.snapshotInto(child.nameNormalizerState); - RuntimeGraphCloner cloner = new RuntimeGraphCloner(this, child, skipped); - try (Binding ignored = bind()) { - globalState.snapshotInto(child.globalState, cloner); - cloner.cloneCompilationHints(compilationState, child.compilationState); - cloner.cloneCompilationWarnings(compilationState, child.compilationState); - runtimeCodeState.snapshotCompiledMetadataInto(child.runtimeCodeState); - sourceMapperState.snapshotInto(child.sourceMapperState); - regexState.snapshotInto(child.regexState); + try { + nameNormalizerState.snapshotInto(child.nameNormalizerState); + RuntimeGraphCloner cloner = new RuntimeGraphCloner(this, child, skipped); + try (Binding ignored = bind()) { + globalState.snapshotInto(child.globalState, cloner); + cloner.cloneCompilationHints(compilationState, child.compilationState); + cloner.cloneCompilationWarnings(compilationState, child.compilationState); + runtimeCodeState.snapshotCompiledMetadataInto(child.runtimeCodeState); + sourceMapperState.snapshotInto(child.sourceMapperState); + regexState.snapshotInto(child.regexState); + } + try (Binding ignored = child.bind()) { + child.globalState.rebuildPackageScalarOwnerSlots(); + child.globalState.rebuildPackageAggregateOwnerSlots(); + child.globalState.rebuildPackageIoGlobOwnerSlots(); + } + RuntimeGraphCloner.SnapshotRoots clonedRoots = + cloner.cloneSnapshotRoots(roots); + snapshot = new RootSnapshot( + child, clonedRoots.roots(), clonedRoots.ownerSlots()); + try { + cloner.finishSnapshot(); + } catch (RuntimeException | Error failure) { + rethrowCleanupFailure(closeSnapshotAfterFailure(snapshot, failure)); + throw failure; + } + child.currentDirectory = currentDirectory; + child.initialized = true; + } catch (RuntimeException | Error failure) { + rethrowCleanupFailure(closeRuntimeAfterFailure(child, failure)); + throw failure; } - java.util.List clonedRoots = cloner.cloneSnapshotRoots(roots); - cloner.finishSnapshot(); - child.currentDirectory = currentDirectory; - child.initialized = true; - snapshot = new RootSnapshot(child, clonedRoots); } finally { org.perlonjava.app.scriptengine.PerlLanguageProvider.COMPILE_LOCK.unlock(); } try (Binding ignored = snapshot.runtime().bind()) { snapshot.runtime().runCloneHooks(); + } catch (RuntimeException | Error failure) { + rethrowCleanupFailure(closeSnapshotAfterFailure(snapshot, failure)); + throw failure; } return snapshot; } finally { @@ -631,50 +777,51 @@ private void materializeLazyCodeDefinitions() { } private void runCloneHooks() { - lifecycleState.weakSweepSuppressionDepth++; - try { - for (String fqn : new TreeSet<>(globalState.codeRefs().keySet())) { - if (!fqn.endsWith("::CLONE") || fqn.endsWith("::CLONE_SKIP")) continue; - RuntimeScalar hook = globalState.codeRefs().get(fqn); - if (hook == null || !(hook.value instanceof RuntimeCode code) || !code.defined()) continue; - String packageName = fqn.substring(0, fqn.length() - "::CLONE".length()); - RuntimeCode.apply(hook, new RuntimeArray(new RuntimeScalar(packageName)), - RuntimeContextType.VOID); - } - } finally { - lifecycleState.weakSweepSuppressionDepth--; + for (String fqn : new TreeSet<>(globalState.codeRefs().keySet())) { + if (!fqn.endsWith("::CLONE") || fqn.endsWith("::CLONE_SKIP")) continue; + RuntimeScalar hook = globalState.codeRefs().get(fqn); + if (hook == null || !(hook.value instanceof RuntimeCode code) || !code.defined()) continue; + String packageName = fqn.substring(0, fqn.length() - "::CLONE".length()); + RuntimeCode.apply(hook, new RuntimeArray(new RuntimeScalar(packageName)), + RuntimeContextType.VOID); } } - void beginThreadEntrySnapshotGrace() { - lifecycleState.weakSweepSuppressionDepth++; - } - - void endThreadEntrySnapshotGrace() { - lifecycleState.weakSweepSuppressionDepth--; - } - /** Release runtime-owned I/O, alarms, signals, and lifecycle registries. */ @Override public void close() { executionLock.lock(); try { if (closed) return; - try (Binding ignored = bind()) { - Time.cancelCurrentAlarm(); - PerlSignalQueue.clearSignals(); - RuntimeIO.closeAllHandles(); - NetSSLeay.resetState(); - MortalList.clearCurrentRuntimeState(); - stateVariableInitialized.clear(); - ioRegistryState.clear(); - nativeState.clear(); - flipFlopState.clear(); - scalarGlobState.clear(); - pointerPackState.clear(); - referenceAddresses.clear(); + Throwable pendingException = null; + try { + try (Binding ignored = bind()) { + pendingException = attemptCleanup( + pendingException, Time::cancelCurrentAlarm); + pendingException = attemptCleanup( + pendingException, PerlSignalQueue::clearSignals); + pendingException = attemptCleanup( + pendingException, RuntimeIO::closeAllHandles); + pendingException = attemptCleanup(pendingException, NetSSLeay::resetState); + pendingException = attemptCleanup( + pendingException, this::releaseRetainedRootSnapshots); + pendingException = attemptCleanup( + pendingException, MortalList::clearCurrentRuntimeState); + pendingException = attemptCleanup( + pendingException, stateVariableInitialized::clear); + pendingException = attemptCleanup(pendingException, ioRegistryState::clear); + pendingException = attemptCleanup(pendingException, nativeState::clear); + pendingException = attemptCleanup(pendingException, flipFlopState::clear); + pendingException = attemptCleanup(pendingException, scalarGlobState::clear); + pendingException = attemptCleanup(pendingException, pointerPackState::clear); + pendingException = attemptCleanup(pendingException, referenceAddresses::clear); + } + } catch (Throwable bindingFailure) { + pendingException = bindingFailure; + } finally { + closed = true; } - closed = true; + rethrowCleanupFailure(pendingException); } finally { executionLock.unlock(); } @@ -851,14 +998,14 @@ void replaceStandardHandle(String name, RuntimeIO io) { private void installInitialStandardGlob(String name, RuntimeIO io) { RuntimeGlob glob = new RuntimeGlob(name); - glob.IO = new RuntimeScalar(io); + glob.replaceIOScalar(new RuntimeScalar(io)); standardIOGlobs.put(name, glob); } private void updateStandardGlobHandle(String name, RuntimeIO io) { RuntimeGlob glob = standardIOGlobs.get(name); if (glob != null) { - glob.IO = new RuntimeScalar(io); + glob.replaceIOScalar(new RuntimeScalar(io)); } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/PerlThreadControlBlock.java b/src/main/java/org/perlonjava/runtime/runtimetypes/PerlThreadControlBlock.java index 8edb2f04c6..f641da0bee 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/PerlThreadControlBlock.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/PerlThreadControlBlock.java @@ -25,6 +25,7 @@ public record Completion(RuntimeBase value, Throwable error) {} private final PerlThreadRegistry registry; private final PerlRuntime parentRuntime; private volatile PerlRuntime childRuntime; + private volatile PerlRuntime.RootSnapshot entrySnapshot; private volatile EntryPoint entryPoint; private volatile Runnable entryCleanup; private final int context; @@ -68,6 +69,7 @@ private PerlThreadControlBlock(PerlRuntime parent, RuntimeScalar code, RuntimeAr roots.add(Objects.requireNonNull(code, "code")); for (int i = 0; i < args.size(); i++) roots.add(args.get(i)); PerlRuntime.RootSnapshot snapshot = parent.snapshotCloneForThread(registry, id, roots); + this.entrySnapshot = snapshot; this.childRuntime = snapshot.runtime(); this.context = context; this.stackSize = stackSize; @@ -82,46 +84,49 @@ private PerlThreadControlBlock(PerlRuntime parent, RuntimeScalar code, RuntimeAr RuntimeArray childArgs = new RuntimeArray(); for (int i = 1; i < cloned.size(); i++) childArgs.push(cloned.get(i).scalar()); this.entryPoint = runtime -> { - runtime.beginThreadEntrySnapshotGrace(); - try { - RuntimeList values = RuntimeCode.apply(childCode, childArgs, context); - RuntimeArray retained = new RuntimeArray(); - for (RuntimeBase value : values.elements) retained.push(value.scalar()); - return retained; - } finally { - runtime.endThreadEntrySnapshotGrace(); - } + RuntimeList values = RuntimeCode.apply(childCode, childArgs, context); + RuntimeArray retained = new RuntimeArray(); + for (RuntimeBase value : values.elements) retained.push(value.scalar()); + return retained; }; this.entryCleanup = () -> { - // The thread invocation owns an anonymous entry CV independently - // of its parent. Releasing it at thread end drops captured child - // lexicals before END, while named package CVs remain stash-owned. - if (releaseEntryCode) { - if (childCode.value instanceof RuntimeCode entryCode) { - RuntimeScalar[] capturedScalars = entryCode.capturedScalars; - if (capturedScalars != null) { - for (RuntimeScalar captured : capturedScalars) { - // These pads were cloned from the parent's active - // scope, but the child has no enclosing invocation - // that can later retire them. Thread termination is - // their scope boundary in this runtime. - // A shared scalar, including one reached through a - // child-local reference wrapper, is the parent's - // canonical storage. Releasing the child closure - // must drop only its capture; marking that pad - // scope-exited lets child teardown destroy or clear - // a value the parent still owns. - RuntimeBase capturedReferent = SharedPerlStorage.referent(captured); - if (capturedReferent == null || !capturedReferent.threadShared) { - captured.scopeExited = true; + try { + // The thread invocation owns an anonymous entry CV independently + // of its parent. Releasing it at thread end drops captured child + // lexicals before END, while named package CVs remain stash-owned. + if (releaseEntryCode) { + if (childCode.value instanceof RuntimeCode entryCode) { + RuntimeScalar[] capturedScalars = entryCode.capturedScalars; + if (capturedScalars != null) { + for (RuntimeScalar captured : capturedScalars) { + // These pads were cloned from the parent's active + // scope, but the child has no enclosing invocation + // that can later retire them. Thread termination is + // their scope boundary in this runtime. + // A shared scalar, including one reached through a + // child-local reference wrapper, is the parent's + // canonical storage. Releasing the child closure + // must drop only its capture; marking that pad + // scope-exited lets child teardown destroy or clear + // a value the parent still owns. + RuntimeBase capturedReferent = SharedPerlStorage.referent(captured); + if (capturedReferent == null || !capturedReferent.threadShared) { + captured.scopeExited = true; + } } } + entryCode.releaseCaptures(); } - entryCode.releaseCaptures(); + RuntimeScalar.scopeExitCleanup(childCode); } - RuntimeScalar.scopeExitCleanup(childCode); + MortalList.scopeExitCleanupArray(childArgs); + MortalList.flush(); + } finally { + // Child arguments and the anonymous entry CV have finished + // their Perl lifetimes. Retire the Java-held snapshot roots + // only after their ordinary owner slots have been released. + snapshot.close(); } - MortalList.flush(); }; registry.register(this); } @@ -233,9 +238,9 @@ private void run() { RuntimeRegex.emitCurrentRuntimeDebugFreeTraces(); } // A child interpreter must not finalize objects whose shared - // references remain owned by the parent thread. The process - // level pass handles otherwise unreachable reference cycles. - GlobalDestruction.runGlobalDestruction(false); + // references remain owned by the parent thread. Teardown uses + // its package owner slots without scanning unreachable cycles. + GlobalDestruction.runGlobalDestruction(); return new Outcome(value, failure); }); result = outcome.value(); @@ -342,12 +347,15 @@ public boolean hasSignalHandler(String signal) { public void releaseTerminalResources() { PerlRuntime runtime; RuntimeBase terminalResult; + PerlRuntime.RootSnapshot snapshot; synchronized (this) { if (state != State.JOINED && state != State.DETACHED) return; terminalResult = result; result = null; entryPoint = null; entryCleanup = null; + snapshot = entrySnapshot; + entrySnapshot = null; runtime = childRuntime; childRuntime = null; } @@ -356,11 +364,14 @@ public void releaseTerminalResources() { if (terminalResult instanceof RuntimeArray values) { MortalList.scopeExitCleanupArray(values); } + if (snapshot != null) snapshot.close(); MortalList.flush(); MortalList.flushDeferredCaptures(); - GlobalDestruction.runGlobalDestruction(false); + GlobalDestruction.runGlobalDestruction(); }); runtime.close(); + } else if (snapshot != null) { + snapshot.close(); } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/ReachabilityQueryStats.java b/src/main/java/org/perlonjava/runtime/runtimetypes/ReachabilityQueryStats.java index 8938a4577a..ed440aedd6 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/ReachabilityQueryStats.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/ReachabilityQueryStats.java @@ -1,6 +1,6 @@ package org.perlonjava.runtime.runtimetypes; -/** Optional per-runtime counters for deterministic reachability cost tests. */ +/** Optional counters retained for owner-ledger lifecycle regression tests. */ final class ReachabilityQueryStats { long rootQueries; long rootsSeeded; @@ -14,11 +14,8 @@ final class ReachabilityQueryStats { long liveRootSnapshotsBuilt; long liveRootSnapshotNodesVisited; long globalCodeCaptureRootsWalked; - long weakBackrefCaptureRootsWalked; - long weakBackrefCaptureNodesVisited; - long weakBackrefCaptureEdgesInspected; - long weakBackrefCaptureSnapshotsBuilt; long unblessedAggregateDrainPositiveProofsCached; long scalarReachabilityQueries; long scalarReachabilityRootWalks; + long codeOwnerSlotRestorations; } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/ReachabilityWalker.java b/src/main/java/org/perlonjava/runtime/runtimetypes/ReachabilityWalker.java deleted file mode 100644 index d5153b130e..0000000000 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/ReachabilityWalker.java +++ /dev/null @@ -1,3607 +0,0 @@ -package org.perlonjava.runtime.runtimetypes; - -import org.perlonjava.runtime.regex.RuntimeRegex; - -import java.util.ArrayList; -import java.util.AbstractSet; -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; -import java.lang.ref.WeakReference; - -/** - * Phase 4 (refcount_alignment_plan.md): On-demand reachability walker. - *

    - * Walks the live object graph from Perl-visible roots and identifies which - * objects in the weak-ref registry are unreachable. Clears weak refs for - * those objects, simulating Perl 5's refcount-based collection when - * PerlOnJava's selective refCount has drifted due to JVM temporaries. - *

    - * Roots: - *

      - *
    • {@link GlobalVariable#globalVariables} — package scalars ($pkg::name)
    • - *
    • {@link GlobalVariable#globalArrays} — package arrays (@pkg::name)
    • - *
    • {@link GlobalVariable#globalHashes} — package hashes (%pkg::name)
    • - *
    • {@link GlobalVariable#globalCodeRefs} — package subs
    • - *
    • Rescued objects from {@link DestroyDispatch}
    • - *
    - *

    - * Not yet walked (TODO): - *

      - *
    • Live lexicals in the call stack — JVM doesn't easily expose these. - * Mitigated by assuming a short-lived sweep runs during/after Perl code - * completes a unit of work (e.g., every N flushes).
    • - *
    • Closures that capture lexicals — we walk them via their CODE refs but - * not into the captured variables directly.
    • - *
    - */ -public class ReachabilityWalker { - - private static final String WALKER_TRACE_CLASS = - System.getenv("JPERL_WALKER_TRACE_CLASS"); - - private Set weakWitnessTargets; - private final IdentityHashMap weakWitnessCaptureRoots = - new IdentityHashMap<>(); - private final IdentityHashMap discoveredWeakRootWitnesses = - new IdentityHashMap<>(); - private int discoveredLexicalCodeWitnesses; - - record WeakRootWitness(WeakReference rootCode, - WeakReference capturedAggregate, - WeakReference ownerScalar, - WeakReference referent, - boolean liveLexicalScalar) {} - - private record ReflectiveCaptureFields( - java.lang.reflect.Field[] scalars, - java.lang.reflect.Field[] bases) {} - - // Generated closure implementations have a stable class layout. Cache - // the captured scalar/base fields per class so repeated weak-reference - // sweeps do not redo reflective discovery on the callback path. - private static final ClassValue REFLECTIVE_CAPTURE_FIELDS = - new ClassValue<>() { - @Override - protected ReflectiveCaptureFields computeValue(Class type) { - java.util.ArrayList scalars = new java.util.ArrayList<>(); - java.util.ArrayList bases = new java.util.ArrayList<>(); - for (java.lang.reflect.Field field : type.getDeclaredFields()) { - Class fieldType = field.getType(); - if (fieldType == RuntimeScalar.class - && !"__SUB__".equals(field.getName())) { - scalars.add(field); - } else if (fieldType != RuntimeScalar.class - && RuntimeBase.class.isAssignableFrom(fieldType)) { - bases.add(field); - } - } - return new ReflectiveCaptureFields( - scalars.toArray(java.lang.reflect.Field[]::new), - bases.toArray(java.lang.reflect.Field[]::new)); - } - }; - - // Re-use the weak-ref registry's internal map (we add a getter) - private final Set reachable = - java.util.Collections.newSetFromMap(new IdentityHashMap<>(512)); - - // Whether to follow RuntimeCode.capturedScalars edges. Off by default - // because Sub::Quote/Moo-generated accessors over-capture instances, - // which would mark DBIC Schema/ResultSource instances as reachable - // even after they should be GC'd. Native Perl doesn't hit this pitfall - // because its refcount already tracks the captures accurately. - private boolean walkCodeCaptures = false; - - // Whether to seed active Perl lexicals. The live-variable table supplies - // these roots directly; scanning ScalarRefRegistry as well would duplicate - // the same live scalar slots. - private boolean useLexicalSeeds = true; - - // Ordinary sweeps must retain values that are still in expression - // temporaries. A targeted sweep requested by destruction of that very - // temporary must be able to exclude those stale JVM register roots: Perl's - // FREETMPS has already released them at the statement boundary. - private boolean useTemporaryRoots = true; - - /** Enable walking closures' captured scalars. */ - public ReachabilityWalker withCodeCaptures(boolean v) { - this.walkCodeCaptures = v; - return this; - } - - /** Disable live-lexical roots (globals-only walk). */ - public ReachabilityWalker withLexicalSeeds(boolean v) { - this.useLexicalSeeds = v; - return this; - } - - public ReachabilityWalker withTemporaryRoots(boolean v) { - this.useTemporaryRoots = v; - return this; - } - - ReachabilityWalker withWeakWitnessTargets(Set targets) { - this.weakWitnessTargets = targets; - return this; - } - - private static boolean isNonOwningDebugArgsArray(String name) { - // @DB::args aliases caller arguments for debugger/Carp introspection. - // It is not an owning root after the source frame has unwound; live - // frames are already represented by RuntimeCode.snapshotArgsStack(). - return "DB::args".equals(name); - } - - private static boolean hasCapturedAggregateElementOwner(RuntimeBase referent) { - for (RuntimeScalar owner : ScalarRefRegistry.snapshot()) { - if (owner == null || !owner.refCountOwned || owner.value != referent) continue; - RuntimeBase container = owner.containerOwner; - if (container instanceof RuntimeArray array - && array.captureCount > 0 && array.elements.contains(owner)) { - return true; - } - if (container instanceof RuntimeHash hash - && hash.captureCount > 0 && hash.elements.containsValue(owner)) { - return true; - } - } - return false; - } - - /** - * Walk from Perl-visible roots and mark reachable objects. - *

    - * Phase I (refcount_alignment_52leaks_plan.md): Two-phase walk. - *

      - *
    1. Phase 1: seed from {@code globalCodeRefs}, BFS WITH closure- - * capture walking. Stash-installed closures (Sub::Defer - * deferred subs, Moo/Sub::Quote accessors) capture lexicals - * that represent real live-data paths (e.g. - * {@code $deferred_info} ARRAY, {@code $quoted_info} HASH, - * {@code $unquoted} scalar slot). Following captures here - * ensures Sub::Defer's %DEFERRED / Sub::Quote's %QUOTED - * entries are seen as reachable.
    2. - *
    3. Phase 2: seed remaining roots (globalVariables, - * globalArrays, globalHashes, rescuedObjects, lexical seeds), - * BFS without capture walking by default. Anon closures held - * by instance hashes (DBIC handler callbacks) stay opaque - * so instances captured only by them can be marked - * unreachable — letting 52leaks detect real Schema leaks.
    4. - *
    - * - * @return the set of reachable RuntimeBase instances - */ - public Set walk() { - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - - // Phase 1: seed globalCodeRefs, walk WITH captures. - for (RuntimeScalar codeRef : GlobalVariable.globalCodeRefEdgeRootsView()) { - addGlobalCodeRoot(codeRef, todo); - } - // An executing anonymous closure is a live Perl root even when no - // package/global slot refers to its CODE value. Statement-boundary - // sweeps run inside RuntimeCode.apply(); follow that active closure's - // captures before deciding that a blessed referent is unreachable. - // Test2::AsyncSubtest exposes this with a weak hub back-reference: the - // child entry closure is the sole strong owner of $self while it runs. - for (RuntimeCode active : new ArrayList<>( - PerlRuntime.current().executionState().activeCodeStack)) { - addReachable(active, todo); - } - // Active call arguments are live even after a callee shifts @_. Walk - // them with captures enabled: an in-flight Future commonly owns a - // callback closure whose captured slot array owns its child Futures. - // This root disappears as soon as the call frame returns. - for (java.util.List args : RuntimeCode.snapshotPristineArgsStack()) { - for (RuntimeScalar arg : args) { - if (arg == null || WeakRefRegistry.isweak(arg)) continue; - addReachable(arg, todo); - visitScalar(arg, todo); - } - } - bfs(todo, /*walkCaptures=*/ true); - - // Phase 2: seed remaining roots. - for (RuntimeScalar scalar : GlobalVariable.globalVariableValuesView()) { - visitScalar(scalar, todo); - } - for (Map.Entry e : GlobalVariable.globalArrayEntriesView()) { - if (isNonOwningDebugArgsArray(e.getKey())) continue; - addReachable(e.getValue(), todo); - } - for (RuntimeHash hash : GlobalVariable.globalHashValuesView()) { - addReachable(hash, todo); - } - for (RuntimeBase rescued : DestroyDispatch.snapshotRescuedForWalk()) { - addReachable(rescued, todo); - } - // Explicit owner slots carry semantic Perl ownership even when the - // owning pad cell is intentionally absent from conservative lexical - // walker roots. Captured aggregate pads use this path so their - // elements remain reachable until the closure releases the slot. - for (RuntimeBase ownerReferent : PerlRuntime.snapshotOwnerSlotReferents()) { - addReachable(ownerReferent, todo); - } - for (RuntimeBase suspended : MortalList.snapshotSuspendedRoots()) { - addReachable(suspended, todo); - } - if (useLexicalSeeds) { - // Phase D-W1 (walker_gate_dbic_minimal.t): seed from live - // my-vars themselves (RuntimeArray / RuntimeHash that the - // user declared with `my @arr` / `my %hash`). Without this, - // the auto-sweep's reachability check misses top-level - // arrays/hashes — their elements end up flagged unreachable - // and DESTROY fires on still-held blessed objects. - // - // Mirrors the seeding already in `isReachableFromRoots()`. - // Order matters: RuntimeScalar IS-A RuntimeBase, so the - // RuntimeScalar branch must come first to walk through its - // reference bit. Otherwise the BFS only steps into hashes - // and arrays, missing the scalar's referent. The previous - // ScalarRefRegistry seed was redundant: every scalar accepted - // by its MyVarCleanupStack.isLive check is present in this list. - // Use this one live-slot snapshot to avoid copying and rescanning - // the ref-scalar registry during every complete weak sweep. - for (Object liveVar : MyVarCleanupStack.snapshotLiveVars()) { - if (liveVar instanceof RuntimeScalar sc) { - if (WeakRefRegistry.isweak(sc)) continue; - recordWeakLiveLexicalScalarWitness(sc); - addReachable(sc, todo); - visitScalar(sc, todo); - } else if (liveVar instanceof RuntimeBase rb) { - addReachable(rb, todo); - } - } - for (RuntimeArray args : RuntimeCode.snapshotArgsStack()) { - addReachable(args, todo); - } - if (useTemporaryRoots) { - for (RuntimeBase tempRoot : MortalList.snapshotTemporaryRoots()) { - addReachable(tempRoot, todo); - } - } - } - - bfs(todo, walkCodeCaptures); - - return withInstalledGlobalCodeRoots(); - } - - /** - * Return the graph that must remain live while END blocks execute. - * - * Package CODE slots and queued END blocks are the only seeds. Captures - * are followed from both: they are real Perl ownership paths at this - * lifecycle boundary, unlike the conservative lexical seeds used by the - * general weak-reference sweep. - */ - static Set walkEndBlockRoots() { - ReachabilityWalker walker = new ReachabilityWalker(); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - - for (RuntimeScalar codeRef : GlobalVariable.globalCodeRefValuesView()) { - if (codeRef == null || !(codeRef.value instanceof RuntimeCode code)) continue; - - // The registry also contains anonymous/eval compilation artifacts. - // Those are implementation caches, not Perl package CODE roots; - // following them would retain every lexical conservatively captured - // for eval STRING. A genuinely callable package sub has a stable - // package/sub name and remains a valid path for END to invoke. - if (code.subName == null || code.subName.isEmpty() - || code.subName.equals("__ANON__") - || code.packageName == null || code.packageName.isEmpty() - || code.packageName.startsWith("(eval") - || (code.cvStartFile != null && code.cvStartFile.startsWith("(eval"))) { - continue; - } - walker.visitScalar(codeRef, todo); - } - walker.addReachable(SpecialBlock.getEndBlocks(), todo); - walker.bfsEndBlockRoots(todo); - return walker.reachable; - } - - /** - * Traverse only semantic closure edges for END lifetime decisions. - * RuntimeCode.capturedScalars and reflective capture arrays also contain - * transient eval STRING captures attached while named code executes; those - * implementation edges must not extend a file lexical's Perl lifetime. - * closedOverVariables is populated from the closure's explicit lexical - * environment by both generated and interpreted backends. - */ - private void bfsEndBlockRoots(java.util.ArrayDeque todo) { - while (!todo.isEmpty()) { - RuntimeBase cur = todo.removeFirst(); - if (cur instanceof RuntimeHash hash) { - if (hash.elements instanceof HashSpecialVariable) continue; - for (RuntimeScalar value : hash.elements.values()) { - addReachable(value, todo); - visitScalar(value, todo); - } - } else if (cur instanceof RuntimeArray array) { - // A child thread can run this lifecycle walk while another - // thread mutates a shared array. Iterating the live ArrayList - // leaks its fail-fast ConcurrentModificationException into - // thread teardown (seen in threads/t/free2.t). Traverse a - // point-in-time copy instead; the graph walk is advisory and - // must tolerate concurrent updates to shared Perl values. - for (RuntimeScalar value : array.elements.toArray(RuntimeScalar[]::new)) { - addReachable(value, todo); - visitScalar(value, todo); - } - } else if (cur instanceof RuntimeCode code) { - visitCodePadConstants(code, todo); - visitCodeStateVariables(code, todo); - if (code.closedOverVariables != null) { - for (RuntimeBase captured : code.closedOverVariables.values()) { - addReachable(captured, todo); - if (captured instanceof RuntimeScalar scalar) { - visitScalar(scalar, todo); - } - } - } - } else if (cur instanceof RuntimeScalar scalar) { - visitScalar(scalar, todo); - } - } - } - - private void bfs(java.util.ArrayDeque todo, boolean walkCaptures) { - while (!todo.isEmpty()) { - RuntimeBase cur = todo.removeFirst(); - // Phase D-W2 (perf): skip RuntimeStash. A stash's `elements` - // is a HashSpecialVariable that eagerly copies all global - // keys via entrySet() — O(globals) per visit, quadratic - // in number of packages × per-flush gate fires. - // Stash entries (the per-package code/var/array/hash) are - // already directly seeded from GlobalVariable.global*Refs, - // so iterating them here is redundant work. - if (cur instanceof RuntimeStash) { - continue; - } - if (cur instanceof RuntimeHash h) { - if (h.elements instanceof HashSpecialVariable) { - continue; - } - if (h.elements instanceof TieHash tieHash) { - visitScalar(tieHash.getSelf(), todo); - } - for (RuntimeScalar v : h.elements.values()) { - addReachable(v, todo); - visitScalar(v, todo); - } - } else if (cur instanceof RuntimeArray a) { - if (a.elements instanceof TieArray tieArray) { - visitScalar(tieArray.getSelf(), todo); - } - // This broader weak-reference walk can also run during a - // child thread's teardown while another thread mutates a - // shared array. Never expose ArrayList's fail-fast iterator - // to concurrent Perl updates. - for (RuntimeScalar v : a.elements.toArray(RuntimeScalar[]::new)) { - recordWeakArraySlotWitness(a, v); - addReachable(v, todo); - visitScalar(v, todo); - } - } else if (cur instanceof RuntimeCode code) { - if (!hasWalkableCodeEdges(code, walkCaptures)) { - continue; - } - visitCodePadConstants(code, todo); - visitCodeStateVariables(code, todo); - // Phase 2 normally keeps closure captures opaque to avoid - // over-rescuing DBIC objects through internal callbacks. - // Exception: Sub::Defer/Sub::Quote deferred wrappers keep a - // weak backref to the CODE object itself. If such a CODE ref - // is reachable through package metadata (not a direct stash - // entry), its captured info array is a real strong Perl edge - // and must survive the weak sweep. - if (walkCaptures || WeakRefRegistry.hasWeakRefsTo(code)) { - visitCodeCaptures(code, todo); - } else if (code.capturedAggregates != null) { - // Explicit aggregate capture entries are semantic owner - // edges even when conservative scalar/reflection capture - // walking is disabled. Unlike retired interpreter capture - // metadata, this list is cleared by releaseCaptures(). - for (RuntimeBase aggregate : code.capturedAggregates) { - addReachable(aggregate, todo); - } - } - } else if (cur instanceof RuntimeRegex regex) { - for (RuntimeCode callback : regex.executableCallbackCodes()) { - addReachable(callback, todo); - visitCodeStateVariables(callback, todo); - visitCodeCaptures(callback, todo); - } - } else if (cur instanceof RuntimeScalar s) { - visitScalar(s, todo); - } - } - } - - private void visitCodePadConstants(RuntimeCode code, - java.util.ArrayDeque todo) { - if (code.padConstants == null) return; - for (RuntimeBase constant : code.padConstants) { - addReachable(constant, todo); - } - } - - /** - * Global CODE slots themselves are roots, but most named subs have no - * object-valued pad, state, or capture edges. Keep those CODE refs in the - * returned reachable set without sending them through the BFS queue. - */ - private void addGlobalCodeRoot(RuntimeScalar slot, java.util.ArrayDeque todo) { - if (slot != null - && (slot.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && slot.value instanceof RuntimeCode code) { - if (hasWalkableCodeEdges(code, /*walkCaptures=*/ true) && reachable.add(code)) { - todo.addLast(code); - } - return; - } - visitScalar(slot, todo); - } - - static boolean hasWalkableCodeEdges(RuntimeCode code, boolean walkCaptures) { - if ((code.padConstants != null && code.padConstants.length != 0) - || !code.stateVariable.isEmpty() - || !code.stateArray.isEmpty() - || !code.stateHash.isEmpty()) { - return true; - } - if (!walkCaptures && !WeakRefRegistry.hasWeakRefsTo(code)) return false; - if ((code.capturedScalars != null && code.capturedScalars.length != 0) - || (code.capturedAggregates != null && code.capturedAggregates.length != 0) - || (code.closedOverVariables != null && !code.closedOverVariables.isEmpty())) { - return true; - } - if (!code.captureFieldsRecorded) { - Object closureObject = code.codeObject != null ? code.codeObject : code.subroutine; - if (closureObject != null) { - ReflectiveCaptureFields fields = REFLECTIVE_CAPTURE_FIELDS.get(closureObject.getClass()); - if (fields.scalars().length != 0 || fields.bases().length != 0) return true; - } - } - return code instanceof org.perlonjava.backend.bytecode.InterpretedCode interpreted - && interpreted.capturedVars != null - && interpreted.capturedVars.length != 0; - } - - /** - * Terminal installed CODE refs remain roots, but storing each one in the - * per-sweep identity set is redundant. Expose them through a union view so - * ordinary reachability checks still see the exact complete root set. - */ - private Set withInstalledGlobalCodeRoots() { - Set installedCodes = GlobalVariable.installedGlobalCodeRefsView(); - if (installedCodes.isEmpty()) return reachable; - return new AbstractSet<>() { - @Override - public boolean contains(Object value) { - return reachable.contains(value) - || (value instanceof RuntimeCode code && installedCodes.contains(code)); - } - - @Override - public int size() { - int size = reachable.size(); - for (RuntimeCode code : installedCodes) { - if (!reachable.contains(code)) size++; - } - return size; - } - - @Override - public Iterator iterator() { - Iterator reached = reachable.iterator(); - Iterator installed = installedCodes.iterator(); - return new Iterator<>() { - private RuntimeBase next; - private boolean hasNext; - - @Override - public boolean hasNext() { - if (hasNext) return true; - if (reached.hasNext()) return true; - while (installed.hasNext()) { - RuntimeCode candidate = installed.next(); - if (!reachable.contains(candidate)) { - next = candidate; - hasNext = true; - return true; - } - } - return false; - } - - @Override - public RuntimeBase next() { - if (reached.hasNext()) return reached.next(); - if (!hasNext()) throw new NoSuchElementException(); - RuntimeBase result = next; - next = null; - hasNext = false; - return result; - } - }; - } - }; - } - - /** - * Follow persistent {@code state} storage owned by a subroutine. - * - *

    State variables are semantic strong Perl roots for as long as their - * owning CODE remains installed. They are not closure-capture metadata, - * so they must be traversed even when capture walking is deliberately - * disabled. Omitting these edges lets a weak-reference sweep destroy a - * still-live state singleton, as used by Mojo::IOLoop.

    - */ - private void visitCodeStateVariables(RuntimeCode code, - java.util.ArrayDeque todo) { - for (RuntimeScalar state : code.stateVariable.values()) { - addReachable(state, todo); - visitScalar(state, todo); - } - for (RuntimeArray state : code.stateArray.values()) { - addReachable(state, todo); - } - for (RuntimeHash state : code.stateHash.values()) { - addReachable(state, todo); - } - } - - private void visitCodeCaptures(RuntimeCode code, - java.util.ArrayDeque todo) { - if (code.capturedScalars != null) { - for (RuntimeScalar cap : code.capturedScalars) { - addReachable(cap, todo); - visitScalar(cap, todo); - } - } - if (code.capturedAggregates != null) { - for (RuntimeBase cap : code.capturedAggregates) addReachable(cap, todo); - } - visitReflectiveCodeScalars(code, cap -> { - addReachable(cap, todo); - visitScalar(cap, todo); - }); - visitReflectiveCodeBases(code, base -> { - if (weakWitnessTargets != null - && code.captureFieldsRecorded - && GlobalVariable.installedGlobalCodeRefsView().contains(code) - && base instanceof RuntimeArray array - && isSupportedWitnessArray(array)) { - weakWitnessCaptureRoots.putIfAbsent(array, code); - } - addReachable(base, todo); - }); - // InterpretedCode.capturedVars is immutable execution-frame metadata. - // Captured entries can remain there after their lexical lifetime has - // ended and releaseCaptures has removed them from the semantic owner - // lists. Only capturedScalars/capturedAggregates describe live owners. - } - - private void recordWeakArraySlotWitness(RuntimeArray array, RuntimeScalar ownerScalar) { - if (weakWitnessTargets == null || ownerScalar == null - || !isSupportedWitnessArray(array) - || WeakRefRegistry.isweak(ownerScalar) - || (ownerScalar.type & RuntimeScalarType.REFERENCE_BIT) == 0 - || !(ownerScalar.value instanceof RuntimeBase referent) - || !weakWitnessTargets.contains(referent)) { - return; - } - RuntimeCode rootCode = weakWitnessCaptureRoots.get(array); - if (rootCode != null) { - discoveredWeakRootWitnesses.putIfAbsent(referent, - new WeakRootWitness(new WeakReference<>(rootCode), - new WeakReference<>(array), new WeakReference<>(ownerScalar), - new WeakReference<>(referent), false)); - } - } - - private void recordWeakLiveLexicalScalarWitness(RuntimeScalar ownerScalar) { - if (weakWitnessTargets == null || ownerScalar.scopeExited - || (ownerScalar.type & RuntimeScalarType.REFERENCE_BIT) == 0 - || !(ownerScalar.value instanceof RuntimeBase referent) - || (!weakWitnessTargets.contains(referent) - && !(referent instanceof RuntimeCode))) { - return; - } - if (!weakWitnessTargets.contains(referent) - && !discoveredWeakRootWitnesses.containsKey(referent) - && discoveredLexicalCodeWitnesses >= 128) { - return; - } - if (discoveredWeakRootWitnesses.putIfAbsent(referent, - new WeakRootWitness(new WeakReference<>(null), - new WeakReference<>(null), new WeakReference<>(ownerScalar), - new WeakReference<>(referent), true)) == null - && referent instanceof RuntimeCode - && !weakWitnessTargets.contains(referent)) { - discoveredLexicalCodeWitnesses++; - } - } - - private static boolean isSupportedWitnessArray(RuntimeArray array) { - return array != null - && !array.threadShared - && array.type != RuntimeArray.TIED_ARRAY - && !(array.elements instanceof TieArray); - } - - /** - * Diagnostic: walk from roots and return the first path found to the - * specified target object. Returns null if unreachable. Used for - * debugging DBIC 52leaks-style issues where an object that should be - * collectible is found reachable. - *

    - * When {@code skipLexicalSeeds} is true, omits the ScalarRefRegistry - * seed loop so the path is forced through Perl-semantic roots - * (globals, stashes, rescued objects) — useful for understanding - * what data structure keeps an object alive at the Perl level. - */ - public static java.util.List findPathTo(RuntimeBase target) { - return findPathTo(target, false, true); - } - - public static java.util.List findPathTo(RuntimeBase target, boolean skipLexicalSeeds) { - return findPathTo(target, skipLexicalSeeds, true); - } - - private static java.util.List findPathTo( - RuntimeBase target, boolean skipLexicalSeeds, boolean forceJvmGc) { - java.util.IdentityHashMap howReached = new java.util.IdentityHashMap<>(); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - // Seed from roots with labels - for (Map.Entry e : GlobalVariable.scalarSlots().entrySet()) { - seedPath(e.getValue(), "$" + e.getKey(), howReached, todo); - } - for (Map.Entry e : GlobalVariable.globalArrays.entrySet()) { - if (isNonOwningDebugArgsArray(e.getKey())) continue; - if (howReached.putIfAbsent(e.getValue(), "@" + e.getKey()) == null) todo.add(e.getValue()); - } - for (Map.Entry e : GlobalVariable.globalHashes.entrySet()) { - if (howReached.putIfAbsent(e.getValue(), "%" + e.getKey()) == null) todo.add(e.getValue()); - } - for (Map.Entry e : GlobalVariable.globalCodeRefs.entrySet()) { - seedPath(e.getValue(), "&" + e.getKey(), howReached, todo); - } - int activeCodeIdx = 0; - for (RuntimeCode active : PerlRuntime.current().executionState().activeCodeStack) { - String label = ""; - if (howReached.putIfAbsent(active, label) == null) todo.add(active); - } - int argsFrameIdx = 0; - for (List args : RuntimeCode.snapshotPristineArgsStack()) { - for (RuntimeScalar arg : args) { - seedPath(arg, "", howReached, todo); - } - argsFrameIdx++; - } - int rescuedIdx = 0; - for (RuntimeBase rescued : DestroyDispatch.snapshotRescuedForWalk()) { - if (howReached.putIfAbsent(rescued, "") == null) { - todo.add(rescued); - } - } - // Phase I: seed from WarningBitsRegistry.callerHintHashStack — - // %^H snapshots can preserve scalars from earlier scopes and are - // NOT accounted for by Perl-level walker roots. - int hhIdx = 0; - for (RuntimeScalar sc : org.perlonjava.runtime.WarningBitsRegistry.snapshotHintHashStackScalars()) { - seedPath(sc, "", howReached, todo); - } - int suspendedIdx = 0; - for (RuntimeBase suspended : MortalList.snapshotSuspendedRoots()) { - if (howReached.putIfAbsent(suspended, "") == null) { - todo.add(suspended); - } - } - // Phase B1: seed from ScalarRefRegistry (same as walk()) so the - // trace matches what sweepWeakRefs sees. - // Phase I: force GC before snapshotting so stale - // (already-Java-unreachable) entries don't produce misleading - // "live-lexical" paths in diagnostic traces. - // skipLexicalSeeds=true omits this — produces a path that goes - // through Perl-semantic data (globals/stash/rescued) only. - int scIdx = 0; - if (!skipLexicalSeeds) { - java.util.List lexicalScalars = forceJvmGc - ? ScalarRefRegistry.forceGcAndSnapshot() - : ScalarRefRegistry.snapshot(); - for (RuntimeScalar sc : lexicalScalars) { - if (sc == null) continue; - if (sc.captureCount > 0) continue; - if (WeakRefRegistry.isweak(sc)) continue; - if (MortalList.isDeferredCapture(sc)) continue; - if (!MyVarCleanupStack.isLive(sc)) continue; - if ((sc.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && sc.value instanceof RuntimeBase b) { - String label = ""; - if (howReached.putIfAbsent(b, label) == null) { - todo.add(b); - } - } - } - int liveVarIdx = 0; - for (Object liveVar : MyVarCleanupStack.snapshotLiveVars()) { - String label = ""; - if (liveVar instanceof RuntimeScalar sc) { - seedPath(sc, label, howReached, todo); - } else if (liveVar instanceof RuntimeBase rb) { - if (howReached.putIfAbsent(rb, label) == null) todo.add(rb); - } - } - int argsIdx = 0; - for (RuntimeArray args : RuntimeCode.snapshotArgsStack()) { - if (howReached.putIfAbsent(args, "") == null) { - todo.add(args); - } - } - int tempIdx = 0; - for (RuntimeBase tempRoot : MortalList.snapshotTemporaryRoots()) { - if (howReached.putIfAbsent(tempRoot, "") == null) { - todo.add(tempRoot); - } - } - } - while (!todo.isEmpty()) { - RuntimeBase cur = todo.removeFirst(); - String curPath = howReached.get(cur); - if (cur == target) { - java.util.List r = new java.util.ArrayList<>(); - r.add(curPath); - return r; - } - if (cur instanceof RuntimeHash h) { - if (h.elements instanceof TieHash tieHash) { - visitScalarPath(tieHash.getSelf(), curPath + "", howReached, todo); - } - for (Map.Entry ent : h.elements.entrySet()) { - visitScalarPath(ent.getValue(), curPath + "{" + ent.getKey() + "}", howReached, todo); - } - } else if (cur instanceof RuntimeArray a) { - int idx = 0; - if (a.elements instanceof TieArray tieArray) { - visitScalarPath(tieArray.getSelf(), curPath + "", howReached, todo); - } - for (RuntimeScalar v : a.elements) { - visitScalarPath(v, curPath + "[" + (idx++) + "]", howReached, todo); - } - } else if (cur instanceof RuntimeCode code) { - if (code.closedOverVariables != null) { - for (Map.Entry captured - : code.closedOverVariables.entrySet()) { - String path = curPath + ""; - RuntimeBase value = captured.getValue(); - if (value instanceof RuntimeScalar scalar) { - visitScalarPath(scalar, path, howReached, todo); - } else if (howReached.putIfAbsent(value, path) == null) { - todo.add(value); - } - } - } - int stateIdx = 0; - for (Map.Entry state : code.stateVariable.entrySet()) { - visitScalarPath(state.getValue(), curPath + "", howReached, todo); - } - for (Map.Entry state : code.stateArray.entrySet()) { - String path = curPath + ""; - if (howReached.putIfAbsent(state.getValue(), path) == null) todo.add(state.getValue()); - } - for (Map.Entry state : code.stateHash.entrySet()) { - String path = curPath + ""; - if (howReached.putIfAbsent(state.getValue(), path) == null) todo.add(state.getValue()); - } - // Phase I: mirror the main walker — follow closure captures - // so findPathTo traces through the same graph as sweepWeakRefs. - if (code.capturedScalars != null) { - int i = 0; - String name = code.packageName == null ? "?" : code.packageName; - String sub = code.subName == null ? "(anon)" : code.subName; - for (RuntimeScalar cap : code.capturedScalars) { - visitScalarPath(cap, curPath + "", howReached, todo); - } - } - if (code.capturedAggregates != null) { - int i = 0; - for (RuntimeBase cap : code.capturedAggregates) { - String path = curPath + ""; - if (howReached.putIfAbsent(cap, path) == null) todo.add(cap); - } - } - String name = code.packageName == null ? "?" : code.packageName; - String sub = code.subName == null ? "(anon)" : code.subName; - final int[] reflectiveIdx = {0}; - visitReflectiveCodeScalars(code, cap -> - visitScalarPath(cap, curPath + "", howReached, todo)); - final int[] reflectiveBaseIdx = {0}; - visitReflectiveCodeBases(code, captured -> { - String path = curPath + ""; - if (howReached.putIfAbsent(captured, path) == null) todo.add(captured); - }); - } else if (cur instanceof RuntimeScalar scalar - && !WeakRefRegistry.isweak(scalar) - && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && scalar.value instanceof RuntimeBase referent) { - if (howReached.putIfAbsent(referent, curPath + "->") == null) { - todo.add(referent); - } - } else if (cur instanceof RuntimeRegex regex) { - int callbackIdx = 0; - for (RuntimeCode callback : regex.executableCallbackCodes()) { - String path = curPath + ""; - if (howReached.putIfAbsent(callback, path) == null) todo.add(callback); - } - } - } - return null; - } - - private static void seedPath(RuntimeScalar s, String label, - java.util.IdentityHashMap howReached, - java.util.ArrayDeque todo) { - if (s == null) return; - if (WeakRefRegistry.isweak(s)) return; - if (howReached.putIfAbsent(s, label) == null) todo.add(s); - } - - private static void visitScalarPath(RuntimeScalar s, String path, - java.util.IdentityHashMap howReached, - java.util.ArrayDeque todo) { - if (s == null) return; - if (WeakRefRegistry.isweak(s)) return; - if (howReached.putIfAbsent(s, path) == null) todo.add(s); - } - - private void visitScalar(RuntimeScalar s, java.util.ArrayDeque todo) { - if (s == null) return; - // Weak refs are not counted as strong edges in reachability - if (WeakRefRegistry.isweak(s)) return; - if ((s.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && s.value instanceof RuntimeBase b) { - addReachable(b, todo); - } - } - - private void addReachable(RuntimeBase b, java.util.ArrayDeque todo) { - if (b == null) return; - if (reachable.add(b)) { - todo.addLast(b); - } - } - - /** - * Return true if {@code target} can reach itself through strong Perl - * references. Weak scalars are ignored. This models Perl's refcount - * behavior for self-cycles: they remain alive even when no package/global - * root points at them. - */ - public static boolean hasStrongCycle(RuntimeBase target) { - if (target == null) return false; - final int MAX_VISITS = 50_000; - Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - - if (enqueueStrongEdges(target, target, seen, todo)) { - return true; - } - - int visits = 0; - while (!todo.isEmpty() && visits < MAX_VISITS) { - RuntimeBase cur = todo.removeFirst(); - visits++; - if (enqueueStrongEdges(cur, target, seen, todo)) { - return true; - } - } - return false; - } - - /** - * Return whether {@code target} is strongly reachable from an explicit - * set of roots. Runtime snapshots use this before the child entry CODE is - * installed on an execution stack: its captures are already real Perl - * owners, but the ordinary live-root queries cannot see them yet. - */ - static boolean isReachableFromStrongRoots( - RuntimeBase target, java.util.List roots) { - if (target == null || roots == null || roots.isEmpty()) return false; - final int MAX_VISITS = 50_000; - Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - for (RuntimeBase root : roots) { - if (root == null) continue; - if (root == target) return true; - if (seen.add(root)) todo.addLast(root); - } - int visits = 0; - while (!todo.isEmpty() && visits++ < MAX_VISITS) { - if (enqueueStrongEdges(todo.removeFirst(), target, seen, todo)) { - return true; - } - } - return false; - } - - private static boolean enqueueStrongEdges(RuntimeBase cur, RuntimeBase target, - Set seen, - java.util.ArrayDeque todo) { - if (cur instanceof RuntimeHash h) { - // Shared hashes are backed by Collections.synchronizedMap. Its - // iterators still require the caller to hold the map monitor; - // otherwise a concurrently running Perl thread can invalidate a - // destruction-time reachability walk. - java.util.List values; - if (h.threadShared) { - synchronized (h.elements) { - values = new ArrayList<>(h.elements.values()); - } - } else { - values = h.elements.values().stream().toList(); - } - for (RuntimeScalar v : values) { - if (enqueueStrongScalar(v, target, seen, todo)) return true; - } - } else if (cur instanceof RuntimeArray a) { - // See the hash case: iterating a synchronized list without - // taking its monitor is explicitly unsafe. - java.util.List values; - if (a.threadShared) { - synchronized (a.elements) { - values = new ArrayList<>(a.elements); - } - } else { - values = a.elements; - } - for (RuntimeScalar v : values) { - if (enqueueStrongScalar(v, target, seen, todo)) return true; - } - } else if (cur instanceof RuntimeCode code) { - for (RuntimeScalar state : code.stateVariable.values()) { - if (enqueueStrongScalar(state, target, seen, todo)) return true; - } - for (RuntimeArray state : code.stateArray.values()) { - if (state == target) return true; - if (seen.add(state)) todo.addLast(state); - } - for (RuntimeHash state : code.stateHash.values()) { - if (state == target) return true; - if (seen.add(state)) todo.addLast(state); - } - if (code.capturedScalars != null) { - for (RuntimeScalar cap : code.capturedScalars) { - if (enqueueStrongScalar(cap, target, seen, todo)) return true; - } - } - if (code.capturedAggregates != null) { - for (RuntimeBase cap : code.capturedAggregates) { - if (cap == null) continue; - if (cap == target) return true; - if (seen.add(cap)) todo.addLast(cap); - } - } - // Do not traverse InterpretedCode.capturedVars here. It is retained - // for execution after capture owners have been retired; walking it - // would turn dead pad metadata into a strong Perl reference. - Object closureObject = code.codeObject != null ? code.codeObject : code.subroutine; - if (closureObject != null) { - try { - for (java.lang.reflect.Field field : closureObject.getClass().getDeclaredFields()) { - if (field.getType() == RuntimeScalar.class && !"__SUB__".equals(field.getName())) { - RuntimeScalar cap = (RuntimeScalar) field.get(closureObject); - if (enqueueStrongScalar(cap, target, seen, todo)) return true; - } - } - } catch (IllegalAccessException ignored) { - // Generated closure fields are public. If another - // implementation denies access, fall back to the explicit - // capturedScalars / capturedVars metadata above. - } - } - } else if (cur instanceof RuntimeRegex regex) { - for (RuntimeCode callback : regex.executableCallbackCodes()) { - if (callback == target) return true; - if (seen.add(callback)) todo.addLast(callback); - } - } else if (cur instanceof RuntimeScalar s) { - return enqueueStrongScalar(s, target, seen, todo); - } - return false; - } - - private record BoundedArrayCycleResult(boolean cycle, boolean complete, int edges) {} - - /** - * Cheap cycle proof for the witness fast path. Unsupported edge forms and - * budget exhaustion are inconclusive and require the ordinary full walk. - */ - private static BoundedArrayCycleResult hasBoundedStrongArrayCycle( - RuntimeBase target, int maxEdges) { - if (!isSupportedCycleContainer(target)) { - return new BoundedArrayCycleResult(false, false, 0); - } - Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - seen.add(target); - todo.add(target); - int edges = 0; - while (!todo.isEmpty()) { - RuntimeBase current = todo.removeFirst(); - if (current instanceof RuntimeScalar scalar) { - if (++edges > maxEdges) { - return new BoundedArrayCycleResult(false, false, edges); - } - if (followBoundedCycleScalar(scalar, target, seen, todo)) { - return new BoundedArrayCycleResult(true, true, edges); - } - continue; - } - if (current instanceof RuntimeCode code) { - for (RuntimeScalar state : code.stateVariable.values()) { - if (++edges > maxEdges) return new BoundedArrayCycleResult(false, false, edges); - if (followBoundedCycleScalar(state, target, seen, todo)) { - return new BoundedArrayCycleResult(true, true, edges); - } - } - for (RuntimeArray state : code.stateArray.values()) { - if (++edges > maxEdges) return new BoundedArrayCycleResult(false, false, edges); - if (followBoundedCycleBase(state, target, seen, todo)) { - return new BoundedArrayCycleResult(true, true, edges); - } - } - for (RuntimeHash state : code.stateHash.values()) { - if (++edges > maxEdges) return new BoundedArrayCycleResult(false, false, edges); - if (followBoundedCycleBase(state, target, seen, todo)) { - return new BoundedArrayCycleResult(true, true, edges); - } - } - if (code.capturedScalars != null) { - for (RuntimeScalar capture : code.capturedScalars) { - if (++edges > maxEdges) return new BoundedArrayCycleResult(false, false, edges); - if (followBoundedCycleScalar(capture, target, seen, todo)) { - return new BoundedArrayCycleResult(true, true, edges); - } - } - } - if (code.captureFieldsRecorded && code.capturedAggregates != null) { - for (RuntimeBase capture : code.capturedAggregates) { - if (++edges > maxEdges) return new BoundedArrayCycleResult(false, false, edges); - if (followBoundedCycleBase(capture, target, seen, todo)) { - return new BoundedArrayCycleResult(true, true, edges); - } - } - } - if (code instanceof org.perlonjava.backend.bytecode.InterpretedCode interpreted - && interpreted.capturedVars != null) { - for (RuntimeBase capture : interpreted.capturedVars) { - if (++edges > maxEdges) return new BoundedArrayCycleResult(false, false, edges); - boolean found = capture instanceof RuntimeScalar scalar - ? followBoundedCycleScalar(scalar, target, seen, todo) - : followBoundedCycleBase(capture, target, seen, todo); - if (found) return new BoundedArrayCycleResult(true, true, edges); - } - } - continue; - } - Iterable slots; - if (current instanceof RuntimeArray array) { - if (!isSupportedWitnessArray(array)) { - return new BoundedArrayCycleResult(false, false, edges); - } - slots = array.elements; - } else if (current instanceof RuntimeHash hash) { - if (!isSupportedCycleContainer(hash)) { - return new BoundedArrayCycleResult(false, false, edges); - } - slots = hash.elements.values(); - } else { - return new BoundedArrayCycleResult(false, false, edges); - } - for (RuntimeScalar slot : slots) { - if (++edges > maxEdges) { - return new BoundedArrayCycleResult(false, false, edges); - } - if (followBoundedCycleScalar(slot, target, seen, todo)) { - return new BoundedArrayCycleResult(true, true, edges); - } - } - } - return new BoundedArrayCycleResult(false, true, edges); - } - - private static boolean followBoundedCycleScalar( - RuntimeScalar scalar, RuntimeBase target, Set seen, - java.util.ArrayDeque todo) { - if (scalar == null || WeakRefRegistry.isweak(scalar) - || (scalar.type & RuntimeScalarType.REFERENCE_BIT) == 0 - || !(scalar.value instanceof RuntimeBase child)) return false; - return followBoundedCycleBase(child, target, seen, todo); - } - - private static boolean followBoundedCycleBase( - RuntimeBase child, RuntimeBase target, Set seen, - java.util.ArrayDeque todo) { - if (child == null) return false; - if (child == target) return true; - if (isSupportedCycleNode(child) && seen.add(child)) todo.addLast(child); - return false; - } - - private static boolean isSupportedCycleContainer(RuntimeBase value) { - if (value instanceof RuntimeArray array) return isSupportedWitnessArray(array); - if (value instanceof RuntimeHash hash) { - return !hash.threadShared - && hash.type != RuntimeHash.TIED_HASH - && !(hash.elements instanceof TieHash) - && !(hash.elements instanceof HashSpecialVariable); - } - return false; - } - - private static boolean isSupportedCycleNode(RuntimeBase value) { - if (value instanceof RuntimeScalar scalar) return !WeakRefRegistry.isweak(scalar); - return value instanceof RuntimeCode || isSupportedCycleContainer(value); - } - - /** - * True when a CODE cycle strongly retains an object that has an external - * weak reference. Perl refcounting keeps this graph alive; AnyEvent uses - * it for weak event-loop registries whose watcher callbacks own themselves - * through captured state. - */ - public static boolean strongCycleRetainsWeakReferent(RuntimeCode code) { - if (code == null || !hasStrongCycle(code)) return false; - final int MAX_VISITS = 50_000; - Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - seen.add(code); - todo.addLast(code); - int visits = 0; - while (!todo.isEmpty() && visits++ < MAX_VISITS) { - RuntimeBase current = todo.removeFirst(); - if (WeakRefRegistry.hasWeakRefsTo(current)) return true; - enqueueStrongEdges(current, null, seen, todo); - } - return false; - } - - private static boolean enqueueStrongScalar(RuntimeScalar s, RuntimeBase target, - Set seen, - java.util.ArrayDeque todo) { - if (s == null || WeakRefRegistry.isweak(s)) return false; - if ((s.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && s.value instanceof RuntimeBase b) { - if (b == target) return true; - if (seen.add(b)) todo.addLast(b); - } - return false; - } - - /** - * Lightweight per-object reachability query: walk from Perl-visible - * roots and return {@code true} as soon as {@code target} is found, - * without enumerating the full live set. - *

    - * Used by {@link MortalList#flush} to avoid prematurely firing - * DESTROY on a blessed object whose selective refCount dipped to - * 0 transiently while the object is still held by a container the - * walker can see (globals, hash/array elements registered in - * {@link ScalarRefRegistry}). Concrete failure mode without this - * check: Class::MOP self-bootstrap weakens ~10 attribute back-refs - * to a single metaclass; refCount drift under heavy reference - * shuffling drops the count to 0; flush fires DESTROY; weak refs - * clear; bootstrap dies. - *

    - * BFS with a hard step cap so the cost stays bounded (the worst - * case is the same nodes-visited bound as a full sweep, which is - * fine because flush is already O(pending) per call). - * - * @param target the object to check for reachability - * @return true iff target is reachable from roots through strong refs - */ - public static boolean isReachableFromRoots(RuntimeBase target) { - return isReachableFromRoots(target, false); - } - - /** - * Collect the same bounded root graph as {@link #isReachableFromRoots}, - * once for all weak referents in a mortal drain. The existing query's - * target-specific early returns become identity membership in this set. - * Node and edge budgets bound both wide and deep root graphs; an incomplete - * snapshot conservatively treats unresolved targets as reachable. - */ - record RootReachabilitySnapshot(Set reachable, boolean complete, - int edgesVisited) { - boolean isReachable(RuntimeBase target) { - // A node- or edge-cap hit cannot prove an unresolved target dead. - return !complete || reachable.contains(target); - } - } - - private static final class RootWalkBudget { - private final int maxEdges; - private int edgesVisited; - private boolean complete = true; - - private RootWalkBudget(int maxEdges) { - this.maxEdges = maxEdges; - } - - private boolean visitEdge() { - if (edgesVisited >= maxEdges) { - complete = false; - return false; - } - edgesVisited++; - return true; - } - } - - static final int MAX_ROOT_SNAPSHOT_EDGES = 50_000; - static final int MAX_ROOT_SNAPSHOT_VISITS = 50_000; - - static Set reachableFromRootsSnapshot() { - return reachableFromRootsSnapshotWithStatus().reachable(); - } - - static RootReachabilitySnapshot reachableFromRootsSnapshotWithStatus() { - return reachableFromRootsSnapshotWithStatus(true); - } - - /** - * Collect the bounded root graph needed to answer reachability for - * unblessed aggregates. Installed CODE slot identities cannot own an - * aggregate by themselves; their captured values are followed separately - * through the cached CODE roots with capture edges. Omitting terminal CODE - * slots avoids seeding every installed subroutine during aggregate cleanup. - */ - static RootReachabilitySnapshot unblessedAggregateRootsSnapshotWithStatus() { - return reachableFromRootsSnapshotWithStatus(false); - } - - private static RootReachabilitySnapshot reachableFromRootsSnapshotWithStatus( - boolean includeInstalledCodeSlots) { - ReachabilityQueryStats stats = MortalList.activeReachabilityQueryStats(); - if (stats != null) stats.snapshotsBuilt++; - final int maxVisits = MAX_ROOT_SNAPSHOT_VISITS; - RootWalkBudget budget = new RootWalkBudget(MAX_ROOT_SNAPSHOT_EDGES); - Set seen = Collections.newSetFromMap(new IdentityHashMap<>(512)); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - - rootScan: { - if (includeInstalledCodeSlots) { - for (RuntimeScalar codeRef : GlobalVariable.globalCodeRefValuesView()) { - if (!budget.visitEdge()) break rootScan; - seedTarget(codeRef, null, seen, todo, stats); - } - } - for (RuntimeScalar codeRef : GlobalVariable.globalCodeRefEdgeRootsView()) { - if (codeRef != null && codeRef.value instanceof RuntimeCode code) { - if (stats != null) stats.globalCodeCaptureRootsWalked++; - followGlobalCodeCaptures(code, null, seen, todo, budget); - if (!budget.complete) break rootScan; - } - } - for (RuntimeScalar scalar : GlobalVariable.globalVariableValuesView()) { - if (!budget.visitEdge()) break rootScan; - seedTarget(scalar, null, seen, todo, stats); - } - for (Map.Entry e : GlobalVariable.globalArrayEntriesView()) { - if (!budget.visitEdge()) break rootScan; - if (!isNonOwningDebugArgsArray(e.getKey()) && e.getValue() != null) { - if (seen.add(e.getValue())) { - todo.addLast(e.getValue()); - if (stats != null) stats.rootsSeeded++; - } - } - } - for (RuntimeHash hash : GlobalVariable.globalHashValuesView()) { - if (!budget.visitEdge()) break rootScan; - if (hash != null && seen.add(hash)) { - todo.addLast(hash); - if (stats != null) stats.rootsSeeded++; - } - } - for (RuntimeScalar scalar : ScalarRefRegistry.snapshot()) { - if (!budget.visitEdge()) break rootScan; - if (scalar == null || scalar.captureCount > 0 || WeakRefRegistry.isweak(scalar) - || (!MyVarCleanupStack.isLive(scalar) && !scalar.refCountOwned) - || scalar.scopeExited) continue; - seedTarget(scalar, null, seen, todo, stats); - } - for (Object liveVar : MyVarCleanupStack.snapshotLiveVars()) { - if (!budget.visitEdge()) break rootScan; - if (liveVar instanceof RuntimeScalar scalar) { - if (seen.add(scalar) && stats != null) stats.rootsSeeded++; - seedTarget(scalar, null, seen, todo, stats); - } else if (liveVar instanceof RuntimeBase base && seen.add(base)) { - todo.addLast(base); - if (stats != null) stats.rootsSeeded++; - } - } - for (Object registeredVar : MyVarCleanupStack.snapshotRegisteredVars()) { - if (!budget.visitEdge()) break rootScan; - if (registeredVar instanceof RuntimeScalar scalar - && scalar.type == RuntimeScalarType.REGEX - && !scalar.scopeExited - && !WeakRefRegistry.isweak(scalar)) { - seedTarget(scalar, null, seen, todo, stats); - } - } - for (RuntimeBase rescued : DestroyDispatch.snapshotRescuedForWalk()) { - if (!budget.visitEdge()) break rootScan; - if (seen.add(rescued)) { - todo.addLast(rescued); - if (stats != null) stats.rootsSeeded++; - } - } - for (RuntimeBase ownerReferent : PerlRuntime.snapshotOwnerSlotReferents()) { - if (!budget.visitEdge()) break rootScan; - if (seen.add(ownerReferent)) { - todo.addLast(ownerReferent); - if (stats != null) stats.rootsSeeded++; - } - } - } - - int visits = 0; - walk: while (!todo.isEmpty() && visits < maxVisits) { - visits++; - RuntimeBase cur = todo.removeFirst(); - if (stats != null) stats.nodesVisited++; - if (cur instanceof RuntimeStash) continue; - if (cur instanceof RuntimeHash hash) { - if (hash.elements instanceof TieHash tieHash) { - if (!budget.visitEdge()) break walk; - if (stats != null) stats.edgesInspected++; - followScalar(tieHash.getSelf(), null, seen, todo); - } - for (RuntimeScalar value : hash.elements.values()) { - if (!budget.visitEdge()) break walk; - if (stats != null) stats.edgesInspected++; - followScalar(value, null, seen, todo); - } - } else if (cur instanceof RuntimeArray array) { - for (RuntimeScalar value : array.elements) { - if (!budget.visitEdge()) break walk; - if (stats != null) stats.edgesInspected++; - followScalar(value, null, seen, todo); - } - } else if (cur instanceof RuntimeRegex regex) { - for (RuntimeCode callback : regex.executableCallbackCodes()) { - if (!budget.visitEdge()) break walk; - if (stats != null) stats.edgesInspected++; - followGlobalCodeCaptures(callback, null, seen, todo, budget); - } - } - } - return new RootReachabilitySnapshot(seen, budget.complete && todo.isEmpty(), - budget.edgesVisited); - } - - /** - * Lightweight fallback for {@link WeakRefRegistry#weaken}: check whether a - * target is still reachable from a JVM-live scalar even when that scalar is - * not a counted owner. Test2::Tools::Refcount weakens a local probe copy - * before reading B::REFCNT; if selective refcounting has drifted to zero, - * clearing every weak callback at that point is premature while the caller's - * lexical still points at the object. - * - *

    This is deliberately separate from the normal sweep/root query. It - * force-prunes stale weak-map keys first, only follows non-weak scalars, and - * is used only at the immediate weaken() zero-count decision.

    - */ - public static boolean isReachableFromLiveScalarRegistry(RuntimeBase target) { - return isReachableFromLiveScalarRegistry(target, ScalarRefRegistry.forceGcAndSnapshot()); - } - - public static boolean isReachableFromLiveCodeCaptures(RuntimeBase target) { - if (target == null) return false; - Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - for (Object liveVar : MyVarCleanupStack.snapshotLiveVars()) { - if (!(liveVar instanceof RuntimeScalar sc)) continue; - if (WeakRefRegistry.isweak(sc)) continue; - if (sc.value instanceof RuntimeCode code - && followGlobalCodeCaptures(code, target, seen, todo)) return true; - } - // A closure CODE scalar can outlive the lexical register that created - // it while the caller is suspended. ScalarRefRegistry retains a weak - // key for such reference-holding scalars; use those live keys as - // additional code roots when the cleanup-stack snapshot has detached - // the caller's frame. - for (RuntimeScalar sc : ScalarRefRegistry.snapshot()) { - if (sc == null || sc.scopeExited || WeakRefRegistry.isweak(sc)) continue; - if (sc.value instanceof RuntimeCode code - && followGlobalCodeCaptures(code, target, seen, todo)) return true; - } - return false; - } - - public static boolean hasLiveStrongScalarReferent(RuntimeBase target) { - return hasLiveStrongScalarReferentOtherThan(target, null); - } - - public static boolean hasLiveStrongScalarReferentOtherThan( - RuntimeBase target, RuntimeScalar excluded) { - if (target == null) return false; - // snapshotLiveVars() is the authoritative set for any later scalar - // registry entry that passes MyVarCleanupStack.isLive(). Scanning - // ScalarRefRegistry.snapshot() below used to revisit the same live - // lexical slots and repeatedly copy the weak-key registry while a - // callback-boundary weak sweep was clearing CODE refs. - for (Object liveVar : MyVarCleanupStack.snapshotLiveVars()) { - if (liveVar instanceof RuntimeScalar sc - && sc != excluded - && !WeakRefRegistry.isweak(sc) - && !sc.scopeExited - && sc.value == target) { - return true; - } - } - return false; - } - - public static boolean isReachableFromGlobalCodeCaptures(RuntimeBase target) { - if (target == null) return false; - Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - Set followed = Collections.newSetFromMap(new IdentityHashMap<>()); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - for (RuntimeScalar sc : GlobalVariable.globalCodeRefEdgeRootsView()) { - if (sc != null && sc.value instanceof RuntimeCode code - && followed.add(code) - && followGlobalCodeCaptures(code, target, seen, todo)) return true; - } - return false; - } - - static boolean isReachableFromLiveScalarRegistry(RuntimeBase target, - java.util.List roots) { - if (target == null) return false; - final int MAX_VISITS = MAX_ROOT_SNAPSHOT_VISITS; - - Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - - for (RuntimeScalar sc : roots) { - if (sc == null) continue; - if (sc.captureCount > 0) continue; - if (WeakRefRegistry.isweak(sc)) continue; - if (sc.scopeExited) continue; - if (followScalar(sc, target, seen, todo)) return true; - } - - int visits = 0; - while (!todo.isEmpty() && visits < MAX_VISITS) { - RuntimeBase cur = todo.removeFirst(); - visits++; - if (cur == target) return true; - if (cur instanceof RuntimeStash) continue; - if (cur instanceof RuntimeHash h) { - if (h.elements instanceof TieHash tieHash - && followScalar(tieHash.getSelf(), target, seen, todo)) { - return true; - } - for (RuntimeScalar v : h.elements.values()) { - if (followScalar(v, target, seen, todo)) return true; - } - } else if (cur instanceof RuntimeArray a) { - for (RuntimeScalar v : a.elements) { - if (followScalar(v, target, seen, todo)) return true; - } - } - } - return !todo.isEmpty(); - } - - /** - * D-W6.14: check if a specific RuntimeScalar instance is reachable - * from package globals or live lexical roots. Used at refCount→0 - * transitions to verify that surviving "owner" scalars in the - * activeOwners set are actually live (not phantoms). - * - * Walks containers and verifies whether the specific scalar - * identity can be reached. Critical: walks INTO scalars (so - * a my-var holding a hash-ref leads us into the hash to find - * its element scalars). - */ - public static boolean isScalarReachable(RuntimeScalar target) { - if (target == null) return false; - ReachabilityQueryStats stats = MortalList.activeReachabilityQueryStats(); - if (stats != null) stats.scalarReachabilityQueries++; - - // Most calls come from reference assignment's weak-owner guard. Avoid - // rebuilding and traversing the complete package-root graph when the - // owning scalar has a directly verifiable root. - if (!target.scopeExited && MyVarCleanupStack.isRegistered(target)) { - return true; - } - if (target.isStoredInRegisteredContainerOwner()) { - return true; - } - RuntimeBase container = target.containerOwner; - if (container instanceof RuntimeHash hash - && hash.isPackageRootedHash() - && hash.elements.containsValue(target)) { - return true; - } - if (container instanceof RuntimeArray array - && array.isPackageGlobalRoot - && array.elements.contains(target)) { - return true; - } - if (target.isPackageGlobalRoot - && (GlobalVariable.scalarSlots().containsValue(target) - || GlobalVariable.globalCodeRefs.containsValue(target))) { - return true; - } - if (MortalList.isScalarReachableThroughRootedContainer(target)) { - return true; - } - Boolean drainSnapshotResult = - MortalList.isScalarReachableFromDrainSnapshot(target); - if (drainSnapshotResult != null) return drainSnapshotResult; - if (stats != null) stats.scalarReachabilityRootWalks++; - final int MAX_VISITS = MAX_ROOT_SNAPSHOT_VISITS; - - Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - - // D-W6.16 strict: PACKAGE-GLOBAL ROOTS ONLY. - // - // The walker's purpose at MortalList.flush refCount→0 is to - // distinguish "object held by a real long-lived root" (e.g., - // `our %METAS` cache, package method tables) from "object's - // reachability is via expiring lexicals or temporaries". - // - // Including my-vars / ScalarRefRegistry as seeds over-rescues - // DBIC row objects whose only owners are intermediate my-vars - // in DBIC's internal method dispatches (still in MyVarCleanupStack - // until the dispatch returns, but logically should be released - // for refcount accounting). - // - // Restricting seeds to package globals matches what - // Class::MOP/Moose actually need: their metaclasses live in - // `our %METAS`, accessible through globalHashes. DBIC's per-row - // cycles aren't reachable via package globals → not rescued - // → DESTROY fires correctly. - for (RuntimeScalar codeRef : GlobalVariable.globalCodeRefValuesView()) { - if (codeRef == target) return true; - if (codeRef != null && seen.add(codeRef)) todo.addLast(codeRef); - } - for (RuntimeScalar scalar : GlobalVariable.globalVariableValuesView()) { - if (scalar == target) return true; - if (scalar != null && seen.add(scalar)) todo.addLast(scalar); - } - for (Map.Entry e : GlobalVariable.globalArrayEntriesView()) { - if (isNonOwningDebugArgsArray(e.getKey())) continue; - if (e.getValue() != null && seen.add(e.getValue())) todo.addLast(e.getValue()); - } - for (RuntimeHash hash : GlobalVariable.globalHashValuesView()) { - if (hash != null && seen.add(hash)) todo.addLast(hash); - } - - // D-W6.16: live my-vars (currently-active lexical scopes). - // These represent persistent scalar references in ACTIVE - // execution scopes — the "my $schema = ..." at file scope is - // here; transient method-call argument scalars are NOT - // (they get unwound when the method returns). - for (Object liveVar : MyVarCleanupStack.snapshotLiveVars()) { - if (liveVar == target) return true; - if (liveVar instanceof RuntimeBase rb && seen.add(rb)) todo.addLast(rb); - } - - int visits = 0; - while (!todo.isEmpty() && visits < MAX_VISITS) { - RuntimeBase cur = todo.removeFirst(); - visits++; - // A RuntimeStash is a synthetic view across the global slot maps, - // all of which were seeded above. Walking its values both creates - // transient glob proxies and rescans every global symbol for each - // refcount transition. - if (cur instanceof RuntimeStash) { - continue; - } else if (cur instanceof RuntimeHash hash) { - if (hash.elements instanceof HashSpecialVariable) continue; - // A tied hash's Java Map facade does not expose the values - // retained by its pure-Perl handler. Follow the handler - // object, then its arrays/hashes, so an owner scalar stored by - // implementations such as Tie::IxHash is recognized as a real - // strong path. Without this edge, undefining a different - // strong scalar can clear weak back-references prematurely. - if (hash.elements instanceof TieHash tieHash) { - RuntimeScalar self = tieHash.getSelf(); - if (self == target) return true; - if (self != null && !WeakRefRegistry.isweak(self) - && seen.add(self)) { - todo.addLast(self); - } - } - for (RuntimeScalar val : hash.elements.values()) { - if (val == null) continue; - // Skip weak refs — they don't keep their referent alive. - if (WeakRefRegistry.isweak(val)) continue; - if (val == target) return true; - if (seen.add(val)) todo.addLast(val); - } - } else if (cur instanceof RuntimeArray arr) { - for (RuntimeScalar elem : arr.elements) { - if (elem == null) continue; - if (WeakRefRegistry.isweak(elem)) continue; - if (elem == target) return true; - if (seen.add(elem)) todo.addLast(elem); - } - } else if (cur instanceof RuntimeScalar sc) { - if (WeakRefRegistry.isweak(sc)) continue; - if ((sc.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && sc.value instanceof RuntimeBase rb - && seen.add(rb)) todo.addLast(rb); - } else if (cur instanceof RuntimeCode code) { - if (code.closedOverVariables != null) { - for (RuntimeBase captured : code.closedOverVariables.values()) { - if (captured == null) continue; - if (captured instanceof RuntimeScalar scalar - && WeakRefRegistry.isweak(scalar)) { - continue; - } - if (captured == target) return true; - if (seen.add(captured)) todo.addLast(captured); - } - } - if (code.capturedScalars != null) { - for (RuntimeScalar cap : code.capturedScalars) { - if (cap == null) continue; - if (WeakRefRegistry.isweak(cap)) continue; - if (cap == target) return true; - if (seen.add(cap)) todo.addLast(cap); - } - } - if (code.capturedAggregates != null) { - for (RuntimeBase cap : code.capturedAggregates) { - if (cap == target) return true; - if (seen.add(cap)) todo.addLast(cap); - } - } - final boolean[] foundReflectiveCapture = {false}; - visitReflectiveCodeScalars(code, cap -> { - if (foundReflectiveCapture[0]) return; - if (cap == null || WeakRefRegistry.isweak(cap)) return; - if (cap == target) { - foundReflectiveCapture[0] = true; - } else if (seen.add(cap)) { - todo.addLast(cap); - } - }); - if (foundReflectiveCapture[0]) return true; - visitReflectiveCodeBases(code, base -> { - if (seen.add(base)) { - todo.addLast(base); - } - }); - } else if (cur instanceof RuntimeRegex regex) { - for (RuntimeCode callback : regex.executableCallbackCodes()) { - if (seen.add(callback)) todo.addLast(callback); - } - } - } - return !todo.isEmpty(); - } - - /** - * Identity set for scalar reachability queries during one cleanup drain. - * It follows the same package and active-lexical roots and strong edges as - * {@link #isScalarReachable(RuntimeScalar)}, allowing owner scalars to be - * checked against one bounded traversal. - */ - static final class ScalarRootReachabilitySnapshot { - private final Set reachable; - private final boolean complete; - - private ScalarRootReachabilitySnapshot(Set reachable, - boolean complete) { - this.reachable = reachable; - this.complete = complete; - } - - boolean isReachable(RuntimeScalar target) { - // A capped traversal cannot prove that an unvisited owner scalar - // is unreachable. Preserve it until a complete boundary scan. - return target != null && (!complete || reachable.contains(target)); - } - - boolean complete() { - return complete; - } - } - - static ScalarRootReachabilitySnapshot scalarReachabilitySnapshot() { - ReachabilityQueryStats stats = MortalList.activeReachabilityQueryStats(); - if (stats != null) { - stats.snapshotsBuilt++; - stats.scalarReachabilityRootWalks++; - } - Set seen = Collections.newSetFromMap(new IdentityHashMap<>(512)); - Set reachableScalars = - Collections.newSetFromMap(new IdentityHashMap<>(512)); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - - for (RuntimeScalar scalar : GlobalVariable.globalCodeRefValuesView()) { - addScalarReachabilityRoot(scalar, seen, reachableScalars, todo, stats); - } - for (RuntimeScalar scalar : GlobalVariable.globalVariableValuesView()) { - addScalarReachabilityRoot(scalar, seen, reachableScalars, todo, stats); - } - for (Map.Entry entry : GlobalVariable.globalArrayEntriesView()) { - if (isNonOwningDebugArgsArray(entry.getKey())) continue; - addScalarReachabilityRoot(entry.getValue(), seen, reachableScalars, todo, stats); - } - for (RuntimeHash hash : GlobalVariable.globalHashValuesView()) { - addScalarReachabilityRoot(hash, seen, reachableScalars, todo, stats); - } - for (Object liveVar : MyVarCleanupStack.snapshotLiveVars()) { - if (liveVar instanceof RuntimeBase base) { - addScalarReachabilityRoot(base, seen, reachableScalars, todo, stats); - } - } - - final int maxVisits = MAX_ROOT_SNAPSHOT_VISITS; - int visits = 0; - while (!todo.isEmpty() && visits < maxVisits) { - RuntimeBase current = todo.removeFirst(); - visits++; - if (stats != null) stats.nodesVisited++; - if (current instanceof RuntimeStash) { - continue; - } else if (current instanceof RuntimeHash hash) { - if (hash.elements instanceof HashSpecialVariable) continue; - if (hash.elements instanceof TieHash tieHash) { - addScalarReachabilityEdge(tieHash.getSelf(), seen, - reachableScalars, todo, stats, true, true); - } - for (RuntimeScalar value : hash.elements.values()) { - addScalarReachabilityEdge(value, seen, - reachableScalars, todo, stats, true, false); - } - } else if (current instanceof RuntimeArray array) { - for (RuntimeScalar value : array.elements) { - addScalarReachabilityEdge(value, seen, - reachableScalars, todo, stats, true, false); - } - } else if (current instanceof RuntimeScalar scalar) { - if (stats != null) stats.edgesInspected++; - if (!WeakRefRegistry.isweak(scalar) - && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && scalar.value instanceof RuntimeBase base) { - if (base instanceof RuntimeScalar referencedScalar) { - reachableScalars.add(referencedScalar); - } - if (seen.add(base)) todo.addLast(base); - } - } else if (current instanceof RuntimeCode code) { - if (code.closedOverVariables != null) { - for (RuntimeBase captured : code.closedOverVariables.values()) { - if (stats != null) stats.edgesInspected++; - if (captured instanceof RuntimeScalar scalar - && WeakRefRegistry.isweak(scalar)) continue; - addScalarReachabilityEdge(captured, seen, - reachableScalars, todo, null, true, false); - } - } - if (code.capturedScalars != null) { - for (RuntimeScalar captured : code.capturedScalars) { - addScalarReachabilityEdge(captured, seen, - reachableScalars, todo, stats, true, false); - } - } - if (code.capturedAggregates != null) { - for (RuntimeBase captured : code.capturedAggregates) { - addScalarReachabilityEdge(captured, seen, - reachableScalars, todo, stats, true, true); - } - } - visitReflectiveCodeScalars(code, captured -> - addScalarReachabilityEdge(captured, seen, - reachableScalars, todo, stats, true, false)); - visitReflectiveCodeBases(code, captured -> - addScalarReachabilityEdge(captured, seen, - reachableScalars, todo, stats, false, false)); - } else if (current instanceof RuntimeRegex regex) { - for (RuntimeCode callback : regex.executableCallbackCodes()) { - addScalarReachabilityEdge(callback, seen, - reachableScalars, todo, stats, false, false); - } - } - } - return new ScalarRootReachabilitySnapshot(reachableScalars, todo.isEmpty()); - } - - private static void addScalarReachabilityRoot( - RuntimeBase base, Set seen, Set reachableScalars, - java.util.ArrayDeque todo, ReachabilityQueryStats stats) { - if (base instanceof RuntimeScalar scalar && WeakRefRegistry.isweak(scalar)) return; - if (base != null && seen.add(base)) { - todo.addLast(base); - if (stats != null) stats.rootsSeeded++; - } - if (base instanceof RuntimeScalar scalar) reachableScalars.add(scalar); - } - - private static void addScalarReachabilityEdge( - RuntimeBase base, Set seen, Set reachableScalars, - java.util.ArrayDeque todo, ReachabilityQueryStats stats, - boolean trackScalarIdentity, boolean includeWeakIdentity) { - if (stats != null) stats.edgesInspected++; - if (base instanceof RuntimeScalar scalar) { - boolean weak = WeakRefRegistry.isweak(scalar); - if (trackScalarIdentity && (!weak || includeWeakIdentity)) { - reachableScalars.add(scalar); - } - if (weak) return; - } - if (base != null && seen.add(base)) todo.addLast(base); - } - - /** - * Phase D-W2c: distinguish reachability via package globals - * (`our %METAS`, `our @ISA`, `our $...`, `&Class::MOP::class_of`) - * from reachability via local lexicals (`my $x`, MyVarCleanupStack - * entries, `ScalarRefRegistry`). - * - * The walker gate uses {@code globalOnly=true}: an object is - * "really" reachable only if a package global path leads to it. - * Stack-local my-vars don't count — those are transient holders - * that should release at scope exit. This matches Perl 5 - * semantics: `weaken($foo)` clears when no STRONG package-level - * or lexical-still-holding-strong path exists, and cycle-break - * tests rely on stack-local refs releasing properly. - * - * The default {@code globalOnly=false} is preserved for - * diagnostic / debugging callers. - */ - public static boolean isReachableFromRoots(RuntimeBase target, boolean globalOnly) { - if (target == null) return false; - ReachabilityQueryStats stats = MortalList.activeReachabilityQueryStats(); - if (stats != null) stats.rootQueries++; - // Node and edge caps bound both graph traversal and root seeding. An - // incomplete proof conservatively retains an unresolved target. - final int MAX_VISITS = MAX_ROOT_SNAPSHOT_VISITS; - RootWalkBudget budget = new RootWalkBudget(MAX_ROOT_SNAPSHOT_EDGES); - - Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - - // Seed: package globals (scalars, arrays, hashes, code refs). - for (RuntimeScalar codeRef : GlobalVariable.globalCodeRefValuesView()) { - if (!budget.visitEdge()) return true; - seedTarget(codeRef, target, seen, todo, stats); - if (seen.contains(target)) return true; - if (!globalOnly - && codeRef != null - && codeRef.value instanceof RuntimeCode code) { - if (followGlobalCodeCaptures(code, target, seen, todo, budget)) return true; - if (!budget.complete) return true; - } - } - for (RuntimeScalar scalar : GlobalVariable.globalVariableValuesView()) { - if (!budget.visitEdge()) return true; - seedTarget(scalar, target, seen, todo, stats); - if (seen.contains(target)) return true; - } - for (Map.Entry e : GlobalVariable.globalArrayEntriesView()) { - if (isNonOwningDebugArgsArray(e.getKey())) continue; - if (!budget.visitEdge()) return true; - if (e.getValue() == target) { - if (stats != null) stats.rootsSeeded++; - return true; - } - if (e.getValue() != null && seen.add(e.getValue())) { - todo.addLast(e.getValue()); - if (stats != null) stats.rootsSeeded++; - } - } - for (RuntimeHash hash : GlobalVariable.globalHashValuesView()) { - if (!budget.visitEdge()) return true; - if (hash == target) { - if (stats != null) stats.rootsSeeded++; - return true; - } - if (hash != null && seen.add(hash)) { - todo.addLast(hash); - if (stats != null) stats.rootsSeeded++; - } - } - for (RuntimeBase ownerReferent : PerlRuntime.snapshotOwnerSlotReferents()) { - if (!budget.visitEdge()) return true; - if (ownerReferent == target) return true; - if (ownerReferent != null && seen.add(ownerReferent)) { - todo.addLast(ownerReferent); - if (stats != null) stats.rootsSeeded++; - } - } - // Seed: ScalarRefRegistry-tracked scalars whose declaration - // scope is still live (per MyVarCleanupStack). This is what - // makes hash elements like $METAS{HasMethods} act as roots — - // their enclosing my %METAS hash is on the live-vars stack. - // - // The MyVarCleanupStack filter is critical: ScalarRefRegistry - // alone holds stale entries (scope-exited scalars that haven't - // been JVM-GC'd yet). Without filtering, cycle-broken-via-weaken - // tests would falsely consider the cycle members reachable - // through their own (scope-exited) scalars. - if (!globalOnly) { - for (RuntimeScalar sc : ScalarRefRegistry.snapshot()) { - if (!budget.visitEdge()) return true; - if (sc == null) continue; - if (sc.captureCount > 0) continue; - if (WeakRefRegistry.isweak(sc)) continue; - if (!MyVarCleanupStack.isLive(sc) && !sc.refCountOwned) continue; - if (sc.scopeExited) continue; - seedTarget(sc, target, seen, todo, stats); - if (seen.contains(target)) return true; - } - // Seed: live my-vars themselves (RuntimeHash / RuntimeArray / - // RuntimeScalar instances currently registered in - // MyVarCleanupStack). Walking INTO these picks up hash/array - // elements that hold strong refs to the target — e.g. - // `our %METAS = ();` registers the RuntimeHash, and walking - // its values surfaces the metaclass. - for (Object liveVar : MyVarCleanupStack.snapshotLiveVars()) { - if (!budget.visitEdge()) return true; - // Order matters: RuntimeScalar IS a RuntimeBase, so the - // RuntimeScalar branch must come first to walk through its - // reference bit. Otherwise we'd add the scalar to todo but - // the BFS only follows hashes/arrays, missing the scalar's - // referent (e.g. `my $schema = DBICTest->init_schema()`). - if (liveVar instanceof RuntimeScalar sc) { - if (sc == target) { - if (stats != null) stats.rootsSeeded++; - return true; - } - seedTarget(sc, target, seen, todo, stats); - if (seen.contains(target)) return true; - } else if (liveVar instanceof RuntimeBase rb) { - if (rb == target) { - if (stats != null) stats.rootsSeeded++; - return true; - } - if (seen.add(rb)) { - todo.addLast(rb); - if (stats != null) stats.rootsSeeded++; - } - } - } - // Live regex lexicals own executable callback captures even when - // weak-ref tracking has not populated the optimized live-count - // snapshot. Seed only regex scalars from the actual cleanup stack - // so callback captures remain reachable without widening ordinary - // lexical reachability for the refcount walk. - for (Object registeredVar : MyVarCleanupStack.snapshotRegisteredVars()) { - if (!budget.visitEdge()) return true; - if (!(registeredVar instanceof RuntimeScalar scalar) - || scalar.type != RuntimeScalarType.REGEX - || scalar.scopeExited - || WeakRefRegistry.isweak(scalar)) continue; - seedTarget(scalar, target, seen, todo, stats); - if (seen.contains(target)) return true; - } - } - // Seed: rescued objects. - for (RuntimeBase rescued : DestroyDispatch.snapshotRescuedForWalk()) { - if (!budget.visitEdge()) return true; - if (rescued == target) { - if (stats != null) stats.rootsSeeded++; - return true; - } - if (seen.add(rescued)) { - todo.addLast(rescued); - if (stats != null) stats.rootsSeeded++; - } - } - - // BFS, short-circuiting on target. - int visits = 0; - walk: while (!todo.isEmpty() && visits < MAX_VISITS) { - RuntimeBase cur = todo.removeFirst(); - visits++; - if (stats != null) stats.nodesVisited++; - if (cur == target) return true; - // Phase D-W2 (perf): skip RuntimeStash — see bfs(). - if (cur instanceof RuntimeStash) continue; - if (cur instanceof RuntimeHash h) { - if (h.elements instanceof TieHash) { - if (!budget.visitEdge()) return true; - if (stats != null) stats.edgesInspected++; - } - if (h.elements instanceof TieHash tieHash - && followScalar(tieHash.getSelf(), target, seen, todo)) { - return true; - } - for (RuntimeScalar v : h.elements.values()) { - if (!budget.visitEdge()) break walk; - if (stats != null) stats.edgesInspected++; - if (followScalar(v, target, seen, todo)) return true; - } - } else if (cur instanceof RuntimeArray a) { - for (RuntimeScalar v : a.elements) { - if (!budget.visitEdge()) break walk; - if (stats != null) stats.edgesInspected++; - if (followScalar(v, target, seen, todo)) return true; - } - } else if (cur instanceof RuntimeRegex regex) { - // Executable regex callbacks are strong owners of their - // lexical captures while a qr// scalar remains live. Follow - // only these callback capture edges; ordinary closure edges - // remain opaque to this refcount reachability query. - for (RuntimeCode callback : regex.executableCallbackCodes()) { - if (!budget.visitEdge()) break walk; - if (callback.capturedScalars != null) { - for (RuntimeScalar captured : callback.capturedScalars) { - if (!budget.visitEdge()) break walk; - if (stats != null) stats.edgesInspected++; - if (captured == target) return true; - } - } - if (callback.closedOverVariables != null) { - for (RuntimeBase captured : callback.closedOverVariables.values()) { - if (!budget.visitEdge()) break walk; - if (stats != null) stats.edgesInspected++; - if (captured == target) return true; - } - } - if (followGlobalCodeCaptures(callback, target, seen, todo, budget)) return true; - if (!budget.complete) break walk; - } - } - // Note: we deliberately don't follow RuntimeCode.capturedScalars - // here — closure captures are NOT considered strong reachability - // edges for this query (matches the default of - // ReachabilityWalker.walk() which has walkCodeCaptures=false - // for the second-phase BFS). Without this discipline, DBIC's - // leak detector (t/52leaks.t) reports false positives because - // the walker would keep things alive that user code released. - // - // For Class::MOP's %METAS hash (which we also need to find for - // the Moose bootstrap), we don't need closure-capture walking - // because %METAS is declared `our %METAS` (package global) so - // it appears directly in GlobalVariable.globalHashes. - } - return !budget.complete || !todo.isEmpty(); - } - - /** - * Return true when {@code target} is held by a live reference scalar other - * than its own named my-variable slot. This is deliberately narrower than a - * full root walk: scope cleanup calls it often, and DBIC can have thousands - * of live roots by the time its leak tests initialize. - */ - public static boolean isReachableFromExternalRoot(RuntimeBase target) { - return new ExternalRootSnapshot().isReachable(target); - } - - public static boolean isReachableFromExternalRootExcludingRescued(RuntimeBase target) { - return new ExternalRootSnapshot(false).isReachable(target); - } - - public static boolean isReachableFromTemporaryRoots(RuntimeBase target) { - if (target == null) return false; - ReachabilityWalker walker = new ReachabilityWalker(); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - for (RuntimeBase tempRoot : MortalList.snapshotTemporaryRoots()) { - walker.addReachable(tempRoot, todo); - } - walker.bfs(todo, true); - return walker.reachable.contains(target); - } - - /** - * Return true when a strong path from a package or live lexical root to - * {@code target} crosses a tied hash handler. This is intentionally more - * specific than the ordinary root queries: objects with DESTROY normally - * use strict selective-refcount handling, but a pure-Perl tie handler can - * hold a real owner that the count temporarily misses. - */ - public static boolean isReachableThroughTiedHash(RuntimeBase target) { - return target != null && reachableThroughTiedHashes().contains(target); - } - - /** - * Return the objects reached after crossing a tied hash handler from a - * live Perl root. A mortal drain can ask this question for many weak - * referents, so collecting one bounded snapshot avoids an O(targets x - * roots) traversal and its corresponding temporary objects. If the visit - * budget truncates the walk, unresolved targets are conservatively treated - * as reachable. - */ - static TiedHashReachabilitySnapshot reachableThroughTiedHashes() { - final int maxVisits = MAX_ROOT_SNAPSHOT_VISITS; - Set seenPlain = Collections.newSetFromMap(new IdentityHashMap<>()); - Set seenTied = Collections.newSetFromMap(new IdentityHashMap<>()); - Set reachableTied = Collections.newSetFromMap(new IdentityHashMap<>()); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - - for (RuntimeScalar scalar : GlobalVariable.globalCodeRefValuesView()) { - addTiedPathScalar(scalar, false, seenPlain, seenTied, todo); - } - for (RuntimeScalar scalar : GlobalVariable.globalVariableValuesView()) { - addTiedPathScalar(scalar, false, seenPlain, seenTied, todo); - } - for (RuntimeArray array : GlobalVariable.globalArrayValuesView()) { - addTiedPath(array, false, seenPlain, seenTied, todo); - } - for (RuntimeHash hash : GlobalVariable.globalHashValuesView()) { - addTiedPath(hash, false, seenPlain, seenTied, todo); - } - for (Object liveVar : MyVarCleanupStack.snapshotLiveVars()) { - if (liveVar instanceof RuntimeBase base) { - addTiedPath(base, false, seenPlain, seenTied, todo); - } - } - - int visits = 0; - while (!todo.isEmpty() && visits++ < maxVisits) { - TiedPathStep step = todo.removeFirst(); - RuntimeBase cur = step.base; - if (step.crossedTie) reachableTied.add(cur); - if (cur instanceof RuntimeStash) continue; - if (cur instanceof RuntimeHash hash) { - if (hash.elements instanceof HashSpecialVariable) continue; - if (hash.elements instanceof TieHash tieHash) { - addTiedPathScalar(tieHash.getSelf(), true, - seenPlain, seenTied, todo); - } - for (RuntimeScalar value : hash.elements.values()) { - addTiedPathScalar(value, step.crossedTie, - seenPlain, seenTied, todo); - } - } else if (cur instanceof RuntimeArray array) { - for (RuntimeScalar value : array.elements) { - addTiedPathScalar(value, step.crossedTie, - seenPlain, seenTied, todo); - } - } else if (cur instanceof RuntimeScalar scalar) { - addTiedPathScalar(scalar, step.crossedTie, - seenPlain, seenTied, todo); - } - } - return new TiedHashReachabilitySnapshot(reachableTied, todo.isEmpty()); - } - - static final class TiedHashReachabilitySnapshot { - private final Set reachable; - private final boolean complete; - - TiedHashReachabilitySnapshot(Set reachable, - boolean complete) { - this.reachable = reachable; - this.complete = complete; - } - - boolean contains(RuntimeBase target) { - return target != null && (!complete || reachable.contains(target)); - } - - boolean complete() { - return complete; - } - } - - private static void addTiedPathScalar( - RuntimeScalar scalar, boolean crossedTie, - Set seenPlain, Set seenTied, - java.util.ArrayDeque todo) { - if (scalar == null || WeakRefRegistry.isweak(scalar)) return; - addTiedPath(scalar, crossedTie, seenPlain, seenTied, todo); - if ((scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && scalar.value instanceof RuntimeBase base) { - addTiedPath(base, crossedTie, seenPlain, seenTied, todo); - } - } - - private static void addTiedPath( - RuntimeBase base, boolean crossedTie, - Set seenPlain, Set seenTied, - java.util.ArrayDeque todo) { - if (base == null) return; - Set seen = crossedTie ? seenTied : seenPlain; - if (seen.add(base)) { - todo.addLast(new TiedPathStep(base, crossedTie)); - } - } - - private record TiedPathStep(RuntimeBase base, boolean crossedTie) {} - - /** - * Target-specific reachability query for scope-exit cleanup of a named - * lexical container. The container's own my-variable slot is still present - * in {@link MyVarCleanupStack} while cleanup runs, so this deliberately - * skips that direct root and only returns true for another root path. - */ - public static boolean isReachableFromExternalRootExcludingDirectLexical(RuntimeBase target) { - if (target == null) return false; - final int MAX_VISITS = MAX_ROOT_SNAPSHOT_VISITS; - - Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - - for (RuntimeScalar sc : GlobalVariable.globalCodeRefValuesView()) { - seedTarget(sc, target, seen, todo); - if (seen.contains(target)) return true; - if (sc != null && sc.value instanceof RuntimeCode code - && followGlobalCodeCaptures(code, target, seen, todo)) { - return true; - } - } - for (RuntimeScalar sc : GlobalVariable.globalVariableValuesView()) { - seedTarget(sc, target, seen, todo); - if (seen.contains(target)) return true; - } - for (RuntimeArray array : GlobalVariable.globalArrayValuesView()) { - if (array == target) return true; - if (seen.add(array)) todo.addLast(array); - } - for (RuntimeHash hash : GlobalVariable.globalHashValuesView()) { - if (hash == target) return true; - if (seen.add(hash)) todo.addLast(hash); - } - for (RuntimeBase rescued : DestroyDispatch.snapshotRescuedForWalk()) { - if (rescued == target) return true; - if (seen.add(rescued)) todo.addLast(rescued); - } - for (RuntimeScalar sc : ScalarRefRegistry.snapshot()) { - if (sc == null) continue; - if (sc.captureCount > 0) continue; - if (WeakRefRegistry.isweak(sc)) continue; - if (sc.scopeExited) continue; - if (!MyVarCleanupStack.isLive(sc) && !sc.refCountOwned) continue; - if (followScalar(sc, target, seen, todo)) return true; - } - for (Object liveVar : MyVarCleanupStack.snapshotLiveVars()) { - if (liveVar == target) continue; - if (liveVar instanceof RuntimeScalar sc) { - if (WeakRefRegistry.isweak(sc)) continue; - if (followScalar(sc, target, seen, todo)) return true; - } else if (liveVar instanceof RuntimeBase rb) { - if (seen.add(rb)) todo.addLast(rb); - } - } - - int visits = 0; - while (!todo.isEmpty() && visits < MAX_VISITS) { - RuntimeBase cur = todo.removeFirst(); - visits++; - if (cur == target) return true; - if (cur instanceof RuntimeStash) continue; - if (cur instanceof RuntimeHash h) { - if (h.elements instanceof HashSpecialVariable) continue; - if (h.elements instanceof TieHash tieHash - && followScalar(tieHash.getSelf(), target, seen, todo)) { - return true; - } - for (RuntimeScalar v : h.elements.values()) { - if (followScalar(v, target, seen, todo)) return true; - } - } else if (cur instanceof RuntimeArray a) { - for (RuntimeScalar v : a.elements) { - if (followScalar(v, target, seen, todo)) return true; - } - } else if (cur instanceof RuntimeScalar sc) { - if (followScalar(sc, target, seen, todo)) return true; - } - } - return !todo.isEmpty(); - } - - /** - * Cached equivalent of {@link #isReachableFromExternalRoot(RuntimeBase)}. - *

    - * The package/rescued root graph is snapshotted separately from live - * lexical roots so callers can invalidate the live-lexical snapshot when - * scope registrations change without forcing a package-root rebuild. - */ - public static final class ExternalRootSnapshot { - private final Set nonLexicalReachable = - Collections.newSetFromMap(new IdentityHashMap<>(512)); - private final ReachabilityQueryStats queryStats = - MortalList.activeReachabilityQueryStats(); - private boolean complete = true; - private final RootWalkBudget budget = - new RootWalkBudget(MAX_ROOT_SNAPSHOT_EDGES); - - public ExternalRootSnapshot() { - this(true); - } - - public ExternalRootSnapshot(boolean includeRescued) { - if (queryStats != null) queryStats.externalRootSnapshotsBuilt++; - buildNonLexicalRoots(includeRescued); - } - - public boolean isReachable(RuntimeBase target) { - if (target == null) return false; - if (nonLexicalReachable.contains(target)) return true; - if (!complete) return true; - return new LiveRootSnapshot().isReachable(target); - } - - /** Whether the node and edge budgets covered the complete root graph. */ - boolean complete() { - return complete; - } - - /** - * Positive proof only. A false result can mean the snapshot hit its - * visit budget before reaching the target; callers must consult - * {@link #complete()} before treating absence as unreachable. - */ - public boolean isReachableFromNonLexicalRoot(RuntimeBase target) { - return target != null && nonLexicalReachable.contains(target); - } - - private void buildNonLexicalRoots(boolean includeRescued) { - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - - // Every installed CODE slot is itself a root, but only the - // cached subset with capture/state edges needs reflective capture - // traversal. Named subs with empty pads otherwise force this - // sweep to inspect every generated implementation object. - rootScan: { - for (RuntimeScalar codeRef : GlobalVariable.globalCodeRefValuesView()) { - if (!seedNonLexicalScalar(codeRef, todo)) break rootScan; - } - for (RuntimeScalar codeRef : GlobalVariable.globalCodeRefEdgeRootsView()) { - if (!visitExternalEdge()) break rootScan; - if (codeRef != null && codeRef.value instanceof RuntimeCode code) { - seedGlobalCodeCaptures(code, todo); - if (!complete) break rootScan; - } - } - for (RuntimeScalar scalar : GlobalVariable.globalVariableValuesView()) { - if (!seedNonLexicalScalar(scalar, todo)) break rootScan; - } - for (Map.Entry e : GlobalVariable.globalArrayEntriesView()) { - if (isNonOwningDebugArgsArray(e.getKey())) continue; - if (!visitExternalEdge()) break rootScan; - addNonLexical(e.getValue(), todo); - } - for (RuntimeHash hash : GlobalVariable.globalHashValuesView()) { - if (!visitExternalEdge()) break rootScan; - addNonLexical(hash, todo); - } - if (includeRescued) { - for (RuntimeBase rescued : DestroyDispatch.snapshotRescuedForWalk()) { - if (!visitExternalEdge()) break rootScan; - addNonLexical(rescued, todo); - } - } - } - - int visits = 0; - while (complete && !todo.isEmpty() && visits < MAX_ROOT_SNAPSHOT_VISITS) { - RuntimeBase cur = todo.removeFirst(); - visits++; - if (queryStats != null) queryStats.externalRootSnapshotNodesVisited++; - walkSnapshotNode(cur, todo); - } - complete = complete && budget.complete && todo.isEmpty(); - } - - private void walkSnapshotNode(RuntimeBase cur, - java.util.ArrayDeque nonLexicalTodo) { - if (cur instanceof RuntimeStash) return; - if (cur instanceof RuntimeHash h) { - if (h.elements instanceof HashSpecialVariable) return; - if (h.elements instanceof TieHash tieHash) { - seedNonLexicalScalar(tieHash.getSelf(), nonLexicalTodo); - if (!complete) return; - } - for (RuntimeScalar v : h.elements.values()) { - if (!seedNonLexicalScalar(v, nonLexicalTodo)) return; - } - } else if (cur instanceof RuntimeArray a) { - for (RuntimeScalar v : a.elements) { - if (!seedNonLexicalScalar(v, nonLexicalTodo)) return; - } - } else if (cur instanceof RuntimeScalar sc) { - seedNonLexicalScalar(sc, nonLexicalTodo); - } - } - - private boolean seedNonLexicalScalar(RuntimeScalar s, - java.util.ArrayDeque todo) { - if (!visitExternalEdge()) return false; - if (s == null) return true; - if (WeakRefRegistry.isweak(s)) return true; - if ((s.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && s.value instanceof RuntimeBase b) { - addNonLexical(b, todo); - } - return true; - } - - private boolean visitExternalEdge() { - if (!budget.visitEdge()) { - complete = false; - return false; - } - if (queryStats != null) queryStats.externalRootSnapshotEdgesInspected++; - return true; - } - - private void seedGlobalCodeCaptures(RuntimeCode code, - java.util.ArrayDeque todo) { - if (code.capturedScalars != null) { - for (RuntimeScalar cap : code.capturedScalars) { - seedNonLexicalScalar(cap, todo); - if (!complete) return; - } - } - if (code.capturedAggregates != null) { - for (RuntimeBase cap : code.capturedAggregates) { - if (!visitExternalEdge()) return; - addNonLexical(cap, todo); - } - } - visitReflectiveCodeScalars(code, cap -> { - if (complete) seedNonLexicalScalar(cap, todo); - }); - } - - private void addNonLexical(RuntimeBase b, - java.util.ArrayDeque todo) { - if (b == null) return; - if (nonLexicalReachable.add(b)) { - todo.addLast(b); - } - } - - } - - /** - * Snapshot of reachability from currently-live lexical roots only. - * Direct lexical origins are tracked so a named lexical container does not - * count as an external root for itself. - */ - public static final class LiveRootSnapshot { - private static final Object MIXED_DIRECT_LEXICAL_ORIGIN = new Object(); - - private final ReachabilityQueryStats queryStats = - MortalList.activeReachabilityQueryStats(); - - private final Set directLexicalRoots = - Collections.newSetFromMap(new IdentityHashMap<>(512)); - private final IdentityHashMap directLexicalOrigins = - new IdentityHashMap<>(512); - private boolean complete = true; - - public LiveRootSnapshot() { - if (queryStats != null) queryStats.liveRootSnapshotsBuilt++; - build(); - } - - public boolean isReachable(RuntimeBase target) { - if (target == null) return false; - if (!complete) return true; - Object origin = directLexicalOrigins.get(target); - if (origin == null) return false; - if (!directLexicalRoots.contains(target)) return true; - return origin != target; - } - - /** Whether this node is in the lexical graph and may need rewalking after mutation. */ - boolean mayContain(RuntimeBase target) { - return !complete || directLexicalOrigins.containsKey(target); - } - - /** Whether the visit budget drained the complete queued lexical graph. */ - boolean complete() { - return complete; - } - - private void build() { - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - - for (Object liveVar : MyVarCleanupStack.snapshotLiveVars()) { - if (!(liveVar instanceof RuntimeBase root)) continue; - directLexicalRoots.add(root); - if (root instanceof RuntimeScalar sc) { - seedDirectScalar(sc, root, todo); - } else { - addDirect(root, root, todo); - } - } - - int visits = 0; - while (!todo.isEmpty() && visits < MAX_ROOT_SNAPSHOT_VISITS) { - DirectRootStep step = todo.removeFirst(); - visits++; - if (queryStats != null) queryStats.liveRootSnapshotNodesVisited++; - walkLiveNode(step.base, todo, step.origin); - } - complete = todo.isEmpty(); - } - - private void walkLiveNode(RuntimeBase cur, - java.util.ArrayDeque todo, - Object origin) { - if (cur instanceof RuntimeStash) return; - if (cur instanceof RuntimeHash h) { - if (h.elements instanceof HashSpecialVariable) return; - if (h.elements instanceof TieHash tieHash) { - seedDirectScalar(tieHash.getSelf(), origin, todo); - } - for (RuntimeScalar v : h.elements.values()) { - seedDirectScalar(v, origin, todo); - } - } else if (cur instanceof RuntimeArray a) { - for (RuntimeScalar v : a.elements) { - seedDirectScalar(v, origin, todo); - } - } else if (cur instanceof RuntimeScalar sc) { - seedDirectScalar(sc, origin, todo); - } - } - - private void seedDirectScalar(RuntimeScalar s, Object origin, - java.util.ArrayDeque todo) { - if (s == null) return; - if (WeakRefRegistry.isweak(s)) return; - if ((s.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && s.value instanceof RuntimeBase b) { - addDirect(b, origin, todo); - } - } - - private void addDirect(RuntimeBase b, Object origin, - java.util.ArrayDeque todo) { - if (b == null || origin == null) return; - Object existing = directLexicalOrigins.get(b); - if (existing == null) { - directLexicalOrigins.put(b, origin); - todo.addLast(new DirectRootStep(b, origin)); - return; - } - if (existing == MIXED_DIRECT_LEXICAL_ORIGIN || existing == origin) { - return; - } - directLexicalOrigins.put(b, MIXED_DIRECT_LEXICAL_ORIGIN); - todo.addLast(new DirectRootStep(b, MIXED_DIRECT_LEXICAL_ORIGIN)); - } - - private static final class DirectRootStep { - private final RuntimeBase base; - private final Object origin; - - private DirectRootStep(RuntimeBase base, Object origin) { - this.base = base; - this.origin = origin; - } - } - } - - private static void seedTarget(RuntimeScalar s, RuntimeBase target, - Set seen, - java.util.ArrayDeque todo) { - seedTarget(s, target, seen, todo, null); - } - - private static void seedTarget(RuntimeScalar s, RuntimeBase target, - Set seen, - java.util.ArrayDeque todo, - ReachabilityQueryStats stats) { - if (s == null) return; - if (stats != null) stats.edgesInspected++; - if (WeakRefRegistry.isweak(s)) return; - if ((s.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && s.value instanceof RuntimeBase b) { - if (b == target) { - if (seen.add(target) && stats != null) stats.rootsSeeded++; - return; - } - if (seen.add(b)) { - todo.addLast(b); - if (stats != null) stats.rootsSeeded++; - } - } - } - - private static boolean followScalar(RuntimeScalar s, RuntimeBase target, - Set seen, - java.util.ArrayDeque todo) { - if (s == null) return false; - if (WeakRefRegistry.isweak(s)) return false; - if ((s.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && s.value instanceof RuntimeBase b) { - if (b == target) return true; - if (seen.add(b)) todo.addLast(b); - } - return false; - } - - private static boolean followGlobalCodeCaptures(RuntimeCode code, RuntimeBase target, - Set seen, - java.util.ArrayDeque todo) { - return followGlobalCodeCaptures(code, target, seen, todo, null); - } - - private static boolean followGlobalCodeCaptures(RuntimeCode code, RuntimeBase target, - Set seen, - java.util.ArrayDeque todo, - RootWalkBudget budget) { - for (RuntimeScalar state : code.stateVariable.values()) { - if (budget != null && !budget.visitEdge()) return false; - if (followScalar(state, target, seen, todo)) return true; - } - for (RuntimeArray state : code.stateArray.values()) { - if (budget != null && !budget.visitEdge()) return false; - if (state == target) return true; - if (seen.add(state)) todo.addLast(state); - } - for (RuntimeHash state : code.stateHash.values()) { - if (budget != null && !budget.visitEdge()) return false; - if (state == target) return true; - if (seen.add(state)) todo.addLast(state); - } - // Interpreted closures keep their semantic lexical environment in - // closedOverVariables. This edge must be followed when deciding - // whether a suspended async sub's returning Future is still owned by - // a live closure; reflective/capture arrays are not guaranteed to - // expose that ownership on every backend. - if (code.closedOverVariables != null) { - for (RuntimeBase captured : code.closedOverVariables.values()) { - if (budget != null && !budget.visitEdge()) return false; - if (captured == null) continue; - if (captured instanceof RuntimeScalar scalar) { - if (followScalar(scalar, target, seen, todo)) return true; - } else if (captured == target) { - return true; - } else if (seen.add(captured)) { - todo.addLast(captured); - } - } - } - if (code.capturedScalars != null) { - for (RuntimeScalar cap : code.capturedScalars) { - if (budget != null && !budget.visitEdge()) return false; - if (followScalar(cap, target, seen, todo)) return true; - } - } - if (code.capturedAggregates != null) { - for (RuntimeBase cap : code.capturedAggregates) { - if (budget != null && !budget.visitEdge()) return false; - if (cap == target) return true; - if (seen.add(cap)) todo.addLast(cap); - } - } - final boolean[] foundReflectiveCapture = {false}; - visitReflectiveCodeScalars(code, cap -> { - if (budget != null && !budget.visitEdge()) return; - if (!foundReflectiveCapture[0] && followScalar(cap, target, seen, todo)) { - foundReflectiveCapture[0] = true; - } - }); - if (budget != null && !budget.complete) return false; - if (foundReflectiveCapture[0]) return true; - final boolean[] foundReflectiveBase = {false}; - visitReflectiveCodeBases(code, base -> { - if (budget != null && !budget.visitEdge()) return; - if (foundReflectiveBase[0]) return; - if (base == target) { - foundReflectiveBase[0] = true; - } else if (seen.add(base)) { - todo.addLast(base); - } - }); - if (budget != null && !budget.complete) return false; - if (foundReflectiveBase[0]) return true; - return false; - } - - private static void visitReflectiveCodeScalars(RuntimeCode code, - java.util.function.Consumer visitor) { - if (code.captureFieldsRecorded) return; - Object closureObject = code.codeObject != null ? code.codeObject : code.subroutine; - if (closureObject == null) return; - try { - for (java.lang.reflect.Field field : - REFLECTIVE_CAPTURE_FIELDS.get(closureObject.getClass()).scalars()) { - RuntimeScalar cap = (RuntimeScalar) field.get(closureObject); - if (cap != null) { - visitor.accept(cap); - } - } - } catch (IllegalAccessException ignored) { - // Generated closure fields are public. If another implementation - // denies reflective access, callers still have capturedScalars and - // interpreter capturedVars metadata as fallbacks. - } - } - - private static void visitReflectiveCodeBases(RuntimeCode code, - java.util.function.Consumer visitor) { - if (code.captureFieldsRecorded) { - if (code.capturedAggregates != null) { - for (RuntimeBase captured : code.capturedAggregates) { - if (captured != null) visitor.accept(captured); - } - } - return; - } - Object closureObject = code.codeObject != null ? code.codeObject : code.subroutine; - if (closureObject == null) return; - try { - for (java.lang.reflect.Field field : - REFLECTIVE_CAPTURE_FIELDS.get(closureObject.getClass()).bases()) { - RuntimeBase cap = (RuntimeBase) field.get(closureObject); - if (cap != null) { - visitor.accept(cap); - } - } - } catch (IllegalAccessException ignored) { - // Generated closure fields are public. If another implementation - // denies reflective access, callers still have capturedScalars and - // interpreter capturedVars metadata as fallbacks. - } - } - - /** - * Run a reachability sweep and clear weak refs for unreachable objects. - * Called from {@code Internals::jperl_gc()} explicitly. - *

    - * Rescued objects (pinned by Schema-style DESTROY self-save) are NOT - * treated as roots here. jperl_gc is opt-in and the caller is asking - * for aggressive cleanup — if the user wanted to keep a phantom chain - * alive, they would not call jperl_gc. The rescued pins are cleared - * via DestroyDispatch.clearRescuedWeakRefs() as part of the sweep. - * - * @return number of weak-ref entries cleared - */ - public static int sweepWeakRefs() { - return sweepWeakRefs(false); - } - - public static int sweepWeakRefs(boolean quiet) { - return sweepWeakRefs(quiet, true); - } - - /** - * Run a reachability sweep. When {@code quiet} is true, only clear - * weak refs for unreachable objects — do NOT fire DESTROY or drain - * rescuedObjects. Used by auto-triggered sweeps from common hot - * paths where firing DESTROY mid-execution would corrupt state - * (e.g. module loading chains that weaken() intermediate values). - * - * @param quiet if true, skip DESTROY invocations - * @return number of weak-ref entries cleared - */ - public static int sweepWeakRefs(boolean quiet, boolean forceJvmGc) { - return sweepWeakRefs(quiet, forceJvmGc, Collections.emptySet(), null); - } - - static int sweepWeakRefs(boolean quiet, boolean forceJvmGc, - Set releasedTargets, - ReleasedWeakSweepResult releasedSweepResult) { - return sweepWeakRefsPass(quiet, forceJvmGc, releasedTargets, - releasedSweepResult).cleared(); - } - - private record WeakSweepPass(int cleared, boolean graphChanged) {} - - private static final int MAX_WITNESS_SWEEP_TARGETS = 64; - private static final int MAX_WITNESS_CYCLE_EDGES = 256; - private static final int MAX_WEAK_BACKREF_CAPTURE_VISITS = 10_000; - - private record WeakBackrefCaptureSnapshot(Set captured, boolean complete) { - boolean protects(RuntimeBase target) { - return !complete || captured.contains(target); - } - } - - private static boolean tryWitnessQuietSweep( - boolean quiet, boolean forceJvmGc, - Set releasedTargets, - ReleasedWeakSweepResult releasedSweepResult, - List weakCandidates, - List destroyableCandidates, - LifecycleRuntimeState runtimeState) { - if (!quiet || forceJvmGc || releasedSweepResult != null || !releasedTargets.isEmpty()) { - return false; - } - if (DestroyDispatch.hasRescuedObjects() - || runtimeState.currentDestroyTarget != null - || runtimeState.sweepPendingAfterOuterDestroy) { - return false; - } - Set targets = Collections.newSetFromMap(new IdentityHashMap<>()); - targets.addAll(weakCandidates); - targets.addAll(destroyableCandidates); - if (targets.size() > MAX_WITNESS_SWEEP_TARGETS) return false; - - for (RuntimeBase referent : weakCandidates) { - if (referent == null) continue; - if (hasDirectCodeRootWitness(referent)) { - continue; - } - ReachabilityWalker.WeakRootWitness witness = - runtimeState.weakSweepRootWitnesses.get(referent); - if (witness != null) { - if (isCurrentWeakRootWitness(witness)) continue; - } - if (hasExistingWeakRetentionRule(referent)) continue; - BoundedArrayCycleResult cycle = hasBoundedStrongArrayCycle( - referent, MAX_WITNESS_CYCLE_EDGES); - if (!cycle.cycle()) return false; - } - for (RuntimeBase referent : destroyableCandidates) { - if (referent == null || referent.destroyFired || referent.currentlyDestroying - || referent.refCount == Integer.MIN_VALUE - || hasExistingDestroyRetentionRule(referent)) { - continue; - } - if (hasDirectCodeRootWitness(referent)) { - continue; - } - ReachabilityWalker.WeakRootWitness witness = - runtimeState.weakSweepRootWitnesses.get(referent); - if (witness == null || !isCurrentWeakRootWitness(witness)) return false; - } - if (!sameIdentityContents(weakCandidates, - WeakRefRegistry.snapshotWeakRefReferents()) - || !sameIdentityContents(destroyableCandidates, - DestroyDispatch.snapshotDestroyableObjects())) { - return false; - } - runtimeState.weakSweepRootWitnesses.entrySet().removeIf(entry -> - !targets.contains(entry.getKey()) - && !(entry.getKey() instanceof RuntimeCode - && entry.getValue().liveLexicalScalar() - && isCurrentWeakRootWitness(entry.getValue()))); - return true; - } - - private static boolean sameIdentityContents( - List first, List second) { - if (first.size() != second.size()) return false; - Set identities = Collections.newSetFromMap(new IdentityHashMap<>()); - identities.addAll(first); - for (RuntimeBase value : second) { - if (!identities.remove(value)) return false; - } - return identities.isEmpty(); - } - - private static boolean hasExistingWeakRetentionRule(RuntimeBase referent) { - if (referent.hasSemanticCaptureOwner()) return true; - if ((referent instanceof RuntimeHash || referent instanceof RuntimeArray) - && referent.localBindingExists) return true; - if (referent instanceof RuntimeScalar scalar) { - return scalar.type == RuntimeScalarType.UNDEF - || ((scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && scalar.value instanceof RuntimeCode); - } - return false; - } - - private static boolean hasExistingDestroyRetentionRule(RuntimeBase referent) { - return referent.hasSemanticCaptureOwner() - || ((referent instanceof RuntimeHash || referent instanceof RuntimeArray) - && referent.localBindingExists); - } - - private static boolean hasDirectCodeRootWitness(RuntimeBase referent) { - if (!(referent instanceof RuntimeCode code)) return false; - if (GlobalVariable.installedGlobalCodeRefsView().contains(code)) return true; - for (RuntimeCode active : PerlRuntime.current().executionState().activeCodeStack) { - if (active == code) return true; - } - return false; - } - - private static boolean isCurrentWeakRootWitness(WeakRootWitness witness) { - RuntimeCode rootCode = witness == null ? null : witness.rootCode().get(); - RuntimeBase capturedAggregate = witness == null ? null : witness.capturedAggregate().get(); - RuntimeScalar ownerScalar = witness == null ? null : witness.ownerScalar().get(); - RuntimeBase referent = witness == null ? null : witness.referent().get(); - if (witness != null && witness.liveLexicalScalar()) { - return ownerScalar != null && referent != null - && MyVarCleanupStack.isLive(ownerScalar) - && !ownerScalar.scopeExited - && !WeakRefRegistry.isweak(ownerScalar) - && (ownerScalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && ownerScalar.value == referent; - } - if (witness == null - || rootCode == null || capturedAggregate == null || ownerScalar == null - || referent == null - || !GlobalVariable.installedGlobalCodeRefsView().contains(rootCode) - || !rootCode.captureFieldsRecorded - || !(capturedAggregate instanceof RuntimeArray array) - || !isSupportedWitnessArray(array) - || WeakRefRegistry.isweak(ownerScalar) - || (ownerScalar.type & RuntimeScalarType.REFERENCE_BIT) == 0 - || ownerScalar.value != referent) { - return false; - } - boolean captureStillInstalled = false; - if (rootCode.capturedAggregates != null) { - for (RuntimeBase captured : rootCode.capturedAggregates) { - if (captured == array) { - captureStillInstalled = true; - break; - } - } - } - if (!captureStillInstalled) return false; - for (RuntimeScalar slot : array.elements) { - if (slot == ownerScalar) return true; - } - return false; - } - - private static WeakSweepPass sweepWeakRefsPass( - boolean quiet, boolean forceJvmGc, - Set releasedTargets, - ReleasedWeakSweepResult releasedSweepResult) { - if (!WeakRefRegistry.weakRefsExist()) return new WeakSweepPass(0, false); - if (forceJvmGc) { - ScalarRefRegistry.forceGcAndSnapshot(); - } - if (!quiet) { - // Explicit sweeps drain rescued objects. Quiet auto-sweeps run - // during user workflows and must not clear DBIC Schema rescue - // links while later chained calls still rely on them. - DestroyDispatch.clearRescuedWeakRefs(); - } - LifecycleRuntimeState runtimeState = PerlRuntime.current().lifecycleState; - ArrayList weakWitnessCandidates = - new ArrayList<>(WeakRefRegistry.snapshotWeakRefReferents()); - releaseUnreachableScopeExitedCaptureOwners(weakWitnessCandidates, null); - ArrayList destroyableWitnessCandidates = null; - if (quiet) { - destroyableWitnessCandidates = DestroyDispatch.snapshotDestroyableObjects(); - if (tryWitnessQuietSweep(quiet, forceJvmGc, releasedTargets, - releasedSweepResult, weakWitnessCandidates, - destroyableWitnessCandidates, runtimeState)) { - return new WeakSweepPass(0, false); - } - } - boolean reuseReleasedSweep = !forceJvmGc - && releasedSweepResult != null - && releasedSweepResult.live() != null; - ReachabilityWalker fullWalker = null; - Set live; - if (reuseReleasedSweep) { - live = releasedSweepResult.live(); - runtimeState.weakSweepRootWitnesses.clear(); - } else if (quiet) { - Set witnessTargets = - Collections.newSetFromMap(new IdentityHashMap<>()); - witnessTargets.addAll(weakWitnessCandidates); - witnessTargets.addAll(destroyableWitnessCandidates); - fullWalker = new ReachabilityWalker().withWeakWitnessTargets(witnessTargets); - live = fullWalker.walk(); - runtimeState.weakSweepRootWitnesses.clear(); - runtimeState.weakSweepRootWitnesses.putAll(fullWalker.discoveredWeakRootWitnesses); - } else { - runtimeState.weakSweepRootWitnesses.clear(); - fullWalker = new ReachabilityWalker(); - live = fullWalker.walk(); - } - ArrayList toClear = new ArrayList<>(); - Set strongCycleProtected = quiet - ? (reuseReleasedSweep - ? releasedSweepResult.strongCycleProtected() - : collectStrongCycleProtected(live)) - : Collections.emptySet(); - Set countedStrongOwners = releasedSweepResult == null - ? Collections.emptySet() - : releasedSweepResult.countedStrongOwners(); - WeakBackrefCaptureSnapshot weakBackrefCaptures = quiet - ? weakBackrefCaptureSnapshot() : null; - for (RuntimeBase referent : WeakRefRegistry.snapshotWeakRefReferents()) { - boolean liveReferent = live.contains(referent); - traceWeakReferent(referent, liveReferent, strongCycleProtected.contains(referent)); - // Semantic closure ownership is an explicit Perl edge. It is not - // necessarily visible to this conservative graph walk because - // generated closure fields and metadata are intentionally opaque. - if (!liveReferent && referent.hasSemanticCaptureOwner()) { - continue; - } - if (!liveReferent && hasCapturedAggregateElementOwner(referent)) { - continue; - } - boolean localBinding = (referent instanceof RuntimeHash || referent instanceof RuntimeArray) - && referent.localBindingExists; - boolean cycleProtected = quiet && strongCycleProtected.contains(referent); - if (!liveReferent) { - // A named hash/array lexical (`my %h`, `my @a`) is NOT a - // walker root — the walker only seeds from globals and - // ScalarRefRegistry (scalars). If `\%h` was weakened, - // `%h` itself does not appear in any walker seed set, - // so it is trivially "unreachable" — but the lexical - // slot is still alive. Guard: localBindingExists=true - // means the named Perl lexical still holds this - // container alive; skip clearing weak refs to it. - // Scope exit (scopeExitCleanupHash/Array) will clear - // the flag and let a later sweep reap it if truly dead. - // Fixes op/hashassign.t 218 (bug #76716). - if (localBinding) { - continue; - } - // Phase I (52leaks/60core): skip clearing weak refs to - // scalars that hold CODE refs, or scalars that are already - // UNDEF. These are commonly Sub::Quote/Sub::Defer - // `$unquoted` / `$undeferred` lexical slots — empty - // scalars to be filled with a compiled sub on first - // invocation, OR already holding the compiled sub. - // Clearing their weak refs breaks the re-dispatch chain - // (`$$_UNQUOTED = sub { ... }` loses its slot, producing - // "Not a CODE reference" at later dispatch points). - // clearWeakRefsTo(RuntimeCode) is already a no-op for - // CODE values themselves, but a weak ref pointing AT a - // scalar that holds a CODE is a different target and - // needs this explicit skip. - if (referent instanceof RuntimeScalar s) { - if (s.type == RuntimeScalarType.UNDEF) continue; - if ((s.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && s.value instanceof RuntimeCode) { - continue; - } - } - // Quiet auto-sweeps can run while a deferred CODE ref is being - // returned to its caller. Sub::Quote stores weak registry - // entries in hashes/arrays that are strongly captured by that - // CODE, but the caller's lexical may not be visible as a root - // yet. Keep this exception limited to unblessed metadata - // containers and only for quiet statement-boundary sweeps; - // explicit jperl_gc() keeps the stricter root-based behavior. - if (quiet - && referent.blessId == 0 - && (referent instanceof RuntimeHash || referent instanceof RuntimeArray) - && weakBackrefCaptures.protects(referent)) { - continue; - } - // Quiet auto-sweeps run at statement boundaries. Do not clear - // weak refs into, or strongly reachable from, a strong cycle: - // Perl's refcounting keeps such cycle islands alive. This - // covers callback-retained futures where the outer future is - // cyclic and inner sequence futures are strong children. - if (cycleProtected) { - continue; - } - // The released-referent pass has a narrower guard for strong - // counted owners which the lexical/root walk cannot see. When - // that pass and the periodic global sweep share a snapshot, - // preserve the same guard for those requested targets. - if (releasedTargets.contains(referent) - && referent.refCount > 0 - && countedStrongOwners.contains(referent)) { - continue; - } - toClear.add(referent); - } - } - for (RuntimeBase referent : DestroyDispatch.snapshotDestroyableObjects()) { - if (referent == null - || referent.destroyFired - || referent.currentlyDestroying - || referent.refCount == Integer.MIN_VALUE) { - continue; - } - if (live.contains(referent)) { - continue; - } - if (referent.hasSemanticCaptureOwner()) { - continue; - } - if (hasCapturedAggregateElementOwner(referent)) { - continue; - } - if ((referent instanceof RuntimeHash || referent instanceof RuntimeArray) - && referent.localBindingExists) { - continue; - } - if (!toClear.contains(referent)) { - toClear.add(referent); - } - } - int cleared = 0; - boolean graphChanged = false; - Set previousSweepLiveReferents = runtimeState.weakSweepLiveReferents; - runtimeState.weakSweepLiveReferents = live; - try { - for (RuntimeBase referent : toClear) { - // Phase I: auto-sweep (quiet) now fires DESTROY on blessed - // unreachable objects and sets refCount=MIN_VALUE — matching - // non-quiet jperl_gc behaviour. Previously quiet mode was - // more conservative to avoid mid-module-init DESTROY cascades, - // but Phase B2a's ModuleInitGuard already protects against - // that, and Phase I's walker seed filters ensure we only - // DESTROY genuinely unreachable objects. Without this, - // DBICTest::Artist and similar rows held only by - // Sub::Quote-generated internal caches never clear their - // weak refs between auto-sweeps. - if (referent.blessId != 0 && !referent.destroyFired - && referent.refCount != Integer.MIN_VALUE) { - referent.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(referent); - graphChanged = true; - } else { - WeakRefRegistry.clearWeakRefsTo(referent); - if (referent.refCount != Integer.MIN_VALUE) { - referent.refCount = Integer.MIN_VALUE; - } - } - cleared++; - } - } finally { - runtimeState.weakSweepLiveReferents = previousSweepLiveReferents; - } - return new WeakSweepPass(cleared, graphChanged); - } - - /** - * Drop semantic capture slots whose declaring pad has exited and is no - * longer reachable from Perl roots. A stale closure can otherwise keep - * its referent in {@code positiveOwnerReferents}; the sweep then mistakes - * that bookkeeping root for a live Perl owner and never clears weak refs. - */ - static void releaseUnreachableScopeExitedCaptureOwners( - List weakReferents, Set endReachable) { - releaseUnreachableScopeExitedCaptureOwners(weakReferents, endReachable, null); - } - - private static void releaseUnreachableScopeExitedCaptureOwners( - List weakReferents, - Set endReachable, - Set statementBoundaryCandidates) { - Set retainedByEnd = endReachable; - ScalarRootReachabilitySnapshot scalarRoots = null; - for (RuntimeBase referent : weakReferents) { - for (PerlOwnerSlot slot : referent.ownerSlotSnapshot()) { - RuntimeScalar padCell = slot.padCell(); - if (padCell == null || !padCell.scopeExited || slot.referent() != referent) { - continue; - } - if (retainedByEnd == null) retainedByEnd = walkEndBlockRoots(); - boolean padInEnd = retainedByEnd.contains(padCell); - boolean referentInEnd = retainedByEnd.contains(referent); - if (scalarRoots == null) scalarRoots = scalarReachabilitySnapshot(); - boolean padInScalarRoots = scalarRoots.isReachable(padCell); - if (padInScalarRoots && statementBoundaryCandidates != null - && containsAnyCandidate(referent, statementBoundaryCandidates) - && findPathTo(padCell, false, false) == null) { - padInScalarRoots = false; - } - if (padInEnd || referentInEnd || padInScalarRoots) continue; - if (WALKER_TRACE_CLASS != null && !WALKER_TRACE_CLASS.isEmpty()) { - String className = NameNormalizer.getBlessStr(referent.blessId); - if (className != null && className.contains(WALKER_TRACE_CLASS)) { - System.err.println("[WALKER_CAPTURE_RELEASE] target=" + className + "@" - + System.identityHashCode(referent) - + " slot=" + slot.identity() - + " pad=" + System.identityHashCode(padCell) - + " captureCount=" + padCell.captureCount - + " legacyCaptures=" + slot.legacyCaptureCount()); - } - } - padCell.releaseUnreachableSemanticCaptureOwner(); - } - } - } - - private static boolean containsAnyCandidate( - RuntimeBase root, Set candidates) { - Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - todo.add(root); - while (!todo.isEmpty()) { - RuntimeBase current = todo.removeFirst(); - if (!seen.add(current)) continue; - if (candidates.contains(current)) return true; - if (current instanceof RuntimeHash hash) { - for (RuntimeScalar value : hash.elements.values()) { - if (value != null) todo.addLast(value); - } - } else if (current instanceof RuntimeArray array) { - for (RuntimeScalar value : array.elements) { - if (value != null) todo.addLast(value); - } - } else if (current instanceof RuntimeScalar scalar) { - if (!WeakRefRegistry.isweak(scalar) - && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && scalar.value instanceof RuntimeBase referent) { - todo.addLast(referent); - } - } else if (current instanceof RuntimeCode code) { - if (code.closedOverVariables != null) { - todo.addAll(code.closedOverVariables.values()); - } - if (code.capturedScalars != null) { - Collections.addAll(todo, code.capturedScalars); - } - if (code.capturedAggregates != null) { - Collections.addAll(todo, code.capturedAggregates); - } - visitReflectiveCodeScalars(code, todo::addLast); - visitReflectiveCodeBases(code, todo::addLast); - } else if (current instanceof RuntimeRegex regex) { - todo.addAll(regex.executableCallbackCodes()); - } - } - return false; - } - - private static void traceWeakReferent( - RuntimeBase referent, boolean live, boolean cycleProtected) { - String filter = WALKER_TRACE_CLASS; - if (filter == null || filter.isEmpty() || referent.blessId == 0) return; - String className = NameNormalizer.getBlessStr(referent.blessId); - if (className == null || !className.contains(filter)) return; - List path = live ? findPathTo(referent) : null; - String pathText = !live ? "" - : path == null ? "" - : path.isEmpty() ? "" : String.join(" -> ", path); - ArrayList ownerSlots = new ArrayList<>(); - for (PerlOwnerSlot slot : referent.ownerSlotSnapshot()) { - RuntimeScalar padCell = slot.padCell(); - ownerSlots.add(slot.identity() - + ":native=" + slot.isNativeCaptureOwner() - + ":legacy=" + slot.legacyCaptureCount() - + ":pad=" + (padCell == null ? "none" : System.identityHashCode(padCell)) - + ":padLive=" + (padCell != null && isScalarReachable(padCell))); - } - System.err.println("[WALKER_TRACE] target=" + className + "@" - + System.identityHashCode(referent) - + " refCount=" + referent.refCount - + " live=" + live - + " cycleProtected=" + cycleProtected - + " activeOwners=" + referent.activeOwnerCount() - + " ownerSlots=" + referent.ownerSlotSnapshot().size() - + " ownerSlotDetails=" + ownerSlots - + " semanticCapture=" + referent.hasSemanticCaptureOwner() - + " path=" + pathText); - } - - /** - * Reconsider only referents explicitly released by {@code undef}. This is - * safe to run at a nested statement boundary because it cannot clear weak - * references belonging to unrelated in-flight return values. - */ - record ReleasedWeakSweepResult( - Set live, - Set strongCycleProtected, - Set countedStrongOwners, - int cleared) {} - - public static ReleasedWeakSweepResult sweepReleasedWeakReferents( - Set referents) { - if (referents == null || referents.isEmpty()) { - return new ReleasedWeakSweepResult(null, Collections.emptySet(), - Collections.emptySet(), 0); - } - Set pending = Collections.newSetFromMap(new IdentityHashMap<>()); - for (RuntimeBase referent : referents) { - if (referent == null || referent.currentlyDestroying) continue; - // Normal decrement-to-zero destruction already clears the - // referent's weak observers and recursively releases contained - // objects in DestroyDispatch.callDestroy(). Re-walking every - // root after that completed path is both redundant and quadratic - // for object trees such as PPI's AST. A rescued object is handled - // by the rescue-specific cleanup path after the assignment. - if (referent.destroyFired || referent.refCount == Integer.MIN_VALUE) continue; - pending.add(referent); - } - if (pending.isEmpty()) { - return new ReleasedWeakSweepResult(null, Collections.emptySet(), - Collections.emptySet(), 0); - } - - // A registered, live, nonweak scalar with an owned direct reference is - // itself a root in walk(). If every released target has such an owner, - // no graph traversal is needed to preserve those targets. This is a - // deliberately narrow proof: nested container slots, exited captures, - // and uncounted references still use the full reachability walk below. - Set directlyOwned = - Collections.newSetFromMap(new IdentityHashMap<>()); - for (RuntimeScalar owner : ScalarRefRegistry.snapshot()) { - if (owner == null || !owner.refCountOwned || owner.scopeExited - || !MyVarCleanupStack.isLive(owner) || WeakRefRegistry.isweak(owner) - || (owner.type & RuntimeScalarType.REFERENCE_BIT) == 0 - || !(owner.value instanceof RuntimeBase target)) { - continue; - } - if (pending.contains(target)) directlyOwned.add(target); - } - if (directlyOwned.containsAll(pending)) { - return new ReleasedWeakSweepResult(null, Collections.emptySet(), - directlyOwned, 0); - } - - // A package or live lexical path is sufficient to retain a target in - // this targeted release sweep. Prove those common positive cases from - // the shared root snapshots before constructing a full walker; the - // remaining targets still use the conservative full-root analysis. - Set snapshotReachable = - Collections.newSetFromMap(new IdentityHashMap<>()); - for (RuntimeBase referent : pending) { - if (MortalList.isReachableFromPersistentRootCached(referent)) { - snapshotReachable.add(referent); - } - } - if (snapshotReachable.containsAll(pending)) { - return new ReleasedWeakSweepResult(null, Collections.emptySet(), - snapshotReachable, 0); - } - - // A single released target that forms its own strong cycle is known - // alive by Perl's refcount semantics. The full weak sweep would keep - // this referent through collectStrongCycleProtected() after traversing - // every runtime root. Resolve this exact target directly and leave - // unrelated registry entries for their normal sweep cadence. - if (pending.size() == 1) { - RuntimeBase only = pending.iterator().next(); - if (only.blessId == 0 && hasStrongCycle(only)) { - Set cycleProtected = - Collections.newSetFromMap(new IdentityHashMap<>()); - collectStrongReachable(only, cycleProtected); - return new ReleasedWeakSweepResult(null, cycleProtected, - Collections.emptySet(), 0); - } - } - Set live = new ReachabilityWalker() - .withTemporaryRoots(false) - .walk(); - Set countedStrongOwners = - Collections.newSetFromMap(new IdentityHashMap<>()); - for (RuntimeScalar owner : ScalarRefRegistry.snapshot()) { - if (owner == null || !owner.refCountOwned || WeakRefRegistry.isweak(owner)) continue; - // Hash/array slots in a discarded aggregate are internal owners of - // that graph, not independent roots. Keep their referents only when - // the containing aggregate is still reachable or was not part of - // this explicitly released graph. - if (owner.containerOwner != null - && referents.contains(owner.containerOwner) - && !live.contains(owner.containerOwner)) { - continue; - } - if (owner.value instanceof RuntimeBase referent && referents.contains(referent)) { - countedStrongOwners.add(referent); - } - } - // Targeted release sweeps run at the same quiet statement boundary as - // sweepWeakRefs(true). Preserve strong cycle islands here too: Perl's - // reference counting intentionally keeps an unreachable strong cycle - // alive, including weak diagnostic references into that cycle. - Set strongCycleProtected = collectStrongCycleProtected(live); - int cleared = 0; - boolean releasedObjectNeedsCascade = false; - boolean releasedGraphChanged = false; - for (RuntimeBase referent : pending) { - if (referent == null || referent.currentlyDestroying) { - continue; - } - // Native closure-pad slots are explicit Perl owners, even when the - // conservative root walk cannot see the generated closure fields. - // Match sweepWeakRefs() above: a targeted release of another edge - // must not destroy an aggregate still captured by a live closure. - if (referent.hasSemanticCaptureOwner()) continue; - // A targeted release only means that one explicit owner went - // away. Other counted owners can still hold the referent through - // local aggregate slots that are not represented in the lexical - // root walk (notably file-scope my arrays and hashes). Preserve - // those objects until their counted owners release them. - if (referent.refCount > 0 && countedStrongOwners.contains(referent)) continue; - if (live.contains(referent)) continue; - if (strongCycleProtected.contains(referent)) continue; - if ((referent instanceof RuntimeHash || referent instanceof RuntimeArray) - && referent.localBindingExists) { - continue; - } - if (referent.blessId != 0) { - referent.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(referent); - releasedGraphChanged = true; - } else { - WeakRefRegistry.clearWeakRefsTo(referent); - referent.refCount = Integer.MIN_VALUE; - } - cleared++; - releasedObjectNeedsCascade = true; - } - - // Destruction can remove the last strong edge to another weakly - // observed object (a tied hash wrapper -> handler -> external hash is - // one example). Reachability snapshots are intentionally immutable, - // so iterate to a fixed point after this explicit release. - if (releasedObjectNeedsCascade) { - for (int pass = 0; pass < 8; pass++) { - // This is still an automatic, statement-boundary sweep. Keep - // DESTROY-rescued objects pinned; the targeted release above - // must not drain unrelated (or newly rescued) object graphs. - // Clearing only unblessed weak aliases cannot change the - // strong root graph, so reuse the targeted pass's snapshot. - // A DESTROY call can mutate that graph; only then rebuild it. - ReleasedWeakSweepResult reusableSnapshot = releasedGraphChanged - ? null - : new ReleasedWeakSweepResult(live, strongCycleProtected, - countedStrongOwners, cleared); - WeakSweepPass passResult = sweepWeakRefsPass( - true, false, referents, reusableSnapshot); - cleared += passResult.cleared(); - releasedGraphChanged |= passResult.graphChanged(); - if (passResult.cleared() == 0 || !passResult.graphChanged()) break; - } - } - // A clear or DESTROY can change the root graph. Only share these - // snapshots with a same-boundary global sweep when the targeted pass - // made no such change. - return new ReleasedWeakSweepResult( - releasedGraphChanged ? null : live, - releasedGraphChanged ? null : strongCycleProtected, - countedStrongOwners, - cleared); - } - - /** - * Sweep only objects registered by {@link DestroyDispatch} as needing - * deterministic DESTROY side effects even when they are not weak-ref - * referents. This is intentionally narrower than {@link #sweepWeakRefs}: - * it does not clear unrelated weak references and it can be used from hot - * DBI statement-polling paths without forcing a JVM GC. - */ - public static int sweepDestroyableObjects(boolean forceJvmGc) { - if (!DestroyDispatch.hasDestroyableObjects()) return 0; - if (forceJvmGc) { - ScalarRefRegistry.forceGcAndSnapshot(); - } - ReachabilityWalker w = new ReachabilityWalker(); - return destroyUnreachableDestroyables(w.walk()); - } - - /** Reconcile File::Temp-style external resources at a safe statement boundary. */ - static int sweepStatementBoundaryDestroyableObjects() { - java.util.List candidates = - DestroyDispatch.snapshotStatementBoundaryDestroyableObjects(); - if (candidates.isEmpty()) return 0; - Set candidateSet = Collections.newSetFromMap(new IdentityHashMap<>()); - candidateSet.addAll(candidates); - releaseUnreachableScopeExitedCaptureOwners( - PerlRuntime.snapshotOwnerSlotReferents(), null, candidateSet); - Set live = new ReachabilityWalker().walk(); - return destroyUnreachableDestroyables(candidates, live); - } - - private static int destroyUnreachableDestroyables(Set live) { - return destroyUnreachableDestroyables( - DestroyDispatch.snapshotDestroyableObjects(), live); - } - - private static int destroyUnreachableDestroyables( - java.util.List candidates, Set live) { - int destroyed = 0; - for (RuntimeBase referent : candidates) { - if (referent == null - || referent.destroyFired - || referent.currentlyDestroying - || referent.refCount == Integer.MIN_VALUE) { - continue; - } - if (live.contains(referent)) { - continue; - } - if ((referent instanceof RuntimeHash || referent instanceof RuntimeArray) - && referent.localBindingExists) { - continue; - } - referent.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(referent); - destroyed++; - } - return destroyed; - } - - private static Set collectStrongCycleProtected(Set live) { - java.util.List referents = WeakRefRegistry.snapshotWeakRefReferents(); - if (referents.isEmpty()) return Collections.emptySet(); - - Set protectedSet = - Collections.newSetFromMap(new IdentityHashMap<>()); - for (RuntimeBase referent : referents) { - // A root-reachable referent and its strong descendants are already - // represented by the main sweep walk. Cycle checks are only needed - // for weak targets that would otherwise be mistaken for dead - // cycle islands. - if (referent == null || live.contains(referent) || protectedSet.contains(referent)) { - continue; - } - if (hasStrongCycle(referent)) { - collectStrongReachable(referent, protectedSet); - } - } - return protectedSet; - } - - static Set strongCycleProtectedReferents() { - return collectStrongCycleProtected(Collections.emptySet()); - } - - private static void collectStrongReachable(RuntimeBase root, Set seen) { - final int MAX_VISITS = 50_000; - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - if (seen.add(root)) { - todo.addLast(root); - } - - int visits = 0; - while (!todo.isEmpty() && visits < MAX_VISITS) { - RuntimeBase cur = todo.removeFirst(); - visits++; - enqueueStrongEdges(cur, null, seen, todo); - } - } - - private static WeakBackrefCaptureSnapshot weakBackrefCaptureSnapshot() { - ReachabilityQueryStats stats = MortalList.activeReachabilityQueryStats(); - if (stats != null) stats.weakBackrefCaptureSnapshotsBuilt++; - Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - RootWalkBudget budget = new RootWalkBudget(MAX_ROOT_SNAPSHOT_EDGES); - for (RuntimeBase referent : WeakRefRegistry.snapshotWeakRefReferents()) { - if (referent instanceof RuntimeCode code - && WeakRefRegistry.hasWeakRefsTo(code)) { - if (stats != null) stats.weakBackrefCaptureRootsWalked++; - followGlobalCodeCaptures(code, null, seen, todo, budget); - if (!budget.complete) break; - } - } - int visits = 0; - while (!todo.isEmpty() && visits < MAX_WEAK_BACKREF_CAPTURE_VISITS) { - RuntimeBase cur = todo.removeFirst(); - visits++; - if (stats != null) stats.weakBackrefCaptureNodesVisited++; - if (cur instanceof RuntimeStash) { - continue; - } else if (cur instanceof RuntimeHash h) { - if (h.elements instanceof HashSpecialVariable) continue; - for (RuntimeScalar v : h.elements.values()) { - if (!budget.visitEdge()) break; - if (stats != null) stats.weakBackrefCaptureEdgesInspected++; - followScalar(v, null, seen, todo); - } - } else if (cur instanceof RuntimeArray a) { - for (RuntimeScalar v : a.elements) { - if (!budget.visitEdge()) break; - if (stats != null) stats.weakBackrefCaptureEdgesInspected++; - followScalar(v, null, seen, todo); - } - } else if (cur instanceof RuntimeCode nestedCode) { - followGlobalCodeCaptures(nestedCode, null, seen, todo, budget); - } else if (cur instanceof RuntimeScalar s) { - if (!budget.visitEdge()) break; - if (stats != null) stats.weakBackrefCaptureEdgesInspected++; - followScalar(s, null, seen, todo); - } - if (!budget.complete) break; - } - boolean complete = budget.complete - && todo.isEmpty() && visits < MAX_WEAK_BACKREF_CAPTURE_VISITS; - return new WeakBackrefCaptureSnapshot(seen, complete); - } -} diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RegexCallbackMutationSnapshot.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RegexCallbackMutationSnapshot.java index a1b5da4b52..be1e40fb79 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RegexCallbackMutationSnapshot.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RegexCallbackMutationSnapshot.java @@ -69,16 +69,31 @@ private void capture(ArrayDeque work) { } public void restore() { - for (Map.Entry entry : arrays.entrySet()) { - entry.getKey().restoreRegexMutationState(entry.getValue()); + try { + for (Map.Entry entry : arrays.entrySet()) { + entry.getKey().restoreRegexMutationState(entry.getValue()); + } + for (Map.Entry entry : hashes.entrySet()) { + entry.getKey().restoreRegexMutationState(entry.getValue()); + } + for (Map.Entry entry : scalars.entrySet()) { + entry.getKey().restoreRegexMutationState(entry.getValue()); + } + MortalList.flush(); + } finally { + discard(); } + } + + /** Release rollback-only Perl owners when the callback's mutations commit. */ + public void discard() { for (Map.Entry entry : hashes.entrySet()) { - entry.getKey().restoreRegexMutationState(entry.getValue()); - } - for (Map.Entry entry : scalars.entrySet()) { - entry.getKey().restoreRegexMutationState(entry.getValue()); + entry.getKey().discardRegexMutationState(entry.getValue()); } - MortalList.flush(); + hashes.clear(); + arrays.clear(); + scalars.clear(); + seen.clear(); } private static void addAll(ArrayDeque work, diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeArray.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeArray.java index e343c14240..90210123d1 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeArray.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeArray.java @@ -93,6 +93,10 @@ private static Stack dynamicStateStack() { // Direct lvalue stores into ordinary arrays can flip elementsOwned on, but // alias arrays must stay non-owning so shift/pop do not consume caller refs. public boolean elementsAliased; + /** Scalar cells retained by explicit refalias list assignment. */ + private IdentityHashMap referenceListAliasCellOwners; + private boolean referenceListAliasOwnerTracking; + private int referenceListAliasOwnerMutationDepth; // True only for a syntactic @array expansion at a subroutine call site. // `undef @array` must invalidate those cells as well as removing slots. private boolean elementSlotsAliasedIntoCallFrame; @@ -131,7 +135,7 @@ void endScalarLocalElement() { // compiled method whose body only updates the two proven hash cells. private RuntimeScalar verifiedMethodHashArgument; private boolean verifiedMethodHashFieldsActive; - private boolean suppressMethodArgumentRootTracking; + private boolean stableMethodArgumentRecycle; private RuntimeScalar verifiedMethodIntegerArgument; private RuntimeScalar verifiedMethodFirstHashCell; private RuntimeScalar verifiedMethodSecondHashCell; @@ -232,18 +236,20 @@ void recycleMethodCallArguments(ExecutionRuntimeState executionState) { private void resetRecycledMethodCallArguments() { clearVerifiedMethodHashFields(); - if (suppressMethodArgumentRootTracking + if (stableMethodArgumentRecycle && elements instanceof InlineMethodArgumentList inlineArguments) { inlineArguments.clearForStableMethodRecycle(); } else { elements.clear(); } - suppressMethodArgumentRootTracking = false; + stableMethodArgumentRecycle = false; type = PLAIN_ARRAY; strictAutovivify = false; scalarContextSize = null; elementsOwned = false; elementsAliased = false; + referenceListAliasOwnerTracking = false; + referenceListAliasOwnerMutationDepth = 0; elementSlotsAliasedIntoCallFrame = false; activeScalarLocalElements = 0; scalarLocalContainerCleared = false; @@ -256,19 +262,17 @@ private void resetRecycledMethodCallArguments() { isaArrayNames = null; } - boolean suppressRootTrackingForStableMethodArguments() { + boolean enableStableMethodArgumentRecycle() { if (type != PLAIN_ARRAY || !(elements instanceof InlineMethodArgumentList) || elements.size() > 2 || threadShared || isPackageGlobalRoot) { return false; } - suppressMethodArgumentRootTracking = true; + stableMethodArgumentRecycle = true; return true; } - void resumeMethodArgumentRootTracking() { - if (!suppressMethodArgumentRootTracking) return; - suppressMethodArgumentRootTracking = false; - notePackageRootClear(elements); + void disableStableMethodArgumentRecycle() { + stableMethodArgumentRecycle = false; } void cacheVerifiedMethodHashFields(int hashArgumentIndex, int integerArgumentIndex, @@ -374,6 +378,25 @@ private RuntimeArrayElementList newElementList(List values) { return list; } + /** Append a scalar cell borrowed by a temporary list-expression result. */ + void addBorrowedListResultValue(RuntimeScalar value) { + if (elements instanceof RuntimeArrayElementList tracked) { + tracked.addBorrowedListResultValue(value); + } else { + elements.add(value); + } + } + + /** Append scalar cells borrowed by a temporary list-expression result. */ + void addBorrowedListResultValues(Collection values) { + for (RuntimeScalar value : values) addBorrowedListResultValue(value); + } + + void replaceWithEmptySharedStorage() { + type = PLAIN_ARRAY; + elements = Collections.synchronizedList(newElementList()); + } + void resetElementListAfterAutovivification() { elements = newElementList(); } @@ -390,7 +413,12 @@ Object snapshotRegexMutationState() { void restoreRegexMutationState(Object token) { if (!(token instanceof RegexMutationState state)) return; deferElementsAddedSince(state.elements); + List replaced = new ArrayList<>(elements); elements = newElementList(state.elements); + for (RuntimeScalar value : replaced) { + if (value != null) value.reconcileContainerOwnerAfterMutation(this); + } + refreshUntrackedElementOwners(); type = state.type; strictAutovivify = state.strictAutovivify; scalarContextSize = state.scalarContextSize; @@ -437,6 +465,13 @@ private RuntimeArrayElementList(RuntimeArray owner, int initialCapacity) { this.owner = owner; } + /** A list result aliases cells already owned by their assignment targets. */ + private void addBorrowedListResultValue(RuntimeScalar value) { + owner.noteIsaMutation(); + super.add(value); + owner.validateIsaMutation(); + } + @Override public boolean add(RuntimeScalar value) { if (owner.threadShared) { @@ -444,10 +479,13 @@ public boolean add(RuntimeScalar value) { SharedPerlStorage.publishBlessing(value); } owner.noteIsaMutation(); - owner.notePackageRootMutation(null, value); - if (value != null) value.markContainerOwner(owner); - owner.markPackageRootedValue(value); boolean changed = super.add(value); + if (changed) { + if (owner.elements == this) owner.retainReferenceListAliasCell(value); + if (value != null) value.markContainerOwner(owner); + owner.markPackageRootedValue(value); + refreshStoredUntrackedOwner(value); + } owner.validateIsaMutation(); return changed; } @@ -459,10 +497,11 @@ public void add(int index, RuntimeScalar element) { SharedPerlStorage.publishBlessing(element); } owner.noteIsaMutation(); - owner.notePackageRootMutation(null, element); + super.add(index, element); + if (owner.elements == this) owner.retainReferenceListAliasCell(element); if (element != null) element.markContainerOwner(owner); owner.markPackageRootedValue(element); - super.add(index, element); + refreshStoredUntrackedOwner(element); owner.validateIsaMutation(); } @@ -470,12 +509,15 @@ public void add(int index, RuntimeScalar element) { public boolean addAll(java.util.Collection c) { if (!owner.threadShared) { if (!c.isEmpty()) owner.noteIsaMutation(); - owner.notePackageRootMutationIf(owner.hasRootEdge(c)); - for (RuntimeScalar value : c) { - if (value != null) value.markContainerOwner(owner); - owner.markPackageRootedValue(value); - } boolean changed = super.addAll(c); + if (changed) { + for (RuntimeScalar value : c) { + if (owner.elements == this) owner.retainReferenceListAliasCell(value); + if (value != null) value.markContainerOwner(owner); + owner.markPackageRootedValue(value); + refreshStoredUntrackedOwner(value); + } + } if (changed) owner.validateIsaMutation(); return changed; } @@ -491,12 +533,15 @@ public boolean addAll(java.util.Collection c) { public boolean addAll(int index, java.util.Collection c) { if (!owner.threadShared) { if (!c.isEmpty()) owner.noteIsaMutation(); - owner.notePackageRootMutationIf(owner.hasRootEdge(c)); - for (RuntimeScalar value : c) { - if (value != null) value.markContainerOwner(owner); - owner.markPackageRootedValue(value); - } boolean changed = super.addAll(index, c); + if (changed) { + for (RuntimeScalar value : c) { + if (owner.elements == this) owner.retainReferenceListAliasCell(value); + if (value != null) value.markContainerOwner(owner); + owner.markPackageRootedValue(value); + refreshStoredUntrackedOwner(value); + } + } if (changed) owner.validateIsaMutation(); return changed; } @@ -516,21 +561,60 @@ public RuntimeScalar set(int index, RuntimeScalar element) { SharedPerlStorage.validateStoredValue(element); SharedPerlStorage.publishBlessing(element); } + if (owner.elements == this) owner.retainReferenceListAliasCell(element); owner.noteIsaMutation(); - owner.notePackageRootMutation(previous, element); + RuntimeScalar result = super.set(index, element); if (element != null) element.markContainerOwner(owner); owner.markPackageRootedValue(element); - RuntimeScalar result = super.set(index, element); + refreshStoredUntrackedOwner(element); + if (previous != element) { + if (previous != null) { + previous.reconcileContainerOwnerAfterMutation(owner); + } + RuntimeCode.argumentArraySlotRemoved(owner, previous); + } + owner.reconcileReferenceListAliasCellOwners(); owner.validateIsaMutation(); return result; } + private void refreshStoredUntrackedOwner(RuntimeScalar value) { + // Copy construction populates a replacement list before assigning + // it to owner.elements. Defer refresh until this list is installed. + if (value != null && owner.elements == this) { + if (owner.isPackageGlobalRoot) { + value.markPrepopulatedPackageAggregateOwner(owner); + } + value.refreshUntrackedReferenceOwner(); + } + } + @Override public RuntimeScalar remove(int index) { RuntimeScalar previous = super.remove(index); + owner.reconcileReferenceListAliasCellOwners(); + if (previous != null) previous.reconcileContainerOwnerAfterMutation(owner); owner.noteIsaMutation(); - owner.notePackageRootMutation(previous, null); owner.validateIsaMutation(); + RuntimeCode.argumentArraySlotRemoved(owner, previous); + return previous; + } + + @Override + public RuntimeScalar removeFirst() { + RuntimeScalar previous = super.removeFirst(); + owner.reconcileReferenceListAliasCellOwners(); + if (previous != null) previous.reconcileContainerOwnerAfterMutation(owner); + RuntimeCode.argumentArraySlotRemoved(owner, previous); + return previous; + } + + @Override + public RuntimeScalar removeLast() { + RuntimeScalar previous = super.removeLast(); + owner.reconcileReferenceListAliasCellOwners(); + if (previous != null) previous.reconcileContainerOwnerAfterMutation(owner); + RuntimeCode.argumentArraySlotRemoved(owner, previous); return previous; } @@ -538,9 +622,11 @@ public RuntimeScalar remove(int index) { public boolean remove(Object o) { boolean removed = super.remove(o); if (removed && o instanceof RuntimeScalar scalar) { + owner.reconcileReferenceListAliasCellOwners(); + scalar.reconcileContainerOwnerAfterMutation(owner); owner.noteIsaMutation(); - owner.notePackageRootMutation(scalar, null); owner.validateIsaMutation(); + RuntimeCode.argumentArraySlotRemoved(owner, scalar); } return removed; } @@ -548,12 +634,86 @@ public boolean remove(Object o) { @Override public void clear() { if (!isEmpty()) { + RuntimeScalar[] removed = toArray(new RuntimeScalar[0]); owner.noteIsaMutation(); - owner.notePackageRootClear(this); + for (RuntimeScalar scalar : removed) { + RuntimeCode.argumentArraySlotRemoved(owner, scalar); + } + super.clear(); + for (RuntimeScalar scalar : removed) { + if (scalar != null) scalar.reconcileContainerOwnerAfterMutation(owner); + } + owner.reconcileReferenceListAliasCellOwners(); + owner.validateIsaMutation(); + return; } super.clear(); + owner.reconcileReferenceListAliasCellOwners(); owner.validateIsaMutation(); } + + @Override + protected void removeRange(int fromIndex, int toIndex) { + List removed = new ArrayList<>(subList(fromIndex, toIndex)); + for (int i = fromIndex; i < toIndex; i++) { + RuntimeCode.argumentArraySlotRemoved(owner, get(i)); + } + super.removeRange(fromIndex, toIndex); + for (RuntimeScalar scalar : removed) { + if (scalar != null) scalar.reconcileContainerOwnerAfterMutation(owner); + } + owner.reconcileReferenceListAliasCellOwners(); + } + + @Override + public boolean removeIf(java.util.function.Predicate filter) { + Objects.requireNonNull(filter); + boolean changed = false; + Iterator iterator = iterator(); + while (iterator.hasNext()) { + RuntimeScalar removed = iterator.next(); + if (filter.test(removed)) { + iterator.remove(); + if (removed != null) removed.reconcileContainerOwnerAfterMutation(owner); + changed = true; + } + } + owner.reconcileReferenceListAliasCellOwners(); + return changed; + } + + @Override + public boolean removeAll(java.util.Collection values) { + Objects.requireNonNull(values); + return removeMatching(values, false); + } + + @Override + public boolean retainAll(java.util.Collection values) { + Objects.requireNonNull(values); + return removeMatching(values, true); + } + + private boolean removeMatching(java.util.Collection values, boolean retainMatches) { + java.util.List membership = new ArrayList<>(values); + boolean changed = false; + for (int index = size() - 1; index >= 0; index--) { + RuntimeScalar value = get(index); + if (membership.contains(value) != retainMatches) { + remove(index); + changed = true; + } + } + return changed; + } + + @Override + public void replaceAll(java.util.function.UnaryOperator operator) { + Objects.requireNonNull(operator); + for (int i = 0; i < size(); i++) { + set(i, operator.apply(get(i))); + } + } } /** Compact backing for the common one-argument method call plus invocant. */ @@ -595,6 +755,11 @@ public RuntimeScalar set(int index, RuntimeScalar element) { second = element; result = previous; } + if (element != null) element.markContainerOwner(owner); + owner.markPackageRootedValue(element); + if (previous != element && previous != null) { + previous.reconcileContainerOwnerAfterMutation(owner); + } if (owner.isaArray) owner.validateIsaMutation(); return result; } @@ -624,6 +789,8 @@ public void add(int index, RuntimeScalar element) { first = null; second = null; } + if (element != null) element.markContainerOwner(owner); + owner.markPackageRootedValue(element); modCount++; if (owner.isaArray) owner.validateIsaMutation(); } @@ -633,11 +800,7 @@ private void prepend(RuntimeScalar element) { add(0, element); return; } - if (owner.suppressMethodArgumentRootTracking && !owner.isaArray) { - if (element != null) element.markContainerOwner(owner); - } else { - prepareStoredValue(null, element); - } + prepareStoredValue(null, element); if (inlineSize == 0) { first = element; inlineSize = 1; @@ -646,6 +809,8 @@ private void prepend(RuntimeScalar element) { first = element; inlineSize = 2; } + if (element != null) element.markContainerOwner(owner); + owner.markPackageRootedValue(element); modCount++; if (owner.isaArray) owner.validateIsaMutation(); } @@ -668,13 +833,12 @@ public boolean addAll(int index, Collection values) { return true; } if (owner.isaArray) owner.noteIsaMutation(); - owner.notePackageRootMutationIf(owner.hasRootEdge(source)); + int insertionIndex = index; + for (RuntimeScalar value : source) addRaw(insertionIndex++, value); for (RuntimeScalar value : source) { if (value != null) value.markContainerOwner(owner); owner.markPackageRootedValue(value); } - int insertionIndex = index; - for (RuntimeScalar value : source) addRaw(insertionIndex++, value); modCount++; if (owner.isaArray) owner.validateIsaMutation(); return true; @@ -719,23 +883,26 @@ public RuntimeScalar remove(int index) { } modCount++; if (owner.isaArray) owner.noteIsaMutation(); - owner.notePackageRootMutation(previous, null); + if (previous != null) previous.reconcileContainerOwnerAfterMutation(owner); if (owner.isaArray) owner.validateIsaMutation(); + RuntimeCode.argumentArraySlotRemoved(owner, previous); return previous; } @Override public void clear() { if (isEmpty()) return; + List removed = new ArrayList<>(); + for (int i = 0; i < size(); i++) removed.add(get(i)); if (owner.isaArray) owner.noteIsaMutation(); - if (!owner.suppressMethodArgumentRootTracking) { - owner.notePackageRootClear(this); - } if (expanded != null) expanded.clear(); first = null; second = null; inlineSize = 0; modCount++; + for (RuntimeScalar scalar : removed) { + if (scalar != null) scalar.reconcileContainerOwnerAfterMutation(owner); + } if (owner.isaArray) owner.validateIsaMutation(); } @@ -753,11 +920,6 @@ private void prepareStoredValue(RuntimeScalar previous, RuntimeScalar element) { SharedPerlStorage.publishBlessing(element); } owner.noteIsaMutation(); - if (!owner.suppressMethodArgumentRootTracking) { - owner.notePackageRootMutation(previous, element); - } - if (element != null) element.markContainerOwner(owner); - owner.markPackageRootedValue(element); } } @@ -787,62 +949,112 @@ private void validateIsaMutation() { } } - private static boolean rootEdge(RuntimeScalar value) { - return value != null - && (value.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && value.value instanceof RuntimeBase; + void markPackageRootedValue(RuntimeScalar value) { + if (isPackageGlobalRoot && !elementsAliased && value != null) { + value.isPackageGlobalRoot = true; + value.markContainerOwner(this); + if (value.value instanceof RuntimeBase referent) { + referent.storedInPackageGlobal = true; + } + } } - private boolean hasRootEdge(java.util.Collection values) { - for (RuntimeScalar value : values) { - if (rootEdge(value)) return true; + private void markPackageRootedValues(int fromIndex) { + if (!isPackageGlobalRoot) return; + for (int i = Math.max(0, fromIndex); i < elements.size(); i++) { + RuntimeScalar value = elements.get(i); + markPackageRootedValue(value); + if (value != null) { + value.markPrepopulatedPackageAggregateOwner(this); + value.refreshUntrackedReferenceOwner(); + } } - return false; } - private void notePackageRootMutation(RuntimeScalar oldValue, RuntimeScalar newValue) { - notePackageRootMutationIf(rootEdge(oldValue) || rootEdge(newValue)); + void refreshUntrackedElementOwners() { + refreshUntrackedElementOwners(false); } - private void notePackageRootMutationIf(boolean hasReferenceEdge) { - if (!hasReferenceEdge) return; - if (isPackageGlobalRoot) { - MortalList.invalidateExternalRootSnapshot(); + void refreshUntrackedElementOwnersAfterTransfer() { + refreshUntrackedElementOwners(true); + } + + private void refreshUntrackedElementOwners(boolean afterTransfer) { + if (elements == null) return; + for (RuntimeScalar value : new ArrayList<>(elements)) { + if (value == null) continue; + if (afterTransfer) value.reconcileContainerOwnerAfterAggregateTransfer(this); + else value.reconcileContainerOwnerAfterMutation(this); } - MortalList.invalidateFullRootSnapshotIfReachable(this); } - private void notePackageRootClear(java.util.Collection values) { - notePackageRootMutationIf(hasRootEdge(values)); + public void markOwnedAliasElement(RuntimeScalar scalar) { + if (scalar == null) return; + if (ownedAliasElements == null) { + ownedAliasElements = Collections.newSetFromMap(new IdentityHashMap<>()); + } + ownedAliasElements.add(scalar); + elementsOwned = true; + } + + private void retainReferenceListAliasCell(RuntimeScalar scalar) { + if (!referenceListAliasOwnerTracking || scalar == null) return; + retainArrayAliasCell(scalar); } - void notePackageRootMutation() { - if (isPackageGlobalRoot) { - MortalList.invalidateExternalRootSnapshot(); + /** Retain one scalar cell stored by refaliasing into an array slot. */ + void retainArrayAliasCell(RuntimeScalar scalar) { + if (scalar == null) return; + if (referenceListAliasCellOwners == null) { + referenceListAliasCellOwners = new IdentityHashMap<>(); } - MortalList.invalidateFullRootSnapshotIfReachable(this); + if (referenceListAliasCellOwners.containsKey(scalar)) return; + PerlOwnerSlot owner = new PerlOwnerSlot(PerlOwnerSlot.Kind.ARRAY_ALIAS_CELL); + owner.acquireArrayAliasCellIdentity(scalar, this); + referenceListAliasCellOwners.put(scalar, owner); } - void markPackageRootedValue(RuntimeScalar value) { - if (isPackageGlobalRoot && value != null) { - value.isPackageGlobalRoot = true; + /** Acquire the cell owner before publishing a scalar refalias in this slot. */ + void setAliasedScalarCell(int index, RuntimeScalar scalar) { + retainArrayAliasCell(scalar); + try { + elements.set(index, scalar); + } catch (RuntimeException | Error failure) { + reconcileReferenceListAliasCellOwners(); + throw failure; } } - private void markPackageRootedValues(int fromIndex) { - if (!isPackageGlobalRoot) return; - for (int i = Math.max(0, fromIndex); i < elements.size(); i++) { - markPackageRootedValue(elements.get(i)); + private void reconcileReferenceListAliasCellOwners() { + if (referenceListAliasOwnerMutationDepth != 0 + || referenceListAliasCellOwners == null) return; + for (RuntimeScalar cell : new ArrayList<>(referenceListAliasCellOwners.keySet())) { + if (elements.contains(cell)) continue; + PerlOwnerSlot owner = referenceListAliasCellOwners.remove(cell); + if (owner != null) owner.release(); } + if (referenceListAliasCellOwners.isEmpty()) referenceListAliasCellOwners = null; } - public void markOwnedAliasElement(RuntimeScalar scalar) { - if (scalar == null) return; - if (ownedAliasElements == null) { - ownedAliasElements = Collections.newSetFromMap(new IdentityHashMap<>()); + void releaseReferenceListAliasCellOwners() { + if (referenceListAliasCellOwners != null) { + ArrayList owners = new ArrayList<>(referenceListAliasCellOwners.values()); + referenceListAliasCellOwners.clear(); + referenceListAliasCellOwners = null; + for (PerlOwnerSlot owner : owners) owner.release(); } - ownedAliasElements.add(scalar); - elementsOwned = true; + referenceListAliasOwnerTracking = false; + referenceListAliasOwnerMutationDepth = 0; + } + + boolean ownsReferenceListAliasCellOwner(PerlOwnerSlot owner, RuntimeBase cell) { + if (owner == null || !(cell instanceof RuntimeScalar scalar) + || referenceListAliasCellOwners == null + || !elements.contains(scalar) + || owner.arrayAliasOwner() != this) { + return false; + } + return referenceListAliasCellOwners.get(scalar) == owner; } public boolean ownsElement(RuntimeScalar scalar) { @@ -851,6 +1063,51 @@ public boolean ownsElement(RuntimeScalar scalar) { return ownedAliasElements != null && ownedAliasElements.contains(scalar); } + /** Check the exact counted slot before a structural mutation removes it. */ + static boolean hasCurrentCountedArrayElementOwner( + RuntimeArray array, RuntimeScalar scalar) { + if (array == null || scalar == null + || !(scalar.value instanceof RuntimeBase referent)) return false; + PerlOwnerSlot slot = scalar.countedOwnerSlot(); + return !RuntimeCode.isCurrentArgumentAlias(scalar) + && scalar.containerOwner == array + && slot != null + && slot.kind() == PerlOwnerSlot.Kind.ARRAY_ELEMENT + && scalar.isCurrentAggregateElementOwner(referent, slot); + } + + /** Transfer a removed slot using its pre-mutation owner proof if needed. */ + static void deferRemovedElementRelease( + RuntimeArray array, RuntimeScalar scalar, String releaseSite, + boolean currentCountedArrayElementOwner) { + if ((array.ownsElement(scalar) || currentCountedArrayElementOwner) + && scalar.refCountOwned + && ((scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 + || scalar.type == RuntimeScalarType.GLOB) + && scalar.value instanceof RuntimeBase base + && base.refCount > 0) { + array.forgetOwnedAliasElement(scalar); + MortalList.deferDecrementFromArraySlot(base, scalar, releaseSite); + } + } + + /** Whole-array replacement releases owned SVs, preserving borrowed caller cells. */ + private void deferOwnedElementReleases() { + if (!elementsAliased) { + MortalList.deferDestroyForContainerClear(elements); + } else if (ownedAliasElements != null) { + MortalList.deferDestroyForContainerClear(new ArrayList<>(ownedAliasElements)); + ownedAliasElements = null; + elementsOwned = false; + } + } + + private List ownedElementReleaseSnapshot() { + if (!elementsAliased) return new ArrayList<>(elements); + if (ownedAliasElements == null || ownedAliasElements.isEmpty()) return List.of(); + return new ArrayList<>(ownedAliasElements); + } + public void forgetOwnedAliasElement(RuntimeScalar scalar) { if (ownedAliasElements == null || scalar == null) return; ownedAliasElements.remove(scalar); @@ -872,6 +1129,7 @@ public void forgetOwnedAliasElement(RuntimeScalar scalar) { */ public RuntimeArray(List list) { this.elements = newElementList(list); + refreshUntrackedElementOwners(); } public RuntimeArray(RuntimeBase... values) { @@ -917,28 +1175,23 @@ public static RuntimeScalar pop(RuntimeArray runtimeArray) { if (runtimeArray.isEmpty()) { yield new RuntimeScalar(); // Return undefined if empty } - runtimeArray.notePackageRootMutation(); + RuntimeScalar candidate = runtimeArray.elements.getLast(); + boolean countedArraySlot = + hasCurrentCountedArrayElementOwner(runtimeArray, candidate); + if (candidate != null) { + deferRemovedElementRelease(runtimeArray, candidate, "RuntimeArray.pop", + countedArraySlot); + } RuntimeScalar result = runtimeArray.elements.removeLast(); // Sparse arrays can have null elements - return undef in that case if (result != null) { // If this element owned a refCount (stored via push or array assignment), // defer the decrement so the caller can capture the value first. // This matches Perl 5's sv_2mortal on popped values. - // Only do this for arrays that own their elements (elementsOwned=true). - // @_ uses aliasing (setArrayOfAlias) without refCount increments, - // so its elements must NOT be mortal-ized on shift/pop — doing so - // would corrupt the caller's refCount tracking. - if (runtimeArray.ownsElement(result) && result.refCountOwned - && (result.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && result.value instanceof RuntimeBase base - && base.refCount > 0) { - result.refCountOwned = false; - runtimeArray.forgetOwnedAliasElement(result); - base.releaseActiveOwner(result); - MortalList.requestWeakSweepsForDestroyedContainer(base); - MortalList.deferDecrementFromArraySlot( - base, result, "RuntimeArray.pop"); - } + // Release only an owned element. The pre-mutation slot proof + // handles counted owners even when the legacy summary flag is + // stale; borrowed @_ cells have no ARRAY_ELEMENT owner and + // must not consume the caller's reference. yield result; } yield scalarUndef; @@ -965,23 +1218,18 @@ public static RuntimeScalar shift(RuntimeArray runtimeArray) { if (runtimeArray.isEmpty()) { yield new RuntimeScalar(); // Return undefined if empty } - runtimeArray.notePackageRootMutation(); + RuntimeScalar candidate = runtimeArray.elements.getFirst(); + boolean countedArraySlot = + hasCurrentCountedArrayElementOwner(runtimeArray, candidate); + if (candidate != null) { + deferRemovedElementRelease(runtimeArray, candidate, "RuntimeArray.shift", + countedArraySlot); + } RuntimeScalar result = runtimeArray.elements.removeFirst(); // Sparse arrays can have null elements - return undef in that case if (result != null) { // If this element owned a refCount, defer the decrement. - // See pop() for rationale and elementsOwned guard. - if (runtimeArray.ownsElement(result) && result.refCountOwned - && (result.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && result.value instanceof RuntimeBase base - && base.refCount > 0) { - result.refCountOwned = false; - runtimeArray.forgetOwnedAliasElement(result); - base.releaseActiveOwner(result); - MortalList.requestWeakSweepsForDestroyedContainer(base); - MortalList.deferDecrementFromArraySlot( - base, result, "RuntimeArray.shift"); - } + // See pop() for the owner identity rationale. yield result; } yield scalarUndef; @@ -1021,29 +1269,70 @@ public static RuntimeScalar push(RuntimeArray runtimeArray, RuntimeBase value) { case PLAIN_ARRAY -> { int sizeBefore = runtimeArray.elements.size(); boolean wasAliased = runtimeArray.elementsAliased; - runtimeArray.notePackageRootMutation(); - value.addToArray(runtimeArray); - runtimeArray.markPackageRootedValues(sizeBefore); - // Increment refCount for tracked references stored by push. - // addToArray creates copies via copy constructor (no refCount increment), - // so we must account for the container store here, matching the behavior - // of array assignment (setFromList) which also calls this. - for (int i = sizeBefore; i < runtimeArray.elements.size(); i++) { - RuntimeScalar elem = runtimeArray.elements.get(i); - if (!wasAliased && runtimeArray.hasDurableElementLifetime()) { - RuntimeScalar.retainUnstashedIoForDurableSlot(elem); - } - RuntimeScalar.incrementRefCountForContainerStore(elem); - if (wasAliased) { - runtimeArray.markOwnedAliasElement(elem); + RuntimeArray staged = new RuntimeArray(); + value.addToArray(staged); + PerlOwnerSlot.Kind ownerKind = wasAliased + ? PerlOwnerSlot.Kind.SCALAR_CELL + : PerlOwnerSlot.Kind.ARRAY_ELEMENT; + if (runtimeArray.threadShared) { + // Shared storage validates each STORE in order. Keep the + // accepted prefix if a later value is rejected, as Perl + // does for push(@shared, ...). + for (RuntimeScalar elem : staged.elements) { + SharedPerlStorage.validateStoredValue(elem); + SharedPerlStorage.publishBlessing(elem); + if (!wasAliased && runtimeArray.hasDurableElementLifetime()) { + RuntimeScalar.retainUnstashedIoForDurableSlot(elem); + } + int index = runtimeArray.elements.size(); + RuntimeScalar.transitionContainerSlots( + List.of(), + elem == null ? List.of() : Collections.singletonList(elem), + ownerKind, + runtimeArray, + () -> { + runtimeArray.elements.add(elem); + runtimeArray.markPackageRootedValues(index); + if (wasAliased) { + runtimeArray.markOwnedAliasElement(elem); + runtimeArray.elementsAliased = true; + } else { + runtimeArray.elementsOwned = true; + runtimeArray.elementsAliased = false; + runtimeArray.ownedAliasElements = null; + } + }, + null); } - } - if (wasAliased) { - runtimeArray.elementsAliased = true; + staged.elements.clear(); } else { - runtimeArray.elementsOwned = true; - runtimeArray.elementsAliased = false; - runtimeArray.ownedAliasElements = null; + for (RuntimeScalar elem : staged.elements) { + if (!wasAliased && runtimeArray.hasDurableElementLifetime()) { + RuntimeScalar.retainUnstashedIoForDurableSlot(elem); + } + } + RuntimeScalar.transitionContainerSlots( + List.of(), staged.elements, ownerKind, runtimeArray, + () -> { + runtimeArray.elements.addAll(staged.elements); + runtimeArray.markPackageRootedValues(sizeBefore); + for (int index = sizeBefore; + index < runtimeArray.elements.size(); index++) { + if (wasAliased) { + runtimeArray.markOwnedAliasElement( + runtimeArray.elements.get(index)); + } + } + staged.elements.clear(); + if (wasAliased) { + runtimeArray.elementsAliased = true; + } else { + runtimeArray.elementsOwned = true; + runtimeArray.elementsAliased = false; + runtimeArray.ownedAliasElements = null; + } + }, + null); } yield getScalarInt(runtimeArray.elements.size()); } @@ -1077,7 +1366,6 @@ public static RuntimeScalar unshift(RuntimeArray runtimeArray, RuntimeBase value boolean wasAliased = runtimeArray.elementsAliased; RuntimeArray arr = new RuntimeArray(); RuntimeArray.push(arr, value); - runtimeArray.notePackageRootMutation(); runtimeArray.elements.addAll(0, arr.elements); runtimeArray.markPackageRootedValues(0); if (wasAliased) { @@ -1188,8 +1476,14 @@ public void add(RuntimeScalar value) { // {@link RuntimeScalar#addToArray} for the full analysis and // minimal repro. RuntimeScalar copy = new RuntimeScalar(value); - elements.add(copy); - RuntimeScalar.incrementRefCountForContainerStore(copy); + if (threadShared) { + SharedPerlStorage.validateStoredValue(copy); + SharedPerlStorage.publishBlessing(copy); + } + RuntimeScalar.transitionContainerSlots( + List.of(), Collections.singletonList(copy), PerlOwnerSlot.Kind.ARRAY_ELEMENT, + this, + () -> elements.add(copy), null); } /** @@ -1199,14 +1493,20 @@ public void add(RuntimeScalar value) { * array slot. */ public void addClonedElement(RuntimeScalar value) { - elements.add(value); if (value != null) { - value.markContainerOwner(this); + if (threadShared) { + SharedPerlStorage.validateStoredValue(value); + SharedPerlStorage.publishBlessing(value); + } if (hasDurableElementLifetime()) { RuntimeScalar.retainUnstashedIoForDurableSlot(value); } - RuntimeScalar.incrementRefCountForContainerStore(value); } + RuntimeScalar.transitionContainerSlots( + List.of(), value == null ? List.of() : Collections.singletonList(value), + PerlOwnerSlot.Kind.ARRAY_ELEMENT, + this, + () -> elements.add(value), null); } public void add(RuntimeArray value) { @@ -1328,7 +1628,14 @@ public RuntimeScalar delete(int index) { } yield previous; } + RuntimeScalar ownerScalar = elements.get(index); + boolean countedArraySlot = + hasCurrentCountedArrayElementOwner(this, ownerScalar); RuntimeScalar previous = this.get(index); + if (ownerScalar != null) { + deferRemovedElementRelease(this, ownerScalar, "RuntimeArray.delete", + countedArraySlot); + } this.elements.set(index, null); yield previous; } @@ -1515,6 +1822,7 @@ public void dynamicSaveState() { @Override public void dynamicRestoreState() { + boolean releasedLocalizedOwner = false; // undef @array can remove the container slots while one or // more element locals are active. Restore the pre-local // container shape first; nested local states then restore @@ -1530,7 +1838,18 @@ public void dynamicRestoreState() { // Remove the localized slot itself, but retain values // assigned to intervening slots during the scope. while (self.elements.size() > idx) { - self.elements.removeLast(); + RuntimeScalar candidate = self.elements.getLast(); + boolean countedArraySlot = + hasCurrentCountedArrayElementOwner(self, candidate); + if (candidate != null) { + MortalList.deferIoOwnerRelease(candidate); + deferRemovedElementRelease(self, candidate, + "RuntimeArray.deleteLocal", countedArraySlot); + } + RuntimeScalar removed = self.elements.removeLast(); + if (removed != null) { + releasedLocalizedOwner = true; + } } while (self.elements.size() > savedSize && isEmptyLocalPlaceholder(self.elements.getLast())) { @@ -1543,11 +1862,30 @@ && isEmptyLocalPlaceholder(self.elements.getLast())) { } if (existed) { if (idx < self.elements.size()) { + RuntimeScalar displaced = self.elements.get(idx); + boolean countedArraySlot = + hasCurrentCountedArrayElementOwner(self, displaced); + if (displaced != null && displaced != savedValue) { + MortalList.deferIoOwnerRelease(displaced); + deferRemovedElementRelease(self, displaced, + "RuntimeArray.deleteLocal", countedArraySlot); + releasedLocalizedOwner = true; + } self.elements.set(idx, savedValue); } } else if (idx >= 0 && idx < self.elements.size()) { + RuntimeScalar displaced = self.elements.get(idx); + boolean countedArraySlot = + hasCurrentCountedArrayElementOwner(self, displaced); + if (displaced != null) { + MortalList.deferIoOwnerRelease(displaced); + deferRemovedElementRelease(self, displaced, + "RuntimeArray.deleteLocal", countedArraySlot); + releasedLocalizedOwner = true; + } self.elements.set(idx, null); } + if (releasedLocalizedOwner) MortalList.flush(); } }); @@ -1830,13 +2168,27 @@ public RuntimeArray set(RuntimeScalar value) { throw new PerlCompilerException("Modification of a read-only value attempted"); } this.eachIteratorIndex = null; - notePackageRootMutation(); - MortalList.deferDestroyForContainerClear(this.elements); - this.elements.clear(); - this.ownedAliasElements = null; - this.elementsAliased = false; - this.elements.add(value); - markPackageRootedValue(value); + if (value != null) { + if (hasDurableElementLifetime()) { + RuntimeScalar.retainUnstashedIoForDurableSlot(value); + } + } + List displaced = ownedElementReleaseSnapshot(); + Collection replacements = value == null + ? List.of() : Collections.singletonList(value); + RuntimeScalar.transitionContainerSlots( + displaced, replacements, PerlOwnerSlot.Kind.ARRAY_ELEMENT, + this, + () -> { + this.elements.clear(); + releaseReferenceListAliasCellOwners(); + this.ownedAliasElements = null; + this.elementsAliased = false; + this.elements.add(value); + elementsOwned = true; + markPackageRootedValue(value); + }, + MortalList::deferDestroyForContainerClear); MortalList.flush(); return this; } @@ -1852,7 +2204,6 @@ public RuntimeArray setFromList(RuntimeList list) { return switch (type) { case PLAIN_ARRAY -> { this.eachIteratorIndex = null; - notePackageRootMutation(); // Check if the list contains references to this array's elements // If so, we need to save the values before clearing boolean needsCopy = false; @@ -1863,10 +2214,10 @@ public RuntimeArray setFromList(RuntimeList list) { } } - int originalSize = this.elements.size(); - MortalList.deferDestroyForContainerClear(this.elements); + RuntimeList source = list; if (needsCopy) { - // Make a defensive copy of the list before clearing + // Make a defensive source copy before materializing the + // replacement, since the RHS may include this array. RuntimeList listCopy = new RuntimeList(); for (RuntimeBase elem : list.elements) { if (elem instanceof RuntimeArray && elem == this) { @@ -1878,31 +2229,85 @@ public RuntimeArray setFromList(RuntimeList list) { listCopy.elements.add(elem); } } - this.elements.clear(); - listCopy.addToArray(this); - } else { - this.elements.clear(); - list.addToArray(this); + source = listCopy; } - // Increment refCount for tracked references stored in the array. - // addToArray creates copies via the copy constructor (which doesn't - // increment refCount), so we do it here for the final container store. - for (RuntimeScalar elem : this.elements) { - markPackageRootedValue(elem); + // Materialize the RHS and acquire each destination edge before + // replacing the current elements. This keeps the replacement + // alive throughout publication and gives each copied scalar an + // owner identity for this array slot. + RuntimeArray staged = new RuntimeArray(); + source.addToArray(staged); + if (threadShared) { + // An array assignment to shared storage is a sequence of + // validated slot stores. Publish each accepted edge before + // validating the next one so a rejected value leaves the + // same partial result as system Perl. + List displaced = ownedElementReleaseSnapshot(); + RuntimeScalar.transitionContainerSlots( + displaced, List.of(), PerlOwnerSlot.Kind.ARRAY_ELEMENT, this, + () -> { + this.elements.clear(); + releaseReferenceListAliasCellOwners(); + this.elementsOwned = true; + this.elementsAliased = false; + this.ownedAliasElements = null; + }, + MortalList::deferDestroyForContainerClear); + for (RuntimeScalar elem : staged.elements) { + SharedPerlStorage.validateStoredValue(elem); + SharedPerlStorage.publishBlessing(elem); + if (hasDurableElementLifetime()) { + RuntimeScalar.retainUnstashedIoForDurableSlot(elem); + } + int index = this.elements.size(); + RuntimeScalar.transitionContainerSlots( + List.of(), + elem == null ? List.of() : Collections.singletonList(elem), + PerlOwnerSlot.Kind.ARRAY_ELEMENT, + this, + () -> { + this.elements.add(elem); + this.markPackageRootedValues(index); + this.elementsOwned = true; + this.elementsAliased = false; + this.ownedAliasElements = null; + }, + null); + } + staged.elements.clear(); + + RuntimeArray result = new RuntimeArray(); + result.addBorrowedListResultValues(this.elements); + result.scalarContextSize = this.elements.size(); + MortalList.flushAboveMark(); + yield result; + } + for (RuntimeScalar elem : staged.elements) { if (hasDurableElementLifetime()) { RuntimeScalar.retainUnstashedIoForDurableSlot(elem); } - RuntimeScalar.incrementRefCountForContainerStore(elem); } - this.elementsOwned = true; - this.elementsAliased = false; - this.ownedAliasElements = null; + + List displaced = ownedElementReleaseSnapshot(); + RuntimeScalar.transitionContainerSlots( + displaced, staged.elements, PerlOwnerSlot.Kind.ARRAY_ELEMENT, this, + () -> { + this.elements.clear(); + releaseReferenceListAliasCellOwners(); + this.elements.addAll(staged.elements); + this.markPackageRootedValues(0); + staged.elements.clear(); + this.elementsOwned = true; + this.elementsAliased = false; + this.ownedAliasElements = null; + }, + MortalList::deferDestroyForContainerClear); // Create a new array with scalarContextSize set for assignment return value // This is needed for eval context where assignment should return element count RuntimeArray result = new RuntimeArray(); - result.elements.addAll(this.elements); + result.addBorrowedListResultValues(this.elements); result.scalarContextSize = this.elements.size(); // Flush refs removed from this container without draining mortals // owned by a caller frame. A lexical array initialized inside a @@ -1971,7 +2376,7 @@ public RuntimeArray setFromList(RuntimeList list) { * Behavior: *

      *
    1. Defer-decrement any existing counted elements (like normal {@code setFromList}).
    2. - *
    3. Copy new elements in without incrementing their referents' refCounts.
    4. + *
    5. Store the source scalar cells directly, without creating new ref owners.
    6. *
    7. Mark {@code elementsOwned=false} so {@link #shift(RuntimeArray)} * and other removal paths don't defer a spurious decrement.
    8. *
    @@ -1983,20 +2388,24 @@ public RuntimeArray setFromListAliased(RuntimeList list) { return setFromList(list); } this.eachIteratorIndex = null; - notePackageRootMutation(); - MortalList.deferDestroyForContainerClear(this.elements); + this.deferOwnedElementReleases(); this.elements.clear(); - list.addToArray(this); - // Elements are aliases: mark as non-owning. setLarge in later - // overwrites will still work correctly because setLarge checks - // refCountOwned before decrementing. - for (RuntimeScalar elem : this.elements) { - if (elem != null) elem.refCountOwned = false; - markPackageRootedValue(elem); - } - this.elementsOwned = false; + releaseReferenceListAliasCellOwners(); + // This array is a view of existing SV cells. Preserve their identity + // so updates and source-cell cleanup are visible through the alias; + // copying each scalar here creates an extra untracked reference owner + // whose lifetime can outlast the source argument slot. this.elementsAliased = true; + this.elementsOwned = false; this.ownedAliasElements = null; + for (RuntimeBase value : list.elements) { + if (value instanceof RuntimeScalar scalar) { + this.elements.add(scalar); + } else if (value != null) { + value.addToArray(this); + } + } + list.elements.clear(); return this; } @@ -2012,21 +2421,47 @@ public RuntimeArray setFromReferenceList(RuntimeList list) { this.eachIteratorIndex = null; RuntimeArray references = new RuntimeArray(); references.setFromList(list); - notePackageRootMutation(); - MortalList.deferDestroyForContainerClear(this.elements); - this.elements.clear(); + ArrayList referents = new ArrayList<>(references.elements.size()); for (RuntimeScalar reference : references.elements) { - // This is refaliasing, not an ordinary dereference. In - // particular, a reference made after a skipped lexical - // declaration must retain that cell until the declaration runs. - RuntimeScalar referent = reference.refAliasScalarReference(); - this.elements.add(referent); - markPackageRootedValue(referent); - referent.refCountOwned = false; + referents.add(reference.refAliasScalarReference()); + } + referenceListAliasOwnerTracking = true; + referenceListAliasOwnerMutationDepth++; + try { + // Acquire each scalar-cell owner before retiring the old array + // contents. Refaliasing keeps the cell itself alive; it does not + // create a second owner for the reference stored inside that cell. + for (RuntimeScalar referent : referents) { + retainReferenceListAliasCell(referent); + } + this.deferOwnedElementReleases(); + this.elements.clear(); + this.elementsAliased = true; + this.elementsOwned = false; + this.ownedAliasElements = null; + for (RuntimeScalar referent : referents) { + this.elements.add(referent); + markPackageRootedValue(referent); + } + } finally { + referenceListAliasOwnerMutationDepth--; + reconcileReferenceListAliasCellOwners(); + } + // The RHS reference wrappers were needed only to identify the cells. + // Their counted edges transfer to the explicit array-to-cell slots. + if (MortalList.isActive()) { + MortalList.deferDestroyForContainerClear(references.elements); + } else { + for (RuntimeScalar reference : references.elements) { + if (reference != null && reference.refCountOwned + && reference.value instanceof RuntimeBase referent + && referent.refCount > 0) { + MortalList.releaseCountedOwnerImmediately( + reference, "RuntimeArray.setArrayOfAlias reference wrapper"); + } + } } - this.elementsOwned = false; - this.elementsAliased = true; - this.ownedAliasElements = null; + references.elements.clear(); return this; } @@ -2046,16 +2481,16 @@ public RuntimeList referenceListFrom(int start) { */ public RuntimeScalar createReference() { // Opt into refCount tracking when a reference to a named array is created. - // Named arrays start at refCount=-1 (untracked). When \@array creates a - // reference, we transition to refCount=0 (tracked, zero external refs) + // Named arrays begin untracked. When \@array creates a reference, we + // enter the tracked mode with zero counted external refs. // and set localBindingExists=true to indicate a JVM local variable slot // holds a strong reference not counted in refCount. // This allows setLargeRefCounted to properly count references, and // scopeExitCleanupArray to skip element cleanup when external refs exist. // Without this, scope exit of `my @array` would destroy elements even when // \@array is stored elsewhere. - if (this.refCount == -1) { - this.refCount = 0; + if (this.isRefCountUntracked()) { + this.startRefCountTracking(); this.localBindingExists = true; } RuntimeScalar result = new RuntimeScalar(); @@ -2076,8 +2511,8 @@ public RuntimeScalar createReference() { * @return A scalar representing the array reference. */ public RuntimeScalar createAnonymousReference() { - if (this.refCount == -1) { - this.refCount = 0; + if (this.isRefCountUntracked()) { + this.startRefCountTracking(); } RuntimeScalar result = new RuntimeScalar(); result.type = RuntimeScalarType.ARRAYREFERENCE; @@ -2093,16 +2528,18 @@ public RuntimeScalar createAnonymousReference() { * @return A scalar representing the array reference. */ public RuntimeScalar createReferenceWithTrackedElements() { - // Birth-track anonymous arrays: set refCount=0 so setLarge() can + // Birth-track anonymous arrays so setLarge() can // accurately count strong references. Anonymous arrays are only // reachable through references (no lexical variable slot), so // refCount is complete and reaching 0 means truly no strong refs. - if (this.refCount == -1) { - this.refCount = 0; + if (this.isRefCountUntracked()) { + this.startRefCountTracking(); } for (RuntimeScalar elem : this.elements) { RuntimeScalar.retainUnstashedIoForDurableSlot(elem); - RuntimeScalar.incrementRefCountForContainerStore(elem); + RuntimeScalar.incrementRefCountForContainerStore( + elem, PerlOwnerSlot.Kind.ARRAY_ELEMENT); + if (elem != null) elem.associateCountedAggregateOwner(this); } // The literal owns the element copies above. Removal paths use this // aggregate flag in addition to each scalar's refCountOwned bit when @@ -2117,7 +2554,7 @@ public RuntimeScalar createReferenceWithTrackedElements() { } private boolean hasDurableElementLifetime() { - return refCount >= 0 || (PerlRuntime.currentOrNull() != null + return isRefCountTracked() || (PerlRuntime.currentOrNull() != null && MyVarCleanupStack.isRegistered(this)); } @@ -2469,6 +2906,25 @@ public RuntimeArray setArrayOfAlias(RuntimeArray arr) { return arr; } + @Override + public RuntimeArray getArrayOfAlias() { + RuntimeArray alias = new RuntimeArray(); + setArrayOfAlias(alias); + alias.elementsAliased = true; + alias.elementsOwned = alias.ownedAliasElements != null + && !alias.ownedAliasElements.isEmpty(); + if (referenceListAliasOwnerTracking) { + alias.referenceListAliasOwnerTracking = true; + for (RuntimeScalar cell : elements) { + if (referenceListAliasCellOwners != null + && referenceListAliasCellOwners.containsKey(cell)) { + alias.retainReferenceListAliasCell(cell); + } + } + } + return alias; + } + /** Marks a direct source array whose cells are aliased into a callee's @_. */ public void markDirectCallArgument() { elementSlotsAliasedIntoCallFrame = true; @@ -2519,6 +2975,15 @@ public RuntimeArray takeTailCallOwnership() { } } } + if (referenceListAliasOwnerTracking) { + carrier.referenceListAliasOwnerTracking = true; + for (RuntimeScalar element : carrier.elements) { + if (referenceListAliasCellOwners != null + && referenceListAliasCellOwners.containsKey(element)) { + carrier.retainReferenceListAliasCell(element); + } + } + } this.elementsOwned = false; carrier.elementsAliased = true; carrier.elementsOwned = carrier.ownedAliasElements != null && !carrier.ownedAliasElements.isEmpty(); @@ -2597,18 +3062,25 @@ public RuntimeArray undefine() { TieArray.tiedClear(this); return this; } - notePackageRootMutation(); markScalarLocalContainerCleared(); - MortalList.deferDestroyForContainerClear(this.elements); - if (elementSlotsAliasedIntoCallFrame) { - for (RuntimeScalar element : this.elements) { - if (element != null - && (element.type & RuntimeScalarType.REFERENCE_BIT) == 0) { - element.clearForArraySlotRemoval(); - } + this.deferOwnedElementReleases(); + for (RuntimeScalar element : this.elements) { + if (element == null + || (element.type & RuntimeScalarType.REFERENCE_BIT) != 0) { + continue; + } + if (element.type == RuntimeScalarType.GLOB + || elementSlotsAliasedIntoCallFrame + || element.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS) != 0) { + // Undefining the AV clears any non-reference scalar cells + // borrowed by active @_ aliases before the array drops them. + // Their old values are released while the argument still sees + // the old cell, matching Perl's GV/component destruction order. + element.clearForArraySlotRemoval(); } } this.elements.clear(); + releaseReferenceListAliasCellOwners(); MortalList.flush(); return this; } @@ -2711,7 +3183,6 @@ public void dynamicSaveState() { // Push the current state onto the stack dynamicStateStack().push(currentState); // Clear the array elements (for tied arrays, this calls CLEAR) - notePackageRootMutation(); if (this.type == TIED_ARRAY) { TieArray.tiedClear(this); } else { @@ -2721,6 +3192,11 @@ public void dynamicSaveState() { this.blessId = 0; } + @Override + public RuntimeBase suspendedOwnerValue() { + return this; + } + /** * Restores the most recently saved state of the RuntimeArray instance. * @@ -2729,6 +3205,10 @@ public void dynamicSaveState() { */ @Override public void dynamicRestoreState() { + restoreDynamicState(false); + } + + private void restoreDynamicState(boolean preserveSuspendedValues) { Stack dynamicStateStack = dynamicStateStack(); if (!dynamicStateStack.isEmpty()) { // Pop the most recent saved state from the stack @@ -2737,13 +3217,13 @@ public void dynamicRestoreState() { // that temporary AV and become orphaned at restoration. Keep // proxies that predate the local scope attached to the restored // outer array. - orphanLocalArraySizeLvalues(); + if (!preserveSuspendedValues) orphanLocalArraySizeLvalues(); // Before discarding the current (local scope's) elements, defer // refCount decrements for any tracked blessed references they own. // Without this, `local @_ = ($obj)` where $obj is tracked would // leak refCounts because the local elements are replaced without // ever going through scopeExitCleanup. - MortalList.deferDestroyForContainerClear(this.elements); + if (!preserveSuspendedValues) this.deferOwnedElementReleases(); // Real Perl semantics: `local @arr` creates a fresh temporary AV // for the scope; `bless \@arr, 'X'` blesses that temporary; at // local-restore, the temporary is freed and DESTROY fires for @@ -2752,28 +3232,32 @@ public void dynamicRestoreState() { // was blessed but the previous state was not (or vice-versa // changed bless class). Test: postfixderef.t #38 "no stooges // outlast their scope". - if (this.blessId != 0 && this.blessId != previousState.blessId) { + if (!preserveSuspendedValues + && this.blessId != 0 && this.blessId != previousState.blessId) { int savedBlessId = this.blessId; int savedRefCount = this.refCount; + RefCountTrackingState savedRefCountTrackingState = + this.refCountTrackingState(); int savedType = this.type; boolean savedDestroyFired = this.destroyFired; - // callDestroy contract: caller sets refCount = MIN_VALUE. - this.refCount = Integer.MIN_VALUE; + RuntimeBase.PerlLifecycleState savedLifecycleState = this.perlLifecycleState(); DestroyDispatch.callDestroy(this); // Restore for safe state replacement below. Reset // destroyFired so subsequent local/restore cycles can // also fire DESTROY. this.destroyFired = savedDestroyFired; - this.refCount = savedRefCount; + this.restoreRefCountState(savedRefCount, savedRefCountTrackingState); this.type = savedType; this.blessId = savedBlessId; + this.restorePerlLifecycleState(savedLifecycleState); } // Restore the elements from the saved state - notePackageRootMutation(); if (previousState.type == TIED_ARRAY) { this.elements = previousState.elements; } else { this.elements = newElementList(previousState.elements); + refreshUntrackedElementOwners(); + previousState.elements.clear(); } markPackageRootedValues(0); // Restore the type from the saved state (important for tied arrays) @@ -2790,7 +3274,7 @@ public Object dynamicSuspendState() { activeState.blessId = this.blessId; activeState.scalarContextSize = this.scalarContextSize; activeState.elements.addAll(this.elements); - dynamicRestoreState(); + restoreDynamicState(true); return activeState; } @@ -2802,6 +3286,7 @@ public void dynamicResumeState(Object token) { this.blessId = activeState.blessId; this.scalarContextSize = activeState.scalarContextSize; this.elements.addAll(activeState.elements); + activeState.elements.clear(); } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeArrayProxyEntry.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeArrayProxyEntry.java index 3f6f97691f..5397fa517a 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeArrayProxyEntry.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeArrayProxyEntry.java @@ -70,6 +70,25 @@ public int getSourceIndex() { /** Parent aggregate, used for diagnostics that retain an element's identity. */ public RuntimeArray getParent() { return parent; } + @Override + RuntimeBase argumentAliasContainer() { + return parent; + } + + @Override + boolean hasLivePerlValueOwner() { + return lvalue != null && parent.elements != null + && parent.elements.stream().anyMatch(element -> element == lvalue); + } + + @Override + boolean hasLivePerlValueOwner(boolean requirePersistentParent) { + return hasLivePerlValueOwner() + && (requirePersistentParent + ? parent.hasPersistentPerlStrongOwnerIdentity() + : parent.hasCurrentPerlStorageOwner()); + } + @Override public RuntimeScalar set(RuntimeScalar value) { if (parent.threadShared) SharedPerlStorage.validateStoredValue(value); @@ -92,11 +111,10 @@ public RuntimeScalar aliasToReference(RuntimeScalar reference) { throw new PerlCompilerException( "Modification of non-creatable array value attempted, subscript " + diagnosticKey); } - parent.notePackageRootMutation(); while (currentKey >= parent.elements.size()) { parent.elements.add(null); } - parent.elements.set(currentKey, referent); + parent.setAliasedScalarCell(currentKey, referent); parent.markPackageRootedValue(referent); this.lvalue = referent; this.type = referent.type; @@ -117,7 +135,6 @@ public RuntimeScalar aliasToAggregateReference(RuntimeScalar reference) { throw new PerlCompilerException( "Modification of non-creatable array value attempted, subscript " + diagnosticKey); } - parent.notePackageRootMutation(); while (currentKey >= parent.elements.size()) parent.elements.add(null); parent.elements.set(currentKey, reference); parent.markPackageRootedValue(reference); @@ -131,7 +148,6 @@ public RuntimeScalar aliasToAggregateReference(RuntimeScalar reference) { public RuntimeScalar undefine() { vivify(); parent.markPackageRootedValue(lvalue); - parent.notePackageRootMutation(); return super.undefine(); } @@ -183,7 +199,6 @@ void vivify() { List elements = parent.elements; // Expand the array if needed - parent.notePackageRootMutation(); while (currentKey >= elements.size()) { elements.add(null); // Add null placeholders } @@ -262,16 +277,21 @@ public void dynamicRestoreState() { if (!dynamicStateStack.isEmpty()) { // Pop the most recent saved state from the stack RuntimeScalar previousState = dynamicStateStack.pop(); + boolean removedStoredOwner = false; if (previousState == null) { - parent.notePackageRootMutation(); // Element didn't exist before. - // Decrement refCount of the current value being displaced. - if (this.lvalue != null - && (this.lvalue.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && this.lvalue.value instanceof RuntimeBase displacedBase - && displacedBase.refCount > 0 && --displacedBase.refCount == 0) { - displacedBase.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(displacedBase); + // Retire the exact stored cell after removing it, through the + // same owner-slot deferred release used by delete/pop/shift. + RuntimeScalar removedOwner = this.lvalue; + boolean countedArraySlot = + RuntimeArray.hasCurrentCountedArrayElementOwner(parent, removedOwner); + int removedIndex = removedOwner == null + ? -1 : parent.elements.indexOf(removedOwner); + if (removedIndex >= 0) { + parent.elements.set(removedIndex, null); + RuntimeArray.deferRemovedElementRelease(parent, removedOwner, + "RuntimeArrayProxyEntry.dynamicRestoreState", countedArraySlot); + removedStoredOwner = true; } this.lvalue = null; this.type = RuntimeScalarType.UNDEF; @@ -290,22 +310,25 @@ public void dynamicRestoreState() { // assigned to intervening indices during the scope. // Structural array operations can move the proxy, so remove // its current physical slot rather than the original index. - int currentKey = currentKey(); - if (currentKey >= 0 && currentKey < parent.elements.size()) { - parent.elements.set(currentKey, null); + if (!removedStoredOwner) { + int currentKey = currentKey(); + if (currentKey >= 0 && currentKey < parent.elements.size()) { + parent.elements.set(currentKey, null); + } } while (parent.elements.size() > previousSize && isEmptyPlaceholder(parent.elements.getLast())) { parent.elements.removeLast(); } + if (removedStoredOwner) MortalList.flush(); return; } if (parent.elements.size() > previousSize) { - parent.notePackageRootMutation(); } while (parent.elements.size() > previousSize) { parent.elements.removeLast(); } + if (removedStoredOwner) MortalList.flush(); } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeArraySizeLvalue.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeArraySizeLvalue.java index 31fa07f389..2160faadd6 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeArraySizeLvalue.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeArraySizeLvalue.java @@ -55,6 +55,11 @@ public RuntimeArraySizeLvalue(RuntimeArray parent) { parent.registerArraySizeLvalue(this); } + @Override + RuntimeBase argumentAliasContainer() { + return lvalue != null && lvalue.value instanceof RuntimeArray parent ? parent : null; + } + void orphan() { type = RuntimeScalarType.UNDEF; value = null; @@ -96,19 +101,14 @@ public RuntimeScalar set(RuntimeScalar value) { @Override public void dynamicSaveState() { - RuntimeArray parent = lvalue.arrayDeref(); - int lastIndex = parent.lastElementIndex(); - savedSizes.push(new SavedSize(lastIndex, new ArrayList<>(parent.elements))); + // Perl treats `local $#array` as an ordinary array-size assignment; + // the assignment is not undone when the dynamic scope exits. } @Override public void dynamicRestoreState() { - if (!savedSizes.empty() && !isOrphaned()) { - RuntimeArray parent = lvalue.arrayDeref(); - SavedSize saved = savedSizes.pop(); - parent.elements.clear(); - parent.elements.addAll(saved.tail); - } + // Do not restore element wrappers whose counted owner slots were + // retired when the localized size assignment removed them. } @Override diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeBase.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeBase.java index 553ac10c8b..e4ea61edb6 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeBase.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeBase.java @@ -11,6 +11,77 @@ * and interfaces for these entities. */ public abstract class RuntimeBase implements DynamicState, Iterable { + /** + * Whether the selective owner count is authoritative for this referent. + * This state is separate from the numeric count: untracked and weak-tracked + * referents still expose an ordinary nonnegative {@link #refCount}. + */ + public enum RefCountTrackingState { + UNTRACKED, + TRACKED, + WEAKLY_TRACKED + } + + private volatile RefCountTrackingState refCountTrackingState = + RefCountTrackingState.UNTRACKED; + + public RefCountTrackingState refCountTrackingState() { + return refCountTrackingState; + } + + public boolean isRefCountTracked() { + return refCountTrackingState == RefCountTrackingState.TRACKED; + } + + public boolean isRefCountUntracked() { + return refCountTrackingState == RefCountTrackingState.UNTRACKED; + } + + public boolean isWeaklyRefCountTracked() { + return refCountTrackingState == RefCountTrackingState.WEAKLY_TRACKED; + } + + /** Start selective counting after the caller has reconciled prior owners. */ + public void startRefCountTracking() { + refCount = 0; + refCountTrackingState = RefCountTrackingState.TRACKED; + } + + /** Leave the selective bridge after its owner identities have been rebuilt. */ + public void markRefCountUntracked() { + refCount = 0; + refCountTrackingState = RefCountTrackingState.UNTRACKED; + } + + /** Defer weak cleanup while some real strong slots remain outside the count. */ + public void markRefCountWeaklyTracked() { + refCount = 0; + refCountTrackingState = RefCountTrackingState.WEAKLY_TRACKED; + } + + /** Set a known count and activate the selective count bridge. */ + public void setTrackedRefCount(int count) { + if (count < 0) { + throw new IllegalArgumentException("Perl refcount cannot be negative"); + } + refCount = count; + refCountTrackingState = RefCountTrackingState.TRACKED; + } + + /** Restore a count and its tracking mode together after temporary mutation. */ + public void restoreRefCountState(int count, RefCountTrackingState state) { + if (count < 0) { + throw new IllegalArgumentException("Perl refcount cannot be negative"); + } + Objects.requireNonNull(state, "state"); + if (state != RefCountTrackingState.TRACKED && count != 0) { + throw new IllegalArgumentException( + "untracked referents cannot have a selective owner count"); + } + refCount = count; + refCountTrackingState = state; + } + /** Lifecycle is independent of the selective-count compatibility bridge. */ public enum PerlLifecycleState { LIVE, @@ -25,6 +96,10 @@ public PerlLifecycleState perlLifecycleState() { return perlLifecycleState; } + public boolean isPerlDestroyed() { + return perlLifecycleState == PerlLifecycleState.DESTROYED; + } + void beginPerlDestruction() { perlLifecycleState = PerlLifecycleState.DESTROYING; } @@ -34,9 +109,17 @@ void markPerlResurrected() { } void markPerlDestroyed() { + // A destroyed referent has no live Perl owner slots. Keep the public + // count in its ordinary nonnegative domain; lifecycle is represented + // only by perlLifecycleState. + refCount = 0; perlLifecycleState = PerlLifecycleState.DESTROYED; } + void restorePerlLifecycleState(PerlLifecycleState state) { + perlLifecycleState = Objects.requireNonNull(state, "state"); + } + /** Storage identity retained across ithread graph clones. */ public volatile boolean threadShared; /** @@ -70,6 +153,12 @@ public static final class SharedLifecycle { volatile String publishedBlessName; } + enum SharedDestroyDisposition { + CONTINUE, + DEFER, + CLEAR_LOCAL_VIEW + } + /** * Refresh an unchanged local shared view after another runtime explicitly * publishes a class through shared scalar/aggregate storage. A view that @@ -116,12 +205,12 @@ void registerSharedFetchedView() { } } - /** - * @return true when ordinary DESTROY dispatch must be suppressed. - */ - boolean deferSharedDestroy() { + /** Decide whether this release owns canonical destruction or only a local view. */ + SharedDestroyDisposition sharedDestroyDisposition() { SharedLifecycle lifecycle = threadSharedLifecycle; - if (!threadShared || lifecycle == null || !lifecycle.active) return false; + if (!threadShared || lifecycle == null || !lifecycle.active) { + return SharedDestroyDisposition.CONTINUE; + } if (threadSharedFetchedView || threadSharedRuntimeView) { int remaining = lifecycle.liveViews.get(); @@ -133,27 +222,30 @@ boolean deferSharedDestroy() { } if (remaining == 0 && lifecycle.destroyPending.get() && lifecycle.destroyFired.compareAndSet(false, true)) { - return false; + return SharedDestroyDisposition.CONTINUE; } - return true; + // A fetch proxy has a Perl-local identity even though its storage + // is shared. Retire only its local weak observers; the canonical + // object's DESTROY and element cleanup still belong to the + // shared lifecycle. Runtime views retain the existing deferred + // destruction behavior until their lifecycle is separated too. + return threadSharedFetchedView + ? SharedDestroyDisposition.CLEAR_LOCAL_VIEW + : SharedDestroyDisposition.DEFER; } lifecycle.destroyPending.set(true); - if (lifecycle.liveViews.get() > 0) return true; - return !lifecycle.destroyFired.compareAndSet(false, true); + if (lifecycle.liveViews.get() > 0) return SharedDestroyDisposition.DEFER; + return lifecycle.destroyFired.compareAndSet(false, true) + ? SharedDestroyDisposition.CONTINUE + : SharedDestroyDisposition.DEFER; } // Index to the class that this reference belongs public int blessId; - // Reference count for blessed objects with DESTROY. - // Four-state lifecycle counter: - // -1 = Not tracked (unblessed, or blessed without DESTROY) - // 0 = Tracked, zero counted containers (fresh from bless) - // >0 = Being tracked; N named-variable containers exist - // Integer.MIN_VALUE = DESTROY already called (or in progress) - // MUST be explicitly initialized to -1 (Java defaults int to 0, which would - // mean "tracked, zero containers" — silently breaking all unblessed objects). - public int refCount = -1; + // Selective legacy count bridge used while owner producers are migrated. + // Destruction and tracking mode are represented independently. + public int refCount = 0; // ───────────────────────────────────────────────────────────────────── // Phase D-W6.10: targeted refCount transition tracing. @@ -191,6 +283,9 @@ boolean deferSharedDestroy() { */ public boolean storedInPackageGlobal = false; + /** Marks a counted referent kept alive only until its uncounted owner slots leave. */ + boolean deferredFinalReleaseForUncountedOwners = false; + /** * Number of live hash-element slots that directly own this referent. * This is separate from selective refCount because a returned method @@ -201,9 +296,8 @@ boolean deferSharedDestroy() { /** * Marks a scalar/container whose contents are reachable from package - * globals. Mutating such an object can change cached root-reachability - * answers, so mutation paths invalidate MortalList's external-root - * snapshot when this flag is set. + * globals. Owner and lifecycle operations use this flag to preserve the + * package slot's Perl ownership semantics when values are replaced. */ public boolean isPackageGlobalRoot = false; @@ -223,6 +317,8 @@ boolean deferSharedDestroy() { */ public int captureCount = 0; public boolean scopeExited = false; + private int legacyCaptureOwnerCount; + private int pendingClosureCaptureReleases; /** * A lexical array whose scope has ended without an escaped {@code \@array} @@ -231,40 +327,125 @@ boolean deferSharedDestroy() { */ public boolean arrayLengthLvalueOrphaned = false; - public void retainClosureCapture() { + public synchronized void retainClosureCapture() { + PerlOwnerSlot.Kind ownerKind = this instanceof RuntimeScalar + ? PerlOwnerSlot.Kind.SCALAR_CAPTURE : PerlOwnerSlot.Kind.CLOSURE_PAD; + verifyClosureCaptureOwnerCount(ownerKind); + retainClosureCaptureCount(true); + verifyClosureCaptureOwnerCount(ownerKind); + } + + public synchronized int legacyCaptureOwnerCount() { + return legacyCaptureOwnerCount; + } + + final synchronized void beginPendingClosureCaptureRelease() { + if (pendingClosureCaptureReleases == Integer.MAX_VALUE) { + throw new IllegalStateException("pending closure capture release overflow"); + } + pendingClosureCaptureReleases++; + } + + final synchronized void endPendingClosureCaptureRelease() { + if (pendingClosureCaptureReleases <= 0) { + throw new IllegalStateException("unbalanced pending closure capture release"); + } + pendingClosureCaptureReleases--; + } + + protected final synchronized void retainClosureCaptureCount(boolean legacyOwner) { + if (captureCount == Integer.MAX_VALUE + || (legacyOwner && legacyCaptureOwnerCount == Integer.MAX_VALUE)) { + throw new IllegalStateException("closure capture count overflow"); + } captureCount++; + if (legacyOwner) legacyCaptureOwnerCount++; + } + + protected final synchronized void releaseClosureCaptureCount(boolean legacyOwner) { + if (legacyOwner) { + if (legacyCaptureOwnerCount <= 0) { + throw new IllegalStateException("release has no legacy closure capture owner"); + } + legacyCaptureOwnerCount--; + } + if (captureCount <= 0) { + throw new IllegalStateException("closure capture count underflow"); + } + captureCount--; + } + + final synchronized void verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind ownerKind) { + if (pendingClosureCaptureReleases != 0) { + throw new IllegalStateException("closure capture release is still pending"); + } + int slotCount = ownerSlotCount(ownerKind); + int legacyCount = legacyCaptureOwnerCount(); + if (captureCount != slotCount + legacyCount) { + throw new IllegalStateException("closure capture owner mismatch: count=" + + captureCount + ", slots=" + slotCount + ", legacy=" + legacyCount + + ", kind=" + ownerKind); + } + } + + /** Whether an explicit, compatibility, or in-flight capture owner remains. */ + public final synchronized boolean hasClosureCaptureOwner() { + PerlOwnerSlot.Kind ownerKind = this instanceof RuntimeScalar + ? PerlOwnerSlot.Kind.SCALAR_CAPTURE : PerlOwnerSlot.Kind.CLOSURE_PAD; + return ownerSlotCount(ownerKind) != 0 || legacyCaptureOwnerCount() != 0 + || pendingClosureCaptureReleases != 0; } /** Retain one aggregate pad capture through an explicit owner slot. */ - public PerlOwnerSlot retainClosureCaptureOwner() { + public synchronized PerlOwnerSlot retainClosureCaptureOwner() { + return retainClosureCaptureOwner(null); + } + + /** Retain one aggregate pad capture and identify its owning CODE object. */ + public synchronized PerlOwnerSlot retainClosureCaptureOwner(RuntimeCode captureOwner) { + verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.CLOSURE_PAD); // A closure-pad slot is a semantic Perl owner even though it does not - // contribute to the legacy selective refcount. A targeted weak sweep - // can therefore leave an unblessed aggregate's legacy count at the - // destroyed sentinel while other native capture slots still own it. - // Reconcile that stale bridge state before adding another owner; a - // blessed or already-destroyed object must never be revived here. - if (refCount == Integer.MIN_VALUE && blessId == 0 && !destroyFired - && captureCount > 0 && hasSemanticCaptureOwner()) { - refCount = 0; - } + // contribute to the selective refcount. Reconcile stale bridge state + // before adding another owner; a blessed or already-destroyed object + // must never be revived here. PerlOwnerSlot ownerSlot = new PerlOwnerSlot(PerlOwnerSlot.Kind.CLOSURE_PAD); - ownerSlot.acquireCapture(this); - retainClosureCapture(); + ownerSlot.acquireCapture(this, captureOwner); + retainClosureCaptureCount(false); + if (this instanceof RuntimeArray || this instanceof RuntimeHash) { + verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.CLOSURE_PAD); + } return ownerSlot; } /** Release one aggregate pad capture, balancing its bridged count. */ - public void releaseClosureCaptureOwner(PerlOwnerSlot ownerSlot) { + public synchronized void releaseClosureCaptureOwner(PerlOwnerSlot ownerSlot) { if (ownerSlot == null) { releaseClosureCapture(); return; } + if (ownerSlot.kind() != PerlOwnerSlot.Kind.CLOSURE_PAD) { + throw new IllegalStateException("capture release requires a closure-pad slot"); + } + if (!ownerSlot.isActive()) return; + if (ownerSlot.referent() != this) { + throw new IllegalStateException("closure-pad slot belongs to a different aggregate"); + } if (ownerSlot.isNativeCaptureOwner()) { // Captured aggregate pads are native owner slots. Remove the slot // before releasing the capture so a final release can dispatch // from the owner count without manufacturing a legacy decrement. - ownerSlot.release(); - releaseClosureCapture(true); + beginPendingClosureCaptureRelease(); + try { + ownerSlot.release(); + } finally { + endPendingClosureCaptureRelease(); + } + releaseClosureCapture(false); + // The owner-slot removal above runs while this capture release is + // marked pending, so its lifecycle callback correctly waits. Retry + // now that the capture count and pending marker have both retired. + WeakRefRegistry.onStrongOwnerSlotReleased(this); + verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.CLOSURE_PAD); return; } ownerSlot.deferLegacyCaptureRelease(this); @@ -273,59 +454,711 @@ public void releaseClosureCaptureOwner(PerlOwnerSlot ownerSlot) { } finally { ownerSlot.release(); } + verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.CLOSURE_PAD); } - public void releaseClosureCapture() { - releaseClosureCapture(false); + /** Retain one persistent scalar or aggregate state binding owned by a CV. */ + synchronized PerlOwnerSlot retainCodeStateOwner(RuntimeCode owner) { + PerlOwnerSlot ownerSlot = new PerlOwnerSlot(PerlOwnerSlot.Kind.CODE_STATE); + ownerSlot.acquireCodeStateIdentity(this, owner); + return ownerSlot; } - private void releaseClosureCapture(boolean nativeOwnerSlot) { - if (captureCount > 0) { - captureCount--; + /** Release one persistent CODE state binding identity. */ + synchronized void releaseCodeStateOwner(PerlOwnerSlot ownerSlot) { + if (ownerSlot == null || !ownerSlot.isActive()) return; + if (ownerSlot.kind() != PerlOwnerSlot.Kind.CODE_STATE || ownerSlot.referent() != this) { + throw new IllegalArgumentException("CODE state release does not match this referent"); } - if (captureCount == 0 && scopeExited) { + ownerSlot.release(); + } + + public synchronized void releaseClosureCapture() { + if (!hasClosureCaptureOwner()) { + if (captureCount != 0) { + throw new IllegalStateException("closure capture has no recorded owner"); + } + return; + } + releaseClosureCapture(true); + verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.CLOSURE_PAD); + } + + private void releaseClosureCapture(boolean legacyOwner) { + releaseClosureCaptureCount(legacyOwner); + if (!hasClosureCaptureOwner() && scopeExited) { scopeExited = false; if (this instanceof RuntimeHash hash) { MortalList.scopeExitCleanupHash(hash); } else if (this instanceof RuntimeArray array) { MortalList.scopeExitCleanupArray(array); } - if (blessId != 0 && refCount <= 0) { - refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(this); - } else if (!nativeOwnerSlot && refCount > 0 - && (blessId != 0 || this instanceof RuntimeCode) - && !hasSemanticCaptureOwner()) { - MortalList.deferDecrement(this, "closure aggregate release"); - } + // A closure pad capture is not a counted RV edge. Any positive + // count belongs to scalar or container slots, which retire their + // own count when those slots are released. + if (blessId != 0 && refCount <= 0) DestroyDispatch.callDestroy(this); } } // ───────────────────────────────────────────────────────────────────── - // D-W6.13: production-grade ownership tracking. - // Active for blessed objects that have at least one weak reference - // (the only case where we care about precise refCount semantics). - // Stores the set of RuntimeScalars that hold a counted strong ref - // to this base (refCountOwned=true && value==this). - // At MortalList.flush() refCount→0, this is consulted: if non-empty, - // refCount is restored to the owner count and DESTROY is suppressed. + // D-W6.13: counted scalar owners are derived from the slot ledger below. // ───────────────────────────────────────────────────────────────────── - public java.util.Set activeOwners = null; - /** Identity ledger for migrated slots; selective refCount remains the * lifecycle bridge while owner families move to this API. */ private java.util.Set ownerSlots = null; + private int argumentAliasOwnerSlots; + private int countedOwnerSlots; + private int closurePadOwnerSlots; + private int scalarCaptureOwnerSlots; + private int argumentValueOwnerSlots; + private int argumentContainerOwnerSlots; + private int argumentTieHandlerOwnerSlots; + private int returnValueOwnerSlots; + private int activeCodeOwnerSlots; + private int packageAggregateOwnerSlots; + private int codeSlotOwnerSlotsCount; + private int transientUntrackedReferenceOwnerSlots; + private java.util.Set untrackedReferenceOwnerSlots = null; + private java.util.Set codeSlotOwnerSlots = null; + /** Untracked proxy value edges whose lvalue parent is this aggregate. */ + private java.util.Set proxyValueOwnerSlots = null; + /** Active semantic Perl owner identities; excludes temporary roots and IO leases. */ + private volatile int perlStrongOwnerSlots; + private int pendingReturnOwners; + private int pendingOwnerReleases; + /** Counted Perl edges whose slots retired but whose refCount release is queued. */ + private int pendingCountedOwnerReleases; + + synchronized boolean hasPendingReturnOwner() { + return pendingReturnOwners != 0; + } + + /** A queued Perl owner release has retired its live slot but not its count yet. */ + synchronized boolean hasPendingOwnerRelease() { + return pendingOwnerReleases != 0; + } + + /** Explicit call-transfer owners remain authoritative during the legacy bridge. */ + synchronized boolean hasCallTransferOwner() { + return pendingReturnOwners != 0 + || ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE) != 0 + || ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_CONTAINER) != 0; + } + + /** A referenced scalar cell is owned by its lexical binding or capture slots. */ + boolean hasScalarCellOwner() { + return this instanceof RuntimeScalar scalar && scalar.referencedByScalarReference + && (scalar.localBindingExists + || hasOwnerSlots() || hasPendingReturnOwner() + || scalar.hasLiveCurrentAggregateStorageOwner()); + } + + /** Storage identities that own a scalar cell itself, excluding its value edges. */ + boolean hasScalarCellStorageOwnerSlotIdentity() { + return ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL) != 0 + || ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT) != 0 + || ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE) != 0 + || ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL) != 0 + || ownerSlotCount(PerlOwnerSlot.Kind.SUSPENDED_FRAME) != 0 + || ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_REFERENCE_CONTENTS) != 0; + } + + synchronized void registerPendingOwnerRelease( + PerlOwnerSlot.PendingRelease release) { + pendingOwnerReleases++; + if (release != null && PerlOwnerSlot.isCountedKind(release.kind())) { + pendingCountedOwnerReleases++; + } + if (release != null && release.kind() == PerlOwnerSlot.Kind.RETURN_VALUE) { + pendingReturnOwners++; + } + } synchronized void addOwnerSlot(PerlOwnerSlot slot) { if (ownerSlots == null) { ownerSlots = java.util.Collections.newSetFromMap( new java.util.IdentityHashMap<>()); } - ownerSlots.add(slot); + if (ownerSlots.add(slot)) { + PerlOwnerSlot.Kind kind = slot.kind(); + adjustIndexedOwnerSlotCount(kind, 1); + if (kind == PerlOwnerSlot.Kind.ARGUMENT_ALIAS) argumentAliasOwnerSlots++; + if (PerlOwnerSlot.isCountedKind(kind)) countedOwnerSlots++; + if (PerlOwnerSlot.isPerlOwnerKind(kind)) perlStrongOwnerSlots++; + if (kind == PerlOwnerSlot.Kind.CODE_SLOT) { + codeSlotOwnerSlotsCount++; + if (codeSlotOwnerSlots == null) { + codeSlotOwnerSlots = java.util.concurrent.ConcurrentHashMap.newKeySet(); + } + codeSlotOwnerSlots.add(slot); + } + if (kind == PerlOwnerSlot.Kind.UNTRACKED_REFERENCE) { + if (untrackedReferenceOwnerSlots == null) { + // PerlOwnerSlot has identity equality. The concurrent set + // lets hot read paths iterate this narrow index without + // copying it or holding the referent lock while examining + // slot state. + untrackedReferenceOwnerSlots = java.util.concurrent.ConcurrentHashMap + .newKeySet(); + } + untrackedReferenceOwnerSlots.add(slot); + } + } } synchronized void removeOwnerSlot(PerlOwnerSlot slot) { - if (ownerSlots != null) ownerSlots.remove(slot); + if (ownerSlots != null && ownerSlots.remove(slot)) { + PerlOwnerSlot.Kind kind = slot.kind(); + adjustIndexedOwnerSlotCount(kind, -1); + if (kind == PerlOwnerSlot.Kind.ARGUMENT_ALIAS) argumentAliasOwnerSlots--; + if (PerlOwnerSlot.isCountedKind(kind)) countedOwnerSlots--; + if (PerlOwnerSlot.isPerlOwnerKind(kind)) perlStrongOwnerSlots--; + if (kind == PerlOwnerSlot.Kind.CODE_SLOT) { + codeSlotOwnerSlotsCount--; + if (codeSlotOwnerSlots != null) { + codeSlotOwnerSlots.remove(slot); + if (codeSlotOwnerSlots.isEmpty()) codeSlotOwnerSlots = null; + } + } + if (kind == PerlOwnerSlot.Kind.UNTRACKED_REFERENCE + && untrackedReferenceOwnerSlots != null) { + untrackedReferenceOwnerSlots.remove(slot); + if (untrackedReferenceOwnerSlots.isEmpty()) { + untrackedReferenceOwnerSlots = null; + } + } + } + } + + /** + * Register an untracked scalar-proxy owner whose value slot is backed by + * this aggregate. The index lets aggregate owner release recheck proxy + * values after this parent loses its final Perl storage owner. + */ + synchronized boolean addProxyValueOwnerSlot(PerlOwnerSlot slot) { + if (threadShared || !(this instanceof RuntimeArray || this instanceof RuntimeHash)) { + return false; + } + if (proxyValueOwnerSlots == null) { + proxyValueOwnerSlots = java.util.Collections.newSetFromMap( + new java.util.IdentityHashMap<>()); + } + proxyValueOwnerSlots.add(slot); + return true; + } + + synchronized void removeProxyValueOwnerSlot(PerlOwnerSlot slot) { + if (proxyValueOwnerSlots != null && proxyValueOwnerSlots.remove(slot) + && proxyValueOwnerSlots.isEmpty()) { + proxyValueOwnerSlots = null; + } + } + + /** Revalidate proxy value owners when an aggregate no longer has Perl storage. */ + void recheckProxyValueOwnersIfUnowned() { + if (threadShared || !(this instanceof RuntimeArray || this instanceof RuntimeHash)) { + return; + } + java.util.List snapshot; + synchronized (this) { + if (proxyValueOwnerSlots == null || proxyValueOwnerSlots.isEmpty()) return; + snapshot = new java.util.ArrayList<>(proxyValueOwnerSlots); + } + if (PerlRuntime.currentOrNull() == null || hasCurrentPerlStorageOwner()) return; + for (PerlOwnerSlot slot : snapshot) { + if (!slot.isActive() || slot.kind() != PerlOwnerSlot.Kind.UNTRACKED_REFERENCE) { + removeProxyValueOwnerSlot(slot); + continue; + } + RuntimeScalar owner = slot.untrackedScalarOwner(); + if (owner == null || owner.untrackedReferenceOwnerSlot() != slot) { + slot.release(); + } else { + owner.refreshUntrackedReferenceOwner(); + } + } + } + + /** Update hot per-kind counts and the narrow untracked-reference index. */ + synchronized void reclassifyOwnerSlotKind( + PerlOwnerSlot slot, PerlOwnerSlot.Kind oldKind, PerlOwnerSlot.Kind newKind) { + if (ownerSlots != null && ownerSlots.contains(slot)) { + adjustIndexedOwnerSlotCount(oldKind, -1); + adjustIndexedOwnerSlotCount(newKind, 1); + if (oldKind == PerlOwnerSlot.Kind.ARGUMENT_ALIAS) argumentAliasOwnerSlots--; + if (newKind == PerlOwnerSlot.Kind.ARGUMENT_ALIAS) argumentAliasOwnerSlots++; + if (PerlOwnerSlot.isCountedKind(oldKind) != PerlOwnerSlot.isCountedKind(newKind)) { + countedOwnerSlots += PerlOwnerSlot.isCountedKind(newKind) ? 1 : -1; + } + if (PerlOwnerSlot.isPerlOwnerKind(oldKind) + != PerlOwnerSlot.isPerlOwnerKind(newKind)) { + perlStrongOwnerSlots += PerlOwnerSlot.isPerlOwnerKind(newKind) ? 1 : -1; + } + if (oldKind == PerlOwnerSlot.Kind.CODE_SLOT) { + codeSlotOwnerSlotsCount--; + if (codeSlotOwnerSlots != null) { + codeSlotOwnerSlots.remove(slot); + if (codeSlotOwnerSlots.isEmpty()) codeSlotOwnerSlots = null; + } + } + if (newKind == PerlOwnerSlot.Kind.CODE_SLOT) { + codeSlotOwnerSlotsCount++; + if (codeSlotOwnerSlots == null) { + codeSlotOwnerSlots = java.util.concurrent.ConcurrentHashMap.newKeySet(); + } + codeSlotOwnerSlots.add(slot); + } + if (oldKind == PerlOwnerSlot.Kind.UNTRACKED_REFERENCE) { + if (untrackedReferenceOwnerSlots != null) { + untrackedReferenceOwnerSlots.remove(slot); + if (untrackedReferenceOwnerSlots.isEmpty()) { + untrackedReferenceOwnerSlots = null; + } + } + } + if (newKind == PerlOwnerSlot.Kind.UNTRACKED_REFERENCE) { + if (untrackedReferenceOwnerSlots == null) { + untrackedReferenceOwnerSlots = java.util.concurrent.ConcurrentHashMap + .newKeySet(); + } + untrackedReferenceOwnerSlots.add(slot); + } + } + slot.setKindFromOwnerLedger(newKind); + } + + private void adjustIndexedOwnerSlotCount(PerlOwnerSlot.Kind kind, int delta) { + switch (kind) { + case CLOSURE_PAD -> closurePadOwnerSlots += delta; + case SCALAR_CAPTURE -> scalarCaptureOwnerSlots += delta; + case ARGUMENT_VALUE -> argumentValueOwnerSlots += delta; + case ARGUMENT_CONTAINER -> argumentContainerOwnerSlots += delta; + case ARGUMENT_TIE_HANDLER -> argumentTieHandlerOwnerSlots += delta; + case RETURN_VALUE -> returnValueOwnerSlots += delta; + case ACTIVE_CODE -> activeCodeOwnerSlots += delta; + case PACKAGE_AGGREGATE_SLOT -> packageAggregateOwnerSlots += delta; + default -> { } + } + } + + private int indexedOwnerSlotCount(PerlOwnerSlot.Kind kind) { + return switch (kind) { + case CLOSURE_PAD -> closurePadOwnerSlots; + case SCALAR_CAPTURE -> scalarCaptureOwnerSlots; + case ARGUMENT_VALUE -> argumentValueOwnerSlots; + case ARGUMENT_CONTAINER -> argumentContainerOwnerSlots; + case ARGUMENT_TIE_HANDLER -> argumentTieHandlerOwnerSlots; + case RETURN_VALUE -> returnValueOwnerSlots; + case ACTIVE_CODE -> activeCodeOwnerSlots; + case PACKAGE_AGGREGATE_SLOT -> packageAggregateOwnerSlots; + case CODE_SLOT -> codeSlotOwnerSlotsCount; + default -> -1; + }; + } + + boolean hasOwnerSlots() { + return perlStrongOwnerSlots > 0; + } + + /** O(1) candidate bound for queries that validate exact owner identities. */ + private synchronized int currentPerlOwnerSlotCandidatesOtherThan( + PerlOwnerSlot excluded) { + int candidates = perlStrongOwnerSlots; + if (candidates == 0) return 0; + if (excluded != null && ownerSlots != null && ownerSlots.contains(excluded) + && PerlOwnerSlot.isPerlOwnerKind(excluded.kind())) { + candidates--; + } + return candidates; + } + + /** + * Whether the legacy count or a direct Perl owner slot proves this value + * is still owned. Runtime temporary roots and IO resource leases are + * runtime bookkeeping, not Perl references, and are deliberately excluded. + */ + public boolean hasPerlStrongOwner() { + return refCount > 0 || hasPerlStrongOwnerIdentity(); + } + + /** Count temporary referent slots held only by active Perl argument frames. */ + public int currentArgumentFrameReferentOwnerCount() { + PerlRuntime runtime = PerlRuntime.currentOrNull(); + if (runtime == null) return 0; + java.util.List activeArgs = RuntimeCode.snapshotArgsStack(); + int count = 0; + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (!slot.isActive()) continue; + if (slot.kind() == PerlOwnerSlot.Kind.ARGUMENT_CONTAINER) { + count++; + continue; + } + RuntimeScalar owner = slot.countedScalarOwner(); + if (owner == null || owner.value != this + || !(owner.containerOwner instanceof RuntimeArray array)) continue; + for (int depth = 0; depth < activeArgs.size(); depth++) { + if (activeArgs.get(depth) != array) continue; + RuntimeCode activeCode = RuntimeCode.getActiveCodeAt(depth); + boolean destroyInvocant = activeCode != null + && "DESTROY".equals(activeCode.subName) + && !array.elements.isEmpty() && array.elements.get(0) == owner; + if (!destroyInvocant) count++; + break; + } + } + return count; + } + + /** + * Whether current Perl owner identities, apart from the legacy count, + * prove that this value is still owned. Temporary roots, IO resource leases, + * and compatibility count pins are not Perl owners. + */ + boolean hasPerlStrongOwnerIdentity() { + if (localBindingExists || hasClosureCaptureOwner() || hasPendingReturnOwner()) { + return true; + } + return perlStrongOwnerSlots > 0; + } + + /** + * Whether this value has a durable Perl owner independent of temporary + * call-frame and result-transfer holds. This is used when deciding whether + * an aliased scalar cell is already kept alive by its aggregate container. + */ + boolean hasPersistentPerlStrongOwnerIdentity() { + PerlRuntime runtime = PerlRuntime.currentOrNull(); + if (localBindingExists || isPackageGlobalRoot || hasClosureCaptureOwner() + || (runtime != null && MyVarCleanupStack.isRegistered(this))) return true; + + int temporaryCountedOwners = ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE) + + ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_CONTAINER) + + ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_TIE_HANDLER) + + ownerSlotCount(PerlOwnerSlot.Kind.RETURN_VALUE) + + ownerSlotCount(PerlOwnerSlot.Kind.EXPRESSION_VALUE); + if (refCount > temporaryCountedOwners) return true; + + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (!slot.isActive() || !PerlOwnerSlot.isPerlOwnerKind(slot.kind())) continue; + switch (slot.kind()) { + case ARGUMENT_VALUE, ARGUMENT_CONTAINER, ARGUMENT_ALIAS, + ARGUMENT_TIE_HANDLER, RETURN_VALUE, ACTIVE_CODE, + EXPRESSION_VALUE -> { } + case UNTRACKED_REFERENCE, SCALAR_REFERENCE_CONTENTS, + ARRAY_ELEMENT, HASH_ELEMENT -> { + if (DestroyDispatch.isCurrentPerlOwnerSlot(this, slot)) return true; + } + default -> { return true; } + } + } + return false; + } + + /** Whether a current Perl owner identity other than one slot remains. */ + boolean hasCurrentPerlOwnerIdentityOtherThan(PerlOwnerSlot excluded) { + if (localBindingExists || hasClosureCaptureOwner() + || hasPendingReturnOwner() || hasPendingOwnerRelease()) { + return true; + } + if (currentPerlOwnerSlotCandidatesOtherThan(excluded) == 0) return false; + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (slot == excluded || !slot.isActive() + || !PerlOwnerSlot.isPerlOwnerKind(slot.kind())) { + continue; + } + if (slot.kind() == PerlOwnerSlot.Kind.ARGUMENT_ALIAS + || slot.isMethodInvocantOwner(this) + || slot.isCountedNativeOwner()) { + return true; + } + RuntimeScalar scalarOwner = slot.countedScalarOwner(); + if (scalarOwner != null) { + PerlOwnerSlot.Kind kind = slot.kind(); + boolean currentCountedOwner = + (kind == PerlOwnerSlot.Kind.ARRAY_ELEMENT + || kind == PerlOwnerSlot.Kind.HASH_ELEMENT) + ? scalarOwner.isCurrentAggregateElementOwner(this, slot) + : scalarOwner.isCurrentCountedScalarOwner(this, slot); + if (currentCountedOwner) return true; + continue; + } + if (DestroyDispatch.isCurrentPerlOwnerSlot(this, slot)) return true; + } + return false; + } + + /** Whether a non-counted owner slot proves Perl ownership of this value. */ + boolean hasUncountedPerlOwnerSlotIdentity() { + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (slot.isActive() + && !PerlOwnerSlot.isCountedKind(slot.kind()) + && !slot.isCountedNativeOwner() + && PerlOwnerSlot.isPerlOwnerKind(slot.kind())) { + return true; + } + } + return false; + } + + /** A snapshot lease delays lifecycle cleanup without becoming a Perl owner. */ + boolean hasTemporaryRootOwnerSlotIdentity() { + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (slot.isActive() && slot.kind() == PerlOwnerSlot.Kind.TEMPORARY_ROOT) { + return true; + } + } + return false; + } + + /** Whether a current uncounted slot proves Perl ownership of this value. */ + boolean hasCurrentUncountedPerlOwnerSlotIdentity() { + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (!PerlOwnerSlot.isCountedKind(slot.kind()) + && !slot.isCountedNativeOwner() + && PerlOwnerSlot.isPerlOwnerKind(slot.kind()) + && DestroyDispatch.isCurrentPerlOwnerSlot(this, slot)) { + return true; + } + } + return false; + } + + /** + * Whether a live lexical scalar directly owns this referent through the + * untracked-reference bridge, without an intervening aggregate slot. + */ + boolean hasCurrentUntrackedLexicalScalarOwnerSlotIdentity() { + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (!slot.isActive() + || slot.kind() != PerlOwnerSlot.Kind.UNTRACKED_REFERENCE) continue; + RuntimeScalar owner = slot.untrackedScalarOwner(); + if (owner == null || owner.getContainerOwner() != null + || owner.scopeExited || !MyVarCleanupStack.isRegistered(owner)) { + continue; + } + if (DestroyDispatch.isCurrentPerlOwnerSlot(this, slot)) return true; + } + return false; + } + + /** Whether any active Perl owner slot still proves a current storage edge. */ + boolean hasCurrentPerlOwnerSlotIdentity() { + if (perlStrongOwnerSlots == 0) { + LifecycleHotPathDiagnostics.ownerSlotIdentityFastPath(); + return false; + } + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (DestroyDispatch.isCurrentPerlOwnerSlot(this, slot)) return true; + } + return false; + } + + /** Whether this aggregate has a current Perl storage or call-transfer owner. */ + boolean hasCurrentPerlStorageOwner() { + PerlRuntime runtime = PerlRuntime.currentOrNull(); + synchronized (this) { + if (refCount > pendingCountedOwnerReleases) return true; + } + if (localBindingExists || hasClosureCaptureOwner() + || hasPendingReturnOwner() + || ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE) != 0 + || ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_CONTAINER) != 0 + || ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_TIE_HANDLER) != 0 + || ownerSlotCount(PerlOwnerSlot.Kind.RETURN_VALUE) != 0) { + return true; + } + if ((this instanceof RuntimeArray || this instanceof RuntimeHash) + && (GlobalVariable.isPackageRootedAggregate(this) + || (runtime != null && MyVarCleanupStack.isRegistered(this)))) { + return true; + } + if (hasTransientUntrackedContainerTransferOwner()) return true; + return hasCurrentPerlOwnerSlotIdentity(); + } + + private boolean hasTransientUntrackedContainerTransferOwner() { + return transientUntrackedReferenceOwnerCount() != 0; + } + + boolean hasDirectOwnerSlotProofForReleasedWeakReferent() { + if (perlStrongOwnerSlots == 0) { + LifecycleHotPathDiagnostics.ownerSlotIdentityFastPath(); + return false; + } + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (!slot.isActive() || !PerlOwnerSlot.isPerlOwnerKind(slot.kind())) continue; + if (slot.kind() == PerlOwnerSlot.Kind.ARRAY_ELEMENT + || slot.kind() == PerlOwnerSlot.Kind.HASH_ELEMENT) { + RuntimeScalar scalar = slot.countedScalarOwner(); + if (scalar != null && scalar.getContainerOwner() == null) continue; + } + if (slot.kind() == PerlOwnerSlot.Kind.UNTRACKED_REFERENCE) { + RuntimeScalar scalar = slot.untrackedScalarOwner(); + if (scalar != null && scalar.hasPackageAggregateUntrackedReferenceOwner()) { + continue; + } + } + return true; + } + return false; + } + + /** + * Whether a durable scalar value owns this referent outside its count. + * Refresh each exact owner first so a stale scalar cell cannot pin a + * referent after that cell has lost its Perl-visible slot. + */ + boolean hasUntrackedReferenceOwnerSlotIdentity() { + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (slot.kind() != PerlOwnerSlot.Kind.UNTRACKED_REFERENCE || !slot.isActive()) continue; + RuntimeScalar owner = slot.untrackedScalarOwner(); + if (owner != null) { + if (owner.hasLiveDurableStrongValueSlot() + || ((blessId != 0 || isWeaklyRefCountTracked()) + && owner.hasCurrentAggregateStorageSlot())) { + owner.refreshUntrackedReferenceOwner(); + } else { + owner.releaseUntrackedReferenceOwner(this); + } + } else { + slot.release(); + WeakRefRegistry.onStrongOwnerSlotReleased(this); + } + } + return ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE) != 0; + } + + /** Promote existing scalar-cell owners when this referent enters counted tracking. */ + public void promoteUntrackedScalarOwners() { + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (slot.kind() != PerlOwnerSlot.Kind.UNTRACKED_REFERENCE || !slot.isActive()) continue; + RuntimeScalar owner = slot.untrackedScalarOwner(); + if (owner == null || WeakRefRegistry.isweak(owner) + || !owner.hasLiveDurableStrongValueSlot()) continue; + RuntimeScalar.incrementRefCountForContainerStore(owner, owner.countedOwnerKind()); + } + } + + boolean hasUntrackedReferenceOwnerSlotIdentity(int scalarType) { + if (!hasUntrackedReferenceOwnerSlotIdentity()) return false; + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (slot.kind() != PerlOwnerSlot.Kind.UNTRACKED_REFERENCE || !slot.isActive()) continue; + RuntimeScalar owner = slot.untrackedScalarOwner(); + if (owner != null && owner.type == scalarType + && owner.hasLiveDurableStrongValueSlot() + && !owner.hasPackageAggregateUntrackedReferenceOwner()) { + return true; + } + } + return false; + } + + /** Whether another current scalar slot holds this referent strongly. */ + public boolean hasLiveStrongScalarOwnerSlotOtherThan(RuntimeScalar excluded) { + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (!slot.isActive() || slot.referent() != this) continue; + RuntimeScalar owner; + boolean ownerSlotMatches; + if (slot.kind() == PerlOwnerSlot.Kind.UNTRACKED_REFERENCE) { + owner = slot.untrackedScalarOwner(); + ownerSlotMatches = owner != null + && owner.untrackedReferenceOwnerSlot() == slot; + } else { + owner = slot.countedScalarOwner(); + ownerSlotMatches = owner != null + && owner.countedOwnerSlot() == slot + && owner.refCountOwned; + } + if (ownerSlotMatches && owner != excluded + && MyVarCleanupStack.isRegistered(owner) + && !WeakRefRegistry.isweak(owner) + && !owner.scopeExited + && owner.value == this) { + return true; + } + } + return false; + } + + /** Whether an aggregate has a surviving owner outside the legacy count. */ + boolean hasUncountedAggregateOwnerSlotIdentity() { + return (this instanceof RuntimeArray || this instanceof RuntimeHash) + && hasUncountedPerlOwnerSlotIdentity(); + } + + boolean hasNonPackageAggregateUncountedOwnerSlotIdentity() { + if (!(this instanceof RuntimeArray || this instanceof RuntimeHash)) return false; + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (!slot.isActive() + || PerlOwnerSlot.isCountedKind(slot.kind()) + || !PerlOwnerSlot.isPerlOwnerKind(slot.kind())) { + continue; + } + if (slot.kind() == PerlOwnerSlot.Kind.UNTRACKED_REFERENCE) { + RuntimeScalar scalar = slot.untrackedScalarOwner(); + boolean currentScalarSlot = scalar != null + && scalar.untrackedReferenceOwnerSlot() == slot + && DestroyDispatch.isCurrentPerlOwnerSlot(this, slot); + if (!currentScalarSlot) { + if (scalar != null && scalar.untrackedReferenceOwnerSlot() == slot) { + scalar.releaseUntrackedReferenceOwner(this); + } else { + slot.release(); + } + continue; + } + if (scalar != null && scalar.hasPackageAggregateUntrackedReferenceOwner()) { + continue; + } + } + return true; + } + return false; + } + + void deferFinalReleaseToUncountedOwnerSlots() { + if (!hasUncountedPerlOwnerSlotIdentity() + && !hasRawUntrackedReferenceOwnerSlotIdentity() + && !(blessId != 0 && hasUntrackedReferenceOwnerSlotIdentity())) return; + markRefCountWeaklyTracked(); + deferredFinalReleaseForUncountedOwners = true; + } + + private boolean hasRawUntrackedReferenceOwnerSlotIdentity() { + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (slot.isActive() + && slot.kind() == PerlOwnerSlot.Kind.UNTRACKED_REFERENCE + && slot.referent() == this + && !slot.hasUntrackedScalarOwnerAssociation()) return true; + } + return false; + } + + /** Defer a zero-count lifecycle transition without encoding it as a count. */ + void deferZeroCountFinalReleaseToUncountedOwnerSlots() { + if (!isRefCountTracked() || refCount != 0) { + throw new IllegalStateException("zero-count owner release requires refCount=0"); + } + if (!hasUncountedPerlOwnerSlotIdentity()) return; + deferredFinalReleaseForUncountedOwners = true; + } + + /** Hold weak cleanup until an explicit runtime snapshot lease is released. */ + void deferFinalReleaseToTemporaryRootSlots() { + if (!isRefCountTracked() || refCount != 0) { + throw new IllegalStateException("temporary-root release requires refCount=0"); + } + if (!hasTemporaryRootOwnerSlotIdentity()) return; + markRefCountWeaklyTracked(); + deferredFinalReleaseForUncountedOwners = true; + } + + /** Check whether a live owner identity besides the slot being replaced remains. */ + boolean hasOwnerSlotsOtherThan(PerlOwnerSlot excluded) { + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (slot != excluded && slot.isActive()) return true; + } + return false; } public boolean hasSemanticCaptureOwner() { @@ -334,14 +1167,57 @@ public boolean hasSemanticCaptureOwner() { /** Number of active slots of the requested kind that own this referent. */ public synchronized int ownerSlotCount(PerlOwnerSlot.Kind kind) { + int indexedCount = indexedOwnerSlotCount(kind); + if (indexedCount >= 0) return indexedCount; + if (kind == PerlOwnerSlot.Kind.ARGUMENT_ALIAS) return argumentAliasOwnerSlots; if (ownerSlots == null) return 0; int count = 0; for (PerlOwnerSlot slot : ownerSlots) { + LifecycleHotPathDiagnostics.ownerSlotsVisited(1); if (slot.kind() == kind) count++; } return count; } + /** Live concurrent view of untracked edges; callers never allocate a copied set. */ + synchronized java.util.Set untrackedReferenceOwnerSlotsView() { + return untrackedReferenceOwnerSlots == null + ? java.util.Collections.emptySet() : untrackedReferenceOwnerSlots; + } + + /** Live narrow index for CODE slots; callers that need identities avoid a full snapshot. */ + synchronized java.util.Set codeSlotOwnerSlotsView() { + return codeSlotOwnerSlots == null + ? java.util.Collections.emptySet() : codeSlotOwnerSlots; + } + + /** Number of active slot identities whose releases balance refCount. */ + synchronized int countedOwnerSlotCount() { + return countedOwnerSlots; + } + + /** Maintain the transient untracked-owner fast-path proof without rescanning slots. */ + synchronized void adjustTransientUntrackedReferenceOwnerCount(int delta) { + int next = transientUntrackedReferenceOwnerSlots + delta; + if (next < 0) { + throw new IllegalStateException( + "transient untracked owner count would become negative"); + } + transientUntrackedReferenceOwnerSlots = next; + } + + synchronized int transientUntrackedReferenceOwnerCount() { + return transientUntrackedReferenceOwnerSlots; + } + + /** Whether a current Perl storage identity already owns this value. */ + boolean hasIndependentPerlOwnerSlotForArgument() { + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (DestroyDispatch.isCurrentPerlOwnerSlot(this, slot)) return true; + } + return false; + } + /** Number of distinct captured pad slots that own this referent. */ public int semanticCaptureOwnerCount() { return ownerSlotCount(PerlOwnerSlot.Kind.CLOSURE_PAD); @@ -360,98 +1236,82 @@ public synchronized int nativeCaptureOwnerCount() { return count; } - // Conservative gate for the tied-handler reachability fallback. Once a - // base has appeared in a tie handler's strong object graph it remains - // marked; a stale true only permits the exact walker to run, while false - // means the expensive tied-root query cannot rescue this object. - boolean possiblyStoredInTiedHandler; - - void markPossiblyStoredInTiedHandler() { - java.util.Set seen = java.util.Collections.newSetFromMap( - new java.util.IdentityHashMap<>()); - java.util.ArrayDeque todo = new java.util.ArrayDeque<>(); - todo.add(this); - while (!todo.isEmpty()) { - RuntimeBase current = todo.removeFirst(); - if (!seen.add(current)) continue; - current.possiblyStoredInTiedHandler = true; - if (current instanceof RuntimeHash hash) { - if (hash.elements instanceof TieHash tieHash) { - addTiedHandlerReferent(tieHash.getSelf(), todo); - } - for (RuntimeScalar value : hash.elements.values()) { - addTiedHandlerReferent(value, todo); - } - } else if (current instanceof RuntimeArray array) { - for (RuntimeScalar value : array.elements) { - addTiedHandlerReferent(value, todo); - } - } else if (current instanceof RuntimeScalar scalar) { - addTiedHandlerReferent(scalar, todo); - } + /** Count all slots whose owners are represented directly by the owner ledger. */ + public synchronized int nativeOwnerSlotCount() { + if (ownerSlots == null) return 0; + int count = 0; + for (PerlOwnerSlot slot : ownerSlots) { + if (slot.isNativeOwner()) count++; } + return count; } - private static void addTiedHandlerReferent( - RuntimeScalar scalar, java.util.ArrayDeque todo) { - if (scalar != null - && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && scalar.value instanceof RuntimeBase base) { - todo.addLast(base); + /** Number of active counted native owner slots of the requested kind. */ + public synchronized int countedNativeOwnerSlotCount(PerlOwnerSlot.Kind kind) { + if (ownerSlots == null) return 0; + int count = 0; + for (PerlOwnerSlot slot : ownerSlots) { + LifecycleHotPathDiagnostics.ownerSlotsVisited(1); + if (slot.kind() == kind && slot.isCountedNativeOwner()) count++; } + return count; + } + + public void recordActiveOwner(RuntimeScalar scalar) { + scalar.recordCountedOwner(this); } + /** Compatibility no-op: counted owner identities are recorded eagerly. */ public void activateOwnerTracking() { - if (activeOwners == null) { - activeOwners = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>()); - // Note: backfilling from ScalarRefRegistry.snapshot() was - // observed to cause DBIC leak-test regressions due to - // WeakHashMap.expungeStaleEntries() side-effects on JVM GC - // observability. We rely on incremental population via - // recordActiveOwner() from setLargeRefCounted; objects that - // had setLarge incs BEFORE activation will be missed, but - // that's a known limitation — the activation should fire on - // first weaken(), which usually precedes the relevant stores. - } } - public void recordActiveOwner(RuntimeScalar scalar) { - if (activeOwners != null) { - activeOwners.add(scalar); + public void releaseActiveOwner(RuntimeScalar scalar) { + retireCountedOwnerIdentity(scalar, "RuntimeBase.releaseActiveOwner"); + } + + /** + * Retire a stale scalar owner identity after a nested-call guard preserved + * the referent at selective count zero. The count was already consumed by + * the guard, so this transition clears only the scalar's mirrored ownership + * flag, trace entry, and exact Perl owner slot. + */ + final void retireZeroCountOwnerIdentity(RuntimeScalar scalar, String releaseSite) { + Objects.requireNonNull(scalar, "scalar"); + Objects.requireNonNull(releaseSite, "releaseSite"); + if (!isRefCountTracked() || refCount != 0) { + throw new IllegalStateException( + "zero-count owner identity retirement requires refCount=0 at " + releaseSite); } + retireCountedOwnerIdentity(scalar, releaseSite); } - public void releaseActiveOwner(RuntimeScalar scalar) { - if (activeOwners != null) { - activeOwners.remove(scalar); + private void retireCountedOwnerIdentity(RuntimeScalar scalar, String releaseSite) { + if (scalar.releaseCountedOwnerIdentity(this, releaseSite, true) == null) { + throw new IllegalStateException( + "counted owner identity retirement requires its active PerlOwnerSlot at " + + releaseSite); } } public int activeOwnerCount() { - if (activeOwners == null) return 0; - // Filter for actual still-owning scalars: refCountOwned=true and - // value==this. Stale entries (overwritten without going through a - // tracked release path, or scope-exited via untracked paths) are - // pruned and ignored. - int count = 0; - java.util.Iterator it = activeOwners.iterator(); - while (it.hasNext()) { - RuntimeScalar sc = it.next(); - if (sc != null && sc.refCountOwned && sc.value == this) { - count++; - } else { - it.remove(); - } - } - return count; + return activeOwnerSnapshot().size(); } - /** Snapshot the currently live scalar owner slots by identity. */ + /** Snapshot current counted scalar owners by their authoritative slot identities. */ public java.util.Set activeOwnerSnapshot() { - if (activeOwnerCount() == 0) return java.util.Collections.emptySet(); java.util.Set snapshot = java.util.Collections.newSetFromMap( new java.util.IdentityHashMap<>()); - snapshot.addAll(activeOwners); + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (!slot.isActive() || slot.referent() != this + || !PerlOwnerSlot.isCountedKind(slot.kind())) { + continue; + } + RuntimeScalar scalar = slot.countedScalarOwner(); + if (scalar != null && scalar.countedOwnerSlot() == slot + && scalar.refCountOwned && scalar.value == this) { + snapshot.add(scalar); + } + } return snapshot; } @@ -460,36 +1320,37 @@ public synchronized java.util.Set ownerSlotSnapshot() { if (ownerSlots == null || ownerSlots.isEmpty()) { return java.util.Collections.emptySet(); } + LifecycleHotPathDiagnostics.ownerSlotsVisited(ownerSlots.size()); java.util.Set snapshot = java.util.Collections.newSetFromMap( new java.util.IdentityHashMap<>()); snapshot.addAll(ownerSlots); return snapshot; } - /** - * D-W6.14: count owners that are reachable from package globals or - * live my-vars. This is the strict version used by the production - * rescue at MortalList.flush refCount→0: only objects whose owners - * can be reached from real roots are kept alive. Phantom owners - * (scalars that should be dead but haven't been released yet) are - * excluded. Cycles with no external root → all owners unreachable - * → 0 → DESTROY fires (matching real Perl's cycle leak behavior - * resolved by user weaken()). - */ - public int reachableOwnerCount() { - if (activeOwners == null) return 0; - int count = 0; - java.util.Iterator it = activeOwners.iterator(); - while (it.hasNext()) { - RuntimeScalar sc = it.next(); - if (sc != null && sc.refCountOwned && sc.value == this - && ReachabilityWalker.isScalarReachable(sc)) { - count++; - } else if (sc == null || !sc.refCountOwned || sc.value != this) { - it.remove(); + private synchronized java.util.List closureCaptureOwnerSnapshot() { + if (ownerSlots == null || ownerSlots.isEmpty()) return java.util.List.of(); + LifecycleHotPathDiagnostics.ownerSlotsVisited(ownerSlots.size()); + java.util.ArrayList snapshot = new java.util.ArrayList<>(); + for (PerlOwnerSlot slot : ownerSlots) { + PerlOwnerSlot.Kind kind = slot.kind(); + if (kind == PerlOwnerSlot.Kind.SCALAR_CAPTURE + || kind == PerlOwnerSlot.Kind.CLOSURE_PAD) { + snapshot.add(slot); + } + } + return snapshot.isEmpty() ? java.util.List.of() : snapshot; + } + + /** Release closure pads whose CODE owners have no surviving owner identity. */ + void releaseUnownedClosureCaptures() { + for (PerlOwnerSlot ownerSlot : closureCaptureOwnerSnapshot()) { + if (!ownerSlot.isActive()) continue; + RuntimeCode captureOwner = ownerSlot.captureOwner(); + if (captureOwner != null + && !captureOwner.hasPerlOwnerForCaptureOtherThan(null)) { + captureOwner.releaseCaptures(); } } - return count; } private static final boolean REFCOUNT_TRACE_ENV = @@ -521,6 +1382,25 @@ public void traceRefCount(int delta, String reason) { System.err.println(sb); } + /** Apply the shared counter half of a tracked Perl-owner acquisition. */ + final void acquireTrackedOwnerCount(String acquisitionSite) { + if (!isRefCountTracked() || refCount == Integer.MAX_VALUE) { + throw new IllegalStateException("tracked owner count is unavailable at " + acquisitionSite); + } + traceRefCount(+1, acquisitionSite); + refCount++; + hadCountedReference = true; + } + + /** Apply one exact tracked-owner decrement; returns true at zero. */ + final boolean releaseTrackedOwnerCount(String releaseSite) { + if (!isRefCountTracked() || refCount <= 0) { + throw new IllegalStateException("tracked owner count is not positive at " + releaseSite); + } + traceRefCount(-1, releaseSite); + return --refCount == 0; + } + // ───────────────────────────────────────────────────────────────────── // D-W6.11 Step 1: per-scalar ownership tracking (debug-only). // When refCountTrace is on, every setLargeRefCounted increment records @@ -558,10 +1438,12 @@ private static final class OwnerTrace { } /** - * Immutable trace record retained between queueing and draining an owned - * decrement. It deliberately does not retain the scalar itself: source - * identity and acquisition site are enough for shutdown diagnosis, and a - * trace facility must not change Perl/JVM reachability. + * Completion token retained between queueing and draining an owner release + * or zero-count lifecycle boundary. It deliberately does not retain the + * scalar itself: source identity and acquisition site are enough for + * shutdown diagnosis, and a trace facility must not change Perl/JVM + * reachability. Completion is idempotent so the pending count and optional + * owner-slot token retire exactly once. */ static final class PendingOwnerRelease { final int scalarIdentity; @@ -569,6 +1451,9 @@ static final class PendingOwnerRelease { final String acquireSite; final String queueSite; final PerlOwnerSlot.PendingRelease ownerSlotRelease; + final boolean lifecycleOnlyAtZero; + final java.util.concurrent.atomic.AtomicBoolean completed = + new java.util.concurrent.atomic.AtomicBoolean(); PendingOwnerRelease(int scalarIdentity, long referentGeneration, String acquireSite, String queueSite) { @@ -578,15 +1463,32 @@ static final class PendingOwnerRelease { PendingOwnerRelease(int scalarIdentity, long referentGeneration, String acquireSite, String queueSite, PerlOwnerSlot.PendingRelease ownerSlotRelease) { + this(scalarIdentity, referentGeneration, acquireSite, queueSite, + ownerSlotRelease, false); + } + + PendingOwnerRelease(int scalarIdentity, long referentGeneration, + String acquireSite, String queueSite, + PerlOwnerSlot.PendingRelease ownerSlotRelease, + boolean lifecycleOnlyAtZero) { this.scalarIdentity = scalarIdentity; this.referentGeneration = referentGeneration; this.acquireSite = acquireSite; this.queueSite = queueSite; this.ownerSlotRelease = ownerSlotRelease; + this.lifecycleOnlyAtZero = lifecycleOnlyAtZero; + } + + boolean identifiesReleasedOwnerEdge() { + return ownerSlotRelease != null; + } + + boolean isLifecycleOnlyAtZero() { + return lifecycleOnlyAtZero; } } - private static long traceReferentGeneration(RuntimeBase base) { + static long traceReferentGeneration(RuntimeBase base) { return traceReferentGenerations.computeIfAbsent(base, ignored -> nextTraceReferentGeneration.incrementAndGet()); } @@ -597,9 +1499,16 @@ public synchronized void recordOwner(RuntimeScalar owner, String site) { .computeIfAbsent(this, k -> new java.util.LinkedHashMap<>()) .put(System.identityHashCode(owner), new OwnerTrace(owner, site)); StackTraceElement[] st = new Throwable().getStackTrace(); + PerlOwnerSlot slot = owner.countedOwnerSlot(); + RuntimeBase aggregateOwner = slot == null ? null : slot.countedAggregateOwner(); StringBuilder sb = new StringBuilder(); sb.append("[REFCOUNT-RECORD] base=").append(System.identityHashCode(this)) .append(" owner=").append(System.identityHashCode(owner)) + .append(" kind=").append(slot == null ? "" : slot.kind()) + .append(" slot=").append(slot == null ? 0 : slot.identity()) + .append(" aggregate=").append(aggregateOwner == null ? 0 + : System.identityHashCode(aggregateOwner)) + .append(" transient=").append(owner.isTransientArgumentValueOwner()) .append(" ").append(site); for (int i = 1; i < Math.min(st.length, 12); i++) { sb.append("\n at ").append(st[i]); @@ -622,14 +1531,49 @@ public synchronized void releaseOwner(RuntimeScalar owner, String site) { } /** Move an active owner trace into the deferred-decrement queue. */ - public synchronized PendingOwnerRelease queueOwnerRelease(RuntimeScalar owner, String queueSite) { - if (!refCountTrace || !REFCOUNT_TRACE_ENV) return null; + public PendingOwnerRelease queueOwnerRelease(RuntimeScalar owner, String queueSite) { + Objects.requireNonNull(owner, "owner"); + Objects.requireNonNull(queueSite, "queueSite"); + PerlOwnerSlot currentSlot = owner.countedOwnerSlot(); + boolean scalarClaimedCountedOwner = owner.refCountOwned; + PerlOwnerSlot.PendingRelease slotRelease = owner.deferCountedOwnerRelease(this); + if (slotRelease == null + && (currentSlot != null + || (scalarClaimedCountedOwner && hadCountedReference))) { + throw new IllegalStateException( + "counted owner release lost its PerlOwnerSlot before queueing: " + + owner.getClass().getSimpleName() + " -> " + + getClass().getSimpleName() + " at " + queueSite); + } + if (slotRelease == null) { + // Compatibility for synthetic or pre-tracking scalars only. The + // validation above ensures a real tracked owner cannot use this. + owner.refCountOwned = false; + registerPendingOwnerRelease(null); + } + if (!refCountTrace || !REFCOUNT_TRACE_ENV) { + return new PendingOwnerRelease( + System.identityHashCode(owner), 0, "counted owner-slot", queueSite, slotRelease); + } + return queueTracedOwnerRelease(owner, queueSite, slotRelease); + } + + /** Queue a zero-count lifecycle boundary without fabricating an owner count. */ + synchronized PendingOwnerRelease queueLifecycleOnlyAtZero(String queueSite) { + registerPendingOwnerRelease(null); + return new PendingOwnerRelease(0, + REFCOUNT_TRACE_ENV ? traceReferentGeneration(this) : 0, + "zero-count lifecycle", queueSite, null, true); + } + + private synchronized PendingOwnerRelease queueTracedOwnerRelease( + RuntimeScalar owner, String queueSite, PerlOwnerSlot.PendingRelease slotRelease) { int scalarIdentity = System.identityHashCode(owner); java.util.LinkedHashMap owners = traceOwners.get(this); OwnerTrace ownerTrace = owners == null ? null : owners.remove(scalarIdentity); String acquireSite = ownerTrace == null ? "" : ownerTrace.acquireSite; PendingOwnerRelease release = new PendingOwnerRelease( - scalarIdentity, traceReferentGeneration(this), acquireSite, queueSite); + scalarIdentity, traceReferentGeneration(this), acquireSite, queueSite, slotRelease); pendingTraceOwnerReleases .computeIfAbsent(this, k -> new java.util.ArrayList<>()) .add(release); @@ -639,6 +1583,7 @@ public synchronized PendingOwnerRelease queueOwnerRelease(RuntimeScalar owner, S /** Queue provenance for a deferred owner-slot decrement. */ synchronized PendingOwnerRelease queueOwnerSlotRelease( PerlOwnerSlot.PendingRelease ownerSlotRelease) { + registerPendingOwnerRelease(ownerSlotRelease); PendingOwnerRelease release = new PendingOwnerRelease( 0, REFCOUNT_TRACE_ENV ? traceReferentGeneration(this) : 0, "owner-slot", "MortalList.deferOwnerSlotDecrement", ownerSlotRelease); @@ -650,10 +1595,23 @@ synchronized PendingOwnerRelease queueOwnerSlotRelease( } /** Mark the exact queued trace record as drained without relying on scalar state. */ - public synchronized void completeQueuedOwnerRelease(PendingOwnerRelease release, String releaseSite) { - if (release == null) return; - if (release.ownerSlotRelease != null) release.ownerSlotRelease.complete(); - if (!REFCOUNT_TRACE_ENV) return; + public synchronized boolean completeQueuedOwnerRelease( + PendingOwnerRelease release, String releaseSite) { + if (release == null || !release.completed.compareAndSet(false, true)) return false; + if (release.ownerSlotRelease != null) { + if (PerlOwnerSlot.isCountedKind(release.ownerSlotRelease.kind())) { + pendingCountedOwnerReleases--; + if (pendingCountedOwnerReleases < 0) { + throw new IllegalStateException("pending counted owner release underflow"); + } + } + if (release.ownerSlotRelease.kind() == PerlOwnerSlot.Kind.RETURN_VALUE) { + pendingReturnOwners--; + } + release.ownerSlotRelease.complete(); + } + pendingOwnerReleases--; + if (!REFCOUNT_TRACE_ENV) return true; java.util.ArrayList releases = pendingTraceOwnerReleases.get(this); if (releases != null) { releases.remove(release); @@ -665,6 +1623,7 @@ public synchronized void completeQueuedOwnerRelease(PendingOwnerRelease release, + " acquire-site=" + release.acquireSite + " queue-site=" + release.queueSite + " release-site=" + releaseSite); + return true; } public void cancelQueuedOwnerRelease(PendingOwnerRelease release, String cancelSite) { @@ -741,7 +1700,11 @@ public synchronized String ownerTraceSnapshot() { } result.append(']'); } - result.append(" capturePads="); + result.append(" state=").append(perlLifecycleState()) + .append(" destroyFired=").append(destroyFired) + .append(" needsReDestroy=").append(needsReDestroy) + .append(" hasWeakRefs=").append(WeakRefRegistry.hasWeakRefsTo(this)) + .append(" capturePads="); if (ownerSlots == null || ownerSlots.isEmpty()) { result.append("[]"); } else { @@ -767,9 +1730,212 @@ public synchronized String ownerTraceSnapshot() { } else { result.append(pad.value.getClass().getSimpleName()); } + result.append(" capturedBy=["); + boolean firstCaptureOwner = true; + for (PerlOwnerSlot padOwner : pad.ownerSlotSnapshot()) { + if (padOwner.kind() != PerlOwnerSlot.Kind.SCALAR_CAPTURE) continue; + if (!firstCaptureOwner) result.append(", "); + firstCaptureOwner = false; + RuntimeCode code = padOwner.captureOwner(); + if (code == null) { + result.append("unknown"); + } else { + result.append(System.identityHashCode(code)).append(':') + .append(code.packageName == null ? "" : code.packageName) + .append("::").append(code.subName == null ? "" : code.subName) + .append('@').append(code.cvStartFile == null ? "" : code.cvStartFile) + .append(':').append(code.cvStartLine); + } + } + result.append(']'); + RuntimeCode captureOwner = slot.captureOwner(); + if (captureOwner != null) { + result.append(" ownerCode=").append(System.identityHashCode(captureOwner)) + .append(" name=") + .append(captureOwner.packageName == null ? "" : captureOwner.packageName) + .append("::") + .append(captureOwner.subName == null ? "" : captureOwner.subName) + .append(" source=") + .append(captureOwner.cvStartFile == null ? "" : captureOwner.cvStartFile) + .append(':').append(captureOwner.cvStartLine); + } } result.append(']'); } + result.append(" ownerSlots=["); + boolean firstOwnerSlot = true; + for (PerlOwnerSlot ownerSlot : ownerSlotSnapshot()) { + if (!ownerSlot.isActive()) continue; + if (!firstOwnerSlot) result.append(", "); + firstOwnerSlot = false; + result.append(ownerSlot.kind()).append('#').append(ownerSlot.identity()); + int resourceOwnerIdentity = ownerSlot.resourceScalarIdentity(); + if (resourceOwnerIdentity != 0) { + result.append(" resourceScalarId=").append(resourceOwnerIdentity); + if (ownerSlot.resourceScalarOwner() == null) result.append(" carrierCollected"); + } + RuntimeScalar owner = ownerSlot.countedScalarOwner(); + if (owner == null) owner = ownerSlot.untrackedScalarOwner(); + if (owner == null) owner = ownerSlot.scalarContentsOwner(); + if (owner == null) owner = ownerSlot.suspendedScalarOwner(); + if (owner == null) owner = ownerSlot.resourceScalarOwner(); + if (owner != null) { + result.append(" scalar=").append(System.identityHashCode(owner)) + .append(" type=").append(owner.type) + .append(" scopeExited=").append(owner.scopeExited) + .append(" owns=").append(owner.refCountOwned) + .append(" weak=").append(WeakRefRegistry.isweak(owner)) + .append(" durable=").append(owner.hasLiveDurableStrongValueSlot()) + .append(" transientArg=").append(owner.isTransientArgumentValueOwner()) + .append(" localBinding=").append(owner.localBindingExists) + .append(" registeredLexical=").append(MyVarCleanupStack.isRegistered(owner)) + .append(" packageRoot=").append(owner.isPackageGlobalRoot) + .append(" closureOwner=").append(owner.hasClosureCaptureOwner()) + .append(" scalarRef=").append(owner.referencedByScalarReference) + .append(" codeSlot=").append(owner.hasCodeSlotBinding()) + .append(" scalarContents=").append(owner.hasScalarReferenceContentsOwner()) + .append(" scalarCellOwner=").append(owner.hasScalarCellOwner()) + .append(" ioOwner=").append(owner.hasIoOwner()) + .append(" pendingReturn=").append(owner.hasPendingReturnOwner()) + .append(" packageScalarSlots=") + .append(owner.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT)) + .append(" globComponentSlots=") + .append(owner.ownerSlotCount(PerlOwnerSlot.Kind.GLOB_COMPONENT_SLOT)) + .append(" argumentValueSlots=") + .append(owner.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)) + .append(" argumentContainerSlots=") + .append(owner.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_CONTAINER)) + .append(" returnValueSlots=") + .append(owner.ownerSlotCount(PerlOwnerSlot.Kind.RETURN_VALUE)) + .append(" tieHandlerSlots=") + .append(owner.ownerSlotCount(PerlOwnerSlot.Kind.TIE_HANDLER)) + .append(" argumentTieHandlerSlots=") + .append(owner.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_TIE_HANDLER)) + .append(" packageNames="); + appendPackageScalarNames(result, owner); + result.append(" ownerClass=").append(owner.getClass().getSimpleName()); + result.append(" containerHistory=").append(owner.debugContainerOwners()); + RuntimeBase container = owner.containerOwner; + if (container != null) { + result.append(" container=").append(container.getClass().getSimpleName()) + .append('#').append(System.identityHashCode(container)); + if (container instanceof RuntimeArray array) { + PerlRuntime runtime = PerlRuntime.currentOrNull(); + boolean activeArgs = runtime != null + && runtime.executionState().argsStack.contains(array); + result.append(" arraySize=").append(array.elements.size()) + .append(" aliased=").append(array.elementsAliased) + .append(" owned=").append(array.elementsOwned) + .append(" activeArgs=").append(activeArgs); + if (activeArgs) { + for (int depth = 0; ; depth++) { + RuntimeArray activeFrame = RuntimeCode.getActiveArgsAt(depth); + if (activeFrame == null) break; + if (activeFrame != array) continue; + RuntimeCode activeCode = RuntimeCode.getActiveCodeAt(depth); + result.append(" argsFrameDepth=").append(depth) + .append(" activeCode="); + if (activeCode == null) { + result.append("none"); + } else { + result.append(activeCode.packageName).append("::") + .append(activeCode.subName) + .append('@').append(activeCode.cvStartFile) + .append(':').append(activeCode.cvStartLine); + } + break; + } + } + for (int i = 0; i < array.elements.size(); i++) { + if (array.elements.get(i) == owner) { + result.append(" index=").append(i); + break; + } + } + result.append(" arrayRefCount=").append(array.refCount) + .append(" arrayOwners=["); + boolean firstArrayOwner = true; + for (PerlOwnerSlot arrayOwner : array.ownerSlotSnapshot()) { + if (!arrayOwner.isActive()) continue; + if (!firstArrayOwner) result.append(", "); + firstArrayOwner = false; + result.append(arrayOwner.kind()).append('#').append(arrayOwner.identity()); + RuntimeScalar arrayOwnerCell = arrayOwner.countedScalarOwner(); + if (arrayOwnerCell == null) { + arrayOwnerCell = arrayOwner.untrackedScalarOwner(); + } + if (arrayOwnerCell != null) { + result.append(" scalar=") + .append(System.identityHashCode(arrayOwnerCell)); + } + } + result.append(']'); + } else if (container instanceof RuntimeHash hash) { + appendHashOwnerContext(result, hash, owner, " hash"); + result.append(" hashOwners=["); + boolean firstHashOwner = true; + for (PerlOwnerSlot hashOwner : hash.ownerSlotSnapshot()) { + if (!hashOwner.isActive()) continue; + if (!firstHashOwner) result.append(", "); + firstHashOwner = false; + result.append(hashOwner.kind()).append('#') + .append(hashOwner.identity()); + RuntimeScalar hashOwnerCell = hashOwner.countedScalarOwner(); + if (hashOwnerCell == null) { + hashOwnerCell = hashOwner.untrackedScalarOwner(); + } + if (hashOwnerCell != null) { + result.append(" scalar=") + .append(System.identityHashCode(hashOwnerCell)) + .append(" ownerCellOwnsCount=") + .append(hashOwnerCell.refCountOwned) + .append(" ownerCellLocalBinding=") + .append(hashOwnerCell.localBindingExists) + .append(" ownerCellScopeExited=") + .append(hashOwnerCell.scopeExited) + .append(" ownerCellPackageRoot=") + .append(hashOwnerCell.isPackageGlobalRoot) + .append(" ownerCellPackageScalarSlots=") + .append(hashOwnerCell.ownerSlotCount( + PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT)) + .append(" ownerCellClosure=") + .append(hashOwnerCell.hasClosureCaptureOwner()) + .append(" ownerCellPackageNames="); + appendPackageScalarNames(result, hashOwnerCell); + result.append(" ownerCellCountedSlot="); + PerlOwnerSlot countedCellOwner = hashOwnerCell.countedOwnerSlot(); + if (countedCellOwner == null) result.append("none"); + else result.append(countedCellOwner.kind()).append('#') + .append(countedCellOwner.identity()) + .append(countedCellOwner.isActive() ? ":active" : ":inactive"); + result.append(" ownerCellReferent="); + if (hashOwnerCell.value instanceof RuntimeBase cellReferent) { + result.append(cellReferent.getClass().getSimpleName()) + .append('#').append(System.identityHashCode(cellReferent)) + .append("/refCount=").append(cellReferent.refCount); + } else { + result.append("none"); + } + RuntimeBase ownerContainer = hashOwnerCell.containerOwner; + if (ownerContainer != null) { + result.append(" ownerContainer=") + .append(ownerContainer.getClass().getSimpleName()) + .append('#').append(System.identityHashCode(ownerContainer)); + if (ownerContainer instanceof RuntimeHash ownerHash) { + appendHashOwnerContext(result, ownerHash, + hashOwnerCell, " ownerHash"); + } + } + } + } + result.append(']'); + } + } + if (owner.isPackageGlobalRoot) result.append(" packageRoot"); + if (owner.localBindingExists) result.append(" localBinding"); + } + } + result.append(']'); result.append(" pending="); java.util.ArrayList pending = pendingTraceOwnerReleases.get(this); if (pending == null || pending.isEmpty()) { @@ -807,9 +1973,446 @@ public synchronized String ownerTraceSnapshot() { result.append(']'); } result.append(" semanticCaptureOwners=").append(semanticCaptureOwnerCount()); + result.append(" matchingArgumentFrames=["); + boolean firstMatchingArgumentFrame = true; + int argumentFrameDepth = 0; + for (RuntimeArray argumentFrame : RuntimeCode.snapshotArgsStack()) { + boolean matches = false; + for (RuntimeScalar argument : argumentFrame.elements) { + if (argument != null && argument.value == this) { + matches = true; + break; + } + } + if (matches) { + if (!firstMatchingArgumentFrame) result.append(", "); + firstMatchingArgumentFrame = false; + RuntimeCode activeCode = RuntimeCode.getActiveCodeAt(argumentFrameDepth); + result.append(argumentFrameDepth).append(':'); + if (activeCode == null) { + result.append("none"); + } else { + result.append(activeCode.packageName).append("::") + .append(activeCode.subName) + .append('@').append(activeCode.cvStartFile) + .append(':').append(activeCode.cvStartLine); + } + } + argumentFrameDepth++; + } + result.append(']'); return result.toString(); } + private static void appendHashOwnerContext(StringBuilder result, RuntimeHash hash, + RuntimeScalar owner, String prefix) { + result.append(prefix).append("Size=").append(hash.elements.size()) + .append(prefix).append("RefCount=").append(hash.refCount) + .append(prefix).append("ScopeExited=").append(hash.scopeExited) + .append(prefix).append("BlessId=").append(hash.blessId) + .append(prefix).append("Class=").append(NameNormalizer.getBlessStr(hash.blessId)) + .append(prefix).append("DestroyFired=").append(hash.destroyFired) + .append(prefix).append("NeedsReDestroy=").append(hash.needsReDestroy) + .append(prefix).append("LocalBinding=").append(hash.localBindingExists) + .append(prefix).append("PerlState=").append(hash.perlLifecycleState()) + .append(prefix).append("OwnerSlots=["); + boolean firstOwner = true; + for (PerlOwnerSlot ownerSlot : hash.ownerSlotSnapshot()) { + if (!ownerSlot.isActive()) continue; + if (!firstOwner) result.append(','); + firstOwner = false; + result.append(ownerSlot.kind()).append('#').append(ownerSlot.identity()); + RuntimeScalar ownerCell = ownerSlot.countedScalarOwner(); + if (ownerCell == null) ownerCell = ownerSlot.untrackedScalarOwner(); + if (ownerCell != null) { + result.append(":scalar=").append(System.identityHashCode(ownerCell)) + .append(":ownsCount=").append(ownerCell.refCountOwned) + .append(":localBinding=").append(ownerCell.localBindingExists) + .append(":scopeExited=").append(ownerCell.scopeExited) + .append(":packageRoot=").append(ownerCell.isPackageGlobalRoot) + .append(":packageScalarSlots=").append(ownerCell.ownerSlotCount( + PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT)) + .append(":closure=").append(ownerCell.hasClosureCaptureOwner()) + .append(":packageNames="); + appendPackageScalarNames(result, ownerCell); + result.append(":value="); + if (ownerCell.value instanceof RuntimeBase valueBase) { + result.append(valueBase.getClass().getSimpleName()).append('#') + .append(System.identityHashCode(valueBase)); + if (REFCOUNT_TRACE_ENV) { + result.append("/generation=").append(traceReferentGeneration(valueBase)); + } + result.append("/refCount=").append(valueBase.refCount); + } else { + result.append("none"); + } + if (ownerCell instanceof RuntimeBaseProxy proxy) { + result.append(":proxyClass=").append(ownerCell.getClass().getSimpleName()) + .append(":proxyHasLvalue=").append(proxy.hasLvalue()) + .append(":proxyLiveValue=").append(proxy.hasLivePerlValueOwner()) + .append(":proxyLivePersistentValue=") + .append(proxy.hasLivePerlValueOwner(true)); + RuntimeBase proxyParent = proxy instanceof RuntimeHashProxyEntry hashProxy + ? hashProxy.getParent() + : proxy instanceof RuntimeArrayProxyEntry arrayProxy + ? arrayProxy.getParent() : null; + if (proxyParent != null) { + result.append(":proxyParent=") + .append(proxyParent.getClass().getSimpleName()).append('#') + .append(System.identityHashCode(proxyParent)) + .append("/refCount=").append(proxyParent.refCount) + .append("/state=").append(proxyParent.perlLifecycleState()) + .append("/perOwner=").append(proxyParent.hasPerlStrongOwnerIdentity()) + .append("/persistentOwner=") + .append(proxyParent.hasPersistentPerlStrongOwnerIdentity()) + .append("/registered=").append(MyVarCleanupStack.isRegistered(proxyParent)) + .append("/global=") + .append(GlobalVariable.findGlobalAggregateName(proxyParent)); + } + } + RuntimeBase cellContainer = ownerCell.containerOwner; + if (cellContainer != null) { + result.append(":container=") + .append(cellContainer.getClass().getSimpleName()).append('#') + .append(System.identityHashCode(cellContainer)); + result.append(":globalContainer=") + .append(GlobalVariable.findGlobalAggregateName(cellContainer)); + if (REFCOUNT_TRACE_ENV) { + result.append("/generation=").append(traceReferentGeneration(cellContainer)); + } + if (cellContainer instanceof RuntimeHash cellHash) { + result.append("/refCount=").append(cellHash.refCount) + .append("/state=").append(cellHash.perlLifecycleState()) + .append("/keys=["); + boolean firstKey = true; + for (java.util.Map.Entry entry + : cellHash.elements.entrySet()) { + if (entry.getValue() != ownerCell) continue; + if (!firstKey) result.append(','); + firstKey = false; + result.append(entry.getKey()); + } + result.append(']'); + } else if (cellContainer instanceof RuntimeArray cellArray) { + result.append("/refCount=").append(cellArray.refCount) + .append("/state=").append(cellArray.perlLifecycleState()) + .append("/scopeExited=").append(cellArray.scopeExited) + .append("/localBinding=").append(cellArray.localBindingExists) + .append("/elementsAliased=").append(cellArray.elementsAliased) + .append("/elementsOwned=").append(cellArray.elementsOwned) + .append("/packageRoot=").append(cellArray.isPackageGlobalRoot) + .append("/hasPerlOwner=").append(cellArray.hasPerlStrongOwner()) + .append("/size=").append(cellArray.elements.size()) + .append("/ownerSlots=["); + boolean firstArraySlot = true; + for (PerlOwnerSlot arraySlot : cellArray.ownerSlotSnapshot()) { + if (!arraySlot.isActive()) continue; + if (!firstArraySlot) result.append(','); + firstArraySlot = false; + result.append(arraySlot.kind()).append('#').append(arraySlot.identity()); + RuntimeScalar arrayOwnerCell = arraySlot.countedScalarOwner(); + if (arrayOwnerCell == null) { + arrayOwnerCell = arraySlot.untrackedScalarOwner(); + } + if (arrayOwnerCell != null) { + result.append(":scalar=") + .append(System.identityHashCode(arrayOwnerCell)) + .append(":weak=").append(WeakRefRegistry.isweak(arrayOwnerCell)) + .append(":owns=").append(arrayOwnerCell.refCountOwned) + .append(":scopeExited=").append(arrayOwnerCell.scopeExited) + .append(":value="); + if (arrayOwnerCell.value instanceof RuntimeBase arrayValue) { + result.append(arrayValue.getClass().getSimpleName()) + .append('#').append(System.identityHashCode(arrayValue)); + } else { + result.append(arrayOwnerCell.value == null ? "null" + : arrayOwnerCell.value.getClass().getSimpleName()); + } + RuntimeBase parentContainer = arrayOwnerCell.containerOwner; + if (parentContainer != null) { + result.append(":parent=") + .append(parentContainer.getClass().getSimpleName()) + .append('#').append(System.identityHashCode(parentContainer)); + if (parentContainer instanceof RuntimeArray parentArray) { + PerlRuntime runtime = PerlRuntime.currentOrNull(); + result.append("/size=").append(parentArray.elements.size()) + .append("/activeArgs=").append(runtime != null + && runtime.executionState().argsStack.contains(parentArray)); + for (int i = 0; i < parentArray.elements.size(); i++) { + if (parentArray.elements.get(i) == arrayOwnerCell) { + result.append("/index=").append(i); + break; + } + } + result.append("/blessId=").append(parentArray.blessId) + .append("/class=") + .append(NameNormalizer.getBlessStr(parentArray.blessId)) + .append("/ownerPaths=["); + boolean firstParentOwner = true; + for (PerlOwnerSlot parentSlot : parentArray.ownerSlotSnapshot()) { + if (!parentSlot.isActive()) continue; + if (!firstParentOwner) result.append(','); + firstParentOwner = false; + result.append(parentSlot.kind()).append('#') + .append(parentSlot.identity()); + RuntimeScalar parentOwnerCell = parentSlot.countedScalarOwner(); + if (parentOwnerCell == null) { + parentOwnerCell = parentSlot.untrackedScalarOwner(); + } + if (parentOwnerCell == null) continue; + result.append(":scalar=") + .append(System.identityHashCode(parentOwnerCell)) + .append(":type=").append(parentOwnerCell.type) + .append(":value="); + if (parentOwnerCell.value instanceof RuntimeBase parentValue) { + result.append(parentValue.getClass().getSimpleName()) + .append('#').append(System.identityHashCode(parentValue)); + } else { + result.append(parentOwnerCell.value == null ? "null" + : parentOwnerCell.value.getClass().getSimpleName()); + } + RuntimeBase rootContainer = parentOwnerCell.containerOwner; + if (rootContainer != null) { + result.append(":root=") + .append(rootContainer.getClass().getSimpleName()) + .append('#').append(System.identityHashCode(rootContainer)); + if (rootContainer instanceof RuntimeArray rootArray) { + result.append("/size=").append(rootArray.elements.size()) + .append("/activeArgs=").append(runtime != null + && runtime.executionState().argsStack.contains(rootArray)); + for (int i = 0; i < rootArray.elements.size(); i++) { + if (rootArray.elements.get(i) == parentOwnerCell) { + result.append("/index=").append(i); + break; + } + } + } else if (rootContainer instanceof RuntimeHash rootHash) { + result.append("/blessId=").append(rootHash.blessId) + .append("/class=") + .append(NameNormalizer.getBlessStr(rootHash.blessId)) + .append("/size=").append(rootHash.elements.size()) + .append("/refCount=").append(rootHash.refCount) + .append("/keys=["); + boolean firstRootKey = true; + for (java.util.Map.Entry rootEntry + : rootHash.elements.entrySet()) { + if (rootEntry.getValue() != parentOwnerCell) continue; + if (!firstRootKey) result.append(','); + firstRootKey = false; + result.append(rootEntry.getKey()); + } + result.append("]/ownerPaths=["); + boolean firstRootOwner = true; + for (PerlOwnerSlot rootSlot : rootHash.ownerSlotSnapshot()) { + if (!rootSlot.isActive()) continue; + if (!firstRootOwner) result.append(','); + firstRootOwner = false; + result.append(rootSlot.kind()).append('#') + .append(rootSlot.identity()); + RuntimeScalar rootOwnerCell = rootSlot.countedScalarOwner(); + if (rootOwnerCell == null) { + rootOwnerCell = rootSlot.untrackedScalarOwner(); + } + if (rootOwnerCell == null) continue; + result.append(":scalar=") + .append(System.identityHashCode(rootOwnerCell)) + .append(":value="); + if (rootOwnerCell.value instanceof RuntimeBase rootValue) { + result.append(rootValue.getClass().getSimpleName()) + .append('#').append(System.identityHashCode(rootValue)); + } else { + result.append(rootOwnerCell.value == null ? "null" + : rootOwnerCell.value.getClass().getSimpleName()); + } + RuntimeBase rootParent = rootOwnerCell.containerOwner; + if (rootParent != null) { + result.append(":parent=") + .append(rootParent.getClass().getSimpleName()) + .append('#').append(System.identityHashCode(rootParent)); + if (rootParent instanceof RuntimeArray rootParentArray) { + result.append("/size=") + .append(rootParentArray.elements.size()) + .append("/activeArgs=").append(runtime != null + && runtime.executionState().argsStack + .contains(rootParentArray)); + } else if (rootParent instanceof RuntimeHash rootParentHash) { + result.append("/blessId=") + .append(rootParentHash.blessId) + .append("/class=") + .append(NameNormalizer.getBlessStr( + rootParentHash.blessId)); + result.append("/ownerSlots=["); + boolean firstCursorOwner = true; + for (PerlOwnerSlot cursorSlot + : rootParentHash.ownerSlotSnapshot()) { + if (!cursorSlot.isActive()) continue; + if (!firstCursorOwner) result.append(','); + firstCursorOwner = false; + result.append(cursorSlot.kind()).append('#') + .append(cursorSlot.identity()); + RuntimeScalar cursorOwnerCell = + cursorSlot.countedScalarOwner(); + if (cursorOwnerCell == null) { + cursorOwnerCell = cursorSlot.untrackedScalarOwner(); + } + if (cursorOwnerCell != null) { + result.append(":cell=") + .append(System.identityHashCode(cursorOwnerCell)) + .append(":owns=") + .append(cursorOwnerCell.refCountOwned) + .append(":value="); + if (cursorOwnerCell.value instanceof RuntimeBase cursorValue) { + result.append(cursorValue.getClass().getSimpleName()) + .append('#') + .append(System.identityHashCode(cursorValue)); + } else { + result.append(cursorOwnerCell.value == null + ? "null" + : cursorOwnerCell.value.getClass() + .getSimpleName()); + } + RuntimeBase cursorOwnerContainer = + cursorOwnerCell.containerOwner; + if (cursorOwnerContainer != null) { + result.append(":container=") + .append(cursorOwnerContainer.getClass() + .getSimpleName()) + .append('#') + .append(System.identityHashCode( + cursorOwnerContainer)); + if (cursorOwnerContainer instanceof RuntimeHash + cursorOwnerHash) { + result.append(":keys=["); + boolean firstCursorKey = true; + for (java.util.Map.Entry cursorEntry + : cursorOwnerHash.elements + .entrySet()) { + if (cursorEntry.getValue() + != cursorOwnerCell) continue; + if (!firstCursorKey) { + result.append(','); + } + firstCursorKey = false; + result.append(cursorEntry.getKey()); + } + result.append(']'); + } + } + } + } + result.append(']'); + result.append("/keys=["); + boolean firstKey = true; + for (java.util.Map.Entry entry + : rootParentHash.elements.entrySet()) { + if (entry.getValue() != rootOwnerCell) continue; + if (!firstKey) result.append(','); + firstKey = false; + result.append(entry.getKey()); + } + result.append(']'); + } + } + } + result.append(']'); + } + } + } + result.append(']'); + } else if (parentContainer instanceof RuntimeHash parentHash) { + result.append("/blessId=").append(parentHash.blessId) + .append("/class=") + .append(NameNormalizer.getBlessStr(parentHash.blessId)); + result.append("/refCount=").append(parentHash.refCount) + .append("/state=").append(parentHash.perlLifecycleState()) + .append("/ownerSlots=["); + boolean firstContainerOwner = true; + for (PerlOwnerSlot containerSlot : parentHash.ownerSlotSnapshot()) { + if (!containerSlot.isActive()) continue; + if (!firstContainerOwner) result.append(','); + firstContainerOwner = false; + result.append(containerSlot.kind()).append('#') + .append(containerSlot.identity()); + RuntimeScalar containerCell = containerSlot.countedScalarOwner(); + if (containerCell == null) { + containerCell = containerSlot.untrackedScalarOwner(); + } + if (containerCell != null) { + result.append(":cell=") + .append(System.identityHashCode(containerCell)) + .append(":owns=").append(containerCell.refCountOwned) + .append(":value="); + if (containerCell.value instanceof RuntimeBase containerValue) { + result.append(containerValue.getClass().getSimpleName()) + .append('#').append(System.identityHashCode(containerValue)); + } else { + result.append(containerCell.value == null ? "null" + : containerCell.value.getClass().getSimpleName()); + } + RuntimeBase ownerContainer = containerCell.containerOwner; + if (ownerContainer != null) { + result.append(":container=") + .append(ownerContainer.getClass().getSimpleName()) + .append('#').append(System.identityHashCode(ownerContainer)); + if (ownerContainer instanceof RuntimeHash ownerHash) { + result.append(":keys="); + for (java.util.Map.Entry ownerEntry + : ownerHash.elements.entrySet()) { + if (ownerEntry.getValue() == containerCell) { + result.append(ownerEntry.getKey()); + break; + } + } + } + } + } + } + result.append("]"); + result.append("/keys=["); + boolean firstParentKey = true; + for (java.util.Map.Entry parentEntry + : parentHash.elements.entrySet()) { + if (parentEntry.getValue() != arrayOwnerCell) continue; + if (!firstParentKey) result.append(','); + firstParentKey = false; + result.append(parentEntry.getKey()); + } + result.append(']'); + } + } + } + } + result.append(']'); + } + } + } + } + result.append(']') + .append(prefix).append("Keys=["); + boolean firstKey = true; + for (java.util.Map.Entry entry : hash.elements.entrySet()) { + if (entry.getValue() != owner) continue; + if (!firstKey) result.append(", "); + firstKey = false; + result.append(entry.getKey()); + } + result.append(']'); + } + + private static void appendPackageScalarNames(StringBuilder result, RuntimeScalar owner) { + result.append('['); + boolean first = true; + for (java.util.Map.Entry entry + : GlobalVariable.globalVariables.entrySet()) { + if (entry.getValue() != owner) continue; + if (!first) result.append(','); + first = false; + result.append(entry.getKey()); + } + result.append(']'); + } + public static void dumpTraceOwners() { if (!REFCOUNT_TRACE_ENV) return; for (java.util.Map.Entry> e @@ -824,6 +2427,7 @@ public static void dumpTraceOwners() { for (java.util.Map.Entry own : e.getValue().entrySet()) { System.err.println(" owner=" + own.getKey() + " from " + own.getValue().acquireSite); } + System.err.println(" " + b.ownerTraceSnapshot()); } for (java.util.Map.Entry> e : pendingTraceOwnerReleases.entrySet()) { @@ -856,8 +2460,8 @@ public static void dumpTraceOwners() { /** * True once a scalar/container slot has taken a counted reference to this * base. If later refcount drift leaves the count at zero during scope - * cleanup, this tells cleanup that an external owner may have existed and a - * bounded reachability check is worthwhile. + * cleanup, this lets queueing verify that the scalar still has its exact + * counted owner slot. */ public boolean hadCountedReference = false; diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeBaseProxy.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeBaseProxy.java index 86a75c29ed..ffcb608b14 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeBaseProxy.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeBaseProxy.java @@ -25,6 +25,16 @@ public boolean hasLvalue() { return lvalue != null; } + /** Whether this proxy still denotes a Perl-owned value slot. */ + boolean hasLivePerlValueOwner() { + return true; + } + + /** Whether the value slot is backed by a parent with the requested lifetime. */ + boolean hasLivePerlValueOwner(boolean requirePersistentParent) { + return hasLivePerlValueOwner(); + } + /** * Resolves the backing slot without applying its scalar dereference magic. * Callers such as tied()/untie() need the slot itself, not a FETCH result. @@ -34,6 +44,16 @@ public RuntimeScalar resolveLvalue() { return lvalue; } + /** Aggregate whose element this lvalue aliases, if it is an aggregate slot. */ + RuntimeBase argumentAliasContainer() { + return lvalue == null ? null : lvalue.getContainerOwner(); + } + + /** Acquire any magic owner that an active argument alias must retain. */ + RuntimeScalar retainArgumentAliasHandlerOwner() { + return null; + } + /** * "Blesses" a Perl reference into an object by associating it with a class name. * This method is used to convert a Perl reference into an object of a specified class. @@ -57,12 +77,6 @@ public static RuntimeScalar bless(RuntimeBaseProxy runtimeBaseProxy, RuntimeScal */ abstract void vivify(); - private static boolean rootEdge(RuntimeScalar scalar) { - return scalar != null - && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && scalar.value instanceof RuntimeBase; - } - /** * Vivifies this proxy as an lvalue. Creates the actual entry in the parent * hash/array, matching Perl 5's behavior where hash element access in lvalue @@ -92,11 +106,7 @@ public RuntimeScalar set(RuntimeScalar value) { && hpe.getParent() != null && hpe.getParent().isGlobalPackageHash; if (globalHashEntry) { - boolean invalidatesRootSnapshot = rootEdge(lvalue) || rootEdge(value); lvalue.isPackageGlobalRoot = true; - if (invalidatesRootSnapshot) { - MortalList.invalidateExternalRootSnapshot(); - } } this.lvalue.set(value); this.type = lvalue.type; @@ -106,8 +116,8 @@ public RuntimeScalar set(RuntimeScalar value) { // D-W6.18: propagate package-global metadata flag. // If this proxy is for an element of a package-global hash, // mark the stored value's referent as storedInPackageGlobal - // so the walker gate at refCount→0 can rescue it across - // transient zeros (replaces the class-name heuristic). + // so final-release cleanup can recognize it across transient + // selective-count zeros (replaces the class-name heuristic). if (globalHashEntry && lvalue.value instanceof RuntimeBase rb) { rb.storedInPackageGlobal = true; } @@ -223,11 +233,7 @@ public RuntimeScalar undefine() { if (this instanceof RuntimeHashProxyEntry hpe && hpe.getParent() != null && hpe.getParent().isGlobalPackageHash) { - boolean invalidatesRootSnapshot = rootEdge(lvalue); lvalue.isPackageGlobalRoot = true; - if (invalidatesRootSnapshot) { - MortalList.invalidateExternalRootSnapshot(); - } } RuntimeScalar ret = lvalue.undefine(); this.type = lvalue.type; diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeCode.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeCode.java index e4d2c2da88..7a276cb733 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeCode.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeCode.java @@ -105,17 +105,62 @@ private record SortComparatorFrame(RuntimeCode comparator, int entryDepth) {} /** Values staged while a JVM call site's argument expressions are evaluated. */ public static final class CallArguments extends RuntimeScalar { + /** + * A non-persistent scalar argument is itself temporary call storage. + * Perl allows the callee to assign through @_, so remember its initial + * contents and retire a replacement value when that temporary leaves + * the call. The separate staged-value owner only protects the value + * that was present before the call. + */ + private static final class TemporaryArgumentCell { + private final RuntimeScalar scalar; + private final int initialType; + private final Object initialValue; + private final PerlOwnerSlot initialOwner; + private final boolean initialOwnerActive; + private final RuntimeBase initialOwnerReferent; + + private TemporaryArgumentCell(RuntimeScalar scalar) { + this.scalar = scalar; + initialType = scalar.type; + initialValue = scalar.value; + initialOwner = scalar.countedOwnerSlot(); + initialOwnerActive = initialOwner != null && initialOwner.isActive(); + initialOwnerReferent = initialOwner == null ? null : initialOwner.referent(); + } + + private boolean wasChanged() { + PerlOwnerSlot owner = scalar.countedOwnerSlot(); + boolean ownerActive = owner != null && owner.isActive(); + RuntimeBase ownerReferent = owner == null ? null : owner.referent(); + return scalar.type != initialType + || scalar.value != initialValue + || owner != initialOwner + || ownerActive != initialOwnerActive + || ownerReferent != initialOwnerReferent; + } + } + private final RuntimeBase[] values; private final java.util.ArrayList listResultOwners = new java.util.ArrayList<>(); + private final IdentityHashMap + temporaryArgumentCells = new IdentityHashMap<>(); + private final java.util.ArrayList temporaryCodeArgumentOwners = + new java.util.ArrayList<>(); + private final java.util.ArrayList argumentAliasOwners = + new java.util.ArrayList<>(); + private final java.util.ArrayList argumentContainerOwners = + new java.util.ArrayList<>(); private int size; private final ExecutionRuntimeState ownerState; - private final java.lang.ref.WeakReference registration; + private final int argumentDepth; + private RuntimeArray materializedArguments; private CallArguments(int capacity) { values = new RuntimeBase[Math.max(0, capacity)]; ownerState = PerlRuntime.current().executionState(); - registration = new java.lang.ref.WeakReference<>(this); - ownerState.callArgumentFrames.add(registration); + argumentDepth = ownerState.argsStack.size(); + ownerState.callArgumentFrames.add(this); } public void add(RuntimeBase value) { @@ -123,59 +168,123 @@ public void add(RuntimeBase value) { throw new IllegalStateException("too many call arguments"); } values[size++] = value; - // A list-valued call result can hold a fresh object returned by - // an inline constructor. The Java staging array keeps that list - // reachable, but it is not a Perl owner and cannot protect the - // returned object's weak observers when later arguments run. - // Give strong references in staged list results ordinary scalar - // owner slots until the enclosing call has consumed its arguments. - if (size < values.length && value instanceof RuntimeList) { + retainArgumentContainerOwners(value, argumentContainerOwners); + // The staging frame retains this scalar cell through argument + // evaluation and the call. Record that cell alias even when it has + // no lexical or container marker yet; the alias does not add a + // referent count. A mortal return keeps its exact RETURN_VALUE + // release queued until this alias frame leaves. + if (value instanceof RuntimeScalar scalar) { + if (!hasPersistentArgumentCell(scalar)) { + temporaryArgumentCells.computeIfAbsent( + scalar, TemporaryArgumentCell::new); + } + // A temporary CODE value can own compiled pad constants or + // closure captures without belonging to a lexical or aggregate. + // A captured CV needs an independent call-frame owner because + // weakening a local copy can retire the scalar cell's own edge. + // Empty capture arrays continue to use the ordinary @_ owner. + if (!WeakRefRegistry.isweak(scalar) + && scalar.type == RuntimeScalarType.CODE + && scalar.value instanceof RuntimeCode code + && argumentAliasContainer(scalar) == null + && (hasNoCaptureMetadata(code) || hasCapturedPadValues(code)) + && !code.hasIndependentPerlOwnerSlotForArgument()) { + PerlOwnerSlot owner = new PerlOwnerSlot(PerlOwnerSlot.Kind.ARGUMENT_VALUE); + owner.acquireCountedIdentity(code); + temporaryCodeArgumentOwners.add(owner); + } + boolean pendingStrongRelease = !WeakRefRegistry.isweak(scalar) + && ((scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 + || scalar.type == RuntimeScalarType.GLOB + || scalar.type == RuntimeScalarType.CODE) + && scalar.value instanceof RuntimeBase referent + && MortalList.hasPendingStrongReleaseFor(referent); + if (hasPersistentArgumentCell(scalar) + || hasCurrentCountedCellOwner(scalar) + || pendingStrongRelease) { + argumentAliasOwners.add(scalar.retainArgumentAliasOwner()); + } + if (needsStagedArgumentValueOwner(scalar)) { + listResultOwners.add(RuntimeScalar.retainStagedArgumentValue(scalar)); + } + } else if (value instanceof RuntimeList) { retainListResultOwners(value); } } - private void retainListResultOwners(RuntimeBase value) { - if (value instanceof RuntimeList list) { - for (RuntimeBase element : list.elements) { - retainListResultOwners(element); - } - } else if (value instanceof RuntimeScalar scalar - && scalar.value instanceof RuntimeBase base - && base.blessId != 0 - && WeakRefRegistry.hasWeakRefsTo(base) - && !WeakRefRegistry.isweak(scalar)) { - RuntimeScalar owner = new RuntimeScalar(); - owner.set(scalar); - listResultOwners.add(owner); - } + private static boolean hasNoCaptureMetadata(RuntimeCode code) { + return code.capturedScalars == null && code.capturedAggregates == null; + } + + private static boolean hasCapturedPadValues(RuntimeCode code) { + return (code.capturedScalars != null && code.capturedScalars.length > 0) + || (code.capturedAggregates != null && code.capturedAggregates.length > 0); } - private boolean containsReferent(RuntimeBase referent) { - for (int i = 0; i < size; i++) { - RuntimeBase value = values[i]; - if (argumentValueOwnsReferent(value, referent)) return true; + private boolean needsStagedArgumentValueOwner(RuntimeScalar scalar) { + if (scalar == null || WeakRefRegistry.isweak(scalar) + || (scalar.type & RuntimeScalarType.REFERENCE_BIT) == 0 + || !(scalar.value instanceof RuntimeBase referent)) { + return false; + } + if (scalar.isMortalReturnSnapshot()) { + // A return snapshot backed by a durable storage edge only + // aliases its source cell. If it is the sole counted edge, + // the call frame must acquire its own value owner before + // later argument cleanup can consume the pending return + // release. + return !referent.hasIndependentPerlOwnerSlotForArgument(); + } + // Anonymous aggregate literals passed directly to a call have no + // source cell whose lifetime covers @_. The argument alias is a + // borrow, so retain an otherwise ownerless literal for the + // argument frame. Stored references and other temporary values + // retain their own rules. + if (hasPersistentArgumentCell(scalar) + || hasCurrentCountedCellOwner(scalar)) return false; + if (scalar.type == RuntimeScalarType.HASHREFERENCE + && referent instanceof RuntimeHash hash) { + return hash.refCount == 0 && !hash.hasCurrentPerlStorageOwner(); + } + if (scalar.type == RuntimeScalarType.ARRAYREFERENCE + && referent instanceof RuntimeArray array) { + return array.refCount == 0 && !array.hasCurrentPerlStorageOwner(); } return false; } - private boolean argumentValueOwnsReferent(RuntimeBase value, RuntimeBase referent) { - if (value instanceof RuntimeScalar scalar) { - return scalar.value == referent && !WeakRefRegistry.isweak(scalar); - } + private void retainListResultOwners(RuntimeBase value) { if (value instanceof RuntimeList list) { for (RuntimeBase element : list.elements) { - if (argumentValueOwnsReferent(element, referent)) return true; + retainListResultOwners(element); } } else if (value instanceof RuntimeArray array) { for (RuntimeScalar element : array.elements) { - if (argumentValueOwnsReferent(element, referent)) return true; + retainListResultOwners(element); } } else if (value instanceof RuntimeHash hash) { for (RuntimeScalar element : hash.elements.values()) { - if (argumentValueOwnsReferent(element, referent)) return true; + retainListResultOwners(element); + } + } else if (value instanceof RuntimeScalar scalar + && scalar.value instanceof RuntimeBase + && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 + && !WeakRefRegistry.isweak(scalar)) { + if (scalar.isMortalReturnSnapshot()) { + if (needsStagedArgumentValueOwner(scalar)) { + listResultOwners.add( + RuntimeScalar.retainStagedArgumentValue(scalar)); + } else { + // A separate durable counted owner already protects + // this referent, so retain only the aliased scalar cell. + argumentAliasOwners.add(scalar.retainArgumentAliasOwner()); + } + } else { + RuntimeScalar owner = RuntimeScalar.retainStagedArgumentValue(scalar); + listResultOwners.add(owner); } } - return false; } private RuntimeBase[] argumentValues() { @@ -183,7 +292,9 @@ private RuntimeBase[] argumentValues() { } public RuntimeArray toRuntimeArray() { + if (materializedArguments != null) return materializedArguments; RuntimeArray args = new RuntimeArray(size); + materializedArguments = args; for (RuntimeBase value : argumentValues()) { value.setArrayOfAlias(args); } @@ -191,34 +302,326 @@ public RuntimeArray toRuntimeArray() { } public void finish() { - ownerState.callArgumentFrames.remove(registration); - for (RuntimeScalar owner : listResultOwners) { - owner.set((RuntimeScalar) null); + ownerState.callArgumentFrames.remove(this); + Throwable failure = null; + Set cleanedArgumentCells = + Collections.newSetFromMap(new IdentityHashMap<>()); + if (materializedArguments != null) { + RuntimeArray arguments = materializedArguments; + materializedArguments = null; + if (arguments.ownedAliasElements != null) { + for (RuntimeScalar scalar : arguments.ownedAliasElements + .toArray(new RuntimeScalar[0])) { + PerlOwnerSlot owner = scalar.countedOwnerSlot(); + if (owner != null && owner.isActive() + && owner.kind() == PerlOwnerSlot.Kind.ARGUMENT_VALUE) { + failure = attemptCleanup( + failure, () -> RuntimeScalar.scopeExitCleanup(scalar)); + cleanedArgumentCells.add(scalar); + } + failure = attemptCleanup( + failure, () -> arguments.forgetOwnedAliasElement(scalar)); + } + } + } + TemporaryArgumentCell[] temporaryCells = + temporaryArgumentCells.values().toArray(new TemporaryArgumentCell[0]); + temporaryArgumentCells.clear(); + for (TemporaryArgumentCell temporaryCell : temporaryCells) { + RuntimeScalar scalar = temporaryCell.scalar; + if (!cleanedArgumentCells.contains(scalar) && temporaryCell.wasChanged()) { + failure = attemptCleanup( + failure, () -> RuntimeScalar.scopeExitCleanup(scalar)); + } + } + failure = releaseStagedArgumentOwners(listResultOwners, failure); + failure = releaseArgumentAliasOwners(argumentAliasOwners, failure); + failure = releaseArgumentContainerOwners(argumentContainerOwners, failure); + failure = releaseOwnerSlots(temporaryCodeArgumentOwners, failure); + failure = attemptCleanup(failure, MortalList::drainDeferredArgumentOwnerReleases); + rethrowCleanupFailure(failure); + } + + private List transferArgumentContainerOwners( + RuntimeArray arguments) { + if (materializedArguments != arguments) return null; + ArrayList transferred = new ArrayList<>(argumentContainerOwners); + argumentContainerOwners.clear(); + return transferred; + } + + /** Release a partially evaluated call that will never enter its callee. */ + public Throwable abandon(Throwable failure) { + Throwable pendingFailure = attemptCleanup(failure, this::finish); + // A non-local return carries a result whose mortal owner must + // survive until the receiving call boundary consumes it. + if (!(failure instanceof PerlNonLocalReturnException)) { + pendingFailure = attemptCleanup(pendingFailure, MortalList::flushAboveMark); } - listResultOwners.clear(); - MortalList.drainDeferredArgumentOwnerReleases(); + return pendingFailure; } } - static boolean hasActiveArgumentOwner(RuntimeScalar scalar) { - if (scalar == null || !(scalar.value instanceof RuntimeBase referent)) return false; - ExecutionRuntimeState state = PerlRuntime.current().executionState(); - for (RuntimeArray args : state.argsStack) { - for (RuntimeScalar element : args.elements) { - if (element != null && element.value == referent - && !WeakRefRegistry.isweak(element)) return true; - } - } - for (int i = state.callArgumentFrames.size() - 1; i >= 0; i--) { - java.lang.ref.WeakReference reference = state.callArgumentFrames.get(i); - CallArguments frame = reference.get(); - if (frame == null) { - state.callArgumentFrames.remove(i); - } else if (frame.containsReferent(referent)) { - return true; + /** One counted edge from an active argument alias to its containing aggregate. */ + static final class ArgumentContainerOwner { + private final RuntimeBase container; + private final RuntimeScalar ownerValue; + // A proxy may carry tie magic independently of the aggregate itself. + // Keep the proxy view and its handler owner until this argument frame + // exits, even if untie replaces the aggregate's current storage. + @SuppressWarnings("unused") + private final RuntimeBaseProxy magicProxy; + private final RuntimeScalar handlerOwner; + private boolean active = true; + + private ArgumentContainerOwner(RuntimeBase container, RuntimeScalar ownerValue, + RuntimeBaseProxy magicProxy, + RuntimeScalar handlerOwner) { + this.container = container; + this.ownerValue = ownerValue; + this.magicProxy = magicProxy; + this.handlerOwner = handlerOwner; + } + + void release() { + if (!active) return; + if (ownerValue.value != container) { + throw new IllegalStateException( + "argument-container owner changed its referent before release"); } + active = false; + Throwable failure = attemptCleanup(null, + () -> RuntimeScalar.releaseTiedHandlerValue(handlerOwner)); + failure = attemptCleanup(failure, + () -> RuntimeScalar.releaseArgumentContainerValue(ownerValue)); + failure = attemptCleanup(failure, + () -> refreshUntrackedCellsAfterContainerTransfer(container)); + rethrowCleanupFailure(failure); } - return false; + } + + /** + * Retire stale scalar-to-value edges after this transfer was the final + * Perl owner of an aggregate. The container's direct cells are the exact + * affected edges; no transitive runtime-root traversal is needed. + */ + static void refreshUntrackedCellsAfterContainerTransfer(RuntimeBase container) { + if (container == null || container.hasCurrentPerlStorageOwner() + || container.hasTemporaryRootOwnerSlotIdentity()) return; + if (container instanceof RuntimeArray array) { + array.refreshUntrackedElementOwnersAfterTransfer(); + } else if (container instanceof RuntimeHash hash) { + hash.refreshUntrackedElementOwnersAfterTransfer(); + } + } + + /** Active {@code @_} value owners held while a {@code goto &sub} changes frames. */ + static final class TailCallArgumentOwners { + private RuntimeArray sourceArguments; + private final java.util.ArrayList owners; + private RuntimeArray ownedArgs; + + private TailCallArgumentOwners(RuntimeArray sourceArguments, + java.util.List owners) { + this.sourceArguments = sourceArguments; + this.owners = new java.util.ArrayList<>(owners); + } + + private boolean matches(RuntimeArray args) { + if (sourceArguments == args) return true; + for (RuntimeScalar scalar : args.elements) { + if (scalar != null && owners.stream().anyMatch(owner -> owner.matches(scalar))) { + return true; + } + } + return owners.isEmpty(); + } + + private List takeMatching(RuntimeArray args) { + java.util.ArrayList adopted = new java.util.ArrayList<>(); + for (java.util.Iterator it = owners.iterator(); + it.hasNext();) { + RuntimeScalar.ArgumentAliasOwner owner = it.next(); + if (args.elements.stream().anyMatch(owner::matches)) { + adopted.add(owner); + it.remove(); + } + } + // The handoff has been matched against the replacement frame. Do + // not keep the abandoned source @_ array alive through the owner + // token after its scalar-cell aliases have moved. + sourceArguments = null; + return adopted; + } + + void releaseRemaining() { + Throwable failure = releaseArgumentAliasOwners(owners, null); + sourceArguments = null; + RuntimeArray pendingOwnedArgs = ownedArgs; + if (pendingOwnedArgs != null) { + try { + cleanupTailCallArgs(pendingOwnedArgs); + ownedArgs = null; + } catch (Throwable cleanupFailure) { + if (failure == null) failure = cleanupFailure; + else if (failure != cleanupFailure) failure.addSuppressed(cleanupFailure); + } + } + rethrowCleanupFailure(failure); + } + + private void attachOwnedArgs(RuntimeArray ownedArgs) { + if (ownedArgs == null) return; + if (this.ownedArgs != null) { + throw new IllegalStateException("tail-call argument owners already have owned args"); + } + this.ownedArgs = ownedArgs; + } + } + + /** Run every cleanup action while preserving the first failure as primary. */ + static Throwable attemptCleanup(Throwable pendingFailure, Runnable cleanup) { + try { + cleanup.run(); + } catch (Throwable cleanupFailure) { + if (pendingFailure == null) return cleanupFailure; + if (pendingFailure != cleanupFailure) pendingFailure.addSuppressed(cleanupFailure); + } + return pendingFailure; + } + + static void rethrowCleanupFailure(Throwable failure) { + if (failure == null) return; + if (failure instanceof RuntimeException runtimeException) throw runtimeException; + if (failure instanceof Error error) throw error; + throw new IllegalStateException("argument-owner cleanup failed", failure); + } + + private static Throwable releaseStagedArgumentOwners( + List owners, Throwable failure) { + RuntimeScalar[] pendingOwners = owners.toArray(new RuntimeScalar[0]); + owners.clear(); + for (RuntimeScalar owner : pendingOwners) { + failure = attemptCleanup( + failure, () -> RuntimeScalar.releaseStagedArgumentValue(owner)); + } + return failure; + } + + private static Throwable releaseArgumentAliasOwners( + List owners, Throwable failure) { + RuntimeScalar.ArgumentAliasOwner[] pendingOwners = + owners.toArray(new RuntimeScalar.ArgumentAliasOwner[0]); + owners.clear(); + for (RuntimeScalar.ArgumentAliasOwner owner : pendingOwners) { + failure = attemptCleanup(failure, owner::release); + } + return failure; + } + + private static Throwable releaseArgumentContainerOwners( + List owners, Throwable failure) { + ArgumentContainerOwner[] pendingOwners = + owners.toArray(new ArgumentContainerOwner[0]); + owners.clear(); + for (ArgumentContainerOwner owner : pendingOwners) { + failure = attemptCleanup(failure, owner::release); + } + return failure; + } + + private static Throwable releaseOwnerSlots(List owners, Throwable failure) { + PerlOwnerSlot[] pendingOwners = owners.toArray(new PerlOwnerSlot[0]); + owners.clear(); + for (PerlOwnerSlot owner : pendingOwners) { + failure = attemptCleanup(failure, owner::release); + } + return failure; + } + + private static RuntimeBase argumentAliasContainer(RuntimeBase value) { + RuntimeBaseProxy proxy = argumentAliasMagicProxy(value); + if (proxy != null) { + RuntimeBase container = proxy.argumentAliasContainer(); + return container instanceof RuntimeArray || container instanceof RuntimeHash + ? container : null; + } + if (value instanceof RuntimeScalar scalar) { + RuntimeBase container = scalar.getContainerOwner(); + return container instanceof RuntimeArray || container instanceof RuntimeHash + ? container : null; + } + return null; + } + + private static ArgumentContainerOwner retainArgumentContainerOwner(RuntimeBase value) { + RuntimeBase container = argumentAliasContainer(value); + if (container == null) return null; + RuntimeScalar ownerValue = RuntimeScalar.retainArgumentContainerValue(container); + if (ownerValue == null) return null; + RuntimeBaseProxy magicProxy = argumentAliasMagicProxy(value); + RuntimeScalar handlerOwner = null; + try { + handlerOwner = magicProxy == null ? null + : magicProxy.retainArgumentAliasHandlerOwner(); + return new ArgumentContainerOwner(container, ownerValue, magicProxy, handlerOwner); + } catch (Throwable acquisitionFailure) { + RuntimeScalar handlerOwnerToRelease = handlerOwner; + Throwable failure = attemptCleanup(acquisitionFailure, + () -> RuntimeScalar.releaseTiedHandlerValue(handlerOwnerToRelease)); + failure = attemptCleanup(failure, + () -> RuntimeScalar.releaseArgumentContainerValue(ownerValue)); + rethrowCleanupFailure(failure); + return null; + } + } + + private static RuntimeBaseProxy argumentAliasMagicProxy(RuntimeBase value) { + if (value instanceof RuntimeBaseProxy proxy) return proxy; + if (value instanceof RuntimeScalar scalar + && scalar.type == RuntimeScalarType.TIED_SCALAR + && scalar.value instanceof RuntimeBaseProxy proxy) { + return proxy; + } + return null; + } + + private static void retainArgumentContainerOwners( + RuntimeBase value, List owners) { + if (value instanceof RuntimeScalar) { + ArgumentContainerOwner owner = retainArgumentContainerOwner(value); + if (owner != null) owners.add(owner); + } else if (value instanceof RuntimeList list) { + for (RuntimeBase element : list.elements) { + if (element != null) retainArgumentContainerOwners(element, owners); + } + } else if (value instanceof RuntimeArray array) { + for (RuntimeScalar element : array.elements) { + if (element != null) { + retainArgumentContainerOwners(element, owners); + } else { + RuntimeScalar ownerValue = RuntimeScalar.retainArgumentContainerValue(array); + if (ownerValue != null) { + owners.add(new ArgumentContainerOwner(array, ownerValue, null, null)); + } + } + } + } + } + + static boolean hasPersistentArgumentCell(RuntimeScalar scalar) { + return scalar.hasPersistentArgumentStorageCell() || isCurrentArgumentAlias(scalar); + } + + /** A staging frame may borrow a counted cell before its storage is registered. */ + private static boolean hasCurrentCountedCellOwner(RuntimeScalar scalar) { + if (scalar == null || !scalar.refCountOwned || WeakRefRegistry.isweak(scalar) + || !(scalar.value instanceof RuntimeBase referent)) { + return false; + } + PerlOwnerSlot owner = scalar.countedOwnerSlot(); + return owner != null && PerlOwnerSlot.isCountedKind(owner.kind()) + && owner.isActive() && owner.referent() == referent; } public static CallArguments newCallArguments(int capacity) { @@ -565,11 +968,8 @@ private static void popJvmClosureFrame(JvmClosureFrame frame) { if (frame.created != null) { for (RuntimeCode closure : frame.created) { if ((closure.capturedScalars != null || closure.capturedAggregates != null) - && closure.refCount == 0 - && closure.stashRefCount <= 0 - && !closure.localBindingExists && (frame.returned == null || !frame.returned.containsKey(closure))) { - closure.releaseCaptures(); + closure.requestCaptureReleaseWhenUnowned(); } } } @@ -1151,6 +1551,17 @@ private static Deque argsStack() { * Java thread. Weak CODE backrefs, especially Sub::Defer's self slot, must * not be cleared while the referent CODE is still running. */ + /** An executing frame retains each of its explicit scalar capture slots. */ + static boolean activeCodeOwnsCapture(RuntimeScalar scalar) { + for (RuntimeCode code : activeCodeStack()) { + if (code.capturedScalarOwnerSlots == null) continue; + for (PerlOwnerSlot slot : code.capturedScalarOwnerSlots) { + if (slot != null && slot.isActive() && slot.referent() == scalar) return true; + } + } + return false; + } + private static Deque activeCodeStack() { return PerlRuntime.current().executionState().activeCodeStack; } @@ -1160,16 +1571,16 @@ private static Deque activeCodeStack(ExecutionRuntimeState executio } private static final class ActiveLexicalFrame { + private final PerlOwnerSlot codeOwner = new PerlOwnerSlot(PerlOwnerSlot.Kind.ACTIVE_CODE); private RuntimeCode code; private Map cells; + private Map lexicalOwnerSlots; private String previousCallerPackage; private String callSitePackage; private ActiveLexicalFrame(RuntimeCode code, String previousCallerPackage, String callSitePackage) { - this.code = code; - this.previousCallerPackage = previousCallerPackage; - this.callSitePackage = callSitePackage; + rebind(code, previousCallerPackage, callSitePackage); } private RuntimeCode code() { @@ -1181,6 +1592,7 @@ private void rebind(RuntimeCode code, String previousCallerPackage, this.code = code; this.previousCallerPackage = previousCallerPackage; this.callSitePackage = callSitePackage; + codeOwner.acquireActiveCodeIdentity(code); } private String previousCallerPackage() { @@ -1192,6 +1604,14 @@ private String callSitePackage() { } private void clearForReuse() { + codeOwner.release(); + if (lexicalOwnerSlots != null) { + for (PerlOwnerSlot ownerSlot : lexicalOwnerSlots.values()) { + if (ownerSlot != null) ownerSlot.release(); + } + lexicalOwnerSlots.clear(); + lexicalOwnerSlots = null; + } code = null; cells = null; previousCallerPackage = null; @@ -1204,12 +1624,73 @@ private Map cells() { private void put(String name, RuntimeBase cell) { if (cells == null) cells = new HashMap<>(); - cells.put(name, cell); + RuntimeBase previous = cells.put(name, cell); + if (previous == cell) { + retainLexicalOwner(name, cell); + return; + } + // Keep the slot identity stable across replacement. The slot + // acquires the new pad cell before its previous referent is + // released, so scope cleanup cannot observe an ownership gap. + retainLexicalOwner(name, cell); + } + + private void retainLexicalOwner(String name, RuntimeBase cell) { + boolean lexicalOwner = isActiveLexicalOwnerCell(cell) + && MyVarCleanupStack.isRegistered(cell); + PerlOwnerSlot existing = lexicalOwnerSlots == null + ? null : lexicalOwnerSlots.get(name); + if (!lexicalOwner) { + releaseLexicalOwner(name); + return; + } + if (existing != null) { + existing.acquireActiveLexicalIdentity(cell); + return; + } + if (lexicalOwnerSlots == null) lexicalOwnerSlots = new HashMap<>(); + PerlOwnerSlot ownerSlot = new PerlOwnerSlot(PerlOwnerSlot.Kind.ACTIVE_LEXICAL); + ownerSlot.acquireActiveLexicalIdentity(cell); + lexicalOwnerSlots.put(name, ownerSlot); } private void remove(String name) { if (cells != null) cells.remove(name); + releaseLexicalOwner(name); + } + + private void releaseLexicalOwner(String name) { + if (lexicalOwnerSlots == null) return; + PerlOwnerSlot ownerSlot = lexicalOwnerSlots.remove(name); + if (ownerSlot != null) ownerSlot.release(); + if (lexicalOwnerSlots.isEmpty()) lexicalOwnerSlots = null; + } + + private int removeLexicalCell(RuntimeBase cell) { + if (cells == null || lexicalOwnerSlots == null) return 0; + for (Map.Entry entry : new ArrayList<>(cells.entrySet())) { + if (entry.getValue() == cell + && lexicalOwnerSlots.containsKey(entry.getKey())) { + remove(entry.getKey()); + return 1; + } + } + return 0; } + + private int removeAllLexicalCells(RuntimeBase cell) { + if (cells == null) return 0; + int removed = 0; + for (Map.Entry entry + : new ArrayList<>(cells.entrySet())) { + if (entry.getValue() == cell) { + remove(entry.getKey()); + removed++; + } + } + return removed; + } + } @SuppressWarnings("unchecked") private static Deque activeLexicalFrames( @@ -1314,6 +1795,43 @@ public static java.util.List snapshotArgsStack() { return new java.util.ArrayList<>(argsStack()); } + /** + * Whether a hash-slot reference is also held by an active user call frame + * outside the B::SV::REFCNT probe that is asking about it. + */ + public static boolean hasUncountedActiveHashArgumentOwner(RuntimeBase referent) { + if (referent == null || PerlRuntime.currentOrNull() == null) return false; + int depth = 0; + for (RuntimeArray activeArgs : argsStack()) { + RuntimeCode activeCode = getActiveCodeAt(depth++); + if (activeCode == null || activeCode.packageName == null + || "B".equals(activeCode.packageName) + || activeCode.packageName.startsWith("B::") + || "Internals".equals(activeCode.packageName)) { + continue; + } + RuntimeCode innerCode = getActiveCodeAt(depth - 2); + if (innerCode != null && "B::SV".equals(innerCode.packageName) + && "REFCNT".equals(innerCode.subName)) { + // The helper's own @_ is the value being queried. It is not a + // second Perl owner; only an outer user frame can add one. + continue; + } + for (int index = 0; index < activeArgs.elements.size(); index++) { + RuntimeScalar argument = activeArgs.elements.get(index); + if (argument == null || argument.value != referent + || (argument.type & RuntimeScalarType.REFERENCE_BIT) == 0 + || WeakRefRegistry.isweak(argument) + || !(argument.getContainerOwner() instanceof RuntimeHash)) { + continue; + } + if (index == 0 && "DESTROY".equals(activeCode.subName)) continue; + return true; + } + } + return false; + } + /** Return the active call's live @_ array at the given stack depth. */ public static RuntimeArray getActiveArgsAt(int depth) { if (depth < 0) return null; @@ -1350,8 +1868,8 @@ public static RuntimeScalar currentClassName() { /** * Snapshot the original arguments of active calls before @_ mutations. * A method commonly shifts its invocant into a lexical; retaining these - * frame arguments keeps reachability sweeps from destroying that invocant - * while the method is still executing. + * frame arguments keeps the owner ledger aligned while the method is + * still executing. */ public static java.util.List> snapshotPristineArgsStack() { java.util.List> snapshot = new java.util.ArrayList<>(); @@ -1432,44 +1950,70 @@ public static String getActiveRegexPropertyCallerPackage() { } public static void popActiveCode(RuntimeCode code) { - popActiveCode(code, PerlRuntime.current().executionState()); + PerlRuntime runtime = PerlRuntime.current(); + popActiveCode(code, runtime.executionState(), runtime.lifecycleState); } private static void popActiveCode( - RuntimeCode code, ExecutionRuntimeState executionState) { + RuntimeCode code, ExecutionRuntimeState executionState, + LifecycleRuntimeState lifecycleState) { + Deque stack = activeCodeStack(executionState); Deque frames = activeLexicalFrames(executionState); + ActiveLexicalFrame retiredFrame = null; if (!frames.isEmpty() && frames.peek().code() == code) { - ActiveLexicalFrame frame = frames.pop(); + retiredFrame = frames.pop(); executionState.currentCallerPackage.setInternalPackageName( - frame.previousCallerPackage()); - recycleActiveLexicalFrame(frame, executionState); + retiredFrame.previousCallerPackage()); } else { var iterator = frames.iterator(); while (iterator.hasNext()) { ActiveLexicalFrame frame = iterator.next(); if (frame.code() == code) { iterator.remove(); - recycleActiveLexicalFrame(frame, executionState); + retiredFrame = frame; + break; } } } - Deque stack = activeCodeStack(executionState); + boolean removedStackEntry = false; if (!stack.isEmpty() && stack.peek() == code) { + RuntimeCode callerCode = null; + if (stack.size() > 1) { + Iterator callerIterator = stack.iterator(); + callerIterator.next(); + callerCode = callerIterator.next(); + } + MortalList.handoffTransientListAssignmentRhs( + lifecycleState, code, stack.size(), callerCode, stack.size() - 1); stack.pop(); if (!executionState.activeCodeCallSites.isEmpty()) { executionState.activeCodeCallSites.pop(); } - return; - } - int index = 0; - for (Iterator iterator = stack.iterator(); iterator.hasNext();) { - if (iterator.next() == code) { - iterator.remove(); - removeActiveCodeCallSiteAt(executionState, index); - break; + removedStackEntry = true; + } else { + int index = 0; + java.util.List stackSnapshot = new java.util.ArrayList<>(stack); + for (Iterator iterator = stack.iterator(); iterator.hasNext();) { + if (iterator.next() == code) { + int executionDepth = stack.size() - index; + RuntimeCode callerCode = index + 1 < stackSnapshot.size() + ? stackSnapshot.get(index + 1) : null; + MortalList.handoffTransientListAssignmentRhs( + lifecycleState, code, executionDepth, callerCode, + executionDepth - 1); + iterator.remove(); + removeActiveCodeCallSiteAt(executionState, index); + removedStackEntry = true; + break; + } + index++; } - index++; } + // Remove the stack entry while its ACTIVE_CODE slot still owns the CV. + // Releasing the slot then becomes the final, authoritative lifecycle + // boundary instead of relying on a second stack-membership check. + if (removedStackEntry) code.finishActiveCodeOwnerRelease(); + if (retiredFrame != null) recycleActiveLexicalFrame(retiredFrame, executionState); } private static void removeActiveCodeCallSiteAt( @@ -1501,6 +2045,203 @@ public static boolean isActiveCode(RuntimeCode code) { return false; } + private boolean finalReleaseDeferredToActiveCode; + /** A temporary closure cleanup requested capture retirement at its last owner boundary. */ + private boolean captureReleaseRequested; + + boolean hasActiveCodeOwner() { + return ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_CODE) != 0; + } + + /** Whether a current named package CODE slot still installs this CV. */ + public boolean hasStashCodeSlotOwner() { + if (ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT) == 0) return false; + for (PerlOwnerSlot slot : codeSlotOwnerSlotsView()) { + LifecycleHotPathDiagnostics.ownerSlotsVisited(1); + if (!slot.isActive() || slot.kind() != PerlOwnerSlot.Kind.CODE_SLOT + || slot.referent() != this) continue; + RuntimeScalar scalar = slot.countedScalarOwner(); + if (scalar != null && scalar.value == this && scalar.hasStashCodeSlotBinding()) { + return true; + } + } + return false; + } + + /** + * Whether this CODE object still has a Perl owner that can use its pad. + * Closure-capture cleanup uses this ledger instead of proving liveness by + * walking the Java object graph. + */ + boolean hasPerlOwnerForCapture() { + return refCount > 0 + || hasActiveCodeOwner() + || hasCallTransferOwner() + || hasOwnerSlots() + || isConstantCv + || constantValue != null; + } + + /** Release an untracked CV's pad tree when its last Perl owner leaves. */ + void releasePadConstantsForUntrackedOwnerSlot() { + // The compatibility count can outlive the scalar slot that contributed + // it. Once a slot release reaches this point, capture liveness comes + // from the remaining owner identities and non-scalar CODE roots. + if (PerlRuntime.currentOrNull() == null + || hasPerlOwnerForCaptureOtherThan(null) + || (padConstantOwnerSlots.isEmpty() + && codeTemplateOwnerSlots.isEmpty())) { + return; + } + clearPadConstantWeakRefs(); + } + + /** Whether a Perl owner other than one scalar slot still needs this CV's captures. */ + public boolean hasPerlOwnerForCaptureOtherThan(PerlOwnerSlot excludedOwner) { + // Do not use refCount here: this release path handles CODE objects + // whose compatibility count can remain positive after their last + // real scalar owner has gone away. + return hasStashCodeSlotOwner() + || hasActiveCodeOwner() + || hasCallTransferOwner() + || hasCurrentPerlOwnerSlotsOtherThan(excludedOwner) + || (PerlRuntime.currentOrNull() != null && SpecialBlock.hasPendingEndBlock(this)) + || isConstantCv + || constantValue != null; + } + + private boolean hasCurrentPerlOwnerSlotsOtherThan(PerlOwnerSlot excludedOwner) { + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (slot == excludedOwner || !slot.isActive()) continue; + if (slot.kind() == PerlOwnerSlot.Kind.UNTRACKED_REFERENCE) { + RuntimeScalar owner = slot.untrackedScalarOwner(); + // A live argument or return transfer is still a Perl owner + // of this CV. Its exact owner slot is released at the transfer + // boundary, so it can safely keep the pad and direct-call + // targets alive until then. + if (owner != null && owner.hasLiveCurrentStrongValueSlot() + && !WeakRefRegistry.isweak(owner) + && (owner.type & RuntimeScalarType.REFERENCE_BIT) != 0 + && owner.value == this) return true; + } else if (slot.kind() == PerlOwnerSlot.Kind.SCALAR_CELL) { + RuntimeScalar owner = slot.countedScalarOwner(); + if (owner != null + && (owner.isCurrentCountedScalarOwner(this, slot) + || owner.isUnregisteredCountedScalarCellOwner(this, slot))) { + return true; + } + } else if (DestroyDispatch.isCurrentPerlOwnerSlot(this, slot)) { + return true; + } + } + return false; + } + + /** A removed stash slot requests final state cleanup at the last owner boundary. */ + void noteStashOwnerReleased() { + if (perlLifecycleState() == RuntimeBase.PerlLifecycleState.DESTROYED + || ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT) != 0) return; + deferFinalReleaseToActiveCode(); + finishActiveCodeOwnerRelease(); + } + + /** + * Retire frame-temporary scalar cells that are the only direct holders of + * this generated CV. The owner-slot back-reference is weak so ownership + * metadata does not extend the scalar's lifetime. + */ + public boolean releaseTemporaryCodeScalarOwners() { + if (hasActiveCodeOwner()) return false; + boolean released = false; + for (PerlOwnerSlot ownerSlot : ownerSlotSnapshot()) { + if (!ownerSlot.isActive() + || ownerSlot.kind() != PerlOwnerSlot.Kind.SCALAR_CELL + || ownerSlot.referent() != this) continue; + RuntimeScalar owner = ownerSlot.countedScalarOwner(); + RuntimeArray ownedArgumentArray = owner != null + && owner.containerOwner instanceof RuntimeArray array + && array.elementsAliased && array.ownsElement(owner) + ? array : null; + RuntimeArray borrowedArgumentArray = owner != null + && owner.containerOwner instanceof RuntimeArray array + && array.elementsAliased && !array.ownsElement(owner) + && array.elements.contains(owner) + ? array : null; + if (owner == null || owner.countedOwnerSlot() != ownerSlot + || owner.type != RuntimeScalarType.CODE || owner.value != this + || !owner.refCountOwned || owner.scopeExited + || owner.hasCodeSlotBinding() + || (owner.containerOwner != null && ownedArgumentArray == null + && borrowedArgumentArray == null) + || owner.localBindingExists || owner.isPackageGlobalRoot + || MyVarCleanupStack.isRegistered(owner)) continue; + RuntimeScalar.scopeExitCleanup(owner); + if (ownedArgumentArray != null) ownedArgumentArray.forgetOwnedAliasElement(owner); + released = true; + } + return released; + } + + /** Rebind shared capture identities when this wrapper becomes the Perl CV. */ + void rebindCaptureOwnerSlots() { + if (capturedScalarOwnerSlots != null) { + for (PerlOwnerSlot ownerSlot : capturedScalarOwnerSlots) { + if (ownerSlot != null) ownerSlot.rebindCaptureOwner(this); + } + } + if (capturedAggregateOwnerSlots != null) { + for (PerlOwnerSlot ownerSlot : capturedAggregateOwnerSlots) { + if (ownerSlot != null) ownerSlot.rebindCaptureOwner(this); + } + } + rebindStateOwnerSlots(stateScalarOwnerSlots); + rebindStateOwnerSlots(stateArrayOwnerSlots); + rebindStateOwnerSlots(stateHashOwnerSlots); + rebindStateOwnerSlots(stateAggregateAliasOwnerSlots); + } + + private void rebindStateOwnerSlots(Map ownerSlots) { + for (PerlOwnerSlot ownerSlot : ownerSlots.values()) { + if (ownerSlot != null) ownerSlot.rebindCaptureOwner(this); + } + } + + void deferFinalReleaseToActiveCode() { + finalReleaseDeferredToActiveCode = true; + } + + void finishActiveCodeOwnerRelease() { + if (hasActiveCodeOwner()) return; + releasePendingCaptureEdges(); + finishRequestedCaptureRelease(); + if (!finalReleaseDeferredToActiveCode) return; + // CODE can reach refCount zero while a current Perl owner still + // protects it. Recheck at each exact owner-release boundary; otherwise + // closure captures could outlive their final owner. + if (hasPerlOwnerForCaptureOtherThan(null) || SpecialBlock.hasPendingEndBlock(this)) return; + finalReleaseDeferredToActiveCode = false; + DestroyDispatch.callDestroyFromCountedOwner(this); + } + + /** Request capture retirement for a temporary closure without consulting its count. */ + public void requestCaptureReleaseWhenUnowned() { + if (capturedScalars == null && capturedAggregates == null) return; + captureReleaseRequested = true; + finishRequestedCaptureRelease(); + } + + private void finishRequestedCaptureRelease() { + if (!captureReleaseRequested) return; + if (!captureReleaseRequested + || hasPerlOwnerForCaptureOtherThan(null) + || SpecialBlock.hasPendingEndBlock(this) + || hasPendingOwnerRelease()) { + return; + } + captureReleaseRequested = false; + releaseCaptures(); + } + public static RuntimeCode getActiveCodeAt(int depth) { if (depth < 0) return null; int i = 0; @@ -1512,6 +2253,20 @@ public static RuntimeCode getActiveCodeAt(int depth) { return null; } + /** Number of Perl code frames currently executing on this thread. */ + static int currentExecutionDepth() { + return activeCodeStack().size(); + } + + /** Whether the active Perl frame is the file-level main block. */ + static boolean isCurrentExecutionTopLevel() { + RuntimeCode active = getActiveCodeAt(0); + return active == null || (activeCodeStack().size() <= 1 + && "main".equals(active.packageName) + && (active.subName == null || active.subName.isBlank() + || "".equals(active.subName))); + } + /** True when the current Perl call chain is executing a sort BLOCK comparator. */ public static boolean hasActiveSortComparator() { for (RuntimeCode active : activeCodeStack()) { @@ -1581,9 +2336,17 @@ public static void pushJvmFrame(RuntimeScalar selfReference, boolean comparator) pushJvmFrame(PerlRuntime.current().executionState(), selfReference, comparator); } + /** Runtime state that must be restored when one generated method frame exits. */ + public record JvmFrameSnapshot(int selfDepth, int sortComparatorDepth, + boolean flushSuppressed) {} + /** Push generated-frame metadata through the state captured by its caller. */ public static void pushJvmFrame( ExecutionRuntimeState state, RuntimeScalar selfReference, boolean comparator) { + state.activeJvmFrameSnapshots.push(new JvmFrameSnapshot( + state.activeJvmSelfReferences.size(), + state.activeJvmSortComparators.size(), + MortalList.isFlushSuppressed())); if (selfReference != null) { state.activeJvmSelfReferences.push(selfReference); } @@ -1609,6 +2372,18 @@ public static void popJvmFrame(RuntimeScalar selfReference) { /** Pop generated-frame metadata through the state captured by its caller. */ public static void popJvmFrame( ExecutionRuntimeState state, RuntimeScalar selfReference) { + JvmFrameSnapshot snapshot = state.activeJvmFrameSnapshots.pollFirst(); + if (snapshot != null) { + restoreJvmFrameMetadata(state, snapshot, false); + // A return can bypass a Java finally block that entered a local + // suppression scope. Clear that leaked scope when the caller was + // not already suppressing; never reassert a stale true snapshot, + // since a finally block may already have restored it. + if (!snapshot.flushSuppressed() && MortalList.isFlushSuppressed()) { + MortalList.suppressFlush(false); + } + return; + } if (selfReference != null) { Deque stack = state.activeJvmSelfReferences; if (!stack.isEmpty() && stack.peek() == selfReference) { @@ -1621,6 +2396,38 @@ public static void popJvmFrame( if (!comparatorStack.isEmpty()) comparatorStack.pop(); } + /** Number of live generated frames at a Perl exception boundary. */ + public static int jvmFrameDepth(ExecutionRuntimeState state) { + return state.activeJvmFrameSnapshots.size(); + } + + /** Remove generated frames that escaped through a Perl eval/try catch. */ + public static void unwindJvmFramesToDepth(ExecutionRuntimeState state, int depth) { + while (state.activeJvmFrameSnapshots.size() > depth) { + JvmFrameSnapshot snapshot = state.activeJvmFrameSnapshots.pollFirst(); + restoreJvmFrameSnapshot(state, snapshot); + } + } + + private static void restoreJvmFrameSnapshot( + ExecutionRuntimeState state, JvmFrameSnapshot snapshot) { + restoreJvmFrameMetadata(state, snapshot, true); + } + + private static void restoreJvmFrameMetadata( + ExecutionRuntimeState state, JvmFrameSnapshot snapshot, + boolean restoreFlushSuppression) { + while (state.activeJvmSelfReferences.size() > snapshot.selfDepth()) { + state.activeJvmSelfReferences.pop(); + } + while (state.activeJvmSortComparators.size() > snapshot.sortComparatorDepth()) { + state.activeJvmSortComparators.pop(); + } + if (restoreFlushSuppression) { + MortalList.suppressFlush(snapshot.flushSuppressed()); + } + } + /** Track whether a JVM-generated frame is a sort BLOCK pseudo-block. */ public static void pushJvmSortComparator(boolean comparator) { PerlRuntime.current().executionState().activeJvmSortComparators.push(comparator); @@ -1639,7 +2446,9 @@ public static RuntimeScalar getJvmSelfReference() { /** True when an interpreter-owned Future::AsyncAwait frame is active. */ public static boolean hasActiveFutureAsyncAwaitSub() { - for (RuntimeCode active : activeCodeStack()) { + PerlRuntime runtime = PerlRuntime.currentOrNull(); + if (runtime == null) return false; + for (RuntimeCode active : runtime.executionState().activeCodeStack) { if (active instanceof InterpretedCode interpreted && interpreted.futureAsyncAwaitSub) { return true; @@ -1774,6 +2583,36 @@ public static boolean isActiveLexicalCell(RuntimeBase cell) { return false; } + /** Whether an active lexical cell belongs to a caller of {@code currentCode}. */ + public static boolean isActiveLexicalCellInCallerFrame( + RuntimeBase cell, RuntimeCode currentCode) { + if (cell == null) return false; + PerlRuntime runtime = PerlRuntime.current(); + boolean skippedCurrentFrame = false; + for (ActiveLexicalFrame frame : activeLexicalFrames(runtime.executionState())) { + if (!skippedCurrentFrame && sameLogicalCode(frame.code(), currentCode)) { + skippedCurrentFrame = true; + continue; + } + boolean containsCell = false; + for (RuntimeBase activeCell : frame.cells().values()) { + if (activeCell == cell) { + containsCell = true; + break; + } + } + if (containsCell) return true; + } + if (runtime.executionState().topLevelLexicals.containsValue(cell)) { + boolean currentIsTopLevel = currentCode != null + && "main".equals(currentCode.packageName) + && (currentCode.subName == null || currentCode.subName.isBlank() + || "".equals(currentCode.subName)); + return !currentIsTopLevel; + } + return false; + } + /** Bind a format's captured lexical to the currently executing pad frame. */ public static void registerCurrentActiveLexical(String variableName, RuntimeBase cell) { ExecutionRuntimeState state = PerlRuntime.current().executionState(); @@ -1781,10 +2620,113 @@ public static void registerCurrentActiveLexical(String variableName, RuntimeBase if (!frames.isEmpty() && variableName != null && cell != null) { frames.peek().put(variableName, cell); } else if (variableName != null && cell != null) { - state.topLevelLexicals.put(variableName, cell); + putTopLevelLexical(state, variableName, cell); } } + /** Backfill lexical owner identities when registration follows the first pad bind. */ + static void noteMyVarRegistered(RuntimeBase cell) { + if (!(cell instanceof RuntimeArray || cell instanceof RuntimeHash + || cell instanceof RuntimeScalar scalar && scalar.referencedByScalarReference) + || PerlRuntime.currentOrNull() == null) return; + ExecutionRuntimeState state = PerlRuntime.current().executionState(); + for (ActiveLexicalFrame frame : activeLexicalFrames(state)) { + for (Map.Entry entry : frame.cells().entrySet()) { + if (entry.getValue() == cell) { + frame.retainLexicalOwner(entry.getKey(), cell); + } + } + } + for (Map.Entry entry : state.topLevelLexicals.entrySet()) { + if (entry.getValue() == cell) { + retainTopLevelLexicalOwner(state, entry.getKey(), cell); + } + } + } + + private static void putTopLevelLexical( + ExecutionRuntimeState state, String variableName, RuntimeBase cell) { + RuntimeBase previous = state.topLevelLexicals.put(variableName, cell); + if (previous == cell) { + retainTopLevelLexicalOwner(state, variableName, cell); + return; + } + retainTopLevelLexicalOwner(state, variableName, cell); + } + + private static void retainTopLevelLexicalOwner( + ExecutionRuntimeState state, String variableName, RuntimeBase cell) { + boolean lexicalOwner = isActiveLexicalOwnerCell(cell) + && MyVarCleanupStack.isRegistered(cell); + PerlOwnerSlot ownerSlot = state.topLevelLexicalOwnerSlots.get(variableName); + if (!lexicalOwner) { + if (ownerSlot != null) { + state.topLevelLexicalOwnerSlots.remove(variableName, ownerSlot); + ownerSlot.release(); + } + return; + } + if (ownerSlot != null) { + ownerSlot.acquireActiveLexicalIdentity(cell); + return; + } + ownerSlot = new PerlOwnerSlot(PerlOwnerSlot.Kind.ACTIVE_LEXICAL); + ownerSlot.acquireActiveLexicalIdentity(cell); + state.topLevelLexicalOwnerSlots.put(variableName, ownerSlot); + } + + private static boolean isActiveLexicalOwnerCell(RuntimeBase cell) { + return cell instanceof RuntimeArray || cell instanceof RuntimeHash + || cell instanceof RuntimeScalar scalar && scalar.referencedByScalarReference; + } + + /** Release pad-map owner identities when a lexical cell leaves scope. */ + static boolean releaseActiveLexicalOwner(RuntimeBase cell) { + if (!(cell instanceof RuntimeArray || cell instanceof RuntimeHash + || cell instanceof RuntimeScalar scalar && scalar.referencedByScalarReference) + || PerlRuntime.currentOrNull() == null) return false; + ExecutionRuntimeState state = PerlRuntime.current().executionState(); + Deque frames = activeLexicalFrames(state); + ActiveLexicalFrame currentFrame = frames.peek(); + if (currentFrame != null && currentFrame.removeLexicalCell(cell) != 0) { + return true; + } + for (Map.Entry entry + : new ArrayList<>(state.topLevelLexicals.entrySet())) { + if (entry.getValue() != cell) continue; + state.topLevelLexicals.remove(entry.getKey()); + PerlOwnerSlot ownerSlot = state.topLevelLexicalOwnerSlots.remove(entry.getKey()); + if (ownerSlot != null) { + ownerSlot.release(); + return true; + } + return false; + } + return false; + } + + /** Release every pad name for a cell after its final lexical registration leaves. */ + static int releaseAllActiveLexicalOwners(RuntimeBase cell) { + if (!(cell instanceof RuntimeArray || cell instanceof RuntimeHash + || cell instanceof RuntimeScalar scalar && scalar.referencedByScalarReference) + || PerlRuntime.currentOrNull() == null) return 0; + ExecutionRuntimeState state = PerlRuntime.current().executionState(); + int removed = 0; + for (ActiveLexicalFrame frame : activeLexicalFrames(state)) { + removed += frame.removeAllLexicalCells(cell); + } + for (Map.Entry entry + : new ArrayList<>(state.topLevelLexicals.entrySet())) { + if (entry.getValue() != cell) continue; + state.topLevelLexicals.remove(entry.getKey()); + PerlOwnerSlot ownerSlot = state.topLevelLexicalOwnerSlots.remove(entry.getKey()); + if (ownerSlot != null) ownerSlot.release(); + removed++; + } + return removed; + } + + /** * Select eval STRING captures for Perl's package-DB rule. An eval run by * a DB subroutine is evaluated in the lexical pad of the code being @@ -1853,15 +2795,197 @@ private static void pushArgs(RuntimeArray args, boolean snapshotRequired) { private static void pushArgs( RuntimeArray args, boolean snapshotRequired, ExecutionRuntimeState executionState) { - executionState.argsStack.push(args); - // Snapshot the args list so @DB::args stays pristine even if the sub - // later shifts/pops from @_. - if (args == null || args.elements.isEmpty()) { - executionState.pristineArgsStack.push(EMPTY_ARGUMENT_SNAPSHOT); - } else if (snapshotRequired) { - executionState.pristineArgsStack.push(new java.util.ArrayList<>(args.elements)); - } else { - executionState.pristineArgsStack.push(args.elements); + Objects.requireNonNull(args, "args"); + TailCallArgumentOwners tailCallOwners = null; + List argumentOwners = new ArrayList<>(); + List containerOwners = new ArrayList<>(); + boolean argsPushed = false; + boolean aliasOwnersPushed = false; + boolean containerOwnersPushed = false; + boolean pristineArgsPushed = false; + if (!executionState.pendingTailCallArgumentOwners.isEmpty()) { + TailCallArgumentOwners pending = + executionState.pendingTailCallArgumentOwners.peek(); + if (pending.matches(args)) { + tailCallOwners = executionState.pendingTailCallArgumentOwners.pop(); + } + } + try { + if (tailCallOwners == null) { + retainArgumentAliasOwners(args, argumentOwners); + } else { + argumentOwners.addAll(tailCallOwners.takeMatching(args)); + retainMissingArgumentAliasOwners(args, argumentOwners); + } + List stagedContainerOwners = + takeStagedArgumentContainerOwners(args, executionState); + if (stagedContainerOwners != null) { + containerOwners = stagedContainerOwners; + } else { + retainArgumentContainerOwners(args, containerOwners); + } + // Snapshot the args list so @DB::args stays pristine even if the + // sub later shifts/pops from @_. + List pristineArguments = args.elements.isEmpty() + ? EMPTY_ARGUMENT_SNAPSHOT + : snapshotRequired + ? new java.util.ArrayList<>(args.elements) + : args.elements; + if (tailCallOwners != null) tailCallOwners.releaseRemaining(); + + executionState.argsStack.push(args); + argsPushed = true; + executionState.argumentAliasOwnerFrames.push(argumentOwners); + aliasOwnersPushed = true; + executionState.argumentContainerOwnerFrames.push(containerOwners); + containerOwnersPushed = true; + executionState.pristineArgsStack.push(pristineArguments); + pristineArgsPushed = true; + } catch (Throwable setupFailure) { + Throwable failure = setupFailure; + if (pristineArgsPushed) executionState.pristineArgsStack.pop(); + if (containerOwnersPushed) executionState.argumentContainerOwnerFrames.pop(); + if (aliasOwnersPushed) executionState.argumentAliasOwnerFrames.pop(); + if (argsPushed) executionState.argsStack.pop(); + failure = releaseArgumentAliasOwners(argumentOwners, failure); + failure = releaseArgumentContainerOwners(containerOwners, failure); + if (tailCallOwners != null) { + failure = attemptCleanup(failure, tailCallOwners::releaseRemaining); + } + rethrowCleanupFailure(failure); + } + } + + private static void retainArgumentAliasOwners( + RuntimeArray args, List owners) { + for (RuntimeScalar scalar : args.elements) { + if (scalar == null || !hasPersistentArgumentCell(scalar)) continue; + owners.add(scalar.retainArgumentAliasOwner()); + } + } + + private static boolean holdsStrongArgumentValue(RuntimeScalar scalar) { + return scalar != null + && (((scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0) + || scalar.type == RuntimeScalarType.GLOB + || scalar.type == RuntimeScalarType.CODE) + && scalar.value instanceof RuntimeBase + && !WeakRefRegistry.isweak(scalar); + } + + private static void retainMissingArgumentAliasOwners( + RuntimeArray args, List adopted) { + java.util.IdentityHashMap adoptedCounts = + new java.util.IdentityHashMap<>(); + for (RuntimeScalar.ArgumentAliasOwner owner : adopted) { + adoptedCounts.merge(owner.scalar(), 1, Integer::sum); + } + for (RuntimeScalar scalar : args.elements) { + if (scalar == null || (!hasPersistentArgumentCell(scalar) + && !holdsStrongArgumentValue(scalar))) continue; + int count = adoptedCounts.getOrDefault(scalar, 0); + if (count > 0) { + adoptedCounts.put(scalar, count - 1); + } else { + adopted.add(scalar.retainArgumentAliasOwner()); + } + } + } + + /** Detach current {@code @_} value owners before source-frame cleanup. */ + static TailCallArgumentOwners takeTailCallArgumentOwners(RuntimeArray args) { + if (args == null || PerlRuntime.currentOrNull() == null) { + return new TailCallArgumentOwners(args, List.of()); + } + ExecutionRuntimeState state = PerlRuntime.current().executionState(); + if (state.argsStack.isEmpty() || state.argumentAliasOwnerFrames.isEmpty()) { + return new TailCallArgumentOwners(args, List.of()); + } + ArrayList transferred = new ArrayList<>(); + List frame = state.argumentAliasOwnerFrames.peek(); + for (java.util.Iterator it = frame.iterator(); + it.hasNext();) { + RuntimeScalar.ArgumentAliasOwner owner = it.next(); + if (args.elements.stream().anyMatch(owner::matches)) { + transferred.add(owner); + it.remove(); + } + } + for (RuntimeScalar scalar : args.elements) { + if (scalar == null || !holdsStrongArgumentValue(scalar) + || transferred.stream().anyMatch(owner -> owner.matches(scalar))) continue; + // A transient reference argument may not have received an alias + // identity at ordinary call entry. Establish the handoff owner + // while the source @_ cell is still active so its mortal release + // cannot run before the replacement frame adopts the cell. + transferred.add(scalar.retainArgumentAliasOwner()); + } + return new TailCallArgumentOwners(args, transferred); + } + + private static void releaseExitedArgumentArrayContainerOwners( + RuntimeArray args, ExecutionRuntimeState executionState) { + if (args == null || args.threadShared + || executionState.argsStack.contains(args) + || args.hasPerlStrongOwner()) { + return; + } + Throwable failure = attemptCleanup(null, + () -> refreshUntrackedCellsAfterContainerTransfer(args)); + for (RuntimeScalar scalar : new ArrayList<>(args.elements)) { + if (scalar != null) { + failure = attemptCleanup(failure, () -> scalar.releaseContainerOwner(args)); + } + } + rethrowCleanupFailure(failure); + } + + private static List takeStagedArgumentContainerOwners( + RuntimeArray args, ExecutionRuntimeState executionState) { + for (int i = executionState.callArgumentFrames.size() - 1; i >= 0; i--) { + CallArguments frame = executionState.callArgumentFrames.get(i); + List owners = frame.transferArgumentContainerOwners(args); + if (owners != null) return owners; + } + return null; + } + + private static void retainArgumentContainerOwners( + RuntimeArray args, List owners) { + for (RuntimeScalar scalar : args.elements) { + if (scalar == null) continue; + ArgumentContainerOwner owner = retainArgumentContainerOwner(scalar); + if (owner != null) owners.add(owner); + } + } + + /** Retire the active {@code @_} alias identity for one removed argument slot. */ + static void argumentArraySlotRemoved(RuntimeArray args, RuntimeScalar scalar) { + if (args == null || scalar == null) return; + PerlRuntime runtime = PerlRuntime.currentOrNull(); + if (runtime == null) return; + ExecutionRuntimeState state = runtime.executionState(); + Iterator argumentFrames = state.argsStack.iterator(); + Iterator> ownerFrames = + state.argumentAliasOwnerFrames.iterator(); + while (argumentFrames.hasNext() && ownerFrames.hasNext()) { + RuntimeArray activeArgs = argumentFrames.next(); + List owners = ownerFrames.next(); + if (activeArgs != args) continue; + RuntimeScalar.ArgumentAliasOwner aliasOwnerToRelease = null; + for (Iterator iterator = owners.iterator(); + iterator.hasNext();) { + RuntimeScalar.ArgumentAliasOwner owner = iterator.next(); + if (owner.matches(scalar)) { + iterator.remove(); + aliasOwnerToRelease = owner; + break; + } + } + if (aliasOwnerToRelease != null) aliasOwnerToRelease.release(); + // Perl keeps the containing aggregate through the entire active + // argument frame, even after the alias is shifted out of @_ . + return; } } @@ -1902,9 +3026,19 @@ public static int resolveWantArrayContext(int context) { if (current != null && current.isMapGrepBlock) { return contexts.peek(); } - // A subroutine called from the block receives the block's ordinary - // expression context; map evaluates its block expression in list context. - return RuntimeContextType.LIST; + RuntimeCode caller = getActiveCodeAtCallerFrame(1); + if (caller != null && caller.isMapGrepBlock) { + // Map evaluates its block in list context, but an expression inside + // that block can still call a sub in scalar or void context. Keep + // the direct call's context when available; only use list context + // when the generated call frame reports void for the block result. + Integer directCallContext = getCallContextAtCallerFrame(0); + if (directCallContext == null || directCallContext == RuntimeContextType.VOID) { + return RuntimeContextType.LIST; + } + return directCallContext; + } + return context; } private static void pushCallContext( @@ -1931,28 +3065,53 @@ public static void popArgs() { private static void popArgs(ExecutionRuntimeState executionState) { Deque stack = executionState.argsStack; RuntimeArray exitedArgs = null; + Throwable failure = null; if (!stack.isEmpty()) { exitedArgs = stack.pop(); + if (!executionState.argumentAliasOwnerFrames.isEmpty()) { + failure = releaseArgumentAliasOwners( + executionState.argumentAliasOwnerFrames.pop(), failure); + } + if (!executionState.argumentContainerOwnerFrames.isEmpty()) { + failure = releaseArgumentContainerOwners( + executionState.argumentContainerOwnerFrames.pop(), failure); + } } + // A return inside an argument expression can bypass the invocation + // wrapper without throwing. Retire staging frames belonging to this + // callee, preserving frames created in its still-active callers. + if (!executionState.callArgumentFrames.isEmpty()) { + for (CallArguments frame : executionState.callArgumentFrames.toArray(new CallArguments[0])) { + if (frame.argumentDepth > stack.size()) { + failure = attemptCleanup(failure, frame::finish); + } + } + } + RuntimeArray argumentsToRelease = exitedArgs; Deque> pStack = executionState.pristineArgsStack; if (!pStack.isEmpty()) { - pStack.pop(); - } - MortalList.drainDeferredArgumentOwnerReleases(); - cleanupOwnedArgumentAliases(exitedArgs); - drainDeferredArgumentAggregateCleanup(executionState); + failure = attemptCleanup(failure, pStack::pop); + } + failure = attemptCleanup(failure, MortalList::drainDeferredArgumentOwnerReleases); + failure = attemptCleanup( + failure, () -> cleanupOwnedArgumentAliases(argumentsToRelease)); + failure = attemptCleanup(failure, + () -> releaseExitedArgumentArrayContainerOwners(argumentsToRelease, executionState)); + failure = attemptCleanup(failure, + () -> drainDeferredArgumentAggregateCleanup(executionState)); Deque haStack = executionState.hasArgsStack; if (!haStack.isEmpty()) { - haStack.pop(); + failure = attemptCleanup(failure, haStack::pop); } Deque ctxStack = executionState.callContextStack; if (!ctxStack.isEmpty()) { - ctxStack.pop(); + failure = attemptCleanup(failure, ctxStack::pop); } Deque pendingPackages = executionState.pendingCallerPackages; if (!pendingPackages.isEmpty()) { - pendingPackages.pop(); + failure = attemptCleanup(failure, pendingPackages::pop); } + rethrowCleanupFailure(failure); } /** @@ -1964,24 +3123,12 @@ private static void cleanupOwnedArgumentAliases(RuntimeArray args) { if (args == null || args.ownedAliasElements == null || args.ownedAliasElements.isEmpty()) return; RuntimeScalar[] owned = args.ownedAliasElements.toArray(new RuntimeScalar[0]); + Throwable failure = null; for (RuntimeScalar scalar : owned) { - RuntimeScalar.scopeExitCleanup(scalar); - if (scalar.type == RuntimeScalarType.CODE - && scalar.value instanceof RuntimeCode code - && (code.capturedScalars != null || code.capturedAggregates != null) - && code.refCount > 0 - && !isActiveCode(code) - && !ReachabilityWalker.isReachableFromRoots(code)) { - // A closure may have reached @_ after its lexical scope had - // already ended. In that case the scalar's original cleanup - // ran while it still appeared to be held by an alias array, - // leaving a positive manual CV count. Once this argument - // frame is gone, release its captures only if no Perl root - // can still reach the CV. - code.releaseCaptures(); - } - args.forgetOwnedAliasElement(scalar); + failure = attemptCleanup(failure, () -> RuntimeScalar.scopeExitCleanup(scalar)); + failure = attemptCleanup(failure, () -> args.forgetOwnedAliasElement(scalar)); } + rethrowCleanupFailure(failure); } /** @@ -2029,6 +3176,13 @@ static Object currentArgumentAliasFrame(RuntimeScalar scalar) { return null; } + /** Resolve the explicit source frame associated with a queued scalar owner. */ + static Object argumentAliasFrameForOwner(RuntimeScalar scalar) { + if (scalar == null || PerlRuntime.currentOrNull() == null) return null; + Object activeFrame = currentArgumentAliasFrame(scalar); + return activeFrame != null ? activeFrame : scalar.copiedFromArgumentFrameToken(); + } + /** True only while the argument frame represented by {@code token} is active. */ static boolean isArgumentFrameActive(Object token) { if (token == null || PerlRuntime.currentOrNull() == null) return false; @@ -2327,6 +3481,90 @@ public static RuntimeList returnList(RuntimeBase retVal, int callContext) { return returnList(retVal, callContext, true); } + /** Materialize context-sensitive aggregate values before their declaring scope ends. */ + public static RuntimeBase prepareScopeResult(RuntimeBase result, int context) { + if (context == RuntimeContextType.LVALUE || context == RuntimeContextType.LVALUE_LIST + || context == RuntimeContextType.OBJECT) { + retainTiedScopeResultOwners(result); + } else if (context != RuntimeContextType.VOID && result instanceof RuntimeScalar scalar + && scalar.type == RuntimeScalarType.TIED_SCALAR) { + // FETCH belongs to this rvalue evaluation, before its lexical magic + // can retire. A returned lvalue instead retains the magic's storage. + result = scalar.tiedFetch(); + } + if (result instanceof RuntimeArray || result instanceof RuntimeHash) { + if (context == RuntimeContextType.LIST) { + result = result.getList(); + } else if (context == RuntimeContextType.SCALAR || context == RuntimeContextType.OBJECT) { + result = result.scalar(); + } + } + return prepareScopeReturn(result, context, true); + } + + private static void retainTiedScopeResultOwners(RuntimeBase result) { + if (result instanceof RuntimeList list) { + for (RuntimeBase value : list.elements) retainTiedScopeResultOwners(value); + return; + } + TiedVariableBase magic = result instanceof TiedVariableBase tied ? tied + : result instanceof RuntimeScalar scalar + && scalar.type == RuntimeScalarType.TIED_SCALAR + && scalar.value instanceof TiedVariableBase tied ? tied : null; + if (magic != null) { + RuntimeScalar storage = magic.storageOwnerReference(); + if (storage != null) RuntimeScalar.copyToMortalReturnSlot(storage); + } + } + + /** Acquire rvalue reference owners before lexical cleanup can retire their referents. */ + public static RuntimeBase prepareScopeReturn( + RuntimeBase returned, int callContext, boolean copyScalars) { + if (!copyScalars || callContext == RuntimeContextType.VOID + || callContext == RuntimeContextType.LVALUE + || callContext == RuntimeContextType.LVALUE_LIST) return returned; + // A CODE object can reach this path directly from a `do` block or + // conditional expression without first passing through a RuntimeScalar. + // Acquire the return owner before the expression's lexical scope exits. + if (returned instanceof RuntimeCode code) { + return RuntimeScalar.copyToMortalReturnSlot(new RuntimeScalar(code)); + } + if (returned instanceof RuntimeScalar scalar + && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 + && !scalar.isMortalReturnSnapshot()) { + return RuntimeScalar.copyToMortalReturnSlot(scalar); + } + if (returned instanceof RuntimeList list && !(returned instanceof RuntimeControlFlowList)) { + for (RuntimeBase value : list.elements) { + if (value instanceof RuntimeScalar scalar + && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 + && !scalar.isMortalReturnSnapshot()) { + return list.copyToMortalReturnSlots(); + } + } + } + return returned; + } + + /** Materialize a local array's rvalue return before its element slots end. */ + public static RuntimeBase prepareLocalArrayReturn( + RuntimeBase returned, RuntimeArray localArray, int callContext, boolean copyScalars) { + if (localArray == null || returned != localArray || !copyScalars + || callContext == RuntimeContextType.LVALUE + || callContext == RuntimeContextType.LVALUE_LIST) return returned; + if (callContext == RuntimeContextType.VOID) return new RuntimeList(); + if (callContext == RuntimeContextType.SCALAR || callContext == RuntimeContextType.OBJECT) { + return localArray.scalar(); + } + RuntimeList result = new RuntimeList(); + for (int i = 0, size = localArray.size(); i < size; i++) { + RuntimeScalar value = localArray.get(i); + result.elements.add(value == null ? new RuntimeScalar() + : RuntimeScalar.copyToMortalReturnSlot(value)); + } + return result; + } + /** Return the scalar lvalue represented by {@code keys %hash}. */ public static RuntimeScalar keysLvalue(RuntimeBase container) { RuntimeScalar result = new RuntimeScalar(container.keys(RuntimeContextType.SCALAR)); @@ -2582,11 +3820,66 @@ public static RuntimeList coerceScalarCallResult(RuntimeList result, int effecti } } + /** Consume a map/grep return at an eval boundary after releasing its lexical owners. */ + public static RuntimeList finishEvalCallbackReturn( + PerlNonLocalReturnException transfer, Object[] locals, int context) { + return finishEvalCallbackReturn(transfer, locals, context, () -> {}); + } + + /** Keep the return owners through backend-specific argument and local restoration. */ + public static RuntimeList finishEvalCallbackReturn( + PerlNonLocalReturnException transfer, Object[] locals, int context, Runnable unwind) { + java.util.ArrayList owners = new java.util.ArrayList<>(); + RuntimeBase value = retainEvalReturnReferences(transfer.returnValue, owners); + try { + // The return slots above remain counted during nested DESTROY and + // flushes. Only expression values are traversed, never referent graphs. + for (int i = locals.length - 1; i >= 0; i--) { + MortalList.evalExceptionScopeCleanup(locals[i]); + MyVarCleanupStack.unregister(locals[i]); + } + unwind.run(); + MortalList.flush(); + GlobalVariable.setGlobalVariable("main::@", ""); + return coerceScalarCallResult(value == null ? new RuntimeList() : value.getList(), + context, context, true); + } finally { + for (RuntimeScalar owner : owners) { + RuntimeScalar.releaseStagedArgumentValue(owner); + } + } + } + + private static RuntimeBase retainEvalReturnReferences( + RuntimeBase value, java.util.List owners) { + if (value instanceof RuntimeList list) { + RuntimeList copy = new RuntimeList(); + for (RuntimeBase element : list.elements) { + copy.elements.add(retainEvalReturnReferences(element, owners)); + } + return copy; + } + if (value instanceof RuntimeScalar scalar + && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0) { + RuntimeScalar owner = RuntimeScalar.retainEvalReturnValue(scalar); + owners.add(owner); + return owner; + } + return value; + } + /** True when draining a callee's scope exits cannot invalidate its result. */ private static boolean containsNoReference(RuntimeList result) { + if (result instanceof RuntimeControlFlowList flow + && flow.getControlFlowType() == ControlFlowType.RETURN) { + RuntimeBase value = flow.getReturnValue(); + return value == null || containsNoReference(value.getList()); + } return result != null && result.elements.stream().noneMatch( element -> element instanceof RuntimeScalar scalar - && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0); + && ((scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 + || scalar.type == RuntimeScalarType.TIED_SCALAR + || scalar instanceof TiedVariableBase)); } /** @@ -2599,7 +3892,9 @@ public static void flushEvalBlockCleanupForScalarResult(RuntimeBase result) { if (result instanceof RuntimeList list) { resultHasNoReferences = containsNoReference(list); } else if (result instanceof RuntimeScalar scalar) { - resultHasNoReferences = (scalar.type & RuntimeScalarType.REFERENCE_BIT) == 0; + resultHasNoReferences = (scalar.type & RuntimeScalarType.REFERENCE_BIT) == 0 + && scalar.type != RuntimeScalarType.TIED_SCALAR + && !(scalar instanceof TiedVariableBase); } else { resultHasNoReferences = true; } @@ -2620,29 +3915,21 @@ private static RuntimeList copyReturnedReferenceScalars(RuntimeList result, int } for (RuntimeBase value : result.elements) { if (value instanceof RuntimeScalar scalar - && !isCodeScalar(scalar)) { + && !scalar.isMortalReturnSnapshot()) { if (recyclableScalarResult && result.elements.size() == 1) { // Scalar-context callers discard the list wrapper after extracting this // copied rvalue. Reuse a private one-scalar input wrapper when possible; // otherwise acquire a runtime-local wrapper for the copied value. - RuntimeScalar copied = scalar.clone(); + RuntimeScalar copied = RuntimeScalar.copyToMortalReturnSlot(scalar); if (result.replaceRecyclableScalarResult(copied)) return result; return RuntimeList.acquireScalarResult(copied); } - return result.cloneScalars(); + return result.copyToMortalReturnSlots(); } } return result; } - private static boolean isCodeScalar(RuntimeScalar scalar) { - RuntimeScalar current = scalar; - while (current != null && current.type == RuntimeScalarType.READONLY_SCALAR) { - current = (RuntimeScalar) current.value; - } - return current != null && current.type == RuntimeScalarType.CODE; - } - private static RuntimeList copyReadonlyListReturns(RuntimeList result, int effectiveContext) { if (effectiveContext != RuntimeContextType.LIST) { return result; @@ -2694,56 +3981,91 @@ public static RuntimeBase acquireMethodInvocantHold(RuntimeScalar runtimeScalar) if (base.blessId == 0) { return null; } - if (base.refCount == Integer.MIN_VALUE || base.currentlyDestroying) { + if (base.isPerlDestroyed() || base.currentlyDestroying) { return null; } - if (base.refCount < 0) { + if (!base.isRefCountTracked()) { return null; } - base.traceRefCount(+1, "RuntimeCode.method invocant hold (+1)"); - base.refCount++; - base.acquireTransientTraceOwner("method invocant hold", "RuntimeCode.acquireMethodInvocantHold"); - return base; + return new MethodInvocantHold(base, PerlRuntime.current().executionState()); } - /** Release a hold returned by {@link #acquireMethodInvocantHold(RuntimeScalar)}. */ - public static void releaseMethodInvocantHold(RuntimeBase holdBase) { - if (holdBase == null) { - return; + /** One call's invocant edge, kept separate from every other hold of the same value. */ + private static final class MethodInvocantHold extends RuntimeScalar { + private final RuntimeBase referent; + private final ExecutionRuntimeState ownerState; + private final PerlOwnerSlot owner = new PerlOwnerSlot(PerlOwnerSlot.Kind.ARGUMENT_VALUE); + + MethodInvocantHold(RuntimeBase referent, ExecutionRuntimeState ownerState) { + this.referent = referent; + this.ownerState = ownerState; + owner.acquireCountedMethodInvocantOwner( + referent, "RuntimeCode.method invocant hold (+1)"); + referent.acquireTransientTraceOwner("method invocant hold", "RuntimeCode.acquireMethodInvocantHold"); + ownerState.methodInvocantHolds.add(this); } - holdBase.traceRefCount(-1, "RuntimeCode.method invocant hold release (-1)"); - holdBase.releaseTransientTraceOwner("method invocant hold", - "RuntimeCode.releaseMethodInvocantHold"); - if (holdBase.refCount > 0 && holdBase.refCount != Integer.MIN_VALUE && !holdBase.currentlyDestroying) { - if (holdBase.refCount == 1) { - // Keep the invocant alive until the caller has had a chance to - // capture a method's return value. If no real owner is added, - // the deferred decrement destroys it at the statement boundary. - MortalList.deferDecrement(holdBase); - } else { - holdBase.refCount--; - } + + void release(boolean abandoned) { + if (!owner.isActive()) return; + ownerState.methodInvocantHolds.remove(this); + referent.releaseTransientTraceOwner("method invocant hold", "RuntimeCode.MethodInvocantHold.release"); + // Normal returns keep the final decrement pending until the + // receiver has acquired the result; abandoned calls drain it now. + MortalList.releaseCountedMethodInvocantOwner(referent, owner, + "RuntimeCode.method invocant hold release (-1)", abandoned); } } + /** Release a hold returned by {@link #acquireMethodInvocantHold(RuntimeScalar)}. */ + public static void releaseMethodInvocantHold(RuntimeBase hold) { + if (hold != null) ((MethodInvocantHold) hold).release(false); + } + + /** Retire an abandoned call's invocant edge without waiting for a result receiver. */ + public static void releaseAbandonedMethodInvocantHold(RuntimeBase hold) { + if (hold != null) ((MethodInvocantHold) hold).release(true); + } + + /** Current method-invocant owner depth, used to scope eval unwinding. */ + public static int methodInvocantHoldDepth(ExecutionRuntimeState executionState) { + return executionState.methodInvocantHolds.size(); + } + + /** Current argument-staging depth, used to scope eval unwinding. */ + public static int callArgumentFrameDepth(ExecutionRuntimeState executionState) { + return executionState.callArgumentFrames.size(); + } + + static boolean hasActiveCallArgumentFrame() { + PerlRuntime runtime = PerlRuntime.currentOrNull(); + return runtime != null && !runtime.executionState().callArgumentFrames.isEmpty(); + } + /** - * Release a method-invocant hold when control flow abandoned the call that - * would have transferred the result. Unlike an ordinary post-call release, - * reaching zero here is final and must run Perl destruction immediately. + * Finish only argument frames and method-invocant owners created inside an + * eval boundary. Argument aliases retire before the enclosing receiver hold, + * matching the interpreter's eval-unwind order. */ - public static void releaseAbandonedMethodInvocantHold(RuntimeBase holdBase) { - if (holdBase == null) { - return; + public static void unwindEvalMethodInvocantHolds( + ExecutionRuntimeState executionState, int argumentDepth, int holdDepth) { + int pendingBefore = MortalList.pendingSize(); + boolean releasedArguments = false; + while (executionState.callArgumentFrames.size() > argumentDepth) { + int last = executionState.callArgumentFrames.size() - 1; + executionState.callArgumentFrames.get(last).finish(); + releasedArguments = true; } - holdBase.traceRefCount(-1, "RuntimeCode.abandoned method invocant hold release (-1)"); - holdBase.releaseTransientTraceOwner("method invocant hold", - "RuntimeCode.releaseAbandonedMethodInvocantHold"); - if (holdBase.refCount > 0 - && holdBase.refCount != Integer.MIN_VALUE - && !holdBase.currentlyDestroying - && --holdBase.refCount == 0) { - holdBase.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(holdBase); + while (executionState.methodInvocantHolds.size() > holdDepth) { + RuntimeBase hold = executionState.methodInvocantHolds + .get(executionState.methodInvocantHolds.size() - 1); + releaseAbandonedMethodInvocantHold(hold); + } + if (releasedArguments) { + // Argument-frame cleanup may queue releases above an outer mark. + // Drain only those new entries: flushAboveMark also consumes older + // caller-owned RETURN_VALUE entries that must survive this unwind + // until the receiving scalar acquires them. + MortalList.drainPendingSince(pendingBefore); } } @@ -2885,7 +4207,57 @@ private static EmitterContext getEvalContext(String evalTag) { } public static void registerPadConstants(String className, RuntimeBase[] constants) { - PerlRuntime.current().runtimeCodeState().padConstantsByClassName.put(className, constants); + registerPadConstants(className, constants, Map.of(), Map.of()); + } + + public static void registerPadConstants( + String className, + RuntimeBase[] constants, + Map embeddedConstants, + Map> embeddedDescendants) { + RuntimeCodeRuntimeState state = PerlRuntime.current().runtimeCodeState(); + state.padConstantsByClassName.put(className, + constants == null ? new RuntimeBase[0] : constants.clone()); + state.embeddedPadConstantsByClassName.put(className, copyPadConstantArrays(embeddedConstants)); + state.embeddedPadConstantDescendantsByClassName.put( + className, copyPadConstantDescendants(embeddedDescendants)); + } + + /** Read a stable optree constant by generated code class and pad index. */ + public static RuntimeScalar getPadConstant(String className, int index) { + RuntimeCode activeCode = getActiveCodeAt(0); + RuntimeBase[] constants = activeCode == null + ? null : activeCode.padConstantsForClass(className); + if (constants == null || index < 0 || index >= constants.length + || !(constants[index] instanceof RuntimeScalar)) { + RuntimeCodeRuntimeState state = PerlRuntime.current().runtimeCodeState(); + constants = state.padConstantsByClassName.get(className); + } + if (constants == null || index < 0 || index >= constants.length + || !(constants[index] instanceof RuntimeScalar scalar)) { + throw new IllegalStateException( + "missing pad constant " + index + " for " + className); + } + return scalar; + } + + private static Map copyPadConstantArrays( + Map source) { + if (source == null || source.isEmpty()) return Collections.emptyMap(); + Map copy = new LinkedHashMap<>(); + source.forEach((name, values) -> copy.put(name, + values == null ? new RuntimeBase[0] : values.clone())); + return Collections.unmodifiableMap(copy); + } + + private static Map> copyPadConstantDescendants( + Map> source) { + if (source == null || source.isEmpty()) return Collections.emptyMap(); + Map> copy = new LinkedHashMap<>(); + source.forEach((name, descendants) -> copy.put(name, + descendants == null ? Collections.emptySet() + : Collections.unmodifiableSet(new LinkedHashSet<>(descendants)))); + return Collections.unmodifiableMap(copy); } public static void registerStableHashMutationMethod( @@ -3007,6 +4379,8 @@ private record WarningBitsCache(Class codeClass, String bits) {} // In Perl 5, MODIFY_CODE_ATTRIBUTES receives the closure prototype for closures. // Calling a closure prototype should die with "Closure prototype called". public boolean isClosurePrototype = false; + /** This anonymous CV is a noncapturing code template owned by its optree. */ + public boolean isOptreeCodeTemplate; // Anonymous CODE attributes are dispatched before backend compilation. // These flags carry built-in effects until the executable definition and // (for closures) captured environment are available. @@ -3181,6 +4555,242 @@ private void exitCall(ExecutionRuntimeState executionState) { public Map stateVariable = new HashMap<>(); public Map stateArray = new HashMap<>(); public Map stateHash = new HashMap<>(); + Map stateAggregateAliasOwners = new HashMap<>(); + Map stateScalarOwnerSlots = new HashMap<>(); + Map stateArrayOwnerSlots = new HashMap<>(); + Map stateHashOwnerSlots = new HashMap<>(); + Map stateAggregateAliasOwnerSlots = new HashMap<>(); + + void bindStateScalar(String name, RuntimeScalar scalar) { + PerlOwnerSlot replacementSlot = scalar.retainCodeStateOwner(this); + RuntimeScalar previous = stateVariable.put(name, scalar); + PerlOwnerSlot previousSlot = stateScalarOwnerSlots.put(name, replacementSlot); + if (previous != null && (previous != scalar || previousSlot != replacementSlot)) { + releaseStateScalarBinding(previous, previousSlot); + } + } + + private void bindStateAggregate(String name, RuntimeBase aggregate) { + boolean array = aggregate instanceof RuntimeArray; + String aliasKey = (array ? "@" : "%") + name; + PerlOwnerSlot replacementSlot = aggregate.retainCodeStateOwner(this); + RuntimeBase previous = array + ? stateArray.put(name, (RuntimeArray) aggregate) + : stateHash.put(name, (RuntimeHash) aggregate); + PerlOwnerSlot previousSlot = array + ? stateArrayOwnerSlots.put(name, replacementSlot) + : stateHashOwnerSlots.put(name, replacementSlot); + RuntimeScalar previousAlias = stateAggregateAliasOwners.remove(aliasKey); + PerlOwnerSlot previousAliasSlot = stateAggregateAliasOwnerSlots.remove(aliasKey); + if (previousAlias != null) releaseStateScalarBinding(previousAlias, previousAliasSlot); + if (previous != null && previous != aggregate) { + if (previousSlot != null) releaseStateAggregateBinding(previous, previousSlot); + else if (previousAlias == null) { + releaseStateAggregateBinding(previous, (PerlOwnerSlot) null); + } + } else if (previousSlot != null && previousSlot != replacementSlot) { + releaseStateAggregateBinding(previous, previousSlot); + } + } + + void bindStateArray(String name, RuntimeArray array) { + bindStateAggregate(name, array); + } + + void bindStateHash(String name, RuntimeHash hash) { + bindStateAggregate(name, hash); + } + + void bindStateAggregateAlias(String name, RuntimeBase aggregate) { + boolean array = aggregate instanceof RuntimeArray; + String ownerKey = (array ? "@" : "%") + name; + RuntimeScalar owner = new RuntimeScalar(); + owner.set(array ? ((RuntimeArray) aggregate).createAnonymousReference() + : ((RuntimeHash) aggregate).createAnonymousReference()); + PerlOwnerSlot ownerSlot = owner.retainCodeStateOwner(this); + RuntimeBase previous = array ? stateArray.put(name, (RuntimeArray) aggregate) + : stateHash.put(name, (RuntimeHash) aggregate); + RuntimeScalar previousOwner = stateAggregateAliasOwners.put(ownerKey, owner); + PerlOwnerSlot previousOwnerSlot = stateAggregateAliasOwnerSlots.put(ownerKey, ownerSlot); + PerlOwnerSlot previousAggregateSlot = array + ? stateArrayOwnerSlots.remove(name) : stateHashOwnerSlots.remove(name); + if (previousOwner != null) releaseStateScalarBinding(previousOwner, previousOwnerSlot); + if (previous != null) releaseStateAggregateBinding(previous, previousAggregateSlot); + } + + /** Retire this CV's persistent pad bindings at final CV destruction. */ + void releaseStateStorage() { + clearPadConstantWeakRefs(); + if (stateVariable.isEmpty() && stateArray.isEmpty() && stateHash.isEmpty() + && stateAggregateAliasOwners.isEmpty() + && stateScalarOwnerSlots.isEmpty() && stateArrayOwnerSlots.isEmpty() + && stateHashOwnerSlots.isEmpty() && stateAggregateAliasOwnerSlots.isEmpty()) { + stateVariableInitialized.clear(); + return; + } + // Detach all bindings before cleanup: destructors may re-enter Perl. + // State aliases can address the same cell under more than one name. + Map> scalarBindings = new IdentityHashMap<>(); + for (Map.Entry entry : stateVariable.entrySet()) { + addStateScalarBinding( + scalarBindings, entry.getValue(), stateScalarOwnerSlots.get(entry.getKey())); + } + for (Map.Entry entry : stateAggregateAliasOwners.entrySet()) { + addStateScalarBinding(scalarBindings, entry.getValue(), + stateAggregateAliasOwnerSlots.get(entry.getKey())); + } + Map> aggregateBindings = new IdentityHashMap<>(); + for (var entry : stateArray.entrySet()) { + if (!stateAggregateAliasOwners.containsKey("@" + entry.getKey())) { + addStateAggregateBinding(aggregateBindings, entry.getValue(), + stateArrayOwnerSlots.get(entry.getKey())); + } + } + for (var entry : stateHash.entrySet()) { + if (!stateAggregateAliasOwners.containsKey("%" + entry.getKey())) { + addStateAggregateBinding(aggregateBindings, entry.getValue(), + stateHashOwnerSlots.get(entry.getKey())); + } + } + stateVariable.clear(); + stateArray.clear(); + stateHash.clear(); + stateAggregateAliasOwners.clear(); + stateScalarOwnerSlots.clear(); + stateArrayOwnerSlots.clear(); + stateHashOwnerSlots.clear(); + stateAggregateAliasOwnerSlots.clear(); + stateVariableInitialized.clear(); + for (Map.Entry> entry : scalarBindings.entrySet()) { + releaseStateScalarBinding(entry.getKey(), entry.getValue()); + } + for (Map.Entry> entry : aggregateBindings.entrySet()) { + releaseStateAggregateBinding(entry.getKey(), entry.getValue()); + } + } + + private static void addStateScalarBinding( + Map> bindings, + RuntimeScalar scalar, PerlOwnerSlot ownerSlot) { + if (scalar == null) return; + bindings.computeIfAbsent(scalar, ignored -> new ArrayList<>()); + if (ownerSlot != null) bindings.get(scalar).add(ownerSlot); + } + + private static void addStateAggregateBinding( + Map> bindings, + RuntimeBase aggregate, PerlOwnerSlot ownerSlot) { + if (aggregate == null) return; + bindings.computeIfAbsent(aggregate, ignored -> new ArrayList<>()); + if (ownerSlot != null) bindings.get(aggregate).add(ownerSlot); + } + + private static void releaseStateScalarBinding(RuntimeScalar scalar, PerlOwnerSlot ownerSlot) { + releaseStateScalarBinding(scalar, + ownerSlot == null ? Collections.emptyList() : List.of(ownerSlot)); + } + + private static void releaseStateScalarBinding( + RuntimeScalar scalar, List ownerSlots) { + if (scalar == null) return; + scalar.localBindingExists = false; + RuntimeScalar.scopeExitCleanup(scalar); + for (PerlOwnerSlot ownerSlot : ownerSlots) { + scalar.releaseCodeStateOwner(ownerSlot); + } + } + + private static void releaseStateAggregateBinding(RuntimeBase aggregate, + PerlOwnerSlot ownerSlot) { + releaseStateAggregateBinding(aggregate, + ownerSlot == null ? Collections.emptyList() : List.of(ownerSlot)); + } + + private static void releaseStateAggregateBinding( + RuntimeBase aggregate, List ownerSlots) { + if (aggregate == null) return; + if (aggregate instanceof RuntimeArray array) MortalList.scopeExitCleanupArray(array); + else if (aggregate instanceof RuntimeHash hash) MortalList.scopeExitCleanupHash(hash); + for (PerlOwnerSlot ownerSlot : ownerSlots) { + aggregate.releaseCodeStateOwner(ownerSlot); + } + if (aggregate instanceof RuntimeArray array) MortalList.scopeExitCleanupArray(array); + else if (aggregate instanceof RuntimeHash hash) MortalList.scopeExitCleanupHash(hash); + } + + /** Reconstruct direct owner slots for independently cloned CODE state storage. */ + void retainClonedStateOwnerSlots() { + for (Map.Entry entry : stateVariable.entrySet()) { + stateScalarOwnerSlots.put(entry.getKey(), entry.getValue().retainCodeStateOwner(this)); + } + for (Map.Entry entry : stateAggregateAliasOwners.entrySet()) { + stateAggregateAliasOwnerSlots.put(entry.getKey(), + entry.getValue().retainCodeStateOwner(this)); + } + for (Map.Entry entry : stateArray.entrySet()) { + if (!stateAggregateAliasOwners.containsKey("@" + entry.getKey())) { + stateArrayOwnerSlots.put(entry.getKey(), + entry.getValue().retainCodeStateOwner(this)); + } + } + for (Map.Entry entry : stateHash.entrySet()) { + if (!stateAggregateAliasOwners.containsKey("%" + entry.getKey())) { + stateHashOwnerSlots.put(entry.getKey(), + entry.getValue().retainCodeStateOwner(this)); + } + } + } + + boolean hasStateScalarOwner(RuntimeScalar scalar, PerlOwnerSlot ownerSlot) { + if (scalar == null || ownerSlot == null + || ownerSlot.kind() != PerlOwnerSlot.Kind.CODE_STATE + || ownerSlot.captureOwner() != this || ownerSlot.referent() != scalar + || !ownerSlot.isActive()) { + return false; + } + for (Map.Entry entry : stateVariable.entrySet()) { + if (entry.getValue() == scalar && stateScalarOwnerSlots.get(entry.getKey()) == ownerSlot) { + return true; + } + } + for (Map.Entry entry : stateAggregateAliasOwners.entrySet()) { + if (entry.getValue() == scalar + && stateAggregateAliasOwnerSlots.get(entry.getKey()) == ownerSlot) { + return true; + } + } + return false; + } + + boolean hasCurrentStateOwner(RuntimeBase value, PerlOwnerSlot ownerSlot) { + if (value == null || ownerSlot == null + || ownerSlot.kind() != PerlOwnerSlot.Kind.CODE_STATE + || ownerSlot.captureOwner() != this || ownerSlot.referent() != value + || !ownerSlot.isActive()) { + return false; + } + if (value instanceof RuntimeScalar scalar) { + return hasStateScalarOwner(scalar, ownerSlot); + } + if (value instanceof RuntimeArray array) { + for (Map.Entry entry : stateArray.entrySet()) { + if (entry.getValue() == array + && stateArrayOwnerSlots.get(entry.getKey()) == ownerSlot) { + return true; + } + } + return false; + } + if (value instanceof RuntimeHash hash) { + for (Map.Entry entry : stateHash.entrySet()) { + if (entry.getValue() == hash + && stateHashOwnerSlots.get(entry.getKey()) == ownerSlot) { + return true; + } + } + } + return false; + } public RuntimeList constantValue; // Field to hold the thread compiling this code public Supplier compilerSupplier; @@ -3243,17 +4853,121 @@ void restoreClonedSelfReference(RuntimeScalar selfRef) { */ public RuntimeScalar[] capturedScalars; + /** One owner identity for each captured scalar pad cell. */ + public PerlOwnerSlot[] capturedScalarOwnerSlots; + /** Generated closure fields were copied into capturedScalars/aggregates. */ public boolean captureFieldsRecorded; /** - * Captured aggregate lexicals (arrays/hashes). Their element cleanup is - * deferred while the closure keeps the aggregate alive. + * Captured aggregate lexicals (arrays/hashes). Their element cleanup is + * deferred while the closure keeps the aggregate alive. + */ + public RuntimeBase[] capturedAggregates; + + /** Owner slots that retain each captured aggregate pad for Perl closure lifetime. */ + public PerlOwnerSlot[] capturedAggregateOwnerSlots; + + private static final class RetiredCaptureEdges { + private final RuntimeScalar[] scalars; + private final PerlOwnerSlot[] scalarOwnerSlots; + private final RuntimeBase[] aggregates; + private final PerlOwnerSlot[] aggregateOwnerSlots; + private final Set retainedOwnerSlots; + + private RetiredCaptureEdges(RuntimeCode previous, RuntimeCode replacement) { + this(previous, captureOwnerSlots(replacement)); + } + + private RetiredCaptureEdges( + RuntimeCode previous, Set retainedOwnerSlots) { + scalars = previous.capturedScalars; + scalarOwnerSlots = previous.capturedScalarOwnerSlots; + aggregates = previous.capturedAggregates; + aggregateOwnerSlots = previous.capturedAggregateOwnerSlots; + this.retainedOwnerSlots = retainedOwnerSlots; + } + + private boolean isEmpty() { + return (scalars == null || scalars.length == 0) + && (aggregates == null || aggregates.length == 0); + } + } + + private final List pendingRetiredCaptureEdges = new ArrayList<>(); + + private static Set captureOwnerSlots(RuntimeCode code) { + Set slots = Collections.newSetFromMap(new IdentityHashMap<>()); + if (code.capturedScalarOwnerSlots != null) { + for (PerlOwnerSlot slot : code.capturedScalarOwnerSlots) { + if (slot != null) slots.add(slot); + } + } + if (code.capturedAggregateOwnerSlots != null) { + for (PerlOwnerSlot slot : code.capturedAggregateOwnerSlots) { + if (slot != null) slots.add(slot); + } + } + return slots; + } + + /** + * Whether this CV currently owns any closure or persistent-state edges. + * Root selection uses these slot identities directly; reflective capture + * discovery and retired-edge history are not Perl ownership proofs. */ - public RuntimeBase[] capturedAggregates; + boolean hasActiveOwnedCaptureEdges() { + if (hasActiveCaptureEdges(capturedScalars, capturedScalarOwnerSlots) + || hasActiveCaptureEdges(capturedAggregates, capturedAggregateOwnerSlots)) { + return true; + } + for (RetiredCaptureEdges captures : pendingRetiredCaptureEdges) { + if (hasActiveCaptureEdges(captures.scalars, captures.scalarOwnerSlots) + || hasActiveCaptureEdges(captures.aggregates, captures.aggregateOwnerSlots)) { + return true; + } + } + for (Map.Entry entry : stateVariable.entrySet()) { + if (hasCurrentStateOwner(entry.getValue(), stateScalarOwnerSlots.get(entry.getKey()))) { + return true; + } + } + for (Map.Entry entry : stateAggregateAliasOwners.entrySet()) { + if (hasCurrentStateOwner( + entry.getValue(), stateAggregateAliasOwnerSlots.get(entry.getKey()))) { + return true; + } + } + for (Map.Entry entry : stateArray.entrySet()) { + if (hasCurrentStateOwner(entry.getValue(), stateArrayOwnerSlots.get(entry.getKey()))) { + return true; + } + } + for (Map.Entry entry : stateHash.entrySet()) { + if (hasCurrentStateOwner(entry.getValue(), stateHashOwnerSlots.get(entry.getKey()))) { + return true; + } + } + return false; + } - /** Owner slots that keep each captured aggregate pad in Perl reachability. */ - public PerlOwnerSlot[] capturedAggregateOwnerSlots; + private boolean hasActiveCaptureEdges(RuntimeBase[] values, PerlOwnerSlot[] ownerSlots) { + if (values == null || ownerSlots == null) return false; + int count = Math.min(values.length, ownerSlots.length); + for (int i = 0; i < count; i++) { + RuntimeBase value = values[i]; + PerlOwnerSlot ownerSlot = ownerSlots[i]; + PerlOwnerSlot.Kind expectedKind = value instanceof RuntimeScalar + ? PerlOwnerSlot.Kind.SCALAR_CAPTURE : PerlOwnerSlot.Kind.CLOSURE_PAD; + if (value != null && ownerSlot != null && ownerSlot.isActive() + && ownerSlot.kind() == expectedKind + && ownerSlot.captureOwner() == this + && ownerSlot.referent() == value) { + return true; + } + } + return false; + } /** Live lexical containers keyed by their Perl pad names for PadWalker. */ public Map closedOverVariables; @@ -3406,6 +5120,27 @@ public void unbindActiveLexical(String variableName, RuntimeBase cell) { } if (runtime.executionState().topLevelLexicals.get(variableName) == cell) { runtime.executionState().topLevelLexicals.remove(variableName); + PerlOwnerSlot ownerSlot = runtime.executionState().topLevelLexicalOwnerSlots + .remove(variableName); + if (ownerSlot != null) ownerSlot.release(); + } + } + + /** Unbind the innermost exact name/cell binding when a backend unwinds a scope. */ + public static void unbindCurrentActiveLexical(RuntimeBase cell, String variableName) { + if (cell == null || variableName == null || PerlRuntime.currentOrNull() == null) return; + PerlRuntime runtime = PerlRuntime.current(); + for (ActiveLexicalFrame frame : activeLexicalFrames(runtime.executionState())) { + if (frame.cells().get(variableName) == cell) { + frame.remove(variableName); + return; + } + } + if (runtime.executionState().topLevelLexicals.get(variableName) == cell) { + runtime.executionState().topLevelLexicals.remove(variableName); + PerlOwnerSlot ownerSlot = runtime.executionState().topLevelLexicalOwnerSlots + .remove(variableName); + if (ownerSlot != null) ownerSlot.release(); } } @@ -3473,82 +5208,436 @@ public void setLexicalAlias(String variableName, RuntimeBase replacement) { } /** - * Tracks the number of stash (glob) entries that reference this CODE object. - * Stash entries created via {@code *Foo::bar = $coderef} are invisible to the - * selective refCount because glob assignments go through a container that - * may be overwritten independently. - *

    - * When stashRefCount > 0, the CODE ref should NOT be considered dead even if - * the selective refCount reaches 0, because the stash still holds a live - * reference. This prevents premature {@code releaseCaptures()} which would - * cascade to clear weak references (e.g., in Sub::Defer's %DEFERRED hash). + * Legacy diagnostic field retained for Java source compatibility. + * Lifecycle decisions use the current CODE_SLOT owner identities instead. */ public int stashRefCount = 0; + /** All GP/CODE edges for this CV use counted slot identities. */ + boolean hasCountedCodeSlots; + // Conservative compatibility-index metadata survives ownership retirement + // when embedding code still holds a CV descriptor. It retains no captures. + boolean retiredOwnedEdges; - /** Number of queued phaser executions currently invoking this CV. */ - int activeEndBlockExecutions; - /** The queue's last selective owner was rescued while this CV was running. */ - boolean rescuedActiveEndBlockOwner; - - void beginEndBlockExecution() { - activeEndBlockExecutions++; - } - - void endEndBlockExecution() { - if (activeEndBlockExecutions > 0) activeEndBlockExecutions--; - if (activeEndBlockExecutions == 0 && rescuedActiveEndBlockOwner) { - rescuedActiveEndBlockOwner = false; - MortalList.deferDecrement(this); + /** Cached scalar constants referenced via backslash inside this CV's optree. */ + public RuntimeBase[] padConstants; + /** One identity for each strong constant edge held by this optree. */ + private final List padConstantOwnerSlots = new ArrayList<>(); + /** Noncapturing anonymous CV templates held by their containing optree. */ + private final Map codeTemplateOwnerSlots = new LinkedHashMap<>(); + /** Strong CV edges owned by this optree's compiled direct named-call sites. */ + private final List compiledDirectCallSiteOwners = new ArrayList<>(); + private final Map> + compiledDirectCallSitesByClassName = new LinkedHashMap<>(); + /** Direct constants for this CV and embedded anonymous optrees. */ + private final Map padConstantArraysByClassName = new LinkedHashMap<>(); + private final Map> padConstantDescendantsByClassName = new LinkedHashMap<>(); + private final Set padConstantRegistryClassNames = new LinkedHashSet<>(); + private String padConstantClassName; + + /** Attach compiled constants and acquire one owner identity per optree edge. */ + public void installPadConstants(RuntimeBase[] constants) { + installPadConstantTree(null, constants, Map.of(), Map.of()); + } + + public void installPadConstantTree( + String className, + RuntimeBase[] constants, + Map embeddedConstants, + Map> embeddedDescendants) { + RuntimeBase[] previousConstants = allPadConstantValues(); + Set previousRegistryNames = new LinkedHashSet<>(padConstantRegistryClassNames); + List previousSlots = new ArrayList<>(padConstantOwnerSlots); + List previousCallSites = + new ArrayList<>(compiledDirectCallSiteOwners); + List nextCallSites = new ArrayList<>(); + Map> nextCallSitesByClassName = + new LinkedHashMap<>(); + Map directCallSitesByIndex = new LinkedHashMap<>(); + + padConstants = prepareCompiledDirectCallConstants( + constants, nextCallSites, directCallSitesByIndex); + if (!directCallSitesByIndex.isEmpty()) { + nextCallSitesByClassName.put( + className == null ? "" : className, directCallSitesByIndex); + } + padConstantClassName = className; + padConstantArraysByClassName.clear(); + padConstantDescendantsByClassName.clear(); + padConstantRegistryClassNames.clear(); + if (className != null) { + padConstantArraysByClassName.put(className, + padConstants == null ? new RuntimeBase[0] : padConstants); + padConstantDescendantsByClassName.put(className, + embeddedConstants == null || embeddedConstants.isEmpty() + ? Collections.emptySet() + : Collections.unmodifiableSet( + new LinkedHashSet<>(embeddedConstants.keySet()))); + padConstantRegistryClassNames.add(className); + } + if (embeddedConstants != null) { + embeddedConstants.forEach((nestedClassName, nestedConstants) -> { + Map nestedCallSites = + new LinkedHashMap<>(); + RuntimeBase[] preparedNestedConstants = + prepareCompiledDirectCallConstants( + nestedConstants, nextCallSites, nestedCallSites); + padConstantArraysByClassName.put(nestedClassName, + preparedNestedConstants == null + ? new RuntimeBase[0] : preparedNestedConstants); + padConstantRegistryClassNames.add(nestedClassName); + if (!nestedCallSites.isEmpty()) { + nextCallSitesByClassName.put(nestedClassName, nestedCallSites); + } + }); } + if (embeddedDescendants != null) { + embeddedDescendants.forEach((nestedClassName, descendants) -> + padConstantDescendantsByClassName.put(nestedClassName, + descendants == null || descendants.isEmpty() + ? Collections.emptySet() + : Collections.unmodifiableSet( + new LinkedHashSet<>(descendants)))); + } + compiledDirectCallSiteOwners.clear(); + compiledDirectCallSiteOwners.addAll(nextCallSites); + compiledDirectCallSitesByClassName.clear(); + compiledDirectCallSitesByClassName.putAll(nextCallSitesByClassName); + padConstantOwnerSlots.clear(); + if (padConstantArraysByClassName.isEmpty()) { + acquirePadConstantOwners(padConstants); + } else { + padConstantArraysByClassName.values().forEach(this::acquirePadConstantOwners); + RuntimeCodeRuntimeState runtimeState = PerlRuntime.current().runtimeCodeState(); + for (String ownedClassName : padConstantArraysByClassName.keySet()) { + runtimeState.padConstantsByClassName.put(ownedClassName, + padConstantArraysByClassName.get(ownedClassName).clone()); + runtimeState.embeddedPadConstantsByClassName.put(ownedClassName, + copyPadConstantArrays(embeddedPadConstantsForClass(ownedClassName))); + runtimeState.embeddedPadConstantDescendantsByClassName.put(ownedClassName, + copyPadConstantDescendants( + padConstantDescendantTreesForClass(ownedClassName))); + } + } + + // New call-site identities are acquired while the previous optree + // still owns its targets. Replacing a compiled body never creates a + // zero-owner interval for a CV that both bodies call. + for (CompiledDirectCallSite owner : previousCallSites) owner.release(); + for (PerlOwnerSlot owner : previousSlots) owner.release(); + clearUnownedPadConstantWeakRefs(previousConstants); + removeUnownedPadConstantRegistryEntries(previousRegistryNames); + } + + private RuntimeBase[] prepareCompiledDirectCallConstants( + RuntimeBase[] constants, + List callSites, + Map callSitesByIndex) { + if (constants == null) return null; + RuntimeBase[] prepared = constants.clone(); + for (int index = 0; index < prepared.length; index++) { + if (!(prepared[index] instanceof RuntimeScalar descriptor) + || descriptor.compiledDirectCallSiteName() == null) { + continue; + } + String name = descriptor.compiledDirectCallSiteName(); + int siteIndex = descriptor.compiledDirectCallSiteIndex(); + if (siteIndex < 0) siteIndex = index; + boolean compileTimePinned = descriptor.compiledDirectCallCompileTimePinned(); + boolean retainTargetIfDeletedBeforeInstall = + descriptor.compiledDirectCallRetainTargetIfDeletedBeforeInstall(); + RuntimeScalar initialSlot = descriptor.compiledDirectCallInitialSlot(); + RuntimeScalar pinSlot = descriptor.compiledDirectCallPinSlot(); + RuntimeCode initialTarget = descriptor.compiledDirectCallInitialTarget(); + if (initialTarget == null && descriptor.value instanceof RuntimeCode code) { + initialTarget = code; + } + if (initialTarget == null) { + RuntimeScalar visible = GlobalVariable.getVisibleGlobalCodeRefForDirectCall(name); + if (visible != null && visible.value instanceof RuntimeCode code) { + initialTarget = code; + } + } + + RuntimeScalar cache = new RuntimeScalar(); + cache.configureCompiledDirectCallSite( + name, siteIndex, null, compileTimePinned, retainTargetIfDeletedBeforeInstall); + CompiledDirectCallSite callSite = + new CompiledDirectCallSite(name, cache, initialTarget, compileTimePinned, + retainTargetIfDeletedBeforeInstall); + prepared[index] = cache; + callSites.add(callSite); + callSitesByIndex.put(siteIndex, callSite); + // Transfer the compiler's temporary pin only after the owning + // RuntimeCode has acquired its callsite edge. RuntimeScalars that + // are already installed caches (for example when cloning a CV) + // keep their source callsite ownership untouched. + if (descriptor.isCompiledDirectCallSiteDescriptor()) { + descriptor.releaseCompiledDirectCallSiteDescriptorBinding(); + GlobalVariable.releaseCompiledDirectCallPin( + name, pinSlot == null ? initialSlot : pinSlot); + if (descriptor.compiledDirectCallHasDeferredParseOwner()) { + GlobalVariable.releaseDeferredDirectCallOwner(initialSlot); + } + } + } + return prepared; } /** - * Cached constants referenced via backslash (e.g., \"yay") inside this subroutine. - * When the CODE slot of a glob is replaced, weak references to these constants - * are cleared to emulate Perl 5's "optree reaping" behavior. + * Release parser-owned CODE edges when JVM generation abandons an optree + * before its pad constants can be transferred to a RuntimeCode. */ - public RuntimeBase[] padConstants; + public static void discardUninstalledCompiledDirectCallDescriptors( + RuntimeBase[] constants) { + if (constants == null) return; + for (RuntimeBase constant : constants) { + if (!(constant instanceof RuntimeScalar descriptor) + || !descriptor.isCompiledDirectCallSiteDescriptor()) continue; + String name = descriptor.compiledDirectCallSiteName(); + RuntimeScalar initialSlot = descriptor.compiledDirectCallInitialSlot(); + RuntimeScalar pinSlot = descriptor.compiledDirectCallPinSlot(); + boolean hasDeferredParseOwner = descriptor.compiledDirectCallHasDeferredParseOwner(); + descriptor.releaseCompiledDirectCallSiteDescriptorBinding(); + GlobalVariable.releaseCompiledDirectCallPin( + name, pinSlot == null ? initialSlot : pinSlot); + if (hasDeferredParseOwner) { + GlobalVariable.releaseDeferredDirectCallOwner(initialSlot); + } + } + } + + private void acquirePadConstantOwners(RuntimeBase[] constants) { + if (constants == null) return; + for (RuntimeBase constant : constants) { + if (constant == null) continue; + PerlOwnerSlot owner = new PerlOwnerSlot(PerlOwnerSlot.Kind.CODE_PAD_CONSTANT); + owner.acquireCodePadConstantIdentity(constant); + padConstantOwnerSlots.add(owner); + } + } + + private RuntimeBase[] allPadConstantValues() { + List values = new ArrayList<>(); + if (padConstantArraysByClassName.isEmpty()) { + if (padConstants != null) Collections.addAll(values, padConstants); + } else { + padConstantArraysByClassName.values().forEach(array -> { + if (array != null) Collections.addAll(values, array); + }); + } + return values.toArray(new RuntimeBase[0]); + } + + public RuntimeBase[] padConstantOwnerReferents() { + return Arrays.stream(allPadConstantValues()) + .filter(value -> !(value instanceof RuntimeScalar scalar) + || scalar.compiledDirectCallSiteName() == null) + .toArray(RuntimeBase[]::new); + } + + /** Resolve one named-call site from this optree's compiled owner table. */ + public RuntimeScalar resolveCompiledDirectCallSite( + String className, int siteIndex, String name) { + Map sites = + compiledDirectCallSitesByClassName.get(className == null ? "" : className); + CompiledDirectCallSite site = sites == null ? null : sites.get(siteIndex); + if (site == null && className == null) { + // Interpreter bytecode is emitted in a per-CV code object, while + // embedded optrees may have registered their callsites under a + // generated-class key. Recover the unique name/index entry from + // this CV's owner table when the bytecode has no class-name operand. + for (Map candidates + : compiledDirectCallSitesByClassName.values()) { + CompiledDirectCallSite candidate = candidates.get(siteIndex); + if (candidate != null && candidate.name().equals(name)) { + site = candidate; + break; + } + } + } + return site == null + ? GlobalVariable.resolveRegisteredCompiledDirectCallSite(name, siteIndex) + : site.resolve(); + } - /** - * Registry mapping generated class names to their pad constants. - * Used to transfer pad constants from compile time to runtime for anonymous subs. - */ - /** - * Clears weak references to this subroutine's pad constants. - * Called when the CODE slot of a glob is replaced, emulating Perl 5's - * behavior where replacing a sub frees its op-tree and clears weak refs - * to compile-time constants. - */ - public void clearPadConstantWeakRefs() { - if (padConstants != null) { - for (RuntimeBase constant : padConstants) { + /** JVM bytecode enters here with the currently executing CV at stack depth zero. */ + public static RuntimeScalar resolveCompiledDirectCallForActive( + String name, String className, int siteIndex) { + RuntimeCode active = getActiveCodeAt(0); + return active == null + ? GlobalVariable.resolveRegisteredCompiledDirectCallSite(name, siteIndex) + : active.resolveCompiledDirectCallSite(className, siteIndex, name); + } + + static void copyPadConstantTree( + RuntimeCode source, + RuntimeCode target, + java.util.function.Function copyValues) { + RuntimeBase[] direct = source.padConstants == null + ? null : copyValues.apply(source.padConstants); + if (source.padConstantClassName == null) { + target.installPadConstants(direct); + return; + } + Map embedded = new LinkedHashMap<>(); + source.embeddedPadConstantsForClass(source.padConstantClassName) + .forEach((name, values) -> embedded.put(name, copyValues.apply(values))); + target.installPadConstantTree(source.padConstantClassName, direct, embedded, + source.padConstantDescendantTreesForClass(source.padConstantClassName)); + } + + /** Transfer this compiled optree's constant owners to its published CV. */ + public void transferPadConstantTreeTo(RuntimeCode target) { + if (target == null || target == this + || (padConstants == null && padConstantClassName == null + && padConstantArraysByClassName.isEmpty() + && codeTemplateOwnerSlots.isEmpty())) { + return; + } + copyPadConstantTree(this, target, values -> values.clone()); + for (Map.Entry entry : codeTemplateOwnerSlots.entrySet()) { + PerlOwnerSlot previous = target.codeTemplateOwnerSlots.putIfAbsent( + entry.getKey(), entry.getValue()); + if (previous != null) entry.getValue().release(); + } + codeTemplateOwnerSlots.clear(); + clearPadConstantWeakRefs(); + } + + private void releasePadConstantOwners() { + RuntimeBase[] constants = allPadConstantValues(); + Set registryNames = new LinkedHashSet<>(padConstantRegistryClassNames); + List owners = new ArrayList<>(padConstantOwnerSlots); + owners.addAll(codeTemplateOwnerSlots.values()); + List callSites = + new ArrayList<>(compiledDirectCallSiteOwners); + padConstants = null; + padConstantClassName = null; + padConstantArraysByClassName.clear(); + padConstantDescendantsByClassName.clear(); + padConstantRegistryClassNames.clear(); + padConstantOwnerSlots.clear(); + codeTemplateOwnerSlots.clear(); + compiledDirectCallSiteOwners.clear(); + compiledDirectCallSitesByClassName.clear(); + for (CompiledDirectCallSite callSite : callSites) callSite.release(); + for (PerlOwnerSlot owner : owners) owner.release(); + Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); + for (RuntimeBase constant : constants) { + if (constant != null && seen.add(constant) + && constant.ownerSlotCount(PerlOwnerSlot.Kind.CODE_PAD_CONSTANT) == 0 + && !constant.isPerlDestroyed() + && constant.refCount <= 0) { + // A caller may retain a backslash-addressed literal through an + // uncounted scalar reference after this CV dies. Carry the + // final-release obligation onto that exact slot so its release + // clears weak observers on this final owner release. + constant.deferFinalReleaseToUncountedOwnerSlots(); + } + } + clearUnownedPadConstantWeakRefs(constants); + removeUnownedPadConstantRegistryEntries(registryNames); + } + + /** Record this optree's strong reference to a noncapturing anonymous CV template. */ + public static RuntimeScalar retainOptreeCodeTemplate( + RuntimeCode owner, RuntimeScalar codeReference) { + if (owner == null || codeReference == null + || !(codeReference.value instanceof RuntimeCode template)) { + return codeReference; + } + Object templateKey = template; + if (!owner.codeTemplateOwnerSlots.containsKey(templateKey)) { + PerlOwnerSlot slot = new PerlOwnerSlot(PerlOwnerSlot.Kind.CODE_PAD_CONSTANT); + slot.acquireCodePadConstantIdentity(template); + owner.codeTemplateOwnerSlots.put(templateKey, slot); + } + return codeReference; + } + + /** Bind an anonymous code literal to the currently executing optree. */ + public static RuntimeScalar retainActiveOptreeCodeTemplate(RuntimeScalar codeReference) { + if (codeReference != null && codeReference.value instanceof RuntimeCode template) { + template.isOptreeCodeTemplate = true; + retainOptreeCodeTemplate(getActiveCodeAt(0), codeReference); + } + return codeReference; + } + + private static void clearUnownedPadConstantWeakRefs(RuntimeBase[] constants) { + if (constants == null) return; + Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); + for (RuntimeBase constant : constants) { + if (constant != null && seen.add(constant) + && constant.ownerSlotCount(PerlOwnerSlot.Kind.CODE_PAD_CONSTANT) == 0 + && !constant.hasPerlStrongOwner()) { WeakRefRegistry.clearWeakRefsTo(constant); } } } - /** - * Return whether a readonly scalar is owned by the optree/pad of a - * currently installed named subroutine. - * - *

    Pad constants are JVM references that selective refcounting cannot - * observe. This targeted lookup lets mortal processing preserve a weak - * reference until the owning glob is replaced, when - * {@link #clearPadConstantWeakRefs()} performs Perl-compatible optree - * reaping.

    - */ - public static boolean isInstalledPadConstant(RuntimeBase target) { - if (target == null) return false; - for (RuntimeScalar codeScalar : GlobalVariable.globalCodeRefValuesView()) { - if (codeScalar == null || !(codeScalar.value instanceof RuntimeCode code) - || code.padConstants == null) { - continue; - } - for (RuntimeBase constant : code.padConstants) { - if (constant == target) return true; + private static void removeUnownedPadConstantRegistryEntries(Set classNames) { + PerlRuntime runtime = PerlRuntime.currentOrNull(); + if (runtime == null || classNames == null || classNames.isEmpty()) return; + RuntimeCodeRuntimeState state = runtime.runtimeCodeState(); + for (String className : classNames) { + RuntimeBase[] constants = state.padConstantsByClassName.get(className); + boolean stillOwned = constants != null && Arrays.stream(constants) + .filter(Objects::nonNull) + .anyMatch(constant -> constant.ownerSlotCount( + PerlOwnerSlot.Kind.CODE_PAD_CONSTANT) != 0); + if (!stillOwned) { + if (constants == null) state.padConstantsByClassName.remove(className); + else state.padConstantsByClassName.remove(className, constants); + state.embeddedPadConstantsByClassName.remove(className); + state.embeddedPadConstantDescendantsByClassName.remove(className); } } - return false; + } + + RuntimeBase[] padConstantsForClass(String className) { + return padConstantArraysByClassName.get(className); + } + + Map embeddedPadConstantsForClass(String className) { + Set descendants = padConstantDescendantsByClassName.get(className); + if (descendants == null || descendants.isEmpty()) return Collections.emptyMap(); + Map result = new LinkedHashMap<>(); + for (String descendant : descendants) { + RuntimeBase[] values = padConstantArraysByClassName.get(descendant); + if (values != null) result.put(descendant, values); + } + return result; + } + + Map> padConstantDescendantTreesForClass(String className) { + Set descendants = padConstantDescendantsByClassName.get(className); + if (descendants == null || descendants.isEmpty()) return Collections.emptyMap(); + Map> result = new LinkedHashMap<>(); + for (String descendant : descendants) { + Set nested = padConstantDescendantsByClassName.get(descendant); + if (nested != null) result.put(descendant, nested); + } + return result; + } + + Map allPadConstantArraysByClassName() { + return Collections.unmodifiableMap(padConstantArraysByClassName); + } + + Map> allPadConstantDescendantsByClassName() { + return Collections.unmodifiableMap(padConstantDescendantsByClassName); + } + + /** Release this CV's optree constant edges and clear observers after the last owner. */ + public void clearPadConstantWeakRefs() { + releasePadConstantOwners(); + } + + /** Return whether an active CODE optree owns this compiled pad constant. */ + public static boolean isInstalledPadConstant(RuntimeBase target) { + return target != null + && target.ownerSlotCount(PerlOwnerSlot.Kind.CODE_PAD_CONSTANT) != 0; } /** @@ -3561,67 +5650,93 @@ public static boolean isInstalledPadConstant(RuntimeBase target) { * captures, those are released recursively. */ public void releaseCaptures() { - if (capturedScalars != null) { - RuntimeScalar[] scalars = capturedScalars; - capturedScalars = null; // null out first to prevent re-entry - for (RuntimeScalar s : scalars) { - s.releaseClosureCapture(); - if (s.captureCount == 0) { - // If the captured scalar itself holds an unowned CODE ref with - // captures, release those recursively (handles nested closures). - // Do not recurse into CODE refs still stored elsewhere (for - // example Iterator.pm keeps a callback in %code_for while an - // eval block temporarily captures the local $code scalar). - if (s.type == RuntimeScalarType.CODE - && s.value instanceof RuntimeCode innerCode + if (hasActiveCodeOwner()) { + deferFinalReleaseToActiveCode(); + return; + } + captureReleaseRequested = false; + RetiredCaptureEdges captures = new RetiredCaptureEdges(this, Collections.emptySet()); + capturedScalars = null; + capturedScalarOwnerSlots = null; + capturedAggregates = null; + capturedAggregateOwnerSlots = null; + releaseCaptureEdges(captures); + } + + private void retireReplacedCaptureEdges(RetiredCaptureEdges captures) { + if (captures == null || captures.isEmpty()) return; + if (hasActiveCodeOwner()) { + pendingRetiredCaptureEdges.add(captures); + } else { + releaseCaptureEdges(captures); + } + } + + private void releasePendingCaptureEdges() { + if (pendingRetiredCaptureEdges.isEmpty()) return; + List pending = new ArrayList<>(pendingRetiredCaptureEdges); + pendingRetiredCaptureEdges.clear(); + for (RetiredCaptureEdges captures : pending) { + releaseCaptureEdges(captures); + } + } + + private void releaseCaptureEdges(RetiredCaptureEdges captures) { + if (captures == null || captures.isEmpty()) return; + boolean retiredEdge = false; + if (captures.scalars != null) { + RuntimeScalar[] scalars = captures.scalars; + PerlOwnerSlot[] ownerSlots = captures.scalarOwnerSlots; + for (int i = 0; i < scalars.length; i++) { + RuntimeScalar scalar = scalars[i]; + PerlOwnerSlot ownerSlot = ownerSlots != null && i < ownerSlots.length + ? ownerSlots[i] : null; + if (ownerSlot != null && captures.retainedOwnerSlots.contains(ownerSlot)) continue; + retiredEdge = true; + if (ownerSlot != null && !ownerSlot.isActive()) continue; + scalar.releaseClosureCaptureSlot(ownerSlot); + if (!scalar.hasClosureCaptureOwner()) { + if (scalar.type == RuntimeScalarType.CODE + && scalar.value instanceof RuntimeCode innerCode && innerCode.refCount <= 0) { innerCode.releaseCaptures(); } - // The captured variable's scope has exited but refCount was NOT - // decremented at that time (scopeExitCleanup returns early for - // captured variables to prevent premature clearing while the - // closure is alive). Now that the last closure is releasing this - // capture, decrement refCount to balance the original increment. - // - // Balance the captured lexical's owned reference now that the - // last closure is gone. MortalList handles the weak-ref rescue - // cases for unblessed containers whose selective refCount can - // transiently reach zero while still reachable through live CODE. - if (s.scopeExited) { - RuntimeScalar.releaseIoOwner(s); - if (s.type == RuntimeScalarType.TIED_SCALAR - && s.value instanceof TiedVariableBase tiedVariable) { + if (scalar.scopeExited) { + RuntimeScalar.releaseIoOwner(scalar); + if (scalar.type == RuntimeScalarType.TIED_SCALAR + && scalar.value instanceof TiedVariableBase tiedVariable) { tiedVariable.releaseTiedObject(); MortalList.noteDeferredCaptureMayBeReady(); continue; } - if ((s.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && s.value instanceof RuntimeBase rb - && (rb.blessId != 0 || !WeakRefRegistry.hasWeakRefsTo(rb))) { - MortalList.releaseCapturedDecrement(s); + if ((scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 + && scalar.value instanceof RuntimeBase) { + MortalList.releaseCapturedDecrement(scalar); } MortalList.noteDeferredCaptureMayBeReady(); } } } } - if (capturedAggregates != null) { - RuntimeBase[] aggregates = capturedAggregates; - capturedAggregates = null; - PerlOwnerSlot[] ownerSlots = capturedAggregateOwnerSlots; - capturedAggregateOwnerSlots = null; + if (captures.aggregates != null) { + RuntimeBase[] aggregates = captures.aggregates; + PerlOwnerSlot[] ownerSlots = captures.aggregateOwnerSlots; for (int i = 0; i < aggregates.length; i++) { RuntimeBase aggregate = aggregates[i]; + PerlOwnerSlot ownerSlot = ownerSlots != null && i < ownerSlots.length + ? ownerSlots[i] : null; + if (ownerSlot != null && captures.retainedOwnerSlots.contains(ownerSlot)) continue; + retiredEdge = true; + if (ownerSlot != null && !ownerSlot.isActive()) continue; if (aggregate != null) { - aggregate.releaseClosureCaptureOwner( - ownerSlots != null && i < ownerSlots.length - ? ownerSlots[i] : null); - } else if (ownerSlots != null && i < ownerSlots.length - && ownerSlots[i] != null) { - ownerSlots[i].release(); + aggregate.releaseClosureCaptureOwner(ownerSlot); + } else if (ownerSlot != null) { + retiredEdge = true; + ownerSlot.release(); } } } + retiredOwnedEdges |= retiredEdge; } /** @@ -3702,6 +5817,10 @@ public RuntimeCode cloneForClosure() { clone.isDeclared = this.isDeclared; clone.hasBodyDefinition = this.hasBodyDefinition; clone.constantValue = this.constantValue; + copyPadConstantTree(this, clone, values -> values.clone()); + // The closure prototype is no longer callable after this clone is + // installed. Transfer its optree edges to the callable CV. + clearPadConstantWeakRefs(); clone.lexicalVariableNames = this.lexicalVariableNames == null ? null : new java.util.LinkedHashSet<>(this.lexicalVariableNames); clone.ourVariableRegistry = this.ourVariableRegistry == null @@ -4431,9 +6550,14 @@ public static void copy(RuntimeCode code, RuntimeCode codeFrom) { code.deparseFlags = codeFrom.deparseFlags; code.deparseSourceOffset = codeFrom.deparseSourceOffset; code.deparseSourceEnd = codeFrom.deparseSourceEnd; + copyPadConstantTree(codeFrom, code, values -> values.clone()); } public void adoptDefinitionFrom(RuntimeCode codeFrom) { + // The incoming definition already owns its capture slots. Keep those + // identities while replacing the metadata, then retire the placeholder's + // obsolete edges (after any active frame that still uses them returns). + RetiredCaptureEdges replacedCaptures = new RetiredCaptureEdges(this, codeFrom); Supplier sourceCompilerSupplier = codeFrom.compilerSupplier; boolean sourceNeedsDelegation = (codeFrom instanceof InterpretedCode && this.hasForwardGlobAlias) || (sourceCompilerSupplier != null @@ -4504,6 +6628,11 @@ public void adoptDefinitionFrom(RuntimeCode codeFrom) { this.stateVariable = codeFrom.stateVariable; this.stateArray = codeFrom.stateArray; this.stateHash = codeFrom.stateHash; + this.stateAggregateAliasOwners = codeFrom.stateAggregateAliasOwners; + this.stateScalarOwnerSlots = codeFrom.stateScalarOwnerSlots; + this.stateArrayOwnerSlots = codeFrom.stateArrayOwnerSlots; + this.stateHashOwnerSlots = codeFrom.stateHashOwnerSlots; + this.stateAggregateAliasOwnerSlots = codeFrom.stateAggregateAliasOwnerSlots; this.constantValue = codeFrom.constantValue; if (sourceNeedsDelegation) { this.subroutine = (runtimeArgs, callContext) -> @@ -4515,6 +6644,7 @@ public void adoptDefinitionFrom(RuntimeCode codeFrom) { } this.__SUB__ = codeFrom.__SUB__; this.capturedScalars = codeFrom.capturedScalars; + this.capturedScalarOwnerSlots = codeFrom.capturedScalarOwnerSlots; this.capturedAggregates = codeFrom.capturedAggregates; this.captureFieldsRecorded = codeFrom.captureFieldsRecorded; this.capturedAggregateOwnerSlots = codeFrom.capturedAggregateOwnerSlots; @@ -4526,7 +6656,9 @@ public void adoptDefinitionFrom(RuntimeCode codeFrom) { this.lexicalDisabledWarningCategories = codeFrom.lexicalDisabledWarningCategories; this.ourVariableRegistry = codeFrom.ourVariableRegistry; this.declaredOurVariables = codeFrom.declaredOurVariables; - this.padConstants = codeFrom.padConstants; + copyPadConstantTree(codeFrom, this, values -> values.clone()); + rebindCaptureOwnerSlots(); + retireReplacedCaptureEdges(replacedCaptures); } /** @@ -6273,21 +8405,27 @@ public static RuntimeScalar makeCodeObject( code.deparseSourceOffset = deparseSourceOffset; code.deparseSourceEnd = deparseSourceEnd; - // Look up pad constants registered at compile time for this class. - // These track cached string literals referenced via \ inside the sub, - // needed for optree reaping (clearing weak refs when sub is replaced). + // Transfer the compiled optree's backslash-addressable constants to + // this CV so they receive owner identities with the rest of its body. String internalClassName = clazz.getName().replace('.', '/'); - String[] stableHashKeys = PerlRuntime.current().runtimeCodeState() - .stableHashMutationMethodKeysByClassName.remove(internalClassName); + RuntimeCodeRuntimeState runtimeCodeState = PerlRuntime.current().runtimeCodeState(); + String[] stableHashKeys = runtimeCodeState.stableHashMutationMethodKeysByClassName + .remove(internalClassName); if (stableHashKeys != null) { code.stableHashMutationMethodKeys = stableHashKeys; } - RuntimeBase[] padConsts = PerlRuntime.current().runtimeCodeState() - .padConstantsByClassName.remove(internalClassName); - if (padConsts != null) { - code.padConstants = padConsts; - GlobalVariable.invalidateGlobalCodeRefGraphRoots(); - } + RuntimeCode activeCode = getActiveCodeAt(0); + boolean activeCodeOwnsTree = activeCode != null + && activeCode.padConstantsForClass(internalClassName) != null; + RuntimeBase[] padConsts = activeCodeOwnsTree + ? activeCode.padConstantsForClass(internalClassName) + : runtimeCodeState.padConstantsByClassName.get(internalClassName); + Map embeddedPadConsts = activeCodeOwnsTree + ? activeCode.embeddedPadConstantsForClass(internalClassName) + : runtimeCodeState.embeddedPadConstantsByClassName.get(internalClassName); + Map> embeddedPadDescendants = activeCodeOwnsTree + ? activeCode.padConstantDescendantTreesForClass(internalClassName) + : runtimeCodeState.embeddedPadConstantDescendantsByClassName.get(internalClassName); Set disabledWarnings = PerlRuntime.current().runtimeCodeState() .disabledWarningsByClassName.get(internalClassName); code.setLexicalDisabledWarningCategories(disabledWarnings); @@ -6321,6 +8459,7 @@ public static RuntimeScalar makeCodeObject( code.captureFieldsRecorded = true; if (meta.hasCaptures()) { List captured = new ArrayList<>(); + List capturedScalarOwnerSlots = new ArrayList<>(); List capturedAggregates = new ArrayList<>(); List capturedAggregateOwnerSlots = new ArrayList<>(); Set seenScalars = Collections.newSetFromMap(new IdentityHashMap<>()); @@ -6331,7 +8470,7 @@ public static RuntimeScalar makeCodeObject( if (!seenScalars.add(capturedVar)) continue; code.putClosedOverVariable(f.getName(), capturedVar); captured.add(capturedVar); - capturedVar.retainClosureCapture(); + capturedScalarOwnerSlots.add(capturedVar.retainClosureCaptureSlot(code)); } } for (Field f : meta.capturedAggregateFields) { @@ -6340,12 +8479,14 @@ public static RuntimeScalar makeCodeObject( if (!seenAggregates.add(capturedAggregate)) continue; code.putClosedOverVariable(f.getName(), capturedAggregate); capturedAggregates.add(capturedAggregate); - PerlOwnerSlot ownerSlot = capturedAggregate.retainClosureCaptureOwner(); + PerlOwnerSlot ownerSlot = capturedAggregate.retainClosureCaptureOwner(code); capturedAggregateOwnerSlots.add(ownerSlot); } } if (!captured.isEmpty()) { code.capturedScalars = captured.toArray(new RuntimeScalar[0]); + code.capturedScalarOwnerSlots = + capturedScalarOwnerSlots.toArray(new PerlOwnerSlot[0]); } if (!capturedAggregates.isEmpty()) { code.capturedAggregates = capturedAggregates.toArray(new RuntimeBase[0]); @@ -6353,11 +8494,19 @@ public static RuntimeScalar makeCodeObject( capturedAggregateOwnerSlots.toArray(new PerlOwnerSlot[0]); } if (!captured.isEmpty() || !capturedAggregates.isEmpty()) { - code.refCount = 0; + code.startRefCountTracking(); registerJvmClosure(code); } } - GlobalVariable.invalidateGlobalCodeRefGraphRoots(); + + // Installing direct-call sites releases their compile-time CODE pins. + // That release can flush pending lifecycle work, so establish this CV's + // capture owners first. Otherwise a captured referent can reach zero + // owners between the pin release and the closure's first capture slot. + if (padConsts != null || embeddedPadConsts != null && !embeddedPadConsts.isEmpty()) { + code.installPadConstantTree(internalClassName, padConsts, + embeddedPadConsts, embeddedPadDescendants); + } // A BEGIN-installed `sub () { $lexical }` is a Perl constant CV. if ((deparseFlags & 0x40000000) != 0) { @@ -6512,7 +8661,7 @@ public static RuntimeList call(RuntimeScalar runtimeScalar, int callContext, String autoboxBindings) { try { - return call(runtimeScalar, method, currentSub, args.argumentValues(), + return call(runtimeScalar, method, currentSub, args.toRuntimeArray(), callContext, autoboxBindings); } finally { args.finish(); @@ -6528,7 +8677,7 @@ public static RuntimeList callCached(int callsiteId, int callContext) { try { return callCached(callsiteId, runtimeScalar, method, currentSub, - args.argumentValues(), callContext); + args.toRuntimeArray(), callContext); } finally { args.finish(); } @@ -6655,11 +8804,11 @@ private static RuntimeList invokeCachedMethodHit( PerlRuntime methodRuntime) { RuntimeArray args = methodArgs; String[] stableHashKeys = code.stableHashMutationMethodKeys; - boolean suppressRootTracking = callContext == RuntimeContextType.SCALAR + boolean stableMethodArgumentRecycle = callContext == RuntimeContextType.SCALAR && stableHashKeys != null && stableHashKeys.length > 0 && stableHashKeys.length <= 2 && code.autoloadVariableName == null && !DebugState.isDebugMode() - && args.suppressRootTrackingForStableMethodArguments(); + && args.enableStableMethodArgumentRecycle(); try { args.prependMethodCallInvocant(methodInvocantArgument(runtimeScalar)); @@ -6675,8 +8824,8 @@ private static RuntimeList invokeCachedMethodHit( boolean stableHashFastPath = canUseStableHashMutationMethodFastPath( code, args, callContext, methodRuntime); - if (!stableHashFastPath && suppressRootTracking) { - args.resumeMethodArgumentRootTracking(); + if (!stableHashFastPath && stableMethodArgumentRecycle) { + args.disableStableMethodArgumentRecycle(); } if (stableHashFastPath) { return invokeStableHashMutationMethodHit(code, args, callContext, methodRuntime); @@ -6686,7 +8835,7 @@ private static RuntimeList invokeCachedMethodHit( if (e instanceof RuntimeException) throw (RuntimeException) e; throw new RuntimeException(e); } finally { - if (suppressRootTracking) args.resumeMethodArgumentRootTracking(); + if (stableMethodArgumentRecycle) args.disableStableMethodArgumentRecycle(); } } @@ -6828,8 +8977,9 @@ private static RuntimeList callCachedMethodMiss( private static RuntimeList applyCachedMethod( RuntimeCode code, RuntimeArray args, int callContext, PerlRuntime cachedRuntime) { + int foreachSourceOwnerDepth = MortalList.foreachSourceOwnerDepth(); try { - return withMethodHasArgs(code, () -> { + RuntimeList result = withMethodHasArgs(code, () -> { // Preserve LVALUE here: generated code performs the callable check // from the raw context. Normalizing it first would silently turn a // forbidden lvalue method assignment into an ordinary scalar call. @@ -6840,6 +8990,7 @@ private static RuntimeList applyCachedMethod( } return code.apply(args, callContext); }); + return finishCachedMethodResult(code, callContext, result); } catch (PerlNonLocalReturnException e) { if (e.targetCode != null && e.targetCode != code) { throw e; @@ -6849,10 +9000,34 @@ private static RuntimeList applyCachedMethod( } RuntimeList result = e.returnValue != null ? e.returnValue.getList() : new RuntimeList(); - return coerceScalarCallResult( + RuntimeList returned = coerceScalarCallResult( result, effectiveCallContext(code, callContext), callContext, !isLvalueCode(code)); + return finishCachedMethodResult(code, callContext, returned); + } finally { + MortalList.restoreForeachSourceOwnerDepth(foreachSourceOwnerDepth); + } + } + + /** + * Inline method dispatch calls {@link RuntimeCode#apply(RuntimeArray, int)} + * directly, bypassing the static apply boundary that retires discarded + * results and flushes scalar-only returns. Keep the same ownership boundary + * here for ordinary method results and consumed non-local returns. + */ + private static RuntimeList finishCachedMethodResult( + RuntimeCode code, int callContext, RuntimeList result) { + if (result instanceof RuntimeControlFlowList || result == null) { + return result; + } + int effectiveContext = effectiveCallContext(code, callContext); + if (effectiveContext == RuntimeContextType.VOID) { + MortalList.mortalizeForVoidDiscard(result); + MortalList.flushAboveMark(); + } else if (containsNoReference(result)) { + MortalList.flushAboveMark(); } + return result; } /** Preserve literal immutability when a constant becomes a method's $_[0]. */ @@ -7265,10 +9440,12 @@ private static RuntimeList bindReturnedMethodCoderef( }, target.prototype); bound.packageName = target.packageName; bound.subName = target.subName; - bound.refCount = 0; + bound.startRefCountTracking(); bound.capturedScalars = new RuntimeScalar[] { new RuntimeScalar(codeRef), invocant }; - for (RuntimeScalar captured : bound.capturedScalars) { - captured.retainClosureCapture(); + bound.capturedScalarOwnerSlots = new PerlOwnerSlot[bound.capturedScalars.length]; + for (int i = 0; i < bound.capturedScalars.length; i++) { + bound.capturedScalarOwnerSlots[i] = + bound.capturedScalars[i].retainClosureCaptureSlot(bound); } registerJvmClosure(bound); return new RuntimeScalar(bound).getList(); @@ -7732,7 +9909,7 @@ public static RuntimeList callerWithSub(RuntimeList args, int ctx, RuntimeScalar RuntimeArray frameArgs = DebugState.getArgsForFrame(frame); if (frameArgs != null) { frameArgs.clearStaleLocalArrayAliases(); - dbArgs.setFromListAliased(frameArgs.getList()); + dbArgs.setFromListAliased(new RuntimeList(frameArgs.elements)); } else { dbArgs.setFromListAliased(new RuntimeList()); } @@ -7778,7 +9955,7 @@ public static RuntimeList callerWithSub(RuntimeList args, int ctx, RuntimeScalar } if (frameArgs != null) { frameArgs.clearStaleLocalArrayAliases(); - dbArgs.setFromListAliased(frameArgs.getList()); + dbArgs.setFromListAliased(new RuntimeList(frameArgs.elements)); } else { dbArgs.setFromListAliased(new RuntimeList()); } @@ -8764,6 +10941,7 @@ public static RuntimeList apply(RuntimeScalar runtimeScalar, RuntimeArray a, int RuntimeScalar curScalar = runtimeScalar; RuntimeArray curArgs = a; boolean curArgsFromTailCall = false; + TailCallArgumentOwners curTailCallArgumentOwners = null; while (true) { RuntimeScalar evalFilledLexicalForward = resolveEvalFilledLexicalForward(curScalar); @@ -8953,19 +11131,41 @@ public static RuntimeList apply(RuntimeScalar runtimeScalar, RuntimeArray a, int // the caller (e.g., bless mortal entries for method chain // temporaries like Foo->new()->method()). MortalList.pushMark(); + int temporaryRootDepth = MortalList.temporaryRootDepth(); + int foreachSourceOwnerDepth = MortalList.foreachSourceOwnerDepth(); // Holds the tailcall target if the body returns one. Populated // inside the try block; after the finally runs we loop back // to the top of apply() instead of recursing, preventing // Java-stack growth on long `goto &func` chains. RuntimeScalar nextTailCode = null; RuntimeArray nextTailArgs = null; + TailCallArgumentOwners nextTailArgumentOwners = null; boolean returnedTailCall = false; + boolean flushAfterScopeExit = false; boolean cleanupArgsAfterCall = curArgsFromTailCall; RuntimeScalar codeRefForCall = curScalar; RuntimeArray argsForCall = curArgs; try { // Cast the value to RuntimeCode and call apply() - RuntimeList result = code.apply(argsForCall, callContext); + RuntimeList result; + if (curTailCallArgumentOwners == null) { + result = code.apply(argsForCall, callContext); + } else { + ExecutionRuntimeState executionState = + PerlRuntime.current().executionState(); + executionState.pendingTailCallArgumentOwners.push( + curTailCallArgumentOwners); + try { + result = code.apply(argsForCall, callContext); + } finally { + if (!executionState.pendingTailCallArgumentOwners.isEmpty() + && executionState.pendingTailCallArgumentOwners.peek() + == curTailCallArgumentOwners) { + executionState.pendingTailCallArgumentOwners.pop(); + } + curTailCallArgumentOwners.releaseRemaining(); + } + } if (code.isSortComparator && result instanceof RuntimeControlFlowList flow) { if (flow.getControlFlowType() == ControlFlowType.TAILCALL && flow.marker.tailCallFromSortComparator) { @@ -8983,16 +11183,37 @@ public static RuntimeList apply(RuntimeScalar runtimeScalar, RuntimeArray a, int if (result instanceof RuntimeControlFlowList cfList && cfList.getControlFlowType() == ControlFlowType.TAILCALL) { returnedTailCall = true; + ControlFlowMarker marker = cfList.marker; nextTailCode = cfList.getTailCallCodeRef(); RuntimeArray tailArgs = cfList.getTailCallArgs(); nextTailArgs = tailArgs != null ? tailArgs : curArgs; + nextTailArgumentOwners = marker.argumentOwners; + // The external resolver retires ownedArgs itself after the + // replacement call. This internal trampoline transfers that + // cleanup into the argument-owner handoff so it survives until + // the next frame has adopted the argument cells. + if (marker.ownedArgs != null) { + if (nextTailArgumentOwners == null) { + nextTailArgumentOwners = new TailCallArgumentOwners( + nextTailArgs, List.of()); + } + nextTailArgumentOwners.attachOwnedArgs(marker.ownedArgs); + } // Retire only deferred owners belonging to the source // argument frame before its replacement runs. The broad // scope flush below deliberately cannot do this: it must // leave caller-owned weak-schema aliases intact. - MortalList.drainPendingTailCallArgs( - tailArgs, cfList.marker.argumentFrame, null); - MortalList.releaseLastOwnedTailCallArgs(tailArgs); + try { + MortalList.drainPendingTailCallArgs( + tailArgs, marker.argumentFrame, null); + MortalList.releaseLastOwnedTailCallArgs(tailArgs); + } finally { + // The consumed marker is transient control flow. It + // must not retain the abandoned @_ cells or pristine + // frame snapshot if a surrounding runtime root keeps + // the control-flow list alive briefly. + marker.clearTailCallHandoff(); + } // Fall through to finally; outer loop will re-enter apply() // with the new code ref. We stay inside this apply() // invocation, so enterCall/exitCall depth tracking is @@ -9023,7 +11244,12 @@ public static RuntimeList apply(RuntimeScalar runtimeScalar, RuntimeArray a, int + flow.marker.fileName + " line " + line + ".\n"); } MyVarCleanupStack.unwindTo(cleanupMark); - MortalList.flush(); + // A non-local return still transfers its value through + // the enclosing call. Its mortals cannot be drained + // until that receiving boundary has acquired them. + if (flowType != ControlFlowType.RETURN) { + MortalList.flush(); + } } // Mortal-ize blessed refs with refCount==0 in void-context calls. // These are objects that were created but never stored in a named @@ -9051,13 +11277,23 @@ public static RuntimeList apply(RuntimeScalar runtimeScalar, RuntimeArray a, int // Reference-valued results deliberately remain deferred until the // caller has materialized them into their destination. if (containsNoReference(returned)) { - MortalList.flushAboveMark(); + flushAfterScopeExit = true; } MyVarCleanupStack.releaseOrTransferSocketOwnersOnReturn( cleanupMark, returned); return returned; } } catch (PerlNonLocalReturnException e) { + // A non-local return exits this invocation even when it is + // propagated to an enclosing subroutine. Retire this frame's + // lexicals before deciding which boundary consumes the value. + try { + MyVarCleanupStack.unwindTo(cleanupMark); + } catch (RuntimeException | Error cleanupFailure) { + // The transfer stopped propagating because cleanup failed. + MortalList.restoreTemporaryRootDepth(temporaryRootDepth); + throw cleanupFailure; + } if (e.targetCode != null && e.targetCode != code) { throw e; } @@ -9068,37 +11304,65 @@ public static RuntimeList apply(RuntimeScalar runtimeScalar, RuntimeArray a, int // Consume at normal subroutine and eval-block boundaries. // Perl treats `return` inside eval { ... } as the eval value, // including when it originates from a nested map/grep block. - RuntimeList result = e.returnValue != null ? e.returnValue.getList() : new RuntimeList(); - return coerceScalarCallResult(result, effectiveContext, callContext, !isLvalueCode(code)); + try { + RuntimeList result = e.returnValue != null ? e.returnValue.getList() : new RuntimeList(); + RuntimeList returned = coerceScalarCallResult( + result, effectiveContext, callContext, !isLvalueCode(code)); + if (effectiveContext == RuntimeContextType.VOID) { + MortalList.mortalizeForVoidDiscard(returned); + flushAfterScopeExit = true; + } else if (containsNoReference(returned)) { + flushAfterScopeExit = true; + } + MyVarCleanupStack.releaseOrTransferSocketOwnersOnReturn( + cleanupMark, returned); + return returned; + } finally { + // The matching frame has materialized the transfer into + // its outgoing return slots. Trim roots only after that + // ownership is established, before the frame's final flush. + MortalList.restoreTemporaryRootDepth(temporaryRootDepth); + } } catch (RuntimeException e) { - e = WarnDie.maybeInvokeUnhandledDieHandler(e); - // On die: run scopeExitCleanup for my-variables whose normal - // SCOPE_EXIT_CLEANUP bytecodes were skipped by the exception. - // PerlExitException (exit()) is excluded — global destruction handles it. - if (!(e instanceof PerlExitException) - && !(e instanceof PerlThreadExitException)) { - MyVarCleanupStack.unwindTo(cleanupMark); - MortalList.flush(); + try { + e = WarnDie.maybeInvokeUnhandledDieHandler(e); + // On die: run scopeExitCleanup for my-variables whose normal + // SCOPE_EXIT_CLEANUP bytecodes were skipped by the exception. + // PerlExitException (exit()) is excluded — global destruction handles it. + if (!(e instanceof PerlExitException) + && !(e instanceof PerlThreadExitException)) { + MyVarCleanupStack.unwindTo(cleanupMark); + MortalList.flush(); + } + } finally { + // A generated return block can install a temporary root + // before lexical cleanup. If cleanup itself throws, its + // normal emitted pop is skipped; do not leak that root + // into the caller's later object-GC checks. + MortalList.restoreTemporaryRootDepth(temporaryRootDepth); } throw e; } finally { if (returnedTailCall) { - // A goto &sub retires this frame before the replacement - // executes. Drain only this frame's scope exits, not the - // caller's deferred coderef metadata. - MortalList.flushAboveMark(); + flushAfterScopeExit = true; } if (cleanupArgsAfterCall) { cleanupTailCallArgs(argsForCall); cleanupTailCallCodeRef(codeRefForCall); } - // Pop the function-scoped mortal mark. Entries added by this - // function's scope-exit cleanup "fall" to the caller's scope - // and will be processed by the caller's flushAboveMark(). - MortalList.popMark(); - // After unwindTo, entries are already removed; popMark is a no-op. - // On normal return, popMark discards registrations without cleanup. - MyVarCleanupStack.popMark(cleanupMark); + if (flushAfterScopeExit) { + // Release the frame's lexical owners before processing the + // decrements they queued, so a stale registration cannot + // keep an explicitly returned capture alive. + MyVarCleanupStack.popMark(cleanupMark); + MortalList.flushAboveMark(); + MortalList.popMark(); + } else { + // Entries added by ordinary scope exit fall to the caller. + MortalList.popMark(); + MyVarCleanupStack.popMark(cleanupMark); + } + MortalList.restoreForeachSourceOwnerDepth(foreachSourceOwnerDepth); WarningBitsRegistry.setCallSiteHints(compilationState, callerCallSiteHints); WarningBitsRegistry.setCallSiteBits(callerCallSiteWarningBits); HintHashRegistry.popCallerHintHash(compilationState); @@ -9127,6 +11391,7 @@ public static RuntimeList apply(RuntimeScalar runtimeScalar, RuntimeArray a, int curScalar = nextTailCode; curArgs = nextTailArgs; curArgsFromTailCall = true; + curTailCallArgumentOwners = nextTailArgumentOwners; continue; } @@ -9575,11 +11840,39 @@ public static RuntimeScalar tryDirectLeafIntegerAddition(RuntimeScalar runtimeSc } // Method to apply (execute) a subroutine reference using native array for parameters - /** Invoke a generated direct call while retaining its Perl source callsite. */ + private static RuntimeList applyDirectCallWithStagedArguments( + RuntimeScalar runtimeScalar, String subroutineName, + CallArguments stagedArguments, int callContext) { + try { + return apply(runtimeScalar, subroutineName, + (RuntimeBase) stagedArguments.toRuntimeArray(), callContext); + } finally { + stagedArguments.finish(); + } + } + + /** Compatibility entry for callers which already evaluated a native argument array. */ public static RuntimeList applyAtLocation(RuntimeScalar runtimeScalar, String subroutineName, RuntimeBase[] args, int callContext, String callerPackage, String callerFile, int callerLine) { + CallArguments stagedArguments = newCallArguments(args.length); + try { + for (RuntimeBase arg : args) { + stagedArguments.add(arg); + } + return applyAtLocation(runtimeScalar, subroutineName, stagedArguments, + callContext, callerPackage, callerFile, callerLine); + } finally { + stagedArguments.finish(); + } + } + + /** Invoke a generated direct call while retaining its Perl source callsite. */ + public static RuntimeList applyAtLocation(RuntimeScalar runtimeScalar, String subroutineName, + CallArguments args, int callContext, + String callerPackage, String callerFile, + int callerLine) { ExecutionRuntimeState executionState = PerlRuntime.current().executionState(); String pkg = callerPackage == null ? "main" : callerPackage; CallerStack.CallerInfo directCallSite = @@ -9597,7 +11890,8 @@ public static RuntimeList applyAtLocation(RuntimeScalar runtimeScalar, String su || "%".equals(code.signatureSlurpySigil)); if (!needsSignatureLocation) { try { - return apply(resolved, subroutineName, args, callContext); + return applyDirectCallWithStagedArguments( + resolved, subroutineName, args, callContext); } finally { if (executionState.pendingDirectCallSites.peek() == directCallSite) { executionState.pendingDirectCallSites.pop(); @@ -9607,7 +11901,8 @@ public static RuntimeList applyAtLocation(RuntimeScalar runtimeScalar, String su pushSignatureValidationCallerFrame(pkg, callerFile, callerLine); try { - return apply(resolved, subroutineName, args, callContext); + return applyDirectCallWithStagedArguments( + resolved, subroutineName, args, callContext); } finally { popSignatureValidationCallerFrame(); if (executionState.pendingDirectCallSites.peek() == directCallSite) { @@ -9640,7 +11935,6 @@ public static RuntimeList apply(RuntimeScalar runtimeScalar, String subroutineNa // Check if the type of this RuntimeScalar is CODE if (runtimeScalar.type == RuntimeScalarType.CODE) { - // Transform the native array to RuntimeArray of aliases (Perl variable `@_`) RuntimeArray a = new RuntimeArray(args.length); for (RuntimeBase arg : args) { @@ -9746,23 +12040,34 @@ public static RuntimeList apply(RuntimeScalar runtimeScalar, String subroutineNa int cleanupMark = MyVarCleanupStack.pushMark(); MortalList.pushMark(); boolean returnedTailCall = false; + boolean flushAfterScopeExit = false; try { // Cast the value to RuntimeCode and call apply() RuntimeList result = code.apply(subroutineName, a, callContext); returnedTailCall = result instanceof RuntimeControlFlowList cfList && cfList.getControlFlowType() == ControlFlowType.TAILCALL; + if (result instanceof RuntimeControlFlowList flow + && flow.getControlFlowType() != ControlFlowType.TAILCALL) { + MyVarCleanupStack.unwindTo(cleanupMark); + if (flow.getControlFlowType() != ControlFlowType.RETURN) { + MortalList.flush(); + } + } // Flush deferred DESTROY decrements for void-context calls. // See the 3-arg apply() overload for detailed rationale. if (effectiveContext == RuntimeContextType.VOID) { MortalList.mortalizeForVoidDiscard(result); - MortalList.flushAboveMark(); + flushAfterScopeExit = true; } else if (containsNoReference(result)) { - MortalList.flushAboveMark(); + flushAfterScopeExit = true; } MyVarCleanupStack.releaseOrTransferSocketOwnersOnReturn( cleanupMark, result); return result; } catch (PerlNonLocalReturnException e) { + // The exception unwinds this Perl frame even when it is + // only being relayed to the frame that owns the return. + MyVarCleanupStack.unwindTo(cleanupMark); if (e.targetCode != null && e.targetCode != code) { throw e; } @@ -9772,7 +12077,15 @@ public static RuntimeList apply(RuntimeScalar runtimeScalar, String subroutineNa } // Consume at normal subroutine and eval-block boundaries. RuntimeList result = e.returnValue != null ? e.returnValue.getList() : new RuntimeList(); - return coerceScalarCallResult(result, effectiveContext, callContext, !isLvalueCode(code)); + RuntimeList returned = coerceScalarCallResult( + result, effectiveContext, callContext, !isLvalueCode(code)); + if (effectiveContext == RuntimeContextType.VOID + || containsNoReference(returned)) { + flushAfterScopeExit = true; + } + MyVarCleanupStack.releaseOrTransferSocketOwnersOnReturn( + cleanupMark, returned); + return returned; } catch (RuntimeException e) { e = WarnDie.maybeInvokeUnhandledDieHandler(e); if (!(e instanceof PerlExitException)) { @@ -9782,14 +12095,25 @@ public static RuntimeList apply(RuntimeScalar runtimeScalar, String subroutineNa throw e; } finally { if (returnedTailCall) { - MortalList.flushAboveMark(); + flushAfterScopeExit = true; } if ("tailcall".equals(subroutineName)) { cleanupTailCallArgs(a); cleanupTailCallCodeRef(runtimeScalar); } - MortalList.popMark(); - MyVarCleanupStack.popMark(cleanupMark); + if (flushAfterScopeExit) { + // Drain return-path decrements only after the callee's + // lexical registrations are gone. Otherwise a captured + // blessed referent can be counted as a live lexical + // owner during this flush and survive until the + // deferred scope-exit cleanup. + MyVarCleanupStack.popMark(cleanupMark); + MortalList.flushAboveMark(); + MortalList.popMark(); + } else { + MortalList.popMark(); + MyVarCleanupStack.popMark(cleanupMark); + } WarningBitsRegistry.setCallSiteHints(compilationState, callerCallSiteHints); WarningBitsRegistry.setCallSiteBits(callerCallSiteWarningBits); HintHashRegistry.popCallerHintHash(compilationState); @@ -9908,7 +12232,8 @@ public static RuntimeList apply(RuntimeScalar runtimeScalar, CallArguments args, int callContext) { try { - return apply(runtimeScalar, subroutineName, args.argumentValues(), callContext); + return apply(runtimeScalar, subroutineName, + (RuntimeBase) args.toRuntimeArray(), callContext); } finally { args.finish(); } @@ -9930,11 +12255,15 @@ public static RuntimeList apply(RuntimeScalar runtimeScalar, public static RuntimeList resolveTailCalls(RuntimeList result, int callContext) { while (result instanceof RuntimeControlFlowList cfList && cfList.getControlFlowType() == ControlFlowType.TAILCALL) { - RuntimeScalar codeRef = cfList.getTailCallCodeRef(); - RuntimeArray args = cfList.getTailCallArgs(); + ControlFlowMarker marker = cfList.marker; + RuntimeScalar tailCodeRef = cfList.getTailCallCodeRef(); + RuntimeScalar codeRef = tailCodeRef; + RuntimeArray args = cfList.getTailCallArgs(); // args may theoretically be null (defensive); treat as empty args list RuntimeArray tailArgs = args != null ? args : new RuntimeArray(); - String namedTarget = cfList.marker.namedTarget; + Object argumentFrame = marker.argumentFrame; + RuntimeArray ownedArgs = marker.ownedArgs; + String namedTarget = marker.namedTarget; if (namedTarget != null) { codeRef = GlobalVariable.getGlobalCodeRefForFreshLookup(namedTarget); // A fresh missing stash entry can be represented either by an @@ -9945,34 +12274,58 @@ public static RuntimeList resolveTailCalls(RuntimeList result, int callContext) && codeRef.value instanceof RuntimeCode code && hasAutoload(code); if (!isCodeDefined(codeRef) && !hasTargetAutoload) { - cleanupTailCallArgs(cfList.marker.ownedArgs); - cleanupTailCallCodeRef(cfList.getTailCallCodeRef()); + try { + cleanupTailCallArgs(ownedArgs); + cleanupTailCallCodeRef(tailCodeRef); + } finally { + marker.clearTailCallHandoff(); + } throw new PerlCompilerException("Goto undefined subroutine &" + namedTarget - + " at " + cfList.marker.fileName + " line " + cfList.marker.lineNumber); + + " at " + marker.fileName + " line " + marker.lineNumber); } } try { if (isCurrentSortComparatorBlock() - && cfList.marker.tailCallFromSortComparator) { + && marker.tailCallFromSortComparator) { throw sortTailCallError(); } - if (cfList.marker.evalScope != null) { - throw new PerlCompilerException("Can't goto subroutine from an " + cfList.marker.evalScope); + if (marker.evalScope != null) { + throw new PerlCompilerException("Can't goto subroutine from an " + marker.evalScope); + } + TailCallArgumentOwners argumentOwners = marker.argumentOwners; + ExecutionRuntimeState executionState = + PerlRuntime.current().executionState(); + executionState.pendingTailCallArgumentOwners.push(argumentOwners); + try { + result = apply(codeRef, "tailcall", tailArgs, callContext); + } finally { + if (!executionState.pendingTailCallArgumentOwners.isEmpty() + && executionState.pendingTailCallArgumentOwners.peek() + == argumentOwners) { + executionState.pendingTailCallArgumentOwners.pop(); + } + argumentOwners.releaseRemaining(); } - result = apply(codeRef, "tailcall", tailArgs, callContext); } catch (RuntimeException e) { - cleanupTailCallArgs(cfList.marker.ownedArgs); - cleanupTailCallCodeRef(cfList.getTailCallCodeRef()); + try { + cleanupTailCallArgs(ownedArgs); + cleanupTailCallCodeRef(tailCodeRef); + } finally { + marker.clearTailCallHandoff(); + } throw e; } // Drain only queued decrements whose original owner is an alias // in the abandoned source @_ frame. This keeps caller-owned // referents (including DBIC schema aliases) out of the handoff. - MortalList.drainPendingTailCallArgs( - cfList.getTailCallArgs(), cfList.marker.argumentFrame, result); - MortalList.releaseLastOwnedTailCallArgs(cfList.getTailCallArgs()); - cleanupTailCallArgs(cfList.marker.ownedArgs); - cleanupTailCallCodeRef(cfList.getTailCallCodeRef()); + try { + MortalList.drainPendingTailCallArgs(tailArgs, argumentFrame, result); + MortalList.releaseLastOwnedTailCallArgs(tailArgs); + cleanupTailCallArgs(ownedArgs); + cleanupTailCallCodeRef(tailCodeRef); + } finally { + marker.clearTailCallHandoff(); + } } return result; } @@ -9990,20 +12343,24 @@ public static void cleanupTailCallCodeRef(RuntimeScalar tailCodeRef) { // Method to apply (execute) a subroutine reference (legacy method for compatibility) public static RuntimeList apply(RuntimeScalar runtimeScalar, String subroutineName, RuntimeBase list, int callContext) { - - // If this is a tail-call trampoline re-entry (emitted by the JVM bytecode - // trampoline for `goto &sub`), mark it so enterCall/exitCall skip depth - // tracking. See enterCall() / inTailCallTrampoline for the rationale. - boolean isTailCall = "tailcall".equals(subroutineName); - if (isTailCall) { - PerlRuntime.current().executionState().tailCallTrampolineDepth++; - try { - return applyImpl(runtimeScalar, subroutineName, list, callContext); - } finally { - PerlRuntime.current().executionState().tailCallTrampolineDepth--; + int foreachSourceOwnerDepth = MortalList.foreachSourceOwnerDepth(); + try { + // If this is a tail-call trampoline re-entry (emitted by the JVM bytecode + // trampoline for `goto &sub`), mark it so enterCall/exitCall skip depth + // tracking. See enterCall() / inTailCallTrampoline for the rationale. + boolean isTailCall = "tailcall".equals(subroutineName); + if (isTailCall) { + PerlRuntime.current().executionState().tailCallTrampolineDepth++; + try { + return applyImpl(runtimeScalar, subroutineName, list, callContext); + } finally { + PerlRuntime.current().executionState().tailCallTrampolineDepth--; + } } + return applyImpl(runtimeScalar, subroutineName, list, callContext); + } finally { + MortalList.restoreForeachSourceOwnerDepth(foreachSourceOwnerDepth); } - return applyImpl(runtimeScalar, subroutineName, list, callContext); } private static RuntimeList applyImpl(RuntimeScalar runtimeScalar, String subroutineName, RuntimeBase list, int callContext) { @@ -10128,6 +12485,13 @@ private static RuntimeList applyImpl(RuntimeScalar runtimeScalar, String subrout RuntimeList result = code.apply(subroutineName, a, callContext); returnedTailCall = result instanceof RuntimeControlFlowList cfList && cfList.getControlFlowType() == ControlFlowType.TAILCALL; + if (result instanceof RuntimeControlFlowList flow + && flow.getControlFlowType() != ControlFlowType.TAILCALL) { + MyVarCleanupStack.unwindTo(cleanupMark); + if (flow.getControlFlowType() != ControlFlowType.RETURN) { + MortalList.flushAboveMark(); + } + } // Flush deferred DESTROY decrements for void-context calls. // See the 3-arg apply() overload for detailed rationale. if (effectiveContext == RuntimeContextType.VOID) { @@ -10138,6 +12502,7 @@ private static RuntimeList applyImpl(RuntimeScalar runtimeScalar, String subrout } return result; } catch (PerlNonLocalReturnException e) { + MyVarCleanupStack.unwindTo(cleanupMark); if (e.targetCode != null && e.targetCode != code) { throw e; } @@ -10147,7 +12512,15 @@ private static RuntimeList applyImpl(RuntimeScalar runtimeScalar, String subrout } // Consume at normal subroutine and eval-block boundaries. RuntimeList result = e.returnValue != null ? e.returnValue.getList() : new RuntimeList(); - return coerceScalarCallResult(result, effectiveContext, callContext, !isLvalueCode(code)); + RuntimeList returned = coerceScalarCallResult( + result, effectiveContext, callContext, !isLvalueCode(code)); + if (effectiveContext == RuntimeContextType.VOID + || containsNoReference(returned)) { + MortalList.flushAboveMark(); + } + MyVarCleanupStack.releaseOrTransferSocketOwnersOnReturn( + cleanupMark, returned); + return returned; } catch (RuntimeException e) { e = WarnDie.maybeInvokeUnhandledDieHandler(e); if (!(e instanceof PerlExitException)) { @@ -10332,8 +12705,10 @@ public static RuntimeScalar createCodeReference(RuntimeScalar runtimeScalar, Str placeholder.requiresForwardGlobAliasGroup = true; placeholder.forwardGlobAliases.add(placeholder); placeholder.lexicalForwardGlobPlaceholder = true; - runtimeScalar.type = RuntimeScalarType.CODE; - runtimeScalar.value = placeholder; + // Promotion of the lexical cell is a real CODE reference store. + // Route it through the scalar transition so its current lexical or + // state-slot owner is attached to the placeholder CV. + runtimeScalar.set(new RuntimeScalar(placeholder)); return runtimeScalar; } @@ -10652,25 +13027,43 @@ public static RuntimeScalar materializeBlockResult(RuntimeScalar result) { * aliasing its former storage when it crosses the do-block boundary. */ public static RuntimeScalar copyDoBlockResult(RuntimeScalar result) { + if ((result.type & RuntimeScalarType.REFERENCE_BIT) != 0) { + return RuntimeScalar.copyToMortalReturnSlot(result); + } return new RuntimeScalar(result); } /** Copy a do-block result used in list context without collapsing the list. */ public static RuntimeBase copyDoBlockListResult(RuntimeBase result) { if (result instanceof RuntimeScalar scalar) { - return new RuntimeScalar(scalar); + return copyDoBlockScalarResult(scalar); + } + if (result instanceof RuntimeCode code) { + return RuntimeScalar.copyToMortalReturnSlot(new RuntimeScalar(code)); } if (result instanceof RuntimeList list) { RuntimeList copy = new RuntimeList(); for (RuntimeBase element : list.elements) { - copy.elements.add(element instanceof RuntimeScalar scalar - ? new RuntimeScalar(scalar) : element); + if (element instanceof RuntimeScalar scalar) { + copy.elements.add(copyDoBlockScalarResult(scalar)); + } else if (element instanceof RuntimeCode code) { + copy.elements.add(RuntimeScalar.copyToMortalReturnSlot( + new RuntimeScalar(code))); + } else { + copy.elements.add(element); + } } return copy; } return result; } + private static RuntimeScalar copyDoBlockScalarResult(RuntimeScalar scalar) { + return (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 + ? RuntimeScalar.copyToMortalReturnSlot(scalar) + : new RuntimeScalar(scalar); + } + public boolean defined() { // Built-in operators are always considered "defined" if (this.isBuiltin) { @@ -10971,6 +13364,7 @@ private RuntimeList apply(RuntimeArray a, int callContext, PerlRuntime cachedRun JvmClosureFrame closureFrame = jvmClosureFrameRequired ? pushJvmClosureFrame() : null; boolean signatureCall = enterSignatureCall(); + int cleanupMark = MyVarCleanupStack.pushMark(executionState); try { validateNamedSignatureArguments(a); if (!signatureNamedParams.isEmpty() || "%".equals(signatureSlurpySigil)) { @@ -10985,6 +13379,13 @@ private RuntimeList apply(RuntimeArray a, int callContext, PerlRuntime cachedRun } else { result = (RuntimeList) this.methodHandle.invoke(this.codeObject, a, effectiveContext); } + if (result instanceof RuntimeControlFlowList flow + && flow.getControlFlowType() != ControlFlowType.TAILCALL) { + // A non-local loop transfer can leave this generated CV + // through a returned marker instead of an exception. Retire + // its locals before finally discards the cleanup-stack mark. + MyVarCleanupStack.unwindTo(cleanupMark, executionState); + } RuntimeList returned = detachTryExpressionLvalueResult( coerceScalarCallResult(result, effectiveContext, callContext, !isLvalueCode(this)), callContext); @@ -10992,7 +13393,14 @@ private RuntimeList apply(RuntimeArray a, int callContext, PerlRuntime cachedRun protectReturnedJvmClosures(closureFrame, returned); } return returned; + } catch (PerlNonLocalReturnException e) { + MyVarCleanupStack.unwindTo(cleanupMark, executionState); + throw e; } catch (RuntimeException e) { + if (!(e instanceof PerlExitException)) { + MyVarCleanupStack.unwindTo(cleanupMark, executionState); + MortalList.flush(); + } throw WarnDie.maybeInvokeUnhandledDieHandler(e); } finally { exitSignatureCall(signatureCall); @@ -11002,12 +13410,16 @@ private RuntimeList apply(RuntimeArray a, int callContext, PerlRuntime cachedRun if (warningBits != null) { WarningBitsRegistry.popCurrent(compilationState); } + if (executionState.myVarCleanupStack.size() > cleanupMark) { + MyVarCleanupStack.popMark(cleanupMark, executionState); + } exitCall(executionState); if (closureFrame != null) { popJvmClosureFrame(closureFrame); } - popActiveCode(this, executionState); + popActiveCode(this, executionState, runtime.lifecycleState); popArgs(executionState); // also pops hasArgsStack — see popArgs() implementation + finishActiveCodeOwnerRelease(); if (DebugState.isDebugMode()) { DebugHooks.exitSubroutine(); DebugState.popArgs(); @@ -11146,6 +13558,9 @@ public RuntimeList apply(String subroutineName, RuntimeArray a, int callContext) JvmClosureFrame closureFrame = jvmClosureFrameRequired ? pushJvmClosureFrame() : null; boolean signatureCall = enterSignatureCall(); + // This overload can bind a callback to another PerlRuntime above. + // Keep the mark here so its lexicals unwind before that binding ends. + int cleanupMark = MyVarCleanupStack.pushMark(); try { validateNamedSignatureArguments(a); if (!signatureNamedParams.isEmpty() || "%".equals(signatureSlurpySigil)) { @@ -11160,6 +13575,13 @@ public RuntimeList apply(String subroutineName, RuntimeArray a, int callContext) } else { result = (RuntimeList) this.methodHandle.invoke(this.codeObject, a, effectiveContext); } + if (result instanceof RuntimeControlFlowList flow + && flow.getControlFlowType() != ControlFlowType.TAILCALL) { + // This named-call overload is used by generated direct calls. + // A non-local loop transfer can return a marker through the + // generated CV, bypassing its ordinary scope teardown. + MyVarCleanupStack.unwindTo(cleanupMark); + } RuntimeList returned = detachTryExpressionLvalueResult( coerceScalarCallResult(result, effectiveContext, callContext, !isLvalueCode(this)), callContext); @@ -11167,7 +13589,14 @@ public RuntimeList apply(String subroutineName, RuntimeArray a, int callContext) protectReturnedJvmClosures(closureFrame, returned); } return returned; + } catch (PerlNonLocalReturnException e) { + MyVarCleanupStack.unwindTo(cleanupMark); + throw e; } catch (RuntimeException e) { + if (!(e instanceof PerlExitException)) { + MyVarCleanupStack.unwindTo(cleanupMark); + MortalList.flush(); + } throw WarnDie.maybeInvokeUnhandledDieHandler(e); } finally { exitSignatureCall(signatureCall); @@ -11178,12 +13607,14 @@ public RuntimeList apply(String subroutineName, RuntimeArray a, int callContext) if (warningBits != null) { WarningBitsRegistry.popCurrent(); } + MyVarCleanupStack.popMark(cleanupMark); exitCall(); if (closureFrame != null) { popJvmClosureFrame(closureFrame); } popActiveCode(this); popArgs(); // also pops hasArgsStack — see popArgs() implementation + finishActiveCodeOwnerRelease(); if (DebugState.isDebugMode()) { DebugHooks.exitSubroutine(); DebugState.popArgs(); diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeRuntimeState.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeRuntimeState.java index 7999d9ace6..a4f0966855 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeRuntimeState.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeRuntimeState.java @@ -33,6 +33,10 @@ public final class RuntimeCodeRuntimeState { new ConcurrentHashMap<>(); final ConcurrentHashMap stableHashMutationMethodKeysByClassName = new ConcurrentHashMap<>(); + final ConcurrentHashMap> embeddedPadConstantsByClassName = + new ConcurrentHashMap<>(); + final ConcurrentHashMap>> embeddedPadConstantDescendantsByClassName = + new ConcurrentHashMap<>(); final ConcurrentHashMap> disabledWarningsByClassName = new ConcurrentHashMap<>(); @@ -152,6 +156,8 @@ void clearCaches() { evalContexts.clear(); padConstantsByClassName.clear(); stableHashMutationMethodKeysByClassName.clear(); + embeddedPadConstantsByClassName.clear(); + embeddedPadConstantDescendantsByClassName.clear(); disabledWarningsByClassName.clear(); nextMethodCallsiteId = 0; clearInlineMethodCache(); diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeControlFlowList.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeControlFlowList.java index afc8e95787..ebfde14f0a 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeControlFlowList.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeControlFlowList.java @@ -134,7 +134,8 @@ public RuntimeControlFlowList(RuntimeScalar codeRef, RuntimeArray args, String f private static RuntimeScalar retainTailCallCodeRef(RuntimeScalar codeRef) { RuntimeScalar retained = new RuntimeScalar(codeRef); - RuntimeScalar.incrementRefCountForContainerStore(retained); + RuntimeScalar.incrementRefCountForContainerStore( + retained, PerlOwnerSlot.Kind.ARGUMENT_VALUE); return retained; } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeGlob.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeGlob.java index 42abafa58d..a83ae66985 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeGlob.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeGlob.java @@ -5,6 +5,7 @@ import org.perlonjava.runtime.mro.InheritanceResolver; import org.perlonjava.runtime.operators.WarnDie; +import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -18,6 +19,29 @@ * This class provides methods to manipulate and interact with typeglobs in the runtime environment. */ public class RuntimeGlob extends RuntimeScalar implements RuntimeScalarReference { + void replaceIOScalar(RuntimeScalar next) { + if (IO == next) return; + retainedIoGlob = null; + IO = next; + } + + /** Install a tied wrapper into the existing IO cell. */ + public void setTiedIOHandle(TieHandle handle) { + if (IO == null) IO = new RuntimeScalar(); + installTiedIOHandle(IO, handle); + } + + /** Install a tied wrapper into an aliased IO cell. */ + public static void installTiedIOHandle(RuntimeScalar ioCell, TieHandle handle) { + if (ioCell == null) return; + ioCell.type = RuntimeScalarType.TIED_SCALAR; + ioCell.value = handle; + } + + private void setLocalizedOriginalIO(RuntimeScalar next) { + localizedOriginalIO = next; + } + /** * Select the value assigned to a typeglob. A direct array expression is * consumed as a list here (not as the array's scalar element count), which @@ -140,6 +164,8 @@ private static boolean isUnderscoreGlobName(String name) { // did not exist at copy time. A later `%{*$copy}` should vivify/share the // canonical GV hash, matching Perl's behavior for globs passed through @_. private boolean hashSlotAliasesNamedGlob; + /** Owner identities for slots retained by a detached typeglob snapshot. */ + private List detachedComponentOwnerSlots; // Dynamic name override set by `*foo = $string` glob-as-scalar assignment. // Used to honor the `local *PKG::__ANON__ = 'name'` idiom (see SUPER.pm, // Try::Tiny, namespace::clean) — caller()/Sub::Util::subname report this @@ -147,12 +173,17 @@ private static boolean isUnderscoreGlobName(String name) { // See dev/modules/anon_sub_naming.md. public String nameOverride; - /** Number of scalar wrappers currently pointing at this anonymous IO glob. */ - public int ioHolderCount = 0; + /** Number of active scalar owner identities retaining this anonymous IO glob. */ + public int ioHolderCount() { + return ownerSlotCount(PerlOwnerSlot.Kind.IO_RESOURCE_HOLDER); + } /** True when this glob's current IO was created by accept(). */ public boolean acceptedSocket; + /** True for the generated Symbol::GEN globs, which are not stash slots. */ + public boolean symbolGensym; + /** * Constructor for RuntimeGlob. * Initializes a new instance of the RuntimeGlob class with the specified glob name. @@ -213,8 +244,13 @@ private static boolean isHintsGlobName(String name) { public RuntimeGlob createDetachedCopy() { RuntimeGlob copy = new RuntimeGlob(this.globName); copy.stringificationName = this.stringificationName; + copy.symbolGensym = this.symbolGensym; copy.slotSnapshot = true; - copy.IO = this.IO; // Share the current IO reference + copy.replaceIOScalar(this.IO); // Share the current IO reference + if (this.namespaceMove != null) { + copy.retainDetachedNamespaceComponents(this.namespaceMove); + return copy; + } // A copied typeglob retains the CODE slot that was visible when it was // copied. This matters for `my $glob = *name; undef *name; &$glob`. // Snapshot the container as well as its CV. `undef *name` clears the @@ -229,11 +265,14 @@ public RuntimeGlob createDetachedCopy() { } copy.codeSlot = new RuntimeScalar(visibleCode != null ? visibleCode : GlobalVariable.getGlobalCodeRef(this.globName)); - copy.scalarSlot = GlobalVariable.scalarSlots().get(this.globName); + copy.scalarSlot = symbolGensym + ? this.scalarSlot : GlobalVariable.scalarSlots().get(this.globName); if (copy.scalarSlot == null) { copy.scalarSlot = new RuntimeScalar(); } - if (GlobalVariable.existsGlobalArray(this.globName)) { + if (symbolGensym) { + copy.arraySlot = this.arraySlot; + } else if (GlobalVariable.existsGlobalArray(this.globName)) { copy.arraySlot = GlobalVariable.getGlobalArray(this.globName); } if (this.hashSlot != null) { @@ -242,11 +281,14 @@ public RuntimeGlob createDetachedCopy() { && GlobalVariable.peekGlobalIO(this.globName) == this) { copy.hashSlotAliasesNamedGlob = true; } + } else if (symbolGensym) { + copy.hashSlot = this.hashSlot; } else if (GlobalVariable.existsGlobalHash(this.globName) || isStashGlobName(this.globName)) { copy.hashSlot = GlobalVariable.getGlobalHash(this.globName); } else if (GlobalVariable.peekGlobalIO(this.globName) == this) { copy.hashSlotAliasesNamedGlob = true; } + copy.retainDetachedComponentOwners(); return copy; } @@ -275,15 +317,85 @@ public static RuntimeGlob createDetachedWithSlots( glob.hashSlot = hash; glob.codeSlot = code; if (io != null) { - glob.IO = io.IO; + glob.replaceIOScalar(io.IO); } + glob.retainDetachedComponentOwners(); return glob; } + private void retainDetachedComponentOwners() { + retainDetachedComponentOwner(scalarSlot); + retainDetachedComponentOwner(arraySlot); + retainDetachedComponentOwner(hashSlot); + retainDetachedComponentOwner(codeSlot); + if (IO != null && IO != this) retainDetachedComponentOwner(IO); + } + + private void retainDetachedNamespaceComponents(NamespaceMove move) { + namespaceMove = move; + for (RuntimeScalar scalar : move.scalars.values()) { + retainDetachedComponentOwner(scalar); + } + for (RuntimeArray array : move.arrays.values()) { + retainDetachedComponentOwner(array); + } + for (RuntimeHash hash : move.hashes.values()) { + retainDetachedComponentOwner(hash); + } + for (RuntimeScalar code : move.codes.values()) { + retainDetachedComponentOwner(code); + } + } + + private void retainDetachedComponentOwner(RuntimeBase component) { + if (component == null) return; + PerlOwnerSlot ownerSlot = new PerlOwnerSlot(PerlOwnerSlot.Kind.GLOB_COMPONENT_SLOT); + ownerSlot.acquireGlobComponentIdentity(this, component); + if (detachedComponentOwnerSlots == null) detachedComponentOwnerSlots = new java.util.ArrayList<>(); + detachedComponentOwnerSlots.add(ownerSlot); + } + + boolean retainsDetachedComponents() { + return detachedComponentOwnerSlots != null && !detachedComponentOwnerSlots.isEmpty(); + } + + /** Release snapshot slots when the final scalar value owner leaves this glob. */ + synchronized void releaseDetachedComponentsIfUnowned() { + if (!retainsDetachedComponents() + || ownerSlotCount(PerlOwnerSlot.Kind.GLOB_VALUE) != 0 + || ownerSlotCount(PerlOwnerSlot.Kind.STASH_NAMESPACE_MOVE) != 0) return; + List owners = detachedComponentOwnerSlots; + detachedComponentOwnerSlots = null; + namespaceMove = null; + List components = new java.util.ArrayList<>(owners.size()); + for (PerlOwnerSlot owner : owners) { + RuntimeBase component = owner.referent(); + if (component != null) components.add(component); + owner.release(); + } + for (RuntimeBase component : components) { + if (component instanceof RuntimeScalar scalar) { + scalar.refreshUntrackedReferenceOwner(); + if (!scalar.hasPerlStrongOwnerIdentity() + && !MyVarCleanupStack.isRegistered(scalar)) { + RuntimeScalar.scopeExitCleanup(scalar); + } + } else if (!component.hasPerlStrongOwnerIdentity() + && !MyVarCleanupStack.isRegistered(component)) { + if (component instanceof RuntimeArray array) { + MortalList.scopeExitCleanupArray(array); + } else if (component instanceof RuntimeHash hash) { + MortalList.scopeExitCleanupHash(hash); + } + } + } + MortalList.flush(); + } + static RuntimeGlob createDetachedNamespaceMove(NamespaceMove move) { RuntimeGlob glob = new RuntimeGlob(move.sourcePrefix); glob.slotSnapshot = true; - glob.namespaceMove = move; + glob.retainDetachedNamespaceComponents(move); return glob; } @@ -409,19 +521,14 @@ public static void aliasCodeSlot(String globName, RuntimeScalar sourceCodeRef) { throw new IllegalArgumentException("A named CODE reference is required"); } RuntimeScalar oldCodeRef = GlobalVariable.globalCodeRefs.get(globName); - if (oldCodeRef == sourceCodeRef) { + if (oldCodeRef == sourceCodeRef && !WeakRefRegistry.isweak(sourceCodeRef)) { return; } - if (oldCodeRef != null && oldCodeRef.value instanceof RuntimeCode oldCode - && oldCode.stashRefCount > 0) { - oldCode.stashRefCount--; - } GlobalVariable.globalCodeRefs.put(globName, sourceCodeRef); - GlobalVariable.replacePinnedCodeRef(globName, sourceCodeRef); + GlobalVariable.replacePinnedCodeRef( + globName, GlobalVariable.globalCodeRefs.get(globName)); newCode.hadStashRef = true; - newCode.stashRefCount++; GlobalVariable.isSubs.put(globName, true); - GlobalVariable.invalidatePackageRootSnapshot(); InheritanceResolver.invalidateCache(); int lastColonIdx = globName.lastIndexOf("::"); if (lastColonIdx > 0) { @@ -467,7 +574,6 @@ protected static boolean fillForwardCodeRefInPlace(String globName, RuntimeScala } attachCoderefToNamedGlob(existingCode, globName); existingCode.hadStashRef = true; - existingCode.stashRefCount++; return true; } @@ -672,6 +778,7 @@ public RuntimeScalar set(RuntimeScalar value) { boolean updateWholeGlobAliasGroup = writesThroughGlobAlias || (!isLocalizedGlob(this.globName) && GlobalVariable.isInGlobAliasGroup(this.globName)); + RuntimeCode replacedStashCode = null; // A non-local typeglob assignment is a redefinition for // prototype purposes too. Parser-time checks do not see @@ -757,8 +864,7 @@ public RuntimeScalar set(RuntimeScalar value) { // the normal alias group alone cannot make a later // glob definition visible to direct lexical calls. // Point that storage at the target's live placeholder. - value.type = codeContainer.type; - value.value = codeContainer.value; + value.set(codeContainer); } // Preserve the target's cached placeholder; the shared // alias group will populate it when either name is defined. @@ -776,15 +882,11 @@ public RuntimeScalar set(RuntimeScalar value) { return value; } - // Before overwriting, clear weak refs to the old sub's pad constants. - // This emulates Perl 5's behavior where replacing a sub frees its op-tree, - // causing compile-time constants to be freed and weak refs to be cleared. + // Replacing this glob drops only its CODE-slot owner. A saved + // coderef may still keep the old CV and its optree constants alive; + // final CV cleanup releases those constants after the last owner leaves. if (codeContainer.value instanceof RuntimeCode oldCode) { - oldCode.clearPadConstantWeakRefs(); - // Decrement stashRefCount on the old CODE ref being replaced - if (oldCode.stashRefCount > 0) { - oldCode.stashRefCount--; - } + replacedStashCode = oldCode; } // A BEGIN-installed `sub () { $lexical }` becomes a constant @@ -804,7 +906,6 @@ public RuntimeScalar set(RuntimeScalar value) { GlobalVariable.globalCodeRefs.put(alias, codeContainer); GlobalVariable.replacePinnedCodeRef(alias, codeContainer); } - GlobalVariable.invalidatePackageRootSnapshot(); } if (value.value instanceof RuntimeCode newCode) { @@ -814,7 +915,9 @@ public RuntimeScalar set(RuntimeScalar value) { // install as anonymous). RuntimeGlob.attachCoderefToNamedGlob(newCode, this.globName); newCode.hadStashRef = true; - newCode.stashRefCount++; + } + if (replacedStashCode != null) { + replacedStashCode.noteStashOwnerReleased(); } // Invalidate the method resolution cache @@ -856,7 +959,6 @@ public RuntimeScalar set(RuntimeScalar value) { for (String aliasedName : GlobalVariable.getGlobAliasGroup(this.globName)) { GlobalVariable.globalArrays.put(aliasedName, arr); } - GlobalVariable.invalidatePackageRootSnapshot(); // Mark as explicitly declared for strict vars (e.g., Exporter imports) GlobalVariable.declareGlobalArray(this.globName); } @@ -876,14 +978,15 @@ public RuntimeScalar set(RuntimeScalar value) { // resolved through Outer:: for @ISA and method lookup. if (isStashGlobName(this.globName) && hash instanceof RuntimeStash sourceStash) { if (sourceStash.savedNamespaceMove != null) { - GlobalVariable.installNamespaceMove(sourceStash.savedNamespaceMove, this.globName); + sourceStash.installSavedNamespaceMove(this.globName); } else if (GlobalVariable.globalHashes.get(sourceStash.namespace) != sourceStash) { // A saved \%Pkg:: can outlive a rebind of *Pkg::. // Move its old descendants under the new name // instead of resolving through Pkg's replacement. - RuntimeGlob.NamespaceMove move = - GlobalVariable.detachNamespaceForStaleStash(sourceStash.namespace); - GlobalVariable.installNamespaceMove(move, this.globName); + RuntimeGlob moveOwner = + GlobalVariable.detachNamespaceForStaleStash( + sourceStash.namespace, sourceStash); + sourceStash.installDetachedNamespaceMove(moveOwner, this.globName); } else { GlobalVariable.setStashAlias(this.globName, sourceStash.namespace); } @@ -897,12 +1000,20 @@ public RuntimeScalar set(RuntimeScalar value) { for (String aliasedName : GlobalVariable.getGlobAliasGroup(this.globName)) { GlobalVariable.globalHashes.put(aliasedName, hash); } - GlobalVariable.invalidatePackageRootSnapshot(); // Mark as explicitly declared for strict vars (e.g., Exporter imports) GlobalVariable.declareGlobalHash(this.globName); } return value; case REFERENCE: + // A blessed reference to a glob (for example IO::Scalar's + // `bless \do { local *FH }`) assigned to a typeglob supplies + // the glob itself, including its tied IO slot. It is distinct + // from `*name = \$scalar`, whose referent is an ordinary + // scalar cell and must continue to alias only the SCALAR slot. + if (value.value instanceof RuntimeScalar referent + && referent.type == GLOB) { + return set(referent.globDeref()); + } // `*foo = \$bar` aliases the SCALAR slot to $bar, regardless of what $bar contains. // This must replace the scalar container (alias) rather than storing into // the existing scalar, otherwise tied scalars would invoke STORE. @@ -989,14 +1100,25 @@ public RuntimeScalar set(RuntimeScalar value) { // `local *data = "$mod\::DATA"`. String aliasName = NameNormalizer.normalizeVariableName( value.toString(), RuntimeCode.getCurrentPackage()); + RuntimeStash detachedStash = null; if (isStashGlobName(this.globName)) { RuntimeHash oldStash = GlobalVariable.globalHashes.get(this.globName); if (oldStash instanceof RuntimeStash oldRuntimeStash) { - oldRuntimeStash.savedNamespaceMove = - GlobalVariable.detachNamespaceForStaleStash(this.globName); + detachedStash = oldRuntimeStash; + oldRuntimeStash.saveNamespaceMove( + GlobalVariable.detachNamespaceForStaleStash( + this.globName, oldRuntimeStash)); } } this.set(GlobalVariable.getGlobalIO(aliasName)); + if (detachedStash != null + && GlobalVariable.globalHashes.get(this.globName) != detachedStash) { + // The package name no longer supplies a local binding to + // the old stash. A saved Perl hash reference may still own + // it; that reference's final release will retire the move. + detachedStash.localBindingExists = false; + MortalList.scopeExitCleanupHash(detachedStash); + } // Perl also uses `local *PKG::__ANON__ = 'name'` to provide a // dynamic display name for anonymous subs. Keep that metadata @@ -1007,6 +1129,11 @@ public RuntimeScalar set(RuntimeScalar value) { if (currentGlob == null) currentGlob = this; currentGlob.nameOverride = value.toString(); } + // LOAD_GLOB may provide a detached snapshot as the lvalue. + // Once this assignment has rebound the named GV, that + // temporary snapshot must release its old component slots; + // a surviving Perl scalar owner keeps them through GLOB_VALUE. + if (slotSnapshot) releaseDetachedComponentsIfUnowned(); return value; case FORMAT: // Handle format assignments to typeglobs @@ -1014,9 +1141,9 @@ public RuntimeScalar set(RuntimeScalar value) { if (value.value instanceof RuntimeFormat sourceFormat) { GlobalVariable.setGlobalFormatRef(this.globName, sourceFormat); if (localizedOriginalIO != null) { - this.IO = localizedOriginalIO; + replaceIOScalar(localizedOriginalIO); RuntimeGlob currentGlob = GlobalVariable.getGlobalIO(this.globName); - currentGlob.IO = localizedOriginalIO; + currentGlob.replaceIOScalar(localizedOriginalIO); } } return value; @@ -1080,12 +1207,12 @@ public RuntimeScalar set(RuntimeGlob value) { oldRuntimeIO = rio; } - this.IO = value.IO; + replaceIOScalar(value.IO); this.retainedIoGlob = value; // Also update the global IO entry for this glob if (this.globName != null) { RuntimeGlob targetIO = GlobalVariable.getGlobalIO(this.globName); - targetIO.IO = value.IO; + targetIO.replaceIOScalar(value.IO); } // Update selectedHandle if the old IO was the currently selected output handle. @@ -1126,7 +1253,6 @@ public RuntimeScalar set(RuntimeGlob value) { RuntimeHash srcStash = GlobalVariable.getGlobalHash(value.globName); GlobalVariable.markPackageGlobalRoot(srcStash); GlobalVariable.globalHashes.put(this.globName, srcStash); - GlobalVariable.invalidatePackageRootSnapshot(); // Migrate any pre-existing IO entries from Dst:: to Src::. Unlike code // and variable slots (where real Perl keeps the CV/SV pinned to its // compile-time package), IO handles are usually transient and the @@ -1221,9 +1347,9 @@ public RuntimeScalar set(RuntimeGlob value) { } if (!isLocalizedGlob(this.globName)) { - this.IO = ioSource; + replaceIOScalar(ioSource); } - targetIO.IO = ioSource; + targetIO.replaceIOScalar(ioSource); // Update selectedHandle if the old IO was the currently selected output handle if (oldRuntimeIO != null && oldRuntimeIO == RuntimeIO.getSelectedHandle() @@ -1241,12 +1367,12 @@ public RuntimeScalar set(RuntimeGlob value) { // `@Fooo::ISA = (...)` visible through Baro even when neither side // had an ARRAY slot at alias time. Ordinary absent ARRAY slots stay // unmaterialized so `defined *glob{ARRAY}` retains its Perl meaning. - if ((value.slotSnapshot && value.arraySlot != null) + if (((value.slotSnapshot || value.symbolGensym) && value.arraySlot != null) || GlobalVariable.existsGlobalArray(globName) || this.globName.endsWith("::ISA") || globName.endsWith("::ISA")) { RuntimeArray sourceArray; - if (value.slotSnapshot) { + if (value.slotSnapshot || value.symbolGensym) { sourceArray = value.arraySlot; } else if (this.globName.endsWith("::ISA") || globName.endsWith("::ISA")) { // Read the source slot directly. Alias-group lookup here can @@ -1283,7 +1409,6 @@ public RuntimeScalar set(RuntimeGlob value) { GlobalVariable.markPackageGlobalRoot(sourceArray); sourceArray.markIsaArray(); GlobalVariable.globalArrays.put(this.globName, sourceArray); - GlobalVariable.invalidatePackageRootSnapshot(); } // Alias the HASH slot: both names point to the same RuntimeHash object. @@ -1291,7 +1416,7 @@ public RuntimeScalar set(RuntimeGlob value) { // that mirrors the package's symbol table — getGlobSlot("HASH") returns // it unconditionally for stashes, so we must materialise the alias here // even if globalHashes hasn't been populated yet. - boolean sourceHasHash = (value.slotSnapshot && value.hashSlot != null) + boolean sourceHasHash = ((value.slotSnapshot || value.symbolGensym) && value.hashSlot != null) || GlobalVariable.existsGlobalHash(globName) || isStashGlobName(globName) || (!isLocalizedGlob(this.globName) @@ -1299,7 +1424,7 @@ public RuntimeScalar set(RuntimeGlob value) { || globName.equals("main::+") || globName.equals("main::-"))); if (sourceHasHash) { - RuntimeHash sourceHash = value.slotSnapshot + RuntimeHash sourceHash = value.slotSnapshot || value.symbolGensym ? value.hashSlot : GlobalVariable.getGlobalHash(globName); if ("main::ENV".equals(this.globName) || "ENV".equals(this.globName)) { @@ -1309,7 +1434,6 @@ public RuntimeScalar set(RuntimeGlob value) { } GlobalVariable.markPackageGlobalRoot(sourceHash); GlobalVariable.globalHashes.put(this.globName, sourceHash); - GlobalVariable.invalidatePackageRootSnapshot(); } // Alias the SCALAR slot: both names point to the same RuntimeScalar @@ -1321,7 +1445,7 @@ public RuntimeScalar set(RuntimeGlob value) { // neither has been written yet. Without this, the second `*& = 0` // hits the original read-only `$&` instead of the freshly-aliased // scalar (refstack.t GH#15752). - RuntimeScalar sourceScalar = value.slotSnapshot + RuntimeScalar sourceScalar = value.slotSnapshot || value.symbolGensym ? value.getGlobScalarSlot() : GlobalVariable.getGlobalVariable(globName); GlobalVariable.markPackageGlobalRoot(sourceScalar); @@ -1331,7 +1455,6 @@ public RuntimeScalar set(RuntimeGlob value) { if (assignmentImportsScalar()) { GlobalVariable.declareGlobalVariable(this.globName); } - GlobalVariable.invalidatePackageRootSnapshot(); // Alias the FORMAT slot: both names point to the same RuntimeFormat object RuntimeFormat sourceFormat = GlobalVariable.getGlobalFormatRef(globName); @@ -1450,7 +1573,7 @@ public RuntimeScalar getGlobSlot(RuntimeScalar index) { } case "SCALAR" -> { // For anonymous globs (null globName), use local scalarSlot - if (this.globName == null || this.slotSnapshot) { + if (this.globName == null || this.slotSnapshot || this.symbolGensym) { if (this.scalarSlot == null) { this.scalarSlot = new RuntimeScalar(); } @@ -1476,7 +1599,7 @@ public RuntimeScalar getGlobSlot(RuntimeScalar index) { } } // For anonymous globs (null globName), use local arraySlot - if (this.globName == null) { + if (this.globName == null || this.symbolGensym) { if (this.arraySlot == null) { this.arraySlot = new RuntimeArray(); } @@ -1496,7 +1619,7 @@ public RuntimeScalar getGlobSlot(RuntimeScalar index) { case "HASH" -> { // For *glob{HASH} (glob slot access), always use the global hash. // The local hashSlot is only for *glob->{key} (arrow hash deref via getGlobHash()). - if (this.globName == null) { + if (this.globName == null || this.symbolGensym) { // Anonymous globs use local hashSlot since they have no global name if (this.hashSlot == null) { this.hashSlot = new RuntimeHash(); @@ -1547,7 +1670,7 @@ public RuntimeScalar getGlobSlot(RuntimeScalar index) { * This is distinct from *glob{SCALAR}, which returns a reference to the slot. */ public RuntimeScalar getGlobScalarSlot() { - if (this.globName == null || this.slotSnapshot) { + if (this.globName == null || this.slotSnapshot || this.symbolGensym) { if (this.scalarSlot == null) { this.scalarSlot = new RuntimeScalar(); } @@ -1566,9 +1689,10 @@ public RuntimeScalar getIO() { * For named globs without a local hashSlot, retrieves from GlobalVariable. */ public RuntimeHash getGlobHash() { - if (this.slotSnapshot) { + if (this.slotSnapshot || this.symbolGensym) { if (this.hashSlot == null) { - this.hashSlot = this.hashSlotAliasesNamedGlob && this.globName != null + this.hashSlot = !this.symbolGensym + && this.hashSlotAliasesNamedGlob && this.globName != null ? GlobalVariable.getGlobalHash(this.globName) : new RuntimeHash(); } @@ -1603,7 +1727,7 @@ public RuntimeHash getGlobHash() { * For named globs, retrieves from GlobalVariable. */ public RuntimeArray getGlobArray() { - if (this.globName == null || this.slotSnapshot) { + if (this.globName == null || this.slotSnapshot || this.symbolGensym) { if (this.arraySlot == null) { this.arraySlot = new RuntimeArray(); } @@ -1613,7 +1737,11 @@ public RuntimeArray getGlobArray() { } public RuntimeGlob setIO(RuntimeScalar io) { - GlobalVariable.markStashEntryVisible(this.globName); + if (symbolGensym || GlobalVariable.isIORefHiddenAfterStashDelete(this.globName)) { + GlobalVariable.hideIORefAfterStashDelete(this.globName); + } else { + GlobalVariable.markStashEntryVisible(this.globName); + } acceptedSocket = false; // Check if the current IO is the selected handle - if so, update it RuntimeIO oldIO = null; @@ -1623,7 +1751,7 @@ public RuntimeGlob setIO(RuntimeScalar io) { // If IO slot is tied (TIED_SCALAR with TieHandle), replace it entirely // Otherwise use set() to modify in place, preserving sharing with detached copies if (this.IO.type == RuntimeScalarType.TIED_SCALAR) { - this.IO = io; + replaceIOScalar(io); } else { this.IO.type = io.type; this.IO.value = io.value; @@ -1655,7 +1783,10 @@ public RuntimeGlob setIOKeepingStashHidden(RuntimeIO io) { } private RuntimeGlob setIO(RuntimeIO io, boolean makeStashEntryVisible) { - if (makeStashEntryVisible) { + if (symbolGensym || !makeStashEntryVisible + || GlobalVariable.isIORefHiddenAfterStashDelete(this.globName)) { + GlobalVariable.hideIORefAfterStashDelete(this.globName); + } else { GlobalVariable.markStashEntryVisible(this.globName); } acceptedSocket = false; @@ -1669,7 +1800,7 @@ private RuntimeGlob setIO(RuntimeIO io, boolean makeStashEntryVisible) { // If IO slot is tied (TIED_SCALAR with TieHandle), replace it entirely // Otherwise modify in place, preserving sharing with detached copies if (this.IO.type == RuntimeScalarType.TIED_SCALAR) { - this.IO = new RuntimeScalar(io); + replaceIOScalar(new RuntimeScalar(io)); } else { this.IO.type = RuntimeScalarType.GLOB; // RuntimeIO is stored as GLOB type this.IO.value = io; @@ -1729,8 +1860,9 @@ private static Integer standardFdForGlobName(String globName) { } private void updateStandardRuntimeHandle(RuntimeIO io) { - if (PerlRuntime.current().standardIOGlob(globName) != null) { - PerlRuntime.current().replaceStandardHandle(globName, io); + PerlRuntime runtime = PerlRuntime.currentOrNull(); + if (runtime != null && runtime.standardIOGlob(globName) != null) { + runtime.replaceStandardHandle(globName, io); } } @@ -1964,6 +2096,14 @@ public RuntimeArray setArrayOfAlias(RuntimeArray arr) { * @return The current RuntimeGlob instance after undefining its elements. */ public RuntimeGlob undefine() { + if (namespaceMove != null) { + releaseDetachedComponentsIfUnowned(); + return this; + } + if (globName == null && retainsDetachedComponents()) { + releaseDetachedComponentsIfUnowned(); + return this; + } if (isHintsGlobName(this.globName)) { HintHashRegistry.clearCurrentHintHash(); } @@ -1981,7 +2121,6 @@ public RuntimeGlob undefine() { GlobalVariable.removeGlobalIORefsForNamespace(prefix); GlobalVariable.globalFormatRefs.keySet().removeIf(k -> k.startsWith(prefix)); GlobalVariable.invalidateStashEnumerationCache(); - GlobalVariable.invalidatePackageRootSnapshot(); // Drop the stash hash view so it's empty. new RuntimeStash(prefix).elements.clear(); InheritanceResolver.invalidateCache(); @@ -1990,23 +2129,16 @@ public RuntimeGlob undefine() { } // Undefine CODE RuntimeScalar codeRef = GlobalVariable.getGlobalCodeRef(this.globName); - RuntimeCode displacedCode = codeRef.value instanceof RuntimeCode code ? code : null; - boolean displacedCodeHadWalkableEdges = displacedCode != null - && ReachabilityWalker.hasWalkableCodeEdges(displacedCode, true); + RuntimeCode removedStashCode = codeRef.value instanceof RuntimeCode code + ? code : null; codeRef.set(new RuntimeScalar()); + if (removedStashCode != null) { + removedStashCode.noteStashOwnerReleased(); + } // The CODE scalar can be pinned separately from the stash-map entry. // Undefining a whole glob must invalidate root indexes even when that // scalar was not marked as a package-global root itself. GlobalVariable.noteGlobalCodeRefSlotMutation(codeRef); - // A CODE-owned state variable can be the only strong Perl owner of an - // unblessed object with weak observers. Removing the glob drops that - // owner immediately in Perl, so clear weak observers before returning - // instead of waiting for a later statement-boundary sweep. - if (displacedCodeHadWalkableEdges - && WeakRefRegistry.weakRefsExist() - && !ModuleInitGuard.inModuleInit()) { - ReachabilityWalker.sweepWeakRefs(true); - } // Invalidate the method resolution cache InheritanceResolver.invalidateCache(); @@ -2044,7 +2176,7 @@ public RuntimeGlob undefine() { if (isUnderscoreGlobName(this.globName)) { PerlRuntime.current().executionState().explicitlyUndefinedGlobArraySlots.add(this.globName); } - if (oldArray != null && oldArray.refCount == -1) oldArray.undefine(); + if (oldArray != null && oldArray.isRefCountUntracked()) oldArray.undefine(); // Keep an empty @ISA slot after undefining a glob. A later // `*Class::ISA = *Empty` must alias that empty source rather than // rediscovering Class's former inheritance array through the alias @@ -2054,22 +2186,20 @@ public RuntimeGlob undefine() { emptyIsa.markIsaArray(); GlobalVariable.globalArrays.put(this.globName, emptyIsa); } - GlobalVariable.invalidatePackageRootSnapshot(); // HASH follows the same detached-but-live-reference semantics. RuntimeHash oldHash = GlobalVariable.globalHashes.remove(this.globName); - if (oldHash != null && oldHash.refCount == -1) oldHash.undefine(); - GlobalVariable.invalidatePackageRootSnapshot(); + if (oldHash != null && oldHash.isRefCountUntracked()) oldHash.undefine(); // Undefine IO - detach the handle from the symbol without closing it, // so a saved *Pkg::name{IO} reference can be re-installed later. RuntimeGlob ioGlob = GlobalVariable.getExistingGlobalIO(this.globName); if (ioGlob != null) { - ioGlob.IO = new RuntimeScalar(); + ioGlob.replaceIOScalar(new RuntimeScalar()); GlobalVariable.hideIORefAfterStashDelete(this.globName); } if (ioGlob != this) { - this.IO = new RuntimeScalar(); + replaceIOScalar(new RuntimeScalar()); } GlobalVariable.invalidateStashEnumerationCache(); @@ -2170,7 +2300,6 @@ public void dynamicSaveState() { // Otherwise `local *X; $X = 5` would mutate the canonical $X and the // change would survive the scope exit. GlobalVariable.scalarSlots().put(this.globName, GlobalVariable.markPackageGlobalRoot(new RuntimeScalar())); - GlobalVariable.invalidatePackageRootSnapshot(); if (savedArray != null) { RuntimeArray localizedArray = GlobalVariable.markPackageGlobalRoot(new RuntimeArray()); // A prior `*Fooo::ISA = *Baro::ISA` makes both names address the @@ -2182,7 +2311,6 @@ public void dynamicSaveState() { for (String aliasedName : GlobalVariable.getGlobAliasGroup(this.globName)) { GlobalVariable.globalArrays.put(aliasedName, localizedArray); } - GlobalVariable.invalidatePackageRootSnapshot(); // A method lookup through another name in the alias group may // already be cached. The new localized @ISA must take effect // immediately, not only after the local scope restores. @@ -2190,22 +2318,19 @@ public void dynamicSaveState() { } if (savedHash != null) { GlobalVariable.globalHashes.put(this.globName, GlobalVariable.markPackageGlobalRoot(new RuntimeHash())); - GlobalVariable.invalidatePackageRootSnapshot(); } RuntimeScalar newCode = new RuntimeScalar(); GlobalVariable.markPackageGlobalRoot(newCode); + // The saved GP owns its CV before the last visible name is replaced. + GlobalVariable.enterLocalizedCodeRef(this.globName, savedCode); // A localized whole-glob alias still addresses one temporary CODE // slot. In particular, `*A = *Base::method; local *A = sub { ... }` // must make Base::method visible to MRO until the scope unwinds. for (String alias : codeAliasGroup) { GlobalVariable.globalCodeRefs.put(alias, newCode); } - GlobalVariable.invalidatePackageRootSnapshot(); - // Decrement stashRefCount on the saved CODE ref being removed from the stash if (savedCode != null && savedCode.value instanceof RuntimeCode savedCodeObj) { - if (savedCodeObj.stashRefCount > 0) { - savedCodeObj.stashRefCount--; - } + savedCodeObj.noteStashOwnerReleased(); } // Also redirect pinnedCodeRefs to the new empty code for the local scope. // Without this, getGlobalCodeRef() returns the saved (pinned) object, and @@ -2214,7 +2339,6 @@ public void dynamicSaveState() { for (String alias : codeAliasGroup) { GlobalVariable.replacePinnedCodeRef(alias, newCode); } - GlobalVariable.enterLocalizedCodeRef(this.globName, savedCode); GlobalVariable.getGlobalFormatRef(this.globName).dynamicSaveState(); // Create a NEW RuntimeGlob for the local scope and install it in globalIORefs. @@ -2222,7 +2346,7 @@ public void dynamicSaveState() { // References captured during the local scope (e.g. \do { local *FH }) will point to the // new glob, which remains valid after the local scope ends and this old glob is restored. RuntimeGlob newGlob = new RuntimeGlob(this.globName); - newGlob.localizedOriginalIO = this.IO; + newGlob.setLocalizedOriginalIO(this.IO); // Give the new glob its own hash/array/scalar slots so that orphaned globs // (captured via \do { local *FH }) have independent per-instance storage. // This is needed by IO::Scalar which stores state via *$self->{Key}. @@ -2237,7 +2361,7 @@ public void dynamicSaveState() { if (isSelectedHandle) { RuntimeIO stubIO = new RuntimeIO(); stubIO.globName = this.globName; - newGlob.IO = new RuntimeScalar(stubIO); + newGlob.replaceIOScalar(new RuntimeScalar(stubIO)); } GlobalVariable.replaceGlobalIO(this.globName, newGlob); @@ -2266,7 +2390,7 @@ public void dynamicRestoreState() { } // Restore the saved IO object reference on this (old) glob. - this.IO = snap.io; + replaceIOScalar(snap.io); if (this.IO != null && this.IO.value instanceof RuntimeIO runtimeIO) { String restoredIoGlobName = snap.savedIOGlobName; runtimeIO.globName = restoredIoGlobName != null @@ -2334,37 +2458,43 @@ && hasDestroyMethod(displacedBase)) { } else { GlobalVariable.globalArrays.remove(snap.globName); } - GlobalVariable.invalidatePackageRootSnapshot(); - // Before replacing the code ref, decrement the refCount of the CODE - // that was installed during the local scope. The local scope's code - // was set via setLarge (which incremented refCount), but the restore - // via put() bypasses setLarge, so we must decrement manually. - // Without this, CODE refs installed in localized globs (e.g., - // `local *Foo::bar; sub bar { ... }` in Sub::Quote's unquote_sub) - // have permanently overcounted refCount, preventing releaseCaptures - // from firing at the right time. + // Retire the local CODE slot's own counted edge before restoring the + // saved stash entry. The scalar owner token identifies which count this + // slot acquired; a positive referent count alone cannot prove this CODE + // slot is the edge to decrement. RuntimeScalar localCode = GlobalVariable.globalCodeRefs.get(snap.globName); - RuntimeCode removedLocalCodeForReachabilityCheck = null; - if (localCode != null && (localCode.type & REFERENCE_BIT) != 0 && localCode.value instanceof RuntimeBase localBase) { - boolean removedLastStashRef = false; - // Decrement stashRefCount on the local scope's CODE ref being removed + RuntimeCode removedLocalCodeForStashRelease = null; + PerlOwnerSlot localCodeOwner = localCode == null ? null : localCode.countedOwnerSlot(); + boolean hasExactLocalCodeOwner = localCode != null && localCode.refCountOwned + && localCodeOwner != null && localCodeOwner.isActive() + && localCodeOwner.referent() == localCode.value; + if (localCode != null && (localCode.type & REFERENCE_BIT) != 0 + && localCode.value instanceof RuntimeBase localBase + // A CV can have other counted stash slots while this localized + // slot still owns its own exact token. Retire that token on + // restore; only keep the conservative guard for legacy slots + // whose decrement has no identity proof. + && (hasExactLocalCodeOwner + || !(localBase instanceof RuntimeCode code && code.hasCountedCodeSlots))) { if (localBase instanceof RuntimeCode localCodeObj) { - if (localCodeObj.stashRefCount > 0) { - localCodeObj.stashRefCount--; - removedLastStashRef = localCodeObj.stashRefCount == 0; - } + removedLocalCodeForStashRelease = localCodeObj; } - if (localBase.refCount > 0 && --localBase.refCount == 0) { - localBase.refCount = Integer.MIN_VALUE; + if (localCode.refCountOwned) { + MortalList.releaseCountedOwnerImmediately( + localCode, "RuntimeGlob.restoreLocalizedCodeRef"); + } else if (localCode.hasCodeSlotBinding() && localBase.refCount > 0) { + // Older direct CODE-slot stores did not create a scalar owner + // token. The current stash binding is the exact storage proof; + // attach that existing count to a token before normal release. + RuntimeScalar.adoptExistingCountedOwnerForCurrentValue( + localCode, localBase, PerlOwnerSlot.Kind.CODE_SLOT, + "RuntimeGlob.restoreLocalizedCodeRef"); + MortalList.releaseCountedOwnerImmediately( + localCode, "RuntimeGlob.restoreLocalizedCodeRef"); + } else if (localBase.isRefCountTracked() && localBase.refCount == 0 + && localBase instanceof RuntimeCode) { DestroyDispatch.callDestroy(localBase); - } else if (localBase.refCount == 0 && localBase instanceof RuntimeCode) { - localBase.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(localBase); - } else if (localBase instanceof RuntimeCode localCodeObj - && removedLastStashRef - && (localCodeObj.capturedScalars != null || localCodeObj.capturedAggregates != null)) { - removedLocalCodeForReachabilityCheck = localCodeObj; } } for (var entry : snap.aliasedCodes.entrySet()) { @@ -2375,19 +2505,11 @@ && hasDestroyMethod(displacedBase)) { GlobalVariable.globalCodeRefs.remove(entry.getKey()); } } - GlobalVariable.invalidatePackageRootSnapshot(); - if (removedLocalCodeForReachabilityCheck != null - && removedLocalCodeForReachabilityCheck.activeOwnerCount() == 0 - && !ReachabilityWalker.isReachableFromLiveScalarRegistry(removedLocalCodeForReachabilityCheck) - && !ReachabilityWalker.isReachableFromLiveCodeCaptures(removedLocalCodeForReachabilityCheck) - && !ReachabilityWalker.isReachableFromRoots(removedLocalCodeForReachabilityCheck)) { - removedLocalCodeForReachabilityCheck.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(removedLocalCodeForReachabilityCheck); - } - // Increment stashRefCount on the restored CODE ref being put back in the stash if (snap.code != null && snap.code.value instanceof RuntimeCode restoredCode) { restoredCode.hadStashRef = true; - restoredCode.stashRefCount++; + } + if (removedLocalCodeForStashRelease != null) { + removedLocalCodeForStashRelease.noteStashOwnerReleased(); } // Also restore the pinned code ref so getGlobalCodeRef() returns the // original code object again. diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeGraphCloner.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeGraphCloner.java index 77d57efaf5..ad6add38bc 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeGraphCloner.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeGraphCloner.java @@ -39,10 +39,11 @@ public class RuntimeGraphCloner { private final IdentityHashMap inheritedHandles = new IdentityHashMap<>(); private final List weakReferences = new ArrayList<>(); - private final List snapshotStrongRoots = new ArrayList<>(); private final Set skippedClasses; private int publicDepth; + record SnapshotRoots(List roots, List ownerSlots) {} + public RuntimeGraphCloner(PerlRuntime sourceRuntime, PerlRuntime targetRuntime) { this(sourceRuntime, targetRuntime, Set.of()); } @@ -90,11 +91,48 @@ public List cloneRoots(List roots) { * Weak edges and observed-address publication are finalized only after the * package graph, entry CODE, and arguments all share this identity map. */ - List cloneSnapshotRoots(List roots) { + SnapshotRoots cloneSnapshotRoots(List roots) { List result = new ArrayList<>(roots.size()); - for (RuntimeBase root : roots) result.add(cloneValue(root)); - snapshotStrongRoots.addAll(result); - return result; + List ownerSlots = new ArrayList<>(roots.size() * 2); + try { + for (RuntimeBase root : roots) { + RuntimeBase clonedRoot = cloneValue(root); + result.add(clonedRoot); + retainSnapshotRoot(clonedRoot, ownerSlots); + if (clonedRoot instanceof RuntimeScalar scalar + && RuntimeScalarType.isReference(scalar) + && scalar.value instanceof RuntimeBase referent + && referent != clonedRoot) { + retainSnapshotRoot(referent, ownerSlots); + } + } + } catch (Throwable failure) { + Throwable pendingException = failure; + for (int i = 0; i < ownerSlots.size(); i++) { + try { + ownerSlots.get(i).release(); + } catch (Throwable cleanupFailure) { + pendingException = cleanupFailure; + } + } + throw cleanupFailure(pendingException); + } + return new SnapshotRoots( + java.util.Collections.unmodifiableList(new ArrayList<>(result)), + List.copyOf(ownerSlots)); + } + + private static RuntimeException cleanupFailure(Throwable failure) { + if (failure instanceof RuntimeException runtimeException) return runtimeException; + if (failure instanceof Error error) throw error; + return new RuntimeException(failure); + } + + private static void retainSnapshotRoot( + RuntimeBase root, List ownerSlots) { + PerlOwnerSlot owner = new PerlOwnerSlot(PerlOwnerSlot.Kind.TEMPORARY_ROOT); + owner.acquireTemporaryRootIdentity(root); + ownerSlots.add(owner); } /** @@ -164,6 +202,22 @@ void finishSnapshot() { finishCloneBoundary(); } + void restoreCodeSlotBindings(java.util.Collection slots) { + try (PerlRuntime.Binding ignored = targetRuntime.bind()) { + for (RuntimeScalar slot : slots) { + if (slot != null) slot.retainCodeSlotBinding(); + } + } + } + + void restoreStashCodeSlotBindings(java.util.Collection slots) { + try (PerlRuntime.Binding ignored = targetRuntime.bind()) { + for (RuntimeScalar slot : slots) { + if (slot != null) slot.retainStashCodeSlotBinding(); + } + } + } + /** Package/runtime snapshot entry point that retains the shared graph map. */ RuntimeBase cloneValue(RuntimeBase value) { if (value == null) return null; @@ -173,6 +227,17 @@ RuntimeBase cloneValue(RuntimeBase value) { // shared synchronization identity. if (value.threadShared && !needsSharedRuntimeView(value)) return value; Object existing = clones.get(value); + if (existing instanceof RuntimeScalar clonedScalar + && clonedScalar.isPerlDestroyed() + && value instanceof RuntimeScalar sourceScalar + && !sourceScalar.isPerlDestroyed()) { + // A lazy CODE definition can expose a pad cell after the initial + // thread snapshot. If this snapshot already cloned that source + // cell and the child has since retired the clone, reuse would + // attach the new closure metadata to a destroyed cell. + clones.remove(value); + existing = null; + } if (existing != null) return (RuntimeBase) existing; if (value instanceof RuntimeScalarReadOnly scalar @@ -199,6 +264,8 @@ protected RuntimeBase cloneCode(RuntimeCode source) { if (existing != null) return (RuntimeCode) existing; RuntimeCode target; + RuntimeBase[] captureValues = null; + InterpretedCode captureOwnerBody = null; if (source instanceof InterpretedCode interpreted) { // cloneInterpretedCode copies metadata itself because it is also // used for an interpreted body nested inside a lazy RuntimeCode @@ -213,12 +280,15 @@ protected RuntimeBase cloneCode(RuntimeCode source) { // the parent's capturedVars array even though the placeholder's // metadata had been cloned correctly. target = new RuntimeCode((PerlSubroutine) null, source.prototype); + copyBase(source, target); clones.put(source, target); InterpretedCode clonedBody = cloneInterpretedCode(interpreted); target.subroutine = clonedBody; target.codeObject = clonedBody; + captureOwnerBody = clonedBody; } else { target = new RuntimeCode((PerlSubroutine) null, source.prototype); + copyBase(source, target); clones.put(source, target); if (source.subroutine instanceof CloneablePerlSubroutine cloneable) { RuntimeBase[] captures = cloneable.capturedValues(); @@ -229,6 +299,7 @@ protected RuntimeBase cloneCode(RuntimeCode source) { CloneablePerlSubroutine clonedSubroutine = cloneable.cloneWithCaptures(clonedCaptures); target.subroutine = clonedSubroutine; target.codeObject = clonedSubroutine; + captureValues = clonedCaptures; } else { // Java/native PerlSubroutine implementations carry no Perl pad. target.subroutine = source.subroutine; @@ -236,7 +307,20 @@ protected RuntimeBase cloneCode(RuntimeCode source) { target.methodHandle = source.methodHandle; } } - copyCodeMetadata(source, target); + copyCodeMetadata(source, target, captureValues, captureOwnerBody == null); + if (captureOwnerBody != null) { + // The wrapper and its interpreted body are one Perl CV. Share the + // body's capture-owner identities instead of retaining each cell + // once for the body and again for its wrapper. + target.capturedScalars = captureOwnerBody.capturedScalars; + target.capturedScalarOwnerSlots = captureOwnerBody.capturedScalarOwnerSlots; + target.capturedAggregates = captureOwnerBody.capturedAggregates; + target.capturedAggregateOwnerSlots = captureOwnerBody.capturedAggregateOwnerSlots; + if (target.capturedScalars != null || target.capturedAggregates != null) { + target.startRefCountTracking(); + } + target.rebindCaptureOwnerSlots(); + } return target; } @@ -281,6 +365,8 @@ private InterpretedCode cloneInterpretedCode(InterpretedCode source) { source.evalSitePragmaFlags, source.warningBitsString); } + copyBase(source, target); + target.setMyScalarNamesByRegister(source.myScalarNamesByRegister); clones.put(source, target); target.ourVariableRegistry = source.ourVariableRegistry; target.declaredOurVariables = source.declaredOurVariables; @@ -293,7 +379,7 @@ private InterpretedCode cloneInterpretedCode(InterpretedCode source) { target.signatureKeyword = source.signatureKeyword; target.gotoLabelPcs = source.gotoLabelPcs; target.gotoLabelsInsideLoop = source.gotoLabelsInsideLoop; - copyCodeMetadata(source, target); + copyCodeMetadata(source, target, captures); return target; } @@ -305,6 +391,16 @@ private RuntimeBase[] cloneRuntimeBases(RuntimeBase[] values) { } private void copyCodeMetadata(RuntimeCode source, RuntimeCode target) { + copyCodeMetadata(source, target, null, true); + } + + private void copyCodeMetadata( + RuntimeCode source, RuntimeCode target, RuntimeBase[] captureValues) { + copyCodeMetadata(source, target, captureValues, true); + } + + private void copyCodeMetadata(RuntimeCode source, RuntimeCode target, + RuntimeBase[] captureValues, boolean copyCaptureOwnership) { target.prototype = source.prototype; target.signatureNamedParams = source.signatureNamedParams; target.signatureRequiredNamedParams = source.signatureRequiredNamedParams; @@ -378,7 +474,12 @@ private void copyCodeMetadata(RuntimeCode source, RuntimeCode target) { clones.put(source, target); } } - target.adoptDefinitionFrom(completed); + try (PerlRuntime.Binding ignored = targetRuntime.bind()) { + target.adoptDefinitionFrom(completed); + // The materialized child copy was an intermediate CV; + // the installed placeholder now owns its pad constants. + completed.clearPadConstantWeakRefs(); + } target.compilerSupplier = null; } finally { org.perlonjava.app.scriptengine.PerlLanguageProvider.COMPILE_LOCK.unlock(); @@ -396,9 +497,13 @@ private void copyCodeMetadata(RuntimeCode source, RuntimeCode target) { target.lexicalSubDisplayName = source.lexicalSubDisplayName; target.isConstantCv = source.isConstantCv; target.isLexicalConstantCv = source.isLexicalConstantCv; + try (PerlRuntime.Binding ignored = targetRuntime.bind()) { + RuntimeCode.copyPadConstantTree(source, target, this::cloneRuntimeBases); + } target.stashInstallPackage = source.stashInstallPackage; target.stashInstallSub = source.stashInstallSub; target.hadStashRef = source.hadStashRef; + target.hasCountedCodeSlots = source.hasCountedCodeSlots; target.explicitlyMaterializedGlob = source.explicitlyMaterializedGlob; target.captureFieldsRecorded = source.captureFieldsRecorded; target.installedViaAnonGlobAssign = source.installedViaAnonGlobAssign; @@ -420,6 +525,10 @@ private void copyCodeMetadata(RuntimeCode source, RuntimeCode target) { target.stateVariable = cloneScalarMap(source.stateVariable); target.stateArray = cloneArrayMap(source.stateArray); target.stateHash = cloneHashMap(source.stateHash); + target.stateAggregateAliasOwners = cloneScalarMap(source.stateAggregateAliasOwners); + try (PerlRuntime.Binding ignored = targetRuntime.bind()) { + target.retainClonedStateOwnerSlots(); + } if (source.__SUB__ != null) { target.restoreClonedSelfReference( (RuntimeScalar) cloneValue(source.__SUB__)); @@ -440,39 +549,81 @@ private void copyCodeMetadata(RuntimeCode source, RuntimeCode target) { } } - // capturedScalars/capturedAggregates are the authoritative ownership - // lists built by makeCodeObject()/CREATE_CLOSURE. closedOverVariables - // is diagnostic/name metadata and can legitimately omit executable - // captures, so rebuilding ownership from that map allowed a method - // return to DESTROY a still-live captured object in an ithread. - if (source.capturedScalars != null) { - target.capturedScalars = new RuntimeScalar[source.capturedScalars.length]; - for (int i = 0; i < source.capturedScalars.length; i++) { - target.capturedScalars[i] = - (RuntimeScalar) cloneValue(source.capturedScalars[i]); - } - try (PerlRuntime.Binding ignored = targetRuntime.bind()) { - for (RuntimeScalar captured : target.capturedScalars) { - captured.retainThreadCloneClosureCapture(); + // The executable closure fields / bytecode capturedVars are the + // authoritative captured cells. Re-cloning RuntimeCode's parallel + // metadata array can create a second scalar cell for the same source + // capture; its legacy capture bridge then retains the referent after + // the executable cell is assigned undef in an ithread. + if (copyCaptureOwnership) { + List clonedCaptureScalars = new ArrayList<>(); + List clonedCaptureAggregates = new ArrayList<>(); + Set seenCaptureValues = java.util.Collections.newSetFromMap( + new IdentityHashMap<>()); + if (captureValues != null) { + for (RuntimeBase capture : captureValues) { + // Preserve the bytecode capture indexes, but do not create + // ownership metadata for a dead cell left in a lazy CV's + // conservative capture array. Such cells are placeholders, + // not live Perl captures. + if (capture == null || capture.isPerlDestroyed() + || !seenCaptureValues.add(capture)) continue; + if (capture instanceof RuntimeScalar scalar) { + clonedCaptureScalars.add(scalar); + } else if (capture instanceof RuntimeArray || capture instanceof RuntimeHash) { + clonedCaptureAggregates.add(capture); + } + } + } else { + RuntimeScalar[] sourceCapturedScalars = source.capturedScalars; + if (sourceCapturedScalars != null) { + for (RuntimeScalar scalar : sourceCapturedScalars) { + // Conservative capture metadata can outlive the pad + // cell it once described, especially while lazy named + // CODE definitions are copied into an ithread. A dead + // cell is not a Perl owner and must not be resurrected + // as a child closure capture. + if (scalar == null || scalar.isPerlDestroyed()) continue; + RuntimeScalar cloned = (RuntimeScalar) cloneValue(scalar); + if (cloned != null && !cloned.isPerlDestroyed() + && seenCaptureValues.add(cloned)) { + clonedCaptureScalars.add(cloned); + } + } + } + if (source.capturedAggregates != null) { + for (RuntimeBase aggregate : source.capturedAggregates) { + RuntimeBase cloned = cloneValue(aggregate); + if (cloned != null && seenCaptureValues.add(cloned)) { + clonedCaptureAggregates.add(cloned); + } + } } } - } - if (source.capturedAggregates != null) { - target.capturedAggregates = new RuntimeBase[source.capturedAggregates.length]; - for (int i = 0; i < source.capturedAggregates.length; i++) { - target.capturedAggregates[i] = cloneValue(source.capturedAggregates[i]); + if (!clonedCaptureScalars.isEmpty()) { + target.capturedScalars = clonedCaptureScalars.toArray(new RuntimeScalar[0]); + try (PerlRuntime.Binding ignored = targetRuntime.bind()) { + target.capturedScalarOwnerSlots = + new PerlOwnerSlot[target.capturedScalars.length]; + for (int i = 0; i < target.capturedScalars.length; i++) { + target.capturedScalarOwnerSlots[i] = target.capturedScalars[i] + .retainThreadCloneClosureCapture(target); + } + } } - try (PerlRuntime.Binding ignored = targetRuntime.bind()) { - target.capturedAggregateOwnerSlots = - new PerlOwnerSlot[target.capturedAggregates.length]; - for (int i = 0; i < target.capturedAggregates.length; i++) { - target.capturedAggregateOwnerSlots[i] = - target.capturedAggregates[i].retainClosureCaptureOwner(); + if (!clonedCaptureAggregates.isEmpty()) { + target.capturedAggregates = clonedCaptureAggregates.toArray(new RuntimeBase[0]); + try (PerlRuntime.Binding ignored = targetRuntime.bind()) { + target.capturedAggregateOwnerSlots = + new PerlOwnerSlot[target.capturedAggregates.length]; + for (int i = 0; i < target.capturedAggregates.length; i++) { + target.capturedAggregateOwnerSlots[i] = + target.capturedAggregates[i].retainClosureCaptureOwner(target); + } } } - } - if (target.capturedScalars != null || target.capturedAggregates != null) { - target.refCount = 0; + if (target.capturedScalars != null || target.capturedAggregates != null) { + target.startRefCountTracking(); + } } } @@ -581,6 +732,15 @@ private RuntimeScalar cloneScalar(RuntimeScalar source) { weakReferences.add(target); } else { restoreScalarReferenceOwnership(source, target); + if (source.hasIoOwner()) { + // IO holder identities are runtime-local just like counted + // scalar edges. The source scalar keeps its parent lease; + // the cloned Perl scalar owns a fresh lease on the cloned + // anonymous glob so child cleanup cannot outlive its handle. + try (PerlRuntime.Binding ignored = targetRuntime.bind()) { + RuntimeScalar.retainUnstashedIoForDurableSlot(target); + } + } } if (target.value instanceof RuntimeCode code && code.__SUB__ == null) { // JVM CODE commonly stores its generated implementation in @@ -599,20 +759,8 @@ private void restoreScalarReferenceOwnership(RuntimeScalar source, RuntimeScalar || !(target.value instanceof RuntimeBase referent)) { return; } - if (referent.refCount < 0 - && (referent instanceof RuntimeHash || referent instanceof RuntimeArray)) { - referent.refCount = 0; - } - if (referent.refCount < 0) return; - if (referent.refCount == 0) referent.registerSharedFetchedView(); - referent.traceRefCount(+1, "RuntimeGraphCloner.restoreScalarReferenceOwnership"); - referent.recordOwner(target, "thread clone scalar owner"); - referent.recordActiveOwner(target); - referent.refCount++; - referent.hadCountedReference = true; - target.refCountOwned = true; try (PerlRuntime.Binding ignored = targetRuntime.bind()) { - ScalarRefRegistry.registerRef(target); + RuntimeScalar.incrementRefCountForContainerStore(target); } } @@ -668,8 +816,12 @@ private RuntimeHash cloneHash(RuntimeHash source) { } else { try (PerlRuntime.Binding ignored = targetRuntime.bind()) { for (Map.Entry entry : source.elements.entrySet()) { - target.putClonedElement(entry.getKey(), - (RuntimeScalar) cloneValue(entry.getValue())); + RuntimeScalar clonedValue = (RuntimeScalar) cloneValue(entry.getValue()); + if (source.ownsHashAliasCell(entry.getKey(), entry.getValue())) { + target.putClonedAliasElement(entry.getKey(), clonedValue); + } else { + target.putClonedElement(entry.getKey(), clonedValue); + } } } } @@ -699,6 +851,7 @@ private RuntimeGlob cloneGlob(RuntimeGlob source) { target.type = source.type; target.value = target; target.nameOverride = source.nameOverride; + target.symbolGensym = source.symbolGensym; target.scalarSlot = (RuntimeScalar) cloneValue(source.scalarSlot); target.arraySlot = (RuntimeArray) cloneValue(source.arraySlot); target.hashSlot = (RuntimeHash) cloneValue(source.hashSlot); @@ -709,9 +862,9 @@ private RuntimeGlob cloneGlob(RuntimeGlob source) { // glob handles cross the snapshot using the same explicit resource policy // as lexical and aggregate-held handles. if (source.IO != null && source.IO.value instanceof RuntimeIO) { - target.IO = (RuntimeScalar) cloneValue(source.IO); + target.replaceIOScalar((RuntimeScalar) cloneValue(source.IO)); } else { - target.IO = new RuntimeScalar(); + target.replaceIOScalar(new RuntimeScalar()); } return target; } @@ -753,8 +906,8 @@ private RuntimeIO cloneRuntimeIO(RuntimeIO source) { // Shared transports replace the parent's raw owner with its lease. For // wrapper stacks this also ensures the parent and child have independent // layer state over the same underlying transport. - source.ioHandle = pair.parent(); - target.ioHandle = pair.child(); + source.replaceIOHandle(pair.parent()); + target.replaceIOHandle(pair.child()); try (PerlRuntime.Binding ignored = targetRuntime.bind()) { RuntimeIO.addHandle(target.ioHandle); } @@ -856,7 +1009,8 @@ private void copyScalarMetadata(RuntimeScalar source, RuntimeScalar target) { target.lexicalSubPackageName = source.lexicalSubPackageName; target.lexicalSubPackageCodeDefinedAtDeclaration = source.lexicalSubPackageCodeDefinedAtDeclaration; - target.ioOwner = false; + target.ioOwnerSlot = null; + target.copyCompiledDirectCallSiteMetadataFrom(source); } private void copyBase(RuntimeBase source, RuntimeBase target) { @@ -874,10 +1028,15 @@ private void copyBase(RuntimeBase source, RuntimeBase target) { target.blessId = cloneBlessId(source.blessId); } target.localBindingExists = source.localBindingExists; + // Keep targeted refcount diagnostics useful across ithreads. This is + // inert unless PJ_REFCOUNT_TRACE is enabled and a class was selected + // with PJ_REFCOUNT_TRACE_CLASS in its source runtime. + target.refCountTrace = source.refCountTrace; target.storedInPackageGlobal = source.storedInPackageGlobal; target.isPackageGlobalRoot = source.isPackageGlobalRoot; // Refcount/lifecycle queues are reconstructed in the child runtime. - target.refCount = source.refCount >= 0 ? 0 : -1; + if (source.isRefCountTracked()) target.startRefCountTracking(); + else target.markRefCountUntracked(); } private int cloneBlessId(int sourceBlessId) { @@ -916,11 +1075,17 @@ private boolean isWeak(RuntimeScalar scalar) { private void finishWeakReferences() { if (weakReferences.isEmpty()) return; try (PerlRuntime.Binding ignored = targetRuntime.bind()) { + int pendingBeforeWeakEdges = MortalList.pendingSize(); for (RuntimeScalar weakReference : weakReferences) { - WeakRefRegistry.weakenForSnapshot(weakReference, snapshotStrongRoots); + WeakRefRegistry.weaken(weakReference); } + // Cloned captures can temporarily contribute a strong bridge until + // their weak edges are installed. Retire those releases only after + // every snapshot weak edge is registered, so a DESTROY callback + // sees the complete weak graph and no stale capture owner survives + // into the child thread's first statement. + MortalList.drainPendingSince(pendingBeforeWeakEdges); } weakReferences.clear(); - snapshotStrongRoots.clear(); } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeHash.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeHash.java index 3d2e1f7e0e..ba53064d73 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeHash.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeHash.java @@ -67,8 +67,7 @@ private static Stack dynamicStateStack() { * D-W6.18: marks this hash as a package-global hash (registered in * GlobalVariable.globalHashes). When a value is stored in this hash, * the value's referent is marked as {@code storedInPackageGlobal} — - * which then allows the walker-gate rescue at refCount→0 to - * preserve module-global metadata (Class::MOP %METAS, similar caches) + * which lets final-release cleanup recognize module-global metadata * across transient selective-refCount zeros. *

    * Set by {@code GlobalVariable.markAsGlobalPackageHash} when the hash @@ -106,12 +105,91 @@ private RuntimeHashElementMap newElementMap() { return new RuntimeHashElementMap(this); } + void replaceWithEmptySharedStorage() { + type = PLAIN_HASH; + elements = Collections.synchronizedMap(newElementMap()); + resetIterator(); + } + private RuntimeHashElementMap newElementMap(Map values) { RuntimeHashElementMap map = new RuntimeHashElementMap(this); map.putAll(values); return map; } + private RuntimeHashElementMap newElementMap(Map values, + Map aliasCells) { + RuntimeHashElementMap map = new RuntimeHashElementMap(this); + for (Map.Entry entry : values.entrySet()) { + RuntimeScalar aliasCell = aliasCells.get(entry.getKey()); + if (aliasCell == entry.getValue()) { + map.putAliasedCell(entry.getKey(), entry.getValue()); + } else { + map.put(entry.getKey(), entry.getValue()); + } + } + return map; + } + + private record HashAliasCellOwner(RuntimeScalar cell, PerlOwnerSlot owner) {} + + boolean ownsHashAliasCell(String key, RuntimeScalar cell) { + return elements instanceof RuntimeHashElementMap map + && map.ownsHashAliasCell(key, cell); + } + + boolean ownsHashAliasCellOwner(PerlOwnerSlot owner, RuntimeScalar cell) { + return elements instanceof RuntimeHashElementMap map + && map.ownsHashAliasCellOwner(owner, cell); + } + + boolean containsElementCellIdentity(RuntimeScalar cell) { + if (cell == null || elements == null) return false; + if (elements instanceof RuntimeHashElementMap map) { + return map.containsValueIdentity(cell); + } + for (RuntimeScalar value : elements.values()) { + if (value == cell) return true; + } + return false; + } + + private boolean hasHashAliasCellOwner(RuntimeScalar cell) { + return cell != null + && cell.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ALIAS_CELL) != 0; + } + + private PerlOwnerSlot newHashAliasCellOwner(RuntimeScalar cell) { + PerlOwnerSlot owner = new PerlOwnerSlot(PerlOwnerSlot.Kind.HASH_ALIAS_CELL); + owner.acquireHashAliasCellIdentity(cell, this); + return owner; + } + + /** + * Install a Perl scalar-cell alias in one hash slot. The new cell identity + * is acquired before map publication, then the displaced identity is + * released after the slot exposes its replacement. + */ + RuntimeScalar aliasScalarCell(String key, RuntimeScalar cell) { + validateRequireHookAssignment(key, cell); + RuntimeScalar previous = elements.get(key); + boolean previousWasAlias = ownsHashAliasCell(key, previous); + if (!(elements instanceof RuntimeHashElementMap)) { + elements = newElementMap(elements); + } + RuntimeHashElementMap map = (RuntimeHashElementMap) elements; + RuntimeScalar displaced = map.putAliasedCell(key, cell); + markPackageRootedValue(cell); + if (displaced != null && displaced != cell && !previousWasAlias) { + if (!isHintHash || suppressHintHashLifecycleCleanup) { + MortalList.deferDestroyForContainerClear( + Collections.singletonList(displaced)); + } + MortalList.flush(); + } + return displaced; + } + /** Revision for stable-method cell caching, or -1 after an untracked map view is exposed. */ long stableMethodFieldCacheRevision() { return elements instanceof RuntimeHashElementMap map @@ -129,6 +207,27 @@ public void validateHashKey(String key, String operation) { } } + private void traceDestroyedCursorMutation(String key, RuntimeScalar value) { + if (!RuntimeBase.refCountTraceEnabled() || !"cursor".equals(key) + || perlLifecycleState() != RuntimeBase.PerlLifecycleState.DESTROYED) { + return; + } + RuntimeBase referent = value != null && value.value instanceof RuntimeBase base + ? base : null; + System.err.println("[DESTROYED-HASH-CURSOR-WRITE] hash=" + + System.identityHashCode(this) + " generation=" + + RuntimeBase.traceReferentGeneration(this) + " blessId=" + blessId + + " class=" + NameNormalizer.getBlessStr(blessId) + " refCount=" + refCount + + " aliasOwners=" + + ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS) + + " scalar=" + (value == null ? 0 : System.identityHashCode(value)) + + " owns=" + (value != null && value.refCountOwned) + + " referent=" + (referent == null ? 0 : System.identityHashCode(referent)) + + " referentGeneration=" + (referent == null ? 0 + : RuntimeBase.traceReferentGeneration(referent))); + new Throwable().printStackTrace(System.err); + } + public boolean isHashRestricted() { return legalHashKeys != null; } @@ -145,26 +244,60 @@ private void validateHashDelete(String key) { } void resetElementMapAfterAutovivification() { + Map previous = elements; elements = newElementMap(); + if (previous instanceof RuntimeHashElementMap map) { + map.releaseAllHashAliasCellOwners(); + } } Object snapshotRegexMutationState() { if (threadShared || type == TIED_HASH || type == READONLY_HASH) return null; - return new RegexMutationState(new LinkedHashMap<>(elements), + Map savedElements = new LinkedHashMap<>(elements); + Map aliasCells = elements instanceof RuntimeHashElementMap map + ? map.aliasedCellsSnapshot() : Map.of(); + List aliasSnapshotOwners = new ArrayList<>(aliasCells.size()); + for (RuntimeScalar cell : aliasCells.values()) { + aliasSnapshotOwners.add(newHashAliasCellOwner(cell)); + } + return new RegexMutationState(savedElements, aliasCells, aliasSnapshotOwners, byteKeys == null ? null : new HashSet<>(byteKeys), type, blessId, taintEnvironmentAliasDescription); } void restoreRegexMutationState(Object token) { if (!(token instanceof RegexMutationState state)) return; - deferValuesAddedSince(state.elements.values()); - elements = newElementMap(state.elements); - byteKeys = state.byteKeys == null ? null : new HashSet<>(state.byteKeys); - type = state.type; - blessId = state.blessId; - taintEnvironmentAliasDescription = state.taintEnvironmentAliasDescription; - if (isPackageRootedHash()) { - for (RuntimeScalar value : elements.values()) markPackageRootedValue(value); + try { + deferValuesAddedSince(state.elements.values()); + Map replacedMap = elements; + List replaced = new ArrayList<>(elements.values()); + elements = newElementMap(state.elements, state.aliasCells); + if (replacedMap instanceof RuntimeHashElementMap map) { + map.releaseAllHashAliasCellOwners(); + } + for (RuntimeScalar value : replaced) { + if (value != null) value.reconcileContainerOwnerAfterMutation(this); + } + refreshUntrackedElementOwners(); + byteKeys = state.byteKeys == null ? null : new HashSet<>(state.byteKeys); + type = state.type; + blessId = state.blessId; + taintEnvironmentAliasDescription = state.taintEnvironmentAliasDescription; + if (isPackageRootedHash()) { + for (RuntimeScalar value : elements.values()) { + markPackageRootedValue(value); + value.markPrepopulatedPackageAggregateOwner(this); + value.refreshUntrackedReferenceOwner(); + } + } + } finally { + state.releaseAliasSnapshotOwners(); + } + } + + void discardRegexMutationState(Object token) { + if (token instanceof RegexMutationState state) { + state.releaseAliasSnapshotOwners(); } } @@ -184,160 +317,244 @@ private void deferValuesAddedSince(Collection saved) { MortalList.deferDestroyForContainerClear(added); } + void refreshUntrackedElementOwners() { + refreshUntrackedElementOwners(false); + } + + void refreshUntrackedElementOwnersAfterTransfer() { + refreshUntrackedElementOwners(true); + } + + private void refreshUntrackedElementOwners(boolean afterTransfer) { + if (elements == null) return; + for (RuntimeScalar value : new ArrayList<>(elements.values())) { + if (value == null) continue; + if (afterTransfer) value.reconcileContainerOwnerAfterAggregateTransfer(this); + else value.reconcileContainerOwnerAfterMutation(this); + } + } + private record RegexMutationState(Map elements, + Map aliasCells, + List aliasSnapshotOwners, Set byteKeys, int type, int blessId, - String taintEnvironmentAliasDescription) {} + String taintEnvironmentAliasDescription) { + synchronized void releaseAliasSnapshotOwners() { + for (PerlOwnerSlot owner : aliasSnapshotOwners) owner.release(); + aliasSnapshotOwners.clear(); + } + } private static final class RuntimeHashElementMap extends StableHashMap { private final RuntimeHash owner; + private final Map hashAliasCellOwners = new HashMap<>(); + private final IdentityHashMap hashAliasCellOwnerKeys = + new IdentityHashMap<>(); + private final IdentityHashMap valueIdentityCounts = + new IdentityHashMap<>(); private long stableMethodFieldCacheRevision; private boolean stableMethodFieldCacheable = true; - private transient Collection trackedValuesView; + private Set> entrySetView; + private Set keySetView; + private Collection valuesView; private RuntimeHashElementMap(RuntimeHash owner) { this.owner = owner; } + private boolean containsValueIdentity(RuntimeScalar value) { + return valueIdentityCounts.containsKey(value); + } + + private void addValueIdentity(RuntimeScalar value) { + if (value != null) valueIdentityCounts.merge(value, 1, Integer::sum); + } + + private void removeValueIdentity(RuntimeScalar value) { + if (value == null) return; + Integer count = valueIdentityCounts.get(value); + if (count == null || count <= 1) valueIdentityCounts.remove(value); + else valueIdentityCounts.put(value, count - 1); + } + + private boolean ownsHashAliasCell(String key, RuntimeScalar cell) { + HashAliasCellOwner aliasOwner = hashAliasCellOwners.get(key); + return aliasOwner != null && aliasOwner.cell == cell; + } + + private boolean ownsHashAliasCellOwner(PerlOwnerSlot owner, RuntimeScalar cell) { + if (!hashAliasCellOwnerKeys.containsKey(owner)) return false; + String key = hashAliasCellOwnerKeys.get(owner); + HashAliasCellOwner aliasOwner = hashAliasCellOwners.get(key); + return aliasOwner != null && aliasOwner.owner == owner + && aliasOwner.cell == cell && super.get(key) == cell; + } + + private Map aliasedCellsSnapshot() { + Map snapshot = new HashMap<>(); + for (Map.Entry entry : hashAliasCellOwners.entrySet()) { + if (super.get(entry.getKey()) == entry.getValue().cell) { + snapshot.put(entry.getKey(), entry.getValue().cell); + } + } + return snapshot; + } + + private void installHashAliasCellOwner(String key, RuntimeScalar cell, + PerlOwnerSlot nextOwner) { + HashAliasCellOwner previous = hashAliasCellOwners.put( + key, new HashAliasCellOwner(cell, nextOwner)); + if (previous != null && previous.owner != nextOwner) { + hashAliasCellOwnerKeys.remove(previous.owner); + previous.owner.release(); + } + hashAliasCellOwnerKeys.put(nextOwner, key); + } + + private void reconcileHashAliasCellOwner(String key, RuntimeScalar current) { + HashAliasCellOwner aliasOwner = hashAliasCellOwners.get(key); + if (aliasOwner != null && aliasOwner.cell != current) { + hashAliasCellOwners.remove(key); + hashAliasCellOwnerKeys.remove(aliasOwner.owner); + aliasOwner.owner.release(); + } + } + + private void releaseHashAliasCellOwner(String key) { + HashAliasCellOwner aliasOwner = hashAliasCellOwners.remove(key); + if (aliasOwner != null) { + hashAliasCellOwnerKeys.remove(aliasOwner.owner); + aliasOwner.owner.release(); + } + } + + private void releaseAllHashAliasCellOwners() { + if (hashAliasCellOwners.isEmpty()) return; + List owners = new ArrayList<>(hashAliasCellOwners.size()); + for (HashAliasCellOwner aliasOwner : hashAliasCellOwners.values()) { + owners.add(aliasOwner.owner); + } + hashAliasCellOwners.clear(); + hashAliasCellOwnerKeys.clear(); + for (PerlOwnerSlot aliasOwner : owners) aliasOwner.release(); + } + @Override public RuntimeScalar put(String key, RuntimeScalar value) { + return putInternal(key, value, false); + } + + private RuntimeScalar putAliasedCell(String key, RuntimeScalar value) { + if (ownsHashAliasCell(key, value)) { + return putInternal(key, value, true); + } + PerlOwnerSlot nextOwner = owner.newHashAliasCellOwner(value); + try { + RuntimeScalar previous = putInternal(key, value, true); + installHashAliasCellOwner(key, value, nextOwner); + return previous; + } catch (RuntimeException | Error failure) { + if (super.get(key) == value) { + installHashAliasCellOwner(key, value, nextOwner); + } else { + nextOwner.release(); + } + throw failure; + } + } + + private RuntimeScalar putInternal(String key, RuntimeScalar value, + boolean aliasCellMutation) { if (owner.threadShared) { SharedPerlStorage.validateStoredValue(value); SharedPerlStorage.publishBlessing(value); } - if (owner.isEnvironmentHash + if (!aliasCellMutation && owner.isEnvironmentHash && value != null && !(value instanceof RuntimeEnvironmentScalar)) { value = new RuntimeEnvironmentScalar(value); } RuntimeScalar previous = super.get(key); + boolean previousWasAlias = ownsHashAliasCell(key, previous); + boolean newValueIsAlias = aliasCellMutation + || (previousWasAlias && previous == value); if (owner.isHintHash && !owner.suppressHintHashLifecycleCleanup - && previous != null && previous != value) { + && previous != null && previous != value && !previousWasAlias) { MortalList.deferDestroyForContainerClear(java.util.Collections.singletonList(previous)); } - owner.notePackageRootMutation(previous, value); - if (value != null) { - value.markContainerOwner(owner); + if (value != null && !newValueIsAlias) { if (owner.hasDurableElementLifetime()) { RuntimeScalar.retainUnstashedIoForDurableSlot(value); } } - owner.markPackageRootedValue(value); RuntimeScalar result = super.put(key, value); + owner.traceDestroyedCursorMutation(key, value); + if (previous != value) { + removeValueIdentity(previous); + addValueIdentity(value); + } stableMethodFieldCacheRevision++; + if (value != null) value.markContainerOwner(owner); + owner.markPackageRootedValue(value); + refreshStoredUntrackedOwner(value); + if (previous != null && previous != value) { + previous.reconcileContainerOwnerAfterMutation(owner); + } updateReferentHashSlotOwnership(previous, value); + if (!aliasCellMutation) reconcileHashAliasCellOwner(key, value); return result; } - @Override - public void putAll(Map m) { - if (owner.threadShared) { - for (Map.Entry entry - : new StableHashMap<>(m).entrySet()) { - put(entry.getKey(), entry.getValue()); - } - return; - } - boolean hasReferenceEdge = false; - for (Map.Entry e : m.entrySet()) { - if (rootEdge(super.get(e.getKey())) || rootEdge(e.getValue())) { - hasReferenceEdge = true; - break; - } - } - owner.notePackageRootMutationIf(hasReferenceEdge); - for (RuntimeScalar value : m.values()) { - if (owner.threadShared) SharedPerlStorage.publishBlessing(value); - if (value != null) { - value.markContainerOwner(owner); - if (owner.hasDurableElementLifetime()) { - RuntimeScalar.retainUnstashedIoForDurableSlot(value); - } - } - owner.markPackageRootedValue(value); - } - super.putAll(m); - if (!m.isEmpty()) stableMethodFieldCacheRevision++; - } - - @Override - public RuntimeScalar remove(Object key) { - RuntimeScalar previous = super.remove(key); - if (previous != null) { - stableMethodFieldCacheRevision++; - if (owner.isHintHash && !owner.suppressHintHashLifecycleCleanup) { - MortalList.deferDestroyForContainerClear(java.util.Collections.singletonList(previous)); - } - owner.notePackageRootMutation(previous, null); - } - return previous; - } - - @Override - public void clear() { - if (!isEmpty()) { - stableMethodFieldCacheRevision++; - if (owner.isHintHash && !owner.suppressHintHashLifecycleCleanup) { - MortalList.deferDestroyForContainerClear(super.values()); - } - owner.notePackageRootClear(super.values()); - } - super.clear(); - } - - private long stableMethodFieldCacheRevision() { - return stableMethodFieldCacheable ? stableMethodFieldCacheRevision : -1; - } - - private void disableStableMethodFieldCaching() { - stableMethodFieldCacheable = false; - } - - private Set> rawEntrySet() { - return super.entrySet(); - } - - private boolean rawContainsValue(Object value) { - return super.containsValue(value); - } - - // These Map APIs can mutate without passing through this wrapper's put/remove hooks. - // Keep the existing Map behavior, but force stable methods back to checked lookups. @Override public RuntimeScalar putIfAbsent(String key, RuntimeScalar value) { disableStableMethodFieldCaching(); - return super.putIfAbsent(key, value); + RuntimeScalar current = get(key); + return current == null ? put(key, value) : current; } @Override public boolean remove(Object key, Object value) { disableStableMethodFieldCaching(); - return super.remove(key, value); + if (!containsKey(key) || !Objects.equals(get(key), value)) return false; + remove(key); + return true; } @Override public boolean replace(String key, RuntimeScalar oldValue, RuntimeScalar newValue) { disableStableMethodFieldCaching(); - return super.replace(key, oldValue, newValue); + if (!containsKey(key) || !Objects.equals(get(key), oldValue)) return false; + put(key, newValue); + return true; } @Override public RuntimeScalar replace(String key, RuntimeScalar value) { disableStableMethodFieldCaching(); - return super.replace(key, value); + if (!containsKey(key)) return null; + return put(key, value); } @Override public void replaceAll(java.util.function.BiFunction function) { disableStableMethodFieldCaching(); - super.replaceAll(function); + Objects.requireNonNull(function); + for (String key : new ArrayList<>(super.keySet())) { + put(key, function.apply(key, get(key))); + } } @Override public RuntimeScalar computeIfAbsent(String key, java.util.function.Function function) { disableStableMethodFieldCaching(); - return super.computeIfAbsent(key, function); + Objects.requireNonNull(function); + RuntimeScalar current = get(key); + if (current != null) return current; + RuntimeScalar computed = function.apply(key); + if (computed != null) put(key, computed); + return computed; } @Override @@ -345,7 +562,13 @@ public RuntimeScalar computeIfPresent(String key, java.util.function.BiFunction function) { disableStableMethodFieldCaching(); - return super.computeIfPresent(key, function); + Objects.requireNonNull(function); + RuntimeScalar current = get(key); + if (current == null) return null; + RuntimeScalar computed = function.apply(key, current); + if (computed == null) remove(key); + else put(key, computed); + return computed; } @Override @@ -353,7 +576,16 @@ public RuntimeScalar compute(String key, java.util.function.BiFunction function) { disableStableMethodFieldCaching(); - return super.compute(key, function); + Objects.requireNonNull(function); + RuntimeScalar current = get(key); + boolean present = current != null || containsKey(key); + RuntimeScalar computed = function.apply(key, current); + if (computed == null) { + if (present) remove(key); + } else { + put(key, computed); + } + return computed; } @Override @@ -361,133 +593,387 @@ public RuntimeScalar merge(String key, RuntimeScalar value, java.util.function.BiFunction function) { disableStableMethodFieldCaching(); - return super.merge(key, value, function); + Objects.requireNonNull(value); + Objects.requireNonNull(function); + RuntimeScalar current = get(key); + RuntimeScalar merged = current == null ? value : function.apply(current, value); + if (merged == null) remove(key); + else put(key, merged); + return merged; } @Override public Set> entrySet() { disableStableMethodFieldCaching(); - return super.entrySet(); + if (entrySetView == null) { + entrySetView = new AbstractSet<>() { + @Override + public int size() { + return RuntimeHashElementMap.this.size(); + } + + @Override + public void clear() { + RuntimeHashElementMap.this.clear(); + } + + @Override + public boolean contains(Object candidate) { + if (!(candidate instanceof Map.Entry entry)) return false; + Object key = entry.getKey(); + return RuntimeHashElementMap.this.containsKey(key) + && Objects.equals(RuntimeHashElementMap.this.get(key), entry.getValue()); + } + + @Override + public boolean remove(Object candidate) { + return candidate instanceof Map.Entry entry + && RuntimeHashElementMap.this.remove(entry.getKey(), entry.getValue()); + } + + @Override + public Iterator> iterator() { + return ownerAwareEntryIterator(); + } + }; + } + return entrySetView; } @Override public Set keySet() { disableStableMethodFieldCaching(); - return super.keySet(); + if (keySetView == null) { + keySetView = new AbstractSet<>() { + @Override + public int size() { + return RuntimeHashElementMap.this.size(); + } + + @Override + public boolean contains(Object key) { + return RuntimeHashElementMap.this.containsKey(key); + } + + @Override + public boolean remove(Object key) { + if (!RuntimeHashElementMap.this.containsKey(key)) return false; + RuntimeHashElementMap.this.remove(key); + return true; + } + + @Override + public void clear() { + RuntimeHashElementMap.this.clear(); + } + + @Override + public Iterator iterator() { + Iterator> delegate = + RuntimeHashElementMap.super.entrySet().iterator(); + return new Iterator<>() { + private Map.Entry currentEntry; + private boolean canRemove; + + @Override + public boolean hasNext() { + return delegate.hasNext(); + } + + @Override + public String next() { + currentEntry = delegate.next(); + canRemove = true; + return currentEntry.getKey(); + } + + @Override + public void remove() { + if (!canRemove) throw new IllegalStateException(); + String removedKey = currentEntry.getKey(); + RuntimeScalar removedValue = currentEntry.getValue(); + delegate.remove(); + removeValueIdentity(removedValue); + retireRemovedValue(removedKey, removedValue); + currentEntry = null; + canRemove = false; + } + }; + } + }; + } + return keySetView; } @Override public Collection values() { - if (trackedValuesView == null) { - trackedValuesView = new AbstractCollection<>() { + if (valuesView == null) { + valuesView = new AbstractCollection<>() { @Override public int size() { return RuntimeHashElementMap.this.size(); } @Override - public boolean contains(Object value) { - return RuntimeHashElementMap.this.rawContainsValue(value); + public void clear() { + RuntimeHashElementMap.this.clear(); } @Override public Iterator iterator() { - Iterator> entries = - RuntimeHashElementMap.this.rawEntrySet().iterator(); + Iterator> delegate = + RuntimeHashElementMap.super.entrySet().iterator(); return new Iterator<>() { - private Map.Entry current; + private Map.Entry currentEntry; + private RuntimeScalar currentValue; + private boolean canRemove; @Override public boolean hasNext() { - return entries.hasNext(); + return delegate.hasNext(); } @Override public RuntimeScalar next() { - current = entries.next(); - return current.getValue(); + currentEntry = delegate.next(); + currentValue = currentEntry.getValue(); + canRemove = true; + return currentValue; } @Override public void remove() { - if (current == null) throw new IllegalStateException(); - String key = current.getKey(); - RuntimeScalar previous = current.getValue(); - entries.remove(); - recordViewRemoval(key, previous); - current = null; + if (!canRemove) throw new IllegalStateException(); + String removedKey = currentEntry.getKey(); + RuntimeScalar removedValue = currentEntry.getValue(); + delegate.remove(); + removeValueIdentity(removedValue); + retireRemovedValue(removedKey, removedValue); + currentEntry = null; + currentValue = null; + canRemove = false; } }; } - - @Override - public void clear() { - RuntimeHashElementMap.this.clear(); - } }; } - return trackedValuesView; + return valuesView; + } + + private Iterator> ownerAwareEntryIterator() { + Iterator> delegate = + RuntimeHashElementMap.super.entrySet().iterator(); + return new Iterator<>() { + private Map.Entry currentEntry; + private String currentKey; + private boolean canRemove; + + @Override + public boolean hasNext() { + return delegate.hasNext(); + } + + @Override + public Map.Entry next() { + Map.Entry entry = delegate.next(); + currentEntry = entry; + currentKey = entry.getKey(); + canRemove = true; + String key = currentKey; + return new Map.Entry<>() { + @Override + public String getKey() { + return key; + } + + @Override + public RuntimeScalar getValue() { + return RuntimeHashElementMap.this.get(key); + } + + @Override + public RuntimeScalar setValue(RuntimeScalar value) { + return RuntimeHashElementMap.this.put(key, value); + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof Map.Entry entry)) return false; + return Objects.equals(key, entry.getKey()) + && Objects.equals(getValue(), entry.getValue()); + } + + @Override + public int hashCode() { + return Objects.hashCode(key) ^ Objects.hashCode(getValue()); + } + }; + } + + @Override + public void remove() { + if (!canRemove) throw new IllegalStateException(); + RuntimeScalar removedValue = currentEntry.getValue(); + delegate.remove(); + removeValueIdentity(removedValue); + retireRemovedValue(currentKey, removedValue); + currentEntry = null; + currentKey = null; + canRemove = false; + } + }; } - private void recordViewRemoval(String key, RuntimeScalar previous) { + private void retireRemovedValue(String key, RuntimeScalar previous) { + if (previous == null) return; stableMethodFieldCacheRevision++; - if (owner.isHintHash && !owner.suppressHintHashLifecycleCleanup - && previous != null) { - MortalList.deferDestroyForContainerClear( - java.util.Collections.singletonList(previous)); + boolean aliasCell = ownsHashAliasCell(key, previous); + if (owner.isHintHash && !owner.suppressHintHashLifecycleCleanup && !aliasCell) { + MortalList.deferDestroyForContainerClear(java.util.Collections.singletonList(previous)); } - owner.notePackageRootMutation(previous, null); + previous.reconcileContainerOwnerAfterMutation(owner); + updateReferentHashSlotOwnership(previous, null); + releaseHashAliasCellOwner(key); } - } - private boolean hasDurableElementLifetime() { - return refCount >= 0 || (PerlRuntime.currentOrNull() != null - && MyVarCleanupStack.isRegistered(this)); - } + @Override + public void putAll(Map m) { + if (m == this) return; + if (m instanceof RuntimeHashElementMap source) { + List> entries = + new ArrayList<>(m.entrySet()); + boolean hasAliases = false; + for (Map.Entry entry : entries) { + if (source.ownsHashAliasCell(entry.getKey(), entry.getValue())) { + hasAliases = true; + break; + } + } + if (hasAliases) { + for (Map.Entry entry : entries) { + String key = entry.getKey(); + RuntimeScalar value = entry.getValue(); + if (source.ownsHashAliasCell(key, value)) { + putAliasedCell(key, value); + } else { + put(key, value); + } + } + return; + } + } + if (owner.threadShared) { + for (Map.Entry entry + : new StableHashMap<>(m).entrySet()) { + put(entry.getKey(), entry.getValue()); + } + return; + } + Set replacedValues = Collections.newSetFromMap( + new IdentityHashMap<>()); + for (Map.Entry e : m.entrySet()) { + RuntimeScalar previous = super.get(e.getKey()); + if (previous != null && previous != e.getValue()) replacedValues.add(previous); + } + for (RuntimeScalar value : m.values()) { + if (owner.threadShared) SharedPerlStorage.publishBlessing(value); + if (value != null) { + if (owner.hasDurableElementLifetime()) { + RuntimeScalar.retainUnstashedIoForDurableSlot(value); + } + } + } + for (Map.Entry entry : m.entrySet()) { + RuntimeScalar previous = super.get(entry.getKey()); + RuntimeScalar replacement = entry.getValue(); + if (previous != replacement) { + removeValueIdentity(previous); + addValueIdentity(replacement); + } + super.put(entry.getKey(), replacement); + owner.traceDestroyedCursorMutation(entry.getKey(), replacement); + } + if (!m.isEmpty()) stableMethodFieldCacheRevision++; + for (RuntimeScalar value : m.values()) { + if (value != null) value.markContainerOwner(owner); + owner.markPackageRootedValue(value); + refreshStoredUntrackedOwner(value); + } + for (RuntimeScalar value : replacedValues) { + value.reconcileContainerOwnerAfterMutation(owner); + } + for (Map.Entry entry : m.entrySet()) { + reconcileHashAliasCellOwner(entry.getKey(), super.get(entry.getKey())); + } + } - boolean isPackageRootedHash() { - return isPackageGlobalRoot || isGlobalPackageHash; - } + private void refreshStoredUntrackedOwner(RuntimeScalar value) { + // Bulk copy reconstructs a replacement map before assigning it to + // owner.elements. Refresh only once this map is installed. + if (value != null && owner.elements == this) { + if (owner.isPackageRootedHash()) { + value.markPrepopulatedPackageAggregateOwner(owner); + } + value.reconcileContainerOwnerAfterMutation(owner); + } + } - private static boolean rootEdge(RuntimeScalar value) { - return value != null - && (value.type & REFERENCE_BIT) != 0 - && value.value instanceof RuntimeBase; - } + @Override + public RuntimeScalar remove(Object key) { + RuntimeScalar previous = super.remove(key); + removeValueIdentity(previous); + retireRemovedValue((String) key, previous); + return previous; + } - private void notePackageRootMutation(RuntimeScalar oldValue, RuntimeScalar newValue) { - notePackageRootMutationIf(rootEdge(oldValue) || rootEdge(newValue)); - } + @Override + public void clear() { + if (!isEmpty()) { + stableMethodFieldCacheRevision++; + List> removedEntries = + new ArrayList<>(RuntimeHashElementMap.super.entrySet()); + List removed = new ArrayList<>(values()); + if (owner.isHintHash && !owner.suppressHintHashLifecycleCleanup) { + MortalList.deferDestroyForContainerClear(removed); + } + super.clear(); + valueIdentityCounts.clear(); + releaseAllHashAliasCellOwners(); + for (Map.Entry entry : removedEntries) { + RuntimeScalar scalar = entry.getValue(); + if (scalar != null) scalar.reconcileContainerOwnerAfterMutation(owner); + updateReferentHashSlotOwnership(scalar, null); + } + return; + } + super.clear(); + valueIdentityCounts.clear(); + releaseAllHashAliasCellOwners(); + } - private void notePackageRootMutationIf(boolean hasReferenceEdge) { - if (!hasReferenceEdge) return; - if (isPackageRootedHash()) { - MortalList.invalidateExternalRootSnapshot(); + private long stableMethodFieldCacheRevision() { + return stableMethodFieldCacheable ? stableMethodFieldCacheRevision : -1; } - MortalList.invalidateFullRootSnapshotIfReachable(this); - } - private void notePackageRootClear(Collection values) { - boolean hasReferenceEdge = false; - for (RuntimeScalar value : values) { - if (rootEdge(value)) { - hasReferenceEdge = true; - break; - } + private void disableStableMethodFieldCaching() { + stableMethodFieldCacheable = false; } - notePackageRootMutationIf(hasReferenceEdge); + } - void notePackageRootMutation() { - if (isPackageRootedHash()) { - MortalList.invalidateExternalRootSnapshot(); - } - MortalList.invalidateFullRootSnapshotIfReachable(this); + private boolean hasDurableElementLifetime() { + return isRefCountTracked() || (PerlRuntime.currentOrNull() != null + && MyVarCleanupStack.isRegistered(this)); + } + + boolean isPackageRootedHash() { + return isPackageGlobalRoot || isGlobalPackageHash; } void markPackageRootedValue(RuntimeScalar value) { if (!isPackageRootedHash() || value == null) return; value.isPackageGlobalRoot = true; + value.markContainerOwner(this); if (value.value instanceof RuntimeBase rb) { rb.storedInPackageGlobal = true; } @@ -572,7 +1058,9 @@ private static RuntimeHash createHashInternal(RuntimeBase value, String oddWarni RuntimeScalar val = iterator.hasNext() ? new RuntimeScalar(iterator.next()) : new RuntimeScalar(); resultHash.put(key, val); if (trackValues) { - RuntimeScalar.incrementRefCountForContainerStore(val); + RuntimeScalar.incrementRefCountForContainerStore( + val, PerlOwnerSlot.Kind.HASH_ELEMENT); + val.associateCountedAggregateOwner(result); } } return result; @@ -597,7 +1085,9 @@ private static RuntimeHash createHashNoWarn(RuntimeBase value, boolean trackValu RuntimeScalar val = iterator.hasNext() ? new RuntimeScalar(iterator.next()) : new RuntimeScalar(); resultHash.put(key, val); if (trackValues) { - RuntimeScalar.incrementRefCountForContainerStore(val); + RuntimeScalar.incrementRefCountForContainerStore( + val, PerlOwnerSlot.Kind.HASH_ELEMENT); + val.associateCountedAggregateOwner(result); } } return result; @@ -693,69 +1183,76 @@ public RuntimeArray setFromList(RuntimeList value) { // incrementRefCountForContainerStore, which would create unmatched // refCounts that prevent DESTROY from firing. RuntimeArray materializedList = new RuntimeArray(); - Iterator iterator = value.iterator(); - while (iterator.hasNext()) { - materializedList.elements.add(new RuntimeScalar(iterator.next())); - } - - validateRequireHookAssignments(materializedList); - - // Store the original list size for scalar context - int originalSize = materializedList.elements.size(); + try { + Iterator iterator = value.iterator(); + while (iterator.hasNext()) { + materializedList.elements.add(new RuntimeScalar(iterator.next())); + } - // Warn about odd elements - if (originalSize % 2 != 0 && !suppressOddAssignmentWarning) { - // Single hash/array reference: "Reference found where even-sized list expected" - // Other odd cases: "Odd number of elements in hash assignment" - String warning; - if (originalSize == 1) { - RuntimeScalar first = materializedList.elements.get(0); - if (first.type == RuntimeScalarType.HASHREFERENCE || first.type == RuntimeScalarType.ARRAYREFERENCE) { - warning = "Reference found where even-sized list expected"; + validateRequireHookAssignments(materializedList); + + // Store the original list size for scalar context + int originalSize = materializedList.elements.size(); + + // Warn about odd elements + if (originalSize % 2 != 0 && !suppressOddAssignmentWarning) { + // Single hash/array reference: "Reference found where even-sized list expected" + // Other odd cases: "Odd number of elements in hash assignment" + String warning; + if (originalSize == 1) { + RuntimeScalar first = materializedList.elements.get(0); + if (first.type == RuntimeScalarType.HASHREFERENCE || first.type == RuntimeScalarType.ARRAYREFERENCE) { + warning = "Reference found where even-sized list expected"; + } else { + warning = "Odd number of elements in hash assignment"; + } } else { warning = "Odd number of elements in hash assignment"; } - } else { - warning = "Odd number of elements in hash assignment"; + WarnDie.warnWithCategory( + new RuntimeScalar(warning), + RuntimeScalarCache.scalarEmptyString, "misc"); } - WarnDie.warnWithCategory( - new RuntimeScalar(warning), - RuntimeScalarCache.scalarEmptyString, "misc"); - } - // Clear existing elements but keep the same Map instance to preserve capacity - MortalList.deferDestroyForContainerClear(this.elements.values()); - this.elements.clear(); - if (this.byteKeys != null) this.byteKeys.clear(); - // Reset each() iterator so it doesn't throw ConcurrentModificationException - // on the next each() call after this hash is re-populated. - hashIterator = null; - - // Populate the hash from the materialized list - iterator = materializedList.iterator(); - while (iterator.hasNext()) { - RuntimeScalar keyScalar = iterator.next(); - String key = keyScalar.toString(); - // Track the key's byte/UTF-8 type for correct semantics in keys() - if (keyScalar.type == BYTE_STRING) { - markKeyByte(key, true); + // Clear existing elements but keep the same Map instance to preserve capacity + MortalList.deferDestroyForContainerClear(this.elements.values()); + this.elements.clear(); + if (this.byteKeys != null) this.byteKeys.clear(); + // Reset each() iterator so it doesn't throw ConcurrentModificationException + // on the next each() call after this hash is re-populated. + resetIterator(); + + // Populate the hash from the materialized list + iterator = materializedList.iterator(); + while (iterator.hasNext()) { + RuntimeScalar keyScalar = iterator.next(); + String key = keyScalar.toString(); + // Track the key's byte/UTF-8 type for correct semantics in keys() + if (keyScalar.type == BYTE_STRING) { + markKeyByte(key, true); + } + // Create a new RuntimeScalar to properly handle aliasing and avoid read-only issues + RuntimeScalar val = iterator.hasNext() ? new RuntimeScalar(iterator.next()) : new RuntimeScalar(); + storeOwnedElement(key, null, val); } - // Create a new RuntimeScalar to properly handle aliasing and avoid read-only issues - RuntimeScalar val = iterator.hasNext() ? new RuntimeScalar(iterator.next()) : new RuntimeScalar(); - markPackageRootedValue(val); - this.elements.put(key, val); - RuntimeScalar.incrementRefCountForContainerStore(val); - } - // Create a RuntimeArray that wraps this hash - // In list context: returns the deduplicated key-value pairs - // In scalar context: should return the original list size - RuntimeArray result = new RuntimeArray(this); - // Store the original size as an annotation for scalar context - result.scalarContextSize = originalSize; - // Flush deferred DESTROY for refs removed from the container - MortalList.flush(); - yield result; + // Create a RuntimeArray that wraps this hash + // In list context: returns the deduplicated key-value pairs + // In scalar context: should return the original list size + RuntimeArray result = new RuntimeArray(this); + // Store the original size as an annotation for scalar context + result.scalarContextSize = originalSize; + // Release displaced values created by this assignment, but + // preserve pending returns owned by the surrounding expression. + MortalList.flushAboveMark(); + yield result; + } finally { + // These scalar copies only stage the RHS while the hash is + // replaced. Keeping them in this unowned Java-side array + // would leave untracked-reference owner slots active after + // the destination has acquired its own value cells. + materializedList.elements.clear(); + } } case AUTOVIVIFY_HASH -> { AutovivificationHash.vivify(this); @@ -767,39 +1264,50 @@ public RuntimeArray setFromList(RuntimeList value) { // where @t2 is also tied and we need to fetch values before clearing // Use direct element addition (not push()) — see PLAIN_HASH comment. RuntimeArray materializedList = new RuntimeArray(); - Iterator iterator = value.iterator(); - while (iterator.hasNext()) { - materializedList.elements.add(new RuntimeScalar(iterator.next())); - } + try { + Iterator iterator = value.iterator(); + while (iterator.hasNext()) { + materializedList.elements.add(new RuntimeScalar(iterator.next())); + } - // %^H is lexically cloned by perl. Assigning an empty list - // in an inner hint scope therefore detaches that clone from a - // tied outer hint hash; it must not dispatch CLEAR on the - // outer tie object (which may deliberately omit CLEAR). - if (isHintHash && materializedList.elements.isEmpty()) { - elements = newElementMap(); - type = PLAIN_HASH; - yield new RuntimeArray(); - } + // %^H is lexically cloned by perl. Assigning an empty list + // in an inner hint scope therefore detaches that clone from a + // tied outer hint hash; it must not dispatch CLEAR on the + // outer tie object (which may deliberately omit CLEAR). + if (isHintHash && materializedList.elements.isEmpty()) { + elements = newElementMap(); + type = PLAIN_HASH; + yield new RuntimeArray(); + } - // Now clear and repopulate from the materialized list - TieHash.tiedClear(this); - RuntimeArray result = new RuntimeArray(); - iterator = materializedList.iterator(); - while (iterator.hasNext()) { - RuntimeScalar key = iterator.next(); - RuntimeScalar val = iterator.hasNext() ? new RuntimeScalar(iterator.next()) : new RuntimeScalar(); - TieHash.tiedStore(this, key, val); - RuntimeArray.push(result, key); - RuntimeArray.push(result, val); + // Now clear and repopulate from the materialized list + TieHash.tiedClear(this); + RuntimeArray result = new RuntimeArray(); + iterator = materializedList.iterator(); + while (iterator.hasNext()) { + RuntimeScalar key = iterator.next(); + RuntimeScalar val = iterator.hasNext() ? new RuntimeScalar(iterator.next()) : new RuntimeScalar(); + TieHash.tiedStore(this, key, val); + RuntimeArray.push(result, key); + RuntimeArray.push(result, val); + } + yield result; + } finally { + materializedList.elements.clear(); } - yield result; } case READONLY_HASH -> throw new PerlCompilerException("Modification of a read-only value attempted"); default -> throw new IllegalStateException("Unknown array type: " + type); }; } + /** Store B's raw SV pointer view without adding a Perl owner edge. */ + public void putBObjectReference(String key, RuntimeScalar source) { + RuntimeScalar view = new RuntimeScalar(source); + view.nonOwningBObjectReference = true; + put(key, view); + } + /** * Adds a key-value pair to the hash. * @@ -830,7 +1338,7 @@ && isAggregateClearAssignment(existing, value)) { if (value == null) existing.undefine(); else value.addToScalar(existing); } else { - elements.put(key, independentSlot(key, value)); + storeOwnedElement(key, existing, value); } } case AUTOVIVIFY_HASH -> { @@ -846,11 +1354,10 @@ && isAggregateClearAssignment(existing, value)) { if (value == null) existing.undefine(); else value.addToScalar(existing); } else { - elements.put(key, independentSlot(key, value)); + storeOwnedElement(key, existing, value); } } case TIED_HASH -> { - notePackageRootMutation(null, value); markPackageRootedValue(value); TieHash.tiedStore(this, new RuntimeScalar(key), value); } @@ -859,6 +1366,36 @@ && isAggregateClearAssignment(existing, value)) { } } + private void storeOwnedElement(String key, RuntimeScalar previous, RuntimeScalar value) { + RuntimeScalar stored = independentSlot(key, value); + if (threadShared) { + SharedPerlStorage.validateStoredValue(stored); + SharedPerlStorage.publishBlessing(stored); + } + RuntimeScalar.transitionContainerSlots( + previous == null ? Collections.emptyList() : Collections.singletonList(previous), + Collections.singletonList(stored), + PerlOwnerSlot.Kind.HASH_ELEMENT, + this, + () -> elements.put(key, stored), + displaced -> { + if (PerlRuntime.currentOrNull() != null) { + MortalList.deferDestroyForContainerClear(displaced); + } else { + for (RuntimeScalar old : displaced) { + if (old.refCountOwned + && old.value instanceof RuntimeBase referent) { + // Host-side graph construction has no Perl callbacks or + // mortal queue, but replacing a field still retires its + // counted edge. + RuntimeScalar.releaseCountedOwnerWithoutPerlRuntime( + old, referent, "RuntimeHash.storeOwnedElement"); + } + } + } + }); + } + private void warnHashIteratorInsertion(RuntimeScalar existing) { if (existing != null || hashIterator == null || hashIteratorInsertionWarningIssued) { return; @@ -941,11 +1478,16 @@ public void putClonedElement(String key, RuntimeScalar value) { if (allHashValuesLocked || (lockedHashValues != null && lockedHashValues.contains(key))) { throw new PerlCompilerException("Modification of a read-only value attempted"); } - elements.put(key, value == null ? new RuntimeScalar() : value); - if (value != null) { - value.markContainerOwner(this); - RuntimeScalar.incrementRefCountForContainerStore(value); + storeOwnedElement(key, elements.get(key), value); + } + + /** Store a cloned alias slot while retaining the cloned scalar cell identity. */ + public void putClonedAliasElement(String key, RuntimeScalar cell) { + validateHashKey(key, "write"); + if (allHashValuesLocked || (lockedHashValues != null && lockedHashValues.contains(key))) { + throw new PerlCompilerException("Modification of a read-only value attempted"); } + aliasScalarCell(key, cell); } /** @@ -1291,7 +1833,12 @@ public RuntimeScalar deleteInContext(RuntimeScalar key, int callContext) { return switch (type) { case PLAIN_HASH -> { String k = key.toString(); - var value = elements.remove(k); + RuntimeScalar value = elements.get(k); + boolean aliasCell = ownsHashAliasCell(k, value); + RuntimeScalar aliasReturnOwner = aliasCell + && callContext != RuntimeContextType.VOID + ? RuntimeScalar.retainEvalReturnValue(value) : null; + value = elements.remove(k); if (byteKeys != null) byteKeys.remove(k); if (value != null) { if (value.type == RuntimeScalarType.TIED_SCALAR) { @@ -1307,6 +1854,14 @@ public RuntimeScalar deleteInContext(RuntimeScalar key, int callContext) { RuntimeScalar.scopeExitCleanup(value); yield fetchedValue; } + if (aliasCell) { + if (callContext == RuntimeContextType.VOID) yield new RuntimeScalar(); + MortalList.deferDecrementIfTracked(aliasReturnOwner); + // Keep the deleted scalar cell itself as the loose + // lvalue result. The separate return owner protects a + // referenced value after the hash alias edge retires. + yield value; + } // Schedule deferred refCount decrement — fires at next safe point // (setLarge or RuntimeCode.apply). This prevents premature DESTROY // when the caller captures the return value. @@ -1347,7 +1902,12 @@ public RuntimeScalar deleteInContext(String key, int callContext) { validateHashDelete(key); return switch (type) { case PLAIN_HASH -> { - var value = elements.remove(key); + RuntimeScalar value = elements.get(key); + boolean aliasCell = ownsHashAliasCell(key, value); + RuntimeScalar aliasReturnOwner = aliasCell + && callContext != RuntimeContextType.VOID + ? RuntimeScalar.retainEvalReturnValue(value) : null; + value = elements.remove(key); if (byteKeys != null) byteKeys.remove(key); if (value != null) { if (value.type == RuntimeScalarType.TIED_SCALAR) { @@ -1359,6 +1919,13 @@ public RuntimeScalar deleteInContext(String key, int callContext) { RuntimeScalar.scopeExitCleanup(value); yield fetchedValue; } + if (aliasCell) { + if (callContext == RuntimeContextType.VOID) yield new RuntimeScalar(); + MortalList.deferDecrementIfTracked(aliasReturnOwner); + // Preserve refaliasing for a loose delete-result lvalue; + // the independent return owner only supplies lifetime. + yield value; + } // Schedule deferred refCount decrement (see delete(RuntimeScalar) above) MortalList.deferDecrementIfTracked(value); MortalList.deferIoOwnerRelease(value); @@ -1417,6 +1984,9 @@ public void dynamicRestoreState() { // Copying the scalar wrapper restores the same value but not the // original referent, which is observable through refaliasing. RuntimeScalar savedValue = existed ? elements.get(key) : null; + boolean savedAliasCell = existed && ownsHashAliasCell(key, savedValue); + PerlOwnerSlot savedAliasOwner = savedAliasCell + ? newHashAliasCellOwner(savedValue) : null; RuntimeScalar returnValue = existed ? new RuntimeScalar(elements.get(key)) : new RuntimeScalar(); RuntimeHash self = this; @@ -1429,10 +1999,30 @@ public void dynamicSaveState() { @Override public void dynamicRestoreState() { - if (existed) { - self.elements.put(key, savedValue); - } else { - self.elements.remove(key); + RuntimeScalar current = self.elements.get(key); + boolean displacedWasAlias = self.ownsHashAliasCell(key, current); + try { + RuntimeScalar displaced; + if (existed) { + displaced = savedAliasCell + ? self.aliasScalarCell(key, savedValue) + : self.elements.put(key, savedValue); + } else { + displaced = self.elements.remove(key); + } + if (!savedAliasCell && !displacedWasAlias + && displaced != null && displaced != savedValue) { + // Hint-hash map mutations already defer their displaced + // values. Ordinary hashes need the same cleanup here, + // where the localized slot is retired during unwind. + if (!self.isHintHash || self.suppressHintHashLifecycleCleanup) { + MortalList.deferDestroyForContainerClear( + Collections.singletonList(displaced)); + } + MortalList.flush(); + } + } finally { + if (savedAliasOwner != null) savedAliasOwner.release(); } } }); @@ -1463,16 +2053,16 @@ public RuntimeList deleteLocalSlice(RuntimeList value) { */ public RuntimeScalar createReference() { // Opt into refCount tracking when a reference to a named hash is created. - // Named hashes start at refCount=-1 (untracked). When \%hash creates a - // reference, we transition to refCount=0 (tracked, zero external refs) + // Named hashes begin untracked. When \%hash creates a reference, we + // enter tracked mode with zero counted external refs. // and set localBindingExists=true to indicate a JVM local variable slot // holds a strong reference not counted in refCount. // This allows setLargeRefCounted to properly count references, and // scopeExitCleanupHash to skip element cleanup when external refs exist. // Without this, scope exit of `my %hash` would destroy elements even when // \%hash is stored elsewhere (e.g., $obj->{data} = \%hash). - if (this.refCount == -1) { - this.refCount = 0; + if (this.isRefCountUntracked()) { + this.startRefCountTracking(); this.localBindingExists = true; } RuntimeScalar result = new RuntimeScalar(); @@ -1497,10 +2087,10 @@ public RuntimeScalar createReference() { */ public RuntimeScalar createAnonymousReference() { // Birth-track the anonymous hash (same as {...} constructor path). - // refCount=0 means tracked with zero counted containers; setLargeRefCounted + // A tracked zero count means no counted containers; setLargeRefCounted // will bump to 1 when this reference is assigned to a variable. - if (this.refCount == -1) { - this.refCount = 0; + if (this.isRefCountUntracked()) { + this.startRefCountTracking(); } RuntimeScalar result = new RuntimeScalar(); result.type = HASHREFERENCE; @@ -1510,17 +2100,19 @@ public RuntimeScalar createAnonymousReference() { @Override public RuntimeScalar createReferenceWithTrackedElements() { - // Birth-track anonymous hashes: set refCount=0 so setLarge() can + // Birth-track anonymous hashes so setLarge() can // accurately count strong references. Anonymous hashes are only // reachable through references (no lexical variable slot), so // refCount is complete and reaching 0 means truly no strong refs. - if (this.refCount == -1) { - this.refCount = 0; + if (this.isRefCountUntracked()) { + this.startRefCountTracking(); } RuntimeScalar result = createAnonymousReference(); for (RuntimeScalar elem : this.elements.values()) { RuntimeScalar.retainUnstashedIoForDurableSlot(elem); - RuntimeScalar.incrementRefCountForContainerStore(elem); + RuntimeScalar.incrementRefCountForContainerStore( + elem, PerlOwnerSlot.Kind.HASH_ELEMENT); + if (elem != null) elem.associateCountedAggregateOwner(this); } return result; } @@ -1745,7 +2337,7 @@ public RuntimeArray keys() { } isKey = !isKey; } - hashIterator = null; // keys resets the iterator + resetIterator(); // keys resets the iterator // Set scalarContextSize so that keys() in scalar context returns the count list.scalarContextSize = list.elements.size(); return list; @@ -1756,7 +2348,7 @@ public RuntimeArray keys() { } if (this.elements.isEmpty()) { - hashIterator = null; + resetIterator(); return EMPTY_KEYS; } @@ -1764,7 +2356,7 @@ public RuntimeArray keys() { for (String key : elements.keySet()) { RuntimeArray.push(list, createKeyScalar(key)); } - hashIterator = null; // keys resets the iterator + resetIterator(); // keys resets the iterator // Set scalarContextSize so that keys() in scalar context returns the count list.scalarContextSize = list.elements.size(); return list; @@ -1773,7 +2365,7 @@ public RuntimeArray keys() { @Override public RuntimeBase keys(int ctx) { // keys() resets the iterator - hashIterator = null; + resetIterator(); if (ctx == RuntimeContextType.SCALAR) { // In scalar context, return the key count without materializing the key list. @@ -1832,7 +2424,7 @@ public RuntimeArray values() { for (RuntimeScalar tiedKey : keys) { RuntimeArray.push(list, TieHash.tiedFetch(this, tiedKey)); } - hashIterator = null; // values resets the iterator + resetIterator(); // values resets the iterator // Set scalarContextSize so that values() in scalar context returns the count. // Without this, when `values %h` is the last expression of a sub called in // scalar context, getList() copies the elements into a RuntimeList whose @@ -1849,7 +2441,7 @@ public RuntimeArray values() { for (RuntimeScalar value : elements.values()) { list.elements.add(value); // push an alias to the value (direct reference, not a copy) } - hashIterator = null; // values resets the iterator + resetIterator(); // values resets the iterator // Mirror keys(): mark this array so scalar context returns the count, not the last value. list.scalarContextSize = list.elements.size(); return list; @@ -1878,7 +2470,7 @@ public RuntimeList each(int ctx) { } return new RuntimeList(hashIterator.next(), hashIterator.next()); } - hashIterator = null; + resetIterator(); return new RuntimeList(); } @@ -1992,10 +2584,9 @@ public boolean getBooleanRef() { public RuntimeHash undefine() { if (this.type == TIED_HASH) { TieHash.tiedClear(this); - hashIterator = null; + resetIterator(); return this; } - notePackageRootClear(this.elements.values()); // Fast path: if no value could possibly fire a DESTROY, use the // old one-shot path (one flush total instead of N flushes). The // slow progressive path below is only required when at least one @@ -2003,18 +2594,26 @@ public RuntimeHash undefine() { // the remaining hash entries (op/undef.t 19-35, bug 3096). // // Without this fast path, large schema-style hashes paid - // O(N) flushes + auto-sweep checks per `undef %hash`, which under + // O(N) flushes + automatic root checks per `undef %hash`, which under // parallel-load DBIC tests pushed t/cdbi/68 / t/96 / t/debug/core // past their 300s harness timeout. if (!hasDestroyableValues()) { + List removed = new ArrayList<>(this.elements.values()); MortalList.deferDestroyForContainerClear(this.elements.values()); if (this.type == PLAIN_HASH) { + Map previous = this.elements; this.elements = newElementMap(); + if (previous instanceof RuntimeHashElementMap map) { + map.releaseAllHashAliasCellOwners(); + } } else { this.elements.clear(); } + for (RuntimeScalar value : removed) { + if (value != null) value.reconcileContainerOwnerAfterMutation(this); + } this.byteKeys = null; - hashIterator = null; + resetIterator(); MortalList.flush(); return this; } @@ -2031,11 +2630,14 @@ public RuntimeHash undefine() { Map.Entry entry = it.next(); String key = entry.getKey(); RuntimeScalar value = entry.getValue(); + boolean aliasCell = ownsHashAliasCell(key, value); it.remove(); - notePackageRootMutation(value, null); + if (value != null) value.reconcileContainerOwnerAfterMutation(this); if (this.byteKeys != null) this.byteKeys.remove(key); // Defer DESTROY for this one value, then flush so it runs now. - MortalList.deferDestroyForContainerClear(java.util.Collections.singletonList(value)); + if (!aliasCell) { + MortalList.deferDestroyForContainerClear(java.util.Collections.singletonList(value)); + } MortalList.flush(); } // For PLAIN_HASH, reset to a fresh StableHashMap with default capacity @@ -2043,7 +2645,7 @@ public RuntimeHash undefine() { this.elements = newElementMap(); } this.byteKeys = null; - hashIterator = null; + resetIterator(); return this; } @@ -2123,12 +2725,21 @@ public void dynamicSaveState() { this.type = PLAIN_HASH; } + @Override + public RuntimeBase suspendedOwnerValue() { + return this; + } + /** * Restores the hash to the last saved state. * This method pops the most recent state from the dynamic state stack and restores it. */ @Override public void dynamicRestoreState() { + restoreDynamicState(false); + } + + private void restoreDynamicState(boolean preserveSuspendedValues) { Stack dynamicStateStack = dynamicStateStack(); if (!dynamicStateStack.isEmpty()) { // Restore the elements map and blessId from the most recent saved state @@ -2138,25 +2749,35 @@ public void dynamicRestoreState() { // Without this, `local %hash = (key => $obj)` where $obj is tracked // would leak refCounts because the local elements are replaced without // ever going through scopeExitCleanup. - MortalList.deferDestroyForContainerClear(this.elements.values()); + if (!preserveSuspendedValues) { + MortalList.deferDestroyForContainerClear(this.elements.values()); + } // Real Perl semantics: a `local %h` that gets `bless`ed during the // local scope must fire DESTROY when restored — the local'd // temporary is conceptually freed. PerlOnJava reuses the same HV, // so we fire DESTROY explicitly. See RuntimeArray.dynamicRestoreState // for the equivalent fix for arrays. - if (this.blessId != 0 && this.blessId != previousState.blessId) { + if (!preserveSuspendedValues + && this.blessId != 0 && this.blessId != previousState.blessId) { int savedBlessId = this.blessId; int savedRefCount = this.refCount; + RefCountTrackingState savedRefCountTrackingState = + this.refCountTrackingState(); boolean savedDestroyFired = this.destroyFired; - this.refCount = Integer.MIN_VALUE; + RuntimeBase.PerlLifecycleState savedLifecycleState = this.perlLifecycleState(); DestroyDispatch.callDestroy(this); this.destroyFired = savedDestroyFired; - this.refCount = savedRefCount; + this.restoreRefCountState(savedRefCount, savedRefCountTrackingState); this.blessId = savedBlessId; + this.restorePerlLifecycleState(savedLifecycleState); + } + Map replacedElements = this.elements; + this.elements = newElementMap(previousState.elements); + if (replacedElements instanceof RuntimeHashElementMap map) { + map.releaseAllHashAliasCellOwners(); } - notePackageRootClear(this.elements.values()); - this.elements = previousState.elements; - notePackageRootClear(this.elements.values()); + refreshUntrackedElementOwners(); + previousState.elements.clear(); if (isPackageRootedHash()) { for (RuntimeScalar value : this.elements.values()) { markPackageRootedValue(value); @@ -2177,7 +2798,7 @@ public Object dynamicSuspendState() { activeState.blessId = this.blessId; activeState.byteKeys = this.byteKeys != null ? new HashSet<>(this.byteKeys) : null; activeState.elements.putAll(this.elements); - dynamicRestoreState(); + restoreDynamicState(true); return activeState; } @@ -2189,6 +2810,7 @@ public void dynamicResumeState(Object token) { this.blessId = activeState.blessId; this.byteKeys = activeState.byteKeys != null ? new HashSet<>(activeState.byteKeys) : null; this.elements.putAll(activeState.elements); + activeState.elements.clear(); } } @@ -2280,7 +2902,7 @@ public void remove() { */ private class RuntimeTiedHashIterator implements Iterator { private RuntimeScalar currentKey; // last key returned by FIRSTKEY/NEXTKEY (passed to next NEXTKEY) - private RuntimeBase currentKeyOwner; // explicit Perl lifetime hold for a reference key + private PerlOwnerSlot currentKeyOwnerSlot; private RuntimeScalar pendingKey; // key fetched by hasNext() but not yet consumed by next() private boolean returnKey; // true: next() returns a key; false: next() returns the value private boolean started; // whether FIRSTKEY has been called @@ -2292,7 +2914,7 @@ public RuntimeTiedHashIterator() { this.returnKey = true; this.started = false; this.currentKey = null; - this.currentKeyOwner = null; + this.currentKeyOwnerSlot = null; this.pendingKey = null; } @@ -2320,10 +2942,13 @@ public boolean hasNext() { pendingKey = TieHash.tiedFirstKey(RuntimeHash.this); started = true; } else { - pendingKey = TieHash.tiedNextKey(RuntimeHash.this, currentKey); - // NEXTKEY has consumed the previous key. Its lifetime ends - // before the newly returned key becomes the iterator state. - releaseCurrentKey(); + try { + pendingKey = TieHash.tiedNextKey(RuntimeHash.this, currentKey); + } finally { + // NEXTKEY consumes the previous key even when the tied + // method throws. Release before retaining the replacement. + releaseCurrentKey(); + } } } @@ -2344,7 +2969,7 @@ public RuntimeScalar next() { if (returnKey) { // Return the key and prepare to return its value next currentKey = pendingKey; - retainCurrentKey(); + currentKeyOwnerSlot = retainIteratorKey(currentKey); pendingKey = null; returnKey = false; return new RuntimeScalar(currentKey); @@ -2368,26 +2993,29 @@ public void remove() { throw new UnsupportedOperationException("Remove not supported for tied hash iterator"); } - private void retainCurrentKey() { - if ((currentKey.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && currentKey.value instanceof RuntimeBase base && base.refCount >= 0) { - base.traceRefCount(+1, "RuntimeTiedHashIterator current key"); - base.refCount++; - base.acquireTransientTraceOwner("tied hash iterator key", "RuntimeHash.RuntimeTiedHashIterator"); - currentKeyOwner = base; + private PerlOwnerSlot retainIteratorKey(RuntimeScalar key) { + if (key == null + || (key.type & RuntimeScalarType.REFERENCE_BIT) == 0 + || !(key.value instanceof RuntimeBase base) + || base.isPerlDestroyed()) { + return null; } + PerlOwnerSlot slot = new PerlOwnerSlot( + PerlOwnerSlot.Kind.TIED_HASH_ITERATOR_KEY); + slot.acquireCountedNativeOwner(base, "RuntimeTiedHashIterator retains key"); + return slot; } private void releaseCurrentKey() { - if (currentKeyOwner == null) return; - RuntimeBase base = currentKeyOwner; - currentKeyOwner = null; - base.traceRefCount(-1, "RuntimeTiedHashIterator current key release"); - base.releaseTransientTraceOwner("tied hash iterator key", "RuntimeHash.RuntimeTiedHashIterator"); - if (base.refCount > 0 && --base.refCount == 0) { - base.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(base); - } + PerlOwnerSlot slot = currentKeyOwnerSlot; + currentKeyOwnerSlot = null; + currentKey = null; + releaseIteratorKey(slot); + } + + private void releaseIteratorKey(PerlOwnerSlot slot) { + if (slot == null) return; + slot.releaseNativeOwner(); } } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeHashProxyEntry.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeHashProxyEntry.java index a14e72a41b..d546372081 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeHashProxyEntry.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeHashProxyEntry.java @@ -8,7 +8,9 @@ * when they are accessed. */ public class RuntimeHashProxyEntry extends RuntimeBaseProxy { - private static Stack dynamicStateStack() { + record SavedHashElement(RuntimeScalar value, PerlOwnerSlot aliasOwner) {} + + private static Stack dynamicStateStack() { return PerlRuntime.current().executionState().hashProxyStates; } @@ -34,6 +36,24 @@ public RuntimeHash getParent() { return parent; } + @Override + RuntimeBase argumentAliasContainer() { + return parent; + } + + @Override + boolean hasLivePerlValueOwner() { + return lvalue != null && parent.containsElementCellIdentity(lvalue); + } + + @Override + boolean hasLivePerlValueOwner(boolean requirePersistentParent) { + return hasLivePerlValueOwner() + && (requirePersistentParent + ? parent.hasPersistentPerlStrongOwnerIdentity() + : parent.hasCurrentPerlStorageOwner()); + } + /** * Constructs a RuntimeHashProxyEntry with key type tracking. * @@ -150,8 +170,7 @@ public RuntimeScalar set(RuntimeScalar value) { public RuntimeScalar aliasToReference(RuntimeScalar reference) { if (parent.threadShared) SharedPerlStorage.validateStoredValue(reference); RuntimeScalar referent = reference.refAliasScalarReference(); - parent.notePackageRootMutation(); - parent.elements.put(key, referent); + parent.aliasScalarCell(key, referent); parent.markKeyByte(key, byteKey); parent.markPackageRootedValue(referent); this.lvalue = referent; @@ -163,7 +182,6 @@ public RuntimeScalar aliasToReference(RuntimeScalar reference) { /** Replace this hash slot with an array or hash reference from an aggregate refalias. */ public RuntimeScalar aliasToAggregateReference(RuntimeScalar reference) { if (parent.threadShared) SharedPerlStorage.validateStoredValue(reference); - parent.notePackageRootMutation(); parent.elements.put(key, reference); parent.markKeyByte(key, byteKey); parent.markPackageRootedValue(reference); @@ -187,12 +205,16 @@ public void dynamicSaveState() { } else { // Preserve the actual hash slot, not merely its value. Refaliasing // can make the slot's scalar identity observable after local() unwinds. - dynamicStateStack().push(this.lvalue); + PerlOwnerSlot savedAliasOwner = null; + if (parent.ownsHashAliasCell(key, this.lvalue)) { + savedAliasOwner = new PerlOwnerSlot(PerlOwnerSlot.Kind.HASH_ALIAS_CELL); + savedAliasOwner.acquireHashAliasCellIdentity(this.lvalue, parent); + } + dynamicStateStack().push(new SavedHashElement(this.lvalue, savedAliasOwner)); // The localized value needs a distinct mutable slot. Clearing the // saved slot would also clear the object that must be reinstalled // at scope exit, losing ordinary `local $hash{key}` values. RuntimeScalar localized = new RuntimeScalar(); - parent.notePackageRootMutation(); parent.elements.put(key, localized); // %ENV wraps slots on insertion. Re-fetch the installed element // so subsequent assignment updates that wrapper rather than the @@ -213,21 +235,31 @@ public void dynamicSaveState() { */ @Override public void dynamicRestoreState() { - Stack dynamicStateStack = dynamicStateStack(); + Stack dynamicStateStack = dynamicStateStack(); if (!dynamicStateStack.isEmpty()) { // Pop the most recent saved state from the stack - RuntimeScalar previousState = dynamicStateStack.pop(); + SavedHashElement savedState = dynamicStateStack.pop(); + RuntimeScalar previousState = savedState == null ? null : savedState.value(); if (previousState == null) { // Key didn't exist before — remove it from the parent hash. // Re-fetch from parent in case hash was reassigned (setFromList clears elements). - parent.notePackageRootMutation(); + RuntimeScalar currentSlot = parent.elements.get(key); + boolean currentWasAlias = parent.ownsHashAliasCell(key, currentSlot); RuntimeScalar current = parent.elements.remove(key); - if (current != null - && (current.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && current.value instanceof RuntimeBase displacedBase - && displacedBase.refCount > 0 && --displacedBase.refCount == 0) { - displacedBase.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(displacedBase); + if (current != null) { + // The key was created only inside the localized scope. + // Removing its temporary scalar must also retire any + // anonymous IO holder acquired by assignments to it. + // Hint hashes already queue full slot cleanup in their + // map's remove hook. + if (!currentWasAlias && !parent.isHintHash) { + // Release the exact counted slot owner. Directly + // decrementing the referent here left refCountOwned and + // the HASH_ELEMENT identity active when another scalar + // still owned the referent, so the removed slot could + // appear live during a later final release. + releaseLocalizedValue(current); + } } this.lvalue = null; this.type = RuntimeScalarType.UNDEF; @@ -236,8 +268,12 @@ public void dynamicRestoreState() { // A temporary local alias may have replaced the map entry. // Reinstall the saved slot so its original scalar identity // remains observable after the dynamic scope unwinds. - parent.notePackageRootMutation(); - RuntimeScalar displaced = parent.elements.put(key, previousState); + RuntimeScalar currentSlot = parent.elements.get(key); + boolean displacedWasAlias = parent.ownsHashAliasCell(key, currentSlot); + boolean savedAliasCell = savedState.aliasOwner() != null; + RuntimeScalar displaced = savedAliasCell + ? parent.aliasScalarCell(key, previousState) + : parent.elements.put(key, previousState); parent.markPackageRootedValue(previousState); this.lvalue = previousState; this.type = this.lvalue.type; @@ -248,17 +284,32 @@ public void dynamicRestoreState() { // reachable after the saved hash entry is restored. Release // it only after restoration, so a DESTROY method observes the // restored dynamic value (notably a restored %SIG handler). - if (displaced != null && displaced != previousState) { + if (!savedAliasCell && !displacedWasAlias + && displaced != null && displaced != previousState) { // Replacing a localized element has the same ownership // effect as deleting a hash element. In particular, a // CODE slot can be the last counted owner of a closure; // deferDecrementIfTracked then releases its captures when // the closure's reference count reaches zero. - MortalList.deferDecrementIfTracked(displaced); - MortalList.deferIoOwnerRelease(displaced); - MortalList.flush(); + releaseLocalizedValue(displaced); } } + if (savedState != null && savedState.aliasOwner() != null) { + savedState.aliasOwner().release(); + } + } + } + + /** Release only this localized entry's value and cleanup it creates. */ + private static void releaseLocalizedValue(RuntimeScalar value) { + // A full flush can drain a pending RETURN_VALUE created just before + // this dynamic scope restores, destroying a value still being returned. + MortalList.pushScopeMark(); + try { + MortalList.deferDecrementIfTracked(value); + MortalList.deferIoOwnerRelease(value); + } finally { + MortalList.popScopeMarkAndFlush(); } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeIO.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeIO.java index bc65d1ca14..c42c27ccee 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeIO.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeIO.java @@ -94,6 +94,12 @@ public RuntimeGlob getOwnerGlob() { return ownerGlob == null ? null : ownerGlob.get(); } + /** Replace the IO handle held by this filehandle scalar. */ + public void replaceIOHandle(IOHandle next) { + if (ioHandle == next) return; + ioHandle = next; + } + /** Glob slot currently owning this IO object, when it has one. */ private static final ThreadLocal lastReadlineHandle = new ThreadLocal<>(); private static final ThreadLocal lastAccessedScalar = new ThreadLocal<>(); @@ -554,7 +560,7 @@ public RuntimeIO() { * @param ioHandle the IOHandle implementation to wrap */ public RuntimeIO(IOHandle ioHandle) { - this.ioHandle = ioHandle; + replaceIOHandle(ioHandle); } /** @@ -594,7 +600,7 @@ public void replaceStateFrom(RuntimeIO other) { this.currentLineNumber = other.currentLineNumber; this.currentChunkNumber = other.currentChunkNumber; this.slurpReadAttempted = other.slurpReadAttempted; - this.ioHandle = other.ioHandle; + replaceIOHandle(other.ioHandle); this.explicitlyClosed = other.explicitlyClosed; this.explicitlyClosedDirectory = other.explicitlyClosedDirectory; this.directoryIO = other.directoryIO; @@ -858,10 +864,10 @@ public static RuntimeIO open(String fileName) { } if (mode.equals(">") || mode.equals(">>")) { // ">-" or just ">" means stdout - fh.ioHandle = new CustomOutputStreamHandle(System.out); + fh.replaceIOHandle(new CustomOutputStreamHandle(System.out)); } else { // "<-" or just "<" means stdin - fh.ioHandle = new StandardIO(System.in); + fh.replaceIOHandle(new StandardIO(System.in)); } return fh; } else { @@ -1028,7 +1034,7 @@ private static RuntimeIO open(String fileName, String mode, boolean sysopen, return null; } // Use SeekableJarHandle to support seek operations (needed by Module::Metadata) - fh.ioHandle = new SeekableJarHandle(is); + fh.replaceIOHandle(new SeekableJarHandle(is)); addHandle(fh.ioHandle); if (!fh.applyOpenLayers(ioLayers, mode)) { return null; @@ -1065,9 +1071,9 @@ private static RuntimeIO open(String fileName, String mode, boolean sysopen, if (Files.isDirectory(filePath) && options.contains(StandardOpenOption.READ) && !options.contains(StandardOpenOption.WRITE)) { - fh.ioHandle = new DirectoryReadErrorHandle(); + fh.replaceIOHandle(new DirectoryReadErrorHandle()); } else { - fh.ioHandle = new CustomFileChannel(filePath, options); + fh.replaceIOHandle(new CustomFileChannel(filePath, options)); } // Reserve the virtual descriptor immediately. Handles can be @@ -1249,7 +1255,7 @@ public static RuntimeIO open(RuntimeScalar scalarRef, String mode) { scalarIO.setAppendMode(true); } - fh.ioHandle = scalarIO; + fh.replaceIOHandle(scalarIO); addHandle(fh.ioHandle); // PerlIO::scalar is not a real OS file descriptor, so a plain scalar @@ -1325,16 +1331,16 @@ public static RuntimeIO openPipe(RuntimeList runtimeList) { if (">".equals(mode)) { // When noShell is true, always use list constructor to bypass shell if (strings.size() == 1 && !noShell) { - fh.ioHandle = new PipeOutputChannel(strings.getFirst()); + fh.replaceIOHandle(new PipeOutputChannel(strings.getFirst())); } else { - fh.ioHandle = new PipeOutputChannel(strings); + fh.replaceIOHandle(new PipeOutputChannel(strings)); } } else if ("<".equals(mode)) { // When noShell is true, always use list constructor to bypass shell if (strings.size() == 1 && !noShell) { - fh.ioHandle = new PipeInputChannel(strings.getFirst()); + fh.replaceIOHandle(new PipeInputChannel(strings.getFirst())); } else { - fh.ioHandle = new PipeInputChannel(strings); + fh.replaceIOHandle(new PipeInputChannel(strings)); } } else { handleIOError("open failed: invalid mode for pipe"); @@ -1372,9 +1378,9 @@ public static RuntimeIO openForkPipe(String mode, int occurrence) { occurrence + ":" + ProcessHandle.current().pid()); List invocation = org.perlonjava.runtime.ForkOpenState.currentInvocation(); if ("-|".equals(mode)) { - fh.ioHandle = new PipeInputChannel(invocation, marker); + fh.replaceIOHandle(new PipeInputChannel(invocation, marker)); } else { - fh.ioHandle = new PipeOutputChannel(invocation, marker); + fh.replaceIOHandle(new PipeOutputChannel(invocation, marker)); } addHandle(fh.ioHandle); return fh; @@ -1807,7 +1813,7 @@ public RuntimeScalar binmode(String ioLayer) { if (originalHandle instanceof LayeredIOHandle layered) { layered.popAllLayers(); } - ioHandle = baseHandle; + replaceIOHandle(baseHandle); return scalarTrue; } @@ -1820,7 +1826,7 @@ public RuntimeScalar binmode(String ioLayer) { if (originalHandle instanceof LayeredIOHandle layered) { layered.popAllLayers(); } - ioHandle = wrappedHandle; + replaceIOHandle(wrappedHandle); return scalarTrue; } @@ -1934,7 +1940,7 @@ public RuntimeScalar close() { if (ioError) { return scalarFalse; } - ioHandle = new ClosedIOHandle(); + replaceIOHandle(new ClosedIOHandle()); explicitlyClosed = true; // Reset line number to 0 on close, matching Perl 5 behavior. // This ensures $. becomes 0 and error messages don't include diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeList.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeList.java index d9b6e789b6..99dd8dd3f6 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeList.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeList.java @@ -171,6 +171,16 @@ public RuntimeList cloneScalars() { return result; } + RuntimeList copyToMortalReturnSlots() { + RuntimeList result = new RuntimeList(); + for (RuntimeBase value : elements) { + result.elements.add(value instanceof RuntimeScalar scalar + && !scalar.isMortalReturnSnapshot() + ? RuntimeScalar.copyToMortalReturnSlot(scalar) : value); + } + return result; + } + /** * Adds the elements of this list to another RuntimeList. * @@ -701,6 +711,10 @@ public RuntimeList createListReference() { * @return The original list. */ public RuntimeArray setFromList(RuntimeList value) { + return setFromList(value, true); + } + + private RuntimeArray setFromList(RuntimeList value, boolean returnResult) { // Fast path: LHS is all simple scalars, RHS is a single RuntimeArray // This handles the common case: my ($a, $b) = @_ if (value.elements.size() == 1 && value.elements.get(0) instanceof RuntimeArray rhsArray) { @@ -712,7 +726,7 @@ public RuntimeArray setFromList(RuntimeList value) { } } if (allSimpleScalars) { - return assignSimpleScalarsFromArray(rhsArray, true); + return assignSimpleScalarsFromArray(rhsArray, returnResult); } } @@ -754,144 +768,132 @@ public RuntimeArray setFromList(RuntimeList value) { // Avoids O(n^2) from repeated RuntimeArray.shift() which does removeFirst() on ArrayList. RuntimeArray rhs = new RuntimeArray(); rhs.transientListAssignmentRhs = true; - value.addToArray(rhs); + RuntimeArray result = returnResult ? new RuntimeArray() : null; + boolean assignmentCompleted = false; + try { + value.addToArray(rhs); - List rhsElements = rhs.elements; - int rhsSize = rhsElements.size(); - int rhsIndex = 0; + List rhsElements = rhs.elements; + int rhsSize = rhsElements.size(); + int rhsIndex = 0; - // Build result with assigned values (including undef for unassigned scalars) - RuntimeArray result = new RuntimeArray(); - // Store original size for scalar context - result.scalarContextSize = rhsSize; + // Build result with assigned values (including undef for unassigned scalars) + // Store original size for scalar context + if (result != null) result.scalarContextSize = rhsSize; - for (RuntimeBase elem : elements) { - if (elem instanceof RuntimeScalarReadOnly runtimeScalarReadOnly && !runtimeScalarReadOnly.getDefinedBoolean()) { - // `undef` placeholder on LHS: consume one RHS value, but return something for this position. - // When safe, return the RHS element as an lvalue (alias). Otherwise return the pre-assignment value. - RuntimeScalar rhsValue = (rhsIndex < rhsSize) ? rhsElements.get(rhsIndex) : new RuntimeScalar(); - RuntimeScalar rhsAlias = (rhsAliasElements != null && rhsIndex < rhsAliasElements.size()) - ? rhsAliasElements.get(rhsIndex) - : null; - - // If the RHS element is also assigned on the LHS, it must not be returned as an alias - // (it would reflect the post-assignment value rather than the pre-assignment value). - boolean useAlias = rhsAlias != null && lhsScalars != null && !lhsScalars.containsKey(rhsAlias); - - result.elements.add(useAlias ? rhsAlias : rhsValue); - - if (rhsIndex < rhsSize) { - // Undo the materialized copy's refCount increment for the consumed - // RHS value (mirrors the corresponding fix in the assigned-scalar - // branch below). Without this, `my (undef, $name) = @_;` patterns - // leak +1 refCount per call on the discarded first arg — visible - // in op/inccode.t "no leaks" tests #61, #63 (bug perl #92252). - if (rhsValue != null && rhsValue.refCountOwned - && (rhsValue.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && rhsValue.value instanceof RuntimeBase base && base.refCount > 0) { - base.releaseOwner(rhsValue, "RuntimeList materialized-copy undo (undef-target)"); - base.releaseActiveOwner(rhsValue); - base.refCount--; - rhsValue.refCountOwned = false; + for (RuntimeBase elem : elements) { + if (elem instanceof RuntimeScalarReadOnly runtimeScalarReadOnly && !runtimeScalarReadOnly.getDefinedBoolean()) { + // `undef` placeholder on LHS: consume one RHS value, but return something for this position. + // When safe, return the RHS element as an lvalue (alias). Otherwise return the pre-assignment value. + RuntimeScalar rhsValue = (rhsIndex < rhsSize) ? rhsElements.get(rhsIndex) : new RuntimeScalar(); + RuntimeScalar rhsAlias = (rhsAliasElements != null && rhsIndex < rhsAliasElements.size()) + ? rhsAliasElements.get(rhsIndex) + : null; + + // If the RHS element is also assigned on the LHS, it must not be returned as an alias + // (it would reflect the post-assignment value rather than the pre-assignment value). + boolean useAlias = rhsAlias != null && lhsScalars != null && !lhsScalars.containsKey(rhsAlias); + + if (result != null) result.elements.add(useAlias ? rhsAlias : rhsValue); + + if (rhsIndex < rhsSize) { + // Retire the materialized copy's counted edge and IO lease for the consumed + // RHS value (mirrors the corresponding fix in the assigned-scalar + // branch below). Without this, `my (undef, $name) = @_;` patterns + // leak +1 refCount per call on the discarded first arg — visible + // in op/inccode.t "no leaks" tests #61, #63 (bug perl #92252). + RuntimeScalar.releaseMaterializedAssignmentCopy( + rhsValue, "undef-target", result); + rhsIndex++; } - rhsIndex++; - } - } else if (elem instanceof RuntimeScalar runtimeScalar) { - if (runtimeScalar.isKeysLvalue()) { - runtimeScalar.rejectKeysLvalueListAssignment(); - } - RuntimeScalar assigned = (rhsIndex < rhsSize) ? rhsElements.get(rhsIndex++) : null; - runtimeScalar.set(assigned != null ? assigned : new RuntimeScalar()); - result.elements.add(runtimeScalar); // Add reference to the variable itself - // Undo the materialized copy's refCount increment. - // The materialization (addToArray → addToScalar → set → setLarge) incremented - // refCount on the copy. The target's set() above created its own increment. - // The copy's increment is now redundant and would leak (the temporary copy - // sits in the local `rhs` array which is never scope-exit-cleaned). - // Array/hash targets take direct ownership of materialized copies, so only - // scalar targets need this correction. - if (assigned != null && assigned.refCountOwned - && (assigned.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && assigned.value instanceof RuntimeBase base && base.refCount > 0) { - base.releaseOwner(assigned, "RuntimeList materialized-copy undo (scalar-target)"); - base.releaseActiveOwner(assigned); - base.refCount--; - assigned.refCountOwned = false; - } - } else if (elem instanceof RuntimeArray runtimeArray) { - List remaining = (rhsIndex < rhsSize) - ? new ArrayList<>(rhsElements.subList(rhsIndex, rhsSize)) - : new ArrayList<>(); - - // For tied arrays, we must assign through the tied interface. - // Overwriting `elements` would discard the TieArray wrapper while leaving - // `type == TIED_ARRAY`, leading to ClassCastException when tie operations - // cast `array.elements` back to TieArray. - // For autovivify arrays, we must also go through setFromList() to trigger - // the autovivification that converts the parent scalar from UNDEF to ARRAYREFERENCE. - if (runtimeArray.type == RuntimeArray.TIED_ARRAY || runtimeArray.type == RuntimeArray.AUTOVIVIFY_ARRAY) { + } else if (elem instanceof RuntimeScalar runtimeScalar) { + if (runtimeScalar.isKeysLvalue()) { + runtimeScalar.rejectKeysLvalueListAssignment(); + } + RuntimeScalar assigned = (rhsIndex < rhsSize) ? rhsElements.get(rhsIndex++) : null; + runtimeScalar.set(assigned != null ? assigned : new RuntimeScalar()); + if (result != null) result.addBorrowedListResultValue(runtimeScalar); + // Retire the materialized copy's counted edge and IO lease. + // The materialization (addToArray → addToScalar → set → setLarge) incremented + // refCount on the copy. The target's set() above created its own increment. + // The copy's increment is now redundant and would leak (the temporary copy + // sits in the local `rhs` array which is never scope-exit-cleaned). + // Array/hash targets take direct ownership of materialized copies, so only + // scalar targets need this correction. + RuntimeScalar.releaseMaterializedAssignmentCopy( + assigned, "scalar-target", null); + } else if (elem instanceof RuntimeArray runtimeArray) { + List remaining = (rhsIndex < rhsSize) + ? new ArrayList<>(rhsElements.subList(rhsIndex, rhsSize)) + : new ArrayList<>(); + + // Replace through the array's normal store path so the old + // element owners are released and each destination cell gets + // a current ARRAY_ELEMENT identity. This also preserves tied + // array dispatch and autovivification. RuntimeList remainingList = new RuntimeList(); remainingList.elements.addAll(remaining); - runtimeArray.setFromList(remainingList); - // Undo materialized copies' refCount increments. - // setFromList creates new copies via incrementRefCountForContainerStore; - // the materialized rhs elements' increments are now redundant. + RuntimeArray assignedArray = runtimeArray.setFromList(remainingList); + // setFromList creates destination cells and acquires their + // owners. The materialized RHS copies are temporary transport + // values, so retire their counted edges and IO leases as well. for (RuntimeScalar r : remaining) { - if (r.refCountOwned && (r.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && r.value instanceof RuntimeBase base && base.refCount > 0) { - base.releaseOwner(r, "RuntimeList materialized-copy undo (array-target)"); - base.releaseActiveOwner(r); - base.refCount--; - r.refCountOwned = false; - } + RuntimeScalar.releaseMaterializedAssignmentCopy( + r, "array-target", result); } - } else { - // Plain array: directly reuse the materialized copies. - // Their refCountOwned=true transfers to the array elements. - runtimeArray.elements = remaining; - } - result.elements.addAll(remaining); // Use original references - rhsIndex = rhsSize; // Consume the rest - } else if (elem instanceof RuntimeHash runtimeHash) { - RuntimeArray remainingArr = new RuntimeArray(); - remainingArr.elements = (rhsIndex < rhsSize) - ? new ArrayList<>(rhsElements.subList(rhsIndex, rhsSize)) - : new ArrayList<>(); - - RuntimeHash hash = RuntimeHash.createHashForAssignment(remainingArr); - // Complete scalar-to-hash autovivification before replacing the - // deferred hash's elements. Otherwise this assignment discards - // the AutovivificationHash marker without updating the scalar. - AutovivificationHash.vivify(runtimeHash); - runtimeHash.elements = hash.elements; - // Add lvalue references to hash elements for list assignment - for (Map.Entry entry : hash.elements.entrySet()) { - result.elements.add(new RuntimeScalar(entry.getKey())); - result.elements.add(entry.getValue()); // Add reference to hash value + if (result != null) result.addBorrowedListResultValues(assignedArray.elements); + rhsIndex = rhsSize; // Consume the rest + } else if (elem instanceof RuntimeHash runtimeHash) { + List remaining = (rhsIndex < rhsSize) + ? new ArrayList<>(rhsElements.subList(rhsIndex, rhsSize)) + : new ArrayList<>(); + + // Resolve a deferred scalar-to-hash target before setFromList + // mutates its elements, so the originating scalar sees the vivified hash. + AutovivificationHash.vivify(runtimeHash); + RuntimeList remainingList = new RuntimeList(); + remainingList.elements.addAll(remaining); + RuntimeArray assignedHash = runtimeHash.setFromList(remainingList); + // setFromList releases displaced hash slots and acquires current + // HASH_ELEMENT identities. Its result also preserves tied-hash + // assignment behavior and the assigned key/value list. + if (result != null) result.elements.addAll(assignedHash.elements); + // The RHS materialization is temporary transport; retire its + // counted edges and IO leases after the destination acquired slots. + for (RuntimeScalar r : remaining) { + RuntimeScalar.releaseMaterializedAssignmentCopy( + r, "hash-target", result); + } + rhsIndex = rhsSize; // Consume the rest } - // Undo materialized copies' refCount increments. - // createHashForAssignment creates new RuntimeScalars for hash values - // and gives those hash slots their own container-store ownership. - // The original rhs elements' refCount increments (from materialization - // via addToArray -> setLarge) are now redundant and would leak since - // nobody decrements them. - for (RuntimeScalar r : remainingArr.elements) { - if (r.refCountOwned && (r.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && r.value instanceof RuntimeBase base && base.refCount > 0) { - base.releaseOwner(r, "RuntimeList materialized-copy undo (hash-target)"); - base.releaseActiveOwner(r); - base.refCount--; - r.refCountOwned = false; + } + assignmentCompleted = true; + + } finally { + try { + try { + // Assignment can throw while a tied or readonly target is being + // updated. Retire any transport copies that did not reach an LHS. + for (RuntimeScalar copy : rhs.elements) { + RuntimeScalar.releaseMaterializedAssignmentCopy(copy, "unwind", null); } + } finally { + // Keep the copied cells alive until the enclosing Perl mortal + // boundary, after the receiver slots have been registered. + // The boundary then clears their untracked container owners. + MortalList.deferTransientListAssignmentRhs(rhs); + } + } finally { + MortalList.suppressFlush(wasFlushing); + if (!assignmentCompleted && !wasFlushing) { + // A failed target callback can unwind lexical owners while + // flushing is suppressed. Drain those releases now that + // the assignment boundary has restored its caller state. + MortalList.flush(); } - rhsIndex = rhsSize; // Consume the rest } } - // Restore previous flushing state. Now that all LHS variables hold references - // to the return values, it's safe to process pending decrements. - MortalList.suppressFlush(wasFlushing); - return result; } @@ -910,7 +912,7 @@ public RuntimeArray setFromListVoid(RuntimeList value) { return null; } } - return setFromList(value); + return setFromList(value, false); } private RuntimeArray assignSimpleScalarsFromArray(RuntimeArray rhsArray, boolean returnResult) { @@ -951,7 +953,7 @@ private RuntimeArray assignSimpleScalarsFromArray(RuntimeArray rhsArray, boolean if (lhs.isKeysLvalue()) lhs.rejectKeysLvalueListAssignment(); RuntimeScalar rhs = i < rhsSize ? rhsElements.get(i) : null; lhs.set(rhs == null ? new RuntimeScalar() : rhs); - if (result != null) result.elements.add(lhs); + if (result != null) result.addBorrowedListResultValue(lhs); } return result; } @@ -969,7 +971,7 @@ private RuntimeArray assignSimpleScalarsFromArray(RuntimeArray rhsArray, boolean RuntimeScalar lhs = (RuntimeScalar) elements.get(i); if (lhs.isKeysLvalue()) lhs.rejectKeysLvalueListAssignment(); lhs.set(i < rhsValues.length ? rhsValues[i] : new RuntimeScalar()); - if (result != null) result.elements.add(lhs); + if (result != null) result.addBorrowedListResultValue(lhs); } return result; } finally { diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeScalar.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeScalar.java index 84430f53a8..016776653f 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeScalar.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeScalar.java @@ -19,6 +19,7 @@ import java.lang.ref.WeakReference; import java.nio.charset.StandardCharsets; import java.util.*; +import java.util.function.Consumer; import java.util.regex.Pattern; import static org.perlonjava.runtime.runtimetypes.RuntimeArray.*; @@ -198,24 +199,22 @@ public static boolean watcherCleanupNeeded() { return watcherCleanupNeeded; } - /** Fire destruction magic for scalar slots owned by a dying aggregate. */ - public static void notifyDestroyedWatchersRecursively(RuntimeBase value) { - Set visited = Collections.newSetFromMap(new IdentityHashMap<>()); - notifyDestroyedWatchersRecursively(value, visited); + /** + * Fire destruction magic for scalar slots directly owned by a dying aggregate. + * Nested referents keep their own slots while another Perl owner keeps them alive; + * their final-owner cleanup notifies those slots later. + */ + public static void notifyDestroyedWatchersForAggregateSlots(RuntimeBase value) { + if (value instanceof RuntimeArray array) { + notifyDestroyedWatchersForSlots(array.elements); + } else if (value instanceof RuntimeHash hash) { + notifyDestroyedWatchersForSlots(hash.elements.values()); + } } - private static void notifyDestroyedWatchersRecursively(RuntimeBase value, Set visited) { - if (value == null || !visited.add(value)) return; - Collection elements; - if (value instanceof RuntimeArray array) elements = array.elements; - else if (value instanceof RuntimeHash hash) elements = hash.elements.values(); - else return; + private static void notifyDestroyedWatchersForSlots(Collection elements) { for (RuntimeScalar scalar : elements) { - if (scalar == null) continue; - scalar.notifyDestroyedWatchers(); - if (scalar.value instanceof RuntimeBase nested) { - notifyDestroyedWatchersRecursively(nested, visited); - } + if (scalar != null) scalar.notifyDestroyedWatchers(); } } @@ -342,8 +341,71 @@ public boolean isLvalueScalar() { */ private boolean scalarStoredGlob; - /** True on the scalar slot that owns a newly created anonymous IO glob. */ - public boolean ioOwner; + /** Identity of the scalar slot's anonymous IO resource owner, when present. */ + PerlOwnerSlot ioOwnerSlot; + /** Identity retaining a detached glob while this scalar stores its value. */ + private PerlOwnerSlot detachedGlobValueOwnerSlot; + + private void refreshDetachedGlobValueOwner() { + prepareDetachedGlobValueOwner(type, value); + } + + /** + * Move the scalar's detached-glob value edge before mutating the scalar + * payload. Perl releases a detached glob's component values while the + * scalar being overwritten still contains the old glob; a component's + * DESTROY can therefore inspect that old value. Acquire a replacement + * glob edge first, then retire the previous edge against that state. + */ + private void prepareDetachedGlobValueOwner(int nextType, Object nextValue) { + RuntimeGlob next = nextType == GLOB && nextValue instanceof RuntimeGlob glob + && glob != this && glob.retainsDetachedComponents() + && hasDurableStrongValueSlot() ? glob : null; + RuntimeGlob previous = detachedGlobValueOwnerSlot != null + && detachedGlobValueOwnerSlot.referent() instanceof RuntimeGlob glob + ? glob : null; + if (previous == next) { + releaseClearedDetachedGlobSelf(); + return; + } + + PerlOwnerSlot nextSlot = null; + if (next != null) { + nextSlot = new PerlOwnerSlot(PerlOwnerSlot.Kind.GLOB_VALUE); + nextSlot.acquireGlobValueIdentity(next); + } + PerlOwnerSlot previousSlot = detachedGlobValueOwnerSlot; + detachedGlobValueOwnerSlot = nextSlot; + if (previousSlot != null) previousSlot.release(); + if (previous != null) previous.releaseDetachedComponentsIfUnowned(); + releaseClearedDetachedGlobSelf(); + } + + private void releaseDetachedGlobValueOwner() { + PerlOwnerSlot ownerSlot = detachedGlobValueOwnerSlot; + RuntimeGlob glob = ownerSlot != null + && ownerSlot.referent() instanceof RuntimeGlob target ? target : null; + if (glob == null && type == GLOB && value instanceof RuntimeGlob target + && target != this && target.retainsDetachedComponents()) { + glob = target; + } + detachedGlobValueOwnerSlot = null; + if (ownerSlot != null) ownerSlot.release(); + if (glob != null) glob.releaseDetachedComponentsIfUnowned(); + releaseClearedDetachedGlobSelf(); + } + + private void releaseClearedDetachedGlobSelf() { + if (this instanceof RuntimeGlob glob && glob.retainsDetachedComponents() + && (type != GLOB || value != glob)) { + glob.releaseDetachedComponentsIfUnowned(); + } + } + + /** Whether this scalar currently owns an anonymous IO resource slot. */ + public boolean hasIoOwner() { + return ioOwnerSlot != null; + } /** Active call-frame provenance for copies extracted from aliased arguments. */ private Object copiedFromArgumentFrame; @@ -352,8 +414,13 @@ boolean copiedFromArgumentFrame(Object frame) { return frame != null && copiedFromArgumentFrame == frame; } + Object copiedFromArgumentFrameToken() { + return copiedFromArgumentFrame; + } + /** Clears a non-reference array slot after aggregate ownership is queued. */ void clearForArraySlotRemoval() { + prepareDetachedGlobValueOwner(RuntimeScalarType.UNDEF, null); this.type = UNDEF; this.value = null; this.tainted = false; @@ -388,6 +455,168 @@ void clearForArraySlotRemoval() { */ public String globalCodeRefFqn; + /** Compile-time descriptor for one direct named-call site, or its runtime cache. */ + private String compiledDirectCallSiteName; + private int compiledDirectCallSiteIndex = -1; + private WeakReference compiledDirectCallInitialTarget; + private WeakReference compiledDirectCallInitialSlot; + private WeakReference compiledDirectCallPinSlot; + private boolean compiledDirectCallSiteDescriptor; + private boolean compiledDirectCallCompileTimePinned; + private boolean compiledDirectCallRetainTargetIfDeletedBeforeInstall; + private boolean compiledDirectCallHasDeferredParseOwner; + private boolean updatingCompiledDirectCallCache; + + /** Mark this scalar as metadata for a compiled direct named-call site. */ + public void configureCompiledDirectCallSite( + String name, int index, RuntimeScalar initialCodeRef) { + configureCompiledDirectCallSite(name, index, initialCodeRef, false); + } + + public void configureCompiledDirectCallSite( + String name, + int index, + RuntimeScalar initialCodeRef, + boolean compileTimePinned) { + configureCompiledDirectCallSite( + name, index, initialCodeRef, compileTimePinned, false); + } + + public void configureCompiledDirectCallSite( + String name, + int index, + RuntimeScalar initialCodeRef, + boolean compileTimePinned, + boolean retainTargetIfDeletedBeforeInstall) { + compiledDirectCallSiteName = name; + compiledDirectCallSiteIndex = index; + compiledDirectCallSiteDescriptor = true; + compiledDirectCallCompileTimePinned = compileTimePinned; + compiledDirectCallRetainTargetIfDeletedBeforeInstall = retainTargetIfDeletedBeforeInstall; + RuntimeCode target = initialCodeRef != null + && initialCodeRef.value instanceof RuntimeCode code ? code : null; + compiledDirectCallInitialSlot = initialCodeRef == null + ? null : new WeakReference<>(initialCodeRef); + compiledDirectCallInitialTarget = target == null ? null : new WeakReference<>(target); + if (target != null) { + type = RuntimeScalarType.CODE; + value = target; + retainCodeSlotBinding(); + } + } + + public String compiledDirectCallSiteName() { + return compiledDirectCallSiteName; + } + + public int compiledDirectCallSiteIndex() { + return compiledDirectCallSiteIndex; + } + + boolean compiledDirectCallCompileTimePinned() { + return compiledDirectCallCompileTimePinned; + } + + boolean compiledDirectCallRetainTargetIfDeletedBeforeInstall() { + return compiledDirectCallRetainTargetIfDeletedBeforeInstall; + } + + public void setCompiledDirectCallHasDeferredParseOwner(boolean hasOwner) { + compiledDirectCallHasDeferredParseOwner = hasOwner; + } + + public void setCompiledDirectCallPinSlot(RuntimeScalar pinSlot) { + compiledDirectCallPinSlot = pinSlot == null ? null : new WeakReference<>(pinSlot); + } + + boolean compiledDirectCallHasDeferredParseOwner() { + return compiledDirectCallHasDeferredParseOwner; + } + + boolean isCompiledDirectCallSiteDescriptor() { + return compiledDirectCallSiteDescriptor; + } + + /** Copy the installed callsite identity so ithread CV clones can reinstall its owner. */ + void copyCompiledDirectCallSiteMetadataFrom(RuntimeScalar source) { + if (source.compiledDirectCallSiteName == null) return; + compiledDirectCallSiteName = source.compiledDirectCallSiteName; + compiledDirectCallSiteIndex = source.compiledDirectCallSiteIndex; + // Thread snapshots copy the installed cache, not the parser's temporary + // descriptor or its source-runtime owner slots. The cloned CV's pad + // installation creates a fresh child-runtime callsite from this metadata. + compiledDirectCallSiteDescriptor = false; + compiledDirectCallCompileTimePinned = source.compiledDirectCallCompileTimePinned; + compiledDirectCallRetainTargetIfDeletedBeforeInstall = + source.compiledDirectCallRetainTargetIfDeletedBeforeInstall; + compiledDirectCallHasDeferredParseOwner = false; + compiledDirectCallInitialTarget = null; + compiledDirectCallInitialSlot = null; + compiledDirectCallPinSlot = null; + } + + void releaseCompiledDirectCallSiteDescriptorBinding() { + if (!compiledDirectCallSiteDescriptor) return; + compiledDirectCallSiteDescriptor = false; + if (hasCodeSlotBinding()) releaseCodeSlotBinding(); + type = RuntimeScalarType.UNDEF; + value = null; + } + + RuntimeCode compiledDirectCallInitialTarget() { + return compiledDirectCallInitialTarget == null + ? (value instanceof RuntimeCode code ? code : null) + : compiledDirectCallInitialTarget.get(); + } + + RuntimeScalar compiledDirectCallInitialSlot() { + return compiledDirectCallInitialSlot == null + ? null : compiledDirectCallInitialSlot.get(); + } + + RuntimeScalar compiledDirectCallPinSlot() { + return compiledDirectCallPinSlot == null + ? null : compiledDirectCallPinSlot.get(); + } + + void updateCompiledDirectCallTarget(RuntimeCode target) { + compiledDirectCallInitialTarget = target == null ? null : new WeakReference<>(target); + } + + void initializeCompiledDirectCallCache( + String name, int index, RuntimeCode target, boolean compileTimePinned) { + compiledDirectCallSiteName = name; + compiledDirectCallSiteIndex = index; + compiledDirectCallSiteDescriptor = false; + compiledDirectCallCompileTimePinned = compileTimePinned; + compiledDirectCallInitialSlot = null; + compiledDirectCallInitialTarget = target == null ? null : new WeakReference<>(target); + type = RuntimeScalarType.CODE; + value = target; + globalCodeRefFqn = null; + } + + void setCompiledDirectCallTarget(RuntimeScalar replacement) { + if (replacement == null) return; + updatingCompiledDirectCallCache = true; + try { + set(replacement); + } finally { + updatingCompiledDirectCallCache = false; + } + globalCodeRefFqn = null; + RuntimeCode target = replacement.type == RuntimeScalarType.CODE + && replacement.value instanceof RuntimeCode code ? code : null; + updateCompiledDirectCallTarget(target); + } + + void setCompiledDirectCallTarget(RuntimeCode target) { + RuntimeScalar replacement = new RuntimeScalar(); + replacement.type = RuntimeScalarType.CODE; + replacement.value = target; + setCompiledDirectCallTarget(replacement); + } + /** * Source-level name for a generated lexical-sub storage scalar. A * bodyless {@code my/state sub name;} is an undefined callable, not an @@ -412,17 +641,10 @@ void clearForArraySlotRemoval() { * {@link RuntimeCode#makeCodeObject} and decremented in * {@link RuntimeCode#releaseCaptures}. */ - public int captureCount; - /** Explicit identity for this pad cell's closure owner edge. */ private PerlOwnerSlot closureOwnerSlot; - /** - * Number of closure-capture owners currently retained on this scalar's - * referent. This is separate from {@link #captureCount}: a weak scalar, an - * untracked referent, or a scalar that already owns a normal refCount slot - * may be captured without adding an extra selective refCount owner. - */ + /** Number of legacy capture-count increments retained for this cell's referent. */ public int captureRefCountOwned() { return closureOwnerSlot == null ? 0 : closureOwnerSlot.legacyCaptureCount(); } @@ -441,6 +663,11 @@ public int captureRefCountOwned() { // Last hash/array container that stored this scalar slot. Used only as a // narrow guard for live CODE refs whose captures must survive void discard. RuntimeBase containerOwner; + private final Set containerOwners = + Collections.newSetFromMap(new IdentityHashMap<>()); + /** Package aggregates that contained this value before becoming roots. */ + private final Set prepopulatedPackageAggregateOwners = + Collections.newSetFromMap(new IdentityHashMap<>()); /** Return the aggregate slot that directly owns this scalar, if any. */ public RuntimeBase getContainerOwner() { @@ -453,35 +680,140 @@ void markContainerOwner(RuntimeBase owner) { // transient argument or container alive as long as the cache entry. // Reference and proxy-backed scalars retain this edge for lifetime // tracking. - if (getClass() == RuntimeScalarReadOnly.class + if (isSharedImmutableLiteralWithoutOwnerTracking()) return; + synchronized (this) { + if (owner != null) containerOwners.add(owner); + this.containerOwner = owner; + } + associateCountedAggregateOwnerIfAbsent(owner); + refreshDetachedGlobValueOwner(); + } + + void associateCountedAggregateOwner(RuntimeBase owner) { + PerlOwnerSlot slot = countedOwnerSlot; + if (owner != null && slot != null && slot.isActive() + && slot.countedScalarOwner() == this && slot.referent() == value + && isStoredAggregateElementOwner(owner, slot.kind())) { + slot.associateCountedAggregateOwner(owner); + } + } + + private void associateCountedAggregateOwnerIfAbsent(RuntimeBase owner) { + PerlOwnerSlot slot = countedOwnerSlot; + if (owner != null && slot != null && slot.isActive() + && slot.countedScalarOwner() == this && slot.referent() == value + && isStoredAggregateElementOwner(owner, slot.kind())) { + slot.associateCountedAggregateOwnerIfAbsent(owner); + } + } + + private boolean isSharedImmutableLiteralWithoutOwnerTracking() { + return getClass() == RuntimeScalarReadOnly.class && type != RuntimeScalarType.READONLY_SCALAR && (type & RuntimeScalarType.REFERENCE_BIT) == 0 && !(value instanceof RuntimeBase) - && !firstClassRegexScalar) { - return; + && !firstClassRegexScalar; + } + + void markPrepopulatedPackageAggregateOwner(RuntimeBase owner) { + boolean tracked; + synchronized (this) { + tracked = containerOwners.contains(owner); + } + if (!tracked || !isStoredInContainer(owner)) return; + synchronized (this) { + if (containerOwners.contains(owner)) prepopulatedPackageAggregateOwners.add(owner); } - this.containerOwner = owner; - propagateTiedHandlerMarkerToReferent(); } - private void propagateTiedHandlerMarkerToReferent() { - if (containerOwner != null && containerOwner.possiblyStoredInTiedHandler - && (type & RuntimeScalarType.REFERENCE_BIT) != 0 - && value instanceof RuntimeBase base) { - base.markPossiblyStoredInTiedHandler(); + /** Retire this cell's container edge when the container loses its last Perl owner. */ + void releaseContainerOwner(RuntimeBase expectedOwner) { + RuntimeBase referent = (type & RuntimeScalarType.REFERENCE_BIT) != 0 + && value instanceof RuntimeBase base ? base : null; + removeContainerOwnerTracking(expectedOwner); + refreshUntrackedReferenceOwner(); + WeakRefRegistry.onContainerValueOwnerReleased(referent); + } + + /** Retire this aggregate edge after a slot mutation removed its last copy. */ + void reconcileContainerOwnerAfterMutation(RuntimeBase owner) { + if (owner == null) return; + if (isSharedImmutableLiteralWithoutOwnerTracking()) return; + if (isStoredInContainer(owner)) { + synchronized (this) { + containerOwners.add(owner); + containerOwner = owner; + } + } else { + removeContainerOwnerTracking(owner); } + refreshUntrackedReferenceOwner(); + WeakRefRegistry.onContainerValueOwnerReleased( + (type & RuntimeScalarType.REFERENCE_BIT) != 0 + && value instanceof RuntimeBase base ? base : null); } - boolean isStoredInRegisteredContainerOwner() { - RuntimeBase owner = containerOwner; - if (owner == null || !MyVarCleanupStack.isRegistered(owner)) return false; - if (owner instanceof RuntimeHash hash) { - return hash.elements.containsValue(this); + /** Refresh this direct cell after its aggregate's last current Perl owner leaves. */ + void reconcileContainerOwnerAfterAggregateTransfer(RuntimeBase owner) { + if (owner == null || isSharedImmutableLiteralWithoutOwnerTracking()) return; + RuntimeBase referent = (type & RuntimeScalarType.REFERENCE_BIT) != 0 + && value instanceof RuntimeBase base ? base : null; + reconcileContainerOwnerAfterMutation(owner); + if (isStoredInContainer(owner)) { + updateUntrackedReferenceOwner(referent, true); } - if (owner instanceof RuntimeArray array) { - return array.elements.contains(this); + if (referent instanceof RuntimeCode code + && PerlRuntime.currentOrNull() != null + && WeakRefRegistry.hasWeakRefsTo(code)) { + WeakRefRegistry.clearWeakRefsTo(code); } - return false; + } + + private void removeContainerOwnerTracking(RuntimeBase expectedOwner) { + boolean replaceCurrentOwner; + synchronized (this) { + containerOwners.remove(expectedOwner); + prepopulatedPackageAggregateOwners.remove(expectedOwner); + replaceCurrentOwner = containerOwner == expectedOwner; + if (replaceCurrentOwner) containerOwner = null; + } + if (replaceCurrentOwner) { + RuntimeBase replacement = containerOwnerSnapshot().stream() + .filter(this::isStoredInContainer) + .findFirst().orElse(null); + synchronized (this) { + // A concurrent store may already have installed a newer owner. + if (containerOwner == null) containerOwner = replacement; + } + } + } + + /** Reconcile the fast owner hint with all currently stored container edges. */ + void reconcileContainerOwners() { + for (RuntimeBase owner : containerOwnerSnapshot()) { + if (!isStoredInContainer(owner)) removeContainerOwnerTracking(owner); + } + List owners = containerOwnerSnapshot(); + RuntimeBase current = containerOwner; + if (current != null && (!owners.contains(current) || !isStoredInContainer(current))) { + synchronized (this) { + if (containerOwner == current) containerOwner = null; + } + } + if (containerOwner == null) { + RuntimeBase replacement = owners.stream() + .filter(this::isStoredInContainer) + .findFirst().orElse(null); + synchronized (this) { + if (containerOwner == null) containerOwner = replacement; + } + } + } + + boolean isStoredInRegisteredContainerOwner() { + return containerOwnerSnapshot().stream() + .anyMatch(owner -> MyVarCleanupStack.isRegistered(owner) + && isStoredInAnyContainer(owner)); } /** Whether this scalar is backed by durable Perl storage for lvalue use. */ @@ -495,21 +827,28 @@ boolean hasDurableLvalueStorage() { /** True when a container removal returned this scalar slot as a loose value. */ private boolean isDetachedFromContainerOwner() { - RuntimeBase owner = containerOwner; - if (owner == null) { + List owners = containerOwnerSnapshot(); + if (owners.stream().anyMatch(this::isStoredInAnyContainer)) return false; + if (owners.isEmpty()) { return !MyVarCleanupStack.isRegistered(this) && !isPackageGlobalRoot; } - if (owner instanceof RuntimeHash hash) { - return !hash.elements.containsValue(this); - } - if (owner instanceof RuntimeArray array) { - return !array.elements.contains(this); - } - return false; + return true; + } + + public synchronized void retainClosureCapture() { + verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE); + retainClosureCapture(true); + verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE); } - public void retainClosureCapture() { - boolean firstCapture = captureCount++ == 0; + private synchronized void retainClosureCapture(boolean legacyOwner) { + boolean firstCapture = !hasClosureCaptureOwner(); + retainClosureCaptureCount(legacyOwner); + finishClosureCaptureRetention(firstCapture); + } + + private void finishClosureCaptureRetention(boolean firstCapture) { + refreshUntrackedReferenceOwner(); if (firstCapture && type == RuntimeScalarType.CODE) { retainClosureCaptureReferent(); } else if (firstCapture && !refCountOwned) { @@ -523,48 +862,112 @@ public void retainClosureCapture() { retainClosureCaptureReferent(); } else if (firstCapture) { // The ordinary pad-slot increment already exists in refCount. - // Record the semantic edge separately so weak sweeping cannot - // mistake a captured pad for an unowned JVM temporary. + // Record the semantic edge separately so the owner ledger sees + // the captured pad independently from JVM wrapper reachability. RuntimeBase base = semanticCaptureReferent(); updateClosureOwnerSlot(base); } } + /** Retain this lexical cell for one closure capture with a distinct owner identity. */ + public PerlOwnerSlot retainClosureCaptureSlot() { + return retainClosureCaptureSlot(null); + } + + /** Retain this lexical cell and identify the CODE object that owns the capture. */ + public synchronized PerlOwnerSlot retainClosureCaptureSlot(RuntimeCode captureOwner) { + verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE); + boolean firstCapture = !hasClosureCaptureOwner(); + PerlOwnerSlot ownerSlot = new PerlOwnerSlot(PerlOwnerSlot.Kind.SCALAR_CAPTURE); + ownerSlot.acquireCaptureIdentity(this, captureOwner); + retainClosureCaptureCount(false); + finishClosureCaptureRetention(firstCapture); + verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE); + return ownerSlot; + } + + /** Release one closure's lexical-cell owner and its matching capture count. */ + public synchronized void releaseClosureCaptureSlot(PerlOwnerSlot ownerSlot) { + if (ownerSlot == null) { + releaseClosureCapture(); + return; + } + if (ownerSlot.kind() != PerlOwnerSlot.Kind.SCALAR_CAPTURE) { + throw new IllegalStateException("capture release requires a scalar-capture slot"); + } + if (!ownerSlot.isActive()) return; + if (ownerSlot.referent() != this) { + throw new IllegalStateException("scalar-capture slot belongs to a different pad cell"); + } + beginPendingClosureCaptureRelease(); + try { + ownerSlot.release(); + } finally { + endPendingClosureCaptureRelease(); + } + releaseClosureCapture(false); + verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE); + // Releasing the owner slot runs while the capture release is marked + // pending, so its lifecycle callback correctly waits. Retry after the + // capture count and pending marker have both retired, matching the + // aggregate capture path in RuntimeBase.releaseClosureCaptureOwner(). + if (!hasClosureCaptureOwner()) { + WeakRefRegistry.onStrongOwnerSlotReleased(this); + } + } + /** Reconstruct capture ownership for an independent ithread snapshot. */ - void retainThreadCloneClosureCapture() { - captureCount++; + synchronized PerlOwnerSlot retainThreadCloneClosureCapture(RuntimeCode captureOwner) { + verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE); + PerlOwnerSlot ownerSlot = new PerlOwnerSlot(PerlOwnerSlot.Kind.SCALAR_CAPTURE); + ownerSlot.acquireCaptureIdentity(this, captureOwner); + retainClosureCaptureCount(false); + refreshUntrackedReferenceOwner(); // An owning lexical slot already protects its referent. Borrowed // argument aliases do not, and the source runtime's other owners are // not a lifetime guarantee in the cloned runtime. if (!refCountOwned) retainClosureCaptureReferent(); + verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE); + return ownerSlot; } - public void releaseClosureCapture() { - if (captureCount > 0) { - captureCount--; + public synchronized void releaseClosureCapture() { + if (!hasClosureCaptureOwner()) { + if (captureCount != 0) { + throw new IllegalStateException("closure capture has no recorded owner"); + } + return; } - if (captureCount == 0) { - releaseOneClosureCaptureReferent(); - releaseClosureOwnerSlot(); + releaseClosureCapture(true); + verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE); + if (!hasClosureCaptureOwner()) { + WeakRefRegistry.onStrongOwnerSlotReleased(this); } } - /** - * Retire this pad cell's semantic edge once its declaring scope has exited - * and the pre-END reachability walk has established that no END block can - * reach it. The capture count intentionally remains intact: the compiled - * eval code may still be Java-reachable, but it can no longer represent a - * Perl lifetime owner at global-destruction time. - */ - public void releaseUnreachableSemanticCaptureOwner() { - releaseClosureOwnerSlot(); + private synchronized void releaseClosureCapture(boolean legacyOwner) { + releaseClosureCaptureCount(legacyOwner); + if (!hasClosureCaptureOwner()) { + releaseOneClosureCaptureReferent(); + releaseClosureOwnerSlot(); + if (scopeExited) { + cleanupScalarReferenceBinding(this); + } + refreshUntrackedReferenceOwner(); + } + if (!legacyOwner) { + verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE); + } } private void retainClosureCaptureReferent() { RuntimeBase base = closureCaptureReferent(); if (base == null) return; updateClosureOwnerSlot(base, false); - closureOwnerSlot.acquireLegacyCapture(base); + // The explicit CLOSURE_PAD slot is the capture's strong edge. Do not + // mirror it with a selective-count increment; final slot release + // drives weak cleanup through the owner ledger. + closureOwnerSlot.acquireNativeOwner(base); } private void updateClosureOwnerSlot(RuntimeBase referent) { @@ -585,24 +988,16 @@ private void releaseClosureOwnerSlot() { if (closureOwnerSlot != null) closureOwnerSlot.release(); } - private void retainMissingClosureCaptureReferents() { - while (captureRefCountOwned() < captureCount) { - int before = captureRefCountOwned(); - retainClosureCaptureReferent(); - if (captureRefCountOwned() == before) break; - } - } - private RuntimeBase closureCaptureReferent() { if (WeakRefRegistry.isweak(this)) return null; if ((type & RuntimeScalarType.REFERENCE_BIT) == 0 || !(value instanceof RuntimeBase base)) { return null; } - if (type == RuntimeScalarType.CODE && base.refCount < 0) { - base.refCount = 0; + if (type == RuntimeScalarType.CODE && !base.isRefCountTracked()) { + base.startRefCountTracking(); } - if (base.refCount < 0 || base.refCount == WeakRefRegistry.WEAKLY_TRACKED - || base.refCount == Integer.MIN_VALUE) { + if (!base.isRefCountTracked() || base.isWeaklyRefCountTracked() + || base.isPerlDestroyed()) { return null; } return base; @@ -613,8 +1008,8 @@ private RuntimeBase strongCaptureReferent() { if (WeakRefRegistry.isweak(this) || (type & RuntimeScalarType.REFERENCE_BIT) == 0 || !(value instanceof RuntimeBase base) - || base.refCount == WeakRefRegistry.WEAKLY_TRACKED - || base.refCount == Integer.MIN_VALUE) { + || base.isWeaklyRefCountTracked() + || base.isPerlDestroyed()) { return null; } return base; @@ -622,15 +1017,15 @@ private RuntimeBase strongCaptureReferent() { /** * The owner ledger tracks Perl's strong capture edge separately from the - * selective refcount. A live referent can be WEAKLY_TRACKED when a weak - * probe was installed before the closure was constructed; that sentinel + * selective refcount. A live referent can be weakly tracked when a weak + * probe was installed before the closure was constructed; that state * must not prevent the later strong capture from becoming an owner. */ private RuntimeBase semanticCaptureReferent() { if (WeakRefRegistry.isweak(this) || (type & RuntimeScalarType.REFERENCE_BIT) == 0 || !(value instanceof RuntimeBase base) - || base.refCount == Integer.MIN_VALUE) { + || base.isPerlDestroyed()) { return null; } return base; @@ -651,20 +1046,12 @@ private void releaseAllClosureCaptureReferents(RuntimeBase oldBase) { } void releaseClosureCaptureReferentsForWeaken(RuntimeBase oldBase) { - if (captureCount > 0 && oldBase != null) { + if (hasClosureCaptureOwner() && oldBase != null) { releaseClosureOwnerSlot(); } releaseAllClosureCaptureReferents(oldBase); } - void retainClosureCaptureReferentsForUnweaken() { - if (captureCount > 0) { - RuntimeBase base = semanticCaptureReferent(); - updateClosureOwnerSlot(base); - } - retainMissingClosureCaptureReferents(); - } - /** * True if this scalar "owns" a refCount increment on its referent. * Set to true by {@link #setLarge} after incrementing the referent's refCount. @@ -677,28 +1064,1325 @@ void retainClosureCaptureReferentsForUnweaken() { */ public boolean refCountOwned; + /** Changes when a nested operation mutates this scalar's reference slot. */ + private long referenceSlotMutationVersion; + + private PerlOwnerSlot countedOwnerSlot; + /** A B::SV raw pointer view; reachable in Java, but not a Perl owner. */ + boolean nonOwningBObjectReference; + /** Identity for this scalar cell's strong edge to a non-counted referent. */ + private PerlOwnerSlot untrackedReferenceOwnerSlot; + private ArrayList argumentAliasOwnerSlots; + /** Frame identities following this mutable scalar while async code is paused. */ + private Set suspendedFrameOwnerSlots; + + long noteReferenceSlotMutation() { + return ++referenceSlotMutationVersion; + } + + private boolean isCurrentReferenceSlotMutation(long version) { + return referenceSlotMutationVersion == version; + } + // Package names, compiler pins, localized saved slots, and compiled + // references can share one physical CV edge. Keep visible stash bindings + // distinct so weak cleanup does not confuse them with compiler pins. + private int codeSlotBindings; + private int stashCodeSlotBindings; + private boolean deferredDirectCallOwnerBinding; + + boolean hasCodeSlotBinding() { + return codeSlotBindings != 0; + } + + boolean hasStashCodeSlotBinding() { + return stashCodeSlotBindings != 0; + } + + void retainCodeSlotBinding() { + codeSlotBindings++; + refreshCodeSlotOwner(); + } + + void retainStashCodeSlotBinding() { + stashCodeSlotBindings++; + retainCodeSlotBinding(); + } + + void releaseStashCodeSlotBinding() { + if (stashCodeSlotBindings <= 0) { + throw new IllegalStateException("unbalanced stash CODE slot binding"); + } + stashCodeSlotBindings--; + releaseCodeSlotBinding(); + } + + /** Release one compiler-owned CODE edge without draining unrelated releases. */ + void releaseCodeSlotBinding() { + if (codeSlotBindings <= 0) throw new IllegalStateException("unbalanced CODE slot binding"); + if (--codeSlotBindings != 0) return; + refreshUntrackedReferenceOwner(); + MortalList.releaseTrackedCodeSlotAtExactBoundary(this); + } + + synchronized void markDeferredDirectCallOwnerBinding() { + deferredDirectCallOwnerBinding = true; + } + + synchronized boolean consumeDeferredDirectCallOwnerBinding() { + if (!deferredDirectCallOwnerBinding) return false; + deferredDirectCallOwnerBinding = false; + return true; + } + + private void prepareCodeSlotValue(RuntimeScalar source) { + if (codeSlotBindings == 0 || source.type != RuntimeScalarType.CODE + || !(source.value instanceof RuntimeCode code)) return; + code.hasCountedCodeSlots = true; + if (source.compiledDirectCallSiteName == null) code.hadStashRef = true; + if (code.isRefCountUntracked()) code.startRefCountTracking(); + } + + void refreshCodeSlotOwner() { + if (codeSlotBindings == 0 || type != RuntimeScalarType.CODE + || !(value instanceof RuntimeCode code)) return; + MortalList.setActive(true); + prepareCodeSlotValue(this); + incrementRefCountForContainerStore(this, PerlOwnerSlot.Kind.CODE_SLOT); + } + private boolean mortalReturnSnapshot; + private boolean mortalReturnValueOwner; + private RuntimeBase foreachAliasRefCountReferent; + private boolean foreachAliasRefCounted; + private long mortalReturnSourceOwnerIdentity; + private long mortalReturnSourceReleaseSequence; + private RuntimeBase mortalReturnSourceReferent; + private boolean tiedHandlerValueOwner; + private boolean stagedValueOwner; + /** This snapshot temporarily carries a scalar's counted edge during local(). */ + private boolean localizedSavedCountedOwner; + + boolean isMortalReturnSnapshot() { + return mortalReturnSnapshot && !hasStorageOwnerForVoidDiscard() + && !RuntimeCode.isCurrentArgumentAlias(this); + } + + boolean hasMortalReturnSnapshot() { + return mortalReturnSnapshot; + } + + /** Whether the temporary return value still carries its active owner edge. */ + boolean hasActiveMortalReturnValueOwner() { + if (!mortalReturnSnapshot) return false; + if (mortalReturnValueOwner) return true; + PerlOwnerSlot owner = countedOwnerSlot; + if (refCountOwned && owner != null && owner.isActive() + && owner.referent() == value) { + return true; + } + // A deferred return-slot release remains the list's owner until it is + // actually processed. Interpreted calls can enter foreach while that + // release is still queued; counting the alias as well would duplicate + // the same Perl-visible owner. + return value instanceof RuntimeBase referent + && MortalList.pendingCountedReleaseFor(this, referent) != null; + } + + void retainForeachRefCountOwner() { + if (foreachAliasRefCounted || foreachAliasRefCountReferent != null) { + throw new IllegalStateException("foreach refcount owner is already active"); + } + if ((type & RuntimeScalarType.REFERENCE_BIT) == 0 + || !(value instanceof RuntimeBase referent)) return; + foreachAliasRefCountReferent = referent; + boolean activeReturnOwner = hasActiveMortalReturnValueOwner(); + boolean storedCellOwner = hasStorageOwnerForVoidDiscard(); + foreachAliasRefCounted = !activeReturnOwner && !storedCellOwner; + if (referent.refCountTrace && RuntimeBase.refCountTraceEnabled()) { + PerlOwnerSlot owner = countedOwnerSlot; + System.err.println("[FOREACH-ALIAS-HOLD] scalar=" + + System.identityHashCode(this) + " referent=" + + System.identityHashCode(referent) + " refCount=" + referent.refCount + + " snapshot=" + mortalReturnSnapshot + " refCountOwned=" + refCountOwned + + " activeReturnOwner=" + activeReturnOwner + " storedCellOwner=" + + storedCellOwner + " ownerKind=" + (owner == null ? "none" : owner.kind()) + + " ownerActive=" + (owner != null && owner.isActive()) + + " aliasCounted=" + foreachAliasRefCounted); + } + if (foreachAliasRefCounted) referent.foreachAliasCount++; + } + + void releaseForeachRefCountOwner() { + RuntimeBase referent = foreachAliasRefCountReferent; + boolean counted = foreachAliasRefCounted; + foreachAliasRefCountReferent = null; + foreachAliasRefCounted = false; + if (counted && referent != null && referent.foreachAliasCount > 0) { + referent.foreachAliasCount--; + } + } + + /** Whether this scalar is runtime staging, rather than durable Perl storage. */ + boolean isTransientArgumentValueOwner() { + return mortalReturnSnapshot || mortalReturnValueOwner || stagedValueOwner; + } + + /** Identity of this scalar cell's counted edge, retained across assignments. */ + PerlOwnerSlot countedOwnerSlot() { + return countedOwnerSlot; + } + + PerlOwnerSlot untrackedReferenceOwnerSlot() { + return untrackedReferenceOwnerSlot; + } + + boolean hasDurableStrongValueSlot() { + return hasStrongValueSlot(false, true); + } + + /** Whether this scalar still occupies a concrete aggregate storage slot. */ + boolean hasCurrentAggregateStorageSlot() { + synchronized (this) { + for (RuntimeBase owner : containerOwners) { + if (isStoredInContainer(owner)) return true; + } + } + return false; + } + + /** Whether a slot is attached to a container that itself still has a Perl owner. */ + boolean hasLiveDurableStrongValueSlot() { + return hasStrongValueSlot(true, true); + } + + /** Whether a scalar value is current through an active transfer or durable storage. */ + boolean hasLiveCurrentStrongValueSlot() { + return hasStrongValueSlot(true, false); + } + + private boolean hasStrongValueSlot( + boolean requireLiveContainer, boolean requirePersistentContainer) { + PerlRuntime runtime = PerlRuntime.currentOrNull(); + boolean registeredLexical = runtime != null && MyVarCleanupStack.isRegistered(this); + boolean liveOwningContainer; + RuntimeBase currentOwner = containerOwner; + if (currentOwner != null && isStoredInContainer(currentOwner)) { + boolean liveContainerOwner = hasLiveContainerOwner( + currentOwner, requirePersistentContainer, runtime); + if (!requireLiveContainer || liveContainerOwner) return true; + } + liveOwningContainer = hasStoredContainerOwner( + requireLiveContainer, requirePersistentContainer, runtime); + return liveOwningContainer + || ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT) != 0 + || ownerSlotCount(PerlOwnerSlot.Kind.GLOB_COMPONENT_SLOT) != 0 + || localBindingExists + || hasCodeSlotBinding() + || hasClosureCaptureOwner() + || registeredLexical + || mortalReturnValueOwner + || tiedHandlerValueOwner + || stagedValueOwner + || (referencedByScalarReference + && (hasScalarCellOwner() || (!requireLiveContainer && refCount > 0))) + || (this instanceof RuntimeBaseProxy proxy + && proxy.hasLivePerlValueOwner(requirePersistentContainer)); + } + + /** Scan container identities in place so repeated stores do not allocate a full history copy. */ + private boolean hasStoredContainerOwner(boolean requireLiveContainer, + boolean requirePersistentContainer, + PerlRuntime runtime) { + boolean liveOwningContainer = false; + synchronized (this) { + for (Iterator owners = containerOwners.iterator(); owners.hasNext();) { + RuntimeBase owner = owners.next(); + if (!isStoredInContainer(owner)) { + owners.remove(); + prepopulatedPackageAggregateOwners.remove(owner); + if (containerOwner == owner) containerOwner = null; + continue; + } + boolean liveContainerOwner = hasLiveContainerOwner( + owner, requirePersistentContainer, runtime); + if (!requireLiveContainer || liveContainerOwner) liveOwningContainer = true; + } + if (containerOwner == null) { + for (RuntimeBase owner : containerOwners) { + if (isStoredInContainer(owner)) { + containerOwner = owner; + break; + } + } + } + } + return liveOwningContainer; + } + + private static boolean hasLiveContainerOwner(RuntimeBase owner, + boolean requirePersistentContainer, + PerlRuntime runtime) { + return (requirePersistentContainer + ? owner.hasPersistentPerlStrongOwnerIdentity() + : owner.hasCurrentPerlStorageOwner()) + || GlobalVariable.isPackageRootedAggregate(owner) + || (runtime != null && MyVarCleanupStack.isRegistered(owner)); + } + + private boolean isStoredInContainer(RuntimeBase owner) { + return owner instanceof RuntimeHash hash + ? hash.containsElementCellIdentity(this) + : owner instanceof RuntimeArray array && !array.elementsAliased + && array.elements != null && array.elements.contains(this); + } + + private boolean isStoredInAnyContainer(RuntimeBase owner) { + return owner instanceof RuntimeHash hash + ? hash.containsElementCellIdentity(this) + : owner instanceof RuntimeArray array + && array.elements != null && array.elements.contains(this); + } + + private boolean hasStoredContainerOwnerWithoutCurrentOwnerMarker() { + if (containerOwner != null) return false; + for (RuntimeBase owner : containerOwnerSnapshot()) { + if (isStoredInAnyContainer(owner)) return true; + } + return false; + } + + private synchronized List containerOwnerSnapshot() { + return new ArrayList<>(containerOwners); + } + + String debugContainerOwners() { + PerlRuntime runtime = PerlRuntime.currentOrNull(); + return containerOwnerSnapshot().stream().map(owner -> { + String state = owner.getClass().getSimpleName() + "#" + + System.identityHashCode(owner) + + ":stores=" + isStoredInAnyContainer(owner) + + ":perlOwner=" + owner.hasCurrentPerlStorageOwner(); + if (owner instanceof RuntimeArray array) { + state += ":size=" + array.elements.size() + + ":args=" + (runtime != null + && runtime.executionState().argsStack.contains(array)); + } else if (owner instanceof RuntimeHash hash) { + state += ":size=" + hash.elements.size(); + } + return state; + }).toList().toString(); + } + + boolean hasContainerOwnerIn(Set candidates) { + for (RuntimeBase owner : containerOwnerSnapshot()) { + if (candidates.contains(owner)) return true; + } + return false; + } + + private synchronized List prepopulatedPackageAggregateOwnerSnapshot() { + return new ArrayList<>(prepopulatedPackageAggregateOwners); + } + + boolean isPackageAggregateUntrackedReferenceOwner() { + if (type != RuntimeScalarType.ARRAYREFERENCE + && type != RuntimeScalarType.HASHREFERENCE) return false; + RuntimeBase directOwner = containerOwner; + return directOwner != null && hasPackageAggregateOwner(); + } + + boolean hasPackageAggregateUntrackedReferenceOwner() { + if (type != RuntimeScalarType.ARRAYREFERENCE + && type != RuntimeScalarType.HASHREFERENCE) return false; + return hasPackageAggregateOwner(); + } + + private boolean hasPackageAggregateOwner() { + for (RuntimeBase owner : containerOwnerSnapshot()) { + if (isStoredInContainer(owner) + && GlobalVariable.isPackageRootedAggregate(owner)) { + return true; + } + } + return false; + } + + private boolean hasScalarCellOwnerOtherThanClosureCapture() { + if (!referencedByScalarReference) return false; + if (localBindingExists || hasPendingReturnOwner()) return true; + for (PerlOwnerSlot slot : ownerSlotSnapshot()) { + if (slot.isActive() + && slot.kind() != PerlOwnerSlot.Kind.SCALAR_CAPTURE + && PerlOwnerSlot.isPerlOwnerKind(slot.kind())) { + return true; + } + } + return false; + } + + private boolean hasDirectScalarCellStorageOwner() { + if (localBindingExists || MyVarCleanupStack.isRegistered(this) + || ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT) != 0 + || hasCodeSlotBinding() || this instanceof RuntimeBaseProxy + || isStoredInRegisteredContainerOwner() || hasCurrentCodeStateOwner()) { + return true; + } + for (RuntimeBase owner : containerOwnerSnapshot()) { + if (owner instanceof RuntimeHash hash && hash.isPackageRootedHash() + && hash.elements != null && hash.elements.containsValue(this)) { + return true; + } + if (owner instanceof RuntimeArray array && array.isPackageGlobalRoot + && array.elements != null && array.elements.contains(this)) { + return true; + } + } + return referencedByScalarReference && (refCount > 0 + || hasScalarCellOwnerOtherThanClosureCapture()); + } + + private boolean hasCurrentCodeStateOwner() { + for (PerlOwnerSlot ownerSlot : ownerSlotSnapshot()) { + if (ownerSlot.kind() != PerlOwnerSlot.Kind.CODE_STATE + || !ownerSlot.isActive() || ownerSlot.referent() != this) continue; + RuntimeCode owner = ownerSlot.captureOwner(); + if (owner != null && owner.hasStateScalarOwner(this, ownerSlot)) return true; + } + return false; + } + + private void retainUntrackedReferenceOwner(RuntimeBase referent) { + if (untrackedReferenceOwnerSlot == null) { + untrackedReferenceOwnerSlot = new PerlOwnerSlot( + PerlOwnerSlot.Kind.UNTRACKED_REFERENCE); + untrackedReferenceOwnerSlot.associateUntrackedScalarOwner(this); + } + if (this instanceof RuntimeBaseProxy proxy) { + untrackedReferenceOwnerSlot.associateUntrackedProxyValueParent( + proxy.argumentAliasContainer()); + } + // Transfer the existing identity in place. PerlOwnerSlot installs its + // new referent before releasing the previous one, so cleanup callbacks + // cannot observe a gap where this scalar's current value has no owner. + untrackedReferenceOwnerSlot.acquireUntrackedIdentity(referent); + } + + void releaseUntrackedReferenceOwner(RuntimeBase expectedReferent) { + if (untrackedReferenceOwnerSlot == null + || untrackedReferenceOwnerSlot.referent() != expectedReferent) return; + untrackedReferenceOwnerSlot.release(); + WeakRefRegistry.onStrongOwnerSlotReleased(expectedReferent); + } + + void finalizeUntrackedValueAfterScopeExit(RuntimeBase expectedReferent) { + if (expectedReferent == null) return; + refreshUntrackedReferenceOwner(); + if (hasDurableStrongValueSlot()) return; + releaseUntrackedReferenceOwner(expectedReferent); + WeakRefRegistry.finalizeUntrackedAfterOwnerScopeExit(expectedReferent); + } + + private void updateUntrackedReferenceOwner(RuntimeBase referent) { + updateUntrackedReferenceOwner(referent, false); + } + + private void updateUntrackedReferenceOwner(RuntimeBase referent, + boolean requireCurrentValueOwner) { + if (nonOwningBObjectReference) { + if (untrackedReferenceOwnerSlot != null) { + releaseUntrackedReferenceOwner(untrackedReferenceOwnerSlot.referent()); + } + return; + } + // Container-owner proofs are needed only while this scalar holds a + // RuntimeBase reference. Primitive values have no referent to retain, + // and scanning their container history on every array insertion turns + // large scalar-list builds quadratic for no ownership benefit. + if (referent == null) { + if (untrackedReferenceOwnerSlot != null) { + releaseUntrackedReferenceOwner(untrackedReferenceOwnerSlot.referent()); + } + return; + } + // RuntimeGraphCloner may rebuild a tied handler before it binds the + // destination runtime. Such a fresh scalar cannot be a registered weak + // observer yet, and its owner identity still belongs on the clone. + PerlRuntime runtime = PerlRuntime.currentOrNull(); + boolean weakValue = runtime != null && WeakRefRegistry.isweak(this); + boolean existingOwnerForReferent = untrackedReferenceOwnerSlot != null + && untrackedReferenceOwnerSlot.isActive() + && untrackedReferenceOwnerSlot.referent() == referent; + boolean countedOwnerActive = refCountOwned + && countedOwnerSlot != null + && countedOwnerSlot.isActive() + && countedOwnerSlot.referent() == referent; + boolean packageScalarValueOwner = + ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT) != 0; + boolean packageAggregateValueOwner = referent != null + && prepopulatedPackageAggregateOwnerSnapshot().stream().anyMatch(owner -> + isStoredInContainer(owner) + && GlobalVariable.isPackageRootedAggregate(owner)); + boolean localAggregateValueOwner = hasLocalAggregateContainerOwner(); + boolean liveAggregateValueOwner = localAggregateValueOwner + && hasLiveDurableStrongValueSlot(); + boolean untrackedStrongValue = !weakValue + && referent != null + && !referent.isPerlDestroyed() + && (!referent.isRefCountTracked() + || existingOwnerForReferent + || packageScalarValueOwner + || packageAggregateValueOwner + || liveAggregateValueOwner) + && !countedOwnerActive; + boolean hasValueOwner = requireCurrentValueOwner + ? hasLiveCurrentStrongValueSlot() : hasDurableStrongValueSlot(); + if (hasValueOwner && untrackedStrongValue) { + retainUntrackedReferenceOwner(referent); + } else if (untrackedReferenceOwnerSlot != null) { + releaseUntrackedReferenceOwner(untrackedReferenceOwnerSlot.referent()); + } + refreshTransientUntrackedOwnerClassification(); + } + + private void refreshTransientUntrackedOwnerClassification() { + if (untrackedReferenceOwnerSlot != null) { + untrackedReferenceOwnerSlot.refreshTransientUntrackedOwnerClassification(); + } + } + + private boolean hasLocalAggregateContainerOwner() { + RuntimeBase currentOwner; + synchronized (this) { + currentOwner = containerOwner; + if (currentOwner != null && containerOwners.contains(currentOwner) + && isLocalAggregateOwner(currentOwner)) { + return true; + } + } + return containerOwnerSnapshot().stream().anyMatch(this::isLocalAggregateOwner); + } + + private boolean isLocalAggregateOwner(RuntimeBase owner) { + return (owner instanceof RuntimeHash || owner instanceof RuntimeArray) + && !GlobalVariable.isPackageRootedAggregate(owner); + } + + void refreshUntrackedReferenceOwner() { + updateUntrackedReferenceOwner((type & RuntimeScalarType.REFERENCE_BIT) != 0 + && value instanceof RuntimeBase referent ? referent : null); + refreshSuspendedFrameOwnerSlots(); + refreshDetachedGlobValueOwner(); + } + + public static final class ArgumentAliasOwner { + private final RuntimeScalar scalar; + private final PerlOwnerSlot ownerSlot; + + private ArgumentAliasOwner(RuntimeScalar scalar, PerlOwnerSlot ownerSlot) { + this.scalar = scalar; + this.ownerSlot = ownerSlot; + } + + boolean matches(RuntimeScalar candidate) { + return scalar == candidate; + } + + RuntimeScalar scalar() { + return scalar; + } + + public void release() { + scalar.releaseArgumentAliasOwner(ownerSlot); + } + } + + /** + * Retain this scalar cell while Perl code aliases it as an argument or + * list-operator topic. This records the referent owner represented by the + * alias; it does not copy the scalar or add a second Perl-visible value. + */ + public synchronized ArgumentAliasOwner retainArgumentAliasOwner() { + PerlOwnerSlot ownerSlot = new PerlOwnerSlot(PerlOwnerSlot.Kind.ARGUMENT_ALIAS); + if (argumentAliasOwnerSlots == null) argumentAliasOwnerSlots = new ArrayList<>(); + argumentAliasOwnerSlots.add(ownerSlot); + try { + refreshArgumentAliasOwnerSlots(); + } catch (Throwable acquisitionFailure) { + argumentAliasOwnerSlots.remove(ownerSlot); + if (argumentAliasOwnerSlots.isEmpty()) argumentAliasOwnerSlots = null; + Throwable failure = RuntimeCode.attemptCleanup( + acquisitionFailure, ownerSlot::release); + RuntimeCode.rethrowCleanupFailure(failure); + } + return new ArgumentAliasOwner(this, ownerSlot); + } + + private void releaseArgumentAliasOwner(PerlOwnerSlot ownerSlot) { + synchronized (this) { + if (argumentAliasOwnerSlots != null) { + argumentAliasOwnerSlots.remove(ownerSlot); + if (argumentAliasOwnerSlots.isEmpty()) argumentAliasOwnerSlots = null; + } + } + ownerSlot.release(); + } + + synchronized void refreshArgumentAliasOwnerSlots() { + if (argumentAliasOwnerSlots != null) { + RuntimeBase referent = null; + if (((type & RuntimeScalarType.REFERENCE_BIT) != 0 || type == RuntimeScalarType.GLOB) + && value instanceof RuntimeBase base + && !WeakRefRegistry.isweak(this)) { + referent = base; + } + for (PerlOwnerSlot ownerSlot : argumentAliasOwnerSlots) { + if (referent == null) ownerSlot.release(); + else ownerSlot.acquireArgumentAliasIdentity(referent); + } + } + refreshSuspendedFrameOwnerSlots(); + } + + private synchronized boolean hasActiveArgumentAliasOwner(RuntimeBase referent) { + if (referent == null || argumentAliasOwnerSlots == null) return false; + for (PerlOwnerSlot ownerSlot : argumentAliasOwnerSlots) { + if (ownerSlot.isActive() && ownerSlot.referent() == referent) return true; + } + return false; + } + + /** Attach the owner identity for one lexical register retained by a suspended frame. */ + public synchronized void attachSuspendedFrameOwner(PerlOwnerSlot ownerSlot) { + if (ownerSlot == null || ownerSlot.kind() != PerlOwnerSlot.Kind.SUSPENDED_FRAME) { + throw new IllegalArgumentException("suspended lexical owner requires a suspended-frame slot"); + } + if (suspendedFrameOwnerSlots == null) { + suspendedFrameOwnerSlots = Collections.newSetFromMap(new IdentityHashMap<>()); + } + suspendedFrameOwnerSlots.add(ownerSlot); + ownerSlot.associateSuspendedScalarOwner(this); + ownerSlot.updateSuspendedFrameIdentity(currentStrongReferenceValue()); + } + + /** Detach and release one suspended-frame identity from this scalar cell. */ + public synchronized void detachSuspendedFrameOwner(PerlOwnerSlot ownerSlot) { + if (suspendedFrameOwnerSlots != null) { + suspendedFrameOwnerSlots.remove(ownerSlot); + if (suspendedFrameOwnerSlots.isEmpty()) suspendedFrameOwnerSlots = null; + } + if (ownerSlot != null) { + ownerSlot.associateSuspendedScalarOwner(null); + ownerSlot.release(); + } + } + + private void refreshSuspendedFrameOwnerSlots() { + if (suspendedFrameOwnerSlots == null) return; + RuntimeBase referent = currentStrongReferenceValue(); + for (PerlOwnerSlot ownerSlot : new ArrayList<>(suspendedFrameOwnerSlots)) { + ownerSlot.updateSuspendedFrameIdentity(referent); + } + } + + private RuntimeBase currentStrongReferenceValue() { + PerlRuntime runtime = PerlRuntime.currentOrNull(); + if ((runtime != null && WeakRefRegistry.isweak(this)) + || ((type & RuntimeScalarType.REFERENCE_BIT) == 0 && type != RuntimeScalarType.GLOB) + || !(value instanceof RuntimeBase referent) + || referent.isPerlDestroyed()) { + return null; + } + return referent; + } + + boolean hasStorageOwnerForVoidDiscard() { + if (localBindingExists || hasClosureCaptureOwner() || isPackageGlobalRoot + || MyVarCleanupStack.isRegistered(this) || hasScalarCellOwner()) { + return true; + } + PerlOwnerSlot slot = countedOwnerSlot; + return slot != null && slot.isActive() + && (slot.kind() == PerlOwnerSlot.Kind.ARRAY_ELEMENT + || slot.kind() == PerlOwnerSlot.Kind.HASH_ELEMENT) + && value instanceof RuntimeBase referent + && hasCurrentAggregateElementPerlStorageOwner(referent, slot); + } + + /** Whether this scalar is a durable Perl cell that can be aliased by a call. */ + boolean hasPersistentArgumentStorageCell() { + if (hasClosureCaptureOwner() || isPackageGlobalRoot || localBindingExists + || MyVarCleanupStack.isRegistered(this)) { + return true; + } + if (containerOwner instanceof RuntimeHash) return true; + return containerOwner instanceof RuntimeArray array && !array.elementsAliased; + } + + /** Compatibility bridge for fixtures and pre-slot scalar construction. */ + void recordCountedOwner(RuntimeBase referent) { + if (countedOwnerSlot == null) { + countedOwnerSlot = new PerlOwnerSlot(countedOwnerKind()); + } + countedOwnerSlot.acquireCountedIdentity(referent); + countedOwnerSlot.associateCountedScalarOwner(this); + } + + /** Verify that this scalar's Perl strong edge has its paired active slot. */ + private void requireCountedOwner(RuntimeBase referent, String operation) { + PerlOwnerSlot slot = countedOwnerSlot; + if (!refCountOwned || slot == null || !slot.isActive() + || slot.referent() != referent || slot.countedScalarOwner() != this + || !PerlOwnerSlot.isCountedKind(slot.kind())) { + throw new IllegalStateException( + operation + " requires a paired active Perl owner slot"); + } + } + + /** Acquire one counted edge for a scalar that already contains its referent. */ + public static void acquireCountedOwnerForCurrentValue( + RuntimeScalar scalar, RuntimeBase referent, + PerlOwnerSlot.Kind intendedOwnerKind, String acquisitionSite) { + Objects.requireNonNull(scalar, "scalar"); + Objects.requireNonNull(referent, "referent"); + Objects.requireNonNull(acquisitionSite, "acquisitionSite"); + if (intendedOwnerKind != null && !PerlOwnerSlot.isCountedKind(intendedOwnerKind)) { + throw new IllegalArgumentException("counted acquisition requires a counted owner kind"); + } + if (scalar.value != referent + || (!RuntimeScalarType.isReference(scalar) + && scalar.type != RuntimeScalarType.GLOB + && scalar.type != RuntimeScalarType.CODE)) { + throw new IllegalStateException( + "counted acquisition requires the scalar's current referent"); + } + if (scalar.refCountOwned) { + PerlOwnerSlot slot = scalar.countedOwnerSlot; + if (slot == null || !slot.isActive() || slot.referent() != referent + || slot.countedScalarOwner() != scalar) { + throw new IllegalStateException( + "counted scalar flag has no matching active owner slot"); + } + slot.reclassifyCountedIdentity(intendedOwnerKind == null + ? scalar.countedOwnerKind() : intendedOwnerKind); + scalar.associateCountedAggregateOwnerIfAbsent(scalar.containerOwner); + return; + } + PerlOwnerSlot slot = scalar.countedOwnerSlot; + acquireCountedOwnerForPendingValue(scalar, referent, + intendedOwnerKind == null ? scalar.countedOwnerKind() : intendedOwnerKind, + acquisitionSite); + } + + /** Reify an already-counted legacy storage edge as a slot before release. */ + static void adoptExistingCountedOwnerForCurrentValue( + RuntimeScalar scalar, RuntimeBase referent, + PerlOwnerSlot.Kind ownerKind, String acquisitionSite) { + Objects.requireNonNull(scalar, "scalar"); + Objects.requireNonNull(referent, "referent"); + Objects.requireNonNull(ownerKind, "ownerKind"); + Objects.requireNonNull(acquisitionSite, "acquisitionSite"); + if (!PerlOwnerSlot.isCountedKind(ownerKind) + || scalar.value != referent + || (!RuntimeScalarType.isReference(scalar) + && scalar.type != RuntimeScalarType.GLOB + && scalar.type != RuntimeScalarType.CODE) + || referent.refCount <= 0 + || referent.isPerlDestroyed()) { + throw new IllegalStateException( + "legacy owner adoption requires an existing counted storage edge at " + + acquisitionSite); + } + PerlOwnerSlot slot = scalar.countedOwnerSlot; + if (slot == null) { + slot = new PerlOwnerSlot(ownerKind); + scalar.countedOwnerSlot = slot; + } else { + if (slot.isActive()) { + throw new IllegalStateException( + "legacy owner adoption found an active counted slot at " + + acquisitionSite); + } + slot.reclassifyCountedIdentity(ownerKind); + } + slot.acquireCountedIdentity(referent); + slot.associateCountedScalarOwner(scalar); + scalar.refCountOwned = true; + referent.recordOwner(scalar, acquisitionSite); + scalar.associateCountedAggregateOwnerIfAbsent(scalar.containerOwner); + } + + /** Acquire a paired count and identity before a pending scalar value is published. */ + private static void acquireCountedOwnerForPendingValue( + RuntimeScalar scalar, RuntimeBase referent, + PerlOwnerSlot.Kind ownerKind, String acquisitionSite) { + Objects.requireNonNull(scalar, "scalar"); + Objects.requireNonNull(referent, "referent"); + Objects.requireNonNull(ownerKind, "ownerKind"); + Objects.requireNonNull(acquisitionSite, "acquisitionSite"); + if (!PerlOwnerSlot.isCountedKind(ownerKind)) { + throw new IllegalArgumentException("counted acquisition requires a counted owner kind"); + } + if (scalar.refCountOwned) { + throw new IllegalStateException( + "pending counted acquisition requires the scalar's old edge to be retired"); + } + if (!referent.isRefCountTracked() || referent.refCount == Integer.MAX_VALUE) { + throw new IllegalStateException( + "counted acquisition requires an available tracked reference count"); + } + + PerlOwnerSlot slot = scalar.countedOwnerSlot; + if (slot == null) { + slot = new PerlOwnerSlot(ownerKind); + scalar.countedOwnerSlot = slot; + } else { + if (slot.isActive()) { + throw new IllegalStateException( + "unowned scalar already has an active counted owner slot"); + } + slot.reclassifyCountedIdentity(ownerKind); + } + slot.acquireCountedScalarOwner(scalar, referent, acquisitionSite); + scalar.associateCountedAggregateOwnerIfAbsent(scalar.containerOwner); + } + + boolean isCurrentAggregateElementOwner(RuntimeBase referent, PerlOwnerSlot slot) { + if (countedOwnerSlot != slot || !refCountOwned || value != referent + || !slot.isActive() || slot.referent() != referent) { + return false; + } + if (localizedSavedCountedOwner) { + return slot.kind() == PerlOwnerSlot.Kind.ARRAY_ELEMENT + || slot.kind() == PerlOwnerSlot.Kind.HASH_ELEMENT; + } + if (slot.kind() == PerlOwnerSlot.Kind.ARRAY_ELEMENT) { + return containerOwner instanceof RuntimeArray array + && !array.elementsAliased && array.elements.contains(this); + } + return slot.kind() == PerlOwnerSlot.Kind.HASH_ELEMENT + && containerOwner instanceof RuntimeHash hash + && hash.containsElementCellIdentity(this); + } + + private boolean isStoredAggregateElementOwner(RuntimeBase container, + PerlOwnerSlot.Kind kind) { + return switch (kind) { + case ARRAY_ELEMENT -> container instanceof RuntimeArray array + && !array.elementsAliased && array.elements != null + && array.elements.contains(this); + case HASH_ELEMENT -> container instanceof RuntimeHash hash + && hash.containsElementCellIdentity(this); + default -> false; + }; + } + + /** Whether a live container holding this counted owner has Perl storage. */ + boolean hasCurrentAggregateElementPerlStorageOwner( + RuntimeBase referent, PerlOwnerSlot slot) { + if (countedOwnerSlot != slot || !refCountOwned || value != referent + || !slot.isActive() || slot.referent() != referent) { + return false; + } + if (localizedSavedCountedOwner) { + RuntimeBase container = containerOwner; + return container != null + && (container.perlLifecycleState() == RuntimeBase.PerlLifecycleState.DESTROYING + || container.hasCurrentPerlStorageOwner()); + } + RuntimeBase container = slot.countedAggregateOwner(); + if (container == null) container = containerOwner; + return container != null + && isStoredAggregateElementOwner(container, slot.kind()) + && (container.perlLifecycleState() == RuntimeBase.PerlLifecycleState.DESTROYING + || container.hasCurrentPerlStorageOwner()); + } + + /** Return a validated ordinary aggregate owner for temporary-root proofs. */ + RuntimeBase currentTemporaryRootAggregateOwner( + RuntimeBase referent, PerlOwnerSlot slot) { + if (referent == null || slot == null || !slot.isActive() + || slot.referent() != referent || value != referent + || WeakRefRegistry.isweak(this)) { + return null; + } + + RuntimeBase container = containerOwner; + if (container instanceof RuntimeArray array) { + if (array.type != RuntimeArray.PLAIN_ARRAY || array.elementsAliased + || array.threadShared || !array.elements.contains(this)) { + return null; + } + } else if (container instanceof RuntimeHash hash) { + if (hash.type != RuntimeHash.PLAIN_HASH || hash.threadShared + || !hash.containsElementCellIdentity(this)) { + return null; + } + } else { + return null; + } + + return switch (slot.kind()) { + case ARRAY_ELEMENT, HASH_ELEMENT -> + slot.countedScalarOwner() == this + && isCurrentAggregateElementOwner(referent, slot) + ? container : null; + case UNTRACKED_REFERENCE -> + slot == untrackedReferenceOwnerSlot + && slot.untrackedScalarOwner() == this + && !isTransientArgumentValueOwner() + && (((type & RuntimeScalarType.REFERENCE_BIT) != 0) + || type == RuntimeScalarType.GLOB + || type == RuntimeScalarType.CODE) + ? container : null; + default -> null; + }; + } + + boolean isCurrentCountedScalarOwner(RuntimeBase referent, PerlOwnerSlot slot) { + PerlOwnerSlot.Kind kind = slot.kind(); + if (localizedSavedCountedOwner) { + return countedOwnerSlot == slot && refCountOwned && value == referent + && slot.isActive() && slot.referent() == referent; + } + boolean activeArgumentAlias = kind == PerlOwnerSlot.Kind.SCALAR_CELL + && hasActiveArgumentAliasOwner(referent); + if ((kind != PerlOwnerSlot.Kind.SCALAR_CELL + && kind != PerlOwnerSlot.Kind.CODE_SLOT + && kind != PerlOwnerSlot.Kind.ARGUMENT_VALUE + && kind != PerlOwnerSlot.Kind.ARGUMENT_CONTAINER + && kind != PerlOwnerSlot.Kind.RETURN_VALUE + && kind != PerlOwnerSlot.Kind.TIE_HANDLER + && kind != PerlOwnerSlot.Kind.ARGUMENT_TIE_HANDLER) + || countedOwnerSlot != slot || !refCountOwned || value != referent + || ((type & RuntimeScalarType.REFERENCE_BIT) == 0 + && type != RuntimeScalarType.GLOB + && type != RuntimeScalarType.CODE) + || WeakRefRegistry.isweak(this) || !slot.isActive() + || slot.referent() != referent) { + return false; + } + if (kind == PerlOwnerSlot.Kind.ARGUMENT_CONTAINER) return stagedValueOwner; + if (kind == PerlOwnerSlot.Kind.SCALAR_CELL + && hasStoredContainerOwnerWithoutCurrentOwnerMarker() + && !localBindingExists + && !MyVarCleanupStack.isRegistered(this) + && ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT) == 0 + && !hasCodeSlotBinding() + && !(this instanceof RuntimeBaseProxy) + && !activeArgumentAlias) { + return false; + } + if (kind != PerlOwnerSlot.Kind.SCALAR_CELL + || hasDirectScalarCellStorageOwner() || activeArgumentAlias) { + return true; + } + return hasCurrentAggregateStorageOwner() + || isCurrentCapturedScalarCellOwner(referent, slot); + } + + /** + * Narrow compatibility proof for a standalone scalar cell whose storage + * has not yet been registered with a lexical, package, code, or container + * owner. This does not accept stale container associations or aliases. + */ + boolean isUnregisteredCountedScalarCellOwner(RuntimeBase referent, PerlOwnerSlot slot) { + if (slot.kind() != PerlOwnerSlot.Kind.SCALAR_CELL + || countedOwnerSlot != slot || slot.countedScalarOwner() != this + || !refCountOwned || value != referent + || ((type & RuntimeScalarType.REFERENCE_BIT) == 0 + && type != RuntimeScalarType.GLOB + && type != RuntimeScalarType.CODE) + || WeakRefRegistry.isweak(this) || scopeExited + || !slot.isActive() || slot.referent() != referent + || hasClosureCaptureOwner() || hasActiveArgumentAliasOwner(referent) + || !containerOwnerSnapshot().isEmpty() + || hasDirectScalarCellStorageOwner()) { + return false; + } + return true; + } + + boolean hasCurrentAggregateStorageOwner() { + for (RuntimeBase owner : containerOwnerSnapshot()) { + if (isStoredInAnyContainer(owner)) return true; + } + return false; + } + + /** Whether a stored aggregate containing this cell still has a Perl owner. */ + boolean hasLiveCurrentAggregateStorageOwner() { + for (RuntimeBase owner : containerOwnerSnapshot()) { + if (isStoredInAnyContainer(owner) && owner.hasCurrentPerlStorageOwner()) return true; + } + return false; + } + + boolean isCurrentCapturedScalarCellOwner(RuntimeBase referent, PerlOwnerSlot slot) { + if (slot.kind() != PerlOwnerSlot.Kind.SCALAR_CELL + || countedOwnerSlot != slot || !refCountOwned || value != referent + || ((type & RuntimeScalarType.REFERENCE_BIT) == 0 + && type != RuntimeScalarType.GLOB + && type != RuntimeScalarType.CODE) + || WeakRefRegistry.isweak(this) || !slot.isActive() + || slot.referent() != referent || !hasClosureCaptureOwner()) { + return false; + } + for (PerlOwnerSlot captureSlot : ownerSlotSnapshot()) { + if (captureSlot.kind() != PerlOwnerSlot.Kind.SCALAR_CAPTURE + || !captureSlot.isActive() || captureSlot.referent() != this) continue; + RuntimeCode captureOwner = captureSlot.captureOwner(); + if (captureOwner != null && captureOwner.hasPerlOwnerForCapture()) return true; + } + return false; + } + + public PerlOwnerSlot.Kind countedOwnerKind() { + return codeSlotBindings != 0 ? PerlOwnerSlot.Kind.CODE_SLOT + : containerOwner instanceof RuntimeHash ? PerlOwnerSlot.Kind.HASH_ELEMENT + : containerOwner instanceof RuntimeArray array + && !array.elementsAliased + ? PerlOwnerSlot.Kind.ARRAY_ELEMENT : PerlOwnerSlot.Kind.SCALAR_CELL; + } + + /** Copy a reference into a return-owned scalar and defer its exact release. */ + public static RuntimeScalar copyToMortalReturnSlot(RuntimeScalar source) { + RuntimeScalar copy = new RuntimeScalar(source); + copy.mortalReturnSnapshot = true; + copy.copiedFromArgumentFrame = null; + copy.captureMortalReturnSourceOwner(source); + incrementRefCountForContainerStore(copy, PerlOwnerSlot.Kind.RETURN_VALUE); + if (copy.refCountOwned) { + MortalList.deferDecrementIfTracked(copy); + } else { + copy.mortalReturnValueOwner = true; + copy.refreshUntrackedReferenceOwner(); + if (copy.untrackedReferenceOwnerSlot != null) { + MortalList.deferUntrackedReturnValueOwnerRelease(copy); + } else { + copy.mortalReturnValueOwner = false; + } + } + source.releasePostfixReferenceTransferOwner( + "RuntimeScalar.copyToMortalReturnSlot postfix temporary transfer"); + return copy; + } + + /** + * Retire the owner moved into a postfix result after another Perl value + * has taken responsibility for that result. Assignment and subroutine + * return are both such transfers; the latter first acquires its mortal + * return-slot owner in {@link #copyToMortalReturnSlot(RuntimeScalar)}. + */ + private void releasePostfixReferenceTransferOwner(String releaseSite) { + if (!postfixReferenceOwnershipTransfer) return; + postfixReferenceOwnershipTransfer = false; + if (refCountOwned + && (type & REFERENCE_BIT) != 0 + && value instanceof RuntimeBase) { + MortalList.releaseCountedOwnerImmediately(this, releaseSite); + } + } + + private void captureMortalReturnSourceOwner(RuntimeScalar source) { + if (source == null || !(source.value instanceof RuntimeBase referent)) return; + PerlOwnerSlot sourceSlot = source.countedOwnerSlot; + if (sourceSlot == null || sourceSlot.referent() != referent) return; + if (source.refCountOwned && sourceSlot.isActive()) { + mortalReturnSourceOwnerIdentity = sourceSlot.identity(); + mortalReturnSourceReleaseSequence = sourceSlot.nextReleaseSequenceValue(); + mortalReturnSourceReferent = referent; + return; + } + PerlOwnerSlot.PendingRelease pendingRelease = + MortalList.pendingCountedReleaseFor(source, referent); + if (pendingRelease != null) { + mortalReturnSourceOwnerIdentity = pendingRelease.ownerSlotIdentity(); + mortalReturnSourceReleaseSequence = pendingRelease.sequence(); + mortalReturnSourceReferent = referent; + } + } + + long mortalReturnSourceOwnerIdentity() { + return mortalReturnSourceOwnerIdentity; + } + + long mortalReturnSourceReleaseSequence() { + return mortalReturnSourceReleaseSequence; + } + + RuntimeBase mortalReturnSourceReferent() { + return mortalReturnSourceReferent; + } + + void finishMortalReturnHandoff() { + mortalReturnSnapshot = false; + refreshTransientUntrackedOwnerClassification(); + mortalReturnSourceOwnerIdentity = 0; + mortalReturnSourceReleaseSequence = 0; + mortalReturnSourceReferent = null; + } + + void releaseMortalReturnValueOwner() { + if (!mortalReturnValueOwner) return; + mortalReturnValueOwner = false; + refreshUntrackedReferenceOwner(); + } + + /** Snapshot one tie wrapper's strong handler edge independently of its source. */ + static RuntimeScalar retainTiedHandlerValue(RuntimeScalar source) { + return retainTiedHandlerValue(source, PerlOwnerSlot.Kind.TIE_HANDLER); + } + + /** Retain a tie handler for an owner slot with its own Perl lifetime. */ + static RuntimeScalar retainTiedHandlerValue( + RuntimeScalar source, PerlOwnerSlot.Kind ownerKind) { + if (source == null) return null; + if (ownerKind != PerlOwnerSlot.Kind.TIE_HANDLER + && ownerKind != PerlOwnerSlot.Kind.ARGUMENT_TIE_HANDLER) { + throw new IllegalArgumentException("invalid tie-handler owner kind"); + } + RuntimeScalar owner = new RuntimeScalar(source); + incrementRefCountForContainerStore(owner, ownerKind); + owner.tiedHandlerValueOwner = true; + owner.refreshUntrackedReferenceOwner(); + return owner; + } + + /** Retire the tie owner while retaining a borrow for deferred magic restoration. */ + static void releaseTiedHandlerValue(RuntimeScalar owner) { + if (owner == null || !owner.tiedHandlerValueOwner) return; + owner.tiedHandlerValueOwner = false; + owner.refreshUntrackedReferenceOwner(); + if (owner.refCountOwned) MortalList.deferDecrementIfTracked(owner); + if (PerlRuntime.currentOrNull() != null) MortalList.flushAboveMark(); + } + + static RuntimeScalar retainEvalReturnValue(RuntimeScalar source) { + RuntimeScalar owner = retainStagedArgumentValue(source); + if (owner.refCountOwned) { + owner.countedOwnerSlot.reclassifyCountedIdentity(PerlOwnerSlot.Kind.RETURN_VALUE); + } + return owner; + } + + static RuntimeScalar retainStagedArgumentValue(RuntimeScalar source) { + RuntimeScalar owner = new RuntimeScalar(); + owner.set(source); + owner.stagedValueOwner = true; + owner.refreshUntrackedReferenceOwner(); + if (owner.refCountOwned) { + owner.countedOwnerSlot.reclassifyCountedIdentity(PerlOwnerSlot.Kind.ARGUMENT_VALUE); + } + return owner; + } + + /** Acquire the containing aggregate edge for one active aliased argument. */ + static RuntimeScalar retainArgumentContainerValue(RuntimeBase container) { + if (!(container instanceof RuntimeArray || container instanceof RuntimeHash)) return null; + RuntimeScalar owner = new RuntimeScalar(); + owner.type = container instanceof RuntimeArray + ? RuntimeScalarType.ARRAYREFERENCE : RuntimeScalarType.HASHREFERENCE; + owner.value = container; + owner.stagedValueOwner = true; + incrementRefCountForContainerStore(owner, PerlOwnerSlot.Kind.ARGUMENT_CONTAINER); + if (!owner.refCountOwned) owner.refreshUntrackedReferenceOwner(); + return owner; + } + + /** Release one argument-container edge and complete its exact count transition now. */ + static void releaseArgumentContainerValue(RuntimeScalar owner) { + if (owner == null || !owner.stagedValueOwner) return; + owner.stagedValueOwner = false; + owner.refreshUntrackedReferenceOwner(); + MortalList.releaseCountedOwnerImmediately( + owner, "RuntimeCode argument-container alias release"); + } + + /** Release a temporary call/return owner after its boundary has drained. */ + static void releaseStagedArgumentValue(RuntimeScalar owner) { + if (owner == null || !owner.stagedValueOwner) return; + owner.stagedValueOwner = false; + owner.refreshUntrackedReferenceOwner(); + MortalList.deferDecrementIfTracked(owner); + } + + void releaseCountedOwner(RuntimeBase referent) { + if (countedOwnerSlot != null && countedOwnerSlot.referent() == referent) { + countedOwnerSlot.release(); + } + } + + /** Retire a counted storage edge during host-side graph construction. */ + static void releaseCountedOwnerWithoutPerlRuntime( + RuntimeScalar owner, RuntimeBase referent, String releaseSite) { + MortalList.releaseCountedOwnerWithoutPerlRuntime(owner, referent, releaseSite); + } + + /** Retire the paired Perl edge and IO lease of an assignment transport copy. */ + static void releaseMaterializedAssignmentCopy( + RuntimeScalar scalar, String target, RuntimeBase returned) { + if (scalar == null) return; + releaseIoOwnerPreservingReturned(scalar, returned); + if (!scalar.refCountOwned + || ((scalar.type & RuntimeScalarType.REFERENCE_BIT) == 0 + && scalar.type != RuntimeScalarType.GLOB) + || !(scalar.value instanceof RuntimeBase base) + || base.refCount <= 0) return; + MortalList.releaseCountedOwnerImmediately( + scalar, "RuntimeList materialized-copy undo (" + target + ")"); + } + + PerlOwnerSlot.PendingRelease deferCountedOwnerRelease(RuntimeBase referent) { + return releaseCountedOwnerIdentity(referent, null, false, true); + } + + /** + * Retire this scalar's exact counted Perl edge as one ownership transition. + * Deferred queueing leaves the trace owner in place until RuntimeBase has + * captured it; immediate releases remove that trace entry here. + */ + PerlOwnerSlot.PendingRelease releaseCountedOwnerIdentity( + RuntimeBase referent, String releaseSite, boolean releaseTrace) { + return releaseCountedOwnerIdentity(referent, releaseSite, releaseTrace, false); + } + + private PerlOwnerSlot.PendingRelease releaseCountedOwnerIdentity( + RuntimeBase referent, String releaseSite, boolean releaseTrace, + boolean publishPendingOwnerBeforeRelease) { + PerlOwnerSlot slot = countedOwnerSlot; + if (slot == null) { + return null; + } + if (!refCountOwned || !slot.isActive() || slot.referent() != referent + || slot.countedScalarOwner() != this + || !PerlOwnerSlot.isCountedKind(slot.kind())) return null; + PerlOwnerSlot.PendingRelease release = + slot.releaseCountedIdentity(publishPendingOwnerBeforeRelease); + if (release == null) return null; + refCountOwned = false; + if (releaseTrace) referent.releaseOwner(this, releaseSite); + return release; + } + + private void transferCountedOwnerTo(RuntimeScalar destination) { + Objects.requireNonNull(destination, "destination"); + if (destination == this) { + throw new IllegalArgumentException("counted owner transfer requires a distinct scalar"); + } + if (!refCountOwned || countedOwnerSlot == null || !countedOwnerSlot.isActive() + || countedOwnerSlot.referent() != value + || destination.value != value) { + throw new IllegalStateException( + "counted owner transfer requires the source and destination to carry the same active owner"); + } + destination.countedOwnerSlot = countedOwnerSlot; + countedOwnerSlot = null; + destination.countedOwnerSlot.associateCountedScalarOwner(destination); + destination.refCountOwned = true; + refCountOwned = false; + } + + /** + * Promote the old value returned by postfix ++/-- to the existing counted + * edge. A borrowed source may have no scalar token, so this Perl value + * transition adopts the already-counted edge into the returned scalar. + */ + private void transferPostfixReferenceOwnerTo(RuntimeScalar destination) { + Objects.requireNonNull(destination, "destination"); + if (!(value instanceof RuntimeBase referent) || destination.value != referent) { + throw new IllegalStateException( + "postfix owner promotion requires matching reference values"); + } + if (refCountOwned && countedOwnerSlot != null && countedOwnerSlot.isActive() + && countedOwnerSlot.referent() == referent) { + transferCountedOwnerTo(destination); + return; + } + if (refCountOwned) { + throw new IllegalStateException( + "postfix owner promotion found a counted scalar without its active token"); + } + adoptExistingCountedOwnerForCurrentValue( + destination, referent, destination.countedOwnerKind(), + "postfix reference result promotion"); + } + + /** Move a non-counted strong value edge with a localized scalar snapshot. */ + private void transferUntrackedOwnerTo(RuntimeScalar destination) { + destination.untrackedReferenceOwnerSlot = untrackedReferenceOwnerSlot; + untrackedReferenceOwnerSlot = null; + if (destination.untrackedReferenceOwnerSlot != null) { + destination.untrackedReferenceOwnerSlot.associateUntrackedScalarOwner(destination); + RuntimeBase proxyParent = destination instanceof RuntimeBaseProxy proxy + ? proxy.argumentAliasContainer() : null; + destination.untrackedReferenceOwnerSlot.associateUntrackedProxyValueParent( + proxyParent); + } + } + + private static void releaseDetachedUntrackedOwner(PerlOwnerSlot ownerSlot) { + if (ownerSlot == null) return; + RuntimeBase referent = ownerSlot.referent(); + ownerSlot.associateUntrackedScalarOwner(null); + ownerSlot.release(); + if (referent != null) WeakRefRegistry.onStrongOwnerSlotReleased(referent); + } + /** A postfix ++/-- result transfers, rather than duplicates, its reference owner on assignment. */ private boolean postfixReferenceOwnershipTransfer; - /** - * True for the synthetic {@code $_[0]} scalar passed to DESTROY. - * Perl treats that invocant as read-only for operations such as - * {@code weaken($_[0])}, but normal reads and method dispatch still - * need the lightweight mutable RuntimeScalar representation. - */ - public boolean destroySelfArgument; + /** + * True for the synthetic {@code $_[0]} scalar passed to DESTROY. + * Perl treats that invocant as read-only for operations such as + * {@code weaken($_[0])}, but normal reads and method dispatch still + * need the lightweight mutable RuntimeScalar representation. + */ + public boolean destroySelfArgument; + + /** True after this scalar has acquired per-runtime {@code pos()} cache state. */ + volatile boolean posCacheEntryCreated; + + /** Identity for the current contents edge held through a scalar reference. */ + public PerlOwnerSlot scalarReferenceContentsOwner; + private Set scalarReferenceContentsOwners; + + public boolean hasScalarReferenceContentsOwner() { + return scalarReferenceContentsOwner != null + && scalarReferenceContentsOwner.isActive(); + } + + synchronized void registerScalarReferenceContentsOwner(PerlOwnerSlot owner) { + if (scalarReferenceContentsOwners == null) { + scalarReferenceContentsOwners = Collections.newSetFromMap( + new IdentityHashMap<>()); + } + scalarReferenceContentsOwners.add(owner); + } + + synchronized void unregisterScalarReferenceContentsOwner(PerlOwnerSlot owner) { + if (scalarReferenceContentsOwners != null) { + scalarReferenceContentsOwners.remove(owner); + if (scalarReferenceContentsOwners.isEmpty()) scalarReferenceContentsOwners = null; + } + } + + synchronized boolean hasScalarReferenceContentsOwner( + PerlOwnerSlot except, RuntimeBase referent) { + if (scalarReferenceContentsOwners == null) return false; + for (PerlOwnerSlot owner : scalarReferenceContentsOwners) { + if (owner != except && owner.isActive() && owner.referent() == referent) return true; + } + return false; + } - /** True after this scalar has acquired per-runtime {@code pos()} cache state. */ - volatile boolean posCacheEntryCreated; + private synchronized List scalarReferenceContentsOwnersSnapshot() { + return scalarReferenceContentsOwners == null || scalarReferenceContentsOwners.isEmpty() + ? List.of() : List.copyOf(scalarReferenceContentsOwners); + } - /** - * True when this scalar owns a counted reference through a scalar - * reference, e.g. the outer variable in {@code $x = \ bless {}, "X"}. - * The counted referent is inside the RuntimeScalar pointed to by this - * scalar, so regular {@code refCountOwned} cannot describe it. - */ - public boolean ownsScalarReferenceContents; + synchronized void clearScalarReferenceContentsOwner(PerlOwnerSlot owner) { + if (scalarReferenceContentsOwner == owner) scalarReferenceContentsOwner = null; + } /** * True once a scalar reference has been created to this scalar, e.g. @@ -722,8 +2406,8 @@ void retainClosureCaptureReferentsForUnweaken() { /** * True when {@link #createReference()} promoted an otherwise-unbound * scalar temporary into selective reference counting. Such a referent has - * no hidden lexical, closure, global, or aggregate owner, so weakening its - * sole reference can clear it without a reachability walk. + * no hidden lexical, closure, global, or aggregate owner, so releasing its + * sole owner can clear it directly. */ boolean ephemeralScalarReferenceReferent; @@ -747,7 +2431,7 @@ public static RuntimeScalar materializeLexicalCell(RuntimeScalar scalar) { // check before the proxy/null handling below. if (scalar != null && scalar.getClass() == RuntimeScalar.class - && scalar.refCount != Integer.MIN_VALUE) { + && !scalar.isPerlDestroyed()) { return scalar; } // A foreach literal alias deliberately occupies a lexical slot. It @@ -769,7 +2453,7 @@ public static RuntimeScalar materializeLexicalCell(RuntimeScalar scalar) { materialized.materializedBeforeLexicalDeclaration = true; return materialized; } - if (scalar.refCount == Integer.MIN_VALUE) { + if (scalar.isPerlDestroyed()) { // JVM local-slot reuse can assign a new declaration's initializer // into a destroyed prior cell before refgen materializes it. Keep // that new payload, but give the declaration a fresh scalar @@ -802,7 +2486,7 @@ public static RuntimeScalar initializeLexicalCell(RuntimeScalar scalar) { // earlier frame (notably a literal signature argument). boolean retainForwardReference = scalar != null && scalar.retainMaterializedForwardReference - && scalar.refCount != Integer.MIN_VALUE + && !scalar.isPerlDestroyed() && !(scalar instanceof RuntimeScalarReadOnly) && scalar.type != RuntimeScalarType.READONLY_SCALAR; if (retainForwardReference) { @@ -934,15 +2618,16 @@ public RuntimeScalar(RuntimeScalar scalar) { Object argumentFrame = RuntimeCode.currentArgumentAliasFrame(scalar); this.copiedFromArgumentFrame = argumentFrame != null ? argumentFrame : scalar.copiedFromArgumentFrame; - // A scalar detached from both a lexical registration and a durable - // container is an expression temporary. Move its socket ownership + // A scalar detached from lexical and package registration and from a + // durable container is an expression temporary. Move its socket ownership // token into the copy (notably RuntimeList return materialization) // instead of leaving an unreachable phantom holder behind. - if (scalar.ioOwner && scalar.containerOwner == null + if (scalar.hasIoOwner() && scalar.containerOwner == null + && !scalar.isPackageGlobalRoot && !MyVarCleanupStack.isRegistered(scalar)) { - scalar.ioOwner = false; - this.ioOwner = true; + transferIoOwner(scalar, this); } + refreshDetachedGlobValueOwner(); } public RuntimeScalar(RuntimeCode value) { @@ -977,11 +2662,16 @@ public RuntimeScalar(RuntimeGlob value) { // don't participate in local/global scope and we need to preserve // their local slots (e.g., from stash delete). if (value.globName != null && !value.isSlotSnapshot()) { - value = value.createDetachedCopy(); + RuntimeGlob source = value; + value = source.createDetachedCopy(); + if (source.namespaceMove != null) { + source.releaseDetachedComponentsIfUnowned(); + } } } this.value = value; this.scalarStoredGlob = value != null; + refreshDetachedGlobValueOwner(); } public RuntimeScalar(byte[] bytes) { @@ -1105,6 +2795,9 @@ public RuntimeScalar tiedFetch() { * variable still each call FETCH.

    */ public static RuntimeScalar fetchTiedOnce(RuntimeScalar scalar) { + if (scalar instanceof TiedVariableBase tiedVariable) { + return tiedVariable.tiedFetch(); + } return scalar.type == TIED_SCALAR ? scalar.tiedFetch() : scalar; } @@ -1783,8 +3476,13 @@ public RuntimeArray setArrayOfAlias(RuntimeArray arr) { arr.elements.add(this); if (type == RuntimeScalarType.CODE && value instanceof RuntimeCode code && !isPackageGlobalRoot && !localBindingExists - && (code.refCount == 0 || scopeExited) + && (!RuntimeCode.hasPersistentArgumentCell(this) || scopeExited) && (code.capturedScalars != null || code.capturedAggregates != null)) { + // A temporary closure in @_ is a strong argument slot. The code's + // count can belong to a different scalar cell, so decide whether + // this cell needs an owner from its storage identity. Argument + // cleanup can then retire this edge without a graph walk. + incrementRefCountForContainerStore(this, PerlOwnerSlot.Kind.ARGUMENT_VALUE); arr.markOwnedAliasElement(this); } return arr; @@ -2043,15 +3741,10 @@ public void addToArray(RuntimeArray runtimeArray) { */ public RuntimeScalar addToScalar(RuntimeScalar scalar) { RuntimeScalar result = scalar.set(this); - if (postfixReferenceOwnershipTransfer) { - postfixReferenceOwnershipTransfer = false; - if ((type & REFERENCE_BIT) != 0 && value instanceof RuntimeBase base - && base.refCount > 0) { - // set() acquired the destination owner; cancel the extra - // increment because this temporary's owner was transferred. - base.refCount--; - } - } + // set() published and acquired the destination owner. Release this + // exact postfix temporary through the shared slot/count transition. + releasePostfixReferenceTransferOwner( + "RuntimeScalar.addToScalar postfix temporary transfer"); return result; } @@ -2132,53 +3825,232 @@ public void vivifyLogicalAssignmentLvalue() { * constructor, and their refCount was already incremented at creation time. */ public static void incrementRefCountForContainerStore(RuntimeScalar scalar) { - if (scalar == null || scalar.refCountOwned - || (scalar.type & REFERENCE_BIT) == 0 + incrementRefCountForContainerStore(scalar, null); + } + + /** Acquire a counted edge for a destination slot before publishing that slot. */ + public static void incrementRefCountForContainerStore( + RuntimeScalar scalar, PerlOwnerSlot.Kind intendedOwnerKind) { + if (scalar == null) return; + if (scalar.nonOwningBObjectReference) return; + if (intendedOwnerKind != null && !PerlOwnerSlot.isCountedKind(intendedOwnerKind)) { + throw new IllegalArgumentException("container stores require a counted owner kind"); + } + if (scalar.type == REFERENCE + && scalar.value instanceof RuntimeScalar + && !scalar.hasScalarReferenceContentsOwner()) { + scalar.retainScalarReferenceContents(scalar); + } + if (PerlRuntime.currentOrNull() != null && WeakRefRegistry.isweak(scalar)) return; + if (scalar.refCountOwned) { + PerlOwnerSlot slot = scalar.countedOwnerSlot; + if (slot == null || !slot.isActive() || slot.referent() != scalar.value + || slot.countedScalarOwner() != scalar) { + throw new IllegalStateException( + "counted scalar lost its active owner slot during container acquisition"); + } + slot.reclassifyCountedIdentity(intendedOwnerKind == null + ? scalar.countedOwnerKind() : intendedOwnerKind); + scalar.associateCountedAggregateOwnerIfAbsent(scalar.containerOwner); + if (scalar.untrackedReferenceOwnerSlot != null) { + scalar.releaseUntrackedReferenceOwner( + scalar.untrackedReferenceOwnerSlot.referent()); + } + return; + } + if ((scalar.type & REFERENCE_BIT) == 0 || !(scalar.value instanceof RuntimeBase base)) { return; } - // Destroyed / weaken sentinel states must not be reactivated here. - if (base.refCount == Integer.MIN_VALUE - || base.refCount == WeakRefRegistry.WEAKLY_TRACKED) { + // Destroyed and weak-tracked referents must not be reactivated here. + if (base.isPerlDestroyed()) { + return; + } + if (base.isWeaklyRefCountTracked()) { + scalar.refreshUntrackedReferenceOwner(); + return; + } + if (!base.isRefCountTracked() + && intendedOwnerKind == PerlOwnerSlot.Kind.ARGUMENT_CONTAINER) { + // Selective counting has no ledger for the referent's pre-existing + // owners. Keep this real argument edge as an untracked owner rather + // than promoting a partial count that could reach zero too early. + scalar.refreshUntrackedReferenceOwner(); return; } - // Anonymous nested containers start at refCount=-1 (untracked). + // Anonymous nested containers begin with explicit untracked state. // bless {}'s retroactive pass and normal container stores must still count // the hash slot as a strong ref, otherwise delete $h{k} / hash clear never // drops the child (PPI::Node->{children}; cpan PPI t/04_element.t). // Restrict promotion to real containers: doing this for arbitrary -1 // referents (e.g. refs to readonly scalars) breaks Moo weak_ref accessors // (cpan Moo t/accessor-weaken.t). - if (base.refCount < 0) { + if (!base.isRefCountTracked()) { if (!(base instanceof RuntimeHash) && !(base instanceof RuntimeArray)) { + scalar.refreshUntrackedReferenceOwner(); return; } - base.refCount = 0; + base.startRefCountTracking(); + } + acquireCountedOwnerForCurrentValue(scalar, base, intendedOwnerKind, + "RuntimeScalar.incrementRefCountForContainerStore"); + if (scalar.untrackedReferenceOwnerSlot != null) { + scalar.releaseUntrackedReferenceOwner( + scalar.untrackedReferenceOwnerSlot.referent()); + } + } + + /** + * Change container slots in Perl assignment order: acquire replacement + * edges, publish the new slots, then release displaced edges. A scalar + * cell that remains in the destination keeps its existing owner identity. + * The publisher must perform only storage and owner bookkeeping; Perl + * callbacks belong in the release operation after publication. + */ + static void transitionContainerSlots( + Collection displaced, + Collection replacements, + PerlOwnerSlot.Kind ownerKind, + RuntimeBase aggregateOwner, + Runnable publish, + Consumer> releaseDisplaced) { + Set retained = Collections.newSetFromMap(new IdentityHashMap<>()); + if (replacements != null) { + for (RuntimeScalar replacement : replacements) { + incrementRefCountForContainerStore(replacement, ownerKind); + if (replacement != null) retained.add(replacement); + } + } + publish.run(); + if (ownerKind == PerlOwnerSlot.Kind.ARRAY_ELEMENT + || ownerKind == PerlOwnerSlot.Kind.HASH_ELEMENT) { + for (RuntimeScalar replacement : retained) { + replacement.associateCountedAggregateOwner(aggregateOwner); + } + } + if (displaced == null || displaced.isEmpty() || releaseDisplaced == null) return; + + Set alreadyReleased = Collections.newSetFromMap(new IdentityHashMap<>()); + List retired = new ArrayList<>(); + for (RuntimeScalar scalar : displaced) { + if (scalar != null && !retained.contains(scalar) && alreadyReleased.add(scalar)) { + retired.add(scalar); + } + } + if (!retired.isEmpty()) releaseDisplaced.accept(retired); + } + + private record IoOwnerRelease(RuntimeGlob glob, int remainingHolders) {} + + private static PerlOwnerSlot acquireIoOwnerSlot(RuntimeGlob glob) { + synchronized (glob) { + if (glob.ioHolderCount() == Integer.MAX_VALUE) { + throw new IllegalStateException("anonymous IO holder count overflow"); + } + PerlOwnerSlot ownerSlot = new PerlOwnerSlot( + PerlOwnerSlot.Kind.IO_RESOURCE_HOLDER); + ownerSlot.acquireNativeOwner(glob); + return ownerSlot; + } + } + + private static void attachIoOwnerSlot(RuntimeScalar scalar, PerlOwnerSlot ownerSlot) { + if (scalar.ioOwnerSlot != null) { + throw new IllegalStateException("scalar already owns an anonymous IO holder"); + } + if (ownerSlot == null || !ownerSlot.isActive() + || ownerSlot.kind() != PerlOwnerSlot.Kind.IO_RESOURCE_HOLDER + || !ownerSlot.isNativeOwner() + || !(ownerSlot.referent() instanceof RuntimeGlob)) { + throw new IllegalStateException("cannot attach an inactive anonymous IO holder"); + } + scalar.ioOwnerSlot = ownerSlot; + ownerSlot.associateResourceScalarOwner(scalar); + } + + private static IoOwnerRelease releaseIoOwnerSlot(RuntimeScalar scalar) { + if (scalar == null) return null; + if (scalar.ioOwnerSlot == null) return null; + PerlOwnerSlot ownerSlot = scalar.ioOwnerSlot; + scalar.ioOwnerSlot = null; + ownerSlot.associateResourceScalarOwner(null); + return releaseIoOwnerSlot(ownerSlot); + } + + static PerlOwnerSlot detachIoOwnerForDeferredRelease(RuntimeScalar scalar, RuntimeBase referent) { + if (scalar == null || scalar.ioOwnerSlot == null) return null; + PerlOwnerSlot ownerSlot = scalar.ioOwnerSlot; + if (!ownerSlot.isActive() || ownerSlot.kind() != PerlOwnerSlot.Kind.IO_RESOURCE_HOLDER + || ownerSlot.referent() != referent) { + return null; + } + scalar.ioOwnerSlot = null; + ownerSlot.associateResourceScalarOwner(null); + return ownerSlot; + } + + static void releaseDeferredIoOwner(PerlOwnerSlot ownerSlot) { + IoOwnerRelease ownerRelease = releaseIoOwnerSlot(ownerSlot); + finishIoOwnerRelease(ownerRelease); + } + + private static IoOwnerRelease releaseIoOwnerSlot(PerlOwnerSlot ownerSlot) { + if (ownerSlot == null || !ownerSlot.isActive() + || ownerSlot.kind() != PerlOwnerSlot.Kind.IO_RESOURCE_HOLDER + || !(ownerSlot.referent() instanceof RuntimeGlob glob)) { + throw new IllegalStateException("scalar IO owner flag has no active owner identity"); + } + synchronized (glob) { + if (!ownerSlot.isNativeOwner() || glob.ioHolderCount() <= 0) { + throw new IllegalStateException("anonymous IO holder release is unbalanced"); + } + ownerSlot.release(); + return new IoOwnerRelease(glob, glob.ioHolderCount()); + } + } + + static void transferIoOwner(RuntimeScalar source, RuntimeScalar destination) { + if (source == null || destination == null || source == destination) return; + if (source.ioOwnerSlot == null) return; + PerlOwnerSlot ownerSlot = source.ioOwnerSlot; + if (destination.ioOwnerSlot != null + || ownerSlot == null || !ownerSlot.isActive() + || ownerSlot.kind() != PerlOwnerSlot.Kind.IO_RESOURCE_HOLDER + || !(ownerSlot.referent() instanceof RuntimeGlob glob) + || source.type != GLOBREFERENCE || source.value != glob + || destination.type != GLOBREFERENCE || destination.value != glob) { + throw new IllegalStateException("invalid anonymous IO owner transfer"); + } + synchronized (glob) { + if (!ownerSlot.isNativeOwner()) { + throw new IllegalStateException("transferred anonymous IO owner is not native"); + } + source.ioOwnerSlot = null; + destination.ioOwnerSlot = ownerSlot; + ownerSlot.associateResourceScalarOwner(destination); } - base.traceRefCount(+1, "RuntimeScalar.incrementRefCountForContainerStore"); - base.refCount++; - base.hadCountedReference = true; - base.recordOwner(scalar, "incrementRefCountForContainerStore"); - base.recordActiveOwner(scalar); - scalar.refCountOwned = true; - // Phase B1 (refcount_alignment_52leaks_plan.md): track the - // container element so ReachabilityWalker can see it via - // ScalarRefRegistry. - ScalarRefRegistry.registerRef(scalar); } public static void retainUnstashedIoForDurableSlot(RuntimeScalar scalar) { - if (scalar == null) return; + if (scalar == null || (PerlRuntime.currentOrNull() != null + && WeakRefRegistry.isweak(scalar))) return; scalar.copiedFromArgumentFrame = null; - if (scalar.ioOwner - || scalar.type != GLOBREFERENCE + if (scalar.ioOwnerSlot != null) { + if (scalar.ioOwnerSlot == null + || !scalar.ioOwnerSlot.isActive() + || !(scalar.ioOwnerSlot.referent() instanceof RuntimeGlob ownedGlob) + || scalar.type != GLOBREFERENCE || scalar.value != ownedGlob) { + throw new IllegalStateException("durable scalar has a stale anonymous IO owner"); + } + return; + } + if (scalar.type != GLOBREFERENCE || !(scalar.value instanceof RuntimeGlob glob) || !isUnstashedIoGlob(glob) || !hasLiveIo(glob)) { return; } - glob.ioHolderCount++; - scalar.ioOwner = true; + attachIoOwnerSlot(scalar, acquireIoOwnerSlot(glob)); } /** Retain a non-socket anonymous IO handle copied into a hash element slot. */ @@ -2202,14 +4074,13 @@ static RuntimeScalar copyReturnedIoAlias(RuntimeScalar source) { || !isUnstashedIoGlob(glob) || !hasLiveIo(glob)) { return null; } - boolean sourceOwned = source.ioOwner; + boolean sourceOwned = source.hasIoOwner(); RuntimeScalar copy = new RuntimeScalar(source); - if (sourceOwned && copy.ioOwner) { - copy.ioOwner = false; - source.ioOwner = true; + if (sourceOwned && copy.hasIoOwner()) { + transferIoOwner(copy, source); } copy.copiedFromArgumentFrame = null; - copy.containerOwner = null; + copy.reconcileContainerOwners(); return copy; } @@ -2217,56 +4088,30 @@ private static boolean scalarReferenceContentsNeedRetain(RuntimeScalar value) { return value != null && value.type == REFERENCE && value.value instanceof RuntimeScalar scalarReferent + && !WeakRefRegistry.isweak(value) && !WeakRefRegistry.isweak(scalarReferent) && !scalarReferent.refCountOwned && (scalarReferent.type & REFERENCE_BIT) != 0 && scalarReferent.value instanceof RuntimeBase inner - && inner.refCount >= 0; + && inner.isRefCountTracked(); } private void retainScalarReferenceContents(RuntimeScalar value) { - this.ownsScalarReferenceContents = false; + if (this.scalarReferenceContentsOwner != null) { + this.releaseOwnedScalarReferenceContents(); + } if (!scalarReferenceContentsNeedRetain(value)) return; RuntimeScalar scalarReferent = (RuntimeScalar) value.value; RuntimeBase inner = (RuntimeBase) scalarReferent.value; - inner.traceRefCount(+1, "RuntimeScalar.retainScalarReferenceContents"); - inner.refCount++; - inner.hadCountedReference = true; - inner.acquireTransientTraceOwner("scalar-reference contents", - "RuntimeScalar.scalarReferenceContents"); - this.ownsScalarReferenceContents = true; - } - - private static RuntimeScalar scalarReferenceContentsReferent(RuntimeScalar owner) { - if (owner != null - && owner.ownsScalarReferenceContents - && owner.type == REFERENCE - && owner.value instanceof RuntimeScalar scalarReferent) { - return scalarReferent; - } - return null; - } - - public static void releaseScalarReferenceContents(RuntimeScalar scalarReferent) { - if (scalarReferent == null - || (scalarReferent.type & REFERENCE_BIT) == 0 - || !(scalarReferent.value instanceof RuntimeBase inner) - || inner.refCount <= 0) { - return; - } - inner.traceRefCount(-1, "RuntimeScalar.releaseScalarReferenceContents"); - inner.releaseTransientTraceOwner("scalar-reference contents", - "RuntimeScalar.scalarReferenceContents"); - if (--inner.refCount == 0) { - inner.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(inner); - } + PerlOwnerSlot owner = new PerlOwnerSlot(PerlOwnerSlot.Kind.SCALAR_REFERENCE_CONTENTS); + owner.acquireScalarReferenceContents(inner, scalarReferent, this); + this.scalarReferenceContentsOwner = owner; } public void releaseOwnedScalarReferenceContents() { - RuntimeScalar scalarReferent = scalarReferenceContentsReferent(this); - this.ownsScalarReferenceContents = false; - releaseScalarReferenceContents(scalarReferent); + PerlOwnerSlot owner = this.scalarReferenceContentsOwner; + this.scalarReferenceContentsOwner = null; + if (owner != null) owner.releaseScalarReferenceContents(); } /** @@ -2277,15 +4122,9 @@ public void releaseOwnedScalarReferenceContents() { * retain it first and keeps the retain/release accounting balanced. */ public void deferOwnedScalarReferenceContents() { - RuntimeScalar scalarReferent = scalarReferenceContentsReferent(this); - this.ownsScalarReferenceContents = false; - if (scalarReferent == null - || (scalarReferent.type & REFERENCE_BIT) == 0 - || !(scalarReferent.value instanceof RuntimeBase inner) - || inner.refCount <= 0) { - return; - } - MortalList.deferDecrement(inner); + PerlOwnerSlot owner = this.scalarReferenceContentsOwner; + this.scalarReferenceContentsOwner = null; + if (owner != null) owner.deferScalarReferenceContentsRelease(); } // Keep this entry point small so HotSpot can inline it into generated @@ -2311,9 +4150,12 @@ private RuntimeScalar setPlainInteger(RuntimeScalar value) { if (isPackageGlobalRoot || containerOwner != null) { clearLastReadlineHandleIfGlobValue(); } + prepareDetachedGlobValueOwner(value.type, value.value); growingString = null; type = value.type; this.value = copyScalarPayload(value.type, value.value); + refreshDetachedGlobValueOwner(); + refreshArgumentAliasOwnerSlots(); utf8UncheckedOctets = value.utf8UncheckedOctets; utf8MalformedWarning = value.utf8MalformedWarning; tainted = value.tainted; @@ -2348,6 +4190,7 @@ public RuntimeScalar setArithmeticIntegerResult(long result, boolean resultTaint if (isPackageGlobalRoot || containerOwner != null) { clearLastReadlineHandleIfGlobValue(); } + prepareDetachedGlobValueOwner(RuntimeScalarType.INTEGER, null); growingString = null; transferableGrowingString = false; if (value instanceof MutableIntegerValue mutableInteger) { @@ -2358,6 +4201,8 @@ public RuntimeScalar setArithmeticIntegerResult(long result, boolean resultTaint value = new MutableIntegerValue(result); } type = RuntimeScalarType.INTEGER; + refreshDetachedGlobValueOwner(); + refreshArgumentAliasOwnerSlots(); utf8UncheckedOctets = false; utf8MalformedWarning = null; tainted = resultTainted; @@ -2384,6 +4229,7 @@ private RuntimeScalar setSlow(RuntimeScalar value) { hash.preallocateCapacity(value.getInt()); this.type = RuntimeScalarType.INTEGER; this.value = hash.keys(RuntimeContextType.SCALAR).scalar().getInt(); + refreshArgumentAliasOwnerSlots(); return this; } throw new PerlCompilerException("Can't modify keys on array in list assignment"); @@ -2430,8 +4276,10 @@ private RuntimeScalar setSlow(RuntimeScalar value) { // string hash, and refresh in place so existing PosLvalueScalar handles stay valid. if (value != null && this.type < TIED_SCALAR & value.type < TIED_SCALAR) { if (this != value) { + prepareDetachedGlobValueOwner(value.type, value.value); this.type = value.type; this.value = copyScalarPayload(value.type, value.value); + refreshDetachedGlobValueOwner(); this.utf8UncheckedOctets = value.utf8UncheckedOctets; this.utf8MalformedWarning = value.utf8MalformedWarning; this.tainted = value.tainted; @@ -2446,8 +4294,10 @@ private RuntimeScalar setSlow(RuntimeScalar value) { this.globalCodeRefFqn = value.globalCodeRefFqn; RuntimePosLvalue.invalidatePos(this); } else { + prepareDetachedGlobValueOwner(value.type, value.value); this.type = value.type; this.value = copyScalarPayload(value.type, value.value); + refreshDetachedGlobValueOwner(); this.utf8UncheckedOctets = value.utf8UncheckedOctets; this.utf8MalformedWarning = value.utf8MalformedWarning; this.tainted = value.tainted; @@ -2461,6 +4311,7 @@ private RuntimeScalar setSlow(RuntimeScalar value) { this.formatPictureTainted = value.formatPictureTainted; this.globalCodeRefFqn = value.globalCodeRefFqn; } + refreshArgumentAliasOwnerSlots(); refreshSubstrLvalues(); notifyModifiedWatchers(); return this; @@ -2550,15 +4401,7 @@ public RuntimeScalar setPreservingByteString(RuntimeScalar value) { // handles refCount tracking, IO lifecycle, and weak ref bookkeeping. private RuntimeScalar setLarge(RuntimeScalar value) { if (value == null) { - closeIOOnDrop(); - this.type = RuntimeScalarType.UNDEF; - this.value = null; - this.tainted = false; - this.numericLiteralText = null; - this.numericContextSeen = false; - this.firstClassRegexScalar = false; - this.formatPictureTainted = false; - return this; + return undefine(); } // Unwrap source special types via switch dispatcher switch (value.type) { @@ -2597,14 +4440,26 @@ private RuntimeScalar setLarge(RuntimeScalar value) { // All reference types have REFERENCE_BIT (0x8000) set, so a single // bitwise OR + AND check covers both old and new values. if (((this.type | value.type) & REFERENCE_BIT) != 0) { - return setLargeRefCounted(value); + // Keep caller temporaries below this operation's boundary while + // the new slot is installed and its old edge is released. The + // transition flushes only work added above this mark; flushing + // again after popping it would also drain older caller releases. + MortalList.pushMark(); + try { + return transitionReferenceSlot(value, false); + } finally { + MortalList.popMark(); + } } // Simple non-reference assignment (no refCount tracking needed). // No MortalList.flush() here — neither old nor new value is a reference, // so no refCount was incremented/decremented, and no mortal entries were added. + prepareDetachedGlobValueOwner(value.type, value.value); this.type = value.type; this.value = copyScalarPayload(value.type, value.value); + refreshDetachedGlobValueOwner(); + refreshArgumentAliasOwnerSlots(); this.utf8UncheckedOctets = value.utf8UncheckedOctets; this.utf8MalformedWarning = value.utf8MalformedWarning; this.tainted = value.tainted; @@ -2620,61 +4475,76 @@ private RuntimeScalar setLarge(RuntimeScalar value) { } /** - * RefCount-aware slow path for reference assignments. - * Called from setLarge() when either the old or new value involves a reference type. - * Separated to keep setLarge() small enough for JIT inlining of set(). + * Apply one scalar-slot transition for reference assignment and explicit + * undef. The transition retains a replacement before publishing it and + * releases the previous referent against the already-updated scalar state. + * + *

    Explicit undef shares this operation but keeps its Perl-specific weak + * observer and mortal-flush behavior. CODE slots with symbol-table semantics + * are handled by {@link #undefine()} before reaching this method.

    */ - private RuntimeScalar setLargeRefCounted(RuntimeScalar value) { + private RuntimeScalar transitionReferenceSlot(RuntimeScalar value, boolean explicitUndef) { + prepareCodeSlotValue(value); String packageCodeRefName = isPackageGlobalRoot ? globalCodeRefFqn : null; if (isPackageGlobalRoot) { - MortalList.invalidateExternalRootSnapshot(); } if (this.value != value.value) { - MortalList.invalidateFullRootSnapshotIfReachable(this); if (containerOwner != null) { - MortalList.invalidateFullRootSnapshotIfReachable(containerOwner); } } noteClearedAggregateElement(value); - // Fast path for untracked references (refCount == -1). + // Fast path for references outside the selective count bridge. // Most reference assignments involve untracked objects (named variables, // anonymous arrays/hashes that were never blessed). Skip all refCount // tracking, WeakRefRegistry checks, and MortalList flush. boolean scalarRefContentTrackingNeeded = - this.ownsScalarReferenceContents || scalarReferenceContentsNeedRetain(value); + this.hasScalarReferenceContentsOwner() + || scalarReferenceContentsNeedRetain(value); boolean droppingAggregateWithWeakRefs = value.type == UNDEF && WeakRefRegistry.weakRefsExist() && this.value instanceof RuntimeBase oldReferent && (oldReferent instanceof RuntimeHash || oldReferent instanceof RuntimeArray); - if (!scalarRefContentTrackingNeeded - && !this.refCountOwned && this.captureCount == 0 && this.captureRefCountOwned() == 0 + if (!explicitUndef + && !scalarRefContentTrackingNeeded + && !this.refCountOwned && !this.hasClosureCaptureOwner() + && this.captureRefCountOwned() == 0 && !WeakRefRegistry.isweak(this) && !droppingAggregateWithWeakRefs && this.type != GLOBREFERENCE && value.type != GLOBREFERENCE) { // Both old and new are non-GLOB references. Check if referents are untracked. boolean oldUntracked = (this.type & REFERENCE_BIT) == 0 || this.value == null - || ((RuntimeBase) this.value).refCount == -1; + || ((RuntimeBase) this.value).isRefCountUntracked(); boolean newUntracked = (value.type & REFERENCE_BIT) == 0 || value.value == null - || ((RuntimeBase) value.value).refCount == -1; + || ((RuntimeBase) value.value).isRefCountUntracked(); if (oldUntracked && newUntracked) { // Hash/array element stores must count refs to RuntimeHash/RuntimeArray - // at refCount==-1 (see incrementRefCountForContainerStore). Otherwise a + // untracked (see incrementRefCountForContainerStore). Otherwise a // lone `$slot = $obj` assignment can bypass tracking while push() does not. if ((value.type & REFERENCE_BIT) != 0 && value.value instanceof RuntimeBase nb - && nb.refCount < 0 + && !nb.isRefCountTracked() && (nb instanceof RuntimeHash || nb instanceof RuntimeArray)) { // fall through to full refCounted assignment } else { + prepareDetachedGlobValueOwner(value.type, value.value); this.type = value.type; this.value = copyScalarPayload(value.type, value.value); + refreshDetachedGlobValueOwner(); + refreshArgumentAliasOwnerSlots(); this.utf8UncheckedOctets = value.utf8UncheckedOctets; this.utf8MalformedWarning = value.utf8MalformedWarning; this.tainted = value.tainted; this.numericLiteralText = value.numericLiteralText; this.numericContextSeen = value.numericContextSeen; + updateUntrackedReferenceOwner(this.value instanceof RuntimeBase referent + && (this.type & RuntimeScalarType.REFERENCE_BIT) != 0 + ? referent : null); + if (value != this && !stagedValueOwner + && this.value instanceof RuntimeBase referent) { + MortalList.consumeMortalReturnValue(value, referent); + } if (packageCodeRefName != null) { GlobalVariable.noteGlobalCodeRefSlotMutation(this); } @@ -2722,19 +4592,22 @@ private RuntimeScalar setLargeRefCounted(RuntimeScalar value) { // cleanup responsibility to the destination lexical instead of creating // an ownerless extra holder. The detached source is only an expression // temporary and does not receive normal lexical scope cleanup. - boolean durableIoDestination = ioOwner + boolean durableIoDestination = hasIoOwner() || containerOwner != null || isPackageGlobalRoot || MyVarCleanupStack.isRegistered(this); boolean assignedFromArgumentAlias = RuntimeCode.isCurrentArgumentAlias(value) - || (!value.ioOwner + || (!value.hasIoOwner() && RuntimeCode.isArgumentFrameActive(value.copiedFromArgumentFrame)); boolean assignedFromAcceptedSocketArgument = assignedFromArgumentAlias && isAcceptedSocket(value); + boolean preserveCurrentIoOwner = this == value && hasIoOwner() + && ioOwnerSlot != null && ioOwnerSlot.isActive() + && ioOwnerSlot.referent() == value.value; boolean transferDetachedIoOwner = durableIoDestination && this != value && !assignedFromArgumentAlias - && value.ioOwner + && value.hasIoOwner() && value.type == GLOBREFERENCE && value.value instanceof RuntimeGlob transferGlob && isUnstashedIoGlob(transferGlob) @@ -2744,28 +4617,22 @@ && isUnstashedIoGlob(transferGlob) && array.transientListAssignmentRhs) || value.containerOwner == RuntimeCode.getCurrentArgs()); - // Track anonymous-glob aliases so the owning slot only releases the - // descriptor when no copied scalar still points at that glob. + // Acquire a replacement owner before releasing this scalar's previous + // holder. A detached value can transfer its existing identity instead + // of creating a second owner. + PerlOwnerSlot replacementIoOwnerSlot = null; if (value.type == GLOBREFERENCE && value.value instanceof RuntimeGlob newGlob && isUnstashedIoGlob(newGlob) && hasLiveIo(newGlob) && durableIoDestination && (!assignedFromArgumentAlias || assignedFromAcceptedSocketArgument) - && !transferDetachedIoOwner) { - newGlob.ioHolderCount++; - } - if (this.ioOwner - && this.type == GLOBREFERENCE && this.value instanceof RuntimeGlob oldGlob - && isUnstashedIoGlob(oldGlob)) { - this.ioOwner = false; - if (oldGlob.ioHolderCount > 0) oldGlob.ioHolderCount--; - if (oldGlob.ioHolderCount <= 0) { - RuntimeScalar oldIoSlot = oldGlob.getIO(); - if (oldIoSlot != null && oldIoSlot.value instanceof RuntimeIO oldIo - && isSocketIOHandle(oldIo.ioHandle)) { - oldIo.close(); - } - } + && !transferDetachedIoOwner + && !preserveCurrentIoOwner) { + replacementIoOwnerSlot = acquireIoOwnerSlot(newGlob); + } + if (hasIoOwner() && !preserveCurrentIoOwner) { + IoOwnerRelease oldRelease = releaseIoOwnerSlot(this); + finishIoOwnerRelease(oldRelease); } // NOTE: Do NOT release captures here on CODE overwrite. @@ -2775,7 +4642,7 @@ && isSocketIOHandle(oldIo.ioHandle)) { // CODE ref — e.g., the stash entry *Foo::bar holds the constructor // while a local variable also holds it. Overwriting the local should // not release the captures that the stash's copy still needs. - // For untracked CODE refs (refCount == -1), the JVM GC handles cleanup. + // For untracked CODE refs, the JVM GC handles cleanup. // Track refCount for blessed objects with DESTROY. // Save old referent BEFORE the assignment (for correct DESTROY ordering — @@ -2784,128 +4651,266 @@ && isSocketIOHandle(oldIo.ioHandle)) { if ((this.type & RuntimeScalarType.REFERENCE_BIT) != 0 && this.value != null) { oldBase = (RuntimeBase) this.value; } - // A reference to this scalar keeps its current contents alive through - // scalarReferenceContents. Assigning through $$ref transfers that - // ownership to the new contents, so the old referent must be released - // even though this scalar did not itself record a direct store owner. - boolean oldOwnedByScalarReference = oldBase != null - && referencedByScalarReference - && refCount > 0; - boolean oldOwnedScalarReferenceContents = this.ownsScalarReferenceContents; - RuntimeScalar oldScalarReferenceContents = scalarReferenceContentsReferent(this); - boolean shouldReleaseUnrootedRescuedGraph = false; - boolean requestedDiscardedAggregateSweep = false; + boolean oldRefCountOwned = this.refCountOwned; + // Scope unwind can clear a cell's payload after scheduling its array + // edge release while leaving the stable storage token on the cell. + // Retire that exact displaced edge from its token instead of treating + // the missing payload as a lost owner and aborting the replacement. + if (oldBase == null && oldRefCountOwned && countedOwnerSlot != null + && countedOwnerSlot.isActive() + && countedOwnerSlot.countedScalarOwner() == this + && (countedOwnerSlot.kind() == PerlOwnerSlot.Kind.ARRAY_ELEMENT + || countedOwnerSlot.kind() == PerlOwnerSlot.Kind.HASH_ELEMENT)) { + oldBase = countedOwnerSlot.referent(); + } + boolean oldIdentifiedOwner = oldBase != null && oldRefCountOwned + && countedOwnerSlot != null && countedOwnerSlot.isActive() + && countedOwnerSlot.referent() == oldBase; + boolean staleAggregateOwner = oldIdentifiedOwner + && (countedOwnerSlot.kind() == PerlOwnerSlot.Kind.ARRAY_ELEMENT + || countedOwnerSlot.kind() == PerlOwnerSlot.Kind.HASH_ELEMENT) + && !isCurrentAggregateElementOwner(oldBase, countedOwnerSlot); + // A live scalar-reference contents slot is the ownership proof for an + // uncounted scalar cell's current referent. Assigning through $$ref + // retargets those exact slots below; the historical referencedByScalarReference + // flag alone does not identify a live owner and must not authorize a decrement. + List scalarContentsOwnerSnapshot = + this.scalarReferenceContentsOwnersSnapshot(); + List scalarContentsOwners = + new ArrayList<>(scalarContentsOwnerSnapshot); + PerlOwnerSlot oldScalarReferenceContentsOwner = this.scalarReferenceContentsOwner; + if (oldScalarReferenceContentsOwner != null) { + scalarContentsOwners.remove(oldScalarReferenceContentsOwner); + } + boolean oldOwnedScalarReferenceContents = this.hasScalarReferenceContentsOwner(); + boolean scalarContentsOwnedByEscapedReference = + !scalarContentsOwnerSnapshot.isEmpty() && !this.localBindingExists; // If this scalar was a weak ref, remove from weak tracking before overwriting. // Weak refs don't count toward refCount, so skip refCount decrement later. boolean thisWasWeak = (oldBase != null && WeakRefRegistry.removeWeakRef(this, oldBase)); - boolean undefAssignmentOfDestroyableRef = oldBase != null - && !thisWasWeak - && value.type == UNDEF - && oldBase.blessId != 0 - && WeakRefRegistry.weakRefsExist() - && blessedClassHasDestroy(oldBase); if (oldBase != null && this.captureRefCountOwned() > 0) { releaseAllClosureCaptureReferents(oldBase); } - if (oldBase != null && this.captureCount > 0) { - releaseClosureOwnerSlot(); - } - - // Increment new value's refCount for tracked stores, including a GLOB - // whose open handle has already been blessed into an object. Hashes and - // arrays at refCount==-1 are promoted to 0 here (aligned with - // incrementRefCountForContainerStore) so hash/array slots and - // `%hash=()`/`deferDestroyForContainerClear` balance. Other referents at -1 - // stay untracked (e.g. named \@x via local slot). + // Decide whether the replacement is a counted edge before changing the + // scalar. A new count and its slot identity are acquired together; the + // old edge carries a separate release token through cleanup. + boolean oldArgumentAliasReleaseQueued = false; + boolean retireOldCountedOwnerAfterPublish = false; + boolean oldOwnerTraceReleasedDuringReplacement = false; + PerlOwnerSlot displacedCountedOwnerSlot = countedOwnerSlot; + PerlOwnerSlot replacementCountedOwnerSlot = null; + PerlOwnerSlot.PendingRelease oldCountedOwnerRelease = null; boolean newOwned = false; + RuntimeBase newReferent = null; if (((value.type & RuntimeScalarType.REFERENCE_BIT) != 0 || value.type == RuntimeScalarType.GLOB) && value.value != null) { RuntimeBase nb = (RuntimeBase) value.value; - if (nb.refCount < 0 + if (!nb.isRefCountTracked() && (nb instanceof RuntimeHash || nb instanceof RuntimeArray)) { - nb.refCount = 0; + nb.startRefCountTracking(); } - if (nb.refCount >= 0) { + if (nb.isRefCountTracked() && !scalarContentsOwnedByEscapedReference) { if (nb.refCount == 0) nb.registerSharedFetchedView(); - nb.traceRefCount(+1, "RuntimeScalar.setLargeRefCounted (increment on store)"); - nb.recordOwner(this, "setLargeRefCounted store"); - nb.recordActiveOwner(this); - nb.refCount++; - nb.hadCountedReference = true; newOwned = true; + newReferent = nb; + } + } + + if (oldRefCountOwned && !thisWasWeak) { + if (oldBase == null || !oldIdentifiedOwner) { + throw new IllegalStateException( + "counted scalar lost its current owner slot during replacement" + + " (scalar=" + System.identityHashCode(this) + + ", referent=" + (oldBase == null ? "null" + : System.identityHashCode(oldBase)) + + ", ownerSlot=" + (countedOwnerSlot == null ? "null" + : countedOwnerSlot.identity()) + + ", ownerKind=" + (countedOwnerSlot == null ? "null" + : countedOwnerSlot.kind()) + + ", ownerActive=" + (countedOwnerSlot != null + && countedOwnerSlot.isActive()) + + ", slotReferent=" + (countedOwnerSlot == null + || countedOwnerSlot.referent() == null ? "null" + : System.identityHashCode(countedOwnerSlot.referent())) + + ", slotOwner=" + (countedOwnerSlot == null + || countedOwnerSlot.countedScalarOwner() == null ? "null" + : System.identityHashCode( + countedOwnerSlot.countedScalarOwner())) + ")"); + } + if (staleAggregateOwner && oldBase.refCount <= 0) { + // A detached aggregate slot is no longer a Perl edge. Its + // identity can outlive the storage mutation in compatibility + // paths; retire that token without decrementing a count that + // has already reached zero or the referent is destroyed. + retireOldCountedOwnerAfterPublish = true; + if (newOwned) { + // Keep the stale slot intact until the replacement value + // is published, but acquire the new edge on a fresh slot. + // Reusing the stale identity here would make its deferred + // retirement detach the replacement's owner slot too. + replacementCountedOwnerSlot = new PerlOwnerSlot(countedOwnerKind()); + replacementCountedOwnerSlot.acquireCountedScalarReplacementOwner( + this, newReferent, + "RuntimeScalar.setLargeRefCounted stale aggregate replacement"); + } + } else if (oldBase.refCount <= 0) { + throw new IllegalStateException( + "counted scalar replacement requires a positive old reference count"); + } else if (oldBase.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS) != 0) { + MortalList.deferDecrementFromArraySlot(oldBase, this, + "RuntimeScalar.setLargeRefCounted overwrite"); + oldArgumentAliasReleaseQueued = true; + if (newOwned) { + acquireCountedOwnerForPendingValue(this, newReferent, + countedOwnerKind(), + "RuntimeScalar.setLargeRefCounted store"); + } + } else if (newOwned) { + oldCountedOwnerRelease = countedOwnerSlot + .replaceCountedScalarOwnerAndAcquire( + oldBase, newReferent, this, + "RuntimeScalar.setLargeRefCounted store"); + oldOwnerTraceReleasedDuringReplacement = oldBase != newReferent; + } else { + retireOldCountedOwnerAfterPublish = true; + } + } else { + if (thisWasWeak && oldIdentifiedOwner) { + throw new IllegalStateException( + "weak scalar still owns a counted referent slot"); + } + this.refCountOwned = false; + if (newOwned) { + acquireCountedOwnerForPendingValue(this, newReferent, + countedOwnerKind(), + "RuntimeScalar.setLargeRefCounted store"); } } int preAssignType = this.type; Object preAssignValue = this.value; + prepareDetachedGlobValueOwner(value.type, value.value); // Do the assignment this.type = value.type; this.value = copyScalarPayload(value.type, value.value); - // An explicitly discarded closure can have an inflated CODE refcount, - // so waiting for callDestroy() leaves its captures alive indefinitely. - // Release them only after this slot is gone, the code is inactive, and - // a complete Perl root walk finds no other strong owner (including - // owners stored inside nested containers). - if (value.type == UNDEF - && oldBase instanceof RuntimeCode oldCode - && oldCode.capturedScalars != null - && !RuntimeCode.isActiveCode(oldCode) - && !ReachabilityWalker.isReachableFromRoots(oldCode)) { - oldCode.releaseCaptures(); - } - // Hash-element slots remain durable owners when their existing - // scalar wrapper is assigned a new referent (the normal class-field - // ADJUST path). RuntimeHash's map hook covers slot replacement; this - // covers mutation of a slot that is already in the map. - if (containerOwner instanceof RuntimeHash && oldBase != this.value) { - if (oldBase != null && oldBase.hashSlotOwnerCount > 0) { - oldBase.hashSlotOwnerCount--; + long referenceSlotMutationVersion = noteReferenceSlotMutation(); + this.refCountOwned = newOwned; + if (replacementCountedOwnerSlot != null) { + countedOwnerSlot = replacementCountedOwnerSlot; + } + this.scalarReferenceContentsOwner = null; + if (retireOldCountedOwnerAfterPublish) { + // The replacement is now visible. Retire the old slot only after + // publication, while carrying its exact count obligation forward. + oldCountedOwnerRelease = displacedCountedOwnerSlot.releaseCountedIdentity(); + if (oldCountedOwnerRelease == null) { + throw new IllegalStateException( + "published scalar replacement lost its old release token"); + } + } + // The replacement count and identity are already paired before any + // displaced-edge cleanup can call Perl code. + if (isCurrentReferenceSlotMutation(referenceSlotMutationVersion)) { + // Hash-element slots remain durable owners when their existing + // scalar wrapper is assigned a new referent (the normal class-field + // ADJUST path). RuntimeHash's map hook covers slot replacement; this + // covers mutation of a slot that is already in the map. + if (containerOwner instanceof RuntimeHash && oldBase != this.value) { + if (oldBase != null && oldBase.hashSlotOwnerCount > 0) { + oldBase.hashSlotOwnerCount--; + } + if (this.value instanceof RuntimeBase newBase) { + newBase.hashSlotOwnerCount++; + } } - if (this.value instanceof RuntimeBase newBase) { - newBase.hashSlotOwnerCount++; + this.utf8UncheckedOctets = value.utf8UncheckedOctets; + this.utf8MalformedWarning = value.utf8MalformedWarning; + this.tainted = value.tainted; + this.numericLiteralText = value.numericLiteralText; + this.numericContextSeen = value.numericContextSeen; + this.firstClassRegexScalar = value.firstClassRegexScalar; + this.firstClassRegexReferent = value.firstClassRegexReferent; + this.firstClassRegexValue = value.firstClassRegexValue; + this.formatPictureTainted = value.formatPictureTainted; + this.globalCodeRefFqn = packageCodeRefName != null + ? packageCodeRefName : value.globalCodeRefFqn; + if (transferDetachedIoOwner) { + transferIoOwner(value, this); + } else if (replacementIoOwnerSlot != null) { + attachIoOwnerSlot(this, replacementIoOwnerSlot); + } + if (this.globalCodeRefFqn != null && this.value instanceof RuntimeCode code) { + code.hadStashRef = true; + } + if (!updatingCompiledDirectCallCache + && (packageCodeRefName != null || hasCodeSlotBinding()) + && (preAssignType != this.type || preAssignValue != this.value)) { + GlobalVariable.noteGlobalCodeRefSlotMutation(this); + } + + // Transfer a captured cell's value owner after publishing the new + // contents. The slot transfer acquires the replacement first and + // then releases the previous referent, so callbacks see the updated + // cell and there is no ownership gap. + if (this.hasClosureCaptureOwner()) { + if ((this.type & RuntimeScalarType.REFERENCE_BIT) != 0 + && this.value instanceof RuntimeBase capturedBase + && !WeakRefRegistry.isweak(this)) { + if (this.type == RuntimeScalarType.CODE) { + // Capturing an undef cell precedes assignment in recursive + // closures. The new CODE value needs the capture's own edge, + // independently of the declaring lexical's store owner. + retainClosureCaptureReferent(); + } else { + updateClosureOwnerSlot(capturedBase); + } + } else { + updateClosureOwnerSlot(null); + } } } - if (this.captureCount > 0 && (this.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && this.value instanceof RuntimeBase capturedBase - && !WeakRefRegistry.isweak(this)) { - updateClosureOwnerSlot(capturedBase); + + if (isCurrentReferenceSlotMutation(referenceSlotMutationVersion)) { + RuntimeBase currentReferent = + (this.type & RuntimeScalarType.REFERENCE_BIT) != 0 + && this.value instanceof RuntimeBase referent ? referent : null; + updateUntrackedReferenceOwner(currentReferent); } - this.utf8UncheckedOctets = value.utf8UncheckedOctets; - this.utf8MalformedWarning = value.utf8MalformedWarning; - this.tainted = value.tainted; - this.numericLiteralText = value.numericLiteralText; - this.numericContextSeen = value.numericContextSeen; - this.firstClassRegexScalar = value.firstClassRegexScalar; - this.firstClassRegexReferent = value.firstClassRegexReferent; - this.firstClassRegexValue = value.firstClassRegexValue; - this.formatPictureTainted = value.formatPictureTainted; - this.globalCodeRefFqn = packageCodeRefName != null - ? packageCodeRefName : value.globalCodeRefFqn; - if (transferDetachedIoOwner) { - value.ioOwner = false; - this.ioOwner = true; - } else if (durableIoDestination - && (!assignedFromArgumentAlias || assignedFromAcceptedSocketArgument) - && this != value - && value.type == GLOBREFERENCE - && value.value instanceof RuntimeGlob assignedGlob - && isUnstashedIoGlob(assignedGlob) - && hasLiveIo(assignedGlob)) { - this.ioOwner = true; + if (isCurrentReferenceSlotMutation(referenceSlotMutationVersion)) { + refreshDetachedGlobValueOwner(); } - // Hash and array assignment normally preserves the aggregate's existing - // scalar slot. If that slot belongs to a tied-handler graph, propagate - // its conservative marker to the newly installed reference graph too. - propagateTiedHandlerMarkerToReferent(); - if (this.globalCodeRefFqn != null && this.value instanceof RuntimeCode code) { - code.hadStashRef = true; + if (isCurrentReferenceSlotMutation(referenceSlotMutationVersion)) { + refreshArgumentAliasOwnerSlots(); + } + // During global destruction Perl warns when DESTROY stores its dying + // object into durable Perl storage, even if that storage cell already + // held the same reference before the callback. Owner-slot delta alone + // cannot see that same-cell assignment, so record the store at its + // scalar-slot producer while the lifecycle phase is still DESTRUCT. + if (isCurrentReferenceSlotMutation(referenceSlotMutationVersion) + && DestroyDispatch.currentDestroyTarget() != null + && "DESTRUCT".equals(GlobalVariable + .getGlobalVariable(GlobalContext.GLOBAL_PHASE).toString()) + && isPackageGlobalRoot + && !WeakRefRegistry.isweak(this) + && this.value == DestroyDispatch.currentDestroyTarget() + && hasLiveDurableStrongValueSlot()) { + DestroyDispatch.markDestroyTargetRescued(); } - if (packageCodeRefName != null - && (preAssignType != this.type || preAssignValue != this.value)) { - GlobalVariable.noteGlobalCodeRefSlotMutation(this); + // An explicitly discarded closure can have an inflated CODE refcount, + // so waiting for callDestroy() leaves its captures alive indefinitely. + // Release them only when the owner ledger shows no other Perl owner + // besides the scalar slot currently being overwritten. + if (value.type == UNDEF + && oldBase instanceof RuntimeCode oldCode + && !oldCode.hasCountedCodeSlots + && oldCode.capturedScalars != null + && !oldCode.hasPendingReturnOwner() + && !oldCode.hasPerlOwnerForCaptureOtherThan(countedOwnerSlot)) { + oldCode.releaseCaptures(); } // DESTROY rescue detection for reference types. @@ -2915,18 +4920,17 @@ && hasLiveIo(assignedGlob)) { // $source->{schema} = $self (overwriting weak ref with strong ref) // But avoids false positives from: // my $self = shift (new local variable, oldBase is null) - if (thisWasWeak + if (isCurrentReferenceSlotMutation(referenceSlotMutationVersion) + && thisWasWeak && DestroyDispatch.currentDestroyTarget() != null && oldBase == DestroyDispatch.currentDestroyTarget() - // Package weak maps (PPI's global parent indexes are the - // common case) may briefly replace/reuse an entry while its - // target is being destroyed. That is handled by the normal - // refCount>0 resurrection path below; the special rescued- - // object lifecycle is only for an owning aggregate such as a - // DBIC ResultSource saving its Schema through a weak slot. - && containerOwner != null - && !(containerOwner instanceof RuntimeHash owner - && owner.isPackageRootedHash()) + // The scalar must still occupy durable Perl storage after the + // assignment. Use the exact storage proof here because the + // fast container hint can be absent during lvalue dispatch. + // Package-rooted aggregate slots count as durable owners too: + // their explicit storage identity keeps a promoted value alive + // until that exact slot is released. + && hasLiveDurableStrongValueSlot() && this.value instanceof RuntimeBase base && base == DestroyDispatch.currentDestroyTarget()) { DestroyDispatch.markDestroyTargetRescued(); @@ -2937,37 +4941,29 @@ && hasLiveIo(assignedGlob)) { // object stays untracked (-1) and weak refs are never cleared, causing // leak detection failures (DBIC t/52leaks.t tests 12-20). // - // Set to 1: the rescue container's single counted reference. - // When the rescue source dies and DESTROY weakens source->{schema}, - // refCount goes 1→0→callDestroy. That callDestroy is intercepted by - // the rescuedObjects check in callDestroy's destroyFired path (no - // clearWeakRefsTo or cascade), keeping Schema's internals intact. - // Proper cleanup happens at END time via clearRescuedWeakRefs. - if (base.refCount == Integer.MIN_VALUE) { - base.traceRefCount(0, "RuntimeScalar.setLargeRefCounted (rescue MIN_VALUE -> 1)"); - base.refCount = 1; - } else if (base.refCount >= 0) { - base.traceRefCount(+1, "RuntimeScalar.setLargeRefCounted (rescue increment)"); - base.refCount++; - } - base.hadCountedReference = true; - base.recordOwner(this, "rescue from currentDestroyTarget"); - newOwned = true; - } - - // Phase B1 (refcount_alignment_52leaks_plan.md): register this scalar - // once, after rescue handling has had a chance to acquire ownership. - // This used to run both before and after the assignment, causing two - // WeakHashMap.put() calls for every ordinary tracked reference store. - if (newOwned) { - ScalarRefRegistry.registerRef(this); + // The ordinary store above already counted and identified this + // slot unless the scalar-reference-contents slot is its owner. + // Rescue changes the lifecycle decision; it must not add a second + // count for the same strong edge. Only install a count here when + // the normal store path left this edge uncounted and no contents + // owner already represents it. + boolean rescueNeedsCountedOwner = !newOwned + && !scalarContentsOwnedByEscapedReference; + if (rescueNeedsCountedOwner && base.isRefCountTracked()) { + acquireCountedOwnerForPendingValue( + this, base, countedOwnerKind(), + "RuntimeScalar.setLargeRefCounted DESTROY rescue"); + newOwned = true; + } } + // A returned blessed container may have no selective count even though // this scalar is its final Perl owner. It will not enter the counted // decrement branch below, so release nested objects explicitly before // an undef overwrite discards the container. - if (oldBase != null && oldBase.blessId != 0 && oldBase.refCount == 0 + if (oldBase != null && oldBase.blessId != 0 + && oldBase.isRefCountTracked() && oldBase.refCount == 0 && !thisWasWeak && value.type == UNDEF) { if (oldBase instanceof RuntimeArray array) { MortalList.deferDestroyForContainerClear(array.elements); @@ -2976,111 +4972,43 @@ && hasLiveIo(assignedGlob)) { } } + if (explicitUndef && oldBase != null + && oldBase.isWeaklyRefCountTracked()) { + boolean argumentAliasKeepsOldBase = + oldBase.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS) != 0; + if (argumentAliasKeepsOldBase) { + // The deferred alias is the remaining strong edge. Keep the + // weak lifecycle obligation on that exact owner until it leaves. + oldBase.deferFinalReleaseToUncountedOwnerSlots(); + } else if (!oldBase.hasPerlStrongOwner()) { + DestroyDispatch.callDestroy(oldBase); + } + } + // Decrement old value's refCount AFTER assignment (skip for weak refs // and for scalars that didn't own a refCount increment). - if (oldBase != null && !thisWasWeak - && (this.refCountOwned || oldOwnedByScalarReference)) { - if (oldBase.refCount > 0) { - oldBase.traceRefCount(-1, "RuntimeScalar.setLargeRefCounted (decrement on overwrite)"); - oldBase.releaseOwner(this, "setLargeRefCounted overwrite"); - oldBase.releaseActiveOwner(this); - } - if (oldBase.refCount > 0 && --oldBase.refCount == 0) { - if (oldBase.localBindingExists) { - // Named container (my %hash / my @array): the local variable - // slot holds a strong reference not counted in refCount. - // Don't call callDestroy — the container is still alive. - // Cleanup will happen at scope exit (scopeExitCleanupHash/Array). - } else if (oldBase.blessId == 0 - && (oldBase instanceof RuntimeArray || oldBase instanceof RuntimeHash) - && WeakRefRegistry.hasWeakRefsTo(oldBase) - && RuntimeCode.argsStackDepth() > 1 - && !oldBase.clearedOwnedAggregateElement) { - // A parser can walk weak parent links through a temporary - // alias while the owning tree still keeps an unblessed - // aggregate alive. Defer clearing until the statement - // boundary so the shared root snapshot can distinguish a - // live ancestor from one whose final owner has gone away. - MortalList.requestTargetedWeakSweep(oldBase); - } else if (oldBase.blessId != 0 - && WeakRefRegistry.hasWeakRefsTo(oldBase) - && !blessedClassHasDestroy(oldBase) - && RuntimeCode.argsStackDepth() > 1 - && !oldBase.clearedOwnedAggregateElement) { - // A nested method can still have JVM expression temporaries - // that are not represented in the selective count. Do not - // invent a replacement owner here: that count outlives the - // frame when a local alias has already been cleaned up (as - // in Algorithm::SlidingWindow's cleared buffer slot). - // Defer the reachability decision until the enclosing Perl - // statement boundary, where all method-local temporaries - // have gone away and the walker can see real Perl roots. - MortalList.requestTargetedWeakSweep(oldBase); - } else if (oldBase.blessId != 0 - && oldBase.storedInPackageGlobal - && WeakRefRegistry.hasWeakRefsTo(oldBase) - && ReachabilityWalker.isReachableFromRoots(oldBase)) { - // D-W6.18: property-based walker gate (mirror of - // MortalList.flush). Replaces classNeedsWalkerGate - // class-name heuristic with the storedInPackageGlobal - // flag set at hash-store time. - // Phase D / Step W3-Path 2: mirror of the gate in - // MortalList.flush(). Blessed object with outstanding - // weak refs whose selective refCount dipped to 0 - // under an overwrite, but the walker says it's still - // reachable from roots (e.g. held by `our %METAS`). - // Treat as transient refCount drift; don't fire - // DESTROY; don't clear weak refs. - // - // See MortalList.flush() for full rationale and - // dev/modules/moose_support.md (Phase D / Step W). - } else { - oldBase.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(oldBase); + if (oldBase != null && !thisWasWeak && oldRefCountOwned) { + if (oldCountedOwnerRelease != null) { + // The slot now describes the replacement edge. Drain the exact + // displaced edge token so this release cannot retire or infer + // ownership from the scalar's newer value. + if (!oldOwnerTraceReleasedDuringReplacement + && (!newOwned || oldBase != newReferent)) { + oldBase.releaseOwner(this, "setLargeRefCounted overwrite"); } - } else if (oldBase.refCount > 0 && value.type == UNDEF - && oldBase.blessId != 0 - && DestroyDispatch.isInsideDestroy() - && WeakRefRegistry.weakRefsExist()) { - // Phase D: inside a DESTROY body, an explicit undef - // assignment released our strong ref to another - // blessed-with-DESTROY object but selective refCount - // didn't drop to 0 (cycles). Flag a deferred sweep to - // run once at the end of the outermost DESTROY. - // Narrow gating (only inside DESTROY, only value==UNDEF, - // only blessed) keeps per-set() cost to an int compare - // and one BitSet lookup. - String cn = NameNormalizer.getBlessStr(oldBase.blessId); - if (cn != null && DestroyDispatch.classHasDestroy(oldBase.blessId, cn)) { - DestroyDispatch.requestSweepAfterOuterDestroy(); + if (staleAggregateOwner && oldBase.refCount <= 0) { + oldCountedOwnerRelease.complete(); + } else { + MortalList.releaseCountedOwnerSlotImmediately(oldBase, + oldCountedOwnerRelease, + "RuntimeScalar.setLargeRefCounted overwrite"); } - } - } - - // A returned call-frame alias can leave the selective count one owner - // high after the caller overwrites its last real reference. Clear weak - // observers only when the referent has no independent package/lexical - // root and is not retained by a live closure. ExternalRootSnapshot - // deliberately treats a named lexical's own slot as non-external while - // preserving nested metadata owners such as Sub::Quote's saved info. - if ((oldBase instanceof RuntimeArray || oldBase instanceof RuntimeHash) - && !thisWasWeak - && !DestroyDispatch.isRescued(oldBase) - && !(oldBase.blessId != 0 && blessedClassHasDestroy(oldBase)) - && WeakRefRegistry.hasWeakRefsTo(oldBase) - && (RuntimeCode.argsStackDepth() <= 1 - || oldBase.clearedOwnedAggregateElement) - && !ReachabilityWalker.isReachableFromExternalRoot(oldBase) - && !ReachabilityWalker.isReachableFromLiveCodeCaptures(oldBase)) { - // The root is already proven unreachable. Use the regular - // no-DESTROY disposal path for blessed aggregates so owned child - // slots are released with the root; clearing only the root's weak - // aliases leaves descendants alive through stale selective counts. - if (oldBase.blessId != 0) { - oldBase.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(oldBase); + } else if (oldArgumentAliasReleaseQueued) { + // The old edge was already queued before the active alias could + // observe the scalar's replacement. } else { - WeakRefRegistry.clearWeakRefsTo(oldBase); + throw new IllegalStateException( + "counted scalar replacement lost its pending owner release"); } } @@ -3091,48 +5019,60 @@ && hasLiveIo(assignedGlob)) { // nested DESTROY cleanup can release the just-returned value. boolean flushWasSuppressed = MortalList.suppressFlush(true); try { - releaseScalarReferenceContents(oldScalarReferenceContents); + if (oldScalarReferenceContentsOwner != null) { + oldScalarReferenceContentsOwner.releaseScalarReferenceContents(); + } } finally { MortalList.suppressFlush(flushWasSuppressed); } } - if (undefAssignmentOfDestroyableRef && !DestroyDispatch.isInsideDestroy()) { - shouldReleaseUnrootedRescuedGraph = true; - } - - // WEAKLY_TRACKED objects: do NOT clear weak refs on overwrite. - // These objects have refCount == -2 and their strong refs don't have + // Weak-tracked objects: do NOT clear weak refs on overwrite. + // Their strong refs don't have // refCountOwned=true (they were set before tracking started). // Overwriting ONE reference doesn't mean no other strong refs exist — // closures may capture copies (e.g., Sub::Quote's $_QUOTED capture). // This is the same rationale as in scopeExitCleanup. - // Weak refs for WEAKLY_TRACKED objects are cleared only when a strong - // reference is explicitly undef'd (or assigned undef), via a targeted - // sweep so other strong scalar refs can still keep the referent alive. - if (oldBase != null - && oldBase.refCount == WeakRefRegistry.WEAKLY_TRACKED - && value.type == UNDEF) { - MortalList.requestTargetedWeakSweep(oldBase); + // Final strong-owner release clears weak refs through the owner-slot + // ledger; overwrite does not schedule later graph inspection. + + // A reentrant setter or weaken() may already have completed the slot's + // ownership transition while old-value cleanup ran. Do not restore the + // outer assignment's stale bookkeeping over that newer state. + if (isCurrentReferenceSlotMutation(referenceSlotMutationVersion)) { + this.refCountOwned = newOwned; + if (newOwned && this.value instanceof RuntimeBase ownedReferent) { + requireCountedOwner(ownedReferent, "RuntimeScalar.setLargeRefCounted store"); + if (untrackedReferenceOwnerSlot != null) { + releaseUntrackedReferenceOwner(untrackedReferenceOwnerSlot.referent()); + } + } else { + updateUntrackedReferenceOwner(this.value instanceof RuntimeBase referent + && (this.type & RuntimeScalarType.REFERENCE_BIT) != 0 + ? referent : null); + } + } + if (isCurrentReferenceSlotMutation(referenceSlotMutationVersion) + && !scalarContentsOwners.isEmpty()) { + RuntimeBase nextContents = (this.type & REFERENCE_BIT) != 0 + && this.value instanceof RuntimeBase base + && !WeakRefRegistry.isweak(this) ? base : null; + for (PerlOwnerSlot owner : scalarContentsOwners) { + RuntimeScalar scalarOwner = owner.scalarContentsOwner(); + owner.retargetScalarReferenceContents(nextContents); + if (!owner.isActive() && scalarOwner != null) { + scalarOwner.clearScalarReferenceContentsOwner(owner); + } + } } - if (undefAssignmentOfDestroyableRef && !ModuleInitGuard.inModuleInit()) { - MortalList.requestTargetedWeakSweep(oldBase); + if (isCurrentReferenceSlotMutation(referenceSlotMutationVersion)) { + retainScalarReferenceContents(value); } - // An explicitly discarded aggregate can own a tree of blessed values - // whose selective counts have drifted above zero. Schedule only its - // weakly observed descendants; a complete root walk is unnecessary. - if (value.type == UNDEF - && WeakRefRegistry.weakRefsExist() - && (oldBase instanceof RuntimeHash || oldBase instanceof RuntimeArray)) { - if (MortalList.requestWeakSweepsForDestroyedContainer(oldBase)) { - requestedDiscardedAggregateSweep = true; - } + if (value != this && !stagedValueOwner + && this.value instanceof RuntimeBase referent) { + MortalList.consumeMortalReturnValue(value, referent); } - // Update ownership: this scalar now owns a refCount iff we incremented. - this.refCountOwned = newOwned; - retainScalarReferenceContents(value); - // Flush deferred mortal decrements from the current function scope. // Entries below the current MortalList mark belong to the caller, and // must survive through nested calls such as chained AUTOLOAD dispatch. @@ -3140,28 +5080,12 @@ && hasLiveIo(assignedGlob)) { MortalList.pushTemporaryRoot(this); MortalList.pushTemporaryRoot(value); try { - MortalList.flushAboveMark(); + if (explicitUndef) MortalList.flush(); + else MortalList.flushAboveMark(); } finally { MortalList.popTemporaryRoot(value); MortalList.popTemporaryRoot(this); } - if (requestedDiscardedAggregateSweep) { - MortalList.flushReleasedWeakSweepsIfSafe(); - } - - // An explicit undef can run DESTROY and let the object self-rescue. - // Preserve real Perl resurrection when another package/closure root - // still reaches that graph. If the only remaining pin is the runtime's - // rescued-object queue, release its nested weak callbacks now: DBIC's - // retained DBI handle relies on its weak HandleError closure observing - // that the owning Schema/Storage graph has gone away. - if (shouldReleaseUnrootedRescuedGraph - && DestroyDispatch.isRescued(oldBase) - && !ModuleInitGuard.inModuleInit() - && !ReachabilityWalker.isReachableFromExternalRootExcludingRescued(oldBase)) { - DestroyDispatch.clearNestedWeakRefsForRescued(oldBase); - } - if (isPackageGlobalRoot && globalCodeRefFqn != null) { boolean invalidate = preAssignType != this.type || preAssignValue != this.value; if (!invalidate && this.type == CODE && this.value instanceof RuntimeCode nc @@ -3196,9 +5120,16 @@ private void noteClearedAggregateElement(RuntimeScalar replacement) { } } - private static boolean blessedClassHasDestroy(RuntimeBase base) { - String cn = NameNormalizer.getBlessStr(base.blessId); - return cn != null && DestroyDispatch.classHasDestroy(base.blessId, cn); + /** Whether a primitive/string setter must retire an existing Perl owner edge. */ + private boolean requiresOwnerAwareScalarOverwrite() { + return (type & REFERENCE_BIT) != 0 + || type == GLOB + || type == CODE + || refCountOwned + || (countedOwnerSlot != null && countedOwnerSlot.isActive()) + || untrackedReferenceOwnerSlot != null + || scalarReferenceContentsOwner != null + || ioOwnerSlot != null; } public RuntimeScalar set(int value) { @@ -3212,8 +5143,10 @@ public RuntimeScalar set(int value) { } throw new PerlCompilerException("Modification of a read-only value attempted"); } + if (requiresOwnerAwareScalarOverwrite()) return set(new RuntimeScalar(value)); this.type = RuntimeScalarType.INTEGER; this.value = value; + refreshArgumentAliasOwnerSlots(); this.tainted = false; this.numericLiteralText = null; this.numericContextSeen = false; @@ -3230,7 +5163,9 @@ public RuntimeScalar set(long value) { if (this.type == READONLY_SCALAR) { throw new PerlCompilerException("Modification of a read-only value attempted"); } + if (requiresOwnerAwareScalarOverwrite()) return set(new RuntimeScalar(value)); this.initializeWithLong(value); + refreshArgumentAliasOwnerSlots(); this.tainted = false; this.numericLiteralText = null; this.numericContextSeen = false; @@ -3254,6 +5189,7 @@ public RuntimeScalar set(BigInteger value) { if (this.type == READONLY_SCALAR) { throw new PerlCompilerException("Modification of a read-only value attempted"); } + if (requiresOwnerAwareScalarOverwrite()) return set(new RuntimeScalar(value)); // Check if the value fits in an int if (value.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) <= 0 @@ -3273,6 +5209,7 @@ else if (value.abs().compareTo(BigInteger.valueOf(9007199254740992L)) <= 0) { // this.type = RuntimeScalarType.STRING; this.value = value.toString(); } + refreshArgumentAliasOwnerSlots(); this.tainted = false; this.numericLiteralText = null; this.numericContextSeen = false; @@ -3289,8 +5226,10 @@ public RuntimeScalar set(boolean value) { if (this.type == READONLY_SCALAR) { throw new PerlCompilerException("Modification of a read-only value attempted"); } + if (requiresOwnerAwareScalarOverwrite()) return set(new RuntimeScalar(value)); this.type = RuntimeScalarType.BOOLEAN; this.value = value; + refreshArgumentAliasOwnerSlots(); this.tainted = false; this.numericLiteralText = null; this.numericContextSeen = false; @@ -3312,12 +5251,14 @@ public RuntimeScalar set(String value) { } throw new PerlCompilerException("Modification of a read-only value attempted"); } + if (requiresOwnerAwareScalarOverwrite()) return set(new RuntimeScalar(value)); if (value == null) { this.type = UNDEF; } else { this.type = RuntimeScalarType.STRING; } this.value = value; + refreshArgumentAliasOwnerSlots(); this.utf8UncheckedOctets = false; this.utf8MalformedWarning = null; this.tainted = false; @@ -3337,6 +5278,7 @@ RuntimeScalar setInternalPackageName(String value) { growingString = null; type = value == null ? UNDEF : RuntimeScalarType.STRING; this.value = value; + refreshArgumentAliasOwnerSlots(); utf8UncheckedOctets = false; utf8MalformedWarning = null; tainted = false; @@ -4196,6 +6138,7 @@ public RuntimeScalar scalarDeref() { RuntimeScalar newScalar = new RuntimeScalar(); this.value = newScalar; this.type = RuntimeScalarType.REFERENCE; + refreshArgumentAliasOwnerSlots(); this.numericLiteralText = null; this.numericContextSeen = false; this.firstClassRegexScalar = false; @@ -4263,12 +6206,13 @@ public RuntimeScalar refAliasScalarReference() { } requireForeachReference(REFERENCE, "SCALAR"); RuntimeScalar referent = (RuntimeScalar) value; - // Refaliasing, rather than reference creation, is what gives a - // forward lexical cell its declaration identity. Preserve one - // declaration initialization for this referent. An ordinary escaped - // reference never reaches this path, so it cannot leak into a later - // shadowing lexical. - referent.retainMaterializedForwardReference = true; + // Keep the one-shot declaration permit only for a cell materialized + // before its lexical declaration. Ordinary refaliases to an already + // declared lexical must not let a later same-named declaration reuse + // and overwrite the escaped cell. + if (referent.materializedBeforeLexicalDeclaration) { + referent.retainMaterializedForwardReference = true; + } return referent; } @@ -4927,13 +6871,13 @@ public RuntimeScalar createReference() { } referencedByScalarReference = true; boolean isRegisteredLexical = - this.refCount == -1 && MyVarCleanupStack.isRegistered(this); - if (this.refCount == -1 && isRegisteredLexical) { - this.refCount = 0; + this.isRefCountUntracked() && MyVarCleanupStack.isRegistered(this); + if (this.isRefCountUntracked() && isRegisteredLexical) { + this.startRefCountTracking(); this.localBindingExists = true; - } else if (this.refCount == -1 + } else if (this.isRefCountUntracked() && !isRegisteredLexical - && captureCount == 0 + && !hasClosureCaptureOwner() && (!isPackageGlobalRoot || GlobalVariable.isTemporaryGlobalAliasValue(this)) && containerOwner == null && !RuntimeCode.isInstalledPadConstant(this)) { @@ -4942,10 +6886,13 @@ public RuntimeScalar createReference() { // consumes its sole owner immediately. Bound lexicals, closure // captures, globals, aggregate elements, active @_ arguments, and // constants owned by an installed subroutine's optree retain the - // established untracked/WEAKLY_TRACKED behavior. - this.refCount = 0; + // established untracked/weak-tracked behavior. + this.startRefCountTracking(); this.ephemeralScalarReferenceReferent = true; } + if (MyVarCleanupStack.isRegistered(this)) { + RuntimeCode.noteMyVarRegistered(this); + } RuntimeScalar result = new RuntimeScalar(); result.type = RuntimeScalarType.REFERENCE; result.value = this; @@ -4953,11 +6900,10 @@ public RuntimeScalar createReference() { } public RuntimeScalar undefine() { + releaseDetachedGlobValueOwner(); if (isPackageGlobalRoot) { - MortalList.invalidateExternalRootSnapshot(); } if ((type & REFERENCE_BIT) != 0 && value != null) { - MortalList.invalidateFullRootSnapshotForScalarClear(); } // Special handling for CODE type - don't set the ref to undef, // just clear the code from the global symbol table. @@ -4989,17 +6935,7 @@ public RuntimeScalar undefine() { return RuntimeCode.undefineCodeReference(this); } if (type == RuntimeScalarType.CODE && value instanceof RuntimeCode code && globalCodeRefFqn != null) { - boolean releasedCode = false; releaseAllClosureCaptureReferents(code); - if (this.refCountOwned && code.refCount > 0) { - this.refCountOwned = false; - code.releaseActiveOwner(this); - if (--code.refCount == 0) { - code.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(code); - releasedCode = true; - } - } // Clear the body but keep a declared CODE slot. Perl preserves the // glob's CODE entry after both `undef &existing` and // `undef &previously_unknown`: exists(&name) remains true while @@ -5014,152 +6950,48 @@ public RuntimeScalar undefine() { undefinedCode.packageName = "main"; undefinedCode.subName = globalCodeRefFqn; } + + PerlOwnerSlot.PendingRelease oldCodeRelease = null; + if (this.refCountOwned) { + if (code.isPerlDestroyed()) { + throw new IllegalStateException( + "counted global CODE slot refers to an already destroyed CV"); + } + PerlOwnerSlot ownerSlot = this.countedOwnerSlot; + if (ownerSlot == null || !ownerSlot.isActive() + || ownerSlot.referent() != code + || ownerSlot.countedScalarOwner() != this) { + throw new IllegalStateException( + "global CODE undefine lost its counted stash owner slot"); + } + undefinedCode.startRefCountTracking(); + oldCodeRelease = ownerSlot.replaceCountedScalarOwnerAndAcquire( + code, undefinedCode, this, + "RuntimeScalar.undefine global CODE replacement"); + } + this.value = undefinedCode; this.tainted = false; this.numericLiteralText = null; this.numericContextSeen = false; this.firstClassRegexScalar = false; this.formatPictureTainted = false; + refreshCodeSlotOwner(); + if (oldCodeRelease != null) { + MortalList.releaseCountedOwnerSlotImmediately( + code, oldCodeRelease, + "RuntimeScalar.undefine global CODE replacement"); + } // Invalidate the method resolution cache InheritanceResolver.invalidateCache(); - if (releasedCode && WeakRefRegistry.weakRefsExist() && !ModuleInitGuard.inModuleInit()) { - ReachabilityWalker.sweepWeakRefs(true); - } return this; } - // Decrement refCount for blessed references with DESTROY or weakly-tracked refs - RuntimeBase oldBase = null; - if ((this.type & RuntimeScalarType.REFERENCE_BIT) != 0 && this.value instanceof RuntimeBase base - && base.refCount != -1 && base.refCount != Integer.MIN_VALUE) { - oldBase = base; - } - if (oldBase != null && this.captureRefCountOwned() > 0) { - releaseAllClosureCaptureReferents(oldBase); - } - - // Close IO handles when dropping a glob reference. - // This mimics Perl's internal sv_clear behavior where IO handles are closed - // when the glob's reference count drops to zero (independent of DESTROY). + // Retire non-CODE values through the same reference-slot transition as + // assignment. Explicit undef closes the handle first and asks the shared + // operation to apply undef's weak-observer and full-mortal-flush rules. closeIOOnDrop(); - // For all other types, set to undef - this.type = UNDEF; - this.value = null; - this.tainted = false; - this.numericLiteralText = null; - this.numericContextSeen = false; - this.firstClassRegexScalar = false; - this.formatPictureTainted = false; - - // Decrement AFTER clearing (Perl 5 semantics: DESTROY sees the new state) - boolean undefOnBlessedWithDestroy = false; - boolean undefOnWeakObservedBlessedWrapper = false; - if (oldBase != null) { - if (oldBase.refCount == WeakRefRegistry.WEAKLY_TRACKED) { - // Weakly-tracked object (unblessed, birth-tracked, with weak refs): - // clear weak refs on explicit undef. These objects transitioned to - // WEAKLY_TRACKED in weaken() because their refCount was unreliable - // (closure captures bypass setLarge). Clearing on undef is a heuristic - // but safe since unblessed objects have no DESTROY. - oldBase.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(oldBase); - } else if (this.refCountOwned && oldBase.refCount > 0) { - this.refCountOwned = false; - oldBase.releaseActiveOwner(this); - if (--oldBase.refCount == 0) { - if (oldBase.localBindingExists) { - // Named container: local variable may still exist. Skip callDestroy. - } else { - oldBase.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(oldBase); - // Phase H (t/storage/error.t test 49): if the DESTROY self- - // saved the object (rescued), user's explicit undef still - // means their lexical handle is gone — weak refs pointing - // to the rescued object (e.g. HandleError closure's weak - // $schema) must be cleared so callbacks that fire AFTER - // this point can detect "schema is gone". - if (oldBase.blessId != 0 && WeakRefRegistry.weakRefsExist()) { - String cn = NameNormalizer.getBlessStr(oldBase.blessId); - if (cn != null && DestroyDispatch.classHasDestroy(oldBase.blessId, cn)) { - undefOnBlessedWithDestroy = true; - } - } - } - } else if (oldBase.blessId != 0 && oldBase.refCount > 0 - && WeakRefRegistry.weakRefsExist()) { - // Phase D: selective refCount suggests this object still has - // strong references, but those may all be internal cycles - // (e.g. DBIC's Schema <-> source_registrations). Defer to the - // reachability walker if the class has DESTROY — it's the - // canonical decider of liveness once the user has explicitly - // released their lexical handle. - String cn = NameNormalizer.getBlessStr(oldBase.blessId); - if (cn != null && DestroyDispatch.classHasDestroy(oldBase.blessId, cn)) { - undefOnBlessedWithDestroy = true; - } - } - } else if (oldBase.blessId != 0 && WeakRefRegistry.weakRefsExist()) { - // Phase D: no owned-count decrement (refCountOwned was false, or - // refCount was already 0 from prior selective drift). The - // object is blessed — if its class has DESTROY, let the walker - // decide whether this undef just released the last live lexical - // handle. - String cn = NameNormalizer.getBlessStr(oldBase.blessId); - if (cn != null && DestroyDispatch.classHasDestroy(oldBase.blessId, cn)) { - undefOnBlessedWithDestroy = true; - } - } - } - - // An explicitly released blessed wrapper may have no DESTROY method - // of its own while still owning a tied container whose handler does. - // If the wrapper itself is being observed weakly, let the reachability - // walker decide at the next statement boundary whether this was its - // last strong owner. - // Hash::AutoHash's wraptie constructor has exactly this shape. - if (oldBase != null - && oldBase.blessId != 0 - && WeakRefRegistry.hasWeakRefsTo(oldBase)) { - undefOnWeakObservedBlessedWrapper = true; - } - - // Flush deferred mortal decrements. Without this, pending DECs from - // scope exit of locals (e.g., `my ($a,$b) = @_` inside a sub) would - // not be processed until the next setLarge/apply, making the refCount - // appear inflated at the point of `undef $ref`. This matches Perl 5 - // where FREETMPS runs at statement boundaries. - MortalList.flush(); - - // Phase D: undef-of-blessed auto-trigger for the reachability walker. - // When the user explicitly undef's a blessed ref with DESTROY but - // selective refCount stays > 0 (internal cycles), ask the walker - // to determine real reachability. Bypasses the MortalList auto-sweep - // throttle because this is an explicit release, not an opportunistic - // check. Skips when we're in module-init to avoid clearing weak refs - // that require/use chains still depend on. - if ((undefOnBlessedWithDestroy || undefOnWeakObservedBlessedWrapper) - && !ModuleInitGuard.inModuleInit()) { - // The current undef call can still have JVM temporaries that make - // the just-released wrapper appear live. Also arm the next Perl - // statement boundary, after those temporaries have disappeared. - MortalList.requestTargetedWeakSweep(oldBase); - if (System.getenv("JPERL_PHASE_D_DBG") != null) { - System.err.println("DBG Phase D undef-of-blessed trigger for " + - (oldBase != null ? org.perlonjava.runtime.runtimetypes.NameNormalizer.getBlessStr(oldBase.blessId) : "?") + - " refCount=" + (oldBase != null ? oldBase.refCount : -1)); - } - // The DESTROY path historically needs an immediate global pass so - // callbacks after explicit undef observe the released object as - // gone. A weak-observed wrapper without DESTROY only needs the - // targeted statement-boundary pass: sweeping globally while a - // nested call frame is still assembling objects can clear unrelated - // weak owner links (for example SQL::Translator index -> table). - if (undefOnBlessedWithDestroy) { - ReachabilityWalker.sweepWeakRefs(false); - } - } - - return this; + return transitionReferenceSlot(new RuntimeScalar(), true); } /** @@ -5210,8 +7042,26 @@ private void closeIOOnDrop() { /** Performs scalar-specific scope cleanup, including owned anonymous IO fds. */ public static void scopeExitCleanup(RuntimeScalar scalar) { - if (scalar == null) return; + scopeExitCleanup(scalar, false); + } + + /** Performs final cleanup for a scalar referent that has reached DESTROY. */ + static void scopeExitCleanupDestroyed(RuntimeScalar scalar) { + scopeExitCleanup(scalar, true); + } + private static void scopeExitCleanup(RuntimeScalar scalar, boolean finalRelease) { + if (scalar == null) return; + if (scalar.hasCodeSlotBinding()) return; + if (scalar instanceof RuntimeGlob glob) glob.releaseDetachedComponentsIfUnowned(); + if (finalRelease || (!scalar.hasClosureCaptureOwner() && !scalar.hasOwnerSlots() + && !scalar.hasScalarCellOwner())) { + scalar.releaseDetachedGlobValueOwner(); + } + RuntimeBase untrackedValueAtScopeExit = scalar.untrackedReferenceOwnerSlot == null + ? null : scalar.untrackedReferenceOwnerSlot.referent(); + scalar.refreshUntrackedReferenceOwner(); + if (finalRelease) scalar.localBindingExists = false; // ${^LAST_FH} is tied to the lexical handle that performed the last // tell/read. A lexical coercible glob must stop being observable once // that lexical leaves scope, even though the named STDOUT glob remains @@ -5228,7 +7078,7 @@ public static void scopeExitCleanup(RuntimeScalar scalar) { // that durable owner leaves; clearing on the borrow breaks // getline/input_line_number calls inside wrapper subroutines. boolean borrowedLiveIo = isUnstashedIoGlob(glob) - && !scalar.ioOwner && glob.ioHolderCount > 0; + && !scalar.hasIoOwner() && glob.ioHolderCount() > 0; if (!borrowedLiveIo) { RuntimeIO.setLastAccessedHandle(null); RuntimeIO.setLastReadlineHandleName(null); @@ -5236,9 +7086,10 @@ public static void scopeExitCleanup(RuntimeScalar scalar) { } } - if (scalar.referencedByScalarReference - && scalar.localBindingExists - && scalar.captureCount == 0) { + if (!finalRelease && scalar.referencedByScalarReference + && !scalar.hasClosureCaptureOwner() + && (scalar.localBindingExists || scalar.refCount > 0 + || scalar.hasScalarCellOwner())) { cleanupScalarReferenceBinding(scalar); // A reference to the lexical escaped its declaring scope. The // RuntimeScalar is now the Perl SV container, so its current value @@ -5247,13 +7098,14 @@ public static void scopeExitCleanup(RuntimeScalar scalar) { // scalar self-tie that wrapper owns the remaining counted // reference to this same scalar; returning here would leave the // cycle intact and suppress the handler's DESTROY. - if (scalar.refCount > 0 && scalar.type != RuntimeScalarType.TIED_SCALAR) return; + if ((scalar.refCount > 0 || scalar.hasScalarCellOwner()) + && scalar.type != RuntimeScalarType.TIED_SCALAR) return; } // A captured lexical or an SV with an escaped scalar reference is still // alive after its declaring scope exits. Its destruction watcher fires // when the final owner later releases it, not at lexical scope exit. - if (scalar.captureCount == 0) { + if (!scalar.hasClosureCaptureOwner()) { scalar.notifyDestroyedWatchers(); } @@ -5261,72 +7113,42 @@ public static void scopeExitCleanup(RuntimeScalar scalar) { // When all three conditions are true, the entire method body is a no-op: // - refCountOwned=false → deferDecrementIfTracked returns immediately // - captureCount=0 → capture handling branch not taken - if (!scalar.refCountOwned && scalar.captureCount == 0 && !scalar.ioOwner - && !scalar.ownsScalarReferenceContents + if (!scalar.refCountOwned && !scalar.hasClosureCaptureOwner() + && !scalar.hasIoOwner() + && !scalar.hasScalarReferenceContentsOwner() + && scalar.untrackedReferenceOwnerSlot == null && scalar.type != RuntimeScalarType.TIED_SCALAR) { - // Special case: CODE refs with unreleased captures that were never - // stored via set() (e.g., anonymous subs passed directly as arguments). - // These have refCount=0 (from makeCodeObject) and refCountOwned=false - // (never went through setLargeRefCounted). Without this check, - // releaseCaptures() would never fire, permanently elevating - // captureCount on captured variables and leaking blessed objects. - // The null check on capturedScalars ensures we only fire once - // (releaseCaptures sets capturedScalars=null to prevent re-entry). + // A temporary CODE scalar may reach scope exit without passing + // through setLargeRefCounted. Ask the CODE owner ledger to retire + // its captures; the request waits for active, pending, or durable + // owners and does not trust the compatibility count. if (scalar.type == RuntimeScalarType.CODE && scalar.value instanceof RuntimeCode code - && code.capturedScalars != null - && code.refCount == 0 - && !GlobalVariable.installedGlobalCodeRefsView().contains(code)) { - code.releaseCaptures(); + && (code.capturedScalars != null || code.capturedAggregates != null)) { + code.requestCaptureReleaseWhenUnowned(); } return; } scalar.releaseOwnedScalarReferenceContents(); + scalar.releaseUnownedClosureCaptures(); + + // RuntimeCode captures carry one SCALAR_CAPTURE owner identity each. + // Retire any remaining compatibility-only capture counts here: they + // have no CODE slot that could keep the pad alive or release the + // count later. Live closures remain protected by their explicit slots. + while (scalar.legacyCaptureOwnerCount() > 0) { + scalar.releaseClosureCapture(); + } + scalar.verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE); // If this variable is captured by a closure, mark it so releaseCaptures // knows the scope has exited. But still proceed with refCount cleanup below // so that blessed ref refCounts and weak refs are handled properly. - if (scalar.captureCount > 0) { - // Self-referential capture cycle detection: if this variable holds - // a CODE ref that captures this same variable, we have a cycle that - // will never resolve on its own. This happens when eval STRING creates - // closures that capture ALL visible lexicals (including the variable - // the closure is assigned to). Break the cycle by decrementing our own - // captureCount and removing ourselves from the CODE's captures array. - // The full release of other captures will happen when the CODE ref's - // refCount reaches 0 (via callDestroy/releaseCaptures). - if (scalar.type == RuntimeScalarType.CODE - && scalar.value instanceof RuntimeCode code - && code.capturedScalars != null) { - boolean selfRef = false; - for (RuntimeScalar s : code.capturedScalars) { - if (s == scalar) { selfRef = true; break; } - } - if (selfRef) { - // Decrement our captureCount (the closure captured us) - scalar.releaseClosureCapture(); - // Remove self from capturedScalars to prevent double-decrement - // when releaseCaptures runs later during CODE ref destruction - RuntimeScalar[] old = code.capturedScalars; - if (old.length == 1) { - code.capturedScalars = null; - } else { - RuntimeScalar[] updated = new RuntimeScalar[old.length - 1]; - int j = 0; - for (RuntimeScalar cap : old) { - if (cap != scalar && j < updated.length) updated[j++] = cap; - } - code.capturedScalars = updated; - } - } - } + if (scalar.hasClosureCaptureOwner()) { // Mark that this variable's scope has exited. When releaseCaptures // later decrements captureCount to 0, it will know the scope is gone. scalar.scopeExited = true; - if (scalar.type != RuntimeScalarType.CODE) { - MortalList.noteDeferredScopeExitCaptureCandidate(scalar); - } // For CODE refs: still decrement the VALUE's refCount so the RuntimeCode // is eventually destroyed and its releaseCaptures fires (decrementing // captureCount on all the variables IT captured). This is critical for @@ -5382,48 +7204,52 @@ public static void scopeExitCleanup(RuntimeScalar scalar) { // when the same referent is on the JVM stack as a return value. MortalList.deferDecrementIfTracked(scalar); - // WEAKLY_TRACKED objects: do NOT clear weak refs on scope exit. - // These objects transitioned from untracked (-1) to WEAKLY_TRACKED (-2) in + // The lexical may have owned this cell when the initial refresh ran. + // Recheck after scope-exit state changes so its untracked value leaves + // with the final scalar-cell owner instead of waiting for graph cleanup. + scalar.finalizeUntrackedValueAfterScopeExit(untrackedValueAtScopeExit); + + // Weak-tracked objects: do NOT clear weak refs on scope exit. + // These objects transitioned from untracked state during weaken() and // weaken(), but scope exit of ONE reference doesn't mean no other strong // references exist — closures may capture copies of the same reference // (e.g., Sub::Quote's $_QUOTED capture keeps $quoted_info alive even after // unquote_sub's local exits scope). Clearing weak refs here would break // Sub::Quote/Moo constructor inlining. - // Weak refs for WEAKLY_TRACKED objects are cleared only via: + // Weak refs for weak-tracked objects are cleared only via: // - explicit undefine() of a strong reference // Since unblessed objects have no DESTROY, delayed clearing is safe. } - /** Release one durable scalar slot's ownership of an unstashed IO glob. */ + /** Release one durable scalar slot's anonymous IO resource owner identity. */ public static void releaseIoOwner(RuntimeScalar scalar) { - if (scalar == null || !scalar.ioOwner) return; - scalar.ioOwner = false; - if (scalar.type == GLOBREFERENCE - && scalar.value instanceof RuntimeGlob glob - && isUnstashedIoGlob(glob)) { - RuntimeScalar ioSlot = glob.getIO(); - if (ioSlot != null && ioSlot.value instanceof RuntimeIO io - && !(io.ioHandle instanceof ClosedIOHandle)) { - if (glob.ioHolderCount > 0) { - glob.ioHolderCount--; - } - if (glob.ioHolderCount <= 0) { + IoOwnerRelease ownerRelease = releaseIoOwnerSlot(scalar); + finishIoOwnerRelease(ownerRelease); + } + + private static void finishIoOwnerRelease(IoOwnerRelease ownerRelease) { + if (ownerRelease != null) { + RuntimeGlob glob = ownerRelease.glob(); + if (ownerRelease.remainingHolders() <= 0 && isUnstashedIoGlob(glob)) { + RuntimeScalar ioSlot = glob.getIO(); + if (ioSlot != null && ioSlot.value instanceof RuntimeIO io + && !(io.ioHandle instanceof ClosedIOHandle)) { // Closing is required for stream sockets: merely dropping // the synthetic fileno does not send EOF to the peer. - // Other anonymous handles still encounter transient - // method-invocant cleanup paths that are not true Perl SV - // destruction, so retain their established unregister-only - // behavior until those aliases have dedicated ownership. + // Ordinary handles can still have transient IO::File + // aliases whose Perl ownership is not represented by this + // resource lease, so they keep the unregister-only path. if (isSocketIOHandle(io.ioHandle)) io.close(); else io.unregisterFileno(); } + GlobalVariable.retireHiddenIORef(glob.globName); } } } /** Release an IO owner only when its live handle is a stream/datagram socket. */ public static void releaseSocketIoOwner(RuntimeScalar scalar) { - if (scalar == null || !scalar.ioOwner || scalar.type != GLOBREFERENCE + if (scalar == null || !scalar.hasIoOwner() || scalar.type != GLOBREFERENCE || !(scalar.value instanceof RuntimeGlob glob) || !isUnstashedIoGlob(glob)) { return; @@ -5442,8 +7268,8 @@ && isSocketIOHandle(io.ioHandle)) { */ public static void releaseOrTransferSocketIoOwnerOnReturn( RuntimeScalar owner, RuntimeBase returned) { - if (owner == null || owner.captureCount > 0 - || !owner.ioOwner || owner.type != GLOBREFERENCE + if (owner == null || owner.hasClosureCaptureOwner() + || !owner.hasIoOwner() || owner.type != GLOBREFERENCE || !(owner.value instanceof RuntimeGlob glob) || !isUnstashedIoGlob(glob)) { return; @@ -5457,17 +7283,16 @@ public static void releaseOrTransferSocketIoOwnerOnReturn( RuntimeScalar recipient = returnedSocketScalar(returned, glob); if (recipient == owner) { owner.copiedFromArgumentFrame = null; - owner.containerOwner = null; + owner.reconcileContainerOwners(); return; } - if (recipient != null && !recipient.ioOwner) { - owner.ioOwner = false; - recipient.ioOwner = true; + if (recipient != null && !recipient.hasIoOwner()) { + transferIoOwner(owner, recipient); recipient.copiedFromArgumentFrame = null; // RuntimeCode.returnList wraps scalar returns in a temporary list. // The returned scalar is a movable value, not a durable element of // that temporary container; let the caller assignment take over. - recipient.containerOwner = null; + recipient.reconcileContainerOwners(); return; } releaseIoOwner(owner); @@ -5480,13 +7305,13 @@ public static void releaseOrTransferSocketIoOwnerOnReturn( */ public static void releaseIoOwnerPreservingReturned( RuntimeScalar owner, RuntimeBase returned) { - if (owner == null || !owner.ioOwner + if (owner == null || !owner.hasIoOwner() || owner.type != GLOBREFERENCE || !(owner.value instanceof RuntimeGlob glob) || !isUnstashedIoGlob(glob)) { return; } - boolean capturedOwner = owner.captureCount > 0; + boolean capturedOwner = owner.hasClosureCaptureOwner(); boolean returnedOwner = false; if (returned != null) { for (RuntimeScalar alias : returnedIoAliases(returned, glob)) { @@ -5506,7 +7331,7 @@ public static void releaseIoOwnerPreservingReturned( /** Move an anonymous-IO holder token to the final scalar copy returned to a caller. */ public static void transferIoOwnerToReturnedCopy( RuntimeScalar source, RuntimeScalar returnedCopy) { - if (source == null || returnedCopy == null || !source.ioOwner + if (source == null || returnedCopy == null || !source.hasIoOwner() || source.type != GLOBREFERENCE || returnedCopy.type != GLOBREFERENCE || source.value != returnedCopy.value @@ -5514,10 +7339,9 @@ public static void transferIoOwnerToReturnedCopy( || !isUnstashedIoGlob(glob)) { return; } - source.ioOwner = false; - returnedCopy.ioOwner = true; + transferIoOwner(source, returnedCopy); returnedCopy.copiedFromArgumentFrame = null; - returnedCopy.containerOwner = null; + returnedCopy.reconcileContainerOwners(); } private static java.util.List returnedIoAliases( @@ -5583,7 +7407,13 @@ private static boolean isAcceptedSocket(RuntimeScalar scalar) { } private static boolean isUnstashedIoGlob(RuntimeGlob glob) { - return glob.globName == null || !GlobalVariable.existsGlobalIO(glob.globName); + // Symbol::gensym deliberately keeps a hidden lookup entry while + // scalar IO holders are live. That entry is a lifetime index, not a + // Perl stash owner; the final holder must still close the resource and + // retire the hidden entry. + return glob.symbolGensym + || glob.globName == null + || !GlobalVariable.existsGlobalIO(glob.globName); } private static boolean hasLiveIo(RuntimeGlob glob) { @@ -5625,6 +7455,7 @@ public RuntimeScalar preAutoIncrement() { result = preAutoIncrementWithoutWatcherNotification(); } finally { watcherMutationDepth--; + refreshArgumentAliasOwnerSlots(); } notifyModifiedWatchers(); return result; @@ -5787,6 +7618,7 @@ public RuntimeScalar postAutoIncrement() { result = postAutoIncrementWithoutWatcherNotification(); } finally { watcherMutationDepth--; + refreshArgumentAliasOwnerSlots(); } notifyModifiedWatchers(); return result; @@ -5815,6 +7647,7 @@ public void postAutoIncrementVoid() { } } finally { watcherMutationDepth--; + refreshArgumentAliasOwnerSlots(); } if (completed) notifyModifiedWatchers(); } @@ -5827,6 +7660,7 @@ public RuntimeScalar integerPreAutoIncrement() { result = integerAutoIncrement(false, 1); } finally { watcherMutationDepth--; + refreshArgumentAliasOwnerSlots(); } notifyModifiedWatchers(); return result; @@ -5840,6 +7674,7 @@ public RuntimeScalar integerPostAutoIncrement() { result = integerAutoIncrement(true, 1); } finally { watcherMutationDepth--; + refreshArgumentAliasOwnerSlots(); } notifyModifiedWatchers(); return result; @@ -5853,6 +7688,7 @@ public RuntimeScalar integerPreAutoDecrement() { result = integerAutoIncrement(false, -1); } finally { watcherMutationDepth--; + refreshArgumentAliasOwnerSlots(); } notifyModifiedWatchers(); return result; @@ -5866,6 +7702,7 @@ public RuntimeScalar integerPostAutoDecrement() { result = integerAutoIncrement(true, -1); } finally { watcherMutationDepth--; + refreshArgumentAliasOwnerSlots(); } notifyModifiedWatchers(); return result; @@ -6009,9 +7846,8 @@ private RuntimeScalar postAutoIncrementLarge() { // returned reference becomes the first durable owner. The // assignment receiving this scalar will balance the temporary // copy, so retain one cleanup token for that returned value. - old.refCountOwned = true; old.postfixReferenceOwnershipTransfer = true; - this.refCountOwned = false; + transferPostfixReferenceOwnerTo(old); // Check if object is eligible for overloading int blessId = blessedId(this); if (blessId != 0) { @@ -6075,6 +7911,7 @@ public RuntimeScalar preAutoDecrement() { result = preAutoDecrementWithoutWatcherNotification(); } finally { watcherMutationDepth--; + refreshArgumentAliasOwnerSlots(); } notifyModifiedWatchers(); return result; @@ -6229,6 +8066,7 @@ public RuntimeScalar postAutoDecrement() { result = postAutoDecrementWithoutWatcherNotification(); } finally { watcherMutationDepth--; + refreshArgumentAliasOwnerSlots(); } notifyModifiedWatchers(); return result; @@ -6318,9 +8156,8 @@ private RuntimeScalar postAutoDecrementWithoutWatcherNotification() { default -> { // All reference types // See postAutoIncrementLarge(): the returned pre-mutation // reference inherits this lvalue's ownership token. - old.refCountOwned = true; old.postfixReferenceOwnershipTransfer = true; - this.refCountOwned = false; + transferPostfixReferenceOwnerTo(old); // Check if object is eligible for overloading int blessId = blessedId(this); if (blessId != 0) { @@ -6471,7 +8308,11 @@ public void dynamicSaveState() { currentState.type = this.type; currentState.value = copyScalarPayload(this.type, this.value); currentState.blessId = this.blessId; - currentState.ownsScalarReferenceContents = this.ownsScalarReferenceContents; + currentState.scalarReferenceContentsOwner = this.scalarReferenceContentsOwner; + if (currentState.scalarReferenceContentsOwner != null) { + currentState.scalarReferenceContentsOwner.transferScalarReferenceContentsOwner( + currentState); + } currentState.referencedByScalarReference = this.referencedByScalarReference; currentState.tainted = this.tainted; currentState.numericLiteralText = this.numericLiteralText; @@ -6480,13 +8321,27 @@ public void dynamicSaveState() { currentState.firstClassRegexReferent = this.firstClassRegexReferent; currentState.firstClassRegexValue = this.firstClassRegexValue; currentState.formatPictureTainted = this.formatPictureTainted; + if (refCountOwned && countedOwnerSlot != null + && countedOwnerSlot.isActive() + && countedOwnerSlot.referent() == currentState.value) { + // local() changes the value in this same scalar cell. Carry the + // old counted edge with the saved state before a store can reuse + // this scalar's slot for the localized replacement. + currentState.localizedSavedCountedOwner = true; + transferCountedOwnerTo(currentState); + } + if (untrackedReferenceOwnerSlot != null + && untrackedReferenceOwnerSlot.isActive() + && untrackedReferenceOwnerSlot.referent() == currentState.value) { + transferUntrackedOwnerTo(currentState); + } // Push the current state onto the stack dynamicStateStack().push(currentState); // Clear the current type and value this.type = UNDEF; this.value = null; this.blessId = 0; - this.ownsScalarReferenceContents = false; + this.scalarReferenceContentsOwner = null; this.tainted = false; this.numericLiteralText = null; this.numericContextSeen = false; @@ -6494,6 +8349,8 @@ public void dynamicSaveState() { this.firstClassRegexReferent = null; this.firstClassRegexValue = null; this.formatPictureTainted = false; + refreshArgumentAliasOwnerSlots(); + refreshUntrackedReferenceOwner(); } /** @@ -6518,7 +8375,18 @@ public void dynamicRestoreState() { if (i != ownerIndex && owner.elements.get(i) == this) { // shift/unshift moved the localized SV. Detach the // current localized value before restoring this SV. - owner.elements.set(i, new RuntimeScalar(this)); + RuntimeScalar movedValue = new RuntimeScalar(this); + if (refCountOwned && countedOwnerSlot != null + && countedOwnerSlot.isActive() + && countedOwnerSlot.referent() == value) { + transferCountedOwnerTo(movedValue); + } + if (untrackedReferenceOwnerSlot != null + && untrackedReferenceOwnerSlot.isActive() + && untrackedReferenceOwnerSlot.referent() == value) { + transferUntrackedOwnerTo(movedValue); + } + owner.elements.set(i, movedValue); break; } } @@ -6526,49 +8394,82 @@ public void dynamicRestoreState() { boolean referencedDuringLocal = this.referencedByScalarReference; RuntimeBase displacedBase = null; - if ((this.type & RuntimeScalarType.REFERENCE_BIT) != 0 + if (((this.type & RuntimeScalarType.REFERENCE_BIT) != 0 + || this.type == RuntimeScalarType.GLOB + || this.type == RuntimeScalarType.CODE) && this.value instanceof RuntimeBase base) { displacedBase = base; } - RuntimeScalar scalarReferenceContents = scalarReferenceContentsReferent(this); - - // Restore the type, value from the saved state - this.type = previousState.type; - this.value = copyScalarPayload(previousState.type, previousState.value); - this.blessId = previousState.blessId; - this.ownsScalarReferenceContents = previousState.ownsScalarReferenceContents; - this.referencedByScalarReference = - previousState.referencedByScalarReference || referencedDuringLocal; - this.tainted = previousState.tainted; - this.numericLiteralText = previousState.numericLiteralText; - this.numericContextSeen = previousState.numericContextSeen; - this.firstClassRegexScalar = previousState.firstClassRegexScalar; - this.firstClassRegexReferent = previousState.firstClassRegexReferent; - this.firstClassRegexValue = previousState.firstClassRegexValue; - this.formatPictureTainted = previousState.formatPictureTainted; - if (owner != null) { - if (owner.scalarLocalContainerCleared()) { - while (owner.elements.size() < ownerSize) owner.elements.add(null); + boolean releaseDisplacedCountedOwner = displacedBase != null && refCountOwned; + if (releaseDisplacedCountedOwner + && (countedOwnerSlot == null || !countedOwnerSlot.isActive() + || countedOwnerSlot.referent() != displacedBase)) { + throw new IllegalStateException( + "localized scalar lost its counted owner before restore"); + } + if (releaseDisplacedCountedOwner) MortalList.pushMark(); + try { + if (releaseDisplacedCountedOwner) { + MortalList.deferDecrementFromScalarSlot( + displacedBase, this, "RuntimeScalar.dynamicRestoreState"); } - if (ownerExisted && ownerIndex < owner.elements.size() - && owner.elements.get(ownerIndex) != this) { - // Array mutations such as shift move the localized SV; - // restore its original slot while retaining the moved - // localized value at its current position. - owner.elements.set(ownerIndex, this); + PerlOwnerSlot displacedUntrackedOwner = this.untrackedReferenceOwnerSlot; + PerlOwnerSlot displacedScalarReferenceContentsOwner = + this.scalarReferenceContentsOwner; + + // Restore the type, value from the saved state + this.type = previousState.type; + this.value = copyScalarPayload(previousState.type, previousState.value); + this.refCountOwned = previousState.refCountOwned; + if (previousState.refCountOwned && previousState.countedOwnerSlot != null) { + previousState.transferCountedOwnerTo(this); + previousState.localizedSavedCountedOwner = false; + } + previousState.transferUntrackedOwnerTo(this); + this.blessId = previousState.blessId; + this.scalarReferenceContentsOwner = previousState.scalarReferenceContentsOwner; + previousState.scalarReferenceContentsOwner = null; + if (this.scalarReferenceContentsOwner != null) { + this.scalarReferenceContentsOwner.transferScalarReferenceContentsOwner(this); + } + this.referencedByScalarReference = + previousState.referencedByScalarReference || referencedDuringLocal; + this.tainted = previousState.tainted; + this.numericLiteralText = previousState.numericLiteralText; + this.numericContextSeen = previousState.numericContextSeen; + this.firstClassRegexScalar = previousState.firstClassRegexScalar; + this.firstClassRegexReferent = previousState.firstClassRegexReferent; + this.firstClassRegexValue = previousState.firstClassRegexValue; + this.formatPictureTainted = previousState.formatPictureTainted; + refreshArgumentAliasOwnerSlots(); + refreshUntrackedReferenceOwner(); + if (owner != null) { + if (owner.scalarLocalContainerCleared()) { + while (owner.elements.size() < ownerSize) owner.elements.add(null); + } + if (ownerExisted && ownerIndex < owner.elements.size() + && owner.elements.get(ownerIndex) != this) { + // Array mutations such as shift move the localized SV; + // restore its original slot while retaining the moved + // localized value at its current position. + owner.elements.set(ownerIndex, this); + } + owner.endScalarLocalElement(); } - owner.endScalarLocalElement(); - } - releaseScalarReferenceContents(scalarReferenceContents); + if (displacedScalarReferenceContentsOwner != null + && displacedScalarReferenceContentsOwner + != this.scalarReferenceContentsOwner) { + displacedScalarReferenceContentsOwner.releaseScalarReferenceContents(); + } + if (displacedUntrackedOwner != null + && displacedUntrackedOwner != this.untrackedReferenceOwnerSlot) { + releaseDetachedUntrackedOwner(displacedUntrackedOwner); + } - // Decrement refCount of the value displaced by local restoration - // after restoring the old scalar state, so DESTROY sees the restored - // variable rather than the dying localized value. - if (displacedBase != null - && displacedBase.refCount > 0 && --displacedBase.refCount == 0) { - displacedBase.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(displacedBase); + if (releaseDisplacedCountedOwner) MortalList.flushAboveMark(); + } finally { + if (releaseDisplacedCountedOwner) MortalList.popMark(); } } } @@ -6576,6 +8477,22 @@ public void dynamicRestoreState() { @Override public Object dynamicSuspendState() { RuntimeScalar activeState = new RuntimeScalar(this); + if (refCountOwned && countedOwnerSlot != null + && countedOwnerSlot.isActive() + && countedOwnerSlot.referent() == value) { + activeState.localizedSavedCountedOwner = true; + transferCountedOwnerTo(activeState); + } + if (untrackedReferenceOwnerSlot != null + && untrackedReferenceOwnerSlot.isActive() + && untrackedReferenceOwnerSlot.referent() == value) { + transferUntrackedOwnerTo(activeState); + } + activeState.scalarReferenceContentsOwner = this.scalarReferenceContentsOwner; + if (activeState.scalarReferenceContentsOwner != null) { + activeState.scalarReferenceContentsOwner.transferScalarReferenceContentsOwner(activeState); + } + this.scalarReferenceContentsOwner = null; dynamicRestoreState(); return activeState; } @@ -6586,12 +8503,24 @@ public void dynamicResumeState(Object token) { if (token instanceof RuntimeScalar activeState) { this.type = activeState.type; this.value = copyScalarPayload(activeState.type, activeState.value); + this.refCountOwned = activeState.refCountOwned; + if (activeState.refCountOwned && activeState.countedOwnerSlot != null) { + activeState.transferCountedOwnerTo(this); + activeState.localizedSavedCountedOwner = false; + } + activeState.transferUntrackedOwnerTo(this); this.blessId = activeState.blessId; - this.ownsScalarReferenceContents = activeState.ownsScalarReferenceContents; + this.scalarReferenceContentsOwner = activeState.scalarReferenceContentsOwner; + activeState.scalarReferenceContentsOwner = null; + if (this.scalarReferenceContentsOwner != null) { + this.scalarReferenceContentsOwner.transferScalarReferenceContentsOwner(this); + } this.referencedByScalarReference = activeState.referencedByScalarReference; this.tainted = activeState.tainted; this.numericLiteralText = activeState.numericLiteralText; this.numericContextSeen = activeState.numericContextSeen; + refreshArgumentAliasOwnerSlots(); + refreshUntrackedReferenceOwner(); } } @@ -6623,15 +8552,15 @@ public static void scopeExitCleanupPreservingReturnedLvalue(RuntimeScalar scalar * subroutine through the JVM return cleanup path. * *

    This deliberately does not release IO ownership, change - * {@link RuntimeGlob#ioHolderCount}, unregister the descriptor, or close the + * {@link RuntimeGlob#ioHolderCount()}, unregister the descriptor, or close the * handle. The general return path may still have a returned or otherwise * copied scalar pointing at the anonymous glob; those aliases are reflected * by a holder count greater than the lexical owner's single holder.

    */ public static void clearStaleDiagnosticContextForUnaliasedIO(RuntimeScalar scalar) { - if (scalar == null || !scalar.ioOwner || scalar.type != GLOBREFERENCE + if (scalar == null || !scalar.hasIoOwner() || scalar.type != GLOBREFERENCE || !(scalar.value instanceof RuntimeGlob glob) - || !isUnstashedIoGlob(glob) || glob.ioHolderCount > 1) { + || !isUnstashedIoGlob(glob) || glob.ioHolderCount() > 1) { return; } RuntimeScalar ioSlot = glob.getIO(); @@ -6647,8 +8576,9 @@ private static void cleanupScalarReferenceBinding(RuntimeScalar scalar) { return; } scalar.localBindingExists = false; - if (scalar.refCount == 0 && scalar.blessId != 0) { - scalar.refCount = Integer.MIN_VALUE; + if (scalar.isRefCountTracked() && scalar.refCount == 0 + && !scalar.hasScalarCellOwner() + && !scalar.hasUncountedPerlOwnerSlotIdentity()) { DestroyDispatch.callDestroy(scalar); } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeStash.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeStash.java index fae11442c4..75866e0256 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeStash.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeStash.java @@ -15,7 +15,8 @@ private static Stack dynamicStateStack() { // Map to store the elements of the hash public Map elements; public String namespace; - RuntimeGlob.NamespaceMove savedNamespaceMove; + RuntimeGlob savedNamespaceMove; + private PerlOwnerSlot savedNamespaceMoveOwnerSlot; // Iterator for traversing the hash elements Iterator hashIterator; @@ -33,6 +34,66 @@ public RuntimeStash(String namespace) { super.elements = this.elements; } + void saveNamespaceMove(RuntimeGlob moveOwner) { + PerlOwnerSlot nextOwner = null; + if (moveOwner != null) { + if (moveOwner.namespaceMove == null) { + throw new IllegalArgumentException("saved namespace move has no captured slots"); + } + nextOwner = new PerlOwnerSlot(PerlOwnerSlot.Kind.STASH_NAMESPACE_MOVE); + nextOwner.acquireStashNamespaceMoveIdentity(moveOwner); + } + + RuntimeGlob previousMove = savedNamespaceMove; + PerlOwnerSlot previousOwner = savedNamespaceMoveOwnerSlot; + savedNamespaceMove = moveOwner; + savedNamespaceMoveOwnerSlot = nextOwner; + if (previousOwner != null) previousOwner.release(); + if (previousMove != null && previousMove != moveOwner) { + previousMove.releaseDetachedComponentsIfUnowned(); + } + } + + void installSavedNamespaceMove(String destinationNamespace) { + RuntimeGlob moveOwner = savedNamespaceMove; + if (moveOwner == null) return; + RuntimeGlob.NamespaceMove move = moveOwner.namespaceMove; + if (move == null) { + releaseSavedNamespaceMove(); + return; + } + GlobalVariable.installNamespaceMove(move, destinationNamespace); + rebindNamespace(destinationNamespace); + releaseSavedNamespaceMove(); + } + + void installDetachedNamespaceMove(RuntimeGlob moveOwner, String destinationNamespace) { + try { + GlobalVariable.installNamespaceMove(moveOwner.namespaceMove, destinationNamespace); + rebindNamespace(destinationNamespace); + } finally { + moveOwner.releaseDetachedComponentsIfUnowned(); + } + } + + void releaseSavedNamespaceMove() { + RuntimeGlob moveOwner = savedNamespaceMove; + PerlOwnerSlot ownerSlot = savedNamespaceMoveOwnerSlot; + savedNamespaceMove = null; + savedNamespaceMoveOwnerSlot = null; + if (ownerSlot != null) ownerSlot.release(); + if (moveOwner != null) moveOwner.releaseDetachedComponentsIfUnowned(); + } + + void rebindNamespace(String destinationNamespace) { + String nextNamespace = destinationNamespace.endsWith("::") + ? destinationNamespace : destinationNamespace + "::"; + if (nextNamespace.equals(namespace)) return; + namespace = nextNamespace; + elements = new HashSpecialVariable(HashSpecialVariable.Id.STASH, namespace); + super.elements = elements; + } + /** * Creates a hash reference with the elements of a list. * @@ -99,7 +160,6 @@ public RuntimeList getList() { */ public void put(String key, RuntimeScalar value) { new RuntimeStashEntry(namespace + key, true).set(value); - GlobalVariable.invalidatePackageRootSnapshot(); } /** @@ -185,22 +245,30 @@ public RuntimeScalar exists(RuntimeScalar key) { */ @Override public RuntimeScalar delete(String key) { - return deleteGlob(key); + return deleteInContext(key, RuntimeContextType.LIST); } @Override public RuntimeScalar delete(RuntimeScalar key) { - return deleteGlob(key.toString()); + return deleteInContext(key, RuntimeContextType.LIST); } @Override public RuntimeScalar deleteInContext(RuntimeScalar key, int callContext) { - return delete(key); + return deleteInContext(key.toString(), callContext); } @Override public RuntimeScalar deleteInContext(String key, int callContext) { - return delete(key); + RuntimeScalar deleted = deleteGlob(key); + if (callContext == RuntimeContextType.VOID) { + // Stash deletion returns a detached glob that owns its captured + // slots. In void context there is no Perl value owner to release + // that glob later, so retire the temporary result here. + RuntimeScalar.scopeExitCleanup(deleted); + return new RuntimeScalar(); + } + return deleted; } private RuntimeScalar deleteGlob(String k) { @@ -234,54 +302,39 @@ private RuntimeScalar deleteGlob(String k) { RuntimeGlob savedIO = GlobalVariable.getExistingGlobalIO(fullKey); RuntimeScalar savedCode = GlobalVariable.globalCodeRefs.get(fullKey); - // Delete all slots from GlobalVariable. The CODE slot helper removes - // the visible stash entry while keeping already-pinned CVs alive for - // previously compiled call sites. + // Transfer the component slots to the detached glob before removing + // their package owners. The returned GV is the new strong owner of + // the cells and aggregates even when the old package scalar had the + // only counted edge to its referent. + RuntimeGlob detached = RuntimeGlob.createDetachedWithSlots( + savedScalar, savedArray, savedHash, savedIO, savedCode); + + // Delete all slots from GlobalVariable. The CODE slot helper transfers + // surviving compiled-call edges to their owning RuntimeCode objects. GlobalVariable.removeGlobalCodeRefForStashDelete(fullKey); GlobalVariable.clearGlobalPseudoConstant(fullKey); GlobalVariable.scalarSlots().remove(fullKey); GlobalVariable.detachScalarPin(fullKey, savedScalar); GlobalVariable.globalArrays.remove(fullKey); GlobalVariable.globalHashes.remove(fullKey); - if (savedIO != null) { + if (GlobalVariable.isSymbolGensymName(fullKey)) { + // The glob reference returned by Symbol::gensym remains live after + // this deletion. Mark that object as anonymous so later scalar, + // array, or hash dereferences stay on its local slots instead of + // recreating package roots under the generated name. + if (savedIO != null) savedIO.symbolGensym = true; + GlobalVariable.hideIORefAfterStashDelete(fullKey); + } else if (savedIO != null) { + // Symbol::gensym deletes the generated GV before its IO slot is + // installed. Remember the hidden identity even when this lookup + // table has not materialized the IO slot yet. GlobalVariable.hideIORefAfterStashDelete(fullKey); } GlobalVariable.globalFormatRefs.remove(fullKey); - GlobalVariable.invalidatePackageRootSnapshot(); - - // Clear weak refs when a reference-holding scalar is deleted from the stash. - // In Perl 5, removing a global variable drops the strong reference to its referent. - // If the referent's only strong ref was the global, its refcount reaches 0, the - // referent is freed, and all weak refs to it become undef. In PerlOnJava, the - // JVM keeps the referent alive, so we must manually clear weak refs. - // This is critical for Class::Unload + DBIC AccessorGroup reload pattern. - if (savedScalar != null && (savedScalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && savedScalar.value instanceof RuntimeBase base) { - if (base.refCount == WeakRefRegistry.WEAKLY_TRACKED) { - // Unblessed object with weak refs: clear all weak refs to it. - // Safe because unblessed objects have no DESTROY side effects. - base.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(base); - } else if (base.refCount > 0 && savedScalar.refCountOwned) { - // Tracked object: decrement refCount (the stash was holding a strong ref). - savedScalar.refCountOwned = false; - base.releaseActiveOwner(savedScalar); - if (--base.refCount == 0) { - base.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(base); - } - } - } // Removing symbols from a stash can affect method lookup. InheritanceResolver.invalidateCache(); - // Create a detached glob that holds the saved slot values including CODE. - // In Perl 5, delete $stash->{name} returns the glob with all its old slot values. - // Use globName=null so getGlobSlot() uses local slots instead of GlobalVariable. - RuntimeGlob detached = RuntimeGlob.createDetachedWithSlots( - savedScalar, savedArray, savedHash, savedIO, savedCode); - return detached; } @@ -306,6 +359,13 @@ private RuntimeScalar deleteNamespace(String k) { Map movedHashes = snapshotNamespace(GlobalVariable.globalHashes, childPrefix); Map movedCodes = snapshotNamespace(GlobalVariable.globalCodeRefs, childPrefix); + // Acquire detached-glob owners before removing the package-map owners + // below. The returned glob keeps each moved slot alive until its final + // Perl owner is released. + RuntimeGlob.NamespaceMove movedNamespace = new RuntimeGlob.NamespaceMove( + childPrefix, movedScalars, movedArrays, movedHashes, movedCodes); + RuntimeGlob detachedNamespace = RuntimeGlob.createDetachedNamespaceMove(movedNamespace); + // Remove all symbols with this prefix from all global maps (prefix-based removal) GlobalVariable.globalCodeRefs.keySet().removeIf(key -> key.startsWith(childPrefix)); GlobalVariable.globalCodeRefs.keySet().removeIf(key -> key.startsWith(mainQualifiedChildPrefix)); @@ -323,14 +383,11 @@ private RuntimeScalar deleteNamespace(String k) { GlobalVariable.globalFormatRefs.keySet().removeIf(key -> key.startsWith(mainQualifiedChildPrefix)); GlobalVariable.invalidateStashEnumerationCache(); GlobalVariable.clearHiddenIORefsForNamespace(childPrefix); - GlobalVariable.invalidatePackageRootSnapshot(); // A namespace can retain another effective name after `*two:: = // *one::`. Deleting one:: must not empty the stash still reachable // as two::. Materialise the saved slots under each such alias before // discarding the obsolete source mapping. - RuntimeGlob.NamespaceMove movedNamespace = new RuntimeGlob.NamespaceMove( - childPrefix, movedScalars, movedArrays, movedHashes, movedCodes); for (Map.Entry alias : new HashMap<>(GlobalVariable.stashAliases).entrySet()) { if (childPrefix.equals(alias.getValue())) { GlobalVariable.installNamespaceMove(movedNamespace, alias.getKey()); @@ -365,7 +422,7 @@ private RuntimeScalar deleteNamespace(String k) { GlobalVariable.clearPackageCache(); GlobalVariable.markStashPackageFreed(childPrefix); - return RuntimeGlob.createDetachedNamespaceMove(movedNamespace); + return detachedNamespace; } private static Map snapshotNamespace(Map values, String prefix) { @@ -521,6 +578,7 @@ public String dump() { * @return The current RuntimeStash instance after undefining its elements. */ public RuntimeStash undefine() { + releaseSavedNamespaceMove(); // Perl: undef %pkg:: clears the package symbol table and makes the stash anonymous. // We must remove all slots from the GlobalVariable maps, not just clear the view. String prefix = this.namespace; @@ -540,7 +598,6 @@ public RuntimeStash undefine() { GlobalVariable.globalFormatRefs.keySet().removeIf(k -> k.startsWith(prefix)); GlobalVariable.invalidateStashEnumerationCache(); GlobalVariable.clearHiddenIORefsForNamespace(prefix); - GlobalVariable.invalidatePackageRootSnapshot(); this.elements.clear(); @@ -593,7 +650,6 @@ public RuntimeArray setFromList(RuntimeList value) { GlobalVariable.globalFormatRefs.keySet().removeIf(k -> k.startsWith(prefix)); GlobalVariable.invalidateStashEnumerationCache(); GlobalVariable.clearHiddenIORefsForNamespace(prefix); - GlobalVariable.invalidatePackageRootSnapshot(); elements.clear(); InheritanceResolver.invalidateCache(); GlobalVariable.clearPackageCache(); diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeStashEntry.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeStashEntry.java index 1563ae6cf1..90a3fd890d 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeStashEntry.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeStashEntry.java @@ -80,6 +80,16 @@ public RuntimeGlob createStashIteratorCopy() { */ @Override public RuntimeScalar createReference() { + if (GlobalVariable.isSymbolGensymName(this.globName)) { + // A generated Symbol glob is represented by the canonical glob + // object that the caller keeps after deleting its stash entry. + // Materialize it here so deletion can mark that same object as an + // anonymous glob and keep later component accesses off package + // slot maps. + RuntimeGlob gensymGlob = GlobalVariable.getGlobalIO(this.globName); + gensymGlob.symbolGensym = true; + return gensymGlob.createReference(); + } RuntimeScalar pseudoConstant = GlobalVariable.getGlobalPseudoConstant(this.globName); RuntimeScalar codeSlot = GlobalVariable.globalCodeRefs.get(this.globName); diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeTiedArrayProxyEntry.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeTiedArrayProxyEntry.java index e0699c53cf..a8d14a2a01 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeTiedArrayProxyEntry.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeTiedArrayProxyEntry.java @@ -7,6 +7,9 @@ public class RuntimeTiedArrayProxyEntry extends TiedVariableBase { // Reference to the parent RuntimeArray (which is tied) private final RuntimeArray parent; + // Preserve the magic view captured when this lvalue was formed. untie may + // replace parent.elements while this proxy remains active in @_ . + private final TieArray tieHandle; // Index associated with this proxy in the parent array (already normalized) private final RuntimeScalar key; // Original (unnormalized) negative index, when the normalized key would still be @@ -24,6 +27,11 @@ public RuntimeTiedArrayProxyEntry(RuntimeArray parent, RuntimeScalar key) { this(parent, key, null); } + @Override + RuntimeBase argumentAliasContainer() { + return parent; + } + /** * Constructs a proxy that represents an out-of-range (still-negative after * normalization) subscript. Reads return undef without touching the tie @@ -32,14 +40,27 @@ public RuntimeTiedArrayProxyEntry(RuntimeArray parent, RuntimeScalar key) { public RuntimeTiedArrayProxyEntry(RuntimeArray parent, RuntimeScalar key, Integer outOfRangeOriginalIndex) { super(null, null); this.parent = parent; + this.tieHandle = parent.elements instanceof TieArray tieArray ? tieArray : null; this.key = key; this.outOfRangeOriginalIndex = outOfRangeOriginalIndex; } + @Override + RuntimeScalar retainArgumentAliasHandlerOwner() { + return tieHandle == null ? null + : RuntimeScalar.retainTiedHandlerValue(tieHandle.getSelf(), + PerlOwnerSlot.Kind.ARGUMENT_TIE_HANDLER); + } + /** * Vivifies the element by calling FETCH on the tied object. * This ensures lvalue is populated with the current value from the tied array. */ + @Override + RuntimeScalar storageOwnerReference() { + return parent.createAnonymousReference(); + } + @Override void vivify() { if (outOfRangeOriginalIndex != null) { @@ -50,7 +71,7 @@ void vivify() { return; } // Always fetch the current value from the tied object - RuntimeScalar fetchedValue = TieArray.tiedFetch(parent, key); + RuntimeScalar fetchedValue = tiedFetchFromAlias(); this.type = fetchedValue.type; this.value = fetchedValue.value; } @@ -68,7 +89,7 @@ public RuntimeScalar tiedStore(RuntimeScalar value) { "Modification of non-creatable array value attempted, subscript " + outOfRangeOriginalIndex); } - return TieArray.tiedStore(parent, key, value); + return tiedStoreFromAlias(value); } @Override @@ -76,6 +97,17 @@ public RuntimeScalar tiedFetch() { if (outOfRangeOriginalIndex != null) { return new RuntimeScalar(); } - return TieArray.tiedFetch(parent, key); + return tiedFetchFromAlias(); + } + + private RuntimeScalar tiedFetchFromAlias() { + return tieHandle == null ? TieArray.tiedFetch(parent, key) + : TieArray.tiedFetch(tieHandle, key); + } + + private RuntimeScalar tiedStoreFromAlias(RuntimeScalar value) { + parent.clearTiedLocalSizeOverride(); + return tieHandle == null ? TieArray.tiedStore(parent, key, value) + : TieArray.tiedStore(tieHandle, key, value); } -} \ No newline at end of file +} diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeTiedHashProxyEntry.java b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeTiedHashProxyEntry.java index ac8951d697..d0f232542b 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeTiedHashProxyEntry.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/RuntimeTiedHashProxyEntry.java @@ -15,6 +15,9 @@ private static Stack dynamicStateStack() { // Reference to the parent RuntimeHash (which is tied) private final RuntimeHash parent; + // Preserve the magic view captured when this lvalue was formed. untie may + // replace parent.elements while this proxy remains active in @_ . + private final TieHash tieHandle; // Index associated with this proxy in the parent array private final RuntimeScalar key; @@ -37,17 +40,35 @@ private static final class SavedState { public RuntimeTiedHashProxyEntry(RuntimeHash parent, RuntimeScalar key) { super(null, null); this.parent = parent; + this.tieHandle = parent.elements instanceof TieHash tieHash ? tieHash : null; this.key = key; } + @Override + RuntimeBase argumentAliasContainer() { + return parent; + } + + @Override + RuntimeScalar retainArgumentAliasHandlerOwner() { + return tieHandle == null ? null + : RuntimeScalar.retainTiedHandlerValue(tieHandle.getSelf(), + PerlOwnerSlot.Kind.ARGUMENT_TIE_HANDLER); + } + /** * Vivifies the element by calling FETCH on the tied object. * This ensures lvalue is populated with the current value from the tied array. */ + @Override + RuntimeScalar storageOwnerReference() { + return parent.createAnonymousReference(); + } + @Override void vivify() { // Always fetch the current value from the tied object - RuntimeScalar fetchedValue = TieHash.tiedFetch(parent, key); + RuntimeScalar fetchedValue = tiedFetchFromAlias(); this.type = fetchedValue.type; this.value = fetchedValue.value; } @@ -60,12 +81,12 @@ void vivify() { */ @Override public RuntimeScalar tiedStore(RuntimeScalar value) { - return TieHash.tiedStore(parent, key, value); + return tiedStoreFromAlias(value); } @Override public RuntimeScalar tiedFetch() { - return TieHash.tiedFetch(parent, key); + return tiedFetchFromAlias(); } @Override @@ -98,8 +119,8 @@ public RuntimeArray arrayDerefNonStrict(String packageName) { @Override public void dynamicSaveState() { - boolean existed = TieHash.tiedExists(parent, key).getBoolean(); - RuntimeScalar saved = existed ? new RuntimeScalar(TieHash.tiedFetch(parent, key)) : null; + boolean existed = tiedExistsFromAlias().getBoolean(); + RuntimeScalar saved = existed ? new RuntimeScalar(tiedFetchFromAlias()) : null; dynamicStateStack().push(new SavedState(existed, saved)); } @@ -111,9 +132,29 @@ public void dynamicRestoreState() { } SavedState previous = dynamicStateStack.pop(); if (previous.existed) { - TieHash.tiedStore(parent, key, new RuntimeScalar(previous.value)); + tiedStoreFromAlias(new RuntimeScalar(previous.value)); } else { - TieHash.tiedDelete(parent, key); + tiedDeleteFromAlias(); } } + + private RuntimeScalar tiedFetchFromAlias() { + return tieHandle == null ? TieHash.tiedFetch(parent, key) + : TieHash.tiedFetch(tieHandle, key); + } + + private RuntimeScalar tiedStoreFromAlias(RuntimeScalar value) { + return tieHandle == null ? TieHash.tiedStore(parent, key, value) + : TieHash.tiedStore(tieHandle, key, value); + } + + private RuntimeScalar tiedExistsFromAlias() { + return tieHandle == null ? TieHash.tiedExists(parent, key) + : TieHash.tiedExists(tieHandle, key); + } + + private RuntimeScalar tiedDeleteFromAlias() { + return tieHandle == null ? TieHash.tiedDelete(parent, key) + : TieHash.tiedDelete(tieHandle, key); + } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/ScalarRefRegistry.java b/src/main/java/org/perlonjava/runtime/runtimetypes/ScalarRefRegistry.java deleted file mode 100644 index 32200dea61..0000000000 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/ScalarRefRegistry.java +++ /dev/null @@ -1,236 +0,0 @@ -package org.perlonjava.runtime.runtimetypes; - -import java.lang.ref.ReferenceQueue; -import java.lang.ref.WeakReference; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Phase B1 of {@code dev/design/refcount_alignment_52leaks_plan.md}: - * tracks all {@link RuntimeScalar} instances currently holding a - * reference, keyed weakly so JVM GC can collect entries when the scalar - * itself becomes unreachable. - *

    - * Purpose: the {@link ReachabilityWalker} can't enumerate live - * JVM-call-stack lexicals directly. By tracking ref-holding scalars - * here with weak keys, a {@code System.gc()} followed by iteration of - * surviving entries gives the walker a Perl-compatible view of "what - * scalars are still alive in the call stack". - *

    - * The map is only populated when {@link WeakRefRegistry#weakRefsExist} - * is {@code true}, so non-{@code weaken()} programs pay zero cost. - *

    - * Thread-safety: not thread-safe. Matches PerlOnJava's single-threaded - * execution model (see {@code weaken-destroy.md} §5). - */ -public class ScalarRefRegistry { - - /** - * Weak identity keys with batched ReferenceQueue draining. Java 24's - * WeakHashMap polls its queue on every put, contending with the JVM - * reference-handler thread in allocation-heavy weaken() workloads. This - * map drains every 1024 registrations and before snapshots instead. - */ - static final class WeakIdentityMap { - private final Map entries = new HashMap<>(); - private final ReferenceQueue clearedKeys = new ReferenceQueue<>(); - private int registrations; - - void put(RuntimeScalar scalar, V value) { - entries.put(new IdentityWeakReference(scalar, clearedKeys), value); - // Amortize ReferenceQueue's monitor acquisition. WeakHashMap polls - // on every put; this workload creates enough references for that - // to contend heavily with the JVM reference-handler thread. - if ((++registrations & 1023) == 0) drainClearedKeys(); - } - - V get(RuntimeScalar scalar) { - return entries.get(new IdentityWeakReference(scalar, null)); - } - - List snapshotKeys() { - drainClearedKeys(); - List live = new ArrayList<>(entries.size()); - var iterator = entries.keySet().iterator(); - while (iterator.hasNext()) { - RuntimeScalar scalar = iterator.next().get(); - if (scalar == null) { - iterator.remove(); - } else { - live.add(scalar); - } - } - return live; - } - - int liveSize() { - return snapshotKeys().size(); - } - - void clear() { - entries.clear(); - while (clearedKeys.poll() != null) { - // Drain references whose map entries were just cleared. - } - registrations = 0; - } - - private void drainClearedKeys() { - IdentityWeakReference reference; - while ((reference = (IdentityWeakReference) clearedKeys.poll()) != null) { - entries.remove(reference); - } - } - } - - private static final class IdentityWeakReference extends WeakReference { - private final int identityHash; - - IdentityWeakReference( - RuntimeScalar scalar, ReferenceQueue clearedKeys) { - super(scalar, clearedKeys); - identityHash = System.identityHashCode(scalar); - } - - @Override - public int hashCode() { - return identityHash; - } - - @Override - public boolean equals(Object other) { - if (this == other) return true; - if (!(other instanceof IdentityWeakReference reference)) return false; - RuntimeScalar scalar = get(); - return scalar != null && scalar == reference.get(); - } - } - - // IdentityWeakReference preserves Object identity while allowing scalar - // wrappers to be reclaimed by JVM GC. - // Phase E: optional per-scalar registerRef call-site stacks. - // Populated only when JPERL_REGISTER_STACKS=1 is set. Uses a - // WeakHashMap with the same scalar as key, so entries are pruned - // automatically when the scalar is JVM-GC'd. Lookup via - // stackFor() is O(1). - private static LifecycleRuntimeState state() { - return PerlRuntime.current().lifecycleState; - } - - // Phase B1 performance toggle: when set, skip all registry - // maintenance. Useful for benchmarks; does NOT affect correctness - // for programs that don't use weaken() (no weak-ref registry = - // no sweep triggers = unused registry). - private static final boolean OPT_OUT = - System.getenv("JPERL_NO_SCALAR_REGISTRY") != null; - private static final boolean DEBUG = - System.getenv("JPERL_GC_DEBUG") != null; - private static final boolean RECORD_STACKS = - System.getenv("JPERL_REGISTER_STACKS") != null; - // Opt back to unconditional registration for scripts that weaken() - // after a long warm-up phase where many scalars were assigned. - private static final boolean UNGATED = - System.getenv("JPERL_UNGATED_SCALAR_REGISTRY") != null; - - /** - * Register a scalar that now holds a reference. Called from - * {@link RuntimeScalar#setLarge} paths that assign a ref value. - *

    - * Gated on {@link WeakRefRegistry#weakRefsExist}: this registry - * exists solely to feed {@link ReachabilityWalker#sweepWeakRefs} - * live-lexical seeds. If no weaken() has ever been called, no - * sweep will ever examine the registry, so registering is pure - * overhead — and it's a {@code synchronized(WeakHashMap).put} - * which is expensive per call. Life_bitpacked.pl profile showed - * this put path as the single largest post-compile hotspot. - *

    - * Trade-off: if a script holds many scalars-with-refs PRIOR to - * the first weaken(), those scalars won't be in the registry - * when the walker first runs. However, any subsequent - * {@code setLarge} on those scalars will register them, and the - * walker's primary seeds (globals, code refs, DESTROY rescued - * set) still find reachable structures via the normal BFS. - *

    - * Opt back to unconditional registration via - * {@code JPERL_UNGATED_SCALAR_REGISTRY=1} if needed. - */ - public static void registerRef(RuntimeScalar scalar) { - if (OPT_OUT || scalar == null) return; - if (!WeakRefRegistry.weakRefsExist() && !UNGATED) return; - state().scalarRegistry.put(scalar, Boolean.TRUE); - if (RECORD_STACKS) { - state().scalarRegisterStacks.put(scalar, new Throwable("registerRef")); - } - if (DEBUG) { - System.err.println("DBG registerRef scalar=" + System.identityHashCode(scalar) - + " type=" + scalar.type + " size=" + state().scalarRegistry.liveSize()); - } - } - - /** - * Phase E: return the call-site stack recorded at the time - * {@link #registerRef} was called for the given scalar. Returns - * {@code null} if no stack was recorded (either RECORD_STACKS is - * off, the scalar was never registered, or its entry was pruned - * by JVM GC). - */ - public static Throwable stackFor(RuntimeScalar sc) { - if (!RECORD_STACKS || sc == null) return null; - return state().scalarRegisterStacks.get(sc); - } - - /** - * Snapshot the current live set. Caller should invoke - * {@code System.gc()} beforehand if they want JVM GC to prune - * unreachable entries first (e.g., freshly-exited lexical scopes). - */ - public static java.util.List snapshot() { - return state().scalarRegistry.snapshotKeys(); - } - - /** - * Force JVM GC, wait briefly for finalization, then return a - * snapshot of still-live ref-holding scalars. Used by - * {@link ReachabilityWalker#sweepWeakRefs} to seed its walk with - * live call-stack lexicals. Idempotent but not cheap — bounded to - * a few hundred ms at most. - */ - public static java.util.List forceGcAndSnapshot() { - // Multiple GC cycles are sometimes needed: the first cycle may - // only clear one level of unreachable objects, exposing more - // for a subsequent pass. A WeakReference sentinel tells us - // when weak-ref processing has completed for a cycle. - for (int pass = 0; pass < 3; pass++) { - Object sentinel = new Object(); - WeakReference probe = new WeakReference<>(sentinel); - sentinel = null; // drop the only strong ref - for (int i = 0; i < 5; i++) { - System.gc(); - if (probe.get() == null) break; - try { - Thread.sleep(10); - } catch (InterruptedException ie) { - Thread.currentThread().interrupt(); - break; - } - } - } - return snapshot(); - } - - /** - * Test-only hook: how many entries does the registry currently - * hold? (Subject to JVM GC between calls.) - */ - public static int approximateSize() { - return state().scalarRegistry.liveSize(); - } - - /** Drop weak-key bookkeeping belonging to the previous top-level script. */ - public static void resetState() { - state().scalarRegistry.clear(); - state().scalarRegisterStacks.clear(); - } -} diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/SharedElementProxy.java b/src/main/java/org/perlonjava/runtime/runtimetypes/SharedElementProxy.java index b165c34421..2303234a7c 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/SharedElementProxy.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/SharedElementProxy.java @@ -12,14 +12,30 @@ final class SharedElementProxy extends RuntimeScalar { super(storage); this.storage = storage; this.value = localView; - // A fetched shared reference is a real, short-lived Perl proxy owner. - // Register that owner so releasing the proxy suppresses DESTROY on its - // runtime-local view while the canonical shared slot still exists. - RuntimeScalar.incrementRefCountForContainerStore(this); + // This wrapper is an expression/lvalue borrow. The receiving Perl slot + // acquires the local view's owner edge; counting the wrapper itself + // leaves an extra owner behind when the fetch result is weakened. + } + + /** + * An lvalue fetch is replaced through the canonical slot, so its local + * aggregate view is not copied into a Perl scalar owner. Retire that + * otherwise-unowned view before releasing the canonical slot; otherwise + * the shared lifecycle sees a permanent live view and defers DESTROY. + */ + private void retireUnownedFetchView() { + if (value instanceof RuntimeBase view + && view.threadSharedFetchedView + && view.isRefCountTracked() && view.refCount == 0) { + DestroyDispatch.callDestroy(view); + value = null; + type = RuntimeScalarType.UNDEF; + } } @Override public RuntimeScalar set(RuntimeScalar value) { + retireUnownedFetchView(); SharedPerlStorage.publishBlessing(value); // The proxy is a transient FETCH view, not a second Perl scalar slot. // Updating it through RuntimeScalar.set() would acquire a second @@ -31,11 +47,13 @@ public RuntimeScalar set(RuntimeScalar value) { @Override public RuntimeScalar undefine() { + retireUnownedFetchView(); return storage.undefine(); } @Override public RuntimeScalar createReference() { + retireUnownedFetchView(); return storage.createReference(); } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/SharedPerlStorage.java b/src/main/java/org/perlonjava/runtime/runtimetypes/SharedPerlStorage.java index adc08d660d..8c21769176 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/SharedPerlStorage.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/SharedPerlStorage.java @@ -426,8 +426,7 @@ private static void markGraph(RuntimeBase value, Set seen) { // threads::shared replaces an existing aggregate tie with its // own shared storage without invoking CLEAR or UNTIE. if (array.elements instanceof TieArray tie) tie.releaseTiedObject(); - array.type = RuntimeArray.PLAIN_ARRAY; - array.elements = Collections.synchronizedList(new ArrayList<>()); + array.replaceWithEmptySharedStorage(); markShared(array); return; } @@ -439,9 +438,7 @@ private static void markGraph(RuntimeBase value, Set seen) { if (value instanceof RuntimeHash hash) { if (hash.type == RuntimeHash.TIED_HASH) { if (hash.elements instanceof TieHash tie) tie.releaseTiedObject(); - hash.type = RuntimeHash.PLAIN_HASH; - hash.elements = Collections.synchronizedMap(new StableHashMap<>()); - hash.resetIterator(); + hash.replaceWithEmptySharedStorage(); markShared(hash); return; } @@ -475,6 +472,10 @@ static RuntimeScalar fetchedElement(RuntimeBase owner, RuntimeScalar stored) { PerlRuntime runtime = PerlRuntime.current(); RuntimeBase view = new RuntimeGraphCloner(runtime, runtime).cloneGraph(nested); view.threadSharedFetchedView = true; + // The fetched view can be discarded before any receiving scalar slot + // stores it. Register the local view now so its first release is + // classified as a view cleanup rather than canonical shared DESTROY. + view.registerSharedFetchedView(); return new SharedElementProxy(stored, view); } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/SpecialBlock.java b/src/main/java/org/perlonjava/runtime/runtimetypes/SpecialBlock.java index aa9041cc62..8b2b2916a1 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/SpecialBlock.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/SpecialBlock.java @@ -57,11 +57,26 @@ public static void saveEndBlock(RuntimeScalar codeRef) { RuntimeArray.unshift(getEndBlocks(), codeRef); } - /** Return whether {@code code} still has an owning slot in the END queue. */ + /** Return whether {@code code} still has a current strong slot in the END queue. */ static boolean hasPendingEndBlock(RuntimeCode code) { if (code == null) return false; - for (RuntimeScalar block : getEndBlocks().elements) { - if (block != null && block.value == code) return true; + RuntimeArray endBlocks = getEndBlocks(); + for (RuntimeScalar block : endBlocks.elements) { + if (block == null || block.value != code || block.containerOwner != endBlocks + || !endBlocks.elements.contains(block)) { + continue; + } + if (RuntimeArray.hasCurrentCountedArrayElementOwner(endBlocks, block)) { + return true; + } + PerlOwnerSlot untracked = block.untrackedReferenceOwnerSlot(); + if (untracked != null + && untracked.kind() == PerlOwnerSlot.Kind.UNTRACKED_REFERENCE + && untracked.isActive() + && untracked.referent() == code + && untracked.untrackedScalarOwner() == block) { + return true; + } } return false; } @@ -102,25 +117,35 @@ public static Throwable runEndBlocks(boolean resetChildStatus) { Throwable firstFailure = null; RuntimeArray endBlocks = getEndBlocks(); while (!endBlocks.isEmpty()) { - RuntimeScalar block = RuntimeArray.shift(endBlocks); - if (block.getDefinedBoolean()) { - RuntimeCode code = block.value instanceof RuntimeCode runtimeCode ? runtimeCode : null; - if (code != null) code.beginEndBlockExecution(); - try { + RuntimeScalar queuedBlock = endBlocks.elements.getFirst(); + RuntimeCode queuedCode = queuedBlock != null + && queuedBlock.value instanceof RuntimeCode runtimeCode + ? runtimeCode : null; + // Transfer lifetime across shift: releasing the array-element + // owner can run deferred CODE cleanup before RuntimeCode.apply() + // installs its ordinary active-frame identity. + PerlOwnerSlot executionOwner = null; + if (queuedCode != null) { + executionOwner = new PerlOwnerSlot(PerlOwnerSlot.Kind.ACTIVE_CODE); + executionOwner.acquireActiveCodeIdentity(queuedCode); + } + try { + RuntimeScalar block = RuntimeArray.shift(endBlocks); + if (block.getDefinedBoolean()) { RuntimeCode.apply(block, new RuntimeArray(), RuntimeContextType.VOID); - } catch (PerlExitException exit) { - // exit() recursively drains the remaining queue. It is a - // control signal, not a failing END callback. - throw exit; - } catch (Throwable failure) { - if (firstFailure == null) firstFailure = failure; - String message = ErrorMessageUtil.stringifyException(failure); - System.err.print(message); - if (!message.endsWith("\n")) System.err.println(); - System.err.println("END failed--call queue aborted."); - } finally { - if (code != null) code.endEndBlockExecution(); } + } catch (PerlExitException exit) { + // exit() recursively drains the remaining queue. It is a + // control signal, not a failing END callback. + throw exit; + } catch (Throwable failure) { + if (firstFailure == null) firstFailure = failure; + String message = ErrorMessageUtil.stringifyException(failure); + System.err.print(message); + if (!message.endsWith("\n")) System.err.println(); + System.err.println("END failed--call queue aborted."); + } finally { + if (executionOwner != null) executionOwner.release(); } } return firstFailure; diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/StateVariable.java b/src/main/java/org/perlonjava/runtime/runtimetypes/StateVariable.java index dd50aaa62f..331708014d 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/StateVariable.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/StateVariable.java @@ -130,8 +130,12 @@ public static RuntimeScalar retrieveStateScalar(RuntimeScalar codeRef, String va return tagGeneratedLexicalSub(GlobalVariable.getGlobalVariable(beginVar), var); } variable = new RuntimeScalar(); - code.stateVariable.put(beginVar, variable); - GlobalVariable.invalidateGlobalCodeRefGraphRoots(); + // The persistent pad is a binding even though this SV is not on + // the per-invocation lexical cleanup stack. A returned \$state + // must keep the cell's value after the CV releases that binding. + variable.startRefCountTracking(); + variable.localBindingExists = true; + code.bindStateScalar(beginVar, variable); return tagGeneratedLexicalSub(variable, var); } } @@ -185,8 +189,7 @@ public static RuntimeArray retrieveStateArray(RuntimeScalar codeRef, String var, return GlobalVariable.getGlobalArray(beginVar); } variable = new RuntimeArray(); - code.stateArray.put(beginVar, variable); - GlobalVariable.invalidateGlobalCodeRefGraphRoots(); + code.bindStateArray(beginVar, variable); return variable; } } @@ -197,8 +200,7 @@ public static void aliasStateArray(RuntimeScalar codeRef, String var, int id, Ru if (!codeRef.getDefinedBoolean()) { GlobalVariable.aliasGlobalArray(beginVar, array); } else { - ((RuntimeCode) codeRef.value).stateArray.put(beginVar, array); - GlobalVariable.invalidateGlobalCodeRefGraphRoots(); + ((RuntimeCode) codeRef.value).bindStateAggregateAlias(beginVar, array); } markInitializedStateVariable(codeRef, var, id); } @@ -222,8 +224,7 @@ public static void aliasStateHash(RuntimeScalar codeRef, String var, int id, Run if (!codeRef.getDefinedBoolean()) { GlobalVariable.aliasGlobalHash(beginVar, hash); } else { - ((RuntimeCode) codeRef.value).stateHash.put(beginVar, hash); - GlobalVariable.invalidateGlobalCodeRefGraphRoots(); + ((RuntimeCode) codeRef.value).bindStateAggregateAlias(beginVar, hash); } markInitializedStateVariable(codeRef, var, id); } @@ -289,8 +290,7 @@ public static RuntimeHash retrieveStateHash(RuntimeScalar codeRef, String var, i return GlobalVariable.getGlobalHash(beginVar); } variable = new RuntimeHash(); - code.stateHash.put(beginVar, variable); - GlobalVariable.invalidateGlobalCodeRefGraphRoots(); + code.bindStateHash(beginVar, variable); return variable; } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/TieArray.java b/src/main/java/org/perlonjava/runtime/runtimetypes/TieArray.java index 90b878caf5..b09a92ea93 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/TieArray.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/TieArray.java @@ -62,28 +62,30 @@ public class TieArray extends ArrayList { public TieArray(String tiedPackage, RuntimeArray previousValue, RuntimeScalar self, RuntimeArray parent) { this.tiedPackage = tiedPackage; this.previousValue = previousValue; - this.self = self; + this.self = RuntimeScalar.retainTiedHandlerValue(self); this.parent = parent; - // Increment refCount: the tie wrapper holds a strong reference to the tied object. - if (self != null && (self.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && self.value instanceof RuntimeBase base - && base.refCount >= 0) { - base.refCount++; - base.acquireTransientTraceOwner("tie wrapper", "TieArray"); - } + } /** * Helper method to call methods on the tied object. */ private static RuntimeList tieCall(RuntimeArray array, String method, RuntimeBase... args) { - return tieCall(array, method, RuntimeContextType.SCALAR, args); + return tieCall((TieArray) array.elements, method, RuntimeContextType.SCALAR, args); } private static RuntimeList tieCall(RuntimeArray array, String method, int ctx, RuntimeBase... args) { - TieArray tieArray = (TieArray) array.elements; + return tieCall((TieArray) array.elements, method, ctx, args); + } + + private static RuntimeList tieCall( + TieArray tieArray, String method, RuntimeBase... args) { + return tieCall(tieArray, method, RuntimeContextType.SCALAR, args); + } + + private static RuntimeList tieCall( + TieArray tieArray, String method, int ctx, RuntimeBase... args) { RuntimeScalar self = tieArray.getSelf(); - String className = tieArray.getTiedPackage(); // Call the Perl method return RuntimeCode.call( @@ -127,6 +129,11 @@ public static RuntimeScalar tiedFetch(RuntimeArray array, RuntimeScalar index) { return tieCall(array, "FETCH", index).getFirst(); } + /** Fetch through the tie magic captured by an element alias before untie. */ + public static RuntimeScalar tiedFetch(TieArray tieArray, RuntimeScalar index) { + return tieCall(tieArray, "FETCH", index).getFirst(); + } + /** * Stores an element into a tied array (delegates to STORE). */ @@ -135,6 +142,12 @@ public static RuntimeScalar tiedStore(RuntimeArray array, RuntimeScalar index, R return tieCall(array, "STORE", index, value).getFirst(); } + /** Store through the tie magic captured by an element alias before untie. */ + public static RuntimeScalar tiedStore( + TieArray tieArray, RuntimeScalar index, RuntimeScalar value) { + return tieCall(tieArray, "STORE", index, value).getFirst(); + } + /** * Gets the size of a tied array (delegates to FETCHSIZE). */ @@ -290,6 +303,16 @@ public int size() { return tiedFetchSize(parent).getInt(); } + /** Returns the locally stored slots without invoking tied FETCHSIZE. */ + int rawStorageSize() { + return super.size(); + } + + /** Returns a locally stored slot without invoking tied FETCH. */ + RuntimeScalar rawStorageGet(int index) { + return super.get(index); + } + public RuntimeScalar get(int i) { return parent.get(i); } @@ -302,13 +325,6 @@ public void releaseTiedObject() { if (tiedObjectReleased) return; tiedObjectReleased = true; if (self == null) return; - if ((self.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && self.value instanceof RuntimeBase base) { - base.releaseTransientTraceOwner("tie wrapper", "TieArray"); - if (base.refCount > 0 && --base.refCount == 0) { - base.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(base); - } - } + RuntimeScalar.releaseTiedHandlerValue(self); } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/TieHandle.java b/src/main/java/org/perlonjava/runtime/runtimetypes/TieHandle.java index cf68a57ad4..568fc3d18d 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/TieHandle.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/TieHandle.java @@ -36,6 +36,7 @@ public class TieHandle extends RuntimeIO { */ private final RuntimeScalar self; private final boolean holdsSelfReference; + private boolean tiedObjectReleased; /** * The package name that this handle is tied to. @@ -61,16 +62,9 @@ public TieHandle(String tiedPackage, RuntimeIO previousValue, RuntimeScalar self public TieHandle(String tiedPackage, RuntimeIO previousValue, RuntimeScalar self, boolean holdSelfReference) { this.tiedPackage = tiedPackage; this.previousValue = previousValue; - this.self = self; + this.self = holdSelfReference ? RuntimeScalar.retainTiedHandlerValue(self) : self; this.holdsSelfReference = holdSelfReference; - // Increment refCount: the tie wrapper holds a strong reference to the tied object. - if (holdSelfReference - && self != null && (self.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && self.value instanceof RuntimeBase base - && base.refCount >= 0) { - base.refCount++; - base.acquireTransientTraceOwner("tie wrapper", "TieHandle"); - } + } /** @@ -355,16 +349,8 @@ public String toString() { * Decrements refCount and triggers DESTROY if it reaches 0. */ public void releaseTiedObject() { - if (!holdsSelfReference) { - return; - } - if ((self.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && self.value instanceof RuntimeBase base) { - base.releaseTransientTraceOwner("tie wrapper", "TieHandle"); - if (base.refCount > 0 && --base.refCount == 0) { - base.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(base); - } - } + if (!holdsSelfReference || tiedObjectReleased) return; + tiedObjectReleased = true; + RuntimeScalar.releaseTiedHandlerValue(self); } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/TieHash.java b/src/main/java/org/perlonjava/runtime/runtimetypes/TieHash.java index 606b040e05..c01f749c95 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/TieHash.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/TieHash.java @@ -54,27 +54,18 @@ public class TieHash extends HashMap { public TieHash(String tiedPackage, RuntimeHash previousValue, RuntimeScalar self) { this.tiedPackage = tiedPackage; this.previousValue = previousValue; - this.self = self; - // Increment refCount: the tie wrapper holds a strong reference to the tied object. - if (self != null && (self.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && self.value instanceof RuntimeBase base - && base.refCount >= 0) { - base.refCount++; - base.acquireTransientTraceOwner("tie wrapper", "TieHash"); - } - if (self != null && (self.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && self.value instanceof RuntimeBase base) { - base.markPossiblyStoredInTiedHandler(); - } + this.self = RuntimeScalar.retainTiedHandlerValue(self); } /** * Helper method to call methods on the tied object. */ private static RuntimeScalar tieCall(RuntimeHash hash, String method, RuntimeBase... args) { - TieHash tieHash = (TieHash) hash.elements; + return tieCall((TieHash) hash.elements, method, args); + } + + private static RuntimeScalar tieCall(TieHash tieHash, String method, RuntimeBase... args) { RuntimeScalar self = tieHash.getSelf(); - String className = tieHash.getTiedPackage(); // Call the Perl method return RuntimeCode.call( @@ -128,6 +119,11 @@ public static RuntimeScalar tiedFetch(RuntimeHash hash, RuntimeScalar key) { return tieCall(hash, "FETCH", key); } + /** Fetch through the tie magic captured by an element alias before untie. */ + public static RuntimeScalar tiedFetch(TieHash tieHash, RuntimeScalar key) { + return tieCall(tieHash, "FETCH", key); + } + /** * Stores a value into a tied hash (delegates to STORE). */ @@ -135,6 +131,12 @@ public static RuntimeScalar tiedStore(RuntimeHash hash, RuntimeScalar key, Runti return tieCall(hash, "STORE", key, value); } + /** Store through the tie magic captured by an element alias before untie. */ + public static RuntimeScalar tiedStore( + TieHash tieHash, RuntimeScalar key, RuntimeScalar value) { + return tieCall(tieHash, "STORE", key, value); + } + /** * Deletes a key from a tied hash (delegates to DELETE). */ @@ -142,6 +144,11 @@ public static RuntimeScalar tiedDelete(RuntimeHash hash, RuntimeScalar key) { return tieCall(hash, "DELETE", key); } + /** Delete through the tie magic captured by an element alias before untie. */ + public static RuntimeScalar tiedDelete(TieHash tieHash, RuntimeScalar key) { + return tieCall(tieHash, "DELETE", key); + } + /** * Checks if a key exists in a tied hash (delegates to EXISTS). */ @@ -151,6 +158,13 @@ public static RuntimeScalar tiedExists(RuntimeHash hash, RuntimeScalar key) { : RuntimeScalarCache.scalarEmptyString; } + /** Check a key through the tie magic captured by an element alias before untie. */ + public static RuntimeScalar tiedExists(TieHash tieHash, RuntimeScalar key) { + return tieCall(tieHash, "EXISTS", key).getBoolean() + ? RuntimeScalarCache.scalarOne + : RuntimeScalarCache.scalarEmptyString; + } + /** * Gets the first key for iterating over a tied hash (delegates to FIRSTKEY). */ @@ -230,13 +244,6 @@ public void releaseTiedObject() { if (tiedObjectReleased) return; tiedObjectReleased = true; if (self == null) return; - if ((self.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && self.value instanceof RuntimeBase base) { - base.releaseTransientTraceOwner("tie wrapper", "TieHash"); - if (base.refCount > 0 && --base.refCount == 0) { - base.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(base); - } - } + RuntimeScalar.releaseTiedHandlerValue(self); } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/TiedVariableBase.java b/src/main/java/org/perlonjava/runtime/runtimetypes/TiedVariableBase.java index ef0b83f7bc..fec406a7fd 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/TiedVariableBase.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/TiedVariableBase.java @@ -35,20 +35,9 @@ public abstract class TiedVariableBase extends RuntimeBaseProxy { */ public TiedVariableBase(RuntimeScalar tiedObject, String tiedPackage) { super(); - this.self = tiedObject; + this.self = RuntimeScalar.retainTiedHandlerValue(tiedObject); this.tiedPackage = tiedPackage; - // The tie wrapper holds a strong reference to the tied object. - // Increment refCount so that untie's decrement can trigger DESTROY - // when no other references remain (matching Perl 5 behavior). - // Note: tiedObject is null for proxy entries (RuntimeTiedHashProxyEntry, - // RuntimeTiedArrayProxyEntry) which delegate to the parent container. - if (tiedObject != null - && (tiedObject.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && tiedObject.value instanceof RuntimeBase base - && base.refCount >= 0) { - base.refCount++; - base.acquireTransientTraceOwner("tie wrapper", "TiedVariableBase"); - } + } /** @@ -212,6 +201,11 @@ public RuntimeScalar addToScalar(RuntimeScalar v) { return super.addToScalar(v); } + /** Storage kept alive by an escaping magic lvalue; this is a borrowed reference. */ + RuntimeScalar storageOwnerReference() { + return self; + } + public RuntimeScalar getSelf() { return self; } @@ -231,13 +225,6 @@ public void releaseTiedObject() { // Array/hash element proxy entries delegate to their parent tied // container and intentionally have no handler of their own. if (self == null) return; - if ((self.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && self.value instanceof RuntimeBase base) { - base.releaseTransientTraceOwner("tie wrapper", "TiedVariableBase"); - if (base.refCount > 0 && --base.refCount == 0) { - base.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(base); - } - } + RuntimeScalar.releaseTiedHandlerValue(self); } } diff --git a/src/main/java/org/perlonjava/runtime/runtimetypes/WeakRefRegistry.java b/src/main/java/org/perlonjava/runtime/runtimetypes/WeakRefRegistry.java index 5811970656..7bc445b0dd 100644 --- a/src/main/java/org/perlonjava/runtime/runtimetypes/WeakRefRegistry.java +++ b/src/main/java/org/perlonjava/runtime/runtimetypes/WeakRefRegistry.java @@ -13,6 +13,9 @@ */ public class WeakRefRegistry { + /** Numeric compatibility marker for tests of the weakly tracked state. */ + public static final int WEAKLY_TRACKED = 0; + private static LifecycleRuntimeState state() { return PerlRuntime.current().lifecycleState; } @@ -31,26 +34,10 @@ public static boolean weakRefsExist() { return state().weakRefsExist; } - /** - * Special refCount value for objects that have weak refs but whose strong - * refs can't be counted accurately. Used in two cases: - *

    - * 1. Unblessed birth-tracked objects (refCount started at 0) with blessId == 0, - * where closure captures and temporary copies bypass {@code setLarge()}, - * making refCount unreliable. - *

    - * 2. Untracked non-CODE objects (refCount == -1) that acquire weak refs via - * {@code weaken()}. These are transitioned to WEAKLY_TRACKED so that - * {@code undefine()} and {@code scopeExitCleanup()} can clear weak refs - * when a strong reference is dropped. CODE refs are excluded because they - * live in both lexicals and the symbol table, making stash references - * invisible to refcounting. - *

    - * Setting refCount to WEAKLY_TRACKED prevents {@code setLarge()} from - * incorrectly decrementing to 0 and triggering false destruction. - * Weak ref clearing happens only via explicit {@code undef} or scope exit. - */ - public static final int WEAKLY_TRACKED = -2; + /** Whether this runtime currently has any registered weak observers. */ + public static boolean hasAnyWeakRefs() { + return !state().referentToWeakRefs.isEmpty(); + } /** Drop references belonging to the previous top-level script. */ public static void resetState() { @@ -63,23 +50,15 @@ public static void resetState() { /** * Make a reference weak. The reference no longer counts as a strong reference * for refCount purposes. If this was the last strong reference, DESTROY fires. - * For untracked objects (refCount == -1), simply registers in WeakRefRegistry + * For untracked objects, simply registers in WeakRefRegistry * without changing refCount — weak refs to untracked objects are never cleared * deterministically (see Strategy A in weaken-destroy.md). */ public static void weaken(RuntimeScalar ref) { - weaken(ref, java.util.List.of()); - } - - /** Install a cloned weak edge while treating the not-yet-running thread - * entry graph as a strong root. */ - static void weakenForSnapshot( - RuntimeScalar ref, java.util.List snapshotRoots) { - weaken(ref, snapshotRoots); + weakenInternal(ref); } - private static void weaken( - RuntimeScalar ref, java.util.List snapshotRoots) { + private static void weakenInternal(RuntimeScalar ref) { if (ref.destroySelfArgument || ref instanceof RuntimeScalarReadOnly || ref.type == RuntimeScalarType.READONLY_SCALAR) { @@ -90,12 +69,17 @@ private static void weaken( throw new PerlCompilerException("Can't weaken a nonreference"); } if (!(ref.value instanceof RuntimeBase base)) return; + // Older producers used a negative raw count as the untracked sentinel. + // The explicit tracking state is authoritative now, but normalize that + // legacy representation before choosing the weak-reference transition. + if (base.refCount < 0) base.markRefCountUntracked(); LifecycleRuntimeState state = state(); if (state.weakScalars.contains(ref)) return; // already weak - // Weakness changes the strong root graph even though the scalar's + ref.noteReferenceSlotMutation(); + + // Weakness retires the scalar's strong owner identity even though its // referent field is unchanged. - MortalList.invalidateAllRootSnapshots(); // If referent was already destroyed, immediately undef the weak ref. // CODE refs are an exception: Sub::Quote compiles named, no-install @@ -103,23 +87,35 @@ private static void weaken( // that glob. The restore path can mark the temporary stash reference as // destroyed even though a strong coderef escaped. Revive that stale // marker so a later weaken() of the escaped CODE behaves like Perl. - if (base.refCount == Integer.MIN_VALUE) { + if (base.isPerlDestroyed()) { if (base instanceof RuntimeCode code && code.defined() && !code.currentlyDestroying) { - base.refCount = -1; + base.markRefCountUntracked(); + base.markPerlResurrected(); } else { ref.type = RuntimeScalarType.UNDEF; ref.value = null; + ref.refreshArgumentAliasOwnerSlots(); + RuntimeScalar.releaseIoOwner(ref); return; } } state.weakScalars.add(ref); + ref.refreshArgumentAliasOwnerSlots(); + ref.refreshUntrackedReferenceOwner(); state.referentToWeakRefs .computeIfAbsent(base, k -> Collections.newSetFromMap(new IdentityHashMap<>())) .add(ref); - base.activateOwnerTracking(); + ref.releaseUntrackedReferenceOwner(base); + // Releasing the final strong slot can synchronously run DESTROY and + // clear this newly registered weak observer, as Perl does when the + // weakened variable was the last owner. + if (!state.weakScalars.contains(ref) || ref.value != base) { + RuntimeScalar.releaseIoOwner(ref); + return; + } ref.releaseClosureCaptureReferentsForWeaken(base); if (System.getenv("PJ_WEAKCLEAR_TRACE") != null) { System.err.println("[WEAKEN] ref=" + System.identityHashCode(ref) @@ -129,96 +125,48 @@ private static void weaken( // Flip the fast-path flag so scopeExit cascades don't bail out // via the !blessedObjectExists shortcut when unblessed data has // weak refs that need clearing. - // Phase D-W2b (perf): the very first weaken() also has to - // backfill `MyVarCleanupStack.liveCounts` so that already-live - // my-vars become visible to the walker. We gate the per-`my` - // merge cost on weakRefsExist; without backfill, my-vars - // declared before the first weaken would never appear in - // liveCounts and the walker would miss them. if (!state.weakRefsExist) { MortalList.noteBoundaryWork(); state.weakRefsExist = true; - MyVarCleanupStack.snapshotStackToLiveCounts(); - // Prepare the installed-CODE capture root index on the first - // weaken(), during setup, so the first callback-boundary sweep - // does not have to build it synchronously while dispatching work. - GlobalVariable.globalCodeRefEdgeRootsView(); } - boolean weakenedLiveLexical = MyVarCleanupStack.isLive(ref); + boolean weakenedLiveLexical = MyVarCleanupStack.isRegistered(ref); boolean weakenedLiveCodeRef = base instanceof RuntimeCode && weakenedLiveLexical; - boolean weakenedLiveBlessedRef = base.blessId != 0 - && !(base instanceof RuntimeCode) - && weakenedLiveLexical; - - if (base.refCount > 0 && ref.refCountOwned) { - // Tracked object with a properly-counted reference: - // decrement strong count (weak ref doesn't count). - // Only decrement if refCountOwned=true, meaning the hash element - // or variable's creation incremented the referent's refCount via - // setLargeRefCounted or incrementRefCountForContainerStore. - // If refCountOwned=false (e.g., element in an untracked anonymous - // hash like `{ weakref => $target }`), the store never incremented - // refCount, so weaken must not decrement either — otherwise we - // get a double-decrement that causes premature destruction. - // Clear refCountOwned because weaken's DEC consumes the ownership — - // the weak scalar should not trigger another DEC on scope exit or overwrite. - ref.refCountOwned = false; - base.traceRefCount(-1, "WeakRefRegistry.weaken (decrement on weakening)"); - base.releaseOwner(ref, "weaken"); - base.releaseActiveOwner(ref); - if (--base.refCount == 0) { - if (base.hasSemanticCaptureOwner()) { - // A captured pad is an authoritative Perl owner even when - // the weak probe being weakened held the last ordinary - // counted slot. Keep the referent alive until the shared - // pad cell is released; multiple closures share this one - // owner and must not inflate refCount. - base.refCount = 1; - } else if (base.localBindingExists) { - // Named container (my %hash / my @array): the local variable - // slot holds a strong reference not counted in refCount. - // Don't call callDestroy — the container is still alive. - // Cleanup will happen at scope exit (scopeExitCleanupHash/Array). - } else if (!(base instanceof RuntimeScalar scalar - && scalar.ephemeralScalarReferenceReferent) - && hasWeakRefsTo(base) - && (ReachabilityWalker.isReachableFromRoots(base) - || ReachabilityWalker.isReachableFromLiveScalarRegistry(base) - || ReachabilityWalker.isReachableFromLiveCodeCaptures(base) - || ReachabilityWalker.isReachableFromStrongRoots(base, snapshotRoots) - || RuntimeCode.isInstalledPadConstant(base))) { - // A temporary probe can be weakened without owning the last - // strong Perl reference. Test::Refcount does this when it - // weakens a local copy before calling B::svref_2object(). - // If another strong lexical/global path is still reachable, - // keep existing weak refs intact instead of treating this - // selective refCount==0 as object death. - base.refCount = 1; - } else { - // No local binding: refCount==0 means truly no strong refs. - // Trigger DESTROY + clear weak refs. - base.refCount = Integer.MIN_VALUE; - DestroyDispatch.callDestroy(base); + if (base.isRefCountTracked() && base.refCount > 0 && ref.refCountOwned) { + PerlOwnerSlot releasedSlot = ref.countedOwnerSlot(); + boolean identifiedOwner = releasedSlot != null && releasedSlot.isActive() + && releasedSlot.referent() == base; + if (!identifiedOwner) { + // Legacy scalar construction can mark an already-counted edge + // before its storage producer has installed a slot token. + // Adopt that existing count as an identity without incrementing + // it, then retire the exact edge through the standard release. + RuntimeScalar.adoptExistingCountedOwnerForCurrentValue( + ref, base, ref.countedOwnerKind(), "WeakRefRegistry.weaken legacy edge"); + releasedSlot = ref.countedOwnerSlot(); + if (releasedSlot == null || !releasedSlot.isActive() + || releasedSlot.referent() != base) { + throw new IllegalStateException( + "weakening failed to adopt the current counted owner slot"); } } - // Note: we do NOT transition unblessed tracked objects to WEAKLY_TRACKED - // here anymore. The previous transition (base.blessId == 0 → WEAKLY_TRACKED) - // caused premature clearing of weak refs when ANY strong ref exited scope, - // even though other strong refs still existed (e.g., Moo's CODE refs in - // glob slots). Birth-tracked objects maintain accurate refCounts through - // setLarge(), so we can trust the count. The concern about untracked copies - // (new RuntimeScalar(RuntimeScalar)) is mitigated by the fact that such - // copies don't decrement refCount on cleanup (refCountOwned=false), so - // they can't cause false-positive refCount==0 destruction. - } else if (base.refCount == -1 + // Weakening retires the exact strong edge. Queue its token through + // the same lifecycle path as overwrite and aggregate removal so + // the slot identity and count cannot drift apart. + PerlOwnerSlot.PendingRelease release = + ref.releaseCountedOwnerIdentity(base, "weaken", true); + if (release == null) { + throw new IllegalStateException( + "weakening a counted scalar lost its owner release token"); + } + MortalList.releaseCountedOwnerSlotImmediately( + base, release, "WeakRefRegistry.weaken"); + } else if (base.isRefCountUntracked() && base instanceof RuntimeScalarReadOnly && RuntimeCode.isInstalledPadConstant(base)) { - // The defining subroutine's pad is the strong owner. Its ownership - // is not represented in selective refCount, and glob replacement - // clears the weak ref explicitly via clearPadConstantWeakRefs(). - } else if (base.refCount == -1 && !(base instanceof RuntimeCode)) { - // Untracked non-CODE object: transition to WEAKLY_TRACKED so that + // A live CV optree owns this constant through an explicit owner slot. + } else if (base.isRefCountUntracked() && !(base instanceof RuntimeCode)) { + // Untracked non-CODE object: transition to weak-tracked state so that // undefine() and scopeExitCleanup() can clear weak refs // when a strong reference is dropped. This is a heuristic — // it may clear weak refs too early when multiple strong refs @@ -230,63 +178,45 @@ && hasWeakRefsTo(base) // CODE refs are excluded because they live in BOTH lexicals AND // the symbol table (stash). Stash assignments (*Foo::bar = $coderef) // don't go through setLarge(), making the stash reference invisible - // to refcounting. If we transition CODE refs to WEAKLY_TRACKED, + // to refcounting. If we transition CODE refs to weak-tracked state, // setLarge()/scopeExitCleanup() will prematurely clear weak refs // when a lexical reference is overwritten — even though the CODE ref // is still alive in the stash. This breaks Sub::Quote/Sub::Defer // (which use weaken() for back-references) and cascades to break // Moo's accessor inlining (51 test failures). See §15. ref.refCountOwned = false; - if (base.blessId == 0 - && (base instanceof RuntimeArray || base instanceof RuntimeHash) - && ReachabilityWalker.isReachableFromRoots(base)) { - // An untracked aggregate may already be owned by a live tree - // before its first weak parent edge is installed. Keep it - // through this transition; a later full sweep can clear the - // observer after that Perl root actually leaves scope. - base.refCount = 1; - } else { - base.refCount = WEAKLY_TRACKED; - MortalList.requestImmediateWeakSweep(); - } - } - // A live lexical can be the final Perl-visible strong owner even when - // selective refCount remains inflated by earlier argument/temporary - // copies. Request one root-based sweep at the next safe statement - // boundary so weaken($lexical) has Perl's immediate observable - // semantics. Keep this limited to blessed non-CODE referents: DBIC - // schema/parser flows need it, while CODE refs and container-internal - // weak backrefs use their targeted cleanup paths below. - if (weakenedLiveBlessedRef - && base.refCount > 0 - && base.reachableOwnerCount() == 0 - && !ModuleInitGuard.inModuleInit()) { - MortalList.requestImmediateWeakSweep(); + // Keep weak-tracked state instead of fabricating a + // positive count for package-nested aggregates. Their exact + // UNTRACKED_REFERENCE slots keep the observer live and trigger + // cleanup when the final scalar owner releases its edge. + base.markRefCountWeaklyTracked(); } boolean shouldCheckLiveCodeRef = weakenedLiveCodeRef - && codeRefHasCountedOwners(base) - && !ModuleInitGuard.inModuleInit(); + && codeRefHasCountedOwners(base); if (base instanceof RuntimeCode code - && code.refCount >= 0 + && code.isRefCountTracked() && state.weakRefsExist && (shouldCheckLiveCodeRef || (code.hadStashRef - && code.stashRefCount <= 0 && !isInstalledGlobalCodeRef(code)))) { // Keep this path targeted to the CODE referent. DBIC weakens - // callback CODE refs in hot cursor paths; running a full - // ReachabilityWalker sweep here forces repeated System.gc() calls. + // callback CODE refs in hot cursor paths, so use the CODE-specific + // lifetime checks below. // The CODE-specific stale-ref decision below is enough: live CODE // refs are protected by clearWeakRefsTo()/shouldKeepCodeWeakRefs, // while expired anonymous or former-stash CODE refs can still clear // their weak registry entries immediately. if (hasWeakRefsTo(code) - && code.stashRefCount <= 0 - && !isInstalledGlobalCodeRef(code) - && (code.hadStashRef || code.reachableOwnerCount() == 0)) { + && !isInstalledGlobalCodeRef(code)) { + // clearWeakRefsTo() makes the final decision from stash state, + // active frames, and explicit owner-slot identities. clearWeakRefsTo(code); } } + // A weakened glob scalar cannot keep an anonymous IO resource alive + // independently of the glob referent. Release its resource-owner slot + // only after any final DESTROY dispatch above has completed. + RuntimeScalar.releaseIoOwner(ref); } private static boolean codeRefHasCountedOwners(RuntimeBase base) { @@ -307,24 +237,36 @@ public static boolean isweak(RuntimeScalar ref) { public static void unweaken(RuntimeScalar ref) { LifecycleRuntimeState state = state(); if (!state.weakScalars.contains(ref)) return; - MortalList.invalidateAllRootSnapshots(); if (!state.weakScalars.remove(ref)) return; + ref.noteReferenceSlotMutation(); if (ref.value instanceof RuntimeBase base) { Set weakRefs = state.referentToWeakRefs.get(base); if (weakRefs != null) { weakRefs.remove(ref); if (weakRefs.isEmpty()) state.referentToWeakRefs.remove(base); } - if (base.refCount >= 0) { - base.traceRefCount(+1, "WeakRefRegistry.unweaken (restore strong count)"); - base.refCount++; // restore strong count - ref.refCountOwned = true; // restore ownership - base.hadCountedReference = true; - base.recordOwner(ref, "WeakRefRegistry.unweaken"); - base.recordActiveOwner(ref); + PerlOwnerSlot currentOwner = ref.countedOwnerSlot(); + if (ref.refCountOwned + && (currentOwner == null || !currentOwner.isActive() + || currentOwner.referent() != base + || currentOwner.countedScalarOwner() != ref)) { + // Weak scalars own no counted edge. Legacy paths can leave the + // marker behind after the exact slot has already been retired; + // normalize that stale marker before reacquiring the strong + // edge below, which will install a fresh identity if needed. + ref.refCountOwned = false; + } + // Restore the scalar edge through the same count-and-slot + // acquisition used by ordinary container stores. The helper also + // leaves formerly untracked referents uncounted. + RuntimeScalar.incrementRefCountForContainerStore( + ref, ref.countedOwnerKind()); + if (!base.isPerlDestroyed()) { + RuntimeScalar.retainUnstashedIoForDurableSlot(ref); } // Note: if MIN_VALUE, object already destroyed — unweaken is a no-op } + ref.refreshArgumentAliasOwnerSlots(); } /** @@ -335,7 +277,6 @@ public static void unweaken(RuntimeScalar ref) { public static boolean removeWeakRef(RuntimeScalar ref, RuntimeBase oldReferent) { LifecycleRuntimeState state = state(); if (!state.weakScalars.contains(ref)) return false; - MortalList.invalidateAllRootSnapshots(); if (!state.weakScalars.remove(ref)) return false; if (System.getenv("PJ_WEAKCLEAR_TRACE") != null) { System.err.println("[WEAKREMOVE] ref=" + System.identityHashCode(ref) @@ -359,14 +300,165 @@ public static boolean hasWeakRefsTo(RuntimeBase referent) { return weakRefs != null && !weakRefs.isEmpty(); } + /** Drop untracked scalar owners whose storage or proxy slot has gone away. */ + private static void releaseDetachedUntrackedReferenceOwners(RuntimeBase referent) { + for (PerlOwnerSlot slot : referent.untrackedReferenceOwnerSlotsView()) { + if (!slot.isActive() || slot.referent() != referent) continue; + RuntimeScalar owner = slot.untrackedScalarOwner(); + if (owner == null && !slot.hasUntrackedScalarOwnerAssociation()) { + continue; + } else if (owner == null || owner.untrackedReferenceOwnerSlot() != slot) { + slot.release(); + } else if (isweak(owner) + || !(owner.hasLiveCurrentStrongValueSlot() + || ((referent.blessId != 0 + || referent.isWeaklyRefCountTracked()) + && owner.hasCurrentAggregateStorageSlot()))) { + owner.releaseUntrackedReferenceOwner(referent); + } + } + } + + /** Finish tracked cleanup when its final owner slot leaves. */ + static void onStrongOwnerSlotReleased(RuntimeBase referent) { + if (referent != null && PerlRuntime.currentOrNull() != null) { + releaseDetachedUntrackedReferenceOwners(referent); + // A proxy can retain an untracked value owner while its lvalue + // parent is live. Recheck those exact proxy owners when the parent + // loses its final Perl storage owner; no later release on the + // value referent is guaranteed to trigger that check for us. + referent.recheckProxyValueOwnersIfUnowned(); + } + if (referent instanceof RuntimeCode code) { + code.releasePadConstantsForUntrackedOwnerSlot(); + code.finishActiveCodeOwnerRelease(); + } + boolean zeroCountOwnerSlotsExhausted = referent != null + && referent.isRefCountTracked() + && referent.refCount == 0 + && !(referent instanceof RuntimeCode) + && !GlobalVariable.isPackageRootedAggregate(referent) + && MortalList.canTrustFinalCountedRelease(referent); + if (referent != null + && ((referent.deferredFinalReleaseForUncountedOwners + && (referent.isWeaklyRefCountTracked() + || (referent.isRefCountTracked() && referent.refCount == 0))) + || zeroCountOwnerSlotsExhausted) + && !referent.hasOwnerSlots() + && PerlRuntime.currentOrNull() != null + && !referent.localBindingExists + && !referent.hasClosureCaptureOwner() + && !referent.hasPendingReturnOwner() + && referent.countedOwnerSlotCount() == 0 + && !(referent instanceof RuntimeScalarReadOnly + && RuntimeCode.isInstalledPadConstant(referent))) { + referent.deferredFinalReleaseForUncountedOwners = false; + DestroyDispatch.callDestroy(referent); + return; + } + if (referent == null + || (!referent.isWeaklyRefCountTracked() && !referent.isRefCountUntracked()) + || referent.hasOwnerSlots() + || PerlRuntime.currentOrNull() == null + || !hasWeakRefsTo(referent) + || referent.localBindingExists + || referent.hasClosureCaptureOwner() + || referent.hasPendingReturnOwner() + || referent.countedOwnerSlotCount() != 0 + || (referent instanceof RuntimeScalarReadOnly + && RuntimeCode.isInstalledPadConstant(referent))) return; + + if (referent.blessId != 0 + || referent instanceof RuntimeArray + || referent instanceof RuntimeHash) { + DestroyDispatch.callDestroy(referent); + } else { + clearWeakRefsTo(referent); + } + } + + /** Finish an uncounted value after one aggregate storage edge is retired. */ + static void onContainerValueOwnerReleased(RuntimeBase referent) { + boolean aggregate = referent instanceof RuntimeArray || referent instanceof RuntimeHash; + if ((!aggregate && (referent == null || referent.blessId == 0)) + || referent.isPerlDestroyed() + || referent.isRefCountTracked() + || referent.refCount != 0 + || referent.hasOwnerSlots() + || referent.localBindingExists + || referent.hasPendingOwnerRelease() + || referent.hasClosureCaptureOwner() + || GlobalVariable.isPackageRootedAggregate(referent) + || PerlRuntime.currentOrNull() == null + || (referent instanceof RuntimeArray array && array.threadShared)) { + return; + } + // The incoming storage owner is gone. Let an aggregate release its + // direct element slots recursively through this same boundary. + DestroyDispatch.callDestroy(referent); + } + + /** Recheck cleared aggregate cleanup after a suspended lexical owner retires. */ + public static void onSuspendedFrameOwnerReleased(RuntimeBase referent) { + if (referent != null && !referent.isPerlDestroyed() + && referent.clearedOwnedAggregateElement) { + MortalList.finalizeClearedAggregateOwnerAfterScopeExit(referent); + } + } + + /** Finalize an untracked value after its scalar owner has left scope. */ + static void finalizeUntrackedAfterOwnerScopeExit(RuntimeBase referent) { + if (referent == null || !referent.isRefCountUntracked() + || PerlRuntime.currentOrNull() == null + || referent.hasOwnerSlots() || referent.localBindingExists + || referent.hasClosureCaptureOwner() || referent.hasPendingReturnOwner() + || referent.countedOwnerSlotCount() != 0 + || (referent instanceof RuntimeCode code && RuntimeCode.isActiveCode(code))) { + return; + } + DestroyDispatch.callDestroy(referent); + } + + /** Finish an aggregate's cleanup after its active lexical pad owner left. */ + static void onActiveLexicalOwnerReleased(RuntimeBase referent) { + if (referent == null || PerlRuntime.currentOrNull() == null + || referent.hasOwnerSlots() || referent.hasClosureCaptureOwner() + || referent.hasPendingReturnOwner() + || referent.countedOwnerSlotCount() != 0 + || referent.localBindingExists || referent.refCount > 0 + || referent.isPerlDestroyed()) return; + + boolean untrackedAggregate = referent.blessId == 0 + && (referent instanceof RuntimeArray || referent instanceof RuntimeHash); + if (untrackedAggregate && referent.isRefCountTracked() + && referent.refCount == 1) { + referent.markRefCountWeaklyTracked(); + } + + if (referent.blessId != 0) { + DestroyDispatch.callDestroy(referent); + return; + } + + if ((referent.isWeaklyRefCountTracked() + || (referent.isRefCountTracked() && referent.refCount == 0)) + && hasWeakRefsTo(referent)) { + clearWeakRefsTo(referent); + } + } + /** * Clear all weak references to a referent. Called when refCount reaches 0, * before DESTROY. Sets all weak scalars pointing to this referent to undef. */ public static void clearWeakRefsTo(RuntimeBase referent) { + clearWeakRefsTo(referent, false); + } + + static void clearWeakRefsTo(RuntimeBase referent, boolean finalCountedOwner) { // A captured pad is a semantic strong owner even when the selective - // refcount has reached a weak-tracking sentinel. All destruction and - // sweeping paths funnel through this method, so preserve that edge at + // refcount has entered weak-tracked state. Destruction paths + // funnel through this method, so preserve that edge at // the weak-clearing boundary as well as in refcount transitions. if (referent.hasSemanticCaptureOwner()) return; // CODE refs can live in both lexicals and the symbol table. Do not @@ -375,7 +467,8 @@ public static void clearWeakRefsTo(RuntimeBase referent) { // Sub::Quote/Sub::Defer store weak backrefs to anonymous deferred subs; // leaving those weak scalars defined keeps the whole quoted/deferred // metadata graph Java-reachable and leaks until global destruction. - if (referent instanceof RuntimeCode code && shouldKeepCodeWeakRefs(code)) return; + if (!finalCountedOwner && referent instanceof RuntimeCode code + && shouldKeepCodeWeakRefs(code)) return; LifecycleRuntimeState state = state(); Set weakRefs = state.referentToWeakRefs.remove(referent); if (weakRefs == null) return; @@ -393,89 +486,78 @@ public static void clearWeakRefsTo(RuntimeBase referent) { } private static boolean isInstalledGlobalCodeRef(RuntimeCode code) { - // Anonymous CODE refs have never occupied a package slot, so their - // common weak-clear path can avoid consulting the package-root index. - // Formerly installed refs remain in the index while any alias occupies - // a package slot, independent of their current stash reference count. - if (!code.hadStashRef) return false; - return GlobalVariable.installedGlobalCodeRefsView().contains(code); + return code.hasStashCodeSlotOwner(); } private static boolean shouldKeepCodeWeakRefs(RuntimeCode code) { - if (code.stashRefCount > 0 || isInstalledGlobalCodeRef(code)) return true; + boolean installed = isInstalledGlobalCodeRef(code); + boolean trace = System.getenv("PJ_WEAKCLEAR_TRACE") != null + && code.hadStashRef && !installed; + if (trace) { + System.err.println("[WEAKCODE-CHECK] code=" + System.identityHashCode(code) + + " refCount=" + code.refCount + + " installed=" + installed + " slots=" + code.ownerSlotSnapshot().size()); + } + if (installed) return true; // The active frame is already a definitive strong owner. Check it - // before scanning the live scalar registries, which can be large and - // sits on the callback dispatch path when a quiet sweep runs. + // before inspecting remaining owner slots, which can be numerous on + // the callback dispatch path. if (RuntimeCode.isActiveCode(code)) return true; - LifecycleRuntimeState lifecycleState = state(); - Set sweepLiveReferents = lifecycleState.weakSweepLiveReferents; - if (sweepLiveReferents != null && sweepLiveReferents.contains(code)) return true; - ReachabilityWalker.RootReachabilitySnapshot fullRootSnapshot = - lifecycleState.fullRootSnapshot; - if (fullRootSnapshot != null && fullRootSnapshot.isReachable(code)) return true; - if (ReachabilityWalker.hasLiveStrongScalarReferent(code)) return true; + // Stale frame-temporary scalar cells can leave counted identities on + // a CODE after their Perl scope exits. Retire those cells before using + // the remaining owner ledger as direct liveness evidence. + code.releaseTemporaryCodeScalarOwners(); + if (hasWeakPreservingCodeOwnerSlot(code)) { + if (trace) { + for (PerlOwnerSlot slot : code.ownerSlotSnapshot()) { + RuntimeScalar owner = slot.countedScalarOwner(); + System.err.println("[WEAKCODE-SLOT] kind=" + slot.kind() + + " id=" + slot.identity() + " native=" + slot.isNativeOwner() + + " owner=" + (owner == null ? "null" + : System.identityHashCode(owner)) + + " ownerType=" + (owner == null ? "-" : owner.type) + + " valueIsCode=" + (owner != null && owner.value == code) + + " refCountOwned=" + (owner != null && owner.refCountOwned) + + " registered=" + (owner != null && MyVarCleanupStack.isRegistered(owner)) + + " scopeExited=" + (owner != null && owner.scopeExited) + + " local=" + (owner != null && owner.localBindingExists) + + " package=" + (owner != null && owner.isPackageGlobalRoot) + + " container=" + (owner != null && owner.containerOwner != null)); + } + } + return true; + } + // A Perl-visible owner must have an active slot identity. Java-side + // diagnostic references are not Perl ownership. return false; } - /** - * Clear weak refs for ALL blessed, non-CODE objects in the registry. - * Called after flushDeferredCaptures() — at this point the main script - * has returned and all lexical scopes have exited. Objects with inflated - * selective refCounts (due to JVM temporaries, method-call argument - * copies, etc.) may still appear "alive" even though no Perl code holds - * a reference. Clearing their weak refs allows DBIC's leak tracer - * (which runs in an END block) to see them as "collected". - *

    - * This is safe because: - * 1. Only weak refs are cleared — the Java objects remain alive - * 2. CODE refs are excluded (they may still be called from stashes) - * 3. END blocks that check for leaks run AFTER this method - */ - /** - * Phase 4 (refcount_alignment_plan.md): snapshot all referents currently - * in the weak-ref registry. Used by {@link ReachabilityWalker} to iterate - * safely (the registry may be modified by concurrent DESTROY / weak-ref - * clearing during the walk). - */ - public static java.util.List snapshotWeakRefReferents() { - return new java.util.ArrayList<>(state().referentToWeakRefs.keySet()); - } - - public static void clearAllBlessedWeakRefs() { - clearBlessedWeakRefsExcept(java.util.Collections.emptySet()); - } - - /** - * Clear weak references whose referents cannot be observed by END code. - * This is the pre-END counterpart to {@link #clearAllBlessedWeakRefs()}: - * genuine END captures remain intact, while stale selective-refcount - * owners do not make leak tracers report objects that Perl has released. - */ - public static void clearBlessedWeakRefsExcept(Set retained) { - // Snapshot the keys to avoid ConcurrentModificationException, - // since clearWeakRefsTo modifies referentToWeakRefs. - java.util.List referents = - new java.util.ArrayList<>(state().referentToWeakRefs.keySet()); - for (RuntimeBase referent : referents) { - if (retained.contains(referent)) continue; - if (referent instanceof RuntimeCode) continue; - // Phase H3: skip unblessed containers (ARRAY/HASH) at pre-END - // time. Sub::Defer's $deferred_info and Sub::Quote's - // $quoted_info are reachable only via closure captures not - // traversed by `clearAllBlessedWeakRefs`. Clearing them - // breaks END-block leak-tracer dispatch loops that call - // Moo accessors to stringify weak-registry slots. - if (referent.blessId == 0 && !(referent instanceof RuntimeScalar)) continue; - // Phase I: skip clearing weak refs to scalars that hold CODE - // refs or are UNDEF (Sub::Quote/Sub::Defer slot scalars). - if (referent instanceof RuntimeScalar s) { - if (s.type == RuntimeScalarType.UNDEF) continue; - if ((s.type & RuntimeScalarType.REFERENCE_BIT) != 0 - && s.value instanceof RuntimeCode) { - continue; - } + private static boolean hasWeakPreservingCodeOwnerSlot(RuntimeCode code) { + for (PerlOwnerSlot slot : code.ownerSlotSnapshot()) { + // CODE_SLOT identities also represent compatibility pins retained + // for compiled call sites after a glob is deleted. The visible + // stash checks above distinguish live Perl CODE owners from those + // Java-facing pins. + if (!slot.isActive() || slot.kind() == PerlOwnerSlot.Kind.CODE_SLOT) continue; + if (slot.kind() == PerlOwnerSlot.Kind.UNTRACKED_REFERENCE) { + RuntimeScalar owner = slot.untrackedScalarOwner(); + boolean currentStrongValue = owner != null + && owner.untrackedReferenceOwnerSlot() == slot + && !owner.isTransientArgumentValueOwner() + && !isweak(owner) + && (owner.type & RuntimeScalarType.REFERENCE_BIT) != 0 + && owner.value == code + && owner.hasLiveCurrentStrongValueSlot(); + if (currentStrongValue) return true; + // A stale untracked token is not a live Perl owner. The exact + // container-transfer release retires it; if a weak-clear + // boundary arrives first, do not let an exited @_ array pin + // the observer. + continue; } - clearWeakRefsTo(referent); + return true; } + return false; } + } diff --git a/src/main/perl/lib/B.pm b/src/main/perl/lib/B.pm index 9bbaf870c0..aaf17d67db 100644 --- a/src/main/perl/lib/B.pm +++ b/src/main/perl/lib/B.pm @@ -51,44 +51,17 @@ use constant { # Stub classes for B objects package B::SV { sub new { - # IMPORTANT: Avoid `my ($class, $ref) = @_` or `shift` — each local - # variable assignment that holds a reference inflates the referent's - # selective refcount by 1 (via setLargeRefCounted). Instead, use - # $_[0]/$_[1] (aliases into @_) which don't increment refcount. - # This keeps the only inflation to the `$self->{ref}` hash slot, - # which REFCNT compensates for with its -1 adjustment. + # Native B objects keep an SV pointer without owning the referent. + # Store the runtime's equivalent non-owning view so the target remains + # inspectable during DESTROY without extending its Perl lifetime. my $self = bless {}, $_[0]; - $self->{ref} = $_[1]; + Internals::jperl_b_object_store_reference($self, $_[1]); return $self; } sub REFCNT { - # Return the selective refcount via Internals::SvREFCNT. - # - # In PerlOnJava, B::SV stores the reference in $self->{ref} which is - # a tracked (blessed) hash element. This inflates the referent's - # selective refCount by +1 via setLargeRefCounted. - # - # In Perl 5, B::svref_2object() stores the SV pointer directly (a C - # pointer), so it does NOT inflate the referent's refcnt. However, - # Perl 5 has higher refcounts overall because ALL references count - # (hash elements, stack temporaries, mortal slots). PerlOnJava's - # selective refCount is lower because: - # 1. Stack/JVM temporaries don't contribute - # 2. Method call argument copies don't contribute - # - # The B::SV inflation (+1) roughly compensates for these deficits, - # so we return the raw selective refCount WITHOUT subtracting 1. - # - # For Schema::DESTROY's `refcount($source) > 1` check: - # - Source with 1 selective ref (e.g., source_registrations only): - # B::SV inflation → 2, REFCNT = 2 → > 1 → rescue ✓ - # (In Perl 5 this source also shows > 1 because stack temps add refs) - # - Source with 0 selective refs (untracked): - # B::SV inflation → 1, REFCNT = 1 → no rescue ✓ - # B's C implementation inspects the referent without creating a Perl - # owner. Ask the runtime to compensate for an independently live - # lexical owner that selective refcounting may not have counted. + # The $self->{ref} slot is a non-owning runtime view. Ask the runtime + # for the Perl-visible count while accounting for the active B frame. Internals::SvREFCNT($_[0]->{ref}, 1); } @@ -579,7 +552,7 @@ sub svref_2object { my $name = *{$_[0]}{NAME} // ''; my $pkg = *{$_[0]}{PACKAGE} // 'main'; my $gv = B::GV->new($name, $pkg); - $gv->{ref} = $_[0]; # store glob ref for SV method access + Internals::jperl_b_object_store_reference($gv, $_[0]); return $gv; } diff --git a/src/main/perl/lib/DBD/JDBC.pm b/src/main/perl/lib/DBD/JDBC.pm index 685b7f2dd2..899bfe9b32 100644 --- a/src/main/perl/lib/DBD/JDBC.pm +++ b/src/main/perl/lib/DBD/JDBC.pm @@ -92,11 +92,33 @@ sub _do_impl { my ($dbh, $statement, $attr, @params) = @_; return "0E0" if DBI::_is_comment_only_sql($statement); DBI::_cleanup_before_ddl($statement); - my $sth = $dbh->prepare($statement, $attr) or return undef; - $sth->execute(@params) or do { $sth->finish; return undef }; - my $rows = $sth->rows; - $sth->finish; - return ($rows == 0) ? "0E0" : $rows; + + my ($sth, $result); + my $ok = eval { + $sth = $dbh->prepare($statement, $attr); + if ($sth) { + if ($sth->execute(@params)) { + my $rows = $sth->rows; + $sth->finish; + $result = ($rows == 0) ? "0E0" : $rows; + } + else { + $sth->finish; + } + } + 1; + }; + if (!$ok) { + my $error = $@; + # HandleError can rethrow a DBI failure through this Perl method. + # Retire its local statement and database-handle owners before the + # exception crosses back to the caller. + eval { $sth->finish if $sth; 1 }; + undef $sth; + undef $dbh; + die $error; + } + return $result; } *DBD::JDBC::db::do = \&_do_impl; diff --git a/src/main/perl/lib/DBI.pm b/src/main/perl/lib/DBI.pm index 779bd739d7..c8e6855cf7 100644 --- a/src/main/perl/lib/DBI.pm +++ b/src/main/perl/lib/DBI.pm @@ -69,15 +69,17 @@ XSLoader::load( 'DBI' ); # inner handle passed to driver STORE/FETCH methods, while applications hold # a DBI::db or DBI::st outer handle. Keep that distinction for pure-Perl DBDs # such as DBD::Mock, which configure behavior through direct hash assignment. -sub DBI::dr::TIEHASH { bless $_[1], $_[0] } -sub DBI::db::TIEHASH { bless $_[1], $_[0] } -sub DBI::st::TIEHASH { bless $_[1], $_[0] } +# Native DBI creates these handles outside Perl's overridable bless, so keep +# the pure-Perl implementation equivalent. +sub DBI::dr::TIEHASH { CORE::bless($_[1], $_[0]) } +sub DBI::db::TIEHASH { CORE::bless($_[1], $_[0]) } +sub DBI::st::TIEHASH { CORE::bless($_[1], $_[0]) } sub _tie_handle_hash { my ($handle, $class) = @_; my %outer; my $inner = tie %outer, $class, $handle; - my $outer = bless \%outer, $class; + my $outer = CORE::bless(\%outer, $class); return wantarray ? ($outer, $inner) : $outer; } @@ -512,7 +514,6 @@ sub _cleanup_before_ddl { eval { require Internals; Internals::jperl_freetmps(); - Internals::jperl_sweep_destroyables_no_jvm_gc(); 1; }; return 1; @@ -1066,7 +1067,6 @@ sub _fetch_handle_value { eval { require Internals; Internals::jperl_freetmps(); - Internals::jperl_sweep_destroyables_no_jvm_gc(); 1; }; } diff --git a/src/main/perl/lib/Exporter.pm b/src/main/perl/lib/Exporter.pm index b3f6cb5f8f..ca450fd7f1 100644 --- a/src/main/perl/lib/Exporter.pm +++ b/src/main/perl/lib/Exporter.pm @@ -9,6 +9,12 @@ our $Verbose ||= 0; our $VERSION = '5.79'; our %Cache; +# Load the delegated helpers before any compile-time import invokes them. +# PerlOnJava's `caller` frames include the lazy `require` path when Exporter +# first loads Heavy from inside an import, which can shift export_to_level's +# caller depth and install symbols into the wrong package. +require Exporter::Heavy; + sub as_heavy { require Exporter::Heavy; # Unfortunately, this does not work if the caller is aliased as *name = \&foo diff --git a/src/main/perl/lib/POSIX.pm b/src/main/perl/lib/POSIX.pm index 4944970601..3001751282 100644 --- a/src/main/perl/lib/POSIX.pm +++ b/src/main/perl/lib/POSIX.pm @@ -49,15 +49,16 @@ sub import { Exporter::import($pkg, @list); } -# libc-style conversion used by older pure-Perl CPAN modules. Return the -# numeric prefix and the unparsed suffix, matching Perl's POSIX::strtod API. +# libc-style conversion used by older pure-Perl CPAN modules. The second +# return value is the number of unparsed characters, matching POSIX::strtod. sub strtod { my ($input) = @_; my $text = defined($input) ? "$input" : ''; + my $input_length = length($text); $text =~ s/^\s+//; - return (0, $text) + return (0, $input_length) unless $text =~ /^([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)(.*)$/s; - return (0 + $1, $2); + return (0 + $1, length($2)); } # C99 floating-point helpers exposed by current core POSIX releases. @@ -799,6 +800,8 @@ for my $const (qw( F_DUPFD F_GETFD F_SETFD F_GETFL F_SETFL FD_CLOEXEC + LONG_MAX + SIGHUP SIGINT SIGQUIT SIGILL SIGTRAP SIGABRT SIGBUS SIGFPE SIGKILL SIGUSR1 SIGSEGV SIGUSR2 SIGPIPE SIGALRM SIGTERM SIGCHLD SIGCONT SIGSTOP SIGTSTP diff --git a/src/test/java/org/perlonjava/IOSocketSSLChunkedBodyTest.java b/src/test/java/org/perlonjava/IOSocketSSLChunkedBodyTest.java new file mode 100644 index 0000000000..91e83f224a --- /dev/null +++ b/src/test/java/org/perlonjava/IOSocketSSLChunkedBodyTest.java @@ -0,0 +1,141 @@ +package org.perlonjava; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.net.InetAddress; +import java.nio.charset.StandardCharsets; +import java.security.KeyStore; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLSocket; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.app.cli.CompilerOptions; +import org.perlonjava.app.scriptengine.PerlLanguageProvider; +import org.perlonjava.runtime.io.StandardIO; +import org.perlonjava.runtime.runtimetypes.GlobalVariable; +import org.perlonjava.runtime.runtimetypes.RuntimeArray; +import org.perlonjava.runtime.runtimetypes.RuntimeIO; +import org.perlonjava.runtime.runtimetypes.RuntimeScalar; + +@Tag("unit") +class IOSocketSSLChunkedBodyTest extends PerlRuntimeTestBase { + @Test + void temporarySocketArgumentRemainsOpenThroughChunkedBodyReads() throws Exception { + for (boolean useInterpreter : new boolean[] { false, true }) { + String output = executeFixture(useInterpreter); + assertFalse(output.contains("not ok"), output); + assertTrue(output.contains("the TLS response body is read to completion"), output); + assertTrue(output.contains("the complete chunked TLS response body is preserved"), output); + } + } + + private String executeFixture(boolean useInterpreter) throws Exception { + SSLServerSocket server = (SSLServerSocket) serverContext().getServerSocketFactory() + .createServerSocket(0, 1, InetAddress.getLoopbackAddress()); + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future response = executor.submit(() -> serveOneChunkedResponse(server)); + + ByteArrayOutputStream output = new ByteArrayOutputStream(); + PrintStream originalSystemOut = System.out; + RuntimeIO originalStdout = RuntimeIO.getStdout(); + PrintStream capturedOut = new PrintStream(output, true, StandardCharsets.UTF_8); + try { + PerlLanguageProvider.resetAll(); + System.setOut(capturedOut); + RuntimeIO.setStdout(new RuntimeIO(new StandardIO(capturedOut, true))); + GlobalVariable.getGlobalIO("main::STDOUT").setIO(RuntimeIO.getStdout()); + + String fixture = readFixture().replace("__PORT__", Integer.toString(server.getLocalPort())); + CompilerOptions options = new CompilerOptions(); + options.code = fixture; + options.fileName = "iosocketssl_chunked_tls_body.pl"; + options.useInterpreter = useInterpreter; + RuntimeArray.push(options.inc, new RuntimeScalar("src/main/perl/lib")); + + PerlLanguageProvider.executePerlCode(options, true); + RuntimeIO.getStdout().flush(); + response.get(15, TimeUnit.SECONDS); + return output.toString(StandardCharsets.UTF_8); + } finally { + server.close(); + executor.shutdownNow(); + RuntimeIO.setStdout(originalStdout); + GlobalVariable.getGlobalIO("main::STDOUT").setIO(originalStdout); + System.setOut(originalSystemOut); + capturedOut.close(); + PerlLanguageProvider.resetAll(); + } + } + + private static String readFixture() throws Exception { + try (InputStream input = IOSocketSSLChunkedBodyTest.class.getResourceAsStream( + "/fixtures/iosocketssl_chunked_tls_body.pl")) { + assertNotNull(input, "chunked TLS Perl fixture is available"); + return new String(input.readAllBytes(), StandardCharsets.UTF_8); + } + } + + private static void serveOneChunkedResponse(SSLServerSocket server) { + try (SSLSocket socket = (SSLSocket) server.accept()) { + socket.setSoTimeout(10_000); + socket.startHandshake(); + int matched = 0; + while (matched < 4) { + int value = socket.getInputStream().read(); + if (value < 0) throw new IllegalStateException("client closed before HTTP request"); + matched = switch (matched) { + case 0 -> value == '\r' ? 1 : 0; + case 1 -> value == '\n' ? 2 : value == '\r' ? 1 : 0; + case 2 -> value == '\r' ? 3 : 0; + default -> value == '\n' ? 4 : 0; + }; + } + + byte[] body = "x".repeat(8192).getBytes(StandardCharsets.US_ASCII); + String responseHeaders = "HTTP/1.1 200 OK\r\n" + + "Transfer-Encoding: chunked\r\n" + + "Connection: close\r\n\r\n"; + String chunkHeader = Integer.toHexString(body.length) + "\r\n"; + ByteArrayOutputStream response = new ByteArrayOutputStream(); + response.write(responseHeaders.getBytes(StandardCharsets.US_ASCII)); + response.write(chunkHeader.getBytes(StandardCharsets.US_ASCII)); + response.write(body); + response.write("\r\n0\r\n\r\n".getBytes(StandardCharsets.US_ASCII)); + OutputStream output = socket.getOutputStream(); + output.write(response.toByteArray()); + output.flush(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private static SSLContext serverContext() throws Exception { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (InputStream input = IOSocketSSLChunkedBodyTest.class.getResourceAsStream( + "/module/Net-SSLeay/t/data/simple-cert.enc.p12")) { + assertNotNull(input, "bundled TLS test keystore is available"); + keyStore.load(input, "test".toCharArray()); + } + + KeyManagerFactory keyManagers = KeyManagerFactory.getInstance( + KeyManagerFactory.getDefaultAlgorithm()); + keyManagers.init(keyStore, "test".toCharArray()); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(keyManagers.getKeyManagers(), null, null); + return context; + } +} diff --git a/src/test/java/org/perlonjava/backend/bytecode/InterpreterSuspensionOwnerTest.java b/src/test/java/org/perlonjava/backend/bytecode/InterpreterSuspensionOwnerTest.java new file mode 100644 index 0000000000..c43418c2f9 --- /dev/null +++ b/src/test/java/org/perlonjava/backend/bytecode/InterpreterSuspensionOwnerTest.java @@ -0,0 +1,60 @@ +package org.perlonjava.backend.bytecode; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.runtime.runtimetypes.NameNormalizer; +import org.perlonjava.runtime.runtimetypes.MortalList; +import org.perlonjava.runtime.runtimetypes.PerlOwnerSlot; +import org.perlonjava.runtime.runtimetypes.PerlRuntime; +import org.perlonjava.runtime.runtimetypes.RuntimeContextType; +import org.perlonjava.runtime.runtimetypes.RuntimeHash; +import org.perlonjava.runtime.runtimetypes.RuntimeScalar; +import org.perlonjava.runtime.runtimetypes.RuntimeScalarType; +import org.perlonjava.runtime.runtimetypes.WeakRefRegistry; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class InterpreterSuspensionOwnerTest { + @Test + void awaitedValueUsesSuspendedFrameOwnerUntilCompletionOrCancellation() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash awaitedFuture = new RuntimeHash(); + awaitedFuture.blessId = NameNormalizer.getBlessId( + "InterpreterSuspensionOwnerTest::AwaitedFuture"); + RuntimeScalar strongFuture = new RuntimeScalar(); + strongFuture.set(awaitedFuture.createAnonymousReference()); + RuntimeScalar weakObserver = new RuntimeScalar(); + weakObserver.set(awaitedFuture.createAnonymousReference()); + WeakRefRegistry.weaken(weakObserver); + + InterpreterSuspension suspension = new InterpreterSuspension( + null, strongFuture, 0, RuntimeContextType.SCALAR); + try { + assertEquals(1, awaitedFuture.ownerSlotCount( + PerlOwnerSlot.Kind.SUSPENDED_FRAME)); + strongFuture.set(new RuntimeScalar()); + MortalList.flush(); + assertTrue(WeakRefRegistry.isweak(weakObserver), + "the suspended frame keeps the awaited value alive after its source slot clears"); + + suspension.releaseAwaitedOwner(); + MortalList.flush(); + + assertEquals(0, awaitedFuture.ownerSlotCount( + PerlOwnerSlot.Kind.SUSPENDED_FRAME)); + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + } finally { + suspension.releaseAwaitedOwner(); + strongFuture.set(new RuntimeScalar()); + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + } + } + } +} diff --git a/src/test/java/org/perlonjava/frontend/parser/TryFinallyReturnOwnerTest.java b/src/test/java/org/perlonjava/frontend/parser/TryFinallyReturnOwnerTest.java new file mode 100644 index 0000000000..c651cad584 --- /dev/null +++ b/src/test/java/org/perlonjava/frontend/parser/TryFinallyReturnOwnerTest.java @@ -0,0 +1,90 @@ +package org.perlonjava.frontend.parser; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.app.cli.CompilerOptions; +import org.perlonjava.app.scriptengine.PerlLanguageProvider; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +@Tag("unit") +class TryFinallyReturnOwnerTest { + private static final String PROGRAM = """ + use strict; + use warnings; + use feature 'try'; + no warnings 'experimental::try'; + use Scalar::Util qw(weaken); + + { + package TryFinallyReturnOwnerTestObject; + our $destroyed = 0; + sub DESTROY { ++$destroyed } + } + + our $lvalue_slot = 'before'; + our $lvalue_finally_count = 0; + sub return_lvalue :lvalue { + try { + return $lvalue_slot; + } + catch ($error) { die $error; } + finally { ++$lvalue_finally_count; } + } + + my ($weak, $finally_count); + sub make_object { + try { + my $object = bless {}, 'TryFinallyReturnOwnerTestObject'; + $weak = $object; + weaken($weak); + return $object; + } + catch ($error) { die $error; } + finally { ++$finally_count; } + } + + my $strong = make_object(); + die "return value did not survive finally\\n" + unless defined($weak) + && $TryFinallyReturnOwnerTestObject::destroyed == 0 + && $finally_count == 1; + undef $strong; + die "final owner release did not destroy the object exactly once\\n" + unless !defined($weak) + && $TryFinallyReturnOwnerTestObject::destroyed == 1; + return_lvalue() = 'after'; + die "lvalue return through finally was detached\\n" + unless $lvalue_slot eq 'after' && $lvalue_finally_count == 1; + """; + + @BeforeEach + void setUp() { + PerlLanguageProvider.resetAll(); + } + + @AfterEach + void tearDown() { + PerlLanguageProvider.resetAll(); + } + + @Test + void retainsReturnOwnerAcrossFinallyOnJvmBackend() { + assertDoesNotThrow(() -> execute(false)); + } + + @Test + void retainsReturnOwnerAcrossFinallyOnInterpreterBackend() { + assertDoesNotThrow(() -> execute(true)); + } + + private static void execute(boolean useInterpreter) throws Exception { + CompilerOptions options = new CompilerOptions(); + options.code = PROGRAM; + options.fileName = "try_finally_return_owner.t"; + options.useInterpreter = useInterpreter; + PerlLanguageProvider.executePerlCode(options, true); + } +} diff --git a/src/test/java/org/perlonjava/runtime/io/ViaLayerCountedOwnerLifecycleTest.java b/src/test/java/org/perlonjava/runtime/io/ViaLayerCountedOwnerLifecycleTest.java new file mode 100644 index 0000000000..4cb63a9f29 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/io/ViaLayerCountedOwnerLifecycleTest.java @@ -0,0 +1,48 @@ +package org.perlonjava.runtime.io; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.runtime.runtimetypes.PerlOwnerSlot; +import org.perlonjava.runtime.runtimetypes.PerlRuntime; +import org.perlonjava.runtime.runtimetypes.RuntimeArray; +import org.perlonjava.runtime.runtimetypes.RuntimeScalar; +import org.perlonjava.runtime.runtimetypes.RuntimeScalarType; +import org.perlonjava.runtime.runtimetypes.WeakRefRegistry; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ViaLayerCountedOwnerLifecycleTest { + @Test + void releasingLayerDoesNotDestroyReferentWithLiveClosurePadOwner() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeArray referent = new RuntimeArray(); + referent.setTrackedRefCount(0); + PerlOwnerSlot captureOwner = referent.retainClosureCaptureOwner(); + + RuntimeScalar pushed = new RuntimeScalar(); + pushed.type = RuntimeScalarType.ARRAYREFERENCE; + pushed.value = referent; + ViaLayer.SelfReferenceOwner layerOwner = ViaLayer.SelfReferenceOwner.retain(pushed); + + RuntimeScalar weakObserver = new RuntimeScalar(); + weakObserver.type = RuntimeScalarType.ARRAYREFERENCE; + weakObserver.value = referent; + WeakRefRegistry.weaken(weakObserver); + + try { + layerOwner.release(); + + assertTrue(captureOwner.isActive()); + assertTrue(WeakRefRegistry.isweak(weakObserver), + "the closure-pad owner keeps weak observers alive after POPPED"); + assertEquals(0, referent.refCount, + "the layer's paired count is released without destroying the live pad"); + } finally { + if (captureOwner.isActive()) referent.releaseClosureCaptureOwner(captureOwner); + WeakRefRegistry.clearWeakRefsTo(referent); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/io/ViaLayerReleaseDuringDestroyTest.java b/src/test/java/org/perlonjava/runtime/io/ViaLayerReleaseDuringDestroyTest.java new file mode 100644 index 0000000000..7c558bbca5 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/io/ViaLayerReleaseDuringDestroyTest.java @@ -0,0 +1,35 @@ +package org.perlonjava.runtime.io; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.runtime.runtimetypes.PerlRuntime; +import org.perlonjava.runtime.runtimetypes.RuntimeArray; +import org.perlonjava.runtime.runtimetypes.RuntimeScalar; +import org.perlonjava.runtime.runtimetypes.RuntimeScalarType; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Tag("unit") +class ViaLayerReleaseDuringDestroyTest { + @Test + void countedLayerHoldBalancesWhileReferentIsAlreadyDestroying() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeArray referent = new RuntimeArray(); + referent.setTrackedRefCount(0); + RuntimeScalar pushed = new RuntimeScalar(); + pushed.type = RuntimeScalarType.ARRAYREFERENCE; + pushed.value = referent; + ViaLayer.SelfReferenceOwner owner = ViaLayer.SelfReferenceOwner.retain(pushed); + + referent.currentlyDestroying = true; + try { + owner.release(); + assertEquals(0, referent.refCount, + "the retiring layer hold must not look like resurrection"); + } finally { + referent.currentlyDestroying = false; + owner.release(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/io/ViaLayerSelfOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/io/ViaLayerSelfOwnerSlotTest.java new file mode 100644 index 0000000000..f4374810b7 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/io/ViaLayerSelfOwnerSlotTest.java @@ -0,0 +1,84 @@ +package org.perlonjava.runtime.io; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.runtime.runtimetypes.DestroyDispatch; +import org.perlonjava.runtime.runtimetypes.PerlOwnerSlot; +import org.perlonjava.runtime.runtimetypes.PerlRuntime; +import org.perlonjava.runtime.runtimetypes.RuntimeBase; +import org.perlonjava.runtime.runtimetypes.DestroyDispatch; +import org.perlonjava.runtime.runtimetypes.RuntimeArray; +import org.perlonjava.runtime.runtimetypes.RuntimeScalar; +import org.perlonjava.runtime.runtimetypes.RuntimeScalarType; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ViaLayerSelfOwnerSlotTest { + @Test + void trackedPushedObjectHasOneOwnerIdentityUntilLayerRelease() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeArray referent = new RuntimeArray(); + referent.setTrackedRefCount(0); + + ViaLayer.SelfReferenceOwner owner = + ViaLayer.SelfReferenceOwner.retain(referent.createReference()); + assertNotNull(owner); + PerlOwnerSlot slot = owner.ownerSlot(); + + assertEquals(1, referent.refCount); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.IO_VIA_LAYER)); + assertTrue(slot.isNativeOwner()); + assertTrue(slot.isCountedNativeOwner()); + assertSame(referent, slot.referent()); + + owner.release(); + owner.release(); + + assertFalse(slot.isActive()); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.IO_VIA_LAYER)); + assertFalse(slot.isCountedNativeOwner()); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState(), + "the counted hold is released exactly once after its owner identity"); + assertEquals(0, referent.refCount); + } + } + + @Test + void untrackedPushedObjectStillHasAnIdentityWithoutCountPromotion() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeArray referent = new RuntimeArray(); + referent.markRefCountUntracked(); + RuntimeScalar untrackedReference = new RuntimeScalar(); + untrackedReference.type = RuntimeScalarType.ARRAYREFERENCE; + untrackedReference.value = referent; + ViaLayer.SelfReferenceOwner owner = + ViaLayer.SelfReferenceOwner.retain(untrackedReference); + + assertNotNull(owner); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, referent.refCountTrackingState()); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.IO_VIA_LAYER)); + + owner.release(); + + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, referent.refCountTrackingState()); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.IO_VIA_LAYER)); + } + } + + @Test + void destroyedPushedObjectDoesNotAcquireALayerOwner() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeArray referent = new RuntimeArray(); + DestroyDispatch.callDestroy(referent); + + assertNull(ViaLayer.SelfReferenceOwner.retain(referent.createReference())); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.IO_VIA_LAYER)); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/regex/RuntimeRegexCallbackCountedOwnerTest.java b/src/test/java/org/perlonjava/runtime/regex/RuntimeRegexCallbackCountedOwnerTest.java new file mode 100644 index 0000000000..431e830f06 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/regex/RuntimeRegexCallbackCountedOwnerTest.java @@ -0,0 +1,79 @@ +package org.perlonjava.runtime.regex; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.runtime.runtimetypes.PerlOwnerSlot; +import org.perlonjava.runtime.runtimetypes.PerlRuntime; +import org.perlonjava.runtime.runtimetypes.RuntimeCode; +import org.perlonjava.runtime.runtimetypes.RuntimeScalar; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RuntimeRegexCallbackCountedOwnerTest { + @Test + void countedCallbackOwnerRecordsAndReleasesItsPairedCount() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode code = new RuntimeCode(null, List.of()); + code.setTrackedRefCount(0); + RuntimeRegexCallback callback = callback(code); + + callback.retainOwner(); + + PerlOwnerSlot slot = callbackSlot(code); + assertTrue(slot.isCountedNativeOwner()); + assertEquals(1, code.refCount); + + callback.retainOwner(); + assertEquals(1, code.refCount, "multiple regex wrappers share one callback owner"); + callback.releaseOwner(); + assertEquals(1, code.refCount, "the shared callback owner remains active"); + + callback.releaseOwner(); + assertEquals(0, code.refCount); + assertFalse(slot.isActive()); + } + } + + @Test + void initiallyUncountedCallbackDoesNotReleaseAnotherOwnersLaterCount() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode code = new RuntimeCode(null, List.of()); + code.markRefCountUntracked(); + RuntimeRegexCallback callback = callback(code); + + callback.retainOwner(); + + PerlOwnerSlot slot = callbackSlot(code); + assertFalse(slot.isCountedNativeOwner()); + code.setTrackedRefCount(3); + + callback.releaseOwner(); + + assertEquals(3, code.refCount, + "an uncounted callback must not decrement a later unrelated count"); + assertFalse(slot.isActive()); + } + } + + private static RuntimeRegexCallback callback(RuntimeCode code) { + return (RuntimeRegexCallback) + RuntimeRegexCallback.wrap(new RuntimeScalar(code), "BLOCK").value; + } + + private static PerlOwnerSlot callbackSlot(RuntimeCode code) { + PerlOwnerSlot slot = code.ownerSlotSnapshot().stream() + .filter(candidate -> candidate.kind() == PerlOwnerSlot.Kind.REGEX_CALLBACK) + .findFirst() + .orElse(null); + assertNotNull(slot, "the callback owns a stable CODE slot"); + return slot; + } +} diff --git a/src/test/java/org/perlonjava/runtime/regex/RuntimeRegexCallbackOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/regex/RuntimeRegexCallbackOwnerSlotTest.java new file mode 100644 index 0000000000..c6b1aa651f --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/regex/RuntimeRegexCallbackOwnerSlotTest.java @@ -0,0 +1,53 @@ +package org.perlonjava.runtime.regex; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.runtime.runtimetypes.MortalList; +import org.perlonjava.runtime.runtimetypes.PerlOwnerSlot; +import org.perlonjava.runtime.runtimetypes.PerlRuntime; +import org.perlonjava.runtime.runtimetypes.RuntimeArray; +import org.perlonjava.runtime.runtimetypes.RuntimeBase; +import org.perlonjava.runtime.runtimetypes.RuntimeCode; +import org.perlonjava.runtime.runtimetypes.RuntimeScalar; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RuntimeRegexCallbackOwnerSlotTest { + @Test + void finalCallbackOwnerReleasesCapturesDespiteStaleCodeCount() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray capturedPad = new RuntimeArray(); + RuntimeCode code = new RuntimeCode(null, List.of()); + code.setTrackedRefCount(0); + PerlOwnerSlot padOwner = capturedPad.retainClosureCaptureOwner(code); + code.capturedAggregates = new RuntimeBase[] {capturedPad}; + code.capturedAggregateOwnerSlots = new PerlOwnerSlot[] {padOwner}; + code.captureFieldsRecorded = true; + + RuntimeRegexCallback callback = (RuntimeRegexCallback) + RuntimeRegexCallback.wrap(new RuntimeScalar(code), "BLOCK").value; + callback.retainOwner(); + assertTrue(code.hasPerlOwnerForCaptureOtherThan(null)); + + code.setTrackedRefCount(8); // compatibility count outlives the callback owner + MortalList.scopeExitCleanupArray(capturedPad); + assertTrue(padOwner.isActive(), "the callback owner keeps its captured pad alive"); + + callback.releaseOwner(); + + assertTrue(code.refCount > 0, "the regression requires a stale positive count"); + assertFalse(code.hasPerlOwnerForCaptureOtherThan(null)); + assertNull(code.capturedAggregates); + assertNull(code.capturedAggregateOwnerSlots); + assertFalse(padOwner.isActive()); + assertEquals(0, capturedPad.captureCount); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveArgumentOwnerLedgerFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveArgumentOwnerLedgerFastPathTest.java new file mode 100644 index 0000000000..4a1aa3dda1 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveArgumentOwnerLedgerFastPathTest.java @@ -0,0 +1,54 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ActiveArgumentOwnerLedgerFastPathTest { + @Test + void countedCallerCellRemainsOwnedUntilCallEnd() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId("Issue1649::ActiveArgumentLedger"); + RuntimeScalar released = new RuntimeScalar(); + released.set(target.createAnonymousReference()); + RuntimeScalar callerCell = new RuntimeScalar(); + callerCell.set(target.createAnonymousReference()); + RuntimeScalar weak = target.createAnonymousReference(); + WeakRefRegistry.weaken(weak); + RuntimeCode.CallArguments arguments = RuntimeCode.newCallArguments(1); + arguments.add(callerCell); + + try { + assertEquals(0, target.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE), + "a persistent caller cell remains an aliased borrow"); + assertEquals(2, target.refCount, + "both scalar cells contribute their acquired owner count"); + MortalList.deferDecrementIfTracked(released); + + { + MortalList.flushAboveMark(); + + assertEquals(1, target.refCount); + assertEquals(1, target.countedOwnerSlotCount()); + assertTrue(runtime.lifecycleState.deferredArgumentOwnerReleases.isEmpty(), + "the owner ledger avoids scanning the active argument frame"); + assertTrue(WeakRefRegistry.isweak(weak)); + } + + arguments.finish(); + callerCell.set(new RuntimeScalar()); + assertEquals(RuntimeScalarType.UNDEF, weak.type, + "clearing the caller's final slot clears the weak observer"); + assertEquals(0, target.countedOwnerSlotCount()); + } finally { + arguments.finish(); + if (WeakRefRegistry.isweak(weak)) WeakRefRegistry.unweaken(weak); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveCodeOwnerReleaseOrderingTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveCodeOwnerReleaseOrderingTest.java new file mode 100644 index 0000000000..358e168867 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveCodeOwnerReleaseOrderingTest.java @@ -0,0 +1,57 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; + +@Tag("unit") +class ActiveCodeOwnerReleaseOrderingTest { + @Test + void activeOwnerIdentityOutlivesTheStackEntryDuringFramePop() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar pad = new RuntimeScalar(42); + ObservedRuntimeCode code = new ObservedRuntimeCode(); + code.setTrackedRefCount(0); + code.capturedScalars = new RuntimeScalar[] {pad}; + code.capturedScalarOwnerSlots = new PerlOwnerSlot[] { + pad.retainClosureCaptureSlot(code) + }; + + RuntimeCode.pushActiveCode(code); + code.releaseCaptures(); + assertEquals(1, pad.captureCount, + "the active CODE frame defers capture retirement"); + + { + RuntimeCode.popActiveCode(code); + + assertFalse(code.lastActiveOwnerReleasedWhileOnStack, + "the active owner slot must remain until the stack entry is removed"); + assertEquals(0, code.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_CODE)); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, code.perlLifecycleState()); + assertNull(code.capturedScalars); + assertEquals(0, pad.captureCount); + } + } + } + + private static final class ObservedRuntimeCode extends RuntimeCode { + private boolean lastActiveOwnerReleasedWhileOnStack; + + private ObservedRuntimeCode() { + super((args, context) -> new RuntimeList(), null); + } + + @Override + void finishActiveCodeOwnerRelease() { + if (!hasActiveCodeOwner() && RuntimeCode.isActiveCode(this)) { + lastActiveOwnerReleasedWhileOnStack = true; + } + super.finishActiveCodeOwnerRelease(); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveCodeOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveCodeOwnerTest.java new file mode 100644 index 0000000000..38e5d699a2 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveCodeOwnerTest.java @@ -0,0 +1,143 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.HashSet; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class ActiveCodeOwnerTest { + @Test + void borrowedCodeIsNotFinalizedWithoutACountedOwnerRelease() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar pad = new RuntimeScalar(42); + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + code.setTrackedRefCount(0); + code.capturedScalars = new RuntimeScalar[]{pad}; + code.capturedScalarOwnerSlots = new PerlOwnerSlot[]{pad.retainClosureCaptureSlot()}; + RuntimeCode.pushActiveCode(code); + RuntimeCode.popActiveCode(code); + assertNotNull(code.capturedScalars); + assertEquals(1, pad.captureCount); + assertEquals(0, code.nativeOwnerSlotCount()); + code.releaseCaptures(); + assertEquals(0, pad.captureCount); + } + } + + @Test + void recursiveFramesHaveDistinctNativeOwnersAndReleaseAtTheLastReturn() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + code.setTrackedRefCount(0); + RuntimeScalar owner = new RuntimeScalar(); + owner.set(new RuntimeScalar(code)); + RuntimeScalar weak = new RuntimeScalar(); + weak.set(owner); + WeakRefRegistry.weaken(weak); + RuntimeCode.pushActiveCode(code); + RuntimeCode.pushActiveCode(code); + var identities = new HashSet(); + for (PerlOwnerSlot slot : code.ownerSlotSnapshot()) { + if (slot.kind() == PerlOwnerSlot.Kind.ACTIVE_CODE) { + assertTrue(slot.isNativeOwner()); + identities.add(slot.identity()); + } + } + assertEquals(2, identities.size()); + assertEquals(2, code.nativeOwnerSlotCount()); + assertEquals(0, runtime.positiveOwnerSlotReferentCount(code)); + owner.set(new RuntimeScalar()); + assertEquals(0, code.refCount); + assertEquals(RuntimeScalarType.CODE, weak.type); + RuntimeCode.popActiveCode(code); + assertEquals(1, code.nativeOwnerSlotCount()); + assertEquals(RuntimeScalarType.CODE, weak.type); + { + RuntimeCode.popActiveCode(code); + assertEquals(0, code.nativeOwnerSlotCount()); + assertEquals(RuntimeScalarType.UNDEF, weak.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, code.perlLifecycleState()); + } + } + } + + @Test + void activeFrameProtectsCapturesUntilTheCallerDrainsTheirRetiredOwners() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash guard = new RuntimeHash(); + RuntimeScalar pad = new RuntimeScalar(); + pad.set(guard.createAnonymousReference()); + RuntimeScalar weak = new RuntimeScalar(); + weak.set(pad); + WeakRefRegistry.weaken(weak); + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + code.setTrackedRefCount(0); + code.capturedScalars = new RuntimeScalar[]{pad}; + code.capturedScalarOwnerSlots = new PerlOwnerSlot[]{pad.retainClosureCaptureSlot()}; + RuntimeScalar.scopeExitCleanup(pad); + RuntimeCode.pushActiveCode(code); + code.releaseCaptures(); + assertNotNull(code.capturedScalars); + assertEquals(1, pad.captureCount); + assertEquals(RuntimeScalarType.HASHREFERENCE, weak.type); + RuntimeCode.popActiveCode(code); + MortalList.flushAboveMark(); + assertNull(code.capturedScalars); + assertEquals(0, pad.captureCount); + assertEquals(RuntimeScalarType.UNDEF, weak.type); + } + } + + @Test + void removingAnOuterFrameRetiresOneIdentityAndPreservesOtherRecursiveFrames() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeCode other = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeCode.pushActiveCode(code); + RuntimeCode.pushActiveCode(code); + RuntimeCode.pushActiveCode(other); + RuntimeCode.popActiveCode(code); + assertEquals(1, code.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_CODE)); + assertEquals(1, other.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_CODE)); + RuntimeCode.popActiveCode(other); + RuntimeCode.popActiveCode(code); + assertFalse(code.hasActiveCodeOwner()); + assertFalse(other.hasActiveCodeOwner()); + assertTrue(runtime.executionState().activeCodeStack.isEmpty()); + } + } + @Test + void inactiveClosureCaptureRemainsLiveUntilClosureOwnerLeaves() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash guard = new RuntimeHash(); + guard.blessId = NameNormalizer.getBlessId("Issue1649::CapturedScopeGuard"); + RuntimeScalar pad = new RuntimeScalar(); + pad.set(guard.createAnonymousReference()); + RuntimeScalar weak = new RuntimeScalar(); + weak.set(pad); + WeakRefRegistry.weaken(weak); + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + code.setTrackedRefCount(0); + code.capturedScalars = new RuntimeScalar[]{pad}; + code.capturedScalarOwnerSlots = new PerlOwnerSlot[]{pad.retainClosureCaptureSlot()}; + RuntimeScalar owner = new RuntimeScalar(); + owner.set(new RuntimeScalar(code)); + RuntimeScalar.scopeExitCleanup(pad); + MortalList.flushAboveMark(); + assertEquals(1, pad.captureCount); + assertEquals(RuntimeScalarType.HASHREFERENCE, weak.type); + owner.set(RuntimeScalarCache.scalarUndef); + assertEquals(0, pad.captureCount); + assertEquals(RuntimeScalarType.UNDEF, weak.type); + } + } + +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalAggregateOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalAggregateOwnerSlotTest.java new file mode 100644 index 0000000000..69cedfb9fc --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalAggregateOwnerSlotTest.java @@ -0,0 +1,60 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class ActiveLexicalAggregateOwnerSlotTest { + @Test + void activeArrayAndHashPadsOwnAndReleaseAggregateSlots() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeCode.pushActiveCode(code); + int mark = MyVarCleanupStack.pushMark(); + RuntimeArray array = new RuntimeArray(); + RuntimeHash hash = new RuntimeHash(); + RuntimeScalar weakArray = weakReferenceTo(array); + RuntimeScalar weakHash = weakReferenceTo(hash); + try { + MyVarCleanupStack.register(array); + MyVarCleanupStack.register(hash); + RuntimeCode.registerCurrentActiveLexical("@pad", array); + RuntimeCode.registerCurrentActiveLexical("%pad", hash); + WeakRefRegistry.weaken(weakArray); + WeakRefRegistry.weaken(weakHash); + + assertEquals(1, array.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + assertEquals(1, hash.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + assertTrue(WeakRefRegistry.isweak(weakArray)); + assertTrue(WeakRefRegistry.isweak(weakHash)); + + MortalList.scopeExitCleanupArray(array); + MyVarCleanupStack.unregister(array); + assertEquals(0, array.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + assertFalse(WeakRefRegistry.isweak(weakArray), + "the final array-pad release clears its weak observer immediately"); + + MortalList.scopeExitCleanupHash(hash); + MyVarCleanupStack.unregister(hash); + assertEquals(0, hash.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + assertFalse(WeakRefRegistry.isweak(weakHash), + "the final hash-pad release clears its weak observer immediately"); + } finally { + MyVarCleanupStack.unregister(array); + MyVarCleanupStack.unregister(hash); + MyVarCleanupStack.popMark(mark); + RuntimeCode.popActiveCode(code); + if (WeakRefRegistry.isweak(weakArray)) WeakRefRegistry.unweaken(weakArray); + if (WeakRefRegistry.isweak(weakHash)) WeakRefRegistry.unweaken(weakHash); + } + } + } + + private static RuntimeScalar weakReferenceTo(RuntimeBase target) { + return target.createReference(); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalAggregateWeakOwnerLifecycleTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalAggregateWeakOwnerLifecycleTest.java new file mode 100644 index 0000000000..df48ab786b --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalAggregateWeakOwnerLifecycleTest.java @@ -0,0 +1,56 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ActiveLexicalAggregateWeakOwnerLifecycleTest { + @Test + void weakeningLastCountedReferenceDefersToTheActiveLexicalOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeCode.pushActiveCode(code); + int mark = MyVarCleanupStack.pushMark(); + RuntimeArray array = new RuntimeArray(); + RuntimeScalar weakOwner = new RuntimeScalar(); + try { + MyVarCleanupStack.register(array); + RuntimeCode.registerCurrentActiveLexical("@pad", array); + weakOwner.set(array.createReference()); + + assertEquals(1, array.refCount); + assertEquals(1, array.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + + { + WeakRefRegistry.weaken(weakOwner); + + assertTrue(WeakRefRegistry.isweak(weakOwner)); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, array.refCountTrackingState(), + "the active lexical edge must not be fabricated as a count"); + assertTrue(array.deferredFinalReleaseForUncountedOwners, + "the zero-count lifecycle must wait on the exact pad owner"); + + MortalList.scopeExitCleanupArray(array); + MyVarCleanupStack.unregister(array); + + assertEquals(0, array.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + assertEquals(RuntimeScalarType.UNDEF, weakOwner.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, array.perlLifecycleState()); + assertEquals(0, array.refCount); + assertFalse(array.deferredFinalReleaseForUncountedOwners); + } + } finally { + MyVarCleanupStack.unregister(array); + MyVarCleanupStack.popMark(mark); + RuntimeCode.popActiveCode(code); + if (WeakRefRegistry.isweak(weakOwner)) WeakRefRegistry.unweaken(weakOwner); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalCallerFrameTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalCallerFrameTest.java new file mode 100644 index 0000000000..e3eca4a436 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalCallerFrameTest.java @@ -0,0 +1,32 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ActiveLexicalCallerFrameTest { + @Test + void identifiesCallerCellsAcrossRecursiveFramesOfTheSameCode() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode recursiveCode = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar callerCell = new RuntimeScalar(1); + RuntimeScalar currentCell = new RuntimeScalar(2); + + RuntimeCode.pushActiveCode(recursiveCode); + RuntimeCode.registerCurrentActiveLexical("$caller", callerCell); + RuntimeCode.pushActiveCode(recursiveCode); + RuntimeCode.registerCurrentActiveLexical("$current", currentCell); + try { + assertTrue(RuntimeCode.isActiveLexicalCellInCallerFrame(callerCell, recursiveCode)); + assertFalse(RuntimeCode.isActiveLexicalCellInCallerFrame(currentCell, recursiveCode)); + } finally { + RuntimeCode.popActiveCode(recursiveCode); + RuntimeCode.popActiveCode(recursiveCode); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalOwnerReplacementOrderTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalOwnerReplacementOrderTest.java new file mode 100644 index 0000000000..07220f708e --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalOwnerReplacementOrderTest.java @@ -0,0 +1,105 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +@Tag("unit") +class ActiveLexicalOwnerReplacementOrderTest { + @Test + void activeFrameRetargetsItsLexicalOwnerSlotBeforeReleasingThePreviousCell() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + MortalList.setActive(true); + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeCode.pushActiveCode(code); + int mark = MyVarCleanupStack.pushMark(); + List events = new ArrayList<>(); + RecordingArray previous = new RecordingArray("previous", events); + RecordingArray replacement = new RecordingArray("replacement", events); + try { + MyVarCleanupStack.register(previous); + MyVarCleanupStack.register(replacement); + RuntimeCode.registerCurrentActiveLexical("@pad", previous); + PerlOwnerSlot slot = activeLexicalSlot(previous); + events.clear(); + + RuntimeCode.registerCurrentActiveLexical("@pad", replacement); + + assertEquals(List.of("replacement:add", "previous:remove"), events); + assertSame(replacement, slot.referent()); + assertSame(slot, activeLexicalSlot(replacement)); + assertEquals(0, previous.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + assertEquals(1, replacement.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + } finally { + MyVarCleanupStack.unregister(previous); + MyVarCleanupStack.unregister(replacement); + MyVarCleanupStack.popMark(mark); + RuntimeCode.popActiveCode(code); + } + } + } + + @Test + void topLevelPadRetargetsItsLexicalOwnerSlotBeforeReleasingThePreviousCell() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + MortalList.setActive(true); + int mark = MyVarCleanupStack.pushMark(); + List events = new ArrayList<>(); + RecordingArray previous = new RecordingArray("previous", events); + RecordingArray replacement = new RecordingArray("replacement", events); + try { + MyVarCleanupStack.register(previous); + MyVarCleanupStack.register(replacement); + RuntimeCode.registerCurrentActiveLexical("@pad", previous); + PerlOwnerSlot slot = activeLexicalSlot(previous); + events.clear(); + + RuntimeCode.registerCurrentActiveLexical("@pad", replacement); + + assertEquals(List.of("replacement:add", "previous:remove"), events); + assertSame(replacement, slot.referent()); + assertSame(slot, activeLexicalSlot(replacement)); + assertEquals(0, previous.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + assertEquals(1, replacement.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + } finally { + MyVarCleanupStack.unregister(previous); + MyVarCleanupStack.unregister(replacement); + MyVarCleanupStack.popMark(mark); + } + } + } + + private static PerlOwnerSlot activeLexicalSlot(RuntimeBase cell) { + return cell.ownerSlotSnapshot().stream() + .filter(slot -> slot.kind() == PerlOwnerSlot.Kind.ACTIVE_LEXICAL) + .findFirst() + .orElseThrow(); + } + + private static final class RecordingArray extends RuntimeArray { + private final String name; + private final List events; + + private RecordingArray(String name, List events) { + this.name = name; + this.events = events; + } + + @Override + synchronized void addOwnerSlot(PerlOwnerSlot slot) { + events.add(name + ":add"); + super.addOwnerSlot(slot); + } + + @Override + synchronized void removeOwnerSlot(PerlOwnerSlot slot) { + events.add(name + ":remove"); + super.removeOwnerSlot(slot); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalScalarOwnerLifecycleTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalScalarOwnerLifecycleTest.java new file mode 100644 index 0000000000..c96fff2fc5 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalScalarOwnerLifecycleTest.java @@ -0,0 +1,82 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ActiveLexicalScalarOwnerLifecycleTest { + @Test + void scalarOverwriteDefersZeroCountCleanupToTheLexicalOwnerIdentity() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeCode.pushActiveCode(code); + int mark = MyVarCleanupStack.pushMark(); + RuntimeScalar cell = new RuntimeScalar(42); + cell.blessId = NameNormalizer.getBlessId( + "ActiveLexicalScalarOwnerLifecycleTest::Cell"); + RuntimeCode.registerCurrentActiveLexical("$cell", cell); + MyVarCleanupStack.register(cell); + + RuntimeScalar objectOwner = new RuntimeScalar(); + RuntimeScalar weakOwner = new RuntimeScalar(); + RuntimeScalar weakReference = null; + try { + RuntimeScalar reference = cell.createReference(); + objectOwner.set(reference); + weakOwner.set(reference); + WeakRefRegistry.weaken(weakOwner); + weakReference = weakOwner; + + assertEquals(1, cell.refCount); + objectOwner.set(new RuntimeScalar()); + + assertEquals(0, cell.refCount); + assertTrue(cell.deferredFinalReleaseForUncountedOwners, + "zero-count cleanup waits on the active lexical owner identity"); + assertTrue(WeakRefRegistry.isweak(weakReference)); + + RuntimeScalar.scopeExitCleanup(cell); + MyVarCleanupStack.unregister(cell); + + assertEquals(RuntimeScalarType.UNDEF, weakReference.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + cell.perlLifecycleState()); + } finally { + MyVarCleanupStack.unregister(cell); + MyVarCleanupStack.popMark(mark); + RuntimeCode.popActiveCode(code); + if (weakReference != null && WeakRefRegistry.isweak(weakReference)) { + WeakRefRegistry.unweaken(weakReference); + } + } + } + } + + @Test + void lexicalPadRegistrationAfterReferenceCreationBackfillsTheOwnerIdentity() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeCode.pushActiveCode(code); + int mark = MyVarCleanupStack.pushMark(); + RuntimeScalar cell = new RuntimeScalar(42); + try { + cell.createReference(); + MyVarCleanupStack.register(cell); + RuntimeCode.registerCurrentActiveLexical("$cell", cell); + + assertEquals(1, cell.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL), + "late pad binding backfills the scalar-cell owner identity"); + } finally { + MyVarCleanupStack.unregister(cell); + MyVarCleanupStack.popMark(mark); + RuntimeCode.popActiveCode(code); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalScalarOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalScalarOwnerSlotTest.java new file mode 100644 index 0000000000..262a742ecd --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ActiveLexicalScalarOwnerSlotTest.java @@ -0,0 +1,65 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class ActiveLexicalScalarOwnerSlotTest { + @Test + void referencedScalarCellOwnsItsLexicalLifetimeUntilScopeExit() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeCode.pushActiveCode(code); + int mark = MyVarCleanupStack.pushMark(); + RuntimeScalar cell = new RuntimeScalar(42); + cell.blessId = NameNormalizer.getBlessId("Issue1649::LexicalScalarCell"); + RuntimeCode.registerCurrentActiveLexical("$cell", cell); + MyVarCleanupStack.register(cell); + + RuntimeScalar objectOwner = new RuntimeScalar(); + RuntimeScalar weakOwner = new RuntimeScalar(); + RuntimeScalar weakReference = null; + try { + RuntimeScalar reference = cell.createReference(); + objectOwner.set(reference); + weakOwner.set(reference); + WeakRefRegistry.weaken(weakOwner); + weakReference = weakOwner; + + assertEquals(1, cell.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL), + "the registered lexical cell has an explicit owner identity"); + assertEquals(1, cell.refCount, + "weakening leaves only the strong scalar-cell reference counted"); + + objectOwner.set(new RuntimeScalar()); + + assertEquals(0, cell.refCount, + "releasing the counted edge does not fabricate a positive count"); + assertTrue(WeakRefRegistry.isweak(weakReference), + "the lexical owner keeps the weak observer live"); + assertEquals(RuntimeBase.PerlLifecycleState.LIVE, + cell.perlLifecycleState()); + + RuntimeScalar.scopeExitCleanup(cell); + MyVarCleanupStack.unregister(cell); + + assertEquals(0, cell.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + assertEquals(RuntimeScalarType.UNDEF, weakReference.type, + "the final lexical owner release clears the weak observer"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + cell.perlLifecycleState()); + } finally { + MyVarCleanupStack.unregister(cell); + MyVarCleanupStack.popMark(mark); + RuntimeCode.popActiveCode(code); + if (weakReference != null && WeakRefRegistry.isweak(weakReference)) { + WeakRefRegistry.unweaken(weakReference); + } + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/AggregateOutgoingEdgeCleanupTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/AggregateOutgoingEdgeCleanupTest.java new file mode 100644 index 0000000000..4dc6c3662c --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/AggregateOutgoingEdgeCleanupTest.java @@ -0,0 +1,105 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class AggregateOutgoingEdgeCleanupTest { + @Test + void hashCleanupReleasesNestedArrayOutgoingEdge() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash child = blessedHash("HashChild"); + RuntimeScalar childReference = child.createAnonymousReference(); + RuntimeArray nested = new RuntimeArray(); + nested.push(childReference); + RuntimeHash parent = new RuntimeHash(); + parent.put("nested", nested.createAnonymousReference()); + RuntimeScalar childWeakReference = child.createAnonymousReference(); + + WeakRefRegistry.weaken(childWeakReference); + assertEquals(1, + child.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + + MortalList.scopeExitCleanupHash(parent); + MortalList.flush(); + + assertEquals(0, + child.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + assertFalse(WeakRefRegistry.isweak(childWeakReference)); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + child.perlLifecycleState()); + } + } + + @Test + void arrayCleanupReleasesNestedHashOutgoingEdge() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash child = blessedHash("ArrayChild"); + RuntimeScalar childReference = child.createAnonymousReference(); + RuntimeHash nested = new RuntimeHash(); + nested.put("child", childReference); + RuntimeArray parent = new RuntimeArray(); + parent.push(nested.createAnonymousReference()); + RuntimeScalar childWeakReference = child.createAnonymousReference(); + + WeakRefRegistry.weaken(childWeakReference); + assertEquals(1, + child.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + + MortalList.scopeExitCleanupArray(parent); + MortalList.flush(); + + assertEquals(0, + child.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + assertFalse(WeakRefRegistry.isweak(childWeakReference)); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + child.perlLifecycleState()); + } + } + + @Test + void liveNestedAggregateOwnerKeepsItsOutgoingEdges() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash child = blessedHash("SharedChild"); + RuntimeScalar childReference = child.createAnonymousReference(); + RuntimeArray nested = new RuntimeArray(); + nested.push(childReference); + RuntimeArray parent = new RuntimeArray(); + parent.push(nested.createAnonymousReference()); + RuntimeScalar nestedKeeper = new RuntimeScalar(); + nestedKeeper.localBindingExists = true; + nestedKeeper.set(nested.createAnonymousReference()); + RuntimeScalar childWeakReference = child.createAnonymousReference(); + + WeakRefRegistry.weaken(childWeakReference); + assertEquals(1, + child.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + + MortalList.scopeExitCleanupArray(parent); + MortalList.flush(); + + assertTrue(WeakRefRegistry.isweak(childWeakReference)); + assertEquals(1, + child.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + assertTrue(nested.hasCurrentPerlStorageOwner()); + + RuntimeScalar.scopeExitCleanup(nestedKeeper); + MortalList.flush(); + assertFalse(WeakRefRegistry.isweak(childWeakReference)); + assertEquals(0, + child.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + WeakRefRegistry.unweaken(childWeakReference); + } + } + + private static RuntimeHash blessedHash(String suffix) { + RuntimeHash hash = new RuntimeHash(); + hash.setBlessId(NameNormalizer.getBlessId( + "AggregateOutgoingEdgeCleanupTest::" + suffix)); + return hash; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ArgumentAliasHandoffOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ArgumentAliasHandoffOwnerSlotTest.java new file mode 100644 index 0000000000..ded350021d --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ArgumentAliasHandoffOwnerSlotTest.java @@ -0,0 +1,133 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +@Tag("unit") +class ArgumentAliasHandoffOwnerSlotTest { + @Test + void queuedArgumentReleaseKeepsExplicitFrameIdentityAcrossCopyButNotThreadClone() { + PerlRuntime sourceRuntime = new PerlRuntime(); + PerlRuntime childRuntime = new PerlRuntime(); + RuntimeScalar sourceArgument = new RuntimeScalar(7); + RuntimeHash pendingBase = new RuntimeHash(); + RuntimeScalar copiedArgument; + Object sourceFrame; + boolean frameActive = false; + + try (PerlRuntime.Binding ignored = sourceRuntime.bind()) { + RuntimeArray arguments = new RuntimeArray(); + arguments.elements.add(sourceArgument); + RuntimeCode.pushArgs(arguments); + frameActive = true; + sourceFrame = RuntimeCode.currentArgumentAliasFrame(sourceArgument); + + copiedArgument = new RuntimeScalar(sourceArgument); + assertSame(sourceFrame, + RuntimeCode.argumentAliasFrameForOwner(copiedArgument)); + + MortalList.deferDecrementFromArraySlot( + pendingBase, copiedArgument, "argument-frame identity test"); + assertSame(sourceFrame, sourceRuntime.lifecycleState.pendingArgumentFrames.get(0), + "the queue records the originating frame identity at enqueue time"); + + RuntimeCode.popArgs(); + frameActive = false; + + RuntimeScalar clonedArgument = (RuntimeScalar) new RuntimeGraphCloner( + sourceRuntime, childRuntime).cloneGraph(copiedArgument); + try (PerlRuntime.Binding childBinding = childRuntime.bind()) { + assertNull(RuntimeCode.argumentAliasFrameForOwner(clonedArgument), + "a cloned scalar cannot retain a parent thread's argument frame"); + } + MortalList.clearCurrentRuntimeState(); + } finally { + if (frameActive) { + try (PerlRuntime.Binding ignored = sourceRuntime.bind()) { + RuntimeCode.popArgs(); + MortalList.clearCurrentRuntimeState(); + } + } + } + } + + @Test + void tailCallTargetFrameGetsAndReleasesItsOwnAliasIdentity() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar cell = new RuntimeScalar(); + cell.isPackageGlobalRoot = true; + cell.set(referent.createAnonymousReference()); + int originalRefCount = referent.refCount; + + RuntimeArray sourceArgs = new RuntimeArray(); + sourceArgs.elements.add(cell); + RuntimeArray targetArgs = new RuntimeArray(); + targetArgs.elements.add(cell); + boolean sourceFrameActive = false; + boolean targetFrameActive = false; + try { + RuntimeCode.pushArgs(sourceArgs); + sourceFrameActive = true; + RuntimeCode.pushArgs(targetArgs); + targetFrameActive = true; + + assertEquals(2, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS), + "the tail-call target owns a separate active-frame identity"); + assertEquals(originalRefCount, referent.refCount, + "frame identities do not change Perl-visible reference counts"); + + RuntimeCode.popArgs(); + targetFrameActive = false; + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS)); + + RuntimeCode.popArgs(); + sourceFrameActive = false; + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS)); + } finally { + if (targetFrameActive) RuntimeCode.popArgs(); + if (sourceFrameActive) RuntimeCode.popArgs(); + } + } + } + + @Test + void sharedScalarArgumentRetiresItsAliasIdentityOnOverwriteAndFrameExit() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash sharedReferent = new RuntimeHash(); + sharedReferent.threadShared = true; + sharedReferent.threadSharedIdentity = new Object(); + RuntimeScalar sharedCell = new RuntimeScalar(); + sharedCell.localBindingExists = true; + sharedCell.set(sharedReferent.createAnonymousReference()); + sharedCell.threadShared = true; + sharedCell.threadSharedIdentity = new Object(); + + RuntimeArray args = new RuntimeArray(); + args.elements.add(sharedCell); + boolean argsActive = false; + try { + RuntimeCode.pushArgs(args); + argsActive = true; + assertEquals(1, sharedReferent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS)); + + sharedCell.set(new RuntimeScalar(1)); + assertEquals(0, sharedReferent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS), + "a shared cell transfers its frame identity when its value changes"); + + RuntimeCode.popArgs(); + argsActive = false; + assertEquals(0, sharedReferent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS), + "frame exit does not release the transferred identity twice"); + } finally { + if (argsActive) RuntimeCode.popArgs(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ArgumentAliasOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ArgumentAliasOwnerSlotTest.java new file mode 100644 index 0000000000..88e779aec4 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ArgumentAliasOwnerSlotTest.java @@ -0,0 +1,290 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ArgumentAliasOwnerSlotTest { + @Test + void removingOneDuplicateArgumentSlotRetiresOnlyItsFrameIdentity() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + RuntimeScalar cell = new RuntimeScalar(); + cell.isPackageGlobalRoot = true; + cell.set(target.createAnonymousReference()); + RuntimeArray args = new RuntimeArray(); + args.elements.add(cell); + args.elements.add(cell); + boolean argsActive = false; + try { + RuntimeCode.pushArgs(args); + argsActive = true; + + assertEquals(2, target.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS)); + assertSame(cell, RuntimeArray.shift(args)); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS), + "removing one duplicate @_ slot retires exactly one frame identity"); + + assertSame(cell, RuntimeArray.pop(args)); + assertEquals(0, target.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS), + "removing the last duplicate retires its remaining identity"); + + RuntimeCode.popArgs(); + argsActive = false; + assertEquals(0, target.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS)); + } finally { + if (argsActive) RuntimeCode.popArgs(); + } + } + } + + @Test + void replacingAndClearingArgumentSlotsRetiresTheirFrameIdentities() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash first = new RuntimeHash(); + RuntimeHash second = new RuntimeHash(); + RuntimeScalar firstCell = new RuntimeScalar(); + firstCell.isPackageGlobalRoot = true; + firstCell.set(first.createAnonymousReference()); + RuntimeScalar secondCell = new RuntimeScalar(); + secondCell.isPackageGlobalRoot = true; + secondCell.set(second.createAnonymousReference()); + RuntimeArray args = new RuntimeArray(); + args.elements.add(firstCell); + args.elements.add(secondCell); + boolean argsActive = false; + try { + RuntimeCode.pushArgs(args); + argsActive = true; + + args.elements.set(0, new RuntimeScalar()); + assertEquals(0, first.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS)); + assertEquals(1, second.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS)); + + args.elements.clear(); + assertEquals(0, second.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS)); + + RuntimeCode.popArgs(); + argsActive = false; + assertEquals(0, first.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS)); + assertEquals(0, second.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS)); + } finally { + if (argsActive) RuntimeCode.popArgs(); + } + } + } + + @Test + void stagedAndActiveArgumentAliasesTrackCellAssignmentsWithoutChangingRefCount() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash first = new RuntimeHash(); + RuntimeHash second = new RuntimeHash(); + RuntimeScalar cell = new RuntimeScalar(); + cell.isPackageGlobalRoot = true; + RuntimeCode.CallArguments staged = RuntimeCode.newCallArguments(1); + RuntimeArray args = null; + boolean argsActive = false; + + try { + cell.set(first.createAnonymousReference()); + int initialRuntimeRoots = runtime.positiveOwnerSlotReferentCount(first); + int firstRefCount = first.refCount; + staged.add(cell); + args = staged.toRuntimeArray(); + RuntimeCode.pushArgs(args); + argsActive = true; + + assertEquals(firstRefCount, first.refCount, + "argument alias identities must not add Perl-visible references"); + assertEquals(initialRuntimeRoots, runtime.positiveOwnerSlotReferentCount(first), + "an active alias frame must not register another runtime root"); + assertEquals(2, first.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS), + "staging and active @_ each have their own frame identity"); + + cell.set(new RuntimeScalar(7)); + assertEquals(0, first.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS), + "assigning a primitive releases the old referent identities"); + + RuntimeScalar secondReference = second.createAnonymousReference(); + int secondRefCountBeforeStore = second.refCount; + cell.set(secondReference); + assertEquals(2, second.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS), + "a primitive argument cell can acquire a later reference value"); + assertEquals(secondRefCountBeforeStore + 1, second.refCount, + "the two alias identities do not add to the normal scalar-store count"); + + cell.set(new RuntimeScalar()); + assertEquals(0, second.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS)); + } finally { + if (argsActive) RuntimeCode.popArgs(); + staged.finish(); + } + } + } + + @Test + void overwrittenOwnerWaitsForAllArgumentAliasFramesBeforeFinalRelease() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + MortalList.pushMark(); + boolean markActive = true; + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId("Issue1649::ArgumentAlias"); + RuntimeScalar released = new RuntimeScalar(); + released.set(target.createAnonymousReference()); + RuntimeScalar argumentCell = new RuntimeScalar(); + argumentCell.isPackageGlobalRoot = true; + argumentCell.set(target.createAnonymousReference()); + PerlOwnerSlot argumentCellOwner = argumentCell.countedOwnerSlot(); + argumentCellOwner.release(); + argumentCell.refCountOwned = false; + target.setTrackedRefCount(1); // The released scalar is the only counted owner. + + RuntimeScalar weak = target.createAnonymousReference(); + WeakRefRegistry.weaken(weak); + RuntimeCode.CallArguments staged = RuntimeCode.newCallArguments(1); + RuntimeArray args = null; + boolean argsActive = false; + try { + staged.add(argumentCell); + args = staged.toRuntimeArray(); + RuntimeCode.pushArgs(args); + argsActive = true; + + { + released.set(new RuntimeScalar()); + MortalList.flushAboveMark(); + + assertEquals(1, target.refCount); + assertEquals(2, target.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS)); + assertTrue(WeakRefRegistry.isweak(weak)); + } + + RuntimeCode.popArgs(); + argsActive = false; + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS), + "the staged call identity remains until CallArguments.finish()"); + assertTrue(WeakRefRegistry.isweak(weak)); + + staged.finish(); + assertEquals(0, target.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS)); + assertEquals(RuntimeScalarType.UNDEF, weak.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + target.perlLifecycleState()); + + MortalList.popAndFlush(); + markActive = false; + } finally { + if (argsActive) RuntimeCode.popArgs(); + staged.finish(); + if (markActive) MortalList.popAndFlush(); + if (WeakRefRegistry.isweak(weak)) WeakRefRegistry.unweaken(weak); + } + } + } + + @Test + void explicitUndefKeepsAWeaklyObservedTargetUntilArgumentAliasesExit() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + MortalList.pushMark(); + boolean markActive = true; + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId("Issue1649::ArgumentAliasUndef"); + RuntimeScalar released = new RuntimeScalar(); + released.set(target.createAnonymousReference()); + RuntimeScalar argumentCell = new RuntimeScalar(); + argumentCell.isPackageGlobalRoot = true; + argumentCell.set(target.createAnonymousReference()); + argumentCell.countedOwnerSlot().release(); + argumentCell.refCountOwned = false; + target.setTrackedRefCount(1); + + RuntimeScalar weak = target.createAnonymousReference(); + WeakRefRegistry.weaken(weak); + RuntimeCode.CallArguments staged = RuntimeCode.newCallArguments(1); + RuntimeArray args = null; + boolean argsActive = false; + try { + staged.add(argumentCell); + args = staged.toRuntimeArray(); + RuntimeCode.pushArgs(args); + argsActive = true; + + released.undefine(); + assertEquals(1, target.refCount); + assertTrue(WeakRefRegistry.isweak(weak)); + assertEquals(2, target.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS)); + + RuntimeCode.popArgs(); + argsActive = false; + assertTrue(WeakRefRegistry.isweak(weak)); + staged.finish(); + + assertEquals(RuntimeScalarType.UNDEF, weak.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + target.perlLifecycleState()); + MortalList.popAndFlush(); + markActive = false; + } finally { + if (argsActive) RuntimeCode.popArgs(); + staged.finish(); + if (markActive) MortalList.popAndFlush(); + if (WeakRefRegistry.isweak(weak)) WeakRefRegistry.unweaken(weak); + } + } + } + + @Test + void transientArgumentValuesDoNotGetPersistentCellIdentities() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + RuntimeScalar transientValue = target.createAnonymousReference(); + RuntimeCode.CallArguments staged = RuntimeCode.newCallArguments(1); + RuntimeArray args = null; + boolean argsActive = false; + + try { + staged.add(transientValue); + args = staged.toRuntimeArray(); + RuntimeCode.pushArgs(args); + argsActive = true; + + assertEquals(0, target.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS), + "temporary expression wrappers are not caller storage cells"); + } finally { + if (argsActive) RuntimeCode.popArgs(); + staged.finish(); + } + } + } + + @Test + void staleCellReleasesAliasIdentityWhenReferentWasAlreadyDestroyed() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + RuntimeScalar cell = new RuntimeScalar(); + cell.isPackageGlobalRoot = true; + cell.set(target.createAnonymousReference()); + RuntimeScalar.ArgumentAliasOwner alias = cell.retainArgumentAliasOwner(); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS)); + + target.markPerlDestroyed(); + cell.refreshArgumentAliasOwnerSlots(); + + assertEquals(0, target.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS)); + alias.release(); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ArgumentOwnerCleanupFailureTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ArgumentOwnerCleanupFailureTest.java new file mode 100644 index 0000000000..1f8c70c27b --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ArgumentOwnerCleanupFailureTest.java @@ -0,0 +1,33 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +@Tag("unit") +class ArgumentOwnerCleanupFailureTest { + @Test + void cleanupAttemptsLaterActionsAndPreservesTheFirstFailure() { + IllegalStateException firstFailure = new IllegalStateException("first release failed"); + IllegalArgumentException secondFailure = + new IllegalArgumentException("second release failed"); + AtomicInteger laterCleanupCount = new AtomicInteger(); + + Throwable failure = RuntimeCode.attemptCleanup(null, () -> { + throw firstFailure; + }); + failure = RuntimeCode.attemptCleanup(failure, () -> { + throw secondFailure; + }); + failure = RuntimeCode.attemptCleanup(failure, laterCleanupCount::incrementAndGet); + + assertSame(firstFailure, failure); + assertEquals(1, failure.getSuppressed().length); + assertSame(secondFailure, failure.getSuppressed()[0]); + assertEquals(1, laterCleanupCount.get()); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ArrayElementOwnerReleaseClearsWeakObserverTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ArrayElementOwnerReleaseClearsWeakObserverTest.java new file mode 100644 index 0000000000..421cbbead8 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ArrayElementOwnerReleaseClearsWeakObserverTest.java @@ -0,0 +1,37 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ArrayElementOwnerReleaseClearsWeakObserverTest { + @Test + void arrayElementOwnerReleaseClearsTheWeakObserver() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray capturedParent = new RuntimeArray(); + RuntimeArray target = new RuntimeArray(); + target.localBindingExists = false; + capturedParent.addClonedElement(target.createAnonymousReference()); + + RuntimeScalar weakTarget = target.createAnonymousReference(); + WeakRefRegistry.weaken(weakTarget); + try { + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + assertTrue(WeakRefRegistry.isweak(weakTarget), + "the exact array element owner preserves its weak observer"); + MortalList.scopeExitCleanupArray(capturedParent); + MortalList.flush(); + assertEquals(0, target.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + assertFalse(WeakRefRegistry.isweak(weakTarget), + "clearing the final strong Perl slot releases the weak observer"); + } finally { + if (WeakRefRegistry.isweak(weakTarget)) WeakRefRegistry.unweaken(weakTarget); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/BlessExistingScalarOwnerIdentityTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/BlessExistingScalarOwnerIdentityTest.java new file mode 100644 index 0000000000..6ec6aafc21 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/BlessExistingScalarOwnerIdentityTest.java @@ -0,0 +1,55 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.runtime.operators.ReferenceOperators; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class BlessExistingScalarOwnerIdentityTest { + @Test + void reblessingAnUntrackedReferentRecordsBothScalarAndMortalOwners() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + RuntimeHash referent = new RuntimeHash(); + referent.blessId = NameNormalizer.getBlessId("Issue1649::Original"); + assertTrue(referent.blessId != 0, "the setup is an already-blessed referent"); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, referent.refCountTrackingState(), "the existing referent is untracked"); + RuntimeScalar scalarOwner = new RuntimeScalar(); + scalarOwner.type = RuntimeScalarType.REFERENCE; + scalarOwner.value = referent; + MyVarCleanupStack.register(scalarOwner); + + try { + { + ReferenceOperators.bless(scalarOwner, + new RuntimeScalar("Issue1649::Reblessed")); + + assertEquals("Issue1649::Reblessed", + NameNormalizer.getBlessStr(referent.blessId)); + assertEquals(2, referent.refCount, + "the existing scalar slot and bless temporary each own one count"); + assertEquals(2, referent.countedOwnerSlotCount(), + "both count producers must install one owner identity"); + PerlOwnerSlot scalarSlot = scalarOwner.countedOwnerSlot(); + assertNotNull(scalarSlot); + assertTrue(scalarOwner.isCurrentCountedScalarOwner(referent, scalarSlot)); + + MortalList.flush(); + + assertEquals(1, referent.refCount, + "draining the bless temporary leaves the scalar slot's count"); + assertEquals(1, referent.countedOwnerSlotCount()); + assertTrue(scalarOwner.isCurrentCountedScalarOwner(referent, scalarSlot)); + } + } finally { + if (scalarOwner.refCountOwned) scalarOwner.set(new RuntimeScalar()); + MyVarCleanupStack.unregister(scalarOwner); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/BlessTemporaryOwnerProvenanceTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/BlessTemporaryOwnerProvenanceTest.java new file mode 100644 index 0000000000..cc74811309 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/BlessTemporaryOwnerProvenanceTest.java @@ -0,0 +1,44 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.runtime.operators.ReferenceOperators; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class BlessTemporaryOwnerProvenanceTest { + @Test + void firstBlessQueuesTheTemporaryCountWithItsScalarOwnerIdentity() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar expression = referent.createAnonymousReference(); + + ReferenceOperators.bless(expression, new RuntimeScalar( + "Issue1649::BlessTemporaryOwner")); + + assertEquals(1, referent.refCount, + "the bless expression has one deferred temporary owner"); + assertEquals(1, referent.countedOwnerSlotCount()); + RuntimeBase.PendingOwnerRelease pending = + runtime.lifecycleState.pendingOwnerReleases.getLast(); + assertNotNull(pending.ownerSlotRelease, + "the temporary decrement carries exact owner-slot provenance"); + assertEquals(PerlOwnerSlot.Kind.SCALAR_CELL, + pending.ownerSlotRelease.kind()); + assertFalse(pending.completed.get()); + + MortalList.flush(); + + assertTrue(pending.completed.get()); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState(), + "the final temporary release completes lifecycle cleanup"); + assertEquals(0, referent.refCount); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/BlessedGlobAliasOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/BlessedGlobAliasOwnerSlotTest.java new file mode 100644 index 0000000000..f2440d7cd6 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/BlessedGlobAliasOwnerSlotTest.java @@ -0,0 +1,93 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.perlonjava.runtime.operators.ReferenceOperators; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class BlessedGlobAliasOwnerSlotTest { + @Test + void weakAliasIsNotCountedAlongsideStrongLexicalAliases() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeGlob glob = new RuntimeGlob(null); + glob.setTrackedRefCount(2); + glob.blessId = NameNormalizer.getBlessId( + "BlessedGlobAliasOwnerSlotTest::GlobOwner"); + + RuntimeScalar first = globAlias(glob); + RuntimeScalar second = globAlias(glob); + RuntimeScalar weak = globReference(glob); + MyVarCleanupStack.register(first); + MyVarCleanupStack.register(second); + MyVarCleanupStack.register(weak); + WeakRefRegistry.weaken(weak); + + try { + MyVarCleanupStack.retainBlessedGlobAliases(glob, glob); + + assertEquals(4, glob.refCount); + assertEquals(2, glob.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + assertTrue(first.refCountOwned); + assertTrue(second.refCountOwned); + assertTrue(first.isCurrentCountedScalarOwner( + glob, first.countedOwnerSlot())); + assertTrue(second.isCurrentCountedScalarOwner( + glob, second.countedOwnerSlot())); + assertTrue(WeakRefRegistry.isweak(weak)); + assertFalse(weak.refCountOwned, + "a weak scalar must not be retained as a glob alias"); + } finally { + WeakRefRegistry.clearWeakRefsTo(glob); + MyVarCleanupStack.unregister(weak); + MyVarCleanupStack.unregister(second); + MyVarCleanupStack.unregister(first); + } + } + } + + @Test + void blessingWeakRegisteredScalarDoesNotAcquireStrongGlobOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeGlob glob = new RuntimeGlob(null); + glob.markRefCountWeaklyTracked(); + RuntimeScalar weak = globReference(glob); + MyVarCleanupStack.register(weak); + WeakRefRegistry.weaken(weak); + + try { + ReferenceOperators.bless(weak, + new RuntimeScalar("BlessedGlobAliasOwnerSlotTest::WeakBless")); + + assertEquals(1, glob.refCount); + assertEquals(0, glob.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + assertFalse(weak.refCountOwned, + "bless must not turn a weak scalar into a strong glob owner"); + assertTrue(WeakRefRegistry.isweak(weak)); + } finally { + WeakRefRegistry.clearWeakRefsTo(glob); + MyVarCleanupStack.unregister(weak); + MortalList.flush(); + } + } + } + + private static RuntimeScalar globAlias(RuntimeGlob glob) { + RuntimeScalar alias = new RuntimeScalar(); + alias.type = RuntimeScalarType.GLOB; + alias.value = glob; + return alias; + } + + private static RuntimeScalar globReference(RuntimeGlob glob) { + RuntimeScalar alias = new RuntimeScalar(); + alias.type = RuntimeScalarType.GLOBREFERENCE; + alias.value = glob; + return alias; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/BlessedPackageOwnerRecursiveReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/BlessedPackageOwnerRecursiveReleaseTest.java new file mode 100644 index 0000000000..041bf986af --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/BlessedPackageOwnerRecursiveReleaseTest.java @@ -0,0 +1,78 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class BlessedPackageOwnerRecursiveReleaseTest { + @Test + void lastCountedOuterReleaseDoesNotReleaseChildrenOfPackageOwnedParent() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + String globalName = + "BlessedPackageOwnerRecursiveReleaseTest::packageRoot"; + RuntimeArray packageRoot = new RuntimeArray(); + GlobalVariable.globalArrays.put(globalName, packageRoot); + + RuntimeHash parent = new RuntimeHash(); + parent.blessId = NameNormalizer.getBlessId( + "Issue1649::PackageOwnedParent"); + RuntimeScalar packageOwner = parent.createAnonymousReference(); + parent.markRefCountUntracked(); + packageRoot.elements.add(packageOwner); + + RuntimeArray child = new RuntimeArray(); + RuntimeScalar childOwner = child.createAnonymousReference(); + parent.put("child", childOwner); + RuntimeScalar weakObserver = child.createAnonymousReference(); + WeakRefRegistry.weaken(weakObserver); + + RuntimeHash outer = new RuntimeHash(); + outer.put("parent", parent.createAnonymousReference()); + + try { + assertEquals(1, + parent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertEquals(1, parent.countedOwnerSlotCount()); + assertTrue(parent.hasPerlStrongOwnerIdentity(), + "the package slot proves a live Perl owner before clearing the outer hash"); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + + outer.undefine(); + + assertEquals(1, + parent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE), + "the package slot still owns the blessed parent"); + assertEquals(0, parent.countedOwnerSlotCount(), + "the outer hash slot was the parent's only counted owner"); + assertTrue(parent.hasPerlStrongOwnerIdentity(), + "the package owner remains live after the outer hash is cleared"); + assertNotEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + parent.perlLifecycleState()); + assertTrue(WeakRefRegistry.isweak(weakObserver), + "the package-owned parent still owns its nested child"); + assertTrue(weakObserver.value == child, + "recursive release must not clear the child's weak observer"); + + packageOwner.undefine(); + + assertEquals(0, + parent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + parent.perlLifecycleState(), + "the parent is destroyed when its final package owner leaves"); + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type, + "the child weak observer clears with final parent destruction"); + } finally { + WeakRefRegistry.clearWeakRefsTo(child); + GlobalVariable.globalArrays.remove(globalName); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/BoundRuntimeNamedCallExceptionUnwindTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/BoundRuntimeNamedCallExceptionUnwindTest.java new file mode 100644 index 0000000000..c4f4c0b81e --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/BoundRuntimeNamedCallExceptionUnwindTest.java @@ -0,0 +1,57 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@Tag("unit") +class BoundRuntimeNamedCallExceptionUnwindTest { + @Test + void namedCallUnwindsLexicalsInTheRuntimeBoundToItsCode() { + PerlRuntime callerRuntime = new PerlRuntime(); + PerlRuntime codeRuntime = new PerlRuntime(); + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar[] localSlot = new RuntimeScalar[1]; + RuntimeScalar callable; + int codeRuntimeCleanupMark; + + try (PerlRuntime.Binding ignored = codeRuntime.bind()) { + codeRuntimeCleanupMark = MyVarCleanupStack.pushMark(); + RuntimeCode code = new RuntimeCode((args, context) -> { + RuntimeScalar local = new RuntimeScalar(); + local.set(referent.createAnonymousReference()); + localSlot[0] = local; + MyVarCleanupStack.register(local); + throw new PerlDieException(new RuntimeScalar("expected failure")); + }, null).bindCallbackTo(codeRuntime); + callable = new RuntimeScalar(code); + } + + try { + try (PerlRuntime.Binding ignored = callerRuntime.bind()) { + assertThrows(PerlDieException.class, + () -> RuntimeCode.apply( + callable, "bound_runtime_named_call", + new RuntimeList(), RuntimeContextType.SCALAR)); + } + + try (PerlRuntime.Binding ignored = codeRuntime.bind()) { + assertNotNull(localSlot[0]); + assertFalse(MyVarCleanupStack.isRegistered(localSlot[0]), + "a named call must unwind lexicals in the code's bound runtime"); + assertEquals(codeRuntimeCleanupMark, MyVarCleanupStack.pushMark(), + "exception cleanup must restore the bound runtime's lexical stack"); + assertEquals(0, referent.refCount, + "the exceptional lexical must release its reference value"); + } + } finally { + try (PerlRuntime.Binding ignored = codeRuntime.bind()) { + MyVarCleanupStack.unwindTo(codeRuntimeCleanupMark); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CallArgumentsNestedAggregateOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CallArgumentsNestedAggregateOwnerSlotTest.java new file mode 100644 index 0000000000..775e43a4a3 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CallArgumentsNestedAggregateOwnerSlotTest.java @@ -0,0 +1,52 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Tag("unit") +class CallArgumentsNestedAggregateOwnerSlotTest { + @Test + void nestedListArgumentOwnsStrongArrayAndHashElementsUntilCallFinishes() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar source = new RuntimeScalar(); + source.set(referent.createAnonymousReference()); + RuntimeScalar arrayValue = RuntimeScalar.copyToMortalReturnSlot(source); + RuntimeScalar hashValue = RuntimeScalar.copyToMortalReturnSlot(source); + + RuntimeArray nestedArray = new RuntimeArray(); + nestedArray.elements.add(arrayValue); + RuntimeHash nestedHash = new RuntimeHash(); + nestedHash.elements.put("value", hashValue); + RuntimeList innerList = new RuntimeList(); + innerList.elements.add(nestedArray); + innerList.elements.add(nestedHash); + RuntimeList outerList = new RuntimeList(); + outerList.elements.add(innerList); + + RuntimeCode.CallArguments arguments = RuntimeCode.newCallArguments(2); + try { + arguments.add(outerList); + arguments.add(new RuntimeScalar(1)); + + assertEquals(2, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE), + "nested aggregate elements each get a staged argument owner"); + + MortalList.flushAboveMark(); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.RETURN_VALUE)); + assertEquals(2, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE), + "later argument cleanup must preserve both aggregate elements"); + + arguments.finish(); + MortalList.flushAboveMark(); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE), + "call completion retires every staged aggregate owner"); + } finally { + arguments.finish(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CallArgumentsScalarStagingOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CallArgumentsScalarStagingOwnerTest.java new file mode 100644 index 0000000000..893e379f4f --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CallArgumentsScalarStagingOwnerTest.java @@ -0,0 +1,92 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class CallArgumentsScalarStagingOwnerTest { + @Test + void mortalScalarArgumentOwnsItsReferentAcrossLaterArgumentCleanup() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar source = new RuntimeScalar(); + source.set(referent.createAnonymousReference()); + RuntimeScalar temporary = RuntimeScalar.copyToMortalReturnSlot(source); + RuntimeCode.CallArguments arguments = RuntimeCode.newCallArguments(2); + + arguments.add(temporary); + arguments.add(new RuntimeScalar(1)); + + assertTrue(temporary.isMortalReturnSnapshot()); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(RuntimeBase.PerlLifecycleState.LIVE, referent.perlLifecycleState()); + + // A later argument expression can drain the return owner before + // the call has materialized its @_ aliases. + MortalList.flushAboveMark(); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.RETURN_VALUE)); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(RuntimeBase.PerlLifecycleState.LIVE, referent.perlLifecycleState()); + + arguments.finish(); + MortalList.flushAboveMark(); + + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(0, runtime.positiveOwnerSlotReferentCount(referent)); + assertTrue(source.countedOwnerSlot().isActive()); + } + } + + @Test + void persistentScalarArgumentContinuesToBorrowItsCallerCell() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar source = new RuntimeScalar(); + source.set(referent.createAnonymousReference()); + RuntimeCode.CallArguments arguments = RuntimeCode.newCallArguments(2); + + arguments.add(source); + + assertEquals(1, referent.refCount); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + + arguments.finish(); + assertEquals(1, referent.refCount); + assertTrue(source.countedOwnerSlot().isActive()); + } + } + + @Test + void finalMortalScalarArgumentSurvivesCalleeCleanup() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar borrowedSource = new RuntimeScalar(referent.createAnonymousReference()); + assertFalse(borrowedSource.refCountOwned); + RuntimeScalar temporary = RuntimeScalar.copyToMortalReturnSlot(borrowedSource); + RuntimeCode.CallArguments arguments = RuntimeCode.newCallArguments(1); + + arguments.add(temporary); + + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.RETURN_VALUE)); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + + // Safe cleanup inside the callee must preserve the staged owner. + MortalList.flushAboveMark(); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.RETURN_VALUE)); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(RuntimeBase.PerlLifecycleState.LIVE, referent.perlLifecycleState()); + + arguments.finish(); + MortalList.flushAboveMark(); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(0, runtime.positiveOwnerSlotReferentCount(referent)); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CaptureOwnerLedgerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CaptureOwnerLedgerTest.java new file mode 100644 index 0000000000..1842c6aa61 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CaptureOwnerLedgerTest.java @@ -0,0 +1,116 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class CaptureOwnerLedgerTest { + @Test + void scalarCaptureAcquiresAndReleasesOneMatchingOwnerSlot() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeScalar scalar = new RuntimeScalar(); + RuntimeCode owner = code(); + + PerlOwnerSlot slot = scalar.retainClosureCaptureSlot(owner); + + assertEquals(1, scalar.captureCount); + assertEquals(1, scalar.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE)); + assertEquals(0, scalar.legacyCaptureOwnerCount()); + assertTrue(scalar.hasClosureCaptureOwner()); + scalar.verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE); + + scalar.releaseClosureCaptureSlot(slot); + + assertEquals(0, scalar.captureCount); + assertEquals(0, scalar.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE)); + assertFalse(scalar.hasClosureCaptureOwner()); + scalar.verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE); + } + } + + @Test + void aggregateCaptureAcquiresAndReleasesOneMatchingOwnerSlot() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeArray array = new RuntimeArray(); + RuntimeCode owner = code(); + + PerlOwnerSlot slot = array.retainClosureCaptureOwner(owner); + + assertEquals(1, array.captureCount); + assertEquals(1, array.ownerSlotCount(PerlOwnerSlot.Kind.CLOSURE_PAD)); + assertEquals(0, array.legacyCaptureOwnerCount()); + assertTrue(array.hasClosureCaptureOwner()); + array.verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.CLOSURE_PAD); + + array.releaseClosureCaptureOwner(slot); + + assertEquals(0, array.captureCount); + assertEquals(0, array.ownerSlotCount(PerlOwnerSlot.Kind.CLOSURE_PAD)); + assertFalse(array.hasClosureCaptureOwner()); + array.verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.CLOSURE_PAD); + } + } + + @Test + void directLegacyCaptureCountKeepsExplicitProvenance() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeScalar scalar = new RuntimeScalar(); + + scalar.retainClosureCapture(); + + assertEquals(1, scalar.captureCount); + assertEquals(0, scalar.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE)); + assertEquals(1, scalar.legacyCaptureOwnerCount()); + assertTrue(scalar.hasClosureCaptureOwner()); + scalar.verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE); + + scalar.releaseClosureCapture(); + + assertEquals(0, scalar.captureCount); + assertEquals(0, scalar.legacyCaptureOwnerCount()); + assertFalse(scalar.hasClosureCaptureOwner()); + scalar.verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE); + } + } + + @Test + void staleRawCaptureCountFailsTheOwnerInvariant() { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.captureCount = 1; + + assertThrows(IllegalStateException.class, + () -> scalar.verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE)); + assertFalse(scalar.hasClosureCaptureOwner()); + assertThrows(IllegalStateException.class, + () -> scalar.releaseClosureCaptureSlot(null)); + } + + @Test + void absentLegacyCaptureCanBeReleasedAsAnUntrackedEdge() { + RuntimeScalar scalar = new RuntimeScalar(); + + assertDoesNotThrow(() -> scalar.releaseClosureCaptureSlot(null)); + assertEquals(0, scalar.captureCount); + assertEquals(0, scalar.legacyCaptureOwnerCount()); + } + + @Test + void pendingCaptureReleaseRemainsAnOwnerUntilTheReleaseCompletes() { + RuntimeScalar scalar = new RuntimeScalar(); + + scalar.beginPendingClosureCaptureRelease(); + assertTrue(scalar.hasClosureCaptureOwner()); + assertThrows(IllegalStateException.class, + () -> scalar.verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE)); + scalar.endPendingClosureCaptureRelease(); + + assertFalse(scalar.hasClosureCaptureOwner()); + scalar.verifyClosureCaptureOwnerCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE); + } + + private static RuntimeCode code() { + return new RuntimeCode((args, context) -> new RuntimeList(), null); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CaptureOwnerReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CaptureOwnerReleaseTest.java new file mode 100644 index 0000000000..610282f7dc --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CaptureOwnerReleaseTest.java @@ -0,0 +1,33 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class CaptureOwnerReleaseTest { + @Test + void explicitCodeOwnerSlotReleasesItsCapturedAggregateDirectly() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray referent = new RuntimeArray(); + referent.scopeExited = true; + + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + closure.setTrackedRefCount(1); + PerlOwnerSlot capture = referent.retainClosureCaptureOwner(closure); + closure.capturedAggregates = new RuntimeBase[] {referent}; + closure.capturedAggregateOwnerSlots = new PerlOwnerSlot[] {capture}; + + assertTrue(capture.isActive()); + closure.releaseCaptures(); + + assertFalse(capture.isActive(), + "releasing the CODE owner retires its capture slot"); + assertEquals(0, referent.semanticCaptureOwnerCount()); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CaptureReleaseOwnerIdentityTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CaptureReleaseOwnerIdentityTest.java new file mode 100644 index 0000000000..916120cc83 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CaptureReleaseOwnerIdentityTest.java @@ -0,0 +1,59 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class CaptureReleaseOwnerIdentityTest { + @Test + void scalarCaptureReleaseValidatesItsPadBeforeRetiringTheSlot() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar actualPad = new RuntimeScalar(1); + RuntimeScalar wrongPad = new RuntimeScalar(2); + PerlOwnerSlot owner = actualPad.retainClosureCaptureSlot(closure); + + assertThrows(IllegalStateException.class, + () -> wrongPad.releaseClosureCaptureSlot(owner)); + + assertTrue(owner.isActive(), "a mismatched release must preserve the actual pad slot"); + assertSame(actualPad, owner.referent()); + assertEquals(1, actualPad.captureCount); + assertEquals(0, wrongPad.captureCount); + + actualPad.releaseClosureCaptureSlot(owner); + assertFalse(owner.isActive()); + assertEquals(0, actualPad.captureCount); + } + } + + @Test + void aggregateCaptureReleaseValidatesItsPadBeforeRetiringTheSlot() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeHash actualPad = new RuntimeHash(); + RuntimeArray wrongPad = new RuntimeArray(); + PerlOwnerSlot owner = actualPad.retainClosureCaptureOwner(closure); + + assertThrows(IllegalStateException.class, + () -> wrongPad.releaseClosureCaptureOwner(owner)); + + assertTrue(owner.isActive(), "a mismatched release must preserve the actual pad slot"); + assertSame(actualPad, owner.referent()); + assertEquals(1, actualPad.captureCount); + assertEquals(0, wrongPad.captureCount); + + actualPad.releaseClosureCaptureOwner(owner); + assertFalse(owner.isActive()); + assertEquals(0, actualPad.captureCount); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CapturedAggregateWeakOwnerReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CapturedAggregateWeakOwnerReleaseTest.java new file mode 100644 index 0000000000..4bb0b13844 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CapturedAggregateWeakOwnerReleaseTest.java @@ -0,0 +1,46 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class CapturedAggregateWeakOwnerReleaseTest { + + @Test + void finalCaptureOwnerReleasesWeakSentinelWithoutSyntheticCount() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray referent = new RuntimeArray(); + RuntimeScalar weakObserver = referent.createAnonymousReference(); + RuntimeScalar.incrementRefCountForContainerStore(weakObserver); + PerlOwnerSlot captureOwner = referent.retainClosureCaptureOwner(); + + try { + assertEquals(1, referent.refCount); + WeakRefRegistry.weaken(weakObserver); + + assertTrue(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, referent.refCountTrackingState(), + "a semantic closure owner preserves lifecycle without a count shim"); + assertTrue(referent.deferredFinalReleaseForUncountedOwners); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.CLOSURE_PAD)); + + referent.releaseClosureCaptureOwner(captureOwner); + + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState(), + "the final capture owner retires the weak referent exactly once"); + assertEquals(0, referent.refCount); + assertFalse(referent.deferredFinalReleaseForUncountedOwners); + } finally { + if (captureOwner.isActive()) referent.releaseClosureCaptureOwner(captureOwner); + WeakRefRegistry.clearWeakRefsTo(referent); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CapturedCellOwnerReplacementOrderTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CapturedCellOwnerReplacementOrderTest.java new file mode 100644 index 0000000000..abd0a393ec --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CapturedCellOwnerReplacementOrderTest.java @@ -0,0 +1,67 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +@Tag("unit") +class CapturedCellOwnerReplacementOrderTest { + @Test + void capturedValueOwnerTransfersBeforeRetiringThePreviousReferent() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + List events = new ArrayList<>(); + RecordingReferent previous = new RecordingReferent("previous", events); + previous.setTrackedRefCount(0); + previous.localBindingExists = true; + RecordingReferent replacement = new RecordingReferent("replacement", events); + replacement.setTrackedRefCount(0); + replacement.blessId = NameNormalizer.getBlessId( + "Issue1649::CapturedCellReplacement"); + + RuntimeScalar cell = new RuntimeScalar(); + cell.type = RuntimeScalarType.REFERENCE; + cell.value = previous; + PerlOwnerSlot capture = cell.retainClosureCaptureSlot(); + events.clear(); + + cell.set(replacement.createReference()); + + assertEquals(List.of("replacement:CLOSURE_PAD:add", + "previous:CLOSURE_PAD:remove"), + events.stream().filter(event -> event.contains("CLOSURE_PAD")).toList()); + assertSame(replacement, cell.value); + cell.releaseClosureCaptureSlot(capture); + } + } + + private static final class RecordingReferent extends RuntimeScalar { + private final String name; + private final List events; + + private RecordingReferent(String name, List events) { + this.name = name; + this.events = events; + } + + @Override + synchronized void addOwnerSlot(PerlOwnerSlot slot) { + if (slot.kind() == PerlOwnerSlot.Kind.CLOSURE_PAD) { + events.add(name + ":CLOSURE_PAD:add"); + } + super.addOwnerSlot(slot); + } + + @Override + synchronized void removeOwnerSlot(PerlOwnerSlot slot) { + if (slot.kind() == PerlOwnerSlot.Kind.CLOSURE_PAD) { + events.add(name + ":CLOSURE_PAD:remove"); + } + super.removeOwnerSlot(slot); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CapturedScalarCellOwnerFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CapturedScalarCellOwnerFastPathTest.java new file mode 100644 index 0000000000..98356c98c0 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CapturedScalarCellOwnerFastPathTest.java @@ -0,0 +1,100 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class CapturedScalarCellOwnerFastPathTest { + @Test + void deferredCleanupPreservesTheActiveClosureCaptureOwner() { + exerciseActiveCaptureOwner(); + } + + private void exerciseActiveCaptureOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + MortalList.setActive(true); + try { + RuntimeHash target = new RuntimeHash(); + RuntimeScalar seedOwner = new RuntimeScalar(); + RuntimeScalar weakObserver = target.createAnonymousReference(); + RuntimeScalar capturedOwner = new RuntimeScalar(); + RuntimeScalar transientOwner = new RuntimeScalar(); + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + int mark = MyVarCleanupStack.pushMark(); + MyVarCleanupStack.register(seedOwner); + MyVarCleanupStack.register(capturedOwner); + MyVarCleanupStack.register(transientOwner); + + try { + seedOwner.set(target.createAnonymousReference()); + WeakRefRegistry.weaken(weakObserver); + capturedOwner.set(target.createAnonymousReference()); + transientOwner.set(target.createAnonymousReference()); + closure.capturedScalars = new RuntimeScalar[]{capturedOwner}; + closure.capturedScalarOwnerSlots = new PerlOwnerSlot[]{ + capturedOwner.retainClosureCaptureSlot(closure) + }; + RuntimeCode.pushActiveCode(closure); + RuntimeScalar.scopeExitCleanup(capturedOwner); + MyVarCleanupStack.unregister(capturedOwner); + seedOwner.set(new RuntimeScalar()); + + assertFalse(target.localBindingExists); + assertEquals(PerlOwnerSlot.Kind.SCALAR_CELL, + capturedOwner.countedOwnerSlot().kind()); + assertTrue(capturedOwner.refCountOwned, + "the captured scalar cell still owns its reference count"); + assertTrue(capturedOwner.countedOwnerSlot().isActive(), + "the captured scalar cell's owner identity is active"); + assertSame(target, capturedOwner.countedOwnerSlot().referent()); + assertSame(capturedOwner, capturedOwner.countedOwnerSlot().countedScalarOwner()); + assertEquals(1, capturedOwner.captureCount); + assertEquals(1, capturedOwner.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE)); + assertTrue(closure.hasPerlOwnerForCapture(), + "the closure remains a Perl owner of the captured scalar cell"); + assertTrue(capturedOwner.isCurrentCapturedScalarCellOwner( + target, capturedOwner.countedOwnerSlot()), + "the exact scalar-cell and closure-capture identities prove ownership"); + + { + transientOwner.set(new RuntimeScalar()); + + assertEquals(1, target.refCount); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + } + + MortalList.setActive(true); + RuntimeCode.popActiveCode(closure); + closure.releaseCaptures(); + MortalList.flush(); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "releasing the captured scalar cell clears the final weak observer"); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + } finally { + if (RuntimeCode.isActiveCode(closure)) RuntimeCode.popActiveCode(closure); + if (closure.capturedScalars != null) closure.releaseCaptures(); + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + RuntimeScalar.scopeExitCleanup(seedOwner); + RuntimeScalar.scopeExitCleanup(capturedOwner); + RuntimeScalar.scopeExitCleanup(transientOwner); + MyVarCleanupStack.unregister(seedOwner); + MyVarCleanupStack.unregister(capturedOwner); + MyVarCleanupStack.unregister(transientOwner); + MyVarCleanupStack.popMark(mark); + } + } finally { + MortalList.setActive(previousMortalListState); + } + } + } + +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CleanupTargetProbeReuseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CleanupTargetProbeReuseTest.java new file mode 100644 index 0000000000..4034549689 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CleanupTargetProbeReuseTest.java @@ -0,0 +1,33 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class CleanupTargetProbeReuseTest { + @Test + void probeReusesScratchAcrossShortCircuitsAndCycles() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + MortalList.CleanupTargetProbe probe = new MortalList.CleanupTargetProbe(); + assertFalse(probe.mayContainCleanupTargets(new RuntimeHash())); + + RuntimeArray withTarget = new RuntimeArray(); + RuntimeHash blessed = new RuntimeHash(); + blessed.setBlessId(NameNormalizer.getBlessId( + "CleanupTargetProbeReuseTest::Target")); + withTarget.push(blessed.createAnonymousReference()); + assertTrue(probe.mayContainCleanupTargets(withTarget)); + + RuntimeArray cycleWithoutTargets = new RuntimeArray(); + cycleWithoutTargets.push(cycleWithoutTargets.createAnonymousReference()); + assertFalse(probe.mayContainCleanupTargets(cycleWithoutTargets)); + assertFalse(probe.mayContainCleanupTargets(new RuntimeArray())); + + MortalList.scopeExitCleanupArray(cycleWithoutTargets); + MortalList.flush(); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ClearedAggregateNestedPackageOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ClearedAggregateNestedPackageOwnerTest.java new file mode 100644 index 0000000000..41328114d9 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ClearedAggregateNestedPackageOwnerTest.java @@ -0,0 +1,61 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ClearedAggregateNestedPackageOwnerTest { + @Test + void nestedPackageSlotPreservesWeakObserver() { + PerlRuntime runtime = new PerlRuntime(); + RuntimeArray packageRoot = new RuntimeArray(); + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar strongOwner = referent.createAnonymousReference(); + RuntimeScalar weakObserver = referent.createAnonymousReference(); + String globalName = "ClearedAggregateNestedPackageOwnerTest::root"; + + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + GlobalVariable.globalArrays.put(globalName, packageRoot); + packageRoot.elements.add(strongOwner); + referent.markRefCountUntracked(); + weakObserver.value = referent; + weakObserver.type = RuntimeScalarType.HASHREFERENCE; + MortalList.setActive(true); + try { + strongOwner.refreshUntrackedReferenceOwner(); + WeakRefRegistry.weaken(weakObserver); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + assertEquals(1, referent.ownerSlotCount( + PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + // Model the scope-exit count transition after the owner cell + // has been marked cleared; the package element slot is still + // the current strong edge. + referent.clearedOwnedAggregateElement = true; + referent.setTrackedRefCount(0); + MortalList.finalizeClearedAggregateOwnerAfterScopeExit(referent); + + assertTrue(WeakRefRegistry.isweak(weakObserver), + "the nested package scalar owner keeps its weak observer live"); + + assertEquals(0, referent.refCount, + "the exact package owner remains authoritative despite the stale zero count"); + strongOwner.undefine(); + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState()); + assertEquals(0, referent.refCount); + } finally { + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + GlobalVariable.globalArrays.remove(globalName); + MortalList.setActive(previousMortalListState); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ClearedAggregateOwnerIdentityFinalizationTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ClearedAggregateOwnerIdentityFinalizationTest.java new file mode 100644 index 0000000000..a1764916f4 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ClearedAggregateOwnerIdentityFinalizationTest.java @@ -0,0 +1,108 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ClearedAggregateOwnerIdentityFinalizationTest { + @Test + void scopeExitUsesPackageOwnerIdentityWithoutExternalRootWalk() { + PerlRuntime runtime = new PerlRuntime(); + RuntimeHash packageRoot = new RuntimeHash(); + RuntimeScalar weakPackageRoot = packageRoot.createAnonymousReference(); + String globalName = + "ClearedAggregateOwnerIdentityFinalizationTest::packageRoot"; + + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + MortalList.setActive(true); + try { + GlobalVariable.globalHashes.put(globalName, packageRoot); + assertEquals(1, packageRoot.ownerSlotCount( + PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + packageRoot.clearedOwnedAggregateElement = true; + WeakRefRegistry.weaken(weakPackageRoot); + packageRoot.setTrackedRefCount(0); + + { + MortalList.finalizeClearedAggregateOwnerAfterScopeExit(packageRoot); + + assertTrue(WeakRefRegistry.isweak(weakPackageRoot), + "the package slot keeps the aggregate alive"); + } + + } finally { + GlobalVariable.globalHashes.remove(globalName); + WeakRefRegistry.clearWeakRefsTo(packageRoot); + MortalList.setActive(previousMortalListState); + } + } + } + + @Test + void finalCellCleanupReleasesNestedUntrackedOwnerDespiteLegacyCount() { + PerlRuntime runtime = new PerlRuntime(); + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar weakObserver = referenceTo(referent); + RuntimeArray container = new RuntimeArray(); + RuntimeScalar nestedCell = referenceTo(referent); + container.elements.add(nestedCell); + nestedCell.markContainerOwner(container); + + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + int mark = MyVarCleanupStack.pushMark(); + MyVarCleanupStack.register(container); + MortalList.setActive(true); + try { + referent.markRefCountUntracked(); + nestedCell.refreshUntrackedReferenceOwner(); + PerlOwnerSlot nestedOwner = nestedCell.untrackedReferenceOwnerSlot(); + assertTrue(nestedOwner != null && nestedOwner.isActive()); + + WeakRefRegistry.weaken(weakObserver); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + + // Model a positive compatibility count left behind after the + // nested scalar's final untracked owner identity is retired. + referent.setTrackedRefCount(5); + referent.clearedOwnedAggregateElement = true; + nestedCell.set(new RuntimeScalar()); + assertFalse(nestedOwner.isActive()); + assertEquals(0, referent.ownerSlotCount( + PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + MortalList.finalizeClearedAggregateOwnerAfterScopeExit(referent); + + assertFalse(WeakRefRegistry.isweak(weakObserver), + "legacy count alone must not keep a cleared aggregate alive"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState()); + assertEquals(0, referent.refCount); + } finally { + if (nestedCell.untrackedReferenceOwnerSlot() != null + && nestedCell.untrackedReferenceOwnerSlot().isActive()) { + nestedCell.set(new RuntimeScalar()); + } + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + WeakRefRegistry.clearWeakRefsTo(referent); + MortalList.scopeExitCleanupArray(container); + MyVarCleanupStack.unregister(container); + MyVarCleanupStack.popMark(mark); + MortalList.setActive(previousMortalListState); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.HASHREFERENCE; + scalar.value = referent; + return scalar; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ClearedAggregateOwnerIdentityTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ClearedAggregateOwnerIdentityTest.java new file mode 100644 index 0000000000..92f1f9dc34 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ClearedAggregateOwnerIdentityTest.java @@ -0,0 +1,72 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ClearedAggregateOwnerIdentityTest { + @Test + void finalUntrackedCellReleaseIgnoresStaleCount() { + PerlRuntime runtime = new PerlRuntime(); + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar weakObserver = referenceTo(referent); + RuntimeArray lexicalContainer = new RuntimeArray(); + RuntimeScalar nestedCell = referenceTo(referent); + lexicalContainer.elements.add(nestedCell); + nestedCell.markContainerOwner(lexicalContainer); + + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + int mark = MyVarCleanupStack.pushMark(); + MyVarCleanupStack.register(lexicalContainer); + MortalList.setActive(true); + try { + referent.markRefCountUntracked(); + nestedCell.refreshUntrackedReferenceOwner(); + PerlOwnerSlot nestedOwner = nestedCell.untrackedReferenceOwnerSlot(); + assertTrue(nestedOwner != null && nestedOwner.isActive()); + + WeakRefRegistry.weaken(weakObserver); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + + // Retire the exact owner while leaving a positive compatibility + // count behind, as can happen during async aggregate cleanup. + referent.setTrackedRefCount(5); + referent.clearedOwnedAggregateElement = true; + nestedCell.set(new RuntimeScalar()); + assertFalse(nestedOwner.isActive()); + + MortalList.finalizeClearedAggregateOwnerAfterScopeExit(referent); + + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type, + "a stale count cannot preserve the cleared referent"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState()); + assertEquals(0, referent.refCount); + } finally { + if (nestedCell.untrackedReferenceOwnerSlot() != null + && nestedCell.untrackedReferenceOwnerSlot().isActive()) { + nestedCell.set(new RuntimeScalar()); + } + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + WeakRefRegistry.clearWeakRefsTo(referent); + MortalList.scopeExitCleanupArray(lexicalContainer); + MyVarCleanupStack.unregister(lexicalContainer); + MyVarCleanupStack.popMark(mark); + MortalList.setActive(previousMortalListState); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.HASHREFERENCE; + scalar.value = referent; + return scalar; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ClearedAggregateRequiresOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ClearedAggregateRequiresOwnerSlotTest.java new file mode 100644 index 0000000000..a5462aa913 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ClearedAggregateRequiresOwnerSlotTest.java @@ -0,0 +1,60 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +@Tag("unit") +class ClearedAggregateRequiresOwnerSlotTest { + @Test + void untrackedJavaReferenceDoesNotReplaceAPerlOwnerSlot() { + PerlRuntime runtime = new PerlRuntime(); + RuntimeHash referent = new RuntimeHash(); + RuntimeHash packageRoot = new RuntimeHash(); + RuntimeScalar weakObserver = referenceTo(referent); + RuntimeScalar untrackedElement = referenceTo(referent); + String globalName = + "ClearedAggregateRequiresOwnerSlotTest::packageRoot"; + + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + GlobalVariable.globalHashes.put(globalName, packageRoot); + // This intentionally bypasses the normal hash store API. The Java + // reference it creates has no HASH_ELEMENT owner identity. + packageRoot.elements = new java.util.LinkedHashMap<>(); + packageRoot.elements.put("referent", untrackedElement); + MyVarCleanupStack.register(referent); + MortalList.setActive(true); + try { + WeakRefRegistry.weaken(weakObserver); + referent.setTrackedRefCount(0); + referent.clearedOwnedAggregateElement = true; + + MyVarCleanupStack.unregister(referent); + + assertFalse(DestroyDispatch.hasLivePerlOwnerIdentity(referent)); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + referent.perlLifecycleState()); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "a Java reference without an owner slot cannot preserve the observer"); + } finally { + MyVarCleanupStack.unregister(referent); + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + WeakRefRegistry.clearWeakRefsTo(referent); + GlobalVariable.globalHashes.remove(globalName); + MortalList.setActive(previousMortalListState); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.HASHREFERENCE; + scalar.value = referent; + return scalar; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ClosureAggregateOwnerIdentityReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ClosureAggregateOwnerIdentityReleaseTest.java new file mode 100644 index 0000000000..7123f327ad --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ClosureAggregateOwnerIdentityReleaseTest.java @@ -0,0 +1,71 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ClosureAggregateOwnerIdentityReleaseTest { + @Test + void scopeExitReleasesCaptureDespiteStaleCodeRefCountWithoutWalkingRoots() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray capturedPad = new RuntimeArray(); + RuntimeCode closure = new RuntimeCode(null, List.of()); + PerlOwnerSlot padOwner = capturedPad.retainClosureCaptureOwner(closure); + closure.capturedAggregates = new RuntimeBase[] {capturedPad}; + closure.capturedAggregateOwnerSlots = new PerlOwnerSlot[] {padOwner}; + closure.captureFieldsRecorded = true; + + RuntimeScalar weakCode = new RuntimeScalar(closure); + WeakRefRegistry.weaken(weakCode); + closure.setTrackedRefCount(7); // stale compatibility count, with no strong owner slot + assertFalse(closure.hasPerlOwnerForCaptureOtherThan(null)); + + try { + MortalList.scopeExitCleanupArray(capturedPad); + + assertNull(closure.capturedAggregates); + assertNull(closure.capturedAggregateOwnerSlots); + assertFalse(padOwner.isActive()); + assertEquals(0, capturedPad.captureCount); + } finally { + WeakRefRegistry.removeWeakRef(weakCode, closure); + } + } + } + + @Test + void scopeExitKeepsCaptureWhileCodeHasAScalarOwnerIdentity() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray capturedPad = new RuntimeArray(); + RuntimeCode closure = new RuntimeCode(null, List.of()); + closure.setTrackedRefCount(0); + PerlOwnerSlot padOwner = capturedPad.retainClosureCaptureOwner(closure); + closure.capturedAggregates = new RuntimeBase[] {capturedPad}; + closure.capturedAggregateOwnerSlots = new PerlOwnerSlot[] {padOwner}; + closure.captureFieldsRecorded = true; + closure.capturedScalars = new RuntimeScalar[0]; + RuntimeScalar codeOwner = new RuntimeScalar(); + codeOwner.set(new RuntimeScalar(closure)); + + assertTrue(closure.hasPerlOwnerForCaptureOtherThan(null)); + MortalList.scopeExitCleanupArray(capturedPad); + + assertTrue(padOwner.isActive()); + assertEquals(1, capturedPad.captureCount); + assertTrue(capturedPad.scopeExited); + + codeOwner.set(new RuntimeScalar()); + assertNull(closure.capturedAggregates); + assertFalse(padOwner.isActive()); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilityWalkerCapturedAggregateReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ClosurePadAggregateOwnerTest.java similarity index 74% rename from src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilityWalkerCapturedAggregateReleaseTest.java rename to src/test/java/org/perlonjava/runtime/runtimetypes/ClosurePadAggregateOwnerTest.java index cf2a514b87..c3a692d056 100644 --- a/src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilityWalkerCapturedAggregateReleaseTest.java +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ClosurePadAggregateOwnerTest.java @@ -3,26 +3,21 @@ import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import java.util.Collections; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @Tag("unit") -class ReachabilityWalkerCapturedAggregateReleaseTest { +class ClosurePadAggregateOwnerTest { @Test - void targetedReleaseKeepsAnAggregateOwnedByAClosurePad() { + void closurePadOwnerKeepsAnAggregateAlive() { PerlRuntime runtime = new PerlRuntime(); try (PerlRuntime.Binding ignored = runtime.bind()) { RuntimeHash captured = new RuntimeHash(); - captured.refCount = 1; + captured.setTrackedRefCount(1); captured.put("value", new RuntimeScalar("alive")); captured.scopeExited = true; PerlOwnerSlot closureOwner = captured.retainClosureCaptureOwner(); - ReachabilityWalker.sweepReleasedWeakReferents( - Collections.singleton(captured)); - assertEquals(1, captured.refCount); assertEquals(1, captured.semanticCaptureOwnerCount()); assertEquals("alive", captured.get("value").toString()); @@ -33,18 +28,18 @@ void targetedReleaseKeepsAnAggregateOwnedByAClosurePad() { } @Test - void laterCaptureReconcilesAStaleDestroyedSentinelWhileOwnersRemain() { + void laterCaptureReconcilesZeroCountWhileOwnersRemain() { PerlRuntime runtime = new PerlRuntime(); try (PerlRuntime.Binding ignored = runtime.bind()) { RuntimeHash captured = new RuntimeHash(); - captured.refCount = 1; + captured.setTrackedRefCount(1); captured.put("value", new RuntimeScalar("alive")); captured.scopeExited = true; PerlOwnerSlot firstOwner = captured.retainClosureCaptureOwner(); - // A targeted weak sweep can miss the native owner slots and leave - // this bridge sentinel behind while the captured lexical is live. - captured.refCount = Integer.MIN_VALUE; + // Model a count that reached zero while native capture owners + // still keep the aggregate alive. + captured.setTrackedRefCount(0); PerlOwnerSlot secondOwner = captured.retainClosureCaptureOwner(); assertEquals(0, captured.refCount); diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CodeCycleOwnerSlotLifecycleTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CodeCycleOwnerSlotLifecycleTest.java new file mode 100644 index 0000000000..09dff147fd --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CodeCycleOwnerSlotLifecycleTest.java @@ -0,0 +1,38 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class CodeCycleOwnerSlotLifecycleTest { + @Test + void restoresTheCurrentSelfCaptureOwnerWithoutWalkingTheObjectGraph() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + code.setTrackedRefCount(0); + RuntimeScalar capture = new RuntimeScalar(); + PerlOwnerSlot captureSlot = capture.retainClosureCaptureSlot(code); + capture.set(new RuntimeScalar(code)); + code.capturedScalars = new RuntimeScalar[] { capture }; + code.capturedScalarOwnerSlots = new PerlOwnerSlot[] { captureSlot }; + code.captureFieldsRecorded = true; + + RuntimeScalar weakObserver = new RuntimeScalar(code); + WeakRefRegistry.weaken(weakObserver); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + assertEquals(1, code.countedOwnerSlotCount()); + + assertEquals(1, code.refCount, + "the current self-capture edge has one ordinary owner count"); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + + capture.set(new RuntimeScalar()); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "removing the final self-capture edge releases the weak observer"); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CodeOwnerSlotReleaseFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CodeOwnerSlotReleaseFastPathTest.java new file mode 100644 index 0000000000..6f8166c69e --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CodeOwnerSlotReleaseFastPathTest.java @@ -0,0 +1,44 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +@Tag("unit") +class CodeOwnerSlotReleaseFastPathTest { + @Test + void anotherScalarOwnerSkipsClosureCaptureRootWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + closure.setTrackedRefCount(0); + RuntimeScalar pad = new RuntimeScalar(); + closure.capturedScalars = new RuntimeScalar[] {pad}; + closure.capturedScalarOwnerSlots = new PerlOwnerSlot[] { + pad.retainClosureCaptureSlot(closure) + }; + + RuntimeScalar external = new RuntimeScalar(); + external.set(new RuntimeScalar(closure)); + RuntimeScalar local = new RuntimeScalar(); + local.set(new RuntimeScalar(closure)); + assertEquals(2, closure.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + assertEquals(0, closure.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + + { + local.set(new RuntimeScalar()); + + assertNotNull(closure.capturedScalars, + "the other scalar owner keeps closure captures alive"); + assertEquals(1, closure.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + } + + external.set(new RuntimeScalar()); + assertNull(closure.capturedScalars, + "the final scalar owner still releases closure captures"); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CodePadConstantOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CodePadConstantOwnerSlotTest.java new file mode 100644 index 0000000000..e283450c7d --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CodePadConstantOwnerSlotTest.java @@ -0,0 +1,229 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class CodePadConstantOwnerSlotTest { + @Test + void compiledPadTreeTransfersToThePublishedCvOwner() { + PerlRuntime runtime = new PerlRuntime(); + RuntimeScalarReadOnly constant = new RuntimeScalarReadOnly("owned"); + RuntimeCode compiledCode = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeCode publishedCv = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar weakObserver = referenceTo(constant); + String className = "org/perlonjava/test/PadConstantTransfer"; + + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + MortalList.setActive(true); + try { + WeakRefRegistry.weaken(weakObserver); + compiledCode.installPadConstantTree( + className, new RuntimeBase[]{constant}, java.util.Map.of(), java.util.Map.of()); + PerlOwnerSlot compiledOwner = constant.ownerSlotSnapshot().stream() + .filter(slot -> slot.kind() == PerlOwnerSlot.Kind.CODE_PAD_CONSTANT) + .findFirst().orElseThrow(); + + compiledCode.transferPadConstantTreeTo(publishedCv); + + assertFalse(compiledOwner.isActive(), + "the temporary compiler wrapper gives up its owner slot"); + assertEquals(1, constant.ownerSlotCount(PerlOwnerSlot.Kind.CODE_PAD_CONSTANT), + "the published CV replaces the temporary owner exactly once"); + assertSame(constant, RuntimeCode.getPadConstant(className, 0), + "generated code resolves the constant through the published CV tree"); + assertTrue(WeakRefRegistry.isweak(weakObserver), + "transferring the owner does not clear a live constant"); + + publishedCv.setTrackedRefCount(0); + DestroyDispatch.callDestroy(publishedCv); + assertEquals(0, constant.ownerSlotCount(PerlOwnerSlot.Kind.CODE_PAD_CONSTANT)); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the published CV's final release reaps its constant"); + } finally { + if (compiledCode.perlLifecycleState() != RuntimeBase.PerlLifecycleState.DESTROYED) { + compiledCode.setTrackedRefCount(0); + DestroyDispatch.callDestroy(compiledCode); + } + if (publishedCv.perlLifecycleState() != RuntimeBase.PerlLifecycleState.DESTROYED) { + publishedCv.setTrackedRefCount(0); + DestroyDispatch.callDestroy(publishedCv); + } + WeakRefRegistry.clearWeakRefsTo(constant); + MortalList.setActive(previousMortalListState); + } + } + } + + @Test + void untrackedCallerOwnerIsFinalizedAfterItsCvReleasesThePadConstant() { + PerlRuntime runtime = new PerlRuntime(); + RuntimeScalarReadOnly constant = new RuntimeScalarReadOnly("owned"); + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar strongOwner = new RuntimeScalar(); + RuntimeScalar weakObserver = referenceTo(constant); + + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + MortalList.setActive(true); + int mark = MyVarCleanupStack.pushMark(); + MyVarCleanupStack.register(strongOwner); + try { + code.installPadConstants(new RuntimeBase[]{constant}); + strongOwner.set(referenceTo(constant)); + assertTrue(strongOwner.untrackedReferenceOwnerSlot().isActive()); + WeakRefRegistry.weaken(weakObserver); + + code.clearPadConstantWeakRefs(); + + assertEquals(0, constant.ownerSlotCount(PerlOwnerSlot.Kind.CODE_PAD_CONSTANT)); + assertEquals(1, constant.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertTrue(WeakRefRegistry.isweak(weakObserver), + "the caller's strong scalar keeps the constant alive after CV release"); + + strongOwner.undefine(); + + assertEquals(0, constant.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the final untracked caller slot triggers immediate weak cleanup"); + } finally { + RuntimeScalar.scopeExitCleanup(strongOwner); + MyVarCleanupStack.unregister(strongOwner); + MyVarCleanupStack.popMark(mark); + if (code.perlLifecycleState() != RuntimeBase.PerlLifecycleState.DESTROYED) { + code.setTrackedRefCount(0); + DestroyDispatch.callDestroy(code); + } + WeakRefRegistry.clearWeakRefsTo(constant); + MortalList.setActive(previousMortalListState); + } + } + } + + @Test + void finalUntrackedCodeReferenceReleasesItsPadTreeDespiteStaleLegacyCount() { + PerlRuntime runtime = new PerlRuntime(); + RuntimeScalarReadOnly constant = new RuntimeScalarReadOnly("owned"); + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar codeSlot = new RuntimeScalar(); + RuntimeScalar weakObserver = referenceTo(constant); + + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + MortalList.setActive(true); + int mark = MyVarCleanupStack.pushMark(); + MyVarCleanupStack.register(codeSlot); + try { + closure.installPadConstants(new RuntimeBase[]{constant}); + codeSlot.set(new RuntimeScalar(closure)); + WeakRefRegistry.weaken(weakObserver); + + assertEquals(1, + closure.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertEquals(1, + constant.ownerSlotCount(PerlOwnerSlot.Kind.CODE_PAD_CONSTANT)); + // The scalar slot is the actual CODE owner. Its old + // compatibility count can remain positive after that owner + // identity is the only remaining proof of Perl liveness. + closure.setTrackedRefCount(7); + + { + codeSlot.set(new RuntimeScalar()); + + } + + assertEquals(0, + constant.ownerSlotCount(PerlOwnerSlot.Kind.CODE_PAD_CONSTANT)); + assertEquals(0, closure.padConstantOwnerReferents().length); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the final uncounted CV slot releases the optree constants"); + } finally { + RuntimeScalar.scopeExitCleanup(codeSlot); + MyVarCleanupStack.unregister(codeSlot); + MyVarCleanupStack.popMark(mark); + closure.clearPadConstantWeakRefs(); + WeakRefRegistry.clearWeakRefsTo(constant); + MortalList.setActive(previousMortalListState); + } + } + } + + @Test + void eachOptreeConstantEdgeLivesUntilItsCvOwnerIsDestroyed() { + PerlRuntime runtime = new PerlRuntime(); + RuntimeScalarReadOnly constant = new RuntimeScalarReadOnly("owned"); + RuntimeCode firstCode = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeCode secondCode = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar weakObserver = referenceTo(constant); + + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + MortalList.setActive(true); + try { + firstCode.installPadConstants(new RuntimeBase[]{constant, constant}); + secondCode.installPadConstants(new RuntimeBase[]{constant}); + + PerlOwnerSlot[] owners = constant.ownerSlotSnapshot().stream() + .filter(slot -> slot.kind() == PerlOwnerSlot.Kind.CODE_PAD_CONSTANT) + .toArray(PerlOwnerSlot[]::new); + assertEquals(3, owners.length, + "each constant occurrence in each CV has a distinct strong slot"); + assertEquals(3, constant.ownerSlotCount(PerlOwnerSlot.Kind.CODE_PAD_CONSTANT)); + + { + WeakRefRegistry.weaken(weakObserver); + + assertTrue(WeakRefRegistry.isweak(weakObserver)); + assertTrue(RuntimeCode.isInstalledPadConstant(constant)); + } + + assertTrue(WeakRefRegistry.isweak(weakObserver), + "the direct optree owner slots retain the constant observer"); + assertEquals(3, constant.ownerSlotCount( + PerlOwnerSlot.Kind.CODE_PAD_CONSTANT)); + + firstCode.setTrackedRefCount(0); + DestroyDispatch.callDestroy(firstCode); + assertEquals(1, constant.ownerSlotCount(PerlOwnerSlot.Kind.CODE_PAD_CONSTANT)); + assertTrue(WeakRefRegistry.isweak(weakObserver), + "one surviving CV still owns the shared optree constant"); + + secondCode.setTrackedRefCount(0); + DestroyDispatch.callDestroy(secondCode); + assertEquals(0, constant.ownerSlotCount(PerlOwnerSlot.Kind.CODE_PAD_CONSTANT)); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the final CV release clears the constant's weak observers"); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + for (PerlOwnerSlot owner : owners) assertFalse(owner.isActive()); + + DestroyDispatch.callDestroy(secondCode); + assertEquals(0, constant.ownerSlotCount(PerlOwnerSlot.Kind.CODE_PAD_CONSTANT), + "repeated destruction cannot release an owner twice"); + } finally { + if (firstCode.perlLifecycleState() != RuntimeBase.PerlLifecycleState.DESTROYED) { + firstCode.setTrackedRefCount(0); + DestroyDispatch.callDestroy(firstCode); + } + if (secondCode.perlLifecycleState() != RuntimeBase.PerlLifecycleState.DESTROYED) { + secondCode.setTrackedRefCount(0); + DestroyDispatch.callDestroy(secondCode); + } + WeakRefRegistry.clearWeakRefsTo(constant); + MortalList.setActive(previousMortalListState); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.REFERENCE; + scalar.value = referent; + return scalar; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CodeSlotOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CodeSlotOwnerTest.java new file mode 100644 index 0000000000..8e64b21c53 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CodeSlotOwnerTest.java @@ -0,0 +1,230 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class CodeSlotOwnerTest { + private static RuntimeCode code() { + return new RuntimeCode((args, context) -> new RuntimeList(), null); + } + + @Test + void compiledLookupPinOwnsTheGpAfterItsStashNameIsDeleted() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeScalar slot = GlobalVariable.getGlobalCodeRef("CodeOwner::pinned"); + RuntimeCode code = code(); + slot.set(new RuntimeScalar(code)); + GlobalVariable.globalCodeRefs.remove("CodeOwner::pinned"); + assertEquals(1, code.refCount); + assertEquals(RuntimeBase.PerlLifecycleState.LIVE, code.perlLifecycleState()); + assertEquals(1, code.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + GlobalVariable.clearPinnedCodeRefsForNamespace("CodeOwner::"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, code.perlLifecycleState()); + } + } + + @Test + void firstAssignmentToAnEmptySlotAcquiresExactlyOneEdge() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeScalar slot = new RuntimeScalar(); + GlobalVariable.globalCodeRefs.put("CodeOwner::empty", slot); + RuntimeCode first = code(); + slot.set(new RuntimeScalar(first)); + assertEquals(1, first.refCount); + long identity = slot.countedOwnerSlot().identity(); + RuntimeCode second = code(); + slot.set(new RuntimeScalar(second)); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, first.perlLifecycleState()); + assertEquals(1, second.refCount); + assertEquals(identity, slot.countedOwnerSlot().identity()); + slot.set(RuntimeScalarCache.scalarUndef); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, second.perlLifecycleState()); + GlobalVariable.globalCodeRefs.remove("CodeOwner::empty"); + } + } + + @Test + void wholeGlobNamesShareOnePhysicalCodeOwner() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeCode code = code(); + RuntimeScalar slot = new RuntimeScalar(code); + GlobalVariable.globalCodeRefs.put("CodeOwner::first", slot); + GlobalVariable.globalCodeRefs.put("CodeOwner::second", slot); + assertEquals(1, code.refCount); + assertEquals(1, code.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + long identity = slot.countedOwnerSlot().identity(); + GlobalVariable.globalCodeRefs.remove("CodeOwner::first"); + assertEquals(1, code.refCount); + assertEquals(identity, slot.countedOwnerSlot().identity()); + RuntimeScalar.scopeExitCleanup(slot); // A borrow cannot retire a GP slot. + assertEquals(1, code.refCount); + { + GlobalVariable.globalCodeRefs.remove("CodeOwner::second"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, code.perlLifecycleState()); + assertEquals(0, code.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + } + } + } + + @Test + void separateCodeSlotsOwnDistinctEdgesToTheSameCv() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeCode code = code(); + RuntimeScalar first = new RuntimeScalar(code); + RuntimeScalar second = new RuntimeScalar(code); + GlobalVariable.globalCodeRefs.put("CodeOwner::first", first); + GlobalVariable.globalCodeRefs.put("CodeOwner::second", second); + assertEquals(2, code.refCount); + assertEquals(2, code.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + assertNotEquals(first.countedOwnerSlot().identity(), second.countedOwnerSlot().identity()); + GlobalVariable.globalCodeRefs.remove("CodeOwner::first"); + assertEquals(1, code.refCount); + assertEquals(RuntimeBase.PerlLifecycleState.LIVE, code.perlLifecycleState()); + GlobalVariable.globalCodeRefs.entrySet().removeIf(e -> e.getKey().equals("CodeOwner::second")); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, code.perlLifecycleState()); + } + } + + @Test + void localizedSavedSlotKeepsItsOwnerUntilItIsRestored() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeCode original = code(); + RuntimeCode temporary = code(); + RuntimeScalar saved = new RuntimeScalar(original); + GlobalVariable.globalCodeRefs.put("CodeOwner::localized", saved); + long identity = saved.countedOwnerSlot().identity(); + GlobalVariable.enterLocalizedCodeRef("CodeOwner::localized", saved); + GlobalVariable.globalCodeRefs.put("CodeOwner::localized", new RuntimeScalar(temporary)); + assertEquals(1, original.refCount); + assertEquals(identity, saved.countedOwnerSlot().identity()); + GlobalVariable.globalCodeRefs.put("CodeOwner::localized", saved); + GlobalVariable.exitLocalizedCodeRef("CodeOwner::localized", saved); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, temporary.perlLifecycleState()); + assertEquals(1, original.refCount); + assertEquals(identity, saved.countedOwnerSlot().identity()); + GlobalVariable.globalCodeRefs.clear(); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, original.perlLifecycleState()); + } + } + + @Test + void finalNamedOwnerWaitsForTheLastActiveCall() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeCode code = code(); + GlobalVariable.globalCodeRefs.put("CodeOwner::active", new RuntimeScalar(code)); + RuntimeCode.pushActiveCode(code); + GlobalVariable.globalCodeRefs.remove("CodeOwner::active"); + assertEquals(0, code.refCount); + assertEquals(RuntimeBase.PerlLifecycleState.LIVE, code.perlLifecycleState()); + { + RuntimeCode.popActiveCode(code); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, code.perlLifecycleState()); + assertEquals(0, code.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_CODE)); + } + } + } + + @Test + void visibleStashCodeOwnersAreDistinctFromCompilerPins() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeCode code = code(); + RuntimeScalar sharedSlot = new RuntimeScalar(code); + GlobalVariable.globalCodeRefs.put("CodeOwner::visibleA", sharedSlot); + GlobalVariable.globalCodeRefs.put("CodeOwner::visibleB", sharedSlot); + assertTrue(code.hasStashCodeSlotOwner()); + + GlobalVariable.globalCodeRefs.remove("CodeOwner::visibleA"); + assertTrue(code.hasStashCodeSlotOwner()); + GlobalVariable.globalCodeRefs.remove("CodeOwner::visibleB"); + assertFalse(code.hasStashCodeSlotOwner()); + + RuntimeCode pinnedCode = code(); + RuntimeScalar pinnedSlot = GlobalVariable.getGlobalCodeRef("CodeOwner::pinnedOnly"); + pinnedSlot.set(new RuntimeScalar(pinnedCode)); + GlobalVariable.globalCodeRefs.remove("CodeOwner::pinnedOnly"); + + assertFalse(pinnedCode.hasStashCodeSlotOwner()); + assertEquals(1, pinnedCode.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + GlobalVariable.clearPinnedCodeRefsForNamespace("CodeOwner::"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, pinnedCode.perlLifecycleState()); + } + } + + @Test + void installedStashCodeOwnerPreservesWeakObserverWithoutRootScan() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeCode code = code(); + GlobalVariable.globalCodeRefs.put( + "CodeOwner::weakObserver", new RuntimeScalar(code)); + RuntimeScalar weakRef = new RuntimeScalar(code); + WeakRefRegistry.weaken(weakRef); + + { + WeakRefRegistry.clearWeakRefsTo(code); + + assertTrue(WeakRefRegistry.isweak(weakRef)); + } + + GlobalVariable.globalCodeRefs.remove("CodeOwner::weakObserver"); + assertEquals(RuntimeScalarType.UNDEF, weakRef.type); + } + } + + @Test + void clonedPackageCodeSlotRetainsItsStashOwnerIdentity() { + PerlRuntime sourceRuntime = new PerlRuntime(); + PerlRuntime targetRuntime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = sourceRuntime.bind()) { + GlobalVariable.globalCodeRefs.put( + "CodeOwner::cloned", new RuntimeScalar(code())); + } + + RuntimeGraphCloner cloner = new RuntimeGraphCloner(sourceRuntime, targetRuntime); + try (PerlRuntime.Binding ignored = sourceRuntime.bind()) { + sourceRuntime.globalState().snapshotInto(targetRuntime.globalState(), cloner); + } + try (PerlRuntime.Binding ignored = targetRuntime.bind()) { + RuntimeScalar clonedSlot = targetRuntime.globalState().codeRefs().get("CodeOwner::cloned"); + RuntimeCode clonedCode = (RuntimeCode) clonedSlot.value; + assertTrue(clonedCode.hasStashCodeSlotOwner()); + assertEquals(1, clonedCode.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + } + } + + @Test + void resettingRuntimeReleasesCodeSlotOwners() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + GlobalVariable.resetAllGlobals(); + RuntimeCode compiledCode = code(); + RuntimeScalar compiledRef = new RuntimeScalar(compiledCode); + GlobalVariable.registerCompiledCodeRef(compiledRef); + + RuntimeCode pinnedCode = code(); + RuntimeScalar pinnedRef = GlobalVariable.getGlobalCodeRef("CodeOwner::resetPinned"); + pinnedRef.set(new RuntimeScalar(pinnedCode)); + GlobalVariable.globalCodeRefs.remove("CodeOwner::resetPinned"); + + RuntimeCode localizedCode = code(); + RuntimeScalar localizedRef = new RuntimeScalar(localizedCode); + GlobalVariable.enterLocalizedCodeRef("CodeOwner::resetLocalized", localizedRef); + GlobalVariable.enterLocalizedCodeRef("CodeOwner::resetLocalized", localizedRef); + + assertEquals(1, compiledCode.refCount); + assertEquals(1, compiledCode.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + assertEquals(1, pinnedCode.refCount); + assertEquals(1, pinnedCode.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + assertEquals(1, localizedCode.refCount); + assertEquals(1, localizedCode.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + + GlobalVariable.resetAllGlobals(); + + for (RuntimeCode code : new RuntimeCode[]{compiledCode, pinnedCode, localizedCode}) { + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, code.perlLifecycleState()); + assertEquals(0, code.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CodeSlotReleaseBoundaryTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CodeSlotReleaseBoundaryTest.java new file mode 100644 index 0000000000..614d404cd5 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CodeSlotReleaseBoundaryTest.java @@ -0,0 +1,44 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +@Tag("unit") +class CodeSlotReleaseBoundaryTest { + @Test + void releasingCodeSlotDoesNotFlushAnOlderPendingOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash earlierTarget = new RuntimeHash(); + RuntimeScalar anonymousReference = earlierTarget.createAnonymousReference(); + RuntimeScalar earlierOwner = new RuntimeScalar(); + earlierOwner.set(anonymousReference); + + MortalList.pushMark(); + try { + MortalList.deferDecrementIfTracked(earlierOwner); + assertEquals(1, runtime.lifecycleState.pending.size()); + + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar codeSlot = new RuntimeScalar(code); + codeSlot.retainCodeSlotBinding(); + codeSlot.releaseCodeSlotBinding(); + + assertEquals(1, earlierTarget.refCount, + "the unrelated pending owner stays live at CODE-slot cleanup"); + assertEquals(1, runtime.lifecycleState.pending.size(), + "CODE-slot cleanup completes only its own queued release"); + } finally { + MortalList.popAndFlush(); + } + + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, earlierTarget.perlLifecycleState(), + "the pending owner is released at its enclosing boundary"); + assertEquals(0, earlierTarget.refCount); + assertFalse(earlierTarget.hasPendingOwnerRelease()); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CodeStateAggregateOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CodeStateAggregateOwnerSlotTest.java new file mode 100644 index 0000000000..7f092f6a1d --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CodeStateAggregateOwnerSlotTest.java @@ -0,0 +1,96 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class CodeStateAggregateOwnerSlotTest { + @Test + void deferredStateAggregateReleaseUsesCodeOwnerIdentity() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode code = new RuntimeCode(null, List.of()); + RuntimeScalar codeRoot = new RuntimeScalar(code); + String codeName = "CodeStateAggregateOwnerSlotTest::holder"; + GlobalVariable.globalCodeRefs.put(codeName, codeRoot); + RuntimeArray stateArray = StateVariable.retrieveStateArray(codeRoot, "@state", 914_027); + RuntimeScalar temporaryOwner = + CountedOwnerFixture.temporaryReference(stateArray); + RuntimeScalar weak = stateArray.createAnonymousReference(); + WeakRefRegistry.weaken(weak); + + try { + assertEquals(1, stateArray.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE), + "the persistent CODE state entry must own its aggregate directly"); + + MortalList.pushMark(); + CountedOwnerFixture.queueRelease(temporaryOwner); + { + MortalList.popAndFlush(); + + assertTrue(WeakRefRegistry.isweak(weak), + "the live CODE state binding keeps the weakly observed array alive"); + assertEquals(1, stateArray.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + } + + code.releaseStateStorage(); + + assertEquals(0, stateArray.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + assertFalse(WeakRefRegistry.isweak(weak), + "retiring the CODE state binding releases the final aggregate owner"); + assertEquals(RuntimeScalarType.UNDEF, weak.type); + } finally { + code.releaseStateStorage(); + if (WeakRefRegistry.isweak(weak)) WeakRefRegistry.unweaken(weak); + GlobalVariable.globalCodeRefs.remove(codeName); + } + } + } + + @Test + void stateScalarsAndRefaliasesRetainTheirCodeStateCells() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode code = new RuntimeCode(null, List.of()); + RuntimeScalar codeRoot = new RuntimeScalar(code); + RuntimeScalar stateScalar = StateVariable.retrieveStateScalar( + codeRoot, "$scalar", 914_028); + RuntimeArray stateArray = StateVariable.retrieveStateArray( + codeRoot, "@array", 914_029); + RuntimeHash stateHash = StateVariable.retrieveStateHash( + codeRoot, "%hash", 914_030); + RuntimeArray aliasedArray = new RuntimeArray(); + RuntimeHash aliasedHash = new RuntimeHash(); + StateVariable.aliasStateArray(codeRoot, "@alias", 914_031, aliasedArray); + StateVariable.aliasStateHash(codeRoot, "%alias", 914_032, aliasedHash); + RuntimeScalar arrayAliasCell = code.stateAggregateAliasOwners.get("@" + + PersistentVariable.beginVariable(914_031, "alias")); + RuntimeScalar hashAliasCell = code.stateAggregateAliasOwners.get("%" + + PersistentVariable.beginVariable(914_032, "alias")); + + assertEquals(1, stateScalar.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + assertEquals(1, stateArray.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + assertEquals(1, stateHash.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + assertEquals(1, arrayAliasCell.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + assertEquals(1, hashAliasCell.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + assertSame(aliasedArray, arrayAliasCell.countedOwnerSlot().referent()); + assertSame(aliasedHash, hashAliasCell.countedOwnerSlot().referent()); + + code.releaseStateStorage(); + MortalList.flush(); + + assertEquals(0, stateScalar.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + assertEquals(0, stateArray.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + assertEquals(0, stateHash.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + assertEquals(0, arrayAliasCell.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + assertEquals(0, hashAliasCell.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ContainerSlotAcquisitionOrderTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ContainerSlotAcquisitionOrderTest.java new file mode 100644 index 0000000000..ccadb78611 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ContainerSlotAcquisitionOrderTest.java @@ -0,0 +1,171 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ContainerSlotAcquisitionOrderTest { + @Test + void hashReplacementAcquiresNewEdgeBeforePublishingAndReleasesOldEdgeAfterward() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray previous = new RuntimeArray(); + RuntimeArray replacement = new RuntimeArray(); + ObservingHash hash = new ObservingHash(replacement, previous); + RuntimeScalar previousReference = previous.createAnonymousReference(); + RuntimeScalar replacementReference = replacement.createAnonymousReference(); + + hash.put("child", previousReference); + assertEquals(1, previous.refCount); + + hash.observePublication = true; + hash.put("child", replacementReference); + + assertTrue(hash.replacementCountAtPublication > 0, + "the new referent must be retained before the map publishes its slot"); + assertTrue(hash.previousOwnerAtPublication, + "the old edge must remain owned until the replacement is published"); + assertEquals(1, replacement.refCount); + assertEquals(1, previous.refCount, + "the displaced release is deferred until after publication"); + + MortalList.flush(); + + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, previous.perlLifecycleState(), + "the previous referent reaches its final lifecycle state"); + assertEquals(0, previous.refCount); + assertEquals(0, previous.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + assertEquals(1, replacement.refCount); + assertEquals(1, replacement.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + } + } + + @Test + void arrayLiteralAcquiresElementBeforePublishing() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray referent = new RuntimeArray(); + RuntimeScalar reference = referent.createAnonymousReference(); + ObservingArray array = new ObservingArray(referent); + + array.add(reference); + + assertEquals(1, array.referentCountAtPublication, + "an array literal must acquire its element edge before publishing the cell"); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + } + } + + @Test + void pushAcquiresElementsBeforePublishing() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray referent = new RuntimeArray(); + RuntimeScalar reference = referent.createAnonymousReference(); + ObservingArray array = new ObservingArray(referent); + + RuntimeArray.push(array, reference); + + assertEquals(1, array.referentCountAtPublication, + "push must acquire each strong element edge before publishing it"); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + } + } + + @Test + void wholeArrayReplacementAcquiresElementsBeforePublishing() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray referent = new RuntimeArray(); + RuntimeScalar reference = referent.createAnonymousReference(); + RuntimeArray destination = new RuntimeArray(); + RuntimeArray.push(destination, new RuntimeScalar(1)); + ObservingArray array = new ObservingArray(referent); + array.elements.addAll(destination.elements); + RuntimeList replacement = new RuntimeList(); + replacement.add(reference); + + array.setFromList(replacement); + + assertEquals(1, array.referentCountAtPublication, + "whole-array replacement must acquire new element edges before publication"); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + } + } + + @Test + void singleValueArrayReplacementPublishesBeforeReleasingPreviousElement() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray previous = new RuntimeArray(); + RuntimeScalar previousReference = previous.createAnonymousReference(); + RuntimeArray replacement = new RuntimeArray(); + RuntimeScalar replacementReference = replacement.createAnonymousReference(); + ObservingArray array = new ObservingArray(replacement, previous); + array.add(previousReference); + + array.set(replacementReference); + + assertEquals(1, array.referentCountAtPublication, + "the replacement referent is retained before the array slot is published"); + assertEquals(1, array.previousOwnersAtPublication, + "the previous element remains owned until the replacement is published"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, previous.perlLifecycleState(), + "the old element is released after the replacement is visible"); + assertEquals(0, previous.refCount); + } + } + + private static final class ObservingHash extends RuntimeHash { + private final RuntimeArray replacement; + private final RuntimeArray previous; + private boolean observePublication; + private int replacementCountAtPublication = -1; + private boolean previousOwnerAtPublication; + + private ObservingHash(RuntimeArray replacement, RuntimeArray previous) { + this.replacement = replacement; + this.previous = previous; + } + + @Override + void markPackageRootedValue(RuntimeScalar value) { + super.markPackageRootedValue(value); + if (!observePublication || value == null || value.value != replacement) return; + replacementCountAtPublication = replacement.refCount; + previousOwnerAtPublication = + previous.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT) == 1; + } + } + + private static final class ObservingArray extends RuntimeArray { + private final RuntimeArray referent; + private final RuntimeArray previous; + private int referentCountAtPublication = -1; + private int previousOwnersAtPublication = -1; + + private ObservingArray(RuntimeArray referent) { + this(referent, null); + } + + private ObservingArray(RuntimeArray referent, RuntimeArray previous) { + this.referent = referent; + this.previous = previous; + } + + @Override + void markPackageRootedValue(RuntimeScalar value) { + super.markPackageRootedValue(value); + if (value != null && value.value == referent) { + referentCountAtPublication = referent.refCount; + if (previous != null) { + previousOwnersAtPublication = + previous.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT); + } + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CountedArrayOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CountedArrayOwnerSlotTest.java new file mode 100644 index 0000000000..8f86096f05 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CountedArrayOwnerSlotTest.java @@ -0,0 +1,23 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Tag("unit") +class CountedArrayOwnerSlotTest { + @Test + void countedArraySlotsRetainNestedReferents() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray parent = new RuntimeArray(); + RuntimeHash child = new RuntimeHash(); + child.setTrackedRefCount(0); + parent.addClonedElement(child.createAnonymousReference()); + + assertEquals(1, child.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + assertEquals(1, child.refCount); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CountedOwnerFixture.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CountedOwnerFixture.java new file mode 100644 index 0000000000..462177e56c --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CountedOwnerFixture.java @@ -0,0 +1,22 @@ +package org.perlonjava.runtime.runtimetypes; + +/** Helpers for tests that model a concrete counted Perl reference slot. */ +final class CountedOwnerFixture { + private CountedOwnerFixture() { } + + static RuntimeScalar reference(RuntimeBase referent, PerlOwnerSlot.Kind kind) { + RuntimeScalar owner = new RuntimeScalar(); + owner.type = RuntimeScalarType.REFERENCE; + owner.value = referent; + RuntimeScalar.incrementRefCountForContainerStore(owner, kind); + return owner; + } + + static RuntimeScalar temporaryReference(RuntimeBase referent) { + return reference(referent, PerlOwnerSlot.Kind.RETURN_VALUE); + } + + static void queueRelease(RuntimeScalar owner) { + MortalList.deferDecrementIfTracked(owner); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CountedOwnerReleaseRequiresOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CountedOwnerReleaseRequiresOwnerSlotTest.java new file mode 100644 index 0000000000..74404a5044 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CountedOwnerReleaseRequiresOwnerSlotTest.java @@ -0,0 +1,36 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@Tag("unit") +class CountedOwnerReleaseRequiresOwnerSlotTest { + @Test + void countedReleaseCannotQueueWithoutItsOwnerIdentity() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeArray referent = new RuntimeArray(); + referent.setTrackedRefCount(1); + referent.hadCountedReference = true; + + RuntimeArray replacement = new RuntimeArray(); + replacement.setTrackedRefCount(1); + + RuntimeScalar owner = new RuntimeScalar(); + owner.type = RuntimeScalarType.ARRAYREFERENCE; + owner.value = replacement; + owner.refCountOwned = true; + owner.recordCountedOwner(replacement); + + IllegalStateException failure = assertThrows(IllegalStateException.class, + () -> referent.queueOwnerRelease(owner, "invariant regression")); + + assertEquals(1, referent.refCount, + "a rejected queue leaves the counted referent unchanged"); + org.junit.jupiter.api.Assertions.assertTrue( + failure.getMessage().contains("lost its PerlOwnerSlot")); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CountedOwnerSlotLedgerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CountedOwnerSlotLedgerTest.java new file mode 100644 index 0000000000..5f512ce504 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CountedOwnerSlotLedgerTest.java @@ -0,0 +1,27 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class CountedOwnerSlotLedgerTest { + @Test + void countedOwnersAreVisibleBeforeFirstWeaken() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar firstOwner = new RuntimeScalar(); + RuntimeScalar secondOwner = new RuntimeScalar(); + firstOwner.set(referent.createAnonymousReference()); + secondOwner.set(referent.createAnonymousReference()); + + assertEquals(2, referent.countedOwnerSlotCount()); + assertEquals(2, referent.activeOwnerCount()); + assertTrue(referent.activeOwnerSnapshot().contains(firstOwner)); + assertTrue(referent.activeOwnerSnapshot().contains(secondOwner)); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CountedOwnerSlotOwnerReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CountedOwnerSlotOwnerReleaseTest.java new file mode 100644 index 0000000000..fc41580fd3 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CountedOwnerSlotOwnerReleaseTest.java @@ -0,0 +1,48 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class CountedOwnerSlotOwnerReleaseTest { + @Test + void scalarOverwriteReleasesOnlyTheReplacedOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + RuntimeArray arrayOwner = new RuntimeArray(); + arrayOwner.push(target.createAnonymousReference()); + RuntimeScalar scalarOwner = new RuntimeScalar(); + scalarOwner.set(target.createAnonymousReference()); + RuntimeScalar observer = target.createAnonymousReference(); + WeakRefRegistry.weaken(observer); + + try { + assertEquals(2, target.countedOwnerSlotCount()); + assertEquals(2, target.refCount); + + { + scalarOwner.set(new RuntimeScalar()); + + assertEquals(1, target.refCount); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + assertTrue(WeakRefRegistry.isweak(observer)); + } + + arrayOwner.elements.getFirst().set(new RuntimeScalar()); + assertFalse(WeakRefRegistry.isweak(observer)); + } finally { + if (WeakRefRegistry.isweak(observer)) WeakRefRegistry.unweaken(observer); + scalarOwner.set(new RuntimeScalar()); + if (!arrayOwner.elements.isEmpty()) { + arrayOwner.elements.getFirst().set(new RuntimeScalar()); + } + } + } + } + +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CountedOwnerStorageTransferTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CountedOwnerStorageTransferTest.java new file mode 100644 index 0000000000..f0b77c4d2c --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CountedOwnerStorageTransferTest.java @@ -0,0 +1,48 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class CountedOwnerStorageTransferTest { + @Test + void countedScalarCellRemainsCurrentWhenStoredInAggregateSlots() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash arrayReferent = new RuntimeHash(); + RuntimeScalar arrayScalar = arrayReferent.createAnonymousReference(); + + RuntimeScalar.incrementRefCountForContainerStore(arrayScalar); + assertEquals(PerlOwnerSlot.Kind.SCALAR_CELL, arrayScalar.countedOwnerSlot().kind()); + + RuntimeArray array = new RuntimeArray(); + array.elements.add(arrayScalar); + + assertEquals(PerlOwnerSlot.Kind.SCALAR_CELL, arrayScalar.countedOwnerSlot().kind(), + "the referent owner belongs to the scalar cell, even when an array stores it"); + assertTrue(arrayScalar.isCurrentCountedScalarOwner( + arrayReferent, arrayScalar.countedOwnerSlot()), + "the current array storage proves the scalar cell is a live Perl owner"); + assertEquals(1, arrayReferent.refCount, + "moving the scalar owner changes provenance without changing its count"); + + RuntimeHash hashReferent = new RuntimeHash(); + RuntimeScalar hashScalar = hashReferent.createAnonymousReference(); + RuntimeScalar.incrementRefCountForContainerStore(hashScalar); + + RuntimeHash hash = new RuntimeHash(); + hash.elements.put("owner", hashScalar); + + assertEquals(PerlOwnerSlot.Kind.SCALAR_CELL, hashScalar.countedOwnerSlot().kind(), + "the referent owner belongs to the scalar cell, even when a hash stores it"); + assertTrue(hashScalar.isCurrentCountedScalarOwner( + hashReferent, hashScalar.countedOwnerSlot()), + "the current hash storage proves the scalar cell is a live Perl owner"); + assertEquals(1, hashReferent.refCount, + "moving the scalar owner changes provenance without changing its count"); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CountedScalarOwnerAcquisitionTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CountedScalarOwnerAcquisitionTest.java new file mode 100644 index 0000000000..2de86b3fe3 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CountedScalarOwnerAcquisitionTest.java @@ -0,0 +1,59 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class CountedScalarOwnerAcquisitionTest { + @Test + void containerAcquisitionPairsTheCountWithItsCurrentScalarSlot() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar owner = referent.createAnonymousReference(); + + RuntimeScalar.incrementRefCountForContainerStore(owner); + + PerlOwnerSlot slot = owner.countedOwnerSlot(); + assertTrue(owner.refCountOwned); + assertEquals(1, referent.refCount); + assertEquals(1, referent.countedOwnerSlotCount()); + assertEquals(1, referent.activeOwnerCount()); + assertSame(referent, slot.referent()); + assertSame(owner, slot.countedScalarOwner()); + assertEquals(PerlOwnerSlot.Kind.SCALAR_CELL, slot.kind()); + } + } + + @Test + void unweakenReacquiresTheScalarSlotAndItsCountTogether() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar firstOwner = new RuntimeScalar(); + RuntimeScalar weakOwner = new RuntimeScalar(); + firstOwner.set(referent.createAnonymousReference()); + weakOwner.set(referent.createAnonymousReference()); + + assertEquals(2, referent.refCount); + assertEquals(2, referent.countedOwnerSlotCount()); + + WeakRefRegistry.weaken(weakOwner); + assertEquals(1, referent.refCount); + assertEquals(1, referent.countedOwnerSlotCount()); + assertFalse(weakOwner.refCountOwned); + + WeakRefRegistry.unweaken(weakOwner); + assertEquals(2, referent.refCount); + assertEquals(2, referent.countedOwnerSlotCount()); + assertEquals(2, referent.activeOwnerCount()); + assertTrue(weakOwner.refCountOwned); + assertSame(referent, weakOwner.countedOwnerSlot().referent()); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CountedScalarOwnerReplacementTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CountedScalarOwnerReplacementTest.java new file mode 100644 index 0000000000..d3c9fe688d --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CountedScalarOwnerReplacementTest.java @@ -0,0 +1,58 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class CountedScalarOwnerReplacementTest { + @Test + void replacementPairsTheNewCountWithTheStableScalarSlot() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash previous = new RuntimeHash(); + RuntimeHash replacement = new RuntimeHash(); + RuntimeScalar owner = new RuntimeScalar(); + owner.set(previous.createAnonymousReference()); + + PerlOwnerSlot slot = owner.countedOwnerSlot(); + assertEquals(1, previous.refCount); + assertEquals(1, previous.countedOwnerSlotCount()); + + owner.set(replacement.createAnonymousReference()); + + assertSame(slot, owner.countedOwnerSlot()); + assertSame(replacement, slot.referent()); + assertSame(owner, slot.countedScalarOwner()); + assertTrue(owner.refCountOwned); + assertEquals(1, replacement.refCount); + assertEquals(1, replacement.countedOwnerSlotCount()); + assertEquals(0, previous.countedOwnerSlotCount()); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, previous.perlLifecycleState()); + assertEquals(0, previous.refCount); + } + } + + @Test + void replacingAReferenceWithTheSameReferentKeepsOneCountedEdge() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar owner = new RuntimeScalar(); + RuntimeScalar reference = referent.createAnonymousReference(); + owner.set(reference); + PerlOwnerSlot slot = owner.countedOwnerSlot(); + + owner.set(reference); + + assertSame(slot, owner.countedOwnerSlot()); + assertSame(referent, slot.referent()); + assertEquals(1, referent.refCount); + assertEquals(1, referent.countedOwnerSlotCount()); + assertTrue(owner.refCountOwned); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CurrentAggregateElementOwnerContainerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CurrentAggregateElementOwnerContainerTest.java new file mode 100644 index 0000000000..6673332abe --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CurrentAggregateElementOwnerContainerTest.java @@ -0,0 +1,42 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class CurrentAggregateElementOwnerContainerTest { + @Test + void liveHashElementOwnerSurvivesAnotherContainerChangingTheOwnerHint() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeHash schema = new RuntimeHash(); + schema.localBindingExists = true; + RuntimeArray temporaryList = new RuntimeArray(); + + try { + schema.put("source", referent.createAnonymousReference()); + RuntimeScalar cell = schema.elements.get("source"); + PerlOwnerSlot owner = cell.countedOwnerSlot(); + assertEquals(PerlOwnerSlot.Kind.HASH_ELEMENT, owner.kind()); + + // List-result construction can leave one scalar cell visible + // through another aggregate without transferring its counted + // HASH_ELEMENT edge. That aggregate updates only the fast hint. + temporaryList.elements.add(cell); + assertSame(temporaryList, cell.getContainerOwner()); + + assertTrue(DestroyDispatch.isCurrentPerlOwnerSlot(referent, owner), + "the counted owner identity keeps the live schema as a Perl owner"); + } finally { + temporaryList.elements.clear(); + schema.elements.clear(); + schema.localBindingExists = false; + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/CurrentCountedOwnerReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/CurrentCountedOwnerReleaseTest.java new file mode 100644 index 0000000000..a734bfe531 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/CurrentCountedOwnerReleaseTest.java @@ -0,0 +1,58 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class CurrentCountedOwnerReleaseTest { + @Test + void deferredReleaseBalancesCurrentScalarCellOwners() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + RuntimeScalar released = new RuntimeScalar(); + RuntimeScalar surviving = new RuntimeScalar(); + RuntimeScalar weakObserver = target.createAnonymousReference(); + WeakRefRegistry.weaken(weakObserver); + MyVarCleanupStack.register(released); + MyVarCleanupStack.register(surviving); + + try { + released.set(target.createAnonymousReference()); + surviving.set(target.createAnonymousReference()); + + assertEquals(2, target.countedOwnerSlotCount()); + assertEquals(2, target.activeOwnerSnapshot().size()); + assertTrue(target.activeOwnerSnapshot().stream().allMatch(owner -> + owner.countedOwnerSlot() != null + && owner.countedOwnerSlot().isActive() + && owner.countedOwnerSlot().referent() == target), + "each active scalar owner has a corresponding counted identity"); + { + MortalList.deferDecrementIfTracked(released); + MortalList.flushAboveMark(); + + assertEquals(1, target.refCount); + assertEquals(1, target.countedOwnerSlotCount()); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + } + + surviving.set(new RuntimeScalar()); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type, + "the final current owner clears the weak observer"); + } finally { + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + RuntimeScalar.scopeExitCleanup(released); + RuntimeScalar.scopeExitCleanup(surviving); + MyVarCleanupStack.unregister(released); + MyVarCleanupStack.unregister(surviving); + MortalList.flush(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/DbicTailCallArgumentFrameCleanupTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/DbicTailCallArgumentFrameCleanupTest.java new file mode 100644 index 0000000000..0c0076b24c --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/DbicTailCallArgumentFrameCleanupTest.java @@ -0,0 +1,139 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.app.cli.CompilerOptions; +import org.perlonjava.app.scriptengine.PerlLanguageProvider; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class DbicTailCallArgumentFrameCleanupTest { + + @Test + void nestedTryTinyGotoReleasesCallbackAndArgumentFrame() throws Exception { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + CompilerOptions options = new CompilerOptions(); + options.fileName = ""; + options.code = """ + use strict; + use warnings; + use Scalar::Util qw(weaken); + use Try::Tiny; + our %weak_callbacks; + for my $function (qw(try catch finally)) { + no strict 'refs'; + no warnings 'redefine'; + my $original = \\&{"Try::Tiny::$function"}; + *{"Try::Tiny::$function"} = sub (&;@) { + if ($function eq 'try') { + push @{$weak_callbacks{$function}}, $_[0]; + weaken($weak_callbacks{$function}[-1]); + } + goto $original; + }; + } + { + package Unit::TailCallOwner::Storage; + sub txn_do { + my ($self, $callback) = @_; + return Try::Tiny::try { $callback->() } + Try::Tiny::catch { die $_ }; + } + sub _dbh_last_insert_id { + my ($self, $dbh, $source, $column) = @_; + my $id = Try::Tiny::try { + $dbh->last_insert_id(undef, undef, $source->name, $column); + }; + return $id if defined $id; + } + package Unit::TailCallOwner::DBH; + sub last_insert_id { $_[0]->{id} } + package Unit::TailCallOwner::Source; + sub name { $_[0]->{name} } + } + { + my $dbh = bless { id => 42 }, 'Unit::TailCallOwner::DBH'; + my $source = bless { name => 'Artist' }, 'Unit::TailCallOwner::Source'; + weaken(my $weak_dbh = $dbh); + weaken(my $weak_source = $source); + Unit::TailCallOwner::Storage->txn_do(sub { + Unit::TailCallOwner::Storage->_dbh_last_insert_id( + $dbh, $source, 'artist_id'); + }); + } + 1; + """; + RuntimeArray.push(options.inc, new RuntimeScalar("src/main/perl/lib")); + RuntimeArray.push(options.inc, new RuntimeScalar("src/test/resources/unit/lib")); + PerlLanguageProvider.executePerlCode(options, true); + + RuntimeHash weakCallbacks = GlobalVariable.getGlobalHash("main::weak_callbacks"); + assertNotNull(weakCallbacks); + RuntimeScalar triesValue = weakCallbacks.elements.get("try"); + assertNotNull(triesValue); + assertTrue(triesValue.value instanceof RuntimeArray); + RuntimeArray tries = (RuntimeArray) triesValue.value; + assertEquals(2, tries.elements.size(), "both try callback blocks must be observed"); + + RuntimeScalar retainedCallback = tries.elements.get(1); + assertNotNull(retainedCallback); + RuntimeBase callback = retainedCallback.value instanceof RuntimeBase base ? base : null; + int argsDepth = runtime.executionState().argsStack.size(); + String ownerTrace = callback == null ? "cleared" + : callback.ownerTraceSnapshot() + "; " + untrackedOwnerDetails(callback); + assertEquals(0, argsDepth, + "tail-call left an argument frame active; " + ownerTrace); + if (callback != null) { + assertTrue(WeakRefRegistry.isweak(retainedCallback), + "a retained callback probe must be weak; " + ownerTrace); + } + assertEquals(RuntimeScalarType.UNDEF, retainedCallback.type, + "inner Try::Tiny callback remains after goto; weakCell#" + + System.identityHashCode(retainedCallback) + " argsDepth=" + + argsDepth + "; " + ownerTrace); + assertNull(retainedCallback.value, + "cleared callback probe still contains a referent; " + ownerTrace); + } + } + + private static String untrackedOwnerDetails(RuntimeBase referent) { + StringBuilder details = new StringBuilder("untrackedOwners=["); + boolean first = true; + for (PerlOwnerSlot slot : referent.ownerSlotSnapshot()) { + if (!slot.isActive() || slot.kind() != PerlOwnerSlot.Kind.UNTRACKED_REFERENCE) { + continue; + } + RuntimeScalar owner = slot.untrackedScalarOwner(); + if (!first) details.append(", "); + first = false; + details.append("slot#").append(slot.identity()).append(" scalar#"); + if (owner == null) { + details.append("collected"); + continue; + } + details.append(System.identityHashCode(owner)) + .append(" weak=").append(WeakRefRegistry.isweak(owner)) + .append(" owns=").append(owner.refCountOwned) + .append(" scopeExited=").append(owner.scopeExited) + .append(" local=").append(owner.localBindingExists) + .append(" transient=").append(owner.isTransientArgumentValueOwner()) + .append(" registered=").append(MyVarCleanupStack.isRegistered(owner)); + if (owner.containerOwner != null) { + details.append(" container=") + .append(owner.containerOwner.getClass().getSimpleName()) + .append('#').append(System.identityHashCode(owner.containerOwner)) + .append(" perlOwned=").append(owner.containerOwner.hasPerlStrongOwner()) + .append(" packageRoot=").append(owner.containerOwner.isPackageGlobalRoot) + .append(" local=").append(owner.containerOwner.localBindingExists) + .append(" registered=") + .append(MyVarCleanupStack.isRegistered(owner.containerOwner)); + } + } + return details.append(']').toString(); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/DeferredOwnerLedgerProducerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/DeferredOwnerLedgerProducerTest.java new file mode 100644 index 0000000000..354d897bbc --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/DeferredOwnerLedgerProducerTest.java @@ -0,0 +1,55 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.app.cli.CompilerOptions; +import org.perlonjava.app.scriptengine.PerlLanguageProvider; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Tag("unit") +class DeferredOwnerLedgerProducerTest { + private static final String SOURCE = """ + use strict; + use warnings; + use Scalar::Util qw(weaken); + our (@roots, @unrelated, $destroyed, $weak); + $destroyed = 0; + { + package Issue1649::DeferredOwnerNormalStore; + sub DESTROY { ++$main::destroyed } + } + @unrelated = map { { nested => [$_, { leaf => $_ }] } } 1 .. 256; + { + my $value = bless {}, 'Issue1649::DeferredOwnerNormalStore'; + $weak = $value; + weaken($weak); + $roots[0] = [$value]; + } + my $survived_under_root = defined($weak) && $destroyed == 0; + $roots[0] = undef; + my $released_after_root = !defined($weak) && $destroyed == 1; + join ':', $survived_under_root ? 1 : 0, + $released_after_root ? 1 : 0, $destroyed; + """; + + @Test + void ordinaryNestedPackageStoreUsesOwnerSlotsWithoutRootQueries() throws Exception { + for (boolean interpreter : new boolean[]{false, true}) { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + CompilerOptions options = new CompilerOptions(); + options.fileName = ""; + options.code = SOURCE; + options.useInterpreter = interpreter; + + { + RuntimeList result = PerlLanguageProvider.executePerlCode(options, false); + + assertEquals("1:1:1", result.scalar().toString(), + "the nested package owner preserves and then releases the value"); + } + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/DeferredReleaseOwnerSlotFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/DeferredReleaseOwnerSlotFastPathTest.java new file mode 100644 index 0000000000..88827d579f --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/DeferredReleaseOwnerSlotFastPathTest.java @@ -0,0 +1,46 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class DeferredReleaseOwnerSlotFastPathTest { + @Test + void deferredReleaseBalancesTheRemainingScalarOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId("Issue1649::DeferredOwnerSlot"); + RuntimeScalar released = new RuntimeScalar(); + released.set(target.createAnonymousReference()); + RuntimeScalar remaining = new RuntimeScalar(); + remaining.set(target.createAnonymousReference()); + RuntimeScalar weak = target.createAnonymousReference(); + WeakRefRegistry.weaken(weak); + + try { + assertEquals(2, target.countedOwnerSlotCount()); + assertEquals(2, target.refCount); + + { + MortalList.deferDecrementIfTracked(released); + MortalList.flushAboveMark(); + + assertEquals(1, target.refCount); + assertEquals(1, target.countedOwnerSlotCount()); + assertTrue(WeakRefRegistry.isweak(weak)); + + remaining.set(new RuntimeScalar()); + assertEquals(RuntimeScalarType.UNDEF, weak.type); + assertEquals(0, target.countedOwnerSlotCount()); + } + } finally { + if (WeakRefRegistry.isweak(weak)) WeakRefRegistry.unweaken(weak); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/DeferredReleaseRejectsStaleAggregateSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/DeferredReleaseRejectsStaleAggregateSlotTest.java new file mode 100644 index 0000000000..8728dcd8b1 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/DeferredReleaseRejectsStaleAggregateSlotTest.java @@ -0,0 +1,68 @@ +package org.perlonjava.runtime.runtimetypes; + +import java.util.function.Consumer; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Tag("unit") +class DeferredReleaseRejectsStaleAggregateSlotTest { + @Test + void detachedArrayElementIdentityDoesNotRestoreTheReferentCount() { + RuntimeArray container = new RuntimeArray(); + assertDetachedElementDoesNotRestore( + owner -> { + container.push(owner); + owner.set(new RuntimeScalar()); + }, + owner -> container.elements.remove(0), + PerlOwnerSlot.Kind.ARRAY_ELEMENT); + } + + @Test + void detachedHashElementIdentityDoesNotRestoreTheReferentCount() { + RuntimeHash container = new RuntimeHash(); + assertDetachedElementDoesNotRestore( + owner -> container.put("owner", owner), + owner -> container.elements.remove("owner"), + PerlOwnerSlot.Kind.HASH_ELEMENT); + } + + private static void assertDetachedElementDoesNotRestore( + Consumer store, Consumer detach, + PerlOwnerSlot.Kind ownerKind) { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId( + "DeferredReleaseRejectsStaleAggregateSlotTest::Target"); + RuntimeScalar released = new RuntimeScalar(); + released.set(target.createAnonymousReference()); + RuntimeScalar staleOwner = new RuntimeScalar(); + staleOwner.set(target.createAnonymousReference()); + store.accept(staleOwner); + RuntimeScalar weak = target.createAnonymousReference(); + WeakRefRegistry.weaken(weak); + + try { + assertEquals(1, target.ownerSlotCount(ownerKind)); + target.setTrackedRefCount(1); // Model a transient undercount before deferred release. + detach.accept(staleOwner); // Deliberately leave the old identity active. + + MortalList.deferDecrementIfTracked(released); + MortalList.flushAboveMark(); + + assertEquals(RuntimeScalarType.UNDEF, weak.type, + "a detached aggregate slot is not a current Perl owner"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, target.perlLifecycleState(), + "a stale aggregate slot cannot restore the compatibility count"); + assertEquals(0, target.refCount); + } finally { + released.set(new RuntimeScalar()); + staleOwner.set(new RuntimeScalar()); + if (WeakRefRegistry.isweak(weak)) WeakRefRegistry.unweaken(weak); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/DeferredUnblessedAggregateOwnerSlotRepairTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/DeferredUnblessedAggregateOwnerSlotRepairTest.java new file mode 100644 index 0000000000..d7f16c459c --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/DeferredUnblessedAggregateOwnerSlotRepairTest.java @@ -0,0 +1,46 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class DeferredUnblessedAggregateOwnerSlotRepairTest { + @Test + void deferredReleaseUsesCurrentArrayElementSlotWithoutRootSnapshot() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + RuntimeArray ownerArray = new RuntimeArray(); + ownerArray.push(target.createAnonymousReference()); + RuntimeScalar weakObserver = target.createAnonymousReference(); + WeakRefRegistry.weaken(weakObserver); + + try { + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + RuntimeScalar temporaryOwner = + CountedOwnerFixture.temporaryReference(target); + MortalList.pushMark(); + CountedOwnerFixture.queueRelease(temporaryOwner); + + { + MortalList.popAndFlush(); + + assertEquals(1, target.refCount); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + } + + ownerArray.elements.getFirst().set(new RuntimeScalar()); + assertFalse(WeakRefRegistry.isweak(weakObserver)); + } finally { + if (WeakRefRegistry.isweak(weakObserver)) WeakRefRegistry.unweaken(weakObserver); + if (!ownerArray.elements.isEmpty()) { + ownerArray.elements.getFirst().set(new RuntimeScalar()); + } + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/DestroyCountOnlyResurrectionTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/DestroyCountOnlyResurrectionTest.java new file mode 100644 index 0000000000..a429748787 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/DestroyCountOnlyResurrectionTest.java @@ -0,0 +1,32 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class DestroyCountOnlyResurrectionTest { + @Test + void positiveCountDoesNotResurrectWithoutALiveOwnerSlot() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash referent = new RuntimeHash(); + referent.setTrackedRefCount(1); + + assertTrue(referent.ownerSlotSnapshot().isEmpty()); + assertFalse(DestroyDispatch.hasEscapedPerlOwner(referent, false, null), + "a count without a current Perl owner is not resurrection"); + + PerlOwnerSlot owner = new PerlOwnerSlot( + PerlOwnerSlot.Kind.TIED_HASH_ITERATOR_KEY); + owner.acquireNativeOwner(referent); + try { + assertTrue(DestroyDispatch.hasEscapedPerlOwner(referent, false, null), + "a live native Perl owner identity is resurrection evidence"); + } finally { + owner.release(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/DestroyCountedOwnerReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/DestroyCountedOwnerReleaseTest.java new file mode 100644 index 0000000000..e0f869bb82 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/DestroyCountedOwnerReleaseTest.java @@ -0,0 +1,51 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +@Tag("unit") +class DestroyCountedOwnerReleaseTest { + @Test + void argumentContainerReleaseBalancesCountInsideDestroy() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + referent.setTrackedRefCount(0); + RuntimeScalar owner = RuntimeScalar.retainArgumentContainerValue(referent); + assertEquals(1, referent.refCount); + + referent.currentlyDestroying = true; + RuntimeScalar.releaseArgumentContainerValue(owner); + + assertEquals(0, referent.refCount); + assertEquals(0, referent.countedOwnerSlotCount()); + assertFalse(referent.destroyFired, + "releasing a temporary owner must not re-enter DESTROY"); + } + } + + @Test + void methodInvocantReleaseBalancesCountInsideDestroy() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + referent.setTrackedRefCount(0); + PerlOwnerSlot owner = new PerlOwnerSlot(PerlOwnerSlot.Kind.ARGUMENT_VALUE); + owner.acquireCountedMethodInvocantOwner(referent, + "DestroyCountedOwnerReleaseTest method hold"); + assertEquals(1, referent.refCount); + + referent.currentlyDestroying = true; + MortalList.releaseCountedMethodInvocantOwner(referent, owner, + "DestroyCountedOwnerReleaseTest method release", false); + + assertEquals(0, referent.refCount); + assertEquals(0, referent.countedOwnerSlotCount()); + assertFalse(referent.destroyFired, + "releasing a method hold must not re-enter DESTROY"); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/DestroyOwnerSlotResurrectionTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/DestroyOwnerSlotResurrectionTest.java new file mode 100644 index 0000000000..497da876db --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/DestroyOwnerSlotResurrectionTest.java @@ -0,0 +1,140 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class DestroyOwnerSlotResurrectionTest { + @Test + void currentCountedGlobalOwnerIsDetectedWithoutRootWalk() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash referent = new RuntimeHash(); + referent.setTrackedRefCount(0); + RuntimeScalar global = GlobalVariable.getGlobalVariable( + "DestroyOwnerSlotResurrectionTest::countedOwner"); + Set ownersAtStart = referent.ownerSlotSnapshot(); + + try { + global.set(referenceTo(referent)); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + + { + assertTrue(DestroyDispatch.hasNewPerlOwnerSlot(referent, ownersAtStart)); + } + } finally { + global.set(new RuntimeScalar()); + } + } + } + + @Test + void durableUntrackedGlobalOwnerIsDetectedWithoutRootWalk() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + String globalName = "DestroyOwnerSlotResurrectionTest::untrackedRoot"; + RuntimeArray packageRoot = new RuntimeArray(); + GlobalVariable.globalArrays.put(globalName, packageRoot); + RuntimeArray referent = new RuntimeArray(); + referent.markRefCountUntracked(); + RuntimeScalar globalOwner = referent.createAnonymousReference(); + Set ownersAtStart = referent.ownerSlotSnapshot(); + + try { + packageRoot.elements.add(globalOwner); + assertTrue(referent.hasUntrackedReferenceOwnerSlotIdentity()); + + { + assertTrue(DestroyDispatch.hasNewPerlOwnerSlot(referent, ownersAtStart)); + assertTrue(referent.hasUntrackedReferenceOwnerSlotIdentity()); + } + } finally { + packageRoot.elements.clear(); + GlobalVariable.globalArrays.remove(globalName); + } + } + } + + @Test + void currentCountedOwnerIsDetectedOutsideGlobalTeardownWithoutRootWalk() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash referent = new RuntimeHash(); + referent.setTrackedRefCount(0); + RuntimeScalar global = GlobalVariable.getGlobalVariable( + "DestroyOwnerSlotResurrectionTest::nonGlobalCountedOwner"); + + try { + global.set(referenceTo(referent)); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + + { + assertTrue(DestroyDispatch.hasEscapedPerlOwner(referent, false, null), + "a durable current owner slot keeps a local DESTROY from finalizing"); + } + } finally { + global.set(new RuntimeScalar()); + } + } + } + + @Test + void detachedCountedCellDoesNotResurrectTheReferent() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash referent = new RuntimeHash(); + referent.setTrackedRefCount(0); + RuntimeScalar detachedCell = new RuntimeScalar(); + detachedCell.localBindingExists = true; + detachedCell.set(referenceTo(referent)); + Set ownersAtStart = Set.of(); + detachedCell.localBindingExists = false; + + try { + assertFalse(DestroyDispatch.hasNewPerlOwnerSlot(referent, ownersAtStart), + "a scalar cell outside any live slot is stale bookkeeping"); + assertFalse(referent.hasSemanticCaptureOwner(), + "the detached scalar has no live closure capture"); + String ownerSlotState = referent.ownerSlotSnapshot().stream() + .map(slot -> slot.kind() + "=" + + DestroyDispatch.isCurrentPerlOwnerSlot(referent, slot)) + .toList().toString(); + assertFalse(DestroyDispatch.hasCurrentPerlOwnerSlot(referent), ownerSlotState); + assertFalse(DestroyDispatch.hasEscapedPerlOwner(referent, false, null), + "a detached counted cell does not escape a local DESTROY"); + } finally { + detachedCell.set(new RuntimeScalar()); + } + } + } + + @Test + void temporaryArgumentOwnerIsNotResurrection() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash referent = new RuntimeHash(); + referent.setTrackedRefCount(0); + Set ownersAtStart = referent.ownerSlotSnapshot(); + RuntimeScalar staged = RuntimeScalar.retainStagedArgumentValue(referenceTo(referent)); + + try { + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + { + assertFalse(DestroyDispatch.hasNewPerlOwnerSlot(referent, ownersAtStart), + "a staged call argument does not outlive DESTROY as a Perl owner"); + } + } finally { + RuntimeScalar.releaseStagedArgumentValue(staged); + MortalList.flush(); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.HASHREFERENCE; + scalar.value = referent; + return scalar; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/DestroySelfOwnerReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/DestroySelfOwnerReleaseTest.java new file mode 100644 index 0000000000..f63d7b996e --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/DestroySelfOwnerReleaseTest.java @@ -0,0 +1,34 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; + +@Tag("unit") +class DestroySelfOwnerReleaseTest { + @Test + void syntheticSelfArgumentRetiresItsSlotWithoutReenteringDestroy() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + referent.setTrackedRefCount(0); + RuntimeScalar selfArgument = referent.createAnonymousReference(); + RuntimeScalar.incrementRefCountForContainerStore( + selfArgument, PerlOwnerSlot.Kind.ARRAY_ELEMENT); + PerlOwnerSlot ownerSlot = selfArgument.countedOwnerSlot(); + + referent.currentlyDestroying = true; + MortalList.releaseDestroySelfArgument( + selfArgument, "DestroySelfOwnerReleaseTest"); + + assertEquals(0, referent.refCount); + assertEquals(0, referent.countedOwnerSlotCount()); + assertFalse(selfArgument.refCountOwned); + assertNull(ownerSlot.referent()); + assertFalse(referent.destroyFired); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/DestroyedAggregateStaleOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/DestroyedAggregateStaleOwnerSlotTest.java new file mode 100644 index 0000000000..4962eeb02a --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/DestroyedAggregateStaleOwnerSlotTest.java @@ -0,0 +1,96 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +@Tag("unit") +class DestroyedAggregateStaleOwnerSlotTest { + @Test + void finalHashCleanupRetiresSlotToAlreadyDestroyedAggregate() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash child = new RuntimeHash(); + child.setBlessId(NameNormalizer.getBlessId( + "DestroyedAggregateStaleOwnerSlot::HashChild")); + RuntimeScalar childReference = child.createAnonymousReference(); + RuntimeHash parent = new RuntimeHash(); + parent.put("related_resultsets", childReference); + RuntimeScalar ownerCell = parent.elements.get("related_resultsets"); + + assertEquals(1, child.refCount); + assertEquals(1, + child.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + + markDestroyedWithStaleOwner(child); + MortalList.scopeExitCleanupDestroyedHash(parent); + MortalList.flush(); + + assertFalse(ownerCell.refCountOwned); + assertEquals(0, + child.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + } + } + + @Test + void finalArrayCleanupRetiresSlotToAlreadyDestroyedAggregate() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash blessedMarker = new RuntimeHash(); + blessedMarker.setBlessId(NameNormalizer.getBlessId( + "DestroyedAggregateStaleOwnerSlot::Marker")); + RuntimeHash child = new RuntimeHash(); + RuntimeScalar childReference = child.createAnonymousReference(); + RuntimeArray parent = new RuntimeArray(); + parent.push(childReference); + RuntimeScalar ownerCell = parent.elements.getFirst(); + + assertEquals(1, child.refCount); + assertEquals(1, + child.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + + markDestroyedWithStaleOwner(child); + MortalList.scopeExitCleanupDestroyedArray(parent); + MortalList.flush(); + + assertFalse(ownerCell.refCountOwned); + assertEquals(0, + child.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + } + } + + @Test + void scalarReferenceContentsOwnerAlreadyRetiresZeroCountTarget() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash target = new RuntimeHash(); + target.setTrackedRefCount(1); + + RuntimeScalar referenceCell = new RuntimeScalar(); + referenceCell.type = RuntimeScalarType.REFERENCE; + referenceCell.value = target; + referenceCell.referencedByScalarReference = true; + referenceCell.setTrackedRefCount(1); + + RuntimeScalar wrapper = new RuntimeScalar(); + wrapper.type = RuntimeScalarType.REFERENCE; + wrapper.value = referenceCell; + wrapper.localBindingExists = true; + PerlOwnerSlot contentsOwner = new PerlOwnerSlot( + PerlOwnerSlot.Kind.SCALAR_REFERENCE_CONTENTS); + contentsOwner.acquireScalarReferenceContents(target, referenceCell, wrapper); + wrapper.scalarReferenceContentsOwner = contentsOwner; + + markDestroyedWithStaleOwner(target); + wrapper.releaseOwnedScalarReferenceContents(); + + assertFalse(contentsOwner.isActive()); + assertEquals(0, target.ownerSlotCount( + PerlOwnerSlot.Kind.SCALAR_REFERENCE_CONTENTS)); + } + } + + private static void markDestroyedWithStaleOwner(RuntimeBase referent) { + referent.beginPerlDestruction(); + referent.markPerlDestroyed(); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/DynamicVariableManagerSuspendedOwnerFailureTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/DynamicVariableManagerSuspendedOwnerFailureTest.java new file mode 100644 index 0000000000..592baa1d1a --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/DynamicVariableManagerSuspendedOwnerFailureTest.java @@ -0,0 +1,128 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@Tag("unit") +class DynamicVariableManagerSuspendedOwnerFailureTest { + @Test + void resumeFailureStopsLaterRestoresAndReleasesAllSuspendedOwners() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash firstReferent = new RuntimeHash(); + RuntimeHash failingReferent = new RuntimeHash(); + RuntimeHash lastReferent = new RuntimeHash(); + TestState first = new TestState(firstReferent, false, false); + TestState failing = new TestState(failingReferent, true, false); + TestState last = new TestState(lastReferent, false, false); + + DynamicVariableManager.pushLocalVariable(first); + DynamicVariableManager.pushLocalVariable(failing); + DynamicVariableManager.pushLocalVariable(last); + List suspended = + DynamicVariableManager.suspendAbove(0); + + assertEquals(1, firstReferent.ownerSlotCount(PerlOwnerSlot.Kind.SUSPENDED_FRAME)); + assertEquals(1, failingReferent.ownerSlotCount(PerlOwnerSlot.Kind.SUSPENDED_FRAME)); + assertEquals(1, lastReferent.ownerSlotCount(PerlOwnerSlot.Kind.SUSPENDED_FRAME)); + + IllegalStateException failure = assertThrows(IllegalStateException.class, + () -> DynamicVariableManager.resumeSuspended(suspended)); + + assertEquals("resume failed", failure.getMessage()); + assertEquals(0, DynamicVariableManager.getLocalLevel()); + assertEquals(0, firstReferent.ownerSlotCount(PerlOwnerSlot.Kind.SUSPENDED_FRAME)); + assertEquals(0, failingReferent.ownerSlotCount(PerlOwnerSlot.Kind.SUSPENDED_FRAME)); + assertEquals(0, lastReferent.ownerSlotCount(PerlOwnerSlot.Kind.SUSPENDED_FRAME)); + assertEquals(1, first.resumeCount); + assertEquals(1, failing.resumeCount); + assertEquals(0, last.resumeCount); + assertEquals(1, first.restoreAfterResumeCount); + assertEquals(1, failing.restoreAfterResumeCount); + assertEquals(0, last.restoreAfterResumeCount); + } + } + + @Test + void suspendFailureReleasesEarlierOwnersAndUnwindsRemainingStates() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash firstReferent = new RuntimeHash(); + RuntimeHash failingReferent = new RuntimeHash(); + RuntimeHash lastReferent = new RuntimeHash(); + TestState first = new TestState(firstReferent, false, false); + TestState failing = new TestState(failingReferent, false, true); + TestState last = new TestState(lastReferent, false, false); + + DynamicVariableManager.pushLocalVariable(first); + DynamicVariableManager.pushLocalVariable(failing); + DynamicVariableManager.pushLocalVariable(last); + + IllegalStateException failure = assertThrows(IllegalStateException.class, + () -> DynamicVariableManager.suspendAbove(0)); + + assertEquals("suspend failed", failure.getMessage()); + assertEquals(0, DynamicVariableManager.getLocalLevel()); + assertEquals(0, firstReferent.ownerSlotCount(PerlOwnerSlot.Kind.SUSPENDED_FRAME)); + assertEquals(0, failingReferent.ownerSlotCount(PerlOwnerSlot.Kind.SUSPENDED_FRAME)); + assertEquals(0, lastReferent.ownerSlotCount(PerlOwnerSlot.Kind.SUSPENDED_FRAME)); + assertEquals(0, first.suspendCount); + assertEquals(1, failing.suspendCount); + assertEquals(1, last.suspendCount); + assertEquals(1, first.restoreCount); + assertEquals(1, failing.restoreCount); + assertEquals(1, last.restoreCount); + } + } + + private static final class TestState implements DynamicState { + private final RuntimeHash referent; + private final boolean failOnResume; + private final boolean failOnSuspend; + private int resumeCount; + private int suspendCount; + private int restoreCount; + private int restoreAfterResumeCount; + private boolean resumeAttempted; + + TestState(RuntimeHash referent, boolean failOnResume, boolean failOnSuspend) { + this.referent = referent; + this.failOnResume = failOnResume; + this.failOnSuspend = failOnSuspend; + } + + @Override + public void dynamicSaveState() {} + + @Override + public void dynamicRestoreState() { + restoreCount++; + if (resumeAttempted) restoreAfterResumeCount++; + } + + @Override + public RuntimeBase suspendedOwnerValue() { + return referent; + } + + @Override + public Object dynamicSuspendState() { + suspendCount++; + if (failOnSuspend) throw new IllegalStateException("suspend failed"); + return DynamicState.super.dynamicSuspendState(); + } + + @Override + public void dynamicResumeState(Object token) { + resumeCount++; + resumeAttempted = true; + dynamicSaveState(); + if (failOnResume) throw new IllegalStateException("resume failed"); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/EndBlockOwnerIdentityTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/EndBlockOwnerIdentityTest.java new file mode 100644 index 0000000000..af147feee2 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/EndBlockOwnerIdentityTest.java @@ -0,0 +1,80 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class EndBlockOwnerIdentityTest { + @Test + void queuedAndExecutingEndBlockKeepExactOwnersWithoutInventingACount() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar capturedPad = new RuntimeScalar(42); + AtomicReference codeRef = new AtomicReference<>(); + AtomicInteger callbackActiveOwnerCount = new AtomicInteger(); + AtomicBoolean callbackSawCapture = new AtomicBoolean(); + RuntimeCode code = new RuntimeCode((args, context) -> { + RuntimeCode activeCode = codeRef.get(); + callbackActiveOwnerCount.set( + activeCode.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_CODE)); + callbackSawCapture.set(activeCode.capturedScalars != null + && activeCode.capturedScalars.length == 1 + && activeCode.capturedScalars[0] == capturedPad); + return new RuntimeList(); + }, null); + codeRef.set(code); + code.setTrackedRefCount(0); + code.capturedScalars = new RuntimeScalar[]{capturedPad}; + code.capturedScalarOwnerSlots = new PerlOwnerSlot[]{ + capturedPad.retainClosureCaptureSlot()}; + + RuntimeScalar lexicalOwner = new RuntimeScalar(); + MyVarCleanupStack.register(lexicalOwner); + try { + lexicalOwner.set(new RuntimeScalar(code)); + SpecialBlock.saveEndBlock(new RuntimeScalar(code)); + + assertEquals(2, code.refCount); + assertEquals(1, code.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + assertEquals(1, code.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + assertEquals(2, code.refCount, + "the owner count remains paired with the queued and lexical slots"); + assertEquals(1, capturedPad.captureCount, + "the queued END block continues to own its captured pad"); + + SpecialBlock.runEndBlocks(); + MortalList.flushAboveMark(); + + assertEquals(2, callbackActiveOwnerCount.get(), + "the handoff identity and active frame span dequeue through invocation"); + assertTrue(callbackSawCapture.get(), + "the capture remains live while the END block executes"); + assertEquals(1, code.refCount, + "dequeue releases exactly the END queue's counted edge"); + assertEquals(0, code.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + assertEquals(1, code.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + + lexicalOwner.set(new RuntimeScalar()); + assertEquals(0, capturedPad.captureCount, + "the lexical's final release retires the captured pad"); + assertFalse(code.hasActiveCodeOwner()); + } finally { + while (!SpecialBlock.getEndBlocks().isEmpty()) { + RuntimeArray.shift(SpecialBlock.getEndBlocks()); + } + MortalList.flush(); + lexicalOwner.set(new RuntimeScalar()); + MyVarCleanupStack.unregister(lexicalOwner); + MortalList.flushAboveMark(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/EndBoundaryPackageCodeRootTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/EndBoundaryPackageCodeRootTest.java new file mode 100644 index 0000000000..6c7345f9e6 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/EndBoundaryPackageCodeRootTest.java @@ -0,0 +1,80 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class EndBoundaryPackageCodeRootTest { + @Test + void installedAnonymousClosureKeepsItsCapturedReferentRooted() { + assertInstalledCodeCaptureRoot( + "Issue1649AnonymousCodeSlot::installed", + "__ANON__", + "issue1649-anonymous-code-slot.pl"); + } + + @Test + void evalDefinedNamedClosureKeepsItsCapturedReferentRooted() { + assertInstalledCodeCaptureRoot( + "Issue1649EvalCodeSlot::installed", + "installed", + "(eval 1649)"); + } + + @Test + void codeCaptureOwnerUsesItsDirectSlotIdentity() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash capturedReferent = new RuntimeHash(); + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + PerlOwnerSlot capture = capturedReferent.retainClosureCaptureOwner(code); + code.capturedAggregates = new RuntimeBase[] {capturedReferent}; + code.capturedAggregateOwnerSlots = new PerlOwnerSlot[] {capture}; + + assertTrue(capture.isActive()); + assertTrue(capturedReferent.hasSemanticCaptureOwner()); + + code.releaseCaptures(); + + assertFalse(capture.isActive(), + "the CODE owner releases the captured aggregate's exact slot"); + assertFalse(capturedReferent.hasSemanticCaptureOwner()); + } + } + + private static void assertInstalledCodeCaptureRoot( + String slotName, String subName, String sourceFile) { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash capturedReferent = new RuntimeHash(); + RuntimeScalar capturedScalar = capturedReferent.createAnonymousReference(); + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + code.packageName = slotName.substring(0, slotName.lastIndexOf("::")); + code.subName = subName; + code.cvStartFile = sourceFile; + code.putClosedOverVariable("$captured", capturedScalar); + PerlOwnerSlot capture = capturedReferent.retainClosureCaptureOwner(code); + code.capturedAggregates = new RuntimeBase[] {capturedReferent}; + code.capturedAggregateOwnerSlots = new PerlOwnerSlot[] {capture}; + RuntimeScalar codeRef = new RuntimeScalar(code); + + GlobalVariable.globalCodeRefs.put(slotName, codeRef); + try { + RuntimeScalar installedCodeRef = GlobalVariable.globalCodeRefs.get(slotName); + assertTrue(installedCodeRef.refCountOwned, + "the installed package CODE slot owns its CV"); + assertTrue(capture.isActive(), + "the installed CV carries a direct capture owner slot"); + assertTrue(capturedReferent.hasSemanticCaptureOwner()); + assertTrue(DestroyDispatch.hasLivePerlOwnerIdentity(capturedReferent), + "the capture slot itself proves the current Perl owner"); + } finally { + GlobalVariable.globalCodeRefs.remove(slotName); + code.releaseCaptures(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/EscapedScalarCellFinalOwnerReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/EscapedScalarCellFinalOwnerReleaseTest.java new file mode 100644 index 0000000000..bbd98260f9 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/EscapedScalarCellFinalOwnerReleaseTest.java @@ -0,0 +1,68 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class EscapedScalarCellFinalOwnerReleaseTest { + @Test + void deferredCellCleanupRunsWhenItsLastOwnerLeaves() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + String className = "EscapedScalarCellFinalOwnerReleaseTest::Target"; + String destroyFqn = className + "::DESTROY"; + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId(className); + target.setTrackedRefCount(1); + + AtomicInteger destroyCalls = new AtomicInteger(); + RuntimeCode destroy = new RuntimeCode((args, context) -> { + destroyCalls.incrementAndGet(); + return new RuntimeList(); + }, null); + destroy.packageName = "EscapedScalarCellFinalOwnerReleaseTest"; + destroy.subName = "DESTROY"; + GlobalVariable.getGlobalCodeRef(destroyFqn).set(new RuntimeScalar(destroy)); + DestroyDispatch.registerIfDestroyable(target, target.blessId); + + RuntimeScalar cell = new RuntimeScalar(); + cell.type = RuntimeScalarType.HASHREFERENCE; + cell.value = target; + cell.refCountOwned = true; + target.recordActiveOwner(cell); + + RuntimeScalar weak = new RuntimeScalar(); + weak.type = RuntimeScalarType.HASHREFERENCE; + weak.value = target; + WeakRefRegistry.weaken(weak); + + // The wrapper's DESTROY cleanup sees its temporary self owner and + // must keep the escaped scalar cell's current value until that + // owner is released. + cell.referencedByScalarReference = true; + PerlOwnerSlot scalarCellOwner = new PerlOwnerSlot(PerlOwnerSlot.Kind.SCALAR_CELL); + scalarCellOwner.acquireNativeOwner(cell); + try { + RuntimeScalar.scopeExitCleanup(cell); + assertEquals(0, destroyCalls.get()); + assertTrue(WeakRefRegistry.isweak(weak), + "the observer remains weak while the scalar cell is owned"); + + scalarCellOwner.release(); + MortalList.flush(); + + assertEquals(1, destroyCalls.get(), "the nested object is destroyed once"); + assertEquals(RuntimeScalarType.UNDEF, weak.type, + "the nested object's weak observer clears with the final cell owner"); + } finally { + if (scalarCellOwner.isActive()) scalarCellOwner.release(); + GlobalVariable.globalCodeRefs.remove(destroyFqn); + DestroyDispatch.unregisterDestroyable(target); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ExternalRootSnapshotBudgetTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ExternalRootSnapshotBudgetTest.java deleted file mode 100644 index 7125170ca7..0000000000 --- a/src/test/java/org/perlonjava/runtime/runtimetypes/ExternalRootSnapshotBudgetTest.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.perlonjava.runtime.runtimetypes; - -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Tag("unit") -class ExternalRootSnapshotBudgetTest { - @Test - void oversizedTargetRootWalkStopsAndRetainsUnknownTargets() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeHash largeRoot = new RuntimeHash(); - for (int i = 0; i <= ReachabilityWalker.MAX_ROOT_SNAPSHOT_EDGES; i++) { - largeRoot.elements.put("edge-" + i, null); - } - RuntimeArray global = new RuntimeArray(); - global.elements.add(largeRoot.createReference()); - String globalName = "ExternalRootSnapshotBudgetTest::targetLargeRoot"; - GlobalVariable.globalArrays.put(globalName, global); - RuntimeArray unresolved = new RuntimeArray(); - - try { - ReachabilityQueryStats stats; - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - assertTrue(ReachabilityWalker.isReachableFromRoots(unresolved), - "an incomplete targeted walk cannot prove an object dead"); - stats = measurement.stats(); - } - - assertEquals(1, stats.rootQueries); - assertTrue(stats.edgesInspected <= ReachabilityWalker.MAX_ROOT_SNAPSHOT_EDGES, - "the targeted root walk stays within its edge budget"); - } finally { - GlobalVariable.globalArrays.remove(globalName); - MortalList.invalidateAllRootSnapshots(); - } - } - } - - @Test - void oversizedExternalRootWalkStopsAtEdgeBudgetAndRetainsUnknownTargets() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeHash largeRoot = new RuntimeHash(); - for (int i = 0; i <= ReachabilityWalker.MAX_ROOT_SNAPSHOT_EDGES; i++) { - largeRoot.elements.put("edge-" + i, null); - } - RuntimeArray global = new RuntimeArray(); - global.elements.add(largeRoot.createReference()); - String globalName = "ExternalRootSnapshotBudgetTest::largeRoot"; - GlobalVariable.globalArrays.put(globalName, global); - RuntimeArray unresolved = new RuntimeArray(); - - try { - ReachabilityWalker.ExternalRootSnapshot snapshot; - ReachabilityQueryStats stats; - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - snapshot = new ReachabilityWalker.ExternalRootSnapshot(false); - stats = measurement.stats(); - } - - assertEquals(ReachabilityWalker.MAX_ROOT_SNAPSHOT_EDGES, - stats.externalRootSnapshotEdgesInspected, - "the external-root walk stops inspecting edges at its cap"); - assertFalse(snapshot.complete(), - "a capped external-root walk cannot prove an object dead"); - assertTrue(snapshot.isReachable(unresolved), - "unknown targets remain protected when the root proof is incomplete"); - } finally { - GlobalVariable.globalArrays.remove(globalName); - MortalList.invalidateAllRootSnapshots(); - } - } - } -} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/FinalCodeOwnerCaptureReleaseFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/FinalCodeOwnerCaptureReleaseFastPathTest.java new file mode 100644 index 0000000000..a94c3fc9fc --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/FinalCodeOwnerCaptureReleaseFastPathTest.java @@ -0,0 +1,38 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; + +@Tag("unit") +class FinalCodeOwnerCaptureReleaseFastPathTest { + @Test + void finalScalarOwnerReleasesCapturesWithoutRootWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + closure.setTrackedRefCount(0); + RuntimeScalar capturedPad = new RuntimeScalar(); + PerlOwnerSlot captureSlot = capturedPad.retainClosureCaptureSlot(closure); + closure.capturedScalars = new RuntimeScalar[]{capturedPad}; + closure.capturedScalarOwnerSlots = new PerlOwnerSlot[]{captureSlot}; + + RuntimeScalar codeOwner = new RuntimeScalar(); + codeOwner.set(new RuntimeScalar(closure)); + assertEquals(1, closure.refCount); + + { + codeOwner.set(new RuntimeScalar()); + + assertNull(closure.capturedScalars, + "the final scalar owner releases the closure's captured pads"); + assertNull(closure.capturedScalarOwnerSlots); + assertEquals(0, capturedPad.captureCount); + assertFalse(captureSlot.isActive()); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/FinalOwnerReleaseWeakObserverTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/FinalOwnerReleaseWeakObserverTest.java new file mode 100644 index 0000000000..a32c4886df --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/FinalOwnerReleaseWeakObserverTest.java @@ -0,0 +1,26 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class FinalOwnerReleaseWeakObserverTest { + @Test + void finalStrongOwnerReleaseClearsWeakObserver() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeArray owner = new RuntimeArray(); + owner.addClonedElement(referent.createAnonymousReference()); + RuntimeScalar weak = referent.createAnonymousReference(); + WeakRefRegistry.weaken(weak); + MortalList.scopeExitCleanupArray(owner); + MortalList.flush(); + + assertEquals(RuntimeScalarType.UNDEF, weak.type, + "the final exact element-owner release clears the weak observer"); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/FirstWeakenKeepsRegisteredLexicalTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/FirstWeakenKeepsRegisteredLexicalTest.java new file mode 100644 index 0000000000..b24318937c --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/FirstWeakenKeepsRegisteredLexicalTest.java @@ -0,0 +1,32 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class FirstWeakenKeepsRegisteredLexicalTest { + @Test + void weakeningPreservesRegisteredLexicalState() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar weak = new RuntimeHash().createAnonymousReference(); + MyVarCleanupStack.register(weak); + try { + assertTrue(MyVarCleanupStack.isRegistered(weak)); + assertTrue(MyVarCleanupStack.isLive(weak)); + + WeakRefRegistry.weaken(weak); + + assertTrue(WeakRefRegistry.isweak(weak)); + assertTrue(MyVarCleanupStack.isRegistered(weak)); + assertTrue(MyVarCleanupStack.isLive(weak)); + } finally { + if (WeakRefRegistry.isweak(weak)) WeakRefRegistry.unweaken(weak); + MyVarCleanupStack.unregister(weak); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/FirstWeakenUsesCurrentPackageOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/FirstWeakenUsesCurrentPackageOwnerTest.java new file mode 100644 index 0000000000..ddbfa99412 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/FirstWeakenUsesCurrentPackageOwnerTest.java @@ -0,0 +1,55 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class FirstWeakenUsesCurrentPackageOwnerTest { + @Test + void weakeningLocalOwnerPreservesThePackageElementOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + String globalName = "FirstWeakenUsesCurrentPackageOwnerTest::root"; + RuntimeArray packageRoot = new RuntimeArray(); + RuntimeHash target = new RuntimeHash(); + GlobalVariable.globalArrays.put(globalName, packageRoot); + + RuntimeScalar packageElement = target.createAnonymousReference(); + packageRoot.addClonedElement(packageElement); + RuntimeScalar weakOwner = new RuntimeScalar(); + MyVarCleanupStack.register(weakOwner); + weakOwner.set(target.createAnonymousReference()); + + try { + assertEquals(2, target.countedOwnerSlotCount()); + assertEquals(2, target.refCount); + + { + WeakRefRegistry.weaken(weakOwner); + + assertTrue(WeakRefRegistry.isweak(weakOwner)); + assertEquals(1, target.refCount); + assertEquals(1, target.countedOwnerSlotCount()); + } + + RuntimeArray.pop(packageRoot); + MortalList.flush(); + assertFalse(WeakRefRegistry.isweak(weakOwner), + "the final package element release clears the weak observer"); + assertEquals(RuntimeScalarType.UNDEF, weakOwner.type); + } finally { + if (WeakRefRegistry.isweak(weakOwner)) WeakRefRegistry.unweaken(weakOwner); + MyVarCleanupStack.unregister(weakOwner); + if (!packageRoot.elements.isEmpty()) { + RuntimeArray.pop(packageRoot); + MortalList.flush(); + } + GlobalVariable.globalArrays.remove(globalName); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ForwardedArgumentAliasCurrentOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ForwardedArgumentAliasCurrentOwnerTest.java new file mode 100644 index 0000000000..8d417f277d --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ForwardedArgumentAliasCurrentOwnerTest.java @@ -0,0 +1,54 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ForwardedArgumentAliasCurrentOwnerTest { + @Test + void forwardedCellAliasPreservesItsCurrentCountedOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + RuntimeScalar argumentCell = new RuntimeScalar(); + argumentCell.set(target.createAnonymousReference()); + RuntimeArray outerArgs = new RuntimeArray(); + outerArgs.elementsAliased = true; + outerArgs.elements.add(argumentCell); + RuntimeCode.CallArguments staged = RuntimeCode.newCallArguments(1); + boolean outerArgsActive = false; + boolean innerArgsActive = false; + + try { + RuntimeCode.pushArgs(outerArgs); + outerArgsActive = true; + assertFalse(argumentCell.hasPersistentArgumentStorageCell(), + "the forwarded argument is not backed by a lexical or container marker"); + assertTrue(RuntimeCode.isCurrentArgumentAlias(argumentCell), + "the outer argument frame still aliases the scalar cell"); + + staged.add(argumentCell); + RuntimeArray innerArgs = staged.toRuntimeArray(); + RuntimeCode.pushArgs(innerArgs); + innerArgsActive = true; + + assertEquals(2, target.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS), + "the staged call and inner argument frame each own an alias identity"); + assertTrue(argumentCell.isCurrentCountedScalarOwner( + target, argumentCell.countedOwnerSlot()), + "a live forwarded alias makes its current scalar cell authoritative"); + assertEquals(1, target.refCount); + assertEquals(1, target.countedOwnerSlotCount()); + } finally { + if (innerArgsActive) RuntimeCode.popArgs(); + staged.finish(); + if (outerArgsActive) RuntimeCode.popArgs(); + argumentCell.set(new RuntimeScalar()); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/GlobalCodeRefMapWeakSourceOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/GlobalCodeRefMapWeakSourceOwnerTest.java new file mode 100644 index 0000000000..9419610d6e --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/GlobalCodeRefMapWeakSourceOwnerTest.java @@ -0,0 +1,66 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class GlobalCodeRefMapWeakSourceOwnerTest { + @Test + void stashSlotCopiesWeakCodeValueAndOwnsItsCountedEdge() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + GlobalVariable.resetAllGlobals(); + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + code.setTrackedRefCount(0); + + RuntimeScalar otherStrongOwner = new RuntimeScalar(code); + RuntimeScalar.incrementRefCountForContainerStore( + otherStrongOwner, PerlOwnerSlot.Kind.SCALAR_CELL); + RuntimeScalar weakSource = new RuntimeScalar(code); + WeakRefRegistry.weaken(weakSource); + String name = "GlobalCodeRefMapWeakSourceOwnerTest::target"; + + try { + int countBeforeStashStore = code.refCount; + GlobalVariable.globalCodeRefs.put(name, weakSource); + RuntimeScalar stashSlot = GlobalVariable.globalCodeRefs.get(name); + + assertNotSame(weakSource, stashSlot, + "the stash stores its own scalar slot, not the weak source cell"); + assertTrue(WeakRefRegistry.isweak(weakSource), + "storing into a glob does not strengthen the source scalar"); + assertFalse(WeakRefRegistry.isweak(stashSlot), + "the stash CODE slot is a strong Perl owner"); + assertTrue(stashSlot.refCountOwned); + assertSame(code, stashSlot.countedOwnerSlot().referent()); + assertEquals(countBeforeStashStore + 1, code.refCount, + "the stash slot acquires its own counted owner"); + + GlobalVariable.globalCodeRefs.remove(name); + assertEquals(countBeforeStashStore, code.refCount, + "removing the stash slot releases only its own count"); + assertTrue(WeakRefRegistry.isweak(weakSource)); + } finally { + GlobalVariable.globalCodeRefs.remove(name); + if (WeakRefRegistry.isweak(weakSource)) { + WeakRefRegistry.unweaken(weakSource); + } + if (weakSource.refCountOwned) { + MortalList.releaseCountedOwnerImmediately( + weakSource, "GlobalCodeRefMapWeakSourceOwnerTest weak cleanup"); + } + if (otherStrongOwner.refCountOwned) { + MortalList.releaseCountedOwnerImmediately( + otherStrongOwner, "GlobalCodeRefMapWeakSourceOwnerTest cleanup"); + } + GlobalVariable.resetAllGlobals(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/GlobalCodeSlotUndefOwnerTransitionTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/GlobalCodeSlotUndefOwnerTransitionTest.java new file mode 100644 index 0000000000..1f5556c29e --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/GlobalCodeSlotUndefOwnerTransitionTest.java @@ -0,0 +1,45 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class GlobalCodeSlotUndefOwnerTransitionTest { + @Test + void undefGlobalCodeSlotPublishesReplacementBeforeReleasingOldCode() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + GlobalVariable.resetAllGlobals(); + try { + String name = "GlobalCodeSlotUndefOwnerTransitionTest::target"; + RuntimeCode oldCode = new RuntimeCode((String) null, null); + oldCode.isConstantCv = true; + oldCode.lexicalSubDisplayName = true; + RuntimeScalar slot = new RuntimeScalar(oldCode); + GlobalVariable.globalCodeRefs.put(name, slot); + + assertTrue(slot.refCountOwned); + assertSame(oldCode, slot.countedOwnerSlot().referent()); + assertEquals(1, oldCode.refCount); + + slot.undefine(); + + RuntimeCode undefinedCode = (RuntimeCode) slot.value; + assertNotSame(oldCode, undefinedCode); + assertSame(slot, GlobalVariable.globalCodeRefs.get(name)); + assertSame(undefinedCode, slot.countedOwnerSlot().referent()); + assertEquals(1, undefinedCode.refCount); + assertEquals(1, undefinedCode.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + assertEquals(0, oldCode.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, oldCode.perlLifecycleState()); + assertEquals(0, oldCode.refCount); + } finally { + GlobalVariable.resetAllGlobals(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/GrowingLexicalOutputOwnerSlotCostTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/GrowingLexicalOutputOwnerSlotCostTest.java new file mode 100644 index 0000000000..22f1130994 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/GrowingLexicalOutputOwnerSlotCostTest.java @@ -0,0 +1,71 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class GrowingLexicalOutputOwnerSlotCostTest { + @Test + void nestedOutputCleanupDoesNotRescanTheGrowingLexicalRoot() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + final int resultCount = 256; + RuntimeArray output = new RuntimeArray(); + RuntimeArray[] records = new RuntimeArray[resultCount]; + RuntimeScalar[] weakLeaves = new RuntimeScalar[resultCount]; + MyVarCleanupStack.register(output); + + try { + for (int i = 0; i < resultCount; i++) { + RuntimeArray leaf = new RuntimeArray(); + RuntimeScalar leafOwner = leaf.createAnonymousReference(); + RuntimeScalar weakLeaf = leaf.createAnonymousReference(); + leaf.markRefCountUntracked(); + + RuntimeArray record = new RuntimeArray(); + record.elements.add(leafOwner); + RuntimeScalar recordOwner = record.createAnonymousReference(); + record.markRefCountUntracked(); + output.elements.add(recordOwner); + + WeakRefRegistry.weaken(weakLeaf); + records[i] = record; + weakLeaves[i] = weakLeaf; + } + + { + for (RuntimeArray record : records) { + // Model a recursive callback frame ending after its + // result has been appended to the live output array. + MortalList.scopeExitCleanupArray(record); + } + + assertEquals(resultCount, output.size()); + for (RuntimeScalar weakLeaf : weakLeaves) { + assertTrue(WeakRefRegistry.isweak(weakLeaf), + "a live output row keeps its nested aggregate alive"); + } + } + + for (int i = resultCount - 1; i >= 0; i--) { + RuntimeScalar rootOwner = output.elements.removeLast(); + rootOwner.undefine(); + MortalList.scopeExitCleanupArray(records[i]); + MortalList.flush(); + assertFalse(WeakRefRegistry.isweak(weakLeaves[i]), + "the nested weak observer clears after its final output owner leaves"); + } + } finally { + for (RuntimeScalar weakLeaf : weakLeaves) { + if (weakLeaf != null) WeakRefRegistry.unweaken(weakLeaf); + } + MyVarCleanupStack.unregister(output); + MortalList.scopeExitCleanupArray(output); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/HostSideHashOwnerReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/HostSideHashOwnerReleaseTest.java new file mode 100644 index 0000000000..78542a9c79 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/HostSideHashOwnerReleaseTest.java @@ -0,0 +1,38 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +@Tag("unit") +class HostSideHashOwnerReleaseTest { + @Test + void replacementRetiresTheDisplacedSlotAndItsCountTogether() { + assertNull(PerlRuntime.currentOrNull()); + + RuntimeHash hash = new RuntimeHash(); + RuntimeHash previous = new RuntimeHash(); + RuntimeHash replacement = new RuntimeHash(); + hash.put("value", previous.createAnonymousReference()); + RuntimeScalar previousCell = hash.elements.get("value"); + PerlOwnerSlot previousSlot = previousCell.countedOwnerSlot(); + + assertEquals(1, previous.refCount); + assertEquals(1, previous.countedOwnerSlotCount()); + + hash.put("value", replacement.createAnonymousReference()); + RuntimeScalar replacementCell = hash.elements.get("value"); + + assertEquals(0, previous.refCount); + assertEquals(0, previous.countedOwnerSlotCount()); + assertEquals(1, replacement.refCount); + assertEquals(1, replacement.countedOwnerSlotCount()); + assertSame(replacement, replacementCell.countedOwnerSlot().referent()); + assertEquals(PerlOwnerSlot.Kind.HASH_ELEMENT, + replacementCell.countedOwnerSlot().kind()); + assertNull(previousSlot.referent()); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/IoResourceLeaseIsNotPerlOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/IoResourceLeaseIsNotPerlOwnerTest.java new file mode 100644 index 0000000000..3f871f3ab5 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/IoResourceLeaseIsNotPerlOwnerTest.java @@ -0,0 +1,52 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.runtime.io.StandardIO; + +import java.io.ByteArrayOutputStream; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class IoResourceLeaseIsNotPerlOwnerTest { + private PerlRuntime.Binding runtimeBinding; + + @BeforeEach + void bindRuntime() { + runtimeBinding = new PerlRuntime().bind(); + } + + @AfterEach + void unbindRuntime() { + runtimeBinding.close(); + } + + @Test + void ioResourceLeaseDoesNotKeepPerlGlobAlive() { + RuntimeGlob glob = new RuntimeGlob(null).setIO(new RuntimeIO( + new StandardIO(new ByteArrayOutputStream(), true))); + RuntimeScalar handle = new RuntimeScalar(); + handle.type = RuntimeScalarType.GLOBREFERENCE; + handle.value = glob; + + RuntimeScalar.retainUnstashedIoForDurableSlot(handle); + + assertEquals(1, glob.ioHolderCount()); + assertFalse(glob.hasPerlStrongOwnerIdentity(), + "a resource lease must not stand in for a Perl reference"); + assertFalse(glob.hasPerlStrongOwner(), + "the runtime lease alone must not postpone Perl destruction"); + assertFalse(glob.hasOwnerSlots(), + "runtime resource slots must not masquerade as Perl owner slots"); + assertFalse(glob.hasUncountedPerlOwnerSlotIdentity(), + "the runtime lease must not be mistaken for an uncounted Perl edge"); + assertFalse(DestroyDispatch.hasCurrentPerlOwnerSlot(glob), + "a runtime resource lease must not be treated as destructor resurrection"); + + RuntimeScalar.releaseIoOwner(handle); + assertEquals(0, glob.ioHolderCount()); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/JavaOnlyScalarDoesNotOwnReferentTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/JavaOnlyScalarDoesNotOwnReferentTest.java new file mode 100644 index 0000000000..b3eb63382e --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/JavaOnlyScalarDoesNotOwnReferentTest.java @@ -0,0 +1,41 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +@Tag("unit") +class JavaOnlyScalarDoesNotOwnReferentTest { + @Test + void javaLiveScalarWithoutPerlOwnerDoesNotRescueZeroCountReferent() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + runtime.lifecycleState.weakRefsExist = true; + + RuntimeArray referent = new RuntimeArray(); + referent.setTrackedRefCount(1); + + // This wrapper remains Java-live in the test, but it has no Perl + // storage slot, lexical binding, or owner identity. + RuntimeScalar javaOnly = new RuntimeScalar(); + javaOnly.type = RuntimeScalarType.REFERENCE; + javaOnly.value = referent; + assertFalse(javaOnly.hasOwnerSlots()); + + RuntimeScalar observer = new RuntimeScalar(); + observer.type = RuntimeScalarType.REFERENCE; + observer.value = referent; + observer.refCountOwned = true; + WeakRefRegistry.weaken(observer); + + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState(), + "a Java-only scalar without a Perl owner cannot rescue the referent"); + assertEquals(0, referent.refCount); + assertEquals(RuntimeScalarType.UNDEF, observer.type, + "the last real owner release clears the weak observer immediately"); + assertFalse(WeakRefRegistry.hasWeakRefsTo(referent)); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/LegacyClosureAggregateReleaseOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/LegacyClosureAggregateReleaseOwnerTest.java new file mode 100644 index 0000000000..ff97c1d014 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/LegacyClosureAggregateReleaseOwnerTest.java @@ -0,0 +1,46 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class LegacyClosureAggregateReleaseOwnerTest { + @Test + void releasingLegacyCaptureDoesNotQueueAnotherOwnersCountedEdge() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray capturedPad = new RuntimeArray(); + capturedPad.blessId = NameNormalizer.getBlessId( + "Issue1649::LegacyClosureAggregateReleaseOwner"); + RuntimeScalar countedOwner = new RuntimeScalar(); + countedOwner.set(capturedPad.createReference()); + RuntimeScalar weakObserver = capturedPad.createAnonymousReference(); + WeakRefRegistry.weaken(weakObserver); + + capturedPad.retainClosureCapture(); + MortalList.scopeExitCleanupArray(capturedPad); + assertTrue(capturedPad.scopeExited, + "scope cleanup waits while the closure capture remains active"); + assertEquals(1, capturedPad.refCount, + "the scalar cell is the only counted owner"); + + try { + capturedPad.releaseClosureCapture(); + MortalList.flush(); + + assertEquals(1, capturedPad.refCount, + "releasing a capture must not decrement the scalar cell's edge"); + assertTrue(WeakRefRegistry.isweak(weakObserver), + "the remaining scalar cell keeps the weak referent alive"); + } finally { + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + countedOwner.set(new RuntimeScalar()); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/LegacyClosureCaptureOwnerReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/LegacyClosureCaptureOwnerReleaseTest.java new file mode 100644 index 0000000000..1c234e195a --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/LegacyClosureCaptureOwnerReleaseTest.java @@ -0,0 +1,69 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class LegacyClosureCaptureOwnerReleaseTest { + @Test + void finalReleaseWaitsForSemanticCaptureSlotWithoutFabricatingARefCount() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + String className = "LegacyCaptureOwnerRelease::Tracked"; + RuntimeHash referent = new RuntimeHash(); + referent.blessId = NameNormalizer.getBlessId(className); + referent.setTrackedRefCount(0); + installDestroy(className); + + RuntimeScalar pad = referenceTo(referent); + pad.refCountOwned = true; + pad.retainClosureCapture(); + assertEquals(1, referent.semanticCaptureOwnerCount()); + assertEquals(0, referent.nativeCaptureOwnerCount()); + + RuntimeScalar temporaryOwner = CountedOwnerFixture.temporaryReference(referent); + RuntimeScalar weak = referenceTo(referent); + WeakRefRegistry.weaken(weak); + + { + CountedOwnerFixture.queueRelease(temporaryOwner); + MortalList.flush(); + + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, referent.refCountTrackingState(), + "a live capture holds weak cleanup after the final counted slot leaves"); + assertTrue(referent.deferredFinalReleaseForUncountedOwners, + "final cleanup waits for that identity to leave"); + assertTrue(WeakRefRegistry.isweak(weak)); + + pad.releaseClosureCapture(); + + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + referent.perlLifecycleState()); + assertEquals(RuntimeScalarType.UNDEF, weak.type, + "the final owner release clears weak observers"); + assertFalse(referent.deferredFinalReleaseForUncountedOwners); + } + + GlobalVariable.removeGlobalCodeRefForStashDelete(className + "::DESTROY"); + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.HASHREFERENCE; + scalar.value = referent; + return scalar; + } + + private static void installDestroy(String className) { + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + int separator = className.lastIndexOf("::"); + code.packageName = className.substring(0, separator); + code.subName = "DESTROY"; + GlobalVariable.getGlobalCodeRef(className + "::DESTROY").set(new RuntimeScalar(code)); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/LegacyUnpairedUncountedOwnerSlotFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/LegacyUnpairedUncountedOwnerSlotFastPathTest.java new file mode 100644 index 0000000000..c3aae471a5 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/LegacyUnpairedUncountedOwnerSlotFastPathTest.java @@ -0,0 +1,68 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class LegacyUnpairedUncountedOwnerSlotFastPathTest { + @Test + void currentUncountedOwnerDefersWeakCleanupWithoutRootRecovery() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + MortalList.setActive(true); + RuntimeArray target = new RuntimeArray(); + target.markRefCountUntracked(); + RuntimeArray lexicalOwner = new RuntimeArray(); + RuntimeScalar strongOwner = referenceTo(target); + lexicalOwner.elements.add(strongOwner); + RuntimeScalar weakObserver = referenceTo(target); + int lexicalMark = MyVarCleanupStack.pushMark(); + try { + MyVarCleanupStack.register(lexicalOwner); + PerlOwnerSlot strongOwnerSlot = strongOwner.untrackedReferenceOwnerSlot(); + assertTrue(strongOwnerSlot != null && strongOwnerSlot.isActive()); + target.setTrackedRefCount(1); + weakObserver.refCountOwned = true; + WeakRefRegistry.weaken(weakObserver); + + assertTrue(strongOwnerSlot.isActive()); + assertTrue(target.hasCurrentUncountedPerlOwnerSlotIdentity()); + { + assertTrue(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState(), + "weak tracking preserves the current uncounted Perl owner"); + } + + strongOwner.set(new RuntimeScalar()); + + assertFalse(strongOwnerSlot.isActive()); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the final exact owner release clears the weak observer"); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + target.perlLifecycleState()); + } finally { + if (strongOwner.value == target) strongOwner.undefine(); + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + RuntimeScalar.scopeExitCleanup(strongOwner); + MyVarCleanupStack.unregister(lexicalOwner); + MyVarCleanupStack.popMark(lexicalMark); + MortalList.setActive(previousMortalListState); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.ARRAYREFERENCE; + scalar.value = referent; + return scalar; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/LiveAggregateValueOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/LiveAggregateValueOwnerSlotTest.java new file mode 100644 index 0000000000..a82a5586c3 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/LiveAggregateValueOwnerSlotTest.java @@ -0,0 +1,63 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class LiveAggregateValueOwnerSlotTest { + @Test + void borrowedCellInLiveAggregateRetainsTrackedReferentUntilSlotLeaves() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + int lexicalMark = MyVarCleanupStack.pushMark(); + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar countedOwner = new RuntimeScalar(); + countedOwner.set(referent.createAnonymousReference()); + + RuntimeArray ownerContainer = new RuntimeArray(); + MyVarCleanupStack.register(ownerContainer); + RuntimeScalar uncountedOwner = referent.createAnonymousReference(); + ownerContainer.elements.add(uncountedOwner); + PerlOwnerSlot valueOwner = uncountedOwner.untrackedReferenceOwnerSlot(); + + RuntimeScalar weakObserver = referent.createAnonymousReference(); + WeakRefRegistry.weaken(weakObserver); + try { + assertNotNull(valueOwner, + "the live aggregate cell owns its uncounted value edge"); + assertEquals(1, + referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + countedOwner.set(new RuntimeScalar()); + + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, referent.refCountTrackingState()); + assertTrue(WeakRefRegistry.isweak(weakObserver), + "the aggregate cell keeps the weakly observed referent alive"); + + uncountedOwner.set(new RuntimeScalar()); + + assertFalse(valueOwner.isActive(), "the value owner leaves exactly once"); + assertEquals(0, + referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the final owner release clears weak observers"); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState()); + assertEquals(0, referent.refCount); + } finally { + if (valueOwner != null && valueOwner.isActive()) { + uncountedOwner.set(new RuntimeScalar()); + } + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + countedOwner.set(new RuntimeScalar()); + MyVarCleanupStack.popMark(lexicalMark); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/LocalizedGlobCodeOwnerReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/LocalizedGlobCodeOwnerReleaseTest.java new file mode 100644 index 0000000000..7bfd44e010 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/LocalizedGlobCodeOwnerReleaseTest.java @@ -0,0 +1,59 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +@Tag("unit") +class LocalizedGlobCodeOwnerReleaseTest { + @Test + void unownedLocalizedCodeReleasesCapture() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + String name = "LocalizedGlobCodeOwnerReleaseTest::sub"; + RuntimeCode original = code(); + original.stashRefCount = 1; + GlobalVariable.globalCodeRefs.put(name, new RuntimeScalar(original)); + + RuntimeGlob glob = new RuntimeGlob(name); + RuntimeCode localized = code(); + localized.setTrackedRefCount(2); + localized.stashRefCount = 1; + RuntimeScalar capturedPad = new RuntimeScalar(42); + localized.capturedScalars = new RuntimeScalar[] {capturedPad}; + localized.capturedScalarOwnerSlots = new PerlOwnerSlot[] { + capturedPad.retainClosureCaptureSlot(localized) + }; + localized.captureFieldsRecorded = true; + + glob.dynamicSaveState(); + RuntimeScalar localizedSlot = GlobalVariable.globalCodeRefs.get(name); + // Reproduce a legacy direct stash write that has no CODE-slot edge. + localizedSlot.type = RuntimeScalarType.CODE; + localizedSlot.value = localized; + localizedSlot.globalCodeRefFqn = name; + + try { + { + glob.dynamicRestoreState(); + + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + localized.perlLifecycleState()); + assertNull(localized.capturedScalars); + assertEquals(0, capturedPad.captureCount); + } + } finally { + GlobalVariable.globalCodeRefs.remove(name); + if (localized.perlLifecycleState() != RuntimeBase.PerlLifecycleState.DESTROYED) { + localized.setTrackedRefCount(0); + DestroyDispatch.callDestroy(localized); + } + } + } + } + + private static RuntimeCode code() { + return new RuntimeCode((args, context) -> new RuntimeList(), null); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/LocalizedGlobCodeOwnerSlotFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/LocalizedGlobCodeOwnerSlotFastPathTest.java new file mode 100644 index 0000000000..a9843d953b --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/LocalizedGlobCodeOwnerSlotFastPathTest.java @@ -0,0 +1,59 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@Tag("unit") +class LocalizedGlobCodeOwnerSlotFastPathTest { + @Test + void activeCallOwnerPreservesCaptureOnGlobRestore() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + String name = "LocalizedGlobCodeOwnerSlotFastPath::sub"; + RuntimeCode original = code(); + original.stashRefCount = 1; + GlobalVariable.globalCodeRefs.put(name, new RuntimeScalar(original)); + + RuntimeGlob glob = new RuntimeGlob(name); + RuntimeCode localized = code(); + localized.setTrackedRefCount(2); + localized.stashRefCount = 1; + localized.capturedScalars = new RuntimeScalar[] {new RuntimeScalar(42)}; + + glob.dynamicSaveState(); + // Exercise the legacy stash path: the localized slot already has + // a CODE-slot binding while still undef. Bypass set() just as old + // direct stash writes did, so the CV has not opted into counted + // CODE-slot ownership yet. + RuntimeScalar localizedSlot = GlobalVariable.globalCodeRefs.get(name); + localizedSlot.type = RuntimeScalarType.CODE; + localizedSlot.value = localized; + localizedSlot.globalCodeRefFqn = name; + RuntimeCode.pushActiveCode(localized); + try { + { + glob.dynamicRestoreState(); + + assertEquals(0, localized.activeOwnerCount()); + assertEquals(1, localized.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_CODE)); + assertEquals(1, localized.refCount, + "restoring the glob retires only the localized stash owner"); + assertNotNull(localized.capturedScalars, + "the active call keeps its captured pad alive"); + } + } finally { + RuntimeCode.popActiveCode(localized); + GlobalVariable.globalCodeRefs.remove(name); + localized.setTrackedRefCount(0); + DestroyDispatch.callDestroy(localized); + } + } + } + + private static RuntimeCode code() { + return new RuntimeCode((args, context) -> new RuntimeList(), null); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/LocalizedHashMissingKeyOwnerReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/LocalizedHashMissingKeyOwnerReleaseTest.java new file mode 100644 index 0000000000..1eb0398b01 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/LocalizedHashMissingKeyOwnerReleaseTest.java @@ -0,0 +1,56 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class LocalizedHashMissingKeyOwnerReleaseTest { + @Test + void restoringAnAbsentHashKeyRetiresItsCountedSlotExactlyOnce() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousActive = MortalList.isActive(); + MortalList.setActive(true); + + RuntimeArray referent = new RuntimeArray(); + referent.setTrackedRefCount(0); + RuntimeScalar externalOwner = new RuntimeScalar(); + RuntimeHash parent = new RuntimeHash(); + RuntimeHashProxyEntry proxy = new RuntimeHashProxyEntry(parent, "temporary"); + + try { + externalOwner.set(referent.createAnonymousReference()); + proxy.dynamicSaveState(); + proxy.set(referent.createAnonymousReference()); + + RuntimeScalar localizedCell = parent.elements.get("temporary"); + assertNotNull(localizedCell); + assertTrue(localizedCell.refCountOwned); + PerlOwnerSlot localizedOwner = localizedCell.countedOwnerSlot(); + assertNotNull(localizedOwner); + assertEquals(PerlOwnerSlot.Kind.HASH_ELEMENT, localizedOwner.kind()); + assertEquals(2, referent.refCount); + + proxy.dynamicRestoreState(); + + assertFalse(parent.elements.containsKey("temporary")); + assertFalse(localizedCell.refCountOwned, + "removing the localized key retires the removed value cell's edge"); + assertFalse(localizedOwner.isActive(), + "the removed HASH_ELEMENT identity cannot outlive its storage slot"); + assertEquals(1, referent.refCount, + "only the external scalar cell still owns the referent"); + } finally { + if (parent.elements.containsKey("temporary")) proxy.dynamicRestoreState(); + externalOwner.undefine(); + MortalList.flush(); + MortalList.setActive(previousActive); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/MethodInvocantOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/MethodInvocantOwnerSlotTest.java new file mode 100644 index 0000000000..1a12f879cd --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/MethodInvocantOwnerSlotTest.java @@ -0,0 +1,33 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class MethodInvocantOwnerSlotTest { + @Test + void directMethodHoldAddsAndReleasesOneCountedOwner() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId("Issue1649::MethodOwnerRepair"); + RuntimeScalar source = new RuntimeScalar(); + source.set(target.createAnonymousReference()); + RuntimeBase hold = RuntimeCode.acquireMethodInvocantHold(source); + + assertEquals(2, target.refCount, + "the scalar cell and direct method hold each add one owner count"); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertTrue(target.ownerSlotSnapshot().stream() + .filter(slot -> slot.kind() == PerlOwnerSlot.Kind.ARGUMENT_VALUE) + .anyMatch(slot -> slot.isMethodInvocantOwner(target))); + + RuntimeCode.releaseAbandonedMethodInvocantHold(hold); + assertEquals(1, target.refCount, + "releasing the direct method hold retires only its own count"); + source.set(RuntimeScalarCache.scalarUndef); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/MethodInvocantOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/MethodInvocantOwnerTest.java new file mode 100644 index 0000000000..add4ad3698 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/MethodInvocantOwnerTest.java @@ -0,0 +1,90 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class MethodInvocantOwnerTest { + private static RuntimeHash invocant() { + RuntimeHash value = new RuntimeHash(); + value.setTrackedRefCount(0); + value.blessId = NameNormalizer.getBlessId("Issue1649::MethodOwner"); + return value; + } + + @Test + void eachCallAcquiresItsOwnArgumentIdentityAndRetiresItOnce() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash value = invocant(); + RuntimeScalar source = new RuntimeScalar(); + source.set(value.createAnonymousReference()); + RuntimeBase first = RuntimeCode.acquireMethodInvocantHold(source); + RuntimeBase second = RuntimeCode.acquireMethodInvocantHold(source); + assertNotSame(first, second); + assertEquals(2, value.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(2, value.ownerSlotSnapshot().stream() + .filter(slot -> slot.kind() == PerlOwnerSlot.Kind.ARGUMENT_VALUE) + .map(PerlOwnerSlot::identity).distinct().count()); + assertEquals(3, value.refCount); + RuntimeCode.releaseMethodInvocantHold(first); + RuntimeCode.releaseMethodInvocantHold(first); + assertEquals(2, value.refCount); + RuntimeCode.releaseAbandonedMethodInvocantHold(second); + RuntimeCode.releaseAbandonedMethodInvocantHold(second); + assertEquals(1, value.refCount); + assertEquals(0, value.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(0, runtime.positiveOwnerSlotReferentCount(value)); + } + } + + @Test + void finalNormalHoldCarriesItsIdentityUntilTheReceivingBoundaryDrains() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash value = invocant(); + RuntimeScalar source = new RuntimeScalar(); + source.set(value.createAnonymousReference()); + RuntimeScalar weak = new RuntimeScalar(); + weak.set(source); + WeakRefRegistry.weaken(weak); + RuntimeBase hold = RuntimeCode.acquireMethodInvocantHold(source); + source.set(RuntimeScalarCache.scalarUndef); + { + RuntimeCode.releaseMethodInvocantHold(hold); + RuntimeCode.releaseMethodInvocantHold(hold); + assertEquals(RuntimeScalarType.HASHREFERENCE, weak.type); + assertEquals(0, value.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(1, runtime.positiveOwnerSlotReferentCount(value)); + MortalList.flush(); + assertEquals(RuntimeScalarType.UNDEF, weak.type); + assertEquals(0, runtime.positiveOwnerSlotReferentCount(value)); + } + } + } + + @Test + void abandonedFinalHoldReleasesImmediately() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash value = invocant(); + RuntimeScalar source = new RuntimeScalar(); + source.set(value.createAnonymousReference()); + RuntimeScalar weak = new RuntimeScalar(); + weak.set(source); + WeakRefRegistry.weaken(weak); + RuntimeBase hold = RuntimeCode.acquireMethodInvocantHold(source); + source.set(RuntimeScalarCache.scalarUndef); + { + RuntimeCode.releaseAbandonedMethodInvocantHold(hold); + RuntimeCode.releaseAbandonedMethodInvocantHold(hold); + assertEquals(RuntimeScalarType.UNDEF, weak.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, value.perlLifecycleState()); + assertFalse(value.hasOwnerSlots()); + assertEquals(0, runtime.positiveOwnerSlotReferentCount(value)); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/MortalListTransientRhsFrameTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/MortalListTransientRhsFrameTest.java new file mode 100644 index 0000000000..b810af01b7 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/MortalListTransientRhsFrameTest.java @@ -0,0 +1,148 @@ +package org.perlonjava.runtime.runtimetypes; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class MortalListTransientRhsFrameTest { + @Test + void returnedRhsIsHeldForCallerAndDrainedInLifoOrder() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + List released = new ArrayList<>(); + RuntimeCode caller = code(); + RuntimeCode callee = code(); + RuntimeCode.pushActiveCode(caller); + RuntimeCode.pushActiveCode(callee); + + RuntimeArray first = transientRhs("first", released); + RuntimeArray second = transientRhs("second", released); + MortalList.deferTransientListAssignmentRhs(first); + MortalList.deferTransientListAssignmentRhs(second); + + MortalList.flushStatementBoundary(); + assertTrue(first.transientListAssignmentRhs, + "a callee boundary must not retire the caller's returned-list copies"); + assertTrue(second.transientListAssignmentRhs, + "the second returned-list copy must also reach the caller"); + assertTrue(released.isEmpty(), "no cells are released while the callee is active"); + + RuntimeCode.popActiveCode(callee); + MortalList.flushStatementBoundary(); + + assertEquals(List.of("second", "first"), released, + "the caller drains returned-list copies in LIFO order"); + assertTrue(first.elements.isEmpty()); + assertTrue(second.elements.isEmpty()); + RuntimeCode.popActiveCode(caller); + } + } + + @Test + void pendingCallerBucketHandsOffWhenThatFrameReturnsBeforeItsBoundary() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + List released = new ArrayList<>(); + RuntimeCode outer = code(); + RuntimeCode middle = code(); + RuntimeCode inner = code(); + RuntimeCode.pushActiveCode(outer); + RuntimeCode.pushActiveCode(middle); + RuntimeCode.pushActiveCode(inner); + + RuntimeArray rhs = transientRhs("nested", released); + MortalList.deferTransientListAssignmentRhs(rhs); + RuntimeCode.popActiveCode(inner); + RuntimeCode.popActiveCode(middle); + + assertTrue(rhs.transientListAssignmentRhs, + "the middle frame's returned value remains held during handoff"); + MortalList.flushStatementBoundary(); + + assertEquals(List.of("nested"), released, + "the outer frame releases a handoff after its next statement"); + RuntimeCode.popActiveCode(outer); + } + } + + @Test + void appendBufferPreservesAscendingBoundaryGroupsAndLifoWithinEachGroup() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + List released = new ArrayList<>(); + RuntimeCode caller = code(); + RuntimeCode callee = code(); + RuntimeCode.pushActiveCode(caller); + RuntimeCode.pushActiveCode(callee); + + RuntimeArray first = transientRhs("first", released); + RuntimeArray second = transientRhs("second", released); + RuntimeArray third = transientRhs("third", released); + RuntimeArray fourth = transientRhs("fourth", released); + MortalList.deferTransientListAssignmentRhs(first); + MortalList.deferTransientListAssignmentRhs(second); + + MortalList.flushStatementBoundary(); + MortalList.deferTransientListAssignmentRhs(third); + MortalList.deferTransientListAssignmentRhs(fourth); + RuntimeCode.popActiveCode(callee); + MortalList.flushStatementBoundary(); + + assertEquals(List.of("fourth", "third", "second", "first"), released, + "newer boundaries drain first, with LIFO order inside each boundary"); + RuntimeCode.popActiveCode(caller); + } + } + + @Test + void outOfOrderBoundaryFallsBackToOrderedQueue() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + List released = new ArrayList<>(); + LifecycleRuntimeState.TransientListAssignmentQueue queue = + new LifecycleRuntimeState.TransientListAssignmentQueue(); + queue.append(transientRhs("later", released), 1, 2); + queue.append(transientRhs("earlier", released), 2, 1); + + queue.drainAtBoundary(2); + + assertEquals(List.of("later", "earlier"), released, + "an out-of-order boundary must preserve the ordered-map behavior"); + assertTrue(queue.isEmpty()); + } + } + + private static RuntimeCode code() { + return new RuntimeCode((args, context) -> new RuntimeScalar().getList(), null); + } + + private static RuntimeArray transientRhs(String label, List released) { + RuntimeArray array = new RuntimeArray(); + array.transientListAssignmentRhs = true; + RecordingScalar cell = new RecordingScalar(label, released); + cell.markContainerOwner(array); + array.elements.add(cell); + return array; + } + + private static final class RecordingScalar extends RuntimeScalar { + private final String label; + private final List released; + + RecordingScalar(String label, List released) { + this.label = label; + this.released = released; + } + + @Override + void releaseContainerOwner(RuntimeBase expectedOwner) { + released.add(label); + super.releaseContainerOwner(expectedOwner); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/MortalReturnUntrackedOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/MortalReturnUntrackedOwnerTest.java new file mode 100644 index 0000000000..edd6914b0c --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/MortalReturnUntrackedOwnerTest.java @@ -0,0 +1,96 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class MortalReturnUntrackedOwnerTest { + @Test + void untrackedReturnOwnerLivesThroughNestedMortalBoundaryAndReleasesOnce() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar target = new RuntimeScalar("return target"); + RuntimeScalar source = referenceTo(target); + + MortalList.pushMark(); + RuntimeScalar returned = RuntimeScalar.copyToMortalReturnSlot(source); + PerlOwnerSlot returnOwner = returned.untrackedReferenceOwnerSlot(); + assertNotNull(returnOwner); + assertSame(target, returnOwner.referent()); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, target.refCountTrackingState(), + "return ownership must not promote an untracked referent"); + + MortalList.pushMark(); + MortalList.popAndFlush(); + assertTrue(returnOwner.isActive(), + "an inner frame must not release its caller's return value"); + + MortalList.popAndFlush(); + assertFalse(returnOwner.isActive()); + assertEquals(0, target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, target.refCountTrackingState(), + "releasing a return identity must leave the legacy count unchanged"); + } + } + + @Test + void weaklyTrackedReturnOwnerClearsObserverAfterLastScalarCellLeaves() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar target = new RuntimeScalar("weakly tracked return target"); + RuntimeScalar source = new RuntimeScalar(); + RuntimeScalar weakObserver = referenceTo(target); + int lexicalMark = MyVarCleanupStack.pushMark(); + MyVarCleanupStack.register(source); + source.set(referenceTo(target)); + WeakRefRegistry.weaken(weakObserver); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState()); + + try { + MortalList.pushMark(); + RuntimeScalar returned = RuntimeScalar.copyToMortalReturnSlot(source); + PerlOwnerSlot returnOwner = returned.untrackedReferenceOwnerSlot(); + assertNotNull(returnOwner); + assertEquals(2, + target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + { + MortalList.popAndFlush(); + assertFalse(returnOwner.isActive()); + assertEquals(1, + target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertTrue(WeakRefRegistry.isweak(weakObserver), + "the source lexical still owns the referent"); + + RuntimeScalar.scopeExitCleanup(source); + MyVarCleanupStack.unregister(source); + assertEquals(0, + target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + } + } finally { + RuntimeScalar.scopeExitCleanup(source); + MyVarCleanupStack.unregister(source); + MyVarCleanupStack.popMark(lexicalMark); + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase value) { + RuntimeScalar reference = new RuntimeScalar(); + reference.type = RuntimeScalarType.REFERENCE; + reference.value = value; + return reference; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/MortalizeRegisteredCodeOwnerFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/MortalizeRegisteredCodeOwnerFastPathTest.java new file mode 100644 index 0000000000..963dc0f1b0 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/MortalizeRegisteredCodeOwnerFastPathTest.java @@ -0,0 +1,45 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class MortalizeRegisteredCodeOwnerFastPathTest { + @Test + void registeredContainerOwnerKeepsCodeAlive() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + int lexicalMark = MyVarCleanupStack.pushMark(); + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + String codeSlotName = "MortalizeRegisteredCodeOwnerFastPath::code"; + RuntimeScalar owner = new RuntimeScalar(code); + GlobalVariable.globalCodeRefs.put(codeSlotName, owner); + RuntimeArray registeredContainer = new RuntimeArray(); + registeredContainer.elements.add(owner); + MyVarCleanupStack.register(registeredContainer); + RuntimeList discardedResult = new RuntimeList(); + discardedResult.elements.add(owner); + + try { + { + MortalList.mortalizeForVoidDiscard(discardedResult); + + assertTrue(owner.refCountOwned, + "the registered container still owns its CODE scalar slot"); + assertEquals(1, code.refCount); + assertTrue(runtime.lifecycleState.pendingOwnerReleases.isEmpty()); + } + } finally { + registeredContainer.elements.remove(owner); + owner.releaseContainerOwner(registeredContainer); + MyVarCleanupStack.unregister(registeredContainer); + GlobalVariable.globalCodeRefs.remove(codeSlotName); + MyVarCleanupStack.popMark(lexicalMark); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/NamedCodeReferenceInstallsCountedSlotOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/NamedCodeReferenceInstallsCountedSlotOwnerTest.java new file mode 100644 index 0000000000..42e14683aa --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/NamedCodeReferenceInstallsCountedSlotOwnerTest.java @@ -0,0 +1,64 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class NamedCodeReferenceInstallsCountedSlotOwnerTest { + @Test + void undefinedBoundStashSlotAcquiresOwnerWhenNamedReferenceVivifiesCode() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + GlobalVariable.resetAllGlobals(); + String name = "NamedCodeReferenceInstallsCountedSlotOwnerTest::target"; + RuntimeCode original = new RuntimeCode((args, context) -> new RuntimeList(), null); + GlobalVariable.globalCodeRefs.put(name, new RuntimeScalar(original)); + RuntimeGlob glob = new RuntimeGlob(name); + boolean localized = false; + + try { + glob.dynamicSaveState(); + localized = true; + RuntimeScalar slot = GlobalVariable.globalCodeRefs.get(name); + assertTrue(slot.hasCodeSlotBinding(), "the stash owns the empty CODE slot"); + RuntimeScalar resolved = GlobalVariable.getGlobalCodeRefForNamedReference(name); + RuntimeCode code = (RuntimeCode) resolved.value; + PerlOwnerSlot ownerSlot = resolved.countedOwnerSlot(); + + assertSame(slot, resolved); + assertEquals(name, resolved.globalCodeRefFqn); + assertTrue(resolved.refCountOwned, + "vivifying the value must acquire through the bound scalar slot"); + assertNotNull(ownerSlot); + assertEquals(PerlOwnerSlot.Kind.CODE_SLOT, + ownerSlot.kind()); + assertSame(resolved, ownerSlot.countedScalarOwner()); + assertSame(code, ownerSlot.referent()); + assertEquals(1, code.refCount); + assertTrue(code.hasCountedCodeSlots); + + localized = false; + glob.dynamicRestoreState(); + + assertSame(original, GlobalVariable.globalCodeRefs.get(name).value); + assertFalse(resolved.refCountOwned, + "restore retires the exact localized CODE-slot token"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + code.perlLifecycleState(), + "the now ownerless forward CV is destroyed on local restore"); + } finally { + if (localized) { + glob.dynamicRestoreState(); + } + GlobalVariable.globalCodeRefs.remove(name); + GlobalVariable.resetAllGlobals(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/NamespaceAliasOwnerTransferTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/NamespaceAliasOwnerTransferTest.java new file mode 100644 index 0000000000..6acfeb2314 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/NamespaceAliasOwnerTransferTest.java @@ -0,0 +1,79 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +@Tag("unit") +class NamespaceAliasOwnerTransferTest { + @Test + void packageRootIdentitiesFollowMovedNamespaceSlots() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + String sourcePrefix = "NamespaceAliasOwnerTransferTest::Source::"; + String aliasPrefix = "NamespaceAliasOwnerTransferTest::Copy::"; + String replacementPrefix = "NamespaceAliasOwnerTransferTest::Other::"; + String scalarSource = sourcePrefix + "scalar"; + String arraySource = sourcePrefix + "array"; + String hashSource = sourcePrefix + "hash"; + String scalarAlias = aliasPrefix + "scalar"; + String arrayAlias = aliasPrefix + "array"; + String hashAlias = aliasPrefix + "hash"; + + RuntimeScalar scalar = new RuntimeScalar("value"); + RuntimeArray array = new RuntimeArray(); + RuntimeHash hash = new RuntimeHash(); + PerlOwnerSlot scalarOwner; + PerlOwnerSlot arrayOwner; + PerlOwnerSlot hashOwner; + + try { + GlobalVariable.globalVariables.put(scalarSource, scalar); + GlobalVariable.globalArrays.put(arraySource, array); + GlobalVariable.globalHashes.put(hashSource, hash); + scalarOwner = runtime.globalState.packageScalarOwnerSlots().get(scalarSource); + arrayOwner = runtime.globalState.packageArrayOwnerSlots().get(arraySource); + hashOwner = runtime.globalState.packageHashOwnerSlots().get(hashSource); + assertNotNull(scalarOwner); + assertNotNull(arrayOwner); + assertNotNull(hashOwner); + + GlobalVariable.setStashAlias(aliasPrefix, sourcePrefix); + GlobalVariable.setStashAlias(sourcePrefix, replacementPrefix); + + assertSame(scalar, GlobalVariable.globalVariables.get(scalarAlias)); + assertSame(array, GlobalVariable.globalArrays.get(arrayAlias)); + assertSame(hash, GlobalVariable.globalHashes.get(hashAlias)); + assertSame(scalarOwner, + runtime.globalState.packageScalarOwnerSlots().get(scalarAlias)); + assertSame(arrayOwner, + runtime.globalState.packageArrayOwnerSlots().get(arrayAlias)); + assertSame(hashOwner, + runtime.globalState.packageHashOwnerSlots().get(hashAlias)); + assertEquals(0, scalar.ownerSlotCount(PerlOwnerSlot.Kind.GLOB_COMPONENT_SLOT)); + assertEquals(0, array.ownerSlotCount(PerlOwnerSlot.Kind.GLOB_COMPONENT_SLOT)); + assertEquals(0, hash.ownerSlotCount(PerlOwnerSlot.Kind.GLOB_COMPONENT_SLOT)); + + GlobalVariable.globalVariables.remove(scalarAlias); + GlobalVariable.globalArrays.remove(arrayAlias); + GlobalVariable.globalHashes.remove(hashAlias); + assertFalse(scalarOwner.isActive()); + assertFalse(arrayOwner.isActive()); + assertFalse(hashOwner.isActive()); + } finally { + GlobalVariable.globalVariables.remove(scalarSource); + GlobalVariable.globalVariables.remove(scalarAlias); + GlobalVariable.globalArrays.remove(arraySource); + GlobalVariable.globalArrays.remove(arrayAlias); + GlobalVariable.globalHashes.remove(hashSource); + GlobalVariable.globalHashes.remove(hashAlias); + GlobalVariable.clearStashAlias(sourcePrefix); + GlobalVariable.clearStashAlias(aliasPrefix); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/NestedUntrackedOwnerFinalCellCleanupTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/NestedUntrackedOwnerFinalCellCleanupTest.java new file mode 100644 index 0000000000..ed63e7a4d8 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/NestedUntrackedOwnerFinalCellCleanupTest.java @@ -0,0 +1,82 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class NestedUntrackedOwnerFinalCellCleanupTest { + @Test + void finalCellCleanupReleasesItsSlotWhileAnotherCountedOwnerKeepsReferentAlive() { + PerlRuntime runtime = new PerlRuntime(); + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar countedOwner = new RuntimeScalar(); + RuntimeScalar weakObserver = null; + RuntimeArray packageRoot = new RuntimeArray(); + String globalName = + "NestedUntrackedOwnerFinalCellCleanupTest::packageRoot"; + + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + MortalList.setActive(true); + try { + countedOwner.set(referent.createAnonymousReference()); + weakObserver = referent.createAnonymousReference(); + WeakRefRegistry.weaken(weakObserver); + assertEquals(1, referent.refCount, + "the counted scalar is an independent live owner"); + + GlobalVariable.globalArrays.put(globalName, packageRoot); + RuntimeScalar nestedCell = referenceTo(referent); + packageRoot.elements.add(nestedCell); + nestedCell.markContainerOwner(packageRoot); + nestedCell.markPrepopulatedPackageAggregateOwner(packageRoot); + nestedCell.refreshUntrackedReferenceOwner(); + + PerlOwnerSlot nestedOwner = nestedCell.untrackedReferenceOwnerSlot(); + assertTrue(nestedOwner != null && nestedOwner.isActive()); + assertEquals(1, referent.ownerSlotCount( + PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + { + GlobalVariable.globalArrays.remove(globalName); + MortalList.scopeExitCleanupArray(packageRoot); + + assertFalse(nestedOwner.isActive(), + "final cell cleanup retires this exact nested edge"); + assertEquals(0, referent.ownerSlotCount( + PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertEquals(1, referent.refCount, + "releasing the nested edge must preserve the separate counted owner"); + assertEquals(1, referent.countedOwnerSlotCount()); + assertTrue(WeakRefRegistry.isweak(weakObserver), + "the remaining counted owner keeps the weak observer live"); + } + + countedOwner.undefine(); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the final counted owner clears the observer when it leaves"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState()); + assertEquals(0, referent.refCount); + } finally { + if (weakObserver != null && WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + GlobalVariable.globalArrays.remove(globalName); + MortalList.scopeExitCleanupArray(packageRoot); + countedOwner.undefine(); + MortalList.setActive(previousMortalListState); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.HASHREFERENCE; + scalar.value = referent; + return scalar; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/OwnerSlotCandidateFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/OwnerSlotCandidateFastPathTest.java new file mode 100644 index 0000000000..ed5ce8cef3 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/OwnerSlotCandidateFastPathTest.java @@ -0,0 +1,41 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class OwnerSlotCandidateFastPathTest { + @Test + void temporaryRootDoesNotTriggerPerlOwnerLedgerScan() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeArray referent = new RuntimeArray(); + PerlOwnerSlot temporaryRoot = new PerlOwnerSlot( + PerlOwnerSlot.Kind.TEMPORARY_ROOT); + temporaryRoot.acquireTemporaryRootIdentity(referent); + + assertFalse(referent.hasCurrentPerlOwnerSlotIdentity()); + assertTrue(referent.hasTemporaryRootOwnerSlotIdentity()); + + temporaryRoot.release(); + assertFalse(referent.hasCurrentPerlOwnerSlotIdentity()); + } + } + + @Test + void indexedPerlOwnerCandidateStillUsesCurrentSlotValidation() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeArray referent = new RuntimeArray(); + PerlOwnerSlot packageOwner = new PerlOwnerSlot( + PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT); + packageOwner.acquirePackageAggregateIdentity(referent); + + assertTrue(referent.hasCurrentPerlOwnerSlotIdentity()); + + packageOwner.release(); + assertFalse(referent.hasCurrentPerlOwnerSlotIdentity()); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/OwnerSlotKindIndexTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/OwnerSlotKindIndexTest.java new file mode 100644 index 0000000000..0d9de55f68 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/OwnerSlotKindIndexTest.java @@ -0,0 +1,141 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class OwnerSlotKindIndexTest { + @Test + void packageAggregateAndActiveCodeIndexesTrackSlotLifecycle() { + RuntimeArray array = new RuntimeArray(); + PerlOwnerSlot packageOwner = new PerlOwnerSlot( + PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT); + packageOwner.acquirePackageAggregateIdentity(array); + assertEquals(1, + array.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + assertCountsMatchLedger(array); + packageOwner.release(); + assertEquals(0, + array.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + PerlOwnerSlot activeCodeOwner = new PerlOwnerSlot(PerlOwnerSlot.Kind.ACTIVE_CODE); + activeCodeOwner.acquireActiveCodeIdentity(code); + assertEquals(1, code.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_CODE)); + assertCountsMatchLedger(code); + activeCodeOwner.release(); + assertEquals(0, code.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_CODE)); + assertCountsMatchLedger(code); + } + + @Test + void countedSlotReclassificationAndReleaseKeepPerKindIndexCurrent() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash referent = new RuntimeHash(); + referent.setBlessId(NameNormalizer.getBlessId( + "OwnerSlotKindIndexTest::Referent")); + RuntimeScalar owner = new RuntimeScalar(); + RuntimeScalar reference = new RuntimeScalar(); + reference.type = RuntimeScalarType.HASHREFERENCE; + reference.value = referent; + owner.set(reference); + + PerlOwnerSlot slot = owner.countedOwnerSlot(); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(1, referent.countedOwnerSlotCount()); + assertCountsMatchLedger(referent); + + slot.reclassifyCountedIdentity(PerlOwnerSlot.Kind.ARGUMENT_VALUE); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(1, referent.countedOwnerSlotCount()); + assertCountsMatchLedger(referent); + + slot.reclassifyCountedIdentity(PerlOwnerSlot.Kind.RETURN_VALUE); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.RETURN_VALUE)); + assertEquals(1, referent.countedOwnerSlotCount()); + assertCountsMatchLedger(referent); + + owner.set(new RuntimeScalar()); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.RETURN_VALUE)); + assertEquals(0, referent.countedOwnerSlotCount()); + assertCountsMatchLedger(referent); + } + } + + @Test + void transientUntrackedOwnerCountTracksStagingAndMortalReturnTransitions() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeScalar referent = new RuntimeScalar("transient referent"); + RuntimeScalar reference = referenceTo(referent); + RuntimeScalar staged = RuntimeScalar.retainStagedArgumentValue(reference); + PerlOwnerSlot stagedSlot = staged.untrackedReferenceOwnerSlot(); + + assertNotNull(stagedSlot); + assertEquals(1, referent.transientUntrackedReferenceOwnerCount()); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + RuntimeScalar.releaseStagedArgumentValue(staged); + assertEquals(0, referent.transientUntrackedReferenceOwnerCount()); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + MortalList.pushMark(); + RuntimeScalar returned = RuntimeScalar.copyToMortalReturnSlot(reference); + PerlOwnerSlot returnSlot = returned.untrackedReferenceOwnerSlot(); + assertNotNull(returnSlot); + assertEquals(1, referent.transientUntrackedReferenceOwnerCount()); + returned.finishMortalReturnHandoff(); + assertEquals(1, referent.transientUntrackedReferenceOwnerCount(), + "the return owner remains transient until its handoff owner is released"); + returned.releaseMortalReturnValueOwner(); + assertEquals(0, referent.transientUntrackedReferenceOwnerCount()); + MortalList.popAndFlush(); + assertEquals(0, referent.transientUntrackedReferenceOwnerCount()); + } + } + + @Test + void stashCodeSlotCheckUsesTheIndexedCodeSlotLedger() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar stashSlot = new RuntimeScalar(); + stashSlot.type = RuntimeScalarType.CODE; + stashSlot.value = code; + + stashSlot.retainStashCodeSlotBinding(); + assertEquals(1, code.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + assertCountsMatchLedger(code); + assertTrue(code.hasStashCodeSlotOwner()); + + stashSlot.releaseStashCodeSlotBinding(); + MortalList.flush(); + assertEquals(0, code.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + assertFalse(code.hasStashCodeSlotOwner()); + assertCountsMatchLedger(code); + } + } + + private static RuntimeScalar referenceTo(RuntimeBase value) { + RuntimeScalar reference = new RuntimeScalar(); + reference.type = RuntimeScalarType.REFERENCE; + reference.value = value; + return reference; + } + + private static void assertCountsMatchLedger(RuntimeBase referent) { + java.util.Set slots = referent.ownerSlotSnapshot(); + for (PerlOwnerSlot.Kind kind : PerlOwnerSlot.Kind.values()) { + int ledgerCount = 0; + for (PerlOwnerSlot slot : slots) { + if (slot.kind() == kind) ledgerCount++; + } + assertEquals(ledgerCount, referent.ownerSlotCount(kind), kind.toString()); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PackageAggregateOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageAggregateOwnerSlotTest.java new file mode 100644 index 0000000000..2d1d56ba8f --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageAggregateOwnerSlotTest.java @@ -0,0 +1,197 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class PackageAggregateOwnerSlotTest { + @Test + void packageArrayAndHashKeysOwnDistinctRootIdentities() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray array = new RuntimeArray(); + RuntimeHash hash = new RuntimeHash(); + int arrayRefCount = array.refCount; + int hashRefCount = hash.refCount; + String firstArrayKey = "PackageAggregateOwnerSlotTest::array_one"; + String secondArrayKey = "PackageAggregateOwnerSlotTest::array_two"; + String sharedKey = "PackageAggregateOwnerSlotTest::shared_name"; + + try { + GlobalVariable.globalArrays.put(firstArrayKey, array); + PerlOwnerSlot firstArrayOwner = array.ownerSlotSnapshot().stream() + .filter(slot -> slot.kind() == PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT) + .findFirst().orElse(null); + assertNotNull(firstArrayOwner); + assertSame(array, firstArrayOwner.referent()); + assertEquals(1, array.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + + GlobalVariable.globalArrays.put(secondArrayKey, array); + assertEquals(2, array.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT), + "each package key owns an independent array root slot"); + PerlOwnerSlot secondArrayOwner = array.ownerSlotSnapshot().stream() + .filter(slot -> slot.kind() == PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT + && slot != firstArrayOwner) + .findFirst().orElse(null); + assertNotNull(secondArrayOwner); + + GlobalVariable.globalHashes.put(sharedKey, hash); + assertEquals(1, hash.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT), + "array and hash roots with one name have separate identities"); + + GlobalVariable.globalArrays.keySet().remove(firstArrayKey); + assertFalse(firstArrayOwner.isActive()); + assertTrue(secondArrayOwner.isActive()); + assertEquals(1, array.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + + GlobalVariable.globalArrays.remove(secondArrayKey); + GlobalVariable.globalHashes.remove(sharedKey); + assertFalse(secondArrayOwner.isActive()); + assertEquals(0, array.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + assertEquals(0, hash.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + assertEquals(arrayRefCount, array.refCount, + "package root identities must not promote the aggregate count"); + assertEquals(hashRefCount, hash.refCount, + "package root identities must not promote the aggregate count"); + + GlobalVariable.globalArrays.put(firstArrayKey, array); + GlobalVariable.globalHashes.put(sharedKey, hash); + PerlOwnerSlot clearArrayOwner = array.ownerSlotSnapshot().stream() + .filter(slot -> slot.isActive() + && slot.kind() == PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT) + .findFirst().orElseThrow(); + PerlOwnerSlot clearHashOwner = hash.ownerSlotSnapshot().stream() + .filter(slot -> slot.isActive() + && slot.kind() == PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT) + .findFirst().orElseThrow(); + GlobalVariable.globalArrays.clear(); + GlobalVariable.globalHashes.clear(); + assertFalse(clearArrayOwner.isActive()); + assertFalse(clearHashOwner.isActive()); + } finally { + GlobalVariable.globalArrays.remove(firstArrayKey); + GlobalVariable.globalArrays.remove(secondArrayKey); + GlobalVariable.globalHashes.remove(sharedKey); + } + } + } + + @Test + void packageArrayAndHashRootsRebuildFromSnapshotTables() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray array = new RuntimeArray(); + RuntimeHash hash = new RuntimeHash(); + runtime.globalState.arrayValues().put("PackageAggregateOwnerSlotTest::clone_array", array); + runtime.globalState.hashValues().put("PackageAggregateOwnerSlotTest::clone_hash", hash); + + runtime.globalState.rebuildPackageAggregateOwnerSlots(); + + assertEquals(1, array.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + assertEquals(1, hash.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, array.refCountTrackingState()); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, hash.refCountTrackingState()); + } + } + + @Test + void packageRootEntryValueReplacementTransfersItsIdentity() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray first = new RuntimeArray(); + RuntimeArray replacement = new RuntimeArray(); + String key = "PackageAggregateOwnerSlotTest::replace_array"; + + try { + GlobalVariable.globalArrays.put(key, first); + PerlOwnerSlot owner = first.ownerSlotSnapshot().stream() + .filter(slot -> slot.kind() == PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT) + .findFirst().orElseThrow(); + GlobalVariable.globalArrays.entrySet().stream() + .filter(entry -> entry.getKey().equals(key)) + .findFirst().orElseThrow().setValue(replacement); + + assertSame(replacement, owner.referent()); + assertEquals(0, first.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + assertEquals(1, + replacement.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + + GlobalVariable.globalArrays.remove(key); + assertFalse(owner.isActive()); + assertEquals(0, + replacement.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + } finally { + GlobalVariable.globalArrays.remove(key); + } + } + } + + @Test + void finalPackageAggregateOwnerClearsWeakObserver() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray array = new RuntimeArray(); + RuntimeScalar weakObserver = referenceTo(array); + WeakRefRegistry.weaken(weakObserver); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, array.refCountTrackingState()); + String key = "PackageAggregateOwnerSlotTest::weak_array"; + + try { + GlobalVariable.globalArrays.put(key, array); + assertEquals(1, array.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + + { + GlobalVariable.globalArrays.remove(key); + + assertEquals(0, array.ownerSlotCount( + PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + } + } finally { + GlobalVariable.globalArrays.remove(key); + if (WeakRefRegistry.isweak(weakObserver)) WeakRefRegistry.unweaken(weakObserver); + } + } + } + + @Test + void finalPackageScalarOwnerClearsWeakObserverToCell() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar packageCell = new RuntimeScalar("package scalar cell"); + RuntimeScalar weakObserver = referenceTo(packageCell); + WeakRefRegistry.weaken(weakObserver); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, packageCell.refCountTrackingState()); + String key = "PackageAggregateOwnerSlotTest::weak_scalar"; + + try { + GlobalVariable.globalVariables.put(key, packageCell); + assertEquals(1, packageCell.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT)); + + GlobalVariable.globalVariables.remove(key); + + assertEquals(0, packageCell.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT)); + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + } finally { + GlobalVariable.globalVariables.remove(key); + if (WeakRefRegistry.isweak(weakObserver)) WeakRefRegistry.unweaken(weakObserver); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase value) { + RuntimeScalar reference = new RuntimeScalar(); + reference.type = RuntimeScalarType.REFERENCE; + reference.value = value; + return reference; + } + +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PackageAggregateValueOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageAggregateValueOwnerSlotTest.java new file mode 100644 index 0000000000..2e0b932213 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageAggregateValueOwnerSlotTest.java @@ -0,0 +1,219 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class PackageAggregateValueOwnerSlotTest { + @Test + void prepopulatedPackageArrayOwnsUncountedValue() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar referent = new RuntimeScalar("package aggregate referent"); + RuntimeScalar countedOwner = new RuntimeScalar(); + countedOwner.set(referent.createReference()); + + RuntimeScalar aggregateValue = referenceTo(referent); + RuntimeArray packageArray = new RuntimeArray(); + packageArray.elements.add(aggregateValue); + String key = "PackageAggregateValueOwnerSlotTest::values"; + RuntimeScalar weakObserver = referenceTo(referent); + PerlOwnerSlot valueOwner = null; + + try { + GlobalVariable.globalArrays.put(key, packageArray); + valueOwner = aggregateValue.untrackedReferenceOwnerSlot(); + assertNotNull(valueOwner, + "rooting a prepopulated aggregate records its uncounted value edge"); + assertEquals(1, + referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + WeakRefRegistry.weaken(weakObserver); + { + countedOwner.set(new RuntimeScalar()); + assertTrue(WeakRefRegistry.isweak(weakObserver), + "the package aggregate value keeps the referent alive"); + + aggregateValue.set(new RuntimeScalar()); + + assertFalse(valueOwner.isActive(), "the value owner releases exactly once"); + assertEquals(0, + referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + } + } finally { + if (valueOwner != null && valueOwner.isActive()) { + aggregateValue.set(new RuntimeScalar()); + } + GlobalVariable.globalArrays.remove(key); + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + countedOwner.set(new RuntimeScalar()); + } + } + } + + @Test + void prepopulatedPackageHashOwnsUncountedValue() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar referent = new RuntimeScalar("package hash referent"); + RuntimeScalar countedOwner = new RuntimeScalar(); + countedOwner.set(referent.createReference()); + + RuntimeScalar aggregateValue = referenceTo(referent); + RuntimeHash packageHash = new RuntimeHash(); + packageHash.elements.put("child", aggregateValue); + String key = "PackageAggregateValueOwnerSlotTest::hash_values"; + RuntimeScalar weakObserver = referenceTo(referent); + PerlOwnerSlot valueOwner = null; + + try { + GlobalVariable.globalHashes.put(key, packageHash); + valueOwner = aggregateValue.untrackedReferenceOwnerSlot(); + assertNotNull(valueOwner, + "rooting a prepopulated hash records its uncounted value edge"); + assertEquals(1, + referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + WeakRefRegistry.weaken(weakObserver); + { + countedOwner.set(new RuntimeScalar()); + assertTrue(WeakRefRegistry.isweak(weakObserver), + "the package hash value keeps the referent alive"); + + aggregateValue.set(new RuntimeScalar()); + + assertFalse(valueOwner.isActive(), "the value owner releases exactly once"); + assertEquals(0, + referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + } + } finally { + if (valueOwner != null && valueOwner.isActive()) { + aggregateValue.set(new RuntimeScalar()); + } + GlobalVariable.globalHashes.remove(key); + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + countedOwner.set(new RuntimeScalar()); + } + } + } + + @Test + void packageAggregateValuesOwnArrayAndHashReferents() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + assertPackageAggregateValueKeepsReferentAlive( + new RuntimeArray(), new RuntimeArray(), true, + "PackageAggregateValueOwnerSlotTest::array_referent"); + assertPackageAggregateValueKeepsReferentAlive( + new RuntimeHash(), new RuntimeHash(), false, + "PackageAggregateValueOwnerSlotTest::hash_referent"); + } + } + + @Test + void crossContainerAliasKeepsOneValueOwnerUntilItsFinalPackageSlotLeaves() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray packageArray = new RuntimeArray(); + RuntimeHash packageHash = new RuntimeHash(); + RuntimeArray referent = new RuntimeArray(); + RuntimeScalar sharedValue = referenceTo(referent); + RuntimeScalar weakObserver = referenceTo(referent); + String arrayKey = "PackageAggregateValueOwnerSlotTest::alias_array"; + String hashKey = "PackageAggregateValueOwnerSlotTest::alias_hash"; + + try { + GlobalVariable.globalArrays.put(arrayKey, packageArray); + GlobalVariable.globalHashes.put(hashKey, packageHash); + packageArray.elements.add(sharedValue); + packageHash.elements.put("shared", sharedValue); + + PerlOwnerSlot owner = sharedValue.untrackedReferenceOwnerSlot(); + assertNotNull(owner); + assertEquals(1, + referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + WeakRefRegistry.weaken(weakObserver); + + { + packageArray.elements.remove(sharedValue); + + assertTrue(WeakRefRegistry.isweak(weakObserver), + "the hash alias remains a strong owner after the array slot leaves"); + assertTrue(owner.isActive()); + + packageHash.elements.remove("shared"); + + assertFalse(owner.isActive(), "the shared value owner releases once"); + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + } + } finally { + GlobalVariable.globalArrays.remove(arrayKey); + GlobalVariable.globalHashes.remove(hashKey); + if (WeakRefRegistry.isweak(weakObserver)) WeakRefRegistry.unweaken(weakObserver); + } + } + } + + private static void assertPackageAggregateValueKeepsReferentAlive( + RuntimeBase referent, RuntimeBase packageAggregate, boolean packageArray, + String key) { + RuntimeScalar aggregateValue = referenceTo(referent); + if (packageArray) { + ((RuntimeArray) packageAggregate).elements.add(aggregateValue); + GlobalVariable.globalArrays.put(key, (RuntimeArray) packageAggregate); + } else { + ((RuntimeHash) packageAggregate).elements.put("child", aggregateValue); + GlobalVariable.globalHashes.put(key, (RuntimeHash) packageAggregate); + } + RuntimeScalar weakObserver = referenceTo(referent); + PerlOwnerSlot valueOwner = aggregateValue.untrackedReferenceOwnerSlot(); + + try { + assertNotNull(valueOwner, + "a package aggregate slot records its direct aggregate referent edge"); + assertEquals(1, + referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + WeakRefRegistry.weaken(weakObserver); + { + assertTrue(WeakRefRegistry.isweak(weakObserver)); + + aggregateValue.set(new RuntimeScalar()); + + assertFalse(valueOwner.isActive()); + assertEquals(0, + referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + } + } finally { + if (valueOwner != null && valueOwner.isActive()) { + aggregateValue.set(new RuntimeScalar()); + } + if (packageArray) GlobalVariable.globalArrays.remove(key); + else GlobalVariable.globalHashes.remove(key); + if (WeakRefRegistry.isweak(weakObserver)) WeakRefRegistry.unweaken(weakObserver); + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar reference = new RuntimeScalar(); + reference.type = RuntimeScalarType.REFERENCE; + reference.value = referent; + return reference; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PackageArrayRootMarkingFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageArrayRootMarkingFastPathTest.java new file mode 100644 index 0000000000..1efe4cf597 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageArrayRootMarkingFastPathTest.java @@ -0,0 +1,49 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Tag("unit") +class PackageArrayRootMarkingFastPathTest { + private static final class CountingElements extends ArrayList { + private int snapshots; + + @Override + public T[] toArray(T[] target) { + snapshots++; + return super.toArray(target); + } + } + + @Test + void repeatedGlobalArrayLookupDoesNotRescanPrepopulatedSlots() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + String name = "PackageArrayRootMarkingFastPathTest::values"; + RuntimeArray array = new RuntimeArray(); + CountingElements elements = new CountingElements(); + elements.add(new RuntimeScalar("prepopulated")); + array.elements = elements; + + try { + GlobalVariable.globalArrays.put(name, array); + int snapshotsAfterRooting = elements.snapshots; + assertEquals(1, snapshotsAfterRooting, + "initial package installation marks prepopulated slots"); + + for (int i = 0; i < 4; i++) { + assertEquals(array, GlobalVariable.getGlobalArray(name)); + } + + assertEquals(snapshotsAfterRooting, elements.snapshots, + "reading an already-rooted array does not snapshot its slots again"); + } finally { + GlobalVariable.globalArrays.remove(name); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PackageGlobOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageGlobOwnerSlotTest.java new file mode 100644 index 0000000000..ae9ed77516 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageGlobOwnerSlotTest.java @@ -0,0 +1,58 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.Iterator; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +@Tag("unit") +class PackageGlobOwnerSlotTest { + @Test + void replacementAndIteratorRemovalTransferAndReleaseTheNamedGlobOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + String name = "PackageGlobOwnerSlotTest::FH"; + RuntimeGlob previous = new RuntimeGlob(name); + RuntimeGlob replacement = new RuntimeGlob(name); + + GlobalVariable.globalIORefs.put(name, previous); + assertEquals(1, previous.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_GLOB_SLOT)); + + GlobalVariable.globalIORefs.put(name, replacement); + assertEquals(0, previous.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_GLOB_SLOT)); + assertEquals(1, replacement.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_GLOB_SLOT)); + + Iterator> entries = + GlobalVariable.globalIORefs.entrySet().iterator(); + while (entries.hasNext()) { + if (name.equals(entries.next().getKey())) { + entries.remove(); + break; + } + } + + assertNull(GlobalVariable.globalIORefs.get(name)); + assertEquals(0, replacement.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_GLOB_SLOT)); + } + } + + @Test + void clearReleasesEveryNamedGlobOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeGlob first = new RuntimeGlob("PackageGlobOwnerSlotTest::FIRST"); + RuntimeGlob second = new RuntimeGlob("PackageGlobOwnerSlotTest::SECOND"); + GlobalVariable.globalIORefs.put(first.globName, first); + GlobalVariable.globalIORefs.put(second.globName, second); + + GlobalVariable.globalIORefs.clear(); + + assertEquals(0, first.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_GLOB_SLOT)); + assertEquals(0, second.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_GLOB_SLOT)); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PackageGlobOwnerVisibilityTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageGlobOwnerVisibilityTest.java new file mode 100644 index 0000000000..c93b38375e --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageGlobOwnerVisibilityTest.java @@ -0,0 +1,32 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Tag("unit") +class PackageGlobOwnerVisibilityTest { + @Test + void hiddenStashEntryReleasesItsOwnerAndVisibleEntryReacquiresIt() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + String name = "PackageGlobOwnerVisibilityTest::FH"; + RuntimeGlob original = new RuntimeGlob(name); + RuntimeGlob replacement = new RuntimeGlob(name); + + GlobalVariable.globalIORefs.put(name, original); + assertEquals(1, original.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_GLOB_SLOT)); + + GlobalVariable.hideIORefAfterStashDelete(name); + assertEquals(0, original.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_GLOB_SLOT)); + + GlobalVariable.globalIORefs.put(name, replacement); + assertEquals(0, replacement.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_GLOB_SLOT)); + + GlobalVariable.markStashEntryVisible(name); + assertEquals(0, original.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_GLOB_SLOT)); + assertEquals(1, replacement.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_GLOB_SLOT)); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PackageNestedUntrackedAggregateReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageNestedUntrackedAggregateReleaseTest.java new file mode 100644 index 0000000000..76b3f6ec1d --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageNestedUntrackedAggregateReleaseTest.java @@ -0,0 +1,95 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class PackageNestedUntrackedAggregateReleaseTest { + @Test + void firstWeakTransitionUsesUntrackedOwnerIdentityWithoutWalkingRoots() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray packageRoot = new RuntimeArray(); + String globalName = + "PackageNestedUntrackedAggregateReleaseTest::ownerSlotFastPath"; + GlobalVariable.globalArrays.put(globalName, packageRoot); + + RuntimeArray target = new RuntimeArray(); + RuntimeScalar strong = target.createAnonymousReference(); + target.markRefCountUntracked(); + packageRoot.elements.add(strong); + RuntimeScalar weak = target.createAnonymousReference(); + target.markRefCountUntracked(); + + try { + assertEquals(1, + target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + { + WeakRefRegistry.weaken(weak); + + assertTrue(WeakRefRegistry.isweak(weak)); + } + } finally { + WeakRefRegistry.clearWeakRefsTo(target); + GlobalVariable.globalArrays.remove(globalName); + } + } + } + + @Test + void finalUntrackedPackageOwnerClearsWeakObserver() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray packageRoot = new RuntimeArray(); + String globalName = + "PackageNestedUntrackedAggregateReleaseTest::packageRoot"; + GlobalVariable.globalArrays.put(globalName, packageRoot); + + RuntimeArray target = new RuntimeArray(); + RuntimeScalar firstOwner = target.createAnonymousReference(); + target.markRefCountUntracked(); + packageRoot.elements.add(firstOwner); + RuntimeScalar secondOwner = target.createAnonymousReference(); + target.markRefCountUntracked(); + packageRoot.elements.add(secondOwner); + RuntimeScalar weak = target.createAnonymousReference(); + target.markRefCountUntracked(); + + try { + assertEquals(2, + target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + WeakRefRegistry.weaken(weak); + + assertTrue(WeakRefRegistry.isweak(weak)); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState(), + "weak tracking does not fabricate a positive owner count"); + assertEquals(2, target.ownerSlotCount( + PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + firstOwner.undefine(); + assertTrue(WeakRefRegistry.isweak(weak), + "one remaining package owner keeps the weak observer live"); + assertEquals(1, + target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + secondOwner.undefine(); + + assertFalse(WeakRefRegistry.isweak(weak)); + assertNull(weak.value, + "the observer is cleared when the final untracked owner leaves"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, target.perlLifecycleState()); + assertEquals(0, target.refCount); + } finally { + WeakRefRegistry.clearWeakRefsTo(target); + GlobalVariable.globalArrays.remove(globalName); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PackageRootOwnerIdentityLookupTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageRootOwnerIdentityLookupTest.java new file mode 100644 index 0000000000..f904726870 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageRootOwnerIdentityLookupTest.java @@ -0,0 +1,35 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class PackageRootOwnerIdentityLookupTest { + @Test + void packageAggregateRootLookupUsesTheCurrentRootSlotIdentity() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + assertRootSlotControlsLookup(new RuntimeArray()); + assertRootSlotControlsLookup(new RuntimeHash()); + } + } + + private static void assertRootSlotControlsLookup(RuntimeBase aggregate) { + assertFalse(GlobalVariable.isPackageRootedAggregate(aggregate)); + + PerlOwnerSlot rootSlot = new PerlOwnerSlot(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT); + rootSlot.acquirePackageAggregateIdentity(aggregate); + try { + assertTrue(GlobalVariable.isPackageRootedAggregate(aggregate), + "the package slot identity proves the aggregate is rooted"); + } finally { + rootSlot.release(); + } + + assertFalse(GlobalVariable.isPackageRootedAggregate(aggregate), + "releasing the final package slot removes the root proof"); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PackageRootOwnerSlotFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageRootOwnerSlotFastPathTest.java new file mode 100644 index 0000000000..ec3f1c62e4 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageRootOwnerSlotFastPathTest.java @@ -0,0 +1,55 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class PackageRootOwnerSlotFastPathTest { + @Test + void releasingOnePackageHashSlotPreservesTheOtherOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + String leftName = "PackageRootOwnerSlotFastPath::left"; + String rightName = "PackageRootOwnerSlotFastPath::right"; + RuntimeHash left = new RuntimeHash(); + RuntimeHash right = new RuntimeHash(); + GlobalVariable.aliasGlobalHash(leftName, left); + GlobalVariable.aliasGlobalHash(rightName, right); + + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId("PackageRootOwnerSlotFastPath::Target"); + left.put("target", target.createAnonymousReference()); + right.put("target", target.createAnonymousReference()); + RuntimeScalar observer = new RuntimeScalar(); + observer.set(target.createAnonymousReference()); + WeakRefRegistry.weaken(observer); + + try { + assertTrue(target.storedInPackageGlobal); + assertEquals(2, target.countedOwnerSlotCount()); + assertTrue(WeakRefRegistry.isweak(observer)); + + { + left.elements.get("target").set(new RuntimeScalar()); + + assertEquals(1, target.refCount); + assertEquals(1, target.countedOwnerSlotCount()); + assertTrue(WeakRefRegistry.isweak(observer)); + assertFalse(target.destroyFired); + } + + right.elements.get("target").set(new RuntimeScalar()); + assertFalse(WeakRefRegistry.isweak(observer), + "the final counted owner still releases the weak observer"); + } finally { + if (WeakRefRegistry.isweak(observer)) WeakRefRegistry.unweaken(observer); + GlobalVariable.globalHashes.remove(leftName); + GlobalVariable.globalHashes.remove(rightName); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PackageScalarValueOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageScalarValueOwnerSlotTest.java new file mode 100644 index 0000000000..c020a224f0 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageScalarValueOwnerSlotTest.java @@ -0,0 +1,56 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +@Tag("unit") +class PackageScalarValueOwnerSlotTest { + @Test + void trackedReferentGetsOneUncountedIdentityForPackageScalarCell() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar countedOwner = new RuntimeScalar(); + countedOwner.set(referent.createAnonymousReference()); + + RuntimeScalar packageCell = referent.createAnonymousReference(); + String globalName = + "PackageScalarValueOwnerSlotTest::trackedPackageCell"; + PerlOwnerSlot valueOwner; + + try { + GlobalVariable.globalVariables.put(globalName, packageCell); + valueOwner = packageCell.untrackedReferenceOwnerSlot(); + + assertNotNull(valueOwner, + "the package scalar cell owns its uncounted value edge"); + assertSame(referent, valueOwner.referent()); + assertEquals(1, referent.refCount, + "the extra slot identity does not duplicate the legacy count"); + assertEquals(1, + referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + GlobalVariable.globalVariables.remove(globalName); + + assertFalse(valueOwner.isActive(), + "removing the package cell releases its value edge once"); + assertEquals(0, + referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertEquals(1, referent.refCount, + "the independent counted scalar owner remains"); + + countedOwner.set(new RuntimeScalar()); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState(), + "the final counted owner performs final release"); + assertEquals(0, referent.refCount); + } finally { + GlobalVariable.globalVariables.remove(globalName); + countedOwner.set(new RuntimeScalar()); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PackageWeakCompatibilityPinOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageWeakCompatibilityPinOwnerSlotTest.java new file mode 100644 index 0000000000..1ba7058d86 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PackageWeakCompatibilityPinOwnerSlotTest.java @@ -0,0 +1,105 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class PackageWeakCompatibilityPinOwnerSlotTest { + @Test + void packageWeakObserverFollowsTheFinalUntrackedScalarOwner() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeArray packageRoot = new RuntimeArray(); + String globalName = "PackageWeakCompatibilityPinOwnerSlotTest::packageRoot"; + GlobalVariable.globalArrays.put(globalName, packageRoot); + + RuntimeArray target = new RuntimeArray(); + RuntimeScalar firstOwner = target.createAnonymousReference(); + target.markRefCountUntracked(); + packageRoot.elements.add(firstOwner); + RuntimeScalar secondOwner = target.createAnonymousReference(); + target.markRefCountUntracked(); + packageRoot.elements.add(secondOwner); + RuntimeScalar weakObserver = target.createAnonymousReference(); + target.markRefCountUntracked(); + + try { + WeakRefRegistry.weaken(weakObserver); + + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState(), + "weak tracking does not manufacture a positive count"); + assertEquals(2, target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + firstOwner.undefine(); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + secondOwner.undefine(); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, target.perlLifecycleState()); + assertEquals(0, target.refCount); + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertFalse(target.hasOwnerSlots()); + secondOwner.undefine(); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, target.perlLifecycleState(), + "repeated owner release cannot revive or destroy the referent twice"); + assertEquals(0, target.refCount); + } finally { + WeakRefRegistry.clearWeakRefsTo(target); + GlobalVariable.globalArrays.remove(globalName); + } + } + } + + @Test + void unweakenedReferenceBecomesAnOrdinaryUntrackedOwner() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeArray packageRoot = new RuntimeArray(); + String globalName = "PackageWeakCompatibilityPinOwnerSlotTest::unweakenedRoot"; + GlobalVariable.globalArrays.put(globalName, packageRoot); + + RuntimeArray target = new RuntimeArray(); + RuntimeScalar firstOwner = target.createAnonymousReference(); + target.markRefCountUntracked(); + packageRoot.elements.add(firstOwner); + RuntimeScalar secondOwner = target.createAnonymousReference(); + target.markRefCountUntracked(); + packageRoot.elements.add(secondOwner); + RuntimeScalar observer = target.createAnonymousReference(); + target.markRefCountUntracked(); + + try { + WeakRefRegistry.weaken(observer); + MyVarCleanupStack.register(observer); + WeakRefRegistry.unweaken(observer); + + assertFalse(WeakRefRegistry.isweak(observer)); + assertEquals(3, + target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE), + "unweakening installs the observer's direct strong owner slot"); + + firstOwner.undefine(); + assertTrue(observer.value == target, + "the unweakened observer remains a strong referent"); + assertEquals(2, + target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + secondOwner.undefine(); + assertTrue(observer.value == target, + "the observer alone now owns the referent"); + assertEquals(1, + target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + observer.undefine(); + assertFalse(target.hasOwnerSlots(), + "undef retires the final direct untracked owner"); + } finally { + MyVarCleanupStack.unregister(observer); + WeakRefRegistry.clearWeakRefsTo(target); + GlobalVariable.globalArrays.remove(globalName); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PendingMortalArgumentAliasOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PendingMortalArgumentAliasOwnerTest.java new file mode 100644 index 0000000000..450a262221 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PendingMortalArgumentAliasOwnerTest.java @@ -0,0 +1,57 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class PendingMortalArgumentAliasOwnerTest { + @Test + void stagedArgumentAliasKeepsQueuedMortalReferentAliveThroughTheCall() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + MortalList.pushMark(); + boolean markActive = true; + RuntimeHash referent = new RuntimeHash(); + referent.blessId = NameNormalizer.getBlessId( + "Issue1649::PendingMortalArgumentAlias"); + RuntimeScalar weak = referent.createAnonymousReference(); + WeakRefRegistry.weaken(weak); + RuntimeScalar argument = referent.createAnonymousReference(); + RuntimeCode.CallArguments arguments = RuntimeCode.newCallArguments(1); + + try { + MortalList.deferBlessTemporary(referent, false); + arguments.add(argument); + + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS), + "staging the strong value records its live scalar alias"); + + MortalList.flushAboveMark(); + + assertTrue(WeakRefRegistry.isweak(weak), + "the queued mortal decrement cannot destroy a live call argument"); + assertEquals(RuntimeBase.PerlLifecycleState.LIVE, + referent.perlLifecycleState()); + + arguments.finish(); + + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS)); + assertEquals(RuntimeScalarType.UNDEF, weak.type, + "the referent is released when the staged argument exits"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + referent.perlLifecycleState()); + MortalList.popAndFlush(); + markActive = false; + } finally { + arguments.finish(); + if (markActive) MortalList.popAndFlush(); + if (WeakRefRegistry.isweak(weak)) WeakRefRegistry.unweaken(weak); + } + } + } + +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PendingOwnerReleaseFinalizationTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PendingOwnerReleaseFinalizationTest.java new file mode 100644 index 0000000000..e2c726f2db --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PendingOwnerReleaseFinalizationTest.java @@ -0,0 +1,66 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class PendingOwnerReleaseFinalizationTest { + @Test + void clearedAggregateFinalizationWaitsForQueuedCountedRelease() { + PerlRuntime runtime = new PerlRuntime(); + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar owner = new RuntimeScalar(); + RuntimeScalar weakObserver = referenceTo(referent); + + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + MortalList.setActive(true); + try { + owner.set(referent.createAnonymousReference()); + WeakRefRegistry.weaken(weakObserver); + assertEquals(1, referent.refCount); + assertEquals(1, referent.countedOwnerSlotCount()); + + referent.clearedOwnedAggregateElement = true; + MortalList.deferDecrementIfTracked(owner); + + assertFalse(owner.refCountOwned); + assertEquals(0, referent.countedOwnerSlotCount()); + assertEquals(1, referent.refCount, + "the queued release has not decremented the compatibility count yet"); + assertTrue(referent.hasPendingOwnerRelease()); + + MortalList.finalizeClearedAggregateOwnerAfterScopeExit(referent); + + assertTrue(WeakRefRegistry.isweak(weakObserver), + "scope cleanup must leave the queued release to decide finalization"); + assertEquals(1, referent.refCount); + + MortalList.flush(); + + assertFalse(WeakRefRegistry.isweak(weakObserver), + "draining the final counted release clears the weak observer"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState()); + assertEquals(0, referent.refCount); + assertFalse(referent.hasPendingOwnerRelease()); + } finally { + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + if (referent.hasPendingOwnerRelease()) MortalList.flush(); + MortalList.setActive(previousMortalListState); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.HASHREFERENCE; + scalar.value = referent; + return scalar; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PendingOwnerReleaseIdentityTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PendingOwnerReleaseIdentityTest.java new file mode 100644 index 0000000000..c96ad2cc13 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PendingOwnerReleaseIdentityTest.java @@ -0,0 +1,47 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class PendingOwnerReleaseIdentityTest { + @Test + void onlyAnEdgeReleaseTokenIdentifiesAReleasedPerlOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash lifecycleTarget = new RuntimeHash(); + lifecycleTarget.setTrackedRefCount(0); + RuntimeBase.PendingOwnerRelease lifecycleOnly = + lifecycleTarget.queueLifecycleOnlyAtZero("identity regression"); + try { + assertFalse(lifecycleOnly.identifiesReleasedOwnerEdge(), + "a lifecycle completion token names no Perl edge"); + } finally { + lifecycleTarget.completeQueuedOwnerRelease(lifecycleOnly, "test cleanup"); + } + + boolean previousActive = MortalList.isActive(); + RuntimeHash countedTarget = new RuntimeHash(); + RuntimeScalar owner = new RuntimeScalar(); + try { + MortalList.setActive(true); + owner.set(countedTarget.createAnonymousReference()); + MortalList.deferDecrementIfTracked(owner); + RuntimeBase.PendingOwnerRelease edgeRelease = + runtime.lifecycleState.pendingOwnerReleases.get( + runtime.lifecycleState.pendingOwnerReleases.size() - 1); + + assertTrue(edgeRelease.identifiesReleasedOwnerEdge(), + "a queued counted-slot release carries its exact edge token"); + + MortalList.flush(); + } finally { + MortalList.setActive(previousActive); + if (countedTarget.hasPendingOwnerRelease()) MortalList.flush(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PerlArgumentUnwindOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlArgumentUnwindOwnerTest.java new file mode 100644 index 0000000000..89c11142a7 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlArgumentUnwindOwnerTest.java @@ -0,0 +1,147 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class PerlArgumentUnwindOwnerTest { + @Test + void argumentArrayReplacementReleasesInsertedOwnersButBorrowsCallerCells() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash callerReferent = new RuntimeHash(); + RuntimeScalar caller = new RuntimeScalar(); + caller.set(callerReferent.createAnonymousReference()); + PerlOwnerSlot callerSlot = caller.countedOwnerSlot(); + RuntimeArray arguments = new RuntimeArray(); + caller.setArrayOfAlias(arguments); + RuntimeHash inserted = new RuntimeHash(); + arguments.push(inserted.createAnonymousReference()); + assertEquals(1, inserted.refCount); + arguments.setFromList(new RuntimeList()); + assertTrue(callerSlot.isActive()); + assertTrue(caller.refCountOwned); + assertEquals(1, callerReferent.refCount); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, inserted.perlLifecycleState()); + caller.setArrayOfAlias(arguments); + RuntimeHash nextInserted = new RuntimeHash(); + arguments.push(nextInserted.createAnonymousReference()); + arguments.undefine(); + assertTrue(callerSlot.isActive()); + assertEquals(1, callerReferent.refCount); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, nextInserted.perlLifecycleState()); + caller.set(new RuntimeScalar()); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, callerReferent.perlLifecycleState()); + } + } + + @Test + void abandonedInnerFrameReleasesOnlyItsOwnRepeatedArgumentOwners() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar source = new RuntimeScalar(); + source.set(referent.createAnonymousReference()); + RuntimeList values = new RuntimeList(); + values.elements.add(source); + values.elements.add(source); + RuntimeCode.CallArguments outer = RuntimeCode.newCallArguments(2); + outer.add(values); + RuntimeCode.CallArguments inner = RuntimeCode.newCallArguments(2); + inner.add(values); + assertEquals(5, referent.refCount); + assertEquals(4, runtime.positiveOwnerSlotReferentCount(referent)); + RuntimeException failure = new RuntimeException("argument failed"); + assertSame(failure, inner.abandon(failure)); + assertEquals(3, referent.refCount); + assertEquals(2, runtime.positiveOwnerSlotReferentCount(referent)); + assertEquals(2, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(java.util.List.of(outer), runtime.executionState().callArgumentFrames); + assertTrue(runtime.lifecycleState.pendingOwnerReleases.isEmpty()); + inner.finish(); + assertEquals(3, referent.refCount); + outer.finish(); + MortalList.flushAboveMark(); + assertEquals(1, referent.refCount); + assertFalse(runtime.retainsPositiveOwnerSlotReferent(referent)); + assertTrue(runtime.executionState().callArgumentFrames.isEmpty()); + } + } + + @Test + void frameExitRetiresAbandonedStagingButPreservesItsCallersFrame() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode.CallArguments caller = RuntimeCode.newCallArguments(2); + RuntimeCode.pushArgs(new RuntimeArray()); + RuntimeCode.CallArguments abandoned = RuntimeCode.newCallArguments(2); + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar source = new RuntimeScalar(); + source.set(referent.createAnonymousReference()); + abandoned.add(source.getList()); + assertEquals(2, referent.refCount); + RuntimeCode.popArgs(); + assertEquals(java.util.List.of(caller), runtime.executionState().callArgumentFrames); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(1, runtime.lifecycleState.pendingOwnerReleases.size()); + abandoned.finish(); + assertEquals(1, runtime.lifecycleState.pendingOwnerReleases.size()); + MortalList.flushAboveMark(); + assertEquals(1, referent.refCount); + caller.finish(); + } + } + + @Test + void nonLocalReturnKeepsItsMortalResultUntilTheReceiverConsumesIt() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode.CallArguments abandoned = RuntimeCode.newCallArguments(2); + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar source = new RuntimeScalar(); + source.set(referent.createAnonymousReference()); + RuntimeScalar returned = RuntimeScalar.copyToMortalReturnSlot(source); + PerlNonLocalReturnException transfer = new PerlNonLocalReturnException(returned); + assertSame(transfer, abandoned.abandon(transfer)); + assertTrue(referent.hasPendingReturnOwner()); + assertTrue(runtime.retainsPositiveOwnerSlotReferent(referent)); + assertEquals(2, referent.refCount); + RuntimeScalar receiver = new RuntimeScalar(); + receiver.set(returned); + assertFalse(referent.hasPendingReturnOwner()); + assertFalse(runtime.retainsPositiveOwnerSlotReferent(referent)); + assertEquals(2, referent.refCount); + assertSame(referent, receiver.value); + } + } + + @Test + void stagedArgumentRetainsItsChildrenUntilItsExplicitRelease() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash child = new RuntimeHash(); + RuntimeScalar childOwner = new RuntimeScalar(); + childOwner.set(child.createAnonymousReference()); + RuntimeScalar weakChild = new RuntimeScalar(); + weakChild.set(childOwner); + WeakRefRegistry.weaken(weakChild); + RuntimeHash parent = new RuntimeHash(); + // put consumes an element cell; the caller keeps its own SV. + parent.put("child", new RuntimeScalar(childOwner)); + RuntimeScalar parentOwner = new RuntimeScalar(); + parentOwner.set(parent.createAnonymousReference()); + RuntimeCode.CallArguments arguments = RuntimeCode.newCallArguments(2); + arguments.add(parentOwner.getList()); + MortalList.deferDecrementIfTracked(childOwner); + MortalList.deferDecrementIfTracked(parentOwner); + MortalList.flushAboveMark(); + assertEquals(RuntimeScalarType.HASHREFERENCE, weakChild.type); + assertEquals(1, parent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + arguments.abandon(new RuntimeException("later argument failed")); + assertEquals(RuntimeScalarType.UNDEF, weakChild.type); + assertFalse(runtime.retainsPositiveOwnerSlotReferent(parent)); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PerlCallTransferOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlCallTransferOwnerTest.java new file mode 100644 index 0000000000..c841e090db --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlCallTransferOwnerTest.java @@ -0,0 +1,122 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class PerlCallTransferOwnerTest { + @Test + void scalarReturnOwnsItsReferentUntilTheReceivingCellConsumesIt() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar source = new RuntimeScalar(); + source.set(referent.createAnonymousReference()); + RuntimeList returned = RuntimeCode.coerceScalarCallResult( + source.getList(), RuntimeContextType.SCALAR); + RuntimeScalar value = (RuntimeScalar) returned.elements.getFirst(); + assertNotSame(source, value); + assertTrue(referent.hasPendingReturnOwner()); + assertEquals(PerlOwnerSlot.Kind.RETURN_VALUE, + runtime.lifecycleState.pendingOwnerReleases.getLast().ownerSlotRelease.kind()); + + MortalList.deferDecrementIfTracked(source); + RuntimeScalar receiver = new RuntimeScalar(); + receiver.set(value); + assertEquals(1, referent.refCount); + assertFalse(referent.hasPendingReturnOwner()); + assertTrue(receiver.countedOwnerSlot().isActive()); + assertEquals(RuntimeBase.PerlLifecycleState.LIVE, referent.perlLifecycleState()); + } + } + + @Test + void listReturnHasDistinctOwnersAndForwardingDoesNotDuplicateThem() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar source = new RuntimeScalar(); + source.set(referent.createAnonymousReference()); + RuntimeList input = new RuntimeList(); + input.elements.add(source); + input.elements.add(source); + RuntimeList returned = RuntimeCode.coerceScalarCallResult(input, RuntimeContextType.LIST); + assertNotSame(returned.elements.get(0), returned.elements.get(1)); + assertEquals(2, runtime.lifecycleState.pendingOwnerReleases.size()); + PerlOwnerSlot.PendingRelease first = runtime.lifecycleState.pendingOwnerReleases.get(0).ownerSlotRelease; + PerlOwnerSlot.PendingRelease second = runtime.lifecycleState.pendingOwnerReleases.get(1).ownerSlotRelease; + assertNotEquals(first.ownerSlotIdentity(), second.ownerSlotIdentity()); + assertEquals(PerlOwnerSlot.Kind.RETURN_VALUE, first.kind()); + assertEquals(PerlOwnerSlot.Kind.RETURN_VALUE, second.kind()); + assertSame(returned, RuntimeCode.coerceScalarCallResult(returned, RuntimeContextType.LIST)); + assertEquals(2, runtime.lifecycleState.pendingOwnerReleases.size()); + assertEquals(3, referent.refCount); + } + } + + @Test + void trackedCodeReturnGetsAnIndependentMortalOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + code.setTrackedRefCount(0); + RuntimeScalar source = new RuntimeScalar(); + source.set(new RuntimeScalar(code)); + RuntimeList returned = RuntimeCode.coerceScalarCallResult(source.getList(), RuntimeContextType.SCALAR); + RuntimeScalar value = (RuntimeScalar) returned.elements.getFirst(); + assertNotSame(source, value); + assertSame(code, value.value); + assertTrue(code.hasPendingReturnOwner()); + MortalList.deferDecrementIfTracked(source); + RuntimeScalar receiver = new RuntimeScalar(); + receiver.set(value); + assertEquals(1, code.refCount); + assertFalse(code.hasPendingReturnOwner()); + assertSame(code, receiver.value); + } + } + + @Test + void stagedRepeatedValuesHaveIndependentArgumentOwnersAndFinishOnce() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar source = new RuntimeScalar(); + source.set(referent.createAnonymousReference()); + RuntimeList values = new RuntimeList(); + values.elements.add(source); + values.elements.add(source); + RuntimeCode.CallArguments frame = RuntimeCode.newCallArguments(2); + frame.add(values); + frame.add(new RuntimeScalar(1)); + assertEquals(2, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(3, referent.refCount); + frame.finish(); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(2, runtime.lifecycleState.pendingOwnerReleases.size()); + for (RuntimeBase.PendingOwnerRelease pending : runtime.lifecycleState.pendingOwnerReleases) { + assertEquals(PerlOwnerSlot.Kind.ARGUMENT_VALUE, pending.ownerSlotRelease.kind()); + } + frame.finish(); + assertEquals(2, runtime.lifecycleState.pendingOwnerReleases.size()); + MortalList.flushAboveMark(); + assertEquals(1, referent.refCount); + assertTrue(source.countedOwnerSlot().isActive()); + } + } + + @Test + void lvalueReturnContinuesToBorrowTheOriginalCell() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar source = new RuntimeScalar(); + source.set(new RuntimeHash().createAnonymousReference()); + RuntimeList returned = RuntimeCode.coerceScalarCallResult( + source.getList(), RuntimeContextType.LVALUE, RuntimeContextType.LVALUE, false); + assertSame(source, returned.elements.getFirst()); + assertTrue(runtime.lifecycleState.pendingOwnerReleases.isEmpty()); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PerlClosureArgumentOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlClosureArgumentOwnerTest.java new file mode 100644 index 0000000000..5ca9cb39d0 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlClosureArgumentOwnerTest.java @@ -0,0 +1,92 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class PerlClosureArgumentOwnerTest { + @Test + void temporaryClosureArgumentHasOneCountedOwnerUntilTheCallFrameExits() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + closure.setTrackedRefCount(0); + closure.capturedScalars = new RuntimeScalar[0]; + RuntimeScalar argument = new RuntimeScalar(closure); + RuntimeCode.CallArguments staged = RuntimeCode.newCallArguments(1); + + { + MortalList.pushMark(); + boolean markActive = true; + boolean argsActive = false; + RuntimeArray perlArgs = null; + try { + staged.add(argument); + perlArgs = staged.toRuntimeArray(); + assertTrue(perlArgs.ownsElement(argument)); + assertEquals(1, closure.refCount); + assertEquals(1, closure.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(PerlOwnerSlot.Kind.ARGUMENT_VALUE, + argument.countedOwnerSlot().kind()); + + RuntimeCode.pushArgs(perlArgs); + argsActive = true; + RuntimeCode.popArgs(); + argsActive = false; + staged.finish(); + MortalList.popAndFlush(); + markActive = false; + + assertEquals(0, closure.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertFalse(perlArgs.ownsElement(argument)); + assertNull(closure.capturedScalars, + "the final argument release retires the temporary CV's captures"); + + } finally { + if (argsActive) RuntimeCode.popArgs(); + staged.finish(); + if (markActive) MortalList.popAndFlush(); + } + } + } + } + + @Test + void abandonedMaterializedArgumentsReleaseTheirCountedClosureOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + closure.setTrackedRefCount(0); + closure.capturedScalars = new RuntimeScalar[0]; + RuntimeScalar argument = new RuntimeScalar(closure); + RuntimeCode.CallArguments staged = RuntimeCode.newCallArguments(1); + + MortalList.pushMark(); + boolean markActive = true; + try { + staged.add(argument); + RuntimeArray perlArgs = staged.toRuntimeArray(); + assertEquals(1, closure.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + + RuntimeException failure = new RuntimeException("call rejected before entry"); + assertSame(failure, staged.abandon(failure)); + MortalList.popAndFlush(); + markActive = false; + + assertEquals(0, closure.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertFalse(perlArgs.ownsElement(argument)); + assertNull(closure.capturedScalars, + "abandoning the call retires the temporary CV's captures"); + } finally { + staged.finish(); + if (markActive) MortalList.popAndFlush(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PerlDestroyFailureOwnershipTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlDestroyFailureOwnershipTest.java new file mode 100644 index 0000000000..de3f64ed94 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlDestroyFailureOwnershipTest.java @@ -0,0 +1,54 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +@Tag("unit") +class PerlDestroyFailureOwnershipTest { + @Test + void throwingDestructorReleasesObserversAndOwnedChildren() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + String className = "Issue1649::FailedOwnerCleanup"; + AtomicInteger calls = new AtomicInteger(); + RuntimeCode code = new RuntimeCode((args, context) -> { + calls.incrementAndGet(); + throw new PerlDieException(new RuntimeScalar("owner cleanup failed\n")); + }, null); + code.packageName = className; + code.subName = "DESTROY"; + GlobalVariable.getGlobalCodeRef(className + "::DESTROY").set(new RuntimeScalar(code)); + try { + RuntimeHash child = new RuntimeHash(); + RuntimeHash parent = new RuntimeHash(); + parent.put("child", child.createAnonymousReference()); + parent.blessId = NameNormalizer.getBlessId(className); + RuntimeScalar owner = new RuntimeScalar(); + owner.set(parent.createAnonymousReference()); + RuntimeScalar weakParent = new RuntimeScalar(); + weakParent.set(owner); + WeakRefRegistry.weaken(weakParent); + RuntimeScalar weakChild = child.createAnonymousReference(); + WeakRefRegistry.weaken(weakChild); + + owner.set(new RuntimeScalar()); + + assertEquals(1, calls.get()); + assertEquals(RuntimeScalarType.UNDEF, weakParent.type); + assertEquals(RuntimeScalarType.UNDEF, weakChild.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, parent.perlLifecycleState()); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, child.perlLifecycleState()); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, parent.perlLifecycleState()); + assertEquals(0, parent.refCount); + assertFalse(parent.currentlyDestroying); + } finally { + GlobalVariable.removeGlobalCodeRefForStashDelete(className + "::DESTROY"); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PerlFinalWeakOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlFinalWeakOwnerTest.java new file mode 100644 index 0000000000..16151fdc50 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlFinalWeakOwnerTest.java @@ -0,0 +1,169 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class PerlFinalWeakOwnerTest { + @Test + void returnOwnerAcquiresTheScalarCellBeforeItsLexicalBindingExits() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash contents = new RuntimeHash(); + RuntimeScalar cell = new RuntimeScalar(); + MyVarCleanupStack.register(cell); + cell.set(contents.createAnonymousReference()); + RuntimeBase returned = RuntimeCode.prepareScopeReturn( + cell.createReference(), RuntimeContextType.SCALAR, true); + assertEquals(1, cell.refCount); + MortalList.deferDecrementIfNotCaptured(cell); + MyVarCleanupStack.unregister(cell); + assertFalse(cell.localBindingExists); + assertTrue(cell.refCountOwned); + assertEquals(1, contents.refCount); + RuntimeScalar receiver = new RuntimeScalar(); + receiver.set(returned.scalar()); + assertEquals(1, cell.refCount); + assertSame(cell, receiver.value); + cell.set(new RuntimeScalar()); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, contents.perlLifecycleState()); + receiver.set(new RuntimeScalar()); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, cell.perlLifecycleState()); + } + } + + @Test + void finalNestedArraySlotOverwriteReleasesItsObserver() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode.pushArgs(new RuntimeArray()); + RuntimeCode.pushArgs(new RuntimeArray()); + try { + RuntimeHash referent = new RuntimeHash(); + referent.blessId = NameNormalizer.getBlessId("FinalWeakOwner::NoDestroy"); + RuntimeArray array = new RuntimeArray(); + array.push(referent.createAnonymousReference()); + RuntimeScalar element = array.elements.getFirst(); + RuntimeScalar observer = new RuntimeScalar(); + observer.set(element); + WeakRefRegistry.weaken(observer); + PerlOwnerSlot slot = element.countedOwnerSlot(); + { + element.set(new RuntimeScalar()); + assertEquals(RuntimeScalarType.UNDEF, observer.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState()); + assertFalse(slot.isActive()); + } + } finally { + RuntimeCode.popArgs(); + RuntimeCode.popArgs(); + } + } + } + + @Test + void weakeningTheLastIdentifiedOwnerClearsItsObserver() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar owner = new RuntimeScalar(); + owner.set(referent.createAnonymousReference()); + PerlOwnerSlot slot = owner.countedOwnerSlot(); + { + WeakRefRegistry.weaken(owner); + assertEquals(RuntimeScalarType.UNDEF, owner.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState()); + assertFalse(slot.isActive()); + } + } + } + + @Test + void weakeningOneLexicalOwnerTrustsAnotherExplicitOwnerSlot() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + referent.blessId = NameNormalizer.getBlessId("FinalWeakOwner::Shared"); + RuntimeScalar observer = referent.createAnonymousReference(); + WeakRefRegistry.weaken(observer); + + RuntimeScalar weakenedOwner = new RuntimeScalar(); + RuntimeScalar survivingOwner = new RuntimeScalar(); + MyVarCleanupStack.register(weakenedOwner); + MyVarCleanupStack.register(survivingOwner); + weakenedOwner.set(referent.createAnonymousReference()); + survivingOwner.set(referent.createAnonymousReference()); + + try { + assertEquals(2, referent.countedOwnerSlotCount()); + { + WeakRefRegistry.weaken(weakenedOwner); + + assertTrue(WeakRefRegistry.isweak(observer)); + assertTrue(WeakRefRegistry.isweak(weakenedOwner)); + assertEquals(1, referent.countedOwnerSlotCount()); + } + } finally { + if (WeakRefRegistry.isweak(weakenedOwner)) { + WeakRefRegistry.unweaken(weakenedOwner); + } + if (WeakRefRegistry.isweak(observer)) WeakRefRegistry.unweaken(observer); + MyVarCleanupStack.unregister(weakenedOwner); + MyVarCleanupStack.unregister(survivingOwner); + weakenedOwner.set(new RuntimeScalar()); + survivingOwner.set(new RuntimeScalar()); + observer.set(new RuntimeScalar()); + } + } + } + + @Test + void scalarCellsReleaseTheirWeakObserversWhenTheLexicalOwnerExits() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar cell = new RuntimeScalar(42); + MyVarCleanupStack.register(cell); + RuntimeScalar observer = new RuntimeScalar(); + observer.set(cell.createReference()); + WeakRefRegistry.weaken(observer); + assertEquals(0, cell.refCount); + assertTrue(cell.localBindingExists); + assertEquals(RuntimeScalarType.REFERENCE, observer.type); + RuntimeScalar.scopeExitCleanup(cell); + MyVarCleanupStack.unregister(cell); + assertFalse(cell.localBindingExists); + assertEquals(RuntimeScalarType.UNDEF, observer.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, cell.perlLifecycleState()); + RuntimeScalar.scopeExitCleanup(cell); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, cell.perlLifecycleState()); + } + } + + @Test + void escapedReferenceOutlivesTheLexicalBindingAndOwnsTheCellsContents() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash contents = new RuntimeHash(); + RuntimeScalar cell = new RuntimeScalar(); + cell.set(contents.createAnonymousReference()); + MyVarCleanupStack.register(cell); + RuntimeScalar escaped = new RuntimeScalar(); + escaped.set(cell.createReference()); + RuntimeScalar observer = new RuntimeScalar(); + observer.set(escaped); + WeakRefRegistry.weaken(observer); + RuntimeScalar.scopeExitCleanup(cell); + MyVarCleanupStack.unregister(cell); + assertEquals(RuntimeScalarType.REFERENCE, observer.type); + assertTrue(cell.refCountOwned); + assertEquals(1, cell.refCount); + assertEquals(1, contents.refCount); + escaped.set(new RuntimeScalar()); + assertEquals(RuntimeScalarType.UNDEF, observer.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, cell.perlLifecycleState()); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, contents.perlLifecycleState()); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PerlOwnerSlotLegacyBridgeTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlOwnerSlotLegacyBridgeTest.java deleted file mode 100644 index 1d1751eaf5..0000000000 --- a/src/test/java/org/perlonjava/runtime/runtimetypes/PerlOwnerSlotLegacyBridgeTest.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.perlonjava.runtime.runtimetypes; - -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@Tag("unit") -class PerlOwnerSlotLegacyBridgeTest { - @Test - void rejectsCaptureCountOverflowBeforeAcquiringTheSlot() { - RuntimeHash referent = new RuntimeHash(); - referent.refCount = Integer.MAX_VALUE; - PerlOwnerSlot slot = new PerlOwnerSlot(PerlOwnerSlot.Kind.CLOSURE_PAD); - - assertThrows(IllegalStateException.class, () -> slot.acquireLegacyCapture(referent)); - assertEquals(Integer.MAX_VALUE, referent.refCount); - assertEquals(0, slot.legacyCaptureCount()); - assertFalse(slot.isActive()); - } - - @Test - void releasingAnUnownedCaptureDoesNotUnderflowOrScheduleCleanup() { - RuntimeHash referent = new RuntimeHash(); - referent.refCount = 0; - PerlOwnerSlot slot = new PerlOwnerSlot(PerlOwnerSlot.Kind.CLOSURE_PAD); - - assertNull(slot.deferLegacyCaptureRelease(referent)); - assertEquals(0, referent.refCount); - assertEquals(0, slot.legacyCaptureCount()); - assertFalse(slot.isActive()); - } - - @Test - void queuedCaptureReleaseRetainsSlotProvenanceUntilDrain() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeHash referent = new RuntimeHash(); - referent.refCount = 0; - referent.localBindingExists = true; - PerlOwnerSlot slot = new PerlOwnerSlot(PerlOwnerSlot.Kind.CLOSURE_PAD); - - slot.acquireLegacyCapture(referent); - assertEquals(1, referent.refCount); - assertEquals(1, slot.legacyCaptureCount()); - - MortalList.pushMark(); - PerlOwnerSlot.PendingRelease release = slot.deferLegacyCaptureRelease(referent); - slot.release(); - assertNotNull(release); - assertEquals(0, slot.legacyCaptureCount()); - assertEquals(1, referent.refCount); - assertEquals(slot.identity(), release.ownerSlotIdentity()); - assertEquals(1, release.sequence()); - assertEquals(PerlOwnerSlot.Kind.CLOSURE_PAD, release.kind()); - assertFalse(release.isCompleted()); - - MortalList.flushAboveMark(); - - assertEquals(0, referent.refCount); - assertTrue(release.isCompleted()); - MortalList.popMark(); - } - } -} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PerlOwnerSlotReplacementOrderTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlOwnerSlotReplacementOrderTest.java new file mode 100644 index 0000000000..b94691e63c --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlOwnerSlotReplacementOrderTest.java @@ -0,0 +1,89 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +@Tag("unit") +class PerlOwnerSlotReplacementOrderTest { + @Test + void countedSlotAcquiresReplacementBeforeReleasingPreviousReferent() { + List events = new ArrayList<>(); + RecordingArray previous = new RecordingArray("previous", events); + RecordingArray replacement = new RecordingArray("replacement", events); + PerlOwnerSlot slot = new PerlOwnerSlot(PerlOwnerSlot.Kind.SCALAR_CELL); + slot.acquireCountedIdentity(previous); + events.clear(); + + slot.acquireCountedIdentity(replacement); + + assertEquals(List.of("replacement:add", "previous:remove"), events); + assertSame(replacement, slot.referent()); + assertEquals(0, previous.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + assertEquals(1, replacement.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + } + + @Test + void activeLexicalSlotAcquiresReplacementBeforeReleasingPreviousReferent() { + List events = new ArrayList<>(); + RecordingArray previous = new RecordingArray("previous", events); + RecordingArray replacement = new RecordingArray("replacement", events); + PerlOwnerSlot slot = new PerlOwnerSlot(PerlOwnerSlot.Kind.ACTIVE_LEXICAL); + slot.acquireActiveLexicalIdentity(previous); + events.clear(); + + slot.acquireActiveLexicalIdentity(replacement); + + assertEquals(List.of("replacement:add", "previous:remove"), events); + assertSame(replacement, slot.referent()); + assertEquals(0, previous.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + assertEquals(1, replacement.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + } + + @Test + void runtimeRootedTransferRegistersReplacementBeforeReleasingPrevious() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + List events = new ArrayList<>(); + RecordingArray previous = new RecordingArray("previous", events); + RecordingArray replacement = new RecordingArray("replacement", events); + PerlOwnerSlot slot = new PerlOwnerSlot(PerlOwnerSlot.Kind.ARGUMENT_VALUE); + slot.acquireCountedIdentity(previous); + events.clear(); + + slot.transferTo(replacement); + + assertEquals(List.of("replacement:add", "previous:remove"), events); + assertSame(replacement, slot.referent()); + assertEquals(0, previous.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(1, replacement.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + slot.release(); + } + } + + private static final class RecordingArray extends RuntimeArray { + private final String name; + private final List events; + + private RecordingArray(String name, List events) { + this.name = name; + this.events = events; + } + + @Override + synchronized void addOwnerSlot(PerlOwnerSlot slot) { + events.add(name + ":add"); + super.addOwnerSlot(slot); + } + + @Override + synchronized void removeOwnerSlot(PerlOwnerSlot slot) { + events.add(name + ":remove"); + super.removeOwnerSlot(slot); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PerlOwnerSlotScalarReferenceContentsTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlOwnerSlotScalarReferenceContentsTest.java new file mode 100644 index 0000000000..43de753c0a --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlOwnerSlotScalarReferenceContentsTest.java @@ -0,0 +1,132 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class PerlOwnerSlotScalarReferenceContentsTest { + @Test + void referencedCellOverwriteRetargetsTheStableContentsOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash previous = new RuntimeHash(); + RuntimeHash replacement = new RuntimeHash(); + previous.setTrackedRefCount(3); + replacement.setTrackedRefCount(3); + + RuntimeScalar referenceCell = new RuntimeScalar(); + referenceCell.type = RuntimeScalarType.REFERENCE; + referenceCell.value = previous; + referenceCell.setTrackedRefCount(1); + referenceCell.referencedByScalarReference = true; + RuntimeScalar outerReference = new RuntimeScalar(); + outerReference.type = RuntimeScalarType.REFERENCE; + outerReference.value = referenceCell; + outerReference.localBindingExists = true; + PerlOwnerSlot slot = new PerlOwnerSlot( + PerlOwnerSlot.Kind.SCALAR_REFERENCE_CONTENTS); + slot.acquireScalarReferenceContents(previous, referenceCell, outerReference); + outerReference.scalarReferenceContentsOwner = slot; + + RuntimeScalar replacementValue = new RuntimeScalar(); + replacementValue.type = RuntimeScalarType.REFERENCE; + replacementValue.value = replacement; + referenceCell.set(replacementValue); + + assertEquals(3, previous.refCount); + assertEquals(4, replacement.refCount); + assertSame(replacement, slot.referent()); + assertEquals(0, previous.ownerSlotCount( + PerlOwnerSlot.Kind.SCALAR_REFERENCE_CONTENTS)); + assertEquals(1, replacement.ownerSlotCount( + PerlOwnerSlot.Kind.SCALAR_REFERENCE_CONTENTS)); + + outerReference.releaseOwnedScalarReferenceContents(); + assertEquals(3, replacement.refCount); + assertFalse(slot.isActive()); + } + } + + @Test + void aliasesToOneCellShareOneCountAndReleaseIndependently() { + RuntimeHash referent = new RuntimeHash(); + referent.setTrackedRefCount(3); + RuntimeScalar referenceCell = new RuntimeScalar(); + referenceCell.type = RuntimeScalarType.REFERENCE; + referenceCell.value = referent; + RuntimeScalar first = scalarReferenceOwner(referenceCell); + RuntimeScalar second = scalarReferenceOwner(referenceCell); + PerlOwnerSlot firstSlot = new PerlOwnerSlot( + PerlOwnerSlot.Kind.SCALAR_REFERENCE_CONTENTS); + PerlOwnerSlot secondSlot = new PerlOwnerSlot( + PerlOwnerSlot.Kind.SCALAR_REFERENCE_CONTENTS); + + firstSlot.acquireScalarReferenceContents(referent, referenceCell, first); + secondSlot.acquireScalarReferenceContents(referent, referenceCell, second); + first.scalarReferenceContentsOwner = firstSlot; + second.scalarReferenceContentsOwner = secondSlot; + + assertEquals(4, referent.refCount); + assertEquals(2, referent.ownerSlotCount( + PerlOwnerSlot.Kind.SCALAR_REFERENCE_CONTENTS)); + + first.releaseOwnedScalarReferenceContents(); + assertEquals(4, referent.refCount); + assertEquals(1, referent.ownerSlotCount( + PerlOwnerSlot.Kind.SCALAR_REFERENCE_CONTENTS)); + second.releaseOwnedScalarReferenceContents(); + assertEquals(3, referent.refCount); + assertEquals(0, referent.ownerSlotCount( + PerlOwnerSlot.Kind.SCALAR_REFERENCE_CONTENTS)); + } + + @Test + void deferredFinalAliasReleaseCarriesItsOwnerIdentity() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + referent.setTrackedRefCount(3); + RuntimeScalar referenceCell = new RuntimeScalar(); + referenceCell.type = RuntimeScalarType.REFERENCE; + referenceCell.value = referent; + RuntimeScalar owner = scalarReferenceOwner(referenceCell); + PerlOwnerSlot slot = new PerlOwnerSlot( + PerlOwnerSlot.Kind.SCALAR_REFERENCE_CONTENTS); + slot.acquireScalarReferenceContents(referent, referenceCell, owner); + owner.scalarReferenceContentsOwner = slot; + + MortalList.pushMark(); + PerlOwnerSlot.PendingRelease release = slot.deferScalarReferenceContentsRelease(); + owner.scalarReferenceContentsOwner = null; + + assertNotNull(release); + assertEquals(slot.identity(), release.ownerSlotIdentity()); + assertEquals(PerlOwnerSlot.Kind.SCALAR_REFERENCE_CONTENTS, release.kind()); + assertFalse(release.isCompleted()); + assertFalse(slot.isActive()); + assertEquals(4, referent.refCount); + assertEquals(0, referent.ownerSlotCount( + PerlOwnerSlot.Kind.SCALAR_REFERENCE_CONTENTS)); + + MortalList.flushAboveMark(); + + assertEquals(3, referent.refCount); + assertTrue(release.isCompleted()); + MortalList.popMark(); + } + } + + private static RuntimeScalar scalarReferenceOwner(RuntimeScalar referenceCell) { + RuntimeScalar owner = new RuntimeScalar(); + owner.type = RuntimeScalarType.REFERENCE; + owner.value = referenceCell; + owner.localBindingExists = true; + return owner; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PerlOwnerSlotSemanticOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlOwnerSlotSemanticOwnerTest.java new file mode 100644 index 0000000000..e22ce07acd --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlOwnerSlotSemanticOwnerTest.java @@ -0,0 +1,123 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class PerlOwnerSlotSemanticOwnerTest { + @Test + void scalarCellSlotCanAcquireBorrowReplaceAndRelease() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash first = new RuntimeHash(); + RuntimeHash second = new RuntimeHash(); + PerlOwnerSlot slot = new PerlOwnerSlot(PerlOwnerSlot.Kind.SCALAR_CELL); + + slot.acquireNativeOwner(first); + + assertSame(first, slot.borrowReferent()); + assertTrue(slot.isNativeOwner()); + assertEquals(1, first.nativeOwnerSlotCount()); + assertEquals(1, runtime.positiveOwnerSlotReferentCount(first)); + + slot.replaceNativeOwner(second); + + assertEquals(0, first.nativeOwnerSlotCount()); + assertEquals(0, runtime.positiveOwnerSlotReferentCount(first)); + assertSame(second, slot.borrowReferent()); + assertEquals(1, second.nativeOwnerSlotCount()); + assertEquals(1, runtime.positiveOwnerSlotReferentCount(second)); + + slot.release(); + + assertNull(slot.borrowReferent()); + assertFalse(slot.isNativeOwner()); + assertTrue(slot.usesNativeOwnerLedger()); + assertEquals(0, second.nativeOwnerSlotCount()); + assertEquals(0, runtime.positiveOwnerSlotReferentCount(second)); + } + } + + @Test + void eachClosureCaptureOwnsItsScalarPadCellIndependently() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar padCell = new RuntimeScalar(); + + PerlOwnerSlot first = padCell.retainClosureCaptureSlot(); + PerlOwnerSlot second = padCell.retainClosureCaptureSlot(); + + assertNotEquals(first.identity(), second.identity()); + assertEquals(2, padCell.captureCount); + assertTrue(first.isActive()); + assertTrue(second.isActive()); + assertEquals(2, padCell.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE)); + assertEquals(0, runtime.positiveOwnerSlotReferentCount(padCell)); + + padCell.releaseClosureCaptureSlot(first); + + assertEquals(1, padCell.captureCount); + assertFalse(first.isActive()); + assertTrue(second.isActive()); + assertEquals(1, padCell.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE)); + assertFalse(runtime.retainsPositiveOwnerSlotReferent(padCell)); + + padCell.releaseClosureCaptureSlot(second); + + assertEquals(0, padCell.captureCount); + assertFalse(second.isActive()); + assertEquals(0, padCell.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE)); + assertFalse(runtime.retainsPositiveOwnerSlotReferent(padCell)); + } + } + + @Test + void aggregateSlotKindsUseIndependentSemanticOwners() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + PerlOwnerSlot arraySlot = new PerlOwnerSlot(PerlOwnerSlot.Kind.ARRAY_ELEMENT); + PerlOwnerSlot hashSlot = new PerlOwnerSlot(PerlOwnerSlot.Kind.HASH_ELEMENT); + + arraySlot.acquireNativeOwner(referent); + hashSlot.acquireNativeOwner(referent); + + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + assertEquals(2, referent.nativeOwnerSlotCount()); + assertEquals(2, runtime.positiveOwnerSlotReferentCount(referent)); + + arraySlot.release(); + assertEquals(1, referent.nativeOwnerSlotCount()); + assertTrue(runtime.retainsPositiveOwnerSlotReferent(referent)); + + hashSlot.release(); + assertEquals(0, referent.nativeOwnerSlotCount()); + assertFalse(runtime.retainsPositiveOwnerSlotReferent(referent)); + } + } + + @Test + void nativeOwnerCannotReuseADeadReferentOrMigratePendingLegacyReleases() { + RuntimeHash destroyed = new RuntimeHash(); + destroyed.markPerlDestroyed(); + PerlOwnerSlot deadSlot = new PerlOwnerSlot(PerlOwnerSlot.Kind.SCALAR_CELL); + assertThrows(IllegalStateException.class, () -> deadSlot.acquireNativeOwner(destroyed)); + + RuntimeHash live = new RuntimeHash(); + live.setTrackedRefCount(0); + PerlOwnerSlot pendingSlot = new PerlOwnerSlot(PerlOwnerSlot.Kind.CLOSURE_PAD); + pendingSlot.acquireLegacyCapture(live); + assertThrows(IllegalStateException.class, () -> pendingSlot.acquireNativeOwner(live)); + assertEquals(1, live.refCount); + assertEquals(1, pendingSlot.legacyCaptureCount()); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PerlReferentDestroyLifecycleTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlReferentDestroyLifecycleTest.java deleted file mode 100644 index 4da99ae602..0000000000 --- a/src/test/java/org/perlonjava/runtime/runtimetypes/PerlReferentDestroyLifecycleTest.java +++ /dev/null @@ -1,99 +0,0 @@ -package org.perlonjava.runtime.runtimetypes; - -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; - -@Tag("unit") -class PerlReferentDestroyLifecycleTest { - @Test - void blessedDestroyExceptionStillCompletesLifecycle() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - String className = "Issue1649::ThrowingDestroy"; - RuntimeHash referent = new RuntimeHash(); - referent.blessId = NameNormalizer.getBlessId(className); - referent.refCount = Integer.MIN_VALUE; - installDestroy(className, (args, context) -> { - throw new PerlDieException(new RuntimeScalar("destructor failed\n")); - }); - - try { - DestroyDispatch.callDestroy(referent); - assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, - referent.perlLifecycleState()); - assertFalse(referent.currentlyDestroying); - assertEquals(Integer.MIN_VALUE, referent.refCount); - } finally { - GlobalVariable.removeGlobalCodeRefForStashDelete(className + "::DESTROY"); - } - } - } - - @Test - void blessedDestroyCanReenterDispatchWithoutRepeatingTheLifecycle() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - String className = "Issue1649::ReentrantDestroy"; - RuntimeHash referent = new RuntimeHash(); - referent.blessId = NameNormalizer.getBlessId(className); - referent.refCount = Integer.MIN_VALUE; - AtomicReference observed = new AtomicReference<>(); - installDestroy(className, (args, context) -> { - observed.set(referent.perlLifecycleState()); - DestroyDispatch.callDestroy(referent); - return new RuntimeScalar().getList(); - }); - - try { - DestroyDispatch.callDestroy(referent); - assertEquals(RuntimeBase.PerlLifecycleState.DESTROYING, observed.get()); - assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState()); - } finally { - GlobalVariable.removeGlobalCodeRefForStashDelete(className + "::DESTROY"); - } - } - } - - @Test - void rescuedBlessedReferentMovesFromResurrectedToDestroyed() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - String className = "Issue1649::ResurrectedDestroy"; - RuntimeHash referent = new RuntimeHash(); - referent.blessId = NameNormalizer.getBlessId(className); - referent.refCount = Integer.MIN_VALUE; - installDestroy(className, (args, context) -> { - referent.refCount++; - DestroyDispatch.markDestroyTargetRescued(); - return new RuntimeScalar().getList(); - }); - - try { - DestroyDispatch.callDestroy(referent); - assertEquals(RuntimeBase.PerlLifecycleState.RESURRECTED, - referent.perlLifecycleState()); - assertEquals(1, referent.refCount); - - DestroyDispatch.processRescuedObjects(); - - assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, - referent.perlLifecycleState()); - } finally { - GlobalVariable.removeGlobalCodeRefForStashDelete(className + "::DESTROY"); - } - } - } - - private static void installDestroy(String className, PerlSubroutine body) { - RuntimeCode code = new RuntimeCode(body, null); - int separator = className.lastIndexOf("::"); - code.packageName = className.substring(0, separator); - code.subName = className.substring(separator + 2); - GlobalVariable.getGlobalCodeRef(className + "::DESTROY").set(new RuntimeScalar(code)); - } -} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PerlReferentLifecycleStateTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlReferentLifecycleStateTest.java deleted file mode 100644 index 2c36dffcc8..0000000000 --- a/src/test/java/org/perlonjava/runtime/runtimetypes/PerlReferentLifecycleStateTest.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.perlonjava.runtime.runtimetypes; - -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -@Tag("unit") -class PerlReferentLifecycleStateTest { - @Test - void lifecycleTransitionsAreIndependentFromTheSelectiveCountSentinel() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeHash referent = new RuntimeHash(); - assertEquals(RuntimeBase.PerlLifecycleState.LIVE, referent.perlLifecycleState()); - - referent.beginPerlDestruction(); - assertEquals(RuntimeBase.PerlLifecycleState.DESTROYING, referent.perlLifecycleState()); - - referent.markPerlResurrected(); - assertEquals(RuntimeBase.PerlLifecycleState.RESURRECTED, referent.perlLifecycleState()); - - referent.beginPerlDestruction(); - referent.markPerlDestroyed(); - assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState()); - assertEquals(-1, referent.refCount, - "the explicit lifecycle state does not encode refCount sentinels"); - } - } - - @Test - void destroyDispatchRecordsFinalUnblessedLifecycleSeparately() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeHash referent = new RuntimeHash(); - referent.refCount = 0; - - DestroyDispatch.callDestroy(referent); - - assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState()); - assertEquals(0, referent.refCount, - "lifecycle completion is represented without rewriting the selective count"); - - DestroyDispatch.callDestroy(referent); - assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState()); - assertEquals(0, referent.refCount, "completed lifecycle ignores repeated destroy dispatch"); - } - } -} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PerlReturnOwnerConsumptionTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlReturnOwnerConsumptionTest.java new file mode 100644 index 0000000000..9a4ed29ef2 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlReturnOwnerConsumptionTest.java @@ -0,0 +1,95 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class PerlReturnOwnerConsumptionTest { + @Test + void nestedNoDestroyCleanupLeavesCallerReturnOwnerPending() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + String returnedClass = "Issue1649::PendingReturnOwner"; + String cleanupClass = "Issue1649::NoDestroyCleanup"; + AtomicInteger destroyCalls = new AtomicInteger(); + RuntimeCode destroy = new RuntimeCode((args, context) -> { + destroyCalls.incrementAndGet(); + return new RuntimeScalar().getList(); + }, null); + destroy.packageName = "Issue1649"; + destroy.subName = "DESTROY"; + GlobalVariable.getGlobalCodeRef(returnedClass + "::DESTROY") + .set(new RuntimeScalar(destroy)); + + try { + RuntimeHash returnedReferent = new RuntimeHash(); + returnedReferent.blessId = NameNormalizer.getBlessId(returnedClass); + RuntimeScalar source = new RuntimeScalar(); + source.type = RuntimeScalarType.HASHREFERENCE; + source.value = returnedReferent; + RuntimeScalar returned = RuntimeScalar.copyToMortalReturnSlot(source); + + RuntimeHash unrelated = new RuntimeHash(); + unrelated.blessId = NameNormalizer.getBlessId(cleanupClass); + unrelated.setTrackedRefCount(0); + DestroyDispatch.callDestroy(unrelated); + + assertEquals(1, returnedReferent.refCount, + "unrelated no-DESTROY cleanup must leave the return decrement pending"); + assertTrue(returnedReferent.hasPendingReturnOwner()); + assertEquals(0, destroyCalls.get()); + + RuntimeScalar receiver = new RuntimeScalar(); + receiver.set(returned); + assertFalse(returnedReferent.hasPendingReturnOwner()); + assertEquals(1, returnedReferent.refCount, + "the receiver replaces the temporary return owner"); + assertEquals(0, destroyCalls.get()); + + receiver.set(new RuntimeScalar()); + MortalList.flushAboveMark(); + assertEquals(1, destroyCalls.get(), + "the receiver's final release dispatches DESTROY once"); + } finally { + GlobalVariable.removeGlobalCodeRefForStashDelete(returnedClass + "::DESTROY"); + } + } + } + + @Test + void receivingReturnConsumesOnlyItsReturnAndRetiredSourceEdges() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar source = new RuntimeScalar(); + RuntimeScalar unrelated = new RuntimeScalar(); + source.set(referent.createAnonymousReference()); + unrelated.set(referent.createAnonymousReference()); + PerlOwnerSlot unrelatedOwner = unrelated.countedOwnerSlot(); + + RuntimeList returned = RuntimeCode.coerceScalarCallResult( + source.getList(), RuntimeContextType.SCALAR); + RuntimeScalar returnValue = (RuntimeScalar) returned.elements.getFirst(); + MortalList.deferDecrementIfTracked(source); + MortalList.deferDecrementIfTracked(unrelated); + + RuntimeScalar receiver = new RuntimeScalar(); + receiver.set(returnValue); + + assertEquals(2, referent.refCount, + "the receiving cell and unrelated live edge remain counted"); + assertFalse(referent.hasPendingReturnOwner()); + assertTrue(receiver.refCountOwned); + assertFalse(unrelated.refCountOwned); + assertEquals(1, runtime.lifecycleState.pendingOwnerReleases.size()); + assertEquals(unrelatedOwner.identity(), runtime.lifecycleState + .pendingOwnerReleases.getFirst().ownerSlotRelease.ownerSlotIdentity()); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PerlStrongOwnerProofTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlStrongOwnerProofTest.java new file mode 100644 index 0000000000..442e3ed434 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PerlStrongOwnerProofTest.java @@ -0,0 +1,84 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class PerlStrongOwnerProofTest { + @Test + void indexesSemanticOwnerSlotsAndExcludesTemporaryRoots() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash target = new RuntimeHash(); + assertFalse(target.hasOwnerSlots()); + assertFalse(target.hasPerlStrongOwnerIdentity()); + + PerlOwnerSlot temporaryOwner = new PerlOwnerSlot(PerlOwnerSlot.Kind.TEMPORARY_ROOT); + temporaryOwner.acquireTemporaryRootIdentity(target); + try { + assertFalse(target.hasOwnerSlots(), + "temporary roots are not semantic Perl owner slots"); + assertFalse(target.hasPerlStrongOwnerIdentity()); + } finally { + temporaryOwner.release(); + } + + PerlOwnerSlot first = new PerlOwnerSlot(PerlOwnerSlot.Kind.SCALAR_CAPTURE); + PerlOwnerSlot second = new PerlOwnerSlot(PerlOwnerSlot.Kind.SCALAR_CAPTURE); + first.acquireCaptureIdentity(target); + second.acquireCaptureIdentity(target); + assertTrue(target.hasOwnerSlots()); + assertTrue(target.hasPerlStrongOwnerIdentity()); + + first.release(); + assertTrue(target.hasOwnerSlots(), "one live identity remains"); + assertTrue(target.hasPerlStrongOwnerIdentity()); + + second.release(); + assertFalse(target.hasOwnerSlots()); + assertFalse(target.hasPerlStrongOwnerIdentity()); + } + } + + @Test + void excludesTemporaryRootsButAcceptsCountedAndUntrackedOwners() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash target = new RuntimeHash(); + assertFalse(target.hasPerlStrongOwner()); + + PerlOwnerSlot temporaryOwner = new PerlOwnerSlot(PerlOwnerSlot.Kind.TEMPORARY_ROOT); + temporaryOwner.acquireTemporaryRootIdentity(target); + try { + assertFalse(target.hasPerlStrongOwner(), + "a temporary evaluation root is not a Perl owner"); + } finally { + temporaryOwner.release(); + } + + RuntimeScalar countedOwner = new RuntimeScalar(); + countedOwner.set(target.createAnonymousReference()); + assertTrue(target.hasPerlStrongOwner()); + countedOwner.set(new RuntimeScalar()); + assertFalse(target.hasPerlStrongOwner()); + + RuntimeHash untrackedTarget = new RuntimeHash(); + RuntimeArray container = new RuntimeArray(); + RuntimeScalar untrackedOwner = referenceTo(untrackedTarget); + container.elements.add(untrackedOwner); + untrackedOwner.markContainerOwner(container); + untrackedOwner.refreshUntrackedReferenceOwner(); + assertTrue(untrackedTarget.hasPerlStrongOwner()); + untrackedOwner.set(new RuntimeScalar()); + assertFalse(untrackedTarget.hasPerlStrongOwner()); + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.REFERENCE; + scalar.value = referent; + return scalar; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/PromotedUntrackedOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/PromotedUntrackedOwnerSlotTest.java new file mode 100644 index 0000000000..8987b7e57a --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/PromotedUntrackedOwnerSlotTest.java @@ -0,0 +1,89 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class PromotedUntrackedOwnerSlotTest { + @Test + void scalarInUnownedTemporaryArrayDoesNotPinPromotedReferent() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar target = new RuntimeScalar("temporary array referent"); + RuntimeScalar element = referenceTo(target); + RuntimeArray temporaryArray = new RuntimeArray(); + temporaryArray.elements.add(element); + element.markContainerOwner(temporaryArray); + element.refreshUntrackedReferenceOwner(); + PerlOwnerSlot ownerSlot = element.untrackedReferenceOwnerSlot(); + assertNotNull(ownerSlot); + + target.setTrackedRefCount(0); + + assertFalse(target.hasUntrackedReferenceOwnerSlotIdentity()); + assertFalse(ownerSlot.isActive(), + "a temporary container without a Perl owner must not retain the referent"); + assertEquals(0, target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + } + } + + @Test + void durableUncountedPackageValueSurvivesReferentPromotionAndFinalCountedRelease() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar target = new RuntimeScalar("promoted referent"); + RuntimeScalar packageOwner = referenceTo(target); + String globalName = "PromotedUntrackedOwnerSlotTest::packageOwner"; + GlobalVariable.globalVariables.put(globalName, packageOwner); + PerlOwnerSlot ownerSlot = packageOwner.untrackedReferenceOwnerSlot(); + assertNotNull(ownerSlot, + "a durable owner without a count needs an owner-slot identity"); + assertEquals(target, ownerSlot.referent()); + + RuntimeScalar countedOwner = new RuntimeScalar(); + countedOwner.set(target.createReference()); + packageOwner.refreshUntrackedReferenceOwner(); + RuntimeScalar weak = target.createReference(); + WeakRefRegistry.weaken(weak); + + try { + assertEquals(1, target.refCount, + "a later counted store promotes the referent independently"); + assertTrue(ownerSlot.isActive(), + "promotion must not retire the earlier uncounted Perl slot"); + + { + countedOwner.set(new RuntimeScalar()); + + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState()); + assertTrue(WeakRefRegistry.isweak(weak), + "the surviving package scalar keeps the weak referent alive"); + } + + GlobalVariable.globalVariables.remove(globalName); + + assertFalse(ownerSlot.isActive()); + assertFalse(WeakRefRegistry.isweak(weak)); + assertEquals(RuntimeScalarType.UNDEF, weak.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, target.perlLifecycleState()); + assertEquals(0, target.refCount); + } finally { + GlobalVariable.globalVariables.remove(globalName); + if (WeakRefRegistry.isweak(weak)) WeakRefRegistry.unweaken(weak); + countedOwner.set(new RuntimeScalar()); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar reference = new RuntimeScalar(); + reference.type = RuntimeScalarType.REFERENCE; + reference.value = referent; + return reference; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilityQueryCostTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilityQueryCostTest.java deleted file mode 100644 index d24797810d..0000000000 --- a/src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilityQueryCostTest.java +++ /dev/null @@ -1,502 +0,0 @@ -package org.perlonjava.runtime.runtimetypes; - -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import java.util.AbstractMap; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Set; -import java.util.ArrayList; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Tag("unit") -class ReachabilityQueryCostTest { - private static final class CountingStashMap extends AbstractMap { - private int valuesCalls; - - @Override - public Set> entrySet() { - return Collections.emptySet(); - } - - @Override - public Collection values() { - valuesCalls++; - return Collections.emptyList(); - } - } - - @Test - void repeatedContainerScopeCleanupDoesNotEnumerateNestedStashRoots() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeStash stash = new RuntimeStash("ReachabilityQueryCostTest::"); - CountingStashMap stashView = new CountingStashMap(); - stash.elements = stashView; - ((RuntimeHash) stash).elements = stashView; - - for (int i = 0; i < 3; i++) { - RuntimeArray container = new RuntimeArray(); - container.elements.add(stash.createReference()); - - assertFalse(MortalList.requestWeakSweepsForDestroyedContainer(container)); - } - - assertEquals(0, stashView.valuesCalls, - "scope cleanup must not enumerate dynamic stash entries on each container walk"); - } - } - - @Test - void scopeExitedCaptureOwnersShareOneScalarRootSnapshot() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - ArrayList candidates = new ArrayList<>(); - for (int i = 0; i < 8; i++) { - RuntimeHash referent = new RuntimeHash(); - RuntimeScalar padCell = referent.createReference(); - padCell.retainClosureCapture(); - padCell.scopeExited = true; - candidates.add(referent); - } - - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - ReachabilityWalker.releaseUnreachableScopeExitedCaptureOwners( - candidates, null); - - ReachabilityQueryStats stats = measurement.stats(); - assertEquals(1, stats.scalarReachabilityRootWalks, - "one scalar-root walk should cover all stale capture owners"); - assertEquals(1, stats.snapshotsBuilt); - } - } - } - - @Test - void targetedWeakReleaseSkipsFullWalkerForSnapshotRootedTargets() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray global = new RuntimeArray(); - String globalName = - "ReachabilityQueryCostTest::targetedWeakReleaseSnapshot"; - GlobalVariable.globalArrays.put(globalName, global); - - RuntimeHash[] targets = new RuntimeHash[8]; - RuntimeScalar[] weakRefs = new RuntimeScalar[targets.length]; - Set released = Collections.newSetFromMap( - new java.util.IdentityHashMap<>()); - for (int i = 0; i < targets.length; i++) { - RuntimeHash target = new RuntimeHash(); - RuntimeScalar strong = target.createReference(); - RuntimeScalar weak = target.createReference(); - WeakRefRegistry.weaken(weak); - global.elements.add(strong); - target.refCount = 0; - targets[i] = target; - weakRefs[i] = weak; - released.add(target); - } - - try { - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - ReachabilityWalker.sweepReleasedWeakReferents(released); - - ReachabilityQueryStats stats = measurement.stats(); - assertEquals(0, stats.snapshotsBuilt, - "positive package-root proofs should avoid the full weak sweep walker"); - assertEquals(1, stats.externalRootSnapshotsBuilt, - "the package-root graph is snapshotted once for the whole batch"); - for (int i = 0; i < targets.length; i++) { - assertTrue(WeakRefRegistry.isweak(weakRefs[i])); - assertTrue(targets[i].refCount != Integer.MIN_VALUE); - } - } - } finally { - for (RuntimeScalar weak : weakRefs) { - if (weak != null) WeakRefRegistry.unweaken(weak); - } - GlobalVariable.globalArrays.remove(globalName); - MortalList.invalidateAllRootSnapshots(); - } - } - } - - @Test - void targetedWeakReleaseDoesNotTreatTemporaryRootsAsPersistentOwners() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray target = new RuntimeArray(); - RuntimeScalar weak = target.createReference(); - WeakRefRegistry.weaken(weak); - target.refCount = 0; - target.localBindingExists = false; - MortalList.pushTemporaryRoot(target); - - try { - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - ReachabilityWalker.sweepReleasedWeakReferents( - Collections.singleton(target)); - - assertEquals(RuntimeScalarType.UNDEF, weak.type, - "temporary roots do not keep a released weak referent alive"); - assertEquals(1, measurement.stats().externalRootSnapshotsBuilt, - "the temporary-only target must miss the persistent-root snapshot proof"); - } - } finally { - MortalList.popTemporaryRoot(target); - WeakRefRegistry.unweaken(weak); - } - } - } - - @Test - void scalarOnlyMutationReusesTheAggregateRootSnapshot() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray global = new RuntimeArray(); - RuntimeHash first = new RuntimeHash(); - RuntimeHash second = new RuntimeHash(); - global.elements.add(first.createReference()); - global.elements.add(second.createReference()); - global.elements.add(new RuntimeScalar("before")); - String globalName = "ReachabilityQueryCostTest::scalarOnlyMutation"; - GlobalVariable.globalArrays.put(globalName, global); - - try { - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - assertTrue(MortalList.isUnblessedAggregateReachableDuringDrain(first)); - global.elements.set(2, new RuntimeScalar("after")); - assertTrue(MortalList.isUnblessedAggregateReachableDuringDrain(second)); - - assertEquals(1, measurement.stats().externalRootSnapshotsBuilt, - "changing a scalar leaf does not change the aggregate root graph"); - } - } finally { - GlobalVariable.globalArrays.remove(globalName); - MortalList.invalidateAllRootSnapshots(); - } - } - } - - @Test - void capturedAggregateOwnerReleaseDoesNotScanUnrelatedRoots() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray global = new RuntimeArray(); - String globalName = "ReachabilityQueryCostTest::captureGlobal"; - GlobalVariable.globalArrays.put(globalName, global); - try { - for (int i = 0; i < 256; i++) { - global.elements.add(new RuntimeHash().createReference()); - } - - RuntimeArray captured = new RuntimeArray(); - PerlOwnerSlot owner = captured.retainClosureCaptureOwner(); - captured.scopeExited = true; - - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - captured.releaseClosureCaptureOwner(owner); - - ReachabilityQueryStats stats = measurement.stats(); - assertEquals(0, stats.rootQueries, - "native captured-pad release must use its owner slot, not a root proof"); - assertEquals(0, stats.snapshotsBuilt); - assertEquals(0, stats.externalRootSnapshotsBuilt); - assertEquals(0, stats.edgesInspected, - "unrelated package roots must not add cleanup work"); - assertEquals(0, stats.externalRootSnapshotEdgesInspected); - assertEquals(0, captured.semanticCaptureOwnerCount()); - } - } finally { - GlobalVariable.globalArrays.remove(globalName); - } - } - } - - @Test - void repeatedAggregateScopeCleanupSharesExternalRootSnapshot() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray global = new RuntimeArray(); - for (int i = 0; i < 256; i++) { - global.elements.add(new RuntimeHash().createReference()); - } - String globalName = "ReachabilityQueryCostTest::global"; - GlobalVariable.globalArrays.put(globalName, global); - - RuntimeHash[] targets = new RuntimeHash[3]; - RuntimeScalar[] weakRefs = new RuntimeScalar[targets.length]; - for (int i = 0; i < targets.length; i++) { - RuntimeHash target = new RuntimeHash(); - MyVarCleanupStack.register(target); - RuntimeScalar weak = target.createReference(); - WeakRefRegistry.weaken(weak); - target.refCount = 0; - target.clearedOwnedAggregateElement = true; - targets[i] = target; - weakRefs[i] = weak; - } - MortalList.invalidateAllRootSnapshots(); - - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - for (RuntimeHash target : targets) { - MyVarCleanupStack.unregister(target); - - assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, - target.perlLifecycleState()); - } - - ReachabilityQueryStats stats = measurement.stats(); - assertEquals(0, stats.rootQueries, - "scope cleanup should use the cached package-root snapshot"); - assertEquals(1, stats.externalRootSnapshotsBuilt, - "unchanged package roots should be traversed once across scope exits"); - assertTrue(stats.externalRootSnapshotEdgesInspected >= 256, - "the shared snapshot must account for the unrelated root array edges"); - assertTrue(stats.externalRootSnapshotNodesVisited >= 257, - "the shared snapshot visits the root array and its children once"); - } finally { - for (RuntimeScalar weak : weakRefs) { - if (weak != null) WeakRefRegistry.unweaken(weak); - } - GlobalVariable.globalArrays.remove(globalName); - MortalList.invalidateAllRootSnapshots(); - } - } - } - - @Test - void repeatedDeferredCleanupCountsExternalRootSnapshotWork() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray global = new RuntimeArray(); - String globalName = "ReachabilityQueryCostTest::deferredGlobal"; - GlobalVariable.globalArrays.put(globalName, global); - try { - for (int i = 0; i < 256; i++) { - global.elements.add(new RuntimeHash().createReference()); - } - - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - for (int i = 0; i < 3; i++) { - RuntimeHash target = new RuntimeHash(); - target.blessId = NameNormalizer.getBlessId( - "Issue1649::DeferredRootTarget"); - global.elements.add(target.createAnonymousReference()); - RuntimeScalar weak = target.createAnonymousReference(); - WeakRefRegistry.weaken(weak); - target.refCount = 1; - - MortalList.deferDecrement(target); - MortalList.flush(); - - assertEquals(1, target.refCount, - "a strong package-root edge must protect the weak target"); - } - - ReachabilityQueryStats stats = measurement.stats(); - assertEquals(3, stats.deferredBasesProcessed, - "each deferred release must reach processDeferredBase"); - assertEquals(3, stats.externalRootSnapshotsBuilt, - "each separate flush rebuilds the external-root graph"); - assertTrue(stats.externalRootSnapshotEdgesInspected >= 3 * 256, - "each deferred cleanup re-inspects the unrelated root array"); - assertTrue(stats.externalRootSnapshotNodesVisited >= 3 * 257, - "each deferred cleanup revisits the root and its 256 children"); - } - } finally { - GlobalVariable.globalArrays.remove(globalName); - } - } - } - - @Test - void unchangedPackageRootsReuseExternalSnapshotAcrossDrains() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray global = new RuntimeArray(); - String globalName = - "ReachabilityQueryCostTest::stableDeferredGlobal"; - GlobalVariable.globalArrays.put(globalName, global); - RuntimeHash[] targets = new RuntimeHash[4]; - RuntimeScalar[] weakRefs = new RuntimeScalar[targets.length]; - - try { - for (int i = 0; i < 3; i++) { - targets[i] = new RuntimeHash(); - targets[i].blessId = NameNormalizer.getBlessId( - "Issue1642::StableDeferredRootTarget"); - global.elements.add(targets[i].createAnonymousReference()); - weakRefs[i] = targets[i].createAnonymousReference(); - WeakRefRegistry.weaken(weakRefs[i]); - targets[i].refCount = 1; - } - MortalList.invalidateAllRootSnapshots(); - - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - for (int i = 0; i < 3; i++) { - MortalList.deferDecrement(targets[i]); - MortalList.flush(); - - assertEquals(1, targets[i].refCount, - "a stable package-root edge protects each target"); - } - - ReachabilityQueryStats stats = measurement.stats(); - assertEquals(3, stats.deferredBasesProcessed); - assertEquals(1, stats.externalRootSnapshotsBuilt, - "separate drains reuse the external-root snapshot while roots stay unchanged"); - long edgesBeforeMutation = stats.externalRootSnapshotEdgesInspected; - - targets[3] = new RuntimeHash(); - targets[3].blessId = NameNormalizer.getBlessId( - "Issue1642::StableDeferredRootTarget"); - weakRefs[3] = targets[3].createAnonymousReference(); - WeakRefRegistry.weaken(weakRefs[3]); - targets[3].refCount = 1; - global.elements.add(targets[3].createAnonymousReference()); - - MortalList.deferDecrement(targets[3]); - MortalList.flush(); - - assertEquals(1, targets[3].refCount, - "a new package-root edge protects the target after invalidation"); - assertEquals(4, stats.deferredBasesProcessed); - assertEquals(2, stats.externalRootSnapshotsBuilt, - "a package-root mutation invalidates the reused snapshot"); - assertTrue(stats.externalRootSnapshotEdgesInspected > edgesBeforeMutation, - "the rebuilt snapshot inspects the changed root graph"); - } - } finally { - for (RuntimeScalar weakRef : weakRefs) { - if (weakRef != null) WeakRefRegistry.unweaken(weakRef); - } - GlobalVariable.globalArrays.remove(globalName); - MortalList.invalidateAllRootSnapshots(); - } - } - } - - @Test - void unchangedPackageRootsReuseSnapshotAndLexicalMutationRefreshesLiveRoots() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray global = new RuntimeArray(); - RuntimeArray lexicalRoot = new RuntimeArray(); - RuntimeScalar weakProbe = new RuntimeHash().createAnonymousReference(); - String globalName = - "ReachabilityQueryCostTest::stableFullSnapshotGlobal"; - GlobalVariable.globalArrays.put(globalName, global); - MyVarCleanupStack.register(lexicalRoot); - WeakRefRegistry.weaken(weakProbe); - try { - for (int i = 0; i < 256; i++) { - global.elements.add(new RuntimeHash().createReference()); - } - MortalList.invalidateAllRootSnapshots(); - - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - for (int i = 0; i < 3; i++) { - RuntimeArray target = new RuntimeArray(); - target.refCount = 1; - target.localBindingExists = false; - target.clearedOwnedAggregateElement = true; - - MortalList.deferDecrement(target); - MortalList.flush(); - - assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, - target.perlLifecycleState(), - "an unrooted aggregate should be reclaimed"); - } - - ReachabilityQueryStats stats = measurement.stats(); - assertEquals(3, stats.deferredBasesProcessed); - assertEquals(1, stats.liveRootSnapshotsBuilt, - "unchanged lexical roots should share one snapshot across drains"); - RuntimeArray nextTarget = new RuntimeArray(); - lexicalRoot.elements.add(nextTarget.createReference()); - assertTrue(MortalList.isReachableFromExternalRootCached(nextTarget), - "a lexical edge mutation must refresh the live-root snapshot"); - assertEquals(1, stats.externalRootSnapshotsBuilt, - "unchanged package roots should share one snapshot across drains"); - assertEquals(2, stats.liveRootSnapshotsBuilt, - "a lexical edge mutation must build a fresh live-root snapshot"); - assertTrue(stats.externalRootSnapshotNodesVisited >= 257, - "the shared package-root snapshot must account for its graph walk"); - } - } finally { - WeakRefRegistry.unweaken(weakProbe); - MyVarCleanupStack.unregister(lexicalRoot); - GlobalVariable.globalArrays.remove(globalName); - MortalList.invalidateAllRootSnapshots(); - } - } - } - - @Test - void deferredOwnerChecksShareOneRootSnapshotPerDrain() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray global = new RuntimeArray(); - RuntimeArray nestedOwners = new RuntimeArray(); - global.elements.add(nestedOwners.createReference()); - for (int i = 0; i < 256; i++) { - global.elements.add(new RuntimeHash().createReference()); - } - String globalName = "ReachabilityQueryCostTest::nestedOwnerGlobal"; - GlobalVariable.globalArrays.put(globalName, global); - - try { - MortalList.pushMark(); - RuntimeHash[] targets = new RuntimeHash[3]; - for (int i = 0; i < targets.length; i++) { - RuntimeHash target = new RuntimeHash(); - target.activateOwnerTracking(); - RuntimeScalar owner = target.createAnonymousReference(); - RuntimeScalar.incrementRefCountForContainerStore(owner); - nestedOwners.elements.add(owner); - RuntimeScalar weak = target.createAnonymousReference(); - WeakRefRegistry.weaken(weak); - targets[i] = target; - MortalList.deferDecrement(target); - } - - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - MortalList.popAndFlush(); - - ReachabilityQueryStats stats = measurement.stats(); - assertEquals(3, stats.deferredBasesProcessed); - assertEquals(3, stats.scalarReachabilityQueries, - "each deferred referent still validates its counted owner"); - assertEquals(0, stats.scalarReachabilityRootWalks, - "owner scalars below one package root reuse the drain snapshot"); - assertEquals(1, stats.snapshotsBuilt, - "the first nested owner builds one snapshot for the whole drain"); - for (RuntimeHash target : targets) { - assertEquals(1, target.refCount, - "a strong package-root path preserves the weak target"); - } - } - } finally { - GlobalVariable.globalArrays.remove(globalName); - MortalList.invalidateAllRootSnapshots(); - } - } - } -} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilitySnapshotCompletenessTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilitySnapshotCompletenessTest.java deleted file mode 100644 index 5319ea6459..0000000000 --- a/src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilitySnapshotCompletenessTest.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.perlonjava.runtime.runtimetypes; - -import java.lang.reflect.Method; -import java.util.Collections; -import java.util.List; - -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Tag("unit") -class ReachabilitySnapshotCompletenessTest { - @Test - void cappedRootSnapshotsCannotProveAnUnseenTargetUnreachable() throws Exception { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray root = new RuntimeArray(); - ArrayChain chain = appendChain(root); - RuntimeArray tail = chain.tail(); - String globalName = - "ReachabilitySnapshotCompletenessTest::global"; - GlobalVariable.globalArrays.put(globalName, root); - MyVarCleanupStack.register(root); - MyVarCleanupStack.snapshotStackToLiveCounts(); - - LifecycleRuntimeState state = runtime.lifecycleState; - try { - ReachabilityWalker.ExternalRootSnapshot external; - ReachabilityWalker.ScalarRootReachabilitySnapshot scalars; - ReachabilityWalker.LiveRootSnapshot live = - new ReachabilityWalker.LiveRootSnapshot(); - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - external = new ReachabilityWalker.ExternalRootSnapshot(false); - scalars = ReachabilityWalker.scalarReachabilitySnapshot(); - assertEquals(50_000L, - measurement.stats().externalRootSnapshotNodesVisited, - "the external snapshot reaches its visit cap"); - assertEquals(50_000L, measurement.stats().nodesVisited, - "the scalar snapshot reaches its visit cap"); - } - - assertFalse(external.complete(), "the external snapshot records truncation"); - assertFalse(live.complete(), "the live snapshot records truncation"); - assertFalse(scalars.complete(), "the scalar snapshot records truncation"); - assertTrue(external.isReachable(tail), - "an incomplete external snapshot cannot prove a miss"); - assertTrue(live.isReachable(tail), - "an incomplete lexical snapshot cannot prove a miss"); - assertTrue(scalars.isReachable(chain.tailOwner()), - "an incomplete scalar snapshot cannot prove an owner miss"); - state.scalarRootSnapshot = scalars; - state.reachabilityDrainDepth++; - try { - assertTrue(MortalList.isScalarReachableFromDrainSnapshot( - chain.tailOwner()), - "the cleanup drain cannot treat an incomplete scalar snapshot as a miss"); - } finally { - state.reachabilityDrainDepth--; - } - assertTrue(ReachabilityWalker.isScalarReachable(chain.tailOwner()), - "a capped scalar walk cannot prove an owner unreachable"); - assertTrue(ReachabilityWalker.isReachableFromLiveScalarRegistry( - tail, List.of(root.createReference())), - "a capped live-scalar registry walk cannot prove a target unreachable"); - assertTrue(ReachabilityWalker.isReachableFromRoots(tail, true), - "a capped general root walk cannot prove a target unreachable"); - assertTrue(ReachabilityWalker - .isReachableFromExternalRootExcludingDirectLexical(tail), - "a capped external-root walk cannot prove a target unreachable"); - ReachabilityWalker.TiedHashReachabilitySnapshot tiedSnapshot = - ReachabilityWalker.reachableThroughTiedHashes(); - assertFalse(tiedSnapshot.complete(), - "the tied-hash snapshot records the visit cap"); - assertTrue(tiedSnapshot.contains(tail), - "an incomplete tied-hash snapshot cannot prove a miss"); - - state.externalRootSnapshot = external; - state.liveRootSnapshot = live; - state.fullRootSnapshot = new ReachabilityWalker.RootReachabilitySnapshot( - Collections.emptySet(), true, - ReachabilityWalker.MAX_ROOT_SNAPSHOT_EDGES); - Method cachedQuery = MortalList.class.getDeclaredMethod( - "isReachableFromExternalRootCached", RuntimeBase.class); - cachedQuery.setAccessible(true); - assertTrue((boolean) cachedQuery.invoke(null, tail), - "the cached cleanup query conservatively retains misses without " - + "a second full-root snapshot"); - } finally { - MyVarCleanupStack.unregister(root); - GlobalVariable.globalArrays.remove(globalName); - MortalList.invalidateAllRootSnapshots(); - } - } - } - - private static ArrayChain appendChain(RuntimeArray root) { - RuntimeArray parent = root; - RuntimeScalar lastOwner = null; - for (int i = 0; i < 50_001; i++) { - RuntimeArray child = new RuntimeArray(); - lastOwner = child.createAnonymousReference(); - parent.elements.add(lastOwner); - parent = child; - } - return new ArrayChain(parent, lastOwner); - } - - private record ArrayChain(RuntimeArray tail, RuntimeScalar tailOwner) {} -} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilityWalker.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilityWalker.java new file mode 100644 index 0000000000..486ca3915a --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilityWalker.java @@ -0,0 +1,132 @@ +package org.perlonjava.runtime.runtimetypes; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Set; + +/** Test-only diagnostic traversal for temporary-root owner-path assertions. */ +final class ReachabilityWalker { + static final int MAX_ROOT_SNAPSHOT_EDGES = 50_000; + + static final class RootReachabilitySnapshot { + private final Set reachable; + private final boolean complete; + private final int edgesVisited; + + private RootReachabilitySnapshot(Set reachable, + boolean complete, + int edgesVisited) { + this.reachable = reachable; + this.complete = complete; + this.edgesVisited = edgesVisited; + } + + boolean complete() { + return complete; + } + + boolean isReachable(RuntimeBase target) { + return target != null && (reachable.contains(target) || !complete); + } + + int edgesVisited() { + return edgesVisited; + } + } + + static boolean isReachableFromTemporaryRoots(RuntimeBase target) { + if (target == null) return false; + ArrayList roots = new ArrayList<>(); + for (LifecycleRuntimeState.TemporaryRootLease lease + : PerlRuntime.current().lifecycleState.temporaryRoots) { + roots.add(lease.root()); + } + return walk(roots).isReachable(target); + } + + static RootReachabilitySnapshot reachableFromRootsSnapshotWithStatus() { + ArrayList roots = new ArrayList<>(); + roots.addAll(GlobalVariable.globalVariables.values()); + roots.addAll(GlobalVariable.globalArrays.values()); + roots.addAll(GlobalVariable.globalHashes.values()); + for (LifecycleRuntimeState.TemporaryRootLease lease + : PerlRuntime.current().lifecycleState.temporaryRoots) { + roots.add(lease.root()); + } + return walk(roots); + } + + private static RootReachabilitySnapshot walk(List roots) { + Set reachable = + Collections.newSetFromMap(new IdentityHashMap<>()); + ArrayDeque pending = new ArrayDeque<>(); + for (RuntimeBase root : roots) { + if (root != null) pending.addLast(root); + } + + int edgesVisited = 0; + boolean complete = true; + while (!pending.isEmpty() && complete) { + RuntimeBase current = pending.removeFirst(); + if (current == null || !reachable.add(current)) continue; + + ArrayList children = childrenOf(current); + for (RuntimeBase child : children) { + if (child == null) continue; + if (edgesVisited == MAX_ROOT_SNAPSHOT_EDGES) { + complete = false; + break; + } + edgesVisited++; + pending.addLast(child); + } + } + return new RootReachabilitySnapshot(reachable, complete, edgesVisited); + } + + private static ArrayList childrenOf(RuntimeBase value) { + ArrayList children = new ArrayList<>(); + if (value instanceof RuntimeScalar scalar) { + if (!WeakRefRegistry.isweak(scalar) + && (scalar.type & RuntimeScalarType.REFERENCE_BIT) != 0 + && scalar.value instanceof RuntimeBase referent) { + children.add(referent); + } + if (scalar instanceof RuntimeBaseProxy proxy && proxy.lvalue != null) { + children.add(proxy.lvalue); + } + } + if (value instanceof RuntimeArray array) { + if (array.elements != null) children.addAll(array.elements); + if (array.ownedAliasElements != null) children.addAll(array.ownedAliasElements); + } else if (value instanceof RuntimeHash hash) { + if (hash.elements != null && !(hash.elements instanceof HashSpecialVariable)) { + for (java.util.Map.Entry entry + : hash.elements.entrySet()) { + children.add(entry.getValue()); + } + } + if (hash.elements instanceof TieHash tieHash) children.add(tieHash.getSelf()); + } else if (value instanceof RuntimeList list) { + if (list instanceof RuntimeControlFlowList flow) { + children.add(flow.getReturnValue()); + } + children.addAll(list.elements); + } else if (value instanceof RuntimeCode code) { + if (code.capturedScalars != null) { + Collections.addAll(children, code.capturedScalars); + } + if (code.capturedAggregates != null) { + Collections.addAll(children, code.capturedAggregates); + } + if (code.stateVariable != null) children.addAll(code.stateVariable.values()); + if (code.stateArray != null) children.addAll(code.stateArray.values()); + if (code.stateHash != null) children.addAll(code.stateHash.values()); + if (code.padConstants != null) Collections.addAll(children, code.padConstants); + } + return children; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilityWalkerFullRootSnapshotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilityWalkerFullRootSnapshotTest.java deleted file mode 100644 index b837a96af9..0000000000 --- a/src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilityWalkerFullRootSnapshotTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.perlonjava.runtime.runtimetypes; - -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Tag("unit") -class ReachabilityWalkerFullRootSnapshotTest { - @Test - void oneSnapshotAnswersAllTargetsLikeThePerTargetRootWalk() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeHash global = new RuntimeHash(); - List targets = new ArrayList<>(); - for (int i = 0; i < 200; i++) { - RuntimeHash target = new RuntimeHash(); - targets.add(target); - global.put("target-" + i, target.createReference()); - } - RuntimeHash unrooted = new RuntimeHash(); - RuntimeHash directLexical = new RuntimeHash(); - MyVarCleanupStack.register(directLexical); - MyVarCleanupStack.snapshotStackToLiveCounts(); - GlobalVariable.globalHashes.put("FullRootSnapshotTest::global", global); - try { - Set snapshot = ReachabilityWalker.reachableFromRootsSnapshot(); - for (RuntimeHash target : targets) { - assertEquals(ReachabilityWalker.isReachableFromRoots(target), - snapshot.contains(target)); - } - assertTrue(snapshot.contains(directLexical)); - assertFalse(snapshot.contains(unrooted)); - } finally { - GlobalVariable.globalHashes.remove("FullRootSnapshotTest::global"); - MyVarCleanupStack.unregister(directLexical); - } - } - } -} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilityWalkerTiedSnapshotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilityWalkerTiedSnapshotTest.java deleted file mode 100644 index 6ac68a6535..0000000000 --- a/src/test/java/org/perlonjava/runtime/runtimetypes/ReachabilityWalkerTiedSnapshotTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.perlonjava.runtime.runtimetypes; - -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Tag("unit") -class ReachabilityWalkerTiedSnapshotTest { - @Test - void discoversReplacementStoredThroughExistingTiedHandlerSlot() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeHash original = new RuntimeHash(); - RuntimeHash handler = new RuntimeHash(); - handler.put("slot", original.createReference()); - - RuntimeHash tied = new RuntimeHash(); - tied.type = RuntimeHash.TIED_HASH; - tied.elements = new TieHash("RegexImplementationA178::Tie", - new RuntimeHash(), handler.createReference()); - - RuntimeHash nestedTarget = new RuntimeHash(); - RuntimeHash replacement = new RuntimeHash(); - replacement.put("nested", nestedTarget.createReference()); - assertFalse(replacement.possiblyStoredInTiedHandler); - assertFalse(nestedTarget.possiblyStoredInTiedHandler); - - RuntimeScalar existingSlot = handler.elements.get("slot"); - existingSlot.set(replacement.createReference()); - - assertTrue(replacement.possiblyStoredInTiedHandler); - assertTrue(nestedTarget.possiblyStoredInTiedHandler); - - String globalName = "RegexImplementationA178::replacement"; - GlobalVariable.globalHashes.put(globalName, tied); - try { - ReachabilityWalker.TiedHashReachabilitySnapshot reachable = - ReachabilityWalker.reachableThroughTiedHashes(); - assertTrue(reachable.contains(replacement)); - assertTrue(reachable.contains(nestedTarget)); - } finally { - GlobalVariable.globalHashes.remove(globalName); - } - } - } - - @Test - void collectsAllTargetsBehindOneTiedHandlerInOneSnapshot() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - String globalName = "RegexImplementationA178::tied"; - RuntimeHash handler = new RuntimeHash(); - List targets = new ArrayList<>(); - for (int i = 0; i < 200; i++) { - RuntimeHash target = new RuntimeHash(); - targets.add(target); - handler.elements.put("target-" + i, target.createReference()); - } - - RuntimeHash tied = new RuntimeHash(); - tied.type = RuntimeHash.TIED_HASH; - tied.elements = new TieHash("RegexImplementationA178::Tie", - new RuntimeHash(), handler.createReference()); - - assertTrue(handler.possiblyStoredInTiedHandler); - for (RuntimeHash target : targets) { - assertTrue(target.possiblyStoredInTiedHandler); - } - - assertFalse(ReachabilityWalker.reachableThroughTiedHashes() - .contains(targets.getFirst())); - GlobalVariable.globalHashes.put(globalName, tied); - try { - ReachabilityWalker.TiedHashReachabilitySnapshot reachable = - ReachabilityWalker.reachableThroughTiedHashes(); - assertTrue(reachable.contains(handler)); - for (RuntimeHash target : targets) { - assertTrue(reachable.contains(target)); - } - } finally { - GlobalVariable.globalHashes.remove(globalName); - } - } - } -} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RecursiveCleanupCurrentOwnerIdentityTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RecursiveCleanupCurrentOwnerIdentityTest.java new file mode 100644 index 0000000000..cb3645fe36 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RecursiveCleanupCurrentOwnerIdentityTest.java @@ -0,0 +1,61 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RecursiveCleanupCurrentOwnerIdentityTest { + @Test + void closureOwnedAggregateSkipsExternalRootSnapshotAndKeepsNestedWeakValue() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + + RuntimeArray unrelatedPackageRoot = new RuntimeArray(); + for (int i = 0; i < 128; i++) { + RuntimeArray.push(unrelatedPackageRoot, + new RuntimeHash().createAnonymousReference()); + } + String globalName = "RecursiveCleanupCurrentOwnerIdentityTest::global"; + GlobalVariable.globalArrays.put(globalName, unrelatedPackageRoot); + + RuntimeHash nested = new RuntimeHash(); + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar weak = referent.createAnonymousReference(); + RuntimeScalar strong = referent.createAnonymousReference(); + WeakRefRegistry.weaken(weak); + nested.put("referent", strong); + + RuntimeHash captured = new RuntimeHash(); + captured.put("nested", nested.createAnonymousReference()); + PerlOwnerSlot capture = captured.retainClosureCaptureOwner(); + RuntimeScalar removedOwner = captured.createAnonymousReference(); + RuntimeScalar.incrementRefCountForContainerStore(removedOwner); + assertEquals(1, captured.refCount); + + // Model a legacy count without a current counted slot. The live + // closure-pad identity is still authoritative for the aggregate. + captured.refCount++; + + try { + { + MortalList.deferDestroyForContainerClear(List.of(removedOwner)); + MortalList.flush(); + + assertTrue(WeakRefRegistry.isweak(weak)); + assertTrue(weak.value == referent, + "the captured aggregate keeps its nested referent alive"); + } + } finally { + GlobalVariable.globalArrays.remove(globalName); + WeakRefRegistry.unweaken(weak); + captured.releaseClosureCaptureOwner(capture); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RecursiveZeroCountLifecycleTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RecursiveZeroCountLifecycleTest.java new file mode 100644 index 0000000000..d50dd8708a --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RecursiveZeroCountLifecycleTest.java @@ -0,0 +1,93 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RecursiveZeroCountLifecycleTest { + @Test + void blessedContainerCleanupQueuesZeroCountLifecycleWithoutSyntheticOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId("Issue1649::ZeroCountCleanup"); + target.setTrackedRefCount(0); + RuntimeScalar discarded = new RuntimeScalar(); + discarded.type = RuntimeScalarType.REFERENCE; + discarded.value = target; + + MortalList.pushMark(); + try { + MortalList.deferDestroyForContainerClear(java.util.List.of(discarded)); + + assertEquals(0, target.refCount, + "recursive cleanup must not manufacture a positive owner count"); + assertEquals(1, runtime.lifecycleState.pending.size()); + assertNotNull(runtime.lifecycleState.pendingOwnerReleases.get(0), + "the lifecycle boundary carries an explicit completion token"); + + MortalList.popAndFlush(); + + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, target.perlLifecycleState()); + assertEquals(0, target.refCount); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + target.perlLifecycleState()); + assertFalse(target.hasPendingOwnerRelease(), + "the lifecycle token completes exactly once"); + } finally { + if (runtime.lifecycleState.hasMortalMarks()) MortalList.popAndFlush(); + } + } + } + + @Test + void zeroCountLifecycleDoesNotDecrementAReacquiredCountedOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId("Issue2043::ReacquiredOwner"); + target.setTrackedRefCount(0); + RuntimeScalar discarded = new RuntimeScalar(); + discarded.type = RuntimeScalarType.REFERENCE; + discarded.value = target; + RuntimeScalar owner = new RuntimeScalar(); + + MortalList.pushMark(); + try { + MortalList.deferDestroyForContainerClear(java.util.List.of(discarded)); + assertEquals(1, runtime.lifecycleState.pending.size()); + assertTrue(runtime.lifecycleState.pendingOwnerReleases.get(0) + .isLifecycleOnlyAtZero()); + + owner.set(target.createAnonymousReference()); + assertEquals(1, target.refCount, + "storing the new reference acquires one counted owner"); + + MortalList.popAndFlush(); + + assertEquals(1, target.refCount, + "a zero-count lifecycle token must not release a later owner"); + assertTrue(owner.refCountOwned); + assertNotNull(owner.countedOwnerSlot()); + assertTrue(owner.countedOwnerSlot().isActive()); + assertSame(target, owner.countedOwnerSlot().referent()); + assertFalse(target.perlLifecycleState() == RuntimeBase.PerlLifecycleState.DESTROYED, + "the re-acquired referent remains alive"); + + MortalList.deferDecrementIfTracked(owner); + MortalList.flush(); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + target.perlLifecycleState(), + "the actual counted owner still controls final cleanup"); + } finally { + if (runtime.lifecycleState.hasMortalMarks()) MortalList.popAndFlush(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ReentrantScalarOverwriteWeakOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ReentrantScalarOverwriteWeakOwnerTest.java new file mode 100644 index 0000000000..421453f2d8 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ReentrantScalarOverwriteWeakOwnerTest.java @@ -0,0 +1,66 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.app.cli.CompilerOptions; +import org.perlonjava.app.scriptengine.PerlLanguageProvider; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ReentrantScalarOverwriteWeakOwnerTest { + private static final String SOURCE = """ + use strict; + use warnings; + use Scalar::Util qw(weaken); + { + package Issue1649::ReentrantOverwriteWeakOwner; + sub new { bless { name => $_[1] }, $_[0] } + sub DESTROY { + my ($self) = @_; + if ($self->{name} eq 'old') { + $main::keeper = $main::slot; + Scalar::Util::weaken($main::slot); + } + } + } + our ($slot, $keeper); + $slot = Issue1649::ReentrantOverwriteWeakOwner->new('old'); + $slot = Issue1649::ReentrantOverwriteWeakOwner->new('replacement'); + 1; + """; + + @Test + void destructorWeakeningRemainsTheOnlyOwnerTransition() throws Exception { + for (boolean interpreter : new boolean[]{false, true}) { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + CompilerOptions options = new CompilerOptions(); + options.fileName = ""; + options.code = SOURCE; + options.useInterpreter = interpreter; + PerlLanguageProvider.executePerlCode(options, false); + + RuntimeScalar slot = GlobalVariable.getGlobalVariable("main::slot"); + RuntimeScalar keeper = GlobalVariable.getGlobalVariable("main::keeper"); + RuntimeBase referent = (RuntimeBase) keeper.value; + + assertSame(referent, slot.value); + assertTrue(WeakRefRegistry.isweak(slot)); + assertFalse(slot.refCountOwned, + "the outer overwrite must not restore ownership after DESTROY weakens the slot"); + PerlOwnerSlot slotOwner = slot.countedOwnerSlot(); + assertFalse(slotOwner != null && slotOwner.isActive() + && slotOwner.referent() == referent, + "a weakened slot must not remain in the referent's counted-owner ledger"); + assertEquals(1, referent.refCount, + "the keeper is the only strong reference after the callback"); + assertEquals(1, referent.countedOwnerSlotCount(), + "the owner ledger must contain only the keeper's counted edge"); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RescuedAggregateOwnerFinalizationTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RescuedAggregateOwnerFinalizationTest.java new file mode 100644 index 0000000000..478fbf1e4e --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RescuedAggregateOwnerFinalizationTest.java @@ -0,0 +1,79 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; + +@Tag("unit") +class RescuedAggregateOwnerFinalizationTest { + @Test + void deferredRescueFinalizationReleasesNestedOwnersThroughSlots() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + String parentClass = "Issue1649::RescuedOwnerParent"; + String childClass = "Issue1649::RescuedOwnerChild"; + RuntimeHash parent = new RuntimeHash(); + RuntimeHash child = new RuntimeHash(); + parent.blessId = NameNormalizer.getBlessId(parentClass); + child.blessId = NameNormalizer.getBlessId(childClass); + child.setTrackedRefCount(0); + + RuntimeScalar childSlot = new RuntimeScalar(); + parent.elements.put("child", childSlot); + childSlot.set(child.createAnonymousReference()); + + RuntimeScalar weakChild = new RuntimeScalar(); + weakChild.type = RuntimeScalarType.HASHREFERENCE; + weakChild.value = child; + WeakRefRegistry.weaken(weakChild); + + AtomicInteger childDestroyCount = new AtomicInteger(); + installDestroy(parentClass, (args, context) -> { + DestroyDispatch.markDestroyTargetRescued(); + return new RuntimeScalar().getList(); + }); + installDestroy(childClass, (args, context) -> { + childDestroyCount.incrementAndGet(); + return new RuntimeScalar().getList(); + }); + + parent.setTrackedRefCount(0); + try { + DestroyDispatch.callDestroy(parent); + assertEquals(RuntimeBase.PerlLifecycleState.RESURRECTED, + parent.perlLifecycleState()); + + // This runtime has no deferred captures: shutdown must still + // process rescued objects instead of returning early. + MortalList.flushDeferredCaptures(); + + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + parent.perlLifecycleState()); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + child.perlLifecycleState()); + assertEquals(1, childDestroyCount.get(), + "releasing the rescued aggregate's slot runs the nested destructor once"); + assertNull(weakChild.value, + "the nested weak reference clears when its actual owner leaves"); + assertFalse(WeakRefRegistry.isweak(weakChild)); + } finally { + WeakRefRegistry.unweaken(weakChild); + GlobalVariable.removeGlobalCodeRefForStashDelete(parentClass + "::DESTROY"); + GlobalVariable.removeGlobalCodeRefForStashDelete(childClass + "::DESTROY"); + } + } + } + + private static void installDestroy(String className, PerlSubroutine body) { + RuntimeCode code = new RuntimeCode(body, null); + int separator = className.lastIndexOf("::"); + code.packageName = className.substring(0, separator); + code.subName = className.substring(separator + 2); + GlobalVariable.getGlobalCodeRef(className + "::DESTROY").set(new RuntimeScalar(code)); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RescuedObjectOwnerIdentityTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RescuedObjectOwnerIdentityTest.java new file mode 100644 index 0000000000..500943f9bd --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RescuedObjectOwnerIdentityTest.java @@ -0,0 +1,52 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RescuedObjectOwnerIdentityTest { + @Test + void durableGlobalSlotIsRecognizedWithoutWalkingRoots() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + referent.setTrackedRefCount(0); + RuntimeScalar global = GlobalVariable.getGlobalVariable( + "RescuedObjectOwnerIdentityTest::globalOwner"); + + try { + global.set(referent.createReference()); + assertTrue(DestroyDispatch.hasLivePerlOwnerIdentity(referent)); + + { + assertTrue(DestroyDispatch.hasLivePerlOwnerIdentity(referent)); + } + } finally { + global.set(new RuntimeScalar()); + } + } + } + + @Test + void rescueQueueHasNoOwnerButAnExpressionTemporaryDoes() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash rescued = new RuntimeHash(); + runtime.lifecycleState.rescuedObjects.add(rescued); + assertFalse(DestroyDispatch.hasLivePerlOwnerIdentity(rescued)); + MortalList.pushTemporaryRoot(rescued); + + try { + assertTrue(DestroyDispatch.hasLivePerlOwnerIdentity(rescued)); + } finally { + MortalList.popTemporaryRoot(rescued); + runtime.lifecycleState.rescuedObjects.remove(rescued); + } + assertFalse(DestroyDispatch.hasLivePerlOwnerIdentity(rescued)); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RescuedWeakRefsBeforeEndTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RescuedWeakRefsBeforeEndTest.java new file mode 100644 index 0000000000..1900e9955c --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RescuedWeakRefsBeforeEndTest.java @@ -0,0 +1,232 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RescuedWeakRefsBeforeEndTest { + @Test + void preEndBoundaryPreservesObserversForStrongRescuedCycle() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash schema = blessedHash("Issue1649::RescuedSchema"); + RuntimeHash storage = blessedHash("Issue1649::RescuedStorage"); + RuntimeHash dbh = blessedHash("Issue1649::RescuedDbh"); + + RuntimeScalar storageEdge = storage.createAnonymousReference(); + storeStrongHashEdge(schema, "storage", storageEdge); + RuntimeScalar dbhEdge = dbh.createAnonymousReference(); + storeStrongHashEdge(storage, "_dbh", dbhEdge); + RuntimeScalar schemaBackref = schema.createAnonymousReference(); + storeStrongHashEdge(dbh, "schema", schemaBackref); + + RuntimeScalar weakSchema = schema.createAnonymousReference(); + RuntimeScalar weakStorage = storage.createAnonymousReference(); + RuntimeScalar weakDbh = dbh.createAnonymousReference(); + WeakRefRegistry.weaken(weakSchema); + WeakRefRegistry.weaken(weakStorage); + WeakRefRegistry.weaken(weakDbh); + markRescued(schema); + + assertTrue(WeakRefRegistry.isweak(weakSchema)); + assertTrue(WeakRefRegistry.isweak(weakStorage)); + assertTrue(WeakRefRegistry.isweak(weakDbh)); + + MortalList.flushDeferredCapturesBeforeEnd(); + + assertTrue(WeakRefRegistry.isweak(weakSchema), "strongly owned rescue keeps its observer"); + assertTrue(WeakRefRegistry.isweak(weakStorage), "strongly owned Storage keeps its observer"); + assertTrue(WeakRefRegistry.isweak(weakDbh), "strongly owned DBH keeps its observer"); + assertSame(schema, schemaBackref.value, "strong cycle remains available to END"); + assertSame(storage, storageEdge.value); + assertSame(dbh, dbhEdge.value); + assertTrue(DestroyDispatch.isRescued(schema), "END still has the rescued root"); + assertTrue(schema.destroyFired, "the pre-existing DESTROY state remains recorded"); + } + } + + @Test + void preEndBoundaryPreservesWeakObserversWithIndependentPackageRoot() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash rescued = blessedHash("Issue1649::GloballyRescued"); + RuntimeScalar weak = rescued.createAnonymousReference(); + WeakRefRegistry.weaken(weak); + RuntimeHash globalRoot = new RuntimeHash(); + storeStrongHashEdge( + globalRoot, "rescued", rescued.createAnonymousReference()); + String globalName = "RescuedWeakRefsBeforeEndTest::globalRoot"; + GlobalVariable.globalHashes.put(globalName, globalRoot); + markRescued(rescued); + + try { + assertTrue(WeakRefRegistry.isweak(weak)); + MortalList.flushDeferredCapturesBeforeEnd(); + + assertTrue(WeakRefRegistry.isweak(weak), + "a package-rooted rescue keeps its weak observer through END"); + assertSame(rescued, weak.value); + } finally { + GlobalVariable.globalHashes.remove(globalName); + } + } + } + + @Test + void preEndBoundaryPreservesWeakObserverForOwnerSlotOutsideRescuedGraph() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash rescued = blessedHash("Issue1649::OwnerSlotRescue"); + RuntimeScalar weak = rescued.createAnonymousReference(); + WeakRefRegistry.weaken(weak); + + RuntimeScalar lexicalOwner = rescued.createAnonymousReference(); + lexicalOwner.localBindingExists = true; + MyVarCleanupStack.register(lexicalOwner); + RuntimeScalar.incrementRefCountForContainerStore( + lexicalOwner, PerlOwnerSlot.Kind.SCALAR_CELL); + markRescued(rescued); + + assertTrue(DestroyDispatch.hasLivePerlOwnerIdentity(rescued)); + assertTrue(WeakRefRegistry.isweak(weak)); + MortalList.flushDeferredCapturesBeforeEnd(); + + assertTrue(WeakRefRegistry.isweak(weak), + "a current semantic owner slot outside the rescued graph keeps its observer"); + assertSame(rescued, weak.value); + } + } + + @Test + void preEndBoundaryPreservesWeakObserverForIndependentNestedRoot() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash rescued = blessedHash("Issue1649::NestedRescueRoot"); + RuntimeHash nested = blessedHash("Issue1649::NestedIndependentRoot"); + RuntimeScalar nestedEdge = nested.createAnonymousReference(); + storeStrongHashEdge(rescued, "nested", nestedEdge); + + RuntimeScalar weakRescued = rescued.createAnonymousReference(); + RuntimeScalar weakNested = nested.createAnonymousReference(); + WeakRefRegistry.weaken(weakRescued); + WeakRefRegistry.weaken(weakNested); + + RuntimeHash globalRoot = new RuntimeHash(); + storeStrongHashEdge( + globalRoot, "nested", nested.createAnonymousReference()); + String globalName = "RescuedWeakRefsBeforeEndTest::nestedGlobalRoot"; + GlobalVariable.globalHashes.put(globalName, globalRoot); + markRescued(rescued); + + try { + assertTrue(WeakRefRegistry.isweak(weakRescued)); + assertTrue(WeakRefRegistry.isweak(weakNested)); + MortalList.flushDeferredCapturesBeforeEnd(); + + assertFalse(WeakRefRegistry.isweak(weakRescued), + "the rescue-only parent observer clears"); + assertTrue(WeakRefRegistry.isweak(weakNested), + "an independently rooted descendant keeps its observer"); + assertSame(nested, nestedEdge.value); + assertSame(nested, weakNested.value); + } finally { + GlobalVariable.globalHashes.remove(globalName); + } + } + } + + @Test + void preEndBoundaryPreservesObjectsCapturedByQueuedEndBlocks() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash rescued = blessedHash("Issue1649::EndCapturedRescue"); + RuntimeScalar weak = rescued.createAnonymousReference(); + WeakRefRegistry.weaken(weak); + RuntimeCode endBlock = new RuntimeCode((args, context) -> new RuntimeList(), null); + endBlock.closedOverVariables = new java.util.LinkedHashMap<>(); + endBlock.closedOverVariables.put("rescued", rescued.createAnonymousReference()); + retainCapturedAggregate(endBlock, rescued); + SpecialBlock.saveEndBlock(new RuntimeScalar(endBlock)); + markRescued(rescued); + + assertTrue(WeakRefRegistry.isweak(weak)); + MortalList.flushDeferredCapturesBeforeEnd(); + + assertTrue(WeakRefRegistry.isweak(weak), + "a queued END callback keeps its captured object alive"); + assertSame(rescued, weak.value); + endBlock.releaseCaptures(); + } + } + + @Test + void preEndBoundaryPreservesObjectsHeldByActiveCode() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash rescued = blessedHash("Issue1649::ActiveCodeRescue"); + RuntimeScalar weak = rescued.createAnonymousReference(); + WeakRefRegistry.weaken(weak); + RuntimeCode activeCode = new RuntimeCode( + (args, context) -> new RuntimeList(), null); + activeCode.capturedScalars = new RuntimeScalar[]{rescued.createAnonymousReference()}; + retainCapturedAggregate(activeCode, rescued); + runtime.executionState().activeCodeStack.add(activeCode); + markRescued(rescued); + + assertTrue(WeakRefRegistry.isweak(weak)); + MortalList.flushDeferredCapturesBeforeEnd(); + + assertTrue(WeakRefRegistry.isweak(weak), + "an active Perl callback keeps its captured object alive"); + assertSame(rescued, weak.value); + runtime.executionState().activeCodeStack.remove(activeCode); + activeCode.releaseCaptures(); + } + } + + @Test + void postEndFlushClearsRescuedObserversWithoutDeferredCaptures() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash rescued = blessedHash("Issue1649::RescuedAfterEnd"); + RuntimeScalar weak = rescued.createAnonymousReference(); + WeakRefRegistry.weaken(weak); + markRescued(rescued); + + MortalList.flushDeferredCaptures(); + + assertFalse(WeakRefRegistry.isweak(weak)); + assertFalse(DestroyDispatch.isRescued(rescued), + "final owner release removes the rescue lifecycle record"); + } + } + + private static RuntimeHash blessedHash(String className) { + RuntimeHash hash = new RuntimeHash(); + hash.blessId = NameNormalizer.getBlessId(className); + return hash; + } + + private static void markRescued(RuntimeBase rescued) { + rescued.destroyFired = true; + PerlRuntime.current().lifecycleState.rescuedObjects.add(rescued); + } + + private static void retainCapturedAggregate(RuntimeCode code, RuntimeBase aggregate) { + code.capturedAggregates = new RuntimeBase[]{aggregate}; + code.capturedAggregateOwnerSlots = new PerlOwnerSlot[]{ + aggregate.retainClosureCaptureOwner(code) + }; + } + + private static void storeStrongHashEdge( + RuntimeHash hash, String key, RuntimeScalar owner) { + RuntimeScalar.incrementRefCountForContainerStore( + owner, PerlOwnerSlot.Kind.HASH_ELEMENT); + hash.elements.put(key, owner); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RescuedWeakRefsEmptyRegistryFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RescuedWeakRefsEmptyRegistryFastPathTest.java new file mode 100644 index 0000000000..1df4757561 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RescuedWeakRefsEmptyRegistryFastPathTest.java @@ -0,0 +1,51 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.AbstractMap; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RescuedWeakRefsEmptyRegistryFastPathTest { + private static final class CountingHashValues extends AbstractMap { + private int valuesCalls; + + @Override + public Set> entrySet() { + return Collections.emptySet(); + } + + @Override + public Collection values() { + valuesCalls++; + return Collections.emptyList(); + } + } + + @Test + void rescuedObjectProcessingDoesNotWalkNestedHashValues() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash rescued = new RuntimeHash(); + CountingHashValues nestedValues = new CountingHashValues(); + rescued.elements = nestedValues; + runtime.lifecycleState.rescuedObjects.add(rescued); + + assertFalse(WeakRefRegistry.hasAnyWeakRefs()); + DestroyDispatch.processRescuedObjects(); + + assertEquals(0, nestedValues.valuesCalls, + "the END boundary must skip rescue-graph traversal without observers"); + assertTrue(DestroyDispatch.isRescued(rescued), + "the optimization must preserve the rescued object through END"); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RootSnapshotOwnerReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RootSnapshotOwnerReleaseTest.java new file mode 100644 index 0000000000..039f7defb2 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RootSnapshotOwnerReleaseTest.java @@ -0,0 +1,96 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RootSnapshotOwnerReleaseTest { + @Test + void releaseFailureDoesNotSkipLaterSnapshotOwners() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash first = new RuntimeHash(); + RuntimeHash second = new RuntimeHash(); + PerlOwnerSlot laterOwner = temporaryOwner(first); + PerlOwnerSlot failingOwner = temporaryOwner(second); + PerlRuntime.RootSnapshot snapshot = new PerlRuntime.RootSnapshot( + runtime, List.of(first, second), List.of(failingOwner, laterOwner), owner -> { + owner.release(); + if (owner == failingOwner) { + throw new IllegalStateException("owner release failed"); + } + }); + + try { + IllegalStateException failure = assertThrows(IllegalStateException.class, + snapshot::close); + + assertEquals("owner release failed", failure.getMessage()); + assertFalse(failingOwner.isActive()); + assertFalse(laterOwner.isActive(), "later owners are still retired after failure"); + assertEquals(0, first.ownerSlotCount(PerlOwnerSlot.Kind.TEMPORARY_ROOT)); + assertEquals(0, second.ownerSlotCount(PerlOwnerSlot.Kind.TEMPORARY_ROOT)); + } finally { + failingOwner.release(); + laterOwner.release(); + } + } + runtime.close(); + } + + @Test + void runtimeCloseAttemptsEverySnapshotAfterOneReleaseFails() { + PerlRuntime runtime = new PerlRuntime(); + PerlRuntime.RootSnapshot firstSnapshot; + PerlRuntime.RootSnapshot secondSnapshot; + PerlOwnerSlot firstOwner; + PerlOwnerSlot secondOwner; + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash first = new RuntimeHash(); + RuntimeHash second = new RuntimeHash(); + firstOwner = temporaryOwner(first); + secondOwner = temporaryOwner(second); + firstSnapshot = new PerlRuntime.RootSnapshot( + runtime, List.of(first), List.of(firstOwner), owner -> { + owner.release(); + throw new IllegalStateException("owner release failed"); + }); + secondSnapshot = new PerlRuntime.RootSnapshot( + runtime, List.of(second), List.of(secondOwner), owner -> { + owner.release(); + throw new IllegalStateException("owner release failed"); + }); + } + + try { + IllegalStateException failure = assertThrows( + IllegalStateException.class, runtime::close); + + assertEquals("owner release failed", failure.getMessage()); + assertEquals(1, failure.getSuppressed().length); + assertEquals("owner release failed", failure.getSuppressed()[0].getMessage()); + assertFalse(firstOwner.isActive()); + assertFalse(secondOwner.isActive()); + assertTrue(runtime.isClosed(), "runtime teardown completes after all releases are tried"); + } finally { + firstOwner.release(); + secondOwner.release(); + firstSnapshot.close(); + secondSnapshot.close(); + runtime.close(); + } + } + + private static PerlOwnerSlot temporaryOwner(RuntimeBase referent) { + PerlOwnerSlot owner = new PerlOwnerSlot(PerlOwnerSlot.Kind.TEMPORARY_ROOT); + owner.acquireTemporaryRootIdentity(referent); + return owner; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeArrayLiteralOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeArrayLiteralOwnerSlotTest.java new file mode 100644 index 0000000000..d2c839016c --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeArrayLiteralOwnerSlotTest.java @@ -0,0 +1,32 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RuntimeArrayLiteralOwnerSlotTest { + @Test + void copiedLiteralElementHasCurrentArrayElementOwnerIdentity() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray referent = new RuntimeArray(); + RuntimeScalar value = referent.createAnonymousReference(); + RuntimeArray literal = new RuntimeArray(); + + literal.add(value); + literal.createReferenceWithTrackedElements(); + + RuntimeScalar stored = literal.elements.getFirst(); + PerlOwnerSlot owner = stored.countedOwnerSlot(); + assertSame(literal, stored.getContainerOwner()); + assertSame(stored, owner.countedScalarOwner()); + assertEquals(PerlOwnerSlot.Kind.ARRAY_ELEMENT, owner.kind()); + assertTrue(stored.isCurrentAggregateElementOwner(referent, owner)); + assertEquals(1, referent.refCount); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeArrayMethodCallArgumentsTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeArrayMethodCallArgumentsTest.java deleted file mode 100644 index 8aac2f487c..0000000000 --- a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeArrayMethodCallArgumentsTest.java +++ /dev/null @@ -1,118 +0,0 @@ -package org.perlonjava.runtime.runtimetypes; - -import java.util.ArrayList; -import java.util.List; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Tag("unit") -class RuntimeArrayMethodCallArgumentsTest { - - @Test - void oneArgumentAndInvocantUseInlineListStorage() { - RuntimeArray arguments = RuntimeArray.methodCallArguments(2); - - assertFalse(arguments.elements instanceof ArrayList, - "common method argument arrays should not allocate ArrayList backing storage"); - } - - @Test - void inlineArgumentsSupportInsertionMutationRemovalAndSelfAppend() { - RuntimeArray arguments = RuntimeArray.methodCallArguments(2); - RuntimeScalar invocant = new RuntimeScalar("object"); - RuntimeScalar first = new RuntimeScalar("first"); - RuntimeScalar replacement = new RuntimeScalar("replacement"); - - arguments.elements.add(invocant); - arguments.elements.add(first); - assertSame(invocant, arguments.elements.get(0)); - assertSame(first, arguments.elements.set(1, replacement)); - assertEquals("replacement", arguments.elements.get(1).toString()); - - arguments.elements.add(1, first); - assertEquals(List.of(invocant, first, replacement), arguments.elements); - arguments.elements.addAll(arguments.elements); - assertEquals(List.of(invocant, first, replacement, invocant, first, replacement), - arguments.elements); - - assertSame(invocant, arguments.elements.remove(0)); - assertEquals(List.of(first, replacement, invocant, first, replacement), arguments.elements); - arguments.elements.clear(); - assertEquals(0, arguments.elements.size()); - } - - @Test - void methodInvocantPrependPreservesAliasedArgumentOrderForBothStorageModes() { - RuntimeScalar invocant = new RuntimeScalar("object"); - RuntimeScalar explicit = new RuntimeScalar("explicit"); - - RuntimeArray inlineArguments = RuntimeArray.methodCallArguments(2); - explicit.setArrayOfAlias(inlineArguments); - inlineArguments.prependMethodCallInvocant(invocant); - assertSame(invocant, inlineArguments.elements.get(0)); - assertSame(explicit, inlineArguments.elements.get(1)); - - RuntimeArray ordinaryArguments = RuntimeArray.methodCallArguments(3); - explicit.setArrayOfAlias(ordinaryArguments); - ordinaryArguments.prependMethodCallInvocant(invocant); - assertSame(invocant, ordinaryArguments.elements.get(0)); - assertSame(explicit, ordinaryArguments.elements.get(1)); - } - - @Test - void stableMethodInvocantPrependHonorsRootTrackingSuppression() { - RuntimeArray arguments = RuntimeArray.methodCallArguments(2); - RuntimeScalar invocant = new RuntimeScalar("object"); - RuntimeScalar explicit = new RuntimeScalar("explicit"); - explicit.setArrayOfAlias(arguments); - - assertTrue(arguments.suppressRootTrackingForStableMethodArguments()); - arguments.prependMethodCallInvocant(invocant); - - assertSame(invocant, arguments.elements.get(0)); - assertSame(explicit, arguments.elements.get(1)); - arguments.resumeMethodArgumentRootTracking(); - } - - @Test - void largerInitialArgumentListsKeepOrdinaryArrayStorage() { - RuntimeArray arguments = RuntimeArray.methodCallArguments(3); - - assertTrue(arguments.elements instanceof ArrayList, - "larger argument lists should keep the existing storage implementation"); - } - - @Test - void recycledMethodArgumentsAreReusedAfterTheirValuesAreCleared() { - RuntimeArray arguments = RuntimeArray.methodCallArguments(2); - new RuntimeScalar("stale").setArrayOfAlias(arguments); - assertTrue(arguments.elementsAliased); - arguments.recycleMethodCallArguments(); - - RuntimeArray reused = RuntimeArray.methodCallArguments(2); - - assertSame(arguments, reused); - assertTrue(reused.elements.isEmpty()); - assertFalse(reused.elementsAliased); - } - - @Test - void generatedMethodArgumentsReuseTheOwningExecutionStatePool() { - ExecutionRuntimeState state = new ExecutionRuntimeState(new PerlRuntime()); - RuntimeArray arguments = RuntimeArray.methodCallArguments(2, state); - new RuntimeScalar(1).setArrayOfAlias(arguments); - assertTrue(arguments.elementsAliased); - - arguments.recycleMethodCallArguments(state); - RuntimeArray reused = RuntimeArray.methodCallArguments(2, state); - - assertSame(arguments, reused); - assertTrue(reused.elements.isEmpty()); - assertFalse(reused.elementsAliased); - } -} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeArraySingleValueOwnerTransferTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeArraySingleValueOwnerTransferTest.java new file mode 100644 index 0000000000..0bdcdc1ace --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeArraySingleValueOwnerTransferTest.java @@ -0,0 +1,57 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RuntimeArraySingleValueOwnerTransferTest { + @Test + void setTransfersTheCountedCellToTheCurrentElementWithoutRootWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + RuntimeScalar value = new RuntimeScalar(); + value.set(target.createAnonymousReference()); + PerlOwnerSlot owner = value.countedOwnerSlot(); + assertNotNull(owner); + assertEquals(PerlOwnerSlot.Kind.SCALAR_CELL, owner.kind()); + + RuntimeArray array = new RuntimeArray(); + array.set(value); + + assertSame(owner, value.countedOwnerSlot(), + "moving the scalar cell preserves its counted owner identity"); + assertEquals(PerlOwnerSlot.Kind.ARRAY_ELEMENT, owner.kind()); + assertTrue(value.isCurrentAggregateElementOwner(target, owner)); + assertTrue(array.ownsElement(value)); + + RuntimeScalar observer = target.createAnonymousReference(); + try { + // The two live cells own the target, but simulate the transient + // selective-count undercount that deferred cleanup must repair. + target.setTrackedRefCount(1); + { + WeakRefRegistry.weaken(observer); + + assertTrue(WeakRefRegistry.isweak(observer)); + assertEquals(1, target.refCount, + "the current array element identity restores its count"); + } + + value.set(new RuntimeScalar()); + assertFalse(WeakRefRegistry.isweak(observer), + "releasing the transferred element clears its weak observer"); + } finally { + if (WeakRefRegistry.isweak(observer)) WeakRefRegistry.unweaken(observer); + observer.set(new RuntimeScalar()); + value.set(new RuntimeScalar()); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeBaseRefCountTrackingStateTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeBaseRefCountTrackingStateTest.java new file mode 100644 index 0000000000..12823dd7d9 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeBaseRefCountTrackingStateTest.java @@ -0,0 +1,51 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@Tag("unit") +class RuntimeBaseRefCountTrackingStateTest { + @Test + void trackingModeIsSeparateFromTheNonnegativeCount() { + RuntimeScalar referent = new RuntimeScalar(); + + assertEquals(0, referent.refCount); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, + referent.refCountTrackingState()); + + referent.setTrackedRefCount(2); + assertEquals(2, referent.refCount); + assertEquals(RuntimeBase.RefCountTrackingState.TRACKED, + referent.refCountTrackingState()); + + referent.markRefCountWeaklyTracked(); + assertEquals(0, referent.refCount); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, + referent.refCountTrackingState()); + + referent.markRefCountUntracked(); + assertEquals(0, referent.refCount); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, + referent.refCountTrackingState()); + } + + @Test + void trackingStateCannotRestoreAnInvalidCount() { + RuntimeScalar referent = new RuntimeScalar(); + + assertThrows(IllegalArgumentException.class, + () -> referent.setTrackedRefCount(-1)); + assertThrows(IllegalArgumentException.class, + () -> referent.restoreRefCountState(-1, + RuntimeBase.RefCountTrackingState.TRACKED)); + assertThrows(IllegalArgumentException.class, + () -> referent.restoreRefCountState(1, + RuntimeBase.RefCountTrackingState.UNTRACKED)); + assertThrows(IllegalArgumentException.class, + () -> referent.restoreRefCountState(1, + RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED)); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeAdoptDefinitionCaptureOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeAdoptDefinitionCaptureOwnerTest.java new file mode 100644 index 0000000000..cca6589ba5 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeAdoptDefinitionCaptureOwnerTest.java @@ -0,0 +1,84 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RuntimeCodeAdoptDefinitionCaptureOwnerTest { + @Test + void adoptingDefinitionRetiresReplacedCaptureAndKeepsNewCapture() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode placeholder = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar oldPad = new RuntimeScalar(1); + PerlOwnerSlot oldCapture = oldPad.retainClosureCaptureSlot(placeholder); + placeholder.capturedScalars = new RuntimeScalar[] {oldPad}; + placeholder.capturedScalarOwnerSlots = new PerlOwnerSlot[] {oldCapture}; + + RuntimeCode definition = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar newPad = new RuntimeScalar(2); + PerlOwnerSlot newCapture = newPad.retainClosureCaptureSlot(definition); + definition.capturedScalars = new RuntimeScalar[] {newPad}; + definition.capturedScalarOwnerSlots = new PerlOwnerSlot[] {newCapture}; + + assertEquals(1, oldPad.captureCount); + assertEquals(1, newPad.captureCount); + + placeholder.adoptDefinitionFrom(definition); + + assertFalse(oldCapture.isActive(), "the replaced pad edge is retired"); + assertEquals(0, oldPad.captureCount); + assertEquals(0, oldPad.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CAPTURE)); + assertSame(newPad, placeholder.capturedScalars[0]); + assertSame(newCapture, placeholder.capturedScalarOwnerSlots[0]); + assertSame(placeholder, newCapture.captureOwner()); + assertTrue(newCapture.isActive()); + assertEquals(1, newPad.captureCount); + + placeholder.releaseCaptures(); + assertFalse(newCapture.isActive()); + assertEquals(0, newPad.captureCount); + } + } + + @Test + void activeFrameDefersRetiredCaptureUntilTheFrameReturns() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode placeholder = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar oldPad = new RuntimeScalar(1); + PerlOwnerSlot oldCapture = oldPad.retainClosureCaptureSlot(placeholder); + placeholder.capturedScalars = new RuntimeScalar[] {oldPad}; + placeholder.capturedScalarOwnerSlots = new PerlOwnerSlot[] {oldCapture}; + + RuntimeCode definition = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar newPad = new RuntimeScalar(2); + PerlOwnerSlot newCapture = newPad.retainClosureCaptureSlot(definition); + definition.capturedScalars = new RuntimeScalar[] {newPad}; + definition.capturedScalarOwnerSlots = new PerlOwnerSlot[] {newCapture}; + + RuntimeCode.pushActiveCode(placeholder); + try { + placeholder.adoptDefinitionFrom(definition); + + assertTrue(oldCapture.isActive(), "the running frame retains its old pad edge"); + assertEquals(1, oldPad.captureCount); + assertTrue(newCapture.isActive()); + assertEquals(1, newPad.captureCount); + } finally { + RuntimeCode.popActiveCode(placeholder); + } + + assertFalse(oldCapture.isActive(), "the old pad edge retires after frame return"); + assertEquals(0, oldPad.captureCount); + placeholder.releaseCaptures(); + assertFalse(newCapture.isActive()); + assertEquals(0, newPad.captureCount); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeAttributeOwnerTransitionTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeAttributeOwnerTransitionTest.java new file mode 100644 index 0000000000..7c7ed40705 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeAttributeOwnerTransitionTest.java @@ -0,0 +1,52 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.runtime.perlmodule.Attributes; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +@Tag("unit") +class RuntimeCodeAttributeOwnerTransitionTest { + @Test + void attributedClosureMovesItsStashOwnerFromPrototypeToCallableClone() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + String packageName = "RuntimeCodeAttributeOwnerTransition"; + String codeName = packageName + "::installed"; + String attributesName = packageName + "::MODIFY_CODE_ATTRIBUTES"; + + RuntimeCode prototype = code(); + prototype.attributes = new ArrayList<>(List.of("OwnerTransition")); + RuntimeScalar codeSlot = new RuntimeScalar(prototype); + GlobalVariable.globalCodeRefs.put(codeName, codeSlot); + GlobalVariable.globalCodeRefs.put( + attributesName, new RuntimeScalar(code())); + + PerlOwnerSlot owner = codeSlot.countedOwnerSlot(); + assertSame(prototype, owner.referent()); + assertEquals(1, prototype.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + + try { + Attributes.runtimeDispatchModifyCodeAttributes( + packageName, codeSlot, true); + + RuntimeCode clone = (RuntimeCode) codeSlot.value; + assertSame(clone, owner.referent(), + "the existing CODE slot identity follows the replacement value"); + assertEquals(0, prototype.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + assertEquals(1, clone.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + } finally { + GlobalVariable.globalCodeRefs.remove(codeName); + GlobalVariable.globalCodeRefs.remove(attributesName); + } + } + } + + private static RuntimeCode code() { + return new RuntimeCode((args, context) -> new RuntimeList(), null); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeOwnerIdentityTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeOwnerIdentityTest.java new file mode 100644 index 0000000000..b3a761db86 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeOwnerIdentityTest.java @@ -0,0 +1,22 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; + +@Tag("unit") +class RuntimeCodeOwnerIdentityTest { + @Test + void inheritedLocalBindingMarkerIsNotACodeOwner() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + code.localBindingExists = true; + + assertFalse(code.hasPerlOwnerForCapture(), + "CODE capture liveness must come from CODE owners, not aggregate metadata"); + assertFalse(code.hasPerlOwnerForCaptureOtherThan(null), + "the inherited marker does not identify a Perl CODE slot"); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeSlotTransitionTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeSlotTransitionTest.java new file mode 100644 index 0000000000..ca6f5978e4 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeSlotTransitionTest.java @@ -0,0 +1,92 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Method; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +@Tag("unit") +class RuntimeCodeSlotTransitionTest { + @Test + void lexicalForwardPlaceholderPromotionRecordsTheScalarOwner() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeScalar lexicalCell = new RuntimeScalar(); + lexicalCell.lexicalSubName = "forward"; + lexicalCell.lexicalSubPackageName = "CodeOwner"; + MyVarCleanupStack.register(lexicalCell); + + try { + RuntimeScalar reference = RuntimeCode.createCodeReference(lexicalCell, "CodeOwner"); + RuntimeCode placeholder = (RuntimeCode) reference.value; + + assertSame(lexicalCell, reference); + assertNotNull(lexicalCell.untrackedReferenceOwnerSlot()); + assertSame(placeholder, lexicalCell.untrackedReferenceOwnerSlot().referent()); + assertEquals(1, placeholder.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + lexicalCell.set(new RuntimeScalar()); + assertEquals(0, placeholder.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + } finally { + MyVarCleanupStack.unregister(lexicalCell); + } + } + } + + @Test + void forwardGlobAliasMovesTheSourceCellOwnerToTheTargetPlaceholder() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + GlobalVariable.resetAllGlobals(); + String sourceName = "CodeOwner::forward"; + String targetName = "CodeOwner::target"; + RuntimeCode sourceCode = undefinedCode(); + sourceCode.lexicalForwardGlobPlaceholder = true; + sourceCode.hasForwardGlobAlias = true; + sourceCode.requiresForwardGlobAliasGroup = true; + sourceCode.forwardGlobAliases.add(sourceCode); + RuntimeScalar sourceSlot = new RuntimeScalar(sourceCode); + GlobalVariable.globalCodeRefs.put(sourceName, sourceSlot); + + RuntimeCode targetCode = undefinedCode(); + RuntimeScalar targetSlot = new RuntimeScalar(targetCode); + GlobalVariable.globalCodeRefs.put(targetName, targetSlot); + + assertEquals(1, sourceCode.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + new RuntimeGlob(targetName).set(sourceSlot); + + assertSame(targetCode, sourceSlot.value); + assertSame(targetCode, sourceSlot.countedOwnerSlot().referent()); + assertEquals(0, sourceCode.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + assertEquals(2, targetCode.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + GlobalVariable.resetAllGlobals(); + } + } + + @Test + void constructorPredeclarationTransitionsAnExistingEmptyCodeCell() throws Exception { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + GlobalVariable.resetAllGlobals(); + String name = "CodeOwner::Widget::new"; + RuntimeScalar codeCell = new RuntimeScalar(); + GlobalVariable.globalCodeRefs.put(name, codeCell); + + Method predeclare = org.perlonjava.frontend.parser.ClassTransformer.class + .getDeclaredMethod("predeclareConstructor", String.class); + predeclare.setAccessible(true); + predeclare.invoke(null, "CodeOwner::Widget"); + + RuntimeCode constructor = (RuntimeCode) codeCell.value; + assertNotNull(codeCell.countedOwnerSlot()); + assertSame(constructor, codeCell.countedOwnerSlot().referent()); + assertEquals(1, constructor.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + GlobalVariable.resetAllGlobals(); + } + } + + private static RuntimeCode undefinedCode() { + return new RuntimeCode((String) null, null); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeStashOwnerReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeStashOwnerReleaseTest.java new file mode 100644 index 0000000000..39374de9e5 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeStashOwnerReleaseTest.java @@ -0,0 +1,53 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RuntimeCodeStashOwnerReleaseTest { + @Test + void activeCallReleasesStateAfterLastStashOwnerLeavesDespiteStaleBridgeCount() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + String name = "RuntimeCodeStashOwnerReleaseTest::active"; + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + code.hadStashRef = true; + code.stashRefCount = 1; + + RuntimeScalar stashSlot = new RuntimeScalar(); + stashSlot.type = RuntimeScalarType.CODE; + stashSlot.value = code; + GlobalVariable.globalCodeRefs.put(name, stashSlot); + + RuntimeScalar weak = new RuntimeScalar(); + weak.type = RuntimeScalarType.CODE; + weak.value = code; + WeakRefRegistry.weaken(weak); + // The bridge count can outlive its Perl owners during the staged + // migration; the owner ledger must decide final state cleanup. + code.setTrackedRefCount(5); + + PerlOwnerSlot activeCall = + new PerlOwnerSlot(PerlOwnerSlot.Kind.ACTIVE_CODE); + activeCall.acquireActiveCodeIdentity(code); + + try { + GlobalVariable.removeGlobalCodeRefForStashDelete(name); + assertTrue(WeakRefRegistry.isweak(weak), + "the active call keeps CODE state alive until it returns"); + + activeCall.release(); + + assertEquals(RuntimeScalarType.UNDEF, weak.type, + "the active call releases Perl state despite a stale bridge count"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + code.perlLifecycleState()); + } finally { + if (activeCall.isActive()) activeCall.release(); + GlobalVariable.globalCodeRefs.remove(name); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeStateGraphClonerOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeStateGraphClonerOwnerTest.java new file mode 100644 index 0000000000..6d75e36c00 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeStateGraphClonerOwnerTest.java @@ -0,0 +1,70 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; + +@Tag("unit") +class RuntimeCodeStateGraphClonerOwnerTest { + @Test + void clonedPersistentStateRebuildsIndependentOwnerSlots() { + PerlRuntime sourceRuntime = new PerlRuntime(); + PerlRuntime targetRuntime = new PerlRuntime(); + RuntimeCode sourceCode; + RuntimeScalar sourceScalar; + RuntimeArray sourceArray; + RuntimeHash sourceHash; + RuntimeScalar sourceAliasCell; + RuntimeScalar sourceCodeRef; + try (PerlRuntime.Binding ignored = sourceRuntime.bind()) { + sourceCode = new RuntimeCode(null, List.of()); + sourceScalar = new RuntimeScalar(); + sourceScalar.localBindingExists = true; + sourceArray = new RuntimeArray(); + sourceHash = new RuntimeHash(); + RuntimeArray sourceAliasedArray = new RuntimeArray(); + sourceCode.bindStateScalar("scalar", sourceScalar); + sourceCode.bindStateArray("array", sourceArray); + sourceCode.bindStateHash("hash", sourceHash); + sourceCode.bindStateAggregateAlias("alias", sourceAliasedArray); + sourceAliasCell = sourceCode.stateAggregateAliasOwners.get("@alias"); + sourceCodeRef = new RuntimeScalar(sourceCode); + } + + RuntimeScalar clonedCodeRef = (RuntimeScalar) new RuntimeGraphCloner( + sourceRuntime, targetRuntime).cloneGraph(sourceCodeRef); + RuntimeCode clonedCode = (RuntimeCode) clonedCodeRef.value; + RuntimeScalar clonedScalar = clonedCode.stateVariable.get("scalar"); + RuntimeArray clonedArray = clonedCode.stateArray.get("array"); + RuntimeHash clonedHash = clonedCode.stateHash.get("hash"); + RuntimeScalar clonedAliasCell = clonedCode.stateAggregateAliasOwners.get("@alias"); + + assertNotSame(sourceCodeRef, clonedCodeRef); + assertNotSame(sourceScalar, clonedScalar); + assertNotSame(sourceArray, clonedArray); + assertNotSame(sourceHash, clonedHash); + assertNotSame(sourceAliasCell, clonedAliasCell); + assertEquals(1, sourceScalar.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + assertEquals(1, sourceArray.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + assertEquals(1, sourceHash.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + assertEquals(1, sourceAliasCell.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + assertEquals(1, clonedScalar.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + assertEquals(1, clonedArray.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + assertEquals(1, clonedHash.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + assertEquals(1, clonedAliasCell.ownerSlotCount(PerlOwnerSlot.Kind.CODE_STATE)); + + PerlRuntime targetBoundRuntime = targetRuntime; + try (PerlRuntime.Binding ignored = targetBoundRuntime.bind()) { + assertSame(clonedCode.stateArray.get("alias"), clonedAliasCell.countedOwnerSlot().referent()); + clonedCode.releaseStateStorage(); + } + try (PerlRuntime.Binding ignored = sourceRuntime.bind()) { + sourceCode.releaseStateStorage(); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeTemporaryCaptureOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeTemporaryCaptureOwnerTest.java new file mode 100644 index 0000000000..3f13739640 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeCodeTemporaryCaptureOwnerTest.java @@ -0,0 +1,66 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RuntimeCodeTemporaryCaptureOwnerTest { + @Test + void scopeExitUsesOwnerIdentitiesWhenTheCompatibilityCountIsStale() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar capturedPad = new RuntimeScalar(42); + PerlOwnerSlot captureOwner = capturedPad.retainClosureCaptureSlot(closure); + closure.capturedScalars = new RuntimeScalar[] {capturedPad}; + closure.capturedScalarOwnerSlots = new PerlOwnerSlot[] {captureOwner}; + closure.setTrackedRefCount(7); // No owner slot backs this compatibility count. + + RuntimeScalar temporary = new RuntimeScalar(); + temporary.type = RuntimeScalarType.CODE; + temporary.value = closure; + + RuntimeScalar.scopeExitCleanup(temporary); + + assertNull(closure.capturedScalars, + "an ownerless temporary CODE releases captures despite a stale count"); + assertFalse(captureOwner.isActive()); + } + } + + @Test + void activeCodeOwnerDefersTemporaryCaptureReleaseUntilReturn() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar capturedPad = new RuntimeScalar(42); + PerlOwnerSlot captureOwner = capturedPad.retainClosureCaptureSlot(closure); + closure.capturedScalars = new RuntimeScalar[] {capturedPad}; + closure.capturedScalarOwnerSlots = new PerlOwnerSlot[] {captureOwner}; + closure.setTrackedRefCount(7); + + RuntimeScalar temporary = new RuntimeScalar(); + temporary.type = RuntimeScalarType.CODE; + temporary.value = closure; + + RuntimeCode.pushActiveCode(closure); + try { + RuntimeScalar.scopeExitCleanup(temporary); + assertNotNull(closure.capturedScalars, + "the active frame keeps its captured pad alive"); + assertTrue(captureOwner.isActive()); + } finally { + RuntimeCode.popActiveCode(closure); + } + + assertNull(closure.capturedScalars, + "the deferred request retires captures after the last active owner leaves"); + assertFalse(captureOwner.isActive()); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeGlobAliasCodeSlotOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeGlobAliasCodeSlotOwnerTest.java new file mode 100644 index 0000000000..43bee30200 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeGlobAliasCodeSlotOwnerTest.java @@ -0,0 +1,48 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +@Tag("unit") +class RuntimeGlobAliasCodeSlotOwnerTest { + @Test + void aliasedStashNamesShareOneCountedSlotWithoutLegacyCounterMutation() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + GlobalVariable.resetAllGlobals(); + String sourceName = "RuntimeGlobAliasCodeSlotOwnerTest::source"; + String aliasName = "RuntimeGlobAliasCodeSlotOwnerTest::alias"; + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + code.stashRefCount = 11; + RuntimeScalar sourceSlot = new RuntimeScalar(code); + GlobalVariable.globalCodeRefs.put(sourceName, sourceSlot); + + try { + assertEquals(1, code.refCount); + assertEquals(1, code.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + + RuntimeGlob.aliasCodeSlot(aliasName, sourceSlot); + + assertSame(sourceSlot, GlobalVariable.globalCodeRefs.get(aliasName)); + assertEquals(1, code.refCount, + "whole-glob aliases share the existing CODE scalar owner"); + assertEquals(1, code.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + assertEquals(11, code.stashRefCount, + "the unused legacy counter does not participate in ownership"); + + GlobalVariable.globalCodeRefs.remove(sourceName); + assertEquals(1, code.refCount, + "removing one alias leaves the shared stash slot alive"); + GlobalVariable.globalCodeRefs.remove(aliasName); + assertEquals(0, code.ownerSlotCount(PerlOwnerSlot.Kind.CODE_SLOT)); + } finally { + GlobalVariable.globalCodeRefs.remove(sourceName); + GlobalVariable.globalCodeRefs.remove(aliasName); + GlobalVariable.resetAllGlobals(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeGraphClonerIoOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeGraphClonerIoOwnerTest.java new file mode 100644 index 0000000000..01c57ae939 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeGraphClonerIoOwnerTest.java @@ -0,0 +1,68 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.perlonjava.runtime.io.CustomFileChannel; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RuntimeGraphClonerIoOwnerTest { + @TempDir Path temporaryDirectory; + + @Test + void clonedScalarReacquiresAnonymousIoHolderInChildRuntime() throws Exception { + Path path = temporaryDirectory.resolve("anonymous-handle.txt"); + Files.writeString(path, "payload"); + PerlRuntime sourceRuntime = new PerlRuntime(); + PerlRuntime targetRuntime = new PerlRuntime(); + RuntimeIO sourceIO = new RuntimeIO(new CustomFileChannel(path, + Set.of(StandardOpenOption.READ, StandardOpenOption.WRITE))); + RuntimeGlob sourceGlob = new RuntimeGlob(null).setIO(sourceIO); + RuntimeScalar sourceScalar = globReference(sourceGlob); + try (PerlRuntime.Binding ignored = sourceRuntime.bind()) { + RuntimeScalar.retainUnstashedIoForDurableSlot(sourceScalar); + assertEquals(1, sourceGlob.ioHolderCount()); + } + + RuntimeScalar targetScalar = (RuntimeScalar) new RuntimeGraphCloner( + sourceRuntime, targetRuntime).cloneGraph(sourceScalar); + RuntimeGlob targetGlob = (RuntimeGlob) targetScalar.value; + RuntimeIO targetIO = (RuntimeIO) targetGlob.getIO().value; + + try (PerlRuntime.Binding ignored = targetRuntime.bind()) { + assertNotSame(sourceGlob, targetGlob); + assertNotSame(sourceIO, targetIO); + assertTrue(targetScalar.hasIoOwner(), + "the cloned scalar needs its own runtime-local IO holder"); + assertSame(targetGlob, targetScalar.ioOwnerSlot.referent()); + assertEquals(1, targetGlob.ioHolderCount()); + RuntimeScalar.releaseIoOwner(targetScalar); + assertEquals(0, targetGlob.ioHolderCount()); + assertEquals(1, sourceGlob.ioHolderCount(), + "releasing the child lease must preserve the parent lease"); + targetIO.close(); + } finally { + try (PerlRuntime.Binding ignored = sourceRuntime.bind()) { + RuntimeScalar.releaseIoOwner(sourceScalar); + sourceIO.close(); + } + } + } + + private static RuntimeScalar globReference(RuntimeGlob glob) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.GLOBREFERENCE; + scalar.value = glob; + return scalar; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeGraphClonerScalarOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeGraphClonerScalarOwnerTest.java new file mode 100644 index 0000000000..2951b9292a --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeGraphClonerScalarOwnerTest.java @@ -0,0 +1,57 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RuntimeGraphClonerScalarOwnerTest { + @Test + void clonedCountedScalarAcquiresAndReleasesItsChildOwnerSlot() { + PerlRuntime sourceRuntime = new PerlRuntime(); + PerlRuntime targetRuntime = new PerlRuntime(); + RuntimeHash sourceReferent = new RuntimeHash(); + RuntimeScalar sourceOwner = new RuntimeScalar(); + try (PerlRuntime.Binding ignored = sourceRuntime.bind()) { + sourceOwner.set(sourceReferent.createAnonymousReference()); + assertEquals(1, sourceReferent.refCount); + assertEquals(1, sourceReferent.countedOwnerSlotCount()); + } + + RuntimeScalar clonedOwner = (RuntimeScalar) new RuntimeGraphCloner( + sourceRuntime, targetRuntime).cloneGraph(sourceOwner); + RuntimeHash clonedReferent = (RuntimeHash) clonedOwner.value; + RuntimeScalar weakObserver = new RuntimeScalar(); + try (PerlRuntime.Binding ignored = targetRuntime.bind()) { + assertEquals(1, clonedReferent.refCount); + assertEquals(1, clonedReferent.countedOwnerSlotCount()); + assertEquals(1, clonedReferent.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + assertTrue(clonedOwner.refCountOwned); + + weakObserver.set(clonedOwner); + WeakRefRegistry.weaken(weakObserver); + assertEquals(1, clonedReferent.refCount); + + clonedOwner.undefine(); + + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type, + "releasing the cloned owner clears its final weak observer"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, clonedReferent.perlLifecycleState()); + assertEquals(0, clonedReferent.refCount); + } finally { + try (PerlRuntime.Binding ignored = targetRuntime.bind()) { + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + if (clonedOwner.refCountOwned) clonedOwner.undefine(); + } + try (PerlRuntime.Binding ignored = sourceRuntime.bind()) { + if (sourceOwner.refCountOwned) sourceOwner.undefine(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeGraphClonerSnapshotRootFailureTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeGraphClonerSnapshotRootFailureTest.java new file mode 100644 index 0000000000..583c424ab7 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeGraphClonerSnapshotRootFailureTest.java @@ -0,0 +1,39 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@Tag("unit") +class RuntimeGraphClonerSnapshotRootFailureTest { + @Test + void failedLaterRootReleasesEarlierTemporaryRootSlots() { + PerlRuntime source = new PerlRuntime(); + PerlRuntime target = new PerlRuntime(); + RuntimeHash firstRoot = new RuntimeHash(); + RuntimeScalar destroyedSharedRoot = new RuntimeScalar(); + destroyedSharedRoot.threadShared = true; + destroyedSharedRoot.markPerlDestroyed(); + RuntimeGraphCloner cloner = new RuntimeGraphCloner(source, target); + + try (PerlRuntime.Binding ignored = target.bind()) { + IllegalStateException failure = assertThrows(IllegalStateException.class, + () -> cloner.cloneSnapshotRoots(List.of(firstRoot, destroyedSharedRoot))); + assertEquals("cannot retain a destroyed temporary root", failure.getMessage()); + + RuntimeHash clonedFirstRoot = (RuntimeHash) cloner.cloneValue(firstRoot); + assertEquals(0, clonedFirstRoot.ownerSlotCount(PerlOwnerSlot.Kind.TEMPORARY_ROOT)); + } finally { + RuntimeBase clonedFirstRoot = cloner.cloneValue(firstRoot); + for (PerlOwnerSlot owner : clonedFirstRoot.ownerSlotSnapshot()) { + if (owner.kind() == PerlOwnerSlot.Kind.TEMPORARY_ROOT) owner.release(); + } + source.close(); + target.close(); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeHashClonedElementReplacementOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeHashClonedElementReplacementOwnerTest.java new file mode 100644 index 0000000000..39d5f3a05a --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeHashClonedElementReplacementOwnerTest.java @@ -0,0 +1,62 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RuntimeHashClonedElementReplacementOwnerTest { + @Test + void clonedElementReplacementReleasesTheDisplacedOwnerAfterAcquiringTheNewOne() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash displaced = new RuntimeHash(); + RuntimeScalar displacedValue = countedValue(displaced); + RuntimeHash destination = new RuntimeHash(); + destination.putClonedElement("slot", displacedValue); + + RuntimeScalar weakObserver = displaced.createAnonymousReference(); + RuntimeHash replacement = new RuntimeHash(); + RuntimeScalar replacementValue = countedValue(replacement); + try { + WeakRefRegistry.weaken(weakObserver); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + + destination.putClonedElement("slot", replacementValue); + + assertSame(replacementValue, destination.elements.get("slot")); + assertEquals(PerlOwnerSlot.Kind.HASH_ELEMENT, + replacementValue.countedOwnerSlot().kind()); + assertEquals(1, replacement.refCount, + "the replacement is acquired before the displaced value is drained"); + + MortalList.flush(); + + assertFalse(WeakRefRegistry.isweak(weakObserver), + "replacing the final hash owner clears the displaced weak observer"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, displaced.perlLifecycleState()); + assertEquals(0, displaced.refCount); + + destination.putClonedElement("slot", null); + MortalList.flush(); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, replacement.perlLifecycleState()); + assertEquals(0, replacement.refCount); + } finally { + if (WeakRefRegistry.isweak(weakObserver)) WeakRefRegistry.unweaken(weakObserver); + weakObserver.set(new RuntimeScalar()); + destination.putClonedElement("slot", null); + MortalList.flush(); + } + } + } + + private static RuntimeScalar countedValue(RuntimeHash referent) { + RuntimeScalar value = new RuntimeScalar(); + value.set(referent.createAnonymousReference()); + return value; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeHashIdentityMembershipTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeHashIdentityMembershipTest.java new file mode 100644 index 0000000000..671674f3ee --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeHashIdentityMembershipTest.java @@ -0,0 +1,63 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RuntimeHashIdentityMembershipTest { + @Test + void identityMembershipTracksEveryOwnedSlotMutation() { + RuntimeHash hash = new RuntimeHash(); + RuntimeScalar sharedCell = new RuntimeScalar("same"); + RuntimeScalar equalButDistinctCell = new RuntimeScalar("same"); + + hash.elements.put("first", sharedCell); + assertTrue(hash.containsElementCellIdentity(sharedCell)); + assertFalse(hash.containsElementCellIdentity(equalButDistinctCell)); + + hash.elements.put("second", sharedCell); + hash.elements.put("first", new RuntimeScalar("replacement")); + assertTrue(hash.containsElementCellIdentity(sharedCell), + "one of two slots still contains the same scalar cell"); + + hash.elements.remove("second"); + assertFalse(hash.containsElementCellIdentity(sharedCell), + "removing its final slot removes the identity entry"); + + Map bulk = new LinkedHashMap<>(); + bulk.put("bulk-a", sharedCell); + bulk.put("bulk-b", sharedCell); + hash.elements.putAll(bulk); + assertTrue(hash.containsElementCellIdentity(sharedCell)); + + var values = hash.elements.values().iterator(); + while (values.hasNext()) { + if (values.next() == sharedCell) { + values.remove(); + break; + } + } + assertTrue(hash.containsElementCellIdentity(sharedCell), + "removing one duplicate through values() preserves the other slot"); + + var entries = hash.elements.entrySet().iterator(); + while (entries.hasNext()) { + if (entries.next().getValue() == sharedCell) { + entries.remove(); + break; + } + } + assertFalse(hash.containsElementCellIdentity(sharedCell), + "removing the final duplicate through entrySet() clears membership"); + + hash.elements.put("last", sharedCell); + hash.elements.clear(); + assertFalse(hash.containsElementCellIdentity(sharedCell)); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeHashSetFromListTemporaryOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeHashSetFromListTemporaryOwnerTest.java new file mode 100644 index 0000000000..34d7006630 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeHashSetFromListTemporaryOwnerTest.java @@ -0,0 +1,37 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Tag("unit") +class RuntimeHashSetFromListTemporaryOwnerTest { + @Test + void releasingHashAssignmentTemporariesRetiresTheirUntrackedValueOwners() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + referent.markRefCountWeaklyTracked(); + + RuntimeScalar sourceValue = new RuntimeScalar(); + sourceValue.type = RuntimeScalarType.HASHREFERENCE; + sourceValue.value = referent; + + RuntimeHash target = new RuntimeHash(); + RuntimeArray assignmentResult = target.setFromList(new RuntimeList( + new RuntimeScalar("item"), sourceValue)); + + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE), + "the private RHS materialization releases its value owner before returning"); + + assignmentResult.elements.clear(); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE), + "the returned assignment value is the hash, not another value edge"); + + target.elements.clear(); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE), + "hash assignment releases its private RHS materialization when it returns"); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarContainerOwnerConsistencyTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarContainerOwnerConsistencyTest.java new file mode 100644 index 0000000000..54bdda1570 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarContainerOwnerConsistencyTest.java @@ -0,0 +1,213 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +@Tag("unit") +class RuntimeScalarContainerOwnerConsistencyTest { + @Test + void stalePreferredOwnerIsReplacedByAStillStoredContainer() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar value = new RuntimeHash().createAnonymousReference(); + RuntimeArray survivingOwner = new RuntimeArray(); + RuntimeArray removedOwner = new RuntimeArray(); + + survivingOwner.elements.add(value); + removedOwner.elements.add(value); + assertSame(removedOwner, value.getContainerOwner()); + + removedOwner.elements.remove(value); + + assertSame(survivingOwner, value.getContainerOwner()); + } + } + + @Test + void packageRootOwnerSurvivesWhenCurrentOwnerChanges() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar value = new RuntimeHash().createAnonymousReference(); + RuntimeArray packageRoot = new RuntimeArray(); + RuntimeArray otherOwner = new RuntimeArray(); + + packageRoot.elements.add(value); + GlobalVariable.markPackageGlobalRoot(packageRoot); + otherOwner.elements.add(value); + assertSame(otherOwner, value.getContainerOwner()); + + assertNotNull(value.untrackedReferenceOwnerSlot()); + } + } + + @Test + void slotRemovalRetiresOnlyTheEdgesThatNoLongerExist() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar value = new RuntimeHash().createAnonymousReference(); + RuntimeArray array = new RuntimeArray(); + array.elements.add(value); + assertSame(array, value.getContainerOwner()); + + array.elements.remove(value); + assertNull(value.getContainerOwner()); + + RuntimeHash hash = new RuntimeHash(); + hash.elements.put("first", value); + hash.elements.put("second", value); + hash.elements.remove("first"); + assertSame(hash, value.getContainerOwner()); + + hash.elements.remove("second"); + assertNull(value.getContainerOwner()); + } + } + + @Test + void dynamicStateRestoreRebindsOwnersToTheLiveAggregate() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar arrayValue = new RuntimeHash().createAnonymousReference(); + RuntimeArray array = new RuntimeArray(); + array.elements.add(arrayValue); + array.dynamicSaveState(); + array.dynamicRestoreState(); + assertSame(array, arrayValue.getContainerOwner()); + + RuntimeScalar hashValue = new RuntimeHash().createAnonymousReference(); + RuntimeHash hash = new RuntimeHash(); + hash.elements.put("value", hashValue); + hash.dynamicSaveState(); + hash.dynamicRestoreState(); + assertSame(hash, hashValue.getContainerOwner()); + } + } + + @Test + void arrayIteratorRemovalRetiresTheContainerOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar value = new RuntimeHash().createAnonymousReference(); + RuntimeArray array = new RuntimeArray(); + array.elements.add(value); + + var iterator = array.elements.iterator(); + assertSame(value, iterator.next()); + iterator.remove(); + + assertNull(value.getContainerOwner()); + } + } + + @Test + void arrayBulkRemovalRetiresTheContainerOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar value = new RuntimeHash().createAnonymousReference(); + RuntimeArray array = new RuntimeArray(); + array.elements.add(value); + + array.elements.removeAll(java.util.List.of(value)); + + assertNull(value.getContainerOwner()); + } + } + + @Test + void arrayBulkReplacementUpdatesContainerOwners() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar oldValue = new RuntimeHash().createAnonymousReference(); + RuntimeScalar newValue = new RuntimeHash().createAnonymousReference(); + RuntimeArray array = new RuntimeArray(); + array.elements.add(oldValue); + + array.elements.replaceAll(ignoredValue -> newValue); + + assertNull(oldValue.getContainerOwner()); + assertSame(array, newValue.getContainerOwner()); + } + } + + @Test + void hashEntryViewRemovalRetiresTheContainerOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar value = new RuntimeHash().createAnonymousReference(); + RuntimeHash hash = new RuntimeHash(); + hash.elements.put("value", value); + + var iterator = hash.elements.entrySet().iterator(); + assertSame(value, iterator.next().getValue()); + iterator.remove(); + + assertNull(value.getContainerOwner()); + } + } + + @Test + void hashEntryReplacementUpdatesBothContainerOwners() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar oldValue = new RuntimeHash().createAnonymousReference(); + RuntimeScalar newValue = new RuntimeHash().createAnonymousReference(); + RuntimeHash hash = new RuntimeHash(); + hash.elements.put("value", oldValue); + + hash.elements.entrySet().iterator().next().setValue(newValue); + + assertNull(oldValue.getContainerOwner()); + assertSame(hash, newValue.getContainerOwner()); + } + } + + @Test + void hashValuesViewRemovalRetiresTheContainerOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar value = new RuntimeHash().createAnonymousReference(); + RuntimeHash hash = new RuntimeHash(); + hash.elements.put("value", value); + + hash.elements.values().remove(value); + + assertNull(value.getContainerOwner()); + } + } + + @Test + void hashKeyViewRemovalRetiresTheContainerOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar value = new RuntimeHash().createAnonymousReference(); + RuntimeHash hash = new RuntimeHash(); + hash.elements.put("value", value); + + var iterator = hash.elements.keySet().iterator(); + assertSame("value", iterator.next()); + iterator.remove(); + + assertNull(value.getContainerOwner()); + } + } + + @Test + void hashComputeReplacementUpdatesContainerOwners() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar oldValue = new RuntimeHash().createAnonymousReference(); + RuntimeScalar newValue = new RuntimeHash().createAnonymousReference(); + RuntimeHash hash = new RuntimeHash(); + hash.elements.put("value", oldValue); + + hash.elements.computeIfPresent("value", (key, value) -> newValue); + + assertNull(oldValue.getContainerOwner()); + assertSame(hash, newValue.getContainerOwner()); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarCountedOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarCountedOwnerSlotTest.java new file mode 100644 index 0000000000..2a67260cc9 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarCountedOwnerSlotTest.java @@ -0,0 +1,52 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RuntimeScalarCountedOwnerSlotTest { + @Test + void scalarReleasePreservesTheArrayElementOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId("RuntimeScalarCountedOwnerRepairTest::Target"); + RuntimeArray arrayOwner = new RuntimeArray(); + arrayOwner.push(target.createAnonymousReference()); + + RuntimeScalar scalarOwner = new RuntimeScalar(); + scalarOwner.set(target.createAnonymousReference()); + RuntimeScalar observer = target.createAnonymousReference(); + WeakRefRegistry.weaken(observer); + + try { + assertFalse(target.storedInPackageGlobal); + assertFalse(target.localBindingExists); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + assertTrue(WeakRefRegistry.isweak(observer)); + + assertEquals(2, target.refCount, + "the scalar cell and array element each contribute one owner count"); + { + scalarOwner.set(new RuntimeScalar()); + + assertEquals(1, target.refCount); + assertEquals(1, target.countedOwnerSlotCount()); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + assertTrue(WeakRefRegistry.isweak(observer)); + } + + arrayOwner.elements.get(0).set(new RuntimeScalar()); + assertFalse(WeakRefRegistry.isweak(observer), + "releasing the final counted slot clears the weak observer"); + } finally { + if (WeakRefRegistry.isweak(observer)) WeakRefRegistry.unweaken(observer); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarDirectSetterOwnerReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarDirectSetterOwnerReleaseTest.java new file mode 100644 index 0000000000..4bd53ab372 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarDirectSetterOwnerReleaseTest.java @@ -0,0 +1,55 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.math.BigInteger; +import java.util.List; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RuntimeScalarDirectSetterOwnerReleaseTest { + @Test + void assigningJavaNullReleasesThePriorScalarCellOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + List> setters = List.of( + cell -> cell.set("replacement"), + cell -> cell.set((String) null), + cell -> cell.set((RuntimeScalar) null), + cell -> cell.set(7), + cell -> cell.set(7L), + cell -> cell.set(BigInteger.valueOf(7)), + cell -> cell.set(true)); + for (Consumer setter : setters) { + assertSetterReleasesCurrentOwner(setter); + } + } + } + + private static void assertSetterReleasesCurrentOwner(Consumer setter) { + RuntimeHash referent = new RuntimeHash(); + + RuntimeScalar cell = new RuntimeScalar(); + cell.set(referent.createAnonymousReference()); + RuntimeScalar weakObserver = referent.createAnonymousReference(); + WeakRefRegistry.weaken(weakObserver); + assertTrue(cell.refCountOwned); + assertEquals(1, referent.refCount); + + setter.accept(cell); + MortalList.flush(); + + assertFalse(cell.refCountOwned, + "primitive/string setter retires the prior scalar-content owner token"); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the final referent owner clears its weak observer"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState(), + "the referent is finalized after its scalar cell is overwritten"); + assertEquals(0, referent.refCount); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarIoOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarIoOwnerSlotTest.java new file mode 100644 index 0000000000..f8f6dfd03f --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarIoOwnerSlotTest.java @@ -0,0 +1,207 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.runtime.io.StandardIO; +import org.perlonjava.runtime.operators.IOOperator; + +import java.io.ByteArrayOutputStream; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class RuntimeScalarIoOwnerSlotTest { + private PerlRuntime runtime; + private PerlRuntime.Binding runtimeBinding; + + @BeforeEach + void bindRuntime() { + runtime = new PerlRuntime(); + runtimeBinding = runtime.bind(); + } + + @AfterEach + void unbindRuntime() { + runtimeBinding.close(); + } + + @Test + void durableIoOwnerHasOneIdentityAndReleasesExactlyOnce() { + RuntimeGlob glob = anonymousGlob(); + RuntimeScalar owner = handle(glob); + + RuntimeScalar.retainUnstashedIoForDurableSlot(owner); + PerlOwnerSlot ownerSlot = owner.ioOwnerSlot; + + assertTrue(owner.hasIoOwner()); + assertNotNull(ownerSlot); + assertEquals(PerlOwnerSlot.Kind.IO_RESOURCE_HOLDER, ownerSlot.kind()); + assertTrue(ownerSlot.isNativeOwner()); + assertSame(glob, ownerSlot.referent()); + assertEquals(1, glob.ioHolderCount()); + assertEquals(1, glob.ownerSlotCount(PerlOwnerSlot.Kind.IO_RESOURCE_HOLDER)); + + RuntimeScalar.releaseIoOwner(owner); + RuntimeScalar.releaseIoOwner(owner); + + assertFalse(owner.hasIoOwner()); + assertNull(owner.ioOwnerSlot); + assertFalse(ownerSlot.isActive()); + assertEquals(0, glob.ioHolderCount()); + assertEquals(0, glob.ownerSlotCount(PerlOwnerSlot.Kind.IO_RESOURCE_HOLDER)); + } + + @Test + void ownerTransferPreservesIdentityAndHolderCount() { + RuntimeGlob glob = anonymousGlob(); + RuntimeScalar source = handle(glob); + RuntimeScalar destination = handle(glob); + + RuntimeScalar.retainUnstashedIoForDurableSlot(source); + PerlOwnerSlot ownerSlot = source.ioOwnerSlot; + RuntimeScalar.transferIoOwner(source, destination); + + assertFalse(source.hasIoOwner()); + assertNull(source.ioOwnerSlot); + assertTrue(destination.hasIoOwner()); + assertSame(ownerSlot, destination.ioOwnerSlot); + assertEquals(1, glob.ioHolderCount()); + assertEquals(1, glob.ownerSlotCount(PerlOwnerSlot.Kind.IO_RESOURCE_HOLDER)); + + RuntimeScalar.releaseIoOwner(destination); + assertEquals(0, glob.ioHolderCount()); + } + + @Test + void distinctScalarAliasesHaveDistinctOwnerIdentities() { + RuntimeGlob glob = anonymousGlob(); + RuntimeScalar first = handle(glob); + RuntimeScalar second = handle(glob); + + RuntimeScalar.retainUnstashedIoForDurableSlot(first); + RuntimeScalar.retainUnstashedIoForDurableSlot(second); + + assertNotSame(first.ioOwnerSlot, second.ioOwnerSlot); + assertEquals(2, glob.ioHolderCount()); + assertEquals(2, glob.ownerSlotCount(PerlOwnerSlot.Kind.IO_RESOURCE_HOLDER)); + + RuntimeScalar.releaseIoOwner(first); + assertEquals(1, glob.ioHolderCount()); + assertTrue(second.ioOwnerSlot.isActive()); + RuntimeScalar.releaseIoOwner(second); + assertEquals(0, glob.ioHolderCount()); + } + + @Test + void sysopenOnExistingGlobRetainsEveryCurrentScalarOwner() throws Exception { + RuntimeGlob glob = new RuntimeGlob(null); + RuntimeScalar handle = handle(glob); + RuntimeScalar alias = handle(glob); + retainCountedAlias(glob, handle); + retainCountedAlias(glob, alias); + MyVarCleanupStack.register(handle); + MyVarCleanupStack.register(alias); + Path path = Files.createTempFile("perlonjava-sysopen-owner-", ".tmp"); + + try { + RuntimeScalar result = IOOperator.sysopen(0, + handle, + new RuntimeScalar(path.toString()), + new RuntimeScalar(2)); // O_RDWR + + assertTrue(result.getBoolean()); + assertTrue(handle.hasIoOwner()); + assertTrue(alias.hasIoOwner(), + "opening an existing glob must retain each scalar cell that owns it"); + assertEquals(2, glob.ioHolderCount()); + assertEquals(2, glob.ownerSlotCount(PerlOwnerSlot.Kind.IO_RESOURCE_HOLDER)); + } finally { + RuntimeScalar io = glob.getIO(); + if (io != null && io.value instanceof RuntimeIO runtimeIO) runtimeIO.close(); + RuntimeScalar.releaseIoOwner(handle); + RuntimeScalar.releaseIoOwner(alias); + MyVarCleanupStack.unregister(alias); + MyVarCleanupStack.unregister(handle); + Files.deleteIfExists(path); + } + } + + @Test + void expressionCopyMovesOwnerButPackageScalarCopyKeepsItsOwner() { + RuntimeGlob expressionGlob = anonymousGlob(); + RuntimeScalar expression = handle(expressionGlob); + RuntimeScalar.retainUnstashedIoForDurableSlot(expression); + PerlOwnerSlot expressionOwner = expression.ioOwnerSlot; + + RuntimeScalar expressionCopy = new RuntimeScalar(expression); + + assertFalse(expression.hasIoOwner()); + assertSame(expressionOwner, expressionCopy.ioOwnerSlot); + assertEquals(1, expressionGlob.ioHolderCount()); + + RuntimeGlob packageGlob = anonymousGlob(); + RuntimeScalar packageScalar = handle(packageGlob); + packageScalar.isPackageGlobalRoot = true; + RuntimeScalar.retainUnstashedIoForDurableSlot(packageScalar); + PerlOwnerSlot packageOwner = packageScalar.ioOwnerSlot; + + RuntimeScalar packageCopy = new RuntimeScalar(packageScalar); + + assertTrue(packageScalar.hasIoOwner()); + assertFalse(packageCopy.hasIoOwner()); + assertSame(packageOwner, packageScalar.ioOwnerSlot); + assertEquals(1, packageGlob.ioHolderCount()); + + RuntimeScalar.transferIoOwner(packageScalar, packageCopy); + assertSame(packageOwner, packageCopy.ioOwnerSlot); + RuntimeScalar.releaseIoOwner(expressionCopy); + RuntimeScalar.releaseIoOwner(packageCopy); + } + + @Test + void selfAssignmentPreservesOwnerAndReplacementAcquiresBeforeRetiringOldSlot() { + RuntimeGlob firstGlob = anonymousGlob(); + RuntimeGlob replacementGlob = anonymousGlob(); + RuntimeScalar owner = handle(firstGlob); + RuntimeScalar.retainUnstashedIoForDurableSlot(owner); + PerlOwnerSlot originalOwnerSlot = owner.ioOwnerSlot; + + owner.set(owner); + assertSame(originalOwnerSlot, owner.ioOwnerSlot); + assertEquals(1, firstGlob.ioHolderCount()); + + RuntimeScalar replacement = handle(replacementGlob); + owner.set(replacement); + + assertFalse(originalOwnerSlot.isActive()); + assertEquals(0, firstGlob.ioHolderCount()); + assertEquals(0, firstGlob.ownerSlotCount(PerlOwnerSlot.Kind.IO_RESOURCE_HOLDER)); + assertTrue(owner.hasIoOwner()); + assertSame(replacementGlob, owner.ioOwnerSlot.referent()); + assertEquals(1, replacementGlob.ioHolderCount()); + assertEquals(1, replacementGlob.ownerSlotCount( + PerlOwnerSlot.Kind.IO_RESOURCE_HOLDER)); + } + + private static RuntimeScalar handle(RuntimeGlob glob) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.GLOBREFERENCE; + scalar.value = glob; + return scalar; + } + + private static RuntimeGlob anonymousGlob() { + return new RuntimeGlob(null).setIO(new RuntimeIO( + new StandardIO(new ByteArrayOutputStream(), true))); + } + + private static void retainCountedAlias(RuntimeGlob glob, RuntimeScalar alias) { + alias.refCountOwned = true; + glob.recordOwner(alias, "existing glob IO owner regression"); + glob.recordActiveOwner(alias); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarOwnerSlotTest.java new file mode 100644 index 0000000000..163689fef3 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarOwnerSlotTest.java @@ -0,0 +1,271 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class RuntimeScalarOwnerSlotTest { + @Test + void independentScalarCellsKeepTheirIdentitiesAcrossOverwriteAndSameReferentAssignment() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash first = new RuntimeHash(); + RuntimeHash replacement = new RuntimeHash(); + RuntimeScalar left = new RuntimeScalar(); + RuntimeScalar right = new RuntimeScalar(); + RuntimeScalar reference = first.createReference(); + + left.set(reference); + right.set(reference); + PerlOwnerSlot leftSlot = left.countedOwnerSlot(); + PerlOwnerSlot rightSlot = right.countedOwnerSlot(); + + assertNotEquals(leftSlot.identity(), rightSlot.identity()); + assertEquals(2, first.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + assertEquals(2, first.refCount); + assertEquals(0, runtime.positiveOwnerSlotReferentCount(first)); + + left.set(reference); + assertSame(leftSlot, left.countedOwnerSlot()); + assertSame(first, leftSlot.referent()); + assertEquals(2, first.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + assertEquals(2, first.refCount); + + left.set(replacement.createReference()); + assertSame(leftSlot, left.countedOwnerSlot()); + assertSame(replacement, leftSlot.referent()); + assertSame(first, rightSlot.referent()); + assertEquals(1, first.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + assertEquals(1, replacement.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + assertEquals(1, first.refCount); + + left.set(new RuntimeScalar()); + assertFalse(leftSlot.isActive()); + assertEquals(0, replacement.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + assertTrue(rightSlot.isActive()); + } + } + + @Test + void arrayRemovalCarriesTheRemovedElementsIdentityUntilItsDecrementDrains() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + MortalList.pushMark(); + RuntimeHash target = new RuntimeHash(); + RuntimeArray array = new RuntimeArray(); + array.push(target.createReference()); + array.push(target.createReference()); + PerlOwnerSlot retainedSlot = array.elements.get(0).countedOwnerSlot(); + PerlOwnerSlot removedSlot = array.elements.get(1).countedOwnerSlot(); + + assertNotEquals(retainedSlot.identity(), removedSlot.identity()); + assertEquals(2, target.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + assertEquals(0, runtime.positiveOwnerSlotReferentCount(target)); + + RuntimeScalar removed = RuntimeArray.pop(array); + RuntimeBase.PendingOwnerRelease pending = runtime.lifecycleState.pendingOwnerReleases.getLast(); + PerlOwnerSlot.PendingRelease release = pending.ownerSlotRelease; + + assertNotNull(release); + assertEquals(removedSlot.identity(), release.ownerSlotIdentity()); + assertEquals(PerlOwnerSlot.Kind.ARRAY_ELEMENT, release.kind()); + assertFalse(release.isCompleted()); + assertFalse(removed.refCountOwned); + assertFalse(removedSlot.isActive()); + assertTrue(retainedSlot.isActive()); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + assertEquals(2, target.refCount); + + MortalList.flushAboveMark(); + assertTrue(release.isCompleted()); + assertEquals(1, target.refCount); + assertTrue(retainedSlot.isActive()); + MortalList.popMark(); + } + } + + @Test + void queuedReleaseCannotReleaseANewerValueStoredInTheSameCell() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + RuntimeHash first = new RuntimeHash(); + RuntimeHash next = new RuntimeHash(); + first.localBindingExists = true; + RuntimeScalar cell = new RuntimeScalar(); + cell.set(first.createReference()); + PerlOwnerSlot slot = cell.countedOwnerSlot(); + + MortalList.pushMark(); + MortalList.deferDecrementIfTracked(cell); + PerlOwnerSlot.PendingRelease release = + runtime.lifecycleState.pendingOwnerReleases.getLast().ownerSlotRelease; + assertNotNull(release); + assertEquals(slot.identity(), release.ownerSlotIdentity()); + + boolean previousSuppression = MortalList.suppressFlush(true); + try { + cell.set(next.createReference()); + } finally { + MortalList.suppressFlush(previousSuppression); + } + assertSame(slot, cell.countedOwnerSlot()); + assertSame(next, slot.referent()); + + MortalList.flushAboveMark(); + assertTrue(release.isCompleted()); + assertSame(next, slot.referent()); + assertEquals(1, next.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + assertEquals(0, first.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + MortalList.popMark(); + } + } + + @Test + void scopedCleanupDrainsItsEntriesDuringFlushSuppression() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + MortalList.pushScopeMark(); + + RuntimeHash earlier = new RuntimeHash(); + RuntimeScalar earlierOwner = new RuntimeScalar(); + earlierOwner.set(earlier.createReference()); + MortalList.deferDecrementIfTracked(earlierOwner); + PerlOwnerSlot.PendingRelease earlierRelease = + runtime.lifecycleState.pendingOwnerReleases.getLast().ownerSlotRelease; + + MortalList.pushScopeMark(); + RuntimeHash scoped = new RuntimeHash(); + RuntimeScalar scopedOwner = new RuntimeScalar(); + scopedOwner.set(scoped.createReference()); + MortalList.deferDecrementIfTracked(scopedOwner); + PerlOwnerSlot.PendingRelease scopedRelease = + runtime.lifecycleState.pendingOwnerReleases.getLast().ownerSlotRelease; + + boolean previousSuppression = MortalList.suppressFlush(true); + try { + MortalList.popScopeMarkAndFlush(); + } finally { + MortalList.suppressFlush(previousSuppression); + } + + assertTrue(scopedRelease.isCompleted(), + "scope cleanup drains entries created within its mark"); + assertFalse(earlierRelease.isCompleted(), + "scope cleanup leaves releases from before its mark pending"); + assertEquals(1, runtime.lifecycleState.pendingOwnerReleases.size()); + + MortalList.popScopeMarkAndFlush(); + assertTrue(earlierRelease.isCompleted()); + } + } + + @Test + void hashKeysOwnDistinctElementSlotsEvenWhenTheyStoreTheSameInputScalar() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + RuntimeHash hash = new RuntimeHash(); + RuntimeScalar reference = target.createReference(); + hash.put("left", reference); + hash.put("right", reference); + + PerlOwnerSlot left = hash.elements.get("left").countedOwnerSlot(); + PerlOwnerSlot right = hash.elements.get("right").countedOwnerSlot(); + assertNotEquals(left.identity(), right.identity()); + assertEquals(PerlOwnerSlot.Kind.HASH_ELEMENT, left.kind()); + assertEquals(PerlOwnerSlot.Kind.HASH_ELEMENT, right.kind()); + assertEquals(2, target.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + + WeakRefRegistry.weaken(hash.elements.get("left")); + assertFalse(left.isActive()); + assertTrue(right.isActive()); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + assertEquals(1, target.refCount); + } + } + + @Test + void overwritingAWeakHashSlotDoesNotReleaseItsTargetsChildOwners() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + RuntimeHash child = new RuntimeHash(); + RuntimeHash parent = new RuntimeHash(); + parent.put("child", child.createReference()); + RuntimeScalar strongParent = new RuntimeScalar(); + strongParent.set(parent.createReference()); + RuntimeScalar weakChild = child.createReference(); + WeakRefRegistry.weaken(weakChild); + + RuntimeHash observer = new RuntimeHash(); + observer.put("parent", parent.createReference()); + WeakRefRegistry.weaken(observer.elements.get("parent")); + PerlOwnerSlot childSlot = parent.elements.get("child").countedOwnerSlot(); + + observer.put("parent", new RuntimeScalar()); + + assertTrue(childSlot.isActive()); + assertTrue(parent.elements.get("child").refCountOwned); + assertEquals(1, child.refCount); + assertTrue(strongParent.countedOwnerSlot().isActive()); + } + } + + @Test + void finalElementOwnerClearsWeakReferencesWithoutConsultingAStaleRootSnapshot() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + int lexicalMark = MyVarCleanupStack.pushMark(); + try { + RuntimeArray child = new RuntimeArray(); + RuntimeScalar strong = new RuntimeScalar(); + strong.set(child.createAnonymousReference()); + RuntimeScalar weak = new RuntimeScalar(); + weak.set(strong); + WeakRefRegistry.weaken(weak); + RuntimeArray metadata = new RuntimeArray(); + metadata.push(strong); + RuntimeScalar metadataCell = new RuntimeScalar(); + metadataCell.set(metadata.createAnonymousReference()); + MyVarCleanupStack.register(metadataCell); + strong.set(new RuntimeScalar(1)); + { + metadataCell.set(new RuntimeScalar()); + + assertEquals(RuntimeScalarType.UNDEF, weak.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, child.perlLifecycleState()); + } + } finally { + MyVarCleanupStack.popMark(lexicalMark); + } + } + } + + @Test + void voidDiscardBorrowsAnActiveCapturedScalarInsteadOfConsumingItsOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray target = new RuntimeArray(); + RuntimeScalar pad = new RuntimeScalar(); + pad.set(target.createAnonymousReference()); + PerlOwnerSlot capture = pad.retainClosureCaptureSlot(); + PerlOwnerSlot valueOwner = pad.countedOwnerSlot(); + RuntimeList result = new RuntimeList(); + result.elements.add(pad); + + MortalList.mortalizeForVoidDiscard(result); + + assertTrue(pad.refCountOwned); + assertTrue(valueOwner.isActive()); + assertEquals(1, target.refCount); + assertTrue(runtime.lifecycleState.pendingOwnerReleases.isEmpty()); + pad.releaseClosureCaptureSlot(capture); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarUncountedOwnerRepairTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarUncountedOwnerRepairTest.java new file mode 100644 index 0000000000..ff9f332ade --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarUncountedOwnerRepairTest.java @@ -0,0 +1,71 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RuntimeScalarUncountedOwnerRepairTest { + @Test + void uncountedContainerSlotKeepsWeakReferentAliveWithoutRootWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId( + "RuntimeScalarUncountedOwnerRepairTest::Target"); + target.markRefCountUntracked(); + + RuntimeArray ownerContainer = new RuntimeArray(); + RuntimeScalar uncountedOwner = referenceTo(target); + ownerContainer.elements.add(uncountedOwner); + PerlOwnerSlot ownerSlot = uncountedOwner.untrackedReferenceOwnerSlot(); + assertNotNull(ownerSlot); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + RuntimeScalar countedOwner = new RuntimeScalar(); + countedOwner.set(target.createAnonymousReference()); + RuntimeScalar weakObserver = target.createAnonymousReference(); + WeakRefRegistry.weaken(weakObserver); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + + try { + // Model a transient selective-count undercount. Releasing this + // last counted slot leaves the array element as the strong owner. + target.setTrackedRefCount(1); + { + countedOwner.set(new RuntimeScalar()); + + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState()); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + assertFalse(target.destroyFired); + } + + uncountedOwner.set(new RuntimeScalar()); + + assertFalse(ownerSlot.isActive()); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the last uncounted owner release clears weak observers"); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, target.perlLifecycleState()); + assertEquals(0, target.refCount); + } finally { + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + if (ownerSlot.isActive()) uncountedOwner.set(new RuntimeScalar()); + countedOwner.set(new RuntimeScalar()); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.REFERENCE; + scalar.value = referent; + return scalar; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarUntrackedOwnerIdentityTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarUntrackedOwnerIdentityTest.java new file mode 100644 index 0000000000..899e8e717a --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeScalarUntrackedOwnerIdentityTest.java @@ -0,0 +1,35 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@Tag("unit") +class RuntimeScalarUntrackedOwnerIdentityTest { + @Test + void staleLegacyScalarCellCountDoesNotKeepUntrackedOwnerAlive() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash referent = new RuntimeHash(); + referent.markRefCountWeaklyTracked(); + + RuntimeScalar cell = new RuntimeScalar(); + cell.type = RuntimeScalarType.HASHREFERENCE; + cell.value = referent; + cell.setTrackedRefCount(1); + cell.referencedByScalarReference = true; + cell.refreshUntrackedReferenceOwner(); + + assertNotNull(cell.untrackedReferenceOwnerSlot(), + "legacy compatibility count initially allows the owner edge to be recorded"); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + assertFalse(referent.hasUntrackedReferenceOwnerSlotIdentity(), + "without a live scalar-cell identity, the legacy count is not proof of ownership"); + assertFalse(cell.untrackedReferenceOwnerSlot().isActive()); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeTiedHashIteratorOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeTiedHashIteratorOwnerSlotTest.java new file mode 100644 index 0000000000..8977c35d7f --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/RuntimeTiedHashIteratorOwnerSlotTest.java @@ -0,0 +1,99 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Iterator; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class RuntimeTiedHashIteratorOwnerSlotTest { + @Test + void currentKeyUsesOneCountedOwnerSlotAndResetBalancesItsCount() throws Exception { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash hash = new RuntimeHash(); + hash.type = RuntimeHash.TIED_HASH; + Iterator iterator = hash.iterator(); + hash.hashIterator = iterator; + + RuntimeArray currentReferent = new RuntimeArray(); + currentReferent.setTrackedRefCount(0); + RuntimeScalar currentKey = referenceTo(currentReferent); + PerlOwnerSlot currentSlot = retainIteratorKey(iterator, currentKey); + setField(iterator, "currentKey", currentKey); + setField(iterator, "currentKeyOwnerSlot", currentSlot); + + assertTrue(currentSlot.isCountedNativeOwner()); + assertEquals(1, currentReferent.refCount); + hash.resetIterator(); + + assertFalse(currentSlot.isActive()); + assertEquals(0, currentReferent.ownerSlotCount( + PerlOwnerSlot.Kind.TIED_HASH_ITERATOR_KEY)); + assertEquals(0, currentReferent.refCount, + "reset releases the iterator's single paired count"); + assertNull(hash.hashIterator); + } + } + + @Test + void uncountedIteratorKeyPreservesAndThenClearsWeakObservers() throws Exception { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash hash = new RuntimeHash(); + hash.type = RuntimeHash.TIED_HASH; + Iterator iterator = hash.iterator(); + hash.hashIterator = iterator; + + RuntimeArray referent = new RuntimeArray(); + referent.markRefCountUntracked(); + RuntimeScalar weak = referenceTo(referent); + WeakRefRegistry.weaken(weak); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, referent.refCountTrackingState()); + assertTrue(WeakRefRegistry.isweak(weak)); + + RuntimeScalar currentKey = referenceTo(referent); + PerlOwnerSlot slot = retainIteratorKey(iterator, currentKey); + setField(iterator, "currentKey", currentKey); + setField(iterator, "currentKeyOwnerSlot", slot); + + assertFalse(slot.isCountedNativeOwner()); + assertTrue(WeakRefRegistry.isweak(weak), + "the uncounted iterator edge keeps the weak observer alive"); + + hash.resetIterator(); + + assertFalse(slot.isActive()); + assertEquals(RuntimeScalarType.UNDEF, weak.type, + "releasing the final iterator owner clears the weak observer"); + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.HASHREFERENCE; + scalar.value = referent; + return scalar; + } + + private static PerlOwnerSlot retainIteratorKey( + Iterator iterator, RuntimeScalar key) throws Exception { + Method retain = iterator.getClass().getDeclaredMethod( + "retainIteratorKey", RuntimeScalar.class); + retain.setAccessible(true); + return (PerlOwnerSlot) retain.invoke(iterator, key); + } + + private static void setField(Object target, String name, Object value) throws Exception { + Field field = target.getClass().getDeclaredField(name); + field.setAccessible(true); + field.set(target, value); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ScalarCaptureNativeOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ScalarCaptureNativeOwnerTest.java new file mode 100644 index 0000000000..e2f234a317 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ScalarCaptureNativeOwnerTest.java @@ -0,0 +1,58 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ScalarCaptureNativeOwnerTest { + @Test + void borrowedCapturedScalarUsesNativeReferentOwnerWithoutCountBridge() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId( + "ScalarCaptureNativeOwnerTest::Target"); + RuntimeScalar source = new RuntimeScalar(); + source.set(target.createAnonymousReference()); + RuntimeScalar weakObserver = target.createAnonymousReference(); + WeakRefRegistry.weaken(weakObserver); + + RuntimeScalar capturedPad = new RuntimeScalar(source); + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + PerlOwnerSlot captureSlot = capturedPad.retainClosureCaptureSlot(closure); + closure.capturedScalars = new RuntimeScalar[] {capturedPad}; + closure.capturedScalarOwnerSlots = new PerlOwnerSlot[] {captureSlot}; + + try { + assertFalse(capturedPad.refCountOwned, + "the copied pad cell borrows the source's counted value"); + assertEquals(1, target.refCount, + "capturing a borrowed cell must not invent a counted reference"); + assertEquals(1, target.nativeCaptureOwnerCount(), + "the capture slot directly owns the referent"); + assertEquals(0, capturedPad.captureRefCountOwned(), + "no legacy capture count is attached to the referent slot"); + + source.set(new RuntimeScalar()); + assertTrue(WeakRefRegistry.isweak(weakObserver), + "the native capture keeps the target alive after the source leaves"); + + closure.releaseCaptures(); + + assertFalse(captureSlot.isActive()); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type, + "the final native capture release clears the weak observer"); + } finally { + if (closure.capturedScalars != null) closure.releaseCaptures(); + if (source.refCountOwned) source.set(new RuntimeScalar()); + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ScalarOverwriteRetiresOldCountedOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ScalarOverwriteRetiresOldCountedOwnerTest.java new file mode 100644 index 0000000000..4518da5427 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ScalarOverwriteRetiresOldCountedOwnerTest.java @@ -0,0 +1,51 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ScalarOverwriteRetiresOldCountedOwnerTest { + @Test + void replacingCountedValueWithUntrackedScalarReferenceRetiresOldSlot() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash oldReferent = new RuntimeHash(); + oldReferent.blessId = NameNormalizer.getBlessId( + "ScalarOverwriteRetiresOldCountedOwnerTest::Old"); + + RuntimeScalar owner = new RuntimeScalar(); + RuntimeScalar oldReference = new RuntimeScalar(); + oldReference.type = RuntimeScalarType.HASHREFERENCE; + oldReference.value = oldReferent; + owner.set(oldReference); + + RuntimeScalar weakObserver = new RuntimeScalar(oldReference); + WeakRefRegistry.weaken(weakObserver); + + PerlOwnerSlot oldSlot = owner.countedOwnerSlot(); + assertTrue(oldSlot != null && oldSlot.isActive()); + assertEquals(1, oldReferent.refCount); + + RuntimeScalar scalarCell = new RuntimeScalar(42); + RuntimeScalar replacement = new RuntimeScalar(); + replacement.type = RuntimeScalarType.REFERENCE; + replacement.value = scalarCell; + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, scalarCell.refCountTrackingState(), + "the referenced scalar cell is an untracked referent"); + + owner.set(replacement); + + assertFalse(oldSlot.isActive(), + "the old counted slot is retired when this scalar stops owning its referent"); + assertEquals(0, oldReferent.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, oldReferent.perlLifecycleState(), + "the old referent reaches final destruction after its last counted owner leaves"); + assertEquals(0, oldReferent.refCount); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type, + "final release clears weak observers immediately"); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ScopeExitHashOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ScopeExitHashOwnerSlotTest.java new file mode 100644 index 0000000000..c3e16dfc2e --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ScopeExitHashOwnerSlotTest.java @@ -0,0 +1,60 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ScopeExitHashOwnerSlotTest { + @Test + void schemaHashElementOwnsEscapedSourceRegistrationsWithoutRootWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + + RuntimeArray unrelatedPackageRoot = new RuntimeArray(); + for (int i = 0; i < 256; i++) { + RuntimeArray.push(unrelatedPackageRoot, + new RuntimeHash().createAnonymousReference()); + } + String rootName = "ScopeExitHashOwnerSlotTest::root"; + String schemaName = "ScopeExitHashOwnerSlotTest::schema"; + GlobalVariable.globalArrays.put(rootName, unrelatedPackageRoot); + + RuntimeHash schema = new RuntimeHash(); + GlobalVariable.globalHashes.put(schemaName, schema); + RuntimeHash sourceRegistrations = new RuntimeHash(); + try { + MyVarCleanupStack.register(sourceRegistrations); + RuntimeCode.registerCurrentActiveLexical("%source_registrations", sourceRegistrations); + + RuntimeScalar sourceRegistrationsReference = + sourceRegistrations.createAnonymousReference(); + schema.put("source_registrations", sourceRegistrationsReference); + assertEquals(1, sourceRegistrations.refCount); + assertEquals(1, + sourceRegistrations.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + assertEquals(1, + sourceRegistrations.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + + { + MortalList.scopeExitCleanupHash(sourceRegistrations); + + assertEquals(1, + sourceRegistrations.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + assertEquals(0, + sourceRegistrations.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + assertTrue(sourceRegistrations.refCount > 0); + } + } finally { + MyVarCleanupStack.unregister(sourceRegistrations); + schema.undefine(); + MortalList.flush(); + GlobalVariable.globalHashes.remove(schemaName); + GlobalVariable.globalArrays.remove(rootName); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/SharedScalarCaptureNativeOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/SharedScalarCaptureNativeOwnerTest.java new file mode 100644 index 0000000000..0cf0be47ae --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/SharedScalarCaptureNativeOwnerTest.java @@ -0,0 +1,73 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class SharedScalarCaptureNativeOwnerTest { + @Test + void sharedPadCellRetainsOneNativeReferentEdgeUntilItsFinalClosureLeaves() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId( + "SharedScalarCaptureNativeOwnerTest::Target"); + RuntimeScalar source = new RuntimeScalar(); + source.set(target.createAnonymousReference()); + RuntimeScalar weakObserver = target.createAnonymousReference(); + WeakRefRegistry.weaken(weakObserver); + + RuntimeScalar capturedPad = new RuntimeScalar(source); + RuntimeCode firstClosure = code(); + RuntimeCode secondClosure = code(); + PerlOwnerSlot firstCapture = capturedPad.retainClosureCaptureSlot(firstClosure); + PerlOwnerSlot secondCapture = capturedPad.retainClosureCaptureSlot(secondClosure); + firstClosure.capturedScalars = new RuntimeScalar[] {capturedPad}; + firstClosure.capturedScalarOwnerSlots = new PerlOwnerSlot[] {firstCapture}; + secondClosure.capturedScalars = new RuntimeScalar[] {capturedPad}; + secondClosure.capturedScalarOwnerSlots = new PerlOwnerSlot[] {secondCapture}; + + try { + assertEquals(2, capturedPad.captureCount); + assertEquals(1, target.nativeCaptureOwnerCount(), + "one captured pad cell owns its value once across multiple closures"); + assertEquals(0, capturedPad.captureRefCountOwned()); + + { + source.set(new RuntimeScalar()); + assertTrue(WeakRefRegistry.isweak(weakObserver), + "the shared pad cell keeps the target after its source leaves"); + + firstClosure.releaseCaptures(); + assertFalse(firstCapture.isActive()); + assertTrue(secondCapture.isActive()); + assertEquals(1, target.nativeCaptureOwnerCount()); + assertTrue(WeakRefRegistry.isweak(weakObserver), + "one remaining closure still owns the shared captured cell"); + + secondClosure.releaseCaptures(); + assertFalse(secondCapture.isActive()); + assertEquals(0, target.nativeCaptureOwnerCount()); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the final capture release clears weak observers"); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + } + } finally { + if (firstClosure.capturedScalars != null) firstClosure.releaseCaptures(); + if (secondClosure.capturedScalars != null) secondClosure.releaseCaptures(); + if (source.refCountOwned) source.set(new RuntimeScalar()); + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + } + } + } + + private static RuntimeCode code() { + return new RuntimeCode((args, context) -> new RuntimeList(), null); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/SharedTiedAggregateContainerOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/SharedTiedAggregateContainerOwnerTest.java new file mode 100644 index 0000000000..efc7446b46 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/SharedTiedAggregateContainerOwnerTest.java @@ -0,0 +1,56 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +@Tag("unit") +class SharedTiedAggregateContainerOwnerTest { + @Test + void convertedTiedArrayTracksDirectElementMutations() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray array = new RuntimeArray(); + array.type = RuntimeArray.TIED_ARRAY; + array.elements = new TieArray("Test::TieArray", null, null, array); + + RuntimeHash target = new RuntimeHash(); + SharedPerlStorage.shareValue(target); + RuntimeScalar value = target.createAnonymousReference(); + SharedPerlStorage.share(array.createReference()); + + array.elements.add(value); + assertSame(array, value.getContainerOwner(), + "a shared array element write must register its container owner"); + + array.elements.remove(0); + assertNull(value.getContainerOwner(), + "removing the shared array element must retire its container owner"); + } + } + + @Test + void convertedTiedHashTracksDirectElementMutations() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash hash = new RuntimeHash(); + hash.type = RuntimeHash.TIED_HASH; + hash.elements = new TieHash("Test::TieHash", null, null); + + RuntimeArray target = new RuntimeArray(); + SharedPerlStorage.shareValue(target); + RuntimeScalar value = target.createAnonymousReference(); + SharedPerlStorage.share(hash.createReference()); + + hash.elements.put("value", value); + assertSame(hash, value.getContainerOwner(), + "a shared hash element write must register its container owner"); + + hash.elements.remove("value"); + assertNull(value.getContainerOwner(), + "removing the shared hash element must retire its container owner"); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/StaleCountedAggregateReplacementTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/StaleCountedAggregateReplacementTest.java new file mode 100644 index 0000000000..f7e5df2caf --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/StaleCountedAggregateReplacementTest.java @@ -0,0 +1,56 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class StaleCountedAggregateReplacementTest { + @Test + void replacingDetachedHashElementRetiresAlreadyZeroCountedOwner() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash previousReferent = new RuntimeHash(); + RuntimeHash stash = new RuntimeHash(); + stash.put("value", previousReferent.createAnonymousReference()); + RuntimeScalar stashValue = stash.elements.get("value"); + PerlOwnerSlot previousSlot = stashValue.countedOwnerSlot(); + RuntimeHash replacementReferent = new RuntimeHash(); + RuntimeScalar replacementValue = replacementReferent.createAnonymousReference(); + + assertEquals(PerlOwnerSlot.Kind.HASH_ELEMENT, previousSlot.kind()); + assertEquals(1, previousReferent.refCount); + assertTrue(stashValue.refCountOwned); + assertTrue(previousSlot.isActive()); + + // Model a detached scalar cell whose compatibility count reached + // zero before its old hash-element identity was retired. + stash.elements = new HashMap<>(); + stashValue.reconcileContainerOwnerAfterMutation(stash); + previousReferent.setTrackedRefCount(0); + assertTrue(stashValue.refCountOwned); + assertTrue(previousSlot.isActive()); + + stashValue.set(replacementValue); + + assertEquals(0, previousReferent.ownerSlotCount( + PerlOwnerSlot.Kind.HASH_ELEMENT)); + assertFalse(previousSlot.isActive()); + assertEquals(1, replacementReferent.refCount); + assertEquals(1, replacementReferent.countedOwnerSlotCount()); + assertSame(replacementReferent, stashValue.value); + assertNotSame(previousSlot, stashValue.countedOwnerSlot()); + assertSame(replacementReferent, stashValue.countedOwnerSlot().referent()); + assertTrue(stashValue.refCountOwned); + + stashValue.set(new RuntimeScalar()); + MortalList.flush(); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/StaleStashPackageOwnerReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/StaleStashPackageOwnerReleaseTest.java new file mode 100644 index 0000000000..f10d6cc310 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/StaleStashPackageOwnerReleaseTest.java @@ -0,0 +1,177 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.app.cli.CompilerOptions; +import org.perlonjava.app.scriptengine.PerlLanguageProvider; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; + +@Tag("unit") +class StaleStashPackageOwnerReleaseTest { + @Test + void compiledPerlRebindReleasesTheSavedMoveOnBothBackends() throws Exception { + String source = """ + use strict; + use warnings; + use Scalar::Util qw(weaken); + our @DESTROYED; + our ($weak_value, $weak_stash); + { + package StaleStashPackageOwnerPerlProbe::Value; + sub DESTROY { push @main::DESTROYED, 'value'; } + } + my $value = bless {}, 'StaleStashPackageOwnerPerlProbe::Value'; + $weak_value = $value; + weaken($weak_value); + my $stash; + { + no strict 'refs'; + ${'StaleStashPackageOwnerPerlProbeAbandoned::item'} = $value; + $stash = \\%StaleStashPackageOwnerPerlProbeAbandoned::; + $weak_stash = $stash; + weaken($weak_stash); + undef $value; + *StaleStashPackageOwnerPerlProbeAbandoned:: = + 'StaleStashPackageOwnerPerlProbeOther::'; + } + undef $stash; + join ':', defined($weak_stash) ? 1 : 0, + defined($weak_value) ? 1 : 0, @DESTROYED; + """; + + List results = new ArrayList<>(); + List diagnostics = new ArrayList<>(); + for (boolean interpreter : new boolean[]{false, true}) { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + CompilerOptions options = new CompilerOptions(); + options.fileName = ""; + options.code = source; + options.useInterpreter = interpreter; + + String result = PerlLanguageProvider.executePerlCode(options, false) + .scalar().toString(); + + results.add(result); + diagnostics.add(describeWeakStashState(interpreter)); + } + } + + assertEquals(List.of("0:0:value", "0:0:value"), results, + "compiled Perl must release the saved namespace move on both backends: " + + diagnostics); + } + + private static String describeWeakStashState(boolean interpreter) { + RuntimeScalar weakStash = GlobalVariable.globalVariables.get("main::weak_stash"); + if (weakStash == null || !(weakStash.value instanceof RuntimeStash stale)) { + return "interpreter=" + interpreter + " weak stash already cleared"; + } + String owners = stale.ownerSlotSnapshot().stream() + .map(slot -> { + RuntimeGlob owner = slot.globComponentOwner(); + return slot.kind().name() + "#" + slot.identity() + " owner=" + + (owner == null ? "collected" + : System.identityHashCode(owner) + ":" + owner.globName + + ":snapshot=" + owner.isSlotSnapshot() + + ":move=" + (owner.namespaceMove != null)); + }) + .sorted().toList().toString(); + RuntimeGlob move = stale.savedNamespaceMove; + String moveDescription = move == null ? "null" + : "id=" + System.identityHashCode(move) + + " slots=" + move.ownerSlotSnapshot().stream() + .map(slot -> slot.kind().name()).sorted().toList() + + " scalars=" + (move.namespaceMove == null + ? "null" : move.namespaceMove.scalars.keySet()) + + " hashes=" + (move.namespaceMove == null ? "null" + : move.namespaceMove.hashes.entrySet().stream() + .map(entry -> entry.getKey() + "#" + + System.identityHashCode(entry.getValue()) + + (entry.getValue() == stale ? "=STALE" : "")) + .toList()); + return "interpreter=" + interpreter + " stale.id=" + System.identityHashCode(stale) + + " stale.namespace=" + stale.namespace + " stale.refCount=" + stale.refCount + + " stale.localBinding=" + stale.localBindingExists + + " stale.owners=" + owners + + " move=" + moveDescription; + } + + @Test + void rebindingStashReleasesItsPackageRootIdentity() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + String source = "StaleStashPackageOwnerReleaseTest::Source::"; + String replacement = "StaleStashPackageOwnerReleaseTest::Other::"; + RuntimeStash stale = (RuntimeStash) GlobalVariable.getGlobalHash(source); + RuntimeStash current = (RuntimeStash) GlobalVariable.getGlobalHash(replacement); + String childKey = source + "Inner::"; + RuntimeStash child = (RuntimeStash) GlobalVariable.getGlobalHash(childKey); + String scalarKey = source + "item"; + RuntimeScalar packageScalar = new RuntimeScalar(); + RuntimeHash value = new RuntimeHash(); + RuntimeScalar weakValue = value.createAnonymousReference(); + WeakRefRegistry.weaken(weakValue); + packageScalar.set(value.createAnonymousReference()); + GlobalVariable.globalVariables.put(scalarKey, packageScalar); + RuntimeScalar stashReference = stale.createReference(); + RuntimeScalar lexical = new RuntimeScalar(); + + try { + lexical.set(stashReference); + assertEquals(1, stale.ownerSlotCount( + PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + + GlobalVariable.getGlobalIO(source).set(new RuntimeScalar(replacement)); + RuntimeGlob savedMove = stale.savedNamespaceMove; + + assertSame(current, GlobalVariable.globalHashes.get(source)); + assertNotSame(stale, current); + assertNotNull(savedMove); + assertEquals(1, savedMove.ownerSlotCount( + PerlOwnerSlot.Kind.STASH_NAMESPACE_MOVE)); + assertEquals(1, child.ownerSlotCount( + PerlOwnerSlot.Kind.GLOB_COMPONENT_SLOT)); + assertEquals(0, packageScalar.ownerSlotCount( + PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT)); + assertEquals(1, packageScalar.ownerSlotCount( + PerlOwnerSlot.Kind.GLOB_COMPONENT_SLOT)); + assertFalse(stale.localBindingExists); + assertEquals(0, stale.ownerSlotCount( + PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT), + "the replaced package hash must release its root owner identity"); + + lexical.undefine(); + + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, stale.perlLifecycleState(), + "the final Perl reference must retire the stale stash"); + assertEquals(0, stale.refCount); + assertEquals(0, savedMove.ownerSlotCount( + PerlOwnerSlot.Kind.STASH_NAMESPACE_MOVE)); + assertEquals(0, child.ownerSlotCount( + PerlOwnerSlot.Kind.GLOB_COMPONENT_SLOT)); + assertEquals(0, packageScalar.ownerSlotCount( + PerlOwnerSlot.Kind.GLOB_COMPONENT_SLOT)); + assertEquals(RuntimeScalarType.UNDEF, weakValue.type, + "releasing the saved move must clean its package scalar contents"); + } finally { + lexical.undefine(); + GlobalVariable.globalHashes.remove(source); + GlobalVariable.globalHashes.remove(replacement); + GlobalVariable.globalHashes.remove(childKey); + GlobalVariable.globalVariables.remove(scalarKey); + GlobalVariable.globalIORefs.remove(source); + GlobalVariable.globalIORefs.remove(replacement); + GlobalVariable.clearStashAlias(source); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/StashCodeLifecycleUsesOwnerIdentityTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/StashCodeLifecycleUsesOwnerIdentityTest.java new file mode 100644 index 0000000000..58e1f03ca1 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/StashCodeLifecycleUsesOwnerIdentityTest.java @@ -0,0 +1,56 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class StashCodeLifecycleUsesOwnerIdentityTest { + @Test + void replacingNamedCodeRetargetsTheStashOwnerIdentity() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + String name = "StashCodeLifecycleUsesOwnerIdentityTest::replaced"; + RuntimeCode original = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeCode replacement = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar stashSlot = new RuntimeScalar(original); + GlobalVariable.globalCodeRefs.put(name, stashSlot); + + assertTrue(original.hasStashCodeSlotOwner()); + assertFalse(replacement.hasStashCodeSlotOwner()); + + stashSlot.set(new RuntimeScalar(replacement)); + + assertFalse(original.hasStashCodeSlotOwner(), + "redefinition releases the previous CV's stash edge"); + assertTrue(replacement.hasStashCodeSlotOwner(), + "redefinition gives the replacement CV the same stash slot owner"); + } + } + + @Test + void releasedStashSlotRetiresCodeDespiteStaleCompatibilityCounter() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + String name = "StashCodeLifecycleUsesOwnerIdentityTest::installed"; + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar stashSlot = new RuntimeScalar(); + stashSlot.type = RuntimeScalarType.CODE; + stashSlot.value = code; + GlobalVariable.globalCodeRefs.put(name, stashSlot); + + assertTrue(code.hasStashCodeSlotOwner(), + "the visible stash cell owns the CODE through its slot identity"); + code.stashRefCount = 7; // Deliberately stale legacy metadata. + + GlobalVariable.removeGlobalCodeRefForStashDelete(name); + + assertFalse(code.hasStashCodeSlotOwner(), + "deleting the stash entry retires its exact CODE_SLOT owner"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + code.perlLifecycleState(), + "a stale compatibility counter cannot preserve a CODE with no Perl owners"); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/StrongCycleOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/StrongCycleOwnerSlotTest.java new file mode 100644 index 0000000000..152dc02714 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/StrongCycleOwnerSlotTest.java @@ -0,0 +1,71 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class StrongCycleOwnerSlotTest { + @Test + void hashCycleLivesThroughItsHashElementOwnerUntilTheEdgeIsRemoved() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash hash = new RuntimeHash(); + hash.put("self", hash.createAnonymousReference()); + RuntimeScalar weakObserver = hash.createAnonymousReference(); + WeakRefRegistry.weaken(weakObserver); + + try { + assertEquals(1, hash.refCount); + assertEquals(1, hash.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + { + MortalList.scopeExitCleanupHash(hash); + + assertEquals(1, hash.refCount); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + } + + hash.elements.get("self").set(new RuntimeScalar()); + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertEquals(0, hash.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + hash.perlLifecycleState()); + } finally { + if (WeakRefRegistry.isweak(weakObserver)) WeakRefRegistry.unweaken(weakObserver); + hash.elements.clear(); + } + } + } + + @Test + void arrayCycleLivesThroughItsArrayElementOwnerUntilTheEdgeIsRemoved() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeArray array = new RuntimeArray(); + array.push(array.createAnonymousReference()); + RuntimeScalar weakObserver = array.createAnonymousReference(); + WeakRefRegistry.weaken(weakObserver); + + try { + assertEquals(1, array.refCount); + assertEquals(1, array.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + { + MortalList.scopeExitCleanupArray(array); + + assertEquals(1, array.refCount); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + } + + array.elements.getFirst().set(new RuntimeScalar()); + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertEquals(0, array.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + array.perlLifecycleState()); + } finally { + if (WeakRefRegistry.isweak(weakObserver)) WeakRefRegistry.unweaken(weakObserver); + array.elements.clear(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/SuspendedFrameEndBoundaryRootTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/SuspendedFrameEndBoundaryRootTest.java new file mode 100644 index 0000000000..cbbd7744fe --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/SuspendedFrameEndBoundaryRootTest.java @@ -0,0 +1,32 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class SuspendedFrameEndBoundaryRootTest { + @Test + void suspendedFrameOwnerSlotDefinesLifetimeUntilItsRelease() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash rescued = new RuntimeHash(); + PerlOwnerSlot suspendedOwner = new PerlOwnerSlot(PerlOwnerSlot.Kind.SUSPENDED_FRAME); + suspendedOwner.acquireSuspendedFrameIdentity(rescued); + + try { + assertTrue(rescued.hasCurrentPerlOwnerSlotIdentity(), + "the suspended frame's current owner slot keeps its referent alive"); + + suspendedOwner.release(); + + assertFalse(rescued.hasCurrentPerlOwnerSlotIdentity(), + "a completed frame retires its exact referent slot"); + } finally { + if (suspendedOwner.isActive()) suspendedOwner.release(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/SysopenAnonymousGlobOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/SysopenAnonymousGlobOwnerSlotTest.java new file mode 100644 index 0000000000..c9dad39e03 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/SysopenAnonymousGlobOwnerSlotTest.java @@ -0,0 +1,43 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.runtime.operators.IOOperator; + +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class SysopenAnonymousGlobOwnerSlotTest { + @Test + void newlyAssignedAnonymousHandleGetsOneScalarResourceOwner() throws Exception { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + Path path = Files.createTempFile("perlonjava-sysopen-anonymous-owner-", ".tmp"); + RuntimeScalar handle = new RuntimeScalar(); + RuntimeGlob glob = null; + try { + RuntimeScalar result = IOOperator.sysopen(0, + handle, + new RuntimeScalar(path.toString()), + new RuntimeScalar(2)); // O_RDWR + + assertTrue(result.getBoolean()); + assertEquals(RuntimeScalarType.GLOBREFERENCE, handle.type); + glob = (RuntimeGlob) handle.value; + assertTrue(handle.hasIoOwner()); + assertEquals(1, glob.ioHolderCount()); + assertEquals(1, glob.ownerSlotCount(PerlOwnerSlot.Kind.IO_RESOURCE_HOLDER)); + + RuntimeScalar.releaseIoOwner(handle); + assertEquals(0, glob.ioHolderCount()); + } finally { + if (glob != null && glob.getIO().value instanceof RuntimeIO io) io.close(); + RuntimeScalar.releaseIoOwner(handle); + Files.deleteIfExists(path); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallActiveLexicalOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallActiveLexicalOwnerTest.java new file mode 100644 index 0000000000..bd89f56208 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallActiveLexicalOwnerTest.java @@ -0,0 +1,61 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class TailCallActiveLexicalOwnerTest { + @Test + void tailCallReleaseUsesActiveLexicalOwnerWithoutPositiveCountPin() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray target = new RuntimeArray(); + target.setTrackedRefCount(0); + target.localBindingExists = true; + + PerlOwnerSlot lexicalOwner = new PerlOwnerSlot(PerlOwnerSlot.Kind.ACTIVE_LEXICAL); + lexicalOwner.acquireActiveLexicalIdentity(target); + + RuntimeScalar tailArgument = new RuntimeScalar(); + tailArgument.set(target.createAnonymousReference()); + RuntimeArray tailArguments = new RuntimeArray(1); + tailArguments.elements.add(tailArgument); + tailArguments.elementsOwned = true; + + RuntimeScalar weakObserver = target.createAnonymousReference(); + WeakRefRegistry.weaken(weakObserver); + try { + assertEquals(1, target.refCount); + assertTrue(tailArgument.refCountOwned); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + + MortalList.releaseTailCallArgs(tailArguments); + + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState(), + "the active lexical identity defers cleanup without a fabricated count"); + assertTrue(WeakRefRegistry.isweak(weakObserver), + "the surviving lexical owner keeps weak observers live"); + + target.localBindingExists = false; + lexicalOwner.release(); + + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, target.perlLifecycleState(), + "the final active lexical owner completes cleanup"); + assertEquals(0, target.refCount); + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + } finally { + if (lexicalOwner.isActive()) { + target.localBindingExists = false; + lexicalOwner.release(); + } + WeakRefRegistry.clearWeakRefsTo(target); + MortalList.flush(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallArgumentOwnerSlotFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallArgumentOwnerSlotFastPathTest.java new file mode 100644 index 0000000000..4912569fe2 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallArgumentOwnerSlotFastPathTest.java @@ -0,0 +1,44 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class TailCallArgumentOwnerSlotFastPathTest { + @Test + void tailCallReleaseBalancesTheSurvivingElementOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId("Issue1649::TailCallOwnerSlot"); + RuntimeArray backing = new RuntimeArray(); + backing.addClonedElement(target.createAnonymousReference()); + + RuntimeScalar tailArgument = new RuntimeScalar(); + tailArgument.set(target.createAnonymousReference()); + RuntimeArray tailArguments = new RuntimeArray(1); + tailArguments.elements.add(tailArgument); + tailArguments.elementsOwned = true; + + RuntimeScalar weak = target.createAnonymousReference(); + WeakRefRegistry.weaken(weak); + try { + assertEquals(2, target.countedOwnerSlotCount()); + + { + MortalList.releaseTailCallArgs(tailArguments); + + assertEquals(1, target.refCount); + assertEquals(1, target.countedOwnerSlotCount()); + assertTrue(WeakRefRegistry.isweak(weak)); + } + } finally { + WeakRefRegistry.unweaken(weak); + backing.undefine(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallCodeRefDoesNotPinFromLocalBindingFlagTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallCodeRefDoesNotPinFromLocalBindingFlagTest.java new file mode 100644 index 0000000000..550de8404f --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallCodeRefDoesNotPinFromLocalBindingFlagTest.java @@ -0,0 +1,35 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +@Tag("unit") +class TailCallCodeRefDoesNotPinFromLocalBindingFlagTest { + @Test + void staleLocalBindingMarkerCannotReplaceTheReleasedCodeSlot() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + code.setTrackedRefCount(1); + // RuntimeCode has no producer for this aggregate/scalar binding + // marker. It must not fabricate a counted owner at tail-call exit. + code.localBindingExists = true; + + RuntimeScalar codeRef = new RuntimeScalar(); + codeRef.type = RuntimeScalarType.CODE; + codeRef.value = code; + codeRef.refCountOwned = true; + code.recordActiveOwner(codeRef); + + MortalList.releaseTailCallCodeRef(codeRef); + + assertFalse(codeRef.refCountOwned); + assertEquals(0, code.countedOwnerSlotCount()); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, code.perlLifecycleState(), + "the final real CODE slot release must complete lifecycle cleanup"); + assertEquals(0, code.refCount); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallCodeRefOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallCodeRefOwnerSlotTest.java new file mode 100644 index 0000000000..5a4385822d --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallCodeRefOwnerSlotTest.java @@ -0,0 +1,42 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; + +@Tag("unit") +class TailCallCodeRefOwnerSlotTest { + @Test + void tailCallTransferAcquiresAndReleasesAnArgumentOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + try { + MortalList.setActive(true); + RuntimeCode target = new RuntimeCode((args, context) -> new RuntimeList(), null); + target.setTrackedRefCount(0); + RuntimeScalar source = new RuntimeScalar(); + source.type = RuntimeScalarType.CODE; + source.value = target; + + RuntimeControlFlowList transfer = new RuntimeControlFlowList( + source, new RuntimeArray(), "tailcall-owner-test", 1); + RuntimeScalar retainedCodeRef = transfer.getTailCallCodeRef(); + + assertEquals(1, target.refCount); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(0, target.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + + MortalList.releaseTailCallCodeRef(retainedCodeRef); + + assertFalse(retainedCodeRef.refCountOwned); + assertEquals(0, target.countedOwnerSlotCount()); + } finally { + MortalList.setActive(previousMortalListState); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallReleasedOwnerLifecycleTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallReleasedOwnerLifecycleTest.java new file mode 100644 index 0000000000..7d8f6e799d --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallReleasedOwnerLifecycleTest.java @@ -0,0 +1,32 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class TailCallReleasedOwnerLifecycleTest { + @Test + void releasingTailCallOwnerClearsTheFinalWeakObserver() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar owner = new RuntimeScalar(); + owner.set(referent.createAnonymousReference()); + + RuntimeScalar weak = referent.createReference(); + WeakRefRegistry.weaken(weak); + RuntimeArray tailArguments = new RuntimeArray(1); + tailArguments.elements.add(owner); + tailArguments.elementsOwned = true; + MortalList.releaseTailCallArgs(tailArguments); + + assertFalse(owner.refCountOwned); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, referent.perlLifecycleState()); + assertEquals(0, referent.refCount); + assertEquals(RuntimeScalarType.UNDEF, weak.type); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallUncountedOwnerSlotFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallUncountedOwnerSlotFastPathTest.java new file mode 100644 index 0000000000..92ff996fdf --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TailCallUncountedOwnerSlotFastPathTest.java @@ -0,0 +1,53 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class TailCallUncountedOwnerSlotFastPathTest { + @Test + void packageScalarOwnerDefersFinalTailCallReleaseWithoutRootWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar target = new RuntimeScalar(); + String globalName = + "TailCallUncountedOwnerSlotFastPathTest::packageScalarOwner"; + GlobalVariable.globalVariables.put(globalName, target); + target.setTrackedRefCount(0); + + RuntimeScalar tailArgument = new RuntimeScalar(); + tailArgument.set(target.createReference()); + RuntimeArray tailArguments = new RuntimeArray(1); + tailArguments.elements.add(tailArgument); + tailArguments.elementsOwned = true; + + RuntimeScalar weak = target.createReference(); + WeakRefRegistry.weaken(weak); + + try { + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT)); + + { + MortalList.releaseTailCallArgs(tailArguments); + + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState()); + assertTrue(WeakRefRegistry.isweak(weak)); + } + + GlobalVariable.globalVariables.remove(globalName); + + assertFalse(WeakRefRegistry.isweak(weak)); + assertEquals(RuntimeScalarType.UNDEF, weak.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, target.perlLifecycleState()); + assertEquals(0, target.refCount); + } finally { + if (WeakRefRegistry.isweak(weak)) WeakRefRegistry.unweaken(weak); + GlobalVariable.globalVariables.remove(globalName); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TargetedWeakReleaseOwnerSlotFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TargetedWeakReleaseOwnerSlotFastPathTest.java new file mode 100644 index 0000000000..29ece6066e --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TargetedWeakReleaseOwnerSlotFastPathTest.java @@ -0,0 +1,33 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class TargetedWeakReleaseOwnerSlotFastPathTest { + @Test + void activeElementOwnerKeepsWeakObserverUntilOwnerRelease() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray owner = new RuntimeArray(); + RuntimeArray target = new RuntimeArray(); + owner.addClonedElement(target.createAnonymousReference()); + RuntimeScalar weak = target.createAnonymousReference(); + WeakRefRegistry.weaken(weak); + + try { + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + MortalList.flush(); + assertTrue(WeakRefRegistry.isweak(weak), + "the active element slot keeps the target's weak observer intact"); + assertTrue(target.refCount > 0, + "the element's strong owner remains counted"); + } finally { + WeakRefRegistry.unweaken(weak); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryCodeArgumentOwnerIdentityTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryCodeArgumentOwnerIdentityTest.java new file mode 100644 index 0000000000..d0e9c1261e --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryCodeArgumentOwnerIdentityTest.java @@ -0,0 +1,116 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class TemporaryCodeArgumentOwnerIdentityTest { + @Test + void temporaryCodeCellGetsArgumentOwnerWhenAnotherCellOwnsTheCode() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + closure.setTrackedRefCount(0); + closure.capturedScalars = new RuntimeScalar[0]; + + RuntimeScalar durableCell = new RuntimeScalar(); + durableCell.localBindingExists = true; + durableCell.set(new RuntimeScalar(closure)); + assertEquals(1, closure.refCount); + assertNotNull(durableCell.countedOwnerSlot()); + + RuntimeScalar temporaryCell = new RuntimeScalar(closure); + assertFalse(temporaryCell.hasPersistentArgumentStorageCell()); + RuntimeCode.CallArguments staged = RuntimeCode.newCallArguments(1); + + MortalList.pushMark(); + boolean markActive = true; + try { + staged.add(temporaryCell); + RuntimeArray arguments = staged.toRuntimeArray(); + + assertTrue(arguments.ownsElement(temporaryCell)); + assertEquals(1, closure.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE), + "the temporary cell needs an edge even when another cell owns the CODE"); + assertEquals(2, closure.refCount); + assertEquals(PerlOwnerSlot.Kind.ARGUMENT_VALUE, + temporaryCell.countedOwnerSlot().kind()); + + staged.finish(); + MortalList.popAndFlush(); + markActive = false; + + assertFalse(arguments.ownsElement(temporaryCell)); + assertEquals(0, closure.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + assertEquals(1, closure.refCount, + "argument cleanup preserves the distinct durable CODE cell"); + assertTrue(closure.capturedScalars != null, + "the remaining cell still owns the closure captures"); + } finally { + staged.finish(); + if (markActive) MortalList.popAndFlush(); + } + + MortalList.pushMark(); + RuntimeScalar.scopeExitCleanup(durableCell); + MortalList.popAndFlush(); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, closure.perlLifecycleState(), + "the final durable CODE owner retires the closure"); + assertEquals(0, closure.refCount); + assertEquals(0, closure.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + } + } + + @Test + void forwardingAnActiveCodeArgumentBorrowsTheCurrentCellOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + closure.setTrackedRefCount(0); + closure.capturedScalars = new RuntimeScalar[0]; + RuntimeScalar argumentCell = new RuntimeScalar(closure); + RuntimeCode.CallArguments outer = RuntimeCode.newCallArguments(1); + RuntimeCode.CallArguments forwarded = null; + boolean markActive = false; + boolean outerArgsActive = false; + + try { + MortalList.pushMark(); + markActive = true; + outer.add(argumentCell); + RuntimeArray outerArgs = outer.toRuntimeArray(); + assertEquals(1, closure.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + + RuntimeCode.pushArgs(outerArgs); + outerArgsActive = true; + forwarded = RuntimeCode.newCallArguments(1); + forwarded.add(argumentCell); + RuntimeArray forwardedArgs = forwarded.toRuntimeArray(); + + assertFalse(forwardedArgs.ownsElement(argumentCell)); + assertEquals(1, closure.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE), + "the forwarded frame borrows its caller's active scalar cell"); + forwarded.finish(); + forwarded = null; + + RuntimeCode.popArgs(); + outerArgsActive = false; + outer.finish(); + MortalList.popAndFlush(); + markActive = false; + + assertEquals(0, closure.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE)); + } finally { + if (forwarded != null) forwarded.finish(); + if (outerArgsActive) RuntimeCode.popArgs(); + outer.finish(); + if (markActive) MortalList.popAndFlush(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryControlFlowRootTraversalTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryControlFlowRootTraversalTest.java new file mode 100644 index 0000000000..de0d1573f1 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryControlFlowRootTraversalTest.java @@ -0,0 +1,31 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Tag("unit") +class TemporaryControlFlowRootTraversalTest { + @Test + void temporaryReturnMarkerOwnsItsReturnValueForTheRootLease() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar returnedReference = referent.createAnonymousReference(); + RuntimeControlFlowList transfer = new RuntimeControlFlowList( + returnedReference, "temporary-control-flow-root.t", 1); + + MortalList.pushTemporaryRoot(transfer); + try { + assertEquals(returnedReference, transfer.getReturnValue()); + assertEquals(1, transfer.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_TEMPORARY_ROOT)); + } finally { + MortalList.popTemporaryRoot(transfer); + } + assertEquals(0, transfer.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_TEMPORARY_ROOT)); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryReturnOwnerTraversalTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryReturnOwnerTraversalTest.java new file mode 100644 index 0000000000..98e0c8b255 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryReturnOwnerTraversalTest.java @@ -0,0 +1,112 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.app.cli.CompilerOptions; +import org.perlonjava.app.scriptengine.PerlLanguageProvider; + +import java.util.AbstractMap; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class TemporaryReturnOwnerTraversalTest { + @Test + void implicitSubReturnPopsTheRootSlotItPushedBeforeScopeCleanup() throws Exception { + for (boolean useInterpreter : new boolean[] {false, true}) { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + int rootDepth = MortalList.temporaryRootDepth(); + CompilerOptions options = new CompilerOptions(); + options.fileName = "temporary_return_owner_root_balance.t"; + options.useInterpreter = useInterpreter; + options.code = "our $destroyed = 0;" + + "sub TemporaryReturnOwnerTraversal::Object::DESTROY " + + "{ ++$main::destroyed }" + + "sub make_result {" + + " my $value = bless {}, 'TemporaryReturnOwnerTraversal::Object';" + + " my @cleanup_scope = (1);" + + " $value;" + + "}" + + "my $returned = make_result();" + + "die 'returned object destroyed too early' if $destroyed;" + + "undef $returned;" + + "die 'returned object not destroyed after release' " + + " unless $destroyed == 1;" + + "1;"; + + PerlLanguageProvider.executePerlCode(options, false); + + assertEquals(rootDepth, MortalList.temporaryRootDepth(), + "implicit return scope cleanup must balance its temporary-root leases " + + "(interpreter=" + useInterpreter + ")"); + } + } + } + + @Test + void lexicalCleanupDoesNotWalkUnrelatedTemporaryReferentGraphs() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash metadata = new RuntimeHash(); + metadata.elements = new AbstractMap<>() { + @Override + public Set> entrySet() { + throw new AssertionError("lexical cleanup walked an unrelated referent graph"); + } + }; + RuntimeScalar expression = metadata.createAnonymousReference(); + RuntimeArray local = new RuntimeArray(); + local.localBindingExists = true; + MortalList.pushTemporaryRoot(expression); + try { + assertDoesNotThrow(() -> MortalList.scopeExitCleanupArray(local)); + assertFalse(local.localBindingExists); + } finally { + MortalList.popTemporaryRoot(expression); + } + } + } + + @Test + void expressionListsStillBorrowTheirDirectAggregateReferents() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray target = new RuntimeArray(); + RuntimeList expression = new RuntimeList(); + expression.elements.add(target.createReference()); + MortalList.pushTemporaryRoot(expression); + try { + assertEquals(target, ((RuntimeScalar) expression.elements.getFirst()).value); + assertEquals(1, expression.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_TEMPORARY_ROOT)); + } finally { + MortalList.popTemporaryRoot(expression); + } + } + } + + @Test + void temporaryReturnListLeaseTracksTheListLifetime() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + RuntimeList expression = new RuntimeList(); + expression.elements.add(target.createReference()); + + MortalList.pushTemporaryRoot(expression); + try { + assertEquals(target, ((RuntimeScalar) expression.elements.getFirst()).value); + assertEquals(1, expression.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_TEMPORARY_ROOT)); + } finally { + MortalList.popTemporaryRoot(expression); + } + + assertEquals(0, expression.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_TEMPORARY_ROOT)); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootArrayAliasOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootArrayAliasOwnerTest.java new file mode 100644 index 0000000000..9d35189f9b --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootArrayAliasOwnerTest.java @@ -0,0 +1,78 @@ +package org.perlonjava.runtime.runtimetypes; + +import java.util.AbstractMap; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class TemporaryRootArrayAliasOwnerTest { + private static final class CountingHashValues extends AbstractMap { + private int valuesCalls; + + @Override + public Set> entrySet() { + return Collections.emptySet(); + } + + @Override + public Collection values() { + valuesCalls++; + return List.of(); + } + } + + @Test + void currentArrayAliasOwnerProvesTemporaryRootWithoutGraphWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar aliasCell = new RuntimeScalar(); + RuntimeArray aliasArray = new RuntimeArray(); + aliasArray.elementsAliased = true; + aliasArray.elements.add(null); + aliasArray.setAliasedScalarCell(0, aliasCell); + + CountingHashValues opaqueValues = new CountingHashValues(); + RuntimeHash opaque = new RuntimeHash(); + opaque.elements = opaqueValues; + RuntimeArray root = new RuntimeArray(); + root.localBindingExists = true; + root.elements.add(aliasArray.createReference()); + root.elements.add(opaque.createReference()); + + MortalList.pushTemporaryRoot(root); + try { + PerlOwnerSlot aliasOwner = aliasCell.ownerSlotSnapshot().stream() + .filter(slot -> slot.kind() == PerlOwnerSlot.Kind.ARRAY_ALIAS_CELL) + .findFirst().orElseThrow(); + assertTrue(DestroyDispatch.isCurrentPerlOwnerSlot(aliasCell, aliasOwner), + "the array-alias slot must be an active owner"); + assertTrue(aliasArray.ownsReferenceListAliasCellOwner(aliasOwner, aliasCell), + "the alias slot must identify the cell currently stored in the array"); + assertFalse(MortalList.temporaryRootDirectlyReferences(aliasCell), + "the root contains the owning array, not the aliased cell"); + assertTrue(MortalList.temporaryRootDirectlyReferences(aliasArray), + "the root directly contains the array that owns the cell"); + + assertTrue(ReachabilityWalker.isReachableFromTemporaryRoots(aliasCell)); + assertEquals(0, opaqueValues.valuesCalls, + "the validated array-alias path must avoid the fallback graph walk"); + } finally { + MortalList.popTemporaryRoot(root); + root.elements.clear(); + root.localBindingExists = false; + MortalList.scopeExitCleanupArray(root); + aliasArray.releaseReferenceListAliasCellOwners(); + aliasArray.elements.clear(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootClosureCaptureOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootClosureCaptureOwnerTest.java new file mode 100644 index 0000000000..5bcb1186ca --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootClosureCaptureOwnerTest.java @@ -0,0 +1,134 @@ +package org.perlonjava.runtime.runtimetypes; + +import java.util.AbstractMap; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class TemporaryRootClosureCaptureOwnerTest { + private static final class CountingHashValues extends AbstractMap { + private int valuesCalls; + + @Override + public Set> entrySet() { + return Collections.emptySet(); + } + + @Override + public Collection values() { + valuesCalls++; + return List.of(); + } + } + + @Test + void aggregateCaptureOwnerProvesTemporaryRootWithoutGraphWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray capturedPad = new RuntimeArray(); + RuntimeCode closure = new RuntimeCode(null, List.of()); + PerlOwnerSlot captureOwner = capturedPad.retainClosureCaptureOwner(closure); + closure.capturedAggregates = new RuntimeBase[] {capturedPad}; + closure.capturedAggregateOwnerSlots = new PerlOwnerSlot[] {captureOwner}; + closure.captureFieldsRecorded = true; + + assertRootCaptureProof(capturedPad, closure, captureOwner); + } + } + + @Test + void scalarCaptureOwnerProvesTemporaryRootWithoutGraphWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar capturedPad = new RuntimeScalar(); + RuntimeCode closure = new RuntimeCode(null, List.of()); + PerlOwnerSlot captureOwner = capturedPad.retainClosureCaptureSlot(closure); + closure.capturedScalars = new RuntimeScalar[] {capturedPad}; + closure.capturedScalarOwnerSlots = new PerlOwnerSlot[] {captureOwner}; + closure.captureFieldsRecorded = true; + + assertRootCaptureProof(capturedPad, closure, captureOwner); + } + } + + @Test + void compiledPadConstantOwnerProvesTemporaryRootWithoutGraphWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalarReadOnly padConstant = new RuntimeScalarReadOnly("constant"); + RuntimeCode code = new RuntimeCode(null, List.of()); + code.installPadConstants(new RuntimeBase[] {padConstant}); + + CountingHashValues opaqueValues = new CountingHashValues(); + RuntimeHash opaque = new RuntimeHash(); + opaque.elements = opaqueValues; + RuntimeArray root = new RuntimeArray(); + root.localBindingExists = true; + root.elements.add(code.createReference()); + root.elements.add(opaque.createReference()); + + MortalList.pushTemporaryRoot(root); + try { + PerlOwnerSlot padOwner = padConstant.ownerSlotSnapshot().stream() + .filter(slot -> slot.kind() == PerlOwnerSlot.Kind.CODE_PAD_CONSTANT) + .findFirst().orElseThrow(); + assertTrue(DestroyDispatch.isCurrentPerlOwnerSlot(padConstant, padOwner), + "the compiled pad-constant slot must be active"); + assertFalse(MortalList.temporaryRootDirectlyReferences(padConstant), + "the root contains the owning CODE object, not the pad constant"); + assertTrue(MortalList.temporaryRootDirectlyReferences(code), + "the root directly contains the CODE object that owns the constant"); + + assertTrue(ReachabilityWalker.isReachableFromTemporaryRoots(padConstant)); + assertEquals(0, opaqueValues.valuesCalls, + "the validated CODE-owner path must avoid the fallback graph walk"); + } finally { + MortalList.popTemporaryRoot(root); + root.elements.clear(); + root.localBindingExists = false; + MortalList.scopeExitCleanupArray(root); + code.clearPadConstantWeakRefs(); + } + } + } + + private static void assertRootCaptureProof( + RuntimeBase capturedPad, RuntimeCode closure, PerlOwnerSlot captureOwner) { + CountingHashValues opaqueValues = new CountingHashValues(); + RuntimeHash opaque = new RuntimeHash(); + opaque.elements = opaqueValues; + RuntimeArray root = new RuntimeArray(); + root.localBindingExists = true; + root.elements.add(closure.createReference()); + root.elements.add(opaque.createReference()); + + MortalList.pushTemporaryRoot(root); + try { + assertTrue(DestroyDispatch.isCurrentPerlOwnerSlot(capturedPad, captureOwner), + "the capture slot must identify a current closure owner"); + assertFalse(MortalList.temporaryRootDirectlyReferences(capturedPad), + "the root contains the closure, not its captured pad"); + assertTrue(MortalList.temporaryRootDirectlyReferences(closure), + "the root directly contains the closure that owns the pad"); + + assertTrue(ReachabilityWalker.isReachableFromTemporaryRoots(capturedPad)); + assertEquals(0, opaqueValues.valuesCalls, + "the validated CODE-owner path must avoid the fallback graph walk"); + } finally { + MortalList.popTemporaryRoot(root); + root.elements.clear(); + root.localBindingExists = false; + MortalList.scopeExitCleanupArray(root); + closure.releaseCaptures(); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootCodeStateOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootCodeStateOwnerTest.java new file mode 100644 index 0000000000..02c1935d4b --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootCodeStateOwnerTest.java @@ -0,0 +1,78 @@ +package org.perlonjava.runtime.runtimetypes; + +import java.util.AbstractMap; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class TemporaryRootCodeStateOwnerTest { + private static final class CountingHashValues extends AbstractMap { + private int valuesCalls; + + @Override + public Set> entrySet() { + return Collections.emptySet(); + } + + @Override + public Collection values() { + valuesCalls++; + return List.of(); + } + } + + @Test + void currentScalarAndAggregateStateOwnersProveTemporaryRootWithoutGraphWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode code = new RuntimeCode(null, List.of()); + RuntimeScalar stateScalar = new RuntimeScalar(); + RuntimeArray stateArray = new RuntimeArray(); + RuntimeHash stateHash = new RuntimeHash(); + code.bindStateScalar("scalar", stateScalar); + code.bindStateArray("array", stateArray); + code.bindStateHash("hash", stateHash); + + CountingHashValues opaqueValues = new CountingHashValues(); + RuntimeHash opaque = new RuntimeHash(); + opaque.elements = opaqueValues; + RuntimeArray root = new RuntimeArray(); + root.localBindingExists = true; + root.elements.add(code.createReference()); + root.elements.add(opaque.createReference()); + + MortalList.pushTemporaryRoot(root); + try { + for (RuntimeBase stateValue : List.of(stateScalar, stateArray, stateHash)) { + PerlOwnerSlot stateOwner = stateValue.ownerSlotSnapshot().stream() + .filter(slot -> slot.kind() == PerlOwnerSlot.Kind.CODE_STATE) + .findFirst().orElseThrow(); + assertTrue(code.hasCurrentStateOwner(stateValue, stateOwner), + "the CODE_STATE slot must match the current CV binding"); + assertFalse(MortalList.temporaryRootDirectlyReferences(stateValue), + "the root contains the owning CODE object, not the state value"); + assertTrue(ReachabilityWalker.isReachableFromTemporaryRoots(stateValue)); + } + assertTrue(MortalList.temporaryRootDirectlyReferences(code), + "the temporary root directly contains the CODE state owner"); + assertEquals(0, opaqueValues.valuesCalls, + "validated CODE_STATE paths must avoid the fallback graph walk"); + } finally { + MortalList.popTemporaryRoot(root); + root.elements.clear(); + root.localBindingExists = false; + MortalList.scopeExitCleanupArray(root); + code.releaseStateStorage(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootCountedCellOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootCountedCellOwnerTest.java new file mode 100644 index 0000000000..5061731ead --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootCountedCellOwnerTest.java @@ -0,0 +1,211 @@ +package org.perlonjava.runtime.runtimetypes; + +import java.util.AbstractMap; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class TemporaryRootCountedCellOwnerTest { + private static final class CountingHashValues extends AbstractMap { + private int valuesCalls; + + @Override + public Set> entrySet() { + return Collections.emptySet(); + } + + @Override + public Collection values() { + valuesCalls++; + return List.of(); + } + } + + @Test + void currentScalarCellOwnerProvesTemporaryRootWithoutGraphWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + RuntimeScalar scalarOwner = new RuntimeScalar(); + scalarOwner.localBindingExists = true; + scalarOwner.set(target.createReference()); + + CountingHashValues opaqueValues = new CountingHashValues(); + RuntimeHash opaque = new RuntimeHash(); + opaque.elements = opaqueValues; + RuntimeArray root = new RuntimeArray(); + root.localBindingExists = true; + // Put the opaque sibling first so a fallback BFS would enumerate + // it before reaching the owner cell. The owner-slot proof must + // return without opening that graph. + root.elements.add(opaque.createReference()); + root.elements.add(scalarOwner.createReference()); + + MortalList.pushTemporaryRoot(root); + try { + PerlOwnerSlot scalarCellOwner = scalarOwner.countedOwnerSlot(); + assertEquals(PerlOwnerSlot.Kind.SCALAR_CELL, scalarCellOwner.kind()); + assertTrue(DestroyDispatch.isCurrentPerlOwnerSlot(target, scalarCellOwner), + "the scalar cell must be the current counted owner of the target"); + assertFalse(MortalList.temporaryRootDirectlyReferences(target), + "the root points to the scalar cell, not directly to its value"); + assertTrue(MortalList.temporaryRootDirectlyReferences(scalarOwner), + "the root directly references the current scalar cell"); + + assertTrue(ReachabilityWalker.isReachableFromTemporaryRoots(target)); + assertEquals(0, opaqueValues.valuesCalls, + "the validated scalar-cell path must avoid the fallback graph walk"); + } finally { + MortalList.popTemporaryRoot(root); + root.elements.clear(); + root.localBindingExists = false; + MortalList.scopeExitCleanupArray(root); + scalarOwner.localBindingExists = false; + RuntimeScalar.scopeExitCleanup(scalarOwner); + } + } + } + + @Test + void currentCodeSlotOwnerProvesTemporaryRootWithoutGraphWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + String name = "TemporaryRootCountedCellOwnerTest::code"; + RuntimeCode code = new RuntimeCode(null, List.of()); + RuntimeScalar codeSlot = new RuntimeScalar(code); + GlobalVariable.globalCodeRefs.put(name, codeSlot); + + CountingHashValues opaqueValues = new CountingHashValues(); + RuntimeHash opaque = new RuntimeHash(); + opaque.elements = opaqueValues; + RuntimeArray root = new RuntimeArray(); + root.localBindingExists = true; + root.elements.add(opaque.createReference()); + root.elements.add(codeSlot.createReference()); + + MortalList.pushTemporaryRoot(root); + try { + PerlOwnerSlot codeOwner = code.ownerSlotSnapshot().stream() + .filter(slot -> slot.kind() == PerlOwnerSlot.Kind.CODE_SLOT) + .findFirst().orElseThrow(); + assertEquals(PerlOwnerSlot.Kind.CODE_SLOT, codeOwner.kind()); + assertTrue(DestroyDispatch.isCurrentPerlOwnerSlot(code, codeOwner), + "the stash scalar must be the current CODE slot owner"); + assertFalse(MortalList.temporaryRootDirectlyReferences(code), + "the root points to the CODE slot cell, not directly to the CV"); + assertTrue(MortalList.temporaryRootDirectlyReferences(codeSlot), + "the root directly references the CODE slot cell"); + + assertTrue(ReachabilityWalker.isReachableFromTemporaryRoots(code)); + assertEquals(0, opaqueValues.valuesCalls, + "the validated CODE-slot path must avoid the fallback graph walk"); + } finally { + MortalList.popTemporaryRoot(root); + root.elements.clear(); + root.localBindingExists = false; + MortalList.scopeExitCleanupArray(root); + GlobalVariable.globalCodeRefs.remove(name); + } + } + } + + @Test + void currentTieHandlerOwnerProvesTemporaryRootWithoutGraphWalk() { + assertTieHandlerOwnerProvesTemporaryRoot(PerlOwnerSlot.Kind.TIE_HANDLER); + } + + @Test + void currentArgumentTieHandlerOwnerProvesTemporaryRootWithoutGraphWalk() { + assertTieHandlerOwnerProvesTemporaryRoot(PerlOwnerSlot.Kind.ARGUMENT_TIE_HANDLER); + } + + @Test + void currentArgumentContainerOwnerProvesTemporaryRootWithoutGraphWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + target.setTrackedRefCount(0); + RuntimeScalar containerOwner = RuntimeScalar.retainArgumentContainerValue(target); + + CountingHashValues opaqueValues = new CountingHashValues(); + RuntimeHash opaque = new RuntimeHash(); + opaque.elements = opaqueValues; + RuntimeArray root = new RuntimeArray(); + root.localBindingExists = true; + root.elements.add(opaque.createReference()); + root.elements.add(containerOwner.createReference()); + + MortalList.pushTemporaryRoot(root); + try { + PerlOwnerSlot ownerSlot = target.ownerSlotSnapshot().stream() + .filter(slot -> slot.kind() == PerlOwnerSlot.Kind.ARGUMENT_CONTAINER) + .findFirst().orElseThrow(); + assertTrue(DestroyDispatch.isCurrentPerlOwnerSlot(target, ownerSlot), + "the argument-container owner must be current"); + assertFalse(MortalList.temporaryRootDirectlyReferences(target), + "the root points to the argument-container cell, not its value"); + assertTrue(MortalList.temporaryRootDirectlyReferences(containerOwner), + "the root directly references the argument-container cell"); + + assertTrue(ReachabilityWalker.isReachableFromTemporaryRoots(target)); + assertEquals(0, opaqueValues.valuesCalls, + "the validated argument-container path must avoid the fallback graph walk"); + } finally { + MortalList.popTemporaryRoot(root); + root.elements.clear(); + root.localBindingExists = false; + MortalList.scopeExitCleanupArray(root); + RuntimeScalar.releaseArgumentContainerValue(containerOwner); + } + } + } + + private void assertTieHandlerOwnerProvesTemporaryRoot(PerlOwnerSlot.Kind kind) { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + RuntimeScalar handlerSource = target.createAnonymousReference(); + RuntimeScalar handlerOwner = RuntimeScalar.retainTiedHandlerValue(handlerSource, kind); + + CountingHashValues opaqueValues = new CountingHashValues(); + RuntimeHash opaque = new RuntimeHash(); + opaque.elements = opaqueValues; + RuntimeArray root = new RuntimeArray(); + root.localBindingExists = true; + root.elements.add(opaque.createReference()); + root.elements.add(handlerOwner.createReference()); + + MortalList.pushTemporaryRoot(root); + try { + PerlOwnerSlot handlerSlot = target.ownerSlotSnapshot().stream() + .filter(slot -> slot.kind() == kind) + .findFirst().orElseThrow(); + assertTrue(DestroyDispatch.isCurrentPerlOwnerSlot(target, handlerSlot), + "the tied-handler owner must be current"); + assertFalse(MortalList.temporaryRootDirectlyReferences(target), + "the root points to the tied-handler cell, not its value"); + assertTrue(MortalList.temporaryRootDirectlyReferences(handlerOwner), + "the root directly references the tied-handler cell"); + + assertTrue(ReachabilityWalker.isReachableFromTemporaryRoots(target)); + assertEquals(0, opaqueValues.valuesCalls, + "the validated tied-handler path must avoid the fallback graph walk"); + } finally { + MortalList.popTemporaryRoot(root); + root.elements.clear(); + root.localBindingExists = false; + MortalList.scopeExitCleanupArray(root); + RuntimeScalar.releaseTiedHandlerValue(handlerOwner); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootExceptionUnwindTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootExceptionUnwindTest.java new file mode 100644 index 0000000000..97eb260e3d --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootExceptionUnwindTest.java @@ -0,0 +1,76 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@Tag("unit") +class TemporaryRootExceptionUnwindTest { + @Test + void failedCallDropsOnlyTemporaryRootsCreatedInsideItsFrame() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash callerValue = new RuntimeHash(); + RuntimeHash failedCallValue = new RuntimeHash(); + MortalList.pushTemporaryRoot(callerValue); + try { + int rootDepth = MortalList.temporaryRootDepth(); + RuntimeCode failingCode = new RuntimeCode((args, context) -> { + MortalList.pushTemporaryRoot(failedCallValue); + throw new PerlDieException(new RuntimeScalar("expected failure")); + }, null); + RuntimeScalar callable = new RuntimeScalar(failingCode); + + assertThrows(PerlDieException.class, + () -> RuntimeCode.apply( + callable, new RuntimeArray(), RuntimeContextType.SCALAR)); + + assertEquals(rootDepth, MortalList.temporaryRootDepth(), + "exceptional call cleanup must preserve caller leases and drop frame leases"); + assertEquals(1, callerValue.ownerSlotCount(PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + assertEquals(0, failedCallValue.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + } finally { + MortalList.popTemporaryRoot(callerValue); + } + } + } + + @Test + void targetBoundaryDropsPropagatedRootsAfterMaterializingTheReturn() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash callerValue = new RuntimeHash(); + RuntimeHash returnedReferent = new RuntimeHash(); + MortalList.pushTemporaryRoot(callerValue); + try { + int rootDepth = MortalList.temporaryRootDepth(); + RuntimeScalar returnValue = returnedReferent.createAnonymousReference(); + RuntimeCode[] target = new RuntimeCode[1]; + RuntimeCode transferringCode = new RuntimeCode((args, context) -> { + MortalList.pushTemporaryRoot(returnValue); + throw new PerlNonLocalReturnException(returnValue, target[0]); + }, null); + RuntimeScalar transferringCallable = new RuntimeScalar(transferringCode); + target[0] = new RuntimeCode((args, context) -> RuntimeCode.apply( + transferringCallable, new RuntimeArray(), RuntimeContextType.SCALAR), null); + + RuntimeList result = RuntimeCode.apply( + new RuntimeScalar(target[0]), new RuntimeArray(), RuntimeContextType.SCALAR); + + assertEquals(rootDepth, MortalList.temporaryRootDepth(), + "the target must preserve caller leases and drop transferred frame leases"); + assertEquals(1, callerValue.ownerSlotCount(PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + assertEquals(0, returnValue.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + assertSame(returnedReferent, ((RuntimeScalar) result.getFirst()).value, + "return ownership must preserve the referent after its temporary root is removed"); + } finally { + MortalList.popTemporaryRoot(callerValue); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootHashAliasOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootHashAliasOwnerTest.java new file mode 100644 index 0000000000..a95b8bd2da --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootHashAliasOwnerTest.java @@ -0,0 +1,78 @@ +package org.perlonjava.runtime.runtimetypes; + +import java.util.AbstractMap; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class TemporaryRootHashAliasOwnerTest { + private static final class CountingHashValues extends AbstractMap { + private int valuesCalls; + + @Override + public Set> entrySet() { + return Collections.emptySet(); + } + + @Override + public Collection values() { + valuesCalls++; + return List.of(); + } + } + + @Test + void exactHashAliasCellOwnerProvesTemporaryRootWithoutGraphWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar cell = new RuntimeScalar("aliased hash cell"); + RuntimeHash hashOwner = new RuntimeHash(); + hashOwner.aliasScalarCell("cell", cell); + + CountingHashValues opaqueValues = new CountingHashValues(); + RuntimeHash opaque = new RuntimeHash(); + opaque.elements = opaqueValues; + RuntimeArray root = new RuntimeArray(); + root.localBindingExists = true; + root.elements.add(opaque.createReference()); + root.elements.add(hashOwner.createReference()); + + MortalList.pushTemporaryRoot(root); + try { + PerlOwnerSlot aliasOwner = cell.ownerSlotSnapshot().stream() + .filter(slot -> slot.kind() == PerlOwnerSlot.Kind.HASH_ALIAS_CELL) + .findFirst().orElseThrow(); + assertTrue(DestroyDispatch.isCurrentPerlOwnerSlot(cell, aliasOwner), + "the hash alias slot must be a current native owner"); + assertSame(cell, hashOwner.elements.get("cell"), + "the hash slot must still contain this exact alias cell"); + assertFalse(MortalList.temporaryRootDirectlyReferences(cell), + "the root points to the owning hash, not directly to its cell"); + assertTrue(MortalList.temporaryRootDirectlyReferences(hashOwner), + "the root directly references the alias-owning hash"); + + assertTrue(ReachabilityWalker.isReachableFromTemporaryRoots(cell)); + assertEquals(0, opaqueValues.valuesCalls, + "the validated hash-alias path must avoid the fallback graph walk"); + } finally { + MortalList.popTemporaryRoot(root); + root.elements.clear(); + root.localBindingExists = false; + MortalList.scopeExitCleanupArray(root); + hashOwner.elements.clear(); + MortalList.scopeExitCleanupHash(hashOwner); + RuntimeScalar.scopeExitCleanup(cell); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootNestedReturnMutationTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootNestedReturnMutationTest.java new file mode 100644 index 0000000000..7882a82b08 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootNestedReturnMutationTest.java @@ -0,0 +1,42 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class TemporaryRootNestedReturnMutationTest { + @Test + void returnListMutationPreservesTheControlFlowLeaseUntilTransferCompletes() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray oldReferent = new RuntimeArray(); + RuntimeArray newReferent = new RuntimeArray(); + RuntimeList returnValues = new RuntimeList(); + returnValues.elements.add(oldReferent.createReference()); + RuntimeControlFlowList transfer = new RuntimeControlFlowList( + returnValues, "temporary-root-nested-return-mutation.t", 1); + + MortalList.pushTemporaryRoot(transfer); + try { + assertEquals(1, transfer.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_TEMPORARY_ROOT)); + assertEquals(oldReferent, ((RuntimeScalar) returnValues.elements.getFirst()).value); + + returnValues.elements.set(0, newReferent.createReference()); + + assertEquals(newReferent, ((RuntimeScalar) returnValues.elements.getFirst()).value); + + returnValues.elements.clear(); + assertTrue(returnValues.elements.isEmpty()); + } finally { + MortalList.popTemporaryRoot(transfer); + } + + assertEquals(0, transfer.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_TEMPORARY_ROOT)); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootOwnerSlotTest.java new file mode 100644 index 0000000000..3dbdeeb49b --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootOwnerSlotTest.java @@ -0,0 +1,151 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Tag("unit") +class TemporaryRootOwnerSlotTest { + @Test + void duplicateAndNonLifoPopsReleaseTheMatchingRootLeases() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash first = new RuntimeHash(); + RuntimeHash second = new RuntimeHash(); + + MortalList.pushTemporaryRoot(first); + MortalList.pushTemporaryRoot(first); + MortalList.pushTemporaryRoot(second); + + assertEquals(2, first.ownerSlotCount(PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + assertEquals(1, second.ownerSlotCount(PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + assertEquals(3, MortalList.temporaryRootDepth()); + + MortalList.popTemporaryRoot(first); + assertEquals(1, first.ownerSlotCount(PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + assertEquals(2, MortalList.temporaryRootDepth()); + + MortalList.popTemporaryRoot(second); + MortalList.popTemporaryRoot(first); + assertEquals(0, first.ownerSlotCount(PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + assertEquals(0, second.ownerSlotCount(PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + assertEquals(0, MortalList.temporaryRootDepth()); + } + } + + @Test + void depthRestoreReleasesEveryLeaseAddedAfterTheSavedBoundary() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash callerRoot = new RuntimeHash(); + RuntimeHash failedCallRoot = new RuntimeHash(); + MortalList.pushTemporaryRoot(callerRoot); + int depth = MortalList.temporaryRootDepth(); + + try { + MortalList.pushTemporaryRoot(failedCallRoot); + MortalList.pushTemporaryRoot(failedCallRoot); + throw new IllegalStateException("synthetic failed call"); + } catch (IllegalStateException expected) { + MortalList.restoreTemporaryRootDepth(depth); + } + + assertEquals(depth, MortalList.temporaryRootDepth()); + assertEquals(1, callerRoot.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + assertEquals(0, failedCallRoot.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + + MortalList.popTemporaryRoot(callerRoot); + assertEquals(0, callerRoot.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + } + } + + @Test + void clearingRuntimeStateReleasesAllTemporaryRootLeases() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash root = new RuntimeHash(); + root.setTrackedRefCount(1); // Keep one external owner while checking runtime reset. + MortalList.pushTemporaryRoot(root); + MortalList.pushTemporaryRoot(root); + + assertEquals(2, root.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + MortalList.clearTemporaryRoots(); + assertEquals(1, root.refCount); + assertEquals(0, root.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + + MortalList.pushTemporaryRoot(root); + MortalList.clearCurrentRuntimeState(); + + assertEquals(1, root.refCount); + assertEquals(0, root.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + assertEquals(0, MortalList.temporaryRootDepth()); + } + } + + @Test + void scalarTemporaryRootOwnsTheScalarValue() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar reference = referent.createAnonymousReference(); + RuntimeHash unrelated = new RuntimeHash(); + + MortalList.pushTemporaryRoot(reference); + try { + assertEquals(1, reference.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + assertEquals(referent, reference.value); + assertEquals(0, unrelated.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + } finally { + MortalList.popTemporaryRoot(reference); + } + } + } + + @Test + void arrayChildOwnershipUsesItsArrayElementSlot() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar reference = referent.createAnonymousReference(); + RuntimeArray root = new RuntimeArray(); + root.addClonedElement(reference); + + MortalList.pushTemporaryRoot(root); + try { + assertEquals(1, root.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + } finally { + MortalList.popTemporaryRoot(root); + } + } + } + + @Test + void hashChildOwnershipUsesItsHashElementSlot() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeHash root = new RuntimeHash(); + root.put("child", referent.createAnonymousReference()); + + MortalList.pushTemporaryRoot(root); + try { + assertEquals(1, root.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_VALUE)); + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + } finally { + MortalList.popTemporaryRoot(root); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootReleaseDoesNotTraverseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootReleaseDoesNotTraverseTest.java new file mode 100644 index 0000000000..2f5981a6b2 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootReleaseDoesNotTraverseTest.java @@ -0,0 +1,57 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.AbstractMap; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Tag("unit") +class TemporaryRootReleaseDoesNotTraverseTest { + private static final class CountingHashValues extends AbstractMap { + private int valuesCalls; + + @Override + public Set> entrySet() { + return Collections.emptySet(); + } + + @Override + public Collection values() { + valuesCalls++; + return List.of(); + } + } + + @Test + void cleanupDoesNotTraverseNestedTemporaryValues() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash nested = new RuntimeHash(); + CountingHashValues nestedValues = new CountingHashValues(); + nested.elements = nestedValues; + RuntimeList temporaryRoot = new RuntimeList(); + temporaryRoot.elements.add(nested.createReference()); + MortalList.pushTemporaryRoot(temporaryRoot); + try { + assertEquals(1, temporaryRoot.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_TEMPORARY_ROOT)); + MortalList.popTemporaryRoot(temporaryRoot); + + assertEquals(0, nestedValues.valuesCalls, + "temporary-root leases record their owner directly without walking nested graphs"); + } finally { + if (temporaryRoot.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_TEMPORARY_ROOT) != 0) { + MortalList.popTemporaryRoot(temporaryRoot); + } + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootScalarContentsOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootScalarContentsOwnerTest.java new file mode 100644 index 0000000000..dfae77ccc9 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootScalarContentsOwnerTest.java @@ -0,0 +1,84 @@ +package org.perlonjava.runtime.runtimetypes; + +import java.util.AbstractMap; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class TemporaryRootScalarContentsOwnerTest { + private static final class CountingHashValues extends AbstractMap { + private int valuesCalls; + + @Override + public Set> entrySet() { + return Collections.emptySet(); + } + + @Override + public Collection values() { + valuesCalls++; + return List.of(); + } + } + + @Test + void scalarReferenceContentsOwnerProvesTemporaryRootWithoutGraphWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + target.setTrackedRefCount(3); + RuntimeScalar scalarCell = new RuntimeScalar(); + scalarCell.type = RuntimeScalarType.REFERENCE; + scalarCell.value = target; + scalarCell.setTrackedRefCount(1); + scalarCell.referencedByScalarReference = true; + + RuntimeScalar wrapper = new RuntimeScalar(); + wrapper.type = RuntimeScalarType.REFERENCE; + wrapper.value = scalarCell; + wrapper.localBindingExists = true; + PerlOwnerSlot contentsOwner = new PerlOwnerSlot( + PerlOwnerSlot.Kind.SCALAR_REFERENCE_CONTENTS); + contentsOwner.acquireScalarReferenceContents(target, scalarCell, wrapper); + wrapper.scalarReferenceContentsOwner = contentsOwner; + + CountingHashValues opaqueValues = new CountingHashValues(); + RuntimeHash opaque = new RuntimeHash(); + opaque.elements = opaqueValues; + RuntimeArray root = new RuntimeArray(); + root.localBindingExists = true; + root.elements.add(wrapper); + root.elements.add(opaque.createReference()); + + MortalList.pushTemporaryRoot(root); + try { + assertTrue(DestroyDispatch.isCurrentPerlOwnerSlot(target, contentsOwner), + "the scalar-reference contents slot must describe the current cell"); + assertFalse(MortalList.temporaryRootDirectlyReferences(target), + "the root points to the scalar cell, not directly to its value"); + assertTrue(MortalList.temporaryRootDirectlyReferences(scalarCell), + "the root's direct edge is the scalar cell"); + + assertTrue(ReachabilityWalker.isReachableFromTemporaryRoots(target)); + assertEquals(0, opaqueValues.valuesCalls, + "the validated scalar-cell ancestry must avoid the fallback graph walk"); + } finally { + MortalList.popTemporaryRoot(root); + root.elements.clear(); + root.localBindingExists = false; + MortalList.scopeExitCleanupArray(root); + wrapper.localBindingExists = false; + wrapper.releaseOwnedScalarReferenceContents(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootUntrackedScalarOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootUntrackedScalarOwnerTest.java new file mode 100644 index 0000000000..8b7a2f6d5e --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TemporaryRootUntrackedScalarOwnerTest.java @@ -0,0 +1,78 @@ +package org.perlonjava.runtime.runtimetypes; + +import java.util.AbstractMap; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class TemporaryRootUntrackedScalarOwnerTest { + private static final class CountingHashValues extends AbstractMap { + private int valuesCalls; + + @Override + public Set> entrySet() { + return Collections.emptySet(); + } + + @Override + public Collection values() { + valuesCalls++; + return List.of(); + } + } + + @Test + void currentUntrackedScalarOwnerProvesTemporaryRootWithoutGraphWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar target = new RuntimeScalar("untracked target"); + RuntimeScalar scalarOwner = new RuntimeScalar(); + scalarOwner.type = RuntimeScalarType.REFERENCE; + scalarOwner.value = target; + scalarOwner.localBindingExists = true; + scalarOwner.refreshUntrackedReferenceOwner(); + PerlOwnerSlot ownerSlot = scalarOwner.untrackedReferenceOwnerSlot(); + + CountingHashValues opaqueValues = new CountingHashValues(); + RuntimeHash opaque = new RuntimeHash(); + opaque.elements = opaqueValues; + RuntimeArray root = new RuntimeArray(); + root.localBindingExists = true; + root.elements.add(opaque.createReference()); + root.elements.add(scalarOwner.createReference()); + + MortalList.pushTemporaryRoot(root); + try { + assertNotNull(ownerSlot); + assertEquals(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE, ownerSlot.kind()); + assertTrue(DestroyDispatch.isCurrentPerlOwnerSlot(target, ownerSlot), + "the scalar must be the current untracked owner of the target"); + assertFalse(MortalList.temporaryRootDirectlyReferences(target), + "the root points to the scalar cell, not directly to its value"); + assertTrue(MortalList.temporaryRootDirectlyReferences(scalarOwner), + "the root directly references the scalar cell"); + + assertTrue(ReachabilityWalker.isReachableFromTemporaryRoots(target)); + assertEquals(0, opaqueValues.valuesCalls, + "the validated untracked-scalar path must avoid the fallback graph walk"); + } finally { + MortalList.popTemporaryRoot(root); + root.elements.clear(); + root.localBindingExists = false; + MortalList.scopeExitCleanupArray(root); + scalarOwner.localBindingExists = false; + RuntimeScalar.scopeExitCleanup(scalarOwner); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/ThreadSnapshotTemporaryRootOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/ThreadSnapshotTemporaryRootOwnerTest.java new file mode 100644 index 0000000000..23e552793f --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/ThreadSnapshotTemporaryRootOwnerTest.java @@ -0,0 +1,68 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class ThreadSnapshotTemporaryRootOwnerTest { + + @Test + void directSnapshotRootUsesAnOwnerIdentityUntilTheLeaseCloses() { + PerlRuntime parent = new PerlRuntime().initialize(); + PerlRuntime.RootSnapshot snapshot = null; + try { + RuntimeArray sourceReferent = new RuntimeArray(); + RuntimeArray sourceObserverRoot = new RuntimeArray(); + RuntimeScalar weakObserver = new RuntimeScalar(); + weakObserver.type = RuntimeScalarType.ARRAYREFERENCE; + weakObserver.value = sourceReferent; + RuntimeScalar directRoot = new RuntimeScalar(); + directRoot.type = RuntimeScalarType.ARRAYREFERENCE; + directRoot.value = sourceReferent; + + try (PerlRuntime.Binding ignored = parent.bind()) { + // The direct Java root is intentionally outside the source + // runtime's counted scalar slots. Keep the source referent + // live while the snapshot reconstructs its external edge. + sourceReferent.setTrackedRefCount(1); + sourceObserverRoot.addClonedElement(weakObserver); + WeakRefRegistry.weaken(weakObserver); + } + + snapshot = parent.snapshotCloneWithRoots(List.of(sourceObserverRoot, directRoot)); + PerlRuntime child = snapshot.runtime(); + RuntimeArray childReferent = (RuntimeArray) + ((RuntimeScalar) snapshot.roots().get(1)).value; + RuntimeScalar childWeakObserver = ((RuntimeArray) snapshot.roots().getFirst()) + .elements.getFirst(); + + try (PerlRuntime.Binding ignored = child.bind()) { + assertNotNull(childReferent); + assertSame(childReferent, childWeakObserver.value); + assertTrue(WeakRefRegistry.isweak(childWeakObserver)); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, childReferent.refCountTrackingState(), + "a snapshot root must not fabricate a positive Perl reference count"); + assertEquals(1, childReferent.ownerSlotCount(PerlOwnerSlot.Kind.TEMPORARY_ROOT), + "the direct snapshot edge must have a stable temporary owner identity"); + } + + snapshot.close(); + snapshot = null; + + try (PerlRuntime.Binding ignored = child.bind()) { + assertEquals(RuntimeScalarType.UNDEF, childWeakObserver.type, + "retiring the final snapshot root must clear its weak observers"); + } + } finally { + if (snapshot != null) snapshot.close(); + parent.close(); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TiedHandlerNestedOwnerCountInvariantTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TiedHandlerNestedOwnerCountInvariantTest.java new file mode 100644 index 0000000000..b270a44f29 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TiedHandlerNestedOwnerCountInvariantTest.java @@ -0,0 +1,64 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class TiedHandlerNestedOwnerCountInvariantTest { + @Test + void nestedValueStoredBeforeFirstWeakenKeepsCountAlignedWithLiveSlots() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + RuntimeHash handler = new RuntimeHash(); + handler.put("target", target.createAnonymousReference()); + + RuntimeHash tied = new RuntimeHash(); + tied.type = RuntimeHash.TIED_HASH; + tied.elements = new TieHash("TiedHandlerOwnerCount::Tie", new RuntimeHash(), + handler.createAnonymousReference()); + + assertEquals(1, target.refCount); + assertEquals(1, target.countedOwnerSlotCount()); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + assertEquals(1, handler.ownerSlotCount(PerlOwnerSlot.Kind.TIE_HANDLER)); + + RuntimeScalar strong = new RuntimeScalar(); + strong.set(target.createAnonymousReference()); + RuntimeScalar weak = new RuntimeScalar(); + weak.set(strong); + try { + WeakRefRegistry.weaken(weak); + + assertEquals(2, target.refCount, + "the nested hash edge and strong scalar each contribute one count"); + assertEquals(target.refCount, target.countedOwnerSlotCount()); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + + strong.undefine(); + assertEquals(1, target.refCount, + "releasing the scalar owner leaves the nested handler edge counted"); + assertTrue(WeakRefRegistry.isweak(weak)); + + { + ((TieHash) tied.elements).releaseTiedObject(); + + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, target.perlLifecycleState(), + "untie destroys the handler and releases its final nested value edge"); + assertEquals(0, target.refCount); + assertEquals(0, target.countedOwnerSlotCount()); + assertEquals(RuntimeScalarType.UNDEF, weak.type, + "the final owner release clears the weak observer"); + } + } finally { + ((TieHash) tied.elements).releaseTiedObject(); + if (WeakRefRegistry.isweak(weak)) WeakRefRegistry.unweaken(weak); + if (strong.refCountOwned) strong.undefine(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TiedHandlerNestedOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TiedHandlerNestedOwnerSlotTest.java new file mode 100644 index 0000000000..27ba0c745a --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TiedHandlerNestedOwnerSlotTest.java @@ -0,0 +1,56 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class TiedHandlerNestedOwnerSlotTest { + @Test + void nestedHandlerHashSlotRetainsItsBalancedOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash handler = new RuntimeHash(); + RuntimeHash target = new RuntimeHash(); + handler.put("target", target.createAnonymousReference()); + + RuntimeHash tied = new RuntimeHash(); + tied.type = RuntimeHash.TIED_HASH; + tied.elements = new TieHash("Issue1649::TiedOwner", new RuntimeHash(), + handler.createAnonymousReference()); + + RuntimeScalar released = new RuntimeScalar(); + released.set(target.createAnonymousReference()); + RuntimeScalar weak = target.createAnonymousReference(); + WeakRefRegistry.weaken(weak); + + try { + assertEquals(1, handler.ownerSlotCount(PerlOwnerSlot.Kind.TIE_HANDLER)); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + assertEquals(2, target.refCount, + "the scalar and nested handler hash each contribute one owner count"); + MortalList.deferDecrementIfTracked(released); + MortalList.flushAboveMark(); + + assertEquals(1, target.refCount); + assertTrue(WeakRefRegistry.isweak(weak)); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.HASH_ELEMENT)); + + handler.elements.get("target").set(new RuntimeScalar()); + assertFalse(WeakRefRegistry.isweak(weak)); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + target.perlLifecycleState()); + } finally { + if (handler.elements.containsKey("target")) { + handler.elements.get("target").set(new RuntimeScalar()); + } + if (WeakRefRegistry.isweak(weak)) WeakRefRegistry.unweaken(weak); + released.set(new RuntimeScalar()); + ((TieHash) tied.elements).releaseTiedObject(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TiedHandlerOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TiedHandlerOwnerTest.java new file mode 100644 index 0000000000..ab92f3242c --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TiedHandlerOwnerTest.java @@ -0,0 +1,118 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class TiedHandlerOwnerTest { + @Test + void wrappersHaveDistinctOwnersAndDoNotBorrowTheirSourceCell() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash handler = new RuntimeHash(); + handler.setTrackedRefCount(0); + RuntimeScalar source = handler.createAnonymousReference(); + TieHash hash = new TieHash("Handler", new RuntimeHash(), source); + TieArray array = new TieArray("Handler", new RuntimeArray(), source, new RuntimeArray()); + TieScalar scalar = new TieScalar("Handler", new RuntimeScalar(), source); + TieHandle handle = new TieHandle("Handler", new RuntimeIO(), source); + assertEquals(4, handler.ownerSlotCount(PerlOwnerSlot.Kind.TIE_HANDLER)); + assertEquals(4, handler.ownerSlotSnapshot().stream() + .map(PerlOwnerSlot::identity).distinct().count()); + assertEquals(4, handler.refCount); + source.set(RuntimeScalarCache.scalarUndef); + assertSame(handler, hash.getSelf().value); + assertSame(handler, array.getSelf().value); + assertSame(handler, scalar.getSelf().value); + RuntimeScalar weak = new RuntimeScalar(); + weak.set(handler.createAnonymousReference()); + WeakRefRegistry.weaken(weak); + hash.releaseTiedObject(); + assertSame(handler, hash.getSelf().value, + "retired magic can still borrow its snapshot during local restoration"); + assertFalse(hash.getSelf().refCountOwned); + hash.releaseTiedObject(); + array.releaseTiedObject(); + array.releaseTiedObject(); + assertEquals(2, handler.refCount); + assertEquals(2, handler.ownerSlotCount(PerlOwnerSlot.Kind.TIE_HANDLER)); + scalar.releaseTiedObject(); + scalar.releaseTiedObject(); + assertEquals(RuntimeScalarType.HASHREFERENCE, weak.type); + { + handle.releaseTiedObject(); + handle.releaseTiedObject(); + assertEquals(RuntimeScalarType.UNDEF, weak.type); + assertFalse(handler.hasOwnerSlots()); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, handler.perlLifecycleState()); + } + } + } + + @Test + void finalHashDestructionReleasesMagicDespiteAnExpressionBorrow() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash handler = new RuntimeHash(); + handler.setTrackedRefCount(0); + RuntimeHash outer = new RuntimeHash(); + outer.type = RuntimeHash.TIED_HASH; + outer.elements = new TieHash("Handler", new RuntimeHash(), handler.createAnonymousReference()); + RuntimeScalar weak = new RuntimeScalar(); + weak.set(handler.createAnonymousReference()); + WeakRefRegistry.weaken(weak); + RuntimeScalar borrowed = outer.createAnonymousReference(); + MortalList.pushTemporaryRoot(borrowed); + try { + outer.setTrackedRefCount(0); + DestroyDispatch.callDestroyFromCountedOwner(outer); + assertEquals(RuntimeScalarType.UNDEF, weak.type); + assertFalse(handler.hasOwnerSlots()); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, outer.perlLifecycleState()); + } finally { + MortalList.popTemporaryRoot(borrowed); + } + } + } + @Test + void finalContainerReleaseDropsItsChildSlotsDespiteExpressionBorrows() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash hashChild = new RuntimeHash(); + RuntimeHash hash = new RuntimeHash(); + hash.put("child", hashChild.createAnonymousReference()); + RuntimeScalar hashWeak = new RuntimeScalar(); + hashWeak.set(hashChild.createAnonymousReference()); + WeakRefRegistry.weaken(hashWeak); + RuntimeHash arrayChild = new RuntimeHash(); + RuntimeArray array = new RuntimeArray(); + array.push(arrayChild.createAnonymousReference()); + RuntimeScalar arrayWeak = new RuntimeScalar(); + arrayWeak.set(arrayChild.createAnonymousReference()); + WeakRefRegistry.weaken(arrayWeak); + RuntimeScalar borrowedHash = hash.createAnonymousReference(); + RuntimeScalar borrowedArray = array.createAnonymousReference(); + MortalList.pushTemporaryRoot(borrowedHash); + MortalList.pushTemporaryRoot(borrowedArray); + try { + hash.setTrackedRefCount(0); + DestroyDispatch.callDestroyFromCountedOwner(hash); + array.setTrackedRefCount(0); + DestroyDispatch.callDestroyFromCountedOwner(array); + // Container finalization queues child decrements; the boundary + // drains those identified releases before observers are checked. + MortalList.flush(); + assertEquals(RuntimeScalarType.UNDEF, hashWeak.type); + assertEquals(RuntimeScalarType.UNDEF, arrayWeak.type); + assertFalse(hashChild.hasOwnerSlots()); + assertFalse(arrayChild.hasOwnerSlots()); + } finally { + MortalList.popTemporaryRoot(borrowedArray); + MortalList.popTemporaryRoot(borrowedHash); + } + } + } + +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TransientAggregateHoldIsNotDurableOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TransientAggregateHoldIsNotDurableOwnerTest.java new file mode 100644 index 0000000000..f6db1b3ac3 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TransientAggregateHoldIsNotDurableOwnerTest.java @@ -0,0 +1,364 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicBoolean; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class TransientAggregateHoldIsNotDurableOwnerTest { + @Test + void stagedArgumentContainerDoesNotMakeAnUnownedArrayDurable() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeArray temporary = new RuntimeArray(); + RuntimeScalar cell = referent.createAnonymousReference(); + temporary.elements.add(cell); + + assertFalse(cell.hasLiveDurableStrongValueSlot()); + RuntimeCode.CallArguments staged = RuntimeCode.newCallArguments(1); + try { + staged.add(cell); + assertTrue(temporary.hasPerlStrongOwner(), + "staging temporarily keeps the untracked array available"); + assertTrue(temporary.hasCurrentPerlStorageOwner(), + "a live argument-container transfer remains a current storage owner"); + assertFalse(temporary.hasPersistentPerlStrongOwnerIdentity(), + "the staging lease is not durable array storage"); + assertFalse(cell.hasLiveDurableStrongValueSlot(), + "a temporary argument-container lease cannot keep the cell durable"); + } finally { + staged.finish(); + } + } + } + + @Test + void durableArrayOwnerSurvivesATemporaryContainerHint() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeArray persistent = new RuntimeArray(); + persistent.localBindingExists = true; + RuntimeScalar cell = referent.createAnonymousReference(); + persistent.elements.add(cell); + RuntimeArray temporary = new RuntimeArray(); + temporary.elements.add(cell); + + assertTrue(cell.hasLiveDurableStrongValueSlot(), + "all current containers are considered, not only the latest hint"); + } + } + + @Test + void stagedArgumentContainerDoesNotMakeAnUnownedHashDurable() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeHash temporary = new RuntimeHash(); + RuntimeScalar cell = referent.createAnonymousReference(); + temporary.elements.put("cell", cell); + + assertFalse(cell.hasLiveDurableStrongValueSlot()); + RuntimeCode.CallArguments staged = RuntimeCode.newCallArguments(1); + try { + staged.add(cell); + assertTrue(temporary.hasPerlStrongOwner()); + assertFalse(temporary.hasPersistentPerlStrongOwnerIdentity()); + assertFalse(cell.hasLiveDurableStrongValueSlot()); + } finally { + staged.finish(); + } + } + } + + @Test + void durableHashOwnerSurvivesATemporaryContainerHint() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeHash persistent = new RuntimeHash(); + persistent.localBindingExists = true; + RuntimeScalar cell = referent.createAnonymousReference(); + persistent.elements.put("cell", cell); + RuntimeHash temporary = new RuntimeHash(); + temporary.elements.put("cell", cell); + + assertTrue(cell.hasLiveDurableStrongValueSlot(), + "all current containers are considered, not only the latest hint"); + } + } + + @Test + void untrackedClosureInTemporaryArrayDoesNotBlockCaptureRetirement() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + closure.markRefCountUntracked(); + RuntimeScalar capturedPad = new RuntimeScalar(42); + PerlOwnerSlot captureOwner = capturedPad.retainClosureCaptureSlot(closure); + closure.capturedScalars = new RuntimeScalar[] {capturedPad}; + closure.capturedScalarOwnerSlots = new PerlOwnerSlot[] {captureOwner}; + RuntimeScalar codeCell = new RuntimeScalar(closure); + RuntimeArray temporary = new RuntimeArray(); + temporary.localBindingExists = true; + temporary.elements.add(codeCell); + temporary.localBindingExists = false; + + assertEquals(1, closure.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertFalse(closure.hasPerlOwnerForCaptureOtherThan(null), + "an unowned aggregate cell is not a durable capture owner"); + closure.requestCaptureReleaseWhenUnowned(); + + assertNull(closure.capturedScalars, + "the stale untracked scalar edge must not keep captures alive"); + assertFalse(captureOwner.isActive()); + } + } + + @Test + void activeAggregateTransferKeepsNestedClosureCapturesAlive() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + closure.markRefCountUntracked(); + RuntimeScalar capturedPad = new RuntimeScalar(42); + PerlOwnerSlot captureOwner = capturedPad.retainClosureCaptureSlot(closure); + closure.capturedScalars = new RuntimeScalar[] {capturedPad}; + closure.capturedScalarOwnerSlots = new PerlOwnerSlot[] {captureOwner}; + RuntimeScalar codeCell = new RuntimeScalar(closure); + RuntimeArray temporary = new RuntimeArray(); + temporary.localBindingExists = true; + temporary.elements.add(codeCell); + temporary.localBindingExists = false; + RuntimeCode.CallArguments staged = RuntimeCode.newCallArguments(1); + + MortalList.pushMark(); + boolean markActive = true; + try { + staged.add(codeCell); + + assertTrue(temporary.hasCurrentPerlStorageOwner()); + assertFalse(temporary.hasPersistentPerlStrongOwnerIdentity()); + assertFalse(closure.hasCallTransferOwner(), + "only the containing aggregate is transferred as an argument"); + assertTrue(closure.hasPerlOwnerForCaptureOtherThan(null), + "the nested callback remains live through its aggregate's call transfer"); + + RuntimeCode.pushActiveCode(closure); + closure.requestCaptureReleaseWhenUnowned(); + assertTrue(captureOwner.isActive()); + + staged.finish(); + assertEquals(0, + closure.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE), + "the last aggregate transfer retires its stale direct CODE-cell edge"); + MortalList.popAndFlush(); + markActive = false; + RuntimeCode.popActiveCode(closure); + + assertNull(closure.capturedScalars, + "the requested release completes after both owners leave"); + assertFalse(captureOwner.isActive()); + } finally { + staged.finish(); + if (markActive) MortalList.popAndFlush(); + if (RuntimeCode.isActiveCode(closure)) RuntimeCode.popActiveCode(closure); + } + } + } + + @Test + void temporaryArrayRootDefersAggregateAndCaptureCleanup() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + closure.markRefCountUntracked(); + RuntimeScalar capturedPad = new RuntimeScalar(42); + PerlOwnerSlot captureOwner = capturedPad.retainClosureCaptureSlot(closure); + closure.capturedScalars = new RuntimeScalar[] {capturedPad}; + closure.capturedScalarOwnerSlots = new PerlOwnerSlot[] {captureOwner}; + + RuntimeScalar codeCell = new RuntimeScalar(closure); + RuntimeArray root = new RuntimeArray(); + root.localBindingExists = true; + root.addClonedElement(codeCell); + root.localBindingExists = false; + + RuntimeCode.CallArguments staged = RuntimeCode.newCallArguments(1); + MortalList.pushTemporaryRoot(root); + try { + assertEquals(1, root.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_TEMPORARY_ROOT)); + staged.add(codeCell); + closure.requestCaptureReleaseWhenUnowned(); + staged.finish(); + + assertTrue(captureOwner.isActive(), + "a nested temporary-root path keeps closure captures live"); + assertEquals(1, + closure.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + } finally { + staged.finish(); + MortalList.popTemporaryRoot(root); + } + + assertNull(closure.capturedScalars, + "queued cleanup retires captures after the last temporary root leaves"); + assertFalse(captureOwner.isActive()); + assertEquals(0, + closure.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + } + } + + @Test + void temporaryHashRootDefersCellCleanup() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + closure.markRefCountUntracked(); + RuntimeScalar capturedPad = new RuntimeScalar(42); + PerlOwnerSlot captureOwner = capturedPad.retainClosureCaptureSlot(closure); + closure.capturedScalars = new RuntimeScalar[] {capturedPad}; + closure.capturedScalarOwnerSlots = new PerlOwnerSlot[] {captureOwner}; + + RuntimeScalar codeCell = new RuntimeScalar(closure); + RuntimeHash root = new RuntimeHash(); + root.localBindingExists = true; + root.put("callback", codeCell); + root.localBindingExists = false; + + RuntimeCode.CallArguments staged = RuntimeCode.newCallArguments(1); + MortalList.pushTemporaryRoot(root); + try { + assertEquals(1, root.ownerSlotCount( + PerlOwnerSlot.Kind.EXPRESSION_TEMPORARY_ROOT)); + staged.add(codeCell); + closure.requestCaptureReleaseWhenUnowned(); + staged.finish(); + + assertTrue(captureOwner.isActive(), + "the temporary hash root keeps callback captures live"); + assertEquals(1, + closure.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + } finally { + staged.finish(); + MortalList.popTemporaryRoot(root); + } + + assertNull(closure.capturedScalars); + assertFalse(captureOwner.isActive()); + assertEquals(0, + closure.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + } + } + + @Test + void aggregateRefreshStopsAfterDestroyAddsRootAndMutatesArray() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + closure.markRefCountUntracked(); + RuntimeScalar capturedPad = new RuntimeScalar(42); + PerlOwnerSlot captureOwner = capturedPad.retainClosureCaptureSlot(closure); + closure.capturedScalars = new RuntimeScalar[] {capturedPad}; + closure.capturedScalarOwnerSlots = new PerlOwnerSlot[] {captureOwner}; + RuntimeScalar codeCell = new RuntimeScalar(closure); + RuntimeArray aggregate = new RuntimeArray(); + AtomicBoolean reenter = new AtomicBoolean(false); + RuntimeScalar mutationTrigger = new RuntimeScalar() { + @Override + void reconcileContainerOwnerAfterMutation(RuntimeBase owner) { + if (reenter.compareAndSet(true, false)) { + MortalList.pushTemporaryRoot(aggregate); + aggregate.elements.add(new RuntimeScalar(123)); + } + super.reconcileContainerOwnerAfterMutation(owner); + } + }; + aggregate.localBindingExists = true; + aggregate.elements.add(mutationTrigger); + aggregate.elements.add(codeCell); + aggregate.localBindingExists = false; + + RuntimeCode.CallArguments staged = RuntimeCode.newCallArguments(1); + staged.add(codeCell); + closure.requestCaptureReleaseWhenUnowned(); + reenter.set(true); + staged.finish(); + + try { + assertEquals(1, MortalList.temporaryRootDepth()); + assertEquals(3, aggregate.elements.size(), + "the reconciliation callback mutates the same array safely"); + assertTrue(captureOwner.isActive(), + "capture cleanup remains deferred while the new root is active"); + } finally { + MortalList.popTemporaryRoot(aggregate); + } + + closure.requestCaptureReleaseWhenUnowned(); + assertNull(closure.capturedScalars); + assertFalse(captureOwner.isActive()); + assertEquals(0, + closure.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + } + } + + @Test + void durableArrayCellKeepsClosureCapturesAlive() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + closure.markRefCountUntracked(); + RuntimeScalar capturedPad = new RuntimeScalar(42); + PerlOwnerSlot captureOwner = capturedPad.retainClosureCaptureSlot(closure); + closure.capturedScalars = new RuntimeScalar[] {capturedPad}; + closure.capturedScalarOwnerSlots = new PerlOwnerSlot[] {captureOwner}; + RuntimeScalar codeCell = new RuntimeScalar(closure); + RuntimeArray persistent = new RuntimeArray(); + persistent.localBindingExists = true; + persistent.elements.add(codeCell); + + assertTrue(closure.hasPerlOwnerForCaptureOtherThan(null)); + closure.requestCaptureReleaseWhenUnowned(); + + assertTrue(closure.capturedScalars != null, + "a durable scalar cell must continue to retain its closure captures"); + assertTrue(captureOwner.isActive()); + } + } + + @Test + void activeCallTransferKeepsTemporaryClosureCapturesAlive() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + closure.setTrackedRefCount(0); + RuntimeScalar capturedPad = new RuntimeScalar(42); + PerlOwnerSlot captureOwner = capturedPad.retainClosureCaptureSlot(closure); + closure.capturedScalars = new RuntimeScalar[] {capturedPad}; + closure.capturedScalarOwnerSlots = new PerlOwnerSlot[] {captureOwner}; + RuntimeCode.CallArguments staged = RuntimeCode.newCallArguments(1); + + MortalList.pushMark(); + boolean markActive = true; + try { + staged.add(new RuntimeScalar(closure)); + staged.toRuntimeArray(); + + assertTrue(closure.hasCallTransferOwner()); + closure.requestCaptureReleaseWhenUnowned(); + assertTrue(closure.capturedScalars != null, + "an active call transfer still needs the closure's captures"); + assertTrue(captureOwner.isActive()); + + staged.finish(); + MortalList.popAndFlush(); + markActive = false; + + assertNull(closure.capturedScalars, + "the requested capture release completes when the transfer ends"); + assertFalse(captureOwner.isActive()); + } finally { + staged.finish(); + if (markActive) MortalList.popAndFlush(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/TransientArgumentAliasOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/TransientArgumentAliasOwnerTest.java new file mode 100644 index 0000000000..acdc688bcc --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/TransientArgumentAliasOwnerTest.java @@ -0,0 +1,58 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Tag("unit") +class TransientArgumentAliasOwnerTest { + @Test + void stagedCallArgumentRecordsItsTransientScalarCell() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar cell = new RuntimeScalar(); + cell.set(referent.createAnonymousReference()); + RuntimeCode.CallArguments arguments = RuntimeCode.newCallArguments(1); + + try { + arguments.add(cell); + + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS), + "the staging frame records the scalar cell it retains"); + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_VALUE), + "borrowing the cell does not add a referent count"); + } finally { + arguments.finish(); + } + + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS), + "finishing the staging frame retires its alias identity"); + } + } + + @Test + void activeArgumentFrameRecordsEveryScalarCell() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeScalar cell = new RuntimeScalar(); + cell.set(referent.createAnonymousReference()); + RuntimeArray arguments = new RuntimeArray(); + arguments.elements.add(cell); + boolean active = false; + + try { + RuntimeCode.pushArgs(arguments); + active = true; + + assertEquals(1, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS), + "the active @_ frame records its scalar cell even without a lexical marker"); + } finally { + if (active) RuntimeCode.popArgs(); + } + + assertEquals(0, referent.ownerSlotCount(PerlOwnerSlot.Kind.ARGUMENT_ALIAS), + "popping @_ retires its alias identity"); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/UnblessedAggregateCachedRootShortcutTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/UnblessedAggregateCachedRootShortcutTest.java deleted file mode 100644 index 711e346a88..0000000000 --- a/src/test/java/org/perlonjava/runtime/runtimetypes/UnblessedAggregateCachedRootShortcutTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package org.perlonjava.runtime.runtimetypes; - -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Tag("unit") -class UnblessedAggregateCachedRootShortcutTest { - @Test - void rootedAggregateReusesAnExternalSnapshotBeforeBuildingFullRoots() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray global = new RuntimeArray(); - String globalName = - "UnblessedAggregateCachedRootShortcutTest::global"; - GlobalVariable.globalArrays.put(globalName, global); - - RuntimeHash blessedSeed = new RuntimeHash(); - blessedSeed.blessId = NameNormalizer.getBlessId( - "UnblessedAggregateCachedRootShortcutTest::Seed"); - RuntimeScalar blessedStrong = blessedSeed.createAnonymousReference(); - RuntimeScalar blessedWeak = blessedSeed.createAnonymousReference(); - global.elements.add(blessedStrong); - WeakRefRegistry.weaken(blessedWeak); - blessedSeed.refCount = 1; - - RuntimeArray aggregate = new RuntimeArray(); - RuntimeScalar aggregateStrong = aggregate.createAnonymousReference(); - RuntimeScalar aggregateWeak = aggregate.createAnonymousReference(); - global.elements.add(aggregateStrong); - WeakRefRegistry.weaken(aggregateWeak); - aggregate.refCount = 1; - - try { - MortalList.pushMark(); - MortalList.deferDecrement(blessedSeed); - MortalList.deferDecrement(aggregate); - - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - MortalList.popAndFlush(); - - ReachabilityQueryStats stats = measurement.stats(); - assertEquals(2, stats.deferredBasesProcessed); - assertEquals(1, stats.externalRootSnapshotsBuilt, - "the blessed seed builds one package-root snapshot"); - assertEquals(0, stats.snapshotsBuilt, - "the rooted aggregate reuses the existing external proof"); - assertTrue(stats.externalRootSnapshotNodesVisited > 0); - assertEquals(1, blessedSeed.refCount); - assertEquals(1, aggregate.refCount); - } - } finally { - WeakRefRegistry.unweaken(blessedWeak); - WeakRefRegistry.unweaken(aggregateWeak); - GlobalVariable.globalArrays.remove(globalName); - MortalList.invalidateAllRootSnapshots(); - } - } - } - - @Test - void positiveAggregateProofSurvivesRootRemovalUntilDrainEnds() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray global = new RuntimeArray(); - String globalName = - "UnblessedAggregateCachedRootShortcutTest::removedRoot"; - GlobalVariable.globalArrays.put(globalName, global); - RuntimeArray aggregate = new RuntimeArray(); - RuntimeScalar strong = aggregate.createAnonymousReference(); - RuntimeScalar weak = aggregate.createAnonymousReference(); - global.elements.add(strong); - WeakRefRegistry.weaken(weak); - aggregate.refCount = 1; - - LifecycleRuntimeState state = runtime.lifecycleState; - try { - state.flushing = true; - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - assertTrue(MortalList.isUnblessedAggregateReachableDuringDrain(aggregate)); - assertEquals(1, measurement.stats().externalRootSnapshotsBuilt); - - global.elements.remove(strong); - MortalList.invalidateExternalRootSnapshot(); - - assertTrue(MortalList.isUnblessedAggregateReachableDuringDrain(aggregate), - "a positive proof is retained until this cleanup drain ends"); - assertEquals(1, measurement.stats().externalRootSnapshotsBuilt, - "root removal must not rebuild package roots for this aggregate"); - } - - state.flushing = false; - MortalList.pushMark(); - MortalList.deferDecrement(aggregate); - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - MortalList.popAndFlush(); - assertEquals(RuntimeScalarType.UNDEF, weak.type, - "the next drain must discard the previous drain's positive proof"); - assertEquals(null, weak.value, - "the weak observer must be cleared after the aggregate becomes unreachable"); - assertEquals(1, measurement.stats().externalRootSnapshotsBuilt, - "the new drain must build a current package-root snapshot"); - } - } finally { - state.flushing = false; - state.unblessedAggregateDrainRoots.clear(); - state.unblessedAggregateDrainSnapshotIncomplete = false; - WeakRefRegistry.unweaken(weak); - GlobalVariable.globalArrays.remove(globalName); - MortalList.invalidateAllRootSnapshots(); - } - } - } -} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/UnblessedAggregateDrainPositiveProofCacheTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/UnblessedAggregateDrainPositiveProofCacheTest.java deleted file mode 100644 index e977b75a16..0000000000 --- a/src/test/java/org/perlonjava/runtime/runtimetypes/UnblessedAggregateDrainPositiveProofCacheTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.perlonjava.runtime.runtimetypes; - -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Tag("unit") -class UnblessedAggregateDrainPositiveProofCacheTest { - @Test - void cachesOnlyPositiveTargetsInsteadOfCopyingEveryReachableRoot() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray global = new RuntimeArray(); - for (int i = 0; i < 128; i++) { - global.elements.add(new RuntimeHash().createAnonymousReference()); - } - String globalName = - "UnblessedAggregateDrainPositiveProofCacheTest::global"; - GlobalVariable.globalArrays.put(globalName, global); - RuntimeArray first = new RuntimeArray(); - RuntimeArray second = new RuntimeArray(); - RuntimeArray third = new RuntimeArray(); - first.refCount = 1; - second.refCount = 1; - third.refCount = 1; - MortalList.pushMark(); - MortalList.deferDecrement(first); - MortalList.deferDecrement(second); - MortalList.deferDecrement(third); - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - MortalList.popAndFlush(); - - assertEquals(3, measurement.stats().deferredBasesProcessed); - assertTrue(measurement.stats().externalRootSnapshotNodesVisited > 128, - "the cleanup snapshot examines the populated package root"); - assertEquals(1, measurement.stats().externalRootSnapshotsBuilt, - "all three cleanup targets reuse one package-root snapshot"); - assertEquals(0, - measurement.stats().unblessedAggregateDrainPositiveProofsCached, - "unreachable cleanup targets create no positive drain proofs"); - } finally { - GlobalVariable.globalArrays.remove(globalName); - MortalList.invalidateAllRootSnapshots(); - } - } - } -} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/UnblessedAggregateReachabilitySnapshotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/UnblessedAggregateReachabilitySnapshotTest.java deleted file mode 100644 index 8f65665e3a..0000000000 --- a/src/test/java/org/perlonjava/runtime/runtimetypes/UnblessedAggregateReachabilitySnapshotTest.java +++ /dev/null @@ -1,241 +0,0 @@ -package org.perlonjava.runtime.runtimetypes; - -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Tag("unit") -class UnblessedAggregateReachabilitySnapshotTest { - @Test - void oversizedRootWalkStopsAtEdgeBudgetAndTreatsUnknownTargetsAsReachable() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeHash largeRoot = new RuntimeHash(); - for (int i = 0; i <= ReachabilityWalker.MAX_ROOT_SNAPSHOT_EDGES; i++) { - largeRoot.elements.put("edge-" + i, new RuntimeScalar(i)); - } - RuntimeArray global = new RuntimeArray(); - global.elements.add(largeRoot.createReference()); - String globalName = - "UnblessedAggregateReachabilitySnapshotTest::largeRoot"; - GlobalVariable.globalArrays.put(globalName, global); - RuntimeArray unresolved = new RuntimeArray(); - - try { - ReachabilityWalker.RootReachabilitySnapshot snapshot = - ReachabilityWalker.reachableFromRootsSnapshotWithStatus(); - - assertEquals(ReachabilityWalker.MAX_ROOT_SNAPSHOT_EDGES, - snapshot.edgesVisited(), "the full-root walk must stop at its edge budget"); - assertFalse(snapshot.complete(), "a capped root walk cannot prove an object dead"); - assertTrue(snapshot.isReachable(unresolved), - "unknown targets remain protected when the root proof is incomplete"); - } finally { - GlobalVariable.globalArrays.remove(globalName); - MortalList.invalidateAllRootSnapshots(); - } - } - } - - @Test - void initialWeakParentRegistrationPreservesAnUntrackedRootedAggregate() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray global = new RuntimeArray(); - String globalName = "UnblessedAggregateReachabilitySnapshotTest::weakParentRoot"; - GlobalVariable.globalArrays.put(globalName, global); - RuntimeArray target = new RuntimeArray(); - RuntimeScalar strong = target.createAnonymousReference(); - target.refCount = -1; - global.elements.add(strong); - RuntimeScalar weak = target.createAnonymousReference(); - target.refCount = -1; - - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - try { - WeakRefRegistry.weaken(weak); - assertTrue(WeakRefRegistry.isweak(weak)); - assertEquals(1, target.refCount, - "the root proof protects an untracked aggregate before its first weak edge"); - assertEquals(1, measurement.stats().rootQueries, - "the initial weak-parent transition checks the current live root"); - } finally { - WeakRefRegistry.unweaken(weak); - GlobalVariable.globalArrays.remove(globalName); - MortalList.invalidateAllRootSnapshots(); - } - } - } - } - - @Test - void liveWeaklyObservedAggregatesSurviveOneSharedRootSnapshotPerDrain() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray global = new RuntimeArray(); - String globalName = "UnblessedAggregateReachabilitySnapshotTest::liveAggregates"; - GlobalVariable.globalArrays.put(globalName, global); - RuntimeArray[] targets = new RuntimeArray[3]; - RuntimeScalar[] weakRefs = new RuntimeScalar[3]; - - try { - MortalList.pushMark(); - for (int i = 0; i < targets.length; i++) { - RuntimeArray target = new RuntimeArray(); - target.refCount = 1; - global.elements.add(target.createAnonymousReference()); - RuntimeScalar weak = target.createAnonymousReference(); - WeakRefRegistry.weaken(weak); - targets[i] = target; - weakRefs[i] = weak; - MortalList.deferDecrement(target); - } - - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - MortalList.popAndFlush(); - - ReachabilityQueryStats stats = measurement.stats(); - assertEquals(3, stats.deferredBasesProcessed); - assertEquals(1, stats.externalRootSnapshotsBuilt, - "live unblessed aggregates share one package-root snapshot per drain"); - assertEquals(0, stats.rootQueries, - "aggregate preservation must not launch one root query per target"); - assertTrue(stats.externalRootSnapshotEdgesInspected >= targets.length, - "the snapshot must inspect the rooted aggregate edges"); - assertTrue(stats.externalRootSnapshotNodesVisited >= targets.length + 1, - "the snapshot must visit the global root and all targets"); - for (RuntimeArray target : targets) { - assertEquals(1, target.refCount, - "a strong global owner preserves the weakly observed aggregate"); - } - } - } finally { - for (RuntimeScalar weak : weakRefs) { - if (weak != null) WeakRefRegistry.unweaken(weak); - } - GlobalVariable.globalArrays.remove(globalName); - MortalList.invalidateAllRootSnapshots(); - } - } - } - - @Test - void deferredUnblessedAggregateOwnersShareOneMeasuredRootWalk() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray global = new RuntimeArray(); - RuntimeArray nestedOwners = new RuntimeArray(); - global.elements.add(nestedOwners.createReference()); - for (int i = 0; i < 256; i++) { - global.elements.add(new RuntimeHash().createReference()); - } - String globalName = "UnblessedAggregateReachabilitySnapshotTest::global"; - GlobalVariable.globalArrays.put(globalName, global); - - try { - MortalList.pushMark(); - RuntimeHash[] targets = new RuntimeHash[3]; - for (int i = 0; i < targets.length; i++) { - RuntimeHash target = new RuntimeHash(); - target.activateOwnerTracking(); - RuntimeScalar owner = target.createAnonymousReference(); - RuntimeScalar.incrementRefCountForContainerStore(owner); - nestedOwners.elements.add(owner); - WeakRefRegistry.weaken(target.createAnonymousReference()); - targets[i] = target; - MortalList.deferDecrement(target); - } - - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - MortalList.popAndFlush(); - - ReachabilityQueryStats stats = measurement.stats(); - assertEquals(3, stats.deferredBasesProcessed); - assertEquals(3, stats.scalarReachabilityQueries, - "each unblessed aggregate validates its counted owner"); - assertEquals(0, stats.scalarReachabilityRootWalks, - "nested owner checks must use the drain snapshot"); - assertEquals(0, stats.rootQueries, - "the drain must not start a target-specific root walk"); - assertEquals(1, stats.snapshotsBuilt, - "all three aggregate checks share one full-root snapshot"); - assertTrue(stats.rootsSeeded > 0, - "the snapshot must seed package roots"); - assertTrue(stats.edgesInspected >= 256, - "the snapshot must account for the unrelated package-root edges"); - assertTrue(stats.nodesVisited >= 257, - "the snapshot must account for visiting the root and its children"); - for (RuntimeHash target : targets) { - assertEquals(1, target.refCount, - "a strong package-root owner preserves its weakly observed target"); - } - } - } finally { - GlobalVariable.globalArrays.remove(globalName); - MortalList.invalidateAllRootSnapshots(); - } - } - } - - @Test - void repeatedOwnerScalarChecksShareOneRootSnapshotPerDrain() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray global = new RuntimeArray(); - String globalName = - "UnblessedAggregateReachabilitySnapshotTest::scalarOwners"; - GlobalVariable.globalArrays.put(globalName, global); - RuntimeHash target = new RuntimeHash(); - target.activateOwnerTracking(); - RuntimeScalar[] owners = new RuntimeScalar[3]; - RuntimeScalar weak = null; - try { - for (int i = 0; i < 256; i++) { - global.elements.add(new RuntimeHash().createReference()); - } - for (int i = 0; i < owners.length; i++) { - RuntimeScalar owner = target.createAnonymousReference(); - RuntimeScalar.incrementRefCountForContainerStore(owner); - global.elements.add(owner); - // Exercise the graph fallback instead of the direct - // package-array/container-owner shortcut. - owner.containerOwner = null; - owners[i] = owner; - } - weak = target.createAnonymousReference(); - WeakRefRegistry.weaken(weak); - - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - for (int i = 0; i < owners.length; i++) { - MortalList.deferDecrement(target); - } - MortalList.flush(); - - ReachabilityQueryStats stats = measurement.stats(); - assertEquals(3, stats.scalarReachabilityQueries, - "all active owner scalars are checked at the zero transition"); - assertEquals(1, stats.scalarReachabilityRootWalks, - "the package/live root graph is traversed once per drain"); - assertEquals(1, stats.snapshotsBuilt, - "subsequent owner checks reuse the same identity snapshot"); - assertTrue(stats.rootsSeeded > 0); - assertTrue(stats.edgesInspected >= 259); - assertTrue(stats.nodesVisited >= 260); - assertEquals(3, target.refCount, - "all three package-rooted owners restore the referent count"); - } - } finally { - if (weak != null) WeakRefRegistry.unweaken(weak); - GlobalVariable.globalArrays.remove(globalName); - MortalList.invalidateAllRootSnapshots(); - } - } - } -} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/UnblessedScalarCellOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/UnblessedScalarCellOwnerSlotTest.java new file mode 100644 index 0000000000..b6839ea769 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/UnblessedScalarCellOwnerSlotTest.java @@ -0,0 +1,180 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class UnblessedScalarCellOwnerSlotTest { + @Test + void unattachedScalarWrapperDoesNotCountAsCurrentPerlCellOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + RuntimeScalar unrootedOwner = new RuntimeScalar(); + unrootedOwner.set(target.createAnonymousReference()); + try { + assertFalse(unrootedOwner.isCurrentCountedScalarOwner( + target, unrootedOwner.countedOwnerSlot()), + "a Java-reachable wrapper without Perl storage is not a current owner"); + } finally { + unrootedOwner.set(new RuntimeScalar()); + } + } + } + + @Test + void captureCountWithoutLiveCodeOwnerDoesNotKeepScalarCellCurrent() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash target = new RuntimeHash(); + RuntimeScalar capturedOwner = new RuntimeScalar(); + capturedOwner.set(target.createAnonymousReference()); + capturedOwner.createReference(); + RuntimeCode closure = new RuntimeCode((args, context) -> new RuntimeList(), null); + closure.capturedScalars = new RuntimeScalar[]{capturedOwner}; + closure.capturedScalarOwnerSlots = new PerlOwnerSlot[]{ + capturedOwner.retainClosureCaptureSlot(closure) + }; + try { + assertFalse(closure.hasPerlOwnerForCapture()); + assertFalse(capturedOwner.isCurrentCountedScalarOwner( + target, capturedOwner.countedOwnerSlot()), + "capture metadata alone does not prove a live closure owner"); + } finally { + closure.releaseCaptures(); + capturedOwner.set(new RuntimeScalar()); + } + } + } + + @Test + void codeSlotCountsAsCurrentScalarBackedOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar codeOwner = new RuntimeScalar(code); + codeOwner.retainCodeSlotBinding(); + try { + assertEquals(PerlOwnerSlot.Kind.CODE_SLOT, codeOwner.countedOwnerSlot().kind()); + assertTrue(codeOwner.isCurrentCountedScalarOwner(code, + codeOwner.countedOwnerSlot())); + } finally { + codeOwner.releaseCodeSlotBinding(); + } + } + } + + @Test + void scalarOverwriteBalancesTheSurvivingScalarCell() { + exerciseScalarCellRelease(false); + } + + @Test + void deferredReleaseBalancesTheSurvivingScalarCell() { + exerciseScalarCellRelease(true); + } + + @Test + void scalarAndAggregateOwnersReleaseIndependently() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + MortalList.setActive(true); + RuntimeHash target = new RuntimeHash(); + RuntimeScalar firstOwner = new RuntimeScalar(); + RuntimeScalar survivingScalarOwner = new RuntimeScalar(); + RuntimeArray aggregateOwner = new RuntimeArray(); + RuntimeScalar weakObserver = target.createAnonymousReference(); + int mark = MyVarCleanupStack.pushMark(); + try { + MyVarCleanupStack.register(firstOwner); + MyVarCleanupStack.register(survivingScalarOwner); + firstOwner.set(target.createAnonymousReference()); + survivingScalarOwner.set(target.createAnonymousReference()); + aggregateOwner.push(target.createAnonymousReference()); + WeakRefRegistry.weaken(weakObserver); + + assertEquals(3, target.refCount); + { + firstOwner.set(new RuntimeScalar()); + + assertEquals(2, target.refCount); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + } + + survivingScalarOwner.set(new RuntimeScalar()); + RuntimeArray.pop(aggregateOwner); + MortalList.flush(); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the last scalar and aggregate owners clear the weak observer"); + } finally { + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + firstOwner.set(new RuntimeScalar()); + survivingScalarOwner.set(new RuntimeScalar()); + while (!aggregateOwner.elements.isEmpty()) RuntimeArray.pop(aggregateOwner); + MortalList.flush(); + MyVarCleanupStack.unregister(firstOwner); + MyVarCleanupStack.unregister(survivingScalarOwner); + MyVarCleanupStack.popMark(mark); + MortalList.setActive(previousMortalListState); + } + } + } + + private void exerciseScalarCellRelease(boolean deferRelease) { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + MortalList.setActive(true); + RuntimeHash target = new RuntimeHash(); + RuntimeScalar firstOwner = new RuntimeScalar(); + RuntimeScalar survivingOwner = new RuntimeScalar(); + RuntimeScalar weakObserver = target.createAnonymousReference(); + int mark = MyVarCleanupStack.pushMark(); + try { + MyVarCleanupStack.register(firstOwner); + MyVarCleanupStack.register(survivingOwner); + firstOwner.set(target.createAnonymousReference()); + survivingOwner.set(target.createAnonymousReference()); + WeakRefRegistry.weaken(weakObserver); + + assertEquals(2, target.refCount); + assertEquals(2, target.ownerSlotCount(PerlOwnerSlot.Kind.SCALAR_CELL)); + + { + if (deferRelease) { + MortalList.pushMark(); + MortalList.deferDecrementIfTracked(firstOwner); + MortalList.popAndFlush(); + } else { + firstOwner.set(new RuntimeScalar()); + } + + assertEquals(1, target.refCount); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + } + + firstOwner.set(new RuntimeScalar()); + survivingOwner.set(new RuntimeScalar()); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the final scalar-cell owner release clears the weak observer"); + } finally { + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + firstOwner.set(new RuntimeScalar()); + survivingOwner.set(new RuntimeScalar()); + MyVarCleanupStack.unregister(firstOwner); + MyVarCleanupStack.unregister(survivingOwner); + MyVarCleanupStack.popMark(mark); + MortalList.setActive(previousMortalListState); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/UncountedOwnerSlotZeroCountReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/UncountedOwnerSlotZeroCountReleaseTest.java new file mode 100644 index 0000000000..2fc6882a1d --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/UncountedOwnerSlotZeroCountReleaseTest.java @@ -0,0 +1,175 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@Tag("unit") +class UncountedOwnerSlotZeroCountReleaseTest { + @Test + void scalarOverwriteDefersFinalCleanupUntilUncountedOwnerLeaves() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + Fixture fixture = fixture(); + assertFinalOwnerRelease(fixture, + () -> fixture.countedOwner.set(new RuntimeScalar())); + } + } + + @Test + void deferredDecrementDefersFinalCleanupUntilUncountedOwnerLeaves() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + Fixture fixture = fixture(); + assertFinalOwnerRelease(fixture, () -> { + MortalList.deferDecrementIfTracked(fixture.countedOwner); + MortalList.flushAboveMark(); + }); + } + } + + @Test + void tailCallReleaseDefersFinalCleanupUntilUncountedOwnerLeaves() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + Fixture fixture = fixture(); + RuntimeArray tailArguments = new RuntimeArray(1); + tailArguments.elements.add(fixture.countedOwner); + tailArguments.elementsOwned = true; + assertFinalOwnerRelease(fixture, + () -> MortalList.releaseTailCallArgs(tailArguments)); + } + } + + @Test + void finalRawOwnerSlotReleaseFinishesDeferredDestruction() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + String className = "UncountedOwnerSlotZeroCountReleaseTest::RawTarget"; + String destroyFqn = className + "::DESTROY"; + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId(className); + target.markRefCountUntracked(); + + AtomicInteger destroyCalls = new AtomicInteger(); + RuntimeCode destroy = new RuntimeCode((args, context) -> { + destroyCalls.incrementAndGet(); + return new RuntimeList(); + }, null); + destroy.packageName = "UncountedOwnerSlotZeroCountReleaseTest"; + destroy.subName = "DESTROY"; + GlobalVariable.getGlobalCodeRef(destroyFqn).set(new RuntimeScalar(destroy)); + DestroyDispatch.registerIfDestroyable(target, target.blessId); + + RuntimeScalar countedOwner = new RuntimeScalar(); + countedOwner.set(target.createAnonymousReference()); + target.setTrackedRefCount(1); + PerlOwnerSlot rawOwner = new PerlOwnerSlot(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE); + rawOwner.acquireUntrackedIdentity(target); + try { + target.deferFinalReleaseToUncountedOwnerSlots(); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState()); + + target.releaseActiveOwner(countedOwner); + countedOwner.refCountOwned = false; + assertEquals(0, destroyCalls.get(), + "the remaining raw owner slot keeps the referent alive"); + + rawOwner.release(); + + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, target.perlLifecycleState()); + assertEquals(0, target.refCount); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + target.perlLifecycleState()); + assertEquals(1, destroyCalls.get(), + "the last owner identity dispatches destruction exactly once"); + } finally { + if (rawOwner.isActive()) rawOwner.release(); + if (countedOwner.countedOwnerSlot() != null + && countedOwner.countedOwnerSlot().isActive()) { + target.releaseActiveOwner(countedOwner); + } + GlobalVariable.globalCodeRefs.remove(destroyFqn); + DestroyDispatch.unregisterDestroyable(target); + } + } + } + + private static Fixture fixture() { + String className = "UncountedOwnerSlotZeroCountReleaseTest::Target"; + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId(className); + target.markRefCountUntracked(); + + AtomicInteger destroyCalls = new AtomicInteger(); + RuntimeCode destroy = new RuntimeCode((args, context) -> { + destroyCalls.incrementAndGet(); + return new RuntimeList(); + }, null); + destroy.packageName = "UncountedOwnerSlotZeroCountReleaseTest"; + destroy.subName = "DESTROY"; + String destroyFqn = className + "::DESTROY"; + GlobalVariable.getGlobalCodeRef(destroyFqn).set(new RuntimeScalar(destroy)); + + RuntimeArray ownerContainer = new RuntimeArray(); + RuntimeScalar uncountedOwner = referenceTo(target); + ownerContainer.elements.add(uncountedOwner); + PerlOwnerSlot ownerSlot = uncountedOwner.untrackedReferenceOwnerSlot(); + assertNotNull(ownerSlot); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + RuntimeScalar countedOwner = new RuntimeScalar(); + countedOwner.set(target.createAnonymousReference()); + assertEquals(1, target.countedOwnerSlotCount()); + target.setTrackedRefCount(1); // Model a transient legacy-count undercount. + assertFalse(WeakRefRegistry.hasWeakRefsTo(target)); + return new Fixture(target, ownerContainer, uncountedOwner, ownerSlot, countedOwner, + destroyCalls, destroyFqn); + } + + private static void assertFinalOwnerRelease(Fixture fixture, Runnable countedRelease) { + try { + { + countedRelease.run(); + + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, fixture.target.refCountTrackingState()); + assertEquals(RuntimeBase.PerlLifecycleState.LIVE, + fixture.target.perlLifecycleState()); + assertEquals(1, + fixture.target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + } + + fixture.uncountedOwner.set(new RuntimeScalar()); + + assertFalse(fixture.ownerSlot.isActive()); + assertEquals(0, + fixture.target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, fixture.target.perlLifecycleState()); + assertEquals(0, fixture.target.refCount); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + fixture.target.perlLifecycleState()); + assertEquals(1, fixture.destroyCalls.get(), + "the final uncounted owner invokes DESTROY exactly once"); + } finally { + if (fixture.ownerSlot.isActive()) { + fixture.uncountedOwner.set(new RuntimeScalar()); + } + fixture.countedOwner.set(new RuntimeScalar()); + GlobalVariable.globalCodeRefs.remove(fixture.destroyFqn); + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.REFERENCE; + scalar.value = referent; + return scalar; + } + + private record Fixture(RuntimeHash target, RuntimeArray ownerContainer, + RuntimeScalar uncountedOwner, PerlOwnerSlot ownerSlot, + RuntimeScalar countedOwner, AtomicInteger destroyCalls, + String destroyFqn) { + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/UnownedTemporaryArrayAggregateOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/UnownedTemporaryArrayAggregateOwnerTest.java new file mode 100644 index 0000000000..59d3c745b5 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/UnownedTemporaryArrayAggregateOwnerTest.java @@ -0,0 +1,118 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class UnownedTemporaryArrayAggregateOwnerTest { + private static final int TEMPORARY_RESULT_COUNT = 60; + + @Test + void countedElementInUnownedTemporaryArrayIsNotACurrentPerlOwner() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeHash referent = new RuntimeHash(); + RuntimeArray temporary = new RuntimeArray(); + temporary.localBindingExists = true; + + RuntimeScalar owner = referent.createAnonymousReference(); + RuntimeScalar.incrementRefCountForContainerStore( + owner, PerlOwnerSlot.Kind.ARRAY_ELEMENT); + temporary.elements.add(owner); + assertTrue(referent.hasCurrentPerlOwnerSlotIdentity(), + "a stored element in a live array is a current Perl owner"); + + owner.localBindingExists = false; + temporary.localBindingExists = false; + assertFalse(temporary.hasPerlStrongOwner()); + assertFalse(referent.hasCurrentPerlOwnerSlotIdentity(), + "an element in an unowned temporary array is not a Perl owner"); + } + } + + @Test + void temporaryRootLeaseDefersAndThenFinishesUntrackedArrayCleanup() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + MortalList.setActive(true); + RuntimeArray temporary = new RuntimeArray(TEMPORARY_RESULT_COUNT); + RuntimeHash[] referents = new RuntimeHash[TEMPORARY_RESULT_COUNT]; + RuntimeScalar[] weakObservers = new RuntimeScalar[TEMPORARY_RESULT_COUNT]; + boolean temporaryRootPushed = false; + try { + // This array models a lexical result list whose scope ends + // while an expression still has a temporary-root lease on + // the array. Java keeps the array reachable throughout. + temporary.localBindingExists = true; + + for (int i = 0; i < TEMPORARY_RESULT_COUNT; i++) { + RuntimeHash referent = new RuntimeHash(); + referents[i] = referent; + temporary.elements.add(untrackedReferenceTo(referent)); + RuntimeScalar weakObserver = untrackedReferenceTo(referent); + weakObservers[i] = weakObserver; + WeakRefRegistry.weaken(weakObserver); + } + + MortalList.pushTemporaryRoot(temporary); + temporaryRootPushed = true; + MortalList.scopeExitCleanupArray(temporary); + + assertFalse(temporary.localBindingExists, + "scope exit removes the array's lexical owner"); + assertEquals(1, temporary.ownerSlotCount(PerlOwnerSlot.Kind.EXPRESSION_VALUE), + "the expression lease is a direct counted owner during cleanup"); + assertEquals(TEMPORARY_RESULT_COUNT, temporary.elements.size(), + "the Java-reachable array remains available during the lease"); + for (RuntimeHash referent : referents) { + assertEquals(1, referent.ownerSlotCount( + PerlOwnerSlot.Kind.UNTRACKED_REFERENCE), + "the temporary-root lease keeps each untracked cell alive"); + } + for (RuntimeScalar weakObserver : weakObservers) { + assertTrue(WeakRefRegistry.isweak(weakObserver), + "a live temporary-root lease preserves weak observers"); + assertEquals(RuntimeScalarType.HASHREFERENCE, weakObserver.type); + } + + MortalList.popTemporaryRoot(temporary); + temporaryRootPushed = false; + + assertEquals(0, temporary.ownerSlotCount(PerlOwnerSlot.Kind.EXPRESSION_VALUE), + "popping the expression root releases its counted owner"); + for (RuntimeHash referent : referents) { + assertEquals(0, referent.ownerSlotCount( + PerlOwnerSlot.Kind.UNTRACKED_REFERENCE), + "the final array transfer retires each untracked owner slot"); + } + for (RuntimeScalar weakObserver : weakObservers) { + assertFalse(WeakRefRegistry.isweak(weakObserver), + "retiring the final untracked owner clears its weak observer"); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + } + assertFalse(temporary.hasPerlStrongOwner(), + "a Java reference does not restore the array's Perl ownership"); + } finally { + if (temporaryRootPushed) MortalList.popTemporaryRoot(temporary); + MortalList.scopeExitCleanupArray(temporary); + for (int i = 0; i < referents.length; i++) { + if (referents[i] != null) { + WeakRefRegistry.clearWeakRefsTo(referents[i]); + } + } + MortalList.setActive(previousMortalListState); + } + } + } + + private static RuntimeScalar untrackedReferenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.HASHREFERENCE; + scalar.value = referent; + return scalar; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/UntrackedAggregateFirstWeakenFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/UntrackedAggregateFirstWeakenFastPathTest.java new file mode 100644 index 0000000000..97ba48bae0 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/UntrackedAggregateFirstWeakenFastPathTest.java @@ -0,0 +1,54 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class UntrackedAggregateFirstWeakenFastPathTest { + @Test + void temporaryAggregateKeepsSentinelUntilDurableSlotWithoutRootWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray target = new RuntimeArray(); + target.markRefCountUntracked(); + RuntimeScalar weakObserver = referenceTo(target); + String key = "UntrackedAggregateFirstWeakenFastPathTest::target"; + + try { + { + WeakRefRegistry.weaken(weakObserver); + + assertTrue(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState()); + } + + GlobalVariable.globalArrays.put(key, target); + assertEquals(1, + target.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + GlobalVariable.globalArrays.remove(key); + + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the durable package slot's final release clears the weak observer"); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, target.perlLifecycleState()); + assertEquals(0, target.refCount); + } finally { + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + GlobalVariable.globalArrays.remove(key); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.REFERENCE; + scalar.value = referent; + return scalar; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/UntrackedAggregateOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/UntrackedAggregateOwnerSlotTest.java new file mode 100644 index 0000000000..93a6ae0466 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/UntrackedAggregateOwnerSlotTest.java @@ -0,0 +1,206 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class UntrackedAggregateOwnerSlotTest { + @Test + void scalarCellsOwnUntrackedAggregateValuesAndReleaseEachIdentityOnce() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray target = new RuntimeArray(); + RuntimeScalar firstOwner = referenceTo(target); + RuntimeScalar secondOwner = referenceTo(target); + RuntimeScalar weakObserver = referenceTo(target); + int mark = MyVarCleanupStack.pushMark(); + try { + MyVarCleanupStack.register(firstOwner); + MyVarCleanupStack.register(secondOwner); + + PerlOwnerSlot firstSlot = firstOwner.untrackedReferenceOwnerSlot(); + PerlOwnerSlot secondSlot = secondOwner.untrackedReferenceOwnerSlot(); + assertNotNull(firstSlot); + assertNotNull(secondSlot); + assertNotSame(firstSlot, secondSlot, + "each durable scalar cell contributes its own owner identity"); + assertEquals(2, + target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, target.refCountTrackingState(), + "explicit owner slots must not promote the legacy count"); + + { + WeakRefRegistry.weaken(weakObserver); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState()); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + } + + firstOwner.set(new RuntimeScalar()); + assertFalse(firstSlot.isActive()); + assertTrue(secondSlot.isActive()); + assertEquals(1, + target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertTrue(WeakRefRegistry.isweak(weakObserver), + "one remaining scalar owner keeps the weak observer alive"); + assertNotEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + target.perlLifecycleState()); + + firstOwner.set(new RuntimeScalar()); + assertEquals(1, + target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE), + "replacing an already-cleared cell must not release another identity"); + + secondOwner.set(new RuntimeScalar()); + assertFalse(secondSlot.isActive()); + assertEquals(0, + target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the final owner release clears the weak observer immediately"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + target.perlLifecycleState(), + "the final owner release cascades aggregate cleanup"); + } finally { + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + RuntimeScalar.scopeExitCleanup(firstOwner); + RuntimeScalar.scopeExitCleanup(secondOwner); + MyVarCleanupStack.unregister(firstOwner); + MyVarCleanupStack.unregister(secondOwner); + MyVarCleanupStack.popMark(mark); + } + } + } + + @Test + void activeLexicalAggregateOwnerAvoidsTheFirstWeakRootWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeCode.pushActiveCode(code); + int mark = MyVarCleanupStack.pushMark(); + RuntimeArray target = new RuntimeArray(); + RuntimeScalar weakObserver = referenceTo(target); + try { + MyVarCleanupStack.register(target); + RuntimeCode.registerCurrentActiveLexical("@aggregate", target); + assertEquals(1, + target.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + + { + WeakRefRegistry.weaken(weakObserver); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + } + + MortalList.scopeExitCleanupArray(target); + MyVarCleanupStack.unregister(target); + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertEquals(0, + target.ownerSlotCount(PerlOwnerSlot.Kind.ACTIVE_LEXICAL)); + } finally { + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + MyVarCleanupStack.unregister(target); + MyVarCleanupStack.popMark(mark); + RuntimeCode.popActiveCode(code); + } + } + } + + @Test + void packageAggregateOwnerAvoidsTheFirstWeakRootWalkAndFinalizesOnRemoval() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray target = new RuntimeArray(); + RuntimeScalar weakObserver = referenceTo(target); + String globalName = "UntrackedAggregateOwnerSlotTest::package_root"; + + try { + GlobalVariable.globalArrays.put(globalName, target); + assertEquals(1, + target.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + + { + WeakRefRegistry.weaken(weakObserver); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + } + + GlobalVariable.globalArrays.remove(globalName); + assertEquals(0, + target.ownerSlotCount(PerlOwnerSlot.Kind.PACKAGE_AGGREGATE_SLOT)); + assertFalse(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + target.perlLifecycleState()); + } finally { + GlobalVariable.globalArrays.remove(globalName); + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + } + } + } + + @Test + void finalUntrackedBlessedAggregateOwnerRunsDestroyBeforeClearingWeakObserver() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + String className = "UntrackedAggregateOwnerSlotTest::BlessedArray"; + RuntimeHash target = new RuntimeHash(); + target.blessId = NameNormalizer.getBlessId(className); + RuntimeScalar owner = referenceTo(target); + RuntimeScalar weakObserver = referenceTo(target); + AtomicInteger destroyCalls = new AtomicInteger(); + AtomicBoolean weakDuringDestroy = new AtomicBoolean(); + int mark = MyVarCleanupStack.pushMark(); + RuntimeCode destroy = new RuntimeCode((args, context) -> { + destroyCalls.incrementAndGet(); + weakDuringDestroy.set(WeakRefRegistry.isweak(weakObserver)); + return new RuntimeList(); + }, null); + destroy.packageName = "UntrackedAggregateOwnerSlotTest"; + destroy.subName = "DESTROY"; + GlobalVariable.getGlobalCodeRef(className + "::DESTROY") + .set(new RuntimeScalar(destroy)); + + try { + MyVarCleanupStack.register(owner); + assertEquals(1, + target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + WeakRefRegistry.weaken(weakObserver); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + + owner.set(new RuntimeScalar()); + + assertEquals(1, destroyCalls.get()); + assertTrue(weakDuringDestroy.get(), + "Perl keeps weak observers valid while DESTROY runs"); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "weak observers clear after a non-resurrecting DESTROY"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + target.perlLifecycleState()); + } finally { + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + RuntimeScalar.scopeExitCleanup(owner); + MyVarCleanupStack.unregister(owner); + MyVarCleanupStack.popMark(mark); + GlobalVariable.removeGlobalCodeRefForStashDelete(className + "::DESTROY"); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar reference = new RuntimeScalar(); + reference.type = RuntimeScalarType.REFERENCE; + reference.value = referent; + return reference; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/UntrackedAggregateStorageReleaseTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/UntrackedAggregateStorageReleaseTest.java new file mode 100644 index 0000000000..0ce48651e5 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/UntrackedAggregateStorageReleaseTest.java @@ -0,0 +1,42 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Tag("unit") +class UntrackedAggregateStorageReleaseTest { + @Test + void retiringTheLastStorageOwnerReleasesDirectNestedOwnerSlots() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + RuntimeArray outer = new RuntimeArray(); + RuntimeHash inner = new RuntimeHash(); + RuntimeScalar innerOwner = new RuntimeScalar(); + innerOwner.type = RuntimeScalarType.HASHREFERENCE; + innerOwner.value = inner; + outer.elements.add(innerOwner); + innerOwner.markContainerOwner(outer); + innerOwner.refreshUntrackedReferenceOwner(); + + RuntimeHash storage = new RuntimeHash(); + RuntimeScalar outerOwner = new RuntimeScalar(); + outerOwner.type = RuntimeScalarType.ARRAYREFERENCE; + outerOwner.value = outer; + storage.elements.put("outer", outerOwner); + outerOwner.markContainerOwner(storage); + outerOwner.refreshUntrackedReferenceOwner(); + + assertEquals(1, + outer.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + storage.elements.clear(); + outerOwner.releaseContainerOwner(storage); + + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + outer.perlLifecycleState()); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + inner.perlLifecycleState(), + "the final parent storage edge releases its direct nested slot"); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/UntrackedReferenceOwnerReplacementOrderTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/UntrackedReferenceOwnerReplacementOrderTest.java new file mode 100644 index 0000000000..a282cf7ef1 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/UntrackedReferenceOwnerReplacementOrderTest.java @@ -0,0 +1,77 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +@Tag("unit") +class UntrackedReferenceOwnerReplacementOrderTest { + @Test + void replacementOwnerIsInstalledBeforePreviousOwnerIsReleased() { + try (PerlRuntime.Binding ignored = new PerlRuntime().bind()) { + List events = new ArrayList<>(); + RecordingReferent previous = new RecordingReferent("previous", events); + RecordingReferent replacement = new RecordingReferent("replacement", events); + RuntimeArray storage = new RuntimeArray(); + int mark = MyVarCleanupStack.pushMark(); + RuntimeScalar element = null; + try { + storage.addClonedElement(referenceTo(previous)); + element = storage.elements.get(0); + MyVarCleanupStack.register(element); + PerlOwnerSlot owner = element.untrackedReferenceOwnerSlot(); + assertNotNull(owner, + "registering the scalar makes its uncounted value edge durable"); + events.clear(); + + element.set(referenceTo(replacement)); + + assertEquals(List.of("replacement:add", "previous:remove"), events); + assertSame(owner, element.untrackedReferenceOwnerSlot()); + assertSame(replacement, owner.referent()); + } finally { + if (element != null) { + RuntimeScalar.scopeExitCleanup(element); + MyVarCleanupStack.unregister(element); + } + MortalList.scopeExitCleanupArray(storage); + MyVarCleanupStack.popMark(mark); + } + } + } + + private static final class RecordingReferent extends RuntimeScalar { + private final String name; + private final List events; + + private RecordingReferent(String name, List events) { + this.name = name; + this.events = events; + } + + @Override + synchronized void addOwnerSlot(PerlOwnerSlot slot) { + events.add(name + ":add"); + super.addOwnerSlot(slot); + } + + @Override + synchronized void removeOwnerSlot(PerlOwnerSlot slot) { + events.add(name + ":remove"); + super.removeOwnerSlot(slot); + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar reference = new RuntimeScalar(); + reference.type = RuntimeScalarType.REFERENCE; + reference.value = referent; + return reference; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/UntrackedReferenceOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/UntrackedReferenceOwnerSlotTest.java new file mode 100644 index 0000000000..7caaa3499e --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/UntrackedReferenceOwnerSlotTest.java @@ -0,0 +1,418 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class UntrackedReferenceOwnerSlotTest { + @Test + void untrackedElementOwnersReleaseAtAggregateScopeExitWithoutWeakRefs() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + RuntimeScalar arrayTarget = new RuntimeScalar("array target"); + RuntimeScalar arrayElement = referenceTo(arrayTarget); + RuntimeArray array = new RuntimeArray(); + array.addClonedElement(arrayElement); + PerlOwnerSlot arrayValueOwner = arrayElement.untrackedReferenceOwnerSlot(); + assertNotNull(arrayValueOwner); + + RuntimeScalar hashTarget = new RuntimeScalar("hash target"); + RuntimeScalar hashElement = referenceTo(hashTarget); + RuntimeHash hash = new RuntimeHash(); + hash.put("value", hashElement); + RuntimeScalar storedHashElement = hash.elements.get("value"); + PerlOwnerSlot hashValueOwner = storedHashElement.untrackedReferenceOwnerSlot(); + assertNotNull(hashValueOwner); + assertSame(hashTarget, hashValueOwner.referent()); + + { + MortalList.scopeExitCleanupArray(array); + MortalList.scopeExitCleanupHash(hash); + + assertFalse(arrayValueOwner.isActive()); + assertFalse(hashValueOwner.isActive()); + + MortalList.scopeExitCleanupArray(array); + MortalList.scopeExitCleanupHash(hash); + assertEquals(0, arrayTarget.ownerSlotCount( + PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertEquals(0, hashTarget.ownerSlotCount( + PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + } + } + } + + @Test + void aggregateCollectionHooksRefreshUntrackedOwnersAfterInsertion() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + RuntimeScalar arrayTarget = new RuntimeScalar("raw array target"); + RuntimeScalar arrayElement = referenceTo(arrayTarget); + RuntimeArray array = new RuntimeArray(); + array.elements.add(arrayElement); + + PerlOwnerSlot arrayValueOwner = arrayElement.untrackedReferenceOwnerSlot(); + assertNotNull(arrayValueOwner); + assertSame(arrayTarget, arrayValueOwner.referent()); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, arrayTarget.refCountTrackingState()); + + RuntimeScalar hashTarget = new RuntimeScalar("raw hash target"); + RuntimeScalar hashElement = referenceTo(hashTarget); + RuntimeHash hash = new RuntimeHash(); + hash.elements.put("value", hashElement); + + PerlOwnerSlot hashValueOwner = hashElement.untrackedReferenceOwnerSlot(); + assertNotNull(hashValueOwner); + assertSame(hashTarget, hashValueOwner.referent()); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, hashTarget.refCountTrackingState()); + + array.elements.remove(arrayElement); + hash.elements.remove("value"); + MortalList.deferDestroyForContainerClear( + java.util.List.of(arrayElement, hashElement)); + assertFalse(arrayValueOwner.isActive()); + assertFalse(hashValueOwner.isActive()); + } + } + + @Test + void arrayCopyConstructionRefreshesOwnersAfterInstallingItsElementList() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar target = new RuntimeScalar("copied array target"); + RuntimeScalar element = referenceTo(target); + + RuntimeArray copy = new RuntimeArray(java.util.List.of(element)); + + PerlOwnerSlot owner = element.untrackedReferenceOwnerSlot(); + assertNotNull(owner); + assertSame(target, owner.referent()); + assertTrue(copy.elements.contains(element)); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, target.refCountTrackingState()); + } + } + + @Test + void untrackedContainerReferentsGetSlotIdentityWithoutCountPromotion() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + RuntimeScalar firstTarget = new RuntimeScalar("first"); + RuntimeScalar secondTarget = new RuntimeScalar("second"); + RuntimeArray targetStorage = new RuntimeArray(); + targetStorage.addClonedElement(firstTarget); + targetStorage.addClonedElement(secondTarget); + RuntimeArray array = new RuntimeArray(); + array.addClonedElement(firstTarget.createReference()); + + RuntimeScalar element = array.elements.get(0); + PerlOwnerSlot owner = element.untrackedReferenceOwnerSlot(); + assertNotNull(owner); + assertEquals(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE, owner.kind()); + assertSame(firstTarget, owner.referent()); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, firstTarget.refCountTrackingState(), + "slot tracking must not promote an arbitrary referent into the legacy count"); + + element.set(secondTarget.createReference()); + assertSame(owner, element.untrackedReferenceOwnerSlot()); + assertSame(secondTarget, owner.referent()); + assertFalse(firstTarget.hasOwnerSlots()); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, secondTarget.refCountTrackingState()); + + array.elements.remove(element); + MortalList.deferDestroyForContainerClear(java.util.List.of(element)); + assertFalse(owner.isActive()); + assertFalse(secondTarget.hasOwnerSlots()); + + RuntimeScalar weaklyTrackedTarget = new RuntimeScalar("weakly tracked"); + targetStorage.addClonedElement(weaklyTrackedTarget); + RuntimeScalar weakObserver = weaklyTrackedTarget.createReference(); + WeakRefRegistry.weaken(weakObserver); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, weaklyTrackedTarget.refCountTrackingState()); + + RuntimeArray weaklyTrackedArray = new RuntimeArray(); + weaklyTrackedArray.addClonedElement(weaklyTrackedTarget.createReference()); + RuntimeScalar weaklyTrackedElement = weaklyTrackedArray.elements.get(0); + PerlOwnerSlot weaklyTrackedOwner = weaklyTrackedElement.untrackedReferenceOwnerSlot(); + assertNotNull(weaklyTrackedOwner); + assertSame(weaklyTrackedTarget, weaklyTrackedOwner.referent()); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, weaklyTrackedTarget.refCountTrackingState(), + "a later strong store must not promote weak-tracked state"); + + WeakRefRegistry.unweaken(weakObserver); + weaklyTrackedArray.elements.remove(weaklyTrackedElement); + MortalList.deferDestroyForContainerClear(java.util.List.of(weaklyTrackedElement)); + assertFalse(weaklyTrackedOwner.isActive()); + } + } + + @Test + void untrackedLexicalValueSlotSurvivesCaptureAndReleasesAtFinalOwnerExit() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar target = new RuntimeScalar("weakly tracked target"); + RuntimeScalar weakObserver = new RuntimeScalar(); + weakObserver.type = RuntimeScalarType.REFERENCE; + weakObserver.value = target; + WeakRefRegistry.weaken(weakObserver); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState()); + + RuntimeScalar lexical = new RuntimeScalar(); + int mark = MyVarCleanupStack.pushMark(); + MyVarCleanupStack.register(lexical); + + RuntimeScalar untrackedTarget = new RuntimeScalar("untracked lexical target"); + RuntimeScalar untrackedReference = new RuntimeScalar(); + untrackedReference.type = RuntimeScalarType.REFERENCE; + untrackedReference.value = untrackedTarget; + lexical.set(untrackedReference); + PerlOwnerSlot valueSlot = lexical.untrackedReferenceOwnerSlot(); + assertNotNull(valueSlot); + assertSame(untrackedTarget, valueSlot.referent()); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, untrackedTarget.refCountTrackingState()); + + RuntimeScalar targetReference = new RuntimeScalar(); + targetReference.type = RuntimeScalarType.REFERENCE; + targetReference.value = target; + lexical.set(targetReference); + assertSame(valueSlot, lexical.untrackedReferenceOwnerSlot()); + assertFalse(untrackedTarget.hasOwnerSlots()); + assertSame(target, valueSlot.referent()); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState(), + "a lexical owner slot must not promote weak-tracked state"); + + PerlOwnerSlot capture = lexical.retainClosureCaptureSlot(); + RuntimeScalar.scopeExitCleanup(lexical); + MyVarCleanupStack.unregister(lexical); + assertTrue(valueSlot.isActive(), "the closure must keep the lexical value slot alive"); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + lexical.releaseClosureCaptureSlot(capture); + assertFalse(valueSlot.isActive(), "the final cell owner must retire the value slot"); + assertFalse(target.hasOwnerSlots()); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState()); + MyVarCleanupStack.popMark(mark); + } + } + + @Test + void packageScalarAliasesOwnDistinctUntrackedReferenceSlotsUntilEachKeyLeaves() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar target = new RuntimeScalar("package-rooted referent"); + RuntimeScalar packageCell = new RuntimeScalar(); + packageCell.type = RuntimeScalarType.REFERENCE; + packageCell.value = target; + String firstName = "RuntimeScalarOwnerSlotTest::rooted_one"; + String secondName = "RuntimeScalarOwnerSlotTest::rooted_two"; + RuntimeScalar observer = new RuntimeScalar(); + observer.type = RuntimeScalarType.REFERENCE; + observer.value = target; + + try { + GlobalVariable.globalVariables.put(firstName, packageCell); + PerlOwnerSlot valueOwner = packageCell.untrackedReferenceOwnerSlot(); + assertNotNull(valueOwner, + "a package scalar cell owns its untracked reference value"); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, target.refCountTrackingState(), + "package ownership must not promote an untracked referent"); + assertEquals(1, packageCell.ownerSlotCount( + PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT)); + + GlobalVariable.globalVariables.put(secondName, packageCell); + assertEquals(2, packageCell.ownerSlotCount( + PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT), + "each package key has an independent scalar-cell owner identity"); + + { + WeakRefRegistry.weaken(observer); + } + assertEquals(1, target.ownerSlotCount( + PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + + GlobalVariable.globalVariables.keySet().remove(firstName); + assertTrue(valueOwner.isActive(), + "removing one alias keeps the scalar's value owner alive"); + assertEquals(1, packageCell.ownerSlotCount( + PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT)); + + GlobalVariable.globalVariables.remove(secondName); + assertFalse(valueOwner.isActive(), + "the final package key releases the untracked value edge"); + assertEquals(0, packageCell.ownerSlotCount( + PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT)); + assertEquals(0, target.ownerSlotCount( + PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + } finally { + GlobalVariable.globalVariables.remove(firstName); + GlobalVariable.globalVariables.remove(secondName); + if (WeakRefRegistry.isweak(observer)) WeakRefRegistry.unweaken(observer); + } + } + } + + @Test + void clonedPackageScalarTableRebuildsOwnerIdentities() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar target = new RuntimeScalar("thread snapshot referent"); + RuntimeScalar packageCell = new RuntimeScalar(); + packageCell.type = RuntimeScalarType.REFERENCE; + packageCell.value = target; + runtime.globalState.scalarValues().put( + "RuntimeScalarOwnerSlotTest::snapshot_root", packageCell); + + runtime.globalState.rebuildPackageScalarOwnerSlots(); + + assertEquals(1, packageCell.ownerSlotCount( + PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT)); + assertEquals(1, target.ownerSlotCount( + PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, target.refCountTrackingState(), + "reconstructing a package root must not promote its untracked value"); + } + } + + @Test + void packageScalarSlotTracksItsCellWithoutChangingTheValueCount() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar packageCell = new RuntimeScalar("value"); + packageCell.setTrackedRefCount(0); + String key = "RuntimeScalarOwnerSlotTest::retired_cell"; + + try { + GlobalVariable.globalVariables.put(key, packageCell); + + assertEquals(0, packageCell.refCount, + "the package slot identifies the cell but does not own its value"); + assertEquals(1, packageCell.ownerSlotCount( + PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT)); + + GlobalVariable.globalVariables.remove(key); + assertEquals(0, packageCell.refCount); + assertEquals(0, packageCell.ownerSlotCount( + PerlOwnerSlot.Kind.PACKAGE_SCALAR_SLOT)); + } finally { + GlobalVariable.globalVariables.remove(key); + } + } + } + + @Test + void tiedHandlerOwnerTracksAndReleasesAnUntrackedValue() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar target = new RuntimeScalar("tied handler target"); + RuntimeScalar handlerReference = new RuntimeScalar(); + handlerReference.type = RuntimeScalarType.REFERENCE; + handlerReference.value = target; + RuntimeScalar handlerOwner = RuntimeScalar.retainTiedHandlerValue(handlerReference); + PerlOwnerSlot valueOwner = handlerOwner.untrackedReferenceOwnerSlot(); + RuntimeScalar observer = new RuntimeScalar(); + observer.type = RuntimeScalarType.REFERENCE; + observer.value = target; + + assertNotNull(valueOwner); + assertSame(target, valueOwner.referent()); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, target.refCountTrackingState(), + "the tie handler slot must not promote the legacy referent count"); + + try { + { + WeakRefRegistry.weaken(observer); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState()); + } + + RuntimeScalar.releaseTiedHandlerValue(handlerOwner); + assertFalse(valueOwner.isActive()); + assertEquals(0, target.ownerSlotCount( + PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + RuntimeScalar.releaseTiedHandlerValue(handlerOwner); + assertEquals(0, target.ownerSlotCount( + PerlOwnerSlot.Kind.UNTRACKED_REFERENCE), + "repeated release must not retire another owner's identity"); + } finally { + if (WeakRefRegistry.isweak(observer)) WeakRefRegistry.unweaken(observer); + } + } + } + + @Test + void stagedArgumentOwnerTracksAndReleasesAnUntrackedValue() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar target = new RuntimeScalar("staged argument target"); + RuntimeScalar reference = new RuntimeScalar(); + reference.type = RuntimeScalarType.REFERENCE; + reference.value = target; + RuntimeScalar stagedOwner = RuntimeScalar.retainStagedArgumentValue(reference); + PerlOwnerSlot valueOwner = stagedOwner.untrackedReferenceOwnerSlot(); + + assertNotNull(valueOwner); + assertSame(target, valueOwner.referent()); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, target.refCountTrackingState(), + "the staged owner must not promote the legacy referent count"); + + RuntimeScalar.releaseStagedArgumentValue(stagedOwner); + assertFalse(valueOwner.isActive()); + assertEquals(0, target.ownerSlotCount( + PerlOwnerSlot.Kind.UNTRACKED_REFERENCE)); + RuntimeScalar.releaseStagedArgumentValue(stagedOwner); + assertEquals(0, target.ownerSlotCount( + PerlOwnerSlot.Kind.UNTRACKED_REFERENCE), + "repeated release must be idempotent"); + } + } + + @Test + void explicitUntrackedValueOwnerClearsWeakObserverOnRelease() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeScalar target = new RuntimeScalar("untracked referent"); + RuntimeScalar owner = new RuntimeScalar(); + int mark = MyVarCleanupStack.pushMark(); + MyVarCleanupStack.register(owner); + RuntimeScalar untrackedReference = new RuntimeScalar(); + untrackedReference.type = RuntimeScalarType.REFERENCE; + untrackedReference.value = target; + owner.set(untrackedReference); + PerlOwnerSlot ownerSlot = owner.untrackedReferenceOwnerSlot(); + assertNotNull(ownerSlot); + assertEquals(PerlOwnerSlot.Kind.UNTRACKED_REFERENCE, ownerSlot.kind()); + assertSame(target, ownerSlot.referent()); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, target.refCountTrackingState(), + "the durable slot identity must not promote the compatibility count"); + + RuntimeScalar observer = new RuntimeScalar(); + observer.type = RuntimeScalarType.REFERENCE; + observer.value = target; + try { + WeakRefRegistry.weaken(observer); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState()); + assertTrue(WeakRefRegistry.isweak(observer)); + + owner.set(new RuntimeScalar()); + assertFalse(ownerSlot.isActive()); + assertFalse(WeakRefRegistry.isweak(observer)); + assertEquals(RuntimeScalarType.UNDEF, observer.type); + } finally { + if (WeakRefRegistry.isweak(observer)) WeakRefRegistry.unweaken(observer); + MyVarCleanupStack.unregister(owner); + MyVarCleanupStack.popMark(mark); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar reference = new RuntimeScalar(); + reference.type = RuntimeScalarType.REFERENCE; + reference.value = referent; + return reference; + } + +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/VoidDiscardZeroCountLifecycleTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/VoidDiscardZeroCountLifecycleTest.java new file mode 100644 index 0000000000..6c9886096c --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/VoidDiscardZeroCountLifecycleTest.java @@ -0,0 +1,44 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@Tag("unit") +class VoidDiscardZeroCountLifecycleTest { + @Test + void zeroCountTemporaryQueuesLifecycleWithoutPositiveCountBridge() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray target = new RuntimeArray(); + RuntimeScalar discarded = target.createAnonymousReference(); + RuntimeList result = new RuntimeList(); + result.elements.add(discarded); + + MortalList.pushMark(); + try { + MortalList.mortalizeForVoidDiscard(result); + + assertEquals(0, target.refCount, + "queuing a zero-count temporary must not fabricate an owner count"); + assertEquals(1, runtime.lifecycleState.pending.size()); + assertNotNull(runtime.lifecycleState.pendingOwnerReleases.get(0), + "the deferred lifecycle boundary has an explicit completion token"); + + MortalList.popAndFlush(); + + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, target.perlLifecycleState()); + assertEquals(0, target.refCount); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + target.perlLifecycleState()); + assertFalse(target.hasPendingOwnerRelease(), + "the lifecycle completion token retires exactly once"); + } finally { + if (runtime.lifecycleState.hasMortalMarks()) MortalList.popAndFlush(); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/WatcherCleanupDoesNotTraverseLiveAggregateTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/WatcherCleanupDoesNotTraverseLiveAggregateTest.java new file mode 100644 index 0000000000..9a5fa80ab6 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/WatcherCleanupDoesNotTraverseLiveAggregateTest.java @@ -0,0 +1,59 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.AbstractMap; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Tag("unit") +class WatcherCleanupDoesNotTraverseLiveAggregateTest { + private static final class CountingStashMap extends AbstractMap { + private int valuesCalls; + + @Override + public Set> entrySet() { + return Collections.emptySet(); + } + + @Override + public Collection values() { + valuesCalls++; + return Collections.emptyList(); + } + } + + @Test + void scopeCleanupDoesNotTraverseReferencedStashWhenWatchersExistElsewhere() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + AtomicInteger callbackCalls = new AtomicInteger(); + RuntimeCode callback = new RuntimeCode((args, context) -> { + callbackCalls.incrementAndGet(); + return new RuntimeList(); + }, null); + + RuntimeStash stash = new RuntimeStash("WatcherCleanupDoesNotTraverseLiveAggregateTest::"); + CountingStashMap stashView = new CountingStashMap(); + stash.elements = stashView; + ((RuntimeHash) stash).elements = stashView; + + RuntimeArray container = new RuntimeArray(); + RuntimeScalar stashReference = stash.createReference(); + stashReference.addDestroyedWatcher(1, new RuntimeScalar(callback)); + container.addClonedElement(stashReference); + MortalList.scopeExitCleanupArray(container); + + assertEquals(0, stashView.valuesCalls, + "destroying a reference container must not traverse a still-live stash"); + assertEquals(1, callbackCalls.get(), + "the destroyed watcher on the released direct slot still runs"); + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/WeakArgumentAliasUndefOwnerTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakArgumentAliasUndefOwnerTest.java new file mode 100644 index 0000000000..731ac4d0a8 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakArgumentAliasUndefOwnerTest.java @@ -0,0 +1,61 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class WeakArgumentAliasUndefOwnerTest { + @Test + void undefersWeaklyTrackedCleanupToTheCurrentArgumentAlias() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + RuntimeArray target = new RuntimeArray(); + target.markRefCountWeaklyTracked(); + RuntimeScalar source = referenceTo(target); + RuntimeScalar weakObserver = referenceTo(target); + MyVarCleanupStack.register(source); + WeakRefRegistry.weaken(weakObserver); + PerlOwnerSlot argumentAlias = new PerlOwnerSlot( + PerlOwnerSlot.Kind.ARGUMENT_ALIAS); + argumentAlias.acquireArgumentAliasIdentity(target); + + try { + source.undefine(); + + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState(), + "the alias identity defers cleanup without a synthetic count"); + assertTrue(target.deferredFinalReleaseForUncountedOwners); + assertTrue(argumentAlias.isActive()); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + + argumentAlias.release(); + + assertFalse(argumentAlias.isActive()); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the final alias release clears the weak observer"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, target.perlLifecycleState()); + assertEquals(0, target.refCount); + } finally { + argumentAlias.release(); + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + RuntimeScalar.scopeExitCleanup(source); + MyVarCleanupStack.unregister(source); + MortalList.flush(); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.REFERENCE; + scalar.value = referent; + return scalar; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/WeakBackrefCodeCaptureSweepTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakBackrefCodeCaptureSweepTest.java deleted file mode 100644 index d44ced5963..0000000000 --- a/src/test/java/org/perlonjava/runtime/runtimetypes/WeakBackrefCodeCaptureSweepTest.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.perlonjava.runtime.runtimetypes; - -import java.util.List; - -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Tag("unit") -class WeakBackrefCodeCaptureSweepTest { - @Test - void quietSweepSharesWeakCodeCaptureWalkAcrossAggregateTargets() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeArray capturedParent = new RuntimeArray(); - RuntimeArray[] targets = new RuntimeArray[12]; - RuntimeScalar[] weakTargets = new RuntimeScalar[targets.length]; - for (int i = 0; i < targets.length; i++) { - RuntimeArray target = new RuntimeArray(); - capturedParent.elements.add(target.createAnonymousReference()); - targets[i] = target; - weakTargets[i] = target.createAnonymousReference(); - WeakRefRegistry.weaken(weakTargets[i]); - } - - RuntimeCode code = new RuntimeCode(null, List.of()); - code.capturedAggregates = new RuntimeBase[] {capturedParent}; - code.captureFieldsRecorded = true; - RuntimeScalar weakCode = new RuntimeScalar(code); - WeakRefRegistry.weaken(weakCode); - - runtime.lifecycleState.sweepPendingAfterOuterDestroy = true; - try { - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - // Drive the same quiet sweep through the lifecycle flush - // used after an outer DESTROY, without depending on cadence. - MortalList.requestImmediateWeakSweep(); - MortalList.flush(); - - ReachabilityQueryStats stats = measurement.stats(); - assertEquals(1, stats.weakBackrefCaptureRootsWalked, - "one weak CODE capture graph should be walked for the whole sweep"); - assertTrue(stats.weakBackrefCaptureNodesVisited >= targets.length, - "the shared walk should visit every captured aggregate"); - assertTrue(stats.weakBackrefCaptureEdgesInspected >= targets.length, - "the shared walk should inspect every captured aggregate edge"); - assertEquals(1, stats.weakBackrefCaptureSnapshotsBuilt); - for (RuntimeScalar weakTarget : weakTargets) { - assertTrue(WeakRefRegistry.isweak(weakTarget), - "a weak backref CODE capture protects each aggregate target"); - } - } - } finally { - runtime.lifecycleState.sweepPendingAfterOuterDestroy = false; - WeakRefRegistry.unweaken(weakCode); - for (RuntimeScalar weakTarget : weakTargets) { - WeakRefRegistry.unweaken(weakTarget); - } - MortalList.invalidateAllRootSnapshots(); - } - } - } -} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/WeakBackrefOwnerSlotFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakBackrefOwnerSlotFastPathTest.java new file mode 100644 index 0000000000..3e8a6f0d83 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakBackrefOwnerSlotFastPathTest.java @@ -0,0 +1,40 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class WeakBackrefOwnerSlotFastPathTest { + @Test + void elementOwnerPreservesWeakBackrefWithoutRootWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray capturedParent = new RuntimeArray(); + RuntimeArray target = new RuntimeArray(); + capturedParent.addClonedElement(target.createAnonymousReference()); + assertEquals(1, target.ownerSlotCount(PerlOwnerSlot.Kind.ARRAY_ELEMENT)); + + RuntimeCode weakBackrefCode = new RuntimeCode(null, List.of()); + weakBackrefCode.capturedAggregates = new RuntimeBase[] {capturedParent}; + weakBackrefCode.captureFieldsRecorded = true; + RuntimeScalar weakCode = new RuntimeScalar(weakBackrefCode); + WeakRefRegistry.weaken(weakCode); + + RuntimeScalar weakTarget = target.createAnonymousReference(); + WeakRefRegistry.weaken(weakTarget); + try { + MortalList.flush(); + assertTrue(WeakRefRegistry.isweak(weakTarget), + "the active element owner keeps the weakly observed target alive"); + } finally { + WeakRefRegistry.unweaken(weakTarget); + WeakRefRegistry.unweaken(weakCode); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/WeakCodeOwnerSlotLifecycleTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakCodeOwnerSlotLifecycleTest.java new file mode 100644 index 0000000000..6091192b29 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakCodeOwnerSlotLifecycleTest.java @@ -0,0 +1,41 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class WeakCodeOwnerSlotLifecycleTest { + @Test + void liveLexicalCodeOwnerPreservesWeakObserver() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + code.setTrackedRefCount(0); + RuntimeScalar strongOwner = new RuntimeScalar(); + RuntimeScalar weakOwner = new RuntimeScalar(); + int mark = MyVarCleanupStack.pushMark(); + MyVarCleanupStack.register(strongOwner); + MyVarCleanupStack.register(weakOwner); + strongOwner.set(new RuntimeScalar(code)); + weakOwner.set(new RuntimeScalar(code)); + + try { + WeakRefRegistry.weaken(weakOwner); + + assertTrue(WeakRefRegistry.isweak(weakOwner)); + assertEquals(RuntimeScalarType.CODE, weakOwner.type); + + strongOwner.set(new RuntimeScalar()); + assertEquals(RuntimeScalarType.UNDEF, weakOwner.type, + "releasing the final lexical CODE owner clears its weak observer"); + } finally { + MyVarCleanupStack.unregister(weakOwner); + MyVarCleanupStack.unregister(strongOwner); + MyVarCleanupStack.popMark(mark); + } + } + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/WeakCodeOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakCodeOwnerSlotTest.java new file mode 100644 index 0000000000..6c36e8fafd --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakCodeOwnerSlotTest.java @@ -0,0 +1,74 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class WeakCodeOwnerSlotTest { + @Test + void packageArrayOwnerSlotPreservesWeakCodeObserver() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + RuntimeScalar strongCodeRef = new RuntimeScalar(code); + RuntimeArray callbacks = new RuntimeArray(); + callbacks.addClonedElement(strongCodeRef); + String globalName = "WeakCodeOwnerSlotTest::callbacks"; + GlobalVariable.globalArrays.put(globalName, callbacks); + + RuntimeScalar weakCodeRef = new RuntimeScalar(code); + WeakRefRegistry.weaken(weakCodeRef); + try { + assertTrue(code.hasOwnerSlots()); + assertTrue(code.ownerSlotSnapshot().stream().anyMatch( + slot -> slot.isActive() + && slot.kind() != PerlOwnerSlot.Kind.CODE_SLOT), + "package arrays create a direct owner identity for their CODE values"); + { + WeakRefRegistry.clearWeakRefsTo(code); + + assertTrue(WeakRefRegistry.isweak(weakCodeRef)); + } + } finally { + GlobalVariable.globalArrays.remove(globalName); + callbacks.elements.remove(strongCodeRef); + MortalList.deferDestroyForContainerClear(java.util.List.of(strongCodeRef)); + if (WeakRefRegistry.isweak(weakCodeRef)) { + WeakRefRegistry.unweaken(weakCodeRef); + } + } + } + } + + @Test + void liveLexicalOwnerSlotSkipsCodeScalarGraphScan() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeCode code = new RuntimeCode((args, context) -> new RuntimeList(), null); + code.setTrackedRefCount(0); + RuntimeScalar owner = new RuntimeScalar(); + int mark = MyVarCleanupStack.pushMark(); + MyVarCleanupStack.register(owner); + owner.set(new RuntimeScalar(code)); + RuntimeScalar observer = new RuntimeScalar(code); + WeakRefRegistry.weaken(observer); + + try { + { + WeakRefRegistry.clearWeakRefsTo(code); + + assertTrue(WeakRefRegistry.isweak(observer)); + } + } finally { + owner.set(new RuntimeScalar()); + MyVarCleanupStack.unregister(owner); + MyVarCleanupStack.popMark(mark); + } + assertEquals(RuntimeScalarType.UNDEF, observer.type, + "the final lexical owner release clears the weak CODE observer"); + } + } + +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/WeakCodeRefAggregateRootTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakCodeRefAggregateRootTest.java deleted file mode 100644 index c343dceb71..0000000000 --- a/src/test/java/org/perlonjava/runtime/runtimetypes/WeakCodeRefAggregateRootTest.java +++ /dev/null @@ -1,207 +0,0 @@ -package org.perlonjava.runtime.runtimetypes; - -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -@Tag("unit") -class WeakCodeRefAggregateRootTest { - @Test - void fullRootSnapshotReflectsOnlyCodeSlotsWithCaptureEdges() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeHash capturedTarget = new RuntimeHash(); - RuntimeScalar capturedScalar = new RuntimeScalar(); - capturedScalar.type = RuntimeScalarType.REFERENCE; - capturedScalar.value = capturedTarget; - RuntimeCode capturedCode = new RuntimeCode(null, java.util.List.of()); - capturedCode.capturedScalars = new RuntimeScalar[] { capturedScalar }; - capturedCode.captureFieldsRecorded = true; - String capturedName = - "WeakCodeRefAggregateRootTest::snapshot_capture_holder"; - GlobalVariable.globalCodeRefs.put(capturedName, new RuntimeScalar(capturedCode)); - - java.util.List terminalNames = new java.util.ArrayList<>(); - for (int i = 0; i < 64; i++) { - String name = "WeakCodeRefAggregateRootTest::terminal_" + i; - terminalNames.add(name); - GlobalVariable.globalCodeRefs.put(name, new RuntimeScalar( - new RuntimeCode(null, java.util.List.of()))); - } - - try { - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - ReachabilityWalker.RootReachabilitySnapshot snapshot = - ReachabilityWalker.reachableFromRootsSnapshotWithStatus(); - - assertTrue(snapshot.isReachable(capturedTarget)); - assertEquals(1, measurement.stats().globalCodeCaptureRootsWalked, - "terminal installed CODE slots do not trigger reflective capture walks"); - } - } finally { - GlobalVariable.globalCodeRefs.remove(capturedName); - for (String name : terminalNames) GlobalVariable.globalCodeRefs.remove(name); - } - } - } - - @Test - void unblessedAggregateSnapshotSkipsTerminalCodeSlotsButFollowsCaptures() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeHash capturedTarget = new RuntimeHash(); - RuntimeScalar capturedScalar = new RuntimeScalar(); - capturedScalar.type = RuntimeScalarType.REFERENCE; - capturedScalar.value = capturedTarget; - RuntimeCode capturedCode = new RuntimeCode(null, java.util.List.of()); - capturedCode.capturedScalars = new RuntimeScalar[] { capturedScalar }; - capturedCode.captureFieldsRecorded = true; - String capturedName = - "WeakCodeRefAggregateRootTest::aggregate_snapshot_capture_holder"; - GlobalVariable.globalCodeRefs.put(capturedName, new RuntimeScalar(capturedCode)); - - java.util.List terminalNames = new java.util.ArrayList<>(); - java.util.List terminalCodes = new java.util.ArrayList<>(); - for (int i = 0; i < 128; i++) { - String name = "WeakCodeRefAggregateRootTest::aggregate_terminal_" + i; - terminalNames.add(name); - RuntimeCode terminal = new RuntimeCode(null, java.util.List.of()); - terminalCodes.add(terminal); - GlobalVariable.globalCodeRefs.put(name, new RuntimeScalar(terminal)); - } - - try { - try (MortalList.ReachabilityQueryMeasurement measurement = - MortalList.measureReachabilityQueries()) { - ReachabilityWalker.RootReachabilitySnapshot snapshot = - ReachabilityWalker.unblessedAggregateRootsSnapshotWithStatus(); - - assertTrue(snapshot.isReachable(capturedTarget), - "installed code capture edges still retain unblessed aggregates"); - assertEquals(1, measurement.stats().globalCodeCaptureRootsWalked); - for (RuntimeCode terminal : terminalCodes) { - assertFalse(snapshot.reachable().contains(terminal), - "terminal installed code identities are irrelevant to aggregate reachability"); - } - } - } finally { - GlobalVariable.globalCodeRefs.remove(capturedName); - for (String name : terminalNames) GlobalVariable.globalCodeRefs.remove(name); - } - } - } - - @Test - void fullRootSnapshotKeepsCodeRefHeldByPackageArray() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeCode code = new RuntimeCode(null, java.util.List.of()); - RuntimeScalar strongCodeRef = new RuntimeScalar(code); - RuntimeArray callbacks = new RuntimeArray(); - callbacks.elements.add(strongCodeRef); - String globalName = "WeakCodeRefAggregateRootTest::callbacks"; - GlobalVariable.globalArrays.put(globalName, callbacks); - - RuntimeScalar weakCodeRef = new RuntimeScalar(code); - WeakRefRegistry.weaken(weakCodeRef); - runtime.lifecycleState.fullRootSnapshot = - ReachabilityWalker.reachableFromRootsSnapshotWithStatus(); - - try { - assertTrue(runtime.lifecycleState.fullRootSnapshot.isReachable(code)); - assertFalse(ReachabilityWalker.hasLiveStrongScalarReferent(code)); - WeakRefRegistry.clearWeakRefsTo(code); - assertTrue(WeakRefRegistry.isweak(weakCodeRef)); - } finally { - GlobalVariable.globalArrays.remove(globalName); - } - } - } - - @Test - void liveStrongLexicalCodeRefIsFoundAfterWeakTrackingStarts() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeCode code = new RuntimeCode(null, java.util.List.of()); - RuntimeScalar strongCodeRef = new RuntimeScalar(code); - MyVarCleanupStack.register(strongCodeRef); - RuntimeScalar weakCodeRef = new RuntimeScalar(code); - WeakRefRegistry.weaken(weakCodeRef); - - try { - assertTrue(ReachabilityWalker.hasLiveStrongScalarReferent(code)); - assertFalse(ReachabilityWalker.hasLiveStrongScalarReferentOtherThan( - code, strongCodeRef)); - } finally { - MyVarCleanupStack.unregister(strongCodeRef); - } - - assertFalse(ReachabilityWalker.hasLiveStrongScalarReferent(code)); - } - } - - @Test - void externalRootSnapshotWalksCapturedScalarsFromInstalledCode() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeHash capturedTarget = new RuntimeHash(); - RuntimeScalar capturedScalar = new RuntimeScalar(); - capturedScalar.type = RuntimeScalarType.REFERENCE; - capturedScalar.value = capturedTarget; - RuntimeCode code = new RuntimeCode(null, java.util.List.of()); - code.capturedScalars = new RuntimeScalar[] { capturedScalar }; - code.captureFieldsRecorded = true; - - String globalName = "WeakCodeRefAggregateRootTest::capture_holder"; - GlobalVariable.globalCodeRefs.put(globalName, new RuntimeScalar(code)); - try { - ReachabilityWalker.ExternalRootSnapshot snapshot = - new ReachabilityWalker.ExternalRootSnapshot(); - assertTrue(snapshot.isReachableFromNonLexicalRoot(capturedTarget)); - } finally { - GlobalVariable.globalCodeRefs.remove(globalName); - } - } - } - - @Test - void codeRefEdgeRootCacheTracksSlotReplacementAndRemoval() { - PerlRuntime runtime = new PerlRuntime(); - try (PerlRuntime.Binding ignored = runtime.bind()) { - RuntimeHash capturedTarget = new RuntimeHash(); - RuntimeScalar capturedScalar = new RuntimeScalar(); - capturedScalar.type = RuntimeScalarType.REFERENCE; - capturedScalar.value = capturedTarget; - RuntimeCode capturedCode = new RuntimeCode(null, java.util.List.of()); - capturedCode.capturedScalars = new RuntimeScalar[] { capturedScalar }; - capturedCode.captureFieldsRecorded = true; - - String globalName = "WeakCodeRefAggregateRootTest::mutable_capture_holder"; - RuntimeScalar capturedRoot = new RuntimeScalar(capturedCode); - GlobalVariable.globalCodeRefs.put(globalName, capturedRoot); - try { - java.util.List cachedRoots = - GlobalVariable.globalCodeRefEdgeRootsView(); - assertTrue(cachedRoots.contains(capturedRoot)); - - RuntimeScalar terminalRoot = new RuntimeScalar( - new RuntimeCode(null, java.util.List.of())); - GlobalVariable.globalCodeRefs.put(globalName, terminalRoot); - assertFalse(cachedRoots.contains(capturedRoot)); - assertFalse(cachedRoots.contains(terminalRoot)); - - GlobalVariable.globalCodeRefs.put(globalName, capturedRoot); - assertTrue(cachedRoots.contains(capturedRoot)); - GlobalVariable.globalCodeRefs.remove(globalName); - assertFalse(cachedRoots.contains(capturedRoot)); - } finally { - GlobalVariable.globalCodeRefs.remove(globalName); - } - } - } - -} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/WeakGlobIoOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakGlobIoOwnerSlotTest.java new file mode 100644 index 0000000000..d95289ba44 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakGlobIoOwnerSlotTest.java @@ -0,0 +1,81 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.perlonjava.runtime.io.StandardIO; + +import java.io.ByteArrayOutputStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class WeakGlobIoOwnerSlotTest { + @Test + void weakGlobAliasReleasesIoOwnerAndUnweakenRestoresIt() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeGlob glob = new RuntimeGlob(null).setIO(new RuntimeIO( + new StandardIO(new ByteArrayOutputStream(), true))); + glob.setTrackedRefCount(2); + RuntimeScalar strong = globAlias(glob); + RuntimeScalar weak = globAlias(glob); + retainCountedAlias(glob, strong); + retainCountedAlias(glob, weak); + MyVarCleanupStack.register(strong); + MyVarCleanupStack.register(weak); + RuntimeScalar.retainUnstashedIoForDurableSlot(strong); + RuntimeScalar.retainUnstashedIoForDurableSlot(weak); + + try { + assertEquals(2, glob.ioHolderCount()); + + WeakRefRegistry.weaken(weak); + + assertTrue(WeakRefRegistry.isweak(weak)); + assertEquals(1, glob.refCount); + assertEquals(1, glob.ioHolderCount()); + assertFalse(weak.hasIoOwner()); + assertTrue(strong.hasIoOwner()); + + RuntimeScalar.retainUnstashedIoForDurableSlot(weak); + assertEquals(1, glob.ioHolderCount(), + "a durable weak scalar must not reacquire an IO owner"); + + WeakRefRegistry.unweaken(weak); + + assertFalse(WeakRefRegistry.isweak(weak)); + assertEquals(2, glob.refCount); + assertEquals(2, glob.ioHolderCount(), + "strengthening the scalar restores its IO owner"); + assertTrue(weak.hasIoOwner()); + + WeakRefRegistry.weaken(weak); + assertEquals(1, glob.refCount); + assertEquals(1, glob.ioHolderCount()); + assertFalse(weak.hasIoOwner()); + } finally { + WeakRefRegistry.clearWeakRefsTo(glob); + MyVarCleanupStack.unregister(weak); + MyVarCleanupStack.unregister(strong); + RuntimeScalar.releaseIoOwner(weak); + RuntimeScalar.releaseIoOwner(strong); + MortalList.flush(); + } + } + } + + private static RuntimeScalar globAlias(RuntimeGlob glob) { + RuntimeScalar alias = new RuntimeScalar(); + alias.type = RuntimeScalarType.GLOBREFERENCE; + alias.value = glob; + return alias; + } + + private static void retainCountedAlias(RuntimeGlob glob, RuntimeScalar alias) { + alias.refCountOwned = true; + glob.recordOwner(alias, "weak IO owner regression"); + glob.recordActiveOwner(alias); + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/WeakUncountedOwnerSlotFastPathTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakUncountedOwnerSlotFastPathTest.java new file mode 100644 index 0000000000..86dd03990b --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakUncountedOwnerSlotFastPathTest.java @@ -0,0 +1,69 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class WeakUncountedOwnerSlotFastPathTest { + @Test + void finalUncountedOwnerUsesSlotIdentityWithoutRootWalk() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + MortalList.setActive(true); + RuntimeArray target = new RuntimeArray(); + target.markRefCountUntracked(); + + RuntimeArray lexicalOwner = new RuntimeArray(); + int mark = MyVarCleanupStack.pushMark(); + MyVarCleanupStack.register(lexicalOwner); + RuntimeScalar strong = referenceTo(target); + lexicalOwner.elements.add(strong); + PerlOwnerSlot strongSlot = strong.untrackedReferenceOwnerSlot(); + assertNotNull(strongSlot); + + RuntimeScalar weakObserver = referenceTo(target); + // Model the counted slot being weakened; the array element remains + // the only uncounted strong Perl owner of the target. + target.setTrackedRefCount(1); + weakObserver.refCountOwned = true; + try { + { + WeakRefRegistry.weaken(weakObserver); + + assertTrue(WeakRefRegistry.isweak(weakObserver)); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState(), + "an uncounted slot retains the target without a compatibility pin"); + } + + strong.set(new RuntimeScalar()); + + assertFalse(strongSlot.isActive()); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the final uncounted owner release clears the weak observer"); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, target.perlLifecycleState()); + assertEquals(0, target.refCount); + } finally { + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + if (strongSlot.isActive()) strong.set(new RuntimeScalar()); + MortalList.scopeExitCleanupArray(lexicalOwner); + MyVarCleanupStack.unregister(lexicalOwner); + MyVarCleanupStack.popMark(mark); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.REFERENCE; + scalar.value = referent; + return scalar; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/WeakeningCountedOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakeningCountedOwnerSlotTest.java new file mode 100644 index 0000000000..675031c099 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakeningCountedOwnerSlotTest.java @@ -0,0 +1,50 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +@Tag("unit") +class WeakeningCountedOwnerSlotTest { + @Test + void weakeningReleasesOnlyTheSelectedCountedOwner() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeHash referent = new RuntimeHash(); + referent.blessId = NameNormalizer.getBlessId("FinalWeakOwner::Undercounted"); + RuntimeScalar observer = referent.createAnonymousReference(); + WeakRefRegistry.weaken(observer); + + RuntimeScalar weakenedOwner = new RuntimeScalar(); + RuntimeScalar survivingOwner = new RuntimeScalar(); + MyVarCleanupStack.register(weakenedOwner); + MyVarCleanupStack.register(survivingOwner); + weakenedOwner.set(referent.createAnonymousReference()); + survivingOwner.set(referent.createAnonymousReference()); + try { + assertEquals(2, referent.countedOwnerSlotCount()); + assertEquals(2, referent.refCount); + + { + WeakRefRegistry.weaken(weakenedOwner); + + assertEquals(1, referent.refCount); + assertEquals(1, referent.countedOwnerSlotCount()); + assertTrue(WeakRefRegistry.isweak(observer)); + } + } finally { + if (WeakRefRegistry.isweak(weakenedOwner)) { + WeakRefRegistry.unweaken(weakenedOwner); + } + if (WeakRefRegistry.isweak(observer)) WeakRefRegistry.unweaken(observer); + MyVarCleanupStack.unregister(weakenedOwner); + MyVarCleanupStack.unregister(survivingOwner); + weakenedOwner.set(new RuntimeScalar()); + survivingOwner.set(new RuntimeScalar()); + observer.set(new RuntimeScalar()); + } + } + } + +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/WeakeningPrunesStaleUntrackedOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakeningPrunesStaleUntrackedOwnerSlotTest.java new file mode 100644 index 0000000000..41d70c5775 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/WeakeningPrunesStaleUntrackedOwnerSlotTest.java @@ -0,0 +1,60 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@Tag("unit") +class WeakeningPrunesStaleUntrackedOwnerSlotTest { + @Test + void staleUntrackedCellDoesNotPreserveWeakReferentAfterFinalCountedOwnerLeaves() { + PerlRuntime runtime = new PerlRuntime(); + RuntimeArray lexicalOwner = new RuntimeArray(); + RuntimeArray target = new RuntimeArray(); + RuntimeScalar staleCell = referenceTo(target); + RuntimeScalar weakObserver = referenceTo(target); + + try (PerlRuntime.Binding ignored = runtime.bind()) { + boolean previousMortalListState = MortalList.isActive(); + MortalList.setActive(true); + lexicalOwner.localBindingExists = true; + lexicalOwner.elements.add(staleCell); + PerlOwnerSlot staleOwner = staleCell.untrackedReferenceOwnerSlot(); + assertNotNull(staleOwner); + target.setTrackedRefCount(1); + weakObserver.refCountOwned = true; + + try { + lexicalOwner.localBindingExists = false; + { + WeakRefRegistry.weaken(weakObserver); + + assertFalse(staleOwner.isActive(), + "weakening must retire an untracked slot with no live durable cell"); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the stale slot must not strand the final weak observer"); + assertEquals(RuntimeScalarType.UNDEF, weakObserver.type); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, target.perlLifecycleState()); + assertEquals(0, target.refCount); + } + } finally { + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + lexicalOwner.localBindingExists = false; + MortalList.scopeExitCleanupArray(lexicalOwner); + MortalList.setActive(previousMortalListState); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.REFERENCE; + scalar.value = referent; + return scalar; + } +} diff --git a/src/test/java/org/perlonjava/runtime/runtimetypes/WeaklyTrackedUndefOwnerSlotTest.java b/src/test/java/org/perlonjava/runtime/runtimetypes/WeaklyTrackedUndefOwnerSlotTest.java new file mode 100644 index 0000000000..cb860b0183 --- /dev/null +++ b/src/test/java/org/perlonjava/runtime/runtimetypes/WeaklyTrackedUndefOwnerSlotTest.java @@ -0,0 +1,69 @@ +package org.perlonjava.runtime.runtimetypes; + +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("unit") +class WeaklyTrackedUndefOwnerSlotTest { + @Test + void undefiningOneUntrackedCellPreservesTheOtherOwnerUntilItsRelease() { + PerlRuntime runtime = new PerlRuntime(); + try (PerlRuntime.Binding ignored = runtime.bind()) { + RuntimeArray target = new RuntimeArray(); + RuntimeScalar firstOwner = referenceTo(target); + RuntimeScalar secondOwner = referenceTo(target); + RuntimeScalar weakObserver = referenceTo(target); + int mark = MyVarCleanupStack.pushMark(); + try { + MyVarCleanupStack.register(firstOwner); + MyVarCleanupStack.register(secondOwner); + + PerlOwnerSlot firstSlot = firstOwner.untrackedReferenceOwnerSlot(); + PerlOwnerSlot secondSlot = secondOwner.untrackedReferenceOwnerSlot(); + assertEquals(RuntimeBase.RefCountTrackingState.UNTRACKED, target.refCountTrackingState()); + assertTrue(firstSlot.isActive()); + assertTrue(secondSlot.isActive()); + + WeakRefRegistry.weaken(weakObserver); + assertEquals(RuntimeBase.RefCountTrackingState.WEAKLY_TRACKED, target.refCountTrackingState()); + + firstOwner.undefine(); + + assertFalse(firstSlot.isActive(), "undef releases this cell's owner exactly once"); + assertTrue(secondSlot.isActive(), "the other scalar cell still owns the referent"); + assertTrue(WeakRefRegistry.isweak(weakObserver)); + assertNotEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + target.perlLifecycleState()); + + secondOwner.undefine(); + + assertFalse(secondSlot.isActive()); + assertFalse(WeakRefRegistry.isweak(weakObserver), + "the final owner release clears the weak observer"); + assertEquals(RuntimeBase.PerlLifecycleState.DESTROYED, + target.perlLifecycleState()); + } finally { + if (WeakRefRegistry.isweak(weakObserver)) { + WeakRefRegistry.unweaken(weakObserver); + } + RuntimeScalar.scopeExitCleanup(firstOwner); + RuntimeScalar.scopeExitCleanup(secondOwner); + MyVarCleanupStack.unregister(firstOwner); + MyVarCleanupStack.unregister(secondOwner); + MyVarCleanupStack.popMark(mark); + } + } + } + + private static RuntimeScalar referenceTo(RuntimeBase referent) { + RuntimeScalar scalar = new RuntimeScalar(); + scalar.type = RuntimeScalarType.REFERENCE; + scalar.value = referent; + return scalar; + } +} diff --git a/src/test/resources/fixtures/iosocketssl_chunked_tls_body.pl b/src/test/resources/fixtures/iosocketssl_chunked_tls_body.pl new file mode 100644 index 0000000000..47472b4735 --- /dev/null +++ b/src/test/resources/fixtures/iosocketssl_chunked_tls_body.pl @@ -0,0 +1,86 @@ +use strict; +use warnings; +use Test::More; +use IO::Socket::SSL; + +my $port = __PORT__; +my $expected = 'x' x 8192; +my $body = read_chunked_response($port); + +is(length($body), length($expected), 'the TLS response body is read to completion'); +is($body, $expected, 'the complete chunked TLS response body is preserved'); +done_testing; + +sub read_chunked_response { + my ($port) = @_; + return read_response( + IO::Socket::SSL->new( + PeerHost => '127.0.0.1', + PeerPort => $port, + SSL_verify_mode => SSL_VERIFY_NONE, + Timeout => 10, + ) + ); +} + +sub read_response { + print { $_[0] } "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n" + or die "write HTTP request: $!"; + + my $wire = ''; + my $count = sysread($_[0], $wire, 2048); + die "read TLS response headers: $!" unless defined $count; + + my $header_end = index($wire, "\r\n\r\n"); + die 'response headers are incomplete' if $header_end < 0; + my $headers = substr($wire, 0, $header_end); + substr($wire, 0, $header_end + 4, ''); + die 'response is not chunked' unless $headers =~ /^Transfer-Encoding:\s*chunked\s*$/mi; + ok(length($wire) > 0, 'the TLS header read also prefetched chunk-body bytes'); + + # The active argument must retain the socket after this captured lexical + # leaves scope. The first TLS read above also leaves body bytes buffered. + my $callback; + { + my $captured_socket = $_[0]; + $callback = sub { $captured_socket }; + } + $main::KEEP_TLS_CALLBACK = $callback; + + # Keep the closure alive until body consumption completes so its capture + # owns the aliased socket after the captured lexical leaves scope. + my $body = ''; + while (1) { + my $line_end = index($wire, "\r\n"); + while ($line_end < 0) { + my $chunk = ''; + my $read = sysread($_[0], $chunk, 4096); + die "read TLS chunk header: $!" unless defined $read; + die 'unexpected TLS EOF in chunk header' unless $read; + $wire .= $chunk; + $line_end = index($wire, "\r\n"); + } + + my $line = substr($wire, 0, $line_end, ''); + substr($wire, 0, 2, ''); + $line =~ s/;.*\z//; + die "invalid chunk size: $line" unless $line =~ /\A[0-9a-fA-F]+\z/; + my $size = hex($line); + last unless $size; + + while (length($wire) < $size + 2) { + my $chunk = ''; + my $read = sysread($_[0], $chunk, 4096); + die "read TLS chunk body: $!" unless defined $read; + die 'unexpected TLS EOF in chunk body' unless $read; + $wire .= $chunk; + } + + $body .= substr($wire, 0, $size, ''); + die 'missing chunk terminator' unless substr($wire, 0, 2, '') eq "\r\n"; + } + + die 'captured socket was released' unless $main::KEEP_TLS_CALLBACK->(); + undef $main::KEEP_TLS_CALLBACK; + return $body; +} diff --git a/src/test/resources/unit/active_lexical_scalar_deferred_release.t b/src/test/resources/unit/active_lexical_scalar_deferred_release.t new file mode 100644 index 0000000000..29e4d6807e --- /dev/null +++ b/src/test/resources/unit/active_lexical_scalar_deferred_release.t @@ -0,0 +1,37 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +use Scalar::Util qw(weaken); +use Test::More; + +{ + package ActiveLexicalScalarDeferredObject; + our $destroy_count = 0; + sub DESTROY { ++$destroy_count } +} + +my $weak; +{ + my $cell = 37; + my $object = bless \$cell, 'ActiveLexicalScalarDeferredObject'; + $weak = $object; + weaken($weak); + my @owners = ($object); + + undef $object; + ok(defined($weak), 'the aggregate slot retains the scalar-cell referent'); + + delete $owners[0]; + + ok(defined($weak), 'deleting the final counted edge waits for lexical-cell release'); + is($$weak, 37, 'the weak reference can still read the live scalar cell'); + is($ActiveLexicalScalarDeferredObject::destroy_count, 0, + 'DESTROY waits until the lexical scalar cell leaves scope'); +} + +ok(!defined($weak), 'the final lexical owner release clears the weak observer'); +is($ActiveLexicalScalarDeferredObject::destroy_count, 1, + 'the scalar referent is destroyed once after lexical scope exit'); + +done_testing(); diff --git a/src/test/resources/unit/active_lexical_scalar_referent_owner.t b/src/test/resources/unit/active_lexical_scalar_referent_owner.t new file mode 100644 index 0000000000..3e98c5f766 --- /dev/null +++ b/src/test/resources/unit/active_lexical_scalar_referent_owner.t @@ -0,0 +1,53 @@ +#!/usr/bin/env perl +use strict; +use warnings; + +use Scalar::Util qw(weaken); +use Test::More; + +{ + package ActiveLexicalScalarObject; + our $destroy_count = 0; + sub DESTROY { ++$destroy_count } +} + +my $weak; +{ + my $cell = 42; + my $object = bless \$cell, 'ActiveLexicalScalarObject'; + $weak = $object; + weaken($weak); + + undef $object; + + ok(defined($weak), 'the live lexical scalar cell keeps its object alive'); + is($$weak, 42, 'the weak reference still reaches the lexical scalar value'); + is($ActiveLexicalScalarObject::destroy_count, 0, + 'DESTROY waits while the lexical scalar referent is in scope'); +} + +ok(!defined($weak), 'leaving the lexical scope releases the scalar cell'); +is($ActiveLexicalScalarObject::destroy_count, 1, + 'the scalar referent is destroyed once after its lexical owner leaves'); + +our $tailcall_weak; +sub active_lexical_scalar_target { + ok(defined($tailcall_weak), 'the tail-call argument survives into its target'); + is($$tailcall_weak, 7, 'the target can still read the scalar referent'); +} + +sub active_lexical_scalar_trampoline { + my $cell = 7; + my $object = bless \$cell, 'ActiveLexicalScalarObject'; + $tailcall_weak = $object; + weaken($tailcall_weak); + unshift @_, $object; + goto &active_lexical_scalar_target; +} + +active_lexical_scalar_trampoline(); +ok(!defined($tailcall_weak), 'the tail-call target releases the final scalar cell owner'); +is($ActiveLexicalScalarObject::destroy_count, 2, + 'the tail-called scalar object is destroyed once after its target returns'); + +done_testing; diff --git a/src/test/resources/unit/caller_db_args_alias_slot.t b/src/test/resources/unit/caller_db_args_alias_slot.t new file mode 100644 index 0000000000..7b69126413 --- /dev/null +++ b/src/test/resources/unit/caller_db_args_alias_slot.t @@ -0,0 +1,17 @@ +use strict; +use warnings; +use Test::More tests => 2; + +sub write_through_caller_args { + package DB; + () = caller(0); + $DB::args[0] = 'changed through caller alias'; +} + +my $value = 'before'; +write_through_caller_args($value); + +is($value, 'changed through caller alias', + 'caller exposes the original scalar slot'); +is($DB::args[0], 'changed through caller alias', + 'caller retains the aliased scalar value'); diff --git a/src/test/resources/unit/closure_capture_explicit_return.t b/src/test/resources/unit/closure_capture_explicit_return.t new file mode 100644 index 0000000000..273b872957 --- /dev/null +++ b/src/test/resources/unit/closure_capture_explicit_return.t @@ -0,0 +1,40 @@ +use strict; +use warnings; +use Test::More tests => 6; +use Scalar::Util qw(weaken); + +my $destroyed = 0; +my $weak_node; + +{ + package Local::ExplicitReturnCapture; + sub DESTROY { ++$destroyed } +} + +sub discard_captured_lexical_with_explicit_return { + my $node = bless {}, 'Local::ExplicitReturnCapture'; + $weak_node = $node; + weaken($weak_node); + my $callback = sub { $node }; + return; +} + +discard_captured_lexical_with_explicit_return(); +is($destroyed, 1, 'captured lexical is released after explicit return'); +ok(!defined $weak_node, 'weak reference clears after explicit return'); + +$destroyed = 0; +$weak_node = undef; +sub return_callback_owning_aggregate { + my @nodes = (bless {}, 'Local::ExplicitReturnCapture'); + $weak_node = $nodes[0]; + weaken($weak_node); + return sub { scalar @nodes }; +} + +my $callback = return_callback_owning_aggregate(); +is($callback->(), 1, 'returned closure retains its captured aggregate'); +is($destroyed, 0, 'captured aggregate survives the returning call frame'); +undef $callback; +is($destroyed, 1, 'captured aggregate is released with the returned closure'); +ok(!defined $weak_node, 'weak reference clears after returned closure release'); diff --git a/src/test/resources/unit/closure_capture_scope_exit.t b/src/test/resources/unit/closure_capture_scope_exit.t new file mode 100644 index 0000000000..f0adfda8e0 --- /dev/null +++ b/src/test/resources/unit/closure_capture_scope_exit.t @@ -0,0 +1,23 @@ +use strict; +use warnings; +use Test::More tests => 2; +use Scalar::Util qw(weaken); + +my $destroyed = 0; +my $weak_node; +{ + package Local::CapturedScopeValue; + sub DESTROY { ++$destroyed } +} + +sub discard_captured_lexical { + my $node = bless {}, 'Local::CapturedScopeValue'; + $weak_node = $node; + weaken($weak_node); + my $callback = sub { $node }; + $callback->(); +} + +discard_captured_lexical(); +is($destroyed, 1, 'captured lexical value is destroyed after its closure leaves scope'); +ok(!defined $weak_node, 'weak reference clears when the captured lexical is released'); diff --git a/src/test/resources/unit/crypt_openssl_rsa_key_size_policy.t b/src/test/resources/unit/crypt_openssl_rsa_key_size_policy.t index e991af54a7..cbbf5db75e 100644 --- a/src/test/resources/unit/crypt_openssl_rsa_key_size_policy.t +++ b/src/test/resources/unit/crypt_openssl_rsa_key_size_policy.t @@ -21,19 +21,21 @@ BEGIN { or plan skip_all => 'Crypt::OpenSSL::RSA required'; } -plan tests => 14; +plan tests => 18; sub rejects_key_size { my ($bits, $label) = @_; my $generated = eval { Crypt::OpenSSL::RSA->generate_key($bits); 1 }; ok(!$generated, "$label is rejected before key generation"); - like($@, qr/RSA key size must be an integer from 1024 through 8192 bits/, + like($@, qr/RSA key size must be an integer from 2048 through 8192 bits/, "$label reports the accepted RSA key-size range"); } rejects_key_size(0, 'zero bits'); rejects_key_size(512, 'undersized RSA key'); +rejects_key_size(1024, 'legacy 1024-bit RSA key'); rejects_key_size(1025, 'non-byte-aligned RSA key'); +rejects_key_size(2040, 'RSA key below the 2048-bit minimum'); rejects_key_size(8193, 'oversized RSA key'); rejects_key_size(2048.5, 'fractional RSA key size'); rejects_key_size('not-a-number', 'nonnumeric RSA key size'); diff --git a/src/test/resources/unit/crypt_openssl_rsa_pkcs1_padding.t b/src/test/resources/unit/crypt_openssl_rsa_pkcs1_padding.t index f968eae924..8b81f1d37f 100644 --- a/src/test/resources/unit/crypt_openssl_rsa_pkcs1_padding.t +++ b/src/test/resources/unit/crypt_openssl_rsa_pkcs1_padding.t @@ -20,7 +20,7 @@ BEGIN { plan tests => 1; -my $rsa = Crypt::OpenSSL::RSA->generate_key(1024); +my $rsa = Crypt::OpenSSL::RSA->generate_key(2048); $rsa->use_pkcs1_padding; my $signature = $rsa->sign('PKCS#1 selector regression'); diff --git a/src/test/resources/unit/cryptx_chacha20poly1305.t b/src/test/resources/unit/cryptx_chacha20poly1305.t new file mode 100644 index 0000000000..3d7150deac --- /dev/null +++ b/src/test/resources/unit/cryptx_chacha20poly1305.t @@ -0,0 +1,31 @@ +use strict; +use warnings; +use Test::More; + +plan skip_all => 'CryptX is optional' + unless eval { require Crypt::AuthEnc::ChaCha20Poly1305; 1 }; + +my $key = pack 'H*', '808182838485868788898a8b8c8d8e8f' + . '909192939495969798999a9b9c9d9e9f'; +my $nonce = pack 'H*', '070000004041424344454647'; +my $aad = pack 'H*', '50515253c0c1c2c3c4c5c6c7'; +my $plaintext = "Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it."; + +my ($ciphertext, $tag) = Crypt::AuthEnc::ChaCha20Poly1305::chacha20poly1305_encrypt_authenticate( + $key, $nonce, $aad, $plaintext); +is unpack('H*', $ciphertext), + 'd31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d6' + . '3dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b36' + . '92ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc' + . '3ff4def08e4b7a9de576d26586cec64b6116', + 'ChaCha20-Poly1305 ciphertext matches RFC 8439'; +is unpack('H*', $tag), '1ae10b594f09e26a7e902ecbd0600691', + 'ChaCha20-Poly1305 tag matches RFC 8439'; +is Crypt::AuthEnc::ChaCha20Poly1305::chacha20poly1305_decrypt_verify( + $key, $nonce, $aad, $ciphertext, $tag), $plaintext, + 'authenticated decryption recovers the plaintext'; +ok !defined Crypt::AuthEnc::ChaCha20Poly1305::chacha20poly1305_decrypt_verify( + $key, $nonce, $aad, $ciphertext, pack('H*', '00000000000000000000000000000000')), + 'decryption rejects an invalid authentication tag'; + +done_testing; diff --git a/src/test/resources/unit/cryptx_key_derivation_pbkdf2.t b/src/test/resources/unit/cryptx_key_derivation_pbkdf2.t new file mode 100644 index 0000000000..2859bff7c1 --- /dev/null +++ b/src/test/resources/unit/cryptx_key_derivation_pbkdf2.t @@ -0,0 +1,13 @@ +use strict; +use warnings; +use Test::More; + +plan skip_all => 'CryptX is optional' unless eval { require Crypt::KeyDerivation; 1 }; + +is unpack('H*', Crypt::KeyDerivation::pbkdf2('password', 'salt', 1, 'SHA256', 32)), + '120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b', + 'PBKDF2-HMAC-SHA256 matches the known one-iteration vector'; +is length(Crypt::KeyDerivation::pbkdf2('password', 'salt')), 32, + 'default PBKDF2 output is 32 bytes'; + +done_testing; diff --git a/src/test/resources/unit/dbi_driver_handle_core_bless.t b/src/test/resources/unit/dbi_driver_handle_core_bless.t new file mode 100644 index 0000000000..dde0dbf6fe --- /dev/null +++ b/src/test/resources/unit/dbi_driver_handle_core_bless.t @@ -0,0 +1,30 @@ +use strict; +use warnings; + +our @observed_dbi_handle_blesses; + +BEGIN { + *CORE::GLOBAL::bless = sub { + my $class = @_ > 1 ? $_[1] : caller(); + push @observed_dbi_handle_blesses, $class + if $class =~ /^DBI::(?:dr|db|st)$/; + return CORE::bless($_[0], @_ > 1 ? $_[1] : caller()); + }; +} + +use Test::More tests => 4; +use DBI; +use Scalar::Util qw(weaken); + +my $weak_driver; +{ + my $driver = DBI->install_driver('SQLite'); + ok($driver, 'DBI installs the SQLite driver'); + is(ref($driver), 'DBI::dr', 'driver handle has the DBI::dr outer class'); + $weak_driver = $driver; + weaken($weak_driver); +} + +ok(defined $weak_driver, 'DBI keeps its installed driver handle alive'); +is_deeply(\@observed_dbi_handle_blesses, [], + 'internal DBI handle construction bypasses CORE::GLOBAL::bless'); diff --git a/src/test/resources/unit/deferred_capture_live_argument.t b/src/test/resources/unit/deferred_capture_live_argument.t new file mode 100644 index 0000000000..166b6d13b9 --- /dev/null +++ b/src/test/resources/unit/deferred_capture_live_argument.t @@ -0,0 +1,37 @@ +use strict; +use warnings; +use Test::More; + +{ + package Local::ClosureOwnerProbe; + our $destroy_count = 0; + our $destroyed_while_argument_live = -1; + + sub new { + return bless { token => 'alive' }, shift; + } + + sub DESTROY { + ++$destroy_count; + } +} + +sub read_after_capture_scope_exits { + { + my $captured = $_[0]; + my $callback = sub { $captured->{token} }; + } + + $Local::ClosureOwnerProbe::destroyed_while_argument_live = + $Local::ClosureOwnerProbe::destroy_count; + return $_[0]->{token}; +} + +my $value = read_after_capture_scope_exits(Local::ClosureOwnerProbe->new); +is($Local::ClosureOwnerProbe::destroyed_while_argument_live, 0, + 'the active call argument keeps its referent alive after the captured lexical leaves scope'); +is($value, 'alive', 'the active call argument remains usable'); +is($Local::ClosureOwnerProbe::destroy_count, 1, + 'the temporary referent is destroyed after the call returns'); + +done_testing; diff --git a/src/test/resources/unit/defined_code_slot_compile_time_stash_delete.t b/src/test/resources/unit/defined_code_slot_compile_time_stash_delete.t new file mode 100644 index 0000000000..1aad7987c7 --- /dev/null +++ b/src/test/resources/unit/defined_code_slot_compile_time_stash_delete.t @@ -0,0 +1,20 @@ +use strict; +use warnings; +use Test::More tests => 2; + +BEGIN { + package DefinedCodeSlotCompileTimeDelete; + sub target { 'old' } +} + +package main; + +my $probe = sub { defined(&DefinedCodeSlotCompileTimeDelete::target) }; + +BEGIN { + delete $DefinedCodeSlotCompileTimeDelete::{target}; +} + +ok($probe->(), 'compiled defined probe retains its CV after compile-time stash deletion'); +ok(!exists($DefinedCodeSlotCompileTimeDelete::{target}), + 'the stash entry was deleted before the probe ran'); diff --git a/src/test/resources/unit/dynamic_method_return_lifetime.t b/src/test/resources/unit/dynamic_method_return_lifetime.t new file mode 100644 index 0000000000..a2843aadb1 --- /dev/null +++ b/src/test/resources/unit/dynamic_method_return_lifetime.t @@ -0,0 +1,92 @@ +use strict; +use warnings; +use Test::More; + +{ + package Local::LookupString; + + sub new { + my $class = ref($_[0]) || $_[0]; + return bless { text => $_[1] }, $class; + } + + sub lower { + $_[0]->{text} = lc $_[0]->{text}; + return $_[0]; + } + + sub equals { + return $_[0]->{text} eq $_[1]->{text}; + } +} + +{ + package Local::LookupStash; + + sub new { + my ($class, $values) = @_; + return bless $values, $class; + } + + sub get { + my ($self, $ident) = @_; + my ($root, $result); + $root = $self; + + for (my $i = 0; $i < @$ident; $i += 2) { + $result = $self->_dotop($root, $ident->[$i], $ident->[$i + 1]); + last unless defined $result; + $root = $result; + } + + return $result; + } + + sub _dotop { + my ($self, $root, $item, $args) = @_; + my (@result); + $args ||= []; + + if (ref($root) eq 'HASH' || ref($root) eq ref($self)) { + return $root->{$item} if defined $root->{$item}; + } + else { + eval { @result = $root->$item(@$args); }; + die $@ if $@; + } + + return unless defined $result[0]; + return @result > 1 ? [@result] : $result[0]; + } +} + +my $stash = Local::LookupStash->new({ + String => Local::LookupString->new(''), + a => 'HeLLo', + b => 'hEllO', +}); +my ($new_strings_differ, $lower_strings_differ, $result); +my $evaluation_succeeded = eval q{ + my $a = $stash->get(['a', 0]); + my $b = $stash->get(['b', 0]); + $new_strings_differ = + $stash->get(['String', 0, 'new', [$a]]) + != $stash->get(['String', 0, 'new', [$b]]); + $lower_strings_differ = + $stash->get(['String', 0, 'new', [$a], 'lower', 0]) + != $stash->get(['String', 0, 'new', [$b], 'lower', 0]); + $result = $stash->get( + [ + 'String', 0, 'new', [$a], 'lower', 0, 'equals', [ + $stash->get(['String', 0, 'new', [$b], 'lower', 0]), + ], + ], + ); + 1; +}; + +ok($evaluation_succeeded, 'dotted lookup sequence completes inside eval'); +is($new_strings_differ, 1, 'dotted lookup creates separate String objects'); +is($lower_strings_differ, 1, 'dotted lookup can call a method returning the same object'); +is($result, 1, 'a returned object remains alive through the next method call'); +done_testing(); diff --git a/src/test/resources/unit/exporter_to_level_first_lazy_require.t b/src/test/resources/unit/exporter_to_level_first_lazy_require.t new file mode 100644 index 0000000000..1388ede505 --- /dev/null +++ b/src/test/resources/unit/exporter_to_level_first_lazy_require.t @@ -0,0 +1,34 @@ +use strict; +use warnings; +use Test::More tests => 2; + +BEGIN { + package Issue1649::FirstLazyExporter; + require Exporter; + our @ISA = qw(Exporter); + our @EXPORT = qw(exported_caller); + + sub import { + my $self = shift; + $self->export_to_level(1, $self, @_); + } + + sub exported_caller { scalar caller } + + $INC{'Issue1649/FirstLazyExporter.pm'} = __FILE__; +} + +{ + package Issue1649::FirstLazyExporter::Client; + use Issue1649::FirstLazyExporter qw(exported_caller); + + our $observed = defined(&exported_caller) + ? &exported_caller() + : 'missing'; +} + +ok(defined(&Issue1649::FirstLazyExporter::Client::exported_caller), + 'export_to_level installs the symbol in the importing package'); +is($Issue1649::FirstLazyExporter::Client::observed, + 'Issue1649::FirstLazyExporter::Client', + 'the exported sub sees the importing package as its caller'); diff --git a/src/test/resources/unit/issue_1860_growing_lexical_output.t b/src/test/resources/unit/issue_1860_growing_lexical_output.t new file mode 100644 index 0000000000..047582cb9f --- /dev/null +++ b/src/test/resources/unit/issue_1860_growing_lexical_output.t @@ -0,0 +1,35 @@ +use strict; +use warnings; +use Test::More tests => 4; + +my $width = 4; +my $depth = 5; +my @output; + +sub tumble { + my ($level, $path, $values, $payload) = @_; + if ($level == $depth) { + push @output, [ $path, $values, $payload ]; + return; + } + + for my $variant (1 .. $width) { + tumble( + $level + 1, + [ @$path, $variant ], + [ @$values, $variant ], + { %$payload }, + ); + } +} + +tumble(0, [], [], { payload => 'kept' }); + +is(scalar @output, $width ** $depth, + 'recursive callbacks append every result to the growing lexical output'); +is_deeply($output[0][0], [ (1) x $depth ], + 'the first retained path survives recursive scope cleanup'); +is_deeply($output[-1][0], [ (4) x $depth ], + 'the last retained path survives recursive scope cleanup'); +is($output[-1][2]{payload}, 'kept', + 'the final callback retains its payload'); diff --git a/src/test/resources/unit/issue_2015_interpreter_dup_stdout.t b/src/test/resources/unit/issue_2015_interpreter_dup_stdout.t new file mode 100644 index 0000000000..a552c86163 --- /dev/null +++ b/src/test/resources/unit/issue_2015_interpreter_dup_stdout.t @@ -0,0 +1,27 @@ +use strict; +use warnings; +use Test::More; +use File::Temp (); + +my %captures; +my $capture = ($captures{streams} ||= {})->{stdout} ||= File::Temp->new(); + +ok(defined fileno($capture), + 'a File::Temp handle stored through nested ||= keeps its descriptor'); + +my $opened; +{ + $opened = open local *STDOUT, '>&', $capture; + if ($opened) { + print STDOUT "captured\n"; + } +} + +ok($opened, 'STDOUT can be duplicated onto the stored temporary handle') + or diag("open dup failed: $!"); + +seek($capture, 0, 0) or die "seek capture: $!"; +my $output = <$capture>; +is($output, "captured\n", 'the duplicated STDOUT writes to the capture'); + +done_testing; diff --git a/src/test/resources/unit/issue_2034_localized_stderr_tied_scalar.t b/src/test/resources/unit/issue_2034_localized_stderr_tied_scalar.t new file mode 100644 index 0000000000..635e080c98 --- /dev/null +++ b/src/test/resources/unit/issue_2034_localized_stderr_tied_scalar.t @@ -0,0 +1,45 @@ +use strict; +use warnings; +use Test::More; + +{ + package IO::Scalar; + no warnings 'once'; + + # Minimal tied glob-reference handle matching IO::Scalar's construction + # path. The regression concerns assignment of this blessed GLOBREFERENCE + # into a localized standard-error glob, not the full CPAN module API. + sub new { + my ($class) = @_; + my $buffer = ''; + my $self = bless \do { local *FH }, $class; + *$self->{buffer} = \$buffer; + tie *$self, $class, $self; + return $self; + } + + sub TIEHANDLE { $_[1] } + + sub PRINT { + my $self = shift; + my $buffer = *$self->{buffer}; + $$buffer .= join '', @_; + return 1; + } + + sub contents { + my $buffer = *{$_[0]}->{buffer}; + return $$buffer; + } +} + +my $capture = IO::Scalar->new(); +{ + local *STDERR = $capture; + print STDERR "diagnostic\n"; +} + +is($capture->contents, "diagnostic\n", + 'localized STDERR writes reach a blessed tied scalar handle'); + +done_testing; diff --git a/src/test/resources/unit/issue_2043_map_callsite_wantarray_context.t b/src/test/resources/unit/issue_2043_map_callsite_wantarray_context.t new file mode 100644 index 0000000000..769f321cb1 --- /dev/null +++ b/src/test/resources/unit/issue_2043_map_callsite_wantarray_context.t @@ -0,0 +1,22 @@ +use strict; +use warnings; +use Test::More; + +sub context_name { + my $context = wantarray; + return !defined($context) ? 'void' : $context ? 'list' : 'scalar'; +} + +sub nested_scalar_context { + return scalar context_name(); +} + +my @direct_list = map { context_name() } 1; +my @direct_scalar = map { scalar context_name() } 1; +my @nested_scalar = map { nested_scalar_context() } 1; + +is_deeply(\@direct_list, ['list'], 'direct map callback call receives list context'); +is_deeply(\@direct_scalar, ['scalar'], 'explicit scalar call inside map stays scalar'); +is_deeply(\@nested_scalar, ['scalar'], 'nested scalar call inside map stays scalar'); + +done_testing(); diff --git a/src/test/resources/unit/issue_2043_map_nested_wantarray_context.t b/src/test/resources/unit/issue_2043_map_nested_wantarray_context.t new file mode 100644 index 0000000000..5a7d6ae9fe --- /dev/null +++ b/src/test/resources/unit/issue_2043_map_nested_wantarray_context.t @@ -0,0 +1,29 @@ +use strict; +use warnings; +use Test::More; + +my ($direct_map_context, $nested_scalar_context); + +sub context_name { + my $context = wantarray; + return !defined($context) ? 'void' : $context ? 'list' : 'scalar'; +} + +sub record_direct_map_context { + my $context = wantarray; + $direct_map_context = !defined($context) ? 'void' : $context ? 'list' : 'scalar'; +} + +sub record_nested_scalar_context { + if (my $context = context_name()) { + $nested_scalar_context = $context; + } +} + +map { record_direct_map_context() } 1; +map { record_nested_scalar_context() } 1; + +is($direct_map_context, 'list', 'sub called directly from map receives list context'); +is($nested_scalar_context, 'scalar', 'scalar subcall keeps its context inside a map-called sub'); + +done_testing(); diff --git a/src/test/resources/unit/issue_2043_nonlocal_last_releases_frame_lexicals.t b/src/test/resources/unit/issue_2043_nonlocal_last_releases_frame_lexicals.t new file mode 100644 index 0000000000..6cae581ac7 --- /dev/null +++ b/src/test/resources/unit/issue_2043_nonlocal_last_releases_frame_lexicals.t @@ -0,0 +1,32 @@ +use strict; +use warnings; +use Test::More; + +our (@guard_cleanups, $resumed_inside_sub); + +{ + package Issue2043::ScopeGuard; + + sub new { bless [$_[1]], $_[0] } + sub DESTROY { $_[0]->[0]->() } +} + +sub leave_through_callback { + my $guard = Issue2043::ScopeGuard->new( + sub { push @guard_cleanups, 'released' }, + ); + $_[0]->(); + $resumed_inside_sub = 1; +} + +my $resumed_after_block = 0; +OUTER: { + leave_through_callback(sub { last OUTER }); + $resumed_after_block = 1; +} + +is($resumed_inside_sub || 0, 0, 'last skips the rest of the active sub'); +is($resumed_after_block, 0, 'last exits the labeled block'); +is_deeply(\@guard_cleanups, ['released'], 'DESTROY runs for a local in the unwound sub'); + +done_testing(); diff --git a/src/test/resources/unit/issue_2071_2091_posix_strtod_limits.t b/src/test/resources/unit/issue_2071_2091_posix_strtod_limits.t new file mode 100644 index 0000000000..5e8a7ee2bb --- /dev/null +++ b/src/test/resources/unit/issue_2071_2091_posix_strtod_limits.t @@ -0,0 +1,38 @@ +use strict; +use warnings; +use Test::More; +use Config (); +use POSIX qw(strtod :limits_h); + +my ($number, $unparsed) = strtod('12.5xy'); +is($number, 12.5, 'strtod parses the numeric prefix'); +is($unparsed, 2, 'strtod reports the count of trailing unparsed characters'); + +($number, $unparsed) = strtod('-'); +is($number, 0, 'strtod returns zero when there is no numeric prefix'); +is($unparsed, 1, 'strtod counts the whole input when nothing parses'); + +($number, $unparsed) = strtod(' -'); +is($number, 0, 'strtod still returns zero when whitespace precedes invalid input'); +is($unparsed, 3, 'strtod counts the original input when no conversion occurs'); + +($number, $unparsed) = strtod('1e+'); +is($number, 1, 'strtod leaves an incomplete exponent unparsed'); +is($unparsed, 2, 'strtod counts every character after the parsed prefix'); + +($number, $unparsed) = strtod(' 12x'); +is($number, 12, 'strtod accepts leading whitespace'); +is($unparsed, 1, 'strtod counts the suffix after leading whitespace'); + +my $longsize = $Config::Config{perlonjava} + ? ($^O eq 'MSWin32' ? 4 : 8) + : $Config::Config{longsize}; +my $expected_long_max = $longsize >= 8 + ? '9223372036854775807' + : '2147483647'; +is("" . POSIX::LONG_MAX(), $expected_long_max, + 'POSIX::LONG_MAX matches the platform C long width'); +is("" . LONG_MAX(), $expected_long_max, + 'LONG_MAX is available through the limits_h export'); + +done_testing; diff --git a/src/test/resources/unit/lib/namespace/clean.pm b/src/test/resources/unit/lib/namespace/clean.pm new file mode 100644 index 0000000000..c9a35fa9e6 --- /dev/null +++ b/src/test/resources/unit/lib/namespace/clean.pm @@ -0,0 +1,29 @@ +package namespace::clean; + +use strict; +use warnings; + +# Keep the unit-test regression independent of a host-installed CPAN copy. +# The focused unit tests only need the default behavior for CODE entries +# present before this pragma is used. +our @CLEAN_AT_CHECK; + +sub import { + my ($pragma, @args) = @_; + die "unit-test namespace::clean shim only supports default import\n" if @args; + + my $caller = caller; + no strict 'refs'; + my @names = grep { defined *{"${caller}::$_"}{CODE} } keys %{"${caller}::"}; + push @CLEAN_AT_CHECK, [$caller, @names]; +} + +CHECK { + no strict 'refs'; + for my $entry (@CLEAN_AT_CHECK) { + my ($caller, @names) = @$entry; + delete ${"${caller}::"}{$_} for @names; + } +} + +1; diff --git a/src/test/resources/unit/mojolicious_controller_destroy_after_deferred_render.t b/src/test/resources/unit/mojolicious_controller_destroy_after_deferred_render.t new file mode 100644 index 0000000000..9a6424e30e --- /dev/null +++ b/src/test/resources/unit/mojolicious_controller_destroy_after_deferred_render.t @@ -0,0 +1,60 @@ +use strict; +use warnings; +use Test::More; + +BEGIN { + $ENV{MOJO_REACTOR} = 'Mojo::Reactor::Poll'; + eval { + require IO::Socket::INET; + require Mojolicious::Lite; + Mojolicious::Lite->import; + require Test::Mojo; + require Mojo::IOLoop; + 1; + } or plan skip_all => 'Mojolicious and Test::Mojo are required'; + + my $probe = IO::Socket::INET->new( + LocalAddr => '127.0.0.1', + LocalPort => 0, + Listen => 1, + Proto => 'tcp', + ) or plan skip_all => 'loopback sockets are unavailable'; + close $probe; +} + +package MyTestApp::Controller; +use Mojo::Base 'Mojolicious::Controller'; +sub DESTROY { shift->stash->{destroyed} = 1 } + +package main; +app->controller_class('MyTestApp::Controller'); + +get '/render' => sub { + my $c = shift; + my $stream = Mojo::IOLoop->stream($c->tx->connection); + $c->on(finish => sub { + shift->stash->{writing} = $stream->is_writing; + }); + $c->render_later; + Mojo::IOLoop->next_tick(sub { + $c->render(msg => 'Finish!'); + }); +}; + +my $stash; +my $test = Test::Mojo->new; +$test->app->plugins->once(before_dispatch => sub { $stash = shift->stash }); +$test->get_ok('/render')->status_is(200)->content_is('Finish!'); + +my $wait_expired = 0; +my $timer = Mojo::IOLoop->timer(5 => sub { $wait_expired = 1 }); +Mojo::IOLoop->one_tick while !$stash->{destroyed} && !$wait_expired; +Mojo::IOLoop->remove($timer); +ok($stash->{destroyed}, 'controller is destroyed after deferred rendering'); +ok(!$stash->{writing}, 'finish callback sees a drained response'); + +done_testing; + +__DATA__ +@@ render.html.ep +<%= $msg %>\ diff --git a/src/test/resources/unit/mojolicious_controller_destroy_after_finish.t b/src/test/resources/unit/mojolicious_controller_destroy_after_finish.t new file mode 100644 index 0000000000..771ff9ce3b --- /dev/null +++ b/src/test/resources/unit/mojolicious_controller_destroy_after_finish.t @@ -0,0 +1,54 @@ +use strict; +use warnings; +use Test::More; + +BEGIN { + $ENV{MOJO_REACTOR} = 'Mojo::Reactor::Poll'; + eval { + require IO::Socket::INET; + require Mojolicious::Lite; + Mojolicious::Lite->import; + require Test::Mojo; + require Mojo::IOLoop; + 1; + } or plan skip_all => 'Mojolicious and Test::Mojo are required'; + + my $probe = IO::Socket::INET->new( + LocalAddr => '127.0.0.1', + LocalPort => 0, + Listen => 1, + Proto => 'tcp', + ) or plan skip_all => 'loopback sockets are unavailable'; + close $probe; +} + +package MojoliciousControllerDestroyAfterFinish; +use Mojo::Base 'Mojolicious::Controller'; +sub DESTROY { shift->stash->{destroyed} = 1 } + +package main; +app->controller_class('MojoliciousControllerDestroyAfterFinish'); +get '/longpoll' => sub { + my $controller = shift; + $controller->on(finish => sub { shift->stash->{finished} = 1 }); + $controller->write_chunk('P' => sub { + shift->write_chunk('oll!' => sub { shift->write_chunk('') }); + }); +}; + +my $stash; +my $tick_count = 0; +my $timer = Mojo::IOLoop->recurring(0.1 => sub { ++$tick_count }); +my $test = Test::Mojo->new; +$test->app->plugins->once(before_dispatch => sub { $stash = shift->stash }); +$test->get_ok('/longpoll')->status_is(200)->content_is('Poll!'); + +Mojo::IOLoop->one_tick while !$stash->{finished} && $tick_count < 50; +is($stash->{finished}, 1, 'long-poll response finish event runs'); + +$tick_count = 0; +Mojo::IOLoop->one_tick while !$stash->{destroyed} && $tick_count < 50; +Mojo::IOLoop->remove($timer); +ok($stash->{destroyed}, 'controller is destroyed after response finish'); + +done_testing; diff --git a/src/test/resources/unit/mojolicious_nested_lite_load_package.t b/src/test/resources/unit/mojolicious_nested_lite_load_package.t new file mode 100644 index 0000000000..bd9e515f6b --- /dev/null +++ b/src/test/resources/unit/mojolicious_nested_lite_load_package.t @@ -0,0 +1,39 @@ +use strict; +use warnings; +use Test::More; +use File::Temp qw(tempfile); + +BEGIN { + $ENV{MOJO_MODE} = 'testing'; + $ENV{MOJO_REACTOR} = 'Mojo::Reactor::Poll'; +} + +my $have_mojolicious = eval { + require Mojolicious::Lite; + require Mojolicious::Plugin::Mount; + 1; +}; +plan skip_all => 'Mojolicious is optional' unless $have_mojolicious; + +Mojolicious::Lite->import(); + +my ($app_file, $path) = tempfile(SUFFIX => '.pl', UNLINK => 1); +print {$app_file} <<'APP' or die "write app: $!"; +use Mojolicious::Lite; +get '/' => {text => 'mounted'}; +app->start; +APP +close $app_file or die "close app: $!"; + +my ($route, $load_error); +{ + local $@; + eval { $route = app()->plugin(Mount => {'/mounted' => $path}); 1 } + or $load_error = $@; +} + +ok(!$load_error && $route, 'Mount loads a nested Lite application') + or diag($load_error // 'Mount returned no route'); +isa_ok($route->to->{app}, 'Mojolicious', 'mounted application') if $route; + +done_testing; diff --git a/src/test/resources/unit/mojolicious_websocket_controller_release.t b/src/test/resources/unit/mojolicious_websocket_controller_release.t new file mode 100644 index 0000000000..9d5c2a8183 --- /dev/null +++ b/src/test/resources/unit/mojolicious_websocket_controller_release.t @@ -0,0 +1,51 @@ +use strict; +use warnings; + +BEGIN { $ENV{MOJO_REACTOR} = 'Mojo::Reactor::Poll' } + +use Test::More; + +BEGIN { + $ENV{MOJO_REACTOR} = 'Mojo::Reactor::Poll'; + eval { + require IO::Socket::INET; + require Mojolicious::Lite; + Mojolicious::Lite->import; + require Test::Mojo; + require Mojo::IOLoop; + 1; + } or plan skip_all => 'Mojolicious and Test::Mojo are required'; + + my $probe = IO::Socket::INET->new( + LocalAddr => '127.0.0.1', + LocalPort => 0, + Listen => 1, + Proto => 'tcp', + ) or plan skip_all => 'loopback sockets are unavailable'; + close $probe; +} + +package WebSocketLifetimeController; +use Mojo::Base 'Mojolicious::Controller'; +sub DESTROY { $main::controller_destroyed = 1 } + +package main; +our $timer_id; +our $controller_destroyed = 0; +app->controller_class('WebSocketLifetimeController'); +websocket '/lifetime' => sub { + my $controller = shift; + $timer_id = Mojo::IOLoop->recurring(0.05 => sub { $controller->send('tick') }); +}; + +my $test = Test::Mojo->new; +$test->websocket_ok('/lifetime')->message_ok->message_is('tick'); +ok(!$controller_destroyed, 'controller stays alive while its WebSocket is open'); +Mojo::IOLoop->remove($timer_id); +$test->finish_ok; + +my $wait_expired = 0; +Mojo::IOLoop->timer(0.25 => sub { $wait_expired = 1 }); +Mojo::IOLoop->one_tick until $controller_destroyed || $wait_expired; +ok($controller_destroyed, 'controller is released after its WebSocket closes'); +done_testing; diff --git a/src/test/resources/unit/namespace_autoclean_nested_metarole_import_lifetime.t b/src/test/resources/unit/namespace_autoclean_nested_metarole_import_lifetime.t new file mode 100644 index 0000000000..d4d0550cc2 --- /dev/null +++ b/src/test/resources/unit/namespace_autoclean_nested_metarole_import_lifetime.t @@ -0,0 +1,86 @@ +use strict; +use warnings; +use Test::More; +use File::Path qw(make_path); +use File::Spec; +use File::Temp qw(tempdir); + +BEGIN { + eval { + require Moose; + require Moose::Role; + require Moose::Util::MetaRole; + require namespace::autoclean; + 1; + } or plan skip_all => 'Moose and namespace::autoclean are required'; +} + +my $module_root = tempdir(CLEANUP => 1); +my $module_dir = File::Spec->catdir($module_root, qw(Issue2043 NestedMetarole)); +make_path($module_dir); + +my @module_sources = ( + [ + File::Spec->catfile($module_dir, 'InnerRole.pm'), + <<'PERL', +package Issue2043::NestedMetarole::InnerRole; +use Moose::Role; +use namespace::autoclean; +sub helper { 'inner' } +1; +PERL + ], + [ + File::Spec->catfile($module_dir, 'OuterRole.pm'), + <<'PERL', +package Issue2043::NestedMetarole::OuterRole; +use Moose::Role; +use Issue2043::NestedMetarole::InnerRole; +use namespace::autoclean; +override wrap => sub { + my $method = super; + return $method; +}; +1; +PERL + ], +); + +for my $module_source (@module_sources) { + my ($path, $source) = @$module_source; + open my $module, '>', $path or die "open $path: $!"; + print {$module} $source or die "write $path: $!"; + close $module or die "close $path: $!"; +} + +unshift @INC, $module_root; + +{ + package Issue2043::NestedMetarole::Consumer; + use Moose; + sub base { 'base' } +} + +my ($result, $call_error); +{ + local $@; + eval { + require Issue2043::NestedMetarole::OuterRole; + Moose::Util::MetaRole::apply_metaroles( + for => 'Issue2043::NestedMetarole::Consumer', + class_metaroles => { + wrapped_method => ['Issue2043::NestedMetarole::OuterRole'], + }, + ); + Issue2043::NestedMetarole::Consumer->meta + ->add_before_method_modifier('base', sub { }); + $result = Issue2043::NestedMetarole::Consumer->new->base; + 1; + } or $call_error = $@; +} + +ok(!$call_error, 'a nested namespace cleanup preserves the imported metarole super call') + or diag($call_error); +is($result, 'base', 'the wrapped method still returns its base result'); + +done_testing(); diff --git a/src/test/resources/unit/netssleay_phase5_6.t b/src/test/resources/unit/netssleay_phase5_6.t index 3cd63fd5d6..4126d5d769 100644 --- a/src/test/resources/unit/netssleay_phase5_6.t +++ b/src/test/resources/unit/netssleay_phase5_6.t @@ -9,7 +9,7 @@ use warnings; use Test::More; BEGIN { Test::More::plan(skip_all => 'tests PerlOnJava Net::SSLeay implementation') - unless $^X eq 'jperl' || $^X =~ m{(?:^|[\\/])jperl(?:\.bat)?$}; + unless $^X eq 'jperl' || $^X =~ m{(?:^|[\\/])(?:jperl|jperl-exec)(?:\.bat)?$}; eval { require Net::SSLeay; Net::SSLeay->import; 1 } or do { require Test::More; @@ -94,17 +94,17 @@ Net::SSLeay::BN_free($_) for $bn, $bn2, $bn3, $bn4; # Phase 6: RSA encrypt/decrypt + sign/verify round-trip # ----------------------------------------------------------------- -# 2048 is slow; 1024 keeps the test fast -my $rsa = Net::SSLeay::RSA_generate_key(1024, 65537); -ok($rsa, 'RSA_generate_key(1024)'); +# Use the minimum supported RSA key size for the round-trip test. +my $rsa = Net::SSLeay::RSA_generate_key(2048, 65537); +ok($rsa, 'RSA_generate_key(2048)'); my $size = Net::SSLeay::RSA_size($rsa); -is($size, 128, 'RSA_size returns 128 for 1024-bit key'); +is($size, 256, 'RSA_size returns 256 for 2048-bit key'); # Encrypt with public key, decrypt with private key my $plain = "hello, ssleay"; my $ct = ''; my $n = Net::SSLeay::RSA_public_encrypt($plain, $ct, $rsa, 1); -is($n, 128, 'RSA_public_encrypt returns 128 (PKCS1 padding, 1024-bit key)'); +is($n, 256, 'RSA_public_encrypt returns 256 (PKCS1 padding, 2048-bit key)'); my $pt = ''; my $m = Net::SSLeay::RSA_private_decrypt($ct, $pt, $rsa, 1); @@ -121,7 +121,7 @@ is($pt2, $plain, 'RSA_private_encrypt / RSA_public_decrypt round-trip'); my $message = "The quick brown fox jumps over the lazy dog"; my $digest_nid = Net::SSLeay::EVP_get_digestbyname('sha256'); my $sig = Net::SSLeay::RSA_sign($digest_nid, $message, $rsa); -ok(defined $sig && length $sig == 128, 'RSA_sign returns 128-byte signature'); +ok(defined $sig && length $sig == 256, 'RSA_sign returns 256-byte signature'); is(Net::SSLeay::RSA_verify($digest_nid, $message, $sig, $rsa), 1, 'RSA_verify succeeds for matching signature'); is(Net::SSLeay::RSA_verify($digest_nid, "tampered", $sig, $rsa), 0, diff --git a/src/test/resources/unit/netssleay_rsa_key_size_bounds.t b/src/test/resources/unit/netssleay_rsa_key_size_bounds.t index 95b2a4c35b..a381e88678 100644 --- a/src/test/resources/unit/netssleay_rsa_key_size_bounds.t +++ b/src/test/resources/unit/netssleay_rsa_key_size_bounds.t @@ -15,13 +15,16 @@ BEGIN { }; } -plan tests => 7; +plan tests => 10; for my $case ( [ 0, 'zero-bit RSA key' ], [ 512, '512-bit RSA key' ], - [ 1023, 'sub-1024-bit RSA key' ], + [ 1023, 'sub-2048-bit RSA key' ], + [ 1024, 'legacy 1024-bit RSA key' ], + [ 2047, 'RSA key below the 2048-bit minimum' ], [ 8193, 'RSA key above the generation limit' ], + [ 2048.5, 'fractional RSA key size' ], [ 'not-a-number', 'nonnumeric RSA key size' ], ) { my ($bits, $description) = @$case; @@ -33,7 +36,7 @@ for my $case ( ok($completed && !defined($key), "$description returns undef"); } -my $legacyKey = Net::SSLeay::RSA_generate_key(1024, 65537); -ok(defined($legacyKey), 'the bundled fast round-trip test size remains available'); -is(Net::SSLeay::RSA_size($legacyKey), 128, 'legacy 1024-bit RSA size is preserved'); -Net::SSLeay::RSA_free($legacyKey); +my $minimumKey = Net::SSLeay::RSA_generate_key(2048, 65537); +ok(defined($minimumKey), '2048-bit RSA generation is accepted at the minimum'); +is(Net::SSLeay::RSA_size($minimumKey), 256, 'minimum RSA key size is 2048 bits'); +Net::SSLeay::RSA_free($minimumKey); diff --git a/src/test/resources/unit/package_nested_untracked_aggregate_weak_lifetime.t b/src/test/resources/unit/package_nested_untracked_aggregate_weak_lifetime.t new file mode 100644 index 0000000000..0625e9382d --- /dev/null +++ b/src/test/resources/unit/package_nested_untracked_aggregate_weak_lifetime.t @@ -0,0 +1,23 @@ +use strict; +use warnings; +use Scalar::Util qw(isweak weaken); +use Test::More tests => 4; + +our @package_root; +my $weak; + +{ + my $target = []; + @package_root = ($target, $target); + $weak = $target; + weaken($weak); +} + +ok(isweak($weak), 'the observer is weak after first weaken'); +ok(defined($weak), 'package array elements keep the target alive after lexical exit'); + +$package_root[0] = undef; +ok(defined($weak), 'one remaining package element keeps the target alive'); + +$package_root[1] = undef; +ok(!defined($weak), 'the final package element release clears the weak observer'); diff --git a/src/test/resources/unit/refcount/active_callback_owner_release.t b/src/test/resources/unit/refcount/active_callback_owner_release.t new file mode 100644 index 0000000000..a3368fdead --- /dev/null +++ b/src/test/resources/unit/refcount/active_callback_owner_release.t @@ -0,0 +1,44 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); +our ($active, $weak_callback, $weak_guard, $destroyed); +$destroyed = 0; +{ package ActiveCallGuard; sub DESTROY { ++$main::destroyed } } +sub make_callback { + my ($throw) = @_; + my $guard = bless { value => 1 }, 'ActiveCallGuard'; + $weak_guard = $guard; + weaken($weak_guard); + return sub { + my ($depth) = @_; + if ($depth) { + $active->(0); + ok(defined $weak_callback, 'outer active call still owns the callback after inner return'); + ok(defined $weak_guard, 'outer call still owns the captured guard'); + } else { + undef $active; + ok(defined $weak_callback, 'active invocation owns callback after the last scalar is cleared'); + ok(defined $weak_guard, 'active callback keeps its captured guard'); + } + die "callback failed\n" if $throw; + return $guard->{value}; + }; +} +$active = make_callback(0); +$weak_callback = $active; +weaken($weak_callback); +$active->(1); +ok(!defined $weak_callback, 'final returning invocation releases its callback'); +ok(!defined $weak_guard, 'final callback release drops its captured guard'); +is($destroyed, 1, 'recursive dispatch destroys the captured guard exactly once'); + +$active = make_callback(1); +$weak_callback = $active; +weaken($weak_callback); +eval { $active->(0) }; +like($@, qr/callback failed/, 'callback exception propagates'); +ok(!defined $weak_callback, 'exception unwind releases its active callback owner'); +ok(!defined $weak_guard, 'exception unwind releases captured data'); +is($destroyed, 2, 'each captured guard is destroyed once'); +done_testing(); diff --git a/src/test/resources/unit/refcount/active_lexical_aggregate_owner_release.t b/src/test/resources/unit/refcount/active_lexical_aggregate_owner_release.t new file mode 100644 index 0000000000..d0859d3778 --- /dev/null +++ b/src/test/resources/unit/refcount/active_lexical_aggregate_owner_release.t @@ -0,0 +1,26 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +my ($weak_array, $weak_hash); + +sub create_weak_aggregate_observers { + my @array = (1, 2, 3); + my %hash = (value => 1); + + $weak_array = \@array; + $weak_hash = \%hash; + weaken($weak_array); + weaken($weak_hash); + + ok(defined($weak_array), 'array referent lives while its lexical scope is active'); + ok(defined($weak_hash), 'hash referent lives while its lexical scope is active'); +} + +create_weak_aggregate_observers(); + +ok(!defined($weak_array), 'normal scope exit clears the final weak array observer'); +ok(!defined($weak_hash), 'normal scope exit clears the final weak hash observer'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/aggregate_owner_release_preserves_lexical_contents.t b/src/test/resources/unit/refcount/aggregate_owner_release_preserves_lexical_contents.t new file mode 100644 index 0000000000..7bf627cec1 --- /dev/null +++ b/src/test/resources/unit/refcount/aggregate_owner_release_preserves_lexical_contents.t @@ -0,0 +1,26 @@ +use strict; +use warnings; +use Test::More tests => 2; +use Scalar::Util qw(weaken); + +my @weak_nodes; +my $root = bless {}, 'Local::AggregateOwnerNode'; +push @weak_nodes, $root; +weaken($weak_nodes[-1]); + +my @children; +for (1 .. 3) { + my $child = bless {}, 'Local::AggregateOwnerNode'; + push @weak_nodes, $child; + weaken($weak_nodes[-1]); + push @children, $child; +} + +$root->{children} = \@children; +is(scalar(grep { defined $_ } @weak_nodes), 4, + 'the lexical array and parent hash keep all child values alive'); + +$root = undef; +@children = (); +is(scalar(grep { defined $_ } @weak_nodes), 0, + 'dropping both strong owners releases all children'); diff --git a/src/test/resources/unit/refcount/anonymous_code_attribute_capture_release.t b/src/test/resources/unit/refcount/anonymous_code_attribute_capture_release.t new file mode 100644 index 0000000000..875ee9d7f9 --- /dev/null +++ b/src/test/resources/unit/refcount/anonymous_code_attribute_capture_release.t @@ -0,0 +1,42 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 3; + +our $DESTROY_COUNT = 0; + +{ + package Issue1649AttributeCapture::Probe; + + sub DESTROY { + ++$main::DESTROY_COUNT; + } +} + +{ + package Issue1649AttributeCapture; + + sub MODIFY_CODE_ATTRIBUTES { + return; + } +} + +my $weak; +my $closure; +{ + package Issue1649AttributeCapture; + + my $object = bless {}, 'Issue1649AttributeCapture::Probe'; + $weak = $object; + Scalar::Util::weaken($weak); + $closure = sub : PreservePrototype { $object }; +} + +package main; + +ok(defined $weak, 'the returned closure retains its captured value'); +undef $closure; +ok(!defined $weak, 'releasing the attributed closure releases its captured pad'); +is($DESTROY_COUNT, 1, 'captured object is destroyed exactly once'); + +done_testing; diff --git a/src/test/resources/unit/refcount/anonymous_hash_argument_releases_contents.t b/src/test/resources/unit/refcount/anonymous_hash_argument_releases_contents.t new file mode 100644 index 0000000000..98fb67d3c8 --- /dev/null +++ b/src/test/resources/unit/refcount/anonymous_hash_argument_releases_contents.t @@ -0,0 +1,42 @@ +use strict; +use warnings; +use Test::More tests => 2; +use Scalar::Util qw(weaken); + +{ + package Refcount::AnonymousHashArgumentTarget; + sub new { bless {}, shift } +} + +sub consume_hash { return scalar keys %{ $_[0] } } +sub consume_nested_hash { return scalar keys %{ $_[0]{args} } } + +my $target = Refcount::AnonymousHashArgumentTarget->new; +my $weak = $target; +weaken($weak); +consume_hash({ + self_result_object => $target, + condition => sub { 1 }, + rel_name => 'artist', + self_alias => 'me', + foreign_alias => 'artist', + require_join_free_condition => 1, +}); +undef $target; +ok(!defined $weak, 'anonymous hash argument releases its strong values'); + +my $nested_target = Refcount::AnonymousHashArgumentTarget->new; +my $nested_weak = $nested_target; +weaken($nested_weak); +consume_nested_hash({ + args => { + self_result_object => $nested_target, + condition => sub { 1 }, + rel_name => 'artist', + self_alias => 'me', + foreign_alias => 'artist', + require_join_free_condition => 1, + }, +}); +undef $nested_target; +ok(!defined $nested_weak, 'nested anonymous hash argument releases its strong values'); diff --git a/src/test/resources/unit/refcount/argument_alias_nested_lvalue_destroy_order.t b/src/test/resources/unit/refcount/argument_alias_nested_lvalue_destroy_order.t new file mode 100644 index 0000000000..a34dc2326c --- /dev/null +++ b/src/test/resources/unit/refcount/argument_alias_nested_lvalue_destroy_order.t @@ -0,0 +1,83 @@ +use strict; +use warnings; +use Test::More tests => 4; + +our $destroy_count = 0; +my $output = ''; +open my $capture, '>', \$output or die "cannot capture stdout: $!"; + +{ + local *STDOUT = $capture; + + package Thing; + + sub new_hash { bless {}, shift } + sub new_array { bless [], shift } + + sub DESTROY { + $main::destroy_count++; + print "DESTROY\n"; + } + + package main; + + our $v; + our $a; + our $s; + + sub inspect { + print "inside before undef\n"; + undef $main::v; + print "inside after undef: ", + defined($_[0]) ? "defined\n" : "undef\n"; + } + + sub inspect_array { + print "inside array before undef\n"; + undef $main::a; + print "inside array after undef: ", + defined($_[0]) ? "defined\n" : "undef\n"; + } + + sub inspect_shift { + print "inside shift before undef\n"; + undef $main::s; + print "inside shift after undef: ", + defined($_[0]) ? "defined\n" : "undef\n"; + print "before shift\n"; + shift @_; + print "after shift\n"; + } + + $v = Thing->new_hash; + print "before call\n"; + inspect($v->{a}); + print "after call\n"; + + $a = Thing->new_array; + print "before array call\n"; + inspect_array($a->[0]); + print "after array call\n"; + + $s = Thing->new_hash; + print "before shift call\n"; + inspect_shift($s->{a}); + print "after shift call\n"; +} + +like( + $output, + qr/\Abefore call\ninside before undef\ninside after undef: undef\nDESTROY\nafter call\n/, + 'an argument alias retains its containing hash through the callee', +); +like( + $output, + qr/before array call\ninside array before undef\ninside array after undef: undef\nDESTROY\nafter array call\n/, + 'an argument alias retains its containing array through the callee', +); +like( + $output, + qr/before shift call\ninside shift before undef\ninside shift after undef: undef\nbefore shift\nafter shift\nDESTROY\nafter shift call\n\z/, + 'removing an alias from @_ keeps its containing hash until the frame exits', +); +is($destroy_count, 3, 'each aggregate is destroyed once after its argument frame releases it'); diff --git a/src/test/resources/unit/refcount/argument_array_clear_borrowed_cells.t b/src/test/resources/unit/refcount/argument_array_clear_borrowed_cells.t new file mode 100644 index 0000000000..f22f9a9302 --- /dev/null +++ b/src/test/resources/unit/refcount/argument_array_clear_borrowed_cells.t @@ -0,0 +1,24 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken isweak); +our @destroyed; +{ package BorrowedArgumentGuard; sub DESTROY { push @main::destroyed, $_[0]{name} } } +sub clear_and_weaken_copy { + my ($copy, $how) = @_; + if ($how eq 'assign') { @_ = () } else { undef @_ } + weaken($copy); + ok(isweak($copy), "$how leaves the independently weakened copy alive"); +} +for my $how ('assign', 'undef') { + my $owner = bless { name => $how }, 'BorrowedArgumentGuard'; + my $weak = $owner; + weaken($weak); + clear_and_weaken_copy($owner, $how); + ok(defined $weak, "$how of arguments preserves the caller's counted owner"); + is($owner->{name}, $how, "$how preserves the caller's value"); + undef $owner; + ok(!defined $weak, "$how leaves exactly one caller owner to release"); +} +is_deeply(\@destroyed, ['assign', 'undef'], 'caller owners are destroyed exactly once'); +done_testing(); diff --git a/src/test/resources/unit/refcount/argument_evaluation_return.t b/src/test/resources/unit/refcount/argument_evaluation_return.t new file mode 100644 index 0000000000..5ed4043039 --- /dev/null +++ b/src/test/resources/unit/refcount/argument_evaluation_return.t @@ -0,0 +1,60 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +our (%weak, %destroyed, $entered); +$entered = 0; +{ package ArgumentReturnGuard; sub DESTROY { ++$main::destroyed{$_[0]{name}} } } +{ package ArgumentReturnReceiver; sub accept { ++$main::entered } } +sub make_argument { + my ($name) = @_; + my $object = bless { name => $name }, 'ArgumentReturnGuard'; + $weak{$name} = $object; + weaken($weak{$name}); + return $object; +} +sub escape_scalar { + ArgumentReturnReceiver->accept(make_argument('scalar'), do { return 'escaped' }); + die 'unreachable'; +} +is(escape_scalar(), 'escaped', 'return during argument evaluation leaves the containing sub'); +is($entered, 0, 'return during arguments never enters the callee'); +ok(!defined $weak{scalar}, 'return releases the abandoned argument'); +is($destroyed{scalar}, 1, 'return destroys the abandoned argument once'); + +sub escape_reference { + ArgumentReturnReceiver->accept(make_argument('reference'), do { + return make_argument('result'); + }); + die 'unreachable'; +} +my $result = escape_reference(); +is($entered, 0, 'reference return also bypasses the callee'); +ok(!defined $weak{reference}, 'reference return releases the abandoned argument'); +is($destroyed{reference}, 1, 'reference return destroys the abandoned argument once'); +ok(defined $weak{result}, 'receiving caller owns the returned reference'); +is($result->{name}, 'result', 'returned reference keeps its contents'); +undef $result; +ok(!defined $weak{result}, 'returned reference is released by its receiver'); +is($destroyed{result}, 1, 'returned reference is destroyed once'); + +sub escape_map { + my @unused = map { + ArgumentReturnReceiver->accept(make_argument('map'), do { + return make_argument('map-result'); + }); + } 1; + die 'unreachable'; +} +my $map_result = escape_map(); +is($entered, 0, 'non-local map return bypasses the callee'); +ok(!defined $weak{map}, 'non-local return releases the abandoned argument'); +is($destroyed{map}, 1, 'non-local return destroys the abandoned argument once'); +ok(defined $weak{'map-result'}, 'non-local return preserves its receiving owner'); +is($map_result->{name}, 'map-result', 'non-local return preserves result contents'); +undef $map_result; +ok(!defined $weak{'map-result'}, 'receiver releases the non-local return result'); +is($destroyed{'map-result'}, 1, 'non-local return result is destroyed once'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/argument_evaluation_unwind.t b/src/test/resources/unit/refcount/argument_evaluation_unwind.t new file mode 100644 index 0000000000..46371f0b3a --- /dev/null +++ b/src/test/resources/unit/refcount/argument_evaluation_unwind.t @@ -0,0 +1,60 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +our (%weak, %destroyed, $entered); +$entered = 0; +{ + package ArgumentUnwindGuard; + sub DESTROY { ++$main::destroyed{$_[0]{name}} } +} +{ + package ArgumentUnwindReceiver; + sub accept { ++$main::entered; return scalar @_ } + sub reject { ++$main::entered; die "callee failed\n" } +} +sub make_argument { + my ($name) = @_; + my $object = bless { name => $name }, 'ArgumentUnwindGuard'; + $weak{$name} = $object; + weaken($weak{$name}); + return $object; +} +sub make_pair { + my $object = make_argument('pair'); + return ($object, $object); +} + +eval { ArgumentUnwindReceiver->accept(make_argument('abandoned'), die "later failed\n") }; +like($@, qr/later failed/, 'later argument failure propagates'); +is($entered, 0, 'failure during arguments never enters the callee'); +ok(!defined $weak{abandoned}, 'abandoned earlier argument releases its referent'); +is($destroyed{abandoned}, 1, 'abandoned referent is destroyed exactly once'); + +eval { ArgumentUnwindReceiver->accept(make_pair(), die "pair failed\n") }; +like($@, qr/pair failed/, 'failure after a repeated return list propagates'); +is($entered, 0, 'failed list arguments never enter the callee'); +ok(!defined $weak{pair}, 'all repeated argument owners are released'); +is($destroyed{pair}, 1, 'repeated argument edges destroy their referent once'); + +my $result = ArgumentUnwindReceiver->accept(make_argument('outer'), do { + eval { ArgumentUnwindReceiver->accept(make_argument('inner'), die "inner failed\n") }; + like($@, qr/inner failed/, 'inner argument failure is caught locally'); + ok(!defined $weak{inner}, 'inner abandoned argument is released'); + ok(defined $weak{outer}, 'inner unwinding preserves the outer staged argument'); + 1; +}); +is($result, 3, 'outer call receives its invocant and both arguments'); +is($entered, 1, 'only the outer call entered the callee'); +is($destroyed{inner}, 1, 'inner referent is destroyed once'); +ok(!defined $weak{outer}, 'successful outer call releases its temporary argument'); +is($destroyed{outer}, 1, 'outer referent is destroyed once'); + +eval { ArgumentUnwindReceiver->reject(make_argument('callee')) }; +like($@, qr/callee failed/, 'callee exception propagates'); +is($entered, 2, 'throwing callee was entered once'); +ok(!defined $weak{callee}, 'callee exception releases the argument'); +is($destroyed{callee}, 1, 'callee exception destroys the argument once'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/array_delete_middle_owner_release.t b/src/test/resources/unit/refcount/array_delete_middle_owner_release.t new file mode 100644 index 0000000000..142108fd4b --- /dev/null +++ b/src/test/resources/unit/refcount/array_delete_middle_owner_release.t @@ -0,0 +1,32 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); +{ + package DeleteMiddleOwnerTracker; + our $DESTROY_COUNT = 0; + sub DESTROY { ++$DESTROY_COUNT } +} + +my $array = [undef, bless({}, 'DeleteMiddleOwnerTracker'), undef]; +my $weak = $array->[1]; +weaken($weak); +my $deleted = delete $array->[1]; +is($DeleteMiddleOwnerTracker::DESTROY_COUNT, 0, + 'delete result retains the removed value'); +ok(defined $weak, 'weak observer remains while the returned value is live'); +undef $deleted; +is($DeleteMiddleOwnerTracker::DESTROY_COUNT, 1, + 'removed value is destroyed after its returned owner is released'); +ok(!defined $weak, 'weak observer clears after the final owner leaves'); + +my $void_array = [undef, bless({}, 'DeleteMiddleOwnerTracker'), undef]; +my $void_weak = $void_array->[1]; +weaken($void_weak); +delete $void_array->[1]; +is($DeleteMiddleOwnerTracker::DESTROY_COUNT, 2, + 'void-context middle delete releases its removed value'); +ok(!defined $void_weak, + 'void-context middle delete clears the final weak observer'); + +done_testing; diff --git a/src/test/resources/unit/refcount/b_object_wrapper_non_owning.t b/src/test/resources/unit/refcount/b_object_wrapper_non_owning.t new file mode 100644 index 0000000000..8a21f02cdf --- /dev/null +++ b/src/test/resources/unit/refcount/b_object_wrapper_non_owning.t @@ -0,0 +1,23 @@ +use strict; +use warnings; +use B qw(svref_2object); +use Test::More; + +our $destroyed = 0; +our $wrapper; + +{ + package Issue2043::BWrapperTarget; + sub DESTROY { $main::destroyed++ } +} + +{ + my $target = bless {}, 'Issue2043::BWrapperTarget'; + $wrapper = B::svref_2object($target); +} + +is($destroyed, 1, + 'a retained B::SV wrapper does not keep its Perl referent alive'); +ok($wrapper, 'the non-owning B::SV wrapper itself remains available'); + +done_testing; diff --git a/src/test/resources/unit/refcount/b_refcount_destroy_aggregate_owner.t b/src/test/resources/unit/refcount/b_refcount_destroy_aggregate_owner.t new file mode 100644 index 0000000000..57ec926f95 --- /dev/null +++ b/src/test/resources/unit/refcount/b_refcount_destroy_aggregate_owner.t @@ -0,0 +1,90 @@ +use strict; +use warnings; +use Test::More; +use B qw(svref_2object); +use Scalar::Util qw(weaken isweak); + +our @observed_refcounts; +our @retained_b_wrappers; +our @nested_refcounts; + +sub issue1649_nested_refcount { + return B::svref_2object($_[0])->REFCNT; +} + +{ + package Issue1649::BRefcountDestroyOwner; + + sub DESTROY { + push @main::observed_refcounts, + B::svref_2object($_[0]{child})->REFCNT; + } +} + +{ + my $owner = bless { + child => bless({}, 'Issue1649::BRefcountDestroyChild'), + }, 'Issue1649::BRefcountDestroyOwner'; + undef $owner; +} +is(shift @observed_refcounts, 1, + 'B::SV::REFCNT reports one hash-element owner during DESTROY'); + +{ + my $child = bless({}, 'Issue1649::BRefcountDestroyChild'); + my $owner = bless { child => $child }, 'Issue1649::BRefcountDestroyOwner'; + undef $owner; +} +is(shift @observed_refcounts, 2, + 'B::SV::REFCNT preserves an independent lexical owner during DESTROY'); + +{ + my $owner = bless { + child => bless({}, 'Issue1649::BRefcountDestroyChild'), + }, 'Issue1649::BRefcountDestroyOwner'; + push @retained_b_wrappers, + B::svref_2object($owner->{child}), + B::svref_2object($owner->{child}); + undef $owner; +} +is(shift @observed_refcounts, 1, + 'overlapping B::SV wrappers do not become extra Perl owners during DESTROY'); +@retained_b_wrappers = (); + +{ + package Issue1649::RescuedSource; + sub DESTROY { + if (defined $_[0]{schema} && !Scalar::Util::isweak($_[0]{schema})) { + Scalar::Util::weaken($_[0]{schema}); + } + } + + package Issue1649::RescuedSchema; + sub DESTROY { + my $self = $_[0]; + my $source = $self->{source_registrations}{Artist}; + return unless ref $source; + my $count = main::issue1649_nested_refcount($source); + push @main::nested_refcounts, $count; + if ($count > 1) { + $source->{schema} = $self; + Scalar::Util::weaken($self->{source_registrations}{Artist}) + unless Scalar::Util::isweak($self->{source_registrations}{Artist}); + } + } +} + +{ + my $schema = bless { source_registrations => {} }, 'Issue1649::RescuedSchema'; + my $source = bless { schema => $schema }, 'Issue1649::RescuedSource'; + weaken($source->{schema}); + $schema->{source_registrations}{Artist} = $source; + my $row = $source; + undef $source; + undef $schema; + undef $row; +} +is_deeply(\@nested_refcounts, [3, 2], + 'nested Schema and source destruction ignore overlapping argument-frame owners'); + +done_testing; diff --git a/src/test/resources/unit/refcount/b_refcount_destroy_aliased_hash_slot_argument.t b/src/test/resources/unit/refcount/b_refcount_destroy_aliased_hash_slot_argument.t new file mode 100644 index 0000000000..16ff5655c0 --- /dev/null +++ b/src/test/resources/unit/refcount/b_refcount_destroy_aliased_hash_slot_argument.t @@ -0,0 +1,51 @@ +use strict; +use warnings; +use B qw(svref_2object); +our @observed_refcounts; + +sub refcount ($) { + return svref_2object($_[0])->REFCNT; +} + +{ + package Issue2043::NestedRefcountOwner; + + sub DESTROY { + my $self = shift; + my $sources = $self->{sources}; + push @main::observed_refcounts, main::refcount($sources->{source}); + } + + package Issue2043::NestedRefcountSource; + sub DESTROY { } +} + +{ + my $holder = bless { + sources => { source => bless({}, 'Issue2043::NestedRefcountSource') }, + }, 'Issue2043::NestedRefcountOwner'; +} + +{ + package Issue2043::NestedRefcountOwnerWithoutChildDestroy; + + sub DESTROY { + my $self = shift; + my $sources = $self->{sources}; + push @main::observed_refcounts, main::refcount($sources->{source}); + } +} + +{ + my $holder = bless { + sources => { source => bless({}, 'Issue2043::NestedRefcountSourceWithoutDestroy') }, + }, 'Issue2043::NestedRefcountOwnerWithoutChildDestroy'; +} + +# Loading Test::More before the probe changes the runtime's count of objects +# created while loading its assertion stack. Keep the observed destructor +# scenario minimal, then load the assertion helper after the measurement. +require Test::More; +Test::More::plan(tests => 1); +Test::More::is_deeply(\@observed_refcounts, [2, 2], + 'DESTROY-time B::SV::REFCNT includes the nested aggregate owner'); diff --git a/src/test/resources/unit/refcount/blessed_code_state_resurrection.t b/src/test/resources/unit/refcount/blessed_code_state_resurrection.t new file mode 100644 index 0000000000..3f5ff6f1e9 --- /dev/null +++ b/src/test/resources/unit/refcount/blessed_code_state_resurrection.t @@ -0,0 +1,37 @@ +use strict; +use warnings; +use feature 'state'; +use Scalar::Util qw(weaken); +use Test::More; +our ($rescued, $weak, $initialized, $code_destroyed, $metadata_destroyed); +our @during_destroy; +($initialized, $code_destroyed, $metadata_destroyed) = (0, 0, 0); +{ + package CodeStateMetadata; + sub DESTROY { ++$main::metadata_destroyed } + package ResurrectedStateCode; + sub DESTROY { + push @main::during_destroy, defined($main::weak) ? 'live' : 'gone'; + ++$main::code_destroyed; + $main::rescued = $_[0] if $main::code_destroyed == 1; + } +} +my $callback = do { + my $seed = 41; + sub { state $metadata = bless { serial => ++$initialized, value => $seed }, 'CodeStateMetadata'; $metadata } +}; +bless $callback, 'ResurrectedStateCode'; +$weak = $callback->(); weaken($weak); +is($initialized, 1, 'state initialized once'); +undef $callback; +is($code_destroyed, 1, 'first CODE owner release invokes DESTROY'); +ok(defined $weak, 'resurrected CODE retains state'); +is($rescued->()->{serial}, 1, 'resurrected CODE uses original state'); +is($initialized, 1, 'resurrection does not initialize replacement state'); +is($metadata_destroyed, 0, 'state metadata survives first CODE DESTROY'); +undef $rescued; +is($code_destroyed, 2, 'last resurrected CODE owner invokes DESTROY again'); +is_deeply(\@during_destroy, ['live', 'live'], 'state survives both CODE destructor callbacks'); +ok(!defined $weak, 'final CODE destruction releases weak state'); +is($metadata_destroyed, 1, 'state metadata destroyed exactly once'); +done_testing(); diff --git a/src/test/resources/unit/refcount/blessed_glob_alias_owner_release.t b/src/test/resources/unit/refcount/blessed_glob_alias_owner_release.t new file mode 100644 index 0000000000..08653a442b --- /dev/null +++ b/src/test/resources/unit/refcount/blessed_glob_alias_owner_release.t @@ -0,0 +1,27 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken isweak); +use Test::More tests => 5; + +our $destroyed = 0; +{ + package Local::BlessedGlobAliasOwner; + sub DESTROY { ++$main::destroyed } +} + +my $buffer = ''; +my $handle; +open $handle, '>', \$buffer or die "open scalar handle: $!"; +my $alias = $handle; +my $weak = $handle; +weaken($weak); +bless $weak, 'Local::BlessedGlobAliasOwner'; +ok(isweak($weak), 'observer is weak'); + +undef $handle; +ok(defined($weak), 'second live glob alias retains the referent'); +is($destroyed, 0, 'DESTROY waits for the remaining alias'); + +undef $alias; +ok(!defined($weak), 'weak observer clears with the last alias'); +is($destroyed, 1, 'last alias release dispatches DESTROY once'); diff --git a/src/test/resources/unit/refcount/block_hash_deref_postincrement.t b/src/test/resources/unit/refcount/block_hash_deref_postincrement.t new file mode 100644 index 0000000000..de7938f6ca --- /dev/null +++ b/src/test/resources/unit/refcount/block_hash_deref_postincrement.t @@ -0,0 +1,18 @@ +use strict; +use warnings; +use Test::More tests => 4; +use Symbol qw(gensym); + +my $self = gensym(); +bless $self, 'Local::Socket'; + +my $old = ${*$self}{io_socket_ip_idx}++; +is($old, 0, 'postincrement returns zero for an undefined glob hash element'); +is(${*$self}{io_socket_ip_idx}, 1, 'postincrement stores the incremented glob hash element'); + +{ + no strict 'refs'; + my $loose_old = ${*$self}{loose_idx}++; + is($loose_old, 0, 'loose-ref postincrement returns zero for an undefined glob hash element'); + is(${*$self}{loose_idx}, 1, 'loose-ref postincrement stores the incremented glob hash element'); +} diff --git a/src/test/resources/unit/refcount/captured_cell_owner_replacement_order.t b/src/test/resources/unit/refcount/captured_cell_owner_replacement_order.t new file mode 100644 index 0000000000..0ce9c603d6 --- /dev/null +++ b/src/test/resources/unit/refcount/captured_cell_owner_replacement_order.t @@ -0,0 +1,25 @@ +use strict; +use warnings; +use Test::More tests => 2; + +package Issue1649::CapturedCellOld; +sub new { bless { name => $_[1] }, $_[0] } +sub DESTROY { + my ($self) = @_; + return unless $self->{name} eq 'old'; + my $current = $main::reader->(); + $main::observed_capture = $current->{name}; +} + +package Issue1649::CapturedCellNew; +sub new { bless { name => $_[1] }, $_[0] } + +package main; +our ($reader, $observed_capture); +my $captured = Issue1649::CapturedCellOld->new('old'); +$reader = sub { $captured }; +$captured = Issue1649::CapturedCellNew->new('new'); + +is($observed_capture, 'new', + 'the displaced capture value is destroyed after the captured cell is updated'); +is($reader->()->{name}, 'new', 'the closure reads the replacement value'); diff --git a/src/test/resources/unit/refcount/catalyst_stats_imported_cv_lifetime.t b/src/test/resources/unit/refcount/catalyst_stats_imported_cv_lifetime.t new file mode 100644 index 0000000000..4fd624f4ba --- /dev/null +++ b/src/test/resources/unit/refcount/catalyst_stats_imported_cv_lifetime.t @@ -0,0 +1,29 @@ +use strict; +use warnings; +use Test::More; + +BEGIN { + # Use the installed CPAN module rather than the small Catalyst test fixture + # in unit/lib, which does not provide the complete MOP implementation. + @INC = grep { + ref($_) || $_ !~ m{(?:^|[/\\])src/test/resources/unit/lib/?\z} + } @INC; + + my $available = eval { + require Catalyst::Stats; + require Tree::Simple; + 1; + }; + plan skip_all => 'Catalyst::Stats test dependencies are not installed' unless $available; +} + +my $stats; +my $error; +eval { + $stats = Catalyst::Stats->new; + 1; +} or $error = $@; + +ok($stats, 'Catalyst::Stats can call its imported clock CV from a stored default'); +diag($error) unless $stats; +done_testing; diff --git a/src/test/resources/unit/refcount/cloned_related_resultset_source_owner.t b/src/test/resources/unit/refcount/cloned_related_resultset_source_owner.t new file mode 100644 index 0000000000..e3c1b1fadb --- /dev/null +++ b/src/test/resources/unit/refcount/cloned_related_resultset_source_owner.t @@ -0,0 +1,162 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); +use B (); + +sub dbic_refcount ($) { B::svref_2object($_[0])->REFCNT } + +{ + package Issue2043::Source; + + sub new { + my ($class, $name, $related, $schema) = @_; + my $self = bless { name => $name, related => $related }, $class; + $self->{schema} = $schema; + Scalar::Util::weaken($self->{schema}); + return $self; + } + + sub clone_for_schema { + my ($self, $schema) = @_; + my $copy = bless { %$self }, ref $self; + $copy->{schema} = $schema; + Scalar::Util::weaken($copy->{schema}); + return $copy; + } + + sub schema { + $_[0]->{schema} = $_[1] if @_ > 1; + die "detached source '$_[0]->{name}'" unless $_[0]->{schema}; + $_[0]->{schema}; + } + + sub resultset { Issue2043::ResultSet->new($_[0]) } + + sub related_source { + my ($self, $relationship) = @_; + my $schema = $self->schema; + my $name = $self->{related}{$relationship} + or die "missing relationship $relationship"; + $schema->{sources}{$name}; + } + + sub DESTROY { + return unless ref $_[0]->{schema} + && !Scalar::Util::isweak($_[0]->{schema}); + Scalar::Util::weaken($_[0]->{schema}); + if ($_[0]->{schema}) { + my $sources = $_[0]->{schema}->{sources}; + for (keys %$sources) { + $sources->{$_} = $_[0] if $sources->{$_} && $sources->{$_} == $_[0]; + } + } + } +} + +{ + package Issue2043::Schema; + + sub new { + my $self = bless { sources => {} }, $_[0]; + $self->{sources}{Artist} = Issue2043::Source->new( + 'Artist', { cds => 'CD' }, $self); + $self->{sources}{CD} = Issue2043::Source->new( + 'CD', { artist => 'Artist' }, $self); + $self; + } + + sub source { $_[0]->{sources}{$_[1]} } + sub resultset { Issue2043::ResultSet->new($_[0]->source($_[1])) } + + sub clone { + my $self = shift; + my $copy = bless { %$self, sources => {} }, ref $self; + for my $name (keys %{$self->{sources}}) { + $copy->{sources}{$name} = $self->{sources}{$name}->clone_for_schema($copy); + } + $copy; + } + + sub DESTROY { + my $self = shift; + my $sources = $self->{sources}; + for my $name (keys %$sources) { + my $count = length ref $sources->{$name} + ? main::dbic_refcount($sources->{$name}) : 0; + if ($count > 1) { + $sources->{$name}->schema($self); + Scalar::Util::weaken($sources->{$name}); + last; + } + } + } +} + +{ + package Issue2043::ResultSet; + + sub new { bless { source => $_[1] }, $_[0] } + sub result_source { $_[0]->{source} } + sub search { Issue2043::ResultSet->new($_[0]->{source}) } + + sub next { + my $self = shift; + $self->{source}->schema; + Issue2043::Row->new($self->{source}); + } +} + +{ + package Issue2043::Row; + + sub new { bless { result_source => $_[1], related_resultsets => {} }, $_[0] } + sub result_source { $_[0]->{result_source} } + + sub related_resultset { + my ($self, $relationship) = @_; + return $self->{related_resultsets}{$relationship} + if defined $self->{related_resultsets}{$relationship}; + my $source = $self->result_source->related_source($relationship); + $self->{related_resultsets}{$relationship} = + Issue2043::ResultSet->new($source); + } + + sub artist { $_[0]->related_resultset('artist')->next } + sub search_related { $_[0]->related_resultset($_[1])->search } +} + +my $phantom; +my @chain = ( + sub { Issue2043::Schema->new }, + sub { shift->source('Artist') }, + sub { shift->resultset }, + sub { shift->result_source }, + sub { shift->schema }, + sub { shift->resultset('Artist') }, + sub { shift->next }, + sub { shift->result_source }, + sub { shift->schema }, + sub { shift->clone }, + sub { shift->resultset('CD') }, + sub { shift->next }, + sub { shift->artist }, + sub { shift->search_related('cds') }, + sub { shift->next }, +); + +my $error; +eval { + for my $index (0 .. $#chain) { + $phantom = $chain[$index]->($phantom); + } + 1; +} or $error = $@; + +ok(!$error, 'related ResultSet keeps its source attached through the owner transfer') + or diag($error); +ok($phantom && $phantom->result_source->schema, + 'the returned related row still has an attached source') + unless $error; + +done_testing; diff --git a/src/test/resources/unit/refcount/closure_capture_multiple_unweaken_owner.t b/src/test/resources/unit/refcount/closure_capture_multiple_unweaken_owner.t new file mode 100644 index 0000000000..ea5be1a544 --- /dev/null +++ b/src/test/resources/unit/refcount/closure_capture_multiple_unweaken_owner.t @@ -0,0 +1,36 @@ +use strict; +use warnings; + +use Scalar::Util qw(weaken unweaken); +use Test::More; + +our $DESTROYED = 0; +{ + package MultipleUnweakenCaptureOwner; + sub DESTROY { ++$main::DESTROYED } +} + +my ($weak, $reader, $writer); +{ + my $object = bless {}, 'MultipleUnweakenCaptureOwner'; + my $value = $object; + $weak = $object; + weaken($weak); + + $reader = sub { $value }; + $writer = sub { $value = $_[0] if @_; return $value }; + weaken($value); + unweaken($value); + undef $object; +} + +ok(defined $weak, 'the shared captured pad keeps the unweakened referent alive'); +is(ref($reader->()), 'MultipleUnweakenCaptureOwner', 'the reader sees the shared referent'); +undef $reader; +ok(defined $weak, 'one remaining closure still owns the captured pad'); +is(ref($writer->()), 'MultipleUnweakenCaptureOwner', 'the writer sees the shared referent'); +undef $writer; +ok(!defined $weak, 'the weak observer clears after the final closure is released'); +is($DESTROYED, 1, 'the final captured referent is destroyed exactly once'); + +done_testing; diff --git a/src/test/resources/unit/refcount/closure_state_owner_release.t b/src/test/resources/unit/refcount/closure_state_owner_release.t new file mode 100644 index 0000000000..54e36751d1 --- /dev/null +++ b/src/test/resources/unit/refcount/closure_state_owner_release.t @@ -0,0 +1,54 @@ +use strict; +use warnings; +use feature 'state'; +use Scalar::Util qw(weaken); +use Test::More; + +sub scalar_callback { + my ($seed) = @_; + return sub { state $metadata = { value => $seed }; return $metadata }; +} +my $callback = scalar_callback(1); +my $weak = $callback->(); weaken($weak); +my $keeper = $callback; +undef $callback; +ok(defined $weak, 'another CODE owner preserves scalar state'); +is($keeper->()->{value}, 1, 'remaining CODE owner can use scalar state'); +undef $keeper; +ok(!defined $weak, 'final CODE owner releases scalar state'); + +sub array_callback { + my ($seed) = @_; + return sub { state @items = ({ value => $seed }); return \@items }; +} +$callback = array_callback(2); +$weak = $callback->()->[0]; weaken($weak); +undef $callback; +ok(!defined $weak, 'final CODE owner releases state array contents'); + +sub hash_callback { + my ($seed) = @_; + return sub { state %items = (item => { value => $seed }); return \%items }; +} +$callback = hash_callback(3); +my $escaped = $callback->(); +$weak = $escaped->{item}; weaken($weak); +undef $callback; +ok(defined $weak, 'escaped state hash retains its contents after CODE release'); +is($escaped->{item}{value}, 3, 'escaped state hash remains usable'); +undef $escaped; +ok(!defined $weak, 'last escaped hash owner releases its contents'); + +sub scalar_cell_callback { + my ($seed) = @_; + return sub { state $item = { value => $seed }; return \$item }; +} +$callback = scalar_cell_callback(4); +$escaped = $callback->(); +$weak = $$escaped; weaken($weak); +undef $callback; +ok(defined $weak, 'escaped state scalar cell retains its contents'); +is($$escaped->{value}, 4, 'escaped state scalar cell remains usable'); +undef $escaped; +ok(!defined $weak, 'last scalar cell owner releases its contents'); +done_testing(); diff --git a/src/test/resources/unit/refcount/code_return_argument_snapshot.t b/src/test/resources/unit/refcount/code_return_argument_snapshot.t new file mode 100644 index 0000000000..30f253c121 --- /dev/null +++ b/src/test/resources/unit/refcount/code_return_argument_snapshot.t @@ -0,0 +1,21 @@ +use strict; +use warnings; +use Test::More tests => 4; + +my $callback = sub { 'before' }; +sub fetch_callback { return $callback } +sub replace_callback { $callback = sub { 'after' }; return 1 } +sub invoke_first { return $_[0]->() } + +is(invoke_first(fetch_callback(), replace_callback()), 'before', + 'a returned coderef is copied before the next argument changes its source'); +is($callback->(), 'after', 'the source coderef remains independently writable'); + +$callback = sub { 'list-before' }; +sub fetch_pair { return ($callback, $callback) } +sub replace_pair { $callback = sub { 'list-after' }; return 1 } +sub invoke_pair { return join '/', $_[0]->(), $_[1]->() } + +is(invoke_pair(fetch_pair(), replace_pair()), 'list-before/list-before', + 'each returned list element keeps its value through later argument evaluation'); +is($callback->(), 'list-after', 'list return copies do not alias the source cell'); diff --git a/src/test/resources/unit/refcount/code_template_owner_lifetime.t b/src/test/resources/unit/refcount/code_template_owner_lifetime.t new file mode 100644 index 0000000000..ee88032da5 --- /dev/null +++ b/src/test/resources/unit/refcount/code_template_owner_lifetime.t @@ -0,0 +1,27 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); +my $plain = sub { 42 }; +my $weak = $plain; +weaken($weak); +$plain->(); +undef $plain; +ok(defined $weak, 'noncapturing anonymous CODE remains owned by its optree'); +my $constant = sub () { 42 }; +$weak = $constant; +weaken($weak); +$constant->(); +undef $constant; +ok(defined $weak, 'constant anonymous CODE remains owned by its optree'); +sub make_counter { + my $value = 0; + return sub { ++$value }; +} +my $capturing = make_counter(); +$weak = $capturing; +weaken($weak); +is($capturing->(), 1, 'capturing callback remains callable'); +undef $capturing; +ok(!defined $weak, 'last counted owner releases an inactive capturing callback'); +done_testing(); diff --git a/src/test/resources/unit/refcount/compiled_callsite_code_owner_release.t b/src/test/resources/unit/refcount/compiled_callsite_code_owner_release.t new file mode 100644 index 0000000000..3873c8e982 --- /dev/null +++ b/src/test/resources/unit/refcount/compiled_callsite_code_owner_release.t @@ -0,0 +1,28 @@ +use strict; +use warnings; +use Test::More tests => 4; +use Scalar::Util qw(weaken); + +eval q{ + package Ownership::CallSiteLifetimeCallee; + sub target { 42 } + 1; +} or die $@; + +# Resolve this at runtime so the test itself does not compile a separate direct +# reference to the CV into its main optree. +my $weak_callee = \&{'Ownership::CallSiteLifetimeCallee::target'}; +weaken($weak_callee); + +my $compiled_caller = eval q{ + sub { Ownership::CallSiteLifetimeCallee::target() } +}; +die $@ unless $compiled_caller; +ok(defined $weak_callee, 'the named CV starts alive'); + +delete $Ownership::CallSiteLifetimeCallee::{target}; +ok(defined $weak_callee, 'the compiled caller keeps the deleted callee alive'); +is($compiled_caller->(), 42, 'the compiled callsite still invokes the deleted CV'); + +undef $compiled_caller; +ok(!defined $weak_callee, 'dropping the compiled caller releases its callee owner'); diff --git a/src/test/resources/unit/refcount/compiled_glob_state_owner_release.t b/src/test/resources/unit/refcount/compiled_glob_state_owner_release.t new file mode 100644 index 0000000000..d5d08d6836 --- /dev/null +++ b/src/test/resources/unit/refcount/compiled_glob_state_owner_release.t @@ -0,0 +1,14 @@ +use strict; +use warnings; +use feature 'state'; +use Scalar::Util qw(weaken); +use Test::More; +our $initialized = 0; +sub pinned_metadata { state $metadata = { serial => ++$initialized }; $metadata } +my $weak = pinned_metadata(); weaken($weak); +delete $main::{pinned_metadata}; +ok(defined $weak, 'compiled GV owner preserves state after stash name deletion'); +is(pinned_metadata()->{serial}, 1, 'compiled call uses original state after stash deletion'); +is($initialized, 1, 'stash deletion does not initialize replacement state'); +ok(defined $weak, 'original state remains owned by the compiled call site'); +done_testing(); diff --git a/src/test/resources/unit/refcount/conditional_collection_owner_release.t b/src/test/resources/unit/refcount/conditional_collection_owner_release.t new file mode 100644 index 0000000000..52fe143a99 --- /dev/null +++ b/src/test/resources/unit/refcount/conditional_collection_owner_release.t @@ -0,0 +1,25 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); +our $destroyed = 0; +{ package ConditionalCollectionOwner; sub DESTROY { ++$main::destroyed } } +sub array_result { + if (my @items = (bless({value => 1}, 'ConditionalCollectionOwner'))) { @items } +} +sub hash_result { + if (my %items = (one => bless({value => 2}, 'ConditionalCollectionOwner'))) { %items } +} +my @array = array_result(); +is($array[0]{value}, 1, 'conditional array returns its elements'); +is($destroyed, 0, 'returned array child remains alive'); +my $weak = $array[0]; weaken($weak); +@array = (); +ok(!defined $weak, 'conditional array child releases after caller array'); +my %hash = hash_result(); +is($hash{one}{value}, 2, 'conditional hash returns its pairs'); +is($destroyed, 1, 'returned hash child remains alive'); +$weak = $hash{one}; weaken($weak); +%hash = (); +ok(!defined $weak, 'conditional hash child releases after caller hash'); +done_testing(); diff --git a/src/test/resources/unit/refcount/conditional_loop_local_owner_release.t b/src/test/resources/unit/refcount/conditional_loop_local_owner_release.t new file mode 100644 index 0000000000..36d89d5f65 --- /dev/null +++ b/src/test/resources/unit/refcount/conditional_loop_local_owner_release.t @@ -0,0 +1,65 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); +our $destroyed = 0; +{ package ConditionalLoopOwner; sub DESTROY { ++$main::destroyed } } +sub consume_items { + my ($owner) = @_; + if (my $items = delete $owner->{items}) { + $_->{error} = 7 for values %$items; + } +} +my $guard = bless {}, 'ConditionalLoopOwner'; +my $owner = { items => { one => $guard } }; +my $weak_items = $owner->{items}; +weaken($weak_items); +my $weak_guard = $guard; +weaken($weak_guard); +undef $guard; +consume_items($owner); +ok(!exists $owner->{items}, 'conditional initializer removes the source container slot'); +ok(!defined $weak_items, 'conditional lexical releases its container after postfix loop'); +ok(!defined $weak_guard, 'conditional container releases its child slot'); +is($destroyed, 1, 'conditional scope destroys the child exactly once'); +is_deeply($owner, {}, 'callee cleanup preserves the caller aggregate'); +sub condition_hash_result { + if (my %items = (one => bless({ value => 9 }, 'ConditionalLoopOwner'))) { + \%items; + } +} +my $hash_destroyed_before = $destroyed; +my $returned = condition_hash_result(); +is($destroyed, $hash_destroyed_before, 'conditional return keeps its child alive before caller acquisition'); +is($returned->{one}{value}, 9, 'conditional result preserves a reference to its lexical hash'); +my $weak_returned_child = $returned->{one}; +weaken($weak_returned_child); +undef $returned; +ok(!defined $weak_returned_child, 'caller releases the returned conditional hash and its child'); +sub conditional_capture { + if (my $item = bless { value => 12 }, 'ConditionalLoopOwner') { + sub { $item->{value} }; + } +} +my $callback = conditional_capture(); +is($callback->(), 12, 'implicit conditional return keeps its captured lexical alive'); +my $before = $destroyed; +undef $callback; +is($destroyed, $before + 1, 'final callback owner releases its conditional capture'); +{ + package FalseConditionalOwner; + use overload bool => sub { 0 }, fallback => 1; + sub DESTROY { ++$main::destroyed } +} +sub false_condition_result { + if (my $item = bless { value => 17 }, 'FalseConditionalOwner') { + die "false conditional branch executed\n"; + } +} +my $false_result = false_condition_result(); +is($false_result->{value}, 17, 'untaken branch preserves its false reference-valued condition'); +my $weak_false = $false_result; +weaken($weak_false); +undef $false_result; +ok(!defined $weak_false, 'caller releases the false conditional result'); +done_testing(); diff --git a/src/test/resources/unit/refcount/conditional_tied_result_owner_release.t b/src/test/resources/unit/refcount/conditional_tied_result_owner_release.t new file mode 100644 index 0000000000..4ba5bc7192 --- /dev/null +++ b/src/test/resources/unit/refcount/conditional_tied_result_owner_release.t @@ -0,0 +1,51 @@ +use strict; +use warnings; +use Test::More; +our ($destroyed, @events); +$destroyed = 0; +{ + package ConditionalTiedResult; + sub TIESCALAR { bless { value => 41 }, shift } + sub FETCH { push @main::events, 'FETCH'; $_[0]{value} } + sub STORE { push @main::events, 'STORE'; $_[0]{value} = $_[1] } + sub DESTROY { push @main::events, 'DESTROY'; ++$main::destroyed } +} +sub scalar_result { + if (tie my $value, 'ConditionalTiedResult') { $value } +} +is(scalar_result(), 41, 'conditional tied scalar returns its fetched value'); +is_deeply(\@events, ['FETCH', 'DESTROY'], 'rvalue fetch precedes conditional tie destruction'); +@events = (); +sub lvalue_result :lvalue { + if (tie my $value, 'ConditionalTiedResult') { $value } +} +lvalue_result() = 73; +is_deeply(\@events, ['STORE', 'DESTROY'], 'lvalue store precedes conditional tie destruction'); +is($destroyed, 2, 'both conditional tied handlers release exactly once'); +{ + package ConditionalHashLvalueOwner; + sub TIEHASH { bless {}, shift } + sub FETCH { push @main::events, 'FETCH'; 0 } + sub STORE { push @main::events, 'STORE' } + sub DESTROY { push @main::events, 'DESTROY'; ++$main::destroyed } + package ConditionalArrayLvalueOwner; + sub TIEARRAY { bless {}, shift } + sub FETCHSIZE { 1 } + sub FETCH { push @main::events, 'FETCH'; 0 } + sub STORE { push @main::events, 'STORE' } + sub DESTROY { push @main::events, 'DESTROY'; ++$main::destroyed } +} +sub hash_lvalue_result :lvalue { + if (tie my %value, 'ConditionalHashLvalueOwner') { $value{slot} } +} +sub array_lvalue_result :lvalue { + if (tie my @value, 'ConditionalArrayLvalueOwner') { $value[0] } +} +@events = (); +hash_lvalue_result() = 83; +is_deeply(\@events, ['STORE', 'DESTROY'], 'returned hash proxy retains its magic through STORE'); +@events = (); +array_lvalue_result() = 97; +is_deeply(\@events, ['STORE', 'DESTROY'], 'returned array proxy retains its magic through STORE'); +is($destroyed, 4, 'all conditional tied owners retire once'); +done_testing(); diff --git a/src/test/resources/unit/refcount/dbi_failed_prepare_releases_parent_handle.t b/src/test/resources/unit/refcount/dbi_failed_prepare_releases_parent_handle.t new file mode 100644 index 0000000000..1f8c08ac2b --- /dev/null +++ b/src/test/resources/unit/refcount/dbi_failed_prepare_releases_parent_handle.t @@ -0,0 +1,32 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +BEGIN { + eval { require DBI; require DBD::SQLite; 1 } + or plan skip_all => 'DBI and DBD::SQLite are required'; +} + +my $weak_dbh; +{ + my $dbh = DBI->connect( + 'dbi:SQLite::memory:', '', '', + { RaiseError => 1, PrintError => 0 }, + ); + ok($dbh, 'connected to SQLite'); + + $weak_dbh = $dbh; + weaken($weak_dbh); + + my $prepare_error; + eval { $dbh->prepare('_NOPE_'); 1 } or $prepare_error = $@; + like($prepare_error, qr/prepare|syntax|near/i, + 'invalid SQL fails while preparing a statement'); + ok(defined $weak_dbh, 'the caller still owns the database handle'); +} + +ok(!defined $weak_dbh, + 'a failed, unreturned statement does not retain the database handle'); + +done_testing; diff --git a/src/test/resources/unit/refcount/dbic_rescued_graph_collection_diagnostic.t b/src/test/resources/unit/refcount/dbic_rescued_graph_collection_diagnostic.t new file mode 100644 index 0000000000..8f99ff7562 --- /dev/null +++ b/src/test/resources/unit/refcount/dbic_rescued_graph_collection_diagnostic.t @@ -0,0 +1,75 @@ +use strict; +use warnings; +use B (); +use Test::More tests => 7; +use Scalar::Util qw(weaken isweak); + +my %weak; +my $row; +{ + package Local::DBICRescue::Schema; + + sub source_registrations { $_[0]->{source_registrations} } + + sub DESTROY { + my $self = shift; + my $sources = $self->source_registrations; + for my $name (keys %$sources) { + if (ref $sources->{$name} + && B::svref_2object($sources->{$name})->REFCNT > 1) { + $sources->{$name}->schema($self); + Scalar::Util::weaken($sources->{$name}); + last; + } + } + } + + package Local::DBICRescue::ResultSource; + + sub schema { + $_[0]->{schema} = $_[1] if @_ > 1; + return $_[0]->{schema}; + } + + sub DESTROY { + return if !ref $_[0]->{schema} || Scalar::Util::isweak($_[0]->{schema}); + + Scalar::Util::weaken($_[0]->{schema}); + if ($_[0]->{schema}) { + my $sources = $_[0]->{schema}->source_registrations; + for (keys %$sources) { + $sources->{$_} = $_[0] + if $sources->{$_} && $sources->{$_} == $_[0]; + } + } + } +} + +package main; + +{ + my $schema = bless { source_registrations => {} }, 'Local::DBICRescue::Schema'; + my $source = bless { schema => $schema }, 'Local::DBICRescue::ResultSource'; + weaken($source->{schema}); + $schema->{source_registrations}{Artist} = $source; + $row = bless { result_source => $source }, 'Local::DBICRescue::Row'; + + $weak{schema} = $schema; + weaken($weak{schema}); + $weak{source} = $source; + weaken($weak{source}); + $weak{row} = $row; + weaken($weak{row}); +} + +ok(defined $weak{schema}, 'ResultSource rescue keeps Schema alive while a row owns it'); +ok(defined $weak{source}, 'the row keeps its ResultSource alive'); +ok(defined $weak{row}, 'the external row remains live before release'); + +undef $row; + +ok(!defined $weak{row}, 'the row is released'); +ok(!defined $weak{source}, 'ResultSource is released after its last row owner leaves'); +ok(!defined $weak{schema}, 'rescued Schema is released after its ResultSource leaves'); +ok(!defined $weak{source} && !defined $weak{schema}, + 'the destructor handoff does not leave a detached source or Schema behind'); diff --git a/src/test/resources/unit/refcount/dbic_result_graph_collection_diagnostic.t b/src/test/resources/unit/refcount/dbic_result_graph_collection_diagnostic.t new file mode 100644 index 0000000000..c2e3bfd53a --- /dev/null +++ b/src/test/resources/unit/refcount/dbic_result_graph_collection_diagnostic.t @@ -0,0 +1,73 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); +use Storable (); + +# Isolate ownership cleanup for the graph shape behind DBIx t/52leaks.t: +# Schema owns Storage and ResultSources, while rows own their sources and one +# row can reference another. Weak backrefs keep the fixture acyclic. This omits +# DBIx DESTROY behavior so a failure points at base graph ownership. +sub make_dbic_style_graph { + my $schema = bless { source_registrations => {} }, 'Local::DBICGraph::Schema'; + my $storage = bless {}, 'Local::DBICGraph::Storage'; + my $dbh = bless { driver_name => 'SQLite' }, 'Local::DBICGraph::DBH'; + my $artist_source = bless { name => 'Artist', schema => $schema }, + 'Local::DBICGraph::ResultSource'; + my $cd_source = bless { name => 'CD', schema => $schema }, + 'Local::DBICGraph::ResultSource'; + my $artist = bless { result_source => $artist_source, cds => [] }, + 'Local::DBICGraph::Row'; + my $cd = bless { result_source => $cd_source, artist => $artist }, + 'Local::DBICGraph::Row'; + + $storage->{schema} = $schema; + weaken($storage->{schema}); + weaken($artist_source->{schema}); + weaken($cd_source->{schema}); + $storage->{dbh} = $dbh; + $schema->{storage} = $storage; + $schema->{source_registrations}{Artist} = $artist_source; + $schema->{source_registrations}{CD} = $cd_source; + return { + schema => $schema, + storage => $storage, + dbh => $dbh, + artist_source => $artist_source, + cd_source => $cd_source, + artist => $artist, + cd => $cd, + rows => [$artist, $cd], + }; +} + +my @nodes = qw(schema storage dbh artist_source cd_source artist cd); +my %weak; +{ + my $original = make_dbic_style_graph(); + my $clone = Storable::dclone($original); + my $double_clone = Storable::dclone($clone); + + my %graphs = ( + original => $original, + clone => $clone, + double_clone => $double_clone, + ); + for my $label (qw(original clone double_clone)) { + my $graph = $graphs{$label}; + for my $node (@nodes) { + my $key = "$label/$node"; + $weak{$key} = $graph->{$node}; + weaken($weak{$key}); + } + } +} + +for my $generation (qw(original clone double_clone)) { + for my $node (@nodes) { + my $key = "$generation/$node"; + ok(!defined $weak{$key}, "$key is released after its aggregate is dropped"); + } +} + +done_testing(); diff --git a/src/test/resources/unit/refcount/dbic_resultset_map_depth_release_diagnostic.t b/src/test/resources/unit/refcount/dbic_resultset_map_depth_release_diagnostic.t new file mode 100644 index 0000000000..a24b71da12 --- /dev/null +++ b/src/test/resources/unit/refcount/dbic_resultset_map_depth_release_diagnostic.t @@ -0,0 +1,63 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +# Isolate the result-list materialization boundary behind DBIx's +# fire_resultsets path. The direct and single-map cases are controls for the +# nested-map result list, which is then exercised with and without the +# localized random_results collection used by LeakTracer. +{ + package Local::DBICMapDepth::Row; + sub get_columns { return (id => $_[0]{id}) } + + package Local::DBICMapDepth::ResultSet; + sub all { return @{ $_[0]{rows} } } +} + +sub run_case { + my ($weak, $mode) = @_; + my $row = bless { id => 1 }, 'Local::DBICMapDepth::Row'; + my $resultset = bless { rows => [$row] }, 'Local::DBICMapDepth::ResultSet'; + my $collection = { + resultset => $resultset, + random_results => [], + }; + + $weak->{$mode} = $row; + weaken($weak->{$mode}); + + my @resultsets = grep { + ref($_) eq 'Local::DBICMapDepth::ResultSet' + } values %$collection; + + if ($mode eq 'direct') { + my @rows = $resultset->all; + } + elsif ($mode eq 'single_map') { + my @rows = map { $_->all } @resultsets; + } + elsif ($mode eq 'nested_map') { + my @rows = map { $_, { $_->get_columns } } + map { $_->all } @resultsets; + } + elsif ($mode eq 'localized_collection') { + my $fire_resultsets = sub { + map { $_, { $_->get_columns } } + map { $_->all } @resultsets; + }; + { + local $collection->{random_results}; + push @{ $collection->{random_results} }, $fire_resultsets->(); + } + } +} + +my %weak; +for my $mode (qw(direct single_map nested_map localized_collection)) { + run_case(\%weak, $mode); + + ok(!defined $weak{$mode}, "$mode releases its result row"); +} + +done_testing(); diff --git a/src/test/resources/unit/refcount/dbic_resultset_map_return_list_cleanup.t b/src/test/resources/unit/refcount/dbic_resultset_map_return_list_cleanup.t new file mode 100644 index 0000000000..948f6a692c --- /dev/null +++ b/src/test/resources/unit/refcount/dbic_resultset_map_return_list_cleanup.t @@ -0,0 +1,49 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +# Mirrors DBIx::Class::Util::LeakTracer's resultset firing step. A method +# returns rows in list context, a nested map reads row columns, and the +# temporary result list is discarded when the localized collection field is +# restored. The returned row must not remain rooted by map's temporary $_. +{ + package Local::DBICMap::Row; + sub get_columns { return (id => $_[0]{id}) } + + package Local::DBICMap::ResultSet; + sub all { return @{ $_[0]{rows} } } +} + +sub fire_resultsets_and_restore { + my ($weak) = @_; + my $row = bless { id => 1 }, 'Local::DBICMap::Row'; + my $resultset = bless { rows => [$row] }, 'Local::DBICMap::ResultSet'; + my $base_collection = { + resultset => $resultset, + random_results => [], + }; + $weak->{row} = $row; + weaken($weak->{row}); + + my @resultsets = grep { + ref($_) eq 'Local::DBICMap::ResultSet' + } values %$base_collection; + my $fire_resultsets = sub { + map { $_, { $_->get_columns } } + map { $_->all } + @resultsets; + }; + + { + local $base_collection->{random_results}; + push @{ $base_collection->{random_results} }, $fire_resultsets->(); + } +} + +my %weak; +fire_resultsets_and_restore(\%weak); + +ok(!defined $weak{row}, 'row is released after resultset enumeration and temporary result cleanup'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/dbic_t52_phantom_related_release.t b/src/test/resources/unit/refcount/dbic_t52_phantom_related_release.t new file mode 100644 index 0000000000..9f9ee37378 --- /dev/null +++ b/src/test/resources/unit/refcount/dbic_t52_phantom_related_release.t @@ -0,0 +1,76 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +# Optional integration regression for DBIx::Class t/52leaks.t's phantom chain. +# Set DBIC_CLASS_TEST_ROOT to an unpacked DBIx::Class tree to run it; ordinary +# unit runs skip this external fixture. +BEGIN { + my $root = $ENV{DBIC_CLASS_TEST_ROOT}; + plan skip_all => 'set DBIC_CLASS_TEST_ROOT to a DBIx::Class checkout' + unless defined($root) && -d "$root/t/lib" && -d "$root/lib"; + + $ENV{DBICTEST_NO_MAKEFILE_VERIFICATION} ||= 1; + $ENV{AUTOMATED_TESTING} ||= 1; + unshift @INC, "$root/t/lib", "$root/lib"; + require DBICTest::RunMode; +} + +# Register before DBICTest so its leak-check END assertions are included in the plan. +END { done_testing(); } + +require DBICTest; + +sub watch { + my ($weak, $name, $value) = @_; + $weak->{$name} = $value; + weaken($weak->{$name}); +} + +my %weak; +{ + my $phantom; + my @chain = ( + sub { DBICTest->init_schema(sqlite_use_file => 0) }, + sub { shift->source('Artist') }, + sub { shift->resultset }, + sub { shift->result_source }, + sub { shift->schema }, + sub { shift->resultset('Artist') }, + sub { shift->find_or_create({ name => 'detachable' }) }, + sub { shift->result_source }, + sub { shift->schema }, + sub { shift->clone }, + sub { shift->resultset('CD') }, + sub { shift->next }, + sub { shift->artist }, + ); + + for my $index (0 .. $#chain) { + $phantom = $chain[$index]->($phantom); + if ($index == 0) { + watch(\%weak, 'schema', $phantom); + my $storage = $phantom->storage; + watch(\%weak, 'storage', $storage); + my $dbh = $storage->_dbh; + watch(\%weak, 'dbh', $dbh); + } + elsif ($index == 3) { + watch(\%weak, 'artist_source', $phantom); + } + elsif ($index == 11) { + watch(\%weak, 'cd_row', $phantom); + } + elsif ($index == 12) { + watch(\%weak, 'artist_row', $phantom); + } + } + + ok($phantom && $phantom->name, 'the phantom chain returns its related Artist'); +} + +for my $name (qw(artist_row cd_row artist_source schema storage dbh)) { + my $released = !defined($weak{$name}); + ok($released, "$name is released after the phantom chain scope"); +} diff --git a/src/test/resources/unit/refcount/dbic_t52_search_related_source_owner.t b/src/test/resources/unit/refcount/dbic_t52_search_related_source_owner.t new file mode 100644 index 0000000000..bc2562b16f --- /dev/null +++ b/src/test/resources/unit/refcount/dbic_t52_search_related_source_owner.t @@ -0,0 +1,76 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +# DBIx::Class t/52leaks.t exercises this ownership handoff in its phantom chain. +# Set DBIC_CLASS_TEST_ROOT to an unpacked DBIx::Class tree to run this optional +# integration regression; ordinary unit runs skip the external fixture. +BEGIN { + my $root = $ENV{DBIC_CLASS_TEST_ROOT}; + plan skip_all => 'set DBIC_CLASS_TEST_ROOT to a DBIx::Class checkout' + unless defined($root) && -d "$root/t/lib" && -d "$root/lib"; + + $ENV{DBICTEST_NO_MAKEFILE_VERIFICATION} ||= 1; + $ENV{AUTOMATED_TESTING} ||= 1; + unshift @INC, "$root/t/lib", "$root/lib"; + require DBICTest::RunMode; +} + +require DBICTest; +require Errno; +require DBI; +require DBD::SQLite; +require FileHandle; +require Moo; + +my @weak_objects; +sub track_weak { + my ($object) = @_; + return $object unless ref $object; + push @weak_objects, $object; + weaken($weak_objects[-1]); + return $object; +} + +{ + my $phantom = track_weak(DBICTest->init_schema(sqlite_use_file => 0)); + track_weak($phantom->storage); + track_weak($phantom->source($_)) for $phantom->sources; + + my @chain = ( + sub { shift->source('Artist') }, + sub { shift->resultset }, + sub { shift->result_source }, + sub { shift->schema }, + sub { shift->resultset('Artist') }, + sub { shift->find_or_create({ name => 'detachable' }) }, + sub { shift->result_source }, + sub { shift->schema }, + sub { shift->clone }, + sub { shift->resultset('CD') }, + sub { shift->next }, + sub { shift->artist }, + sub { shift->search_related('cds') }, + sub { shift->next }, + sub { shift->search_related('artist') }, + sub { shift->result_source }, + sub { shift->resultset }, + sub { shift->create({ name => 'detached' }) }, + sub { shift->update({ name => 'reattached' }) }, + sub { shift->discard_changes }, + sub { shift->delete }, + sub { shift->insert }, + ); + for my $step (@chain) { + $phantom = track_weak(scalar $step->($phantom)); + } + + ok($phantom->in_storage, 'phantom chain returned to storage'); + is($phantom->name, 'reattached', 'phantom chain kept the updated name'); +} + +is(scalar(grep { defined } @weak_objects), 0, + 'phantom results, schema sources, and storage are released'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/dbic_try_tiny_callback_owner_release.t b/src/test/resources/unit/refcount/dbic_try_tiny_callback_owner_release.t new file mode 100644 index 0000000000..dc558e5605 --- /dev/null +++ b/src/test/resources/unit/refcount/dbic_try_tiny_callback_owner_release.t @@ -0,0 +1,81 @@ +use strict; +use warnings; +use Test::More tests => 6; +use Scalar::Util qw(weaken); +use Sub::Util (); +use Try::Tiny; + +our %weak_callbacks; +our ($dbh_destroyed, $source_destroyed) = (0, 0); + +for my $function (qw(try catch finally)) { + no strict 'refs'; + no warnings 'redefine'; + my $original = \&{"Try::Tiny::$function"}; + *{"Try::Tiny::$function"} = sub (&;@) { + if ($function eq 'try') { + push @{$weak_callbacks{$function}}, $_[0]; + weaken($weak_callbacks{$function}[-1]); + } + goto $original; + }; +} + +{ + package Unit::TryCallbackOwner::DBH; + + sub last_insert_id { $_[0]->{id} } + sub DESTROY { $main::dbh_destroyed++ } + + package Unit::TryCallbackOwner::Source; + + sub name { $_[0]->{name} } + sub DESTROY { $main::source_destroyed++ } + + package Unit::TryCallbackOwner::Storage; + + sub txn_do { + my ($self, $callback) = @_; + return Try::Tiny::try { + $callback->(); + } Try::Tiny::catch { + die $_; + }; + } + + sub _dbh_last_insert_id { + my ($self, $dbh, $source, $column) = @_; + my $id = Try::Tiny::try { + $dbh->last_insert_id(undef, undef, $source->name, $column); + }; + return $id if defined $id; + } +} + +my ($weak_dbh, $weak_source); +my $id; +{ + my $dbh = bless { id => 42 }, 'Unit::TryCallbackOwner::DBH'; + my $source = bless { name => 'Artist' }, 'Unit::TryCallbackOwner::Source'; + weaken($weak_dbh = $dbh); + weaken($weak_source = $source); + + ($id) = Unit::TryCallbackOwner::Storage->txn_do(sub { + Unit::TryCallbackOwner::Storage->_dbh_last_insert_id( + $dbh, $source, 'artist_id'); + }); +} + +is($id, 42, 'the nested Try::Tiny calls return the scalar last-insert-id result'); +my @recorded_try_callbacks = @{$weak_callbacks{try} || []}; +is(scalar @recorded_try_callbacks, 2, + 'the outer transaction and inner storage try callbacks were both observed'); +my @retained_callback_indices = grep { defined $recorded_try_callbacks[$_] } + 0 .. $#recorded_try_callbacks; +diag('retained Try::Tiny try callback indices: ' + . join(', ', @retained_callback_indices)) if @retained_callback_indices; +ok(!@retained_callback_indices, + 'all Try::Tiny callback blocks are released after goto forwarding'); +ok(!defined($weak_dbh), 'the temporary try callback releases its captured DBI handle'); +ok(!defined($weak_source), 'the temporary try callback releases its captured result source'); +is($dbh_destroyed + $source_destroyed, 2, 'both captured objects are destroyed exactly once'); diff --git a/src/test/resources/unit/refcount/dbix_plus_select_shutdown_lifecycle.t b/src/test/resources/unit/refcount/dbix_plus_select_shutdown_lifecycle.t new file mode 100644 index 0000000000..5c91ac1cdb --- /dev/null +++ b/src/test/resources/unit/refcount/dbix_plus_select_shutdown_lifecycle.t @@ -0,0 +1,48 @@ +use strict; +use warnings; + +BEGIN { + my $root = $ENV{DBIC_CLASS_TEST_ROOT}; + if (!defined($root) || !-d "$root/t/lib" || !-d "$root/lib") { + print "1..0 # SKIP set DBIC_CLASS_TEST_ROOT to a DBIx::Class checkout\n"; + exit 0; + } + $ENV{DBICTEST_NO_MAKEFILE_VERIFICATION} ||= 1; + $ENV{AUTOMATED_TESTING} ||= 1; + unshift @INC, "$root/t/lib", "$root/lib"; + require DBICTest; +} + +use Test::More; + +my $schema = DBICTest->init_schema(); +my $cd_rs = $schema->resultset('CD')->search( + { genreid => { '!=', undef } }, + { order_by => 'cdid' }, +); +my $track_count = $cd_rs->search({}, { rows => 1 }) + ->search_related('tracks')->count; +my %base_columns = $cd_rs->first->get_columns; +my $plus_rs = $cd_rs->search( + {}, + { + join => 'tracks', + distinct => 1, + '+select' => { count => 'tracks.trackid' }, + '+as' => 'tr_cnt', + }, +); + +is_deeply( + { $plus_rs->first->get_columns }, + { %base_columns, tr_cnt => $track_count }, + 'plus-select returns the expected extra column', +); +my %relationship_override = (artist => $base_columns{artist}); +is_deeply( + { $plus_rs->first->get_inflated_columns, %relationship_override }, + { %base_columns, tr_cnt => $track_count }, + 'plus-select inflated columns retain the expected values', +); + +done_testing(); diff --git a/src/test/resources/unit/refcount/dbix_rowparser_deparse_shutdown_lifecycle.t b/src/test/resources/unit/refcount/dbix_rowparser_deparse_shutdown_lifecycle.t new file mode 100644 index 0000000000..23efc23c70 --- /dev/null +++ b/src/test/resources/unit/refcount/dbix_rowparser_deparse_shutdown_lifecycle.t @@ -0,0 +1,38 @@ +use strict; +use warnings; + +BEGIN { + my $root = $ENV{DBIC_CLASS_TEST_ROOT}; + if (!defined($root) || !-d "$root/t/lib" || !-d "$root/lib") { + print "1..0 # SKIP set DBIC_CLASS_TEST_ROOT to a DBIx::Class checkout\n"; + exit 0; + } + $ENV{DBICTEST_NO_MAKEFILE_VERIFICATION} ||= 1; + $ENV{AUTOMATED_TESTING} ||= 1; + unshift @INC, "$root/t/lib", "$root/lib"; + require DBICTest; +} + +use Test::More; +use B::Deparse; + +my $schema = DBICTest->init_schema(no_deploy => 1); +my $inflate_map = [qw/single_track.cd.artist.name year/]; +my ($parser_source) = ($schema->source('CD')->_mk_row_parser({ + inflate_map => $inflate_map, +}))[0]; + +# Keep the deparser in a lexical captured by a named sub, as rowparser_internals.t +# does while it compares generated parser source. +my $deparser; +sub deparse_parser_source { + my ($source) = @_; + $deparser ||= B::Deparse->new; + my $parser = eval "sub { $source }"; + return $deparser->coderef2text($parser); +} + +my $deparsed = deparse_parser_source($parser_source); +ok(length($deparsed), 'generated DBIx row parser can be deparsed'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/dbix_schema_init_shutdown_lifecycle.t b/src/test/resources/unit/refcount/dbix_schema_init_shutdown_lifecycle.t new file mode 100644 index 0000000000..10079dd86f --- /dev/null +++ b/src/test/resources/unit/refcount/dbix_schema_init_shutdown_lifecycle.t @@ -0,0 +1,33 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More; + +BEGIN { + my $root = $ENV{DBIC_CLASS_TEST_ROOT}; + if (!defined($root) || !-d "$root/t/lib" || !-d "$root/lib") { + plan skip_all => 'set DBIC_CLASS_TEST_ROOT to a DBIx::Class checkout'; + } + unshift @INC, "$root/t/lib", "$root/lib"; + require DBICTest; +} + +plan tests => 4; + +our ($weak_schema, $weak_storage, $weak_dbh); +my $schema = DBICTest->init_schema(); +my $storage = $schema->storage; +my $dbh = $storage->_dbh; +($weak_schema, $weak_storage, $weak_dbh) = ($schema, $storage, $dbh); +weaken($weak_schema); +weaken($weak_storage); +weaken($weak_dbh); + +ok($dbh, 'DBIx schema initialized a live DBI handle'); +exit 0; + +END { + ok(!defined($weak_schema), 'schema is released at file shutdown'); + ok(!defined($weak_storage), 'storage is released at file shutdown'); + ok(!defined($weak_dbh), 'DBI handle is released at file shutdown'); +} diff --git a/src/test/resources/unit/refcount/dbix_undirected_result_list_shutdown_lifecycle.t b/src/test/resources/unit/refcount/dbix_undirected_result_list_shutdown_lifecycle.t new file mode 100644 index 0000000000..c57b7d1de6 --- /dev/null +++ b/src/test/resources/unit/refcount/dbix_undirected_result_list_shutdown_lifecycle.t @@ -0,0 +1,47 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More; + +BEGIN { + my $root = $ENV{DBIC_CLASS_TEST_ROOT}; + if (!defined($root) || !-d "$root/t/lib" || !-d "$root/lib") { + plan skip_all => 'set DBIC_CLASS_TEST_ROOT to a DBIx::Class checkout'; + } + unshift @INC, "$root/t/lib", "$root/lib"; + require DBICTest; +} + +plan tests => 6; + +our ($weak_schema, $weak_storage, $weak_dbh, $weak_producer); +{ + my $schema = DBICTest->init_schema(); + my $storage = $schema->storage; + my $dbh = $storage->_dbh; + ($weak_schema, $weak_storage, $weak_dbh) = ($schema, $storage, $dbh); + weaken($weak_schema); + weaken($weak_storage); + weaken($weak_dbh); + + my $cd = $schema->resultset('CD')->find(2); + my $producer = $schema->resultset('Producer')->find(1); + $weak_producer = $producer; + weaken($weak_producer); + $cd->set_producers([$producer], { attribute => 2 }); + undef $producer; + ok(!defined($weak_producer), 'set_producers releases its temporary array argument'); + + my $maps = $schema->resultset('Artist')->search({ artistid => 1 }) + ->search_related('artist_undirected_maps'); + is($maps->count, 1, 'undirected map query returns one row'); + my $mapped = $schema->resultset('Artist')->find(2)->artist_undirected_maps; + my @artists = $mapped->search_related('mapped_artists')->all; + is(scalar @artists, 2, 'undirected relationship returns both artist rows'); +} + +END { + ok(!defined($weak_schema), 'schema is released at file shutdown'); + ok(!defined($weak_storage), 'storage is released at file shutdown'); + ok(!defined($weak_dbh), 'DBI handle is released at file shutdown'); +} diff --git a/src/test/resources/unit/refcount/destroy_exception_resurrection.t b/src/test/resources/unit/refcount/destroy_exception_resurrection.t new file mode 100644 index 0000000000..a6189fa139 --- /dev/null +++ b/src/test/resources/unit/refcount/destroy_exception_resurrection.t @@ -0,0 +1,55 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 11; + +our ($saved, $calls, $warnings); +our @reblessed; +{ + package Local::DyingResurrector; + sub DESTROY { + ++$main::calls; + $main::saved = $_[0] if $main::calls == 1; + die "dying after rescue\n"; + } +} +{ + package Local::DyingRebless; + sub DESTROY { + push @main::reblessed, 'original'; + bless $_[0], 'Local::AfterDyingRebless'; + die "dying after rebless\n"; + } +} +{ + package Local::AfterDyingRebless; + sub DESTROY { push @main::reblessed, 'replacement' } +} + +local $SIG{__WARN__} = sub { $warnings .= $_[0] }; +my $value = bless {}, 'Local::DyingResurrector'; +my $weak = $value; +weaken($weak); +$@ = 'caller state'; +$value = undef; +ok(defined($saved), 'a dying destructor can publish a strong owner'); +ok(defined($weak), 'weak observers survive real resurrection'); +is($calls, 1, 'the initial destructor runs once'); +$saved = undef; +ok(!defined($weak), 'the final resurrected owner clears weak observers'); +is($calls, 2, 'releasing resurrection invokes DESTROY again'); +is($warnings, "\t(in cleanup) dying after rescue\n" x 2, + 'both dying destructor calls report cleanup warnings'); +is($@, 'caller state', 'destruction preserves the caller exception state'); + +my $reblessed = bless {}, 'Local::DyingRebless'; +my $weak_reblessed = $reblessed; +weaken($weak_reblessed); +$reblessed = undef; +is_deeply(\@reblessed, [qw(original replacement)], + 'a dying destructor still dispatches destruction for its new class'); +ok(!defined($weak_reblessed), 'reblessed destruction clears weak observers'); +is($warnings, ("\t(in cleanup) dying after rescue\n" x 2) + . "\t(in cleanup) dying after rebless\n", + 'reblessing reports the original cleanup exception once'); +is($@, 'caller state', 'reblessed destruction preserves the caller exception state'); diff --git a/src/test/resources/unit/refcount/destroy_weak_aggregate_slot_resurrection.t b/src/test/resources/unit/refcount/destroy_weak_aggregate_slot_resurrection.t new file mode 100644 index 0000000000..41434d849e --- /dev/null +++ b/src/test/resources/unit/refcount/destroy_weak_aggregate_slot_resurrection.t @@ -0,0 +1,28 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 5; + +our ($obj, $observer, $holder, $calls); +{ + package Ownership::WeakSlotResurrection; + sub DESTROY { + ++$main::calls; + $main::holder->{slot} = $_[0] if $main::calls == 1; + } +} + +$obj = bless {}, 'Ownership::WeakSlotResurrection'; +$holder = { slot => $obj }; +$observer = $obj; +weaken($holder->{slot}); +weaken($observer); + +undef $obj; +is($calls, 1, 'DESTROY runs when the original owner leaves'); +ok(defined($holder->{slot}), 'the weak aggregate slot is promoted during DESTROY'); +ok(defined($observer), 'weak observers survive the rescue'); + +undef $holder->{slot}; +is($calls, 2, 'releasing the promoted slot runs DESTROY again'); +ok(!defined($observer), 'weak observers clear after final release'); diff --git a/src/test/resources/unit/refcount/destroyed_aggregate_releases_duplicate_referents.t b/src/test/resources/unit/refcount/destroyed_aggregate_releases_duplicate_referents.t new file mode 100644 index 0000000000..43d976c73c --- /dev/null +++ b/src/test/resources/unit/refcount/destroyed_aggregate_releases_duplicate_referents.t @@ -0,0 +1,43 @@ +use strict; +use warnings; +use Test::More tests => 4; +use Scalar::Util qw(weaken); + +our @destroyed; + +{ + package Issue2043::DuplicateAggregateChild; + sub DESTROY { push @main::destroyed, ref $_[0] } + + package Issue2043::DuplicateHashOwner; + sub DESTROY { } + + package Issue2043::DuplicateArrayOwner; + sub DESTROY { } +} + +{ + my $child = bless {}, 'Issue2043::DuplicateAggregateChild'; + my $weak_child = $child; + weaken($weak_child); + my $owner = bless { left => $child, right => $child }, + 'Issue2043::DuplicateHashOwner'; + undef $child; + undef $owner; + ok(!defined $weak_child, 'hash cleanup releases both slots to one child'); + is_deeply(\@destroyed, ['Issue2043::DuplicateAggregateChild'], + 'hash cleanup destroys the duplicate child exactly once'); +} + +@destroyed = (); +{ + my $child = bless {}, 'Issue2043::DuplicateAggregateChild'; + my $weak_child = $child; + weaken($weak_child); + my $owner = bless [ $child, $child ], 'Issue2043::DuplicateArrayOwner'; + undef $child; + undef $owner; + ok(!defined $weak_child, 'array cleanup releases both slots to one child'); + is_deeply(\@destroyed, ['Issue2043::DuplicateAggregateChild'], + 'array cleanup destroys the duplicate child exactly once'); +} diff --git a/src/test/resources/unit/refcount/detached_glob_array_alias_clear_order.t b/src/test/resources/unit/refcount/detached_glob_array_alias_clear_order.t new file mode 100644 index 0000000000..eec9ec2343 --- /dev/null +++ b/src/test/resources/unit/refcount/detached_glob_array_alias_clear_order.t @@ -0,0 +1,49 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 4; + +our @values; +our @DESTROY_OBSERVED; +our @AFTER_CLEAR; + +{ + package DetachedGlobArrayAliasClearOrder::Probe; + + sub DESTROY { + push @main::DESTROY_OBSERVED, + defined($_[0]) ? 'alias-defined' : 'alias-undef', + defined($main::values[0]) ? 'array-defined' : 'array-undef'; + } +} + +my $object = bless {}, 'DetachedGlobArrayAliasClearOrder::Probe'; +my $weak = $object; +weaken($weak); +{ + no strict 'refs'; + ${'DetachedGlobArrayAliasClearOrder::value'} = $object; +} +undef $object; + +my $glob = delete $DetachedGlobArrayAliasClearOrder::{value}; +@values = ($glob); +undef $glob; +ok(defined $weak, 'the array-held detached glob keeps its scalar value alive'); + +sub clear_values { + undef @values; + push @AFTER_CLEAR, defined($_[0]) ? 'defined' : 'undef'; +} + +clear_values($values[0]); + +is_deeply( + \@DESTROY_OBSERVED, + ['alias-defined', 'array-defined'], + 'component DESTROY runs before array and argument aliases are cleared', +); +is_deeply(\@AFTER_CLEAR, ['undef'], 'the active argument alias is cleared afterward'); +is($weak, undef, 'array clear releases the detached component value'); + +done_testing; diff --git a/src/test/resources/unit/refcount/diamond_prefetch_cursor_leak.t b/src/test/resources/unit/refcount/diamond_prefetch_cursor_leak.t new file mode 100644 index 0000000000..440bea454b --- /dev/null +++ b/src/test/resources/unit/refcount/diamond_prefetch_cursor_leak.t @@ -0,0 +1,82 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); + +BEGIN { + my $root = $ENV{DBIC_CLASS_TEST_ROOT}; + if (!defined($root) || !-d "$root/t/lib" || !-d "$root/lib") { + print "1..0 # SKIP set DBIC_CLASS_TEST_ROOT to a DBIx::Class checkout\n"; + exit 0; + } + $ENV{DBICTEST_NO_MAKEFILE_VERIFICATION} ||= 1; + $ENV{AUTOMATED_TESTING} ||= 1; + unshift @INC, "$root/t/lib", "$root/lib"; + require DBICTest; +} + +use Test::More tests => 4; + +# Regression for issue #2043: the diamond-prefetch search pattern +# creates enough blessed ResultSet and Cursor objects through DBIx +# method dispatch (try/catch closures, condition resolution, attribute +# merging) that PerlOnJava's owner tracking loses an ownership edge. +# A BaseResultSet survives at refcount zero with a durable untracked +# scalar owner, keeping the Schema, Storage, and DBH alive. +# +# The leak requires volume (64+ searches) and relationship traversal +# on each returned row. System Perl collects everything correctly. +# +# diamond.t reference: 768/768 functional assertions pass on all +# backends; JVM and interpreter each fail four shutdown leak assertions. + +my %weak; +{ + my $schema = DBICTest->init_schema(); + $weak{schema} = $schema; weaken($weak{schema}); + $weak{storage} = $schema->storage; weaken($weak{storage}); + $weak{dbh} = $schema->storage->_dbh; weaken($weak{dbh}); + + $schema->populate('Artwork', [[qw/cd_id/], [1]]); + $schema->populate('Artwork_to_Artist', [[qw/artwork_cd_id artist_id/], [1, 2]]); + + my $ars = $schema->resultset('Artwork'); + + my @cd_paths = ( + [], [''], [undef], [{}], [[{}]], [[[undef]]], + ['cd'], {'cd' => 'artist'}, + ); + my @a2a_paths = ( + [], [''], [undef], [{}], [[{}]], [['']], + ['artwork_to_artist'], {'artwork_to_artist' => 'artist'}, + ); + + my %tests; + my $idx = 0; + for my $cd (@cd_paths) { + for my $a2a (@a2a_paths) { + my @join; + push @join, ref $cd eq 'HASH' ? $cd : @$cd; + push @join, ref $a2a eq 'HASH' ? $a2a : @$a2a; + $tests{$idx++} = $ars->search({}, { + join => [@join], + prefetch => [], + }); + } + } + + for my $name (keys %tests) { + for my $artwork ($tests{$name}->all) { + $artwork->cd->artist->artistid; + $artwork->artwork_to_artist->first->artist->artistid; + } + } +} + +ok(!defined $weak{schema}, 'Schema collected after scope exit'); +ok(!defined $weak{storage}, 'Storage collected after scope exit'); +ok(!defined $weak{dbh}, 'DBH collected after scope exit'); + +my $any_leak = defined($weak{schema}) + || defined($weak{storage}) + || defined($weak{dbh}); +ok(!$any_leak, 'no diamond-prefetch cursor leak'); diff --git a/src/test/resources/unit/refcount/diamond_prefetch_cursor_leak_permutations.t b/src/test/resources/unit/refcount/diamond_prefetch_cursor_leak_permutations.t new file mode 100644 index 0000000000..c417a42ffa --- /dev/null +++ b/src/test/resources/unit/refcount/diamond_prefetch_cursor_leak_permutations.t @@ -0,0 +1,100 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); + +BEGIN { + my $root = $ENV{DBIC_CLASS_TEST_ROOT}; + if (!defined($root) || !-d "$root/t/lib" || !-d "$root/lib") { + print "1..0 # SKIP set DBIC_CLASS_TEST_ROOT to a DBIx::Class checkout\n"; + exit 0; + } + $ENV{DBICTEST_NO_MAKEFILE_VERIFICATION} ||= 1; + $ENV{AUTOMATED_TESTING} ||= 1; + unshift @INC, "$root/t/lib", "$root/lib"; + require DBICTest; +} + +use Test::More; + +# Exercise the full search matrix from DBIx::Class's prefetch/diamond.t. +# Each of the 64 join/prefetch attribute-shape pairs creates four resultsets: +# join both sides, prefetch both sides, and the two mixed directions. Traversing +# both relationship paths for every row reproduces the method-dispatch and +# cursor lifetime pressure that the smaller 64-resultset regression misses. +my %weak; +{ + my $schema = DBICTest->init_schema(); + $weak{schema} = $schema; + weaken($weak{schema}); + $weak{storage} = $schema->storage; + weaken($weak{storage}); + $weak{dbh} = $schema->storage->_dbh; + weaken($weak{dbh}); + + $schema->populate('Artwork', [[qw/cd_id/], [1]]); + $schema->populate('Artwork_to_Artist', [[qw/artwork_cd_id artist_id/], [1, 2]]); + my $ars = $schema->resultset('Artwork'); + + my $cd_paths = { + 'no cd' => [], + 'no cd empty' => [''], + 'no cd undef' => [undef], + 'no cd href' => [{}], + 'no cd aoh' => [[{}]], + 'no cd complex' => [[[undef]]], + 'cd' => ['cd'], + 'cd->artist1' => [{'cd' => 'artist'}], + }; + my $a2a_paths = { + 'no a2a' => [], + 'no a2a empty' => [''], + 'no a2a undef' => [undef], + 'no a2a href' => [{}], + 'no a2a aoh' => [[{}]], + 'no a2a complex' => [['']], + 'a2a' => ['artwork_to_artist'], + 'a2a->artist2' => [{'artwork_to_artist' => 'artist'}], + }; + + my %tests; + for my $cd_name (keys %$cd_paths) { + for my $a2a_name (keys %$a2a_paths) { + my @paths = (@{$cd_paths->{$cd_name}}, @{$a2a_paths->{$a2a_name}}); + + $tests{"join $cd_name, $a2a_name"} = $ars->search({}, { + join => [@paths], + prefetch => [], + }); + $tests{"prefetch $cd_name, $a2a_name"} = $ars->search({}, { + join => [], + prefetch => [@paths], + }); + $tests{"join $cd_name, prefetch $a2a_name"} = $ars->search({}, { + join => [@{$cd_paths->{$cd_name}}], + prefetch => [@{$a2a_paths->{$a2a_name}}], + }); + $tests{"join $a2a_name, prefetch $cd_name"} = $ars->search({}, { + join => [@{$a2a_paths->{$a2a_name}}], + prefetch => [@{$cd_paths->{$cd_name}}], + }); + } + } + + for my $name (keys %tests) { + for my $artwork ($tests{$name}->all()) { + is($artwork->id, 1, "$name, correct artwork"); + is($artwork->cd->artist->artistid, 1, + "$name, correct artist_id over cd"); + is($artwork->artwork_to_artist->first->artist->artistid, 2, + "$name, correct artist_id over A2A"); + } + } +} + +ok(!defined $weak{schema}, 'Schema collected after scope exit'); +ok(!defined $weak{storage}, 'Storage collected after scope exit'); +ok(!defined $weak{dbh}, 'DBH collected after scope exit'); +ok(!defined($weak{schema}) && !defined($weak{storage}) && !defined($weak{dbh}), + 'no diamond-prefetch cursor leak'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/diamond_prefetch_shutdown_leak.t b/src/test/resources/unit/refcount/diamond_prefetch_shutdown_leak.t new file mode 100644 index 0000000000..89209c56d8 --- /dev/null +++ b/src/test/resources/unit/refcount/diamond_prefetch_shutdown_leak.t @@ -0,0 +1,90 @@ +use strict; +use warnings; + +BEGIN { + my $root = $ENV{DBIC_CLASS_TEST_ROOT}; + if (!defined($root) || !-d "$root/t/lib" || !-d "$root/lib") { + print "1..0 # SKIP set DBIC_CLASS_TEST_ROOT to a DBIx::Class checkout\n"; + exit 0; + } + $ENV{DBICTEST_NO_MAKEFILE_VERIFICATION} ||= 1; + $ENV{AUTOMATED_TESTING} ||= 1; + unshift @INC, "$root/t/lib", "$root/lib"; + require DBICTest; +} + +use Test::More; + +# Keep this test's executable structure aligned with DBIx::Class's +# t/prefetch/diamond.t. In particular, the search resultsets live in the +# file-scope lexical pad and DBICTest's END leak checker observes them after +# top-level interpreter cleanup. Wrapping this in a block or subroutine masks +# the interpreter-only shutdown leak from issue #2043. +my $schema = DBICTest->init_schema(); + +$schema->populate('Artwork', [ + [qw/cd_id/], + [1], +]); + +$schema->populate('Artwork_to_Artist', [ + [qw/artwork_cd_id artist_id/], + [1, 2], +]); + +my $ars = $schema->resultset('Artwork'); + +my $cd_paths = { + 'no cd' => [], + 'no cd empty' => [''], + 'no cd undef' => [undef], + 'no cd href' => [{}], + 'no cd aoh' => [[{}]], + 'no cd complex' => [[[undef]]], + 'cd' => ['cd'], + 'cd->artist1' => [{'cd' => 'artist'}], +}; +my $a2a_paths = { + 'no a2a' => [], + 'no a2a empty' => [''], + 'no a2a undef' => [undef], + 'no a2a href' => [{}], + 'no a2a aoh' => [[{}]], + 'no a2a complex' => [['']], + 'a2a' => ['artwork_to_artist'], + 'a2a->artist2' => [{'artwork_to_artist' => 'artist'}], +}; + +my %tests; +for my $cd_name (keys %$cd_paths) { + for my $a2a_name (keys %$a2a_paths) { + $tests{"join $cd_name, $a2a_name"} = $ars->search({}, { + join => [@{$cd_paths->{$cd_name}}, @{$a2a_paths->{$a2a_name}}], + prefetch => [], + }); + $tests{"prefetch $cd_name, $a2a_name"} = $ars->search({}, { + join => [], + prefetch => [@{$cd_paths->{$cd_name}}, @{$a2a_paths->{$a2a_name}}], + }); + $tests{"join $cd_name, prefetch $a2a_name"} = $ars->search({}, { + join => [@{$cd_paths->{$cd_name}}], + prefetch => [@{$a2a_paths->{$a2a_name}}], + }); + $tests{"join $a2a_name, prefetch $cd_name"} = $ars->search({}, { + join => [@{$a2a_paths->{$a2a_name}}], + prefetch => [@{$cd_paths->{$cd_name}}], + }); + } +} + +for my $name (keys %tests) { + for my $artwork ($tests{$name}->all()) { + is($artwork->id, 1, "$name, correct artwork"); + is($artwork->cd->artist->artistid, 1, + "$name, correct artist_id over cd"); + is($artwork->artwork_to_artist->first->artist->artistid, 2, + "$name, correct artist_id over A2A"); + } +} + +done_testing(); diff --git a/src/test/resources/unit/refcount/end_imported_cv_survives_namespace_clean.t b/src/test/resources/unit/refcount/end_imported_cv_survives_namespace_clean.t new file mode 100644 index 0000000000..8e8f5fae22 --- /dev/null +++ b/src/test/resources/unit/refcount/end_imported_cv_survives_namespace_clean.t @@ -0,0 +1,22 @@ +use strict; +use warnings; +use Test::More tests => 1; + +package Issue1649::ImportedHelper; +use Exporter 'import'; +BEGIN { our @EXPORT_OK = qw(assert_end_scope_reachable) } + +sub assert_end_scope_reachable { + Test::More::pass('imported helper remains callable after namespace cleanup'); +} + +package Issue1649::EndScope; +BEGIN { Issue1649::ImportedHelper->import('assert_end_scope_reachable') } +use namespace::clean; +my $weak_registry = {}; + +END { + # namespace::clean removes the imported stash entry, but Perl has already + # compiled this direct call and retains its CV for the END block. + assert_end_scope_reachable($weak_registry, 'quiet'); +} diff --git a/src/test/resources/unit/refcount/eval_block_callsite_survives_namespace_clean.t b/src/test/resources/unit/refcount/eval_block_callsite_survives_namespace_clean.t new file mode 100644 index 0000000000..56f2255850 --- /dev/null +++ b/src/test/resources/unit/refcount/eval_block_callsite_survives_namespace_clean.t @@ -0,0 +1,29 @@ +use strict; +use warnings; +use Test::More tests => 6; + +package Issue1649::EvalCallsiteHelper; +use Exporter 'import'; +BEGIN { our @EXPORT_OK = qw(bump) } +our $calls = 0; +sub bump { $calls++ } + +package Issue1649::EvalCallsiteCaller; +BEGIN { Issue1649::EvalCallsiteHelper->import('bump') } +use namespace::clean; + +sub call_inside_eval { + eval { + bump(); + die "expected eval exit"; + }; + return $@; +} + +package main; +for my $expected (1 .. 3) { + like(Issue1649::EvalCallsiteCaller::call_inside_eval(), qr/expected eval exit/, + "eval block call $expected completes"); + is($Issue1649::EvalCallsiteHelper::calls, $expected, + "compiled callsite remains usable on reuse $expected"); +} diff --git a/src/test/resources/unit/refcount/eval_callback_return_owner_release.t b/src/test/resources/unit/refcount/eval_callback_return_owner_release.t new file mode 100644 index 0000000000..4989ed2899 --- /dev/null +++ b/src/test/resources/unit/refcount/eval_callback_return_owner_release.t @@ -0,0 +1,58 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); +our ($weak, $destroyed); +$destroyed = 0; +{ package EvalCallbackOwner; sub DESTROY { ++$main::destroyed } } +sub eval_number { + my $result = eval { + my $guard = bless { value => 41 }, 'EvalCallbackOwner'; + $weak = $guard; + weaken($weak); + map { return 42 } 1; + return 99; + }; + return [$result, 'after eval']; +} +is_deeply(eval_number(), [42, 'after eval'], 'callback return exits eval and resumes its surrounding sub'); +ok(!defined $weak, 'callback return releases eval lexicals before the caller resumes'); +is($destroyed, 1, 'eval lexical destructor runs exactly once'); +sub eval_reference { + my $result = eval { + my $guard = bless { value => 73 }, 'EvalCallbackOwner'; + $weak = $guard; + weaken($weak); + map { return $guard } 1; + return undef; + }; + return $result; +} +my $result = eval_reference(); +is($result->{value}, 73, 'callback return preserves an eval-local reference'); +ok(defined $weak, 'receiving caller owns the returned reference'); +is($destroyed, 1, 'returned eval lexical stays alive'); +undef $result; +ok(!defined $weak, 'last caller owner releases the returned eval lexical'); +is($destroyed, 2, 'each eval object is destroyed once'); +{ + package EvalOwnerReceiver; + sub new { bless {}, shift } + sub never { die "callback should have returned before entering method\n" } +} +sub eval_argument { + my $result = eval { + my $guard = bless { value => 95 }, 'EvalCallbackOwner'; + $weak = $guard; + weaken($weak); + EvalOwnerReceiver->new->never(map { return $guard } 1); + }; + return $result; +} +$result = eval_argument(); +is($result->{value}, 95, 'eval return survives abandoned method argument evaluation'); +ok(defined $weak, 'abandoned method cleanup preserves the eval return owner'); +undef $result; +ok(!defined $weak, 'abandoned method return releases at its last caller'); +is($destroyed, 3, 'abandoned method return destroys the object once'); +done_testing(); diff --git a/src/test/resources/unit/refcount/eval_exception_lexical_destroy_lifo.t b/src/test/resources/unit/refcount/eval_exception_lexical_destroy_lifo.t new file mode 100644 index 0000000000..e297ed05c6 --- /dev/null +++ b/src/test/resources/unit/refcount/eval_exception_lexical_destroy_lifo.t @@ -0,0 +1,25 @@ +use strict; +use warnings; +use Test::More; + +our @destroy_order; + +{ + package EvalExceptionLexicalDestroyLifo::Probe; + sub DESTROY { + push @main::destroy_order, $_[0]{name}; + } +} + +sub unwind_lexicals { + eval { + my $first = bless { name => 'first' }, 'EvalExceptionLexicalDestroyLifo::Probe'; + my $second = bless { name => 'second' }, 'EvalExceptionLexicalDestroyLifo::Probe'; + die "unwind lexical scope\n"; + }; +} + +unwind_lexicals(); +is_deeply(\@destroy_order, [qw(second first)], 'exception cleanup destroys lexicals in reverse declaration order'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/eval_named_sub_unused_file_lexical_capture.t b/src/test/resources/unit/refcount/eval_named_sub_unused_file_lexical_capture.t new file mode 100644 index 0000000000..03723ffbef --- /dev/null +++ b/src/test/resources/unit/refcount/eval_named_sub_unused_file_lexical_capture.t @@ -0,0 +1,21 @@ +use strict; +use warnings; +use Test::More tests => 1; +use Scalar::Util qw(weaken); + +my $schema = bless {}, 'Issue2043::Schema'; +my $weak_schema = $schema; +weaken($weak_schema); + +# A package sub defined in this file cannot close over file lexicals. The +# eval source is literal and references no lexical, so it must not keep the +# unrelated schema alive until global destruction. +sub compile_unrelated_eval_sub { + my $code = eval 'sub { 1 }'; + die $@ if $@; + return $code; +} + +END { + ok(!defined($weak_schema), 'unused file lexical is released before END blocks'); +} diff --git a/src/test/resources/unit/refcount/eval_named_sub_unused_lexical_release.t b/src/test/resources/unit/refcount/eval_named_sub_unused_lexical_release.t new file mode 100644 index 0000000000..5dc99dc5a3 --- /dev/null +++ b/src/test/resources/unit/refcount/eval_named_sub_unused_lexical_release.t @@ -0,0 +1,26 @@ +use strict; +use warnings; +use Test::More tests => 2; +use Scalar::Util qw(weaken); + +our $weak_referent; +my $referent = bless {}, 'EvalNamedSubUnusedLexicalRelease::Probe'; +$weak_referent = $referent; +weaken($weak_referent); +my $eval_source = '1'; + +sub eval_dynamic_source { + return eval $eval_source; +} + +eval_dynamic_source(); +$eval_source = '$referent'; +is(eval_dynamic_source(), $referent, + 'dynamic eval can still resolve a captured lexical'); +$eval_source = '1'; +eval_dynamic_source(); + +END { + ok(!defined($weak_referent), + 'a named dynamic-eval sub does not retain an unrelated lexical referent'); +} diff --git a/src/test/resources/unit/refcount/filetest_glob_cache_lifetime.t b/src/test/resources/unit/refcount/filetest_glob_cache_lifetime.t new file mode 100644 index 0000000000..1f06cca20d --- /dev/null +++ b/src/test/resources/unit/refcount/filetest_glob_cache_lifetime.t @@ -0,0 +1,34 @@ +use strict; +use warnings; +use Test::More; +use File::Temp qw(tempfile); + +our $destroyed = 0; + +{ + package FileTestCacheLifetimeHandle; + + sub DESTROY { + my ($self) = @_; + close $self; + $main::destroyed++; + } +} + +my ($handle, $path) = tempfile(); +bless $handle, 'FileTestCacheLifetimeHandle'; +ok(-e $handle, 'file test accepts a blessed glob handle'); +undef $handle; +is($destroyed, 1, 'file-test cache does not retain the blessed glob'); +unlink $path or die "unlink $path: $!"; + +$destroyed = 0; +my ($stat_handle, $stat_path) = tempfile(); +bless $stat_handle, 'FileTestCacheLifetimeHandle'; +my @stat = stat($stat_handle); +is(scalar(@stat), 13, 'stat accepts a blessed glob handle'); +undef $stat_handle; +is($destroyed, 1, 'stat cache does not retain the blessed glob'); +unlink $stat_path or die "unlink $stat_path: $!"; + +done_testing; diff --git a/src/test/resources/unit/refcount/foreach_alias_does_not_add_referent_owner.t b/src/test/resources/unit/refcount/foreach_alias_does_not_add_referent_owner.t new file mode 100644 index 0000000000..0386c08dba --- /dev/null +++ b/src/test/resources/unit/refcount/foreach_alias_does_not_add_referent_owner.t @@ -0,0 +1,26 @@ +use strict; +use warnings; +use B qw(svref_2object); +use Test::More tests => 3; + +sub refcount { svref_2object($_[0])->REFCNT } + +{ + package ForeachAliasRefcountNode; + + sub new { bless { children => [] }, shift } +} + +my $parent = ForeachAliasRefcountNode->new; +my $child = ForeachAliasRefcountNode->new; +push @{$parent->{children}}, $child; + +is(refcount($child), 2, 'child has one lexical and one array owner'); + +for (@{$parent->{children}}) { + is(refcount($_), 2, 'foreach aliases the element cell without adding a referent owner'); +} + +is(refcount($child), 2, 'leaving foreach preserves the original two owners'); + +done_testing; diff --git a/src/test/resources/unit/refcount/generated_tied_array_handler_lifetime.t b/src/test/resources/unit/refcount/generated_tied_array_handler_lifetime.t new file mode 100644 index 0000000000..eac9525229 --- /dev/null +++ b/src/test/resources/unit/refcount/generated_tied_array_handler_lifetime.t @@ -0,0 +1,36 @@ +use strict; +use warnings; +use Test::More; +use Tie::Array; +use Class::MethodMaker; + +our @events; + +{ + package GeneratedTieArrayHandler; + use base 'Tie::StdArray'; + + sub TIEARRAY { push @main::events, 'TIEARRAY'; $_[0]->SUPER::TIEARRAY } + sub PUSH { push @main::events, 'PUSH'; $_[0]->SUPER::PUSH(@_[1 .. $#_]) } + sub FETCH { push @main::events, 'FETCH'; $_[0]->SUPER::FETCH($_[1]) } + sub DESTROY { push @main::events, 'DESTROY'; $_[0]->SUPER::DESTROY } +} + +{ + package GeneratedTiedArrayOwner; + Class::MethodMaker->import( + [array => [{ -tie_class => 'GeneratedTieArrayHandler' }, 'items']]); +} + +my $object = bless {}, 'GeneratedTiedArrayOwner'; +$object->items_push(17); +is_deeply(\@events, [qw(TIEARRAY PUSH)], + 'generated tied field keeps its handler alive through first operation'); +is($object->items_index(0), 17, 'generated tied field remains readable'); +is_deeply(\@events, [qw(TIEARRAY PUSH FETCH)], + 'handler remains alive through fetch'); +$object->items_reset; +is_deeply(\@events, [qw(TIEARRAY PUSH FETCH DESTROY)], + 'reset releases the handler after the field lifetime'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/grep_active_alias_cell_lifetime.t b/src/test/resources/unit/refcount/grep_active_alias_cell_lifetime.t new file mode 100644 index 0000000000..33ff2f1998 --- /dev/null +++ b/src/test/resources/unit/refcount/grep_active_alias_cell_lifetime.t @@ -0,0 +1,23 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 2; + +{ + package DBICTest::BaseResultSet; +} + +my $resultset = bless {}, 'DBICTest::BaseResultSet'; +my $weak_resultset = $resultset; +weaken($weak_resultset); +my $source = { resultsets => [$resultset] }; +undef $resultset; + +my @selected = grep { + $source->{resultsets} = []; + ok(defined $weak_resultset, + 'active grep alias retains the referent after source replacement'); + $_->{cursor} ||= {}; + ok(defined $_->{cursor}, 'active grep alias remains usable'); + 1; +} @{$source->{resultsets}}; diff --git a/src/test/resources/unit/refcount/hash_assignment_preserves_enclosing_return.t b/src/test/resources/unit/refcount/hash_assignment_preserves_enclosing_return.t new file mode 100644 index 0000000000..af9b372bbf --- /dev/null +++ b/src/test/resources/unit/refcount/hash_assignment_preserves_enclosing_return.t @@ -0,0 +1,36 @@ +use strict; +use warnings; +use Test::More tests => 6; + +our $destroyed = 0; + +{ + package HashListOuterReturn; + sub DESTROY { ++$main::destroyed } +} + +sub produce { + return bless {}, 'HashListOuterReturn'; +} + +sub materialize_hash { + my %hash = (first => 1, second => 2); + return scalar keys %hash; +} + +my @list = (produce(), materialize_hash()); +is($destroyed, 0, + 'list expression keeps earlier return alive during nested hash assignment'); +is(ref($list[0]), 'HashListOuterReturn', + 'earlier return is still in the assigned list'); +undef @list; +is($destroyed, 1, 'list owner releases the return once it is cleared'); + +$destroyed = 0; +my $array = [produce(), materialize_hash()]; +is($destroyed, 0, + 'array expression keeps earlier return alive during nested hash assignment'); +is(ref($array->[0]), 'HashListOuterReturn', + 'earlier return is still in the assigned array'); +undef $array; +is($destroyed, 1, 'array owner releases the return once it is cleared'); diff --git a/src/test/resources/unit/refcount/hash_slot_replacement_visible_before_destroy.t b/src/test/resources/unit/refcount/hash_slot_replacement_visible_before_destroy.t new file mode 100644 index 0000000000..5faf42a1cc --- /dev/null +++ b/src/test/resources/unit/refcount/hash_slot_replacement_visible_before_destroy.t @@ -0,0 +1,50 @@ +use strict; +use warnings; +use Test::More tests => 6; + +{ + package HashSlotReplacementOld; + sub DESTROY { + $main::hash_slot_replacement_destroyed++; + $main::hash_slot_replacement_saw_new = + ref($main::hash_slot_replacement{slot}) eq 'HashSlotReplacementNew'; + } + + package HashSlotReplacementNew; + + package ArraySlotReplacementOld; + sub DESTROY { + $main::array_slot_replacement_destroyed++; + $main::array_slot_replacement_saw_new = + ref($main::array_slot_replacement[0]) eq 'ArraySlotReplacementNew'; + } + + package ArraySlotReplacementNew; +} + +our %hash_slot_replacement; +our $hash_slot_replacement_destroyed = 0; +our $hash_slot_replacement_saw_new = 0; +our @array_slot_replacement; +our $array_slot_replacement_destroyed = 0; +our $array_slot_replacement_saw_new = 0; + +$hash_slot_replacement{slot} = bless {}, 'HashSlotReplacementOld'; +$hash_slot_replacement{slot} = bless {}, 'HashSlotReplacementNew'; + +is($hash_slot_replacement_destroyed, 1, + 'replacing the final hash owner destroys the old referent once'); +ok($hash_slot_replacement_saw_new, + 'the old referent observes the published replacement from DESTROY'); +is(ref($hash_slot_replacement{slot}), 'HashSlotReplacementNew', + 'the replacement remains in the hash slot'); + +$array_slot_replacement[0] = bless {}, 'ArraySlotReplacementOld'; +$array_slot_replacement[0] = bless {}, 'ArraySlotReplacementNew'; + +is($array_slot_replacement_destroyed, 1, + 'replacing the final array owner destroys the old referent once'); +ok($array_slot_replacement_saw_new, + 'the old array referent observes the published replacement from DESTROY'); +is(ref($array_slot_replacement[0]), 'ArraySlotReplacementNew', + 'the replacement remains in the array slot'); diff --git a/src/test/resources/unit/refcount/hash_void_assignment_releases_discarded_result.t b/src/test/resources/unit/refcount/hash_void_assignment_releases_discarded_result.t new file mode 100644 index 0000000000..33c6595c21 --- /dev/null +++ b/src/test/resources/unit/refcount/hash_void_assignment_releases_discarded_result.t @@ -0,0 +1,31 @@ +use strict; +use warnings; +use Test::More tests => 5; + +our $destroyed = 0; + +{ + package HashVoidAssignmentOwner; + sub DESTROY { ++$main::destroyed } +} + +{ + my %hash; + %hash = (owner => bless({}, 'HashVoidAssignmentOwner')); + is($destroyed, 0, 'void hash assignment keeps the stored value alive'); + is(ref($hash{owner}), 'HashVoidAssignmentOwner', 'hash stores its assigned value'); + + %hash = (); + is($destroyed, 1, 'clearing the hash releases the value after discarded result cleanup'); +} + +$destroyed = 0; +{ + my $row = bless { + owner => bless({}, 'HashVoidAssignmentOwner'), + state => 0, + }, 'HashVoidAssignmentRow'; + is($destroyed, 0, 'blessed hash literal retains its field value'); + undef $row; + is($destroyed, 1, 'discarded hash literal result does not retain a field value'); +} diff --git a/src/test/resources/unit/refcount/html_tree_builder_lifecycle.t b/src/test/resources/unit/refcount/html_tree_builder_lifecycle.t new file mode 100644 index 0000000000..e234ac7f9e --- /dev/null +++ b/src/test/resources/unit/refcount/html_tree_builder_lifecycle.t @@ -0,0 +1,48 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More; + +our @OBJECTS; +our $in_core_bless; + +BEGIN { + no strict 'refs'; + *{'CORE::GLOBAL::bless'} = sub { + my $reference = shift; + my $class = @_ ? shift : scalar caller; + my $object = CORE::bless($reference, $class); + if ($object->isa('HTML::Element') && !$main::in_core_bless) { + local $main::in_core_bless = 1; + push @main::OBJECTS, $object; + Scalar::Util::weaken($main::OBJECTS[-1]); + } + return $object; + }; +} + +my $have_html_tree = eval { require HTML::TreeBuilder; 1 }; +plan skip_all => 'HTML::Tree is not installed' unless $have_html_tree; + +sub object_count { scalar grep { defined $_ } @OBJECTS } +sub clear_objects { @OBJECTS = () } + +{ + my $tree = HTML::TreeBuilder->new_from_content('&foo; &bar;'); + ok(object_count() > 0, 'content parsing creates elements'); + $tree = undef; + is(object_count(), 0, 'dropping a content-parsed tree releases its elements'); + clear_objects(); +} + +{ + my $tree = HTML::TreeBuilder->new(no_expand_entities => 1); + $tree->parse("

    &foo; &bar; ' &l

    "); + ok(object_count() > 0, 'incremental parsing creates elements'); + $tree = undef; + is(object_count(), 0, + 'dropping an incrementally parsed tree releases its elements'); + clear_objects(); +} + +done_testing; diff --git a/src/test/resources/unit/refcount/io_file_final_owner_closes_during_destroy.t b/src/test/resources/unit/refcount/io_file_final_owner_closes_during_destroy.t new file mode 100644 index 0000000000..784b3e4f2a --- /dev/null +++ b/src/test/resources/unit/refcount/io_file_final_owner_closes_during_destroy.t @@ -0,0 +1,121 @@ +use strict; +use warnings; +use File::Temp qw(tempfile); +use IO::File; +use Scalar::Util qw(weaken unweaken); +use Test::More; + +{ + package TrackedIOFile; + our @ISA = ('IO::File'); + our $destroyed = 0; + our $fileno_during_destroy; + + sub DESTROY { + my ($self) = @_; + ++$destroyed; + $fileno_during_destroy = defined CORE::fileno($self) ? 1 : 0; + IO::Handle::DESTROY($self); + } +} + +my ($temporary, $path) = tempfile(); +close $temporary or die "close temporary file: $!"; + +sub return_tracked_file { + my ($file) = @_; + my $handle = TrackedIOFile->new($file, '>') + or die "open returned tracked handle: $!"; + return $handle; +} + +{ + my $handle = TrackedIOFile->new($path, '>') + or die "open tracked handle: $!"; + ok(defined fileno($handle), 'IO::File has a live descriptor in its scope'); +} + +is($TrackedIOFile::destroyed, 1, 'final Perl owner runs IO::File DESTROY once'); +is($TrackedIOFile::fileno_during_destroy, 1, + 'descriptor remains registered until IO::File DESTROY closes it'); + +{ + my $handle = TrackedIOFile->new($path, '>') + or die "open aliased tracked handle: $!"; + my $alias = $handle; + ok(defined fileno($alias), 'a scalar alias shares the live IO::File handle'); +} + +is($TrackedIOFile::destroyed, 2, + 'the final scalar alias runs IO::File DESTROY once'); +is($TrackedIOFile::fileno_during_destroy, 1, + 'the final scalar alias keeps its descriptor registered through DESTROY'); + +{ + my $returned = return_tracked_file($path); + is($TrackedIOFile::destroyed, 2, + 'scalar return keeps the IO::File object alive'); + ok(defined fileno($returned), 'scalar return keeps the file descriptor available'); +} + +is($TrackedIOFile::destroyed, 3, 'scalar return releases its final file owner at scope exit'); +is($TrackedIOFile::fileno_during_destroy, 1, + 'scalar return keeps its descriptor registered through DESTROY'); + +{ + my $handle = TrackedIOFile->new($path, '>') + or die "open array-held tracked handle: $!"; + my $array = [$handle]; + ok(defined fileno($array->[0]), 'array element keeps the IO::File descriptor available'); +} + +is($TrackedIOFile::destroyed, 4, 'array element release runs IO::File DESTROY once'); +is($TrackedIOFile::fileno_during_destroy, 1, + 'array element keeps the descriptor registered through DESTROY'); + +{ + my $handle = TrackedIOFile->new($path, '>') + or die "open hash-held tracked handle: $!"; + my $hash = { handle => $handle }; + ok(defined fileno($hash->{handle}), 'hash element keeps the IO::File descriptor available'); +} + +is($TrackedIOFile::destroyed, 5, 'hash element release runs IO::File DESTROY once'); +is($TrackedIOFile::fileno_during_destroy, 1, + 'hash element keeps the descriptor registered through DESTROY'); + +my $weak; +{ + my $strong = TrackedIOFile->new($path, '>') + or die "open weakly observed tracked handle: $!"; + $weak = $strong; + weaken($weak); + ok(defined fileno($weak), 'weak observer reads the live IO::File descriptor'); +} + +ok(!defined($weak), 'weak observer clears when the last strong IO::File owner leaves'); +is($TrackedIOFile::destroyed, 6, 'weak observer does not postpone IO::File DESTROY'); +is($TrackedIOFile::fileno_during_destroy, 1, + 'weak observer does not unregister the descriptor before DESTROY'); + +{ + my $promoted; + { + my $strong = TrackedIOFile->new($path, '>') + or die "open unweakened tracked handle: $!"; + $promoted = $strong; + weaken($promoted); + unweaken($promoted); + ok(defined fileno($promoted), 'unweaken restores a strong IO::File owner'); + } + is($TrackedIOFile::destroyed, 6, + 'unweakened owner survives the original scalar scope'); + ok(defined fileno($promoted), 'unweakened owner keeps its descriptor available'); +} + +is($TrackedIOFile::destroyed, 7, 'unweakened owner runs DESTROY at its own scope exit'); +is($TrackedIOFile::fileno_during_destroy, 1, + 'unweakened owner keeps its descriptor registered through DESTROY'); + +unlink $path or die "unlink temporary file: $!"; +done_testing(); diff --git a/src/test/resources/unit/refcount/io_owner_aggregate_clear.t b/src/test/resources/unit/refcount/io_owner_aggregate_clear.t new file mode 100644 index 0000000000..926068ddcc --- /dev/null +++ b/src/test/resources/unit/refcount/io_owner_aggregate_clear.t @@ -0,0 +1,70 @@ +use strict; +use warnings; +use IO::Select; +use Socket qw(AF_UNIX SOCK_STREAM); +use Test::More tests => 8; + +our %localized_hash_owners; +our @localized_array_owners; + +sub make_hash_owner { + socketpair(my $peer, my $handle, AF_UNIX, SOCK_STREAM, 0) + or die "socketpair hash: $!"; + my %owners = (handle => $handle); + return ($peer, \%owners); +} + +sub make_array_owner { + socketpair(my $peer, my $handle, AF_UNIX, SOCK_STREAM, 0) + or die "socketpair array: $!"; + my @owners = ($handle); + return ($peer, \@owners); +} + +sub make_localized_hash_owner { + socketpair(my $peer, my $handle, AF_UNIX, SOCK_STREAM, 0) + or die "socketpair localized hash: $!"; + { + local $localized_hash_owners{handle} = $handle; + is(syswrite($localized_hash_owners{handle}, 'l'), 1, + 'localized hash socket is live inside its scope'); + } + return $peer; +} + +sub make_localized_array_owner { + socketpair(my $peer, my $handle, AF_UNIX, SOCK_STREAM, 0) + or die "socketpair localized array: $!"; + { + local $localized_array_owners[0] = $handle; + is(syswrite($localized_array_owners[0], 'l'), 1, + 'localized array socket is live inside its scope'); + } + return $peer; +} + +sub peer_reached_eof { + my ($peer) = @_; + my $selector = IO::Select->new($peer); + return 1 unless $selector->can_read(0.1); + sysread($peer, my $buffer, 1); + return 1 unless $selector->can_read(0.1); + return sysread($peer, $buffer, 1); +} + +my ($hash_peer, $hash_owners) = make_hash_owner(); +is(syswrite($hash_owners->{handle}, 'h'), 1, 'hash-owned socket is live'); +undef %$hash_owners; +is(peer_reached_eof($hash_peer), 0, + 'clearing the final hash slot releases its socket owner'); + +my ($array_peer, $array_owners) = make_array_owner(); +is(syswrite($array_owners->[0], 'a'), 1, 'array-owned socket is live'); +@$array_owners = (); +is(peer_reached_eof($array_peer), 0, + 'clearing the final array slot releases its socket owner'); + +is(peer_reached_eof(make_localized_hash_owner()), 0, + 'hash slot localization releases its temporary socket owner on unwind'); +is(peer_reached_eof(make_localized_array_owner()), 0, + 'array slot localization releases its temporary socket owner on unwind'); diff --git a/src/test/resources/unit/refcount/io_owner_local_scalar_restore.t b/src/test/resources/unit/refcount/io_owner_local_scalar_restore.t new file mode 100644 index 0000000000..57ef755bfc --- /dev/null +++ b/src/test/resources/unit/refcount/io_owner_local_scalar_restore.t @@ -0,0 +1,59 @@ +use strict; +use warnings; +use Socket qw(AF_UNIX PF_UNSPEC SOCK_STREAM); +use IO::Select; +use Test::More tests => 11; + +our $localized_io_owner; +my $peer; + +{ + socketpair(my $writer, $peer, AF_UNIX, SOCK_STREAM, PF_UNSPEC) + or die "socketpair: $!"; + { + local $localized_io_owner = $writer; + is(syswrite($localized_io_owner, 'x'), 1, + 'localized socket is usable while the local value is installed'); + } +} + +my $peer_readable = IO::Select->new($peer); +my @readable = $peer_readable->can_read(1); +is(scalar @readable, 1, + 'the peer receives the byte written through the localized socket'); +my $buffer = ''; +is(sysread($peer, $buffer, 1), 1, 'the peer reads the localized socket data'); +@readable = $peer_readable->can_read(1); +is(scalar @readable, 1, + 'restoring the localized scalar releases its socket holder'); +my $eof = @readable ? sysread($peer, $buffer, 1) : undef; +is($eof, 0, + 'the peer observes EOF after the last localized writer owner leaves'); + +my $exception_peer; +{ + socketpair(my $exception_writer, $exception_peer, + AF_UNIX, SOCK_STREAM, PF_UNSPEC) + or die "exception socketpair: $!"; + eval { + local $localized_io_owner = $exception_writer; + is(syswrite($localized_io_owner, 'y'), 1, + 'localized socket is usable before exception unwind'); + die "localized IO unwind\n"; + }; + is($@, "localized IO unwind\n", 'the localized scope unwinds the exception'); +} + +my $exception_readable = IO::Select->new($exception_peer); +@readable = $exception_readable->can_read(1); +is(scalar @readable, 1, + 'the exception peer receives data from the localized socket'); +$buffer = ''; +is(sysread($exception_peer, $buffer, 1), 1, + 'the exception peer reads the localized socket data'); +@readable = $exception_readable->can_read(1); +is(scalar @readable, 1, + 'exception unwind releases the localized scalar socket holder'); +my $exception_eof = @readable ? sysread($exception_peer, $buffer, 1) : undef; +is($exception_eof, 0, + 'the exception peer observes EOF after its final writer owner leaves'); diff --git a/src/test/resources/unit/refcount/issue_1649_cancelled_async_scope_exit.t b/src/test/resources/unit/refcount/issue_1649_cancelled_async_scope_exit.t new file mode 100644 index 0000000000..94c1709cf2 --- /dev/null +++ b/src/test/resources/unit/refcount/issue_1649_cancelled_async_scope_exit.t @@ -0,0 +1,65 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken isweak); + +BEGIN { + package Future; + our $VERSION = '0.52'; + $INC{'Future.pm'} = __FILE__; + + sub done { bless { state => 'done', values => [ @_[1 .. $#_ ] ] }, $_[0] } + sub new { bless { state => 'pending', values => [], callbacks => [], chained => [] }, $_[0] } + sub AWAIT_NEW_DONE { shift->done(@_) } + sub AWAIT_NEW_FAIL { bless { state => 'failed', values => [ @_ ] }, $_[0] } + sub AWAIT_CLONE { ref($_[0])->new } + sub AWAIT_IS_READY { $_[0]{state} ne 'pending' } + sub AWAIT_IS_CANCELLED { $_[0]{state} eq 'cancelled' } + sub AWAIT_GET { die $_[0]{values}[0] if $_[0]{state} eq 'failed'; die 'cancelled' if $_[0]{state} eq 'cancelled'; return $_[0]{values}[0] } + sub AWAIT_ON_READY { my ($self, $cb) = @_; $self->AWAIT_IS_READY ? $cb->($self) : push(@{$self->{callbacks}}, $cb); $self } + sub AWAIT_CHAIN_CANCEL { my ($self, $next) = @_; push(@{$self->{chained}}, $next); $self } + sub AWAIT_DONE { my $self = shift; $self->{state} = 'done'; $self->{values} = [ @_ ]; my @callbacks = @{$self->{callbacks}}; $self->{callbacks} = []; $_->($self) for @callbacks; $self } + sub AWAIT_FAIL { my $self = shift; $self->{state} = 'failed'; $self->{values} = [ @_ ]; my @callbacks = @{$self->{callbacks}}; $self->{callbacks} = []; $_->($self) for @callbacks; $self } + sub AWAIT_CANCEL { + my ($self) = @_; + return $self if $self->{state} ne 'pending'; + $self->{state} = 'cancelled'; + my @callbacks = @{$self->{callbacks}}; + $self->{callbacks} = []; + $_->($self) for @callbacks; + my @chained = @{$self->{chained}}; + $self->{chained} = []; + $_->AWAIT_CANCEL for @chained; + return $self; + } + sub AWAIT_WAIT { $_[0]->AWAIT_GET } +} + +use Future::AsyncAwait; + +our $destroyed = 0; +our $weak; +our $pending = Future->new; + +{ + package Repro::CancelledRoot; + sub DESTROY { ++$main::destroyed } +} + +async sub hold_cancelled_root { + my $root = bless { child => [1] }, 'Repro::CancelledRoot'; + $weak = $root; + weaken($weak); + await $main::pending; +} + +my $future = hold_cancelled_root(); +ok(defined($weak) && isweak($weak), + 'suspended async frame retains its weakly observed root before cancellation'); +is($destroyed, 0, 'root is not destroyed while its async frame is suspended'); +$future->AWAIT_CANCEL; +ok(!defined($weak), 'cancelling the returned Future releases its suspended lexical'); +is($destroyed, 1, 'cancelled suspended root DESTROY runs exactly once'); +$future->AWAIT_CANCEL; +is($destroyed, 1, 'repeated cancellation does not release the frame twice'); +done_testing; diff --git a/src/test/resources/unit/refcount/issue_1649_cleared_aggregate_async_scope_exit.t b/src/test/resources/unit/refcount/issue_1649_cleared_aggregate_async_scope_exit.t new file mode 100644 index 0000000000..f9b1adc1ed --- /dev/null +++ b/src/test/resources/unit/refcount/issue_1649_cleared_aggregate_async_scope_exit.t @@ -0,0 +1,51 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken isweak); + +BEGIN { + package Future; + our $VERSION = '0.52'; + $INC{'Future.pm'} = __FILE__; + + sub done { bless { state => 'done', values => [ @_[1 .. $#_ ] ] }, $_[0] } + sub new { bless { state => 'pending', values => [], callbacks => [] }, $_[0] } + sub AWAIT_NEW_DONE { shift->done(@_) } + sub AWAIT_NEW_FAIL { bless { state => 'failed', values => [ @_ ] }, $_[0] } + sub AWAIT_CLONE { ref($_[0])->new } + sub AWAIT_IS_READY { $_[0]{state} ne 'pending' } + sub AWAIT_IS_CANCELLED { $_[0]{state} eq 'cancelled' } + sub AWAIT_GET { die $_[0]{values}[0] if $_[0]{state} eq 'failed'; return $_[0]{values}[0] } + sub AWAIT_ON_READY { my ($self, $cb) = @_; $self->AWAIT_IS_READY ? $cb->($self) : push(@{$self->{callbacks}}, $cb); $self } + sub AWAIT_CHAIN_CANCEL { $_[0] } + sub AWAIT_DONE { my $self = shift; $self->{state} = 'done'; $self->{values} = [ @_ ]; my @callbacks = @{$self->{callbacks}}; $self->{callbacks} = []; $_->($self) for @callbacks; $self } + sub AWAIT_FAIL { my $self = shift; $self->{state} = 'failed'; $self->{values} = [ @_ ]; my @callbacks = @{$self->{callbacks}}; $self->{callbacks} = []; $_->($self) for @callbacks; $self } + sub AWAIT_WAIT { $_[0]->AWAIT_GET } +} + +use Future::AsyncAwait; + +our $destroyed = 0; +our $weak; +our $pending = Future->new; + +{ + package Repro::Root; + sub DESTROY { ++$main::destroyed } +} + +async sub discard_cleared_root { + my $root = bless { child => [1] }, 'Repro::Root'; + $weak = $root; + weaken($weak); + $root->{child} = []; + await $main::pending; +} + +my $future = discard_cleared_root(); +ok(defined($weak) && isweak($weak), 'suspended async frame retains its weakly observed root'); +$pending->AWAIT_DONE(1); +$future->AWAIT_GET; +ok(!defined($weak), 'weak observer clears when async lexical root exits'); +is($destroyed, 1, 'root DESTROY runs exactly once'); +done_testing; diff --git a/src/test/resources/unit/refcount/issue_1649_deferred_owner_normal_store.t b/src/test/resources/unit/refcount/issue_1649_deferred_owner_normal_store.t new file mode 100644 index 0000000000..e12b44a4c6 --- /dev/null +++ b/src/test/resources/unit/refcount/issue_1649_deferred_owner_normal_store.t @@ -0,0 +1,31 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken isweak); + +our (@roots, @unrelated, $destroyed, $weak); +$destroyed = 0; + +{ + package Issue1649::DeferredOwnerNormalStore; + sub DESTROY { ++$main::destroyed } +} + +@unrelated = map { { nested => [$_, { leaf => $_ }] } } 1 .. 256; +{ + my $value = bless {}, 'Issue1649::DeferredOwnerNormalStore'; + $weak = $value; + weaken($weak); + $roots[0] = [$value]; +} + +ok(defined($weak) && isweak($weak), + 'a nested package-rooted array retains the weakly observed value'); +is($destroyed, 0, 'the rooted value is not destroyed while its package owner lives'); +is(scalar @unrelated, 256, 'unrelated live aggregate roots remain present'); + +$roots[0] = undef; +ok(!defined($weak), 'removing the last package path clears the weak observer'); +is($destroyed, 1, 'the nested value is destroyed exactly once after its final owner leaves'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/issue_1649_escaped_scalar_cell_value_owner.t b/src/test/resources/unit/refcount/issue_1649_escaped_scalar_cell_value_owner.t new file mode 100644 index 0000000000..1e06f8c05b --- /dev/null +++ b/src/test/resources/unit/refcount/issue_1649_escaped_scalar_cell_value_owner.t @@ -0,0 +1,101 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 10; + +our ($scalar_cell_destroyed, $array_cell_destroyed, $hash_cell_destroyed) = (0, 0, 0); + +{ + package Issue1649::ScalarCellValueOwner; + sub DESTROY { $main::scalar_cell_destroyed++ } + + package Issue1649::ArrayCellValueOwner; + sub DESTROY { $main::array_cell_destroyed++ } + + package Issue1649::HashCellValueOwner; + sub DESTROY { $main::hash_cell_destroyed++ } +} + +sub escape_scalar_cell_value { + my $slot = $_[0]; + return \$slot; +} + +sub escape_array_element_cell_value { + my @items = ($_[0]); + return \$items[0]; +} + +sub escape_hash_element_cell_value { + my %items = (value => $_[0]); + return \$items{value}; +} + +sub escape_array_and_element_cell { + my @items = ($_[0]); + return (\@items, \$items[0]); +} + +sub escape_hash_and_element_cell { + my %items = (value => $_[0]); + return (\%items, \$items{value}); +} + +my $scalar_object = bless {}, 'Issue1649::ScalarCellValueOwner'; +my $weak_scalar_object = $scalar_object; +weaken($weak_scalar_object); +my $escaped_scalar_cell = escape_scalar_cell_value($scalar_object); +undef $scalar_object; +ok(defined $weak_scalar_object, + 'escaped scalar cell keeps its value alive after lexical scope exit'); +undef $escaped_scalar_cell; +ok(!defined($weak_scalar_object) && $scalar_cell_destroyed == 1, + 'escaped scalar cell releases its value after the final alias leaves'); + +my $array_object = bless {}, 'Issue1649::ArrayCellValueOwner'; +my $weak_array_object = $array_object; +weaken($weak_array_object); +my $escaped_array_cell = escape_array_element_cell_value($array_object); +undef $array_object; +ok(defined $weak_array_object, + 'escaped array element cell keeps its value alive after array scope exit'); +undef $escaped_array_cell; +ok(!defined($weak_array_object) && $array_cell_destroyed == 1, + 'escaped array element cell releases its value after the final alias leaves'); + +my $hash_object = bless {}, 'Issue1649::HashCellValueOwner'; +my $weak_hash_object = $hash_object; +weaken($weak_hash_object); +my $escaped_hash_cell = escape_hash_element_cell_value($hash_object); +undef $hash_object; +ok(defined $weak_hash_object, + 'escaped hash element cell keeps its value alive after hash scope exit'); +undef $escaped_hash_cell; +ok(!defined($weak_hash_object) && $hash_cell_destroyed == 1, + 'escaped hash element cell releases its value after the final alias leaves'); + +my $shared_array_object = bless {}, 'Issue1649::ArrayCellValueOwner'; +my $weak_shared_array_object = $shared_array_object; +weaken($weak_shared_array_object); +my ($held_array, $held_element_cell) = escape_array_and_element_cell($shared_array_object); +undef $shared_array_object; +undef $held_element_cell; +ok(defined $weak_shared_array_object, + 'dropping the escaped array cell leaves the live array element intact'); +undef $held_array; +ok(!defined($weak_shared_array_object) && $array_cell_destroyed == 2, + 'dropping the final array owner releases the element value'); + +my $shared_hash_object = bless {}, 'Issue1649::HashCellValueOwner'; +my $weak_shared_hash_object = $shared_hash_object; +weaken($weak_shared_hash_object); +my ($held_hash, $held_hash_cell) = escape_hash_and_element_cell($shared_hash_object); +undef $shared_hash_object; +undef $held_hash_cell; +ok(defined $weak_shared_hash_object, + 'dropping the escaped hash cell leaves the live hash element intact'); +undef $held_hash; +ok(!defined($weak_shared_hash_object) && $hash_cell_destroyed == 2, + 'dropping the final hash owner releases the element value'); + +done_testing; diff --git a/src/test/resources/unit/refcount/issue_1649_hash_alias_cell_owner.t b/src/test/resources/unit/refcount/issue_1649_hash_alias_cell_owner.t new file mode 100644 index 0000000000..7d5a03c829 --- /dev/null +++ b/src/test/resources/unit/refcount/issue_1649_hash_alias_cell_owner.t @@ -0,0 +1,213 @@ +use strict; +use warnings; +use feature 'refaliasing'; +no warnings 'experimental::refaliasing'; +use re 'eval'; +use Scalar::Util qw(weaken refaddr); +use threads; +use Test::More; + +{ + package Issue1649::HashAliasCellOwner; + our %destroyed; + our %dynamic_hash; + sub DESTROY { ++$destroyed{$_[0]{id}} } +} + +my %hash; +my ($weak_old, $weak_replacement, $weak_deleted, $weak_cleared); +{ + my $source = bless { id => 'old' }, 'Issue1649::HashAliasCellOwner'; + $weak_old = $source; + weaken($weak_old); + \$hash{slot} = \$source; + $source->{changed_through_source} = 1; + is($hash{slot}{changed_through_source}, 1, + 'hash alias shares the source scalar cell'); +} +ok(defined $weak_old, 'hash alias keeps the scalar cell alive after lexical exit'); +is($Issue1649::HashAliasCellOwner::destroyed{old} // 0, 0, + 'hash alias prevents early destruction'); + +my $local_source = 10; +$hash{localized} = 0; +\$hash{localized} = \$local_source; +{ + local $hash{localized}; + $hash{localized} = 20; + is($local_source, 10, 'localizing an alias writes to a temporary hash cell'); +} +is($hash{localized}, 10, 'scope exit restores the original aliased cell'); +$local_source = 30; +is($hash{localized}, 30, 'the restored hash slot still aliases its source'); +delete $hash{localized}; + +my $exception_source = 5; +$hash{exception} = 0; +\$hash{exception} = \$exception_source; +eval { + local $hash{exception}; + $hash{exception} = 7; + die "unwind localized alias\n"; +}; +is($hash{exception}, 5, 'exception unwind restores a localized hash alias'); +$exception_source = 9; +is($hash{exception}, 9, 'exception unwind preserves the original scalar cell'); +delete $hash{exception}; + +my $package_source = 41; +$Issue1649::HashAliasCellOwner::dynamic_hash{slot} = 0; +\$Issue1649::HashAliasCellOwner::dynamic_hash{slot} = \$package_source; +{ + local %Issue1649::HashAliasCellOwner::dynamic_hash; + $Issue1649::HashAliasCellOwner::dynamic_hash{temporary} = 2; +} +is($Issue1649::HashAliasCellOwner::dynamic_hash{slot}, 41, + 'localizing a package hash restores its aliased scalar cell'); +$package_source = 42; +is($Issue1649::HashAliasCellOwner::dynamic_hash{slot}, 42, + 'restored package hash slot still aliases the original source'); +undef %Issue1649::HashAliasCellOwner::dynamic_hash; + +my %regex_hash; +my $weak_regex; +{ + my $source = bless { id => 'regex_rollback' }, 'Issue1649::HashAliasCellOwner'; + $weak_regex = $source; + weaken($weak_regex); + \$regex_hash{slot} = \$source; +} +ok('ab' !~ /^a(?{ delete $regex_hash{slot} })c$/, + 'failed regex callback abandons its hash deletion'); +ok(defined $weak_regex, 'regex rollback retains the aliased scalar cell'); +is($regex_hash{slot}{id}, 'regex_rollback', + 'regex rollback restores the original aliased cell'); +is($Issue1649::HashAliasCellOwner::destroyed{regex_rollback} // 0, 0, + 'regex rollback prevents premature destruction'); +undef %regex_hash; +ok(!defined $weak_regex, 'committed hash clear releases the restored alias'); +is($Issue1649::HashAliasCellOwner::destroyed{regex_rollback} // 0, 1, + 'restored regex alias is destroyed once when cleared'); + +my $thread_source = 'parent'; +my %thread_hash; +\$thread_hash{slot} = \$thread_source; +my $thread = threads->create(sub { + my $same_cell = refaddr(\$thread_hash{slot}) == refaddr(\$thread_source); + $thread_hash{slot} = 'child'; + return join(':', $same_cell, $thread_source); +}); +is($thread->join, '1:child', 'thread cloning preserves a hash scalar alias'); +is($thread_source, 'parent', 'thread writes stay in the cloned scalar cell'); +is($thread_hash{slot}, 'parent', 'thread clone leaves the parent hash unchanged'); + +my $replacement_result; +{ + my $replacement = bless { id => 'replacement' }, 'Issue1649::HashAliasCellOwner'; + $weak_replacement = $replacement; + weaken($weak_replacement); + $replacement_result = eval { + \$hash{slot} = \$replacement; + 1; + }; + $replacement->{changed_through_source} = 2; + is($replacement_result && ($hash{slot}{changed_through_source} // 0) == 2, 1, + 'rebound hash alias still shares the replacement cell'); +} +ok($replacement_result, 'an existing hash slot can be rebound to another scalar cell') + or diag($@); +ok(!defined $weak_old, 'rebinding releases the old aliased referent'); +is($Issue1649::HashAliasCellOwner::destroyed{old} // 0, 1, + 'rebinding destroys the displaced referent once'); +ok(defined $weak_replacement, 'rebound hash alias keeps its source alive after lexical exit'); +$hash{slot} = undef; +ok(!defined $weak_replacement, 'assigning undef through the alias releases its referent'); +is($Issue1649::HashAliasCellOwner::destroyed{replacement} // 0, 1, + 'rebound referent is destroyed once'); + +{ + my $source = bless { id => 'deleted' }, 'Issue1649::HashAliasCellOwner'; + $weak_deleted = $source; + weaken($weak_deleted); + \$hash{deleted} = \$source; +} +ok(defined $weak_deleted, 'new hash alias survives source lexical exit before delete'); +delete $hash{deleted}; +ok(!defined $weak_deleted, 'deleting the last hash alias releases its referent'); +is($Issue1649::HashAliasCellOwner::destroyed{deleted} // 0, 1, + 'deleted alias referent is destroyed once'); + +my ($weak_deleted_return, $deleted_return); +{ + my $source = bless { id => 'deleted_return' }, 'Issue1649::HashAliasCellOwner'; + $weak_deleted_return = $source; + weaken($weak_deleted_return); + \$hash{deleted_return} = \$source; +} +$deleted_return = delete $hash{deleted_return}; +ok(defined $weak_deleted_return, + 'delete result keeps an aliased referent alive as an ordinary value'); +is($Issue1649::HashAliasCellOwner::destroyed{deleted_return} // 0, 0, + 'delete does not destroy a referent still held by its result'); +undef $deleted_return; +ok(!defined $weak_deleted_return, + 'dropping the delete result releases the aliased referent'); +is($Issue1649::HashAliasCellOwner::destroyed{deleted_return} // 0, 1, + 'delete result referent is destroyed once'); + +my $weak_duplicate; +{ + my $source = bless { id => 'duplicate' }, 'Issue1649::HashAliasCellOwner'; + $weak_duplicate = $source; + weaken($weak_duplicate); + \$hash{duplicate_a} = \$source; + \$hash{duplicate_b} = \$source; +} +ok(defined $weak_duplicate, 'two hash slots retain the same aliased scalar cell'); +delete $hash{duplicate_a}; +ok(defined $weak_duplicate, 'deleting one of two aliases retains the shared cell'); +delete $hash{duplicate_b}; +ok(!defined $weak_duplicate, 'deleting the last alias releases the shared cell'); +is($Issue1649::HashAliasCellOwner::destroyed{duplicate} // 0, 1, + 'duplicate hash aliases destroy their referent once'); + +my $weak_first_weaken; +{ + my $source = bless { id => 'first_weaken' }, 'Issue1649::HashAliasCellOwner'; + $weak_first_weaken = $source; + weaken($weak_first_weaken); + \$hash{first_weaken} = \$source; + weaken($source); +} +ok(!defined $weak_first_weaken, + 'a hash alias does not strengthen a scalar cell weakened after storage'); +ok(!defined $hash{first_weaken}, 'the shared hash cell observes the weakened undef'); +is($Issue1649::HashAliasCellOwner::destroyed{first_weaken} // 0, 1, + 'weakening before source scope exit destroys the referent once'); +delete $hash{first_weaken}; + +{ + my $source = bless { id => 'cleared' }, 'Issue1649::HashAliasCellOwner'; + $weak_cleared = $source; + weaken($weak_cleared); + \$hash{cleared} = \$source; +} +ok(defined $weak_cleared, 'new hash alias survives source lexical exit before clear'); +%hash = (); +ok(!defined $weak_cleared, 'clearing the hash releases its aliased scalar cell'); +is($Issue1649::HashAliasCellOwner::destroyed{cleared} // 0, 1, + 'cleared alias referent is destroyed once'); + +my $weak_undefined; +{ + my $source = bless { id => 'undefined_hash' }, 'Issue1649::HashAliasCellOwner'; + $weak_undefined = $source; + weaken($weak_undefined); + \$hash{undefined_hash} = \$source; +} +undef %hash; +ok(!defined $weak_undefined, 'undefining a hash releases aliased scalar cells'); +is($Issue1649::HashAliasCellOwner::destroyed{undefined_hash} // 0, 1, + 'undefining aliased cells destroys their referents once'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/issue_1649_list_declared_aggregate_weak_owner.t b/src/test/resources/unit/refcount/issue_1649_list_declared_aggregate_weak_owner.t new file mode 100644 index 0000000000..61e4e3a165 --- /dev/null +++ b/src/test/resources/unit/refcount/issue_1649_list_declared_aggregate_weak_owner.t @@ -0,0 +1,51 @@ +use strict; +use warnings; +use Scalar::Util qw(isweak weaken); +use Test::More; +use feature 'signatures'; +no warnings 'experimental::signatures'; + +my ($weak_array, $weak_hash); +{ + my ($array_prefix, @items) = (0, qw(first second)); + my ($hash_prefix, %metadata) = (0, answer => 42); + + $weak_array = \@items; + $weak_hash = \%metadata; + weaken($weak_array); + weaken($weak_hash); + + ok(isweak($weak_array), 'the array observer remains weak'); + ok(isweak($weak_hash), 'the hash observer remains weak'); + ok(defined($weak_array), 'a list-declared lexical array owns its weak referent'); + ok(defined($weak_hash), 'a list-declared lexical hash owns its weak referent'); + is_deeply($weak_array, [qw(first second)], 'the live array remains accessible'); + is_deeply($weak_hash, { answer => 42 }, 'the live hash remains accessible'); +} + +ok(!defined($weak_array), 'the weak array observer clears after lexical scope exit'); +ok(!defined($weak_hash), 'the weak hash observer clears after lexical scope exit'); + +our ($signature_array_weak, $signature_hash_weak); +sub retain_signature_array (@items) { + $signature_array_weak = \@items; + weaken($signature_array_weak); + ok(isweak($signature_array_weak), 'the signature array observer remains weak'); + ok(defined($signature_array_weak), 'the slurpy array pad owns its weak referent'); + is_deeply($signature_array_weak, [qw(left right)], 'the signature array remains accessible'); +} + +sub retain_signature_hash (%metadata) { + $signature_hash_weak = \%metadata; + weaken($signature_hash_weak); + ok(isweak($signature_hash_weak), 'the signature hash observer remains weak'); + ok(defined($signature_hash_weak), 'the slurpy hash pad owns its weak referent'); + is_deeply($signature_hash_weak, { answer => 42 }, 'the signature hash remains accessible'); +} + +retain_signature_array(qw(left right)); +retain_signature_hash(answer => 42); +ok(!defined($signature_array_weak), 'the signature array observer clears after frame exit'); +ok(!defined($signature_hash_weak), 'the signature hash observer clears after frame exit'); + +done_testing; diff --git a/src/test/resources/unit/refcount/issue_1649_localized_global_aggregate_async_owner.t b/src/test/resources/unit/refcount/issue_1649_localized_global_aggregate_async_owner.t new file mode 100644 index 0000000000..e0f1f8c4c2 --- /dev/null +++ b/src/test/resources/unit/refcount/issue_1649_localized_global_aggregate_async_owner.t @@ -0,0 +1,141 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken isweak); + +BEGIN { + package Future; + our $VERSION = '0.52'; + $INC{'Future.pm'} = __FILE__; + + sub done { bless { state => 'done', values => [ @_[1 .. $#_ ] ] }, $_[0] } + sub new { bless { state => 'pending', values => [], callbacks => [], chained => [] }, $_[0] } + sub AWAIT_NEW_DONE { shift->done(@_) } + sub AWAIT_NEW_FAIL { bless { state => 'failed', values => [ @_ ] }, $_[0] } + sub AWAIT_CLONE { ref($_[0])->new } + sub AWAIT_IS_READY { $_[0]{state} ne 'pending' } + sub AWAIT_IS_CANCELLED { $_[0]{state} eq 'cancelled' } + sub AWAIT_GET { die $_[0]{values}[0] if $_[0]{state} eq 'failed'; die 'cancelled' if $_[0]{state} eq 'cancelled'; return $_[0]{values}[0] } + sub AWAIT_ON_READY { my ($self, $cb) = @_; $self->AWAIT_IS_READY ? $cb->($self) : push(@{$self->{callbacks}}, $cb); $self } + sub AWAIT_CHAIN_CANCEL { my ($self, $next) = @_; push(@{$self->{chained}}, $next); $self } + sub AWAIT_DONE { my $self = shift; $self->{state} = 'done'; $self->{values} = [ @_ ]; my @callbacks = @{$self->{callbacks}}; $self->{callbacks} = []; $_->($self) for @callbacks; $self } + sub AWAIT_FAIL { my $self = shift; $self->{state} = 'failed'; $self->{values} = [ @_ ]; my @callbacks = @{$self->{callbacks}}; $self->{callbacks} = []; $_->($self) for @callbacks; $self } + sub AWAIT_CANCEL { my ($self) = @_; return $self if $self->{state} ne 'pending'; $self->{state} = 'cancelled'; my @callbacks = @{$self->{callbacks}}; $self->{callbacks} = []; $_->($self) for @callbacks; my @chained = @{$self->{chained}}; $self->{chained} = []; $_->AWAIT_CANCEL for @chained; return $self } + sub AWAIT_WAIT { $_[0]->AWAIT_GET } +} + +our ($destroyed, $weak_array, $weak_hash); +our ($standard_perl_destroyed, $standard_perl_weak); +our (@localized_array, %localized_hash); +our ($array_gate, $hash_gate, $cancel_gate) = map { Future->new } 1 .. 3; +$destroyed = 0; +$standard_perl_destroyed = 0; + +{ + package Repro::LocalizedGlobalElement; + sub DESTROY { ++$main::destroyed } +} + +{ + package Repro::StandardPerlElement; + sub DESTROY { ++$main::standard_perl_destroyed } +} + +sub check_standard_perl_localized_array_lifetime { + local @main::localized_array = + (bless {}, 'Repro::StandardPerlElement'); + $main::standard_perl_weak = $main::localized_array[0]; + weaken($main::standard_perl_weak); + ok(defined($main::standard_perl_weak) && isweak($main::standard_perl_weak), + 'standard Perl local array strongly owns its element'); + is($main::standard_perl_destroyed, 0, + 'standard Perl does not destroy a localized array element in scope'); +} + +sub check_standard_perl_localized_hash_lifetime { + local %main::localized_hash = ( + value => bless({}, 'Repro::StandardPerlElement')); + $main::standard_perl_weak = $main::localized_hash{value}; + weaken($main::standard_perl_weak); + ok(defined($main::standard_perl_weak) && isweak($main::standard_perl_weak), + 'standard Perl local hash strongly owns its element'); + is($main::standard_perl_destroyed, 1, + 'standard Perl does not destroy a localized hash element in scope'); +} + +check_standard_perl_localized_array_lifetime(); +ok(!defined($standard_perl_weak), + 'standard Perl releases the localized array element at scope exit'); +is($standard_perl_destroyed, 1, + 'standard Perl localized array element DESTROY runs once'); +check_standard_perl_localized_hash_lifetime(); +ok(!defined($standard_perl_weak), + 'standard Perl releases the localized hash element at scope exit'); +is($standard_perl_destroyed, 2, + 'standard Perl localized hash element DESTROY runs once'); + +my $async_source = <<'ASYNC_PERL'; +use Future::AsyncAwait; + +async sub hold_localized_array_element { + local @main::localized_array = + (bless { kind => 'array' }, 'Repro::LocalizedGlobalElement'); + $main::weak_array = $main::localized_array[0]; + weaken($main::weak_array); + await $main::array_gate; +} + +async sub hold_localized_hash_element { + local %main::localized_hash = ( + value => bless({ kind => 'hash' }, 'Repro::LocalizedGlobalElement')); + $main::weak_hash = $main::localized_hash{value}; + weaken($main::weak_hash); + await $main::hash_gate; +} + +async sub hold_cancelled_localized_array_element { + local @main::localized_array = + (bless { kind => 'cancelled array' }, 'Repro::LocalizedGlobalElement'); + $main::weak_array = $main::localized_array[0]; + weaken($main::weak_array); + await $main::cancel_gate; +} +1; +ASYNC_PERL + +my $async_compiled = eval $async_source; + +SKIP: { + skip 'async sub syntax is supported only by the PerlOnJava frontend', 13 + unless $async_compiled; + + my $array_future = hold_localized_array_element(); + ok(defined($weak_array) && isweak($weak_array), + 'localized global array element survives while async frame is suspended'); + is($destroyed, 0, 'localized global array element is not destroyed while suspended'); + $array_gate->AWAIT_DONE(1); + $array_future->AWAIT_GET; + ok(!defined($weak_array), 'localized global array element releases after resume'); + is($destroyed, 1, 'localized global array element DESTROY runs once'); + + my $hash_future = hold_localized_hash_element(); + ok(defined($weak_hash) && isweak($weak_hash), + 'localized global hash element survives while async frame is suspended'); + is($destroyed, 1, 'localized global hash element is not destroyed while suspended'); + $hash_gate->AWAIT_DONE(1); + $hash_future->AWAIT_GET; + ok(!defined($weak_hash), 'localized global hash element releases after resume'); + is($destroyed, 2, 'localized global hash element DESTROY runs once'); + + my $cancel_future = hold_cancelled_localized_array_element(); + ok(defined($weak_array) && isweak($weak_array), + 'localized global array element survives before async cancellation'); + is($destroyed, 2, 'localized global array element remains alive before cancellation'); + $cancel_future->AWAIT_CANCEL; + ok(!defined($weak_array), 'cancellation releases the localized global array element'); + is($destroyed, 3, 'cancelled localized array element DESTROY runs once'); + $cancel_future->AWAIT_CANCEL; + is($destroyed, 3, 'repeated cancellation does not release the localized owner twice'); +} + +done_testing; diff --git a/src/test/resources/unit/refcount/issue_1649_localized_hash_missing_key_release.t b/src/test/resources/unit/refcount/issue_1649_localized_hash_missing_key_release.t new file mode 100644 index 0000000000..fb59a4d79e --- /dev/null +++ b/src/test/resources/unit/refcount/issue_1649_localized_hash_missing_key_release.t @@ -0,0 +1,36 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +package Issue1649::LocalizedHashMissingKey; + +sub DESTROY { + my ($self) = @_; + my $current = exists $main::values{temporary} + ? $main::values{temporary}{id} + : 'absent'; + push @main::DESTROYED, [$self->{id}, $current]; +} + +package main; + +our (%values, @DESTROYED); +@DESTROYED = (); + +my $weak; +{ + local $values{temporary}; + my $temporary = bless { id => 'temporary' }, + 'Issue1649::LocalizedHashMissingKey'; + $weak = $temporary; + weaken($weak); + $values{temporary} = $temporary; +} + +is_deeply(\@DESTROYED, [['temporary', 'absent']], + 'localized missing hash slot is removed before its value is destroyed'); +ok(!defined($weak), 'the localized value weak observer clears on scope exit'); +ok(!exists($values{temporary}), 'scope exit restores the originally absent key'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/issue_1649_localized_hash_retired_owner_identity.t b/src/test/resources/unit/refcount/issue_1649_localized_hash_retired_owner_identity.t new file mode 100644 index 0000000000..cc120e7382 --- /dev/null +++ b/src/test/resources/unit/refcount/issue_1649_localized_hash_retired_owner_identity.t @@ -0,0 +1,38 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +package Issue1649::LocalizedHashRetiredOwner; + +sub DESTROY { + push @main::DESTROYED, $_[0]{id}; +} + +package main; + +our (%values, @DESTROYED); +@DESTROYED = (); + +my ($copy, $weak); +{ + local $values{temporary}; + my $temporary = bless { id => 'temporary' }, + 'Issue1649::LocalizedHashRetiredOwner'; + $copy = $temporary; + $weak = $temporary; + weaken($weak); + $values{temporary} = $temporary; +} + +is_deeply(\@DESTROYED, [], + 'a copied value keeps the localized hash value alive after slot restoration'); +ok(defined($weak), 'the copied value keeps its weak observer defined'); + +undef $copy; +is_deeply(\@DESTROYED, ['temporary'], + 'dropping the last copied reference destroys the localized hash value'); +ok(!defined($weak), 'the weak observer clears after the final copied reference'); +ok(!exists($values{temporary}), 'the original missing hash key stays absent'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/issue_1649_localized_scalar_shared_package_aggregate.t b/src/test/resources/unit/refcount/issue_1649_localized_scalar_shared_package_aggregate.t new file mode 100644 index 0000000000..0aa9e5c87b --- /dev/null +++ b/src/test/resources/unit/refcount/issue_1649_localized_scalar_shared_package_aggregate.t @@ -0,0 +1,50 @@ +use strict; +use warnings; +use Test::More; + +our $destroyed = 0; +our @package_elements; +our %package_values; +our $localized_reference; + +{ + package Repro::LocalizedScalarSharedPackageAggregate; + sub DESTROY { ++$main::destroyed } +} + +@package_elements = (bless {}, 'Repro::LocalizedScalarSharedPackageAggregate'); +{ + local $localized_reference = \@package_elements; +} + +is($destroyed, 0, + 'restoring a localized scalar does not release a package aggregate still in use'); +is(scalar @package_elements, 1, + 'the package aggregate retains its element after the localized scalar is restored'); + +@package_elements = (); +is($destroyed, 1, + 'the package aggregate releases its element when its own slot is cleared'); + +$package_values{kept} = bless {}, 'Repro::LocalizedScalarSharedPackageAggregate'; +{ + local $localized_reference = \%package_values; +} +is($destroyed, 1, + 'restoring a localized scalar does not release a package hash still in use'); +is(scalar keys %package_values, 1, + 'the package hash retains its element after the localized scalar is restored'); + +%package_values = (); +is($destroyed, 2, + 'the package hash releases its element when its own slot is cleared'); + +{ + local $localized_reference = [ + bless {}, 'Repro::LocalizedScalarSharedPackageAggregate' + ]; +} +is($destroyed, 3, + 'a localized scalar releases the elements of its final anonymous aggregate owner'); + +done_testing; diff --git a/src/test/resources/unit/refcount/issue_1649_nested_callback_arrayref_return.t b/src/test/resources/unit/refcount/issue_1649_nested_callback_arrayref_return.t new file mode 100644 index 0000000000..a6e607a7b8 --- /dev/null +++ b/src/test/resources/unit/refcount/issue_1649_nested_callback_arrayref_return.t @@ -0,0 +1,35 @@ +use strict; +use warnings; +use Test::More tests => 4; + +our $destroyed = 0; +our $reference_callbacks = 0; +{ + package NestedArrayRefReturnOwner; + sub DESTROY { ++$main::destroyed } +} + +sub build_results { + my @callbacks = map { + my $as_reference = $_; + sub { + my @items = (bless { branch => $as_reference }, 'NestedArrayRefReturnOwner'); + ++$main::reference_callbacks if $as_reference; + return $as_reference ? \@items : @items; + } + } (0, 1); + + my @middle = map { + my $callback = $_; + map { $callback->() } (1, 2); + } @callbacks; + + return map { $_ } @middle; +} + +my @results = build_results(); +is(scalar @results, 4, 'nested callbacks return all values'); +is($destroyed, 0, 'returned values retain their objects'); +is($reference_callbacks, 2, 'the aggregate-reference callback runs twice'); +undef @results; +is($destroyed, 4, 'discarding the nested callback results releases every object'); diff --git a/src/test/resources/unit/refcount/issue_1649_package_nested_untracked_weak_owner.t b/src/test/resources/unit/refcount/issue_1649_package_nested_untracked_weak_owner.t new file mode 100644 index 0000000000..e30707eb8d --- /dev/null +++ b/src/test/resources/unit/refcount/issue_1649_package_nested_untracked_weak_owner.t @@ -0,0 +1,55 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken isweak); + +{ + package PackageNestedUntrackedWeakOwner; + our @root; +} + +my $weak; +{ + my $target = {}; + @PackageNestedUntrackedWeakOwner::root = ($target); + $weak = $target; + weaken($weak); + + ok(isweak($weak), 'the observer is weak while the package aggregate owns the target'); + ok(defined($weak), 'a nested package owner keeps the weak referent alive'); +} + +ok(defined($weak), 'leaving the original lexical preserves the package-owned referent'); +@PackageNestedUntrackedWeakOwner::root = (); +ok(!defined($weak), 'removing the final package owner clears the weak observer'); + +my $strong_after_unweaken; +my $weak_probe; +my $has_unweaken = eval { + require Scalar::Util; + Scalar::Util->import('unweaken'); + 1; +}; + +SKIP: { + skip 'Scalar::Util::unweaken is unavailable', 3 unless $has_unweaken; + + { + my $target = {}; + @PackageNestedUntrackedWeakOwner::root = ($target); + $strong_after_unweaken = $target; + weaken($strong_after_unweaken); + $weak_probe = $target; + weaken($weak_probe); + Scalar::Util::unweaken($strong_after_unweaken); + } + + @PackageNestedUntrackedWeakOwner::root = (); + ok(defined($strong_after_unweaken), + 'unweakened scalar remains a strong owner after package removal'); + ok(defined($weak_probe), 'the weak probe survives while the unweakened owner lives'); + undef($strong_after_unweaken); + ok(!defined($weak_probe), 'dropping the unweakened owner clears the weak probe'); +} + +done_testing(); diff --git a/src/test/resources/unit/refcount/issue_1649_scalar_slot_transition.t b/src/test/resources/unit/refcount/issue_1649_scalar_slot_transition.t new file mode 100644 index 0000000000..d1e2208eec --- /dev/null +++ b/src/test/resources/unit/refcount/issue_1649_scalar_slot_transition.t @@ -0,0 +1,47 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +package Issue1649::ScalarSlotTransition; + +sub DESTROY { + my ($self) = @_; + my $current = $main::slot; + push @main::DESTROYED, + [$self->{id}, defined($current) ? $current->{id} : 'undef']; +} + +package main; + +our ($slot, @DESTROYED); +@DESTROYED = (); + +my $old = bless { id => 'old' }, 'Issue1649::ScalarSlotTransition'; +$slot = $old; +undef $old; + +my $weak_old = $slot; +weaken($weak_old); +my $copy = $slot; +my $new = bless { id => 'new' }, 'Issue1649::ScalarSlotTransition'; +my $weak_new = $new; +weaken($weak_new); +my $slot_alias = \$slot; + +$slot = $new; +undef $new; +is(scalar @DESTROYED, 0, + 'replacing a slot preserves the old referent while a copied reference owns it'); + +undef $copy; +is_deeply(\@DESTROYED, [['old', 'new']], + 'the displaced referent is destroyed after the slot contains its replacement'); +ok(!defined($weak_old), 'the old weak observer clears with the final strong release'); + +$$slot_alias = undef; +is_deeply(\@DESTROYED, [['old', 'new'], ['new', 'undef']], + 'undef through an alias publishes undef before destroying the old referent'); +ok(!defined($weak_new), 'the new weak observer clears after undef releases its owner'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/issue_1649_suspended_async_end_rescue.t b/src/test/resources/unit/refcount/issue_1649_suspended_async_end_rescue.t new file mode 100644 index 0000000000..b9cc5b2dc8 --- /dev/null +++ b/src/test/resources/unit/refcount/issue_1649_suspended_async_end_rescue.t @@ -0,0 +1,95 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken isweak); + +BEGIN { + package Future; + our $VERSION = '0.52'; + $INC{'Future.pm'} = __FILE__; + + sub done { bless { state => 'done', values => [ @_[1 .. $#_ ] ] }, $_[0] } + sub new { bless { state => 'pending', values => [], callbacks => [], chained => [] }, $_[0] } + sub AWAIT_NEW_DONE { shift->done(@_) } + sub AWAIT_NEW_FAIL { bless { state => 'failed', values => [ @_ ] }, $_[0] } + sub AWAIT_CLONE { ref($_[0])->new } + sub AWAIT_IS_READY { $_[0]{state} ne 'pending' } + sub AWAIT_IS_CANCELLED { $_[0]{state} eq 'cancelled' } + sub AWAIT_GET { die $_[0]{values}[0] if $_[0]{state} eq 'failed'; die 'cancelled' if $_[0]{state} eq 'cancelled'; return $_[0]{values}[0] } + sub AWAIT_ON_READY { my ($self, $cb) = @_; $self->AWAIT_IS_READY ? $cb->($self) : push(@{$self->{callbacks}}, $cb); $self } + sub AWAIT_CHAIN_CANCEL { my ($self, $next) = @_; push(@{$self->{chained}}, $next); $self } + sub AWAIT_DONE { my $self = shift; $self->{state} = 'done'; $self->{values} = [ @_ ]; my @callbacks = @{$self->{callbacks}}; $self->{callbacks} = []; $_->($self) for @callbacks; $self } + sub AWAIT_FAIL { my $self = shift; $self->{state} = 'failed'; $self->{values} = [ @_ ]; my @callbacks = @{$self->{callbacks}}; $self->{callbacks} = []; $_->($self) for @callbacks; $self } + sub AWAIT_CANCEL { + my ($self) = @_; + return $self if $self->{state} ne 'pending'; + $self->{state} = 'cancelled'; + my @callbacks = @{$self->{callbacks}}; + $self->{callbacks} = []; + $_->($self) for @callbacks; + my @chained = @{$self->{chained}}; + $self->{chained} = []; + $_->AWAIT_CANCEL for @chained; + return $self; + } + sub AWAIT_WAIT { $_[0]->AWAIT_GET } +} + +our ($destroyed, $weak, $pending, $returned, $async_ready); +our %rescue_registry; +$destroyed = 0; +$async_ready = 0; +$pending = Future->new; + +{ + package Repro::SuspendedEndRescue; + sub DESTROY { + ++$main::destroyed; + # Resurrect once through a weakened package aggregate slot. The async + # lexical takes ownership and deletes this package slot before await. + $main::rescue_registry{root} = $_[0] + if $main::destroyed == 1; + } +} + +END { + if ($async_ready) { + ok(defined($weak), 'END sees the DESTROY-rescued object through the suspended lexical'); + ok(isweak($weak), 'END observer remains weak while the async frame is pending'); + is($destroyed, 1, 'DESTROY rescued the object exactly once before suspension'); + ok(!exists($rescue_registry{root}), 'no package strong slot remains for the rescued object'); + is($pending->{state}, 'pending', 'the awaited Future remains pending through END'); + is($returned->{state}, 'pending', 'the Future returned by the async sub remains pending through END'); + $returned->AWAIT_CANCEL; + $pending->AWAIT_CANCEL; + done_testing(); + } +} + +my $async_source = <<'ASYNC_PERL'; +use Future::AsyncAwait; + +async sub retain_rescued_root_until_end { + my $held; + my $root = bless {}, 'Repro::SuspendedEndRescue'; + $main::weak = $root; + weaken($main::weak); + + $main::rescue_registry{root} = $root; + weaken($main::rescue_registry{root}); + undef $root; + + $held = $main::rescue_registry{root}; + delete $main::rescue_registry{root}; + await $main::pending; +} + +$main::returned = retain_rescued_root_until_end(); +1; +ASYNC_PERL + +my $compiled = eval $async_source; +if (!$compiled) { + plan skip_all => 'Future::AsyncAwait async syntax is unavailable to this Perl frontend'; +} +$async_ready = 1; diff --git a/src/test/resources/unit/refcount/issue_1649_temporary_closure_argument_owner.t b/src/test/resources/unit/refcount/issue_1649_temporary_closure_argument_owner.t new file mode 100644 index 0000000000..ab03cdf36e --- /dev/null +++ b/src/test/resources/unit/refcount/issue_1649_temporary_closure_argument_owner.t @@ -0,0 +1,32 @@ +use strict; +use warnings; +use Test::More tests => 5; +use Scalar::Util qw(weaken); + +our $saved_callback; +our $destroyed = 0; + +{ + package Issue1649::ArgumentOwner; + sub DESTROY { $main::destroyed++ } +} + +sub retain_and_call { + my ($callback) = @_; + my $captured = $callback->(); + ok(defined $captured, 'temporary callback can read its capture in the callee'); + $saved_callback = $callback; +} + +my $weak; +{ + my $object = bless {}, 'Issue1649::ArgumentOwner'; + weaken($weak = $object); + retain_and_call(sub { $object }); + ok(defined $weak, 'the saved callback retains its capture after caller scope exit'); + is($destroyed, 0, 'the object is not destroyed while the callback is saved'); +} + +undef $saved_callback; +ok(!defined $weak, 'releasing the saved callback releases its captured object'); +is($destroyed, 1, 'the captured object is destroyed exactly once'); diff --git a/src/test/resources/unit/refcount/issue_1794_controller_owner_release.t b/src/test/resources/unit/refcount/issue_1794_controller_owner_release.t new file mode 100644 index 0000000000..1eab25998f --- /dev/null +++ b/src/test/resources/unit/refcount/issue_1794_controller_owner_release.t @@ -0,0 +1,66 @@ +use strict; +use warnings; + +use Test::More; +use Scalar::Util qw(weaken); + +{ + package Issue1794Transaction; + + sub new { bless { events => {} }, shift } + + sub on { + my ($self, $name, $callback) = @_; + push @{$self->{events}{$name}}, $callback; + return $self; + } + + sub finish { shift->emit('finish') } + + sub emit { + my ($self, $name, @args) = @_; + $_->($self, @args) for @{$self->{events}{$name} // []}; + return $self; + } +} + +{ + package Issue1794Controller; + use Scalar::Util qw(weaken); + + sub new { + my ($class, $tx) = @_; + my $self = bless { tx => $tx }, $class; + weaken($self->{tx}); + return $self; + } + + sub on { + my ($self, $name, $callback) = @_; + my $tx = $self->{tx}; + return $tx->on($name => sub { shift; $self->$callback(@_) }); + } + + sub DESTROY { $main::destroyed++ } +} + +our $destroyed = 0; +my $weak_controller; +{ + my $tx = Issue1794Transaction->new; + my $controller = Issue1794Controller->new($tx); + $weak_controller = $controller; + weaken($weak_controller); + + $controller->on(finish => sub { shift }); + $tx->finish; + undef $controller; + + is($destroyed, 0, 'transaction callback keeps controller alive before teardown'); + undef $tx; +} + +is($destroyed, 1, 'controller DESTROY runs when its transaction releases callbacks'); +is($weak_controller, undef, 'controller weak reference clears after transaction teardown'); + +done_testing; diff --git a/src/test/resources/unit/refcount/issue_2043_array_literal_early_exit.t b/src/test/resources/unit/refcount/issue_2043_array_literal_early_exit.t new file mode 100644 index 0000000000..3378f416d1 --- /dev/null +++ b/src/test/resources/unit/refcount/issue_2043_array_literal_early_exit.t @@ -0,0 +1,25 @@ +use strict; +use warnings; +use Test::More; + +our @events; + +{ + package Issue2043::FlushGuard; + sub DESTROY { push @main::events, $_[0]{label} } +} + +sub return_from_array_element { + my $array = [ do { return 'escaped' } ]; + die 'array construction should have exited through return'; +} + +is(return_from_array_element(), 'escaped', + 'return in an array element exits its enclosing subroutine'); + +my $after = bless { label => 'later-local' }, 'Issue2043::FlushGuard'; +undef $after; +is_deeply(\@events, ['later-local'], + 'later lifecycle flushes run after array construction exits early'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/issue_2043_duplicate_aggregate_owners.t b/src/test/resources/unit/refcount/issue_2043_duplicate_aggregate_owners.t new file mode 100644 index 0000000000..0ca93918a5 --- /dev/null +++ b/src/test/resources/unit/refcount/issue_2043_duplicate_aggregate_owners.t @@ -0,0 +1,127 @@ +use strict; +use warnings; +use B (); +use Test::More; +use Scalar::Util qw(weaken); + +our $weak_source; +our @events; + +{ + package Issue2043::DuplicateOwnerSource; + sub DESTROY { push @main::events, 'source-destroyed' } + + package Issue2043::DuplicateOwnerAggregate; + sub DESTROY { } +} + +sub dies_after_duplicate_aggregate_release { + my ($kind) = @_; + @events = (); + + my $source = bless {}, 'Issue2043::DuplicateOwnerSource'; + $weak_source = $source; + weaken($weak_source); + + my $shared = $kind eq 'array' + ? [ $source, $source ] + : { first => $source, second => $source }; + bless $shared, 'Issue2043::DuplicateOwnerAggregate'; + my $root = { nested => $shared }; + my $before = B::svref_2object($source)->REFCNT; + + undef $root; + undef $shared; + my $after = B::svref_2object($source)->REFCNT; + my $weak_alive_after_root = defined $weak_source; + undef $source; + + return [$before - $after, $weak_alive_after_root, + !defined($weak_source), scalar @events]; +} + +sub dies_after_nested_duplicate_aggregate_release { + my ($kind) = @_; + @events = (); + + my $source = bless {}, 'Issue2043::DuplicateOwnerSource'; + $weak_source = $source; + weaken($weak_source); + + my $root = $kind eq 'array' + ? { children => [ $source, $source ] } + : [ { first => $source, second => $source } ]; + my $before = B::svref_2object($source)->REFCNT; + + undef $root; + my $after = B::svref_2object($source)->REFCNT; + my $weak_alive_after_root = defined $weak_source; + undef $source; + + return [$before - $after, $weak_alive_after_root, + !defined($weak_source), scalar @events]; +} + +sub dies_after_sibling_duplicate_aggregate_release { + @events = (); + + my $source = bless {}, 'Issue2043::DuplicateOwnerSource'; + $weak_source = $source; + weaken($weak_source); + + my $root = [ { source => $source }, { source => $source } ]; + my $before = B::svref_2object($source)->REFCNT; + + undef $root; + my $after = B::svref_2object($source)->REFCNT; + my $weak_alive_after_root = defined $weak_source; + undef $source; + + return [$before - $after, $weak_alive_after_root, + !defined($weak_source), scalar @events]; +} + +my ($array_owner_delta, $array_weak_alive, $array_released, $array_destroy_count) = + @{ dies_after_duplicate_aggregate_release('array') }; +is($array_owner_delta, 2, 'array cleanup releases both duplicate owner counts'); +ok($array_weak_alive, 'array cleanup leaves the lexical source alive'); +ok($array_released, 'array cleanup releases the final source owner'); +is($array_destroy_count, 1, 'array duplicate owner releases fire DESTROY once'); + +my ($hash_owner_delta, $hash_weak_alive, $hash_released, $hash_destroy_count) = + @{ dies_after_duplicate_aggregate_release('hash') }; +is($hash_owner_delta, 2, 'hash cleanup releases both duplicate owner counts'); +ok($hash_weak_alive, 'hash cleanup leaves the lexical source alive'); +ok($hash_released, 'hash cleanup releases the final source owner'); +is($hash_destroy_count, 1, 'hash duplicate owner releases fire DESTROY once'); + +my ($nested_array_delta, $nested_array_alive, $nested_array_released, + $nested_array_destroy_count) = + @{ dies_after_nested_duplicate_aggregate_release('array') }; +is($nested_array_delta, 2, + 'nested array cleanup releases both duplicate owner counts'); +ok($nested_array_alive, 'nested array cleanup leaves the lexical source alive'); +ok($nested_array_released, 'nested array cleanup releases the final source owner'); +is($nested_array_destroy_count, 1, + 'nested array duplicate owner releases fire DESTROY once'); + +my ($nested_hash_delta, $nested_hash_alive, $nested_hash_released, + $nested_hash_destroy_count) = + @{ dies_after_nested_duplicate_aggregate_release('hash') }; +is($nested_hash_delta, 2, + 'nested hash cleanup releases both duplicate owner counts'); +ok($nested_hash_alive, 'nested hash cleanup leaves the lexical source alive'); +ok($nested_hash_released, 'nested hash cleanup releases the final source owner'); +is($nested_hash_destroy_count, 1, + 'nested hash duplicate owner releases fire DESTROY once'); + +my ($sibling_delta, $sibling_alive, $sibling_released, $sibling_destroy_count) = + @{ dies_after_sibling_duplicate_aggregate_release() }; +is($sibling_delta, 2, + 'sibling nested aggregate cleanup releases both duplicate owner counts'); +ok($sibling_alive, 'sibling nested cleanup leaves the lexical source alive'); +ok($sibling_released, 'sibling nested cleanup releases the final source owner'); +is($sibling_destroy_count, 1, + 'sibling nested duplicate owner releases fire DESTROY once'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/issue_2043_file_scope_teardown_order.t b/src/test/resources/unit/refcount/issue_2043_file_scope_teardown_order.t new file mode 100644 index 0000000000..7d8183518e --- /dev/null +++ b/src/test/resources/unit/refcount/issue_2043_file_scope_teardown_order.t @@ -0,0 +1,34 @@ +use strict; +use warnings; +use Test::More; + +our @destroy_order; + +{ + package Issue2043::TeardownOrderProbe; + sub DESTROY { + push @main::destroy_order, $_[0]{name}; + } +} + +{ + my $scalar_first = bless { name => 'scalar_first' }, 'Issue2043::TeardownOrderProbe'; + my $scalar_second = bless { name => 'scalar_second' }, 'Issue2043::TeardownOrderProbe'; + my %hash_first = ( + value => bless({ name => 'hash_first' }, 'Issue2043::TeardownOrderProbe'), + ); + my %hash_second = ( + value => bless({ name => 'hash_second' }, 'Issue2043::TeardownOrderProbe'), + ); + my @array = ( + bless({ name => 'array' }, 'Issue2043::TeardownOrderProbe'), + ); +} + +is_deeply( + \@destroy_order, + [qw(hash_second hash_first scalar_second scalar_first array)], + 'lexical teardown reverses hash and scalar declaration order before arrays', +); + +done_testing(); diff --git a/src/test/resources/unit/refcount/issue_2043_interpreted_foreach_source_lifetime.t b/src/test/resources/unit/refcount/issue_2043_interpreted_foreach_source_lifetime.t new file mode 100644 index 0000000000..cd2ff763a6 --- /dev/null +++ b/src/test/resources/unit/refcount/issue_2043_interpreted_foreach_source_lifetime.t @@ -0,0 +1,56 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +our $destroyed_rows = 0; + +{ + package Issue2043::ForeachSourceRow; + + sub DESTROY { + $_[0]{destroyed} = 1; + ++$main::destroyed_rows; + } + + sub related_row { + die "relationship accessed after DESTROY" + if $_[0]{destroyed}; + $_[0]{_relationship_data}{related} ||= bless {}, + 'Issue2043::ForeachSourceRelated'; + } + + package Issue2043::ForeachSourceRelated; +} + +sub all_rows { + my $rows = [ + bless({}, 'Issue2043::ForeachSourceRow'), + bless({}, 'Issue2043::ForeachSourceRow'), + ]; + return @$rows; +} + +my @weak_rows; +for my $row (all_rows()) { + push @weak_rows, $row; + weaken($weak_rows[-1]); + + ok(!$row->{destroyed}, + 'temporary foreach source keeps a row alive after a weak observer is added'); + isa_ok($row->related_row, 'Issue2043::ForeachSourceRelated', + 'relationship cache remains usable during iteration'); +} + +is($destroyed_rows, 2, 'temporary foreach rows are destroyed after iteration'); +is(scalar(grep { defined $_ } @weak_rows), 0, + 'weak observers clear after temporary foreach source is released'); + +my $destroyed_before_last = $destroyed_rows; +for my $row (all_rows()) { + last; +} +is($destroyed_rows - $destroyed_before_last, 2, + 'last releases all rows held by the temporary foreach source'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/issue_2043_list_return_loop_lifetime.t b/src/test/resources/unit/refcount/issue_2043_list_return_loop_lifetime.t new file mode 100644 index 0000000000..0e0b598b31 --- /dev/null +++ b/src/test/resources/unit/refcount/issue_2043_list_return_loop_lifetime.t @@ -0,0 +1,42 @@ +use strict; +use warnings; +use Test::More; + +our @events; + +{ + package Issue2043::LoopRow; + + sub new { bless { id => $_[1] }, $_[0] } + + sub delete { + my ($self) = @_; + push @main::events, 'delete:' . $self->{id} . ':' + . ($self->{destroyed} ? 'destroyed' : 'live'); + $self->{related_resultsets} = {}; + } + + sub DESTROY { + my ($self) = @_; + push @main::events, 'destroy:' . $self->{id}; + $self->{destroyed} = 1; + } +} + +package main; + +sub rows { + return map { Issue2043::LoopRow->new($_) } 1 .. 3; +} + +$_->delete for rows(); + +is_deeply( + [grep { /^delete:/ } @events], + [qw(delete:1:live delete:2:live delete:3:live)], + 'values returned as a list remain alive through the for modifier body', +); +is(scalar grep({ /^destroy:/ } @events), 3, + 'each returned object is destroyed after the loop'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/issue_2043_nested_aggregate_destroy_lifo.t b/src/test/resources/unit/refcount/issue_2043_nested_aggregate_destroy_lifo.t new file mode 100644 index 0000000000..67f5a5ec9b --- /dev/null +++ b/src/test/resources/unit/refcount/issue_2043_nested_aggregate_destroy_lifo.t @@ -0,0 +1,54 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +our ($weak_source, @events); + +{ + package Issue2043::Source; + sub DESTROY { push @main::events, 'source-destroyed' } + + package Issue2043::Probe; + sub DESTROY { + push @main::events, + defined($main::weak_source) ? 'probe-saw-source-live' : 'probe-saw-source-cleared'; + } +} + +sub run_case { + my ($root_kind) = @_; + @events = (); + + my $source = bless {}, 'Issue2043::Source'; + $weak_source = $source; + weaken($weak_source); + + my $nested = { source => $source }; + my $probe = bless {}, 'Issue2043::Probe'; + my $ordered_children = [ $probe, $nested ]; + my $root = $root_kind eq 'hash' + ? { children => $ordered_children } + : $ordered_children; + + undef $source; + undef $nested; + undef $probe; + undef $ordered_children; + undef $root; + return [@events]; +} + +my $array_events = run_case('array'); +is_deeply( + $array_events, + ['source-destroyed', 'probe-saw-source-cleared'], + 'array teardown drains a nested child before its earlier sibling'); + +my $hash_events = run_case('hash'); +is_deeply( + $hash_events, + ['source-destroyed', 'probe-saw-source-cleared'], + 'hash teardown drains a nested child before its earlier sibling'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/lexical_return_slot_owner_release.t b/src/test/resources/unit/refcount/lexical_return_slot_owner_release.t new file mode 100644 index 0000000000..24be455cdc --- /dev/null +++ b/src/test/resources/unit/refcount/lexical_return_slot_owner_release.t @@ -0,0 +1,33 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); +our $destroyed=0; +{ package LexicalReturnOwner; sub DESTROY { ++$main::destroyed } } +sub make { my $value=bless {}, 'LexicalReturnOwner'; $value } +my $object=make();my $weak=$object;weaken($weak);undef $object; +ok(!defined $weak,'return from the lexical register releases its owner'); +is($destroyed,1,'returned lexical referent destroyed exactly once'); +sub make_named { + my ($name) = @_; + my $value = bless { name => $name }, 'LexicalReturnOwner'; + return $value; +} +$object = make_named('later-local'); +$weak = $object; +weaken($weak); +undef $object; +ok(!defined $weak, 'earlier local cleanup preserves the later lexical owner until its release'); +is($destroyed, 2, 'a return shared with a later lexical slot is destroyed once'); +sub make_named_implicit { + my ($name) = @_; + my $value = bless { name => $name }, 'LexicalReturnOwner'; + $value; +} +$object = make_named_implicit('implicit-later-local'); +$weak = $object; +weaken($weak); +undef $object; +ok(!defined $weak, 'implicit return also uses a separate result register'); +is($destroyed, 3, 'multi-local implicit return releases its owner once'); +done_testing(); diff --git a/src/test/resources/unit/refcount/lexical_scalar_refalias_owner_lifetime.t b/src/test/resources/unit/refcount/lexical_scalar_refalias_owner_lifetime.t new file mode 100644 index 0000000000..1d95dd8b9e --- /dev/null +++ b/src/test/resources/unit/refcount/lexical_scalar_refalias_owner_lifetime.t @@ -0,0 +1,32 @@ +use strict; +use warnings; +use feature 'refaliasing'; +no warnings 'experimental::refaliasing'; +use Scalar::Util qw(weaken); +use Test::More; + +{ + package LexicalScalarRefaliasOwnerLifetimeTarget; + our $destroyed = 0; + sub DESTROY { ++$destroyed } +} + +my ($alias, $weak); +{ + my $source = bless {}, 'LexicalScalarRefaliasOwnerLifetimeTarget'; + $weak = $source; + weaken($weak); + \$alias = \$source; +} + +ok(defined $weak, + 'outer lexical refalias retains the source scalar cell after its scope exits'); +is($LexicalScalarRefaliasOwnerLifetimeTarget::destroyed, 0, + 'source referent is not destroyed while the outer alias remains live'); + +undef $alias; +ok(!defined $weak, 'dropping the final lexical alias releases the referent'); +is($LexicalScalarRefaliasOwnerLifetimeTarget::destroyed, 1, + 'referent is destroyed exactly once after the final alias leaves'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/list_assignment_array_tail_releases_displaced_owner.t b/src/test/resources/unit/refcount/list_assignment_array_tail_releases_displaced_owner.t new file mode 100644 index 0000000000..0cb407ed50 --- /dev/null +++ b/src/test/resources/unit/refcount/list_assignment_array_tail_releases_displaced_owner.t @@ -0,0 +1,25 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 5; + +our $DESTROYED = 0; +{ + package ListAssignmentArrayTailOwner; + sub DESTROY { ++$main::DESTROYED } +} + +my $old = bless {}, 'ListAssignmentArrayTailOwner'; +my $old_weak = $old; +weaken($old_weak); +my @tail = ($old); +undef $old; +ok(defined $old_weak, 'the original array element retains its object'); + +my $replacement = bless {}, 'ListAssignmentArrayTailOwner'; +my $prefix; +($prefix, @tail) = (1, $replacement); +is($prefix, 1, 'scalar LHS receives the first RHS value'); +is(scalar @tail, 1, 'array LHS receives the remaining RHS value'); +ok(!defined $old_weak, 'list assignment releases the displaced array element'); +is($DESTROYED, 1, 'the displaced object is destroyed exactly once'); diff --git a/src/test/resources/unit/refcount/list_assignment_hash_tail_releases_displaced_owner.t b/src/test/resources/unit/refcount/list_assignment_hash_tail_releases_displaced_owner.t new file mode 100644 index 0000000000..3b81192af0 --- /dev/null +++ b/src/test/resources/unit/refcount/list_assignment_hash_tail_releases_displaced_owner.t @@ -0,0 +1,25 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 5; + +our $DESTROYED = 0; +{ + package ListAssignmentHashTailOwner; + sub DESTROY { ++$main::DESTROYED } +} + +my $old = bless {}, 'ListAssignmentHashTailOwner'; +my $old_weak = $old; +weaken($old_weak); +my %tail = (old => $old); +undef $old; +ok(defined $old_weak, 'the original hash element retains its object'); + +my $replacement = bless {}, 'ListAssignmentHashTailOwner'; +my $prefix; +($prefix, %tail) = (1, new => $replacement); +is($prefix, 1, 'scalar LHS receives the first RHS value'); +is(scalar keys %tail, 1, 'hash LHS receives the remaining key/value pair'); +ok(!defined $old_weak, 'list assignment releases the displaced hash element'); +is($DESTROYED, 1, 'the displaced object is destroyed exactly once'); diff --git a/src/test/resources/unit/refcount/list_assignment_tied_hash_exception_releases_rhs_owner.t b/src/test/resources/unit/refcount/list_assignment_tied_hash_exception_releases_rhs_owner.t new file mode 100644 index 0000000000..307f922274 --- /dev/null +++ b/src/test/resources/unit/refcount/list_assignment_tied_hash_exception_releases_rhs_owner.t @@ -0,0 +1,47 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 6; + +our $DESTROYED = 0; +{ + package ListAssignmentTiedHashExceptionOwner; + sub DESTROY { ++$main::DESTROYED } +} + +{ + package ListAssignmentTiedHashException; + sub TIEHASH { bless { values => {} }, $_[0] } + sub CLEAR { %{$_[0]{values}} = (); return } + sub FETCH { $_[0]{values}{$_[1]} } + sub STORE { + my ($self, $key, $value) = @_; + die "rejected tied hash store\n" if $key eq 'new'; + $self->{values}{$key} = $value; + } +} + +my $old = bless {}, 'ListAssignmentTiedHashExceptionOwner'; +my $old_weak = $old; +weaken($old_weak); +my %tail; +tie %tail, 'ListAssignmentTiedHashException'; +$tail{old} = $old; +undef $old; +ok(defined $old_weak, 'the tied hash retains its original value'); + +my $replacement = bless {}, 'ListAssignmentTiedHashExceptionOwner'; +my $replacement_weak = $replacement; +weaken($replacement_weak); +my @rhs = (1, new => $replacement); +my $prefix; +my $error = ''; +eval { ($prefix, %tail) = @rhs; 1 } or $error = $@; +like($error, qr/rejected tied hash store/, 'the tied STORE exception propagates'); +ok(!defined $old_weak, 'tied CLEAR releases the displaced hash value'); +ok(defined $replacement_weak, 'the RHS array still owns its replacement'); + +undef @rhs; +undef $replacement; +ok(!defined $replacement_weak, 'failed assignment leaves no temporary RHS owner'); +is($DESTROYED, 2, 'both displaced and rejected values are destroyed exactly once'); diff --git a/src/test/resources/unit/refcount/local_array_return_owner_release.t b/src/test/resources/unit/refcount/local_array_return_owner_release.t new file mode 100644 index 0000000000..5dc460db55 --- /dev/null +++ b/src/test/resources/unit/refcount/local_array_return_owner_release.t @@ -0,0 +1,49 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 8; + +our $destroyed = 0; +{ + package Local::ArrayReturnOwner; + sub DESTROY { ++$main::destroyed } +} + +sub return_local_array { + my @items; + push @items, $_[0]; + return @items; +} + +{ + my $value = bless {}, 'Local::ArrayReturnOwner'; + my $weak = $value; + weaken($weak); + return_local_array($value); + $value = undef; + ok(!defined($weak), 'a discarded local array return releases its element owner'); + is($destroyed, 1, 'void return does not defer destruction past the last real owner'); +} + +{ + my $value = bless {}, 'Local::ArrayReturnOwner'; + my $weak = $value; + weaken($weak); + my $count = return_local_array($value); + $value = undef; + is($count, 1, 'a scalar array return reports its element count'); + ok(!defined($weak), 'a scalar array return retains no element owner'); + is($destroyed, 2, 'scalar return releases one additional object'); +} + +{ + my $value = bless {}, 'Local::ArrayReturnOwner'; + my $weak = $value; + weaken($weak); + my @returned = return_local_array($value); + $value = undef; + ok(defined($weak), 'a list return transfers ownership to the receiving array'); + @returned = (); + ok(!defined($weak), 'clearing the received array releases its element owner'); + is($destroyed, 3, 'list return releases one additional object exactly once'); +} diff --git a/src/test/resources/unit/refcount/localized_array_existing_reference_owner.t b/src/test/resources/unit/refcount/localized_array_existing_reference_owner.t new file mode 100644 index 0000000000..261bec612e --- /dev/null +++ b/src/test/resources/unit/refcount/localized_array_existing_reference_owner.t @@ -0,0 +1,56 @@ +use strict; +use warnings; +use B qw(svref_2object); +use Scalar::Util qw(weaken); +use Test::More tests => 12; + +{ + package LocalizedArrayExistingReferenceOwner; + our %destroyed; + + sub new { + my ($class, $id) = @_; + return bless { id => $id }, $class; + } + + sub DESTROY { + ++$destroyed{$_[0]{id}}; + } +} + +my @values = (LocalizedArrayExistingReferenceOwner->new('outer')); +my $weak_outer = $values[0]; +weaken($weak_outer); +my $weak_local; +sub ref_count { svref_2object($_[0])->REFCNT } + +{ + local $values[0]; + my $inner = LocalizedArrayExistingReferenceOwner->new('inner'); + $weak_local = $inner; + weaken($weak_local); + $values[0] = $inner; + undef $inner; + + ok(defined $weak_outer, 'localization retains the saved outer reference'); + is(ref_count($weak_outer), 1, 'saved outer value has one strong owner'); + ok(defined $weak_local, 'localized slot owns its replacement reference'); + is(ref_count($weak_local), 1, 'localized replacement has one strong owner'); +} + +ok(defined $weak_outer, 'restoring the array slot keeps its original reference'); +is(ref_count($weak_outer), 1, 'restored outer value has one strong owner'); +ok(!defined $weak_local, 'restoring the array slot releases its local reference'); +is($LocalizedArrayExistingReferenceOwner::destroyed{inner}, 1, + 'the localized reference is destroyed exactly once on restore'); +is($LocalizedArrayExistingReferenceOwner::destroyed{outer} || 0, 0, + 'the saved reference is not destroyed during restore'); + +delete $values[0]; +ok(!defined $weak_outer, 'deleting the restored slot releases its reference'); +is($LocalizedArrayExistingReferenceOwner::destroyed{outer}, 1, + 'the restored reference is destroyed exactly once on deletion'); +is($LocalizedArrayExistingReferenceOwner::destroyed{inner}, 1, + 'later cleanup does not repeat localized destruction'); + +done_testing; diff --git a/src/test/resources/unit/refcount/localized_array_size_assignment.t b/src/test/resources/unit/refcount/localized_array_size_assignment.t new file mode 100644 index 0000000000..be9a7be332 --- /dev/null +++ b/src/test/resources/unit/refcount/localized_array_size_assignment.t @@ -0,0 +1,32 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More; + +our $destroyed = 0; +{ + package Issue1649::LocalizedArraySize; + sub DESTROY { ++$main::destroyed } +} + +my @values; +my $weak; +{ + my $object = bless {}, 'Issue1649::LocalizedArraySize'; + $weak = $object; + weaken($weak); + push @values, $object; + undef $object; + + { + local $#values = -1; + is(scalar @values, 0, 'local array length applies its size assignment'); + ok(!defined($weak), 'the removed element releases its referent'); + } + + is(scalar @values, 0, 'local array length is not restored at scope exit'); + ok(!defined($weak), 'scope exit does not restore a dead array element'); + is($destroyed, 1, 'the removed element is destroyed once'); +} + +done_testing(); diff --git a/src/test/resources/unit/refcount/localized_array_slot_owner_release.t b/src/test/resources/unit/refcount/localized_array_slot_owner_release.t new file mode 100644 index 0000000000..14cec04c10 --- /dev/null +++ b/src/test/resources/unit/refcount/localized_array_slot_owner_release.t @@ -0,0 +1,57 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +{ + package LocalizedArraySlotOwner; + our $destroyed = 0; + + sub DESTROY { ++$destroyed } +} + +my $weak; +{ + my @values; + { + local $values[2]; + my $value = bless {}, 'LocalizedArraySlotOwner'; + $weak = $value; + weaken($weak); + $values[2] = $value; + ok(defined($weak), 'localized array slot owns its assigned reference'); + } + + ok(!defined($weak), 'unwinding a new localized array slot releases its reference'); +} + +sub check_localized_array_removal { + my ($operation, $index) = @_; + my $weak; + { + my @values; + local $values[$index]; + my $value = bless {}, 'LocalizedArraySlotOwner'; + $weak = $value; + weaken($weak); + $values[$index] = $value; + undef $value; + + my $removed = $operation eq 'pop' ? pop @values + : $operation eq 'shift' ? shift @values + : delete $values[$index]; + ok(defined($weak), "$operation keeps its returned value alive"); + ok(defined($removed), "$operation returns the localized value"); + undef $removed; + ok(!defined($weak), "$operation releases the removed array owner"); + } +} + +check_localized_array_removal('pop', 0); +check_localized_array_removal('shift', 0); +check_localized_array_removal('delete', 1); + +is($LocalizedArraySlotOwner::destroyed, 4, + 'localized slot removal dispatches DESTROY exactly once per value'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/localized_code_slot_releases_capture.t b/src/test/resources/unit/refcount/localized_code_slot_releases_capture.t new file mode 100644 index 0000000000..b4748a0b5a --- /dev/null +++ b/src/test/resources/unit/refcount/localized_code_slot_releases_capture.t @@ -0,0 +1,30 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 3; + +our @DESTROYED; + +{ + package Issue1649LocalizedCodeCapture::Probe; + + sub DESTROY { + push @main::DESTROYED, 'destroyed'; + } +} + +my $weak; +{ + no warnings qw(redefine once); + my $object = bless {}, 'Issue1649LocalizedCodeCapture::Probe'; + $weak = $object; + weaken($weak); + + local *Issue1649LocalizedCodeCapture::installed = sub { $object }; + ok(defined $weak, 'localized CODE keeps its captured value alive'); +} + +ok(!defined $weak, 'restoring the glob releases its final CODE capture'); +is_deeply(\@DESTROYED, ['destroyed'], 'captured value is destroyed exactly once'); + +done_testing; diff --git a/src/test/resources/unit/refcount/localized_code_state_owner_release.t b/src/test/resources/unit/refcount/localized_code_state_owner_release.t new file mode 100644 index 0000000000..905a3faba4 --- /dev/null +++ b/src/test/resources/unit/refcount/localized_code_state_owner_release.t @@ -0,0 +1,33 @@ +use strict; +use warnings; +use feature 'state'; +use Scalar::Util qw(weaken); +use Test::More; +sub localized_metadata { state $metadata = { value => 10 }; $metadata } +my $original = localized_metadata(); weaken($original); +my ($temporary, $nested); +{ + local *localized_metadata = do { + my $seed = 20; + sub { state $metadata = { value => $seed }; $metadata } + }; + $temporary = localized_metadata(); weaken($temporary); + ok(defined $original, 'saved CODE slot preserves original state'); + is(localized_metadata()->{value}, 20, 'localized CODE owns independent state'); + { + local *localized_metadata = do { + my $seed = 30; + sub { state $metadata = { value => $seed }; $metadata } + }; + $nested = localized_metadata(); weaken($nested); + ok(defined $temporary, 'nested localization preserves outer temporary state'); + is(localized_metadata()->{value}, 30, 'nested CODE owns independent state'); + } + ok(!defined $nested, 'restoring outer slot releases nested CODE state'); + is(localized_metadata()->{value}, 20, 'outer localized CODE is restored'); +} +ok(!defined $temporary, 'restoring original slot releases temporary CODE state'); +is(localized_metadata()->{value}, 10, 'original CODE state is restored'); +undef *localized_metadata; +ok(!defined $original, 'removing final original slot releases original state'); +done_testing(); diff --git a/src/test/resources/unit/refcount/localized_weak_code_slot_ownership.t b/src/test/resources/unit/refcount/localized_weak_code_slot_ownership.t new file mode 100644 index 0000000000..7bb63f2d0e --- /dev/null +++ b/src/test/resources/unit/refcount/localized_weak_code_slot_ownership.t @@ -0,0 +1,32 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 5; + +our ($weak_capture, $weak_cv); + +sub make_cv { + my $captured = bless {}, 'LocalizedWeakCodeSlot::Probe'; + $weak_capture = $captured; + weaken($weak_capture); + my $cv = sub { $captured }; + $weak_cv = $cv; + weaken($weak_cv); + return $cv; +} + +my $other_owner = make_cv(); +{ + no warnings qw(redefine once); + local *LocalizedWeakCodeSlot::target = $weak_cv; + ok(defined $weak_capture, 'localized CODE slot retains its captured object'); + ok(LocalizedWeakCodeSlot::target() == $weak_capture, + 'localized CODE remains callable'); +} +ok(defined $weak_capture, 'independent strong CODE owner survives glob restore'); +ok($other_owner->() == $weak_capture, 'independent CODE owner remains callable'); + +undef $other_owner; +ok(!defined $weak_capture, 'last CODE owner releases the captured object'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/lvalue_sub_returns_local_reference.t b/src/test/resources/unit/refcount/lvalue_sub_returns_local_reference.t new file mode 100644 index 0000000000..2842507f75 --- /dev/null +++ b/src/test/resources/unit/refcount/lvalue_sub_returns_local_reference.t @@ -0,0 +1,24 @@ +use Scalar::Util qw(weaken); +use Test::More tests => 3; + +our ($weak, $destroyed); + +{ + package LvalueLocalReturn::Object; + sub DESTROY { ++$main::destroyed } +} + +sub return_local :lvalue { + my $value = bless {}, 'LvalueLocalReturn::Object'; + $weak = $value; + weaken($weak); + $value; +} + +my $returned = return_local(); +ok($weak, 'callee-local lvalue return remains live in caller'); +is($destroyed // 0, 0, 'object is not destroyed while caller owns the lvalue'); + +undef $returned; +ok(!defined($weak) && $destroyed == 1, + 'weak observer clears and DESTROY runs after the caller releases the lvalue'); diff --git a/src/test/resources/unit/refcount/map_alias_array_cell_lifetime.t b/src/test/resources/unit/refcount/map_alias_array_cell_lifetime.t new file mode 100644 index 0000000000..64cdde3aa9 --- /dev/null +++ b/src/test/resources/unit/refcount/map_alias_array_cell_lifetime.t @@ -0,0 +1,27 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 4; + +{ + package DBICTest::BaseResultSet; +} + +my $resultset = bless {}, 'DBICTest::BaseResultSet'; +my $weak_resultset = $resultset; +weaken($weak_resultset); +my $source = { resultsets => [$resultset] }; +undef $resultset; + +my @mapped = map { + $source->{resultsets} = []; + ok(defined $weak_resultset, + 'map alias retains the scalar cell after the source array is replaced'); + $_->{cursor} ||= {}; + ok(defined $_->{cursor}, 'the active map alias remains usable'); + $_; +} @{$source->{resultsets}}; + +ok(defined $weak_resultset, 'the map result retains the resultset'); +@mapped = (); +ok(!defined $weak_resultset, 'clearing the map result releases the final owner'); diff --git a/src/test/resources/unit/refcount/mojo_route_weak_parent_lifetime.t b/src/test/resources/unit/refcount/mojo_route_weak_parent_lifetime.t new file mode 100644 index 0000000000..24b8f0a246 --- /dev/null +++ b/src/test/resources/unit/refcount/mojo_route_weak_parent_lifetime.t @@ -0,0 +1,62 @@ +use strict; +use warnings; +use Scalar::Util qw(isweak); +use Test::More; + +my $loaded = eval { + require Mojolicious::Controller; + require Mojolicious::Routes; + require Mojolicious::Routes::Match; + 1; +}; +plan skip_all => 'Mojolicious is not installed' unless $loaded; + +# Reparent an existing route subtree before adding a WebSocket branch. This +# exercises the weak parent links after array removal/reinsertion, as in the +# upstream Mojolicious::Routes::Match WebSocket case. +my $root = Mojolicious::Routes->new; +my $source = $root->any('/source')->to('source#'); +my $first = $source->any('/', [format => 0])->any('/first')->to('#first'); +$source->any('/second', [format => ['xml']])->to('#second', format => undef); +my $target = $root->remove->any('/target')->to('target#'); +my $second = $root->find('second'); +is($second->render({}), '/source/second', 'source route starts at its original parent'); +$second->remove; +is($second->render({}), '/second', 'removed route has no parent'); +$target->add_child($first)->add_child($second); +is($second->render({}), '/target/second', 'reparented route follows its new parent'); + +$root->websocket('/websocket' => {testcase => 'ws'}) + ->any('/')->to(action => 'just')->any->to(works => 1); + +my $endpoint; +{ + my $websocket = $root->children->[-1]; + my $nested = $websocket->children->[0]; + $endpoint = $nested->children->[0]; + ok(isweak($endpoint->{parent}), 'route parent is weak before matching'); + ok(defined($endpoint->parent), 'route tree retains the weak parent before matching'); + is($endpoint->root, $root, 'endpoint resolves its root before matching'); +} + +my $controller = Mojolicious::Controller->new; +my $match = Mojolicious::Routes::Match->new(root => $root); +$match->find($controller => {method => 'GET', path => '/websocket'}); +is_deeply($match->stack, [], 'non-WebSocket request does not match'); +ok(isweak($endpoint->{parent}), 'failed match preserves the weak route parent'); +ok(defined($endpoint->parent), 'failed match keeps the route parent alive'); + +$match->find($controller => { + method => 'GET', path => '/websocket', websocket => 1, +}); +is_deeply( + $match->stack, + [{testcase => 'ws', action => 'just', works => 1}], + 'WebSocket request matches through the nested route tree', +); +ok(isweak($match->endpoint->{parent}), 'matching preserves the weak route parent'); +ok(defined($match->endpoint->parent), 'matching preserves the parent referent'); +is($match->path_for->{path}, '/websocket', 'render retains the ancestor path'); +ok($match->path_for->{websocket}, 'render retains WebSocket ancestry'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/mojolicious_promise_async_rejected_owner_release.t b/src/test/resources/unit/refcount/mojolicious_promise_async_rejected_owner_release.t new file mode 100644 index 0000000000..055d4626ee --- /dev/null +++ b/src/test/resources/unit/refcount/mojolicious_promise_async_rejected_owner_release.t @@ -0,0 +1,124 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More; + +{ + package PromiseLoopModel; + + our $SINGLETON; + + sub new { bless {next_tick => [], running => 0}, shift } + sub singleton { $SINGLETON ||= __PACKAGE__->new } + sub next_tick { push @{$_[0]{next_tick}}, $_[1]; return } + sub stop { $_[0]{running} = 0 } + + sub start { + my $self = shift; + local $self->{running} = 1; + while ($self->{running}) { + my $callback = shift @{$self->{next_tick}} + or die 'no pending callback'; + do { + $callback->($self); + } while $callback = shift @{$self->{next_tick}}; + } + } +} + +{ + package PromiseModel; + + sub new { + my $self = bless {resolve => [], reject => []}, shift; + $self->{ioloop} = PromiseLoopModel->singleton; + Scalar::Util::weaken($self->{ioloop}); + return $self; + } + + sub ioloop { $_[0]{ioloop} } + sub clone { ref($_[0])->new } + sub reject { shift->_settle(reject => @_) } + sub resolve { shift->_settle(resolve => @_) } + sub catch { shift->then(undef, shift) } + + sub then { + my ($self, $resolve, $reject) = @_; + my $new = $self->clone; + $self->{handled} = 1; + push @{$self->{resolve}}, sub { _then_cb($new, $resolve, 'resolve', @_) }; + push @{$self->{reject}}, sub { _then_cb($new, $reject, 'reject', @_) }; + $self->_defer if $self->{results}; + return $new; + } + + sub wait { + my $self = shift; + my $loop = $self->ioloop; + return if $loop->{running}; + my $done; + $self->_finally(0, sub { $done++; $loop->stop })->catch(sub { }); + $loop->start until $done; + return; + } + + sub _defer { + my $self = shift; + return unless my $results = $self->{results}; + my $callbacks = $self->{$self->{status}}; + @{$self}{qw(cycle resolve reject)} = (undef, [], []); + $self->ioloop->next_tick(sub { $_->(@$results) for @$callbacks }); + } + + sub _finally { + my ($self, $handled, $finally) = @_; + my $new = $self->clone; + my $cb = sub { + my @results = @_; + $new->resolve($finally->())->then(sub { @results }); + }; + my $before = $self->{handled}; + $self->catch($cb); + my $next = $self->then($cb); + delete $self->{handled} if !$before && !$handled; + return $next; + } + + sub _settle { + my ($self, $status, @results) = @_; + $self = $self->new unless ref $self; + if (!$self->{results}) { + @{$self}{qw(results status)} = (\@results, $status); + $self->_defer; + } + return $self; + } + + sub _then_cb { + my ($new, $cb, $method, @results) = @_; + return $new->$method(@results) unless defined $cb; + my @res; + return $new->reject($@) unless eval { @res = $cb->(@results); 1 }; + return $new->resolve(@res); + } + + sub DESTROY { + my $self = shift; + warn "Unhandled rejected promise: $self->{results}[0]\n" + if $self->{status} && $self->{status} eq 'reject' && !$self->{handled}; + } +} + +my @warnings; +local $SIG{__WARN__} = sub { push @warnings, shift }; + +PromiseModel->reject('two')->then(sub { })->wait; + +like( + $warnings[0] // '', + qr/Unhandled rejected promise: two/, + 'discarded rejected chain warns during wait cleanup' +); +is($warnings[1], undef, 'only one unhandled-rejection warning is delivered'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/named_code_state_owner_release.t b/src/test/resources/unit/refcount/named_code_state_owner_release.t new file mode 100644 index 0000000000..dd6bf345e8 --- /dev/null +++ b/src/test/resources/unit/refcount/named_code_state_owner_release.t @@ -0,0 +1,35 @@ +use strict; +use warnings; +use feature 'state'; +use Scalar::Util qw(weaken); +use Test::More; +sub named_metadata { state $metadata = { value => 1 }; $metadata } +my $weak = named_metadata(); weaken($weak); +my $keeper = \&named_metadata; +undef *named_metadata; +ok(defined $weak, 'external CODE reference retains its state after glob removal'); +is($keeper->()->{value}, 1, 'retained CODE state remains usable without its glob'); +undef $keeper; +ok(!defined $weak, 'final CODE reference releases its state'); +sub aliased_metadata { state $metadata = { value => 2 }; $metadata } +{ + no warnings 'once'; + *alias_metadata = \&aliased_metadata; +} +$weak = aliased_metadata(); weaken($weak); +undef *aliased_metadata; +ok(defined $weak, 'alias CODE slot retains the shared state'); +is(alias_metadata()->{value}, 2, 'alias remains callable after original glob removal'); +undef *alias_metadata; +ok(!defined $weak, 'last CODE alias releases its state'); +our $active_weak; +sub active_metadata { + state $metadata = { value => 3 }; + $active_weak = $metadata; weaken($active_weak); + undef *active_metadata; + ok(defined $active_weak, 'active call keeps state after its glob is removed'); + return $metadata->{value}; +} +is(active_metadata(), 3, 'active call can finish after glob removal'); +ok(!defined $active_weak, 'last active invocation releases its state'); +done_testing(); diff --git a/src/test/resources/unit/refcount/namespace_clean_imported_cv_closure.t b/src/test/resources/unit/refcount/namespace_clean_imported_cv_closure.t new file mode 100644 index 0000000000..8301f28fb6 --- /dev/null +++ b/src/test/resources/unit/refcount/namespace_clean_imported_cv_closure.t @@ -0,0 +1,20 @@ +use strict; +use warnings; +use Test::More tests => 1; + +package Issue2043::ImportedHelper; +use Exporter 'import'; +our @EXPORT_OK; +BEGIN { @EXPORT_OK = qw(gettimeofday) } +sub gettimeofday { 42 } + +package Issue2043::ClosureCaller; +BEGIN { Issue2043::ImportedHelper->import('gettimeofday') } +our $callback = sub { gettimeofday() }; +# Model namespace::clean removing the imported stash entry after this callsite +# has been compiled but before the closure is invoked. +CHECK { delete $Issue2043::ClosureCaller::{gettimeofday} } + +package main; +is($Issue2043::ClosureCaller::callback->(), 42, + 'compiled closure keeps imported CV callable after namespace cleanup'); diff --git a/src/test/resources/unit/refcount/namespace_clean_loaded_module_global_destroy_import_cv.t b/src/test/resources/unit/refcount/namespace_clean_loaded_module_global_destroy_import_cv.t new file mode 100644 index 0000000000..39d04bcd4d --- /dev/null +++ b/src/test/resources/unit/refcount/namespace_clean_loaded_module_global_destroy_import_cv.t @@ -0,0 +1,51 @@ +use strict; +use warnings; +use File::Temp qw(tempdir); + +my $lib_dir = tempdir(CLEANUP => 1); +mkdir "$lib_dir/Issue2043" or die "mkdir $lib_dir/Issue2043: $!"; +open my $module, '>', "$lib_dir/Issue2043/GlobalImportedCV.pm" + or die "open generated module: $!"; +print {$module} <<'MODULE'; +package Issue2043::GlobalImportedCV; +use strict; +use warnings; +use Scalar::Util qw(refaddr); +use namespace::clean; + +our $destructor_calls = 0; +our $last_imported_call_succeeded = 0; +sub DESTROY { + my $address; + my $ok = eval { $address = refaddr($_[0]); 1 }; + $last_imported_call_succeeded = $ok && $address; + ++$destructor_calls; + if ($destructor_calls == 2) { + print $last_imported_call_succeeded + ? "ok 2 - imported CV remains callable during global destruction\n" + : "not ok 2 - imported CV remains callable during global destruction\n"; + } +} +sub imported_call_status { + return ($destructor_calls, $last_imported_call_succeeded); +} + +1; +MODULE +close $module or die "close generated module: $!"; + +unshift @INC, $lib_dir; +require Issue2043::GlobalImportedCV; +print "1..2\n"; +my $first = bless {}, 'Issue2043::GlobalImportedCV'; +undef $first; +my ($destructor_calls, $first_call_succeeded) = + Issue2043::GlobalImportedCV::imported_call_status(); +print $destructor_calls == 1 && $first_call_succeeded + ? "ok 1 - imported CV remains callable after namespace cleanup\n" + : "not ok 1 - imported CV remains callable after namespace cleanup\n"; + +# Global hash values are destroyed after global CV cleanup. Keep a second +# instance there to exercise the imported call from DESTROY at process exit. +our %global_objects; +$global_objects{shutdown} = bless {}, 'Issue2043::GlobalImportedCV'; diff --git a/src/test/resources/unit/refcount/namespace_clean_loaded_module_threaded_import_cv.t b/src/test/resources/unit/refcount/namespace_clean_loaded_module_threaded_import_cv.t new file mode 100644 index 0000000000..b2392665b5 --- /dev/null +++ b/src/test/resources/unit/refcount/namespace_clean_loaded_module_threaded_import_cv.t @@ -0,0 +1,59 @@ +use strict; +use warnings; +use Config; +use File::Temp qw(tempdir); +use Test::More; +BEGIN { + unless ($Config{useithreads}) { + print "1..0 # SKIP system Perl does not support ithreads\n"; + exit 0; + } +} +use threads; + +my $lib_dir = tempdir(CLEANUP => 1); +mkdir "$lib_dir/Issue2043" or die "mkdir $lib_dir/Issue2043: $!"; +open my $module, '>', "$lib_dir/Issue2043/ThreadedImportedCV.pm" + or die "open generated module: $!"; +print {$module} <<'MODULE'; +package Issue2043::ThreadedImportedCV; +use strict; +use warnings; +use Scalar::Util qw/refaddr weaken/; +use namespace::clean; + +{ + my %seek_and_destroy; + + sub register_reference { + weaken($seek_and_destroy{refaddr($_[0])} = $_[0]); + return 1; + } +} + +1; +MODULE +close $module or die "close generated module: $!"; + +unshift @INC, $lib_dir; +require Issue2043::ThreadedImportedCV; + +my $main_result = eval { + Issue2043::ThreadedImportedCV::register_reference({ imported_cv => 1 }); +}; +my $main_error = $@; +ok(!$main_error && $main_result, + 'main interpreter can call the imported CV after runtime module cleanup'); +diag($main_error) if $main_error; + +my $thread = threads->create(sub { + my $result = eval { + Issue2043::ThreadedImportedCV::register_reference({ imported_cv => 1 }); + }; + return [$result, $@]; +}); +my ($result, $error) = @{ $thread->join }; +ok(!$error && $result, + 'thread can call an imported Scalar::Util CV after runtime module cleanup'); +diag($error) if $error; +done_testing; diff --git a/src/test/resources/unit/refcount/native_parser_callback_owner_release.t b/src/test/resources/unit/refcount/native_parser_callback_owner_release.t new file mode 100644 index 0000000000..4182518b4f --- /dev/null +++ b/src/test/resources/unit/refcount/native_parser_callback_owner_release.t @@ -0,0 +1,53 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); +use HTML::Parser; +our $calls = 0; +sub observe_event { ++$calls } +sub fail_event { die "event callback failed\n" } +{ + package NativeParserMethodOwner; + our @ISA = qw(HTML::Parser); + sub observe { ++$main::calls } +} +my $parser = HTML::Parser->new(api_version => 3); +$parser->handler(text => \&observe_event, 'self,text'); +my $weak = $parser; +weaken($weak); +$parser->parse('text'); +$parser->eof; +ok($calls > 0, 'native parser invokes the CODE callback'); +undef $parser; +ok(!defined $weak, 'CODE callback argument arrays release their parser owner'); +$calls = 0; +$parser = NativeParserMethodOwner->new(api_version => 3); +$parser->handler(text => 'observe', 'self,text'); +$weak = $parser; +weaken($weak); +$parser->parse('text'); +$parser->eof; +ok($calls > 0, 'native parser invokes the method callback'); +undef $parser; +ok(!defined $weak, 'method callback argument arrays release their parser owner'); +$parser = HTML::Parser->new(api_version => 3); +$parser->handler(start => \&fail_event, 'self,attr'); +$weak = $parser; +weaken($weak); +eval { $parser->parse('

    ') }; +like($@, qr/event callback failed/, 'native callback exception propagates'); +undef $parser; +ok(!defined $weak, 'exception unwind releases callback argument owners'); +my @events; +$parser = HTML::Parser->new(api_version => 3); +$parser->handler(text => \@events, 'self,text'); +$weak = $parser; +weaken($weak); +$parser->parse('text'); +$parser->eof; +ok(@events > 0, 'accumulator callback stores its event data'); +undef $parser; +ok(defined $weak, 'accumulated self arguments remain genuine strong owners'); +@events = (); +ok(!defined $weak, 'clearing accumulated events breaks the parser cycle'); +done_testing(); diff --git a/src/test/resources/unit/refcount/nested_hash_or_assign_file_temp_owner.t b/src/test/resources/unit/refcount/nested_hash_or_assign_file_temp_owner.t new file mode 100644 index 0000000000..193b88c649 --- /dev/null +++ b/src/test/resources/unit/refcount/nested_hash_or_assign_file_temp_owner.t @@ -0,0 +1,18 @@ +use strict; +use warnings; +use File::Temp; +use Test::More tests => 4; + +my $cache; +$cache ||= {}; +$cache->{capture} ||= {}; +$cache->{capture}{spool} ||= File::Temp->new(UNLINK => 1); + +ok(ref($cache->{capture}{spool}), + 'nested ||= keeps the File::Temp object in its hash slot'); +ok(defined fileno($cache->{capture}{spool}), + 'stored File::Temp handle retains its descriptor'); +ok(print { $cache->{capture}{spool} } "capture probe\n", + 'stored File::Temp handle remains writable'); +ok(defined fileno($cache->{capture}{spool}), + 'stored handle descriptor remains available after write'); diff --git a/src/test/resources/unit/refcount/nested_untracked_aggregate_owner_release.t b/src/test/resources/unit/refcount/nested_untracked_aggregate_owner_release.t new file mode 100644 index 0000000000..46ccf871fd --- /dev/null +++ b/src/test/resources/unit/refcount/nested_untracked_aggregate_owner_release.t @@ -0,0 +1,63 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +our @DESTROYED; +our $RESCUED; +{ + package NestedUntrackedAggregateOwnerRelease::Target; + sub DESTROY { + push @main::DESTROYED, $_[0]{name}; + $main::RESCUED = $_[0] if $_[0]{rescue}; + } +} + +sub nested_owner_graph { + my ($name, $rescue) = @_; + my $target = bless { name => $name, rescue => $rescue }, + 'NestedUntrackedAggregateOwnerRelease::Target'; + my $weak = $target; + weaken($weak); + my $leaf = { target => $target }; + my $level_two = [$leaf]; + my $level_one = { nested => $level_two }; + my $outer = [$level_one]; + return ($outer, $level_one, $weak); +} + +{ + my ($outer, $shared, $weak) = nested_owner_graph('unshared'); + weaken($weak); + undef $shared; + undef $outer; + ok(!defined($weak), + 'releasing mixed nested untracked aggregates releases their deepest target'); +} + +{ + my ($outer, $shared, $weak) = nested_owner_graph('shared'); + weaken($weak); + undef $outer; + ok(defined($weak), 'a surviving shared nested aggregate retains its target'); + undef $shared; + ok(!defined($weak), 'releasing the final nested aggregate owner releases its target'); +} + +{ + my ($outer, $shared, $weak) = nested_owner_graph('rescued', 1); + weaken($weak); + undef $outer; + undef $shared; + ok(defined($weak), 'nested cleanup preserves a target rescued by DESTROY'); + $RESCUED->{rescue} = 0; + undef $RESCUED; + is(scalar @DESTROYED, 4, 'dropping the rescued target invokes its final DESTROY'); +} + +is_deeply( + \@DESTROYED, + [qw(unshared shared rescued rescued)], + 'nested releases and rescue dispatch match Perl destructor order', +); +done_testing(); diff --git a/src/test/resources/unit/refcount/oneshot_callback_self_owner_release.t b/src/test/resources/unit/refcount/oneshot_callback_self_owner_release.t new file mode 100644 index 0000000000..ca71ce31e9 --- /dev/null +++ b/src/test/resources/unit/refcount/oneshot_callback_self_owner_release.t @@ -0,0 +1,79 @@ +use strict; +use warnings; +use feature 'current_sub'; +use Test::More tests => 5; +use Scalar::Util qw(weaken); + +our $destroyed = 0; + +{ + package OneShotOwner; + + sub new { bless {}, shift } + sub touch { 1 } + sub DESTROY { ++$main::destroyed } + + package OneShotEmitter; + use Scalar::Util qw(weaken); + + sub new { bless { events => {} }, shift } + + sub on { + push @{$_[0]{events}{$_[1]}}, $_[2]; + return $_[2]; + } + + sub once { + my ($self, $name, $cb) = @_; + weaken $self; + my $wrapper = sub { + $self->unsubscribe($name => __SUB__); + $cb->(@_); + }; + $self->on($name => $wrapper); + return $wrapper; + } + + sub unsubscribe { + my ($self, $name, $cb) = @_; + if ($cb) { + $self->{events}{$name} = [grep { $cb ne $_ } @{$self->{events}{$name}}]; + delete $self->{events}{$name} unless @{$self->{events}{$name}}; + } + else { + delete $self->{events}{$name}; + } + return $self; + } + + sub subscribers { shift->{events}{shift()} //= [] } + + sub emit { + my ($self, $name) = (shift, shift); + if (my $subscribers = $self->{events}{$name}) { + for my $cb (@$subscribers) { $self->$cb(@_) } + } + return $self; + } +} + +my $emitter = OneShotEmitter->new; +my ($weak_owner, $weak_wrapper); +{ + my $owner = OneShotOwner->new; + $weak_owner = $owner; + weaken($weak_owner); + + my $wrapper = $emitter->once(tick => sub { shift; $owner->touch }); + $weak_wrapper = $wrapper; + weaken($weak_wrapper); +} + +ok defined $weak_owner, 'one-shot callback keeps its captured owner before emission'; +ok defined $weak_wrapper, 'one-shot callback wrapper is registered before emission'; + +$emitter->emit('tick'); + +is $destroyed, 1, 'removing an active self-referential callback releases its capture'; +ok !defined $weak_owner, 'captured owner weak reference clears after one-shot emission'; +ok !defined $weak_wrapper, 'one-shot wrapper weak reference clears after emission'; diff --git a/src/test/resources/unit/refcount/owner_slot_lifecycle_perl_oracle.t b/src/test/resources/unit/refcount/owner_slot_lifecycle_perl_oracle.t new file mode 100644 index 0000000000..0c02079693 --- /dev/null +++ b/src/test/resources/unit/refcount/owner_slot_lifecycle_perl_oracle.t @@ -0,0 +1,118 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken isweak); + +our %DESTROYED; +our (@PACKAGE_CODE, $CODE_WEAK); + +{ + package Issue2043::OwnerSlotLifecycle; + sub new { bless { name => $_[1] }, $_[0] } + sub DESTROY { ++$main::DESTROYED{$_[0]{name}} } +} + +sub make_owner_reader { + my ($value) = @_; + return sub { $value }; +} + +{ + my $left = Issue2043::OwnerSlotLifecycle->new('scalar'); + my $right = $left; + my $weak = $left; + weaken($weak); + + undef $left; + ok(defined($weak), 'one remaining scalar owner keeps the referent alive'); + is($DESTROYED{scalar} || 0, 0, 'DESTROY waits for the final scalar owner'); + + undef $right; + ok(!defined($weak), 'the final scalar owner clears its weak observer'); + is($DESTROYED{scalar}, 1, 'the final scalar release calls DESTROY once'); +} + +{ + my $object = Issue2043::OwnerSlotLifecycle->new('array'); + my $array = [$object]; + my $weak = $object; + weaken($weak); + + undef $object; + ok(defined($weak), 'an array element remains a strong owner'); + is($DESTROYED{array} || 0, 0, 'DESTROY waits while the array slot is live'); + + pop @$array; + ok(!defined($weak), 'removing the final array element clears its weak observer'); + is($DESTROYED{array}, 1, 'array element release calls DESTROY once'); +} + +{ + my $object = Issue2043::OwnerSlotLifecycle->new('closure'); + my $weak = $object; + weaken($weak); + my $reader = make_owner_reader($object); + + undef $object; + ok(defined($weak), 'a live closure capture keeps the referent alive'); + is(ref($reader->()), 'Issue2043::OwnerSlotLifecycle', + 'the closure can still read its captured referent'); + + undef $reader; + ok(!defined($weak), 'releasing the final closure capture clears its weak observer'); + is($DESTROYED{closure}, 1, 'closure release calls DESTROY once'); +} + +{ + $Issue2043::PACKAGE_OWNER = Issue2043::OwnerSlotLifecycle->new('package'); + my $weak = $Issue2043::PACKAGE_OWNER; + weaken($weak); + ok(isweak($weak), 'the package-owner observer is weak'); + ok(defined($weak), 'the package slot keeps the referent alive'); + is($DESTROYED{package} || 0, 0, 'DESTROY waits while the package slot is live'); + + undef $Issue2043::PACKAGE_OWNER; + ok(!defined($weak), 'removing the package owner clears its weak observer'); + is($DESTROYED{package}, 1, 'package-slot release calls DESTROY once'); +} + +{ + my $value = 0; + my $code = sub { ++$value }; + $CODE_WEAK = $code; + weaken($CODE_WEAK); + @PACKAGE_CODE = ($code); + undef $code; + + ok(defined($CODE_WEAK), 'a package array element keeps a capturing CODE value alive'); + is($PACKAGE_CODE[0]->(), 1, 'the captured CODE value remains callable through its array slot'); + + @PACKAGE_CODE = (); + ok(!defined($CODE_WEAK), 'releasing the final array CODE slot clears its weak observer'); +} + +{ + package Issue2043::OwnerSlotTie; + sub TIEHASH { bless { handler => $_[1] }, $_[0] } + sub FETCH { $_[0]->{handler}{$_[1]} } + sub STORE { $_[0]->{handler}{$_[1]} = $_[2] } +} + +{ + my $object = Issue2043::OwnerSlotLifecycle->new('tied'); + my $weak = $object; + weaken($weak); + my $handler = { nested => { target => $object } }; + tie my %tied, 'Issue2043::OwnerSlotTie', $handler; + + undef $object; + undef $handler; + ok(defined($weak), 'the tied handler and nested hash retain the referent'); + is($DESTROYED{tied} || 0, 0, 'DESTROY waits while the nested tied value is live'); + + untie %tied; + ok(!defined($weak), 'untie releases the final nested value owner'); + is($DESTROYED{tied}, 1, 'tied-handler release calls DESTROY once'); +} + +done_testing; diff --git a/src/test/resources/unit/refcount/owner_trace_snapshot.t b/src/test/resources/unit/refcount/owner_trace_snapshot.t deleted file mode 100644 index aa7ef47089..0000000000 --- a/src/test/resources/unit/refcount/owner_trace_snapshot.t +++ /dev/null @@ -1,24 +0,0 @@ -use strict; -use warnings; - -use Test::More; - -plan skip_all => 'PerlOnJava owner-trace diagnostic' unless defined &Internals::jperl_owner_trace; - -my $object = bless {}, 'OwnerTraceSnapshot'; -my $snapshot = Internals::jperl_owner_trace($object); - -like($snapshot, qr/\Abase=\d+ generation=\d+ refCount=-?\d+ active=\[/, - 'snapshot identifies the selected referent and active owner set'); -like($snapshot, qr/ pending=\[\] transient=\[\] semanticCaptureOwners=0\z/, - 'fresh assertion-boundary snapshot has no deferred or transient ownership'); - -my $nested = bless {}, 'OwnerTraceNested'; -Internals::jperl_owner_trace($nested); # enable trace collection before the transient hold -my $scalar_ref = \$nested; -$scalar_ref = undef; -my $nested_snapshot = Internals::jperl_owner_trace($nested); -like($nested_snapshot, qr/ transient=\[\] semanticCaptureOwners=0\z/, - 'scalar-reference contents hold is balanced after release'); - -done_testing; diff --git a/src/test/resources/unit/refcount/package_array_nested_weak_owner_release.t b/src/test/resources/unit/refcount/package_array_nested_weak_owner_release.t new file mode 100644 index 0000000000..67498ff323 --- /dev/null +++ b/src/test/resources/unit/refcount/package_array_nested_weak_owner_release.t @@ -0,0 +1,22 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken isweak); + +our @PACKAGE_OWNER_ROOT; + +my $target = []; +push @PACKAGE_OWNER_ROOT, $target; +my $observer = $target; +weaken($observer); +undef $target; + +ok(isweak($observer), 'package array slot keeps the nested aggregate strongly owned'); +ok(defined($observer), 'weak observer remains live while the package slot exists'); + +pop @PACKAGE_OWNER_ROOT; + +ok(!defined($observer), 'removing the final package slot releases the aggregate'); +ok(!isweak($observer), 'the weak observer clears with the final package owner'); + +done_testing; diff --git a/src/test/resources/unit/refcount/package_io_glob_owner_lifetime.t b/src/test/resources/unit/refcount/package_io_glob_owner_lifetime.t new file mode 100644 index 0000000000..bba3a1e451 --- /dev/null +++ b/src/test/resources/unit/refcount/package_io_glob_owner_lifetime.t @@ -0,0 +1,21 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 3; + +my ($weak_glob, $stash); +{ + no strict 'refs'; + my $package = 'PackageIOGlobOwnerLifetime'; + $stash = \%{"${package}::"}; + my $glob = \*{"${package}::FH"}; + $weak_glob = $glob; + weaken($weak_glob); +} + +ok(defined $weak_glob, 'package glob remains live while its stash slot exists'); +delete $stash->{FH}; +ok(!exists $stash->{FH}, 'stash slot is removed'); +is($weak_glob, undef, 'weak glob clears after its final stash slot is removed'); + +done_testing; diff --git a/src/test/resources/unit/refcount/package_nested_untracked_aggregate_release.t b/src/test/resources/unit/refcount/package_nested_untracked_aggregate_release.t new file mode 100644 index 0000000000..5c547d0bc8 --- /dev/null +++ b/src/test/resources/unit/refcount/package_nested_untracked_aggregate_release.t @@ -0,0 +1,31 @@ +use strict; +use warnings; +use Test::More tests => 6; +use Scalar::Util qw(weaken isweak); + +our @PACKAGE_NESTED_OWNER_ROOT; +our %PACKAGE_NESTED_OWNER_ROOT_HASH; + +my $target = []; +my $weak = $target; +$PACKAGE_NESTED_OWNER_ROOT[0] = $target; +weaken($weak); +undef $target; + +ok(isweak($weak), 'the observer is weak'); +ok(defined($weak), 'the package array keeps the nested aggregate alive'); + +@PACKAGE_NESTED_OWNER_ROOT = (); +ok(!defined($weak), 'clearing the package array releases the final strong slot'); + +my $hash_target = []; +my $hash_weak = $hash_target; +$PACKAGE_NESTED_OWNER_ROOT_HASH{child} = $hash_target; +weaken($hash_weak); +undef $hash_target; + +ok(isweak($hash_weak), 'the hash observer is weak'); +ok(defined($hash_weak), 'the package hash keeps the nested aggregate alive'); + +delete $PACKAGE_NESTED_OWNER_ROOT_HASH{child}; +ok(!defined($hash_weak), 'deleting the package hash entry releases the final strong slot'); diff --git a/src/test/resources/unit/refcount/package_root_nested_array_owner_lifetime.t b/src/test/resources/unit/refcount/package_root_nested_array_owner_lifetime.t new file mode 100644 index 0000000000..07854431a2 --- /dev/null +++ b/src/test/resources/unit/refcount/package_root_nested_array_owner_lifetime.t @@ -0,0 +1,28 @@ +use strict; +use warnings; +use Test::More; +use File::Temp qw(tempfile); + +our $destroyed = 0; +our %cleanup; + +{ + package PackageRootNestedArrayHandle; + + sub DESTROY { + my ($self) = @_; + close $self; + $main::destroyed++; + } +} + +my ($handle, $filename) = tempfile(); +$cleanup{files} = [[ $handle, $filename ]]; +bless $handle, 'PackageRootNestedArrayHandle'; +undef $handle; +is($destroyed, 0, 'nested package-root array keeps its filehandle object alive'); + +delete $cleanup{files}; +unlink $filename or die "unlink $filename: $!"; + +done_testing; diff --git a/src/test/resources/unit/refcount/package_root_survives_first_weakening.t b/src/test/resources/unit/refcount/package_root_survives_first_weakening.t new file mode 100644 index 0000000000..319cfd2e61 --- /dev/null +++ b/src/test/resources/unit/refcount/package_root_survives_first_weakening.t @@ -0,0 +1,16 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken isweak); + +our $PACKAGE_OWNER = []; +my $weak = $PACKAGE_OWNER; + +weaken($weak); +ok(isweak($weak), 'the local alias becomes weak'); +ok(defined($weak), 'the package scalar keeps the referent alive'); + +undef $PACKAGE_OWNER; +ok(!defined($weak), 'removing the final package owner clears the weak alias'); + +done_testing; diff --git a/src/test/resources/unit/refcount/pad_constant_cv_owner_lifetime.t b/src/test/resources/unit/refcount/pad_constant_cv_owner_lifetime.t new file mode 100644 index 0000000000..52f98255ac --- /dev/null +++ b/src/test/resources/unit/refcount/pad_constant_cv_owner_lifetime.t @@ -0,0 +1,82 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken refaddr); +use Test::More; + +{ + no warnings 'redefine'; + sub pad_constant_owner_target { return \q(owned) } +} + +my $old_cv = \&pad_constant_owner_target; +my $strong = $old_cv->(); +my $weak = $strong; +weaken($weak); +undef $strong; + +{ + no warnings 'redefine'; + *pad_constant_owner_target = sub { return undef }; +} + +ok(defined $weak, 'the old CV keeps its pad constant alive after glob replacement'); +my $same_constant = $old_cv->(); +ok(defined $weak && refaddr($weak) == refaddr($same_constant), + 'the retained CV still returns the same constant scalar'); +undef $same_constant; +ok(defined $weak, 'a returned weakly observed constant survives call cleanup'); + +undef $old_cv; +ok(!defined $weak, 'releasing the last old-CV owner reaps its pad constant'); + +{ + no warnings 'redefine'; + sub pad_constant_external_owner_target { return \q(external) } +} + +my $external_cv = \&pad_constant_external_owner_target; +my $external_strong = $external_cv->(); +my $external_weak = $external_strong; +weaken($external_weak); +{ + no warnings 'redefine'; + undef &pad_constant_external_owner_target; +} +undef $external_cv; +ok(defined $external_weak, + 'a caller reference keeps the constant alive after its CV is released'); +undef $external_strong; +ok(!defined $external_weak, + 'the constant is reaped when its final caller reference leaves'); + +{ + no warnings 'redefine'; + sub pad_constant_factory { return sub { return \q(shared) } } +} + +my $factory = \&pad_constant_factory; +my $first_closure = $factory->(); +my $template_weak = $first_closure->(); +weaken($template_weak); +undef $first_closure; +ok(defined $template_weak, + 'the factory CV keeps its nested optree constant alive between closures'); + +my $second_closure = $factory->(); +my $second_constant = $second_closure->(); +ok(defined $template_weak && refaddr($template_weak) == refaddr($second_constant), + 'later closure instances share the nested optree constant identity'); +undef $second_constant; +undef $second_closure; +ok(defined $template_weak, + 'the factory template remains the owner after a closure instance is released'); + +{ + no warnings 'redefine'; + undef &pad_constant_factory; +} +undef $factory; +ok(!defined $template_weak, + 'releasing the factory and its final closure owner reaps the nested constant'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/pad_constant_weak_hash_slot_eval_redefinition.t b/src/test/resources/unit/refcount/pad_constant_weak_hash_slot_eval_redefinition.t new file mode 100644 index 0000000000..621ab27f86 --- /dev/null +++ b/src/test/resources/unit/refcount/pad_constant_weak_hash_slot_eval_redefinition.t @@ -0,0 +1,56 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util (); + +{ + package Issue2043::ReadonlyWeakSlot; + use Scalar::Util (); + + # This mirrors the relevant part of Moo's generated constructor: build a + # temporary argument hash, copy the value into a fresh object hash, then + # weaken the assignment expression itself. + sub new { + my $class = shift; + my $args = scalar @_ == 1 + ? ref $_[0] eq 'HASH' ? { %{ $_[0] } } : die "bad arguments" + : @_ % 2 ? die "odd arguments" : {@_}; + my $object = bless {}, $class; + exists $args->{value} && do { + &Scalar::Util::weaken(($object->{value} = $args->{value})); + no warnings 'void'; + $object->{value}; + }; + return $object; + } +} + +sub issue2043_static_ref { \ 'readonly value' } + +my $object = eval { + Issue2043::ReadonlyWeakSlot->new(value => issue2043_static_ref()); +}; + +if ("$]" < 5.008_003) { + like( + $@, + qr/Reference to readonly value in "value" can not be weakened on Perl < 5.8.3/, + 'old Perl rejects weakening a readonly value', + ); +} +elsif ($^O eq 'cygwin' and "$]" < 5.012_000) { + SKIP: { skip 'Static coderef reaping seems nonfunctional on cygwin < 5.12', 1 } +} +else { + is($@, '', 'constructor accepts the readonly reference inside block eval'); + is(${$object->{value}}, 'readonly value', 'weak field remains live while producer CV is installed'); + ok(Scalar::Util::isweak($object->{value}), 'the object field is weakened'); + + { + no warnings 'redefine'; + *issue2043_static_ref = sub {}; + } + ok(!defined($object->{value}), 'redefining the producer reaps its optree constant'); +} + +done_testing; diff --git a/src/test/resources/unit/refcount/padwalker_rebind_capture_lifecycle.t b/src/test/resources/unit/refcount/padwalker_rebind_capture_lifecycle.t new file mode 100644 index 0000000000..a503ad7abc --- /dev/null +++ b/src/test/resources/unit/refcount/padwalker_rebind_capture_lifecycle.t @@ -0,0 +1,31 @@ +use strict; +use warnings; +use Test::More tests => 5; +use PadWalker qw(set_closed_over); + +our @DESTROYED; + +{ + package Ownership::PadRebindProbe; + + sub DESTROY { + push @main::DESTROYED, $_[0]->{label}; + } +} + +my $old = bless { label => 'old' }, 'Ownership::PadRebindProbe'; +my $closure = sub { $old }; +is($closure->()->{label}, 'old', 'closure begins with the original capture'); + +{ + my $replacement = bless { label => 'replacement' }, 'Ownership::PadRebindProbe'; + set_closed_over($closure, { '$old' => \$replacement }); + is($closure->()->{label}, 'replacement', 'closure uses the rebound capture'); +} + +undef $old; +is_deeply(\@DESTROYED, ['old'], 'the displaced capture is destroyed after its last owner'); +is($closure->()->{label}, 'replacement', 'the closure keeps the replacement cell alive'); +undef $closure; +is_deeply(\@DESTROYED, ['old', 'replacement'], + 'releasing the closure destroys the final replacement capture'); diff --git a/src/test/resources/unit/refcount/perlio_via_self_owner_lifecycle.t b/src/test/resources/unit/refcount/perlio_via_self_owner_lifecycle.t new file mode 100644 index 0000000000..24b00a92f8 --- /dev/null +++ b/src/test/resources/unit/refcount/perlio_via_self_owner_lifecycle.t @@ -0,0 +1,41 @@ +use strict; +use warnings; +use Test::More; +use PerlIO::via; + +our @events; +my $path = "perlio_via_self_owner_$$.tmp"; + +package Local::OwnerVia; + +sub PUSHED { + push @main::events, 'PUSHED'; + return bless {}, $_[0]; +} + +sub WRITE { + print { $_[2] } $_[1]; + return length($_[1]); +} + +sub POPPED { + push @main::events, 'POPPED'; + return 1; +} + +sub DESTROY { + push @main::events, 'DESTROY'; +} + +package main; + +open my $fh, '>:via(Local::OwnerVia)', $path or die "open via layer: $!"; +is_deeply \@events, ['PUSHED'], 'the installed layer owns its PUSHED object'; +print {$fh} 'x'; +is_deeply \@events, ['PUSHED'], 'callbacks run before the layer releases its object'; +close $fh or die "close via layer: $!"; +is_deeply \@events, ['PUSHED', 'POPPED', 'DESTROY'], + 'the layer releases its object after POPPED'; + +unlink $path; +done_testing; diff --git a/src/test/resources/unit/refcount/postfix_argument_alias_releases_old_reference.t b/src/test/resources/unit/refcount/postfix_argument_alias_releases_old_reference.t new file mode 100644 index 0000000000..5aeb5fb3f9 --- /dev/null +++ b/src/test/resources/unit/refcount/postfix_argument_alias_releases_old_reference.t @@ -0,0 +1,53 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More; + +our $destroyed = 0; + +{ + package PostfixArgumentOwner; + use overload '0+' => sub { 1 }, fallback => 1; + sub DESTROY { ++$main::destroyed } +} + +sub postfix_argument { $_[0]++ } +sub postfix_argument_decrement { $_[0]-- } + +my ($weak, $old); +{ + my $object = bless {}, 'PostfixArgumentOwner'; + $weak = $object; + weaken($weak); + + $old = postfix_argument($object); + is(ref($old), 'PostfixArgumentOwner', + 'postfix through an argument alias returns the old reference'); + ok(!ref($object), 'postfix through an argument alias updates the caller scalar'); + ok(defined $weak, 'the returned old reference keeps its referent alive'); +} + +ok(defined $weak, 'postfix result retains the referent after source scope exit'); +undef $old; +ok(!defined $weak, 'dropping the postfix result releases the old referent'); +is($destroyed, 1, 'postfix referent is destroyed exactly once'); + +my ($weak_decrement, $old_decrement); +{ + my $object = bless {}, 'PostfixArgumentOwner'; + $weak_decrement = $object; + weaken($weak_decrement); + + $old_decrement = postfix_argument_decrement($object); + is(ref($old_decrement), 'PostfixArgumentOwner', + 'postfix decrement through an argument alias returns the old reference'); + ok(!ref($object), 'postfix decrement through an argument alias updates the caller scalar'); + ok(defined $weak_decrement, 'the returned old reference keeps its referent alive'); +} + +ok(defined $weak_decrement, 'postfix decrement result retains the referent after source scope exit'); +undef $old_decrement; +ok(!defined $weak_decrement, 'dropping the postfix decrement result releases the old referent'); +is($destroyed, 2, 'postfix increment and decrement referents are each destroyed once'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/postfix_reference_temporary_owner.t b/src/test/resources/unit/refcount/postfix_reference_temporary_owner.t new file mode 100644 index 0000000000..72cde2b560 --- /dev/null +++ b/src/test/resources/unit/refcount/postfix_reference_temporary_owner.t @@ -0,0 +1,43 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(refaddr); + +{ + package Local::PostfixReferenceOwner; + use overload '++' => sub { + ++$_[0]->{value}; + return $_[0]; + }, fallback => 1; + + our $destroy_count = 0; + + sub new { + return bless { value => 0 }, shift; + } + + sub DESTROY { + ++$destroy_count; + } +} + +my $current = Local::PostfixReferenceOwner->new; +my $address = refaddr($current); +my $previous = $current++; + +is(refaddr($current), $address, + 'postfix increment leaves the updated scalar owning the referent'); +is(refaddr($previous), $address, + 'the postfix result keeps the same referent alive'); +is($current->{value}, 1, 'the overloaded increment updates the referent'); + +undef $previous; +is($Local::PostfixReferenceOwner::destroy_count, 0, + 'dropping the postfix result does not destroy the live scalar value'); +is($current->{value}, 1, 'the scalar value remains usable'); + +undef $current; +is($Local::PostfixReferenceOwner::destroy_count, 1, + 'the referent is destroyed after its final Perl owner leaves'); + +done_testing; diff --git a/src/test/resources/unit/refcount/reentrant_overwrite_weaken_keeps_other_owner.t b/src/test/resources/unit/refcount/reentrant_overwrite_weaken_keeps_other_owner.t new file mode 100644 index 0000000000..a141d3fccf --- /dev/null +++ b/src/test/resources/unit/refcount/reentrant_overwrite_weaken_keeps_other_owner.t @@ -0,0 +1,32 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken isweak); +use Test::More tests => 5; + +package Issue1649::ReentrantWeakOwner; + +sub new { bless { name => $_[1] }, $_[0] } + +sub DESTROY { + my ($self) = @_; + push @main::destroyed, $self->{name}; + if ($self->{name} eq 'old') { + $main::keeper = $main::slot; + Scalar::Util::weaken($main::slot); + } +} + +package main; + +our (@destroyed, $slot, $keeper); +$slot = Issue1649::ReentrantWeakOwner->new('old'); +$slot = Issue1649::ReentrantWeakOwner->new('replacement'); + +ok(isweak($slot), 'the old destructor leaves the replacement slot weak'); +is($slot->{name}, 'replacement', 'the weakened slot still observes the replacement'); +is_deeply(\@destroyed, ['old'], 'the keeper retains the replacement through overwrite'); + +undef $keeper; +ok(!defined($slot), 'releasing the keeper clears the weak slot'); +is_deeply(\@destroyed, [qw(old replacement)], + 'the replacement is destroyed when the last strong owner leaves'); diff --git a/src/test/resources/unit/refcount/refalias_array_cell_owner_mutations.t b/src/test/resources/unit/refcount/refalias_array_cell_owner_mutations.t new file mode 100644 index 0000000000..e302d0ba2c --- /dev/null +++ b/src/test/resources/unit/refcount/refalias_array_cell_owner_mutations.t @@ -0,0 +1,80 @@ +use strict; +use warnings; +use feature 'refaliasing'; +no warnings 'experimental::refaliasing'; +use Scalar::Util qw(weaken); +use Test::More; + +{ + package RefaliasArrayCellOwnerMutationTarget; + our %destroyed; + sub DESTROY { ++$destroyed{$_[0]{id}} } +} + +my (@deleted, @replaced, @spliced); +my ($weak_deleted, $weak_replaced, $weak_spliced); +my %observed; + +{ + my $object = bless {id => 'deleted'}, 'RefaliasArrayCellOwnerMutationTarget'; + $weak_deleted = $object; + weaken($weak_deleted); + \(@deleted) = \($object); +} +$observed{delete_kept_cell} = defined $weak_deleted; +$observed{delete_alive_before} = + ($RefaliasArrayCellOwnerMutationTarget::destroyed{deleted} // 0) == 0; +delete $deleted[0]; +$observed{delete_released} = !defined $weak_deleted; +$observed{delete_destroyed_once} = + ($RefaliasArrayCellOwnerMutationTarget::destroyed{deleted} // 0) == 1; + +{ + my $object = bless {id => 'replaced'}, 'RefaliasArrayCellOwnerMutationTarget'; + $weak_replaced = $object; + weaken($weak_replaced); + \(@replaced) = \($object); +} +$observed{replacement_kept_cell} = defined $weak_replaced; +$observed{replacement_alive_before} = + ($RefaliasArrayCellOwnerMutationTarget::destroyed{replaced} // 0) == 0; +{ + my $replacement = 1; + \($replaced[0]) = \($replacement); +} +$observed{replacement_released} = !defined $weak_replaced; +$observed{replacement_destroyed_once} = + ($RefaliasArrayCellOwnerMutationTarget::destroyed{replaced} // 0) == 1; + +{ + my $object = bless {id => 'spliced'}, 'RefaliasArrayCellOwnerMutationTarget'; + $weak_spliced = $object; + weaken($weak_spliced); + \(@spliced) = \($object); +} +$observed{splice_kept_cell} = defined $weak_spliced; +$observed{splice_alive_before} = + ($RefaliasArrayCellOwnerMutationTarget::destroyed{spliced} // 0) == 0; +splice @spliced, 0, 1; +$observed{splice_released} = !defined $weak_spliced; +$observed{splice_destroyed_once} = + ($RefaliasArrayCellOwnerMutationTarget::destroyed{spliced} // 0) == 1; + +ok($observed{delete_kept_cell}, 'delete case retains the aliased cell after lexical exit'); +ok($observed{delete_alive_before}, 'delete target is not destroyed while the alias slot lives'); +ok($observed{delete_released}, 'deleting the slot releases its aliased cell'); +ok($observed{delete_destroyed_once}, 'delete destroys the referent exactly once'); +ok($observed{replacement_kept_cell}, + 'replacement case retains the aliased cell after lexical exit'); +ok($observed{replacement_alive_before}, + 'replacement target is not destroyed while the alias slot lives'); +ok($observed{replacement_released}, + 'replacing the slot releases its prior aliased cell'); +ok($observed{replacement_destroyed_once}, + 'replacement destroys the displaced referent exactly once'); +ok($observed{splice_kept_cell}, 'splice case retains the aliased cell after lexical exit'); +ok($observed{splice_alive_before}, 'splice target is not destroyed while the alias slot lives'); +ok($observed{splice_released}, 'splice removal releases its aliased cell'); +ok($observed{splice_destroyed_once}, 'splice destroys the referent exactly once'); + +done_testing; diff --git a/src/test/resources/unit/refcount/refalias_array_cell_owner_release.t b/src/test/resources/unit/refcount/refalias_array_cell_owner_release.t new file mode 100644 index 0000000000..b9e05c1534 --- /dev/null +++ b/src/test/resources/unit/refcount/refalias_array_cell_owner_release.t @@ -0,0 +1,31 @@ +use strict; +use warnings; +use feature 'refaliasing'; +no warnings 'experimental::refaliasing'; +use Scalar::Util qw(weaken); +use Test::More; + +{ + package RefaliasArrayCellOwnerTarget; + our $destroyed = 0; + sub DESTROY { ++$destroyed } +} + +my @alias; +my $weak; +{ + my $object = bless {}, 'RefaliasArrayCellOwnerTarget'; + $weak = $object; + weaken($weak); + \(@alias) = \($object); +} + +ok(defined $weak, 'aliased array slot retains the scalar cell after lexical scope exit'); +is($RefaliasArrayCellOwnerTarget::destroyed, 0, + 'referent is not destroyed while the alias slot lives'); +@alias = (); +ok(!defined $weak, 'clearing the final alias slot releases the referent'); +is($RefaliasArrayCellOwnerTarget::destroyed, 1, + 'referent is destroyed exactly once'); + +done_testing; diff --git a/src/test/resources/unit/refcount/refalias_array_distinct_lexical_cells.t b/src/test/resources/unit/refcount/refalias_array_distinct_lexical_cells.t new file mode 100644 index 0000000000..8fe8d0245c --- /dev/null +++ b/src/test/resources/unit/refcount/refalias_array_distinct_lexical_cells.t @@ -0,0 +1,46 @@ +use strict; +use warnings; +use feature 'refaliasing'; +no warnings 'experimental::refaliasing'; +use Scalar::Util qw(weaken); +use Test::More; + +{ + package RefaliasArrayDistinctLexicalTarget; + our %destroyed; + sub DESTROY { ++$destroyed{$_[0]{id}} } +} + +my (@first, @second); +my ($weak_first, $weak_second); +{ + my $object = bless {id => 'first'}, 'RefaliasArrayDistinctLexicalTarget'; + $weak_first = $object; + weaken($weak_first); + \(@first) = \($object); +} +{ + my $object = bless {id => 'second'}, 'RefaliasArrayDistinctLexicalTarget'; + $weak_second = $object; + weaken($weak_second); + \(@second) = \($object); +} + +ok(defined $weak_first, + 'the first aliased cell survives a later same-named lexical declaration'); +ok(defined $weak_second, 'the second aliased cell survives its lexical scope'); +is($first[0]{id}, 'first', 'the first array still refers to its original cell'); +is($second[0]{id}, 'second', 'the second array refers to its own cell'); + +@second = (); +ok(!defined $weak_second, 'clearing the second array releases its referent'); +ok(defined $weak_first, 'the first array keeps its referent alive'); +is($RefaliasArrayDistinctLexicalTarget::destroyed{first} // 0, 0, + 'the first referent was not destroyed with the second'); + +@first = (); +ok(!defined $weak_first, 'clearing the first array releases its referent'); +is($RefaliasArrayDistinctLexicalTarget::destroyed{first}, 1, + 'the first referent is destroyed exactly once'); + +done_testing; diff --git a/src/test/resources/unit/refcount/refalias_array_element_cell_owner.t b/src/test/resources/unit/refcount/refalias_array_element_cell_owner.t new file mode 100644 index 0000000000..07d0e33e8b --- /dev/null +++ b/src/test/resources/unit/refcount/refalias_array_element_cell_owner.t @@ -0,0 +1,49 @@ +use strict; +use warnings; +use feature 'refaliasing'; +no warnings 'experimental::refaliasing'; +use Scalar::Util qw(weaken); +use Test::More; + +{ + package RefaliasArrayElementCellOwnerTarget; + our %destroyed; + sub DESTROY { ++$destroyed{$_[0]{id}} } +} + +my @single_alias; +my $weak_single; +{ + my $source = bless { id => 'single' }, 'RefaliasArrayElementCellOwnerTarget'; + $weak_single = $source; + weaken($weak_single); + \($single_alias[0]) = \($source); +} +ok(defined $weak_single, + 'an array element refalias retains its source cell after lexical exit'); +is($RefaliasArrayElementCellOwnerTarget::destroyed{single} // 0, 0, + 'the referent remains alive while its aliased array slot exists'); +$single_alias[0] = undef; +ok(!defined $weak_single, 'replacing the final aliased slot releases its source cell'); +is($RefaliasArrayElementCellOwnerTarget::destroyed{single}, 1, + 'the single-slot referent is destroyed exactly once'); + +my @duplicate_aliases; +my $weak_duplicate; +{ + my $object = bless { id => 'duplicate' }, 'RefaliasArrayElementCellOwnerTarget'; + my ($first_source, $second_source) = ($object, $object); + $weak_duplicate = $object; + weaken($weak_duplicate); + \($duplicate_aliases[0]) = \($first_source); + \($duplicate_aliases[1]) = \($second_source); +} +ok(defined $weak_duplicate, 'two array slots retain distinct source cells for the same referent'); +$duplicate_aliases[0] = undef; +ok(defined $weak_duplicate, 'replacing one slot preserves the other alias'); +$duplicate_aliases[1] = undef; +ok(!defined $weak_duplicate, 'replacing the last alias releases the source cell'); +is($RefaliasArrayElementCellOwnerTarget::destroyed{duplicate}, 1, + 'the shared referent is destroyed exactly once'); + +done_testing; diff --git a/src/test/resources/unit/refcount/refalias_cell_refcount.t b/src/test/resources/unit/refcount/refalias_cell_refcount.t new file mode 100644 index 0000000000..db27f417ea --- /dev/null +++ b/src/test/resources/unit/refcount/refalias_cell_refcount.t @@ -0,0 +1,42 @@ +use strict; +use warnings; +use feature 'refaliasing'; +no warnings 'experimental::refaliasing'; +use B qw(svref_2object); +use Scalar::Util qw(refaddr); +use Test::More tests => 6; + +sub refcount { svref_2object($_[0])->REFCNT } + +my $object = bless {}, 'Local::RefaliasCellRefcount'; +my $source = $object; +my $source_cell = \$source; +my $cell_count_before = refcount($source_cell); +my $referent_count_before = refcount($source); + +{ + my $alias; + \$alias = $source_cell; + + is(refaddr(\$alias), refaddr($source_cell), + 'refalias names the same scalar cell'); + is(refcount($source_cell), $cell_count_before + 1, + 'refalias increments the scalar cell refcount'); + is(refcount($source), $referent_count_before, + 'refalias does not add another owner of the cell contents'); +} + +is(refcount($source_cell), $cell_count_before, + 'leaving the alias scope releases the scalar cell refcount'); + +my $cell_count_before_eval = refcount($source_cell); +eval { + my $alias; + \$alias = $source_cell; + die "leave eval scope\n"; +}; +ok($@, 'eval catches the scope-exit exception'); +is(refcount($source_cell), $cell_count_before_eval, + 'eval exception cleanup releases the scalar cell refcount'); + +done_testing; diff --git a/src/test/resources/unit/refcount/repeated_container_edges_release.t b/src/test/resources/unit/refcount/repeated_container_edges_release.t new file mode 100644 index 0000000000..8edcda9425 --- /dev/null +++ b/src/test/resources/unit/refcount/repeated_container_edges_release.t @@ -0,0 +1,32 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 6; + +our $destroyed = 0; +{ + package Local::RepeatedContainerEdge; + sub DESTROY { ++$main::destroyed } +} + +my $value = bless {}, 'Local::RepeatedContainerEdge'; +my $weak = $value; +weaken($weak); +my $nested = [{ left => $value, right => $value }]; +$value = undef; +ok(defined($weak), 'two nested element slots keep their shared referent alive'); + +$nested = undef; +ok(!defined($weak), 'dropping the outer owner releases both nested element slots'); +is($destroyed, 1, 'the shared referent is destroyed exactly once'); + +my $cycle = bless {}, 'Local::RepeatedContainerEdge'; +$cycle->{self} = $cycle; +my $weak_cycle = $cycle; +weaken($weak_cycle); +$cycle = undef; +ok(defined($weak_cycle), 'a strong cycle survives the final external owner'); + +delete $weak_cycle->{self}; +ok(!defined($weak_cycle), 'breaking the cycle releases its final strong element'); +is($destroyed, 2, 'cycle cleanup runs one additional destructor'); diff --git a/src/test/resources/unit/refcount/returned_object_survives_local_hash_restore.t b/src/test/resources/unit/refcount/returned_object_survives_local_hash_restore.t new file mode 100644 index 0000000000..20a4b38f01 --- /dev/null +++ b/src/test/resources/unit/refcount/returned_object_survives_local_hash_restore.t @@ -0,0 +1,33 @@ +use strict; +use warnings; +use Test::More tests => 4; +use Scalar::Util qw(weaken); + +{ + package LocalizedHashReturn; + our @destroyed; + + sub new { bless { value => 1 }, shift } + sub DESTROY { push @destroyed, 'destroyed' } +} + +our %state = (slot => 'original'); + +sub transaction { + local $state{slot} = 'temporary'; + my $value = LocalizedHashReturn->new; + return $value; +} + +my $returned = transaction(); +is scalar @LocalizedHashReturn::destroyed, 0, + 'localized hash restoration preserves a returned object'; + +my $weak = $returned; +weaken($weak); +isa_ok $weak, 'LocalizedHashReturn', 'the returned object remains live'; + +undef $returned; +is scalar @LocalizedHashReturn::destroyed, 1, + 'the object is destroyed after its final owner is released'; +ok !defined($weak), 'the weak observer clears at final destruction'; diff --git a/src/test/resources/unit/refcount/scalar_cell_return_contents_owner.t b/src/test/resources/unit/refcount/scalar_cell_return_contents_owner.t new file mode 100644 index 0000000000..fda06cc724 --- /dev/null +++ b/src/test/resources/unit/refcount/scalar_cell_return_contents_owner.t @@ -0,0 +1,28 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); +our @destroyed; +{ package ReturnedCellChild; sub DESTROY { push @main::destroyed, $_[0]{name} } } +sub implicit_cell { + my ($name) = @_; + \(my $value = bless { name => $name }, 'ReturnedCellChild'); +} +sub explicit_cell { + my ($name) = @_; + my $value = bless { name => $name }, 'ReturnedCellChild'; + return \$value; +} +for my $factory (\&implicit_cell, \&explicit_cell) { + my $name = $factory == \&implicit_cell ? 'implicit' : 'explicit'; + my $cell = $factory->($name); + my $weak = $$cell; + weaken($weak); + is($$cell->{name}, $name, "$name return preserves the cell's contents"); + ok(defined $weak, "$name return owns its contents after lexical exit"); + $$cell = undef; + ok(!defined $weak, "$name return releases contents on assignment through the cell"); + is_deeply(\@destroyed, $name eq 'implicit' ? ['implicit'] : ['implicit', 'explicit'], + "$name cell contents are destroyed exactly once"); +} +done_testing(); diff --git a/src/test/resources/unit/refcount/scalar_cell_scope_owner_release.t b/src/test/resources/unit/refcount/scalar_cell_scope_owner_release.t new file mode 100644 index 0000000000..59ecd7690d --- /dev/null +++ b/src/test/resources/unit/refcount/scalar_cell_scope_owner_release.t @@ -0,0 +1,45 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +my $bootstrap = []; +weaken($bootstrap); +my $weak; +{ + my $value = 42; + $weak = \$value; + weaken($weak); + ok(defined $weak, 'lexical cell stays alive in scope'); + is($$weak, 42, 'lexical cell keeps its value'); + undef $value; + ok(defined $weak, 'undef changes contents while cell remains alive'); + ok(!defined $$weak, 'weak cell sees undef contents'); +} +ok(!defined $weak, 'final lexical owner releases its scalar cell'); + +my $strong; +{ + my $value = 'held'; + $strong = \$value; + $weak = \$value; + weaken($weak); +} +ok(defined $weak, 'escaped strong reference owns the cell after scope'); +is($$strong, 'held', 'escaped cell retains contents'); +undef $strong; +ok(!defined $weak, 'final escaped reference releases the cell'); + +my $callback; +{ + my $value = 7; + $weak = \$value; + weaken($weak); + $callback = sub { $value }; +} +ok(defined $weak, 'closure owns the captured scalar cell'); +is($callback->(), 7, 'captured cell retains contents'); +undef $callback; +ok(!defined $weak, 'final capture releases the scalar cell'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/scalar_reentrant_overwrite_weaken_order.t b/src/test/resources/unit/refcount/scalar_reentrant_overwrite_weaken_order.t new file mode 100644 index 0000000000..ffcaf16b7a --- /dev/null +++ b/src/test/resources/unit/refcount/scalar_reentrant_overwrite_weaken_order.t @@ -0,0 +1,57 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 8; + +package Local::ReentrantOverwrite; + +sub new { bless { name => $_[1] }, $_[0] } + +sub DESTROY { + my ($self) = @_; + my ($phase, $slot_kind) = split /-/, $self->{name}, 2; + if ($phase eq 'old') { + my $slot = $slot_kind eq 'scalar' ? $main::v + : $slot_kind eq 'hash' ? $main::h->{slot} + : $main::a->[0]; + $main::old_saw_replacement{$slot_kind} = + ref($slot) eq __PACKAGE__ && $slot->{name} eq "new-$slot_kind"; + if ($slot_kind eq 'scalar') { + Scalar::Util::weaken($main::v); + } elsif ($slot_kind eq 'hash') { + Scalar::Util::weaken($main::h->{slot}); + } else { + Scalar::Util::weaken($main::a->[0]); + } + } + push @main::destroyed, $self->{name}; +} + +package main; + +our (@destroyed, %old_saw_replacement, $v, $h, $a); +$h = { slot => undef }; +$a = [undef]; + +$v = Local::ReentrantOverwrite->new('old-scalar'); +$v = Local::ReentrantOverwrite->new('new-scalar'); +$h->{slot} = Local::ReentrantOverwrite->new('old-hash'); +$h->{slot} = Local::ReentrantOverwrite->new('new-hash'); +$a->[0] = Local::ReentrantOverwrite->new('old-array'); +$a->[0] = Local::ReentrantOverwrite->new('new-array'); + +is_deeply(\@destroyed, + [qw(old-scalar new-scalar old-hash new-hash old-array new-array)], + 'each old value is destroyed before its weakened replacement'); +is_deeply([grep { /-scalar\z/ } @destroyed], [qw(old-scalar new-scalar)], + 'package scalar retains its RHS temporary through old destruction'); +is_deeply([grep { /-hash\z/ } @destroyed], [qw(old-hash new-hash)], + 'hash element retains its RHS temporary through old destruction'); +is_deeply([grep { /-array\z/ } @destroyed], [qw(old-array new-array)], + 'array element retains its RHS temporary through old destruction'); +is_deeply(\%old_saw_replacement, + { scalar => 1, hash => 1, array => 1 }, + 'each destructor sees the replacement already installed in its slot'); +ok(!defined($v), 'the scalar replacement stays weak after old destruction'); +ok(!defined($h->{slot}), 'the hash element replacement stays weak after old destruction'); +ok(!defined($a->[0]), 'the array element replacement stays weak after old destruction'); diff --git a/src/test/resources/unit/refcount/scalar_reference_contents_alias_lifetime.t b/src/test/resources/unit/refcount/scalar_reference_contents_alias_lifetime.t new file mode 100644 index 0000000000..a0eaa5f973 --- /dev/null +++ b/src/test/resources/unit/refcount/scalar_reference_contents_alias_lifetime.t @@ -0,0 +1,62 @@ +use strict; +use warnings; +use B qw(svref_2object); +use Scalar::Util qw(weaken); +use Test::More tests => 12; + +{ + package Local::ScalarReferenceAliasLifetime; + our $destroyed = 0; + + sub new { bless {}, shift } + sub DESTROY { ++$destroyed } +} + +sub refcount { svref_2object($_[0])->REFCNT } + +sub make_scalar_reference_aliases { + my $value = Local::ScalarReferenceAliasLifetime->new; + my $first = \$value; + my $second = $first; + return ($first, $second); +} + +my ($first, $second) = make_scalar_reference_aliases(); +my $weak_contents = $$second; +weaken($weak_contents); +is($Local::ScalarReferenceAliasLifetime::destroyed, 0, + 'aliases keep a returned scalar cell and its contents alive'); +ok(defined $weak_contents, + 'the scalar contents remain alive after the declaring scope exits'); +is(refcount($$second), 1, + 'two aliases to one scalar cell contribute one contents owner'); + +undef $first; +is($Local::ScalarReferenceAliasLifetime::destroyed, 0, + 'dropping one alias does not release the shared scalar contents'); +ok(defined $weak_contents, + 'the remaining alias still keeps the scalar cell contents alive'); +is(refcount($$second), 1, + 'dropping one alias does not change the scalar cell contents count'); + +my $replacement = Local::ScalarReferenceAliasLifetime->new; +my $weak_replacement = $replacement; +weaken($weak_replacement); +$$second = $replacement; +undef $replacement; +is($Local::ScalarReferenceAliasLifetime::destroyed, 1, + 'replacing the shared scalar cell releases its previous contents once'); +ok(!defined $weak_contents, + 'the replaced contents weak reference clears'); +ok(defined $weak_replacement, + 'the replacement remains alive through the remaining scalar reference'); +is(refcount($$second), 1, + 'the shared scalar cell contributes one owner for replacement contents'); + +undef $second; +is($Local::ScalarReferenceAliasLifetime::destroyed, 2, + 'dropping the final alias releases the current contents once'); +ok(!defined $weak_replacement, + 'the replacement weak reference clears after the final alias is released'); + +done_testing; diff --git a/src/test/resources/unit/refcount/scalar_reference_contents_retarget.t b/src/test/resources/unit/refcount/scalar_reference_contents_retarget.t new file mode 100644 index 0000000000..2a9cc89255 --- /dev/null +++ b/src/test/resources/unit/refcount/scalar_reference_contents_retarget.t @@ -0,0 +1,46 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 7; + +{ + package Local::ScalarReferenceContentsRetarget; + our $destroyed = 0; + + sub new { + my ($class) = @_; + return bless {}, $class; + } + + sub DESTROY { ++$destroyed } +} + +sub return_scalar_cell { + my $value = Local::ScalarReferenceContentsRetarget->new; + return \$value; +} + +my $cell_ref = return_scalar_cell(); +my $weak_first = $$cell_ref; +weaken($weak_first); +is($Local::ScalarReferenceContentsRetarget::destroyed, 0, + 'returned scalar reference keeps its current contents alive'); +ok(defined $weak_first, 'first referent remains alive after its lexical scope exits'); + +my $second = Local::ScalarReferenceContentsRetarget->new; +my $weak_second = $second; +weaken($weak_second); +$$cell_ref = $second; +undef $second; + +is($Local::ScalarReferenceContentsRetarget::destroyed, 1, + 'overwriting the referenced scalar releases its previous contents'); +ok(!defined $weak_first, 'previous contents weak reference clears on replacement'); +ok(defined $weak_second, 'replacement contents remain owned by the scalar reference'); + +undef $cell_ref; +is($Local::ScalarReferenceContentsRetarget::destroyed, 2, + 'releasing the scalar reference destroys the replacement contents once'); +ok(!defined $weak_second, 'final scalar-reference release clears the replacement weak observer'); + +done_testing; diff --git a/src/test/resources/unit/refcount/scalar_reference_localized_owner_lifetime.t b/src/test/resources/unit/refcount/scalar_reference_localized_owner_lifetime.t new file mode 100644 index 0000000000..0bc1e01d50 --- /dev/null +++ b/src/test/resources/unit/refcount/scalar_reference_localized_owner_lifetime.t @@ -0,0 +1,47 @@ +use strict; +use warnings; +use B qw(svref_2object); +use Scalar::Util qw(weaken); +use Test::More tests => 6; + +{ + package Local::LocalizedScalarReferenceOwner; + our $destroyed = 0; + + sub new { + my ($class) = @_; + return bless {}, $class; + } + + sub DESTROY { + ++$destroyed; + } +} + +our $localized_reference; +my $weak; +sub ref_count { svref_2object($_[0])->REFCNT } + +sub return_local_scalar_reference { + my $object = Local::LocalizedScalarReferenceOwner->new; + $weak = $object; + weaken($weak); + return \$object; +} + +{ + local $localized_reference = return_local_scalar_reference(); + is($Local::LocalizedScalarReferenceOwner::destroyed, 0, + 'localized scalar reference keeps returned lexical contents alive'); + ok(defined $weak, 'localized scalar reference keeps the weak observer live'); + is(ref_count($$localized_reference), 1, + 'localization preserves Perl refcount for scalar-reference contents'); +} + +is($Local::LocalizedScalarReferenceOwner::destroyed, 1, + 'restoring the package scalar releases the final owner exactly once'); +ok(!defined $weak, 'localization unwind clears the weak observer'); +is($Local::LocalizedScalarReferenceOwner::destroyed, 1, + 'later cleanup does not repeat destruction'); + +done_testing; diff --git a/src/test/resources/unit/refcount/schema_related_source_return_owner.t b/src/test/resources/unit/refcount/schema_related_source_return_owner.t new file mode 100644 index 0000000000..efa1249353 --- /dev/null +++ b/src/test/resources/unit/refcount/schema_related_source_return_owner.t @@ -0,0 +1,84 @@ +use strict; +use warnings; +use Test::More; +use B qw(svref_2object); +use Scalar::Util qw(weaken); + +{ + package Issue2043::RelatedSchema; + + sub DESTROY { + my $self = shift; + my $registrations = $self->{source_registrations}; + + for my $name (keys %$registrations) { + if (length ref $registrations->{$name} + && B::svref_2object($registrations->{$name})->REFCNT > 1) { + $registrations->{$name}->schema($self); + Scalar::Util::weaken($registrations->{$name}); + last; + } + } + } +} + +{ + package Issue2043::RelatedSource; + + sub schema { + $_[0]->{schema} = $_[1] if @_ > 1; + $_[0]->{schema}; + } + + sub DESTROY { + return if !ref $_[0]->{schema} + || Scalar::Util::isweak($_[0]->{schema}); + + Scalar::Util::weaken($_[0]->{schema}); + if ($_[0]->{schema}) { + my $registrations = $_[0]->{schema}->{source_registrations}; + for (keys %$registrations) { + $registrations->{$_} = $_[0] + if $registrations->{$_} == $_[0]; + } + } + } +} + +{ + package Issue2043::RelatedRow; + + sub new { bless { source => $_[1] }, $_[0] } + + sub related_source { + my $self = shift; + my $schema = $self->{source}->schema; + my $source = $schema->{source_registrations}{B}; + return $source; + } +} + +my $current; +{ + my $schema = bless { source_registrations => {} }, 'Issue2043::RelatedSchema'; + my $source_a = bless { schema => $schema }, 'Issue2043::RelatedSource'; + my $source_b = bless { schema => $schema }, 'Issue2043::RelatedSource'; + weaken($source_a->{schema}); + weaken($source_b->{schema}); + $schema->{source_registrations}{A} = $source_a; + $schema->{source_registrations}{B} = $source_b; + $current = $schema; + undef $source_a; + undef $source_b; + undef $schema; +} + +$current = Issue2043::RelatedRow->new($current->{source_registrations}{A}); +$current = $current->related_source; + +ok(ref($current) eq 'Issue2043::RelatedSource', + 'related source survives the row-to-source transfer'); +ok(ref($current->{schema}) eq 'Issue2043::RelatedSchema', + 'schema stays attached to the returned related source'); + +done_testing; diff --git a/src/test/resources/unit/refcount/self_capture_cycle_owner.t b/src/test/resources/unit/refcount/self_capture_cycle_owner.t new file mode 100644 index 0000000000..7f949d1b05 --- /dev/null +++ b/src/test/resources/unit/refcount/self_capture_cycle_owner.t @@ -0,0 +1,39 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken refaddr); +our ($weak_callback, $weak_guard, $destroyed); +$destroyed = 0; +{ package SelfCaptureGuard; sub DESTROY { ++$main::destroyed } } +sub install_cycle { + my $guard = bless { value => 1 }, 'SelfCaptureGuard'; + my $cycle; + $cycle = sub { + if ($_[0]) { + undef $cycle; + return $guard->{value}; + } + return $cycle; + }; + $weak_callback = $cycle; + weaken($weak_callback); + $weak_guard = $guard; + weaken($weak_guard); + return 1; +} +install_cycle(); +ok(defined $weak_callback, 'a real self-capture cycle retains its callback after lexical exit'); +SKIP: { + skip 'callback cycle was already lost', 7 unless defined $weak_callback; + ok(defined $weak_guard, 'the self-capture cycle owns its captured guard'); + my $strong = $weak_callback->(0); + is(refaddr($strong), refaddr($weak_callback), 'cycle callback returns its own CV'); + is($strong->(1), 1, 'cycle can be broken while its callback is running'); + ok(defined $weak_callback, 'external holder preserves callback after cycle break'); + ok(defined $weak_guard, 'external callback holder preserves captured data'); + undef $strong; + ok(!defined $weak_callback, 'final external owner releases the broken cycle'); + ok(!defined $weak_guard, 'broken cycle releases its captured guard'); +} +is($destroyed, 1, 'breaking the self-capture cycle destroys its guard exactly once'); +done_testing(); diff --git a/src/test/resources/unit/refcount/socket_gensym_not_package_owner.t b/src/test/resources/unit/refcount/socket_gensym_not_package_owner.t new file mode 100644 index 0000000000..61c8e70d55 --- /dev/null +++ b/src/test/resources/unit/refcount/socket_gensym_not_package_owner.t @@ -0,0 +1,28 @@ +use strict; +use warnings; +use IO::Socket::INET; +use Test::More; + +my %before = map { $_ => 1 } grep { /^GEN\d+$/ } keys %Symbol::; +my $listener = IO::Socket::INET->new( + LocalAddr => '127.0.0.1', + LocalPort => 0, + Listen => 5, + ReuseAddr => 1, + Proto => 'tcp', +); +plan skip_all => "loopback listener unavailable: $!" unless $listener; +my $client = IO::Socket::INET->new( + PeerAddr => '127.0.0.1', + PeerPort => $listener->sockport, + Proto => 'tcp', +) or die "cannot connect to loopback listener: $!"; +{ + my $accepted = $listener->accept or die "cannot accept loopback client: $!"; +} +close $client; +close $listener; + +plan tests => 1; +my @new_gensyms = grep { !$before{$_} } grep { /^GEN\d+$/ } keys %Symbol::; +is_deeply(\@new_gensyms, [], 'anonymous socket gensyms do not become package stash owners'); diff --git a/src/test/resources/unit/refcount/stale_stash_saved_move_owner.t b/src/test/resources/unit/refcount/stale_stash_saved_move_owner.t new file mode 100644 index 0000000000..5a57eb34b3 --- /dev/null +++ b/src/test/resources/unit/refcount/stale_stash_saved_move_owner.t @@ -0,0 +1,55 @@ +use strict; +use warnings; +use Test::More tests => 7; +use Scalar::Util qw(weaken); + +our @DESTROYED; + +{ + package StaleStashSavedMoveOwner::Probe; + + sub DESTROY { + push @main::DESTROYED, 'value'; + } +} + +my $object = bless {}, 'StaleStashSavedMoveOwner::Probe'; +my $weak = $object; +weaken($weak); +my ($source_stash, $copy_stash); +{ + no strict 'refs'; + ${'StaleStashSavedMoveOwnerSource::item'} = $object; + $source_stash = \%StaleStashSavedMoveOwnerSource::; + undef $object; + *StaleStashSavedMoveOwnerSource:: = 'StaleStashSavedMoveOwnerOther::'; + *StaleStashSavedMoveOwnerCopy:: = $source_stash; + $copy_stash = \%StaleStashSavedMoveOwnerCopy::; +} + +ok(defined $weak, 'the copied stale stash retains the moved value'); +ok(exists $copy_stash->{item}, 'the copied stale stash exposes the moved symbol'); + +delete $copy_stash->{item}; + +is($weak, undef, 'deleting the moved slot releases its final value owner'); +is_deeply(\@DESTROYED, ['value'], 'the moved value is destroyed exactly once'); + +my $abandoned_object = bless {}, 'StaleStashSavedMoveOwner::Probe'; +my $abandoned_weak = $abandoned_object; +weaken($abandoned_weak); +my $abandoned_stash; +{ + no strict 'refs'; + ${'StaleStashSavedMoveOwnerAbandoned::item'} = $abandoned_object; + $abandoned_stash = \%StaleStashSavedMoveOwnerAbandoned::; + undef $abandoned_object; + *StaleStashSavedMoveOwnerAbandoned:: = 'StaleStashSavedMoveOwnerOther::'; +} + +ok(defined $abandoned_weak, 'an unconsumed saved move retains its stale stash value'); +undef $abandoned_stash; +is($abandoned_weak, undef, 'final stale-stash release retires its saved move'); +is_deeply(\@DESTROYED, ['value', 'value'], 'both moved values are destroyed once'); + +done_testing; diff --git a/src/test/resources/unit/refcount/stash_alias_rebind_void_delete_owner.t b/src/test/resources/unit/refcount/stash_alias_rebind_void_delete_owner.t new file mode 100644 index 0000000000..c56ef3a289 --- /dev/null +++ b/src/test/resources/unit/refcount/stash_alias_rebind_void_delete_owner.t @@ -0,0 +1,53 @@ +use strict; +use warnings; +use Test::More tests => 7; +use Scalar::Util qw(weaken); + +our @DESTROYED; + +{ + package StashAliasRebindVoidDeleteOwner::Probe; + + sub DESTROY { + push @main::DESTROYED, 'value'; + } +} + +my $object = bless {}, 'StashAliasRebindVoidDeleteOwner::Probe'; +my $weak = $object; +weaken($weak); +my ($source_stash, $alias_stash); +{ + no strict 'refs'; + ${'StashAliasRebindVoidDeleteOwnerSource::item'} = $object; + $source_stash = \%StashAliasRebindVoidDeleteOwnerSource::; + *StashAliasRebindVoidDeleteOwnerCopy:: = $source_stash; + undef $object; + *StashAliasRebindVoidDeleteOwnerSource:: = \%StashAliasRebindVoidDeleteOwnerOther::; + $alias_stash = \%StashAliasRebindVoidDeleteOwnerCopy::; +} + +ok(defined $weak, 'the preserved alias retains the source value after rebinding'); +ok(exists $alias_stash->{item}, 'the alias stash retains the moved symbol'); +is_deeply(\@DESTROYED, [], 'rebinding does not destroy the moved value'); + +delete $alias_stash->{item}; + +is($weak, undef, 'void-context deletion releases the detached glob value'); +is_deeply(\@DESTROYED, ['value'], 'the moved value is destroyed exactly once'); + +my $namespace_object = bless {}, 'StashAliasRebindVoidDeleteOwner::Probe'; +my $namespace_weak = $namespace_object; +weaken($namespace_weak); +{ + no strict 'refs'; + ${'StashAliasRebindVoidDeleteOwnerNamespace::item'} = $namespace_object; +} +undef $namespace_object; + +delete $main::{'StashAliasRebindVoidDeleteOwnerNamespace::'}; + +is($namespace_weak, undef, 'void-context namespace deletion releases moved values'); +is_deeply(\@DESTROYED, ['value', 'value'], 'namespace contents are destroyed once'); + +done_testing; diff --git a/src/test/resources/unit/refcount/stash_delete_detached_glob_scalar_owner.t b/src/test/resources/unit/refcount/stash_delete_detached_glob_scalar_owner.t new file mode 100644 index 0000000000..1dbc538389 --- /dev/null +++ b/src/test/resources/unit/refcount/stash_delete_detached_glob_scalar_owner.t @@ -0,0 +1,34 @@ +use strict; +use warnings; +use Test::More tests => 4; +use Scalar::Util qw(weaken); + +our @DESTROYED; + +{ + package StashDeleteDetachedGlobOwner::Probe; + + sub DESTROY { + push @main::DESTROYED, 'value'; + } +} + +my $object = bless {}, 'StashDeleteDetachedGlobOwner::Probe'; +my $weak = $object; +weaken($weak); +{ + no strict 'refs'; + ${'StashDeleteDetachedGlobOwner::value'} = $object; +} +undef $object; + +my $detached_glob = delete $StashDeleteDetachedGlobOwner::{value}; +ok(defined $weak, 'the returned detached glob keeps its scalar referent alive'); +is_deeply(\@DESTROYED, [], 'stash deletion does not run DESTROY on the detached value'); + +my $scalar_slot = *{$detached_glob}{SCALAR}; +is($$scalar_slot, $weak, 'the detached glob retains its original scalar slot'); + +undef $scalar_slot; +undef $detached_glob; +is_deeply(\@DESTROYED, ['value'], 'releasing the detached glob destroys its value once'); diff --git a/src/test/resources/unit/refcount/stash_delete_detached_glob_undef_order.t b/src/test/resources/unit/refcount/stash_delete_detached_glob_undef_order.t new file mode 100644 index 0000000000..d77ad33c66 --- /dev/null +++ b/src/test/resources/unit/refcount/stash_delete_detached_glob_undef_order.t @@ -0,0 +1,52 @@ +use strict; +use warnings; +use Test::More tests => 5; + +our $detached_glob; +our @DESTROY_OBSERVED; + +{ + package StashDeleteDetachedGlobUndefOrder::Probe; + + sub DESTROY { + push @main::DESTROY_OBSERVED, + defined($main::detached_glob) ? 'defined' : 'undef'; + } +} + +my $object = bless {}, 'StashDeleteDetachedGlobUndefOrder::Probe'; +{ + no strict 'refs'; + ${'StashDeleteDetachedGlobUndefOrder::value'} = $object; +} +undef $object; + +$detached_glob = delete $StashDeleteDetachedGlobUndefOrder::{value}; +ok(defined $detached_glob, 'stash deletion returns a defined detached glob'); + +undef $detached_glob; + +is_deeply( + \@DESTROY_OBSERVED, + ['defined'], + 'component DESTROY runs while the scalar still holds the detached glob', +); +ok(!defined $detached_glob, 'the detached glob scalar is undef after undef returns'); + +my $replacement_object = bless {}, 'StashDeleteDetachedGlobUndefOrder::Probe'; +{ + no strict 'refs'; + ${'StashDeleteDetachedGlobUndefOrder::value'} = $replacement_object; +} +undef $replacement_object; +$detached_glob = delete $StashDeleteDetachedGlobUndefOrder::{value}; +$detached_glob = 'replacement'; + +is_deeply( + \@DESTROY_OBSERVED, + ['defined', 'defined'], + 'component DESTROY sees the old glob during scalar replacement too', +); +is($detached_glob, 'replacement', 'the replacement value is installed after DESTROY'); + +done_testing; diff --git a/src/test/resources/unit/refcount/stash_delete_detached_io_glob.t b/src/test/resources/unit/refcount/stash_delete_detached_io_glob.t new file mode 100644 index 0000000000..51f92507fc --- /dev/null +++ b/src/test/resources/unit/refcount/stash_delete_detached_io_glob.t @@ -0,0 +1,30 @@ +use strict; +use warnings; +use File::Temp qw(tempfile); +use Test::More; + +my ($temporary, $path) = tempfile(); +close $temporary or die "close temporary file: $!"; + +my $stash; +{ + no strict 'refs'; + no warnings 'once'; + $stash = \%{'DetachedIOGlobOwner::'}; + open 'DetachedIOGlobOwner::FH', '>', $path + or die "open package filehandle: $!"; +} + +my $detached = delete $stash->{FH}; +ok(!exists $stash->{FH}, 'package IO glob is removed from its stash'); +ok(defined fileno($detached), 'detached glob retains the open IO slot'); +ok((print {$detached} "detached write\n"), 'detached glob remains writable'); +ok(close($detached), 'detached glob closes its retained IO slot'); + +open my $reader, '<', $path or die "open written file: $!"; +my $contents = do { local $/; <$reader> }; +is($contents, "detached write\n", 'detached glob write reaches the file'); +close $reader or die "close written file: $!"; +unlink $path or die "remove written file: $!"; + +done_testing(); diff --git a/src/test/resources/unit/refcount/stash_delete_namespace_owner.t b/src/test/resources/unit/refcount/stash_delete_namespace_owner.t new file mode 100644 index 0000000000..3308ecbf06 --- /dev/null +++ b/src/test/resources/unit/refcount/stash_delete_namespace_owner.t @@ -0,0 +1,33 @@ +use strict; +use warnings; +use Test::More tests => 4; +use Scalar::Util qw(weaken); + +our @DESTROYED; + +{ + package NamespaceDeleteOwnerProbe; + + sub DESTROY { + push @main::DESTROYED, 'value'; + } +} + +my $object = bless {}, 'NamespaceDeleteOwnerProbe'; +my $weak = $object; +weaken($weak); +{ + no strict 'refs'; + ${'NamespaceDeleteOwner::item'} = $object; +} +undef $object; + +my $detached_namespace = delete $main::{'NamespaceDeleteOwner::'}; +ok(defined $weak, 'the detached namespace retains its scalar referent'); +is_deeply(\@DESTROYED, [], 'namespace deletion does not destroy a moved value'); + +undef $detached_namespace; +is($weak, undef, 'releasing the detached namespace releases its moved scalar'); +is_deeply(\@DESTROYED, ['value'], 'the moved value is destroyed exactly once'); + +done_testing; diff --git a/src/test/resources/unit/refcount/state_aggregate_alias_owner_release.t b/src/test/resources/unit/refcount/state_aggregate_alias_owner_release.t new file mode 100644 index 0000000000..8d8510518b --- /dev/null +++ b/src/test/resources/unit/refcount/state_aggregate_alias_owner_release.t @@ -0,0 +1,33 @@ +use strict; +use warnings; +use feature qw(state refaliasing declared_refs); +no warnings qw(experimental::refaliasing experimental::declared_refs); +use Scalar::Util qw(weaken); +use Test::More; +{ + my @source = ({ value => 21 }); + my $callback = do { + my $reference = \@source; + sub { \state @items = $reference; return $items[0] } + }; + my $weak = $callback->(); weaken($weak); + undef $callback; + ok(defined $weak, 'source array binding survives state alias release'); + is($source[0]{value}, 21, 'source array contents remain usable'); + @source = (); + ok(!defined $weak, 'source array clear releases final element owner'); +} +{ + my %source = (item => { value => 22 }); + my $callback = do { + my $reference = \%source; + sub { \state %items = $reference; return $items{item} } + }; + my $weak = $callback->(); weaken($weak); + undef $callback; + ok(defined $weak, 'source hash binding survives state alias release'); + is($source{item}{value}, 22, 'source hash contents remain usable'); + %source = (); + ok(!defined $weak, 'source hash clear releases final element owner'); +} +done_testing(); diff --git a/src/test/resources/unit/refcount/storable_dclone_return_owner_release.t b/src/test/resources/unit/refcount/storable_dclone_return_owner_release.t new file mode 100644 index 0000000000..a046e10e84 --- /dev/null +++ b/src/test/resources/unit/refcount/storable_dclone_return_owner_release.t @@ -0,0 +1,24 @@ +use strict; +use warnings; +use Storable qw(dclone); +use Test::More tests => 3; + +our $destroyed = 0; + +{ + package Local::DcloneReturnOwner; + + sub new { bless {}, shift } + sub DESTROY { ++$main::destroyed } +} + +my $original = Local::DcloneReturnOwner->new; +my $copy = dclone($original); + +is($destroyed, 0, 'dclone does not destroy either live object'); + +undef $copy; +is($destroyed, 1, 'the cloned object is destroyed when its last Perl owner leaves'); + +undef $original; +is($destroyed, 2, 'the original object is destroyed independently'); diff --git a/src/test/resources/unit/refcount/strong_cycle_owner_slots.t b/src/test/resources/unit/refcount/strong_cycle_owner_slots.t new file mode 100644 index 0000000000..8c1cc5441b --- /dev/null +++ b/src/test/resources/unit/refcount/strong_cycle_owner_slots.t @@ -0,0 +1,26 @@ +use strict; +use warnings; +use Test::More tests => 4; +use Scalar::Util qw(weaken); + +my $hash = {}; +$hash->{self} = $hash; +my $weak_hash = $hash; +weaken($weak_hash); +undef $hash; +ok(defined $weak_hash, + 'an unblessed hash cycle retains its weak observer after root release'); +$weak_hash->{self} = undef; +ok(!defined $weak_hash, + 'removing the final strong hash edge clears the weak observer'); + +my $array = []; +push @$array, $array; +my $weak_array = $array; +weaken($weak_array); +undef $array; +ok(defined $weak_array, + 'an unblessed array cycle retains its weak observer after root release'); +$weak_array->[0] = undef; +ok(!defined $weak_array, + 'removing the final strong array edge clears the weak observer'); diff --git a/src/test/resources/unit/refcount/strong_cycle_weak_refs_survive_end.t b/src/test/resources/unit/refcount/strong_cycle_weak_refs_survive_end.t new file mode 100644 index 0000000000..d037e91d6a --- /dev/null +++ b/src/test/resources/unit/refcount/strong_cycle_weak_refs_survive_end.t @@ -0,0 +1,34 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +our ($WEAK_SCHEMA, $WEAK_STORAGE, $DESTROYED) = (undef, undef, 0); + +{ + package EndStrongCycle::Schema; + sub DESTROY { $main::DESTROYED++ } + + package EndStrongCycle::Storage; + sub DESTROY { $main::DESTROYED++ } +} + +sub create_cycle { + my $schema = bless {}, 'EndStrongCycle::Schema'; + my $storage = bless { schema => $schema }, 'EndStrongCycle::Storage'; + $schema->{storage} = $storage; + + $WEAK_SCHEMA = $schema; + weaken($WEAK_SCHEMA); + $WEAK_STORAGE = $storage; + weaken($WEAK_STORAGE); +} + +create_cycle(); + +END { + ok(defined $WEAK_SCHEMA, 'strong cycle keeps schema weak observer live through END'); + ok(defined $WEAK_STORAGE, 'strong cycle keeps storage weak observer live through END'); + is($DESTROYED, 0, 'strongly owned cycle is not destroyed before END callbacks'); + done_testing(); +} diff --git a/src/test/resources/unit/refcount/tailcall_code_owner_lifetime.t b/src/test/resources/unit/refcount/tailcall_code_owner_lifetime.t new file mode 100644 index 0000000000..bef7b1310b --- /dev/null +++ b/src/test/resources/unit/refcount/tailcall_code_owner_lifetime.t @@ -0,0 +1,19 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More tests => 3; + +sub dispatch_tail { + my ($target) = @_; + goto &$target; +} + +my $answer = 42; +my $target = sub { $answer }; +my $weak_target = $target; +weaken($weak_target); + +is(dispatch_tail($target), 42, 'tail call returns the target result'); +ok(defined $weak_target, 'the caller lexical keeps CODE alive after the tail call'); +undef $target; +ok(!defined $weak_target, 'the final lexical release clears the weak CODE reference'); diff --git a/src/test/resources/unit/refcount/temporary_argument_overwrite_lifetime.t b/src/test/resources/unit/refcount/temporary_argument_overwrite_lifetime.t new file mode 100644 index 0000000000..c2ad9766be --- /dev/null +++ b/src/test/resources/unit/refcount/temporary_argument_overwrite_lifetime.t @@ -0,0 +1,56 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); + +our @weak_references; + +sub capture_weak_reference { + my ($index, $value) = @_; + $weak_references[$index] = $value; + weaken($weak_references[$index]); +} + +sub replace_argument_by_index { + $_[0] = bless {}, 'Issue2043::ByIndex'; + capture_weak_reference(0, $_[0]); +} + +sub replace_argument_by_foreach_alias { + for my $value (@_) { + $value = bless {}, 'Issue2043::ByForeachAlias'; + capture_weak_reference(1, $value); + } +} + +sub replace_argument_and_return { + $_[0] = bless {}, 'Issue2043::ReturnedTemporary'; + capture_weak_reference(2, $_[0]); + return $_[0]; +} + +sub pass_temporary_to_index_assignment { + replace_argument_by_index({}); +} + +sub pass_temporary_to_foreach_assignment { + replace_argument_by_foreach_alias({}); +} + +use Test::More; + +pass_temporary_to_index_assignment(); +pass_temporary_to_foreach_assignment(); +my $returned_temporary = replace_argument_and_return({}); + +is(scalar @weak_references, 3, 'captured all three overwritten temporary arguments'); +ok(!defined $weak_references[0], + 'temporary argument overwritten through $_[0] is released after the call'); +ok(!defined $weak_references[1], + 'temporary argument overwritten through a foreach alias is released after the call'); +ok(defined $weak_references[2], + 'a temporary argument returned by the call stays alive for its caller'); +undef $returned_temporary; +ok(!defined $weak_references[2], + 'the returned temporary argument is released when its caller drops it'); + +done_testing; diff --git a/src/test/resources/unit/refcount/temporary_arrayref_argument_lifetime.t b/src/test/resources/unit/refcount/temporary_arrayref_argument_lifetime.t new file mode 100644 index 0000000000..5b84dfb8f8 --- /dev/null +++ b/src/test/resources/unit/refcount/temporary_arrayref_argument_lifetime.t @@ -0,0 +1,30 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More; + +our @destroyed; + +{ + package TemporaryArrayArgument; + sub new { bless { id => $_[1] }, $_[0] } + sub DESTROY { push @main::destroyed, $_[0]->{id} } +} + +my $consume = sub { + my @values = @{$_[0]}; + return; +}; + +my $weak; +{ + my $object = TemporaryArrayArgument->new('temporary'); + $weak = $object; + weaken($weak); + $consume->([$object]); +} + +ok(!defined($weak), 'object in temporary array argument is released'); +is_deeply(\@destroyed, ['temporary'], 'DESTROY runs after the call drops its array argument'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/temporary_io_invocant_survives_nested_render.t b/src/test/resources/unit/refcount/temporary_io_invocant_survives_nested_render.t new file mode 100644 index 0000000000..7c6e9bffe1 --- /dev/null +++ b/src/test/resources/unit/refcount/temporary_io_invocant_survives_nested_render.t @@ -0,0 +1,47 @@ +use strict; +use warnings; +use Test::More; +use File::Temp qw(tempdir); +use File::Spec; +use IO::File; + +BEGIN { + eval { require Template; 1 } or plan skip_all => 'Template Toolkit is not installed'; +} + +{ + package OutputPath; + sub new { bless { path => $_[1] }, $_[0] } + sub openw { return IO::File->new($_[0]->{path}, 'w') } +} + +{ + package TemplateRenderer; + sub get_content_for { + my ($self, $source_path, $variables) = @_; + my $content = ''; + my $template = Template->new({ ABSOLUTE => 1 }) or die Template->error(); + $template->process($source_path, $variables, \$content) or die $template->error(); + return $content; + } +} + +my $dir = tempdir(CLEANUP => 1); +my $source_path = File::Spec->catfile($dir, 'source.html.tt'); +my $output_path = File::Spec->catfile($dir, 'output.html'); +my $source = IO::File->new($source_path, 'w') or die "create source: $!"; +$source->print("[% title %]\n"); +$source->close or die "close source: $!"; + +my $output = OutputPath->new($output_path); +my $renderer = bless {}, 'TemplateRenderer'; +$output->openw()->write($renderer->get_content_for( + $source_path, { title => 'rendered' } +)); + +my $readback = IO::File->new($output_path, 'r') or die "open output: $!"; +local $/; +my $content = <$readback>; +$readback->close; +is($content, "rendered\n", 'temporary output invocant survives nested template rendering'); +done_testing(); diff --git a/src/test/resources/unit/refcount/test2_event_amnesty_lifetime.t b/src/test/resources/unit/refcount/test2_event_amnesty_lifetime.t new file mode 100644 index 0000000000..945c64dd5f --- /dev/null +++ b/src/test/resources/unit/refcount/test2_event_amnesty_lifetime.t @@ -0,0 +1,33 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); + +our $capture_amnesty = 0; +our @weak_amnesty; + +BEGIN { + no warnings 'redefine'; + *CORE::GLOBAL::bless = sub { + my $class = @_ > 1 ? $_[1] : caller(); + my $object = CORE::bless($_[0], $class); + if ($capture_amnesty && $class eq 'Test2::EventFacet::Amnesty') { + push @weak_amnesty, $object; + weaken($weak_amnesty[-1]); + } + return $object; + }; +} + +use Test::More; + +{ + local $capture_amnesty = 1; + local $TODO = 'exercise one temporary amnesty facet'; + ok(0, 'intentional TODO failure creates an amnesty facet'); +} + +is(scalar @weak_amnesty, 1, 'captured one TODO amnesty facet'); +is(scalar(grep { defined $_ } @weak_amnesty), 0, + 'Test::Builder releases the TODO amnesty facet after sending the event'); + +done_testing; diff --git a/src/test/resources/unit/refcount/test2_event_return_lifetime.t b/src/test/resources/unit/refcount/test2_event_return_lifetime.t new file mode 100644 index 0000000000..9749e1eb68 --- /dev/null +++ b/src/test/resources/unit/refcount/test2_event_return_lifetime.t @@ -0,0 +1,40 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); + +our %captured_events; +our $captured_event_count = 0; +our $capture_events = 0; + +BEGIN { + no warnings 'redefine'; + *CORE::GLOBAL::bless = sub { + my $class = @_ > 1 ? $_[1] : caller(); + my $object = CORE::bless($_[0], $class); + if ($capture_events + && ($class eq 'Test2::Event::Ok' + || $class eq 'Test2::EventFacet::Trace')) { + my $id = ++$captured_event_count; + $captured_events{$id} = { class => $class, object => $object }; + weaken($captured_events{$id}{object}); + } + return $object; + }; +} + +use Test::More; + +{ + local $capture_events = 1; + ok(1, 'Test::Builder sends an assertion event'); +} + +my %captured_class = map { $_->{class} => 1 } values %captured_events; +ok($captured_class{'Test2::Event::Ok'}, 'captured the assertion event'); +ok($captured_class{'Test2::EventFacet::Trace'}, 'captured its trace facet'); + +my @live = sort map { $_->{class} } + grep { defined $_->{object} } values %captured_events; +is_deeply(\@live, [], 'Test::Builder releases assertion events after sending them'); + +done_testing; diff --git a/src/test/resources/unit/refcount/tied_argument_alias_retains_handler.t b/src/test/resources/unit/refcount/tied_argument_alias_retains_handler.t new file mode 100644 index 0000000000..b72175f9d3 --- /dev/null +++ b/src/test/resources/unit/refcount/tied_argument_alias_retains_handler.t @@ -0,0 +1,73 @@ +use strict; +use warnings; +use Test::More tests => 3; + +our @events; +my @warnings; + +{ + package AliasedTieHash; + + sub TIEHASH { push @main::events, 'TIEHASH'; bless {}, shift } + sub FETCH { push @main::events, 'FETCH'; return undef } + sub STORE { push @main::events, 'STORE' } + sub UNTIE { push @main::events, 'UNTIE' } + sub DESTROY { push @main::events, 'DESTROY' } + + package AliasedTieArray; + + sub TIEARRAY { push @main::events, 'TIEARRAY'; bless {}, shift } + sub FETCH { push @main::events, 'FETCH'; return undef } + sub STORE { push @main::events, 'STORE' } + sub FETCHSIZE { push @main::events, 'FETCHSIZE'; return 0 } + sub UNTIE { push @main::events, 'UNTIE' } + sub DESTROY { push @main::events, 'DESTROY' } + + package main; + + local $SIG{__WARN__} = sub { push @warnings, @_ }; + + our %tied_hash; + our @tied_array; + + sub inspect_hash { + push @events, 'inside before untie'; + untie %main::tied_hash; + push @events, defined($_[0]) ? 'inside after defined' : 'inside after undef'; + } + + sub inspect_array { + push @events, 'inside before untie'; + untie @main::tied_array; + push @events, defined($_[0]) ? 'inside after defined' : 'inside after undef'; + } + + tie %tied_hash, 'AliasedTieHash'; + inspect_hash($tied_hash{missing}); + push @events, 'after call'; + is_deeply( + \@events, + [ + 'TIEHASH', 'inside before untie', 'UNTIE', 'FETCH', + 'inside after undef', 'DESTROY', 'after call', + ], + 'a tied hash handler survives untie through an aliased element argument', + ); + + @events = (); + tie @tied_array, 'AliasedTieArray'; + inspect_array($tied_array[0]); + push @events, 'after call'; + is_deeply( + \@events, + [ + 'TIEARRAY', 'inside before untie', 'UNTIE', 'FETCH', + 'inside after undef', 'DESTROY', 'after call', + ], + 'a tied array handler survives untie through an aliased element argument', + ); + + is_deeply(\@warnings, [], 'the argument magic owner does not cause an untie warning'); +} + +done_testing(); diff --git a/src/test/resources/unit/refcount/tied_handler_nested_value_owner.t b/src/test/resources/unit/refcount/tied_handler_nested_value_owner.t new file mode 100644 index 0000000000..d700530f50 --- /dev/null +++ b/src/test/resources/unit/refcount/tied_handler_nested_value_owner.t @@ -0,0 +1,27 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +{ + package NestedValueTieHandler; + sub TIEHASH { $_[1] } + sub FETCH { $_[0]->{values}{$_[1]} } + sub STORE { $_[0]->{values}{$_[1]} = $_[2] } +} + +my $target = bless {}, 'NestedValueTieTarget'; +my $weak_target = $target; +weaken($weak_target); +my $handler = bless { values => { target => $target } }, 'NestedValueTieHandler'; +my %tied; +tie %tied, 'NestedValueTieHandler', $handler; + +undef $target; +undef $handler; +ok(defined $weak_target, 'the tied handler retains values stored in its nested hash'); + +untie %tied; +ok(!defined $weak_target, 'untie releases the handler and its nested value'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/tied_handler_nested_value_owner_before_weaken.t b/src/test/resources/unit/refcount/tied_handler_nested_value_owner_before_weaken.t new file mode 100644 index 0000000000..c1ac2e209d --- /dev/null +++ b/src/test/resources/unit/refcount/tied_handler_nested_value_owner_before_weaken.t @@ -0,0 +1,30 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More; + +{ + package PreWeakenTieHandler; + sub TIEHASH { $_[1] } + sub FETCH { $_[0]->{values}{$_[1]} } + sub STORE { $_[0]->{values}{$_[1]} = $_[2] } +} + +my $target = bless {}, 'PreWeakenTieTarget'; +my $handler = bless { values => { target => $target } }, 'PreWeakenTieHandler'; +my %tied; +tie %tied, 'PreWeakenTieHandler', $handler; + +my $weak_target = $target; +weaken($weak_target); +undef $target; +undef $handler; + +ok(defined $weak_target, + 'a nested tied-handler value stored before first weaken remains strongly owned'); + +untie %tied; +ok(!defined $weak_target, + 'releasing the tied handler clears the weak observer after the last nested owner leaves'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/tied_handler_nested_weak_owner.t b/src/test/resources/unit/refcount/tied_handler_nested_weak_owner.t new file mode 100644 index 0000000000..863dbc13bb --- /dev/null +++ b/src/test/resources/unit/refcount/tied_handler_nested_weak_owner.t @@ -0,0 +1,50 @@ +use strict; +use warnings; +use Scalar::Util qw(weaken); +use Test::More; + +{ + package TiedHandlerNestedWeakOwner::Probe; + + our $DESTROY_COUNT = 0; + + sub new { bless {}, shift } + + sub DESTROY { $DESTROY_COUNT++ } + + package TiedHandlerNestedWeakOwner::Tie; + + sub TIEHASH { bless { target => $_[1] }, $_[0] } + + sub FETCH { $_[0]->{target} } + + sub STORE { $_[0]->{target} = $_[2] } + + sub clear { delete $_[0]->{target} } +} + +our $weak_target; + +sub make_tied_hash_with_weak_target { + my $target = TiedHandlerNestedWeakOwner::Probe->new; + my %hash; + tie %hash, 'TiedHandlerNestedWeakOwner::Tie', $target; + $weak_target = $target; + weaken($weak_target); + return \%hash; +} + +my $hash = make_tied_hash_with_weak_target(); +my $tie = tied %{$hash}; + +ok(defined $weak_target, 'nested value remains alive through the tied handler'); +is($TiedHandlerNestedWeakOwner::Probe::DESTROY_COUNT, 0, + 'nested value is not destroyed while the tied handler stores it'); + +$tie->clear; + +ok(!defined $weak_target, 'removing the final nested handler value clears its weak observer'); +is($TiedHandlerNestedWeakOwner::Probe::DESTROY_COUNT, 1, + 'nested value is destroyed exactly once after its final handler slot leaves'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/tied_handler_owner_release.t b/src/test/resources/unit/refcount/tied_handler_owner_release.t new file mode 100644 index 0000000000..a8098dea30 --- /dev/null +++ b/src/test/resources/unit/refcount/tied_handler_owner_release.t @@ -0,0 +1,83 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); +our $destroyed = 0; +{ + package CountedTieHandler; + sub TIEHASH { $_[1] } + sub TIEARRAY { $_[1] } + sub TIESCALAR { $_[1] } + sub DESTROY { ++$main::destroyed } +} +my (%hash, @array, $scalar); +my $handler = bless {}, 'CountedTieHandler'; +my $weak = $handler; +weaken($weak); +tie %hash, 'CountedTieHandler', $handler; +tie @array, 'CountedTieHandler', $handler; +tie $scalar, 'CountedTieHandler', $handler; +undef $handler; +ok(defined $weak, 'each tie keeps its handler after the source scalar is cleared'); +{ + no warnings 'untie'; + untie %hash; +} +ok(defined $weak, 'array and scalar ties retain the handler after hash untie'); +is($destroyed, 0, 'hash untie does not destroy a shared handler'); +{ + no warnings 'untie'; + untie @array; +} +ok(defined $weak, 'scalar tie retains the handler after array untie'); +is($destroyed, 0, 'array untie does not destroy a shared handler'); +untie $scalar; +ok(!defined $weak, 'last tie releases the handler'); +is($destroyed, 1, 'handler is destroyed exactly once'); +untie %hash; +untie @array; +untie $scalar; +is($destroyed, 1, 'repeated untie does not release another owner'); +{ + package CountedTieOuter; + sub TIEHASH { $_[1] } + sub DESTROY { + my $self = shift; + ++$main::destroyed unless tied(%$self); + } + sub wrap { + my $inner = shift; + my %outer; + tie %outer, __PACKAGE__, $inner; + bless \%outer, __PACKAGE__; + } +} +$destroyed = 0; +my $weak_inner; +{ + my $outer = (bless {}, 'CountedTieOuter')->wrap; + $weak_inner = tied(%$outer); + weaken($weak_inner); + ok(defined $weak_inner, 'tied outer owns its inner handler'); +} +ok(!defined $weak_inner, 'destroying outer releases its inner handler before the next statement'); +is($destroyed, 1, 'inner handler destructor runs exactly once after outer scope exit'); +{ + package BorrowedTieRestoration; + sub TIEHASH { bless {}, shift } + sub EXISTS { 0 } + sub FETCH { undef } + sub STORE { } + sub DELETE { die "restoring tied entry\n" } + sub DESTROY { ++$main::destroyed } +} +my $before = $destroyed; +eval { + my %tied; + tie %tied, 'BorrowedTieRestoration'; + local $tied{key} = 'value'; + die "body failure\n"; +}; +is($@, "restoring tied entry\n", 'local restoration can borrow the handler after its lexical owner retires'); +is($destroyed, $before + 1, 'exception unwind retires the handler owner once'); +done_testing(); diff --git a/src/test/resources/unit/refcount/untracked_reference_owner_replacement_order.t b/src/test/resources/unit/refcount/untracked_reference_owner_replacement_order.t new file mode 100644 index 0000000000..d736d210b6 --- /dev/null +++ b/src/test/resources/unit/refcount/untracked_reference_owner_replacement_order.t @@ -0,0 +1,19 @@ +use strict; +use warnings; +use Test::More tests => 2; + +package Issue1649::OldSlotValue; +sub new { bless {}, shift } +sub DESTROY { + $main::observed_slot_type = ref($main::slot) || 'undef'; +} + +package main; +our ($slot, $observed_slot_type); + +$slot = Issue1649::OldSlotValue->new; +$slot = {}; + +is($observed_slot_type, 'HASH', + 'the displaced referent is destroyed after the slot contains its replacement'); +is(ref($slot), 'HASH', 'the replacement remains in the scalar slot'); diff --git a/src/test/resources/unit/refcount/void_discard_preserves_closure_capture.t b/src/test/resources/unit/refcount/void_discard_preserves_closure_capture.t new file mode 100644 index 0000000000..fd93b36ec1 --- /dev/null +++ b/src/test/resources/unit/refcount/void_discard_preserves_closure_capture.t @@ -0,0 +1,72 @@ +use strict; +use warnings; +use feature 'state'; + +use Scalar::Util qw(weaken); +use Test::More tests => 5; + +{ + package Local::VoidDiscardLoop; + + sub new { bless {}, shift } +} + +{ + package Local::VoidDiscardPromise; + + our $destroyed = 0; + + sub new { + my $class = ref($_[0]) || $_[0]; + return bless {}, $class; + } + + sub ioloop { + return exists $_[0]{ioloop} + ? $_[0]{ioloop} + : ( + ref($_[0]{ioloop} = main::loop_singleton()) + && Scalar::Util::weaken($_[0]{ioloop}), + $_[0]{ioloop} + ) + if @_ == 1; + ref($_[0]{ioloop} = $_[1]) && Scalar::Util::weaken($_[0]{ioloop}); + return $_[0]; + } + + sub clone { $_[0]->new->ioloop($_[0]->ioloop) } + + sub then { + my $self = shift; + my $next = $self->clone; + $main::weak_next = $next; + Scalar::Util::weaken($main::weak_next); + push @{$self->{callbacks}}, sub { return $next->ioloop }; + return $next; + } + + sub DESTROY { $destroyed++ } +} + +sub loop_singleton { + state $loop = Local::VoidDiscardLoop->new; + return $loop; +} + +our ($weak_source, $weak_next); +my $source = Local::VoidDiscardPromise->new; +$weak_source = $source; +weaken($weak_source); +$source->then; + +ok(defined $weak_next, 'stored closure keeps a void-discarded return alive'); +is($Local::VoidDiscardPromise::destroyed, 0, + 'void-discard cleanup does not destroy the closure-owned return'); +isa_ok($source->{callbacks}[0]->(), 'Local::VoidDiscardLoop', + 'stored closure can still use the captured promise'); + +undef $source; +is($Local::VoidDiscardPromise::destroyed, 2, + 'source and closure-owned return are destroyed with their final owner'); +ok(!defined($weak_source) && !defined($weak_next), + 'weak observers clear after both promises are released'); diff --git a/src/test/resources/unit/refcount/void_discard_zero_count_destroy.t b/src/test/resources/unit/refcount/void_discard_zero_count_destroy.t new file mode 100644 index 0000000000..129f91e8e8 --- /dev/null +++ b/src/test/resources/unit/refcount/void_discard_zero_count_destroy.t @@ -0,0 +1,19 @@ +use strict; +use warnings; +use Test::More; + +our $destroyed = 0; + +{ + package VoidDiscardZeroCountProbe; + + sub new { bless {}, shift } + sub DESTROY { $main::destroyed++ } +} + +VoidDiscardZeroCountProbe->new(); + +is($destroyed, 1, + 'a zero-count result discarded in void context is destroyed at the statement boundary'); + +done_testing(); diff --git a/src/test/resources/unit/refcount/weak_scalar_cell_active_lexical_owner.t b/src/test/resources/unit/refcount/weak_scalar_cell_active_lexical_owner.t new file mode 100644 index 0000000000..caf1865b60 --- /dev/null +++ b/src/test/resources/unit/refcount/weak_scalar_cell_active_lexical_owner.t @@ -0,0 +1,18 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +my $weak; +{ + my $value = 42; + $weak = \$value; + weaken($weak); + + ok(defined($weak), 'weak scalar reference is live inside its lexical scope'); + is($$weak, 42, 'weak scalar reference reads the live lexical value'); +} + +ok(!defined($weak), 'weak scalar reference clears when the lexical owner exits'); + +done_testing; diff --git a/src/test/resources/unit/svrefcnt_method_result_hash_owner.t b/src/test/resources/unit/svrefcnt_method_result_hash_owner.t new file mode 100644 index 0000000000..6ad40037eb --- /dev/null +++ b/src/test/resources/unit/svrefcnt_method_result_hash_owner.t @@ -0,0 +1,18 @@ +use strict; +use warnings; +use Test::More tests => 1; + +{ + package SvRefcntFieldValue; + sub new { bless {}, shift } +} + +{ + package SvRefcntFieldOwner; + sub new { bless { value => SvRefcntFieldValue->new }, shift } + sub value { return $_[0]->{value} } +} + +my $owner = SvRefcntFieldOwner->new; +is(&Internals::SvREFCNT($owner->value) + 1, 2, + 'method-result count includes the hash-held field value'); diff --git a/src/test/resources/unit/sysread_regular_file_large_request.t b/src/test/resources/unit/sysread_regular_file_large_request.t new file mode 100644 index 0000000000..c6e08d3e5f --- /dev/null +++ b/src/test/resources/unit/sysread_regular_file_large_request.t @@ -0,0 +1,19 @@ +use strict; +use warnings; +use Test::More; +use File::Temp qw(tempfile); + +my $payload = 'x' x 131072; +my ($writer, $path) = tempfile(UNLINK => 1); +binmode $writer; +print {$writer} $payload or die "write test payload: $!"; +close $writer or die "close test payload: $!"; + +open my $reader, '<:raw', $path or die "open test payload: $!"; +my $buffer = ''; +my $count = sysread($reader, $buffer, length $payload); +is $count, length($payload), 'one sysread fills a large regular-file request'; +is $buffer, $payload, 'large regular-file read returns the complete bytes'; +close $reader or die "close test payload reader: $!"; + +done_testing; diff --git a/src/test/resources/unit/threads_shared_nested_object_release.t b/src/test/resources/unit/threads_shared_nested_object_release.t new file mode 100644 index 0000000000..cfe16d6107 --- /dev/null +++ b/src/test/resources/unit/threads_shared_nested_object_release.t @@ -0,0 +1,95 @@ +use strict; +use warnings; +use threads; +use threads::shared; + +print "1..9\n"; + +{ + package SharedNestedHashObject; + + sub new { + return bless(threads::shared::shared_clone({}), shift); + } + + sub DESTROY { + $main::destroyed++; + } +} + +{ + package SharedNestedArrayObject; + + sub new { + return bless(threads::shared::shared_clone([]), shift); + } + + sub DESTROY { + $main::destroyed++; + } +} + +our $destroyed :shared = 0; +my @shared_array :shared; +my %shared_hash :shared; + +sub discard_shared_array_fetch { + scalar $shared_array[0]; +} + +$shared_array[0] = SharedNestedHashObject->new(); +$shared_array[0] = undef; +print $destroyed == 1 + ? "ok 1 - undef releases nested hash object from shared array\n" + : "not ok 1 - undef releases nested hash object from shared array ($destroyed)\n"; + +$shared_array[0] = SharedNestedArrayObject->new(); +discard_shared_array_fetch(); +$shared_array[0] = undef; +print $destroyed == 2 + ? "ok 2 - discarded fetch does not delay shared array object release\n" + : "not ok 2 - discarded fetch does not delay shared array object release ($destroyed)\n"; + +$shared_array[0] = SharedNestedArrayObject->new(); +$shared_array[0] = SharedNestedArrayObject->new(); +print $destroyed == 3 + ? "ok 3 - replacement releases nested array object from shared array\n" + : "not ok 3 - replacement releases nested array object from shared array ($destroyed)\n"; + +$shared_hash{object} = SharedNestedHashObject->new(); +$shared_hash{object} = undef; +print $destroyed == 4 + ? "ok 4 - undef releases nested hash object from shared hash\n" + : "not ok 4 - undef releases nested hash object from shared hash ($destroyed)\n"; + +$shared_hash{object} = SharedNestedArrayObject->new(); +$shared_hash{object} = SharedNestedArrayObject->new(); +print $destroyed == 5 + ? "ok 5 - replacement releases nested array object from shared hash\n" + : "not ok 5 - replacement releases nested array object from shared hash ($destroyed)\n"; + +# Keep each canonical object reachable until its slot is explicitly cleared. +@shared_array = (SharedNestedHashObject->new()); +%shared_hash = (object => SharedNestedArrayObject->new()); +my $before_clear = $destroyed; +@shared_array = (); +%shared_hash = (); +print $destroyed == $before_clear + 2 + ? "ok 6 - clearing shared aggregates releases nested objects\n" + : "not ok 6 - clearing shared aggregates releases nested objects ($destroyed)\n"; + +$shared_array[0] = SharedNestedHashObject->new(); +my $before_delete = $destroyed; +delete $shared_array[0]; +print $destroyed == $before_delete + 1 + ? "ok 7 - deleting shared array slot releases nested object\n" + : "not ok 7 - deleting shared array slot releases nested object ($destroyed)\n"; + +$shared_hash{object} = SharedNestedArrayObject->new(); +my $before_hash_delete = $destroyed; +delete $shared_hash{object}; +print $destroyed == $before_hash_delete + 1 + ? "ok 8 - deleting shared hash slot releases nested object\n" + : "not ok 8 - deleting shared hash slot releases nested object ($destroyed)\n"; + +print "ok 9 - shared nested object release checks completed\n"; diff --git a/src/test/resources/unit/throwing_captured_coderef_releases_argument.t b/src/test/resources/unit/throwing_captured_coderef_releases_argument.t new file mode 100644 index 0000000000..6e7a36c382 --- /dev/null +++ b/src/test/resources/unit/throwing_captured_coderef_releases_argument.t @@ -0,0 +1,28 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +sub invoke_callback { + my ($callback) = @_; + $callback->(); +} + +my $weak_object; +{ + my $object = bless {}, 'Local::CallbackObject'; + weaken($weak_object = $object); + my $callback = sub { + my $captured_class = ref($object); + die "expected callback exception for $captured_class\n"; + }; + + my $error; + eval { invoke_callback($callback); 1 } or $error = $@; + like($error, qr/expected callback exception/, + 'the callback exception reaches the caller'); +} + +ok(!defined($weak_object), + 'exception unwinding releases the captured callback argument'); +done_testing(); diff --git a/src/test/resources/unit/weak_captured_coderef_argument.t b/src/test/resources/unit/weak_captured_coderef_argument.t new file mode 100644 index 0000000000..73ae163691 --- /dev/null +++ b/src/test/resources/unit/weak_captured_coderef_argument.t @@ -0,0 +1,29 @@ +use strict; +use warnings; +use Test::More; +use Scalar::Util qw(weaken); + +{ + package Local::Runner; + + sub run { + my $self = shift; + Scalar::Util::weaken(my $callback = shift); + return $callback->(); + } +} + +{ + package Local::Storage; + + sub invoke { + my $self = shift; + return Local::Runner->run(sub { $self->{value} }); + } +} + +my $storage = bless { value => 23 }, 'Local::Storage'; +is($storage->invoke(), 23, + 'a temporary captured coderef stays callable after its callee weakens a copy'); + +done_testing(); diff --git a/src/test/resources/unit/weakly_tracked_undef_preserves_other_owner.t b/src/test/resources/unit/weakly_tracked_undef_preserves_other_owner.t new file mode 100644 index 0000000000..7dd9fe3b77 --- /dev/null +++ b/src/test/resources/unit/weakly_tracked_undef_preserves_other_owner.t @@ -0,0 +1,16 @@ +use strict; +use warnings; +use Test::More tests => 2; +use Scalar::Util qw(weaken); + +my $target = []; +my @owners = ($target, $target); +my $weak = $target; +weaken($weak); +undef $target; + +undef $owners[0]; +ok(defined $weak, 'one remaining strong cell keeps the weak target alive'); + +undef $owners[1]; +ok(!defined $weak, 'the final strong cell releases the weak target');