diff --git a/README.md b/README.md index 68513b6..18fd118 100644 --- a/README.md +++ b/README.md @@ -9,12 +9,13 @@ The headline artifact is a states-explored reduction table: naive DFS → +hashi Concurrency bugs — race conditions, deadlocks, missed signals — are notoriously hard to find because they depend on exact thread ordering. Rather than running a program once and hoping for the right schedule, this checker systematically explores every distinct interleaving and reports the exact `(thread, step)` schedule that reaches a bad state. The selected [#12 bounded Java bytecode workstream](docs/plans/bytecode-contract.md) -now exposes the initial **bounded, sequentially consistent bytecode profile**: annotated fixed actors, +now exposes a **bounded, sequentially consistent bytecode heap profile**: annotated fixed actors, exact DFS, monitor deadlocks, declared checks, artifact-bound evidence and strict replay through the -library, CLI, reports and viewer. Start with the [compiled lost-update and two-lock examples](examples/bytecode/README.md). -The [94C release ledger](docs/measurements/94C-bytecode-release.md) records validation and limitations; -[94B](docs/measurements/94B-bytecode-concurrency.md) owns the batching measurements and preservation argument. -Objects/arrays, general exceptions, wider primitives/libraries and additional bytecode search strategies +library, CLI, reports and viewer. Actor-created objects, primitive/reference arrays, aliases, closed hierarchy dispatch and transitive publication are supported. Start with the [compiled lost-update and two-lock examples](examples/bytecode/README.md). +The [95 heap ledger](docs/measurements/95-bytecode-heap.md) records heap acceptance and the extended batching argument; +[94C](docs/measurements/94C-bytecode-release.md) records initial release compatibility, and +[94B](docs/measurements/94B-bytecode-concurrency.md) records the earlier setup-only batching measurements. +General exceptions, wider primitive computation/libraries and additional bytecode search strategies remain later phases. Weak-memory work remains unselected. The project is a spec-driven proof of concept for small explicit models, bounded `.ilv` source and a diff --git a/build.gradle.kts b/build.gradle.kts index 80b226e..9cbd8cf 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -115,6 +115,24 @@ tasks.register("profileBytecode") { args(output.get(), fork.get()) } +// Spec95 heap measurement uses the same fixed heap and compacting collector as the94B runner. +tasks.register("profileBytecodeHeap") { + group = "verification" + description = "Measure instruction/reference bytecode execution (Spec 95)" + dependsOn(tasks.testClasses) + classpath = sourceSets.test.get().runtimeClasspath + mainClass.set("dev.samhb.interleave.bytecode.BytecodeHeapMeasurementTest") + javaLauncher.set(javaToolchains.launcherFor { languageVersion.set(JavaLanguageVersion.of(26)) }) + minHeapSize = "512m" + maxHeapSize = "512m" + // Eliminate SerialGC dead-space retention, which otherwise contaminates live-heap deltas. + jvmArgs("-XX:+UseSerialGC", "-XX:MarkSweepDeadRatio=0") + val fork = providers.gradleProperty("profileFork").orElse("1") + val output = providers.gradleProperty("bytecodeProfileOutput") + .orElse(layout.buildDirectory.dir("reports/bytecode-heap-profile/fork-${fork.get()}").get().asFile.absolutePath) + args(output.get(), fork.get()) +} + tasks.withType { options.encoding = Charsets.UTF_8.name() options.release.set(26) diff --git a/docs/measurements/94C-compare-mutations.py b/docs/measurements/94C-compare-mutations.py index 0a98cbc..0b22309 100644 --- a/docs/measurements/94C-compare-mutations.py +++ b/docs/measurements/94C-compare-mutations.py @@ -12,6 +12,7 @@ parser.add_argument('baseline_classes',type=Path,help='Baseline build/classes/java/main directory') parser.add_argument('feature_classes',type=Path,help='Feature build/classes/java/main directory') parser.add_argument('--javap',default='javap',help='JDK 26 javap executable') +parser.add_argument('--replacement-report',action='append',help='Whole-class replacement XML in evidence; repeat in chronological order (default: historical94C reports)') args=parser.parse_args() EVIDENCE=args.evidence @@ -77,7 +78,7 @@ def finish(): # Replace whole classes with the latest recorded run, never individual favorable mutants. rows=list(E.parse(EVIDENCE/'affected-census.xml').getroot()) -for name in ('postfix-focused.xml','final-codec-dto.xml','final-report-pit.xml'): +for name in (args.replacement_report or ('postfix-focused.xml','final-codec-dto.xml','final-report-pit.xml')): current=list(E.parse(EVIDENCE/name).getroot()) assert current, name replaced={m.findtext('mutatedClass') for m in current} diff --git a/docs/measurements/95-bytecode-heap.md b/docs/measurements/95-bytecode-heap.md new file mode 100644 index 0000000..ec95577 --- /dev/null +++ b/docs/measurements/95-bytecode-heap.md @@ -0,0 +1,493 @@ + +# 95 — Objects, arrays and dispatch + +## Status and reproducibility + +Implementation is based on freshly fetched merged main `5385a3c` (PR141/94C). +Local acceptance results and remaining publication gates are recorded below. Public semantics are defined by +[Spec95](../specs/active/95-bytecode-heap.md) and the [shared contract](../plans/bytecode-contract.md). +No96+ behavior, bytecode reduction or JPF compatibility is claimed. + +Baseline is an untouched detached checkout, sibling `interleave-95-baseline`. Mutation XML, final +fork data and browser logs are retained in sibling `interleave-95-evidence`. Earlier temporary +review/build logs are no longer available; their inspected results are recorded below. +The original dirty Interleave checkout is preserved. All Gradle commands use one worker/PIT thread; +CI parallelism, mutation operators/floors, resource settings and tests remain enabled. + +## Interfaces and profile + +The existing public loader, limits, runner and replay interfaces remain the seams. No new strategy, +CLI selector or host execution route is introduced. `BYTECODE-SC-2` authenticates the expanded language +and canonical encoding v2. SC-1 evidence remains viewable, but this SC-2 runtime rejects it for strict +replay instead of silently assigning new semantics. Source/JSON model formats and source continuations +are unchanged; public evidence record shapes/native serialization fields are unchanged. + +The metadata-only loader closes constructors, signatures, field types, hierarchy, nest hosts and all +reachable dispatch bodies. It rescans role/method obligations when the discovered class set grows. +Unreferenced directory classes cannot enter execution: all instantiation sites and supported reference +sources belong to this frozen closure. There is no runtime classpath lookup. Reachable bridge methods +remain rejected because no replacement for the JDK verifier's bridge-method gap is claimed. + +Field lookup preserves declaring owner/name/descriptor identities. Virtual lookup respects class +methods and maximally specific interface defaults; special calls retain constructor/super semantics. +Reciprocal same-package nest membership, sealed permitted edges in the single unnamed module, +and member/staticness/access rules are checked. +Resolution and runtime selection are distinct, following the admitted cases of +[JVMS5.4.3–5.4.6](https://docs.oracle.com/en/java/javase/26/docs/specs/jvms/jvms-5.html#jvms-5.4.6); +separate JVM cases distinguish class-typed resolution failures from interface default selection. After JDK +verification, protected-receiver analysis uses verified expanded stack-map types and straight-line +category-one transport, supplementing metadata visibility without interpreting target code on the host. + +Heap state includes exact runtime class/array descriptors, owned elements, aliases, initialization, +monitor owner/depth, permanent per-owner counters/sequences and irreversible sharedness. Snapshots +flatten array elements as typed identity/index cells and retain length/type. Wide arrays carry default +zero LONG/FLOAT_BITS/DOUBLE_BITS data only; their element computation/load/store remains excluded. +Array cloning belongs to97; executable initializers, general handlers and unsupported libraries still reject. + +## Requirements and independent checks + +| Contract | Connected delivery and acceptance | +|---|---| +| R1 | Actor application/Object construction, inherited/hidden fields, constructor chaining, interface/default/abstract/virtual/special/private-nest dispatch; JVM differential compiler releases17/21/26; all alternatives checked for unsupported behavior and observer impurity; missing metadata and forged protected receiver reject before search | +| R2 | Primitive/reference/ranked arrays, narrowing, zero defaults and aliases; null/bounds/negative-size/store/cast faults compared with an independent JVM, including monitor cleanup | +| R3 | Actor-local cyclic graphs and operand/callee roots promote transitively at publication; sharing survives unlinking; reference and batching match independent instruction enumeration for arrays and crossed publication | +| R4 | Namespace-local allocation sequences survive reversed schedules and publication; count/cell/length exact boundaries, failed allocation with no identity, partial multidimensional allocation with earlier identities/charges retained | +| R5 | Public JSON/native result transport, strict replay, built-jar library/CLI, reports, viewer and HeapPublication example; old lost-update/deadlock consumers remain exercised | + +`BytecodeHeapTest`, `BytecodeDispatchTest`, `BytecodePublicationTest`, `BytecodeHeapReleaseTest` and +`BytecodeHeapMeasurementTest` exercise the existing approved seams. Existing admission cases for newly +supported behavior migrate to positive assertions rather than disappearing: actor Object allocation, +arrays, constructor chaining, instance helper checks and interface fields. Unsupported narrow field/ +method descriptors, executable initialization, general handlers, wider computation and host calls still reject. + +Fixed seed `0x952026` generates12 bounded sequential heap/cast/dispatch fixtures over releases17/21/26, +compares a separate JVM and saves deletion-shrunk failures. Existing arithmetic generation/shrinking +and saved regressions remain active. Test-only oracle processes are not a production fallback. + +The initial heap-generator attempt emitted `read()--2`; parenthesizing negative operands fixes the +source generator. Its PIT attempt stopped during initial unmutated coverage and produced no census; +that failure is not counted as mutation evidence. The corrected generated suite passes. + +## Batching preservation argument + +Assumptions: admitted verified category-one code, fixed actors, bounded owned heap, no host callbacks, +no general handlers, pure observers, SC visible accesses and identical selected limits. Relate reference +and batched states by exact heap/alias/static/frame/resource/BCI/monitor/history values at matched +boundaries, permitting a finite stutter of one actor's local arithmetic/transport between boundaries. + +All field and array accesses, allocations, monitor operations, returns and fault/terminal delivery remain +conservatively observable boundaries, including actor-local heap operations. No locality optimization +is inferred merely from the allocator or fuel. A shared increment retains distinct load/store choices. +Every batch executes the same fueled opcode primitive and preserves each actual operation/BCI. +Allocation (including partial dimensions) is an explicit boundary; the component sequence is one JVM +opcode, with deterministic depth-first identity/charge order and no interleaving inside that opcode. + +An actor-created reference starts solely on its allocating actor's stack. Reachability refresh includes +fixture/statics, historical shared roots and every actor's locals/operands/return/monitor roots, traversing +field and array edges. Only proven exclusive actor reachability permits false sharedness. Unknown roots +promote, and true is never reset. Publication and its graph promotion commit in the same selected +transition before another actor/check can observe the escape. Losing a local root cannot create a new +cross-actor path; a future reachable alias must come through an already traced edge. Canonical keys +retain history even if public roots disappear. Counters permanently belong to the allocator. + +Omitted local steps cannot change any supported pure check's value/error: observers cannot reach local +frames or private graphs, allocate/mutate, or inspect budgets/history. Observer instruction/depth allowances +reset per invocation; identical visible inputs and call graph therefore preserve observer fuel/depth/error +behavior as well as values. Extra reference-mode observations of the same input cannot introduce a +new per-invocation limit failure; no aggregate observer-fuel bound is claimed. Dynamic faults and resource +cutoffs leave pending events and yield before terminal delivery; probes charge no work or target effects. +Thus batching cannot consume an uncaught terminal and suppress a competing actor's established violation. +Normal returns on the exact last instruction still succeed. Fault cleanup/exception events remain explicit. + +Match observable operations and terminal outcomes by induction over selected boundaries, commuting only +unobserved local stutters of different actors. The relation preserves enabledness, prior committed effects, +check outcomes/errors, real failure sites and cutoff actor/reason/location/limit. It does not require equal +trace length, transition counts or intermediate local snapshots. Independent instruction enumeration and +adversarial tests challenge this argument; they are not a substitute for it. No DPOR preservation claim. + +## Fresh baseline + +- Fresh merged-main build/tests and strict Javadoc passed before production edits. +- Default PIT:455 KILLED,13 SURVIVED,0 NO_COVERAGE /468. +- Affected census:4024 KILLED,413 SURVIVED,556 NO_COVERAGE /4993; completed without resource/run errors. +- These are newly measured at5385a3c, not imported94C ledger totals. + +Default is the existing state/cb gate, not whole-project mutation coverage. Every PIT run retains +`targetTests=dev.samhb.interleave.*`; only production mutation targets are scoped. The baseline and +feature affected scope use the following exact command: + +```sh +./gradlew --max-workers=1 -PpitestThreads=1 build javadoc +./gradlew --max-workers=1 -PpitestThreads=1 pitest +./gradlew --max-workers=1 -PpitestThreads=1 pitest '-PpitestTargetOverride=dev.samhb.interleave.bytecode.*,dev.samhb.interleave.BytecodeTraceJson*,dev.samhb.interleave.ResultJson*,dev.samhb.interleave.core.BytecodeEvidence*,dev.samhb.interleave.InterleaveRunner*,dev.samhb.interleave.TestResult*,dev.samhb.interleave.TraceRecord*,dev.samhb.interleave.search.TraceReplayer*,dev.samhb.interleave.report.BenchmarkHarness*,dev.samhb.interleave.report.BenchmarkResult*,dev.samhb.interleave.report.ReportWriter*,dev.samhb.interleave.report.SoundnessAttestation*,dev.samhb.interleave.cli.Main*' +``` + +Each completed XML is archived before the next PIT run. NO_COVERAGE and resource detections +are never counted as kills. Final scoped results and inherited comparisons are recorded below. + +## Dynamic interface receiver fault + +JVM verification permits some interface receiver flows that still require a dynamic receiver check. +A saved adversarial transformation replaces a null interface receiver with a freshly initialized plain +Object. Loading succeeds on both the Class-File verifier and JVM; the independent JVM throws +IncompatibleClassChangeError. The earlier interpreter leaked a host NullPointerException during +missing-target lookup. It now checks assignability before dispatch/depth and models the genuine VM +fault through the same fueled unwind/terminal protocol. This is a95 supported-instruction fault, +not admission of arbitrary linkage repair, user handlers or host fallback. + +## Dynamic heap measurements + +Correctness gate: both checked-in heap fixtures must have identical normalized independent instruction, +REFERENCE and BATCHED outcome sets before timing. Fixture sources are under +`src/test/resources/bytecode/heap/{cyclic-publication,aliased-array}`. Measurements use the same source, +artifact and limits in both modes, JDK26, fixed512MiB heap, compacting SerialGC, two warmups and three +alternating-mode repetitions per fixture/mode in each of three fresh JVM forks. + +Retained memory is post-compaction used heap with actual explorer/store/witnesses reachable, minus +pre-run compacted heap, measured outside the execution stack. It is not allocation rate/key bytes. +History-only states are counted in a separate production-granularity enumeration checked against actual +unique-state counts, erasing only sharing flags in comparison copies. Its extra work is outside timing. +Sharing work counts real object/edge visits per root traversal, including repeat visits from actor roots; +it is not directly interchangeable with94B's old all-roots-unioned traversal counts. + +```sh +./gradlew --max-workers=1 -PpitestThreads=1 test --tests '*BytecodeHeapMeasurementTest' +./gradlew --max-workers=1 -PpitestThreads=1 profileBytecodeHeap -PprofileFork=1 -PbytecodeProfileOutput=/path/to/evidence/fork-1 +# Repeat with profileFork=2/3 and distinct fork-2/fork-3 output directories. +``` + +Raw `samples.csv` and `conditions.md` record Java/OS/flags, exact source/artifact digests and limits. +Superseded allocation/dispatch samples are archived under `early-forks`; samples predating original +constructor-receiver encoding are under `pre-constructor-measurements`. Neither set is final evidence. +The final six forks are collected after mutation checks, without concurrent PIT work. + +## Review and final gates + +Ordinary connected-source/security review found a missing symbolic class-visibility check on array +allocation/type-check instructions. An isolated malformed array regression failed before the fix; +array/cast variants pass after the fix. Trusted final Object member overrides now produce an early +LINKAGE diagnostic; the earlier test rejected as UNSUPPORTED because its call referenced Object. +These refinements are verified in the isolated validation checkout while the original compiled +feature census remains unchanged. Final mutation evidence must explicitly replace the loader class +observations after its refinement, rather than pretending the earlier snapshot contains that fix. + +CodeRabbit CLI0.8.1 was invoked on the complete staged implementation. Its first invocation ended +with `Connection failed: WebSocket closed`, without findings/completion evidence. The same-scope host +retry completed `review_completed`,8 findings across42 files (`interleave-95-coderabbit-retry.ndjson`). +No completion is attributed to the failed attempt. + + +Fresh-reader review completed using only the spec/contract/ledger. Valid findings addressed: distinguish +implementation status from historical authoring prose, state observer fuel/depth/error preservation +explicitly, and clarify component-level allocation failure in the shared contract. The reader did not +inspect code or validate runtime evidence. + +The final integrated `build javadoc` passes 2,120 tests with zero failures/errors. Strict private +doclint passes all 17 changed production/harness files. Public heap examples and replay are tested +through real built-jar processes. Mutation comparisons, final measurement forks and the fresh +browser matrix are recorded separately below; earlier intermediate checks do not substitute for them. + +### Completed CodeRabbit review disposition + +Original severities are retained: + +- minor: interface static declarations are not inherited; skip them in superclass/interface override comparisons and retain superclass static checks. Regression expects C.value()=2. +- major: reject cross-package nonpublic direct superinterfaces; also check superclass visibility, with public controls. +- major: array/cast leaf-type access checks overlapped the ordinary-review fix; retain malformed array/cast cases and accessible controls. +- major: replace recursive transitive override queries with a bounded superclass walk. Inspect each declaration once from base to candidate, tracking only legally widened inheritance. This avoids repeated false subproblems and keeps metadata immutable without cache/concurrency machinery. The generated30-level cross-package hierarchy retains the base package-private target and a loading ceiling. +- major: observer dispatch purity was already role-specific (`Work(method,role)`), even for decoded methods present in the map. Add the exact actor-then-CHECK mutating-override regression rather than changing correct dispatch semantics. +- major: array-valued stores already check the destination runtime component before mutation. Add int[] success/long[] failure coverage and verify the prior int[] element survives, independently checked on the JVM. +- trivial: assert each public heap fixture's exact terminal/fault category in addition to serialization/replay equality. +- trivial: bound the publication regression's cutoff-driving loop and reject unexpected terminal phases. + +All findings have a concrete fix or verified existing behavior with strengthened regressions. +The bounded follow-up disposition and final verification are recorded separately below. + +### Completed follow-up review disposition + +The bounded follow-up completed `review_completed`,7 findings across43 files +(`interleave-95-coderabbit-followup.ndjson`): + +- minor: pending-review prose was stale after the first completed review; replace it with current gate status. +- major: interface default fallback could rediscover a skipped private superclass method. Select only maximally specific interface declarations after class search, while preserving inherited public class implementations. Independent JVM controls expect1 for a private base method and2 for a public base method. +- major: repeated observer-purity concern is covered by role/method validation and the actor-then-check mutating-override rejection; pure override controls remain admitted. +- major: dispatch-retention concern was traced through the fixed-point closure and common loader/runtime selector. All selectable valid implementations and their dependencies are retained. An additional JVM-valid incompatible-receiver case now produces the modeled VM fault rather than a missing-target host exception. +- trivial: capture the instruction counter immediately before each first faulting primitive, require exactly one charged instruction, and retain cleanup/fault assertions. +- trivial: publication now promotes a two-node private cycle; assert both nodes before escape, after escape and after unlinking, with two allocations/six cells. +- trivial: document constructors/actors in both measurement fixtures, including private-cycle construction and the independent competing write. + +The override implementation uses a bounded superclass walk rather than recursive caching; both deep +inaccessible same-name declarations and legal transitive widening match the JVM. The subsequent +R6 infrastructure work received its own completed review, recorded below. + +## Feature mutation census and loader progress assertion + +The completed initial feature census contained4804 KILLED,647 SURVIVED,625 NO_COVERAGE and6 +TIMED_OUT /6082. R6 failed: no timeout is an assertion kill. The six timeout identities are in +BytecodeLoader.load: three negated convergence/pending conditions and three removed Map.size or +ArrayDeque.isEmpty calls. Raw `affected-census.xml` retains this failed run unchanged. + +The existing PIT-only BytecodeWorkBudget agent now asserts loader fixed-point progress independently +of those conditions. A pass either terminates or grows the application class set; at most64 classes +permit at most64 passes. There are two Map.size checkpoints per pass, with a130-checkpoint invocation +allowance including framing. It binds the exact load(BytecodeLimits) descriptor and validates two +original checkpoints; a single PIT call-removal replacement may retain one. It never reads the mutated +convergence condition to derive its allowance, never instruments target classes and is not shipped in +the production jar. No timeout/resource setting or mutation gate changed. + +Real-definition controls preserve outcomes with and without the agent. An actual removed class-count +call becomes a nonconvergent loader; the transformed replacement fails the independent assertion in a +child JVM and reports BOUND_EXCEEDED. Original binding/checkpoint drift rejects. Focused mutation reports replace whole refined classes, including the six incomplete +loader observations, before the assembled comparison is evaluated. The earlier full census itself +will never be labeled a passing final run. + +### Additional R6-work review disposition + +The R6 progress assertion introduced new test infrastructure, so an additional actual CLI review was +invoked rather than treating earlier reviews as evidence for that work. It completed +`review_completed`,7 findings across46 files (`interleave-95-coderabbit-progress-gate.ndjson`): + +- minor: stale pending-review summary; reconcile the final status with actual completed reviews. +- major: retain all legally overriding declarations in the bounded walk, not merely the last one. JVM-verified raw narrowing can preserve an earlier public widening; generated A/B/C/D classes return4 on the JVM and interpreter. Admission follows JVM overriding rather than imposing Java-source visibility-narrowing rules. +- major: private resolved invocations already bypass subclass selection in loader and executor. A base-private/child-shadow regression returns1, preserving subclass dispatch for ordinary methods. +- major: all four runtime field opcodes already use hierarchy-resolved declaring IDs. An inherited static/instance model/base alias regression verifies one static cell and values2/4 on both JVM and interpreter. +- major: ancestors already uses a visited set. A forged I/J interface cycle rejects with LINKAGE; no recursive expansion is admitted. +- major: array loads/stores were already scheduling boundaries. Two shared int[1] increments with FINAL x[0]==2 retain both COMPLETED and CHECK_FALSE and match independent instruction enumeration in both modes. +- major: constructor receiver identity incorrectly depended on mutable local0. Store the original immutable receiver in the frame, copy/encode/snapshot/root it, and mark completion through that reference. A verified setup/actor constructor overwriting local0 with null completes normally on JVM and interpreter. + +Canonical framing expectations were independently recalculated with a Python linear-opcode state +model:140 states,366 extra encoded frame slots including root,212 retained frame slots. The updated +literal byte totals are119051 and67438. Independent DataInputStream schema decoding and the actual +search agree. This is an encoding calculation, not a performance proxy. + +The final seven-class run (loader, hierarchy, opcode executor, frame, owned state, snapshots and +sharing) completed without R6 detections: 1714 KILLED,237 SURVIVED,93 NO_COVERAGE /2044 +(`final-owned-state.xml`). The earlier three-class run +passed1327 KILLED,186 SURVIVED,91 NO_COVERAGE /1604 (`final-refined.xml`). + +## Pre-review measured results (4f1da27) + +All six fresh JDK26 forks completed with mandatory independent outcome equivalence: three heap +forks and three initial-release forks, nine measured samples per fixture/mode (72 total). No PIT +process ran concurrently. Every fork used `26.0.2.1`, macOS/aarch64 and fixed512MiB compacting +SerialGC. The original initial-release task is reused; its historical94B conditions heading names +the harness origin, not the interpreter/profile revision measured here. + +Counts/bytes below are identical across all nine samples. Time and retained heap are median +(minimum–maximum); milliseconds and KiB respectively. These tiny fixtures show variation and are +not throughput estimates for arbitrary Java. + +| Fixture/mode | States | Transitions | Encodes | Encoded bytes | Encoding ms | Elapsed ms | Retained KiB | +|---|---:|---:|---:|---:|---:|---:|---:| +| aliased-array/REFERENCE | 98 | 175 | 176 | 118649 | 0.472 (0.299–1.150) | 1.262 (0.863–1.973) | 83.570 (83.570–83.641) | +| aliased-array/BATCHED | 35 | 58 | 59 | 39513 | 0.130 (0.107–0.197) | 0.619 (0.533–0.868) | 31.891 (31.891–31.891) | +| cyclic-publication/REFERENCE | 147 | 266 | 267 | 207740 | 0.613 (0.522–2.534) | 2.101 (1.677–7.794) | 138.531 (138.406–139.711) | +| cyclic-publication/BATCHED | 50 | 85 | 86 | 66267 | 0.253 (0.173–0.285) | 1.470 (0.963–1.792) | 49.562 (49.562–50.094) | +| lost-update/REFERENCE | 140 | 246 | 247 | 119051 | 1.686 (0.545–2.745) | 4.569 (1.941–6.189) | 93.312 (93.188–93.961) | +| lost-update/BATCHED | 60 | 98 | 99 | 46297 | 0.471 (0.336–1.437) | 1.709 (1.468–2.785) | 42.570 (42.375–42.711) | +| two-lock/REFERENCE | 475 | 866 | 867 | 709663 | 1.936 (1.663–2.434) | 4.155 (3.641–5.097) | 462.625 (462.555–463.414) | +| two-lock/BATCHED | 116 | 196 | 197 | 160813 | 0.565 (0.352–0.629) | 1.550 (1.105–1.844) | 119.547 (119.547–119.883) | + +| Fixture/mode | Refreshes | Object visits | Edge visits | Promotions | History-only states | Outcome identities | +|---|---:|---:|---:|---:|---:|---:| +| aliased-array/REFERENCE | 22 | 115 | 45 | 7 | 0 | 1 | +| aliased-array/BATCHED | 16 | 81 | 31 | 5 | 0 | 1 | +| cyclic-publication/REFERENCE | 22 | 137 | 45 | 7 | 0 | 1 | +| cyclic-publication/BATCHED | 16 | 97 | 31 | 5 | 0 | 1 | +| lost-update/REFERENCE | 1 | 4 | 0 | 0 | 0 | 2 | +| lost-update/BATCHED | 1 | 4 | 0 | 0 | 0 | 2 | +| two-lock/REFERENCE | 1 | 10 | 6 | 0 | 0 | 2 | +| two-lock/BATCHED | 1 | 10 | 6 | 0 | 0 | 2 | + +Sharing visits/promotions are aggregates over explored successors, not one execution. The dynamic +fixtures exercise cyclic/reference-array publication and nonzero sharing work. Historical flags +remain canonical even though these fixtures produced no pair differing solely in those flags; zero +is not evidence that history can be discarded. Independent targeted tests cover unlinking history. + +Batched execution has fewer states/transitions/encoded bytes and lower median elapsed time/retained +heap on each measured fixture. Timing ranges overlap in some comparisons; cyclic-publication +reference timing has a7.794ms maximum. No universal speedup or percentage target is claimed. +Per-root traversal revisits aliases deliberately, and larger graph costs remain a practical limit. +There is no measured reason here to change the provisional default budgets or weaken sharing. + +Reproduce initial-release forks with `profileBytecode` instead of `profileBytecodeHeap`; use distinct +`final-initial-fork-N` and `final-heap-fork-N` output directories for N=1,2,3. Raw CSV, conditions and +completion logs are retained in the local evidence directory. + +Measured checker/harness/test/build diff SHA-256: `215d266cc2ae0be7242fb9bc0a1c96dcdcfe69b21a8302a3e7de595509bec013`. +These samples precede the PR142 corrections below. Source/artifact digests and +exact limits are in each fork’s `conditions.md`. + +## Pre-review mutation comparison (4f1da27) + +| Observation | KILLED | SURVIVED | NO_COVERAGE | Resource detections | Total | +|---|---:|---:|---:|---:|---:| +| Fresh default baseline |455|13|0|0|468| +| Final default run |455|13|0|0|468| +| Fresh affected baseline |4024|413|556|0|4993| +| Initial feature census, failed R6 |4804|647|625|6 TIMED_OUT|6082| +| Refined three-class run |1327|186|91|0|1604| +| Final seven-class run |1714|237|93|0|2044| +| Assembled affected observations |4917|640|594|0|6151| + +The default fingerprint/status map matches baseline exactly. The affected assembly replaces entire +classes in chronological order using `final-refined.xml`, then `final-owned-state.xml`; it is **not +one passing whole-project or affected PIT run** and is never supplied to the mutation ratchet. The +raw failed census stays unchanged. All runs retain the full target-test selection. + +Descriptor-complete normalized disassembly identifies unchanged compiled methods with3028 baseline +kills,276 survivors and466 uncovered mutants. All3028 comparable kills remain killed; six inherited +survivors become kills and one uncovered mutant gains coverage but survives. Changed/moved methods +are listed separately in `comparison-inherited.json`: their baseline kills do not have a valid +one-to-one preservation claim. The larger denominators include new/changed code. The remaining640 +survivors and594 uncovered observations remain residual risk, not asserted equivalent mutants. + +```sh +python3 docs/measurements/94C-compare-mutations.py /path/to/interleave-95-evidence \ + /path/to/interleave-95-baseline/build/classes/java/main build/classes/java/main \ + --javap /path/to/jdk26/bin/javap \ + --replacement-report final-refined.xml --replacement-report final-owned-state.xml +``` + +The helper retains its historical94C default behavior; its optional repeatable argument supplies +whole-class replacement reports for95. The original94C comparison also passed as a compatibility +check before this final comparison. Missing/duplicate reports, resource statuses and lost comparable +kills fail the diagnostic. This evidence does not establish complete mutation coverage or a proof. + +## Final consumer and publication gates + +Fresh browser producers pass after the last PIT run. The complete CI environment matrix passes +**309 browser assertions, zero failures and zero console errors/exceptions**: BYTECODE heap/faults, +source, declarative symmetry, exact/approximate strategies and resource-prefix evidence. Normalization +checks pass in the same command. The original source/JSON/symmetry formats retain their checks. + +Final ordinary review traces admission through hierarchy/access validation, owned copy/encoding, +opcodes/accounting, publication, scheduler terminals and replay/viewer consumers. Target code is +never host-loaded; the JVM differential subprocesses are test-only. No new runtime dependencies, +timeout relaxations, mutation operator reductions or hidden exact bitstate storage are introduced. +Public additions remain bounded SC; wide array defaults do not admit wide computations. + +Three actual CodeRabbit reviews completed as recorded above; the initial WebSocket failure did not. +The original NDJSON and earlier full-build/doclint logs were written to `/private/tmp` during those +runs and are no longer present after session resumption. Their completion/findings were inspected +and dispositions recorded during execution; this ledger preserves that record, not a claim that +those temporary raw logs remain available. Mutation XML and final fork/browser logs are retained +in the sibling evidence directory. + +CI and Sam’s manual acceptance remain pending; publish as a draft. No deployment, CI watcher,96+ +implementation, optimized bytecode DPOR measurement or JPF compatibility evidence is claimed. + +Final fresh-reader testing correctly distinguished local acceptance, pending CI/manual review, mutation +assembly limits, inherited preservation, six-fork measurements and SC-1 compatibility. Two stale +retention/sharedness-status claims were corrected; the reader inspected docs only, not runtime evidence. + +## PR142 review corrections + +All11 inline findings, the outside-diff viewer finding and the additional sealed-subtype finding +were independently validated. No requested finding was silently deferred. + +| Review item | Disposition and regression | +|---|---| +| Protected-receiver failure Javadoc | Document LINKAGE rejection separately from verified stack analysis | +| Hierarchy failure Javadoc | Distinguish missing declarations/null from METADATA, cycles, conflicting defaults and invalid special owners | +| Special selection/static shadow | Select instance declarations through the superclass chain; independent JVM returns1 with static B and2 with instance B | +| Access/nest helper Javadoc | Describe inaccessible symbolic types and invalid reciprocal nests | +| Repeated hierarchy validation | Cache only successful validation by the existing strictly increasing frozen input-byte version; a2000-call/3000-method fixture timed out at20s before the fix and loads within its bound after it; this is a regression ceiling, not a benchmark | +| Access on selected super target | Retain symbolic resolution access, remove repeated selected-target access; JVM accepts package-private B while inaccessible symbolic A still rejects | +| Invokeinterface visibility | Apply selected public-target rule to the opcode, not the declaration’s interface owner; class-view call returns2, interface-view rejects | +| Transitive unknown promotion | Close newly promoted unreachable parents through descendants before observations; actor-rooted graph stays private, repeated refresh adds no promotions | +| Inherited fields/exhaustiveness | Require exhaustive exploration and exactly COMPLETED in addition to JVM values | +| Heap measurement outcome guard | Require exactly the successful expected graph, aliases and values from each fixture in both test and profiling entry | +| Implicit monitor/oracle | Classify publication only after frame entry; allocation cutoff after a discarded Node omits its private cells | +| Outside-diff viewer bound | Replace per-map65536 field cap with setup+actor selected heap-cell allowances plus9 setup diagnostics; actual two-actor arrays cost36883 cells each and exceed65536 snapshot fields; normalize accepts73728 and rejects88202 entries against88201 bound | +| Additional sealed subtype | JVMS5.3.5 allows a permitted public cross-package subtype in the same runtime module; actual JVM positive/nonpublic-negative controls establish the distinction | + +The JVM references are [special invocation](https://docs.oracle.com/en/java/javase/26/docs/specs/jvms/jvms-6.html#jvms-6.5.invokespecial) +and [deriving classes](https://docs.oracle.com/en/java/javase/26/docs/specs/jvms/jvms-5.html#jvms-5.3.5). +Before fixes, the new regression batch failed on selection/visibility, sealed admission, unknown +promotion, premature oracle promotion and the hierarchy deadline. The first special-static test +transformation was rejected by the Class-File API; replacing its method body/flags via a fresh method +definition fixed that test setup. Viewer normalization independently reproduced the old field cap. +The related regression batch and normalization boundary checks pass after corrections. + +These corrections change sharedness traversal work. The earlier tables and mutation observations +above describe the pre-review snapshot; refreshed measurements/scoped evidence follow below. + +### Refreshed verification and measurement evidence + +The final integrated build and strict Javadoc pass **2127 tests**. Strict private doclint passes +the four changed production files. Complete browser compatibility passes309 assertions,0 failures +and0 console errors; normalization additionally accepts/rejects the large aggregate snapshot cases. +Browser checks consumed the fresh integrated-build artifacts before PIT, avoiding a redundant +Gradle producer run. Existing default/broad mutation runs are not repeated for these scoped fixes. + +Six refreshed forks (`pr142-{heap,initial}-fork-{1,2,3}`) pass normalized outcome equivalence and +the new heap-specific expected-outcome guard. JDK26/512MiB/SerialGC/warmups/repetitions are unchanged. +The short browser matrix overlapped the beginning of this sample batch; no PIT ran concurrently. +Ranges expose this ordinary machine-load variability; no isolated timing or universal speedup is +claimed. All state/transition/encoding/sharedness counts match the pre-review table. + +| Fixture/mode | Encoding ms median (range) | Elapsed ms median (range) | Retained KiB median (range) | +|---|---:|---:|---:| +| aliased-array/REFERENCE | 0.409 (0.358–1.215) | 1.092 (0.941–2.098) | 83.570 (83.570–83.766) | +| aliased-array/BATCHED | 0.135 (0.120–0.201) | 0.597 (0.537–0.905) | 31.891 (31.891–31.891) | +| cyclic-publication/REFERENCE | 0.627 (0.455–1.912) | 2.136 (1.595–8.371) | 138.531 (138.406–139.648) | +| cyclic-publication/BATCHED | 0.253 (0.186–0.295) | 1.497 (1.214–2.048) | 49.562 (49.562–50.047) | +| lost-update/REFERENCE | 1.635 (0.930–1.872) | 3.561 (2.798–5.113) | 93.312 (93.234–94.125) | +| lost-update/BATCHED | 0.605 (0.275–1.336) | 1.917 (1.058–2.433) | 42.406 (42.328–42.773) | +| two-lock/REFERENCE | 1.736 (1.397–2.413) | 3.936 (2.989–5.069) | 462.625 (462.555–463.414) | +| two-lock/BATCHED | 0.517 (0.338–0.648) | 1.598 (1.095–1.673) | 119.547 (119.547–119.883) | + +Measured correction diff against4f1da27 SHA-256: `5c221818c3c0c1fda23f9e8bc057d4c6188734232cce21a80f8432038ae51544`. +A later loader-only cache-key refinement is outside timed search and does not change the measured +executor, state, sharing, encoding or fixtures. The hash identifies the measured source snapshot. The one integrated run before +this final run caught a redundant traversal of an already-rooted promoted object; narrowing the +extra closure to unknown/unreachable parents preserved the original instrumentation expectation +without weakening its assertion. + +CodeRabbit CLI0.8.1 completed an actual `review_completed` with0 findings across12 correction +files (`pr142-coderabbit.ndjson`). The subsequent tiny refinement avoids reclosing already-rooted +promotions; ordinary review and the final integrated build cover it. This is not a fabricated +review of later documentation bookkeeping. Current raw review output is retained durably in the +sibling evidence directory. + +No broad/default PIT rerun or additional Gradle producer run is claimed for this patch. The scoped +Loader/Hierarchy/Sharing observations and updated inherited comparison are recorded below. + +The first three-class correction census produced1078 KILLED,178 SURVIVED,90 NO_COVERAGE and2 +TIMED_OUT /1348; R6 failed, and raw `pr142-scoped-before.xml` preserves it. Both timeouts remove +Map.size calls in the newly added validation cache, reintroducing repeated expensive validation. +The cache now uses the existing bounded aggregate byte count as its class-set version: each new +frozen class read strictly increases total, immutable metadata never changes within that version, +and failed loading aborts. Only successful hierarchy validation records a version. This removes +redundant size queries and a separate generation counter. No operator, timeout, target-test or +resource gate is changed; only the loader needs a scoped rerun. + +### Completed correction mutation evidence + +The loader-only rerun passes R6: **757 KILLED,122 SURVIVED,50 NO_COVERAGE /929**, with zero +timeout, memory, run-error or nonviable detections (`pr142-loader.xml`). The failed three-class +report remains unchanged. The hierarchy/sharing class observations from it contain no resource +detections; latest loader observations replace that entire class, not selected favorable mutants. + +The updated affected assembly is **4947 KILLED,637 SURVIVED,598 NO_COVERAGE /6182**. It is still +not one passing affected/whole-project PIT run and is never supplied to the ratchet. The unchanged +compiled-method comparison retains every one of3017 comparable baseline kills; six inherited +survivors become kills and one uncovered mutant becomes a covered survivor. The comparable count +differs from the pre-review3028 because changed constructor/method bodies leave that comparison, +not because baseline kills are silently discarded or claimed preserved across changed code. +Changed/moved methods remain separately listed with no one-to-one preservation claim. + +The helper reads the existing pre-review default455/13/0 observations; no new default run is +claimed. Reproduce the affected assembly by appending these whole-class reports to the earlier +comparison command, in order: + +```sh +--replacement-report pr142-scoped-before.xml --replacement-report pr142-loader.xml +``` + +The2127-test integrated build preceded the small cache-key refinement. Focused loader, dispatch, +input-boundary, strict Javadoc and four-file private doclint pass after it; the final PIT invocation +also passes its unmutated coverage run with the full unchanged target-test selection. Browser +artifacts and search measurements precede that loader-only refinement and cover unchanged search/ +consumer behavior. No blanket timeout change, mutation gate relaxation or test weakening occurred. diff --git a/docs/plans/bytecode-contract.md b/docs/plans/bytecode-contract.md index af9e05b..d12d2f6 100644 --- a/docs/plans/bytecode-contract.md +++ b/docs/plans/bytecode-contract.md @@ -3,7 +3,7 @@ ## Objective and status -**Selected; 94A/94B implemented, 94C initial public profile locally accepted; PR/CI/manual review pending.** Approved scope: controlled interpretation of compiled Java for fixed +**Selected; 94A/94B/94C merged, 95 heap profile implemented and locally verified; draft PR/CI/manual acceptance pending.** Approved scope: controlled interpretation of compiled Java for fixed actors under bounded sequential consistency (SC). The first public release must find a real lost update and a two-lock deadlock through loading, search, evidence, strict replay, library/CLI, reports and viewer. No target-code host-JVM fallback is permitted. This is not unrestricted Java or full Java Memory Model coverage. @@ -14,7 +14,8 @@ and parked conditional/deferred tasks remain unselected. The specification PR es evidence. The [94A implementation ledger](../measurements/94A-bytecode-foundation.md) records subsequent loader/single-actor evidence; [the94B ledger](../measurements/94B-bytecode-concurrency.md) records internal concurrent execution, batching preservation and measured setup-only sharedness costs. The [94C ledger](../measurements/94C-bytecode-release.md) records public library/CLI, replay and consumer -verification. Broader heap costs, restricted DPOR and JPF gates remain pending. [Vocabulary](../../CONTEXT.md) owns domain terms; this document +verification. The [95 ledger](../measurements/95-bytecode-heap.md) records dynamic heap/sharedness +measurements and local heap-profile acceptance. Restricted DPOR and JPF gates remain pending. [Vocabulary](../../CONTEXT.md) owns domain terms; this document owns common behavior, interface seams, verification and phase boundaries. ## Sequential delivery and ownership @@ -226,7 +227,9 @@ failure into PASS. An earlier established finding remains recorded if a later br ## Faults, monitors and verdicts Model null field/monitor access as NullPointerException and integer divide/remainder zero as -ArithmeticException. Preserve prior instruction effects; the faulting opcode follows JVM semantics +ArithmeticException. Phase95 adds supported array/cast faults and the dynamic +IncompatibleClassChangeError for an incompatible interface receiver; statically known linkage failures +still reject during loading. Preserve prior instruction effects; the faulting opcode follows JVM semantics and consumes fuel. Required cleanup/unwinding runs, then an uncaught actor exception is VIOLATION/UNCAUGHT_EXCEPTION, distinct from CHECK_FALSE. Capture actor, exception type, throwing class/method/descriptor/BCI, and interpreted frames; do not use a host stack as target evidence. @@ -288,8 +291,8 @@ Cell limits bound modeled storage, not JVM bytes. Metadata/input caps and a glob abort protect implementation overhead; report external safety aborts honestly as INCOMPLETE. Allocation, cell and depth cutoffs name the omitted allocation/invoke location, reason and configured limit. For simultaneous failures use fuel first, then opcode dynamic validity (e.g. negative length), then -array/String length, allocation count, cells, depth as applicable. Failed allocations charge no cells -or identities; an executed allocating opcode consumes fuel even if it cannot allocate. No exception +array/String length, allocation count, cells, depth as applicable. Each failed component allocation charges no cells +or identity; earlier successful multidimensional components remain committed as specified in95; an executed allocating opcode consumes fuel even if it cannot allocate. No exception object allocation is required for initial modeled VM faults: bounded pending-fault metadata belongs to actor state, with no fabricated user-visible Throwable before 96. @@ -430,7 +433,8 @@ state relation, event matching, counterexample tests and limits. A green suite a [verified, 94B] Reference/batched tiny-fixture measurements, setup-only sharedness costs and batching preservation are recorded in the [94B ledger](../measurements/94B-bytecode-concurrency.md). -[unverified] Broader-heap sharedness costs, optimized reduction measurements and JPF compatibility. +[measured]95 records tiny cyclic/array heap fixtures and actual sharedness work; larger-graph costs +remain unmeasured. [unverified] Optimized reduction measurements and JPF compatibility. [deferred research] Frozen exhausted actors, fuel-free cycle detection, broader cyclic DPOR and initializer allowlists. None is a release requirement or implied optimization opportunity. diff --git a/docs/plans/future-work.md b/docs/plans/future-work.md index d383bbb..3c946ae 100644 --- a/docs/plans/future-work.md +++ b/docs/plans/future-work.md @@ -168,7 +168,7 @@ milestones (94A–94C, 95–101). #11 and deferred/conditional work remain unsel |---|---|---|---|---|---| | 10 | Symmetry reduction — complete | High | Spec-set | [Spec 75](../specs/active/75-thread-symmetry-canonicalization.md), [Spec 76](../specs/active/76-source-symmetry-exact-search.md) and [Spec 77](../specs/active/77-source-symmetry-strategy-composition.md) shipped in PRs #117–119. Final composition merged at `d8ad49e`: checked source symmetry for exact DFS, static POR, DPOR and CBS, including iterative CBS and original-identity evidence. | Completed in three coherent stages: canonicalization/mappings; checked exact DFS and evidence; exact POR/DPOR/CBS composition with proof, callers and regressions. K1 / [Spec 89](../specs/active/89-approximate-symmetry-dfs-por.md) adds approximate bitstate composition for explicit DFS/static POR; [Spec 90](../specs/active/90-approximate-symmetry-cbs.md) adds CBS in K2; [Spec 91](../specs/active/91-approximate-symmetry-dpor.md) adds DPOR and all-strategy consumers in K3, completing B9 with PR #134 merged at `3d5c09e`. Arbitrary custom-store composition remains unsupported. [Spec 84](../specs/active/84-certified-symmetry-backends.md) adds a separately selected HASHED/ORDERED library storage choice under post-task-#10 B6. B10 [declarative JSON spec set](declarative-symmetry-contract.md) is selected: Specs 92/93 merged in PR #135; L1 exact support merged in PR #136 at `013c963`; L2 approximate support merged in PR #137 at `aebb919`, completing B10. All selected post-task-#10 follow-ups are complete. #12 is subsequently selected separately; #11 and deferred/conditional work remain parked. | | 11 | Relaxed memory models | Very High | Spec-set | Fundamental semantics change — needs formal spec | Stage one selected memory model: state/transition foundations; complete execution and witness support; supported search/reduction integration. Keep each additional memory model separate. Exact PR count follows the semantics/proof scope. | -| 12 | Bounded Java bytecode checking — selected, initial public release | Very High | Spec-set | Controlled JDK 26 Class-File API interpretation of fixed actors under bounded SC; no target host execution. | [Shared contract and Specs 94A–101](bytecode-contract.md): internal foundation (94A), concurrent feasibility gate (94B), complete public release (94C), then heap, exceptions, core library, CBS, restricted DPOR, narrow atomics and bitstate. 94A adds internal loading/single-actor execution; [foundation evidence](../measurements/94A-bytecode-foundation.md). 94B adds internal concurrent exact DFS, checks and measured batching; [concurrency evidence](../measurements/94B-bytecode-concurrency.md). 94C adds public BYTECODE loading, strict replay, CLI, reports and viewer; [release evidence](../measurements/94C-bytecode-release.md). Target ten sequential implementation PRs; broader heap, DPOR measurements and JPF acceptance remain pending. | +| 12 | Bounded Java bytecode checking — selected, initial public release | Very High | Spec-set | Controlled JDK 26 Class-File API interpretation of fixed actors under bounded SC; no target host execution. | [Shared contract and Specs 94A–101](bytecode-contract.md): internal foundation (94A), concurrent feasibility gate (94B), complete public release (94C), then heap, exceptions, core library, CBS, restricted DPOR, narrow atomics and bitstate. 94A adds internal loading/single-actor execution; [foundation evidence](../measurements/94A-bytecode-foundation.md). 94B adds internal concurrent exact DFS, checks and measured batching; [concurrency evidence](../measurements/94B-bytecode-concurrency.md). 94C adds public BYTECODE loading, strict replay, CLI, reports and viewer; [release evidence](../measurements/94C-bytecode-release.md). Target ten sequential implementation PRs; 95 broader heap is implemented and locally verified, with draft PR/CI/manual acceptance pending in its [ledger](../measurements/95-bytecode-heap.md). DPOR measurements and JPF acceptance remain future gates. | ## Deferred @@ -211,4 +211,4 @@ actors under bounded SC. 94A provides internal loading/single-actor interpretati [foundation ledger](../measurements/94A-bytecode-foundation.md) records its evidence. 94B adds internal concurrent exact DFS, pure checks and measured reference/batched execution; the [concurrency ledger](../measurements/94B-bytecode-concurrency.md) records its evidence. 94C adds the initial public release through strict replay and consumers; -[release ledger](../measurements/94C-bytecode-release.md). Broader heap, optimized reduction and JPF acceptance remain pending. +[release ledger](../measurements/94C-bytecode-release.md). 95 broader heap is implemented and locally verified, with draft PR/CI/manual acceptance pending in the [heap ledger](../measurements/95-bytecode-heap.md). Optimized reduction and JPF acceptance remain future gates. diff --git a/docs/specs/active/94C-bytecode-release.md b/docs/specs/active/94C-bytecode-release.md index 1bdf543..7ce0c60 100644 --- a/docs/specs/active/94C-bytecode-release.md +++ b/docs/specs/active/94C-bytecode-release.md @@ -4,7 +4,7 @@ ## Objective Deliver initial public bytecode release as one coherent stage of bounded Java bytecode checking. -**Type: delta. Status: local acceptance complete; release gates recorded in the [94C ledger](../../measurements/94C-bytecode-release.md).** The +**Type: delta. Status: merged in PR141 at5385a3c; release gates recorded in the [94C ledger](../../measurements/94C-bytecode-release.md).** The [shared #12 contract](../../plans/bytecode-contract.md) is normative for common semantics, limits, interface signatures, profile exclusions, phase ownership and verification. This spec owns 94C only. diff --git a/docs/specs/active/95-bytecode-heap.md b/docs/specs/active/95-bytecode-heap.md index cce1c69..6ce728f 100644 --- a/docs/specs/active/95-bytecode-heap.md +++ b/docs/specs/active/95-bytecode-heap.md @@ -1,10 +1,11 @@ - + # Spec 95: Objects, arrays and dispatch ## Objective Deliver objects, arrays and dispatch as one coherent stage of bounded Java bytecode checking. -**Type: delta. Status: specified, not implemented or measured.** The +**Type: delta. Status: implemented and locally verified; draft PR/CI/manual acceptance pending.** +Actual evidence and release limitations are recorded in the [95 ledger](../../measurements/95-bytecode-heap.md). The [shared #12 contract](../../plans/bytecode-contract.md) is normative for common semantics, limits, interface signatures, profile exclusions, phase ownership and verification. This spec owns 95 only. @@ -50,7 +51,7 @@ the shared failure priority, preserving prior committed instructions and explici allocation effects when a later component hits a budget. No GC/renumbering SHALL occur. 5. **R5 — Complete extension.** WHEN this broader profile is selected, THE SYSTEM SHALL extend strict replay/evidence/consumers and the two-mode preservation argument with dynamic allocation, dispatch and -publication cases. New dynamic VM faults SHALL follow initial unwind/uncaught semantics; user catch remains rejected. +publication cases. New dynamic VM faults SHALL follow initial unwind/uncaught semantics, including the JVM's dynamic IncompatibleClassChangeError for an incompatible interface receiver; user catch remains rejected. ## Failure Modes & Edge Cases @@ -104,8 +105,7 @@ choose existing equivalent modules at implementation after connected-source insp - [verified] Planning main is `2a242c4`; the existing engine has immutable Program, forward SourceStep continuations and source-specific evidence. The shared contract records inspected integration constraints. - [approved decision] This milestone and the shared contract define the selected behavior/release boundary. -- [unverified] This milestone's bytecode implementation, measurements, compiler/runtime acceptance and -mutation results. No authoring review establishes those results. +- [implementation] The heap profile is implemented; its ledger records final local checks, fresh mutation comparisons, measurements and completed reviews. Authoring review never establishes runtime acceptance. ## Tests @@ -113,7 +113,7 @@ mutation results. No authoring review establishes those results. `transitivePublicationPrecedesVisibleEscape` (R3), `escapeRetainsAllocatorCharges` (R4), `reversedAllocationsKeepNamespacedIdentity` (R4), `heapProfileReplaysAcrossConsumers` (R5). Kill omitted inherited cells, actor-global allocation sequence, reversible sharing and alias-copy errors. -These are intended behavioral contracts/test names, not tests already implemented or executed. +These names describe the acceptance contracts. The implementation ledger maps them to actual tests and records executed evidence. Use independent expected values/oracles, preserve distinct regression cases and save generated seeds. ## Constraints @@ -142,6 +142,6 @@ publication; record completed/quota/error status through agent-setup without inv - 94B/95/96/97: review the batching preservation argument for every newly admitted behavior; 99/100/101: review reduction admission/resource/product obligations in addition to runtime tests. -The specification-only PR runs document/link/structure validation, reader review and required actual -CodeRabbit invocations. It does not run Java/PIT/browser feature checks for code that does not exist. +The historical specification-only PR ran document/link/structure validation, reader review and required actual +CodeRabbit invocations. Implementation now requires the Java/PIT/browser gates above and its own actual review. After publishing this milestone's implementation PR, report its link and stop; do not watch CI. diff --git a/docs/visualizer-e2e.mjs b/docs/visualizer-e2e.mjs index ed9ab8f..783ab44 100644 --- a/docs/visualizer-e2e.mjs +++ b/docs/visualizer-e2e.mjs @@ -207,19 +207,21 @@ async function runTests() { assert(verdictIncomplete === 'INCOMPLETE', 'incomplete-only renders INCOMPLETE verdict'); if(process.env.BYTECODE_DIR){ - for(const [name,verdict] of Object.entries({'lost-update':'VIOLATION',deadlock:'VIOLATION',fault:'VIOLATION',root:'VIOLATION',cutoff:'INCOMPLETE',observer:'INCOMPLETE','no-line':'PASS','long-label':'PASS',interrupted:'INCOMPLETE',report:'VIOLATION',cli:'VIOLATION'})){ + for(const [name,verdict] of Object.entries({'lost-update':'VIOLATION',deadlock:'VIOLATION',fault:'VIOLATION',root:'VIOLATION',cutoff:'INCOMPLETE',observer:'INCOMPLETE','no-line':'PASS','long-label':'PASS',heap:'PASS','array-fault':'VIOLATION',interrupted:'INCOMPLETE',report:'VIOLATION',cli:'VIOLATION'})){ const payload=readFileSync(resolve(projectRoot,process.env.BYTECODE_DIR,`bytecode-${name}.json`),'utf8'); await page.locator('#clearBtn').click();await page.locator('#paste').fill(payload);await page.locator('#loadPaste').click(); assert(!(await page.locator('#error').getAttribute('class')).includes('show'),`${name}: fresh BYTECODE payload accepted`); assert(await page.locator('#verdictBadge').textContent()===verdict,`${name}: BYTECODE retains ${verdict}`); const meta=await page.locator('#meta').textContent(); - assert(meta.includes('BYTECODE BYTECODE-SC-1') && meta.includes('artifact'),`${name}: artifact profile rendered`); + assert(meta.includes('BYTECODE BYTECODE-SC-2') && meta.includes('artifact'),`${name}: artifact profile rendered`); if(name==='deadlock'){ assert(meta.includes('monitor wait') && meta.includes('waits for'), 'Concrete deadlock ownership rendered'); assert((await page.locator('#stateStrip').textContent()).includes('owner actor 0; depth 1'),'Selected deadlock snapshot shows held monitor depth'); await page.locator('#timeline tbody tr[data-idx="0"]').click(); assert(!(await page.locator('#stateStrip').textContent()).includes('owner actor '),'Initial configuration shows unowned monitors'); } + if(name==='heap')assert((await page.locator('#stateStrip').textContent()).includes('actor:0:0') && (await page.locator('#stateStrip').textContent()).includes('[0]'),'Heap aliases and array cells rendered'); + if(name==='array-fault')assert(meta.includes('ArrayStoreException') && (await page.locator('#stateStrip').textContent()).includes('double_bits'),'Dynamic array fault and lossless wide defaults rendered'); if(name==='fault')assert(meta.includes('ArithmeticException') && meta.includes('BCI'), 'Modeled fault location rendered'); if(name==='cutoff')assert(meta.includes('required') && meta.includes('remaining'), 'Exact cutoff allowance rendered'); if(name==='interrupted')assert(meta.includes('original run INCOMPLETE'),'External stop remains incomplete'); diff --git a/docs/visualizer-normalize-check.mjs b/docs/visualizer-normalize-check.mjs index 8366761..df368c5 100644 --- a/docs/visualizer-normalize-check.mjs +++ b/docs/visualizer-normalize-check.mjs @@ -250,13 +250,15 @@ assert.equal(normalize({...resource,replay:{...replay,states:[replay.states[0],{ // Fresh BYTECODE producers preserve run precision and distinct instruction locations. if(process.env.BYTECODE_DIR){ assert.equal(read(resolve(root,process.env.BYTECODE_DIR,'bytecode-lost-update.json')),read(process.env.BYTECODE_DIR+'/bytecode-lost-update.json'),'Configured relative and absolute BYTECODE directories identify the same artifact'); - const expected={'lost-update':'VIOLATION',deadlock:'VIOLATION',fault:'VIOLATION',root:'VIOLATION',cutoff:'INCOMPLETE',observer:'INCOMPLETE','no-line':'PASS','long-label':'PASS',interrupted:'INCOMPLETE',report:'VIOLATION',cli:'VIOLATION'}; + const expected={'lost-update':'VIOLATION',deadlock:'VIOLATION',fault:'VIOLATION',root:'VIOLATION',cutoff:'INCOMPLETE',observer:'INCOMPLETE','no-line':'PASS','long-label':'PASS',heap:'PASS','array-fault':'VIOLATION',interrupted:'INCOMPLETE',report:'VIOLATION',cli:'VIOLATION'}; for(const [name,verdict] of Object.entries(expected)){ const raw=JSON.parse(read(process.env.BYTECODE_DIR+'/bytecode-'+name+'.json')); const value=normalize(raw);assert.equal(value.meta.verdict,verdict,name); assert.equal(value.meta.programKind,'BYTECODE');assert(value.trace.bytecodeEvidence); assert.equal(value.trace.executedSteps,undefined);assert.equal(value.trace.sourceDigest,undefined); if(name==='no-line')assert(value.trace.bytecodeEvidence.transitions.every(t=>t.operations.every(op=>op.line==null))); + if(name==='heap')assert(value.trace.bytecodeEvidence.snapshots.at(-1).fields['actor:0:0[0]'].raw==='actor:0:0'); + if(name==='array-fault')assert.equal(value.trace.bytecodeEvidence.terminal.fault.type,'java/lang/ArrayStoreException'); if(name==='deadlock')assert.equal(value.trace.bytecodeEvidence.terminal.waits.length,2); } const report=JSON.parse(read(process.env.BYTECODE_DIR+'/bytecode-report.json')); @@ -264,6 +266,22 @@ if(process.env.BYTECODE_DIR){ assert.equal(normalize({benchmarks:[{bug:'legacy',verdict:'PASS'},bytecodeRow]}).meta.programKind,'BYTECODE'); assert.equal(normalize({benchmarks:[{bug:'legacy',verdict:'VIOLATION',failingTrace:{threads:[0],outcomes:['ADVANCED']}},bytecodeRow]}).meta.bug,'legacy'); const raw=JSON.parse(read(process.env.BYTECODE_DIR+'/bytecode-lost-update.json')); + // Two int[9][4096] actor allocations cost 36,883 cells each; both fit 40,000. + // 73,728 element entries already exceed the former per-map cap of65,536. + const large=structuredClone(raw.failingTraces[0]);const largeTrace=large; + largeTrace.bytecodeEvidence.identity.limits.actorHeapCells=40000; + largeTrace.bytecodeEvidence.identity.limits.maxArrayLength=4096; + const fields=Object.fromEntries(Array.from({length:73728},(_,i)=>[`cell${i}`,{type:'INT',raw:'0'}])); + const display=Object.fromEntries(Object.keys(fields).map(k=>[k,'int:0'])); + largeTrace.bytecodeEvidence.snapshots.forEach((snapshot,i)=>{snapshot.fields=fields;largeTrace.states[i].fields=display;}); + assert.doesNotThrow(()=>normalize(large),'In-budget aggregate heap above65536 fields'); + // Selected setup8192 + two actors40000 + nine setup diagnostics =88,201. + const excessive=structuredClone(large); + const over=Object.fromEntries(Array.from({length:88202},(_,i)=>[`cell${i}`,{type:'INT',raw:'0'}])); + excessive.bytecodeEvidence.snapshots[0].fields=over; + excessive.states[0].fields=Object.fromEntries(Object.keys(over).map(k=>[k,'int:0'])); + assert.throws(()=>normalize(excessive),'Reject snapshot above aggregate bound'); + for(const change of [x=>x.storeType='BITSTATE',x=>x.verdict='PASS',x=>x.failingTraces[0].sourceDigest='0'.repeat(64), x=>x.failingTraces[0].bytecodeEvidence.version=2,x=>x.failingTraces[0].bytecodeEvidence.identity.mode='REFERENCE', x=>x.failingTraces[0].bytecodeEvidence.snapshots[0].fields['bad']={type:'LONG',raw:9007199254740992}]){ diff --git a/docs/visualizer.js b/docs/visualizer.js index 47955ae..8178c5c 100644 --- a/docs/visualizer.js +++ b/docs/visualizer.js @@ -198,7 +198,7 @@ function normalizeBytecode(raw){ const method = x => object(x) && ['owner','name','descriptor'].every(k=>text(x[k])); const location = x => method(x) && integer(x.bci); const identity = x => { - if(!object(x) || !digest(x.artifactDigest) || x.profileVersion!=='BYTECODE-SC-1' || !text(x.modelClass) || x.mode!=='BATCHED' || + if(!object(x) || !digest(x.artifactDigest) || !['BYTECODE-SC-1','BYTECODE-SC-2'].includes(x.profileVersion) || !text(x.modelClass) || x.mode!=='BATCHED' || x.requestedStrategy!=='DFS' || x.effectiveStrategy!=='DFS' || x.fallbackReason!=null || !Array.isArray(x.actors) || x.actors.length<1 || x.actors.length>8 || !Array.isArray(x.checks) || x.checks.length>65536) fail(); x.actors.forEach((a,i)=>{if(!object(a) || a.id!==i || !method(a.method) || a.method.descriptor!=='()V')fail();}); @@ -229,7 +229,7 @@ function normalizeBytecode(raw){ if((t.interruption!=null)!==(t.kind==='INTERRUPTED') || (t.interruption!=null && !['MAX_STATES','MAX_TIME','KEY_BYTES','CANCELLED'].includes(t.interruption)))fail(); return outcomes[t.kind]; }; - const opcodes=new Set('NOP POP POP2 DUP DUP_X1 DUP_X2 DUP2 DUP2_X1 DUP2_X2 SWAP IADD ISUB IMUL IDIV IREM INEG ISHL ISHR IUSHR IAND IOR IXOR I2B I2C I2S MONITORENTER MONITOREXIT ATHROW IFEQ IFNE IFLT IFGE IFGT IFLE IF_ICMPEQ IF_ICMPNE IF_ICMPLT IF_ICMPGE IF_ICMPGT IF_ICMPLE IF_ACMPEQ IF_ACMPNE IFNULL IFNONNULL GOTO GOTO_W ACONST_NULL ICONST_M1 ICONST_0 ICONST_1 ICONST_2 ICONST_3 ICONST_4 ICONST_5 BIPUSH SIPUSH LDC LDC_W ILOAD ALOAD ISTORE ASTORE ILOAD_W ALOAD_W ISTORE_W ASTORE_W IINC IINC_W IRETURN ARETURN RETURN LOOKUPSWITCH TABLESWITCH GETFIELD PUTFIELD GETSTATIC PUTSTATIC INVOKESTATIC INVOKESPECIAL INVOKEVIRTUAL INVOKEINTERFACE NEW'.split(' ')); + const opcodes=new Set('NOP POP POP2 DUP DUP_X1 DUP_X2 DUP2 DUP2_X1 DUP2_X2 SWAP IADD ISUB IMUL IDIV IREM INEG ISHL ISHR IUSHR IAND IOR IXOR I2B I2C I2S MONITORENTER MONITOREXIT ATHROW IFEQ IFNE IFLT IFGE IFGT IFLE IF_ICMPEQ IF_ICMPNE IF_ICMPLT IF_ICMPGE IF_ICMPGT IF_ICMPLE IF_ACMPEQ IF_ACMPNE IFNULL IFNONNULL GOTO GOTO_W ACONST_NULL ICONST_M1 ICONST_0 ICONST_1 ICONST_2 ICONST_3 ICONST_4 ICONST_5 BIPUSH SIPUSH LDC LDC_W ILOAD ALOAD ISTORE ASTORE ILOAD_W ALOAD_W ISTORE_W ASTORE_W IINC IINC_W IRETURN ARETURN RETURN LOOKUPSWITCH TABLESWITCH GETFIELD PUTFIELD GETSTATIC PUTSTATIC INVOKESTATIC INVOKESPECIAL INVOKEVIRTUAL INVOKEINTERFACE NEW NEWARRAY ANEWARRAY MULTIANEWARRAY ARRAYLENGTH IALOAD BALOAD CALOAD SALOAD AALOAD IASTORE BASTORE CASTORE SASTORE AASTORE CHECKCAST INSTANCEOF'.split(' ')); for(const prefix of ['ILOAD','ALOAD','ISTORE','ASTORE'])for(let i=0;i<4;i++)opcodes.add(prefix+'_'+i); const typed = v => { if(!object(v) || typeof v.raw!=='string' || v.raw.length>65536)fail(); @@ -244,7 +244,7 @@ function normalizeBytecode(raw){ default: fail(); } }; - const values = map => {if(!object(map) || Object.keys(map).length>65536)fail();Object.entries(map).forEach(([k,v])=>{if(!text(k))fail();typed(v);});}; + const values = (map,limit=65536) => {if(!object(map) || Object.keys(map).length>limit)fail();Object.entries(map).forEach(([k,v])=>{if(!text(k))fail();typed(v);});}; const trace = t => { if(!object(t) || t.programKind!=='BYTECODE' || ['sourceDigest','executedSteps','failure','cutoff'].some(k=>Object.hasOwn(t,k)))fail(); const d=t.bytecodeEvidence; @@ -257,9 +257,13 @@ function normalizeBytecode(raw){ if(!object(s) || s.actor!==t.threads[i] || !Array.isArray(s.operations) || !s.operations.length || (work+=s.operations.length)>65536)fail(); s.operations.forEach(op=>{if(!object(op) || !location(op.location) || (op.line!=null && (!integer(op.line) || op.line<1)) || !['OPCODE','MONITOR_ENTER','RETURN','EXCEPTION','TERMINATION','FAILURE','CUTOFF','FUEL_CUTOFF'].includes(op.event) || (op.opcode!=null)!==(op.event==='OPCODE') || (op.opcode!=null && !opcodes.has(op.opcode)))fail();}); }); + // Each object/array header pays for its length slot; setup has at most nine diagnostics + // after construction completes. Every actor permanently owns its heap-cell charges. + const limits=d.identity.limits; + const fieldLimit=limits.setupHeapCells+d.identity.actors.length*limits.actorHeapCells+9; d.snapshots.forEach((s,i)=>{ if(!object(s) || !digest(s.stateDigest) || !object(s.locals) || Object.keys(s.locals).length>8 || !Array.isArray(s.heap) || s.heap.length>36864)fail(); - values(s.fields);Object.values(s.locals).forEach(values); + values(s.fields,fieldLimit);Object.values(s.locals).forEach(map=>values(map)); s.heap.forEach(o=>{if(!object(o) || !text(o.identity) || !text(o.type) || typeof o.shared!=='boolean' || typeof o.initialized!=='boolean' || !Number.isSafeInteger(o.owner) || o.owner<-2 || o.owner>7 || !integer(o.depth) || (o.owner===-2)!==(o.depth===0))fail();}); const display = map => Object.fromEntries(Object.entries(map).map(([k,v])=>[k,v.type.toLowerCase()+':'+v.raw])); if(!equal(t.states[i],{fields:display(s.fields),locals:Object.fromEntries(Object.entries(s.locals).map(([a,v])=>[a,display(v)]))}))fail(); diff --git a/examples/bytecode/HeapPublication.java b/examples/bytecode/HeapPublication.java new file mode 100644 index 0000000..7b3a22b --- /dev/null +++ b/examples/bytecode/HeapPublication.java @@ -0,0 +1,38 @@ +/** Actor-created aliased arrays and application objects checked through closed interface dispatch. */ +package examples.bytecode; + +import dev.samhb.interleave.bytecode.Actor; +import dev.samhb.interleave.bytecode.Check; +import dev.samhb.interleave.bytecode.Model; + +/** A published graph retains the same object and array identities in evidence and replay. */ +@Model +public class HeapPublication { + /** Pure supported interface dispatch over the closed application hierarchy. */ + interface Read { + /** Reads the aliased payload. + * @return payload value */ + int read(); + } + /** An application object containing a reference cycle and aliased array. */ + static final class Node implements Read { + /** Aliased value storage. */ + int[] values; + /** Cycle retained by the published heap. */ + Node next; + /** Initializes interpreted application fields. */ + Node(){values=new int[1];values[0]=7;next=this;} + /** Reads a value through a preserved alias. + * @return first payload cell */ + public int read(){return next.values[0];} + } + /** Shared graph root. */ + Read published; + /** Public interpreted fixture constructor. */ + public HeapPublication(){} + /** Builds privately and publishes the entire cycle at one reference write. */ + @Actor(id=0) public void publish(){published=new Node();} + /** Observes fully initialized aliases after normal actor termination. + * @return whether the shared graph has the expected value */ + @Check public boolean valid(){return published.read()==7;} +} diff --git a/examples/bytecode/README.md b/examples/bytecode/README.md index 30a39b3..33a913c 100644 --- a/examples/bytecode/README.md +++ b/examples/bytecode/README.md @@ -31,10 +31,38 @@ line tables; replay remains based on exact artifact bytes and real BCIs. Use fixture-constructor fields for locks. A declaration such as `static final Object LOCK=new Object()` requires executable `` and rejects, as do ordinary static arrays, enum initialization and compiler-generated assertion-status setup. Use declared `@Check` methods instead of Java `assert`. -Arrays, actor allocations/general dispatch, user catch/finally, wider primitives/core libraries, +User catch/finally, wider primitive computation/core libraries, CBS/DPOR/bitstate and atomics belong to later selected phases. Weak memory remains unselected. Compiler-generated synchronized cleanup is supported; runtime null/division faults remain modeled behavior rather than loader errors. +The heap profile (`BYTECODE-SC-2`) also interprets actor-created application objects, inherited/hidden +fields, constructor chaining, closed virtual/interface dispatch and private nest access. Arrays retain +exact rank/component types, reference aliases and per-dimension allocation charges; int/boolean/byte/ +char/short array operations are supported. Long/float/double arrays may be allocated with zero defaults; +their element load/store/computation opcodes remain rejected until97. Array cloning remains in97. +Null, bounds, negative-size, array-store and cast faults are modeled, including monitor cleanup. + +`HeapPublication.java` demonstrates a published cycle with an aliased array and interface check: + +```sh +javac --release 17 -g -cp build/libs/interleave-1.0-SNAPSHOT.jar -d build/bytecode-examples examples/bytecode/HeapPublication.java +./gradlew --max-workers=1 -PpitestThreads=1 run --args='--bytecode examples.bytecode.HeapPublication --class-path build/bytecode-examples --json' +``` + +Allocations are charged permanently to setup or the allocating actor, including after escape and loss +of reachability. Identities are namespace plus sequence and are never renumbered/reused. A failed +multidimensional allocation retains earlier successful dimensions in cutoff evidence. No actor is +frozen after exhaustion: that entire prefix ends and sibling alternatives continue. Each object costs +one header cell plus inherited instance fields; each array costs one header plus length elements. +Unknown reachability is shared; sharing is irreversible within a run. This implementation conservatively +keeps all field/array accesses and allocations as scheduling boundaries, including local heap accesses. +Local arithmetic/transport still batches; REFERENCE and BATCHED use one executor. + +Profile identity changed because the admitted language and canonical state changed. Old SC-1 evidence +is rejected by this SC-2 loader/replayer rather than silently reinterpreted; source/JSON model behavior +and existing wire shapes remain unchanged. [The95 ledger](../../docs/measurements/95-bytecode-heap.md) +records this profile's actual acceptance and measurements. + [The shared contract](../../docs/plans/bytecode-contract.md) defines the complete supported profile. The [94B ledger](../../docs/measurements/94B-bytecode-concurrency.md) contains real reference/batched measurements and the preservation argument. These examples establish no Java Memory Model coverage. diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeAccessVerifier.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeAccessVerifier.java new file mode 100644 index 0000000..c97e841 --- /dev/null +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeAccessVerifier.java @@ -0,0 +1,136 @@ +/** Additional cross-package protected-receiver checks over JDK-verified category-one bytecode. */ +package dev.samhb.interleave.bytecode; + +import java.lang.classfile.*; +import java.lang.classfile.attribute.*; +import java.lang.classfile.instruction.*; +import java.util.*; +import static java.lang.classfile.ClassFile.*; +import static dev.samhb.interleave.bytecode.BytecodeLoader.problem; + +/** Uses verified expanded stack-map frames; no target reflection or alternate runtime executor. */ +final class BytecodeAccessVerifier { + /** Explicit verifier null type, assignable to every reference class. */ + private static final String NULL=""; + /** Prevents construction of this stateless access check. */ + private BytecodeAccessVerifier() {} + + /** Checks protected receiver types after the full JDK operand/control-flow verifier succeeds. + * Branch/handler entries use the verified expanded stack maps; straight-line transport tracks + * static reference types only. This supplements member visibility, which the hierarchy-only + * Class-File verifier cannot derive from field/method declarations. + * @param method decoded admitted method + * @param hierarchy frozen declarations + * @param fields resolved field declarations + * @throws BytecodeLoadException with LINKAGE for a non-null cross-package protected instance + * receiver whose verified type is not assignable to the caller class */ + static void validate(BytecodeMethod method,BytecodeHierarchy hierarchy,Map fields) { + var frames=new HashMap(); + method.code.findAttribute(Attributes.stackMapTable()).ifPresent(table->table.entries().forEach(frame->frames.put(method.target(frame.target()),frame))); + var locals=new HashMap();var stack=new ArrayList();int slot=0; + if((method.flags & ACC_STATIC)==0)locals.put(slot++,method.id.owner()); + for(var parameter:java.lang.constant.MethodTypeDesc.ofDescriptor(method.id.descriptor()).parameterList())locals.put(slot++,type(parameter.descriptorString())); + boolean active=true; + for(var op:method.ops.values()) { + var seed=frames.get(op.bci()); + if(seed!=null) { + locals.clear();stack.clear();int index=0; + for(var local:seed.locals())locals.put(index++,verificationType(local,method)); + for(var operand:seed.stack())stack.add(verificationType(operand,method));active=true; + } + if(!active)continue; + Instruction instruction=op.instruction();Opcode code=instruction.opcode(); + if(instruction instanceof FieldInstruction field) { + var id=hierarchy.field(new BytecodeProgram.FieldId(field.owner().asInternalName(),field.name().stringValue(),field.type().stringValue())); + boolean write=code==Opcode.PUTFIELD || code==Opcode.PUTSTATIC; + if(code==Opcode.GETFIELD || code==Opcode.PUTFIELD)receiver(method,op,hierarchy,id.owner(),fields.get(id).flags(),stack.get(stack.size()-(write ? 2 : 1))); + if(write)pop(stack);if(code==Opcode.GETFIELD || code==Opcode.PUTFIELD)pop(stack); + if(!write)stack.add(type(field.type().stringValue()));continue; + } + if(instruction instanceof InvokeInstruction call) { + int parameters=call.typeSymbol().parameterCount();boolean isStatic=code==Opcode.INVOKESTATIC; + if(!isStatic && !call.owner().asInternalName().equals("java/lang/Object")) { + var id=hierarchy.method(call.owner().asInternalName(),call.name().stringValue(),call.type().stringValue()); + receiver(method,op,hierarchy,id.owner(),hierarchy.flags(id),stack.get(stack.size()-parameters-1)); + } + for(int i=0;i { } + case MONITORENTER,MONITOREXIT,POP -> pop(stack); + case POP2 -> {pop(stack);pop(stack);} + case ARRAYLENGTH -> {pop(stack);stack.add("I");} + case DUP -> {String a=pop(stack);push(stack,a,a);} + case DUP_X1 -> {String a=pop(stack),b=pop(stack);push(stack,a,b,a);} + case DUP_X2 -> {String a=pop(stack),b=pop(stack),c=pop(stack);push(stack,a,c,b,a);} + case DUP2 -> {String a=pop(stack),b=pop(stack);push(stack,b,a,b,a);} + case DUP2_X1 -> {String a=pop(stack),b=pop(stack),c=pop(stack);push(stack,b,a,c,b,a);} + case DUP2_X2 -> {String a=pop(stack),b=pop(stack),c=pop(stack),d=pop(stack);push(stack,b,a,d,c,b,a);} + case SWAP -> {String a=pop(stack),b=pop(stack);push(stack,a,b);} + case INEG,I2B,I2C,I2S -> { } + default -> {pop(stack);pop(stack);stack.add("I");} + } + } + } + + /** Enforces JVMS protected instance receiver constraints outside the declaring package. + * @param method caller + * @param op actual reference instruction + * @param hierarchy closed type relation + * @param owner declaring class + * @param flags member flags + * @param receiver verified static receiver type + * @throws BytecodeLoadException with LINKAGE for a non-null cross-package protected instance + * receiver not assignable to the caller class; this is an admission failure, not stack analysis */ + private static void receiver(BytecodeMethod method,BytecodeMethod.Op op,BytecodeHierarchy hierarchy,String owner,int flags,String receiver) { + String caller=method.id.owner(); + if((flags & ACC_PROTECTED)!=0 && !packageName(caller).equals(packageName(owner)) && !NULL.equals(receiver) + && !hierarchy.assignable(receiver,caller))throw problem("LINKAGE","Protected receiver must be current class or subtype",method.location(op.bci())); + } + + /** Resolves a verified expanded stack-map item, including uninitialized allocation references. + * @param info verified type item + * @param method owning method + * @return static type token */ + private static String verificationType(StackMapFrameInfo.VerificationTypeInfo info,BytecodeMethod method) { + if(info instanceof StackMapFrameInfo.ObjectVerificationTypeInfo object)return object.className().asInternalName(); + if(info instanceof StackMapFrameInfo.UninitializedVerificationTypeInfo uninitialized) + return ((NewObjectInstruction)method.ops.get(method.target(uninitialized.newTarget())).instruction()).className().asInternalName(); + return switch(info.tag()) {case 5->NULL;case 6->method.id.owner();default->"I";}; + } + + /** Converts one declared JVM type to a static access-analysis token. + * @param descriptor field/argument/result descriptor + * @return int or reference type */ + private static String type(String descriptor){return descriptor.startsWith("[") ? descriptor : descriptor.startsWith("L") ? BytecodeHierarchy.referenceType(descriptor) : "I";} + /** Pops a verifier-proven category-one type. + * @param stack type stack + * @return top type */ + private static String pop(ArrayList stack){return stack.removeLast();} + /** Appends type tokens in bottom-to-top order. + * @param stack type stack + * @param types ordered type tokens */ + private static void push(ArrayList stack,String...types){Collections.addAll(stack,types);} + /** Extracts the internal package of an application class. + * @param name internal name + * @return package prefix */ + private static String packageName(String name){int slash=name.lastIndexOf('/');return slash<0 ? "" : name.substring(0,slash);} +} diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeArrays.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeArrays.java new file mode 100644 index 0000000..18c98a2 --- /dev/null +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeArrays.java @@ -0,0 +1,103 @@ +/** Array construction/access and reference type checks, sharing the single interpreted opcode executor. */ +package dev.samhb.interleave.bytecode; + +import java.lang.classfile.Instruction; +import java.lang.classfile.Opcode; +import java.lang.classfile.instruction.*; +import java.util.*; +import static dev.samhb.interleave.bytecode.BytecodeState.*; +import static dev.samhb.interleave.bytecode.OpcodeExecutor.*; + +/** Keeps array semantics and permanent dimension accounting in one owned implementation. */ +final class BytecodeArrays { + /** Prevents construction of this stateless opcode family. */ + private BytecodeArrays() {} + + /** Identifies instructions whose complete semantics belong to this family. + * @param instruction validated opcode + * @return array operation or reference type check */ + static boolean handles(Instruction instruction) { + return instruction instanceof NewPrimitiveArrayInstruction || instruction instanceof NewReferenceArrayInstruction + || instruction instanceof NewMultiArrayInstruction || instruction instanceof ArrayLoadInstruction + || instruction instanceof ArrayStoreInstruction || instruction instanceof TypeCheckInstruction || instruction.opcode()==Opcode.ARRAYLENGTH; + } + + /** Executes one fueled opcode, preserving allocated dimensions when a later charge fails. + * @param program validated program + * @param state owned scratch + * @param execution charged execution + * @param frame selected operands and continuation + * @param instruction validated operation + * @param owner setup or actor allocator + * @return whether the instruction completed normally */ + static boolean execute(BytecodeProgram program,BytecodeState state,Execution execution,BytecodeFrame frame,Instruction instruction,int owner) { + if(instruction instanceof TypeCheckInstruction check) { + Ref reference=(Ref)frame.pop();boolean matches=!reference.equals(NULL) + && program.hierarchy.assignable(object(state,reference).type,check.type().asInternalName()); + if(check.opcode()==Opcode.INSTANCEOF)frame.push(new Int(matches ? 1 : 0)); + else {if(!reference.equals(NULL) && !matches)throw new Trap("java/lang/ClassCastException",null);frame.push(reference);} + return true; + } + if(instruction instanceof NewPrimitiveArrayInstruction || instruction instanceof NewReferenceArrayInstruction || instruction instanceof NewMultiArrayInstruction) { + String type=switch(instruction) { + case NewPrimitiveArrayInstruction array -> "["+switch(array.typeKind()) { + case BOOLEAN->"Z";case BYTE->"B";case CHAR->"C";case SHORT->"S";case INT->"I";case LONG->"J";case FLOAT->"F";case DOUBLE->"D"; + default->throw new IllegalStateException("Unvalidated primitive component"); + }; + case NewReferenceArrayInstruction array -> "["+array.componentType().asSymbol().descriptorString(); + case NewMultiArrayInstruction array -> array.arrayType().asSymbol().descriptorString(); + default -> throw new IllegalStateException("Unvalidated allocation"); + }; + int dimensions=instruction instanceof NewMultiArrayInstruction array ? array.dimensions() : 1; + int[] lengths=new int[dimensions];for(int i=dimensions-1;i>=0;i--)lengths[i]=((Int)frame.pop()).value(); + for(int length:lengths)if(length<0)throw new Trap("java/lang/NegativeArraySizeException",null); + Ref reference=allocate(program,state,execution,frame,owner,type,lengths,0); + if(reference==null)return false;frame.push(reference);return true; + } + if(instruction.opcode()==Opcode.ARRAYLENGTH) {frame.push(new Int(object(state,(Ref)frame.pop()).elements.size()));return true;} + Value value=instruction instanceof ArrayStoreInstruction ? frame.pop() : null; + int index=((Int)frame.pop()).value();var array=object(state,(Ref)frame.pop()); + if(index<0 || index>=array.elements.size())throw new Trap("java/lang/ArrayIndexOutOfBoundsException",null); + if(instruction instanceof ArrayLoadInstruction) {frame.push(array.elements.get(index));return true;} + if(instruction.opcode()==Opcode.AASTORE) { + Ref reference=(Ref)value; + if(!reference.equals(NULL) && !program.hierarchy.assignable(object(state,reference).type,BytecodeHierarchy.referenceType(array.type.substring(1)))) + throw new Trap("java/lang/ArrayStoreException",null); + } else { + int integer=((Int)value).value();value=new Int(switch(array.type) { + case "[Z"->integer & 1;case "[B"->(byte)integer;case "[C"->(char)integer;case "[S"->(short)integer;default->integer; + }); + } + array.elements.set(index,value);return true; + } + + /** Allocates dimensions in deterministic depth-first JVM order; failed children never obtain identities. + * @param program immutable limits + * @param state owned heap + * @param execution permanent allocator history + * @param frame omitted operation location + * @param owner allocation namespace + * @param type exact current array descriptor + * @param lengths validated nonnegative sizes + * @param depth current dimension + * @return allocated reference, or null after a prefix-ending resource cutoff */ + private static Ref allocate(BytecodeProgram program,BytecodeState state,Execution execution,BytecodeFrame frame,int owner,String type,int[] lengths,int depth) { + int length=lengths[depth]; + if(length>program.limits.maxArrayLength()) { + cutoff(execution,frame,"ARRAY_LENGTH",program.limits.maxArrayLength(),length,program.limits.maxArrayLength());return null; + } + if(!reserve(program,execution,frame,owner,1+length))return null; + var reference=new Ref(owner,execution.nextSequence++);var array=new ObjectValue(type);array.initialized=true;array.shared=owner==SETUP; + Value initial=switch(type.substring(1)) { + case "J"->new WideZero("LONG");case "F"->new WideZero("FLOAT");case "D"->new WideZero("DOUBLE"); + case "Z","B","C","S","I"->new Int(0);default->NULL; + }; + array.elements=new ArrayList<>(Collections.nCopies(length,initial));state.heap.put(reference,array); + execution.allocations++;execution.cells+=1+length; + if(depth+1 arguments) { this.method = method; + constructorReceiver=method.id.name().equals("") ? (BytecodeState.Ref)arguments.getFirst() : null; for (int i = 0; i < arguments.size(); i++) locals.put(i,arguments.get(i)); entered = (method.flags & java.lang.classfile.ClassFile.ACC_SYNCHRONIZED) == 0; } @@ -51,7 +54,7 @@ final class BytecodeFrame { */ private BytecodeFrame(BytecodeFrame original) { method = original.method; locals.putAll(original.locals); stack.addAll(original.stack); - bci = original.bci; entered = original.entered; methodMonitor = original.methodMonitor; + bci = original.bci; entered = original.entered; methodMonitor = original.methodMonitor;constructorReceiver=original.constructorReceiver; } /** diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeHierarchy.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeHierarchy.java new file mode 100644 index 0000000..cd0300e --- /dev/null +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeHierarchy.java @@ -0,0 +1,226 @@ +/** Frozen metadata-only member resolution and reference assignability for the closed heap profile. */ +package dev.samhb.interleave.bytecode; + +import java.lang.classfile.ClassModel; +import java.util.*; +import static java.lang.classfile.ClassFile.*; +import static dev.samhb.interleave.bytecode.BytecodeLoader.problem; + +/** Resolves application types without loading target classes or consulting the host classpath. */ +final class BytecodeHierarchy { + /** Frozen class declarations, including interfaces. */ + final Map types; + /** Complete field declarations. */ + private final Map fields; + + /** Freezes the closed metadata used by loading and execution. + * @param types application metadata + * @param fields complete field declarations */ + BytecodeHierarchy(Map types,Map fields) { + this.types=Map.copyOf(types);this.fields=Map.copyOf(fields); + } + + /** Returns the direct superclass, or null for the trusted Object root. + * @param type internal application name + * @return superclass internal name */ + String parent(String type) { + if(type.equals("java/lang/Object"))return null; + return metadata(type).superclass().map(c->c.asInternalName()).orElse(null); + } + + /** Requires explicit application metadata. + * @param type internal name + * @return frozen declaration + * @throws BytecodeLoadException with METADATA when the application type is absent */ + ClassModel metadata(String type) { + var value=types.get(type); + if(value==null)throw problem("METADATA","Unknown hierarchy type "+type,null); + return value; + } + + /** Tests JVM reference assignability, retaining exact array component/rank information. + * @param actual runtime internal name or array descriptor + * @param expected requested internal name or array descriptor + * @return whether the reference can inhabit the requested type */ + boolean assignable(String actual,String expected) { + if(actual.equals(expected) || expected.equals("java/lang/Object"))return true; + if(actual.startsWith("[")) { + if(expected.equals("java/lang/Cloneable") || expected.equals("java/io/Serializable"))return true; + if(!expected.startsWith("["))return false; + String a=actual.substring(1),b=expected.substring(1); + if(primitive(a) || primitive(b))return a.equals(b); + return assignable(referenceType(a),referenceType(b)); + } + if(expected.startsWith("[") || actual.equals("java/lang/Object"))return false; + return ancestors(actual).contains(expected); + } + + /** Returns whether a component descriptor denotes a primitive scalar. + * @param descriptor component descriptor + * @return primitive scalar */ + private static boolean primitive(String descriptor){return descriptor.length()==1;} + + /** Converts a reference descriptor to an internal name or preserves an array descriptor. + * @param descriptor reference descriptor + * @return runtime type name */ + static String referenceType(String descriptor) { + return descriptor.startsWith("[") ? descriptor : descriptor.substring(1,descriptor.length()-1); + } + + /** Collects supertypes iteratively, rejecting cycles separately during loading. + * @param type application name + * @return all reachable ancestors including self */ + Set ancestors(String type) { + var seen=new HashSet();var pending=new ArrayDeque();pending.add(type); + while(!pending.isEmpty()) { + String name=pending.removeFirst();if(!seen.add(name) || name.equals("java/lang/Object"))continue; + var declaration=metadata(name);declaration.superclass().ifPresent(c->pending.add(c.asInternalName())); + declaration.interfaces().forEach(c->pending.add(c.asInternalName())); + } + return seen; + } + + /** Resolves a symbolic field in JVM class/interface/superclass order. + * @param id symbolic field identity + * @return declaring field identity */ + BytecodeProgram.FieldId field(BytecodeProgram.FieldId id) { + return field(id,new HashSet<>()); + } + + /** Searches a bounded field hierarchy without recursive cycles. + * @param id current symbolic owner/name/descriptor + * @param seen visited owners + * @return declaring identity, or null for no declaration */ + private BytecodeProgram.FieldId field(BytecodeProgram.FieldId id,Set seen) { + if(!seen.add(id.owner()) || id.owner().equals("java/lang/Object"))return null; + if(fields.containsKey(id))return id; + var type=metadata(id.owner()); + for(var face:type.interfaces()) { + var found=field(new BytecodeProgram.FieldId(face.asInternalName(),id.name(),id.descriptor()),seen); + if(found!=null)return found; + } + String parent=parent(id.owner()); + return parent==null ? null : field(new BytecodeProgram.FieldId(parent,id.name(),id.descriptor()),seen); + } + + /** Finds a declared method's flags without admitting or executing its code. + * @param id complete declared identity + * @return flags or -1 if absent */ + int flags(BytecodeMethod.Id id) { + if(id.owner().equals("java/lang/Object"))return -1; + return metadata(id.owner()).methods().stream().filter(m->m.methodName().equalsString(id.name()) + && m.methodType().equalsString(id.descriptor())).mapToInt(m->m.flags().flagsMask()).findFirst().orElse(-1); + } + + /** Resolves class methods then maximally specific interface declarations. + * @param owner lookup class/interface + * @param name method name + * @param descriptor JVM method descriptor + * @return declaration or null when no method is declared or inherited + * @throws BytecodeLoadException with METADATA for absent type metadata or LINKAGE for a + * superclass cycle or conflicting maximally specific defaults */ + BytecodeMethod.Id method(String owner,String name,String descriptor) { + var seen=new HashSet(); + for(String next=owner;next!=null && !next.equals("java/lang/Object");next=parent(next)) { + if(!seen.add(next))throw problem("LINKAGE","Cyclic superclass hierarchy",null); + var id=new BytecodeMethod.Id(next,name,descriptor); + if(flags(id)>=0)return id; + if(name.equals(""))return null; + } + return interfaceMethod(owner,name,descriptor); + } + + /** Selects only maximally specific interface declarations, without restarting a class lookup. + * @param owner runtime class or interface + * @param name method name + * @param descriptor JVM descriptor + * @return default/abstract interface declaration, or null when none exists + * @throws BytecodeLoadException with METADATA for absent type metadata or LINKAGE for + * conflicting maximally specific defaults */ + private BytecodeMethod.Id interfaceMethod(String owner,String name,String descriptor) { + var candidates=new ArrayList(); + for(String next:ancestors(owner)) { + if(next.equals("java/lang/Object") || (metadata(next).flags().flagsMask() & ACC_INTERFACE)==0)continue; + var id=new BytecodeMethod.Id(next,name,descriptor);int flags=flags(id); + if(flags>=0 && (flags & (ACC_STATIC|ACC_PRIVATE))==0)candidates.add(id); + } + var maximal=candidates.stream().filter(a->candidates.stream().noneMatch(b->!a.equals(b) + && assignable(b.owner(),a.owner()))).toList(); + var defaults=maximal.stream().filter(a->(flags(a)&ACC_ABSTRACT)==0).toList(); + if(defaults.size()>1)throw problem("LINKAGE","Conflicting interface defaults "+defaults,null); + return defaults.isEmpty() ? maximal.stream().sorted(Comparator.comparing(BytecodeMethod.Id::owner)).findFirst().orElse(null) : defaults.getFirst(); + } + + /** Selects a virtual target only when a declaration overrides the resolved member. + * Package-private methods in another package cannot be captured by same-named child methods. + * @param actual runtime class + * @param resolved symbolic resolved declaration + * @return selected concrete or abstract declaration */ + BytecodeMethod.Id dispatch(String actual,BytecodeMethod.Id resolved) { + for(String type=actual;type!=null && !type.equals("java/lang/Object");type=parent(type)) { + var candidate=new BytecodeMethod.Id(type,resolved.name(),resolved.descriptor());int flags=flags(candidate); + if(flags>=0 && (flags & (ACC_PRIVATE|ACC_STATIC))==0 && overrides(candidate,resolved))return candidate; + } + return interfaceMethod(actual,resolved.name(),resolved.descriptor()); + } + + /** Tests overriding including transitive widening of package-private declarations. + * @param candidate descendant declaration + * @param base resolved ancestor declaration + * @return JVM overriding relationship */ + private boolean overrides(BytecodeMethod.Id candidate,BytecodeMethod.Id base) { + if(candidate.equals(base))return true; + int access=flags(base); + if((access & (ACC_PUBLIC|ACC_PROTECTED))!=0)return true; + // Each superclass is inspected once, from base to candidate. A declaration can widen + // an accessible package-private member; a same-named inaccessible member cannot do so. + var chain=new ArrayList(); + for(String type=candidate.owner();type!=null && !type.equals("java/lang/Object") && !type.equals(base.owner());type=parent(type))chain.add(type); + var inherited=new ArrayList();inherited.add(base); + for(String type:chain.reversed()) { + var declared=new BytecodeMethod.Id(type,base.name(),base.descriptor());int flags=flags(declared); + if(flags<0 || (flags & (ACC_STATIC|ACC_PRIVATE))!=0)continue; + if(inherited.stream().anyMatch(prior->(flags(prior) & (ACC_PUBLIC|ACC_PROTECTED))!=0 + || packageName(type).equals(packageName(prior.owner()))))inherited.add(declared); + } + return inherited.contains(candidate); + } + + /** Selects a validated super invocation under ACC_SUPER semantics. + * @param caller calling class + * @param symbolic symbolic owner + * @param resolved resolved member + * @return selected instance declaration, or null when no target exists + * @throws BytecodeLoadException with METADATA for absent type metadata or LINKAGE for an + * invalid special owner or conflicting defaults; caller supplies a validated acyclic hierarchy */ + BytecodeMethod.Id special(String caller,String symbolic,BytecodeMethod.Id resolved) { + if(resolved.name().equals("") || (flags(resolved)&ACC_PRIVATE)!=0)return resolved; + if((metadata(symbolic).flags().flagsMask() & ACC_INTERFACE)!=0) { + if(metadata(caller).interfaces().stream().noneMatch(c->c.asInternalName().equals(symbolic))) + throw problem("LINKAGE","Special interface call requires a direct superinterface",null); + return resolved; + } + if(!caller.equals(symbolic) && !assignable(caller,symbolic))throw problem("LINKAGE","Special call requires current class or superclass",null); + if(caller.equals(symbolic))return resolved; + String start=parent(caller); + for(String next=start;next!=null && !next.equals("java/lang/Object");next=parent(next)) { + var candidate=new BytecodeMethod.Id(next,resolved.name(),resolved.descriptor());int flags=flags(candidate); + if(flags>=0 && (flags & ACC_STATIC)==0)return candidate; + } + return interfaceMethod(start,resolved.name(),resolved.descriptor()); + } + + /** Extracts an internal class package for JVM inheritance rules. + * @param name internal class name + * @return package prefix */ + private static String packageName(String name){int slash=name.lastIndexOf('/');return slash<0 ? "" : name.substring(0,slash);} + + /** Returns all inherited instance fields, preserving declaring identities for hidden fields. + * @param type concrete runtime class + * @return deterministic field declarations */ + List instanceFields(String type) { + var ancestors=ancestors(type); + return fields.values().stream().filter(f->(f.flags() & ACC_STATIC)==0 && ancestors.contains(f.id().owner())) + .sorted(Comparator.comparing(BytecodeProgram.Field::id)).toList(); + } +} diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeLimits.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeLimits.java index 54d9b3e..e5894d9 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/BytecodeLimits.java +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeLimits.java @@ -9,7 +9,7 @@ * @param actorAllocations actor object allowance * @param actorHeapCells actor cell allowance * @param maxCallDepth maximum frames per execution owner - * @param maxArrayLength future array length allowance + * @param maxArrayLength per-array length allowance * @param maxStringLength future String UTF-16 allowance * @param setupInstructions setup work allowance * @param setupAllocations setup object allowance diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeLoader.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeLoader.java index 2287a80..751d992 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/BytecodeLoader.java +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeLoader.java @@ -1,5 +1,5 @@ /** - * Bounded, metadata-only admission and interpreted setup for the internal first bytecode profile. + * Bounded, metadata-only admission and interpreted setup for the bounded bytecode heap profile. */ package dev.samhb.interleave.bytecode; @@ -69,6 +69,8 @@ final class BytecodeLoader { * Input byte accounting. */ private int total; + /** Input version last successfully checked; each frozen class read strictly increases total bytes. */ + private int validatedBytes=-1; /** * Pending role-specific call-graph validation. */ @@ -173,29 +175,37 @@ private BytecodeProgram load(BytecodeLimits limits) throws IOException { var constructor=new BytecodeMethod.Id(model,"","()V"); MethodModel setup=method(constructor); if ((setup.flags().flagsMask() & ACC_PUBLIC)==0) throw problem("DECLARATION","Fixture requires public ()V constructor",null); + validateHierarchy(); pending.add(new Work(constructor,Role.SETUP)); - while (!pending.isEmpty()) { - Work work=pending.removeFirst(); if (!visited.add(work)) continue; - MethodModel method=method(work.method()); - if ((method.flags().flagsMask() & (ACC_NATIVE|ACC_ABSTRACT|ACC_BRIDGE))!=0 || method.code().isEmpty()) - throw problem("UNSUPPORTED","Reachable native/abstract/bridge method",null); - signature(method.methodTypeSymbol()); - var decoded=methods.computeIfAbsent(work.method(),ignored -> new BytecodeMethod(work.method().owner(),method)); - BytecodeVerifier.validate(decoded,work.role()); - if (work.role()==Role.CHECK && (decoded.flags & ACC_SYNCHRONIZED)!=0) - throw problem("PURITY","Checks cannot synchronize",decoded.location(0)); - for (var op : decoded.ops.values()) validateReference(decoded,op,work.role()); - } + int knownClasses; + do { + knownClasses=classes.size(); + while (!pending.isEmpty()) { + Work work=pending.removeFirst(); if (!visited.add(work)) continue; + MethodModel method=method(work.method()); + if ((method.flags().flagsMask() & (ACC_NATIVE|ACC_ABSTRACT|ACC_BRIDGE))!=0 || method.code().isEmpty()) + throw problem("UNSUPPORTED","Reachable native/abstract/bridge method",null); + signature(method.methodTypeSymbol()); + var decoded=methods.computeIfAbsent(work.method(),ignored -> new BytecodeMethod(work.method().owner(),method)); + BytecodeVerifier.validate(decoded,work.role()); + if (work.role()==Role.CHECK && (decoded.flags & ACC_SYNCHRONIZED)!=0) + throw problem("PURITY","Checks cannot synchronize",decoded.location(0)); + for (var op : decoded.ops.values()) validateReference(decoded,op,work.role()); + } + if(classes.size()!=knownClasses){pending.addAll(visited);visited.clear();} + } while(!pending.isEmpty()); + validateHierarchy(); // Parsing is not verification. Never let the default reflection resolver participate. var verifier=ClassFile.of(ClassFile.ClassHierarchyResolverOption.of(this::hierarchy)); for (ClassModel type : classes.values()) { List errors=verifier.verify(type); if (!errors.isEmpty()) throw problem("MALFORMED",errors.getFirst().getMessage(),null); } + for(var decoded:methods.values())BytecodeAccessVerifier.validate(decoded,hierarchy(),fields); checks.sort(Comparator.comparing((BytecodeProgram.Check c)->c.method().owner()) .thenComparing(c->c.method().name()).thenComparing(c->c.method().descriptor())); var program=new BytecodeProgram(model,methods,fields,new ArrayList<>(actors.values()),checks, - new ArrayList<>(classes.keySet()),limits,digest(),null); + new ArrayList<>(classes.keySet()),limits,digest(),null,hierarchy()); var state=BytecodeState.beforeSetup(program); state.start(BytecodeState.SETUP,methods.get(constructor),List.of(BytecodeState.FIXTURE)); while (state.executions.get(BytecodeState.SETUP).phase!=BytecodeState.Phase.TERMINATED) { state=OpcodeExecutor.step(program,state,BytecodeState.SETUP).state(); @@ -204,7 +214,7 @@ private BytecodeProgram load(BytecodeLimits limits) throws IOException { throw problem("SETUP",execution.fault!=null ? execution.fault.type() : execution.cutoff.reason(), execution.fault!=null ? execution.fault.location() : execution.cutoff.location()); } - return new BytecodeProgram(model,methods,fields,program.actors,checks,program.classes,limits,program.artifactDigest(),state); + return new BytecodeProgram(model,methods,fields,program.actors,checks,program.classes,limits,program.artifactDigest(),state,hierarchy()); } /** @@ -217,33 +227,151 @@ private BytecodeProgram load(BytecodeLimits limits) throws IOException { private void validateReference(BytecodeMethod method,BytecodeMethod.Op op,Role role) throws IOException { Instruction instruction=op.instruction(); var location=method.location(op.bci()); if (instruction instanceof FieldInstruction field) { - String owner=field.owner().asInternalName(); read(owner); - var id=new BytecodeProgram.FieldId(owner,field.name().stringValue(),field.type().stringValue()); + String owner=field.owner().asInternalName(); read(owner);classAccess(method.id.owner(),owner,location); + var id=hierarchy().field(new BytecodeProgram.FieldId(owner,field.name().stringValue(),field.type().stringValue())); var declaration=fields.get(id); - if (declaration==null) throw problem("LINKAGE","Missing field "+id,location); - access(method.id.owner(),owner,declaration.flags(),location); + if (declaration==null) throw problem("LINKAGE","Missing field "+field.name(),location); + access(method.id.owner(),id.owner(),declaration.flags(),location); boolean isStatic=instruction.opcode()==Opcode.GETSTATIC || instruction.opcode()==Opcode.PUTSTATIC; if (((declaration.flags() & ACC_STATIC)!=0)!=isStatic) throw problem("LINKAGE","Field staticness mismatch",location); boolean write=instruction.opcode()==Opcode.PUTFIELD || instruction.opcode()==Opcode.PUTSTATIC; - if (write && (declaration.flags() & ACC_FINAL)!=0 && !(method.id.owner().equals(owner) && method.id.name().equals("") && !isStatic)) + if (write && (declaration.flags() & ACC_FINAL)!=0 && !(method.id.owner().equals(id.owner()) && method.id.name().equals("") && !isStatic)) throw problem("LINKAGE","Illegal final field write",location); } if (instruction instanceof NewObjectInstruction allocation) { - if (!allocation.className().asInternalName().equals("java/lang/Object")) - throw problem("UNSUPPORTED","Only setup Object monitor allocation is supported",location); + String type=allocation.className().asInternalName(); + if(!type.equals("java/lang/Object")) { + var target=read(type); + classAccess(method.id.owner(),type,location); + if((target.flags().flagsMask() & (ACC_INTERFACE|ACC_ABSTRACT))!=0) + throw problem("LINKAGE","Cannot instantiate abstract/interface type",location); + } + } + if(instruction instanceof NewReferenceArrayInstruction array) typeAccess(array.componentType().asSymbol(),method.id.owner(),location); + if(instruction instanceof NewMultiArrayInstruction array) typeAccess(array.arrayType().asSymbol(),method.id.owner(),location); + if(instruction instanceof TypeCheckInstruction check) typeAccess(check.type().asSymbol(),method.id.owner(),location); + if (instruction instanceof InvokeInstruction call) validateCall(method,call,role,location); + } + + /** Resolves and checks the leaf class named directly by array/type-check bytecode. + * @param type named component, array or cast type + * @param caller accessing application class + * @param location real reference position + * @throws IOException for unavailable metadata + * @throws BytecodeLoadException with LINKAGE for an inaccessible symbolic leaf type */ + private void typeAccess(ClassDesc type,String caller,BytecodeLocation location) throws IOException { + fieldType(type);while(type.isArray())type=type.componentType(); + if(type.isClassOrInterface() && !type.equals(ConstantDescs.CD_Object)) + classAccess(caller,type.descriptorString().substring(1,type.descriptorString().length()-1),location); + } + + /** Validates symbolic linkage and queues every closed dispatch alternative in its execution role. + * @param caller calling interpreted method + * @param call symbolic invocation + * @param role setup, actor or observer + * @param location real invocation BCI + * @throws IOException for unavailable application metadata */ + private void validateCall(BytecodeMethod caller,InvokeInstruction call,Role role,BytecodeLocation location) throws IOException { + String owner=call.owner().asInternalName(),name=call.name().stringValue(),descriptor=call.type().stringValue(); + if(owner.equals("java/lang/Object") && name.equals("") && descriptor.equals("()V") + && call.opcode()==Opcode.INVOKESPECIAL && !call.isInterface())return; + read(owner);classAccess(caller.id.owner(),owner,location);signature(call.typeSymbol());validateHierarchy();var hierarchy=hierarchy(); + if(((classes.get(owner).flags().flagsMask() & ACC_INTERFACE)!=0)!=call.isInterface()) + throw problem("LINKAGE","Invocation owner kind mismatch",location); + var resolved=hierarchy.method(owner,name,descriptor); + if(resolved==null)throw problem("LINKAGE","Missing method "+owner+"."+name+descriptor,location); + int flags=hierarchy.flags(resolved);boolean isStatic=call.opcode()==Opcode.INVOKESTATIC; + if(((flags & ACC_STATIC)!=0)!=isStatic || name.equals("") + || name.equals("") && call.opcode()!=Opcode.INVOKESPECIAL) + throw problem("LINKAGE","Invocation staticness/name mismatch",location); + access(caller.id.owner(),resolved.owner(),flags,location); + if(isStatic || call.opcode()==Opcode.INVOKESPECIAL || (flags & ACC_PRIVATE)!=0) { + if((flags & ACC_ABSTRACT)!=0)throw problem("LINKAGE","Abstract direct invocation",location); + if(call.opcode()==Opcode.INVOKESPECIAL) { + resolved=hierarchy.special(caller.id.owner(),owner,resolved); + if(resolved==null || (hierarchy.flags(resolved) & (ACC_ABSTRACT|ACC_STATIC))!=0) + throw problem("LINKAGE","Invalid selected special target",location); + } + pending.add(new Work(resolved,role));return; } - if (instruction instanceof InvokeInstruction call) { - String owner=call.owner().asInternalName(), name=call.name().stringValue(), descriptor=call.type().stringValue(); - if (owner.equals("java/lang/Object") && name.equals("") && descriptor.equals("()V") - && call.opcode()==Opcode.INVOKESPECIAL && !call.isInterface()) return; - if (call.opcode()!=Opcode.INVOKESTATIC || call.isInterface()) - throw problem("UNSUPPORTED","Only known static application helpers are supported",location); - read(owner); var id=new BytecodeMethod.Id(owner,name,descriptor); MethodModel callee=method(id); - if ((callee.flags().flagsMask() & ACC_STATIC)==0) throw problem("LINKAGE","Call staticness mismatch",location); - access(method.id.owner(),owner,callee.flags().flagsMask(),location); pending.add(new Work(id,role)); + // Fixed-point rescans include classes reached by later constructors, signatures or dispatch bodies. + for(var entry:new ArrayList<>(classes.entrySet())) { + if((entry.getValue().flags().flagsMask() & (ACC_INTERFACE|ACC_ABSTRACT))!=0 || !hierarchy.assignable(entry.getKey(),owner))continue; + var target=hierarchy.dispatch(entry.getKey(),resolved); + if(target==null || (hierarchy.flags(target) & (ACC_ABSTRACT|ACC_STATIC))!=0 + || call.opcode()==Opcode.INVOKEINTERFACE && (hierarchy.flags(target) & ACC_PUBLIC)==0) + throw problem("LINKAGE","Missing concrete dispatch target for "+entry.getKey(),location); + pending.add(new Work(target,role)); } } + /** Freezes the currently discovered hierarchy for deterministic member lookup. + * @return metadata-only hierarchy */ + private BytecodeHierarchy hierarchy(){return new BytecodeHierarchy(classes,fields);} + + /** Rejects cyclic/wrong-kind inheritance, final superclasses and inherited annotated entries. + * @throws BytecodeLoadException for malformed closed hierarchy */ + private void validateHierarchy() { + // The existing bounded byte count versions the immutable, monotonically growing class set. + // No extra size calls or independently maintained generation counter are needed. + if(validatedBytes==total)return; + var hierarchy=hierarchy(); + for(var entry:classes.entrySet()) { + String name=entry.getKey();var type=entry.getValue();nestHost(name); + var path=new HashSet();String parent=name; + while(parent!=null && !parent.equals("java/lang/Object")) { + if(!path.add(parent))throw problem("LINKAGE","Cyclic superclass hierarchy",null); + parent=hierarchy.parent(parent); + } + String superclass=hierarchy.parent(name); + if(superclass!=null && !superclass.equals("java/lang/Object")){classAccess(name,superclass,null);permittedSubtype(name,superclass);} + if(superclass!=null && !superclass.equals("java/lang/Object") + && (classes.get(superclass).flags().flagsMask() & (ACC_INTERFACE|ACC_FINAL))!=0) + throw problem("LINKAGE","Invalid superclass kind/finality",null); + for(var face:type.interfaces()) { + String target=face.asInternalName();classAccess(name,target,null);permittedSubtype(name,target); + if((classes.get(target).flags().flagsMask() & ACC_INTERFACE)==0 + || hierarchy.ancestors(target).contains(name))throw problem("LINKAGE","Invalid/cyclic interface hierarchy",null); + } + for(var method:type.methods()) { + String methodName=method.methodName().stringValue();int flags=method.flags().flagsMask(); + if(methodName.startsWith("<"))continue; + String signature=methodName+method.methodType().stringValue(); + if((flags & (ACC_PRIVATE|ACC_STATIC))==0 && Set.of("getClass()Ljava/lang/Class;","notify()V","notifyAll()V","wait()V","wait(J)V","wait(JI)V").contains(signature)) + throw problem("LINKAGE","Cannot override trusted final Object member "+signature,null); + for(String ancestor:hierarchy.ancestors(name)) { + if(ancestor.equals(name) || ancestor.equals("java/lang/Object"))continue; + var inherited=new BytecodeMethod.Id(ancestor,methodName,method.methodType().stringValue());int inheritedFlags=hierarchy.flags(inherited); + if(inheritedFlags<0 || (inheritedFlags & ACC_PRIVATE)!=0 + || (classes.get(ancestor).flags().flagsMask() & ACC_INTERFACE)!=0 && (inheritedFlags & ACC_STATIC)!=0 + || (inheritedFlags & (ACC_PUBLIC|ACC_PROTECTED))==0 + && !packageName(name).equals(packageName(ancestor)))continue; + // JVM overriding is distinct from Java source visibility rules: narrower raw + // declarations may be valid, but an instance override of a final member is not. + if((flags & (ACC_STATIC|ACC_PRIVATE))==0 && (inheritedFlags & (ACC_STATIC|ACC_FINAL))==ACC_FINAL) + throw problem("LINKAGE","Illegal final method override "+name+"."+methodName,null); + } + } + if(name.equals(model))for(String ancestor:hierarchy.ancestors(model)) { + if(ancestor.equals(model) || ancestor.equals("java/lang/Object"))continue; + for(var method:classes.get(ancestor).methods())if(!annotations(method,ANNOTATION+"Actor;").isEmpty() + || !annotations(method,ANNOTATION+"Check;").isEmpty())throw problem("DECLARATION","Inherited annotated entry point",null); + } + } + validatedBytes=total; + } + + /** Validates sealed edges in this single-directory, unnamed-module application profile. + * @param child actual direct subtype + * @param parent declaring superclass/interface + * @throws BytecodeLoadException for an unlisted subtype or a nonpublic cross-package subtype */ + private void permittedSubtype(String child,String parent) { + var permitted=classes.get(parent).findAttribute(Attributes.permittedSubclasses()); + if(permitted.isPresent() && ((classes.get(child).flags().flagsMask() & ACC_PUBLIC)==0 && !packageName(child).equals(packageName(parent)) + || permitted.get().permittedSubclasses().stream().noneMatch(type->type.asInternalName().equals(child)))) + throw problem("LINKAGE","Subtype is not permitted by sealed parent "+parent,null); + } + /** * Reads one application class under directory handles, with bounded memory and no symlink traversal. * @param name internal class name @@ -275,15 +403,15 @@ private ClassModel read(String name) throws IOException { BytecodeInput.validate(input); ClassModel type=ClassFile.of().parse(input); if (!type.thisClass().asInternalName().equals(name)) throw problem("MALFORMED","Class name/path mismatch",null); - if ((type.flags().flagsMask() & (ACC_INTERFACE|ACC_ANNOTATION|ACC_ENUM|ACC_MODULE))!=0) + if ((type.flags().flagsMask() & (ACC_ANNOTATION|ACC_ENUM|ACC_MODULE))!=0) throw problem("UNSUPPORTED","Unsupported application class kind",null); annotationPlacement(type,name.equals(model) ? Set.of("Model") : Set.of()); classes.put(name,type); bytes.put(name,input); String parent=type.superclass().orElseThrow(()->problem("MALFORMED","Application class requires a superclass",null)).asInternalName(); - if (!parent.equals("java/lang/Object")) { - read(parent); throw problem("UNSUPPORTED","Application inheritance starts in95",null); - } - if (!type.interfaces().isEmpty()) throw problem("UNSUPPORTED","Application interfaces start in95",null); + if (!parent.equals("java/lang/Object")) read(parent); + for(var face:type.interfaces())read(face.asInternalName()); + var nest=type.findAttribute(Attributes.nestHost()); + if(nest.isPresent())read(nest.get().nestHost().asInternalName()); for (FieldModel field : type.fields()) { visibility(field.flags().flagsMask(),name+"."+field.fieldName().stringValue()); annotationPlacement(field,Set.of()); @@ -357,14 +485,19 @@ private static byte[] read(SecureDirectoryStream directory,String[] parts, */ private void fieldType(ClassDesc type) throws IOException { String descriptor=type.descriptorString(); + if(type.isArray()) { + while(type.isArray())type=type.componentType(); + if(type.isPrimitive())return; + fieldType(type);return; + } if (descriptor.equals("I") || descriptor.equals("Z")) return; - if (!type.isClassOrInterface()) throw problem("UNSUPPORTED","Only int/boolean/reference types in94A",null); + if (!type.isClassOrInterface()) throw problem("UNSUPPORTED","Only int/boolean/reference computation is supported",null); String owner=descriptor.substring(1,descriptor.length()-1); if (!owner.equals("java/lang/Object")) read(owner); } /** - * Checks all parameter and return types against the first profile. + * Checks all parameter and return types against the admitted computation profile. * @param descriptor method type * @throws IOException for missing signature classes */ @@ -401,9 +534,8 @@ private static void entry(MethodModel method,String descriptor) { } /** - * Checks application class and member visibility without host linkage. Public members require - * an accessible class; private access requires the declaring class; package/protected access - * requires the same package in this profile. Nestmate and subclass access arrive in95. + * Checks resolved member visibility without host linkage. Symbolic class visibility is checked + * separately so inherited public members of nonpublic superclasses remain accessible. * @param caller accessing class * @param owner declaring class * @param flags member flags @@ -411,11 +543,36 @@ private static void entry(MethodModel method,String descriptor) { * @throws BytecodeLoadException with LINKAGE for an inaccessible class or member */ private void access(String caller,String owner,int flags,BytecodeLocation location) { - int classFlags=classes.get(owner).flags().flagsMask(); boolean samePackage=packageName(caller).equals(packageName(owner)); - if (((classFlags & ACC_PUBLIC)==0 && !samePackage) || ((flags & ACC_PUBLIC)==0 - && ((flags & ACC_PRIVATE)!=0 ? !caller.equals(owner) : !samePackage))) - throw problem("LINKAGE","Inaccessible member (nestmate access starts in95)",location); + boolean allowed=(flags & ACC_PUBLIC)!=0 || caller.equals(owner) + || (flags & ACC_PRIVATE)!=0 && nestHost(caller).equals(nestHost(owner)) + || (flags & ACC_PRIVATE)==0 && (samePackage || (flags & ACC_PROTECTED)!=0 && hierarchy().assignable(caller,owner)); + if(!allowed) + throw problem("LINKAGE","Inaccessible member",location); + } + + /** Checks symbolic class visibility independently of inherited member declaration visibility. + * @param caller accessing class + * @param owner symbolic class owner + * @param location real reference position + * @throws BytecodeLoadException with LINKAGE for an inaccessible symbolic type */ + private void classAccess(String caller,String owner,BytecodeLocation location) { + if((classes.get(owner).flags().flagsMask() & ACC_PUBLIC)==0 && !packageName(caller).equals(packageName(owner))) + throw problem("LINKAGE","Inaccessible symbolic class",location); + } + + /** Validates reciprocal same-package nest membership before granting private access. + * @param member potential nest member + * @return validated nest host + * @throws BytecodeLoadException with LINKAGE for invalid or nonreciprocal nest metadata */ + private String nestHost(String member) { + var type=classes.get(member);var host=type.findAttribute(Attributes.nestHost()); + if(host.isEmpty())return member; + String name=host.get().nestHost().asInternalName();var root=classes.get(name); + if(root==null || !packageName(member).equals(packageName(name)) || root.findAttribute(Attributes.nestHost()).isPresent() + || root.findAttribute(Attributes.nestMembers()).stream().flatMap(a->a.nestMembers().stream()) + .noneMatch(c->c.asInternalName().equals(member)))throw problem("LINKAGE","Invalid nest membership",null); + return name; } /** @@ -473,12 +630,16 @@ private static void annotationPlacement(AttributedElement element,Set al */ private ClassHierarchyResolver.ClassHierarchyInfo hierarchy(ClassDesc descriptor) { String name=descriptor.descriptorString(); name=name.substring(1,name.length()-1); + if(classes.containsKey(name) && (classes.get(name).flags().flagsMask() & ACC_INTERFACE)!=0) + return ClassHierarchyResolver.ClassHierarchyInfo.ofInterface(); String parent=switch(name) { case "java/lang/Object" -> null; + case "java/lang/ArrayIndexOutOfBoundsException" -> "java/lang/IndexOutOfBoundsException"; case "java/lang/Throwable" -> "java/lang/Object"; case "java/lang/Exception" -> "java/lang/Throwable"; case "java/lang/RuntimeException" -> "java/lang/Exception"; - case "java/lang/NullPointerException", "java/lang/ArithmeticException", "java/lang/IllegalMonitorStateException" -> "java/lang/RuntimeException"; + case "java/lang/NullPointerException", "java/lang/ArithmeticException", "java/lang/IllegalMonitorStateException", + "java/lang/ClassCastException", "java/lang/NegativeArraySizeException", "java/lang/ArrayStoreException", "java/lang/IndexOutOfBoundsException" -> "java/lang/RuntimeException"; default -> { var model=classes.get(name); if (model==null) throw problem("METADATA","Unknown hierarchy type "+name,null); diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeObservations.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeObservations.java index 90711b5..4dc0042 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/BytecodeObservations.java +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeObservations.java @@ -68,7 +68,12 @@ private static BytecodeExplorer.Outcome failed(BytecodeState state,BytecodeCheck * @return immutable normalized observation */ static BytecodeExplorer.Outcome outcome(BytecodeState state,BytecodeExplorer.Kind kind,int actor,Fault fault,Cutoff cutoff,String interruption,List waits,BytecodeChecks.Failure observer) { var shared=new TreeMap();state.statics.forEach((field,value)->shared.put(new BytecodeExplorer.Cell(NULL,field),value)); - state.heap.forEach((reference,object)->{if(object.shared)object.fields.forEach((field,value)->shared.put(new BytecodeExplorer.Cell(reference,field),value));}); + state.heap.forEach((reference,object)->{ + if(!object.shared)return; + object.fields.forEach((field,value)->shared.put(new BytecodeExplorer.Cell(reference,field),value)); + if(object.elements!=null)for(int i=0;i methods, Map fields, List actors, List checks, - List classes, BytecodeLimits limits, String digest, BytecodeState setup) { + List classes, BytecodeLimits limits, String digest, BytecodeState setup,BytecodeHierarchy hierarchy) { + this.hierarchy=hierarchy; this.model = model; this.methods = Map.copyOf(methods); this.fields = Map.copyOf(fields); this.actors = List.copyOf(actors); this.checks = List.copyOf(checks); this.classes = List.copyOf(classes); this.limits = limits; this.digest = digest; this.setup = setup == null ? null : setup.copy(); @@ -104,7 +108,7 @@ record Check(BytecodeMethod.Id method, boolean always) {} public String artifactDigest() { return digest; } /** Version of the admitted language, intrinsic costs and sequentially consistent execution profile. */ - static final String PROFILE_VERSION="BYTECODE-SC-1"; + static final String PROFILE_VERSION="BYTECODE-SC-2"; /** Returns the frozen execution-profile version used to authenticate evidence. * @return bounded sequentially consistent profile identifier */ diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeScheduler.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeScheduler.java index 0da8834..1815fcf 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/BytecodeScheduler.java +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeScheduler.java @@ -2,7 +2,7 @@ package dev.samhb.interleave.bytecode; import java.lang.classfile.Opcode; -import java.lang.classfile.instruction.FieldInstruction; +import java.lang.classfile.instruction.*; import java.util.*; /** Pure choices and isolated selected transitions using the single opcode executor. */ @@ -83,9 +83,11 @@ Transition advance(BytecodeState parent,int actor) { var before=state.executions.get(actor);boolean publication=false; if(probe.opcode()==Opcode.PUTFIELD || probe.opcode()==Opcode.PUTSTATIC) { var frame=before.frames.getLast();var field=(FieldInstruction)frame.method.ops.get(frame.bci).instruction(); - publication=field.type().stringValue().startsWith("L"); + publication=field.type().stringValue().startsWith("L") || field.type().stringValue().startsWith("["); } - var result=OpcodeExecutor.step(program,state,actor);var next=result.state(); + publication|=probe.opcode()==Opcode.AASTORE || probe.opcode()==Opcode.NEW || probe.opcode()==Opcode.NEWARRAY + || probe.opcode()==Opcode.ANEWARRAY || probe.opcode()==Opcode.MULTIANEWARRAY; + int heapBefore=state.heap.size();var result=OpcodeExecutor.step(program,state,actor);var next=result.state(); int charged=next.executions.get(actor).instructions-before.instructions; String event=charged>0 ? "OPCODE" : probe.exhausted() ? "FUEL_CUTOFF" : switch(before.phase) { case RUNNING -> "MONITOR_ENTER";case RETURNING -> "RETURN";case EXCEPTION -> "EXCEPTION"; @@ -94,7 +96,7 @@ Transition advance(BytecodeState parent,int actor) { }; executed.add(new Executed(probe.location(),charged==0 ? null : probe.opcode(),event)); instructions+=charged;kind=result.kind();state=next;observable|=probe.observable(); - if(publication && kind==OpcodeExecutor.Kind.ADVANCED)sharing=sharing.plus(BytecodeSharing.refresh(state)); + if(publication && (kind==OpcodeExecutor.Kind.ADVANCED || next.heap.size()!=heapBefore))sharing=sharing.plus(BytecodeSharing.refresh(state)); // Every discovered return/fault/cutoff yields before terminal delivery, including local failures. if(mode==Mode.REFERENCE || kind!=OpcodeExecutor.Kind.ADVANCED || state.executions.get(actor).phase!=BytecodeState.Phase.RUNNING)break; diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeSharing.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeSharing.java index 38e9162..e320192 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/BytecodeSharing.java +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeSharing.java @@ -1,68 +1,83 @@ -/** Conservative transitive sharing for the setup-only heap, with actual traversal instrumentation. */ +/** Conservative transitive sharedness with irreversible history and measured traversal work. */ package dev.samhb.interleave.bytecode; import java.util.*; import static dev.samhb.interleave.bytecode.BytecodeState.*; -/** Never establishes actor-exclusive heap ownership in94B; unknown and historical sharing stay shared. */ +/** Proves exclusivity from actor roots; publication promotes entire reachable graphs atomically. */ final class BytecodeSharing { - /** Prevents construction of the stateless sharing traversal. */ + /** Prevents construction of this stateless traversal. */ private BytecodeSharing() {} - /** Actual sharedness work, outside the model's canonical state and resource counters. + /** Actual sharing work outside canonical state/resource allowances. * @param traversals refresh operations - * @param objects distinct heap objects processed across refreshes - * @param edges nonnull reference-field edges visited from roots - * @param promotions false-to-true historical sharing changes - */ + * @param objects object visits across root traversals + * @param edges reference edges visited + * @param promotions irreversible false-to-true changes */ record Work(long traversals,long objects,long edges,long promotions) { - /** Empty work for transitions which do not change reference reachability. */ + /** Empty sharing work. */ static final Work NONE=new Work(0,0,0,0); - /** Combines actual work without changing target state. - * @param other additional traversal work - * @return summed counters */ + /** Adds instrumentation without modifying target state. + * @param other additional work + * @return combined measurements */ Work plus(Work other){return new Work(traversals+other.traversals,objects+other.objects,edges+other.edges,promotions+other.promotions);} } - /** Traverses fixture/static/actor roots and conservatively promotes unresolved ownership. - * The initial profile has setup-only objects; no heap access is batched as actor-local. - * @param state owned scratch, never an unselected committed parent - * @return actual object/edge work and irreversible promotions - */ + /** Recomputes reachability after reference writes/allocations, retaining historical promotions. + * Shared roots include historically shared objects even after their last public alias disappears. + * A fresh actor allocation is exclusively on that actor's stack; the executor establishes its + * initial locality. Unreachable objects cannot regain an alias without passing through a traced + * heap edge. Thus losing a last local root cannot create a new cross-actor path between refreshes. + * @param state selected owned successor + * @return actual traversal/edge/promotion counts */ static Work refresh(BytecodeState state) { - var queue=new ArrayDeque();queue.add(FIXTURE); - for(var value:state.statics.values())enqueue(queue,value); - for(var entry:state.executions.entrySet()) { - if(entry.getKey()<0)continue; - var execution=entry.getValue();enqueue(queue,execution.returned); + var roots=new TreeMap>();var shared=new ArrayList();roots.put(SETUP,shared); + shared.add(FIXTURE);state.statics.values().forEach(value->root(shared,value)); + state.heap.forEach((reference,object)->{if(object.shared)shared.add(reference);}); + state.executions.forEach((owner,execution)->{ + if(owner<0)return;var actor=new ArrayList();roots.put(owner,actor);root(actor,execution.returned); for(var frame:execution.frames) { - for(var value:frame.locals.values())enqueue(queue,value); - for(var value:frame.stack)enqueue(queue,value); - enqueue(queue,frame.methodMonitor); + frame.locals.values().forEach(value->root(actor,value));frame.stack.forEach(value->root(actor,value));root(actor,frame.methodMonitor);root(actor,frame.constructorReceiver); } - } - var seen=new HashSet();long objects=0,edges=0,promotions=0; - while(!queue.isEmpty()) { - var reference=queue.removeFirst();if(!seen.add(reference))continue; - var object=state.heap.get(reference);if(object==null)continue; - objects++;if(!object.shared){object.shared=true;promotions++;} - for(var value:object.fields.values()) { - if(value instanceof Ref target && !target.equals(NULL)){edges++;queue.addLast(target);} + }); + var reached=new HashMap>();long objects=0,edges=0,promotions=0; + for(var entry:roots.entrySet()) { + var pending=new ArrayDeque<>(entry.getValue());var seen=new HashSet(); + while(!pending.isEmpty()) { + Ref reference=pending.removeFirst();if(!seen.add(reference))continue; + var object=state.heap.get(reference);if(object==null)continue; + objects++;reached.computeIfAbsent(reference,ignored->new HashSet<>()).add(entry.getKey()); + for(Value value:object.fields.values())if(value instanceof Ref target && !target.equals(NULL)){edges++;pending.add(target);} + if(object.elements!=null)for(Value value:object.elements)if(value instanceof Ref target && !target.equals(NULL)){edges++;pending.add(target);} } } - // shortcut:94B cannot allocate actor-local objects; unresolved setup ownership remains shared until95 analysis. + var promoted=new ArrayDeque(); for(var entry:state.heap.entrySet()) { - if(seen.add(entry.getKey())) { - objects++;if(!entry.getValue().shared){entry.getValue().shared=true;promotions++;} + var owners=reached.get(entry.getKey()); + boolean exclusive=owners!=null && owners.size()==1 && !owners.contains(SETUP); + if(!exclusive && !entry.getValue().shared){ + entry.getValue().shared=true;promotions++; + // Reached shared/multi-actor descendants were already classified transitively above. + if(owners==null)promoted.add(entry.getKey()); + } + } + // Unknown ownership can promote an unreachable parent whose child still has an actor root. + // Close those promotions before any observer sees a shared-to-private edge. + while(!promoted.isEmpty()) { + var object=state.heap.get(promoted.removeFirst());objects++; + var children=new ArrayList(object.fields.values());if(object.elements!=null)children.addAll(object.elements); + for(Value value:children)if(value instanceof Ref reference && !reference.equals(NULL)) { + edges++;var child=state.heap.get(reference); + if(child!=null && !child.shared){child.shared=true;promotions++;promoted.add(reference);} } } return new Work(1,objects,edges,promotions); } - /** Adds actual reference roots, excluding null and non-reference VM metadata. - * @param queue pending roots - * @param value target slot or pending value */ - private static void enqueue(ArrayDeque queue,Value value) { - if(value instanceof Ref reference && !reference.equals(NULL))queue.addLast(reference); + /** Adds only nonnull target reference roots. + * @param roots root list + * @param value interpreted slot */ + private static void root(List roots,Value value) { + if(value instanceof Ref reference && !reference.equals(NULL))roots.add(reference); } } diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeSnapshots.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeSnapshots.java index 8df2f35..e8f7094 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/BytecodeSnapshots.java +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeSnapshots.java @@ -24,6 +24,10 @@ static BytecodeEvidence.Snapshot capture(BytecodeState state,byte[] canonical) { state.heap.forEach((reference,object)->{ String id=identity(reference);heap.add(new BytecodeEvidence.ObjectState(id,object.type,object.shared,object.initialized,object.monitorOwner,object.monitorDepth)); object.fields.forEach((field,slot)->fields.put(id+"."+field(field),value(slot))); + if(object.elements!=null) { + fields.put(id+".length",number(object.elements.size())); + for(int i=0;i{ var slots=new TreeMap(); @@ -38,7 +42,7 @@ static BytecodeEvidence.Snapshot capture(BytecodeState state,byte[] canonical) { var frame=execution.frames.get(index);String prefix="frame"+index+"."; slots.put(prefix+"method",text(frame.method.id.toString()));slots.put(prefix+"bci",number(frame.bci)); slots.put(prefix+"entered",new BytecodeEvidence.Value("BOOLEAN",Boolean.toString(frame.entered))); - slots.put(prefix+"monitor",value(frame.methodMonitor)); + slots.put(prefix+"monitor",value(frame.methodMonitor));slots.put(prefix+"constructor",value(frame.constructorReceiver)); frame.locals.forEach((slot,entry)->slots.put(prefix+"local"+slot,value(entry))); for(int operand=0;operand new BytecodeEvidence.Value("NULL",""); case Int integer -> number(integer.value()); + case WideZero wide -> new BytecodeEvidence.Value(wide.type().equals("LONG") ? "LONG" : wide.type()+"_BITS",wide.type().equals("LONG") ? "0" : wide.type().equals("FLOAT") ? "00000000" : "0000000000000000"); case Ref reference -> reference.equals(NULL) ? new BytecodeEvidence.Value("NULL","") : new BytecodeEvidence.Value("REFERENCE",identity(reference)); case Thrown thrown -> new BytecodeEvidence.Value("FAULT",thrown.fault().toString()); }; diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeState.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeState.java index f8d17dc..81c59fa 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/BytecodeState.java +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeState.java @@ -1,5 +1,5 @@ /** - * Complete owned foundation state, including resources, aliases and pending terminal events. + * Complete owned heap-profile state, including resources, aliases and pending terminal events. */ package dev.samhb.interleave.bytecode; @@ -32,12 +32,15 @@ final class BytecodeState { /** * Operand/local value families admitted by this profile. */ - sealed interface Value permits Int, Ref, Thrown {} + sealed interface Value permits Int, Ref, Thrown, WideZero {} /** * Models a JVM int, including the boolean operand representation. * @param value JVM int (also boolean representation) */ record Int(int value) implements Value {} + /** Default-only wide array slot; computations remain excluded until97. + * @param type LONG, FLOAT or DOUBLE tag */ + record WideZero(String type) implements Value {} /** * Names a permanent object identity in a setup, actor or constant namespace. * @param owner setup/actor/constant namespace @@ -113,7 +116,7 @@ enum Phase { */ CUTOFF } /** - * Mutable heap object; Object/fixture only until95. + * Mutable application object or exact-descriptor array. */ static final class ObjectValue { /** @@ -125,13 +128,15 @@ static final class ObjectValue { */ final NavigableMap fields = new TreeMap<>(); /** - * Historical promotion, conservative for all setup objects in94A. + * Irreversible historical promotion; setup objects begin shared. */ boolean shared = true; /** * Constructor completion affects legal future execution. */ boolean initialized; + /** Array elements, null for ordinary objects; type retains rank and exact component descriptor. */ + ArrayList elements; /** * Monitor owner; -2 denotes unowned. */ @@ -151,7 +156,7 @@ static final class ObjectValue { */ ObjectValue copy() { var copy = new ObjectValue(type); copy.fields.putAll(fields); copy.shared = shared; - copy.initialized = initialized; copy.monitorOwner = monitorOwner; copy.monitorDepth = monitorDepth; + copy.initialized = initialized; copy.elements=elements==null ? null : new ArrayList<>(elements); copy.monitorOwner = monitorOwner; copy.monitorDepth = monitorDepth; return copy; } } @@ -264,13 +269,14 @@ static BytecodeState beforeSetup(BytecodeProgram program) { var state = new BytecodeState(); var setup = new Execution(); state.executions.put(SETUP,setup); long cells=1L+program.classes.size()+program.fields.values().stream().filter(field -> - (field.flags() & ClassFile.ACC_STATIC)!=0 || field.id().owner().equals(program.model)).count(); + (field.flags() & ClassFile.ACC_STATIC)!=0).count()+program.hierarchy.instanceFields(program.model).size(); if (cells>program.limits.setupHeapCells()) throw new BytecodeLoadException("LIMIT","Setup default cells exceed allowance",null); var fixture = new ObjectValue(program.model); for (var field : program.fields.values()) { if ((field.flags() & ClassFile.ACC_STATIC) != 0) state.statics.put(field.id(),field.initial()); - else if (field.id().owner().equals(program.model)) fixture.fields.put(field.id(),field.initial()); + } + program.hierarchy.instanceFields(program.model).forEach(field->fixture.fields.put(field.id(),field.initial())); state.heap.put(FIXTURE,fixture); setup.allocations=1; setup.nextSequence=1; for (String type : program.classes) { var monitor = new ObjectValue("java/lang/Class"); monitor.initialized=true; @@ -298,17 +304,19 @@ Value fixtureField(String field) { } /** - * Encodes all future-relevant foundation state, independent of diagnostic toString output. + * Encodes all future-relevant heap-profile state, independent of diagnostic toString output. * @return versioned length-delimited canonical payload */ byte[] canonicalBytes() { try { var bytes = new ByteArrayOutputStream(); var out = new DataOutputStream(bytes); - out.writeInt(1); out.writeInt(heap.size()); + out.writeInt(2); out.writeInt(heap.size()); for (var entry : heap.entrySet()) { value(out,entry.getKey()); var object=entry.getValue(); text(out,object.type); out.writeBoolean(object.shared); out.writeBoolean(object.initialized); out.writeInt(object.monitorOwner); out.writeInt(object.monitorDepth); fields(out,object.fields); + out.writeBoolean(object.elements!=null); + if(object.elements!=null){out.writeInt(object.elements.size());for(Value element:object.elements)value(out,element);} } fields(out,statics); out.writeInt(executions.size()); for (var entry : executions.entrySet()) { @@ -322,7 +330,7 @@ byte[] canonicalBytes() { } out.writeInt(execution.frames.size()); for (var frame : execution.frames) { - location(out,frame.method.location(frame.bci)); out.writeBoolean(frame.entered); value(out,frame.methodMonitor); + location(out,frame.method.location(frame.bci)); out.writeBoolean(frame.entered); value(out,frame.methodMonitor); value(out,frame.constructorReceiver); out.writeInt(frame.locals.size()); for (var local : frame.locals.entrySet()) { out.writeInt(local.getKey()); value(out,local.getValue()); } out.writeInt(frame.stack.size()); for (Value operand : frame.stack) value(out,operand); @@ -354,6 +362,7 @@ private static void value(DataOutputStream out, Value value) throws IOException switch (value) { case null -> out.writeByte(0); case Int number -> { out.writeByte(1); out.writeInt(number.value()); } + case WideZero wide -> {out.writeByte(4);text(out,wide.type());} case Ref reference -> { out.writeByte(2); out.writeInt(reference.owner()); out.writeLong(reference.sequence()); } case Thrown thrown -> { out.writeByte(3); fault(out,thrown.fault()); } } diff --git a/src/main/java/dev/samhb/interleave/bytecode/BytecodeVerifier.java b/src/main/java/dev/samhb/interleave/bytecode/BytecodeVerifier.java index f01bfce..bc15b4e 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/BytecodeVerifier.java +++ b/src/main/java/dev/samhb/interleave/bytecode/BytecodeVerifier.java @@ -1,5 +1,5 @@ /** - * First-profile opcode/purity admission and structured compiler monitor-cleanup validation. + * Heap-profile opcode/purity admission and structured compiler monitor-cleanup validation. */ package dev.samhb.interleave.bytecode; @@ -23,7 +23,7 @@ private BytecodeVerifier() {} Opcode.DUP_X1,Opcode.DUP_X2,Opcode.DUP2,Opcode.DUP2_X1,Opcode.DUP2_X2,Opcode.SWAP, Opcode.IADD,Opcode.ISUB,Opcode.IMUL,Opcode.IDIV,Opcode.IREM,Opcode.INEG, Opcode.ISHL,Opcode.ISHR,Opcode.IUSHR,Opcode.IAND,Opcode.IOR,Opcode.IXOR, - Opcode.I2B,Opcode.I2C,Opcode.I2S,Opcode.MONITORENTER,Opcode.MONITOREXIT,Opcode.ATHROW); + Opcode.I2B,Opcode.I2C,Opcode.I2S,Opcode.ARRAYLENGTH,Opcode.MONITORENTER,Opcode.MONITOREXIT,Opcode.ATHROW); /** * Supported conditional and unconditional branches. */ @@ -52,12 +52,19 @@ static void validate(BytecodeMethod method,BytecodeLoader.Role role) { case TableSwitchInstruction ignored -> true; case FieldInstruction ignored -> true; case InvokeInstruction ignored -> true; - case NewObjectInstruction ignored -> role==BytecodeLoader.Role.SETUP; + case NewObjectInstruction ignored -> true; + case NewPrimitiveArrayInstruction ignored -> true; + case NewReferenceArrayInstruction ignored -> true; + case NewMultiArrayInstruction ignored -> true; + case TypeCheckInstruction ignored -> true; + case ArrayLoadInstruction load -> load.typeKind()!=TypeKind.LONG && load.typeKind()!=TypeKind.FLOAT && load.typeKind()!=TypeKind.DOUBLE; + case ArrayStoreInstruction store -> store.typeKind()!=TypeKind.LONG && store.typeKind()!=TypeKind.FLOAT && store.typeKind()!=TypeKind.DOUBLE; default -> SIMPLE.contains(code); }; if (!allowed || (code==Opcode.ATHROW && !cleanupThrows.contains(op.bci()))) throw problem("UNSUPPORTED","Unsupported reachable opcode "+code,method.location(op.bci())); - if (role==BytecodeLoader.Role.CHECK && (instruction instanceof NewObjectInstruction + if (role==BytecodeLoader.Role.CHECK && (instruction instanceof NewObjectInstruction || instruction instanceof NewPrimitiveArrayInstruction + || instruction instanceof NewReferenceArrayInstruction || instruction instanceof NewMultiArrayInstruction || instruction instanceof ArrayStoreInstruction || code==Opcode.PUTFIELD || code==Opcode.PUTSTATIC || code==Opcode.MONITORENTER || code==Opcode.MONITOREXIT)) throw problem("PURITY","Checks cannot mutate, allocate or synchronize",method.location(op.bci())); for (int successor : successors(method,op)) { @@ -68,7 +75,7 @@ static void validate(BytecodeMethod method,BytecodeLoader.Role role) { } /** - * Admits only the first profile's category-one load and store types. + * Admits only the heap profile's category-one load and store types. * @param kind verifier type kind * @return whether one-slot int/reference transport is supported */ @@ -151,6 +158,9 @@ private static void structuredMonitors(BytecodeMethod method) { if (instruction instanceof ReturnInstruction && !locks.isEmpty()) throw problem("MALFORMED","Return with unmatched monitor entry",method.location(bci)); boolean canThrow=instruction instanceof FieldInstruction || instruction instanceof InvokeInstruction + || instruction instanceof ArrayLoadInstruction || instruction instanceof ArrayStoreInstruction || instruction instanceof TypeCheckInstruction + || instruction instanceof NewObjectInstruction || instruction instanceof NewPrimitiveArrayInstruction || instruction instanceof NewReferenceArrayInstruction + || instruction instanceof NewMultiArrayInstruction || code==Opcode.ARRAYLENGTH || code==Opcode.IDIV || code==Opcode.IREM || code==Opcode.MONITORENTER || code==Opcode.ATHROW; if (canThrow) { int handler=method.handler(bci); diff --git a/src/main/java/dev/samhb/interleave/bytecode/OpcodeExecutor.java b/src/main/java/dev/samhb/interleave/bytecode/OpcodeExecutor.java index eb37d8b..3ee7c8e 100644 --- a/src/main/java/dev/samhb/interleave/bytecode/OpcodeExecutor.java +++ b/src/main/java/dev/samhb/interleave/bytecode/OpcodeExecutor.java @@ -88,6 +88,9 @@ static Probe probe(BytecodeProgram program,BytecodeState state,int owner) { return new Probe(Availability.BLOCKED,location,code,monitor,true,false); } boolean observable=op.instruction() instanceof FieldInstruction || op.instruction() instanceof ReturnInstruction + || op.instruction() instanceof NewObjectInstruction || op.instruction() instanceof NewPrimitiveArrayInstruction + || op.instruction() instanceof NewReferenceArrayInstruction || op.instruction() instanceof NewMultiArrayInstruction + || op.instruction() instanceof ArrayLoadInstruction || op.instruction() instanceof ArrayStoreInstruction || code==Opcode.MONITORENTER || code==Opcode.MONITOREXIT || code==Opcode.ATHROW; return new Probe(Availability.READY,location,code,monitor,observable,false); } @@ -113,7 +116,7 @@ private static int limit(BytecodeProgram program,int owner) { /** * Internal control transfer for a modeled VM fault, not a host throwable from target execution. */ - private static final class Trap extends RuntimeException { + static final class Trap extends RuntimeException { /** * Existing cleanup exception token, or null for a new fault. */ @@ -209,7 +212,7 @@ private static boolean execute(BytecodeProgram program,BytecodeState state,Execu execution.eventLocation=frame.method.location(frame.bci); execution.phase=Phase.RETURNING; return false; } if(instruction instanceof FieldInstruction field) { - var id=new BytecodeProgram.FieldId(field.owner().asInternalName(),field.name().stringValue(),field.type().stringValue()); + var id=program.hierarchy.field(new BytecodeProgram.FieldId(field.owner().asInternalName(),field.name().stringValue(),field.type().stringValue())); switch(code) { case GETSTATIC -> frame.push(state.statics.get(id)); case PUTSTATIC -> state.statics.put(id,narrow(id,frame.pop())); @@ -219,25 +222,38 @@ private static boolean execute(BytecodeProgram program,BytecodeState state,Execu } return true; } + if(BytecodeArrays.handles(instruction))return BytecodeArrays.execute(program,state,execution,frame,instruction,owner); if(instruction instanceof NewObjectInstruction allocation) { - int allocationLimit=program.limits.setupAllocations(), cellLimit=program.limits.setupHeapCells(); - if(execution.allocations==allocationLimit) { cutoff(execution,frame,"ALLOCATIONS",allocationLimit,1,0); return false; } - if(execution.cells==cellLimit) { cutoff(execution,frame,"HEAP_CELLS",cellLimit,1,0); return false; } - var reference=new Ref(owner,execution.nextSequence++); - state.heap.put(reference,new ObjectValue(allocation.className().asInternalName())); - execution.allocations++; execution.cells++; frame.push(reference); return true; + String type=allocation.className().asInternalName(); + var fields=type.equals("java/lang/Object") ? List.of() : program.hierarchy.instanceFields(type); + int cells=1+fields.size(); + if(!reserve(program,execution,frame,owner,cells))return false; + var reference=new Ref(owner,execution.nextSequence++);var object=new ObjectValue(type); + object.shared=owner==SETUP;fields.forEach(field->object.fields.put(field.id(),field.initial())); + state.heap.put(reference,object);execution.allocations++;execution.cells+=cells;frame.push(reference);return true; } if(instruction instanceof InvokeInstruction call) { + int count=call.typeSymbol().parameterCount();boolean isStatic=code==Opcode.INVOKESTATIC; + Ref receiver=isStatic ? null : (Ref)frame.stack.get(frame.stack.size()-count-1); + if(receiver!=null) { + var target=object(state,receiver); // Dynamic validity precedes depth exhaustion. + if(!program.hierarchy.assignable(target.type,call.owner().asInternalName()))throw new Trap("java/lang/IncompatibleClassChangeError",null); + } if(call.owner().asInternalName().equals("java/lang/Object")) { - object(state,(Ref)frame.pop()).initialized=true; return true; + frame.pop();if(object(state,receiver).type.equals("java/lang/Object"))object(state,receiver).initialized=true;return true; } if(execution.frames.size()==program.limits.maxCallDepth()) { - cutoff(execution,frame,"CALL_DEPTH",program.limits.maxCallDepth(),1,0); return false; + cutoff(execution,frame,"CALL_DEPTH",program.limits.maxCallDepth(),1,0);return false; } - int count=call.typeSymbol().parameterCount(); var arguments=new ArrayList(); - for(int i=0; i(); + for(int i=0;i { } @@ -273,6 +289,21 @@ private static boolean execute(BytecodeProgram program,BytecodeState state,Execu return true; } + /** Checks permanent per-allocator counts/cells before creating an identity. + * @param program selected limits + * @param execution charged owner + * @param frame allocating instruction + * @param owner setup or actor namespace + * @param cells entire new object charge + * @return whether creation may commit */ + static boolean reserve(BytecodeProgram program,Execution execution,BytecodeFrame frame,int owner,int cells) { + int allocations=owner==SETUP ? program.limits.setupAllocations() : program.limits.actorAllocations(); + int heap=owner==SETUP ? program.limits.setupHeapCells() : program.limits.actorHeapCells(); + if(execution.allocations>=allocations){cutoff(execution,frame,"ALLOCATIONS",allocations,1,allocations-execution.allocations);return false;} + if(cells>heap-execution.cells){cutoff(execution,frame,"HEAP_CELLS",heap,cells,heap-execution.cells);return false;} + return true; + } + /** * Evaluates one admitted signed, identity or null branch condition. * @param frame selected frame @@ -312,6 +343,11 @@ private static boolean branch(BytecodeFrame frame,Opcode code) { private static void finishReturn(BytecodeState state,Execution execution,int owner) { var frame=execution.frames.removeLast(); if(frame.methodMonitor!=null) release(state,frame.methodMonitor,owner); + if(frame.method.id.name().equals("")) { + Ref reference=frame.constructorReceiver;var receiver=state.heap.get(reference); + if(receiver.type.equals(frame.method.id.owner()) && execution.frames.stream().noneMatch(f->f.method.id.name().equals("") + && reference.equals(f.constructorReceiver)))receiver.initialized=true; + } if(execution.frames.isEmpty()) execution.phase=Phase.TERMINATION_PENDING; else { var caller=execution.frames.getLast(); caller.bci=caller.method.ops.get(caller.bci).next(); @@ -344,7 +380,7 @@ private static void unwind(BytecodeState state,Execution execution,int owner) { * @param reference receiver * @return modeled object or modeled null fault */ - private static ObjectValue object(BytecodeState state,Ref reference) { + static ObjectValue object(BytecodeState state,Ref reference) { if(reference.equals(NULL)) throw new Trap("java/lang/NullPointerException",null); return Objects.requireNonNull(state.heap.get(reference),"Unknown interpreted reference"); } @@ -389,7 +425,7 @@ private static void release(BytecodeState state,Ref monitor,int owner) { * @param required attempted work * @param remaining unspent allowance */ - private static void cutoff(Execution execution,BytecodeFrame frame,String reason,int limit,int required,int remaining) { + static void cutoff(Execution execution,BytecodeFrame frame,String reason,int limit,int required,int remaining) { execution.eventLocation=frame.method.location(frame.bci); execution.cutoff=new Cutoff(reason,execution.eventLocation,limit,required,remaining); execution.phase=Phase.CUTOFF_PENDING; } diff --git a/src/main/java/dev/samhb/interleave/cli/Main.java b/src/main/java/dev/samhb/interleave/cli/Main.java index b5a9bea..4d6db93 100644 --- a/src/main/java/dev/samhb/interleave/cli/Main.java +++ b/src/main/java/dev/samhb/interleave/cli/Main.java @@ -488,6 +488,7 @@ private static void printUsage() { System.out.println(" interleave --file [flags]"); System.out.println(" interleave --source [flags]"); System.out.println(" interleave --bytecode --class-path [--json] [--strategy DFS] [--store exact]"); + System.out.println(" BYTECODE: bounded SC objects/arrays/closed dispatch; no user handlers or host-JVM fallback"); System.out.println(" interleave --all [flags]"); System.out.println(" interleave generate --template [flags]"); System.out.println(); diff --git a/src/main/java/dev/samhb/interleave/core/BytecodeEvidence.java b/src/main/java/dev/samhb/interleave/core/BytecodeEvidence.java index c613876..e779466 100644 --- a/src/main/java/dev/samhb/interleave/core/BytecodeEvidence.java +++ b/src/main/java/dev/samhb/interleave/core/BytecodeEvidence.java @@ -97,7 +97,7 @@ public record Transition(int actor,List operations) implements Serial } /** Lossless typed value: wide numeric data is a string, never an untyped JSON number. - * LONG and raw FLOAT_BITS/DOUBLE_BITS reserve representation for later language phases. + * LONG and raw FLOAT_BITS/DOUBLE_BITS retain default wide array cells; wider computation belongs to later phases. * @param type INT, LONG, FLOAT_BITS, DOUBLE_BITS, BOOLEAN, REFERENCE, NULL, TEXT or FAULT * @param raw exact decimal, raw hex bits, permanent identity or diagnostic UTF-16 text */ public record Value(String type,String raw) implements Serializable { @@ -145,7 +145,7 @@ public record Snapshot(String stateDigest,Map fields,Map stack) implements Serializable { /** Freezes the genuine fault stack. */ public Fault {text(type);Objects.requireNonNull(location);stack=List.copyOf(stack);if(stack.isEmpty())throw new IllegalArgumentException("Missing fault stack");} diff --git a/src/mutationHarness/java/dev/samhb/mutationharness/BytecodeWorkBudget.java b/src/mutationHarness/java/dev/samhb/mutationharness/BytecodeWorkBudget.java index bd83b84..a6eb94a 100644 --- a/src/mutationHarness/java/dev/samhb/mutationharness/BytecodeWorkBudget.java +++ b/src/mutationHarness/java/dev/samhb/mutationharness/BytecodeWorkBudget.java @@ -1,4 +1,4 @@ -/** PIT-only finite-graph and observer-event assertions, derived from model bounds rather than elapsed time. */ +/** PIT-only finite-graph, loader-closure and observer-event assertions, derived from model bounds rather than elapsed time. */ package dev.samhb.mutationharness; import java.lang.classfile.*; @@ -10,19 +10,21 @@ /** Instruments host checker loops only; target model bytecode is never loaded or executed on the host. */ final class BytecodeWorkBudget { - /** Package containing the two owned checker loops. */ + /** Package containing the owned checker loops. */ private static final String PACKAGE="dev/samhb/interleave/bytecode/"; /** Exact iterative search entry. */ private static final String SEARCH="(L"+PACKAGE+"BytecodeExplorer$Budget;)L"+PACKAGE+"BytecodeExplorer$Result;"; /** Exact pure observer entry. */ private static final String CHECK="(L"+PACKAGE+"BytecodeProgram;L"+PACKAGE+"BytecodeState;Z)L"+PACKAGE+"BytecodeChecks$Evaluation;"; + /** Exact private metadata-closure/setup entry. */ + private static final String LOAD="(L"+PACKAGE+"BytecodeLimits;)L"+PACKAGE+"BytecodeProgram;"; /** Assertion has no runtime dependency on this agent. */ private static final ClassDesc ASSERTION=ClassDesc.of("java.lang.AssertionError"); /** Prevents construction of this test-only transformer utility. */ private BytecodeWorkBudget() {} - /** Adds the two narrow transformers to the established PIT agent. + /** Adds the owned checker-progress transformer to the established PIT agent. * @param instrumentation host instrumentation service */ static void install(Instrumentation instrumentation){instrumentation.addTransformer(new Transformer(),true);} @@ -36,7 +38,9 @@ private BytecodeWorkBudget() {} * @throws IllegalArgumentException for binding drift */ static byte[] instrument(byte[] bytes,boolean redefinition,ClassLoader loader) { var file=ClassFile.of(ClassFile.ClassHierarchyResolverOption.of(ClassHierarchyResolver.ofClassLoading(loader))); - var model=file.parse(bytes);String name=model.thisClass().asInternalName();boolean search=name.equals(PACKAGE+"BytecodeExplorer"); + var model=file.parse(bytes);String name=model.thisClass().asInternalName(); + if(name.equals(PACKAGE+"BytecodeLoader"))return instrumentLoader(file,model,redefinition); + boolean search=name.equals(PACKAGE+"BytecodeExplorer"); if(!search && !name.equals(PACKAGE+"BytecodeChecks"))throw new IllegalArgumentException("Unexpected bytecode checker class"); if(model.methods().stream().filter(method->matches(method,search)).count()!=1)throw new IllegalArgumentException("Unexpected bytecode checker method"); int[] checkpoints={0},resets={0}; @@ -90,6 +94,42 @@ static byte[] instrument(byte[] bytes,boolean redefinition,ClassLoader loader) { return result; } + /** Bounds closure passes independently of the loader's convergence tests. + * A completed pass either ends loading or discovers at least one new class. With at most64 + * application classes there are at most64 passes, each reading Map.size twice. Two spare + * checkpoints accommodate framing; the assertion never consults the mutated loop condition. + * @param file host-checker class-file service + * @param model original or singly mutated loader + * @param redefinition whether PIT replaced a previously validated definition + * @return loader with invocation-local progress assertions */ + private static byte[] instrumentLoader(ClassFile file,ClassModel model,boolean redefinition) { + if(model.methods().stream().filter(m->m.methodName().equalsString("load") && m.methodType().equalsString(LOAD)).count()!=1) + throw new IllegalArgumentException("Unexpected loader closure binding"); + int[] checkpoints={0}; + var result=file.transformClass(model,ClassTransform.transformingMethodBodies( + method->method.methodName().equalsString("load") && method.methodType().equalsString(LOAD), + CodeTransform.ofStateful(()->new CodeTransform(){ + /** Independent invocation-local class-growth checkpoint allowance. */ + private int remaining; + /** Starts the independently derived two-checkpoints-per-pass allowance. + * @param code destination body */ + @Override public void atStart(CodeBuilder code){remaining=code.allocateLocal(TypeKind.INT);code.ldc(130).istore(remaining);} + /** Charges each fixed-point Map.size checkpoint before the original call. + * @param code destination body + * @param element original or mutated instruction */ + @Override public void accept(CodeBuilder code,CodeElement element) { + if(element instanceof InvokeInstruction call && call.owner().asInternalName().equals("java/util/Map") + && call.name().equalsString("size") && call.type().equalsString("()I")) { + checkpoints[0]++;code.iinc(remaining,-1).iload(remaining).ifThen(Opcode.IFLT,bad->bad.new_(ASSERTION).dup() + .ldc("Bytecode logical loader closure bound exceeded").invokespecial(ASSERTION,INIT_NAME,MethodTypeDesc.of(CD_void,CD_Object)).athrow()); + } + code.with(element); + } + }))); + if(checkpoints[0]!=2 && !(redefinition && checkpoints[0]==1))throw new IllegalArgumentException("Unexpected loader closure checkpoint shape"); + return result; + } + /** Matches the exact static/instance method and local-slot layout used by the assertions. * @param method candidate method * @param search search or observer definition @@ -112,7 +152,7 @@ private Transformer() {} * @param bytes incoming definition * @return transformed bytes, null for unrelated classes, invalid bytes on binding failure */ @Override public byte[] transform(Module module,ClassLoader loader,String name,Class redefining,ProtectionDomain domain,byte[] bytes) { - if(!(PACKAGE+"BytecodeExplorer").equals(name) && !(PACKAGE+"BytecodeChecks").equals(name))return null; + if(!(PACKAGE+"BytecodeExplorer").equals(name) && !(PACKAGE+"BytecodeChecks").equals(name) && !(PACKAGE+"BytecodeLoader").equals(name))return null; try {return instrument(bytes,redefining!=null,loader);} catch(RuntimeException failure){System.err.println("Bytecode mutation harness rejected unexpected shape");return new byte[]{0};} } diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeAdmissionTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeAdmissionTest.java index f947da7..9c55073 100644 --- a/src/test/java/dev/samhb/interleave/bytecode/BytecodeAdmissionTest.java +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeAdmissionTest.java @@ -18,8 +18,6 @@ class BytecodeAdmissionTest { * @throws Exception for fixture failures */ @Test void rejectsUnsupportedReachableProfiles(@TempDir Path directory) throws Exception { List bodies=List.of( - "@Actor(id=0) public void actor() { Object x=new Object(); }", - "@Actor(id=0) public void actor() { int[] x=new int[1]; }", "@Actor(id=0) public void actor() { if(value==0) System.nanoTime(); }", "@Actor(id=0) public void actor() { try { value=1/value; } catch(ArithmeticException e) { value=1; } }", "@Actor(id=0) public void actor() { try { value=1/value; } finally { value++; } }", @@ -261,14 +259,13 @@ public Fixture() {} @Actor(id=0) public void actor() {} * * @param directory compiler workspace * @throws Exception for fixture failures */ - @Test void rejectsNarrowDescriptorsAndInstanceCalls(@TempDir Path directory) throws Exception { + @Test void rejectsNarrowDescriptors(@TempDir Path directory) throws Exception { List bodies=List.of("byte value;", "char value;", "short value;", "static byte helper(){return 1;} @Check public boolean check(){return helper()==1;}", "static char helper(){return 1;} @Check public boolean check(){return helper()==1;}", - "static short helper(){return 1;} @Check public boolean check(){return helper()==1;}", - "public Fixture(){this(1);} public Fixture(int x){}", "void helper(){} @Check public boolean check(){helper();return true;}"); + "static short helper(){return 1;} @Check public boolean check(){return helper()==1;}"); for(int index=0;indexBytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults())); + assertTrue(error.category.equals(observer ? "PURITY" : "UNSUPPORTED"),error.getMessage()); + } + } + + /** An absent closed-hierarchy class must reject without target reflection or search-time resolution. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void missingDispatchMetadataRejectsBeforeSearch(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + interface Read{int read();}class Impl implements Read{public int read(){return 1;}} + @Model public class Fixture{public Fixture(){} @Actor(id=0)public void actor(){Read r=new Impl();r.read();}} + """); + Files.delete(classes.resolve("Read.class")); + assertEquals("METADATA",assertThrows(BytecodeLoadException.class,()->BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults())).category); + } + /** Cross-package protected access validates the receiver type, beyond ordinary member visibility. + * @param directory compiler workspace + * @throws Exception for fixture/oracle failures */ + @Test void protectedReceiversAndInheritedPublicMembers(@TempDir Path directory) throws Exception { + for(boolean illegal:new boolean[]{false,true}) { + Path work=directory.resolve(illegal ? "invalid" : "valid"),sources=work.resolve("sources"),classes=work.resolve("classes"); + Files.createDirectories(sources.resolve("a"));Files.createDirectories(sources.resolve("b"));Files.createDirectories(classes); + Path base=sources.resolve("a/Box.java"),child=sources.resolve("b/Child.java"),fixture=sources.resolve("b/Fixture.java"); + Files.writeString(base,"package a;public class Box{protected int secret=7;public int exposed=3;public Box(){}}"); + Files.writeString(child,"package b;public class Child extends a.Box{public static int read("+(illegal ? "a.Box" : "Child")+" c){return c."+(illegal ? "exposed" : "secret")+";}}"); + Files.writeString(fixture,"package b;import dev.samhb.interleave.bytecode.*;@Model public class Fixture extends Child{public int result;public Fixture(){}@Actor(id=0)public void actor(){result=read(this);}}"); + assertEquals(0,javax.tools.ToolProvider.getSystemJavaCompiler().run(null,null,null,"--release","26","-classpath",BytecodeFixtures.classpath(Model.class),"-d",classes.toString(),base.toString(),child.toString(),fixture.toString())); + if(illegal) { + var parser=java.lang.classfile.ClassFile.of();Path target=classes.resolve("b/Child.class"); + Files.write(target,parser.transformClass(parser.parse(Files.readAllBytes(target)),(builder,element)->{ + if(element instanceof java.lang.classfile.MethodModel method && method.methodName().equalsString("read")) + builder.transformMethod(method,java.lang.classfile.MethodTransform.transformingCode((code,item)->{ + if(item instanceof java.lang.classfile.instruction.FieldInstruction field)code.getfield(field.owner().asSymbol(),"secret",java.lang.constant.ConstantDescs.CD_int); + else code.with(item); + }));else builder.with(element); + })); + assertEquals("LINKAGE",assertThrows(BytecodeLoadException.class,()->BytecodeLoader.load(classes,"b.Fixture",BytecodeLimits.defaults())).category); + } else { + var program=BytecodeLoader.load(classes,"b.Fixture",BytecodeLimits.defaults()); + assertEquals(new Int(7),BytecodeFixtures.run(program,program.initialState(),0).fixtureField("result")); + assertEquals("7",BytecodeFixtures.oracle(work,classes,"b.Fixture f=new b.Fixture();f.actor();System.out.print(f.result);")); + } + } + } + + /** Symbolic type operations cannot bypass class visibility, even when the runtime value is null. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void inaccessibleArrayAndCastTypesRejectBeforeSearch(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + class Hidden{}@Model public class Fixture{Object saved;public Fixture(){}@Actor(id=0)public void actor(){saved=new Hidden[1];}} + """); + var parser=java.lang.classfile.ClassFile.of();Path hidden=classes.resolve("Hidden.class"),moved=classes.resolve("other/Hidden.class"); + Files.createDirectories(moved.getParent()); + Files.write(moved,parser.transformClass(parser.parse(Files.readAllBytes(hidden)),java.lang.constant.ClassDesc.of("other.Hidden"),java.lang.classfile.ClassTransform.ACCEPT_ALL)); + Path fixture=classes.resolve("Fixture.class");byte[] original=Files.readAllBytes(fixture); + for(boolean cast:new boolean[]{false,true}) { + Files.write(fixture,parser.transformClass(parser.parse(original),(builder,element)->{ + if(element instanceof java.lang.classfile.MethodModel method && method.methodName().equalsString("actor")) + builder.transformMethod(method,java.lang.classfile.MethodTransform.transformingCode((code,item)->{ + if(item instanceof java.lang.classfile.instruction.NewReferenceArrayInstruction) { + if(cast)code.pop().aconst_null().checkcast(java.lang.constant.ClassDesc.of("other.Hidden")); + else code.anewarray(java.lang.constant.ClassDesc.of("other.Hidden")); + } + else code.with(item); + }));else builder.with(element); + })); + assertEquals("LINKAGE",assertThrows(BytecodeLoadException.class,()->BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults())).category); + } + } + + /** Trusted Object final methods cannot be overridden by forged application metadata. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void finalObjectMembersRejectBeforeExecution(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,"@Model public class Fixture{public Fixture(){}public void helper(){}@Actor(id=0)public void actor(){notify();}}"); + var parser=java.lang.classfile.ClassFile.of();Path target=classes.resolve("Fixture.class"); + Files.write(target,parser.transformClass(parser.parse(Files.readAllBytes(target)),(builder,element)->{ + if(element instanceof java.lang.classfile.MethodModel method && method.methodName().equalsString("helper")) + builder.withMethodBody("notify",java.lang.constant.MethodTypeDesc.of(java.lang.constant.ConstantDescs.CD_void),java.lang.classfile.ClassFile.ACC_PUBLIC,code->code.return_()); + else builder.with(element); + })); + assertEquals("LINKAGE",assertThrows(BytecodeLoadException.class,()->BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults())).category); + } + + /** Static interface members are not inherited by implementing classes. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void interfaceStaticMemberDoesNotConflictWithInstanceMethod(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + interface I{static int value(){return 1;}}class C implements I{public int value(){return 2;}} + @Model public class Fixture{public int result;public Fixture(){}@Actor(id=0)public void actor(){result=new C().value();}} + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + assertEquals(new Int(2),BytecodeFixtures.run(program,program.initialState(),0).fixtureField("result")); + assertEquals("2",BytecodeFixtures.oracle(directory,classes,"Fixture f=new Fixture();f.actor();System.out.print(f.result);")); + } + + /** CHECK validation is role-specific even if the mutating override was already admitted for an actor. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void actorAdmissionCannotBypassObserverDispatchPurity(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + class Base{boolean test(){return true;}}class Sub extends Base{int x;boolean test(){x++;return true;}} + @Model public class Fixture{Base b=new Sub();public Fixture(){}@Actor(id=0)public void actor(){b.test();} + @Check public boolean valid(){return b.test();}} + """); + assertEquals("PURITY",assertThrows(BytecodeLoadException.class,()->BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults())).category); + } + + /** Cross-package nonpublic superclasses/interfaces reject, with public controls retained. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void directSupertypesMustBeAccessible(@TempDir Path directory) throws Exception { + for(boolean face:new boolean[]{false,true}) { + var work=directory.resolve(face ? "interface" : "superclass");Files.createDirectories(work.resolve("sources/a"));Files.createDirectories(work.resolve("sources/b")); + var parent=work.resolve("sources/a/Parent.java");var child=work.resolve("sources/b/Fixture.java");var classes=work.resolve("classes");Files.createDirectories(classes); + Files.writeString(parent,face ? "package a;public interface Parent{}" : "package a;public class Parent{public Parent(){}}"); + Files.writeString(child,"package b;import dev.samhb.interleave.bytecode.*;@Model public class Fixture "+(face ? "implements" : "extends")+" a.Parent{public Fixture(){}@Actor(id=0)public void actor(){}}"); + assertEquals(0,javax.tools.ToolProvider.getSystemJavaCompiler().run(null,null,null,"--release","26","-classpath",BytecodeFixtures.classpath(Model.class),"-d",classes.toString(),parent.toString(),child.toString())); + assertNotNull(BytecodeLoader.load(classes,"b.Fixture",BytecodeLimits.defaults())); + var parser=java.lang.classfile.ClassFile.of();var path=classes.resolve("a/Parent.class");var type=parser.parse(Files.readAllBytes(path)); + Files.write(path,parser.transformClass(type,java.lang.classfile.ClassTransform.endHandler(builder->builder.withFlags(type.flags().flagsMask() & ~java.lang.classfile.ClassFile.ACC_PUBLIC)))); + assertEquals("LINKAGE",assertThrows(BytecodeLoadException.class,()->BytecodeLoader.load(classes,"b.Fixture",BytecodeLimits.defaults())).category); + } + } + + /** Repeated false override relationships have bounded work and cannot redirect a package-private base call. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void deepPackagePrivateOverrideSelectionIsBounded(@TempDir Path directory) throws Exception { + var sources=directory.resolve("sources");var classes=directory.resolve("classes");Files.createDirectories(sources.resolve("a"));Files.createDirectories(sources.resolve("b"));Files.createDirectories(classes); + var arguments=new java.util.ArrayList(java.util.List.of("--release","26","-classpath",BytecodeFixtures.classpath(Model.class),"-d",classes.toString())); + var base=sources.resolve("a/Base.java");Files.writeString(base,"package a;public class Base{public Base(){}int value(){return 1;}public int read(){return value();}}");arguments.add(base.toString()); + for(int depth=1;depth<=30;depth++) { + var source=sources.resolve("b/C"+depth+".java"); + Files.writeString(source,"package b;public class C"+depth+" extends "+(depth==1 ? "a.Base" : "C"+(depth-1))+"{public int value(){return 2;}}");arguments.add(source.toString()); + } + var source=sources.resolve("Fixture.java");Files.writeString(source,"import dev.samhb.interleave.bytecode.*;@Model public class Fixture{public int result;public Fixture(){}@Actor(id=0)public void actor(){a.Base b=new b.C30();result=b.read();}}");arguments.add(source.toString()); + assertEquals(0,javax.tools.ToolProvider.getSystemJavaCompiler().run(null,null,null,arguments.toArray(String[]::new))); + var program=assertTimeoutPreemptively(java.time.Duration.ofSeconds(20),()->BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults())); + var state=BytecodeFixtures.run(program,program.initialState(),0);assertEquals(Phase.TERMINATED,state.executions.get(0).phase);assertEquals(new Int(1),state.fixtureField("result")); + assertEquals("1",BytecodeFixtures.oracle(directory,classes,"Fixture f=new Fixture();f.actor();System.out.print(f.result);")); + var middle=sources.resolve("a/Middle.java");Files.writeString(middle,"package a;public class Middle extends Base{public int value(){return 3;}}");arguments.add(middle.toString()); + Files.writeString(sources.resolve("b/C1.java"),"package b;public class C1 extends a.Middle{public int value(){return 2;}}"); + assertEquals(0,javax.tools.ToolProvider.getSystemJavaCompiler().run(null,null,null,arguments.toArray(String[]::new))); + var limits=new BytecodeLimits(256,128,8192,64,64,256,4096,128,8192,1024); + var widened=assertTimeoutPreemptively(java.time.Duration.ofSeconds(20),()->BytecodeLoader.load(classes,"Fixture",limits)); + var widenedState=BytecodeFixtures.run(widened,widened.initialState(),0);assertEquals(Phase.TERMINATED,widenedState.executions.get(0).phase); + assertEquals(new Int(2),widenedState.fixtureField("result")); + assertEquals("2",BytecodeFixtures.oracle(directory,classes,"Fixture f=new Fixture();f.actor();System.out.print(f.result);")); + } + + /** JVM-verified interface bytecode still performs a dynamic receiver check; no host failure may escape. + * @param directory compiler workspace + * @throws Exception for fixture/oracle failures */ + @Test void incompatibleInterfaceReceiverIsModeled(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,"interface I{void read();}@Model public class Fixture{public Fixture(){}@Actor(id=0)public void actor(){I value=null;value.read();}}"); + var parser=java.lang.classfile.ClassFile.of();Path target=classes.resolve("Fixture.class"); + Files.write(target,parser.transformClass(parser.parse(Files.readAllBytes(target)),(builder,element)->{ + if(element instanceof java.lang.classfile.MethodModel method && method.methodName().equalsString("actor")) + builder.transformMethod(method,java.lang.classfile.MethodTransform.transformingCode((code,item)->{ + if(item instanceof java.lang.classfile.Instruction instruction && instruction.opcode()==java.lang.classfile.Opcode.ACONST_NULL) + code.new_(java.lang.constant.ConstantDescs.CD_Object).dup().invokespecial(java.lang.constant.ConstantDescs.CD_Object,"",java.lang.constant.MethodTypeDesc.of(java.lang.constant.ConstantDescs.CD_void)); + else code.with(item); + }));else builder.with(element); + })); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + var state=BytecodeFixtures.run(program,program.initialState(),0); + assertEquals(Phase.FAILED,state.executions.get(0).phase);assertEquals("java/lang/IncompatibleClassChangeError",state.executions.get(0).fault.type()); + assertEquals("java.lang.IncompatibleClassChangeError",BytecodeFixtures.oracle(directory,classes,"try{new Fixture().actor();}catch(LinkageError e){System.out.print(e.getClass().getName());}")); + } + + /** Private base declarations cannot capture interface defaults; inherited public implementations win. + * @param directory compiler workspace + * @throws Exception for fixture/oracle failures */ + @Test void interfaceDefaultsIgnorePrivateBaseMethods(@TempDir Path directory) throws Exception { + for(boolean privateMember:new boolean[]{true,false})for(boolean interfaceView:new boolean[]{true,false}) { + var work=directory.resolve((privateMember ? "private" : "public")+(interfaceView ? "-interface" : "-class")); + var classes=BytecodeFixtures.compile(work,26,"interface I{default int read(){return 1;}}class Base{"+(privateMember ? "private" : "public") + +" int read(){return 2;}}class Child extends Base implements I{}@Model public class Fixture{public int result;public Fixture(){}@Actor(id=0)public void actor(){"+(interfaceView ? "I" : "Child")+" value=new Child();result=value.read();}}"); + String jvm=BytecodeFixtures.oracle(work,classes,"try{Fixture f=new Fixture();f.actor();System.out.print(f.result);}catch(LinkageError e){System.out.print(e.getClass().getName());}"); + if(privateMember && !interfaceView) { + assertEquals("java.lang.IllegalAccessError",jvm); + assertEquals("LINKAGE",assertThrows(BytecodeLoadException.class,()->BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults())).category); + } else { + assertEquals(privateMember ? "1" : "2",jvm); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults());var state=BytecodeFixtures.run(program,program.initialState(),0); + assertEquals(new Int(privateMember ? 1 : 2),state.fixtureField("result")); + } + } + } + + /** Sealed hierarchy admission checks permitted edges without linking target classes on the host. + * @param directory compiler workspace + * @throws Exception for fixture/oracle failures */ + @Test void sealedParentsValidatePermittedSubtypes(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,17,""" + sealed class Parent permits Allowed,Other{int read(){return 1;}}final class Allowed extends Parent{}final class Other extends Parent{} + @Model public class Fixture{public int result;public Fixture(){}@Actor(id=0)public void actor(){Parent p=new Allowed();result=p.read();}} + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults());assertEquals(new Int(1),BytecodeFixtures.run(program,program.initialState(),0).fixtureField("result")); + assertEquals("1",BytecodeFixtures.oracle(directory,classes,"Fixture f=new Fixture();f.actor();System.out.print(f.result);")); + var parser=java.lang.classfile.ClassFile.of();Path target=classes.resolve("Parent.class"); + Files.write(target,parser.transformClass(parser.parse(Files.readAllBytes(target)),(builder,element)->{ + if(element instanceof java.lang.classfile.attribute.PermittedSubclassesAttribute) + builder.with(java.lang.classfile.attribute.PermittedSubclassesAttribute.ofSymbols(java.lang.constant.ClassDesc.of("Other"))); + else builder.with(element); + })); + assertEquals("LINKAGE",assertThrows(BytecodeLoadException.class,()->BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults())).category); + assertEquals("java.lang.IncompatibleClassChangeError",BytecodeFixtures.oracle(directory,classes, + "try{new Fixture().actor();}catch(LinkageError e){System.out.print(e.getClass().getName());}")); + } + + /** A widened ancestor remains relevant after a later narrower raw declaration, as required by JVMS overriding. + * @param directory compiler workspace + * @throws Exception for fixture/oracle failures */ + @Test void transitiveOverrideRetainsEarlierWidening(@TempDir Path directory) throws Exception { + var sources=directory.resolve("sources");var classes=directory.resolve("classes");Files.createDirectories(sources.resolve("p"));Files.createDirectories(sources.resolve("q"));Files.createDirectories(classes); + var files=java.util.Map.of( + "p/A.java","package p;public class A{int m(){return 1;}public int call(){return m();}}", + "p/B.java","package p;public class B extends A{public int m(){return 2;}}", + "p/C.java","package p;public class C extends B{public int m(){return 3;}}", + "q/D.java","package q;public class D extends p.C{public int m(){return 4;}}", + "Fixture.java","import dev.samhb.interleave.bytecode.*;@Model public class Fixture{public int result;public Fixture(){}@Actor(id=0)public void actor(){p.A a=new q.D();result=a.call();}}"); + var arguments=new java.util.ArrayList(java.util.List.of("--release","26","-classpath",BytecodeFixtures.classpath(Model.class),"-d",classes.toString())); + for(var entry:files.entrySet()){var source=sources.resolve(entry.getKey());Files.writeString(source,entry.getValue());arguments.add(source.toString());} + assertEquals(0,javax.tools.ToolProvider.getSystemJavaCompiler().run(null,null,null,arguments.toArray(String[]::new))); + var parser=java.lang.classfile.ClassFile.of(); + for(String name:java.util.List.of("p/C","q/D")) { + Path target=classes.resolve(name+".class"); + Files.write(target,parser.transformClass(parser.parse(Files.readAllBytes(target)),(builder,element)->{ + if(element instanceof java.lang.classfile.MethodModel method && method.methodName().equalsString("m")) + builder.transformMethod(method,java.lang.classfile.MethodTransform.endHandler(output->output.withFlags(0))); + else builder.with(element); + })); + } + assertEquals("4",BytecodeFixtures.oracle(directory,classes,"Fixture f=new Fixture();f.actor();System.out.print(f.result);")); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + assertEquals(new Int(4),BytecodeFixtures.run(program,program.initialState(),0).fixtureField("result")); + } + + /** Private invocations retain their resolved base declaration instead of selecting a child shadow. + * @param directory compiler workspace + * @throws Exception for fixture/oracle failures */ + @Test void privateResolvedMethodCannotBeOverridden(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,"class Base{private int read(){return 1;}int call(){return read();}}class Child extends Base{int read(){return 2;}}@Model public class Fixture{public int result;public Fixture(){}@Actor(id=0)public void actor(){Base b=new Child();result=b.call();}}"); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + assertEquals(new Int(1),BytecodeFixtures.run(program,program.initialState(),0).fixtureField("result")); + assertEquals("1",BytecodeFixtures.oracle(directory,classes,"Fixture f=new Fixture();f.actor();System.out.print(f.result);")); + } + + /** Cyclic interface metadata terminates in admission instead of recursively expanding ancestors. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void cyclicInterfacesRejectBeforeSearch(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,"interface I{}interface J extends I{}@Model public class Fixture implements J{public Fixture(){}@Actor(id=0)public void actor(){}}"); + var parser=java.lang.classfile.ClassFile.of();Path target=classes.resolve("I.class"); + Files.write(target,parser.transformClass(parser.parse(Files.readAllBytes(target)),java.lang.classfile.ClassTransform.endHandler(builder->builder.withInterfaceSymbols(java.lang.constant.ClassDesc.of("J"))))); + assertEquals("LINKAGE",assertThrows(BytecodeLoadException.class,()->BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults())).category); + } + + /** Static and instance references through a model or its base share the declaration's real cell. + * @param directory compiler workspace + * @throws Exception for fixture/oracle failures */ + @Test void inheritedSymbolicOwnersResolveOneFieldCell(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + class Base{static int n;int v;}@Model public class Fixture extends Base{public Fixture(){} + @Actor(id=0)public void actor(){Fixture.n=1;Base.n++;Fixture f=this;f.v=3;((Base)f).v++;} + @Check public boolean valid(){return Base.n==2 && Fixture.n==2 && v==4;}} + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults());var state=BytecodeFixtures.run(program,program.initialState(),0); + assertEquals(new Int(2),state.statics.get(new BytecodeProgram.FieldId("Base","n","I")));assertEquals(1,state.statics.size()); + assertEquals(new Int(4),state.fixtureField("v"));assertEquals("2:4",BytecodeFixtures.oracle(directory,classes,"Fixture f=new Fixture();f.actor();System.out.print(Fixture.n+\":\"+((Base)f).v);")); + var result=new BytecodeExplorer(program,BytecodeScheduler.Mode.BATCHED).explore(10000);assertTrue(result.exhaustive()); + assertEquals(java.util.Set.of(BytecodeExplorer.Kind.COMPLETED),result.witnesses().stream().map(w->w.outcome().kind()).collect(java.util.stream.Collectors.toSet())); + } + + /** Both production granularities retain the concrete array lost-update violation and successful result. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void arrayIncrementChecksRetainSeparateReadWriteChoices(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,"@Model public class Fixture{int[] x=new int[1];public Fixture(){}@Actor(id=0)public void a(){x[0]++;}@Actor(id=1)public void b(){x[0]++;}@Check public boolean valid(){return x[0]==2;}}"); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults());var expected=BytecodeInstructionOracle.enumerate(program); + for(var mode:BytecodeScheduler.Mode.values()) { + var result=new BytecodeExplorer(program,mode).explore(100000);assertTrue(result.exhaustive()); + assertEquals(java.util.Set.of(BytecodeExplorer.Kind.COMPLETED,BytecodeExplorer.Kind.CHECK_FALSE),result.witnesses().stream().map(w->w.outcome().kind()).collect(java.util.stream.Collectors.toSet())); + assertEquals(expected,BytecodeBatchingOracleTest.independentProjection(result)); + } + } + +} diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeEncodingTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeEncodingTest.java index 0c5cc38..955e522 100644 --- a/src/test/java/dev/samhb/interleave/bytecode/BytecodeEncodingTest.java +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeEncodingTest.java @@ -20,12 +20,12 @@ class BytecodeEncodingTest { """); var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); try(var in=new DataInputStream(new ByteArrayInputStream(program.initialState().canonicalBytes()))) { - assertEquals(1,in.readInt()); assertEquals(3,in.readInt()); - reference(in,-2,0); text(in,"java/lang/Class"); objectHeader(in); assertEquals(0,in.readInt()); + assertEquals(2,in.readInt()); assertEquals(3,in.readInt()); + reference(in,-2,0); text(in,"java/lang/Class"); objectHeader(in); assertEquals(0,in.readInt()); assertFalse(in.readBoolean()); reference(in,-1,0); text(in,"Fixture"); objectHeader(in); assertEquals(2,in.readInt()); field(in,"lock","Ljava/lang/Object;"); reference(in,-1,1); - field(in,"value","I"); integer(in,7); - reference(in,-1,1); text(in,"java/lang/Object"); objectHeader(in); assertEquals(0,in.readInt()); + field(in,"value","I"); integer(in,7); assertFalse(in.readBoolean()); + reference(in,-1,1); text(in,"java/lang/Object"); objectHeader(in); assertEquals(0,in.readInt()); assertFalse(in.readBoolean()); assertEquals(1,in.readInt()); field(in,"CONSTANT","I"); integer(in,3); assertEquals(2,in.readInt()); assertEquals(-1,in.readInt()); assertEquals(6,in.readInt()); // setup TERMINATED @@ -34,7 +34,7 @@ class BytecodeEncodingTest { assertEquals(0,in.readInt()); assertEquals(0,in.readInt()); // actor RUNNING assertEquals(0,in.readInt()); assertEquals(0,in.readInt()); assertEquals(0,in.readInt()); assertEquals(0L,in.readLong()); assertFalse(in.readBoolean()); assertFalse(in.readBoolean()); assertEquals(0,in.readUnsignedByte()); assertFalse(in.readBoolean()); - assertEquals(1,in.readInt()); location(in,"actor",0); assertTrue(in.readBoolean()); assertEquals(0,in.readUnsignedByte()); + assertEquals(1,in.readInt()); location(in,"actor",0); assertTrue(in.readBoolean()); assertEquals(0,in.readUnsignedByte()); assertEquals(0,in.readUnsignedByte()); assertEquals(1,in.readInt()); assertEquals(0,in.readInt()); reference(in,-1,0); assertEquals(0,in.readInt()); assertEquals(-1,in.read()); } } diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeEventTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeEventTest.java index 53611bb..feb7a2a 100644 --- a/src/test/java/dev/samhb/interleave/bytecode/BytecodeEventTest.java +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeEventTest.java @@ -127,7 +127,7 @@ private static BytecodeProgram program(int flags,int fuel,Consumer .withMethodBody("actor",MethodTypeDesc.of(ConstantDescs.CD_void),ACC_PUBLIC|flags,body)); var method=new BytecodeMethod("Fixture",parser.parse(bytes).methods().getFirst()); var limits=new BytecodeLimits(fuel,128,8192,32,64,256,4096,128,8192,1024); - return new BytecodeProgram("Fixture",Map.of(method.id,method),Map.of(),List.of(method.id),List.of(),List.of("Fixture"),limits,"test",null); + return new BytecodeProgram("Fixture",Map.of(method.id,method),Map.of(),List.of(method.id),List.of(),List.of("Fixture"),limits,"test",null,new BytecodeHierarchy(Map.of("Fixture",parser.parse(bytes)),Map.of())); } /** Starts an isolated actor using the internal instruction seam, without invoking a target constructor. diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeGeneratedTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeGeneratedTest.java index 43c6e80..6bcb79d 100644 --- a/src/test/java/dev/samhb/interleave/bytecode/BytecodeGeneratedTest.java +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeGeneratedTest.java @@ -45,6 +45,42 @@ class BytecodeGeneratedTest { } } + /** Fixed-seed heap/cast/dispatch programs use the same independent JVM and deletion shrinker. + * @param directory compiler workspace + * @throws Exception for fixture/oracle failures */ + @Test void generatedHeapProgramsMatchJvmWithShrinking(@TempDir Path directory) throws Exception { + long seed=0x952026L;var random=new Random(seed); + for(int sample=0;sample<12;sample++) { + int initial=random.nextInt();var operations=new ArrayList(); + for(int index=0;index<5;index++) { + int n=random.nextInt(17)-8; + operations.add(switch(random.nextInt(4)) { + case 0 -> "{int[] a=new int[2];a[1]=x;x=a[1]+"+n+";}"; + case 1 -> "{Cell c=new Cell(x);Read r=c;x=r.read()+"+n+";}"; + case 2 -> "{Object[] a=new Cell[1];a[0]=new Cell(x);x=((Cell)a[0]).read()^"+n+";}"; + default -> "{Cell c=new Cell(x);c.next=c;Object o=c;if(o instanceof Cell)x=((Cell)o).next.read()-("+n+");}"; + }); + } + int release=new int[]{17,21,26}[sample%3]; + if(!matches(directory.resolve("case"+sample),release,heapSource(initial,operations))) { + int selected=sample;int[] attempt={0}; + var minimal=shrink(operations,candidate->{try{return !matches(directory.resolve("shrink"+selected+"-"+attempt[0]++),release,heapSource(initial,candidate));} + catch(Exception failure){throw new IllegalStateException(failure);}}); + Path regression=Path.of("build/bytecode-regressions/heap-seed-"+seed+"-case-"+sample+"/Fixture.java"); + Files.createDirectories(regression.getParent());Files.writeString(regression,heapSource(initial,minimal)); + fail("Heap differential mismatch; saved "+regression); + } + } + } + + /** Adds a bounded application hierarchy around independently generated actor statements. + * @param initial initial JVM int + * @param operations bounded statements + * @return complete compiler fixture */ + private static String heapSource(int initial,List operations) { + return "interface Read{int read();}class Cell implements Read{int x;Cell next;Cell(int x){this.x=x;}public int read(){return x;}}"+source(initial,operations); + } + /** The test-only shrinker removes irrelevant operations and reaches deletion-one-minimality. */ @Test void shrinkerRetainsOnlyFailureConditions() { var input=List.of("prefix","requiredA","noise","requiredB","suffix"); diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeHeapMeasurementTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeHeapMeasurementTest.java new file mode 100644 index 0000000..62c4bae --- /dev/null +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeHeapMeasurementTest.java @@ -0,0 +1,123 @@ +/** Reproducible broader-heap measurements gated by independent instruction outcomes. */ +package dev.samhb.interleave.bytecode; + +import java.lang.management.ManagementFactory; +import java.nio.file.*; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import static org.junit.jupiter.api.Assertions.*; + +class BytecodeHeapMeasurementTest { + /** Sole live retention root spanning explicit GC samples. */ + private static volatile Held retained; + /** Keeps actual exact storage and witnesses live outside the measurement stack. + * @param explorer key store owner + * @param result concrete terminal observations */ + private record Held(BytecodeExplorer explorer,BytecodeExplorer.Result result) {} + + /** Both heap fixtures must meet the independent reference/batching gate before measurement. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void dynamicHeapOutcomeGate(@TempDir Path directory) throws Exception { + for(String fixture:List.of("cyclic-publication","aliased-array")) { + var program=fixture(directory,fixture);var expected=BytecodeInstructionOracle.enumerate(program);requireOutcomes(fixture,expected); + for(var mode:BytecodeScheduler.Mode.values()) { + var result=new BytecodeExplorer(program,mode).explore(100000);assertTrue(result.exhaustive()); + assertEquals(expected,BytecodeBatchingOracleTest.independentProjection(result)); + assertTrue(result.metrics().sharing().promotions()>0);assertTrue(result.metrics().sharing().edges()>0); + } + } + } + + /** Runs fixed-heap SerialGC forks with two warmups and three alternating-mode repetitions. + * @param arguments output directory and fork identifier + * @throws Exception for correctness, GC or output failures */ + public static void main(String[] arguments) throws Exception { + if(arguments.length!=2)throw new IllegalArgumentException("Expected output directory and fork id"); + var flags=ManagementFactory.getRuntimeMXBean().getInputArguments(); + if(!flags.contains("-XX:+UseSerialGC") || !flags.contains("-XX:MarkSweepDeadRatio=0"))throw new IllegalArgumentException("Compacting SerialGC required"); + Path output=Path.of(arguments[0]);Files.createDirectories(output);String fork=arguments[1]; + var rows=new ArrayList();rows.add("fixture,fork,repetition,mode,states,transitions,encodingCalls,encodingBytes,encodingNanos,elapsedNanos,heapBefore,heapAfter,heapDelta,sharingTraversals,sharingObjects,sharingEdges,sharingPromotions,historyOnlyStates,outcomes"); + var conditions=new StringBuilder("# 95 raw heap measurement conditions\n\n"); + conditions.append("- Java: ").append(System.getProperty("java.runtime.version")).append("\n- OS/architecture: ") + .append(System.getProperty("os.name")).append('/').append(System.getProperty("os.arch")).append("\n- Flags: ").append(flags) + .append("\n- Two warmups and three measured repetitions per fixture/mode; alternating mode order. Retained heap is post-compaction used heap with actual store/witnesses live, minus the pre-run post-GC heap.\n") + .append("- History-only counts come from a separate production-granularity enumeration, checked against actual unique-state counts; only sharing flags are erased in comparison copies. Its work is outside timed samples.\n"); + for(String fixture:List.of("cyclic-publication","aliased-array")) { + var program=fixture(output,fixture);var expected=BytecodeInstructionOracle.enumerate(program);requireOutcomes(fixture,expected); + conditions.append("- ").append(fixture).append(" source SHA-256: ").append(HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(output.resolve(fixture).resolve("sources/Fixture.java"))))) + .append("; artifact: ").append(program.artifactDigest()).append("; limits: ").append(program.limits()).append('\n'); + for(var mode:BytecodeScheduler.Mode.values())for(int i=0;i<2;i++)run(program,expected,mode); + for(int repetition=0;repetition<3;repetition++)for(var mode:repetition%2==0 ? BytecodeScheduler.Mode.values() : new BytecodeScheduler.Mode[]{BytecodeScheduler.Mode.BATCHED,BytecodeScheduler.Mode.REFERENCE}) { + retained=null;BytecodeMeasurementTest.collect();long before=ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + long elapsed=run(program,expected,mode);BytecodeMeasurementTest.collect();long after=ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed(); + var m=retained.result().metrics();var work=m.sharing();long history=historyOnly(program,mode,m.states()); + rows.add(String.join(",",fixture,fork,Integer.toString(repetition),mode.name(),Long.toString(m.states()),Long.toString(m.transitions()),Long.toString(m.encodingCalls()),Long.toString(m.encodingBytes()),Long.toString(m.encodingNanos()),Long.toString(elapsed),Long.toString(before),Long.toString(after),Long.toString(after-before),Long.toString(work.traversals()),Long.toString(work.objects()),Long.toString(work.edges()),Long.toString(work.promotions()),Long.toString(history),Integer.toString(expected.size()))); + } + } + Files.write(output.resolve("samples.csv"),rows,StandardCharsets.UTF_8);Files.writeString(output.resolve("conditions.md"),conditions); + } + + /** Pins the one successful final graph independently of either execution enumeration. + * @param fixture checked-in source fixture + * @param outcomes independent instruction observations + * @throws AssertionError for a missing/extra outcome or wrong final graph/value */ + private static void requireOutcomes(String fixture,Set outcomes) { + var fields=new TreeMap(); + var reference=new BytecodeState.Ref(0,0);String descriptor=fixture.equals("aliased-array") ? "[Ljava/lang/Object;" : "LNode;"; + fields.put(BytecodeInstructionOracle.cellKey(BytecodeState.FIXTURE,new BytecodeProgram.FieldId("Fixture","published",descriptor)),reference); + fields.put(BytecodeInstructionOracle.cellKey(BytecodeState.FIXTURE,new BytecodeProgram.FieldId("Fixture","seen","I")),new BytecodeState.Int(1)); + if(fixture.equals("aliased-array"))fields.put(BytecodeInstructionOracle.cellKey(reference,new BytecodeProgram.FieldId("[Ljava/lang/Object;","[0]","Ljava/lang/Object;")),reference); + else if(fixture.equals("cyclic-publication")) { + fields.put(BytecodeInstructionOracle.cellKey(reference,new BytecodeProgram.FieldId("Node","next","LNode;")),reference); + fields.put(BytecodeInstructionOracle.cellKey(reference,new BytecodeProgram.FieldId("Node","value","I")),new BytecodeState.Int(7)); + }else throw new AssertionError("Unknown heap fixture "+fixture); + var expected=new BytecodeInstructionOracle.Observation("COMPLETED",-1,null,null,null,List.of(),Map.copyOf(fields)); + if(!outcomes.equals(Set.of(expected)))throw new AssertionError("Wrong known heap outcome: "+fixture+" "+outcomes); + } + + /** Runs with live storage retained and rejects any incomplete/mismatched measurement. + * @param program fixture + * @param expected independent outcomes + * @param mode scheduling mode + * @return elapsed nanoseconds */ + private static long run(BytecodeProgram program,Set expected,BytecodeScheduler.Mode mode) { + var explorer=new BytecodeExplorer(program,mode);long start=System.nanoTime();var result=explorer.explore(100000);long elapsed=System.nanoTime()-start; + if(!result.exhaustive() || !expected.equals(BytecodeBatchingOracleTest.independentProjection(result)))throw new AssertionError("Heap measurement outcome mismatch"); + retained=new Held(explorer,result);return elapsed; + } + + /** Counts extra unique states distinguished solely by historical sharing flags. + * @param program fixture + * @param mode production scheduling granularity + * @param expectedStates actual measured unique state count + * @return full-state count minus distinct history-erased state count */ + private static long historyOnly(BytecodeProgram program,BytecodeScheduler.Mode mode,long expectedStates) { + var scheduler=new BytecodeScheduler(program,mode);var pending=new ArrayDeque();pending.add(program.initialState()); + var seen=new HashSet();var erased=new HashSet(); + while(!pending.isEmpty()) { + var state=pending.removeLast();String key=Base64.getEncoder().encodeToString(state.canonicalBytes());if(!seen.add(key))continue; + if(seen.size()>100000)throw new AssertionError("History enumeration exceeded ceiling"); + var copy=state.copy();copy.heap.values().forEach(object->object.shared=false);erased.add(Base64.getEncoder().encodeToString(copy.canonicalBytes())); + if(BytecodeObservations.evaluate(program,state).outcome()==null)for(int actor:scheduler.choices(state))pending.add(scheduler.advance(state,actor).state()); + } + if(seen.size()!=expectedStates)throw new AssertionError("History enumeration disagrees with measured states"); + return seen.size()-erased.size(); + } + + /** Compiles exactly the saved source and loads the real frozen artifact. + * @param directory workspace + * @param name checked-in fixture name + * @return initialized immutable program + * @throws Exception for missing resource/compiler failures */ + private static BytecodeProgram fixture(Path directory,String name) throws Exception { + String source; + try(var input=BytecodeHeapMeasurementTest.class.getResourceAsStream("/bytecode/heap/"+name+"/Fixture.java")) { + if(input==null)throw new IllegalStateException("Missing heap fixture "+name);source=new String(input.readAllBytes(),StandardCharsets.UTF_8); + } + return BytecodeLoader.load(BytecodeFixtures.compile(directory.resolve(name),26,source),"Fixture",BytecodeLimits.defaults()); + } +} diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeHeapReleaseTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeHeapReleaseTest.java new file mode 100644 index 0000000..ec7bf16 --- /dev/null +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeHeapReleaseTest.java @@ -0,0 +1,78 @@ +/** Public heap-profile evidence, strict replay, reports and lossless default-wide snapshots. */ +package dev.samhb.interleave.bytecode; + +import dev.samhb.interleave.*; +import dev.samhb.interleave.format.BytecodeProgramLoader; +import dev.samhb.interleave.search.TraceReplayer; +import dev.samhb.interleave.search.CorruptedTraceException; +import java.nio.file.Path; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import static org.junit.jupiter.api.Assertions.*; + +class BytecodeHeapReleaseTest { + /** Published arrays/aliases, runtime faults and partial allocation cutoffs round-trip public consumers. + * @param directory compiler workspace + * @throws Exception for fixture/serialization failures */ + @Test void heapProfileReplaysAcrossConsumers(@TempDir Path directory) throws Exception { + for(String body:java.util.List.of( + "Object[] a=new Object[1];a[0]=a;saved=a;result=new int[1][0].length;", + "saved=new double[1];Object[] a=new Fixture[1];a[0]=new Object();", + "saved=new float[1];Object a=new int[1];Fixture f=(Fixture)a;", + "saved=new long[1];Object a=new Object();Object b=new Object();")) { + var work=directory.resolve("case"+body.hashCode()); + var classes=BytecodeFixtures.compile(work,26,"@Model public class Fixture {Object saved;int result;public Fixture(){}" + +"@Actor(id=0)public void a(){"+body+"}}"); + var limits=new BytecodeLimits(256,body.contains("new long") ? 2 : 128,8192,32,64,256,4096,128,8192,1024); + var program=BytecodeProgramLoader.load(classes,"Fixture",limits); + var result=InterleaveRunner.builder().build().runBytecode(program); + var traces=new java.util.ArrayList();traces.addAll(result.completedTraces());traces.addAll(result.failingTraces());traces.addAll(result.incompleteTraces()); + assertEquals(1,traces.size()); + var trace=traces.getFirst();var terminal=trace.bytecodeEvidence().terminal(); + if(body.contains("new double")){assertEquals("UNCAUGHT_EXCEPTION",terminal.kind());assertEquals("java/lang/ArrayStoreException",terminal.fault().type());} + else if(body.contains("new float")){assertEquals("UNCAUGHT_EXCEPTION",terminal.kind());assertEquals("java/lang/ClassCastException",terminal.fault().type());} + else assertEquals(body.contains("new long") ? "CUTOFF" : "COMPLETED",terminal.kind()); + var decoded=TraceRecord.fromJson(trace.toJson()); + assertEquals(trace.bytecodeEvidence(),decoded.bytecodeEvidence()); + assertEquals(trace.states(),new TraceReplayer().replayBytecode(program,decoded).states()); + assertEquals("BYTECODE-SC-2",decoded.bytecodeEvidence().identity().profileVersion()); + var last=trace.bytecodeEvidence().snapshots().getLast();assertTrue(last.heap().stream().anyMatch(o->o.identity().startsWith("actor:0:"))); + if(body.contains("new double"))assertTrue(last.fields().values().stream().anyMatch(v->v.type().equals("DOUBLE_BITS") && v.raw().equals("0000000000000000"))); + if(body.contains("new float"))assertTrue(last.fields().values().stream().anyMatch(v->v.type().equals("FLOAT_BITS") && v.raw().equals("00000000"))); + if(body.contains("new long")){assertTrue(result.hasIncomplete());assertEquals("ALLOCATIONS",trace.bytecodeEvidence().terminal().cutoff().reason());} + var forged=com.google.gson.JsonParser.parseString(trace.toJson()).getAsJsonObject(); + var fields=forged.getAsJsonObject("bytecodeEvidence").getAsJsonArray("snapshots").get(1).getAsJsonObject().getAsJsonObject("fields"); + fields.addProperty("forged-array-element",7); + assertThrows(IllegalArgumentException.class,()->TraceRecord.fromJson(forged.toString())); + var changedFields=new java.util.HashMap<>(last.fields()); + String cell=changedFields.keySet().stream().filter(key->key.endsWith("[0]")).findFirst().orElseThrow(); + var value=changedFields.get(cell);String raw=switch(value.type()) { + case "REFERENCE","NULL"->"setup:0";case "DOUBLE_BITS"->"0000000000000001";case "FLOAT_BITS"->"00000001";default->"1"; + }; + changedFields.put(cell,new dev.samhb.interleave.core.BytecodeEvidence.Value(value.type().equals("NULL") ? "REFERENCE" : value.type(),raw)); + var data=trace.bytecodeEvidence();var snapshots=new java.util.ArrayList<>(data.snapshots()); + snapshots.set(snapshots.size()-1,new dev.samhb.interleave.core.BytecodeEvidence.Snapshot(last.stateDigest(),changedFields,last.locals(),last.heap())); + var forgedData=new dev.samhb.interleave.core.BytecodeEvidence(data.version(),data.identity(),data.transitions(),snapshots,data.terminal(),null); + var forgedRecord=new TraceRecord(trace.threadIds(),trace.outcomes(),trace.outcome(),trace.programHash(),snapshots.stream().map(BytecodeSnapshots::display).toList(),null,forgedData); + assertThrows(CorruptedTraceException.class,()->new TraceReplayer().replayBytecode(program,TraceRecord.fromJson(forgedRecord.toJson()))); + var bytes=new java.io.ByteArrayOutputStream();try(var out=new java.io.ObjectOutputStream(bytes)){out.writeObject(result);} + try(var in=new java.io.ObjectInputStream(new java.io.ByteArrayInputStream(bytes.toByteArray()))) { + var restored=(TestResult)in.readObject();assertEquals(result.bytecodeIdentity(),restored.bytecodeIdentity()); + assertEquals(result.completedTraces().size(),restored.completedTraces().size());assertEquals(result.failingTraces().size(),restored.failingTraces().size()); + assertEquals(result.incompleteTraces().size(),restored.incompleteTraces().size()); + } + } + } + /** Real bounded multidimensional heaps can expose more than65536 snapshot field entries. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void snapshotsCoverAggregateActorHeap(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,"@Model public class Fixture{public Fixture(){}@Actor(id=0)public void a(){int[][] x=new int[9][4096];}@Actor(id=1)public void b(){int[][] x=new int[9][4096];}}"); + var limits=new BytecodeLimits(256,128,40000,32,4096,256,4096,128,8192,1024);var program=BytecodeLoader.load(classes,"Fixture",limits); + var state=BytecodeFixtures.run(program,program.initialState(),0);state=BytecodeFixtures.run(program,state,1); + assertEquals(36883,state.executions.get(0).cells);assertEquals(36883,state.executions.get(1).cells); + var snapshot=BytecodeSnapshots.capture(state,state.canonicalBytes());assertTrue(snapshot.fields().size()>65536); + assertTrue(snapshot.fields().size()<=88201);assertEquals("0",snapshot.fields().get("actor:1:9[4095]").raw()); + } + +} diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeHeapTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeHeapTest.java new file mode 100644 index 0000000..69d432b --- /dev/null +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeHeapTest.java @@ -0,0 +1,224 @@ +/** Heap construction, JVM differential behavior and bounded allocation regressions. */ +package dev.samhb.interleave.bytecode; + +import java.nio.file.Path; +import java.nio.file.Files; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import static org.junit.jupiter.api.Assertions.*; +import static dev.samhb.interleave.bytecode.BytecodeState.*; + +class BytecodeHeapTest { + /** Actor construction, inherited hidden fields and aliases agree with the independent JVM. + * @param directory isolated compiler workspace + * @throws Exception for fixture/oracle failures */ + @Test void heapAliasesAndDispatchMatchJvm(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + class Base { int x=3; int value(){return x;} } + class Child extends Base { int x=7; Child self; Child(){self=this;} int value(){return super.value()+x;} } + @Model public class Fixture { public int result; public Fixture(){} + @Actor(id=0) public void actor(){Child c=new Child();Base b=c;result=b.value()+c.self.x;} + } + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + var state=BytecodeFixtures.run(program,program.initialState(),0); + assertEquals(Phase.TERMINATED,state.executions.get(0).phase); + assertEquals(new Int(17),state.fixtureField("result")); + assertEquals("17",BytecodeFixtures.oracle(directory,classes,"Fixture f=new Fixture();f.actor();System.out.println(f.result);")); + assertEquals(1,state.executions.get(0).allocations); + assertEquals(4,state.executions.get(0).cells); + } + /** Primitive/reference/ranked arrays retain JVM defaults, narrowing, aliases and dynamic types. + * @param directory compiler workspace + * @throws Exception for fixture/oracle failures */ + @Test void arraysAndCastsMatchJvm(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + @Model public class Fixture {public int result;public Object saved;public Fixture(){} + @Actor(id=0) public void actor(){ + int[][] a=new int[2][3];a[1][2]=9;byte[] b=new byte[1];b[0]=(byte)255; + char[] c=new char[1];c[0]=(char)65535;short[] s=new short[1];s[0]=(short)65535; + boolean[] z=new boolean[1];z[0]=true;Object[] refs=new int[1][];refs[0]=a[1]; + Object v=refs;result=((int[])((Object[])v)[0])[2]+a.length+b[0]+c[0]+s[0]+(z[0]?1:0); + if(v instanceof int[][])result++;saved=new long[2]; + } + } + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + var state=BytecodeFixtures.run(program,program.initialState(),0); + assertEquals(Phase.TERMINATED,state.executions.get(0).phase); + assertEquals(new Int(65546),state.fixtureField("result")); + assertEquals("65546",BytecodeFixtures.oracle(directory,classes,"Fixture f=new Fixture();f.actor();System.out.println(f.result);")); + assertEquals(9,state.executions.get(0).allocations); + assertEquals(24,state.executions.get(0).cells); + } + + /** Dynamic array/cast/null failures consume fuel and run compiler monitor cleanup. + * @param directory compiler workspace + * @throws Exception for fixture/oracle failures */ + @Test void arrayFaultsRemainDynamic(@TempDir Path directory) throws Exception { + String[][] cases={ + {"int[] a=new int[-1];","java/lang/NegativeArraySizeException"}, + {"int[] a=new int[1];result=a[1];","java/lang/ArrayIndexOutOfBoundsException"}, + {"int[] a=new int[1];a[-1]=7;","java/lang/ArrayIndexOutOfBoundsException"}, + {"int[] a=null;result=a.length;","java/lang/NullPointerException"}, + {"int[] a=null;result=a[0];","java/lang/NullPointerException"}, + {"int[] a=null;a[0]=7;","java/lang/NullPointerException"}, + {"Object[] a=new Fixture[1];a[0]=new Object();","java/lang/ArrayStoreException"}, + {"Object a=new Object();Fixture f=(Fixture)a;","java/lang/ClassCastException"}, + {"Fixture f=null;result=f.read();","java/lang/NullPointerException"} + }; + for(int i=0;i0);assertEquals("actor",actor.fault.location().name()); + assertEquals(cases[i][1],BytecodeFixtures.oracle(work,classes, + "try{new Fixture().actor();System.out.print(\"NO FAULT\");}catch(RuntimeException e){System.out.print(e.getClass().getName().replace('.', '/'));}")); + } + } + + /** Exact lengths/counts/cells and partial dimensions retain earlier permanent identities. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void perAllocatorBudgetAndPartialDimensions(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + @Model public class Fixture { public Object saved;public Fixture(){} + @Actor(id=0)public void actor(){saved=new int[2][2];} + } + """); + var count=new BytecodeLimits(256,2,8192,32,64,256,4096,128,8192,1024); + var program=BytecodeLoader.load(classes,"Fixture",count);var state=BytecodeFixtures.run(program,program.initialState(),0); + var actor=state.executions.get(0);assertEquals(Phase.CUTOFF,actor.phase);assertEquals("ALLOCATIONS",actor.cutoff.reason()); + assertEquals(2,actor.allocations);assertEquals(6,actor.cells);assertEquals(2,actor.nextSequence); + assertEquals(NULL,state.fixtureField("saved"));assertTrue(state.heap.containsKey(new Ref(0,0)));assertTrue(state.heap.containsKey(new Ref(0,1))); + assertFalse(state.heap.containsKey(new Ref(0,2)));assertEquals(new Ref(0,1),state.heap.get(new Ref(0,0)).elements.get(0)); + var cells=new BytecodeLimits(256,128,5,32,64,256,4096,128,8192,1024); + program=BytecodeLoader.load(classes,"Fixture",cells);state=BytecodeFixtures.run(program,program.initialState(),0); + assertEquals("HEAP_CELLS",state.executions.get(0).cutoff.reason());assertEquals(3,state.executions.get(0).cells); + assertEquals(1,state.executions.get(0).nextSequence);assertEquals(3,state.executions.get(0).cutoff.required());assertEquals(2,state.executions.get(0).cutoff.remaining()); + for(int length:new int[]{0,2,3}) { + var input=BytecodeFixtures.compile(directory.resolve("length"+length),26, + "@Model public class Fixture {public Object saved;public Fixture(){} @Actor(id=0)public void actor(){saved=new int["+length+"];}}"); + var limits=new BytecodeLimits(256,128,8192,32,2,256,4096,128,8192,1024); + program=BytecodeLoader.load(input,"Fixture",limits);state=BytecodeFixtures.run(program,program.initialState(),0); + if(length==3){assertEquals("ARRAY_LENGTH",state.executions.get(0).cutoff.reason());assertEquals(0,state.executions.get(0).nextSequence);} + else {assertEquals(Phase.TERMINATED,state.executions.get(0).phase);assertEquals(1+length,state.executions.get(0).cells);} + } + } + + /** Formerly rejected constructor chaining and plain actor monitors are now fully interpreted. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void constructorChainingAndActorMonitors(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,17,""" + @Model public class Fixture {public int result;public Fixture(){this(4);}public Fixture(int x){result=x;} + @Actor(id=0)public void actor(){Object lock=new Object();synchronized(lock){result+=read();}} + private int read(){return 3;} + @Check public boolean check(){return read()==3 && result==7;} + } + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + var state=BytecodeFixtures.run(program,program.initialState(),0); + assertEquals(new Int(7),state.fixtureField("result"));assertEquals(1,state.executions.get(0).allocations); + assertEquals(0,state.heap.get(new Ref(0,0)).monitorDepth);assertTrue(state.heap.get(new Ref(0,0)).initialized); + assertEquals(BytecodeExplorer.Kind.COMPLETED,new BytecodeExplorer(program,BytecodeScheduler.Mode.BATCHED).explore(10000).witnesses().getFirst().outcome().kind()); + } + + /** Array-valued stores use the runtime component type and preserve the previous element on failure. + * @param directory compiler workspace + * @throws Exception for fixture/oracle failures */ + @Test void covariantArrayStorePreservesPriorElementOnFault(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + @Model public class Fixture{public Object[] saved;public Fixture(){}@Actor(id=0)public void actor(){ + Object[] a=new int[1][];a[0]=new int[2];saved=a;a[0]=new long[1];}} + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults());var state=BytecodeFixtures.run(program,program.initialState(),0); + assertEquals(Phase.FAILED,state.executions.get(0).phase);assertEquals("java/lang/ArrayStoreException",state.executions.get(0).fault.type()); + var array=state.heap.get((Ref)state.fixtureField("saved"));var element=state.heap.get((Ref)array.elements.getFirst()); + assertEquals("[I",element.type);assertEquals(2,element.elements.size()); + assertEquals("java.lang.ArrayStoreException:2",BytecodeFixtures.oracle(directory,classes, + "Fixture f=new Fixture();try{f.actor();}catch(RuntimeException e){System.out.print(e.getClass().getName()+\":\"+((int[])f.saved[0]).length);}")); + } + + /** Successors and repeated runs own their array containers while retaining real alias identities. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void arrayCopiesPreserveParentsAndCanonicalElements(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,"@Model public class Fixture{int[] saved=new int[1];public Fixture(){}@Actor(id=0)public void actor(){saved[0]=7;}}"); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults());var parent=program.initialState();var key=parent.canonicalBytes(); + var reference=(Ref)parent.fixtureField("saved");var result=BytecodeFixtures.run(program,parent,0); + assertEquals(new Int(7),result.heap.get(reference).elements.getFirst());assertEquals(new Int(0),parent.heap.get(reference).elements.getFirst()); + assertArrayEquals(key,parent.canonicalBytes());assertArrayEquals(key,program.initialState().canonicalBytes()); + var changed=parent.copy();changed.heap.get(reference).elements.set(0,new Int(1));assertFalse(java.util.Arrays.equals(key,changed.canonicalBytes())); + changed=parent.copy();changed.heap.get(reference).elements.add(new Int(0));assertFalse(java.util.Arrays.equals(key,changed.canonicalBytes())); + assertEquals(new Int(7),BytecodeFixtures.run(program,program.initialState(),0).heap.get(reference).elements.getFirst()); + } + + /** Null casts preserve null and null instanceof remains false without a target fault. + * @param directory compiler workspace + * @throws Exception for fixture/oracle failures */ + @Test void nullTypeChecksMatchJvm(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,17,"@Model public class Fixture{public int result;public Fixture(){}@Actor(id=0)public void actor(){Object a=null;Fixture f=(Fixture)a;result=(f==null?1:0)+(a instanceof Fixture?2:0)+(a instanceof int[]?4:0);}}"); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults());var state=BytecodeFixtures.run(program,program.initialState(),0); + assertEquals(Phase.TERMINATED,state.executions.get(0).phase);assertEquals(new Int(1),state.fixtureField("result")); + assertEquals("1",BytecodeFixtures.oracle(directory,classes,"Fixture f=new Fixture();f.actor();System.out.print(f.result);")); + } + + /** Early constructor publication preserves effects, charges and an unfinished object after a genuine fault. + * @param directory compiler workspace + * @throws Exception for fixture/oracle failures */ + @Test void publishedConstructorFaultRetainsPartialState(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,""" + class Helper{int value;Helper(Fixture root){value=7;root.saved=this;int zero=0;value=1/zero;}} + @Model public class Fixture{public Object saved;public int mark;public Fixture(){}@Actor(id=0)public void actor(){mark=3;new Helper(this);}} + """); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + for(var mode:BytecodeScheduler.Mode.values()) { + var scheduler=new BytecodeScheduler(program,mode);var state=program.initialState(); + for(int step=0;step<200 && state.executions.get(0).phase!=Phase.FAILED;step++)state=scheduler.advance(state,0).state(); + var execution=state.executions.get(0);assertEquals(Phase.FAILED,execution.phase);assertEquals("java/lang/ArithmeticException",execution.fault.type()); + assertEquals("Helper",execution.fault.location().owner());assertEquals("",execution.fault.location().name());assertEquals(2,execution.fault.stack().size()); + assertEquals(new Int(3),state.fixtureField("mark"));var helper=state.heap.get((Ref)state.fixtureField("saved")); + assertTrue(helper.shared);assertFalse(helper.initialized);assertEquals(new Int(7),helper.fields.get(new BytecodeProgram.FieldId("Helper","value","I"))); + assertEquals(1,execution.allocations);assertEquals(2,execution.cells); + } + assertEquals("3:7",BytecodeFixtures.oracle(directory,classes,"Fixture f=new Fixture();try{f.actor();}catch(ArithmeticException e){System.out.print(f.mark+\":\"+((Helper)f.saved).value);}")); + } + + /** Verified constructors may reuse local zero; setup and actor object identity must survive that store. + * @param directory compiler workspace + * @throws Exception for fixture/oracle failures */ + @Test void constructorReceiverSurvivesLocalZeroReuse(@TempDir Path directory) throws Exception { + var classes=BytecodeFixtures.compile(directory,26,"class Helper{Helper(){}}@Model public class Fixture{public Object saved;public Fixture(){}@Actor(id=0)public void actor(){saved=new Helper();}}"); + var parser=java.lang.classfile.ClassFile.of(); + for(String name:java.util.List.of("Fixture","Helper")) { + Path target=classes.resolve(name+".class"); + Files.write(target,parser.transformClass(parser.parse(Files.readAllBytes(target)),(builder,element)->{ + if(element instanceof java.lang.classfile.MethodModel method && method.methodName().equalsString("")) + builder.transformMethod(method,java.lang.classfile.MethodTransform.transformingCode((code,item)->{ + if(item instanceof java.lang.classfile.Instruction instruction && instruction.opcode()==java.lang.classfile.Opcode.RETURN)code.aconst_null().astore(0); + code.with(item); + }));else builder.with(element); + })); + } + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults());var parent=program.initialState();var before=parent.canonicalBytes(); + var state=BytecodeFixtures.run(program,parent,0);assertEquals(Phase.TERMINATED,state.executions.get(0).phase); + assertTrue(state.heap.get(FIXTURE).initialized);assertTrue(state.heap.get((Ref)state.fixtureField("saved")).initialized); + assertArrayEquals(before,parent.canonicalBytes()); + assertEquals("true",BytecodeFixtures.oracle(directory,classes,"Fixture f=new Fixture();f.actor();System.out.print(f.saved instanceof Helper);")); + } + +} diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeInputBoundaryTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeInputBoundaryTest.java index 539a55c..cef71bf 100644 --- a/src/test/java/dev/samhb/interleave/bytecode/BytecodeInputBoundaryTest.java +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeInputBoundaryTest.java @@ -78,7 +78,7 @@ class BytecodeInputBoundaryTest { assertThrows(BytecodeLoadException.class,()->BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults())); Path interfaces=BytecodeFixtures.compile(directory.resolve("interface"),26, "@Model public class Fixture { Marker value; public Fixture() {} @Actor(id=0) public void actor() {} } interface Marker {}"); - assertEquals("UNSUPPORTED",assertThrows(BytecodeLoadException.class,()->BytecodeLoader.load(interfaces,"Fixture",BytecodeLimits.defaults())).category); + assertEquals(BytecodeState.NULL,BytecodeLoader.load(interfaces,"Fixture",BytecodeLimits.defaults()).initialState().fixtureField("value")); } /** Pads with a bounded, nonexecuting standard debug attribute, retaining a valid class. diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeInstructionOracle.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeInstructionOracle.java index a4d1f31..84937c9 100644 --- a/src/test/java/dev/samhb/interleave/bytecode/BytecodeInstructionOracle.java +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeInstructionOracle.java @@ -55,7 +55,22 @@ static Set enumerate(BytecodeProgram program) { ? BytecodeState.classMonitor(frame.method.id.owner(),program) : (Ref)frame.locals.get(0); else monitor=(Ref)frame.stack.getLast(); var object=state.heap.get(monitor);waits.add(waitKey(actor,object.monitorOwner,monitor,object.monitorDepth)); - } else {pending.push(next.state());choices++;} + } else { + var before=state.executions.get(actor); + if(before.phase==Phase.RUNNING && state.frame(actor).entered) { + var instruction=state.frame(actor).method.ops.get(state.frame(actor).bci).instruction(); + boolean changed=instruction instanceof java.lang.classfile.instruction.NewObjectInstruction + || instruction instanceof java.lang.classfile.instruction.NewPrimitiveArrayInstruction + || instruction instanceof java.lang.classfile.instruction.NewReferenceArrayInstruction + || instruction instanceof java.lang.classfile.instruction.NewMultiArrayInstruction + || instruction.opcode()==java.lang.classfile.Opcode.AASTORE; + if(instruction instanceof java.lang.classfile.instruction.FieldInstruction field + && (field.opcode()==java.lang.classfile.Opcode.PUTFIELD || field.opcode()==java.lang.classfile.Opcode.PUTSTATIC)) + changed=field.type().stringValue().startsWith("L") || field.type().stringValue().startsWith("["); + if(changed && (next.state().executions.get(actor).phase==Phase.RUNNING || next.state().heap.size()!=state.heap.size()))promote(next.state()); + } + pending.push(next.state());choices++; + } } if(choices==0)outcomes.add(observation(state,"DEADLOCK",-1,null,null,null,List.copyOf(waits))); } @@ -125,10 +140,42 @@ private static Observation observation(BytecodeState state,String kind,int actor var fields=new TreeMap(); for(var entry:state.statics.entrySet())fields.put(cellKey(NULL,entry.getKey()),entry.getValue()); for(var entry:state.heap.entrySet())if(entry.getValue().shared) - for(var field:entry.getValue().fields.entrySet())fields.put(cellKey(entry.getKey(),field.getKey()),field.getValue()); + { + for(var field:entry.getValue().fields.entrySet())fields.put(cellKey(entry.getKey(),field.getKey()),field.getValue()); + var array=entry.getValue().elements; + if(array!=null)for(int i=0;i>(); + state.heap.forEach((ref,object)->{if(object.shared)owners.computeIfAbsent(ref,k->new HashSet<>()).add(SETUP);}); + java.util.function.BiConsumer mark=(value,owner)->{ + if(value instanceof Ref ref && !ref.equals(NULL))owners.computeIfAbsent(ref,k->new HashSet<>()).add(owner); + }; + mark.accept(FIXTURE,SETUP);state.statics.values().forEach(value->mark.accept(value,SETUP)); + state.executions.forEach((actor,e)->{if(actor>=0){mark.accept(e.returned,actor);for(var f:e.frames){ + f.locals.values().forEach(v->mark.accept(v,actor));f.stack.forEach(v->mark.accept(v,actor));mark.accept(f.methodMonitor,actor);mark.accept(f.constructorReceiver,actor); + }}}); + boolean changed; + do { + var before=new HashMap>();owners.forEach((ref,set)->before.put(ref,Set.copyOf(set))); + before.forEach((ref,set)->{ + var object=state.heap.get(ref);if(object==null)return; + for(int owner:set){object.fields.values().forEach(v->mark.accept(v,owner));if(object.elements!=null)object.elements.forEach(v->mark.accept(v,owner));} + }); + if(before.equals(owners))state.heap.keySet().forEach(ref->{ + var set=owners.get(ref); + if(set==null || set.size()>1 || set.contains(SETUP))mark.accept(ref,SETUP); + }); + changed=!before.equals(owners); + }while(changed); + state.heap.forEach((ref,object)->{var set=owners.get(ref);if(set==null || set.size()>1 || set.contains(SETUP))object.shared=true;}); + } + /** Independently writes every mutable state component with length-delimited fixture tokens. * Metadata/value records contain only bounded ASCII fixture identifiers and numeric values here. * @param state owned snapshot @@ -137,7 +184,7 @@ private static String key(BytecodeState state) { var key=new StringBuilder();tokens(key,"heap",state.heap.size()); for(var entry:state.heap.entrySet()) { var object=entry.getValue();tokens(key,entry.getKey(),object.type,object.shared,object.initialized,object.monitorOwner,object.monitorDepth,object.fields.size()); - object.fields.forEach((field,value)->tokens(key,field,value)); + object.fields.forEach((field,value)->tokens(key,field,value));tokens(key,object.elements); } tokens(key,"statics",state.statics.size());state.statics.forEach((field,value)->tokens(key,field,value)); tokens(key,"executions",state.executions.size()); @@ -145,7 +192,7 @@ private static String key(BytecodeState state) { var execution=entry.getValue();tokens(key,entry.getKey(),execution.phase,execution.instructions,execution.allocations,execution.cells, execution.nextSequence,execution.fault,execution.cutoff,execution.returned,execution.eventLocation,execution.frames.size()); for(var frame:execution.frames) { - tokens(key,frame.method.id,frame.bci,frame.entered,frame.methodMonitor,frame.locals.size()); + tokens(key,frame.method.id,frame.bci,frame.entered,frame.methodMonitor,frame.constructorReceiver,frame.locals.size()); frame.locals.forEach((slot,value)->tokens(key,slot,value));tokens(key,frame.stack.size());frame.stack.forEach(value->tokens(key,value)); } } diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeLinkageSelectionTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeLinkageSelectionTest.java new file mode 100644 index 0000000..751cbb4 --- /dev/null +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeLinkageSelectionTest.java @@ -0,0 +1,113 @@ +/** JVM differential regressions for unusual but valid selected method and sealed-class metadata. */ +package dev.samhb.interleave.bytecode; + +import java.nio.file.*; +import java.lang.classfile.*; +import java.lang.constant.*; +import java.util.*; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import static java.lang.classfile.ClassFile.*; +import static org.junit.jupiter.api.Assertions.*; +import static dev.samhb.interleave.bytecode.BytecodeState.*; + +class BytecodeLinkageSelectionTest { + /** Special selection skips static shadows and does not repeat resolution access checks. + * @param directory compiler workspace + * @throws Exception for compiler/oracle failures */ + @Test void specialSelectionUsesInstanceDeclarations(@TempDir Path directory) throws Exception { + for(String variant:List.of("static","instance","package","inaccessible")) { + var work=directory.resolve(variant); + var classes=compile(work,Map.of( + "a/A.java","package a;public class A{public int m(){return 1;}}", + "b/B.java","package b;public class B extends a.A{public int m(){return 2;}}", + "c/C.java","package c;public class C extends b.B{public int call(){return super.m();}}", + "Fixture.java","import dev.samhb.interleave.bytecode.*;@Model public class Fixture{public int result;public Fixture(){}@Actor(id=0)public void actor(){result=new c.C().call();}}")); + var parser=ClassFile.of();Path child=classes.resolve("c/C.class"); + Files.write(child,parser.transformClass(parser.parse(Files.readAllBytes(child)),ClassTransform.transformingMethodBodies( + m->m.methodName().equalsString("call"),(code,item)->{ + if(item instanceof java.lang.classfile.instruction.InvokeInstruction call)code.invokespecial(ClassDesc.of("a.A"),"m",call.typeSymbol());else code.with(item); + }))); + if(!variant.equals("instance")) { + Path target=classes.resolve(variant.equals("inaccessible") ? "a/A.class" : "b/B.class"); + Files.write(target,parser.transformClass(parser.parse(Files.readAllBytes(target)),(builder,item)->{ + if(item instanceof MethodModel method && method.methodName().equalsString("m")) { + int flags=variant.equals("static") ? ACC_PUBLIC|ACC_STATIC : 0; + if(variant.equals("static"))builder.withMethod(method.methodName(),method.methodType(),flags,out->out.withCode(code->code.iconst_2().ireturn())); + else builder.transformMethod(method,MethodTransform.endHandler(out->out.withFlags(flags))); + }else builder.with(item); + })); + } + String jvm=BytecodeFixtures.oracle(work,classes,"try{Fixture f=new Fixture();f.actor();System.out.print(f.result);}catch(LinkageError e){System.out.print(e.getClass().getName());}"); + if(variant.equals("inaccessible")) { + assertEquals("java.lang.IllegalAccessError",jvm); + assertEquals("LINKAGE",assertThrows(BytecodeLoadException.class,()->BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults())).category); + } else { + int expected=variant.equals("static") ? 1 : 2;assertEquals(Integer.toString(expected),jvm); + var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults());var state=BytecodeFixtures.run(program,program.initialState(),0); + assertEquals(Phase.TERMINATED,state.executions.get(0).phase);assertEquals(new Int(expected),state.fixtureField("result")); + } + } + } + + /** Invokevirtual may select a nonpublic override of a default; invokeinterface may not. + * @param directory compiler workspace + * @throws Exception for compiler/oracle failures */ + @Test void selectedVisibilityDependsOnOpcode(@TempDir Path directory) throws Exception { + for(boolean interfaceView:new boolean[]{false,true}) { + var work=directory.resolve(interfaceView ? "interface" : "class"); + var classes=BytecodeFixtures.compile(work,26,"interface I{default int m(){return 1;}}class Base implements I{}class Child extends Base{public int m(){return 2;}}@Model public class Fixture{public int result;public Fixture(){}@Actor(id=0)public void actor(){"+(interfaceView ? "I" : "Base")+" value=new Child();result=value.m();}}"); + var parser=ClassFile.of();Path target=classes.resolve("Child.class"); + Files.write(target,parser.transformClass(parser.parse(Files.readAllBytes(target)),(builder,item)->{ + if(item instanceof MethodModel method && method.methodName().equalsString("m"))builder.transformMethod(method,MethodTransform.endHandler(out->out.withFlags(0))); + else builder.with(item); + })); + String jvm=BytecodeFixtures.oracle(work,classes,"try{Fixture f=new Fixture();f.actor();System.out.print(f.result);}catch(LinkageError e){System.out.print(e.getClass().getName());}"); + if(interfaceView) { + assertEquals("java.lang.IllegalAccessError",jvm); + assertEquals("LINKAGE",assertThrows(BytecodeLoadException.class,()->BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults())).category); + } else { + assertEquals("2",jvm);var program=BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults()); + assertEquals(new Int(2),BytecodeFixtures.run(program,program.initialState(),0).fixtureField("result")); + } + } + } + + /** Public permitted children may cross packages in the same unnamed module; nonpublic children may not. + * @param directory compiler workspace + * @throws Exception for compiler/oracle failures */ + @Test void sealedPublicCrossPackageSubtype(@TempDir Path directory) throws Exception { + var classes=compile(directory,Map.of("a/Parent.java","package a;public class Parent{public int m(){return 7;}}", + "b/Child.java","package b;public final class Child extends a.Parent{}", + "b/Fixture.java","package b;import dev.samhb.interleave.bytecode.*;@Model public class Fixture{public int result;public Fixture(){}@Actor(id=0)public void actor(){result=new Child().m();}}")); + var parser=ClassFile.of();Path parent=classes.resolve("a/Parent.class"),child=classes.resolve("b/Child.class"); + Files.write(parent,parser.transformClass(parser.parse(Files.readAllBytes(parent)),ClassTransform.endHandler(out->out.with(java.lang.classfile.attribute.PermittedSubclassesAttribute.ofSymbols(ClassDesc.of("b.Child")))))); + assertEquals("7",BytecodeFixtures.oracle(directory,classes,"b.Fixture f=new b.Fixture();f.actor();System.out.print(f.result);")); + var program=BytecodeLoader.load(classes,"b.Fixture",BytecodeLimits.defaults());assertEquals(new Int(7),BytecodeFixtures.run(program,program.initialState(),0).fixtureField("result")); + Files.write(child,parser.transformClass(parser.parse(Files.readAllBytes(child)),ClassTransform.endHandler(out->out.withFlags(ACC_FINAL|ACC_SUPER)))); + assertEquals("java.lang.IncompatibleClassChangeError",BytecodeFixtures.oracle(directory,classes,"try{new b.Fixture().actor();}catch(LinkageError e){System.out.print(e.getClass().getName());}")); + assertEquals("LINKAGE",assertThrows(BytecodeLoadException.class,()->BytecodeLoader.load(classes,"b.Fixture",BytecodeLimits.defaults())).category); + } + + /** Many repeated calls must not multiply whole-hierarchy validation cost. + * @param directory compiler workspace + * @throws Exception for fixture failures */ + @Test void repeatedCallsDoNotRepeatHierarchyValidation(@TempDir Path directory) throws Exception { + var methods=new StringBuilder();for(int i=0;i<1500;i++)methods.append("public int m").append(i).append("(){return 0;}"); + var classes=BytecodeFixtures.compile(directory,26,"class Base{"+methods+"}class Child extends Base{"+methods.toString().replace("m","n")+"}@Model public class Fixture{Child item=new Child();public Fixture(){}static void helper(){}@Actor(id=0)public void actor(){"+"helper();".repeat(2000)+"}}"); + var program=assertTimeoutPreemptively(java.time.Duration.ofSeconds(20),()->BytecodeLoader.load(classes,"Fixture",BytecodeLimits.defaults())); + assertEquals(3,program.classes.size()); + } + + /** Compiles named application files without executing the target classes. + * @param directory isolated workspace + * @param sources relative filenames and source texts + * @return class directory + * @throws Exception for compiler/filesystem failures */ + private static Path compile(Path directory,Map sources) throws Exception { + Path classes=directory.resolve("classes");Files.createDirectories(classes); + var arguments=new ArrayList(List.of("--release","26","-classpath",BytecodeFixtures.classpath(Model.class),"-d",classes.toString())); + for(var entry:sources.entrySet()){Path source=directory.resolve("sources").resolve(entry.getKey());Files.createDirectories(source.getParent());Files.writeString(source,entry.getValue());arguments.add(source.toString());} + assertEquals(0,javax.tools.ToolProvider.getSystemJavaCompiler().run(null,null,null,arguments.toArray(String[]::new)));return classes; + } +} diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeMeasurementTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeMeasurementTest.java index cda3e8a..504719a 100644 --- a/src/test/java/dev/samhb/interleave/bytecode/BytecodeMeasurementTest.java +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeMeasurementTest.java @@ -29,8 +29,8 @@ private record Held(BytecodeExplorer explorer,BytecodeExplorer.Result result) {} assertTrue(result.exhaustive());assertEquals(expected,BytecodeBatchingOracleTest.independentProjection(result)); assertTrue(result.metrics().encodingBytes()>=result.metrics().retainedKeyBytes()); assertEquals(1,result.metrics().sharing().traversals());assertEquals(0,result.metrics().sharing().promotions()); - assertEquals(fixture.equals("two-lock") ? 4 : 2,result.metrics().sharing().objects()); - assertEquals(fixture.equals("two-lock") ? 2 : 0,result.metrics().sharing().edges()); + assertEquals(fixture.equals("two-lock") ? 10 : 4,result.metrics().sharing().objects()); + assertEquals(fixture.equals("two-lock") ? 6 : 0,result.metrics().sharing().edges()); } } } @@ -121,7 +121,7 @@ private static long runRetained(BytecodeProgram program,Setk.contains("Node"))); + for(var mode:BytecodeScheduler.Mode.values()){var result=new BytecodeExplorer(program,mode).explore(10000);assertTrue(result.traversalComplete());assertEquals(expected,BytecodeBatchingOracleTest.independentProjection(result));} + } + +} diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeReleaseTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeReleaseTest.java index c1d6ae2..31afdd1 100644 --- a/src/test/java/dev/samhb/interleave/bytecode/BytecodeReleaseTest.java +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeReleaseTest.java @@ -55,7 +55,7 @@ class BytecodeReleaseTest { assertTrue(json.get("fallbackReason").isJsonNull());assertFalse(json.get("limitExceeded").getAsBoolean()); var identity=json.getAsJsonObject("bytecodeIdentity"); assertEquals(program.artifactDigest(),identity.get("artifactDigest").getAsString()); - assertEquals("BYTECODE-SC-1",identity.get("profileVersion").getAsString()); + assertEquals("BYTECODE-SC-2",identity.get("profileVersion").getAsString()); assertEquals("Fixture",identity.get("modelClass").getAsString());assertEquals("BATCHED",identity.get("mode").getAsString()); assertEquals(256,identity.getAsJsonObject("limits").get("actorInstructions").getAsInt()); assertEquals(2,identity.getAsJsonArray("actors").size());assertEquals(1,identity.getAsJsonArray("checks").size()); @@ -167,6 +167,8 @@ private static java.util.Map.Entry cli(Path directory,String... "cutoff", "@Actor(id=0)public void a(){while(true){}}", "observer", "public int z;@Actor(id=0)public void a(){}@Check(when=Check.When.ALWAYS)public boolean ok(){return 1/z==0;}", "no-line", "public int x;@Actor(id=0)public void a(){x=1;}", + "heap", "public Object[] saved;@Actor(id=0)public void a(){Object[] a=new Object[1];a[0]=a;saved=a;}", + "array-fault", "public Object saved;@Actor(id=0)public void a(){saved=new double[1];Object[] a=new Fixture[1];a[0]=new Object();}", "long-label", "public int "+"x".repeat(600)+";@Actor(id=0)public void a(){"+"x".repeat(600)+"=1;}"); java.nio.file.Files.createDirectories(Path.of("build")); for(var entry:cases.entrySet()) { @@ -191,8 +193,8 @@ private static java.util.Map.Entry cli(Path directory,String... var classes=directory.resolve("classes");java.nio.file.Files.createDirectories(classes); var compiler=javax.tools.ToolProvider.getSystemJavaCompiler(); assertEquals(0,compiler.run(null,null,null,"--release","17","-g","-cp",jar.toString(),"-d",classes.toString(), - "examples/bytecode/LostUpdate.java","examples/bytecode/TwoLockDeadlock.java")); - for(var name:java.util.List.of("LostUpdate","TwoLockDeadlock")) { + "examples/bytecode/LostUpdate.java","examples/bytecode/TwoLockDeadlock.java","examples/bytecode/HeapPublication.java")); + for(var name:java.util.List.of("LostUpdate","TwoLockDeadlock","HeapPublication")) { var cliOutput=directory.resolve(name+"-cli.json"); var cliProcess=new ProcessBuilder(Path.of(System.getProperty("java.home"),"bin","java").toString(),"-cp", jar+java.io.File.pathSeparator+BytecodeFixtures.classpath(com.google.gson.Gson.class),"dev.samhb.interleave.cli.Main", @@ -202,8 +204,8 @@ private static java.util.Map.Entry cli(Path directory,String... assertTrue(cliProcess.waitFor(15,java.util.concurrent.TimeUnit.SECONDS));var text=java.nio.file.Files.readString(cliOutput); assertEquals(0,cliProcess.exitValue(),text);var report=com.google.gson.JsonParser.parseString(text).getAsJsonObject(); assertTrue(report.get("soundness").getAsBoolean()); - var row=report.getAsJsonArray("benchmarks").get(0).getAsJsonObject();assertEquals("VIOLATION",row.get("verdict").getAsString()); - assertEquals(name.equals("LostUpdate")?"CHECK_FALSE":"DEADLOCK",row.getAsJsonObject("failingTrace").getAsJsonObject("bytecodeEvidence").getAsJsonObject("terminal").get("kind").getAsString()); + var row=report.getAsJsonArray("benchmarks").get(0).getAsJsonObject();assertEquals(name.equals("HeapPublication") ? "PASS" : "VIOLATION",row.get("verdict").getAsString()); + if(!name.equals("HeapPublication"))assertEquals(name.equals("LostUpdate")?"CHECK_FALSE":"DEADLOCK",row.getAsJsonObject("failingTrace").getAsJsonObject("bytecodeEvidence").getAsJsonObject("terminal").get("kind").getAsString()); } finally {if(cliProcess.isAlive())cliProcess.destroyForcibly();} } var source=directory.resolve("Consumer.java"); @@ -214,10 +216,10 @@ private static java.util.Map.Entry cli(Path directory,String... import java.nio.file.Path; public class Consumer {public static void main(String[] args)throws Exception { var runner=InterleaveRunner.builder().build();var replay=new TraceReplayer(); - for(String name:new String[]{"LostUpdate","TwoLockDeadlock"}) { + for(String name:new String[]{"LostUpdate","TwoLockDeadlock","HeapPublication"}) { var program=BytecodeProgramLoader.load(Path.of(args[0]),"examples.bytecode."+name); var result=runner.runBytecode(program); - var traces=name.equals("LostUpdate")?result.failingTraces():result.deadlockedTraces(); + var traces=name.equals("HeapPublication")?result.completedTraces():name.equals("LostUpdate")?result.failingTraces():result.deadlockedTraces(); if(traces.isEmpty() || result.hasIncomplete())throw new AssertionError(name); var record=TraceRecord.fromJson(traces.getFirst().toJson()); if(!replay.replayBytecode(program,record).states().equals(record.states()))throw new AssertionError("replay"); @@ -238,7 +240,7 @@ public class Consumer {public static void main(String[] args)throws Exception { "Consumer",classes.toString()).redirectErrorStream(true).redirectOutput(output.toFile()).start(); try { assertTrue(process.waitFor(15,java.util.concurrent.TimeUnit.SECONDS));var text=java.nio.file.Files.readString(output); - assertEquals(0,process.exitValue(),text);assertEquals(java.util.List.of("LostUpdate:CHECK_FALSE","TwoLockDeadlock:DEADLOCK"),text.lines().toList()); + assertEquals(0,process.exitValue(),text);assertEquals(java.util.List.of("LostUpdate:CHECK_FALSE","TwoLockDeadlock:DEADLOCK","HeapPublication:COMPLETED"),text.lines().toList()); } finally {if(process.isAlive())process.destroyForcibly();} } /** Unsupported routes reject without invoking caller callbacks or changing legacy settings. diff --git a/src/test/java/dev/samhb/interleave/bytecode/BytecodeSearchContractTest.java b/src/test/java/dev/samhb/interleave/bytecode/BytecodeSearchContractTest.java index 2dfa57f..0dda088 100644 --- a/src/test/java/dev/samhb/interleave/bytecode/BytecodeSearchContractTest.java +++ b/src/test/java/dev/samhb/interleave/bytecode/BytecodeSearchContractTest.java @@ -80,12 +80,12 @@ class BytecodeSearchContractTest { var explorer=new BytecodeExplorer(program,BytecodeScheduler.Mode.REFERENCE);long start=System.nanoTime();var result=explorer.explore(140);long elapsed=System.nanoTime()-start; assertTrue(result.exhaustive());assertEquals(140,result.metrics().states());assertEquals(246,result.metrics().transitions()); assertEquals(2,result.witnesses().size());assertEquals(178,result.metrics().instructions());assertEquals(178,result.metrics().opcodes()); - assertEquals(247,result.metrics().encodingCalls());assertEquals(118191,result.metrics().encodingBytes());assertEquals(66946,result.metrics().retainedKeyBytes()); + assertEquals(247,result.metrics().encodingCalls());assertEquals(119051,result.metrics().encodingBytes());assertEquals(67438,result.metrics().retainedKeyBytes()); assertTrue(result.metrics().encodingNanos()>0);assertTrue(result.metrics().encodingNanos()<=elapsed); assertEquals(0,result.metrics().checkInvocations());assertEquals(0,result.metrics().checkInstructions()); - assertEquals(new BytecodeSharing.Work(1,2,0,0),result.metrics().sharing()); - assertTrue(explorer.explore(new BytecodeExplorer.Budget(140,66946)).exhaustive()); - var shortKeys=explorer.explore(new BytecodeExplorer.Budget(140,66945));assertFalse(shortKeys.exhaustive()); + assertEquals(new BytecodeSharing.Work(1,4,0,0),result.metrics().sharing()); + assertTrue(explorer.explore(new BytecodeExplorer.Budget(140,67438)).exhaustive()); + var shortKeys=explorer.explore(new BytecodeExplorer.Budget(140,67437));assertFalse(shortKeys.exhaustive()); assertEquals("KEY_BYTES",shortKeys.witnesses().getLast().outcome().interruption()); var shortStates=explorer.explore(139);assertFalse(shortStates.exhaustive());assertEquals(139,shortStates.metrics().states()); assertTrue(explorer.explore(140).exhaustive(),"A prior interruption must not leak into a reused explorer"); diff --git a/src/test/java/dev/samhb/mutationharness/BytecodeWorkBudgetTest.java b/src/test/java/dev/samhb/mutationharness/BytecodeWorkBudgetTest.java index 3250eef..cfd447a 100644 --- a/src/test/java/dev/samhb/mutationharness/BytecodeWorkBudgetTest.java +++ b/src/test/java/dev/samhb/mutationharness/BytecodeWorkBudgetTest.java @@ -68,6 +68,24 @@ class BytecodeWorkBudgetTest { assertEquals("BOUND_EXCEEDED",run("BytecodeChecks",mutant,true)); } + /** A removed real class-count checkpoint cannot turn the monotone loader closure into an infinite pass loop. + * @throws Exception for checker/child failures */ + @Test void catchesNonconvergentLoaderClosure() throws Exception { + var file=classFile();int[] changed={0}; + var mutant=file.transformClass(file.parse(bytes("BytecodeLoader")),ClassTransform.transformingMethodBodies( + method->method.methodName().equalsString("load"),(code,element)->{ + if(changed[0]==0 && element instanceof InvokeInstruction call && call.owner().asInternalName().equals("java/util/Map") && call.name().equalsString("size")) { + code.pop().iconst_0();changed[0]++; + } else code.with(element); + })); + assertEquals(1,changed[0]);assertEquals(List.of(),file.verify(mutant)); + var instrumented=BytecodeWorkBudget.instrument(mutant,true,getClass().getClassLoader()); + assertEquals(List.of(),file.verify(instrumented)); + assertThrows(IllegalArgumentException.class,()->BytecodeWorkBudget.instrument(mutant,false,getClass().getClassLoader())); + // The child starts with the already transformed replacement, matching PIT's redefinition path. + assertEquals("BOUND_EXCEEDED",run("BytecodeLoader",instrumented,false)); + } + /** Binding/checkpoint drift fails closed rather than silently omitting the instrumentation. * @throws Exception for class-file failures */ @Test void rejectsMethodAndCheckpointDrift() throws Exception { diff --git a/src/test/resources/bytecode/heap/aliased-array/Fixture.java b/src/test/resources/bytecode/heap/aliased-array/Fixture.java new file mode 100644 index 0000000..2c4585e --- /dev/null +++ b/src/test/resources/bytecode/heap/aliased-array/Fixture.java @@ -0,0 +1,11 @@ +// Actor-created reference array retains an alias cycle after publication. +@Model public class Fixture { + Object[] published; + int seen; + /** Constructs the shared fixture without target allocations. */ + public Fixture() {} + /** Builds a private reference-array self-cycle before publishing its shared root. */ + @Actor(id=0) public void publish() { Object[] a=new Object[1]; a[0]=a; published=a; } + /** Performs an independent shared write competing with graph publication. */ + @Actor(id=1) public void compete() { seen=1; } +} diff --git a/src/test/resources/bytecode/heap/cyclic-publication/Fixture.java b/src/test/resources/bytecode/heap/cyclic-publication/Fixture.java new file mode 100644 index 0000000..617209d --- /dev/null +++ b/src/test/resources/bytecode/heap/cyclic-publication/Fixture.java @@ -0,0 +1,17 @@ +// Actor-local cycle promoted through a shared root, with a competing shared write. +/** Private actor graph with a cycle and one value cell. */ +class Node { + Node next; int value; + /** Creates default field storage; actor instructions install the private cycle. */ + Node() {} +} +@Model public class Fixture { + Node published; + int seen; + /** Constructs the shared fixture without target allocations. */ + public Fixture() {} + /** Builds and initializes a private object cycle before publishing its shared root. */ + @Actor(id=0) public void publish() { Node n=new Node(); n.next=n; n.value=7; published=n; } + /** Performs an independent shared write competing with graph publication. */ + @Actor(id=1) public void compete() { seen=1; } +}